const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/LeadSiteHome-760wC_Hs.js","assets/useLeadSiteSearchSuggestions-BoJNzt8S.js","assets/CityPagesModule-Dae3F2uR.js","assets/imageOptimization-D_YRwPcx.js","assets/LeadSiteLuxuryHome-cDAp7Hfb.js","assets/LeadSiteLandRanchHome-B9Gs3Yiq.js","assets/LeadSiteSearch-Bq-aIH-g.js","assets/SaveSearchButton-DoaI-rdv.js","assets/LeadSiteMap-BAXw1acM.js","assets/LeadSiteLuxurySearch-Ber2cw73.js","assets/LeadSiteListingDetail-Cstv6WyB.js","assets/ListingVideoTour-0dJHgOps.js","assets/useListingVideos-CYquSdfg.js","assets/LeadSiteLuxuryListingDetail-mjTwomMD.js","assets/LeadSiteCityPage-siD5Qjgy.js","assets/LeadSiteSubdivisionPage-rEaCgKKL.js","assets/PostcardManager-DhniJU_h.js","assets/usePostcardZones-DfBJk6yC.js","assets/DirectMail-ENq11r3Q.js","assets/jspdf.es.min-bUlGCrK1.js","assets/LeadSiteEditor-Bbwpzbf6.js","assets/ImageUrlField-CjCrW2qQ.js","assets/LeadSiteEditor-BzY4kI8E.css","assets/AdminLeadSiteThemes-BSET15Pe.js","assets/MLSListingDetail-a5f1pjPn.js","assets/EmailCampaignComposer-fb8b77Qq.js","assets/EditorModeSelector-DaQ-fHIz.js","assets/SharedCampaignTemplates-C2h7yiZ_.js","assets/TemplateEditorDialog-0s1BQV1k.js","assets/AgentTemplates-DSFAw2gv.js","assets/TheLocalMoveHome-k4gpbQhM.js","assets/tlm-hero-bg-BbD3acLf.js","assets/TheLocalMoveGetStarted-BjXln4q6.js"])))=>i.map(i=>d[i]); var kjt=Object.defineProperty;var uDe=s=>{throw TypeError(s)};var Sjt=(s,t,r)=>t in s?kjt(s,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):s[t]=r;var ga=(s,t,r)=>Sjt(s,typeof t!="symbol"?t+"":t,r),s1e=(s,t,r)=>t.has(s)||uDe("Cannot "+r);var Ds=(s,t,r)=>(s1e(s,t,"read from private field"),r?r.call(s):t.get(s)),Ai=(s,t,r)=>t.has(s)?uDe("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(s):t.set(s,r),Pa=(s,t,r,n)=>(s1e(s,t,"write to private field"),n?n.call(s,r):t.set(s,r),r),Ro=(s,t,r)=>(s1e(s,t,"access private method"),r);var dU=(s,t,r,n)=>({set _(a){Pa(s,t,a,r)},get _(){return Ds(s,t,n)}});function Cjt(s,t){for(var r=0;rn[a]})}}}return Object.freeze(Object.defineProperty(s,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))n(a);new MutationObserver(a=>{for(const i of a)if(i.type==="childList")for(const l of i.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&n(l)}).observe(document,{childList:!0,subtree:!0});function r(a){const i={};return a.integrity&&(i.integrity=a.integrity),a.referrerPolicy&&(i.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?i.credentials="include":a.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function n(a){if(a.ep)return;a.ep=!0;const i=r(a);fetch(a.href,i)}})();const Tjt="modulepreload",Ejt=function(s){return"/"+s},hDe={},Ti=function(t,r,n){let a=Promise.resolve();if(r&&r.length>0){document.getElementsByTagName("link");const l=document.querySelector("meta[property=csp-nonce]"),o=(l==null?void 0:l.nonce)||(l==null?void 0:l.getAttribute("nonce"));a=Promise.allSettled(r.map(c=>{if(c=Ejt(c),c in hDe)return;hDe[c]=!0;const d=c.endsWith(".css"),h=d?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${c}"]${h}`))return;const m=document.createElement("link");if(m.rel=d?"stylesheet":Tjt,d||(m.as="script"),m.crossOrigin="",m.href=c,o&&m.setAttribute("nonce",o),document.head.appendChild(m),d)return new Promise((p,x)=>{m.addEventListener("load",p),m.addEventListener("error",()=>x(new Error(`Unable to preload CSS for ${c}`)))})}))}function i(l){const o=new Event("vite:preloadError",{cancelable:!0});if(o.payload=l,window.dispatchEvent(o),!o.defaultPrevented)throw l}return a.then(l=>{for(const o of l||[])o.status==="rejected"&&i(o.reason);return t().catch(i)})};var uh=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function ol(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}function Ajt(s){if(s.__esModule)return s;var t=s.default;if(typeof t=="function"){var r=function n(){return this instanceof n?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};r.prototype=t.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(s).forEach(function(n){var a=Object.getOwnPropertyDescriptor(s,n);Object.defineProperty(r,n,a.get?a:{enumerable:!0,get:function(){return s[n]}})}),r}var VYe={exports:{}},Spe={},HYe={exports:{}},tl={};/** * @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 AB=Symbol.for("react.element"),Mjt=Symbol.for("react.portal"),Ijt=Symbol.for("react.fragment"),Pjt=Symbol.for("react.strict_mode"),Ljt=Symbol.for("react.profiler"),Djt=Symbol.for("react.provider"),Rjt=Symbol.for("react.context"),Ojt=Symbol.for("react.forward_ref"),Fjt=Symbol.for("react.suspense"),Bjt=Symbol.for("react.memo"),zjt=Symbol.for("react.lazy"),mDe=Symbol.iterator;function $jt(s){return s===null||typeof s!="object"?null:(s=mDe&&s[mDe]||s["@@iterator"],typeof s=="function"?s:null)}var GYe={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},WYe=Object.assign,KYe={};function JL(s,t,r){this.props=s,this.context=t,this.refs=KYe,this.updater=r||GYe}JL.prototype.isReactComponent={};JL.prototype.setState=function(s,t){if(typeof s!="object"&&typeof s!="function"&&s!=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,s,t,"setState")};JL.prototype.forceUpdate=function(s){this.updater.enqueueForceUpdate(this,s,"forceUpdate")};function YYe(){}YYe.prototype=JL.prototype;function vCe(s,t,r){this.props=s,this.context=t,this.refs=KYe,this.updater=r||GYe}var bCe=vCe.prototype=new YYe;bCe.constructor=vCe;WYe(bCe,JL.prototype);bCe.isPureReactComponent=!0;var fDe=Array.isArray,ZYe=Object.prototype.hasOwnProperty,_Ce={current:null},XYe={key:!0,ref:!0,__self:!0,__source:!0};function QYe(s,t,r){var n,a={},i=null,l=null;if(t!=null)for(n in t.ref!==void 0&&(l=t.ref),t.key!==void 0&&(i=""+t.key),t)ZYe.call(t,n)&&!XYe.hasOwnProperty(n)&&(a[n]=t[n]);var o=arguments.length-2;if(o===1)a.children=r;else if(1>>1,je=ne[fe];if(0>>1;fea(Ve,be))Lea(Me,Ve)?(ne[fe]=Me,ne[Le]=be,fe=Le):(ne[fe]=Ve,ne[We]=be,fe=We);else if(Lea(Me,be))ne[fe]=Me,ne[Le]=be,fe=Le;else break e}}return le}function a(ne,le){var be=ne.sortIndex-le.sortIndex;return be!==0?be:ne.id-le.id}if(typeof performance=="object"&&typeof performance.now=="function"){var i=performance;s.unstable_now=function(){return i.now()}}else{var l=Date,o=l.now();s.unstable_now=function(){return l.now()-o}}var c=[],d=[],h=1,m=null,p=3,x=!1,y=!1,_=!1,b=typeof setTimeout=="function"?setTimeout:null,j=typeof clearTimeout=="function"?clearTimeout:null,k=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function T(ne){for(var le=r(d);le!==null;){if(le.callback===null)n(d);else if(le.startTime<=ne)n(d),le.sortIndex=le.expirationTime,t(c,le);else break;le=r(d)}}function E(ne){if(_=!1,T(ne),!y)if(r(c)!==null)y=!0,ie(A);else{var le=r(d);le!==null&&ce(E,le.startTime-ne)}}function A(ne,le){y=!1,_&&(_=!1,j(z),z=-1),x=!0;var be=p;try{for(T(le),m=r(c);m!==null&&(!(m.expirationTime>le)||ne&&!ee());){var fe=m.callback;if(typeof fe=="function"){m.callback=null,p=m.priorityLevel;var je=fe(m.expirationTime<=le);le=s.unstable_now(),typeof je=="function"?m.callback=je:m===r(c)&&n(c),T(le)}else n(c);m=r(c)}if(m!==null)var ve=!0;else{var We=r(d);We!==null&&ce(E,We.startTime-le),ve=!1}return ve}finally{m=null,p=be,x=!1}}var D=!1,R=null,z=-1,O=5,$=-1;function ee(){return!(s.unstable_now()-$ne||125fe?(ne.sortIndex=be,t(d,ne),r(c)===null&&ne===r(d)&&(_?(j(z),z=-1):_=!0,ce(E,be-fe))):(ne.sortIndex=je,t(c,ne),y||x||(y=!0,ie(A))),ne},s.unstable_shouldYield=ee,s.unstable_wrapCallback=function(ne){var le=p;return function(){var be=p;p=le;try{return ne.apply(this,arguments)}finally{p=be}}}})(rZe);sZe.exports=rZe;var OO=sZe.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 Qjt=S,j0=OO;function Rn(s){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+s,r=1;r"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),d2e=Object.prototype.hasOwnProperty,Jjt=/^[: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]*$/,gDe={},xDe={};function eNt(s){return d2e.call(xDe,s)?!0:d2e.call(gDe,s)?!1:Jjt.test(s)?xDe[s]=!0:(gDe[s]=!0,!1)}function tNt(s,t,r,n){if(r!==null&&r.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return n?!1:r!==null?!r.acceptsBooleans:(s=s.toLowerCase().slice(0,5),s!=="data-"&&s!=="aria-");default:return!1}}function sNt(s,t,r,n){if(t===null||typeof t>"u"||tNt(s,t,r,n))return!0;if(n)return!1;if(r!==null)switch(r.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function Cg(s,t,r,n,a,i,l){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=n,this.attributeNamespace=a,this.mustUseProperty=r,this.propertyName=s,this.type=t,this.sanitizeURL=i,this.removeEmptyString=l}var Wf={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(s){Wf[s]=new Cg(s,0,!1,s,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(s){var t=s[0];Wf[t]=new Cg(t,1,!1,s[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(s){Wf[s]=new Cg(s,2,!1,s.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(s){Wf[s]=new Cg(s,2,!1,s,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(s){Wf[s]=new Cg(s,3,!1,s.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(s){Wf[s]=new Cg(s,3,!0,s,null,!1,!1)});["capture","download"].forEach(function(s){Wf[s]=new Cg(s,4,!1,s,null,!1,!1)});["cols","rows","size","span"].forEach(function(s){Wf[s]=new Cg(s,6,!1,s,null,!1,!1)});["rowSpan","start"].forEach(function(s){Wf[s]=new Cg(s,5,!1,s.toLowerCase(),null,!1,!1)});var NCe=/[\-:]([a-z])/g;function kCe(s){return s[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(s){var t=s.replace(NCe,kCe);Wf[t]=new Cg(t,1,!1,s,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(s){var t=s.replace(NCe,kCe);Wf[t]=new Cg(t,1,!1,s,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(s){var t=s.replace(NCe,kCe);Wf[t]=new Cg(t,1,!1,s,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(s){Wf[s]=new Cg(s,1,!1,s.toLowerCase(),null,!1,!1)});Wf.xlinkHref=new Cg("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(s){Wf[s]=new Cg(s,1,!1,s.toLowerCase(),null,!0,!0)});function SCe(s,t,r,n){var a=Wf.hasOwnProperty(t)?Wf[t]:null;(a!==null?a.type!==0:n||!(2o||a[l]!==i[o]){var c=` `+a[l].replace(" at new "," at ");return s.displayName&&c.includes("")&&(c=c.replace("",s.displayName)),c}while(1<=l&&0<=o);break}}}finally{a1e=!1,Error.prepareStackTrace=r}return(s=s?s.displayName||s.name:"")?lO(s):""}function rNt(s){switch(s.tag){case 5:return lO(s.type);case 16:return lO("Lazy");case 13:return lO("Suspense");case 19:return lO("SuspenseList");case 0:case 2:case 15:return s=i1e(s.type,!1),s;case 11:return s=i1e(s.type.render,!1),s;case 1:return s=i1e(s.type,!0),s;default:return""}}function f2e(s){if(s==null)return null;if(typeof s=="function")return s.displayName||s.name||null;if(typeof s=="string")return s;switch(s){case Z6:return"Fragment";case Y6:return"Portal";case u2e:return"Profiler";case CCe:return"StrictMode";case h2e:return"Suspense";case m2e:return"SuspenseList"}if(typeof s=="object")switch(s.$$typeof){case iZe:return(s.displayName||"Context")+".Consumer";case aZe:return(s._context.displayName||"Context")+".Provider";case TCe:var t=s.render;return s=s.displayName,s||(s=t.displayName||t.name||"",s=s!==""?"ForwardRef("+s+")":"ForwardRef"),s;case ECe:return t=s.displayName||null,t!==null?t:f2e(s.type)||"Memo";case FN:t=s._payload,s=s._init;try{return f2e(s(t))}catch{}}return null}function nNt(s){var t=s.type;switch(s.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return s=t.render,s=s.displayName||s.name||"",t.displayName||(s!==""?"ForwardRef("+s+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return f2e(t);case 8:return t===CCe?"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 t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function uS(s){switch(typeof s){case"boolean":case"number":case"string":case"undefined":return s;case"object":return s;default:return""}}function lZe(s){var t=s.type;return(s=s.nodeName)&&s.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function aNt(s){var t=lZe(s)?"checked":"value",r=Object.getOwnPropertyDescriptor(s.constructor.prototype,t),n=""+s[t];if(!s.hasOwnProperty(t)&&typeof r<"u"&&typeof r.get=="function"&&typeof r.set=="function"){var a=r.get,i=r.set;return Object.defineProperty(s,t,{configurable:!0,get:function(){return a.call(this)},set:function(l){n=""+l,i.call(this,l)}}),Object.defineProperty(s,t,{enumerable:r.enumerable}),{getValue:function(){return n},setValue:function(l){n=""+l},stopTracking:function(){s._valueTracker=null,delete s[t]}}}}function mU(s){s._valueTracker||(s._valueTracker=aNt(s))}function cZe(s){if(!s)return!1;var t=s._valueTracker;if(!t)return!0;var r=t.getValue(),n="";return s&&(n=lZe(s)?s.checked?"true":"false":s.value),s=n,s!==r?(t.setValue(s),!0):!1}function Wue(s){if(s=s||(typeof document<"u"?document:void 0),typeof s>"u")return null;try{return s.activeElement||s.body}catch{return s.body}}function p2e(s,t){var r=t.checked;return bu({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:r??s._wrapperState.initialChecked})}function vDe(s,t){var r=t.defaultValue==null?"":t.defaultValue,n=t.checked!=null?t.checked:t.defaultChecked;r=uS(t.value!=null?t.value:r),s._wrapperState={initialChecked:n,initialValue:r,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function dZe(s,t){t=t.checked,t!=null&&SCe(s,"checked",t,!1)}function g2e(s,t){dZe(s,t);var r=uS(t.value),n=t.type;if(r!=null)n==="number"?(r===0&&s.value===""||s.value!=r)&&(s.value=""+r):s.value!==""+r&&(s.value=""+r);else if(n==="submit"||n==="reset"){s.removeAttribute("value");return}t.hasOwnProperty("value")?x2e(s,t.type,r):t.hasOwnProperty("defaultValue")&&x2e(s,t.type,uS(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(s.defaultChecked=!!t.defaultChecked)}function bDe(s,t,r){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var n=t.type;if(!(n!=="submit"&&n!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+s._wrapperState.initialValue,r||t===s.value||(s.value=t),s.defaultValue=t}r=s.name,r!==""&&(s.name=""),s.defaultChecked=!!s._wrapperState.initialChecked,r!==""&&(s.name=r)}function x2e(s,t,r){(t!=="number"||Wue(s.ownerDocument)!==s)&&(r==null?s.defaultValue=""+s._wrapperState.initialValue:s.defaultValue!==""+r&&(s.defaultValue=""+r))}var cO=Array.isArray;function NI(s,t,r,n){if(s=s.options,t){t={};for(var a=0;a"+t.valueOf().toString()+"",t=fU.firstChild;s.firstChild;)s.removeChild(s.firstChild);for(;t.firstChild;)s.appendChild(t.firstChild)}});function R7(s,t){if(t){var r=s.firstChild;if(r&&r===s.lastChild&&r.nodeType===3){r.nodeValue=t;return}}s.textContent=t}var FO={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},iNt=["Webkit","ms","Moz","O"];Object.keys(FO).forEach(function(s){iNt.forEach(function(t){t=t+s.charAt(0).toUpperCase()+s.substring(1),FO[t]=FO[s]})});function fZe(s,t,r){return t==null||typeof t=="boolean"||t===""?"":r||typeof t!="number"||t===0||FO.hasOwnProperty(s)&&FO[s]?(""+t).trim():t+"px"}function pZe(s,t){s=s.style;for(var r in t)if(t.hasOwnProperty(r)){var n=r.indexOf("--")===0,a=fZe(r,t[r],n);r==="float"&&(r="cssFloat"),n?s.setProperty(r,a):s[r]=a}}var oNt=bu({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 b2e(s,t){if(t){if(oNt[s]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(Rn(137,s));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(Rn(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(Rn(61))}if(t.style!=null&&typeof t.style!="object")throw Error(Rn(62))}}function _2e(s,t){if(s.indexOf("-")===-1)return typeof t.is=="string";switch(s){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var w2e=null;function ACe(s){return s=s.target||s.srcElement||window,s.correspondingUseElement&&(s=s.correspondingUseElement),s.nodeType===3?s.parentNode:s}var j2e=null,kI=null,SI=null;function jDe(s){if(s=PB(s)){if(typeof j2e!="function")throw Error(Rn(280));var t=s.stateNode;t&&(t=Mpe(t),j2e(s.stateNode,s.type,t))}}function gZe(s){kI?SI?SI.push(s):SI=[s]:kI=s}function xZe(){if(kI){var s=kI,t=SI;if(SI=kI=null,jDe(s),t)for(s=0;s>>=0,s===0?32:31-(yNt(s)/vNt|0)|0}var pU=64,gU=4194304;function dO(s){switch(s&-s){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return s&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return s&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return s}}function Xue(s,t){var r=s.pendingLanes;if(r===0)return 0;var n=0,a=s.suspendedLanes,i=s.pingedLanes,l=r&268435455;if(l!==0){var o=l&~a;o!==0?n=dO(o):(i&=l,i!==0&&(n=dO(i)))}else l=r&~a,l!==0?n=dO(l):i!==0&&(n=dO(i));if(n===0)return 0;if(t!==0&&t!==n&&!(t&a)&&(a=n&-n,i=t&-t,a>=i||a===16&&(i&4194240)!==0))return t;if(n&4&&(n|=r&16),t=s.entangledLanes,t!==0)for(s=s.entanglements,t&=n;0r;r++)t.push(s);return t}function MB(s,t,r){s.pendingLanes|=t,t!==536870912&&(s.suspendedLanes=0,s.pingedLanes=0),s=s.eventTimes,t=31-p1(t),s[t]=r}function jNt(s,t){var r=s.pendingLanes&~t;s.pendingLanes=t,s.suspendedLanes=0,s.pingedLanes=0,s.expiredLanes&=t,s.mutableReadLanes&=t,s.entangledLanes&=t,t=s.entanglements;var n=s.eventTimes;for(s=s.expirationTimes;0=zO),IDe=" ",PDe=!1;function OZe(s,t){switch(s){case"keyup":return XNt.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function FZe(s){return s=s.detail,typeof s=="object"&&"data"in s?s.data:null}var X6=!1;function JNt(s,t){switch(s){case"compositionend":return FZe(t);case"keypress":return t.which!==32?null:(PDe=!0,IDe);case"textInput":return s=t.data,s===IDe&&PDe?null:s;default:return null}}function ekt(s,t){if(X6)return s==="compositionend"||!FCe&&OZe(s,t)?(s=DZe(),TV=DCe=xk=null,X6=!1,s):null;switch(s){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:r,offset:t-s};s=n}e:{for(;r;){if(r.nextSibling){r=r.nextSibling;break e}r=r.parentNode}r=void 0}r=ODe(r)}}function UZe(s,t){return s&&t?s===t?!0:s&&s.nodeType===3?!1:t&&t.nodeType===3?UZe(s,t.parentNode):"contains"in s?s.contains(t):s.compareDocumentPosition?!!(s.compareDocumentPosition(t)&16):!1:!1}function qZe(){for(var s=window,t=Wue();t instanceof s.HTMLIFrameElement;){try{var r=typeof t.contentWindow.location.href=="string"}catch{r=!1}if(r)s=t.contentWindow;else break;t=Wue(s.document)}return t}function BCe(s){var t=s&&s.nodeName&&s.nodeName.toLowerCase();return t&&(t==="input"&&(s.type==="text"||s.type==="search"||s.type==="tel"||s.type==="url"||s.type==="password")||t==="textarea"||s.contentEditable==="true")}function ckt(s){var t=qZe(),r=s.focusedElem,n=s.selectionRange;if(t!==r&&r&&r.ownerDocument&&UZe(r.ownerDocument.documentElement,r)){if(n!==null&&BCe(r)){if(t=n.start,s=n.end,s===void 0&&(s=t),"selectionStart"in r)r.selectionStart=t,r.selectionEnd=Math.min(s,r.value.length);else if(s=(t=r.ownerDocument||document)&&t.defaultView||window,s.getSelection){s=s.getSelection();var a=r.textContent.length,i=Math.min(n.start,a);n=n.end===void 0?i:Math.min(n.end,a),!s.extend&&i>n&&(a=n,n=i,i=a),a=FDe(r,i);var l=FDe(r,n);a&&l&&(s.rangeCount!==1||s.anchorNode!==a.node||s.anchorOffset!==a.offset||s.focusNode!==l.node||s.focusOffset!==l.offset)&&(t=t.createRange(),t.setStart(a.node,a.offset),s.removeAllRanges(),i>n?(s.addRange(t),s.extend(l.node,l.offset)):(t.setEnd(l.node,l.offset),s.addRange(t)))}}for(t=[],s=r;s=s.parentNode;)s.nodeType===1&&t.push({element:s,left:s.scrollLeft,top:s.scrollTop});for(typeof r.focus=="function"&&r.focus(),r=0;r=document.documentMode,Q6=null,E2e=null,UO=null,A2e=!1;function BDe(s,t,r){var n=r.window===r?r.document:r.nodeType===9?r:r.ownerDocument;A2e||Q6==null||Q6!==Wue(n)||(n=Q6,"selectionStart"in n&&BCe(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}),UO&&U7(UO,n)||(UO=n,n=ehe(E2e,"onSelect"),0tI||(s.current=R2e[tI],R2e[tI]=null,tI--)}function ad(s,t){tI++,R2e[tI]=s.current,s.current=t}var hS={},jp=MS(hS),ax=MS(!1),sA=hS;function BP(s,t){var r=s.type.contextTypes;if(!r)return hS;var n=s.stateNode;if(n&&n.__reactInternalMemoizedUnmaskedChildContext===t)return n.__reactInternalMemoizedMaskedChildContext;var a={},i;for(i in r)a[i]=t[i];return n&&(s=s.stateNode,s.__reactInternalMemoizedUnmaskedChildContext=t,s.__reactInternalMemoizedMaskedChildContext=a),a}function ix(s){return s=s.childContextTypes,s!=null}function she(){Cd(ax),Cd(jp)}function GDe(s,t,r){if(jp.current!==hS)throw Error(Rn(168));ad(jp,t),ad(ax,r)}function QZe(s,t,r){var n=s.stateNode;if(t=t.childContextTypes,typeof n.getChildContext!="function")return r;n=n.getChildContext();for(var a in n)if(!(a in t))throw Error(Rn(108,nNt(s)||"Unknown",a));return bu({},r,n)}function rhe(s){return s=(s=s.stateNode)&&s.__reactInternalMemoizedMergedChildContext||hS,sA=jp.current,ad(jp,s),ad(ax,ax.current),!0}function WDe(s,t,r){var n=s.stateNode;if(!n)throw Error(Rn(169));r?(s=QZe(s,t,sA),n.__reactInternalMemoizedMergedChildContext=s,Cd(ax),Cd(jp),ad(jp,s)):Cd(ax),ad(ax,r)}var y2=null,Ipe=!1,b1e=!1;function JZe(s){y2===null?y2=[s]:y2.push(s)}function _kt(s){Ipe=!0,JZe(s)}function IS(){if(!b1e&&y2!==null){b1e=!0;var s=0,t=xc;try{var r=y2;for(xc=1;s>=l,a-=l,T2=1<<32-p1(t)+a|r<z?(O=R,R=null):O=R.sibling;var $=p(j,R,T[z],E);if($===null){R===null&&(R=O);break}s&&R&&$.alternate===null&&t(j,R),k=i($,k,z),D===null?A=$:D.sibling=$,D=$,R=O}if(z===T.length)return r(j,R),Wd&&dC(j,z),A;if(R===null){for(;zz?(O=R,R=null):O=R.sibling;var ee=p(j,R,$.value,E);if(ee===null){R===null&&(R=O);break}s&&R&&ee.alternate===null&&t(j,R),k=i(ee,k,z),D===null?A=ee:D.sibling=ee,D=ee,R=O}if($.done)return r(j,R),Wd&&dC(j,z),A;if(R===null){for(;!$.done;z++,$=T.next())$=m(j,$.value,E),$!==null&&(k=i($,k,z),D===null?A=$:D.sibling=$,D=$);return Wd&&dC(j,z),A}for(R=n(j,R);!$.done;z++,$=T.next())$=x(R,j,z,$.value,E),$!==null&&(s&&$.alternate!==null&&R.delete($.key===null?z:$.key),k=i($,k,z),D===null?A=$:D.sibling=$,D=$);return s&&R.forEach(function(Z){return t(j,Z)}),Wd&&dC(j,z),A}function b(j,k,T,E){if(typeof T=="object"&&T!==null&&T.type===Z6&&T.key===null&&(T=T.props.children),typeof T=="object"&&T!==null){switch(T.$$typeof){case hU:e:{for(var A=T.key,D=k;D!==null;){if(D.key===A){if(A=T.type,A===Z6){if(D.tag===7){r(j,D.sibling),k=a(D,T.props.children),k.return=j,j=k;break e}}else if(D.elementType===A||typeof A=="object"&&A!==null&&A.$$typeof===FN&&ZDe(A)===D.type){r(j,D.sibling),k=a(D,T.props),k.ref=xR(j,D,T),k.return=j,j=k;break e}r(j,D);break}else t(j,D);D=D.sibling}T.type===Z6?(k=cE(T.props.children,j.mode,E,T.key),k.return=j,j=k):(E=RV(T.type,T.key,T.props,null,j.mode,E),E.ref=xR(j,k,T),E.return=j,j=E)}return l(j);case Y6:e:{for(D=T.key;k!==null;){if(k.key===D)if(k.tag===4&&k.stateNode.containerInfo===T.containerInfo&&k.stateNode.implementation===T.implementation){r(j,k.sibling),k=a(k,T.children||[]),k.return=j,j=k;break e}else{r(j,k);break}else t(j,k);k=k.sibling}k=T1e(T,j.mode,E),k.return=j,j=k}return l(j);case FN:return D=T._init,b(j,k,D(T._payload),E)}if(cO(T))return y(j,k,T,E);if(hR(T))return _(j,k,T,E);jU(j,T)}return typeof T=="string"&&T!==""||typeof T=="number"?(T=""+T,k!==null&&k.tag===6?(r(j,k.sibling),k=a(k,T),k.return=j,j=k):(r(j,k),k=C1e(T,j.mode,E),k.return=j,j=k),l(j)):r(j,k)}return b}var $P=rXe(!0),nXe=rXe(!1),ihe=MS(null),ohe=null,nI=null,qCe=null;function VCe(){qCe=nI=ohe=null}function HCe(s){var t=ihe.current;Cd(ihe),s._currentValue=t}function B2e(s,t,r){for(;s!==null;){var n=s.alternate;if((s.childLanes&t)!==t?(s.childLanes|=t,n!==null&&(n.childLanes|=t)):n!==null&&(n.childLanes&t)!==t&&(n.childLanes|=t),s===r)break;s=s.return}}function TI(s,t){ohe=s,qCe=nI=null,s=s.dependencies,s!==null&&s.firstContext!==null&&(s.lanes&t&&(ex=!0),s.firstContext=null)}function Xy(s){var t=s._currentValue;if(qCe!==s)if(s={context:s,memoizedValue:t,next:null},nI===null){if(ohe===null)throw Error(Rn(308));nI=s,ohe.dependencies={lanes:0,firstContext:s}}else nI=nI.next=s;return t}var PT=null;function GCe(s){PT===null?PT=[s]:PT.push(s)}function aXe(s,t,r,n){var a=t.interleaved;return a===null?(r.next=r,GCe(t)):(r.next=a.next,a.next=r),t.interleaved=r,sj(s,n)}function sj(s,t){s.lanes|=t;var r=s.alternate;for(r!==null&&(r.lanes|=t),r=s,s=s.return;s!==null;)s.childLanes|=t,r=s.alternate,r!==null&&(r.childLanes|=t),r=s,s=s.return;return r.tag===3?r.stateNode:null}var BN=!1;function WCe(s){s.updateQueue={baseState:s.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function iXe(s,t){s=s.updateQueue,t.updateQueue===s&&(t.updateQueue={baseState:s.baseState,firstBaseUpdate:s.firstBaseUpdate,lastBaseUpdate:s.lastBaseUpdate,shared:s.shared,effects:s.effects})}function O2(s,t){return{eventTime:s,lane:t,tag:0,payload:null,callback:null,next:null}}function Ik(s,t,r){var n=s.updateQueue;if(n===null)return null;if(n=n.shared,Dl&2){var a=n.pending;return a===null?t.next=t:(t.next=a.next,a.next=t),n.pending=t,sj(s,r)}return a=n.interleaved,a===null?(t.next=t,GCe(n)):(t.next=a.next,a.next=t),n.interleaved=t,sj(s,r)}function AV(s,t,r){if(t=t.updateQueue,t!==null&&(t=t.shared,(r&4194240)!==0)){var n=t.lanes;n&=s.pendingLanes,r|=n,t.lanes=r,ICe(s,r)}}function XDe(s,t){var r=s.updateQueue,n=s.alternate;if(n!==null&&(n=n.updateQueue,r===n)){var a=null,i=null;if(r=r.firstBaseUpdate,r!==null){do{var l={eventTime:r.eventTime,lane:r.lane,tag:r.tag,payload:r.payload,callback:r.callback,next:null};i===null?a=i=l:i=i.next=l,r=r.next}while(r!==null);i===null?a=i=t:i=i.next=t}else a=i=t;r={baseState:n.baseState,firstBaseUpdate:a,lastBaseUpdate:i,shared:n.shared,effects:n.effects},s.updateQueue=r;return}s=r.lastBaseUpdate,s===null?r.firstBaseUpdate=t:s.next=t,r.lastBaseUpdate=t}function lhe(s,t,r,n){var a=s.updateQueue;BN=!1;var i=a.firstBaseUpdate,l=a.lastBaseUpdate,o=a.shared.pending;if(o!==null){a.shared.pending=null;var c=o,d=c.next;c.next=null,l===null?i=d:l.next=d,l=c;var h=s.alternate;h!==null&&(h=h.updateQueue,o=h.lastBaseUpdate,o!==l&&(o===null?h.firstBaseUpdate=d:o.next=d,h.lastBaseUpdate=c))}if(i!==null){var m=a.baseState;l=0,h=d=c=null,o=i;do{var p=o.lane,x=o.eventTime;if((n&p)===p){h!==null&&(h=h.next={eventTime:x,lane:0,tag:o.tag,payload:o.payload,callback:o.callback,next:null});e:{var y=s,_=o;switch(p=t,x=r,_.tag){case 1:if(y=_.payload,typeof y=="function"){m=y.call(x,m,p);break e}m=y;break e;case 3:y.flags=y.flags&-65537|128;case 0:if(y=_.payload,p=typeof y=="function"?y.call(x,m,p):y,p==null)break e;m=bu({},m,p);break e;case 2:BN=!0}}o.callback!==null&&o.lane!==0&&(s.flags|=64,p=a.effects,p===null?a.effects=[o]:p.push(o))}else x={eventTime:x,lane:p,tag:o.tag,payload:o.payload,callback:o.callback,next:null},h===null?(d=h=x,c=m):h=h.next=x,l|=p;if(o=o.next,o===null){if(o=a.shared.pending,o===null)break;p=o,o=p.next,p.next=null,a.lastBaseUpdate=p,a.shared.pending=null}}while(!0);if(h===null&&(c=m),a.baseState=c,a.firstBaseUpdate=d,a.lastBaseUpdate=h,t=a.shared.interleaved,t!==null){a=t;do l|=a.lane,a=a.next;while(a!==t)}else i===null&&(a.shared.lanes=0);aA|=l,s.lanes=l,s.memoizedState=m}}function QDe(s,t,r){if(s=t.effects,t.effects=null,s!==null)for(t=0;tr?r:4,s(!0);var n=w1e.transition;w1e.transition={};try{s(!1),t()}finally{xc=r,w1e.transition=n}}function jXe(){return Qy().memoizedState}function kkt(s,t,r){var n=Lk(s);if(r={lane:n,action:r,hasEagerState:!1,eagerState:null,next:null},NXe(s))kXe(t,r);else if(r=aXe(s,t,r,n),r!==null){var a=bg();g1(r,s,n,a),SXe(r,t,n)}}function Skt(s,t,r){var n=Lk(s),a={lane:n,action:r,hasEagerState:!1,eagerState:null,next:null};if(NXe(s))kXe(t,a);else{var i=s.alternate;if(s.lanes===0&&(i===null||i.lanes===0)&&(i=t.lastRenderedReducer,i!==null))try{var l=t.lastRenderedState,o=i(l,r);if(a.hasEagerState=!0,a.eagerState=o,T1(o,l)){var c=t.interleaved;c===null?(a.next=a,GCe(t)):(a.next=c.next,c.next=a),t.interleaved=a;return}}catch{}finally{}r=aXe(s,t,a,n),r!==null&&(a=bg(),g1(r,s,n,a),SXe(r,t,n))}}function NXe(s){var t=s.alternate;return s===gu||t!==null&&t===gu}function kXe(s,t){qO=dhe=!0;var r=s.pending;r===null?t.next=t:(t.next=r.next,r.next=t),s.pending=t}function SXe(s,t,r){if(r&4194240){var n=t.lanes;n&=s.pendingLanes,r|=n,t.lanes=r,ICe(s,r)}}var uhe={readContext:Xy,useCallback:up,useContext:up,useEffect:up,useImperativeHandle:up,useInsertionEffect:up,useLayoutEffect:up,useMemo:up,useReducer:up,useRef:up,useState:up,useDebugValue:up,useDeferredValue:up,useTransition:up,useMutableSource:up,useSyncExternalStore:up,useId:up,unstable_isNewReconciler:!1},Ckt={readContext:Xy,useCallback:function(s,t){return Rb().memoizedState=[s,t===void 0?null:t],s},useContext:Xy,useEffect:eRe,useImperativeHandle:function(s,t,r){return r=r!=null?r.concat([s]):null,IV(4194308,4,yXe.bind(null,t,s),r)},useLayoutEffect:function(s,t){return IV(4194308,4,s,t)},useInsertionEffect:function(s,t){return IV(4,2,s,t)},useMemo:function(s,t){var r=Rb();return t=t===void 0?null:t,s=s(),r.memoizedState=[s,t],s},useReducer:function(s,t,r){var n=Rb();return t=r!==void 0?r(t):t,n.memoizedState=n.baseState=t,s={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:s,lastRenderedState:t},n.queue=s,s=s.dispatch=kkt.bind(null,gu,s),[n.memoizedState,s]},useRef:function(s){var t=Rb();return s={current:s},t.memoizedState=s},useState:JDe,useDebugValue:t3e,useDeferredValue:function(s){return Rb().memoizedState=s},useTransition:function(){var s=JDe(!1),t=s[0];return s=Nkt.bind(null,s[1]),Rb().memoizedState=s,[t,s]},useMutableSource:function(){},useSyncExternalStore:function(s,t,r){var n=gu,a=Rb();if(Wd){if(r===void 0)throw Error(Rn(407));r=r()}else{if(r=t(),Jm===null)throw Error(Rn(349));nA&30||dXe(n,t,r)}a.memoizedState=r;var i={value:r,getSnapshot:t};return a.queue=i,eRe(hXe.bind(null,n,i,s),[s]),n.flags|=2048,Z7(9,uXe.bind(null,n,i,r,t),void 0,null),r},useId:function(){var s=Rb(),t=Jm.identifierPrefix;if(Wd){var r=E2,n=T2;r=(n&~(1<<32-p1(n)-1)).toString(32)+r,t=":"+t+"R"+r,r=K7++,0<\/script>",s=s.removeChild(s.firstChild)):typeof n.is=="string"?s=l.createElement(r,{is:n.is}):(s=l.createElement(r),r==="select"&&(l=s,n.multiple?l.multiple=!0:n.size&&(l.size=n.size))):s=l.createElementNS(s,r),s[Zb]=t,s[H7]=n,RXe(s,t,!1,!1),t.stateNode=s;e:{switch(l=_2e(r,n),r){case"dialog":_d("cancel",s),_d("close",s),a=n;break;case"iframe":case"object":case"embed":_d("load",s),a=n;break;case"video":case"audio":for(a=0;aVP&&(t.flags|=128,n=!0,yR(i,!1),t.lanes=4194304)}else{if(!n)if(s=che(l),s!==null){if(t.flags|=128,n=!0,r=s.updateQueue,r!==null&&(t.updateQueue=r,t.flags|=4),yR(i,!0),i.tail===null&&i.tailMode==="hidden"&&!l.alternate&&!Wd)return hp(t),null}else 2*ch()-i.renderingStartTime>VP&&r!==1073741824&&(t.flags|=128,n=!0,yR(i,!1),t.lanes=4194304);i.isBackwards?(l.sibling=t.child,t.child=l):(r=i.last,r!==null?r.sibling=l:t.child=l,i.last=l)}return i.tail!==null?(t=i.tail,i.rendering=t,i.tail=t.sibling,i.renderingStartTime=ch(),t.sibling=null,r=du.current,ad(du,n?r&1|2:r&1),t):(hp(t),null);case 22:case 23:return o3e(),n=t.memoizedState!==null,s!==null&&s.memoizedState!==null!==n&&(t.flags|=8192),n&&t.mode&1?Zx&1073741824&&(hp(t),t.subtreeFlags&6&&(t.flags|=8192)):hp(t),null;case 24:return null;case 25:return null}throw Error(Rn(156,t.tag))}function Dkt(s,t){switch($Ce(t),t.tag){case 1:return ix(t.type)&&she(),s=t.flags,s&65536?(t.flags=s&-65537|128,t):null;case 3:return UP(),Cd(ax),Cd(jp),ZCe(),s=t.flags,s&65536&&!(s&128)?(t.flags=s&-65537|128,t):null;case 5:return YCe(t),null;case 13:if(Cd(du),s=t.memoizedState,s!==null&&s.dehydrated!==null){if(t.alternate===null)throw Error(Rn(340));zP()}return s=t.flags,s&65536?(t.flags=s&-65537|128,t):null;case 19:return Cd(du),null;case 4:return UP(),null;case 10:return HCe(t.type._context),null;case 22:case 23:return o3e(),null;case 24:return null;default:return null}}var kU=!1,xp=!1,Rkt=typeof WeakSet=="function"?WeakSet:Set,Ga=null;function aI(s,t){var r=s.ref;if(r!==null)if(typeof r=="function")try{r(null)}catch(n){Ou(s,t,n)}else r.current=null}function K2e(s,t,r){try{r()}catch(n){Ou(s,t,n)}}var uRe=!1;function Okt(s,t){if(M2e=Que,s=qZe(),BCe(s)){if("selectionStart"in s)var r={start:s.selectionStart,end:s.selectionEnd};else e:{r=(r=s.ownerDocument)&&r.defaultView||window;var n=r.getSelection&&r.getSelection();if(n&&n.rangeCount!==0){r=n.anchorNode;var a=n.anchorOffset,i=n.focusNode;n=n.focusOffset;try{r.nodeType,i.nodeType}catch{r=null;break e}var l=0,o=-1,c=-1,d=0,h=0,m=s,p=null;t:for(;;){for(var x;m!==r||a!==0&&m.nodeType!==3||(o=l+a),m!==i||n!==0&&m.nodeType!==3||(c=l+n),m.nodeType===3&&(l+=m.nodeValue.length),(x=m.firstChild)!==null;)p=m,m=x;for(;;){if(m===s)break t;if(p===r&&++d===a&&(o=l),p===i&&++h===n&&(c=l),(x=m.nextSibling)!==null)break;m=p,p=m.parentNode}m=x}r=o===-1||c===-1?null:{start:o,end:c}}else r=null}r=r||{start:0,end:0}}else r=null;for(I2e={focusedElem:s,selectionRange:r},Que=!1,Ga=t;Ga!==null;)if(t=Ga,s=t.child,(t.subtreeFlags&1028)!==0&&s!==null)s.return=t,Ga=s;else for(;Ga!==null;){t=Ga;try{var y=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(y!==null){var _=y.memoizedProps,b=y.memoizedState,j=t.stateNode,k=j.getSnapshotBeforeUpdate(t.elementType===t.type?_:Xv(t.type,_),b);j.__reactInternalSnapshotBeforeUpdate=k}break;case 3:var T=t.stateNode.containerInfo;T.nodeType===1?T.textContent="":T.nodeType===9&&T.documentElement&&T.removeChild(T.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(Rn(163))}}catch(E){Ou(t,t.return,E)}if(s=t.sibling,s!==null){s.return=t.return,Ga=s;break}Ga=t.return}return y=uRe,uRe=!1,y}function VO(s,t,r){var n=t.updateQueue;if(n=n!==null?n.lastEffect:null,n!==null){var a=n=n.next;do{if((a.tag&s)===s){var i=a.destroy;a.destroy=void 0,i!==void 0&&K2e(t,r,i)}a=a.next}while(a!==n)}}function Dpe(s,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var r=t=t.next;do{if((r.tag&s)===s){var n=r.create;r.destroy=n()}r=r.next}while(r!==t)}}function Y2e(s){var t=s.ref;if(t!==null){var r=s.stateNode;switch(s.tag){case 5:s=r;break;default:s=r}typeof t=="function"?t(s):t.current=s}}function BXe(s){var t=s.alternate;t!==null&&(s.alternate=null,BXe(t)),s.child=null,s.deletions=null,s.sibling=null,s.tag===5&&(t=s.stateNode,t!==null&&(delete t[Zb],delete t[H7],delete t[D2e],delete t[vkt],delete t[bkt])),s.stateNode=null,s.return=null,s.dependencies=null,s.memoizedProps=null,s.memoizedState=null,s.pendingProps=null,s.stateNode=null,s.updateQueue=null}function zXe(s){return s.tag===5||s.tag===3||s.tag===4}function hRe(s){e:for(;;){for(;s.sibling===null;){if(s.return===null||zXe(s.return))return null;s=s.return}for(s.sibling.return=s.return,s=s.sibling;s.tag!==5&&s.tag!==6&&s.tag!==18;){if(s.flags&2||s.child===null||s.tag===4)continue e;s.child.return=s,s=s.child}if(!(s.flags&2))return s.stateNode}}function Z2e(s,t,r){var n=s.tag;if(n===5||n===6)s=s.stateNode,t?r.nodeType===8?r.parentNode.insertBefore(s,t):r.insertBefore(s,t):(r.nodeType===8?(t=r.parentNode,t.insertBefore(s,r)):(t=r,t.appendChild(s)),r=r._reactRootContainer,r!=null||t.onclick!==null||(t.onclick=the));else if(n!==4&&(s=s.child,s!==null))for(Z2e(s,t,r),s=s.sibling;s!==null;)Z2e(s,t,r),s=s.sibling}function X2e(s,t,r){var n=s.tag;if(n===5||n===6)s=s.stateNode,t?r.insertBefore(s,t):r.appendChild(s);else if(n!==4&&(s=s.child,s!==null))for(X2e(s,t,r),s=s.sibling;s!==null;)X2e(s,t,r),s=s.sibling}var Ef=null,e1=!1;function pN(s,t,r){for(r=r.child;r!==null;)$Xe(s,t,r),r=r.sibling}function $Xe(s,t,r){if(c_&&typeof c_.onCommitFiberUnmount=="function")try{c_.onCommitFiberUnmount(Cpe,r)}catch{}switch(r.tag){case 5:xp||aI(r,t);case 6:var n=Ef,a=e1;Ef=null,pN(s,t,r),Ef=n,e1=a,Ef!==null&&(e1?(s=Ef,r=r.stateNode,s.nodeType===8?s.parentNode.removeChild(r):s.removeChild(r)):Ef.removeChild(r.stateNode));break;case 18:Ef!==null&&(e1?(s=Ef,r=r.stateNode,s.nodeType===8?v1e(s.parentNode,r):s.nodeType===1&&v1e(s,r),z7(s)):v1e(Ef,r.stateNode));break;case 4:n=Ef,a=e1,Ef=r.stateNode.containerInfo,e1=!0,pN(s,t,r),Ef=n,e1=a;break;case 0:case 11:case 14:case 15:if(!xp&&(n=r.updateQueue,n!==null&&(n=n.lastEffect,n!==null))){a=n=n.next;do{var i=a,l=i.destroy;i=i.tag,l!==void 0&&(i&2||i&4)&&K2e(r,t,l),a=a.next}while(a!==n)}pN(s,t,r);break;case 1:if(!xp&&(aI(r,t),n=r.stateNode,typeof n.componentWillUnmount=="function"))try{n.props=r.memoizedProps,n.state=r.memoizedState,n.componentWillUnmount()}catch(o){Ou(r,t,o)}pN(s,t,r);break;case 21:pN(s,t,r);break;case 22:r.mode&1?(xp=(n=xp)||r.memoizedState!==null,pN(s,t,r),xp=n):pN(s,t,r);break;default:pN(s,t,r)}}function mRe(s){var t=s.updateQueue;if(t!==null){s.updateQueue=null;var r=s.stateNode;r===null&&(r=s.stateNode=new Rkt),t.forEach(function(n){var a=Gkt.bind(null,s,n);r.has(n)||(r.add(n),n.then(a,a))})}}function Uv(s,t){var r=t.deletions;if(r!==null)for(var n=0;na&&(a=l),n&=~i}if(n=a,n=ch()-n,n=(120>n?120:480>n?480:1080>n?1080:1920>n?1920:3e3>n?3e3:4320>n?4320:1960*Bkt(n/1960))-n,10s?16:s,yk===null)var n=!1;else{if(s=yk,yk=null,fhe=0,Dl&6)throw Error(Rn(331));var a=Dl;for(Dl|=4,Ga=s.current;Ga!==null;){var i=Ga,l=i.child;if(Ga.flags&16){var o=i.deletions;if(o!==null){for(var c=0;cch()-a3e?lE(s,0):n3e|=r),ox(s,t)}function YXe(s,t){t===0&&(s.mode&1?(t=gU,gU<<=1,!(gU&130023424)&&(gU=4194304)):t=1);var r=bg();s=sj(s,t),s!==null&&(MB(s,t,r),ox(s,r))}function Hkt(s){var t=s.memoizedState,r=0;t!==null&&(r=t.retryLane),YXe(s,r)}function Gkt(s,t){var r=0;switch(s.tag){case 13:var n=s.stateNode,a=s.memoizedState;a!==null&&(r=a.retryLane);break;case 19:n=s.stateNode;break;default:throw Error(Rn(314))}n!==null&&n.delete(t),YXe(s,r)}var ZXe;ZXe=function(s,t,r){if(s!==null)if(s.memoizedProps!==t.pendingProps||ax.current)ex=!0;else{if(!(s.lanes&r)&&!(t.flags&128))return ex=!1,Pkt(s,t,r);ex=!!(s.flags&131072)}else ex=!1,Wd&&t.flags&1048576&&eXe(t,ahe,t.index);switch(t.lanes=0,t.tag){case 2:var n=t.type;PV(s,t),s=t.pendingProps;var a=BP(t,jp.current);TI(t,r),a=QCe(null,t,n,s,a,r);var i=JCe();return t.flags|=1,typeof a=="object"&&a!==null&&typeof a.render=="function"&&a.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,ix(n)?(i=!0,rhe(t)):i=!1,t.memoizedState=a.state!==null&&a.state!==void 0?a.state:null,WCe(t),a.updater=Lpe,t.stateNode=a,a._reactInternals=t,$2e(t,n,s,r),t=V2e(null,t,n,!0,i,r)):(t.tag=0,Wd&&i&&zCe(t),ig(null,t,a,r),t=t.child),t;case 16:n=t.elementType;e:{switch(PV(s,t),s=t.pendingProps,a=n._init,n=a(n._payload),t.type=n,a=t.tag=Kkt(n),s=Xv(n,s),a){case 0:t=q2e(null,t,n,s,r);break e;case 1:t=lRe(null,t,n,s,r);break e;case 11:t=iRe(null,t,n,s,r);break e;case 14:t=oRe(null,t,n,Xv(n.type,s),r);break e}throw Error(Rn(306,n,""))}return t;case 0:return n=t.type,a=t.pendingProps,a=t.elementType===n?a:Xv(n,a),q2e(s,t,n,a,r);case 1:return n=t.type,a=t.pendingProps,a=t.elementType===n?a:Xv(n,a),lRe(s,t,n,a,r);case 3:e:{if(PXe(t),s===null)throw Error(Rn(387));n=t.pendingProps,i=t.memoizedState,a=i.element,iXe(s,t),lhe(t,n,null,r);var l=t.memoizedState;if(n=l.element,i.isDehydrated)if(i={element:n,isDehydrated:!1,cache:l.cache,pendingSuspenseBoundaries:l.pendingSuspenseBoundaries,transitions:l.transitions},t.updateQueue.baseState=i,t.memoizedState=i,t.flags&256){a=qP(Error(Rn(423)),t),t=cRe(s,t,n,r,a);break e}else if(n!==a){a=qP(Error(Rn(424)),t),t=cRe(s,t,n,r,a);break e}else for(o0=Mk(t.stateNode.containerInfo.firstChild),c0=t,Wd=!0,a1=null,r=nXe(t,null,n,r),t.child=r;r;)r.flags=r.flags&-3|4096,r=r.sibling;else{if(zP(),n===a){t=rj(s,t,r);break e}ig(s,t,n,r)}t=t.child}return t;case 5:return oXe(t),s===null&&F2e(t),n=t.type,a=t.pendingProps,i=s!==null?s.memoizedProps:null,l=a.children,P2e(n,a)?l=null:i!==null&&P2e(n,i)&&(t.flags|=32),IXe(s,t),ig(s,t,l,r),t.child;case 6:return s===null&&F2e(t),null;case 13:return LXe(s,t,r);case 4:return KCe(t,t.stateNode.containerInfo),n=t.pendingProps,s===null?t.child=$P(t,null,n,r):ig(s,t,n,r),t.child;case 11:return n=t.type,a=t.pendingProps,a=t.elementType===n?a:Xv(n,a),iRe(s,t,n,a,r);case 7:return ig(s,t,t.pendingProps,r),t.child;case 8:return ig(s,t,t.pendingProps.children,r),t.child;case 12:return ig(s,t,t.pendingProps.children,r),t.child;case 10:e:{if(n=t.type._context,a=t.pendingProps,i=t.memoizedProps,l=a.value,ad(ihe,n._currentValue),n._currentValue=l,i!==null)if(T1(i.value,l)){if(i.children===a.children&&!ax.current){t=rj(s,t,r);break e}}else for(i=t.child,i!==null&&(i.return=t);i!==null;){var o=i.dependencies;if(o!==null){l=i.child;for(var c=o.firstContext;c!==null;){if(c.context===n){if(i.tag===1){c=O2(-1,r&-r),c.tag=2;var d=i.updateQueue;if(d!==null){d=d.shared;var h=d.pending;h===null?c.next=c:(c.next=h.next,h.next=c),d.pending=c}}i.lanes|=r,c=i.alternate,c!==null&&(c.lanes|=r),B2e(i.return,r,t),o.lanes|=r;break}c=c.next}}else if(i.tag===10)l=i.type===t.type?null:i.child;else if(i.tag===18){if(l=i.return,l===null)throw Error(Rn(341));l.lanes|=r,o=l.alternate,o!==null&&(o.lanes|=r),B2e(l,r,t),l=i.sibling}else l=i.child;if(l!==null)l.return=i;else for(l=i;l!==null;){if(l===t){l=null;break}if(i=l.sibling,i!==null){i.return=l.return,l=i;break}l=l.return}i=l}ig(s,t,a.children,r),t=t.child}return t;case 9:return a=t.type,n=t.pendingProps.children,TI(t,r),a=Xy(a),n=n(a),t.flags|=1,ig(s,t,n,r),t.child;case 14:return n=t.type,a=Xv(n,t.pendingProps),a=Xv(n.type,a),oRe(s,t,n,a,r);case 15:return AXe(s,t,t.type,t.pendingProps,r);case 17:return n=t.type,a=t.pendingProps,a=t.elementType===n?a:Xv(n,a),PV(s,t),t.tag=1,ix(n)?(s=!0,rhe(t)):s=!1,TI(t,r),CXe(t,n,a),$2e(t,n,a,r),V2e(null,t,n,!0,s,r);case 19:return DXe(s,t,r);case 22:return MXe(s,t,r)}throw Error(Rn(156,t.tag))};function XXe(s,t){return NZe(s,t)}function Wkt(s,t,r,n){this.tag=s,this.key=r,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,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 Oy(s,t,r,n){return new Wkt(s,t,r,n)}function c3e(s){return s=s.prototype,!(!s||!s.isReactComponent)}function Kkt(s){if(typeof s=="function")return c3e(s)?1:0;if(s!=null){if(s=s.$$typeof,s===TCe)return 11;if(s===ECe)return 14}return 2}function Dk(s,t){var r=s.alternate;return r===null?(r=Oy(s.tag,t,s.key,s.mode),r.elementType=s.elementType,r.type=s.type,r.stateNode=s.stateNode,r.alternate=s,s.alternate=r):(r.pendingProps=t,r.type=s.type,r.flags=0,r.subtreeFlags=0,r.deletions=null),r.flags=s.flags&14680064,r.childLanes=s.childLanes,r.lanes=s.lanes,r.child=s.child,r.memoizedProps=s.memoizedProps,r.memoizedState=s.memoizedState,r.updateQueue=s.updateQueue,t=s.dependencies,r.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},r.sibling=s.sibling,r.index=s.index,r.ref=s.ref,r}function RV(s,t,r,n,a,i){var l=2;if(n=s,typeof s=="function")c3e(s)&&(l=1);else if(typeof s=="string")l=5;else e:switch(s){case Z6:return cE(r.children,a,i,t);case CCe:l=8,a|=8;break;case u2e:return s=Oy(12,r,t,a|2),s.elementType=u2e,s.lanes=i,s;case h2e:return s=Oy(13,r,t,a),s.elementType=h2e,s.lanes=i,s;case m2e:return s=Oy(19,r,t,a),s.elementType=m2e,s.lanes=i,s;case oZe:return Ope(r,a,i,t);default:if(typeof s=="object"&&s!==null)switch(s.$$typeof){case aZe:l=10;break e;case iZe:l=9;break e;case TCe:l=11;break e;case ECe:l=14;break e;case FN:l=16,n=null;break e}throw Error(Rn(130,s==null?s:typeof s,""))}return t=Oy(l,r,t,a),t.elementType=s,t.type=n,t.lanes=i,t}function cE(s,t,r,n){return s=Oy(7,s,n,t),s.lanes=r,s}function Ope(s,t,r,n){return s=Oy(22,s,n,t),s.elementType=oZe,s.lanes=r,s.stateNode={isHidden:!1},s}function C1e(s,t,r){return s=Oy(6,s,null,t),s.lanes=r,s}function T1e(s,t,r){return t=Oy(4,s.children!==null?s.children:[],s.key,t),t.lanes=r,t.stateNode={containerInfo:s.containerInfo,pendingChildren:null,implementation:s.implementation},t}function Ykt(s,t,r,n,a){this.tag=t,this.containerInfo=s,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=l1e(0),this.expirationTimes=l1e(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=l1e(0),this.identifierPrefix=n,this.onRecoverableError=a,this.mutableSourceEagerHydrationData=null}function d3e(s,t,r,n,a,i,l,o,c){return s=new Ykt(s,t,r,o,c),t===1?(t=1,i===!0&&(t|=8)):t=0,i=Oy(3,null,null,t),s.current=i,i.stateNode=s,i.memoizedState={element:n,isDehydrated:r,cache:null,transitions:null,pendingSuspenseBoundaries:null},WCe(i),s}function Zkt(s,t,r){var n=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(tQe)}catch(s){console.error(s)}}tQe(),tZe.exports=L0;var tx=tZe.exports;const f3e=ol(tx);var sQe,_Re=tx;sQe=_Re.createRoot,_Re.hydrateRoot;const tSt=1,sSt=1e6;let E1e=0;function rSt(){return E1e=(E1e+1)%Number.MAX_SAFE_INTEGER,E1e.toString()}const A1e=new Map,wRe=s=>{if(A1e.has(s))return;const t=setTimeout(()=>{A1e.delete(s),WO({type:"REMOVE_TOAST",toastId:s})},sSt);A1e.set(s,t)},nSt=(s,t)=>{switch(t.type){case"ADD_TOAST":return{...s,toasts:[t.toast,...s.toasts].slice(0,tSt)};case"UPDATE_TOAST":return{...s,toasts:s.toasts.map(r=>r.id===t.toast.id?{...r,...t.toast}:r)};case"DISMISS_TOAST":{const{toastId:r}=t;return r?wRe(r):s.toasts.forEach(n=>{wRe(n.id)}),{...s,toasts:s.toasts.map(n=>n.id===r||r===void 0?{...n,open:!1}:n)}}case"REMOVE_TOAST":return t.toastId===void 0?{...s,toasts:[]}:{...s,toasts:s.toasts.filter(r=>r.id!==t.toastId)}}},OV=[];let FV={toasts:[]};function WO(s){FV=nSt(FV,s),OV.forEach(t=>{t(FV)})}function En({...s}){const t=rSt(),r=a=>WO({type:"UPDATE_TOAST",toast:{...a,id:t}}),n=()=>WO({type:"DISMISS_TOAST",toastId:t});return WO({type:"ADD_TOAST",toast:{...s,id:t,open:!0,onOpenChange:a=>{a||n()}}}),{id:t,dismiss:n,update:r}}function li(){const[s,t]=S.useState(FV);return S.useEffect(()=>(OV.push(t),()=>{const r=OV.indexOf(t);r>-1&&OV.splice(r,1)}),[s]),{...s,toast:En,dismiss:r=>WO({type:"DISMISS_TOAST",toastId:r})}}function an(s,t,{checkForDefaultPrevented:r=!0}={}){return function(a){if(s==null||s(a),r===!1||!a.defaultPrevented)return t==null?void 0:t(a)}}function jRe(s,t){if(typeof s=="function")return s(t);s!=null&&(s.current=t)}function nj(...s){return t=>{let r=!1;const n=s.map(a=>{const i=jRe(a,t);return!r&&typeof i=="function"&&(r=!0),i});if(r)return()=>{for(let a=0;a{const{children:l,...o}=i,c=S.useMemo(()=>o,Object.values(o));return e.jsx(r.Provider,{value:c,children:l})};n.displayName=s+"Provider";function a(i){const l=S.useContext(r);if(l)return l;if(t!==void 0)return t;throw new Error(`\`${i}\` must be used within \`${s}\``)}return[n,a]}function _u(s,t=[]){let r=[];function n(i,l){const o=S.createContext(l),c=r.length;r=[...r,l];const d=m=>{var j;const{scope:p,children:x,...y}=m,_=((j=p==null?void 0:p[s])==null?void 0:j[c])||o,b=S.useMemo(()=>y,Object.values(y));return e.jsx(_.Provider,{value:b,children:x})};d.displayName=i+"Provider";function h(m,p){var _;const x=((_=p==null?void 0:p[s])==null?void 0:_[c])||o,y=S.useContext(x);if(y)return y;if(l!==void 0)return l;throw new Error(`\`${m}\` must be used within \`${i}\``)}return[d,h]}const a=()=>{const i=r.map(l=>S.createContext(l));return function(o){const c=(o==null?void 0:o[s])||i;return S.useMemo(()=>({[`__scope${s}`]:{...o,[s]:c}}),[o,c])}};return a.scopeName=s,[n,iSt(a,...t)]}function iSt(...s){const t=s[0];if(s.length===1)return t;const r=()=>{const n=s.map(a=>({useScope:a(),scopeName:a.scopeName}));return function(i){const l=n.reduce((o,{useScope:c,scopeName:d})=>{const m=c(i)[`__scope${d}`];return{...o,...m}},{});return S.useMemo(()=>({[`__scope${t.scopeName}`]:l}),[l])}};return r.scopeName=t.scopeName,r}function mS(s){const t=oSt(s),r=S.forwardRef((n,a)=>{const{children:i,...l}=n,o=S.Children.toArray(i),c=o.find(lSt);if(c){const d=c.props.children,h=o.map(m=>m===c?S.Children.count(d)>1?S.Children.only(null):S.isValidElement(d)?d.props.children:null:m);return e.jsx(t,{...l,ref:a,children:S.isValidElement(d)?S.cloneElement(d,void 0,h):null})}return e.jsx(t,{...l,ref:a,children:i})});return r.displayName=`${s}.Slot`,r}var p3e=mS("Slot");function oSt(s){const t=S.forwardRef((r,n)=>{const{children:a,...i}=r;if(S.isValidElement(a)){const l=dSt(a),o=cSt(i,a.props);return a.type!==S.Fragment&&(o.ref=n?nj(n,l):l),S.cloneElement(a,o)}return S.Children.count(a)>1?S.Children.only(null):null});return t.displayName=`${s}.SlotClone`,t}var rQe=Symbol("radix.slottable");function nQe(s){const t=({children:r})=>e.jsx(e.Fragment,{children:r});return t.displayName=`${s}.Slottable`,t.__radixId=rQe,t}function lSt(s){return S.isValidElement(s)&&typeof s.type=="function"&&"__radixId"in s.type&&s.type.__radixId===rQe}function cSt(s,t){const r={...t};for(const n in t){const a=s[n],i=t[n];/^on[A-Z]/.test(n)?a&&i?r[n]=(...o)=>{const c=i(...o);return a(...o),c}:a&&(r[n]=a):n==="style"?r[n]={...a,...i}:n==="className"&&(r[n]=[a,i].filter(Boolean).join(" "))}return{...s,...r}}function dSt(s){var n,a;let t=(n=Object.getOwnPropertyDescriptor(s.props,"ref"))==null?void 0:n.get,r=t&&"isReactWarning"in t&&t.isReactWarning;return r?s.ref:(t=(a=Object.getOwnPropertyDescriptor(s,"ref"))==null?void 0:a.get,r=t&&"isReactWarning"in t&&t.isReactWarning,r?s.props.ref:s.props.ref||s.ref)}function DB(s){const t=s+"CollectionProvider",[r,n]=_u(t),[a,i]=r(t,{collectionRef:{current:null},itemMap:new Map}),l=_=>{const{scope:b,children:j}=_,k=Nt.useRef(null),T=Nt.useRef(new Map).current;return e.jsx(a,{scope:b,itemMap:T,collectionRef:k,children:j})};l.displayName=t;const o=s+"CollectionSlot",c=mS(o),d=Nt.forwardRef((_,b)=>{const{scope:j,children:k}=_,T=i(o,j),E=_i(b,T.collectionRef);return e.jsx(c,{ref:E,children:k})});d.displayName=o;const h=s+"CollectionItemSlot",m="data-radix-collection-item",p=mS(h),x=Nt.forwardRef((_,b)=>{const{scope:j,children:k,...T}=_,E=Nt.useRef(null),A=_i(b,E),D=i(h,j);return Nt.useEffect(()=>(D.itemMap.set(E,{ref:E,...T}),()=>void D.itemMap.delete(E))),e.jsx(p,{[m]:"",ref:A,children:k})});x.displayName=h;function y(_){const b=i(s+"CollectionConsumer",_);return Nt.useCallback(()=>{const k=b.collectionRef.current;if(!k)return[];const T=Array.from(k.querySelectorAll(`[${m}]`));return Array.from(b.itemMap.values()).sort((D,R)=>T.indexOf(D.ref.current)-T.indexOf(R.ref.current))},[b.collectionRef,b.itemMap])}return[{Provider:l,Slot:d,ItemSlot:x},y,n]}var uSt=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Vn=uSt.reduce((s,t)=>{const r=mS(`Primitive.${t}`),n=S.forwardRef((a,i)=>{const{asChild:l,...o}=a,c=l?r:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),e.jsx(c,{...o,ref:i})});return n.displayName=`Primitive.${t}`,{...s,[t]:n}},{});function g3e(s,t){s&&tx.flushSync(()=>s.dispatchEvent(t))}function Uu(s){const t=S.useRef(s);return S.useEffect(()=>{t.current=s}),S.useMemo(()=>(...r)=>{var n;return(n=t.current)==null?void 0:n.call(t,...r)},[])}function hSt(s,t=globalThis==null?void 0:globalThis.document){const r=Uu(s);S.useEffect(()=>{const n=a=>{a.key==="Escape"&&r(a)};return t.addEventListener("keydown",n,{capture:!0}),()=>t.removeEventListener("keydown",n,{capture:!0})},[r,t])}var mSt="DismissableLayer",sje="dismissableLayer.update",fSt="dismissableLayer.pointerDownOutside",pSt="dismissableLayer.focusOutside",NRe,aQe=S.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),PS=S.forwardRef((s,t)=>{const{disableOutsidePointerEvents:r=!1,onEscapeKeyDown:n,onPointerDownOutside:a,onFocusOutside:i,onInteractOutside:l,onDismiss:o,...c}=s,d=S.useContext(aQe),[h,m]=S.useState(null),p=(h==null?void 0:h.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,x]=S.useState({}),y=_i(t,R=>m(R)),_=Array.from(d.layers),[b]=[...d.layersWithOutsidePointerEventsDisabled].slice(-1),j=_.indexOf(b),k=h?_.indexOf(h):-1,T=d.layersWithOutsidePointerEventsDisabled.size>0,E=k>=j,A=xSt(R=>{const z=R.target,O=[...d.branches].some($=>$.contains(z));!E||O||(a==null||a(R),l==null||l(R),R.defaultPrevented||o==null||o())},p),D=ySt(R=>{const z=R.target;[...d.branches].some($=>$.contains(z))||(i==null||i(R),l==null||l(R),R.defaultPrevented||o==null||o())},p);return hSt(R=>{k===d.layers.size-1&&(n==null||n(R),!R.defaultPrevented&&o&&(R.preventDefault(),o()))},p),S.useEffect(()=>{if(h)return r&&(d.layersWithOutsidePointerEventsDisabled.size===0&&(NRe=p.body.style.pointerEvents,p.body.style.pointerEvents="none"),d.layersWithOutsidePointerEventsDisabled.add(h)),d.layers.add(h),kRe(),()=>{r&&d.layersWithOutsidePointerEventsDisabled.size===1&&(p.body.style.pointerEvents=NRe)}},[h,p,r,d]),S.useEffect(()=>()=>{h&&(d.layers.delete(h),d.layersWithOutsidePointerEventsDisabled.delete(h),kRe())},[h,d]),S.useEffect(()=>{const R=()=>x({});return document.addEventListener(sje,R),()=>document.removeEventListener(sje,R)},[]),e.jsx(Vn.div,{...c,ref:y,style:{pointerEvents:T?E?"auto":"none":void 0,...s.style},onFocusCapture:an(s.onFocusCapture,D.onFocusCapture),onBlurCapture:an(s.onBlurCapture,D.onBlurCapture),onPointerDownCapture:an(s.onPointerDownCapture,A.onPointerDownCapture)})});PS.displayName=mSt;var gSt="DismissableLayerBranch",iQe=S.forwardRef((s,t)=>{const r=S.useContext(aQe),n=S.useRef(null),a=_i(t,n);return S.useEffect(()=>{const i=n.current;if(i)return r.branches.add(i),()=>{r.branches.delete(i)}},[r.branches]),e.jsx(Vn.div,{...s,ref:a})});iQe.displayName=gSt;function xSt(s,t=globalThis==null?void 0:globalThis.document){const r=Uu(s),n=S.useRef(!1),a=S.useRef(()=>{});return S.useEffect(()=>{const i=o=>{if(o.target&&!n.current){let c=function(){oQe(fSt,r,d,{discrete:!0})};const d={originalEvent:o};o.pointerType==="touch"?(t.removeEventListener("click",a.current),a.current=c,t.addEventListener("click",a.current,{once:!0})):c()}else t.removeEventListener("click",a.current);n.current=!1},l=window.setTimeout(()=>{t.addEventListener("pointerdown",i)},0);return()=>{window.clearTimeout(l),t.removeEventListener("pointerdown",i),t.removeEventListener("click",a.current)}},[t,r]),{onPointerDownCapture:()=>n.current=!0}}function ySt(s,t=globalThis==null?void 0:globalThis.document){const r=Uu(s),n=S.useRef(!1);return S.useEffect(()=>{const a=i=>{i.target&&!n.current&&oQe(pSt,r,{originalEvent:i},{discrete:!1})};return t.addEventListener("focusin",a),()=>t.removeEventListener("focusin",a)},[t,r]),{onFocusCapture:()=>n.current=!0,onBlurCapture:()=>n.current=!1}}function kRe(){const s=new CustomEvent(sje);document.dispatchEvent(s)}function oQe(s,t,r,{discrete:n}){const a=r.originalEvent.target,i=new CustomEvent(s,{bubbles:!1,cancelable:!0,detail:r});t&&a.addEventListener(s,t,{once:!0}),n?g3e(a,i):a.dispatchEvent(i)}var vSt=PS,bSt=iQe,Ku=globalThis!=null&&globalThis.document?S.useLayoutEffect:()=>{},_St="Portal",s8=S.forwardRef((s,t)=>{var o;const{container:r,...n}=s,[a,i]=S.useState(!1);Ku(()=>i(!0),[]);const l=r||a&&((o=globalThis==null?void 0:globalThis.document)==null?void 0:o.body);return l?f3e.createPortal(e.jsx(Vn.div,{...n,ref:t}),l):null});s8.displayName=_St;function wSt(s,t){return S.useReducer((r,n)=>t[r][n]??r,s)}var vh=s=>{const{present:t,children:r}=s,n=jSt(t),a=typeof r=="function"?r({present:n.isPresent}):S.Children.only(r),i=_i(n.ref,NSt(a));return typeof r=="function"||n.isPresent?S.cloneElement(a,{ref:i}):null};vh.displayName="Presence";function jSt(s){const[t,r]=S.useState(),n=S.useRef(null),a=S.useRef(s),i=S.useRef("none"),l=s?"mounted":"unmounted",[o,c]=wSt(l,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return S.useEffect(()=>{const d=TU(n.current);i.current=o==="mounted"?d:"none"},[o]),Ku(()=>{const d=n.current,h=a.current;if(h!==s){const p=i.current,x=TU(d);s?c("MOUNT"):x==="none"||(d==null?void 0:d.display)==="none"?c("UNMOUNT"):c(h&&p!==x?"ANIMATION_OUT":"UNMOUNT"),a.current=s}},[s,c]),Ku(()=>{if(t){let d;const h=t.ownerDocument.defaultView??window,m=x=>{const _=TU(n.current).includes(x.animationName);if(x.target===t&&_&&(c("ANIMATION_END"),!a.current)){const b=t.style.animationFillMode;t.style.animationFillMode="forwards",d=h.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=b)})}},p=x=>{x.target===t&&(i.current=TU(n.current))};return t.addEventListener("animationstart",p),t.addEventListener("animationcancel",m),t.addEventListener("animationend",m),()=>{h.clearTimeout(d),t.removeEventListener("animationstart",p),t.removeEventListener("animationcancel",m),t.removeEventListener("animationend",m)}}else c("ANIMATION_END")},[t,c]),{isPresent:["mounted","unmountSuspended"].includes(o),ref:S.useCallback(d=>{n.current=d?getComputedStyle(d):null,r(d)},[])}}function TU(s){return(s==null?void 0:s.animationName)||"none"}function NSt(s){var n,a;let t=(n=Object.getOwnPropertyDescriptor(s.props,"ref"))==null?void 0:n.get,r=t&&"isReactWarning"in t&&t.isReactWarning;return r?s.ref:(t=(a=Object.getOwnPropertyDescriptor(s,"ref"))==null?void 0:a.get,r=t&&"isReactWarning"in t&&t.isReactWarning,r?s.props.ref:s.props.ref||s.ref)}var kSt=jCe[" useInsertionEffect ".trim().toString()]||Ku;function af({prop:s,defaultProp:t,onChange:r=()=>{},caller:n}){const[a,i,l]=SSt({defaultProp:t,onChange:r}),o=s!==void 0,c=o?s:a;{const h=S.useRef(s!==void 0);S.useEffect(()=>{const m=h.current;m!==o&&console.warn(`${n} is changing from ${m?"controlled":"uncontrolled"} to ${o?"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.`),h.current=o},[o,n])}const d=S.useCallback(h=>{var m;if(o){const p=CSt(h)?h(s):h;p!==s&&((m=l.current)==null||m.call(l,p))}else i(h)},[o,s,i,l]);return[c,d]}function SSt({defaultProp:s,onChange:t}){const[r,n]=S.useState(s),a=S.useRef(r),i=S.useRef(t);return kSt(()=>{i.current=t},[t]),S.useEffect(()=>{var l;a.current!==r&&((l=i.current)==null||l.call(i,r),a.current=r)},[r,a]),[r,n,i]}function CSt(s){return typeof s=="function"}var lQe=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"}),TSt="VisuallyHidden",Upe=S.forwardRef((s,t)=>e.jsx(Vn.span,{...s,ref:t,style:{...lQe,...s.style}}));Upe.displayName=TSt;var ESt=Upe,x3e="ToastProvider",[y3e,ASt,MSt]=DB("Toast"),[cQe,cZs]=_u("Toast",[MSt]),[ISt,qpe]=cQe(x3e),dQe=s=>{const{__scopeToast:t,label:r="Notification",duration:n=5e3,swipeDirection:a="right",swipeThreshold:i=50,children:l}=s,[o,c]=S.useState(null),[d,h]=S.useState(0),m=S.useRef(!1),p=S.useRef(!1);return r.trim()||console.error(`Invalid prop \`label\` supplied to \`${x3e}\`. Expected non-empty \`string\`.`),e.jsx(y3e.Provider,{scope:t,children:e.jsx(ISt,{scope:t,label:r,duration:n,swipeDirection:a,swipeThreshold:i,toastCount:d,viewport:o,onViewportChange:c,onToastAdd:S.useCallback(()=>h(x=>x+1),[]),onToastRemove:S.useCallback(()=>h(x=>x-1),[]),isFocusedToastEscapeKeyDownRef:m,isClosePausedRef:p,children:l})})};dQe.displayName=x3e;var uQe="ToastViewport",PSt=["F8"],rje="toast.viewportPause",nje="toast.viewportResume",hQe=S.forwardRef((s,t)=>{const{__scopeToast:r,hotkey:n=PSt,label:a="Notifications ({hotkey})",...i}=s,l=qpe(uQe,r),o=ASt(r),c=S.useRef(null),d=S.useRef(null),h=S.useRef(null),m=S.useRef(null),p=_i(t,m,l.onViewportChange),x=n.join("+").replace(/Key/g,"").replace(/Digit/g,""),y=l.toastCount>0;S.useEffect(()=>{const b=j=>{var T;n.length!==0&&n.every(E=>j[E]||j.code===E)&&((T=m.current)==null||T.focus())};return document.addEventListener("keydown",b),()=>document.removeEventListener("keydown",b)},[n]),S.useEffect(()=>{const b=c.current,j=m.current;if(y&&b&&j){const k=()=>{if(!l.isClosePausedRef.current){const D=new CustomEvent(rje);j.dispatchEvent(D),l.isClosePausedRef.current=!0}},T=()=>{if(l.isClosePausedRef.current){const D=new CustomEvent(nje);j.dispatchEvent(D),l.isClosePausedRef.current=!1}},E=D=>{!b.contains(D.relatedTarget)&&T()},A=()=>{b.contains(document.activeElement)||T()};return b.addEventListener("focusin",k),b.addEventListener("focusout",E),b.addEventListener("pointermove",k),b.addEventListener("pointerleave",A),window.addEventListener("blur",k),window.addEventListener("focus",T),()=>{b.removeEventListener("focusin",k),b.removeEventListener("focusout",E),b.removeEventListener("pointermove",k),b.removeEventListener("pointerleave",A),window.removeEventListener("blur",k),window.removeEventListener("focus",T)}}},[y,l.isClosePausedRef]);const _=S.useCallback(({tabbingDirection:b})=>{const k=o().map(T=>{const E=T.ref.current,A=[E,...GSt(E)];return b==="forwards"?A:A.reverse()});return(b==="forwards"?k.reverse():k).flat()},[o]);return S.useEffect(()=>{const b=m.current;if(b){const j=k=>{var A,D,R;const T=k.altKey||k.ctrlKey||k.metaKey;if(k.key==="Tab"&&!T){const z=document.activeElement,O=k.shiftKey;if(k.target===b&&O){(A=d.current)==null||A.focus();return}const Z=_({tabbingDirection:O?"backwards":"forwards"}),J=Z.findIndex(K=>K===z);M1e(Z.slice(J+1))?k.preventDefault():O?(D=d.current)==null||D.focus():(R=h.current)==null||R.focus()}};return b.addEventListener("keydown",j),()=>b.removeEventListener("keydown",j)}},[o,_]),e.jsxs(bSt,{ref:c,role:"region","aria-label":a.replace("{hotkey}",x),tabIndex:-1,style:{pointerEvents:y?void 0:"none"},children:[y&&e.jsx(aje,{ref:d,onFocusFromOutsideViewport:()=>{const b=_({tabbingDirection:"forwards"});M1e(b)}}),e.jsx(y3e.Slot,{scope:r,children:e.jsx(Vn.ol,{tabIndex:-1,...i,ref:p})}),y&&e.jsx(aje,{ref:h,onFocusFromOutsideViewport:()=>{const b=_({tabbingDirection:"backwards"});M1e(b)}})]})});hQe.displayName=uQe;var mQe="ToastFocusProxy",aje=S.forwardRef((s,t)=>{const{__scopeToast:r,onFocusFromOutsideViewport:n,...a}=s,i=qpe(mQe,r);return e.jsx(Upe,{"aria-hidden":!0,tabIndex:0,...a,ref:t,style:{position:"fixed"},onFocus:l=>{var d;const o=l.relatedTarget;!((d=i.viewport)!=null&&d.contains(o))&&n()}})});aje.displayName=mQe;var RB="Toast",LSt="toast.swipeStart",DSt="toast.swipeMove",RSt="toast.swipeCancel",OSt="toast.swipeEnd",fQe=S.forwardRef((s,t)=>{const{forceMount:r,open:n,defaultOpen:a,onOpenChange:i,...l}=s,[o,c]=af({prop:n,defaultProp:a??!0,onChange:i,caller:RB});return e.jsx(vh,{present:r||o,children:e.jsx(zSt,{open:o,...l,ref:t,onClose:()=>c(!1),onPause:Uu(s.onPause),onResume:Uu(s.onResume),onSwipeStart:an(s.onSwipeStart,d=>{d.currentTarget.setAttribute("data-swipe","start")}),onSwipeMove:an(s.onSwipeMove,d=>{const{x:h,y:m}=d.detail.delta;d.currentTarget.setAttribute("data-swipe","move"),d.currentTarget.style.setProperty("--radix-toast-swipe-move-x",`${h}px`),d.currentTarget.style.setProperty("--radix-toast-swipe-move-y",`${m}px`)}),onSwipeCancel:an(s.onSwipeCancel,d=>{d.currentTarget.setAttribute("data-swipe","cancel"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),d.currentTarget.style.removeProperty("--radix-toast-swipe-end-x"),d.currentTarget.style.removeProperty("--radix-toast-swipe-end-y")}),onSwipeEnd:an(s.onSwipeEnd,d=>{const{x:h,y:m}=d.detail.delta;d.currentTarget.setAttribute("data-swipe","end"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),d.currentTarget.style.setProperty("--radix-toast-swipe-end-x",`${h}px`),d.currentTarget.style.setProperty("--radix-toast-swipe-end-y",`${m}px`),c(!1)})})})});fQe.displayName=RB;var[FSt,BSt]=cQe(RB,{onClose(){}}),zSt=S.forwardRef((s,t)=>{const{__scopeToast:r,type:n="foreground",duration:a,open:i,onClose:l,onEscapeKeyDown:o,onPause:c,onResume:d,onSwipeStart:h,onSwipeMove:m,onSwipeCancel:p,onSwipeEnd:x,...y}=s,_=qpe(RB,r),[b,j]=S.useState(null),k=_i(t,K=>j(K)),T=S.useRef(null),E=S.useRef(null),A=a||_.duration,D=S.useRef(0),R=S.useRef(A),z=S.useRef(0),{onToastAdd:O,onToastRemove:$}=_,ee=Uu(()=>{var re;(b==null?void 0:b.contains(document.activeElement))&&((re=_.viewport)==null||re.focus()),l()}),Z=S.useCallback(K=>{!K||K===1/0||(window.clearTimeout(z.current),D.current=new Date().getTime(),z.current=window.setTimeout(ee,K))},[ee]);S.useEffect(()=>{const K=_.viewport;if(K){const re=()=>{Z(R.current),d==null||d()},ie=()=>{const ce=new Date().getTime()-D.current;R.current=R.current-ce,window.clearTimeout(z.current),c==null||c()};return K.addEventListener(rje,ie),K.addEventListener(nje,re),()=>{K.removeEventListener(rje,ie),K.removeEventListener(nje,re)}}},[_.viewport,A,c,d,Z]),S.useEffect(()=>{i&&!_.isClosePausedRef.current&&Z(A)},[i,A,_.isClosePausedRef,Z]),S.useEffect(()=>(O(),()=>$()),[O,$]);const J=S.useMemo(()=>b?_Qe(b):null,[b]);return _.viewport?e.jsxs(e.Fragment,{children:[J&&e.jsx($St,{__scopeToast:r,role:"status","aria-live":n==="foreground"?"assertive":"polite","aria-atomic":!0,children:J}),e.jsx(FSt,{scope:r,onClose:ee,children:tx.createPortal(e.jsx(y3e.ItemSlot,{scope:r,children:e.jsx(vSt,{asChild:!0,onEscapeKeyDown:an(o,()=>{_.isFocusedToastEscapeKeyDownRef.current||ee(),_.isFocusedToastEscapeKeyDownRef.current=!1}),children:e.jsx(Vn.li,{role:"status","aria-live":"off","aria-atomic":!0,tabIndex:0,"data-state":i?"open":"closed","data-swipe-direction":_.swipeDirection,...y,ref:k,style:{userSelect:"none",touchAction:"none",...s.style},onKeyDown:an(s.onKeyDown,K=>{K.key==="Escape"&&(o==null||o(K.nativeEvent),K.nativeEvent.defaultPrevented||(_.isFocusedToastEscapeKeyDownRef.current=!0,ee()))}),onPointerDown:an(s.onPointerDown,K=>{K.button===0&&(T.current={x:K.clientX,y:K.clientY})}),onPointerMove:an(s.onPointerMove,K=>{if(!T.current)return;const re=K.clientX-T.current.x,ie=K.clientY-T.current.y,ce=!!E.current,ne=["left","right"].includes(_.swipeDirection),le=["left","up"].includes(_.swipeDirection)?Math.min:Math.max,be=ne?le(0,re):0,fe=ne?0:le(0,ie),je=K.pointerType==="touch"?10:2,ve={x:be,y:fe},We={originalEvent:K,delta:ve};ce?(E.current=ve,EU(DSt,m,We,{discrete:!1})):SRe(ve,_.swipeDirection,je)?(E.current=ve,EU(LSt,h,We,{discrete:!1}),K.target.setPointerCapture(K.pointerId)):(Math.abs(re)>je||Math.abs(ie)>je)&&(T.current=null)}),onPointerUp:an(s.onPointerUp,K=>{const re=E.current,ie=K.target;if(ie.hasPointerCapture(K.pointerId)&&ie.releasePointerCapture(K.pointerId),E.current=null,T.current=null,re){const ce=K.currentTarget,ne={originalEvent:K,delta:re};SRe(re,_.swipeDirection,_.swipeThreshold)?EU(OSt,x,ne,{discrete:!0}):EU(RSt,p,ne,{discrete:!0}),ce.addEventListener("click",le=>le.preventDefault(),{once:!0})}})})})}),_.viewport)})]}):null}),$St=s=>{const{__scopeToast:t,children:r,...n}=s,a=qpe(RB,t),[i,l]=S.useState(!1),[o,c]=S.useState(!1);return VSt(()=>l(!0)),S.useEffect(()=>{const d=window.setTimeout(()=>c(!0),1e3);return()=>window.clearTimeout(d)},[]),o?null:e.jsx(s8,{asChild:!0,children:e.jsx(Upe,{...n,children:i&&e.jsxs(e.Fragment,{children:[a.label," ",r]})})})},USt="ToastTitle",pQe=S.forwardRef((s,t)=>{const{__scopeToast:r,...n}=s;return e.jsx(Vn.div,{...n,ref:t})});pQe.displayName=USt;var qSt="ToastDescription",gQe=S.forwardRef((s,t)=>{const{__scopeToast:r,...n}=s;return e.jsx(Vn.div,{...n,ref:t})});gQe.displayName=qSt;var xQe="ToastAction",yQe=S.forwardRef((s,t)=>{const{altText:r,...n}=s;return r.trim()?e.jsx(bQe,{altText:r,asChild:!0,children:e.jsx(v3e,{...n,ref:t})}):(console.error(`Invalid prop \`altText\` supplied to \`${xQe}\`. Expected non-empty \`string\`.`),null)});yQe.displayName=xQe;var vQe="ToastClose",v3e=S.forwardRef((s,t)=>{const{__scopeToast:r,...n}=s,a=BSt(vQe,r);return e.jsx(bQe,{asChild:!0,children:e.jsx(Vn.button,{type:"button",...n,ref:t,onClick:an(s.onClick,a.onClose)})})});v3e.displayName=vQe;var bQe=S.forwardRef((s,t)=>{const{__scopeToast:r,altText:n,...a}=s;return e.jsx(Vn.div,{"data-radix-toast-announce-exclude":"","data-radix-toast-announce-alt":n||void 0,...a,ref:t})});function _Qe(s){const t=[];return Array.from(s.childNodes).forEach(n=>{if(n.nodeType===n.TEXT_NODE&&n.textContent&&t.push(n.textContent),HSt(n)){const a=n.ariaHidden||n.hidden||n.style.display==="none",i=n.dataset.radixToastAnnounceExclude==="";if(!a)if(i){const l=n.dataset.radixToastAnnounceAlt;l&&t.push(l)}else t.push(..._Qe(n))}}),t}function EU(s,t,r,{discrete:n}){const a=r.originalEvent.currentTarget,i=new CustomEvent(s,{bubbles:!0,cancelable:!0,detail:r});t&&a.addEventListener(s,t,{once:!0}),n?g3e(a,i):a.dispatchEvent(i)}var SRe=(s,t,r=0)=>{const n=Math.abs(s.x),a=Math.abs(s.y),i=n>a;return t==="left"||t==="right"?i&&n>r:!i&&a>r};function VSt(s=()=>{}){const t=Uu(s);Ku(()=>{let r=0,n=0;return r=window.requestAnimationFrame(()=>n=window.requestAnimationFrame(t)),()=>{window.cancelAnimationFrame(r),window.cancelAnimationFrame(n)}},[t])}function HSt(s){return s.nodeType===s.ELEMENT_NODE}function GSt(s){const t=[],r=document.createTreeWalker(s,NodeFilter.SHOW_ELEMENT,{acceptNode:n=>{const a=n.tagName==="INPUT"&&n.type==="hidden";return n.disabled||n.hidden||a?NodeFilter.FILTER_SKIP:n.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;r.nextNode();)t.push(r.currentNode);return t}function M1e(s){const t=document.activeElement;return s.some(r=>r===t?!0:(r.focus(),document.activeElement!==t))}var WSt=dQe,wQe=hQe,jQe=fQe,NQe=pQe,kQe=gQe,SQe=yQe,CQe=v3e;function TQe(s){var t,r,n="";if(typeof s=="string"||typeof s=="number")n+=s;else if(typeof s=="object")if(Array.isArray(s)){var a=s.length;for(t=0;ttypeof s=="boolean"?`${s}`:s===0?"0":s,TRe=jo,zA=(s,t)=>r=>{var n;if((t==null?void 0:t.variants)==null)return TRe(s,r==null?void 0:r.class,r==null?void 0:r.className);const{variants:a,defaultVariants:i}=t,l=Object.keys(a).map(d=>{const h=r==null?void 0:r[d],m=i==null?void 0:i[d];if(h===null)return null;const p=CRe(h)||CRe(m);return a[d][p]}),o=r&&Object.entries(r).reduce((d,h)=>{let[m,p]=h;return p===void 0||(d[m]=p),d},{}),c=t==null||(n=t.compoundVariants)===null||n===void 0?void 0:n.reduce((d,h)=>{let{class:m,className:p,...x}=h;return Object.entries(x).every(y=>{let[_,b]=y;return Array.isArray(b)?b.includes({...i,...o}[_]):{...i,...o}[_]===b})?[...d,m,p]:d},[]);return TRe(s,l,c,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 KSt=s=>s.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),EQe=(...s)=>s.filter((t,r,n)=>!!t&&t.trim()!==""&&n.indexOf(t)===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 YSt={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 AQe=S.forwardRef(({color:s="currentColor",size:t=24,strokeWidth:r=2,absoluteStrokeWidth:n,className:a="",children:i,iconNode:l,...o},c)=>S.createElement("svg",{ref:c,...YSt,width:t,height:t,stroke:s,strokeWidth:n?Number(r)*24/Number(t):r,className:EQe("lucide",a),...o},[...l.map(([d,h])=>S.createElement(d,h)),...Array.isArray(i)?i:[i]]));/** * @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 te=(s,t)=>{const r=S.forwardRef(({className:n,...a},i)=>S.createElement(AQe,{ref:i,iconNode:t,className:EQe(`lucide-${KSt(s)}`,n),...a}));return r.displayName=`${s}`,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 BV=te("AArrowDown",[["path",{d:"M3.5 13h6",key:"p1my2r"}],["path",{d:"m2 16 4.5-9 4.5 9",key:"ndf0b3"}],["path",{d:"M18 7v9",key:"pknjwm"}],["path",{d:"m14 12 4 4 4-4",key:"buelq4"}]]);/** * @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 zV=te("AArrowUp",[["path",{d:"M3.5 13h6",key:"p1my2r"}],["path",{d:"m2 16 4.5-9 4.5 9",key:"ndf0b3"}],["path",{d:"M18 16V7",key:"ty0viw"}],["path",{d:"m14 11 4-4 4 4",key:"1pu57t"}]]);/** * @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 $V=te("ALargeSmall",[["path",{d:"M21 14h-5",key:"1vh23k"}],["path",{d:"M16 16v-3.5a2.5 2.5 0 0 1 5 0V16",key:"1wh10o"}],["path",{d:"M4.5 13h6",key:"dfilno"}],["path",{d:"m3 16 4.5-9 4.5 9",key:"2dxa0e"}]]);/** * @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 UV=te("Accessibility",[["circle",{cx:"16",cy:"4",r:"1",key:"1grugj"}],["path",{d:"m18 19 1-7-6 1",key:"r0i19z"}],["path",{d:"m5 8 3-3 5.5 3-2.36 3.5",key:"9ptxx2"}],["path",{d:"M4.24 14.5a5 5 0 0 0 6.88 6",key:"10kmtu"}],["path",{d:"M13.76 17.5a5 5 0 0 0-6.88-6",key:"2qq6rc"}]]);/** * @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 ef=te("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 qV=te("AirVent",[["path",{d:"M6 12H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2",key:"larmp2"}],["path",{d:"M6 8h12",key:"6g4wlu"}],["path",{d:"M18.3 17.7a2.5 2.5 0 0 1-3.16 3.83 2.53 2.53 0 0 1-1.14-2V12",key:"1bo8pg"}],["path",{d:"M6.6 15.6A2 2 0 1 0 10 17v-5",key:"t9h90c"}]]);/** * @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 VV=te("Airplay",[["path",{d:"M5 17H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2h-1",key:"ns4c3b"}],["path",{d:"m12 15 5 6H7Z",key:"14qnn2"}]]);/** * @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 hC=te("AlarmClockCheck",[["circle",{cx:"12",cy:"13",r:"8",key:"3y4lt7"}],["path",{d:"M5 3 2 6",key:"18tl5t"}],["path",{d:"m22 6-3-3",key:"1opdir"}],["path",{d:"M6.38 18.7 4 21",key:"17xu3x"}],["path",{d:"M17.64 18.67 20 21",key:"kv2oe2"}],["path",{d:"m9 13 2 2 4-4",key:"6343dt"}]]);/** * @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 mC=te("AlarmClockMinus",[["circle",{cx:"12",cy:"13",r:"8",key:"3y4lt7"}],["path",{d:"M5 3 2 6",key:"18tl5t"}],["path",{d:"m22 6-3-3",key:"1opdir"}],["path",{d:"M6.38 18.7 4 21",key:"17xu3x"}],["path",{d:"M17.64 18.67 20 21",key:"kv2oe2"}],["path",{d:"M9 13h6",key:"1uhe8q"}]]);/** * @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 HV=te("AlarmClockOff",[["path",{d:"M6.87 6.87a8 8 0 1 0 11.26 11.26",key:"3on8tj"}],["path",{d:"M19.9 14.25a8 8 0 0 0-9.15-9.15",key:"15ghsc"}],["path",{d:"m22 6-3-3",key:"1opdir"}],["path",{d:"M6.26 18.67 4 21",key:"yzmioq"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M4 4 2 6",key:"1ycko6"}]]);/** * @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 fC=te("AlarmClockPlus",[["circle",{cx:"12",cy:"13",r:"8",key:"3y4lt7"}],["path",{d:"M5 3 2 6",key:"18tl5t"}],["path",{d:"m22 6-3-3",key:"1opdir"}],["path",{d:"M6.38 18.7 4 21",key:"17xu3x"}],["path",{d:"M17.64 18.67 20 21",key:"kv2oe2"}],["path",{d:"M12 10v6",key:"1bos4e"}],["path",{d:"M9 13h6",key:"1uhe8q"}]]);/** * @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 GV=te("AlarmClock",[["circle",{cx:"12",cy:"13",r:"8",key:"3y4lt7"}],["path",{d:"M12 9v4l2 2",key:"1c63tq"}],["path",{d:"M5 3 2 6",key:"18tl5t"}],["path",{d:"m22 6-3-3",key:"1opdir"}],["path",{d:"M6.38 18.7 4 21",key:"17xu3x"}],["path",{d:"M17.64 18.67 20 21",key:"kv2oe2"}]]);/** * @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 WV=te("AlarmSmoke",[["path",{d:"M11 21c0-2.5 2-2.5 2-5",key:"1sicvv"}],["path",{d:"M16 21c0-2.5 2-2.5 2-5",key:"1o3eny"}],["path",{d:"m19 8-.8 3a1.25 1.25 0 0 1-1.2 1H7a1.25 1.25 0 0 1-1.2-1L5 8",key:"1bvca4"}],["path",{d:"M21 3a1 1 0 0 1 1 1v2a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V4a1 1 0 0 1 1-1z",key:"x3qr1j"}],["path",{d:"M6 21c0-2.5 2-2.5 2-5",key:"i3w1gp"}]]);/** * @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 KV=te("Album",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["polyline",{points:"11 3 11 11 14 8 17 11 17 3",key:"1wcwz3"}]]);/** * @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 YV=te("AlignCenterHorizontal",[["path",{d:"M2 12h20",key:"9i4pu4"}],["path",{d:"M10 16v4a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2v-4",key:"11f1s0"}],["path",{d:"M10 8V4a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v4",key:"t14dx9"}],["path",{d:"M20 16v1a2 2 0 0 1-2 2h-2a2 2 0 0 1-2-2v-1",key:"1w07xs"}],["path",{d:"M14 8V7c0-1.1.9-2 2-2h2a2 2 0 0 1 2 2v1",key:"1apec2"}]]);/** * @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 ZV=te("AlignCenterVertical",[["path",{d:"M12 2v20",key:"t6zp3m"}],["path",{d:"M8 10H4a2 2 0 0 1-2-2V6c0-1.1.9-2 2-2h4",key:"14d6g8"}],["path",{d:"M16 10h4a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2h-4",key:"1e2lrw"}],["path",{d:"M8 20H7a2 2 0 0 1-2-2v-2c0-1.1.9-2 2-2h1",key:"1fkdwx"}],["path",{d:"M16 14h1a2 2 0 0 1 2 2v2a2 2 0 0 1-2 2h-1",key:"1euafb"}]]);/** * @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 dE=te("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 XV=te("AlignEndHorizontal",[["rect",{width:"6",height:"16",x:"4",y:"2",rx:"2",key:"z5wdxg"}],["rect",{width:"6",height:"9",x:"14",y:"9",rx:"2",key:"um7a8w"}],["path",{d:"M22 22H2",key:"19qnx5"}]]);/** * @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 QV=te("AlignEndVertical",[["rect",{width:"16",height:"6",x:"2",y:"4",rx:"2",key:"10wcwx"}],["rect",{width:"9",height:"6",x:"9",y:"14",rx:"2",key:"4p5bwg"}],["path",{d:"M22 22V2",key:"12ipfv"}]]);/** * @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 JV=te("AlignHorizontalDistributeCenter",[["rect",{width:"6",height:"14",x:"4",y:"5",rx:"2",key:"1wwnby"}],["rect",{width:"6",height:"10",x:"14",y:"7",rx:"2",key:"1fe6j6"}],["path",{d:"M17 22v-5",key:"4b6g73"}],["path",{d:"M17 7V2",key:"hnrr36"}],["path",{d:"M7 22v-3",key:"1r4jpn"}],["path",{d:"M7 5V2",key:"liy1u9"}]]);/** * @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 eH=te("AlignHorizontalDistributeEnd",[["rect",{width:"6",height:"14",x:"4",y:"5",rx:"2",key:"1wwnby"}],["rect",{width:"6",height:"10",x:"14",y:"7",rx:"2",key:"1fe6j6"}],["path",{d:"M10 2v20",key:"uyc634"}],["path",{d:"M20 2v20",key:"1tx262"}]]);/** * @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 tH=te("AlignHorizontalDistributeStart",[["rect",{width:"6",height:"14",x:"4",y:"5",rx:"2",key:"1wwnby"}],["rect",{width:"6",height:"10",x:"14",y:"7",rx:"2",key:"1fe6j6"}],["path",{d:"M4 2v20",key:"gtpd5x"}],["path",{d:"M14 2v20",key:"tg6bpw"}]]);/** * @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 sH=te("AlignHorizontalJustifyCenter",[["rect",{width:"6",height:"14",x:"2",y:"5",rx:"2",key:"dy24zr"}],["rect",{width:"6",height:"10",x:"16",y:"7",rx:"2",key:"13zkjt"}],["path",{d:"M12 2v20",key:"t6zp3m"}]]);/** * @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 rH=te("AlignHorizontalJustifyEnd",[["rect",{width:"6",height:"14",x:"2",y:"5",rx:"2",key:"dy24zr"}],["rect",{width:"6",height:"10",x:"12",y:"7",rx:"2",key:"1ht384"}],["path",{d:"M22 2v20",key:"40qfg1"}]]);/** * @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 nH=te("AlignHorizontalJustifyStart",[["rect",{width:"6",height:"14",x:"6",y:"5",rx:"2",key:"hsirpf"}],["rect",{width:"6",height:"10",x:"16",y:"7",rx:"2",key:"13zkjt"}],["path",{d:"M2 2v20",key:"1ivd8o"}]]);/** * @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 aH=te("AlignHorizontalSpaceAround",[["rect",{width:"6",height:"10",x:"9",y:"7",rx:"2",key:"yn7j0q"}],["path",{d:"M4 22V2",key:"tsjzd3"}],["path",{d:"M20 22V2",key:"1bnhr8"}]]);/** * @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 iH=te("AlignHorizontalSpaceBetween",[["rect",{width:"6",height:"14",x:"3",y:"5",rx:"2",key:"j77dae"}],["rect",{width:"6",height:"10",x:"15",y:"7",rx:"2",key:"bq30hj"}],["path",{d:"M3 2v20",key:"1d2pfg"}],["path",{d:"M21 2v20",key:"p059bm"}]]);/** * @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 oH=te("AlignJustify",[["path",{d:"M3 12h18",key:"1i2n21"}],["path",{d:"M3 18h18",key:"1h113x"}],["path",{d:"M3 6h18",key:"d0wm0j"}]]);/** * @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 uE=te("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 hE=te("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 lH=te("AlignStartHorizontal",[["rect",{width:"6",height:"16",x:"4",y:"6",rx:"2",key:"1n4dg1"}],["rect",{width:"6",height:"9",x:"14",y:"6",rx:"2",key:"17khns"}],["path",{d:"M22 2H2",key:"fhrpnj"}]]);/** * @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 cH=te("AlignStartVertical",[["rect",{width:"9",height:"6",x:"6",y:"14",rx:"2",key:"lpm2y7"}],["rect",{width:"16",height:"6",x:"6",y:"4",rx:"2",key:"rdj6ps"}],["path",{d:"M2 2v20",key:"1ivd8o"}]]);/** * @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 dH=te("AlignVerticalDistributeCenter",[["path",{d:"M22 17h-3",key:"1lwga1"}],["path",{d:"M22 7h-5",key:"o2endc"}],["path",{d:"M5 17H2",key:"1gx9xc"}],["path",{d:"M7 7H2",key:"6bq26l"}],["rect",{x:"5",y:"14",width:"14",height:"6",rx:"2",key:"1qrzuf"}],["rect",{x:"7",y:"4",width:"10",height:"6",rx:"2",key:"we8e9z"}]]);/** * @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 uH=te("AlignVerticalDistributeEnd",[["rect",{width:"14",height:"6",x:"5",y:"14",rx:"2",key:"jmoj9s"}],["rect",{width:"10",height:"6",x:"7",y:"4",rx:"2",key:"aza5on"}],["path",{d:"M2 20h20",key:"owomy5"}],["path",{d:"M2 10h20",key:"1ir3d8"}]]);/** * @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 hH=te("AlignVerticalDistributeStart",[["rect",{width:"14",height:"6",x:"5",y:"14",rx:"2",key:"jmoj9s"}],["rect",{width:"10",height:"6",x:"7",y:"4",rx:"2",key:"aza5on"}],["path",{d:"M2 14h20",key:"myj16y"}],["path",{d:"M2 4h20",key:"mda7wb"}]]);/** * @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=te("AlignVerticalJustifyCenter",[["rect",{width:"14",height:"6",x:"5",y:"16",rx:"2",key:"1i8z2d"}],["rect",{width:"10",height:"6",x:"7",y:"2",rx:"2",key:"ypihtt"}],["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 fH=te("AlignVerticalJustifyEnd",[["rect",{width:"14",height:"6",x:"5",y:"12",rx:"2",key:"4l4tp2"}],["rect",{width:"10",height:"6",x:"7",y:"2",rx:"2",key:"ypihtt"}],["path",{d:"M2 22h20",key:"272qi7"}]]);/** * @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=te("AlignVerticalJustifyStart",[["rect",{width:"14",height:"6",x:"5",y:"16",rx:"2",key:"1i8z2d"}],["rect",{width:"10",height:"6",x:"7",y:"6",rx:"2",key:"13squh"}],["path",{d:"M2 2h20",key:"1ennik"}]]);/** * @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 gH=te("AlignVerticalSpaceAround",[["rect",{width:"10",height:"6",x:"7",y:"9",rx:"2",key:"b1zbii"}],["path",{d:"M22 20H2",key:"1p1f7z"}],["path",{d:"M22 4H2",key:"1b7qnq"}]]);/** * @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 xH=te("AlignVerticalSpaceBetween",[["rect",{width:"14",height:"6",x:"5",y:"15",rx:"2",key:"1w91an"}],["rect",{width:"10",height:"6",x:"7",y:"3",rx:"2",key:"17wqzy"}],["path",{d:"M2 21h20",key:"1nyx9w"}],["path",{d:"M2 3h20",key:"91anmk"}]]);/** * @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 yH=te("Ambulance",[["path",{d:"M10 10H6",key:"1bsnug"}],["path",{d:"M14 18V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v11a1 1 0 0 0 1 1h2",key:"wrbu53"}],["path",{d:"M19 18h2a1 1 0 0 0 1-1v-3.28a1 1 0 0 0-.684-.948l-1.923-.641a1 1 0 0 1-.578-.502l-1.539-3.076A1 1 0 0 0 16.382 8H14",key:"lrkjwd"}],["path",{d:"M8 8v4",key:"1fwk8c"}],["path",{d:"M9 18h6",key:"x1upvd"}],["circle",{cx:"17",cy:"18",r:"2",key:"332jqn"}],["circle",{cx:"7",cy:"18",r:"2",key:"19iecd"}]]);/** * @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 vH=te("Ampersand",[["path",{d:"M17.5 12c0 4.4-3.6 8-8 8A4.5 4.5 0 0 1 5 15.5c0-6 8-4 8-8.5a3 3 0 1 0-6 0c0 3 2.5 8.5 12 13",key:"1o9ehi"}],["path",{d:"M16 12h3",key:"4uvgyw"}]]);/** * @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 bH=te("Ampersands",[["path",{d:"M10 17c-5-3-7-7-7-9a2 2 0 0 1 4 0c0 2.5-5 2.5-5 6 0 1.7 1.3 3 3 3 2.8 0 5-2.2 5-5",key:"12lh1k"}],["path",{d:"M22 17c-5-3-7-7-7-9a2 2 0 0 1 4 0c0 2.5-5 2.5-5 6 0 1.7 1.3 3 3 3 2.8 0 5-2.2 5-5",key:"173c68"}]]);/** * @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 _H=te("Amphora",[["path",{d:"M10 2v5.632c0 .424-.272.795-.653.982A6 6 0 0 0 6 14c.006 4 3 7 5 8",key:"1h8rid"}],["path",{d:"M10 5H8a2 2 0 0 0 0 4h.68",key:"3ezsi6"}],["path",{d:"M14 2v5.632c0 .424.272.795.652.982A6 6 0 0 1 18 14c0 4-3 7-5 8",key:"yt6q09"}],["path",{d:"M14 5h2a2 2 0 0 1 0 4h-.68",key:"8f95yk"}],["path",{d:"M18 22H6",key:"mg6kv4"}],["path",{d:"M9 2h6",key:"1jrp98"}]]);/** * @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 wH=te("Anchor",[["path",{d:"M12 22V8",key:"qkxhtm"}],["path",{d:"M5 12H2a10 10 0 0 0 20 0h-3",key:"1hv3nh"}],["circle",{cx:"12",cy:"5",r:"3",key:"rqqgnr"}]]);/** * @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 jH=te("Angry",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M16 16s-1.5-2-4-2-4 2-4 2",key:"epbg0q"}],["path",{d:"M7.5 8 10 9",key:"olxxln"}],["path",{d:"m14 9 2.5-1",key:"1j6cij"}],["path",{d:"M9 10h.01",key:"qbtxuw"}],["path",{d:"M15 10h.01",key:"1qmjsl"}]]);/** * @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 NH=te("Annoyed",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 15h8",key:"45n4r"}],["path",{d:"M8 9h2",key:"1g203m"}],["path",{d:"M14 9h2",key:"116p9w"}]]);/** * @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 kH=te("Antenna",[["path",{d:"M2 12 7 2",key:"117k30"}],["path",{d:"m7 12 5-10",key:"1tvx22"}],["path",{d:"m12 12 5-10",key:"ev1o1a"}],["path",{d:"m17 12 5-10",key:"1e4ti3"}],["path",{d:"M4.5 7h15",key:"vlsxkz"}],["path",{d:"M12 16v6",key:"c8a4gj"}]]);/** * @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 SH=te("Anvil",[["path",{d:"M7 10H6a4 4 0 0 1-4-4 1 1 0 0 1 1-1h4",key:"1hjpb6"}],["path",{d:"M7 5a1 1 0 0 1 1-1h13a1 1 0 0 1 1 1 7 7 0 0 1-7 7H8a1 1 0 0 1-1-1z",key:"1qn45f"}],["path",{d:"M9 12v5",key:"3anwtq"}],["path",{d:"M15 12v5",key:"5xh3zn"}],["path",{d:"M5 20a3 3 0 0 1 3-3h8a3 3 0 0 1 3 3 1 1 0 0 1-1 1H6a1 1 0 0 1-1-1",key:"1fi4x8"}]]);/** * @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 CH=te("Aperture",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m14.31 8 5.74 9.94",key:"1y6ab4"}],["path",{d:"M9.69 8h11.48",key:"1wxppr"}],["path",{d:"m7.38 12 5.74-9.94",key:"1grp0k"}],["path",{d:"M9.69 16 3.95 6.06",key:"libnyf"}],["path",{d:"M14.31 16H2.83",key:"x5fava"}],["path",{d:"m16.62 12-5.74 9.94",key:"1vwawt"}]]);/** * @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 TH=te("AppWindowMac",[["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}],["path",{d:"M6 8h.01",key:"x9i8wu"}],["path",{d:"M10 8h.01",key:"1r9ogq"}],["path",{d:"M14 8h.01",key:"1primd"}]]);/** * @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=te("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 EH=te("Apple",[["path",{d:"M12 20.94c1.5 0 2.75 1.06 4 1.06 3 0 6-8 6-12.22A4.91 4.91 0 0 0 17 5c-2.22 0-4 1.44-5 2-1-.56-2.78-2-5-2a4.9 4.9 0 0 0-5 4.78C2 14 5 22 8 22c1.25 0 2.5-1.06 4-1.06Z",key:"3s7exb"}],["path",{d:"M10 2c1 .5 2 2 2 5",key:"fcco2y"}]]);/** * @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 AI=te("ArchiveRestore",[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h2",key:"tvwodi"}],["path",{d:"M20 8v11a2 2 0 0 1-2 2h-2",key:"1gkqxj"}],["path",{d:"m9 15 3-3 3 3",key:"1pd0qc"}],["path",{d:"M12 12v9",key:"192myk"}]]);/** * @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 AH=te("ArchiveX",[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8",key:"1s80jp"}],["path",{d:"m9.5 17 5-5",key:"nakeu6"}],["path",{d:"m9.5 12 5 5",key:"1hccrj"}]]);/** * @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 Rk=te("Archive",[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8",key:"1s80jp"}],["path",{d:"M10 12h4",key:"a56b0p"}]]);/** * @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=te("Armchair",[["path",{d:"M19 9V6a2 2 0 0 0-2-2H7a2 2 0 0 0-2 2v3",key:"irtipd"}],["path",{d:"M3 16a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-5a2 2 0 0 0-4 0v1.5a.5.5 0 0 1-.5.5h-9a.5.5 0 0 1-.5-.5V11a2 2 0 0 0-4 0z",key:"1qyhux"}],["path",{d:"M5 18v2",key:"ppbyun"}],["path",{d:"M19 18v2",key:"gy7782"}]]);/** * @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 IH=te("ArrowBigDownDash",[["path",{d:"M15 5H9",key:"1tp3ed"}],["path",{d:"M15 9v3h4l-7 7-7-7h4V9z",key:"ncdc4b"}]]);/** * @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=te("ArrowBigDown",[["path",{d:"M15 6v6h4l-7 7-7-7h4V6h6z",key:"1thax2"}]]);/** * @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 LH=te("ArrowBigLeftDash",[["path",{d:"M19 15V9",key:"1hci5f"}],["path",{d:"M15 15h-3v4l-7-7 7-7v4h3v6z",key:"16tjna"}]]);/** * @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 DH=te("ArrowBigLeft",[["path",{d:"M18 15h-6v4l-7-7 7-7v4h6v6z",key:"lbrdak"}]]);/** * @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 RH=te("ArrowBigRightDash",[["path",{d:"M5 9v6",key:"158jrl"}],["path",{d:"M9 9h3V5l7 7-7 7v-4H9V9z",key:"1sg2xn"}]]);/** * @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 OH=te("ArrowBigRight",[["path",{d:"M6 9h6V5l7 7-7 7v-4H6V9z",key:"7fvt9c"}]]);/** * @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 FH=te("ArrowBigUpDash",[["path",{d:"M9 19h6",key:"456am0"}],["path",{d:"M9 15v-3H5l7-7 7 7h-4v3H9z",key:"1r2uve"}]]);/** * @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 BH=te("ArrowBigUp",[["path",{d:"M9 18v-6H5l7-7 7 7h-4v6H9z",key:"1x06kx"}]]);/** * @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 zH=te("ArrowDown01",[["path",{d:"m3 16 4 4 4-4",key:"1co6wj"}],["path",{d:"M7 20V4",key:"1yoxec"}],["rect",{x:"15",y:"4",width:"4",height:"6",ry:"2",key:"1bwicg"}],["path",{d:"M17 20v-6h-2",key:"1qp1so"}],["path",{d:"M15 20h4",key:"1j968p"}]]);/** * @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 $H=te("ArrowDown10",[["path",{d:"m3 16 4 4 4-4",key:"1co6wj"}],["path",{d:"M7 20V4",key:"1yoxec"}],["path",{d:"M17 10V4h-2",key:"zcsr5x"}],["path",{d:"M15 10h4",key:"id2lce"}],["rect",{x:"15",y:"14",width:"4",height:"6",ry:"2",key:"33xykx"}]]);/** * @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 pC=te("ArrowDownAZ",[["path",{d:"m3 16 4 4 4-4",key:"1co6wj"}],["path",{d:"M7 20V4",key:"1yoxec"}],["path",{d:"M20 8h-5",key:"1vsyxs"}],["path",{d:"M15 10V6.5a2.5 2.5 0 0 1 5 0V10",key:"ag13bf"}],["path",{d:"M15 14h5l-5 6h5",key:"ur5jdg"}]]);/** * @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 UH=te("ArrowDownFromLine",[["path",{d:"M19 3H5",key:"1236rx"}],["path",{d:"M12 21V7",key:"gj6g52"}],["path",{d:"m6 15 6 6 6-6",key:"h15q88"}]]);/** * @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 qH=te("ArrowDownLeft",[["path",{d:"M17 7 7 17",key:"15tmo1"}],["path",{d:"M17 17H7V7",key:"1org7z"}]]);/** * @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 VH=te("ArrowDownNarrowWide",[["path",{d:"m3 16 4 4 4-4",key:"1co6wj"}],["path",{d:"M7 20V4",key:"1yoxec"}],["path",{d:"M11 4h4",key:"6d7r33"}],["path",{d:"M11 8h7",key:"djye34"}],["path",{d:"M11 12h10",key:"1438ji"}]]);/** * @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 YO=te("ArrowDownRight",[["path",{d:"m7 7 10 10",key:"1fmybs"}],["path",{d:"M17 7v10H7",key:"6fjiku"}]]);/** * @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 HH=te("ArrowDownToDot",[["path",{d:"M12 2v14",key:"jyx4ut"}],["path",{d:"m19 9-7 7-7-7",key:"1oe3oy"}],["circle",{cx:"12",cy:"21",r:"1",key:"o0uj5v"}]]);/** * @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 GH=te("ArrowDownToLine",[["path",{d:"M12 17V3",key:"1cwfxf"}],["path",{d:"m6 11 6 6 6-6",key:"12ii2o"}],["path",{d:"M19 21H5",key:"150jfl"}]]);/** * @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 WH=te("ArrowDownUp",[["path",{d:"m3 16 4 4 4-4",key:"1co6wj"}],["path",{d:"M7 20V4",key:"1yoxec"}],["path",{d:"m21 8-4-4-4 4",key:"1c9v7m"}],["path",{d:"M17 4v16",key:"7dpous"}]]);/** * @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=te("ArrowDownWideNarrow",[["path",{d:"m3 16 4 4 4-4",key:"1co6wj"}],["path",{d:"M7 20V4",key:"1yoxec"}],["path",{d:"M11 4h10",key:"1w87gc"}],["path",{d:"M11 8h7",key:"djye34"}],["path",{d:"M11 12h4",key:"q8tih4"}]]);/** * @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 xC=te("ArrowDownZA",[["path",{d:"m3 16 4 4 4-4",key:"1co6wj"}],["path",{d:"M7 4v16",key:"1glfcx"}],["path",{d:"M15 4h5l-5 6h5",key:"8asdl1"}],["path",{d:"M15 20v-3.5a2.5 2.5 0 0 1 5 0V20",key:"r6l5cz"}],["path",{d:"M20 18h-5",key:"18j1r2"}]]);/** * @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=te("ArrowDown",[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]]);/** * @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 KH=te("ArrowLeftFromLine",[["path",{d:"m9 6-6 6 6 6",key:"7v63n9"}],["path",{d:"M3 12h14",key:"13k4hi"}],["path",{d:"M21 19V5",key:"b4bplr"}]]);/** * @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 YH=te("ArrowLeftRight",[["path",{d:"M8 3 4 7l4 4",key:"9rb6wj"}],["path",{d:"M4 7h16",key:"6tx8e3"}],["path",{d:"m16 21 4-4-4-4",key:"siv7j2"}],["path",{d:"M20 17H4",key:"h6l3hr"}]]);/** * @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 ZH=te("ArrowLeftToLine",[["path",{d:"M3 19V5",key:"rwsyhb"}],["path",{d:"m13 6-6 6 6 6",key:"1yhaz7"}],["path",{d:"M7 12h14",key:"uoisry"}]]);/** * @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 za=te("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 XH=te("ArrowRightFromLine",[["path",{d:"M3 5v14",key:"1nt18q"}],["path",{d:"M21 12H7",key:"13ipq5"}],["path",{d:"m15 18 6-6-6-6",key:"6tx3qv"}]]);/** * @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 F2=te("ArrowRightLeft",[["path",{d:"m16 3 4 4-4 4",key:"1x1c3m"}],["path",{d:"M20 7H4",key:"zbl0bi"}],["path",{d:"m8 21-4-4 4-4",key:"h9nckh"}],["path",{d:"M4 17h16",key:"g4d7ey"}]]);/** * @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 QH=te("ArrowRightToLine",[["path",{d:"M17 12H3",key:"8awo09"}],["path",{d:"m11 18 6-6-6-6",key:"8c2y43"}],["path",{d:"M21 5v14",key:"nzette"}]]);/** * @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 bi=te("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 JH=te("ArrowUp01",[["path",{d:"m3 8 4-4 4 4",key:"11wl7u"}],["path",{d:"M7 4v16",key:"1glfcx"}],["rect",{x:"15",y:"4",width:"4",height:"6",ry:"2",key:"1bwicg"}],["path",{d:"M17 20v-6h-2",key:"1qp1so"}],["path",{d:"M15 20h4",key:"1j968p"}]]);/** * @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=te("ArrowUp10",[["path",{d:"m3 8 4-4 4 4",key:"11wl7u"}],["path",{d:"M7 4v16",key:"1glfcx"}],["path",{d:"M17 10V4h-2",key:"zcsr5x"}],["path",{d:"M15 10h4",key:"id2lce"}],["rect",{x:"15",y:"14",width:"4",height:"6",ry:"2",key:"33xykx"}]]);/** * @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=te("ArrowUpAZ",[["path",{d:"m3 8 4-4 4 4",key:"11wl7u"}],["path",{d:"M7 4v16",key:"1glfcx"}],["path",{d:"M20 8h-5",key:"1vsyxs"}],["path",{d:"M15 10V6.5a2.5 2.5 0 0 1 5 0V10",key:"ag13bf"}],["path",{d:"M15 14h5l-5 6h5",key:"ur5jdg"}]]);/** * @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 qu=te("ArrowUpDown",[["path",{d:"m21 16-4 4-4-4",key:"f6ql7i"}],["path",{d:"M17 20V4",key:"1ejh1v"}],["path",{d:"m3 8 4-4 4 4",key:"11wl7u"}],["path",{d:"M7 4v16",key:"1glfcx"}]]);/** * @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 tG=te("ArrowUpFromDot",[["path",{d:"m5 9 7-7 7 7",key:"1hw5ic"}],["path",{d:"M12 16V2",key:"ywoabb"}],["circle",{cx:"12",cy:"21",r:"1",key:"o0uj5v"}]]);/** * @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 sG=te("ArrowUpFromLine",[["path",{d:"m18 9-6-6-6 6",key:"kcunyi"}],["path",{d:"M12 3v14",key:"7cf3v8"}],["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 rG=te("ArrowUpLeft",[["path",{d:"M7 17V7h10",key:"11bw93"}],["path",{d:"M17 17 7 7",key:"2786uv"}]]);/** * @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 vC=te("ArrowUpNarrowWide",[["path",{d:"m3 8 4-4 4 4",key:"11wl7u"}],["path",{d:"M7 4v16",key:"1glfcx"}],["path",{d:"M11 12h4",key:"q8tih4"}],["path",{d:"M11 16h7",key:"uosisv"}],["path",{d:"M11 20h10",key:"jvxblo"}]]);/** * @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 ZO=te("ArrowUpRight",[["path",{d:"M7 7h10v10",key:"1tivn9"}],["path",{d:"M7 17 17 7",key:"1vkiza"}]]);/** * @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 nG=te("ArrowUpToLine",[["path",{d:"M5 3h14",key:"7usisc"}],["path",{d:"m18 13-6-6-6 6",key:"1kf1n9"}],["path",{d:"M12 7v14",key:"1akyts"}]]);/** * @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 aG=te("ArrowUpWideNarrow",[["path",{d:"m3 8 4-4 4 4",key:"11wl7u"}],["path",{d:"M7 4v16",key:"1glfcx"}],["path",{d:"M11 12h10",key:"1438ji"}],["path",{d:"M11 16h7",key:"uosisv"}],["path",{d:"M11 20h4",key:"1krc32"}]]);/** * @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 bC=te("ArrowUpZA",[["path",{d:"m3 8 4-4 4 4",key:"11wl7u"}],["path",{d:"M7 4v16",key:"1glfcx"}],["path",{d:"M15 4h5l-5 6h5",key:"8asdl1"}],["path",{d:"M15 20v-3.5a2.5 2.5 0 0 1 5 0V20",key:"r6l5cz"}],["path",{d:"M20 18h-5",key:"18j1r2"}]]);/** * @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 Hu=te("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 iG=te("ArrowsUpFromLine",[["path",{d:"m4 6 3-3 3 3",key:"9aidw8"}],["path",{d:"M7 17V3",key:"19qxw1"}],["path",{d:"m14 6 3-3 3 3",key:"6iy689"}],["path",{d:"M17 17V3",key:"o0fmgi"}],["path",{d:"M4 21h16",key:"1h09gz"}]]);/** * @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 oG=te("Asterisk",[["path",{d:"M12 6v12",key:"1vza4d"}],["path",{d:"M17.196 9 6.804 15",key:"1ah31z"}],["path",{d:"m6.804 9 10.392 6",key:"1b6pxd"}]]);/** * @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 lG=te("AtSign",[["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8",key:"7n84p3"}]]);/** * @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 cG=te("Atom",[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["path",{d:"M20.2 20.2c2.04-2.03.02-7.36-4.5-11.9-4.54-4.52-9.87-6.54-11.9-4.5-2.04 2.03-.02 7.36 4.5 11.9 4.54 4.52 9.87 6.54 11.9 4.5Z",key:"1l2ple"}],["path",{d:"M15.7 15.7c4.52-4.54 6.54-9.87 4.5-11.9-2.03-2.04-7.36-.02-11.9 4.5-4.52 4.54-6.54 9.87-4.5 11.9 2.03 2.04 7.36.02 11.9-4.5Z",key:"1wam0m"}]]);/** * @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 dG=te("AudioLines",[["path",{d:"M2 10v3",key:"1fnikh"}],["path",{d:"M6 6v11",key:"11sgs0"}],["path",{d:"M10 3v18",key:"yhl04a"}],["path",{d:"M14 8v7",key:"3a1oy3"}],["path",{d:"M18 5v13",key:"123xd1"}],["path",{d:"M22 10v3",key:"154ddg"}]]);/** * @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 uG=te("AudioWaveform",[["path",{d:"M2 13a2 2 0 0 0 2-2V7a2 2 0 0 1 4 0v13a2 2 0 0 0 4 0V4a2 2 0 0 1 4 0v13a2 2 0 0 0 4 0v-4a2 2 0 0 1 2-2",key:"57tc96"}]]);/** * @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 Bc=te("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 hG=te("Axe",[["path",{d:"m14 12-8.5 8.5a2.12 2.12 0 1 1-3-3L11 9",key:"csbz4o"}],["path",{d:"M15 13 9 7l4-4 6 6h3a8 8 0 0 1-7 7z",key:"113wfo"}]]);/** * @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 _C=te("Axis3d",[["path",{d:"M4 4v16h16",key:"1s015l"}],["path",{d:"m4 20 7-7",key:"17qe9y"}]]);/** * @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 mG=te("Baby",[["path",{d:"M9 12h.01",key:"157uk2"}],["path",{d:"M15 12h.01",key:"1k8ypt"}],["path",{d:"M10 16c.5.3 1.2.5 2 .5s1.5-.2 2-.5",key:"1u7htd"}],["path",{d:"M19 6.3a9 9 0 0 1 1.8 3.9 2 2 0 0 1 0 3.6 9 9 0 0 1-17.6 0 2 2 0 0 1 0-3.6A9 9 0 0 1 12 3c2 0 3.5 1.1 3.5 2.5s-.9 2.5-2 2.5c-.8 0-1.5-.4-1.5-1",key:"5yv0yz"}]]);/** * @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 fG=te("Backpack",[["path",{d:"M4 10a4 4 0 0 1 4-4h8a4 4 0 0 1 4 4v10a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2z",key:"1ol0lm"}],["path",{d:"M8 10h8",key:"c7uz4u"}],["path",{d:"M8 18h8",key:"1no2b1"}],["path",{d:"M8 22v-6a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v6",key:"1fr6do"}],["path",{d:"M9 6V4a2 2 0 0 1 2-2h2a2 2 0 0 1 2 2v2",key:"donm21"}]]);/** * @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 pG=te("BadgeAlert",[["path",{d:"M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z",key:"3c2336"}],["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 gG=te("BadgeCent",[["path",{d:"M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z",key:"3c2336"}],["path",{d:"M12 7v10",key:"jspqdw"}],["path",{d:"M15.4 10a4 4 0 1 0 0 4",key:"2eqtx8"}]]);/** * @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 wC=te("BadgeCheck",[["path",{d:"M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z",key:"3c2336"}],["path",{d:"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 xG=te("BadgeDollarSign",[["path",{d:"M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z",key:"3c2336"}],["path",{d:"M16 8h-6a2 2 0 1 0 0 4h4a2 2 0 1 1 0 4H8",key:"1h4pet"}],["path",{d:"M12 18V6",key:"zqpxq5"}]]);/** * @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 yG=te("BadgeEuro",[["path",{d:"M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z",key:"3c2336"}],["path",{d:"M7 12h5",key:"gblrwe"}],["path",{d:"M15 9.4a4 4 0 1 0 0 5.2",key:"1makmb"}]]);/** * @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 vG=te("BadgeHelp",[["path",{d:"M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z",key:"3c2336"}],["path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3",key:"1u773s"}],["line",{x1:"12",x2:"12.01",y1:"17",y2:"17",key:"io3f8k"}]]);/** * @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 bG=te("BadgeIndianRupee",[["path",{d:"M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z",key:"3c2336"}],["path",{d:"M8 8h8",key:"1bis0t"}],["path",{d:"M8 12h8",key:"1wcyev"}],["path",{d:"m13 17-5-1h1a4 4 0 0 0 0-8",key:"nu2bwa"}]]);/** * @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=te("BadgeInfo",[["path",{d:"M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z",key:"3c2336"}],["line",{x1:"12",x2:"12",y1:"16",y2:"12",key:"1y1yb1"}],["line",{x1:"12",x2:"12.01",y1:"8",y2:"8",key:"110wyk"}]]);/** * @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 wG=te("BadgeJapaneseYen",[["path",{d:"M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z",key:"3c2336"}],["path",{d:"m9 8 3 3v7",key:"17yadx"}],["path",{d:"m12 11 3-3",key:"p4cfq1"}],["path",{d:"M9 12h6",key:"1c52cq"}],["path",{d:"M9 16h6",key:"8wimt3"}]]);/** * @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 jG=te("BadgeMinus",[["path",{d:"M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z",key:"3c2336"}],["line",{x1:"8",x2:"16",y1:"12",y2:"12",key:"1jonct"}]]);/** * @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 NG=te("BadgePercent",[["path",{d:"M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z",key:"3c2336"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"M9 9h.01",key:"1q5me6"}],["path",{d:"M15 15h.01",key:"lqbp3k"}]]);/** * @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 kG=te("BadgePlus",[["path",{d:"M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z",key:"3c2336"}],["line",{x1:"12",x2:"12",y1:"8",y2:"16",key:"10p56q"}],["line",{x1:"8",x2:"16",y1:"12",y2:"12",key:"1jonct"}]]);/** * @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 SG=te("BadgePoundSterling",[["path",{d:"M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z",key:"3c2336"}],["path",{d:"M8 12h4",key:"qz6y1c"}],["path",{d:"M10 16V9.5a2.5 2.5 0 0 1 5 0",key:"3mlbjk"}],["path",{d:"M8 16h7",key:"sbedsn"}]]);/** * @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 CG=te("BadgeRussianRuble",[["path",{d:"M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z",key:"3c2336"}],["path",{d:"M9 16h5",key:"1syiyw"}],["path",{d:"M9 12h5a2 2 0 1 0 0-4h-3v9",key:"1ge9c1"}]]);/** * @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 TG=te("BadgeSwissFranc",[["path",{d:"M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z",key:"3c2336"}],["path",{d:"M11 17V8h4",key:"1bfq6y"}],["path",{d:"M11 12h3",key:"2eqnfz"}],["path",{d:"M9 16h4",key:"1skf3a"}]]);/** * @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=te("BadgeX",[["path",{d:"M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z",key:"3c2336"}],["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 AG=te("Badge",[["path",{d:"M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z",key:"3c2336"}]]);/** * @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 MG=te("BaggageClaim",[["path",{d:"M22 18H6a2 2 0 0 1-2-2V7a2 2 0 0 0-2-2",key:"4irg2o"}],["path",{d:"M17 14V4a2 2 0 0 0-2-2h-1a2 2 0 0 0-2 2v10",key:"14fcyx"}],["rect",{width:"13",height:"8",x:"8",y:"6",rx:"1",key:"o6oiis"}],["circle",{cx:"18",cy:"20",r:"2",key:"t9985n"}],["circle",{cx:"9",cy:"20",r:"2",key:"e5v82j"}]]);/** * @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 XO=te("Ban",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m4.9 4.9 14.2 14.2",key:"1m5liu"}]]);/** * @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 IG=te("Banana",[["path",{d:"M4 13c3.5-2 8-2 10 2a5.5 5.5 0 0 1 8 5",key:"1cscit"}],["path",{d:"M5.15 17.89c5.52-1.52 8.65-6.89 7-12C11.55 4 11.5 2 13 2c3.22 0 5 5.5 5 8 0 6.5-4.2 12-10.49 12C5.11 22 2 22 2 20c0-1.5 1.14-1.55 3.15-2.11Z",key:"1y1nbv"}]]);/** * @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 PG=te("Bandage",[["path",{d:"M10 10.01h.01",key:"1e9xi7"}],["path",{d:"M10 14.01h.01",key:"ac23bv"}],["path",{d:"M14 10.01h.01",key:"2wfrvf"}],["path",{d:"M14 14.01h.01",key:"8tw8yn"}],["path",{d:"M18 6v11.5",key:"dkbidh"}],["path",{d:"M6 6v12",key:"vkc79e"}],["rect",{x:"2",y:"6",width:"20",height:"12",rx:"2",key:"1wpnh2"}]]);/** * @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 LG=te("Banknote",[["rect",{width:"20",height:"12",x:"2",y:"6",rx:"2",key:"9lu3g6"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}],["path",{d:"M6 12h.01M18 12h.01",key:"113zkx"}]]);/** * @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 DG=te("Barcode",[["path",{d:"M3 5v14",key:"1nt18q"}],["path",{d:"M8 5v14",key:"1ybrkv"}],["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"M17 5v14",key:"ycjyhj"}],["path",{d:"M21 5v14",key:"nzette"}]]);/** * @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 RG=te("Baseline",[["path",{d:"M4 20h16",key:"14thso"}],["path",{d:"m6 16 6-12 6 12",key:"1b4byz"}],["path",{d:"M8 12h8",key:"1wcyev"}]]);/** * @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=te("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 OG=te("BatteryCharging",[["path",{d:"M15 7h1a2 2 0 0 1 2 2v6a2 2 0 0 1-2 2h-2",key:"1sdynx"}],["path",{d:"M6 7H4a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2h1",key:"1gkd3k"}],["path",{d:"m11 7-3 5h4l-3 5",key:"b4a64w"}],["line",{x1:"22",x2:"22",y1:"11",y2:"13",key:"4dh1rd"}]]);/** * @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 FG=te("BatteryFull",[["rect",{width:"16",height:"10",x:"2",y:"7",rx:"2",ry:"2",key:"1w10f2"}],["line",{x1:"22",x2:"22",y1:"11",y2:"13",key:"4dh1rd"}],["line",{x1:"6",x2:"6",y1:"11",y2:"13",key:"1wd6dw"}],["line",{x1:"10",x2:"10",y1:"11",y2:"13",key:"haxvl5"}],["line",{x1:"14",x2:"14",y1:"11",y2:"13",key:"c6fn6x"}]]);/** * @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 BG=te("BatteryLow",[["rect",{width:"16",height:"10",x:"2",y:"7",rx:"2",ry:"2",key:"1w10f2"}],["line",{x1:"22",x2:"22",y1:"11",y2:"13",key:"4dh1rd"}],["line",{x1:"6",x2:"6",y1:"11",y2:"13",key:"1wd6dw"}]]);/** * @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 zG=te("BatteryMedium",[["rect",{width:"16",height:"10",x:"2",y:"7",rx:"2",ry:"2",key:"1w10f2"}],["line",{x1:"22",x2:"22",y1:"11",y2:"13",key:"4dh1rd"}],["line",{x1:"6",x2:"6",y1:"11",y2:"13",key:"1wd6dw"}],["line",{x1:"10",x2:"10",y1:"11",y2:"13",key:"haxvl5"}]]);/** * @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=te("BatteryWarning",[["path",{d:"M10 17h.01",key:"nbq80n"}],["path",{d:"M10 7v6",key:"nne03l"}],["path",{d:"M14 7h2a2 2 0 0 1 2 2v6a2 2 0 0 1-2 2h-2",key:"1x5o8m"}],["path",{d:"M22 11v2",key:"1wo06k"}],["path",{d:"M6 7H4a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2h2",key:"1mdjgh"}]]);/** * @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 UG=te("Battery",[["rect",{width:"16",height:"10",x:"2",y:"7",rx:"2",ry:"2",key:"1w10f2"}],["line",{x1:"22",x2:"22",y1:"11",y2:"13",key:"4dh1rd"}]]);/** * @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 qG=te("Beaker",[["path",{d:"M4.5 3h15",key:"c7n0jr"}],["path",{d:"M6 3v16a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V3",key:"m1uhx7"}],["path",{d:"M6 14h12",key:"4cwo0f"}]]);/** * @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 VG=te("BeanOff",[["path",{d:"M9 9c-.64.64-1.521.954-2.402 1.165A6 6 0 0 0 8 22a13.96 13.96 0 0 0 9.9-4.1",key:"bq3udt"}],["path",{d:"M10.75 5.093A6 6 0 0 1 22 8c0 2.411-.61 4.68-1.683 6.66",key:"17ccse"}],["path",{d:"M5.341 10.62a4 4 0 0 0 6.487 1.208M10.62 5.341a4.015 4.015 0 0 1 2.039 2.04",key:"18zqgq"}],["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}]]);/** * @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 HG=te("Bean",[["path",{d:"M10.165 6.598C9.954 7.478 9.64 8.36 9 9c-.64.64-1.521.954-2.402 1.165A6 6 0 0 0 8 22c7.732 0 14-6.268 14-14a6 6 0 0 0-11.835-1.402Z",key:"1tvzk7"}],["path",{d:"M5.341 10.62a4 4 0 1 0 5.279-5.28",key:"2cyri2"}]]);/** * @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 B2=te("BedDouble",[["path",{d:"M2 20v-8a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v8",key:"1k78r4"}],["path",{d:"M4 10V6a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v4",key:"fb3tl2"}],["path",{d:"M12 4v6",key:"1dcgq2"}],["path",{d:"M2 18h20",key:"ajqnye"}]]);/** * @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 GG=te("BedSingle",[["path",{d:"M3 20v-8a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v8",key:"1wm6mi"}],["path",{d:"M5 10V6a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v4",key:"4k93s5"}],["path",{d:"M3 18h18",key:"1h113x"}]]);/** * @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 x1=te("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 WG=te("Beef",[["circle",{cx:"12.5",cy:"8.5",r:"2.5",key:"9738u8"}],["path",{d:"M12.5 2a6.5 6.5 0 0 0-6.22 4.6c-1.1 3.13-.78 3.9-3.18 6.08A3 3 0 0 0 5 18c4 0 8.4-1.8 11.4-4.3A6.5 6.5 0 0 0 12.5 2Z",key:"o0f6za"}],["path",{d:"m18.5 6 2.19 4.5a6.48 6.48 0 0 1 .31 2 6.49 6.49 0 0 1-2.6 5.2C15.4 20.2 11 22 7 22a3 3 0 0 1-2.68-1.66L2.4 16.5",key:"k7p6i0"}]]);/** * @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 KG=te("BeerOff",[["path",{d:"M13 13v5",key:"igwfh0"}],["path",{d:"M17 11.47V8",key:"16yw0g"}],["path",{d:"M17 11h1a3 3 0 0 1 2.745 4.211",key:"1xbt65"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M5 8v12a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2v-3",key:"c55o3e"}],["path",{d:"M7.536 7.535C6.766 7.649 6.154 8 5.5 8a2.5 2.5 0 0 1-1.768-4.268",key:"1ydug7"}],["path",{d:"M8.727 3.204C9.306 2.767 9.885 2 11 2c1.56 0 2 1.5 3 1.5s1.72-.5 2.5-.5a1 1 0 1 1 0 5c-.78 0-1.5-.5-2.5-.5a3.149 3.149 0 0 0-.842.12",key:"q81o7q"}],["path",{d:"M9 14.6V18",key:"20ek98"}]]);/** * @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 YG=te("Beer",[["path",{d:"M17 11h1a3 3 0 0 1 0 6h-1",key:"1yp76v"}],["path",{d:"M9 12v6",key:"1u1cab"}],["path",{d:"M13 12v6",key:"1sugkk"}],["path",{d:"M14 7.5c-1 0-1.44.5-3 .5s-2-.5-3-.5-1.72.5-2.5.5a2.5 2.5 0 0 1 0-5c.78 0 1.57.5 2.5.5S9.44 2 11 2s2 1.5 3 1.5 1.72-.5 2.5-.5a2.5 2.5 0 0 1 0 5c-.78 0-1.5-.5-2.5-.5Z",key:"1510fo"}],["path",{d:"M5 8v12a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V8",key:"19jb7n"}]]);/** * @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 ZG=te("BellDot",[["path",{d:"M19.4 14.9C20.2 16.4 21 17 21 17H3s3-2 3-9c0-3.3 2.7-6 6-6 .7 0 1.3.1 1.9.3",key:"xcehk"}],["path",{d:"M10.3 21a1.94 1.94 0 0 0 3.4 0",key:"qgo35s"}],["circle",{cx:"18",cy:"8",r:"3",key:"1g0gzu"}]]);/** * @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 XG=te("BellElectric",[["path",{d:"M18.8 4A6.3 8.7 0 0 1 20 9",key:"xve1fh"}],["path",{d:"M9 9h.01",key:"1q5me6"}],["circle",{cx:"9",cy:"9",r:"7",key:"p2h5vp"}],["rect",{width:"10",height:"6",x:"4",y:"16",rx:"2",key:"17f3te"}],["path",{d:"M14 19c3 0 4.6-1.6 4.6-1.6",key:"n7odp6"}],["circle",{cx:"20",cy:"16",r:"2",key:"1v9bxh"}]]);/** * @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 QG=te("BellMinus",[["path",{d:"M18.4 12c.8 3.8 2.6 5 2.6 5H3s3-2 3-9c0-3.3 2.7-6 6-6 1.8 0 3.4.8 4.5 2",key:"eck70s"}],["path",{d:"M10.3 21a1.94 1.94 0 0 0 3.4 0",key:"qgo35s"}],["path",{d:"M15 8h6",key:"8ybuxh"}]]);/** * @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 u_=te("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 JG=te("BellPlus",[["path",{d:"M19.3 14.8C20.1 16.4 21 17 21 17H3s3-2 3-9c0-3.3 2.7-6 6-6 1 0 1.9.2 2.8.7",key:"guizqy"}],["path",{d:"M10.3 21a1.94 1.94 0 0 0 3.4 0",key:"qgo35s"}],["path",{d:"M15 8h6",key:"8ybuxh"}],["path",{d:"M18 5v6",key:"g5ayrv"}]]);/** * @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 QO=te("BellRing",[["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"}],["path",{d:"M4 2C2.8 3.7 2 5.7 2 8",key:"tap9e0"}],["path",{d:"M22 8c0-2.3-.8-4.3-2-6",key:"5bb3ad"}]]);/** * @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=te("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 jC=te("BetweenHorizontalEnd",[["rect",{width:"13",height:"7",x:"3",y:"3",rx:"1",key:"11xb64"}],["path",{d:"m22 15-3-3 3-3",key:"26chmm"}],["rect",{width:"13",height:"7",x:"3",y:"14",rx:"1",key:"k6ky7n"}]]);/** * @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 NC=te("BetweenHorizontalStart",[["rect",{width:"13",height:"7",x:"8",y:"3",rx:"1",key:"pkso9a"}],["path",{d:"m2 9 3 3-3 3",key:"1agib5"}],["rect",{width:"13",height:"7",x:"8",y:"14",rx:"1",key:"1q5fc1"}]]);/** * @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 eW=te("BetweenVerticalEnd",[["rect",{width:"7",height:"13",x:"3",y:"3",rx:"1",key:"1fdu0f"}],["path",{d:"m9 22 3-3 3 3",key:"17z65a"}],["rect",{width:"7",height:"13",x:"14",y:"3",rx:"1",key:"1squn4"}]]);/** * @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 tW=te("BetweenVerticalStart",[["rect",{width:"7",height:"13",x:"3",y:"8",rx:"1",key:"1fjrkv"}],["path",{d:"m15 2-3 3-3-3",key:"1uh6eb"}],["rect",{width:"7",height:"13",x:"14",y:"8",rx:"1",key:"w3fjg8"}]]);/** * @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 sW=te("BicepsFlexed",[["path",{d:"M12.409 13.017A5 5 0 0 1 22 15c0 3.866-4 7-9 7-4.077 0-8.153-.82-10.371-2.462-.426-.316-.631-.832-.62-1.362C2.118 12.723 2.627 2 10 2a3 3 0 0 1 3 3 2 2 0 0 1-2 2c-1.105 0-1.64-.444-2-1",key:"1pmlyh"}],["path",{d:"M15 14a5 5 0 0 0-7.584 2",key:"5rb254"}],["path",{d:"M9.964 6.825C8.019 7.977 9.5 13 8 15",key:"kbvsx9"}]]);/** * @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 rW=te("Bike",[["circle",{cx:"18.5",cy:"17.5",r:"3.5",key:"15x4ox"}],["circle",{cx:"5.5",cy:"17.5",r:"3.5",key:"1noe27"}],["circle",{cx:"15",cy:"5",r:"1",key:"19l28e"}],["path",{d:"M12 17.5V14l-3-3 4-3 2 3h2",key:"1npguv"}]]);/** * @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 nW=te("Binary",[["rect",{x:"14",y:"14",width:"4",height:"6",rx:"2",key:"p02svl"}],["rect",{x:"6",y:"4",width:"4",height:"6",rx:"2",key:"xm4xkj"}],["path",{d:"M6 20h4",key:"1i6q5t"}],["path",{d:"M14 10h4",key:"ru81e7"}],["path",{d:"M6 14h2v6",key:"16z9wg"}],["path",{d:"M14 4h2v6",key:"1idq9u"}]]);/** * @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 aW=te("Binoculars",[["path",{d:"M10 10h4",key:"tcdvrf"}],["path",{d:"M19 7V4a1 1 0 0 0-1-1h-2a1 1 0 0 0-1 1v3",key:"3apit1"}],["path",{d:"M20 21a2 2 0 0 0 2-2v-3.851c0-1.39-2-2.962-2-4.829V8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v11a2 2 0 0 0 2 2z",key:"rhpgnw"}],["path",{d:"M 22 16 L 2 16",key:"14lkq7"}],["path",{d:"M4 21a2 2 0 0 1-2-2v-3.851c0-1.39 2-2.962 2-4.829V8a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v11a2 2 0 0 1-2 2z",key:"104b3k"}],["path",{d:"M9 7V4a1 1 0 0 0-1-1H6a1 1 0 0 0-1 1v3",key:"14fczp"}]]);/** * @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 iW=te("Biohazard",[["circle",{cx:"12",cy:"11.9",r:"2",key:"e8h31w"}],["path",{d:"M6.7 3.4c-.9 2.5 0 5.2 2.2 6.7C6.5 9 3.7 9.6 2 11.6",key:"17bolr"}],["path",{d:"m8.9 10.1 1.4.8",key:"15ezny"}],["path",{d:"M17.3 3.4c.9 2.5 0 5.2-2.2 6.7 2.4-1.2 5.2-.6 6.9 1.5",key:"wtwa5u"}],["path",{d:"m15.1 10.1-1.4.8",key:"1r0b28"}],["path",{d:"M16.7 20.8c-2.6-.4-4.6-2.6-4.7-5.3-.2 2.6-2.1 4.8-4.7 5.2",key:"m7qszh"}],["path",{d:"M12 13.9v1.6",key:"zfyyim"}],["path",{d:"M13.5 5.4c-1-.2-2-.2-3 0",key:"1bi9q0"}],["path",{d:"M17 16.4c.7-.7 1.2-1.6 1.5-2.5",key:"1rhjqw"}],["path",{d:"M5.5 13.9c.3.9.8 1.8 1.5 2.5",key:"8gsud3"}]]);/** * @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 oW=te("Bird",[["path",{d:"M16 7h.01",key:"1kdx03"}],["path",{d:"M3.4 18H12a8 8 0 0 0 8-8V7a4 4 0 0 0-7.28-2.3L2 20",key:"oj1oa8"}],["path",{d:"m20 7 2 .5-2 .5",key:"12nv4d"}],["path",{d:"M10 18v3",key:"1yea0a"}],["path",{d:"M14 17.75V21",key:"1pymcb"}],["path",{d:"M7 18a6 6 0 0 0 3.84-10.61",key:"1npnn0"}]]);/** * @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 lW=te("Bitcoin",[["path",{d:"M11.767 19.089c4.924.868 6.14-6.025 1.216-6.894m-1.216 6.894L5.86 18.047m5.908 1.042-.347 1.97m1.563-8.864c4.924.869 6.14-6.025 1.215-6.893m-1.215 6.893-3.94-.694m5.155-6.2L8.29 4.26m5.908 1.042.348-1.97M7.48 20.364l3.126-17.727",key:"yr8idg"}]]);/** * @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 cW=te("Blend",[["circle",{cx:"9",cy:"9",r:"7",key:"p2h5vp"}],["circle",{cx:"15",cy:"15",r:"7",key:"19ennj"}]]);/** * @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 dW=te("Blinds",[["path",{d:"M3 3h18",key:"o7r712"}],["path",{d:"M20 7H8",key:"gd2fo2"}],["path",{d:"M20 11H8",key:"1ynp89"}],["path",{d:"M10 19h10",key:"19hjk5"}],["path",{d:"M8 15h12",key:"1yqzne"}],["path",{d:"M4 3v14",key:"fggqzn"}],["circle",{cx:"4",cy:"19",r:"2",key:"p3m9r0"}]]);/** * @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 uW=te("Blocks",[["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["path",{d:"M10 21V8a1 1 0 0 0-1-1H4a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-5a1 1 0 0 0-1-1H3",key:"1fpvtg"}]]);/** * @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 hW=te("BluetoothConnected",[["path",{d:"m7 7 10 10-5 5V2l5 5L7 17",key:"1q5490"}],["line",{x1:"18",x2:"21",y1:"12",y2:"12",key:"1rsjjs"}],["line",{x1:"3",x2:"6",y1:"12",y2:"12",key:"11yl8c"}]]);/** * @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 mW=te("BluetoothOff",[["path",{d:"m17 17-5 5V12l-5 5",key:"v5aci6"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M14.5 9.5 17 7l-5-5v4.5",key:"1kddfz"}]]);/** * @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 fW=te("BluetoothSearching",[["path",{d:"m7 7 10 10-5 5V2l5 5L7 17",key:"1q5490"}],["path",{d:"M20.83 14.83a4 4 0 0 0 0-5.66",key:"k8tn1j"}],["path",{d:"M18 12h.01",key:"yjnet6"}]]);/** * @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 pW=te("Bluetooth",[["path",{d:"m7 7 10 10-5 5V2l5 5L7 17",key:"1q5490"}]]);/** * @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 Ok=te("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 gW=te("Bolt",[["path",{d:"M21 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.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z",key:"yt0hxn"}],["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 xW=te("Bomb",[["circle",{cx:"11",cy:"13",r:"9",key:"hd149"}],["path",{d:"M14.35 4.65 16.3 2.7a2.41 2.41 0 0 1 3.4 0l1.6 1.6a2.4 2.4 0 0 1 0 3.4l-1.95 1.95",key:"jp4j1b"}],["path",{d:"m22 2-1.5 1.5",key:"ay92ug"}]]);/** * @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 yW=te("Bone",[["path",{d:"M17 10c.7-.7 1.69 0 2.5 0a2.5 2.5 0 1 0 0-5 .5.5 0 0 1-.5-.5 2.5 2.5 0 1 0-5 0c0 .81.7 1.8 0 2.5l-7 7c-.7.7-1.69 0-2.5 0a2.5 2.5 0 0 0 0 5c.28 0 .5.22.5.5a2.5 2.5 0 1 0 5 0c0-.81-.7-1.8 0-2.5Z",key:"w610uw"}]]);/** * @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 vW=te("BookA",[["path",{d:"M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20",key:"k3hazp"}],["path",{d:"m8 13 4-7 4 7",key:"4rari8"}],["path",{d:"M9.1 11h5.7",key:"1gkovt"}]]);/** * @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 bW=te("BookAudio",[["path",{d:"M12 6v7",key:"1f6ttz"}],["path",{d:"M16 8v3",key:"gejaml"}],["path",{d:"M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20",key:"k3hazp"}],["path",{d:"M8 8v3",key:"1qzp49"}]]);/** * @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 _W=te("BookCheck",[["path",{d:"M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20",key:"k3hazp"}],["path",{d:"m9 9.5 2 2 4-4",key:"1dth82"}]]);/** * @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 wW=te("BookCopy",[["path",{d:"M2 16V4a2 2 0 0 1 2-2h11",key:"spzkk5"}],["path",{d:"M22 18H11a2 2 0 1 0 0 4h10.5a.5.5 0 0 0 .5-.5v-15a.5.5 0 0 0-.5-.5H11a2 2 0 0 0-2 2v12",key:"1wz07i"}],["path",{d:"M5 14H4a2 2 0 1 0 0 4h1",key:"16gqf9"}]]);/** * @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 kC=te("BookDashed",[["path",{d:"M12 17h2",key:"13u4lk"}],["path",{d:"M12 22h2",key:"kn7ki6"}],["path",{d:"M12 2h2",key:"cvn524"}],["path",{d:"M18 22h1a1 1 0 0 0 1-1",key:"w6gbqz"}],["path",{d:"M18 2h1a1 1 0 0 1 1 1v1",key:"1vpra5"}],["path",{d:"M20 15v2h-2",key:"fph276"}],["path",{d:"M20 8v3",key:"deu0bs"}],["path",{d:"M4 11V9",key:"v3xsx8"}],["path",{d:"M4 19.5V15",key:"6gr39e"}],["path",{d:"M4 5v-.5A2.5 2.5 0 0 1 6.5 2H8",key:"wywhs9"}],["path",{d:"M8 22H6.5a1 1 0 0 1 0-5H8",key:"1cu73q"}]]);/** * @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=te("BookDown",[["path",{d:"M12 13V7",key:"h0r20n"}],["path",{d:"M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20",key:"k3hazp"}],["path",{d:"m9 10 3 3 3-3",key:"zt5b4y"}]]);/** * @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 NW=te("BookHeadphones",[["path",{d:"M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20",key:"k3hazp"}],["path",{d:"M8 12v-2a4 4 0 0 1 8 0v2",key:"1vsqkj"}],["circle",{cx:"15",cy:"12",r:"1",key:"1tmaij"}],["circle",{cx:"9",cy:"12",r:"1",key:"1vctgf"}]]);/** * @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 kW=te("BookHeart",[["path",{d:"M16 8.2A2.22 2.22 0 0 0 13.8 6c-.8 0-1.4.3-1.8.9-.4-.6-1-.9-1.8-.9A2.22 2.22 0 0 0 8 8.2c0 .6.3 1.2.7 1.6A226.652 226.652 0 0 0 12 13a404 404 0 0 0 3.3-3.1 2.413 2.413 0 0 0 .7-1.7",key:"1t75a8"}],["path",{d:"M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20",key:"k3hazp"}]]);/** * @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 SW=te("BookImage",[["path",{d:"m20 13.7-2.1-2.1a2 2 0 0 0-2.8 0L9.7 17",key:"q6ojf0"}],["path",{d:"M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20",key:"k3hazp"}],["circle",{cx:"10",cy:"8",r:"2",key:"2qkj4p"}]]);/** * @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 CW=te("BookKey",[["path",{d:"m19 3 1 1",key:"ze14oc"}],["path",{d:"m20 2-4.5 4.5",key:"1sppr8"}],["path",{d:"M20 8v13a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20",key:"1ocbpn"}],["path",{d:"M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H14",key:"1gfsgw"}],["circle",{cx:"14",cy:"8",r:"2",key:"u49eql"}]]);/** * @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 TW=te("BookLock",[["path",{d:"M18 6V4a2 2 0 1 0-4 0v2",key:"1aquzs"}],["path",{d:"M20 15v6a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20",key:"1rkj32"}],["path",{d:"M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H10",key:"18wgow"}],["rect",{x:"12",y:"6",width:"8",height:"5",rx:"1",key:"73l30o"}]]);/** * @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 EW=te("BookMarked",[["path",{d:"M10 2v8l3-3 3 3V2",key:"sqw3rj"}],["path",{d:"M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20",key:"k3hazp"}]]);/** * @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 AW=te("BookMinus",[["path",{d:"M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20",key:"k3hazp"}],["path",{d:"M9 10h6",key:"9gxzsh"}]]);/** * @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 MW=te("BookOpenCheck",[["path",{d:"M12 21V7",key:"gj6g52"}],["path",{d:"m16 12 2 2 4-4",key:"mdajum"}],["path",{d:"M22 6V4a1 1 0 0 0-1-1h-5a4 4 0 0 0-4 4 4 4 0 0 0-4-4H3a1 1 0 0 0-1 1v13a1 1 0 0 0 1 1h6a3 3 0 0 1 3 3 3 3 0 0 1 3-3h6a1 1 0 0 0 1-1v-1.3",key:"8arnkb"}]]);/** * @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 IW=te("BookOpenText",[["path",{d:"M12 7v14",key:"1akyts"}],["path",{d:"M16 12h2",key:"7q9ll5"}],["path",{d:"M16 8h2",key:"msurwy"}],["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"}],["path",{d:"M6 12h2",key:"32wvfc"}],["path",{d:"M6 8h2",key:"30oboj"}]]);/** * @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=te("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 PW=te("BookPlus",[["path",{d:"M12 7v6",key:"lw1j43"}],["path",{d:"M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20",key:"k3hazp"}],["path",{d:"M9 10h6",key:"9gxzsh"}]]);/** * @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 LW=te("BookText",[["path",{d:"M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20",key:"k3hazp"}],["path",{d:"M8 11h8",key:"vwpz6n"}],["path",{d:"M8 7h6",key:"1f0q6e"}]]);/** * @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 DW=te("BookType",[["path",{d:"M10 13h4",key:"ytezjc"}],["path",{d:"M12 6v7",key:"1f6ttz"}],["path",{d:"M16 8V6H8v2",key:"x8j6u4"}],["path",{d:"M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20",key:"k3hazp"}]]);/** * @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 RW=te("BookUp2",[["path",{d:"M12 13V7",key:"h0r20n"}],["path",{d:"M18 2h1a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20",key:"161d7n"}],["path",{d:"M4 19.5v-15A2.5 2.5 0 0 1 6.5 2",key:"1lorq7"}],["path",{d:"m9 10 3-3 3 3",key:"11gsxs"}],["path",{d:"m9 5 3-3 3 3",key:"l8vdw6"}]]);/** * @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 OW=te("BookUp",[["path",{d:"M12 13V7",key:"h0r20n"}],["path",{d:"M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20",key:"k3hazp"}],["path",{d:"m9 10 3-3 3 3",key:"11gsxs"}]]);/** * @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 FW=te("BookUser",[["path",{d:"M15 13a3 3 0 1 0-6 0",key:"10j68g"}],["path",{d:"M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20",key:"k3hazp"}],["circle",{cx:"12",cy:"8",r:"2",key:"1822b1"}]]);/** * @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 BW=te("BookX",[["path",{d:"m14.5 7-5 5",key:"dy991v"}],["path",{d:"M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20",key:"k3hazp"}],["path",{d:"m9.5 7 5 5",key:"s45iea"}]]);/** * @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 zW=te("Book",[["path",{d:"M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20",key:"k3hazp"}]]);/** * @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 $W=te("BookmarkCheck",[["path",{d:"m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2Z",key:"169p4p"}],["path",{d:"m9 10 2 2 4-4",key:"1gnqz4"}]]);/** * @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 UW=te("BookmarkMinus",[["path",{d:"m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z",key:"1fy3hk"}],["line",{x1:"15",x2:"9",y1:"10",y2:"10",key:"1gty7f"}]]);/** * @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 JO=te("BookmarkPlus",[["path",{d:"m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z",key:"1fy3hk"}],["line",{x1:"12",x2:"12",y1:"7",y2:"13",key:"1cppfj"}],["line",{x1:"15",x2:"9",y1:"10",y2:"10",key:"1gty7f"}]]);/** * @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=te("BookmarkX",[["path",{d:"m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2Z",key:"169p4p"}],["path",{d:"m14.5 7.5-5 5",key:"3lb6iw"}],["path",{d:"m9.5 7.5 5 5",key:"ko136h"}]]);/** * @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 Uy=te("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 VW=te("BoomBox",[["path",{d:"M4 9V5a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v4",key:"vvzvr1"}],["path",{d:"M8 8v1",key:"xcqmfk"}],["path",{d:"M12 8v1",key:"1rj8u4"}],["path",{d:"M16 8v1",key:"1q12zr"}],["rect",{width:"20",height:"12",x:"2",y:"9",rx:"2",key:"igpb89"}],["circle",{cx:"8",cy:"15",r:"2",key:"fa4a8s"}],["circle",{cx:"16",cy:"15",r:"2",key:"14c3ya"}]]);/** * @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 HW=te("BotMessageSquare",[["path",{d:"M12 6V2H8",key:"1155em"}],["path",{d:"m8 18-4 4V8a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2Z",key:"w2lp3e"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M9 11v2",key:"1ueba0"}],["path",{d:"M15 11v2",key:"i11awn"}],["path",{d:"M20 12h2",key:"1q8mjw"}]]);/** * @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 GW=te("BotOff",[["path",{d:"M13.67 8H18a2 2 0 0 1 2 2v4.33",key:"7az073"}],["path",{d:"M2 14h2",key:"vft8re"}],["path",{d:"M20 14h2",key:"4cs60a"}],["path",{d:"M22 22 2 2",key:"1r8tn9"}],["path",{d:"M8 8H6a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h12a2 2 0 0 0 1.414-.586",key:"s09a7a"}],["path",{d:"M9 13v2",key:"rq6x2g"}],["path",{d:"M9.67 4H12v2.33",key:"110xot"}]]);/** * @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 MI=te("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 WW=te("Box",[["path",{d:"M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z",key:"hh9hay"}],["path",{d:"m3.3 7 8.7 5 8.7-5",key:"g66t2b"}],["path",{d:"M12 22V12",key:"d0xqtd"}]]);/** * @license lucide-react v0.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 KW=te("Boxes",[["path",{d:"M2.97 12.92A2 2 0 0 0 2 14.63v3.24a2 2 0 0 0 .97 1.71l3 1.8a2 2 0 0 0 2.06 0L12 19v-5.5l-5-3-4.03 2.42Z",key:"lc1i9w"}],["path",{d:"m7 16.5-4.74-2.85",key:"1o9zyk"}],["path",{d:"m7 16.5 5-3",key:"va8pkn"}],["path",{d:"M7 16.5v5.17",key:"jnp8gn"}],["path",{d:"M12 13.5V19l3.97 2.38a2 2 0 0 0 2.06 0l3-1.8a2 2 0 0 0 .97-1.71v-3.24a2 2 0 0 0-.97-1.71L17 10.5l-5 3Z",key:"8zsnat"}],["path",{d:"m17 16.5-5-3",key:"8arw3v"}],["path",{d:"m17 16.5 4.74-2.85",key:"8rfmw"}],["path",{d:"M17 16.5v5.17",key:"k6z78m"}],["path",{d:"M7.97 4.42A2 2 0 0 0 7 6.13v4.37l5 3 5-3V6.13a2 2 0 0 0-.97-1.71l-3-1.8a2 2 0 0 0-2.06 0l-3 1.8Z",key:"1xygjf"}],["path",{d:"M12 8 7.26 5.15",key:"1vbdud"}],["path",{d:"m12 8 4.74-2.85",key:"3rx089"}],["path",{d:"M12 13.5V8",key:"1io7kd"}]]);/** * @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 SC=te("Braces",[["path",{d:"M8 3H7a2 2 0 0 0-2 2v5a2 2 0 0 1-2 2 2 2 0 0 1 2 2v5c0 1.1.9 2 2 2h1",key:"ezmyqa"}],["path",{d:"M16 21h1a2 2 0 0 0 2-2v-5c0-1.1.9-2 2-2a2 2 0 0 1-2-2V5a2 2 0 0 0-2-2h-1",key:"e1hn23"}]]);/** * @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 YW=te("Brackets",[["path",{d:"M16 3h3v18h-3",key:"1yor1f"}],["path",{d:"M8 21H5V3h3",key:"1qrfwo"}]]);/** * @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 ZW=te("BrainCircuit",[["path",{d:"M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z",key:"l5xja"}],["path",{d:"M9 13a4.5 4.5 0 0 0 3-4",key:"10igwf"}],["path",{d:"M6.003 5.125A3 3 0 0 0 6.401 6.5",key:"105sqy"}],["path",{d:"M3.477 10.896a4 4 0 0 1 .585-.396",key:"ql3yin"}],["path",{d:"M6 18a4 4 0 0 1-1.967-.516",key:"2e4loj"}],["path",{d:"M12 13h4",key:"1ku699"}],["path",{d:"M12 18h6a2 2 0 0 1 2 2v1",key:"105ag5"}],["path",{d:"M12 8h8",key:"1lhi5i"}],["path",{d:"M16 8V5a2 2 0 0 1 2-2",key:"u6izg6"}],["circle",{cx:"16",cy:"13",r:".5",key:"ry7gng"}],["circle",{cx:"18",cy:"3",r:".5",key:"1aiba7"}],["circle",{cx:"20",cy:"21",r:".5",key:"yhc1fs"}],["circle",{cx:"20",cy:"8",r:".5",key:"1e43v0"}]]);/** * @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 XW=te("BrainCog",[["path",{d:"M12 5a3 3 0 1 0-5.997.142 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588 4 4 0 0 0 7.636 2.106 3.2 3.2 0 0 0 .164-.546c.028-.13.306-.13.335 0a3.2 3.2 0 0 0 .163.546 4 4 0 0 0 7.636-2.106 4 4 0 0 0 .556-6.588 4 4 0 0 0-2.526-5.77A3 3 0 1 0 12 5",key:"1kgmhc"}],["path",{d:"M17.599 6.5a3 3 0 0 0 .399-1.375",key:"tmeiqw"}],["path",{d:"M6.003 5.125A3 3 0 0 0 6.401 6.5",key:"105sqy"}],["path",{d:"M3.477 10.896a4 4 0 0 1 .585-.396",key:"ql3yin"}],["path",{d:"M19.938 10.5a4 4 0 0 1 .585.396",key:"1qfode"}],["path",{d:"M6 18a4 4 0 0 1-1.967-.516",key:"2e4loj"}],["path",{d:"M19.967 17.484A4 4 0 0 1 18 18",key:"159ez6"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}],["path",{d:"m15.7 10.4-.9.4",key:"ayzo6p"}],["path",{d:"m9.2 13.2-.9.4",key:"1uzb3g"}],["path",{d:"m13.6 15.7-.4-.9",key:"11ifqf"}],["path",{d:"m10.8 9.2-.4-.9",key:"1pmk2v"}],["path",{d:"m15.7 13.5-.9-.4",key:"7ng02m"}],["path",{d:"m9.2 10.9-.9-.4",key:"1x66zd"}],["path",{d:"m10.5 15.7.4-.9",key:"3js94g"}],["path",{d:"m13.1 9.2.4-.9",key:"18n7mc"}]]);/** * @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 eF=te("Brain",[["path",{d:"M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z",key:"l5xja"}],["path",{d:"M12 5a3 3 0 1 1 5.997.125 4 4 0 0 1 2.526 5.77 4 4 0 0 1-.556 6.588A4 4 0 1 1 12 18Z",key:"ep3f8r"}],["path",{d:"M15 13a4.5 4.5 0 0 1-3-4 4.5 4.5 0 0 1-3 4",key:"1p4c4q"}],["path",{d:"M17.599 6.5a3 3 0 0 0 .399-1.375",key:"tmeiqw"}],["path",{d:"M6.003 5.125A3 3 0 0 0 6.401 6.5",key:"105sqy"}],["path",{d:"M3.477 10.896a4 4 0 0 1 .585-.396",key:"ql3yin"}],["path",{d:"M19.938 10.5a4 4 0 0 1 .585.396",key:"1qfode"}],["path",{d:"M6 18a4 4 0 0 1-1.967-.516",key:"2e4loj"}],["path",{d:"M19.967 17.484A4 4 0 0 1 18 18",key:"159ez6"}]]);/** * @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=te("BrickWall",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M12 9v6",key:"199k2o"}],["path",{d:"M16 15v6",key:"8rj2es"}],["path",{d:"M16 3v6",key:"1j6rpj"}],["path",{d:"M3 15h18",key:"5xshup"}],["path",{d:"M3 9h18",key:"1pudct"}],["path",{d:"M8 15v6",key:"1stoo3"}],["path",{d:"M8 3v6",key:"vlvjmk"}]]);/** * @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=te("BriefcaseBusiness",[["path",{d:"M12 12h.01",key:"1mp3jc"}],["path",{d:"M16 6V4a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v2",key:"1ksdt3"}],["path",{d:"M22 13a18.15 18.15 0 0 1-20 0",key:"12hx5q"}],["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 eK=te("BriefcaseConveyorBelt",[["path",{d:"M10 20v2",key:"1n8e1g"}],["path",{d:"M14 20v2",key:"1lq872"}],["path",{d:"M18 20v2",key:"10uadw"}],["path",{d:"M21 20H3",key:"kdqkdp"}],["path",{d:"M6 20v2",key:"a9bc87"}],["path",{d:"M8 16V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v12",key:"17n9tx"}],["rect",{x:"4",y:"6",width:"16",height:"10",rx:"2",key:"1097i5"}]]);/** * @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 tK=te("BriefcaseMedical",[["path",{d:"M12 11v4",key:"a6ujw6"}],["path",{d:"M14 13h-4",key:"1pl8zg"}],["path",{d:"M16 6V4a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v2",key:"1ksdt3"}],["path",{d:"M18 6v14",key:"1mu4gy"}],["path",{d:"M6 6v14",key:"1s15cj"}],["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 pm=te("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 sK=te("BringToFront",[["rect",{x:"8",y:"8",width:"8",height:"8",rx:"2",key:"yj20xf"}],["path",{d:"M4 10a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2",key:"1ltk23"}],["path",{d:"M14 20a2 2 0 0 0 2 2h4a2 2 0 0 0 2-2v-4a2 2 0 0 0-2-2",key:"1q24h9"}]]);/** * @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 rK=te("Brush",[["path",{d:"m9.06 11.9 8.07-8.06a2.85 2.85 0 1 1 4.03 4.03l-8.06 8.08",key:"1styjt"}],["path",{d:"M7.07 14.94c-1.66 0-3 1.35-3 3.02 0 1.33-2.5 1.52-2 2.02 1.08 1.1 2.49 2.02 4 2.02 2.2 0 4-1.8 4-4.04a3.01 3.01 0 0 0-3-3.02z",key:"z0l1mu"}]]);/** * @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 nK=te("BugOff",[["path",{d:"M15 7.13V6a3 3 0 0 0-5.14-2.1L8 2",key:"vl8zik"}],["path",{d:"M14.12 3.88 16 2",key:"qol33r"}],["path",{d:"M22 13h-4v-2a4 4 0 0 0-4-4h-1.3",key:"1ou0bd"}],["path",{d:"M20.97 5c0 2.1-1.6 3.8-3.5 4",key:"18gb23"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M7.7 7.7A4 4 0 0 0 6 11v3a6 6 0 0 0 11.13 3.13",key:"1njkjs"}],["path",{d:"M12 20v-8",key:"i3yub9"}],["path",{d:"M6 13H2",key:"82j7cp"}],["path",{d:"M3 21c0-2.1 1.7-3.9 3.8-4",key:"4p0ekp"}]]);/** * @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 aK=te("BugPlay",[["path",{d:"M12.765 21.522a.5.5 0 0 1-.765-.424v-8.196a.5.5 0 0 1 .765-.424l5.878 3.674a1 1 0 0 1 0 1.696z",key:"17shqo"}],["path",{d:"M14.12 3.88 16 2",key:"qol33r"}],["path",{d:"M18 11a4 4 0 0 0-4-4h-4a4 4 0 0 0-4 4v3a6.1 6.1 0 0 0 2 4.5",key:"1tjixy"}],["path",{d:"M20.97 5c0 2.1-1.6 3.8-3.5 4",key:"18gb23"}],["path",{d:"M3 21c0-2.1 1.7-3.9 3.8-4",key:"4p0ekp"}],["path",{d:"M6 13H2",key:"82j7cp"}],["path",{d:"M6.53 9C4.6 8.8 3 7.1 3 5",key:"32zzws"}],["path",{d:"m8 2 1.88 1.88",key:"fmnt4t"}],["path",{d:"M9 7.13v-1a3.003 3.003 0 1 1 6 0v1",key:"d7y7pr"}]]);/** * @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 iK=te("Bug",[["path",{d:"m8 2 1.88 1.88",key:"fmnt4t"}],["path",{d:"M14.12 3.88 16 2",key:"qol33r"}],["path",{d:"M9 7.13v-1a3.003 3.003 0 1 1 6 0v1",key:"d7y7pr"}],["path",{d:"M12 20c-3.3 0-6-2.7-6-6v-3a4 4 0 0 1 4-4h4a4 4 0 0 1 4 4v3c0 3.3-2.7 6-6 6",key:"xs1cw7"}],["path",{d:"M12 20v-9",key:"1qisl0"}],["path",{d:"M6.53 9C4.6 8.8 3 7.1 3 5",key:"32zzws"}],["path",{d:"M6 13H2",key:"82j7cp"}],["path",{d:"M3 21c0-2.1 1.7-3.9 3.8-4",key:"4p0ekp"}],["path",{d:"M20.97 5c0 2.1-1.6 3.8-3.5 4",key:"18gb23"}],["path",{d:"M22 13h-4",key:"1jl80f"}],["path",{d:"M17.2 17c2.1.1 3.8 1.9 3.8 4",key:"k3fwyw"}]]);/** * @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 Xa=te("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 mE=te("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 oK=te("BusFront",[["path",{d:"M4 6 2 7",key:"1mqr15"}],["path",{d:"M10 6h4",key:"1itunk"}],["path",{d:"m22 7-2-1",key:"1umjhc"}],["rect",{width:"16",height:"16",x:"4",y:"3",rx:"2",key:"1wxw4b"}],["path",{d:"M4 11h16",key:"mpoxn0"}],["path",{d:"M8 15h.01",key:"a7atzg"}],["path",{d:"M16 15h.01",key:"rnfrdf"}],["path",{d:"M6 19v2",key:"1loha6"}],["path",{d:"M18 21v-2",key:"sqyl04"}]]);/** * @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 lK=te("Bus",[["path",{d:"M8 6v6",key:"18i7km"}],["path",{d:"M15 6v6",key:"1sg6z9"}],["path",{d:"M2 12h19.6",key:"de5uta"}],["path",{d:"M18 18h3s.5-1.7.8-2.8c.1-.4.2-.8.2-1.2 0-.4-.1-.8-.2-1.2l-1.4-5C20.1 6.8 19.1 6 18 6H4a2 2 0 0 0-2 2v10h3",key:"1wwztk"}],["circle",{cx:"7",cy:"18",r:"2",key:"19iecd"}],["path",{d:"M9 18h5",key:"lrx6i"}],["circle",{cx:"16",cy:"18",r:"2",key:"1v4tcr"}]]);/** * @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 cK=te("CableCar",[["path",{d:"M10 3h.01",key:"lbucoy"}],["path",{d:"M14 2h.01",key:"1k8aa1"}],["path",{d:"m2 9 20-5",key:"1kz0j5"}],["path",{d:"M12 12V6.5",key:"1vbrij"}],["rect",{width:"16",height:"10",x:"4",y:"12",rx:"3",key:"if91er"}],["path",{d:"M9 12v5",key:"3anwtq"}],["path",{d:"M15 12v5",key:"5xh3zn"}],["path",{d:"M4 17h16",key:"g4d7ey"}]]);/** * @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 dK=te("Cable",[["path",{d:"M17 21v-2a1 1 0 0 1-1-1v-1a2 2 0 0 1 2-2h2a2 2 0 0 1 2 2v1a1 1 0 0 1-1 1",key:"10bnsj"}],["path",{d:"M19 15V6.5a1 1 0 0 0-7 0v11a1 1 0 0 1-7 0V9",key:"1eqmu1"}],["path",{d:"M21 21v-2h-4",key:"14zm7j"}],["path",{d:"M3 5h4V3",key:"z442eg"}],["path",{d:"M7 5a1 1 0 0 1 1 1v1a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V6a1 1 0 0 1 1-1V3",key:"ebdjd7"}]]);/** * @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 uK=te("CakeSlice",[["circle",{cx:"9",cy:"7",r:"2",key:"1305pl"}],["path",{d:"M7.2 7.9 3 11v9c0 .6.4 1 1 1h16c.6 0 1-.4 1-1v-9c0-2-3-6-7-8l-3.6 2.6",key:"xle13f"}],["path",{d:"M16 13H3",key:"1wpj08"}],["path",{d:"M16 17H3",key:"3lvfcd"}]]);/** * @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=te("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 II=te("Calculator",[["rect",{width:"16",height:"20",x:"4",y:"2",rx:"2",key:"1nb95v"}],["line",{x1:"8",x2:"16",y1:"6",y2:"6",key:"x4nwl0"}],["line",{x1:"16",x2:"16",y1:"14",y2:"18",key:"wjye3r"}],["path",{d:"M16 10h.01",key:"1m94wz"}],["path",{d:"M12 10h.01",key:"1nrarc"}],["path",{d:"M8 10h.01",key:"19clt8"}],["path",{d:"M12 14h.01",key:"1etili"}],["path",{d:"M8 14h.01",key:"6423bh"}],["path",{d:"M12 18h.01",key:"mhygvu"}],["path",{d:"M8 18h.01",key:"lrp35t"}]]);/** * @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 hK=te("Calendar1",[["path",{d:"M11 14h1v4",key:"fy54vd"}],["path",{d:"M16 2v4",key:"4m81vk"}],["path",{d:"M3 10h18",key:"8toen8"}],["path",{d:"M8 2v4",key:"1cmpym"}],["rect",{x:"3",y:"4",width:"18",height:"18",rx:"2",key:"12vinp"}]]);/** * @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 mK=te("CalendarArrowDown",[["path",{d:"m14 18 4 4 4-4",key:"1waygx"}],["path",{d:"M16 2v4",key:"4m81vk"}],["path",{d:"M18 14v8",key:"irew45"}],["path",{d:"M21 11.354V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h7.343",key:"bse4f3"}],["path",{d:"M3 10h18",key:"8toen8"}],["path",{d:"M8 2v4",key:"1cmpym"}]]);/** * @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 fK=te("CalendarArrowUp",[["path",{d:"m14 18 4-4 4 4",key:"ftkppy"}],["path",{d:"M16 2v4",key:"4m81vk"}],["path",{d:"M18 22v-8",key:"su0gjh"}],["path",{d:"M21 11.343V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h9",key:"1exg90"}],["path",{d:"M3 10h18",key:"8toen8"}],["path",{d:"M8 2v4",key:"1cmpym"}]]);/** * @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 pK=te("CalendarCheck2",[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["path",{d:"M21 14V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h8",key:"bce9hv"}],["path",{d:"M3 10h18",key:"8toen8"}],["path",{d:"m16 20 2 2 4-4",key:"13tcca"}]]);/** * @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=te("CalendarCheck",[["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:"m9 16 2 2 4-4",key:"19s6y9"}]]);/** * @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 h_=te("CalendarClock",[["path",{d:"M21 7.5V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h3.5",key:"1osxxc"}],["path",{d:"M16 2v4",key:"4m81vk"}],["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M3 10h5",key:"r794hk"}],["path",{d:"M17.5 17.5 16 16.3V14",key:"akvzfd"}],["circle",{cx:"16",cy:"16",r:"6",key:"qoo3c4"}]]);/** * @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 gK=te("CalendarCog",[["path",{d:"m15.2 16.9-.9-.4",key:"1r0w5f"}],["path",{d:"m15.2 19.1-.9.4",key:"j188fs"}],["path",{d:"M16 2v4",key:"4m81vk"}],["path",{d:"m16.9 15.2-.4-.9",key:"699xu"}],["path",{d:"m16.9 20.8-.4.9",key:"dfjc4z"}],["path",{d:"m19.5 14.3-.4.9",key:"1eb35c"}],["path",{d:"m19.5 21.7-.4-.9",key:"1tonu5"}],["path",{d:"M21 10.5V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h6",key:"11kmuh"}],["path",{d:"m21.7 16.5-.9.4",key:"1knoei"}],["path",{d:"m21.7 19.5-.9-.4",key:"q4dx6b"}],["path",{d:"M3 10h18",key:"8toen8"}],["path",{d:"M8 2v4",key:"1cmpym"}],["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}]]);/** * @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 xu=te("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 xK=te("CalendarFold",[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["path",{d:"M21 17V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h11Z",key:"kg77oy"}],["path",{d:"M3 10h18",key:"8toen8"}],["path",{d:"M15 22v-4a2 2 0 0 1 2-2h4",key:"1gnbqr"}]]);/** * @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=te("CalendarHeart",[["path",{d:"M3 10h18V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h7",key:"136lmk"}],["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["path",{d:"M21.29 14.7a2.43 2.43 0 0 0-2.65-.52c-.3.12-.57.3-.8.53l-.34.34-.35-.34a2.43 2.43 0 0 0-2.65-.53c-.3.12-.56.3-.79.53-.95.94-1 2.53.2 3.74L17.5 22l3.6-3.55c1.2-1.21 1.14-2.8.19-3.74Z",key:"1t7hil"}]]);/** * @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 yK=te("CalendarMinus2",[["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:"M10 16h4",key:"17e571"}]]);/** * @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 vK=te("CalendarMinus",[["path",{d:"M16 19h6",key:"xwg31i"}],["path",{d:"M16 2v4",key:"4m81vk"}],["path",{d:"M21 15V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h8.5",key:"1scpom"}],["path",{d:"M3 10h18",key:"8toen8"}],["path",{d:"M8 2v4",key:"1cmpym"}]]);/** * @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=te("CalendarOff",[["path",{d:"M4.2 4.2A2 2 0 0 0 3 6v14a2 2 0 0 0 2 2h14a2 2 0 0 0 1.82-1.18",key:"16swn3"}],["path",{d:"M21 15.5V6a2 2 0 0 0-2-2H9.5",key:"yhw86o"}],["path",{d:"M16 2v4",key:"4m81vk"}],["path",{d:"M3 10h7",key:"1wap6i"}],["path",{d:"M21 10h-5.5",key:"quycpq"}],["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 bK=te("CalendarPlus2",[["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:"M10 16h4",key:"17e571"}],["path",{d:"M12 14v4",key:"1thi36"}]]);/** * @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 A2=te("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 _K=te("CalendarRange",[["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M16 2v4",key:"4m81vk"}],["path",{d:"M3 10h18",key:"8toen8"}],["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M17 14h-6",key:"bkmgh3"}],["path",{d:"M13 18H7",key:"bb0bb7"}],["path",{d:"M7 14h.01",key:"1qa3f1"}],["path",{d:"M17 18h.01",key:"1bdyru"}]]);/** * @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 wK=te("CalendarSearch",[["path",{d:"M16 2v4",key:"4m81vk"}],["path",{d:"M21 11.75V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h7.25",key:"1jrsq6"}],["path",{d:"m22 22-1.875-1.875",key:"13zax7"}],["path",{d:"M3 10h18",key:"8toen8"}],["path",{d:"M8 2v4",key:"1cmpym"}],["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}]]);/** * @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 jK=te("CalendarSync",[["path",{d:"M11 10v4h4",key:"172dkj"}],["path",{d:"m11 14 1.535-1.605a5 5 0 0 1 8 1.5",key:"vu0qm5"}],["path",{d:"M16 2v4",key:"4m81vk"}],["path",{d:"m21 18-1.535 1.605a5 5 0 0 1-8-1.5",key:"1qgeyt"}],["path",{d:"M21 22v-4h-4",key:"hrummi"}],["path",{d:"M21 8.5V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h4.3",key:"mctw84"}],["path",{d:"M3 10h4",key:"1el30a"}],["path",{d:"M8 2v4",key:"1cmpym"}]]);/** * @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 NK=te("CalendarX2",[["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:"m17 22 5-5",key:"1k6ppv"}],["path",{d:"m17 17 5 5",key:"p7ous7"}]]);/** * @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 kK=te("CalendarX",[["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:"m14 14-4 4",key:"rymu2i"}],["path",{d:"m10 14 4 4",key:"3sz06r"}]]);/** * @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 Nn=te("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 SK=te("CameraOff",[["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}],["path",{d:"M7 7H4a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h16",key:"qmtpty"}],["path",{d:"M9.5 4h5L17 7h3a2 2 0 0 1 2 2v7.5",key:"1ufyfc"}],["path",{d:"M14.121 15.121A3 3 0 1 1 9.88 10.88",key:"11zox6"}]]);/** * @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 lx=te("Camera",[["path",{d:"M14.5 4h-5L7 7H4a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-3l-2.5-3z",key:"1tc9qg"}],["circle",{cx:"12",cy:"13",r:"3",key:"1vg3eu"}]]);/** * @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 CK=te("CandyCane",[["path",{d:"M5.7 21a2 2 0 0 1-3.5-2l8.6-14a6 6 0 0 1 10.4 6 2 2 0 1 1-3.464-2 2 2 0 1 0-3.464-2Z",key:"isaq8g"}],["path",{d:"M17.75 7 15 2.1",key:"12x7e8"}],["path",{d:"M10.9 4.8 13 9",key:"100a87"}],["path",{d:"m7.9 9.7 2 4.4",key:"ntfhaj"}],["path",{d:"M4.9 14.7 7 18.9",key:"1x43jy"}]]);/** * @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 TK=te("CandyOff",[["path",{d:"m8.5 8.5-1 1a4.95 4.95 0 0 0 7 7l1-1",key:"1ff4ui"}],["path",{d:"M11.843 6.187A4.947 4.947 0 0 1 16.5 7.5a4.947 4.947 0 0 1 1.313 4.657",key:"1sbrv4"}],["path",{d:"M14 16.5V14",key:"1maf8j"}],["path",{d:"M14 6.5v1.843",key:"1a6u6t"}],["path",{d:"M10 10v7.5",key:"80pj65"}],["path",{d:"m16 7 1-5 1.367.683A3 3 0 0 0 19.708 3H21v1.292a3 3 0 0 0 .317 1.341L22 7l-5 1",key:"11a9mt"}],["path",{d:"m8 17-1 5-1.367-.683A3 3 0 0 0 4.292 21H3v-1.292a3 3 0 0 0-.317-1.341L2 17l5-1",key:"3mjmon"}],["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}]]);/** * @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 EK=te("Candy",[["path",{d:"m9.5 7.5-2 2a4.95 4.95 0 1 0 7 7l2-2a4.95 4.95 0 1 0-7-7Z",key:"ue6khb"}],["path",{d:"M14 6.5v10",key:"5xnk7c"}],["path",{d:"M10 7.5v10",key:"1uew51"}],["path",{d:"m16 7 1-5 1.37.68A3 3 0 0 0 19.7 3H21v1.3c0 .46.1.92.32 1.33L22 7l-5 1",key:"b9cp6k"}],["path",{d:"m8 17-1 5-1.37-.68A3 3 0 0 0 4.3 21H3v-1.3a3 3 0 0 0-.32-1.33L2 17l5-1",key:"5lney8"}]]);/** * @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 AK=te("Cannabis",[["path",{d:"M12 22v-4",key:"1utk9m"}],["path",{d:"M7 12c-1.5 0-4.5 1.5-5 3 3.5 1.5 6 1 6 1-1.5 1.5-2 3.5-2 5 2.5 0 4.5-1.5 6-3 1.5 1.5 3.5 3 6 3 0-1.5-.5-3.5-2-5 0 0 2.5.5 6-1-.5-1.5-3.5-3-5-3 1.5-1 4-4 4-6-2.5 0-5.5 1.5-7 3 0-2.5-.5-5-2-7-1.5 2-2 4.5-2 7-1.5-1.5-4.5-3-7-3 0 2 2.5 5 4 6",key:"1mezod"}]]);/** * @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 MK=te("CaptionsOff",[["path",{d:"M10.5 5H19a2 2 0 0 1 2 2v8.5",key:"jqtk4d"}],["path",{d:"M17 11h-.5",key:"1961ue"}],["path",{d:"M19 19H5a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2",key:"1keqsi"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M7 11h4",key:"1o1z6v"}],["path",{d:"M7 15h2.5",key:"1ina1g"}]]);/** * @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 CC=te("Captions",[["rect",{width:"18",height:"14",x:"3",y:"5",rx:"2",ry:"2",key:"12ruh7"}],["path",{d:"M7 15h4M15 15h2M7 11h2M13 11h4",key:"1ueiar"}]]);/** * @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 IK=te("CarFront",[["path",{d:"m21 8-2 2-1.5-3.7A2 2 0 0 0 15.646 5H8.4a2 2 0 0 0-1.903 1.257L5 10 3 8",key:"1imjwt"}],["path",{d:"M7 14h.01",key:"1qa3f1"}],["path",{d:"M17 14h.01",key:"7oqj8z"}],["rect",{width:"18",height:"8",x:"3",y:"10",rx:"2",key:"a7itu8"}],["path",{d:"M5 18v2",key:"ppbyun"}],["path",{d:"M19 18v2",key:"gy7782"}]]);/** * @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 PK=te("CarTaxiFront",[["path",{d:"M10 2h4",key:"n1abiw"}],["path",{d:"m21 8-2 2-1.5-3.7A2 2 0 0 0 15.646 5H8.4a2 2 0 0 0-1.903 1.257L5 10 3 8",key:"1imjwt"}],["path",{d:"M7 14h.01",key:"1qa3f1"}],["path",{d:"M17 14h.01",key:"7oqj8z"}],["rect",{width:"18",height:"8",x:"3",y:"10",rx:"2",key:"a7itu8"}],["path",{d:"M5 18v2",key:"ppbyun"}],["path",{d:"M19 18v2",key:"gy7782"}]]);/** * @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 LK=te("Car",[["path",{d:"M19 17h2c.6 0 1-.4 1-1v-3c0-.9-.7-1.7-1.5-1.9C18.7 10.6 16 10 16 10s-1.3-1.4-2.2-2.3c-.5-.4-1.1-.7-1.8-.7H5c-.6 0-1.1.4-1.4.9l-1.4 2.9A3.7 3.7 0 0 0 2 12v4c0 .6.4 1 1 1h2",key:"5owen"}],["circle",{cx:"7",cy:"17",r:"2",key:"u2ysq9"}],["path",{d:"M9 17h6",key:"r8uit2"}],["circle",{cx:"17",cy:"17",r:"2",key:"axvx0g"}]]);/** * @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 DK=te("Caravan",[["path",{d:"M18 19V9a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v8a2 2 0 0 0 2 2h2",key:"19jm3t"}],["path",{d:"M2 9h3a1 1 0 0 1 1 1v2a1 1 0 0 1-1 1H2",key:"13hakp"}],["path",{d:"M22 17v1a1 1 0 0 1-1 1H10v-9a1 1 0 0 1 1-1h2a1 1 0 0 1 1 1v9",key:"1crci8"}],["circle",{cx:"8",cy:"19",r:"2",key:"t8fc5s"}]]);/** * @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 RK=te("Carrot",[["path",{d:"M2.27 21.7s9.87-3.5 12.73-6.36a4.5 4.5 0 0 0-6.36-6.37C5.77 11.84 2.27 21.7 2.27 21.7zM8.64 14l-2.05-2.04M15.34 15l-2.46-2.46",key:"rfqxbe"}],["path",{d:"M22 9s-1.33-2-3.5-2C16.86 7 15 9 15 9s1.33 2 3.5 2S22 9 22 9z",key:"6b25w4"}],["path",{d:"M15 2s-2 1.33-2 3.5S15 9 15 9s2-1.84 2-3.5C17 3.33 15 2 15 2z",key:"fn65lo"}]]);/** * @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 OK=te("CaseLower",[["circle",{cx:"7",cy:"12",r:"3",key:"12clwm"}],["path",{d:"M10 9v6",key:"17i7lo"}],["circle",{cx:"17",cy:"12",r:"3",key:"gl7c2s"}],["path",{d:"M14 7v8",key:"dl84cr"}]]);/** * @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 FK=te("CaseSensitive",[["path",{d:"m3 15 4-8 4 8",key:"1vwr6u"}],["path",{d:"M4 13h6",key:"1r9ots"}],["circle",{cx:"18",cy:"12",r:"3",key:"1kchzo"}],["path",{d:"M21 9v6",key:"anns31"}]]);/** * @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 BK=te("CaseUpper",[["path",{d:"m3 15 4-8 4 8",key:"1vwr6u"}],["path",{d:"M4 13h6",key:"1r9ots"}],["path",{d:"M15 11h4.5a2 2 0 0 1 0 4H15V7h4a2 2 0 0 1 0 4",key:"1sqfas"}]]);/** * @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 zK=te("CassetteTape",[["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}],["circle",{cx:"8",cy:"10",r:"2",key:"1xl4ub"}],["path",{d:"M8 12h8",key:"1wcyev"}],["circle",{cx:"16",cy:"10",r:"2",key:"r14t7q"}],["path",{d:"m6 20 .7-2.9A1.4 1.4 0 0 1 8.1 16h7.8a1.4 1.4 0 0 1 1.4 1l.7 3",key:"l01ucn"}]]);/** * @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 $K=te("Cast",[["path",{d:"M2 8V6a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2h-6",key:"3zrzxg"}],["path",{d:"M2 12a9 9 0 0 1 8 8",key:"g6cvee"}],["path",{d:"M2 16a5 5 0 0 1 4 4",key:"1y1dii"}],["line",{x1:"2",x2:"2.01",y1:"20",y2:"20",key:"xu2jvo"}]]);/** * @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 UK=te("Castle",[["path",{d:"M22 20v-9H2v9a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2Z",key:"109fe4"}],["path",{d:"M18 11V4H6v7",key:"mon5oj"}],["path",{d:"M15 22v-4a3 3 0 0 0-3-3a3 3 0 0 0-3 3v4",key:"1k4jtn"}],["path",{d:"M22 11V9",key:"3zbp94"}],["path",{d:"M2 11V9",key:"1x5rnq"}],["path",{d:"M6 4V2",key:"1rsq15"}],["path",{d:"M18 4V2",key:"1jsdo1"}],["path",{d:"M10 4V2",key:"75d9ly"}],["path",{d:"M14 4V2",key:"8nj3z6"}]]);/** * @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 qK=te("Cat",[["path",{d:"M12 5c.67 0 1.35.09 2 .26 1.78-2 5.03-2.84 6.42-2.26 1.4.58-.42 7-.42 7 .57 1.07 1 2.24 1 3.44C21 17.9 16.97 21 12 21s-9-3-9-7.56c0-1.25.5-2.4 1-3.44 0 0-1.89-6.42-.5-7 1.39-.58 4.72.23 6.5 2.23A9.04 9.04 0 0 1 12 5Z",key:"x6xyqk"}],["path",{d:"M8 14v.5",key:"1nzgdb"}],["path",{d:"M16 14v.5",key:"1lajdz"}],["path",{d:"M11.25 16.25h1.5L12 17l-.75-.75Z",key:"12kq1m"}]]);/** * @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 VK=te("Cctv",[["path",{d:"M16.75 12h3.632a1 1 0 0 1 .894 1.447l-2.034 4.069a1 1 0 0 1-1.708.134l-2.124-2.97",key:"ir91b5"}],["path",{d:"M17.106 9.053a1 1 0 0 1 .447 1.341l-3.106 6.211a1 1 0 0 1-1.342.447L3.61 12.3a2.92 2.92 0 0 1-1.3-3.91L3.69 5.6a2.92 2.92 0 0 1 3.92-1.3z",key:"jlp8i1"}],["path",{d:"M2 19h3.76a2 2 0 0 0 1.8-1.1L9 15",key:"19bib8"}],["path",{d:"M2 21v-4",key:"l40lih"}],["path",{d:"M7 9h.01",key:"19b3jx"}]]);/** * @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 TC=te("ChartArea",[["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["path",{d:"M7 11.207a.5.5 0 0 1 .146-.353l2-2a.5.5 0 0 1 .708 0l3.292 3.292a.5.5 0 0 0 .708 0l4.292-4.292a.5.5 0 0 1 .854.353V16a1 1 0 0 1-1 1H8a1 1 0 0 1-1-1z",key:"q0gr47"}]]);/** * @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 EC=te("ChartBarBig",[["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["rect",{x:"7",y:"13",width:"9",height:"4",rx:"1",key:"1iip1u"}],["rect",{x:"7",y:"5",width:"12",height:"4",rx:"1",key:"1anskk"}]]);/** * @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 HK=te("ChartBarDecreasing",[["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["path",{d:"M7 11h8",key:"1feolt"}],["path",{d:"M7 16h3",key:"ur6vzw"}],["path",{d:"M7 6h12",key:"sz5b0d"}]]);/** * @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 GK=te("ChartBarIncreasing",[["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["path",{d:"M7 11h8",key:"1feolt"}],["path",{d:"M7 16h12",key:"wsnu98"}],["path",{d:"M7 6h3",key:"w9rmul"}]]);/** * @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 WK=te("ChartBarStacked",[["path",{d:"M11 13v4",key:"vyy2rb"}],["path",{d:"M15 5v4",key:"1gx88a"}],["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["rect",{x:"7",y:"13",width:"9",height:"4",rx:"1",key:"1iip1u"}],["rect",{x:"7",y:"5",width:"12",height:"4",rx:"1",key:"1anskk"}]]);/** * @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 AC=te("ChartBar",[["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["path",{d:"M7 16h8",key:"srdodz"}],["path",{d:"M7 11h12",key:"127s9w"}],["path",{d:"M7 6h3",key:"w9rmul"}]]);/** * @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 MC=te("ChartCandlestick",[["path",{d:"M9 5v4",key:"14uxtq"}],["rect",{width:"4",height:"6",x:"7",y:"9",rx:"1",key:"f4fvz0"}],["path",{d:"M9 15v2",key:"r5rk32"}],["path",{d:"M17 3v2",key:"1l2re6"}],["rect",{width:"4",height:"8",x:"15",y:"5",rx:"1",key:"z38je5"}],["path",{d:"M17 13v3",key:"5l0wba"}],["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}]]);/** * @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 IC=te("ChartColumnBig",[["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["rect",{x:"15",y:"5",width:"4",height:"12",rx:"1",key:"q8uenq"}],["rect",{x:"7",y:"8",width:"4",height:"9",rx:"1",key:"sr5ea"}]]);/** * @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 KK=te("ChartColumnDecreasing",[["path",{d:"M13 17V9",key:"1fwyjl"}],["path",{d:"M18 17v-3",key:"1sqioe"}],["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["path",{d:"M8 17V5",key:"1wzmnc"}]]);/** * @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 PC=te("ChartColumnIncreasing",[["path",{d:"M13 17V9",key:"1fwyjl"}],["path",{d:"M18 17V5",key:"sfb6ij"}],["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["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 YK=te("ChartColumnStacked",[["path",{d:"M11 13H7",key:"t0o9gq"}],["path",{d:"M19 9h-4",key:"rera1j"}],["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["rect",{x:"15",y:"5",width:"4",height:"12",rx:"1",key:"q8uenq"}],["rect",{x:"7",y:"8",width:"4",height:"9",rx:"1",key:"sr5ea"}]]);/** * @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 Bo=te("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 ZK=te("ChartGantt",[["path",{d:"M10 6h8",key:"zvc2xc"}],["path",{d:"M12 16h6",key:"yi5mkt"}],["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["path",{d:"M8 11h7",key:"wz2hg0"}]]);/** * @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 LC=te("ChartLine",[["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["path",{d:"m19 9-5 5-4-4-3 3",key:"2osh9i"}]]);/** * @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 XK=te("ChartNetwork",[["path",{d:"m13.11 7.664 1.78 2.672",key:"go2gg9"}],["path",{d:"m14.162 12.788-3.324 1.424",key:"11x848"}],["path",{d:"m20 4-6.06 1.515",key:"1wxxh7"}],["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["circle",{cx:"12",cy:"6",r:"2",key:"1jj5th"}],["circle",{cx:"16",cy:"12",r:"2",key:"4ma0v8"}],["circle",{cx:"9",cy:"15",r:"2",key:"lf2ghp"}]]);/** * @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 QK=te("ChartNoAxesColumnDecreasing",[["path",{d:"M12 20V10",key:"g8npz5"}],["path",{d:"M18 20v-4",key:"8uic4z"}],["path",{d:"M6 20V4",key:"1w1bmo"}]]);/** * @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=te("ChartNoAxesColumnIncreasing",[["line",{x1:"12",x2:"12",y1:"20",y2:"10",key:"1vz5eb"}],["line",{x1:"18",x2:"18",y1:"20",y2:"4",key:"cun8e5"}],["line",{x1:"6",x2:"6",y1:"20",y2:"16",key:"hq0ia6"}]]);/** * @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=te("ChartNoAxesColumn",[["line",{x1:"18",x2:"18",y1:"20",y2:"10",key:"1xfpm4"}],["line",{x1:"12",x2:"12",y1:"20",y2:"4",key:"be30l9"}],["line",{x1:"6",x2:"6",y1:"20",y2:"14",key:"1r4le6"}]]);/** * @license lucide-react v0.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 JK=te("ChartNoAxesCombined",[["path",{d:"M12 16v5",key:"zza2cw"}],["path",{d:"M16 14v7",key:"1g90b9"}],["path",{d:"M20 10v11",key:"1iqoj0"}],["path",{d:"m22 3-8.646 8.646a.5.5 0 0 1-.708 0L9.354 8.354a.5.5 0 0 0-.707 0L2 15",key:"1fw8x9"}],["path",{d:"M4 18v3",key:"1yp0dc"}],["path",{d:"M8 14v7",key:"n3cwzv"}]]);/** * @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 OC=te("ChartNoAxesGantt",[["path",{d:"M8 6h10",key:"9lnwnk"}],["path",{d:"M6 12h9",key:"1g9pqf"}],["path",{d:"M11 18h7",key:"c8dzvl"}]]);/** * @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 FC=te("ChartPie",[["path",{d:"M21 12c.552 0 1.005-.449.95-.998a10 10 0 0 0-8.953-8.951c-.55-.055-.998.398-.998.95v8a1 1 0 0 0 1 1z",key:"pzmjnu"}],["path",{d:"M21.21 15.89A10 10 0 1 1 8 2.83",key:"k2fpak"}]]);/** * @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 BC=te("ChartScatter",[["circle",{cx:"7.5",cy:"7.5",r:".5",fill:"currentColor",key:"kqv944"}],["circle",{cx:"18.5",cy:"5.5",r:".5",fill:"currentColor",key:"lysivs"}],["circle",{cx:"11.5",cy:"11.5",r:".5",fill:"currentColor",key:"byv1b8"}],["circle",{cx:"7.5",cy:"16.5",r:".5",fill:"currentColor",key:"nkw3mc"}],["circle",{cx:"17.5",cy:"14.5",r:".5",fill:"currentColor",key:"1gjh6j"}],["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}]]);/** * @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 eY=te("ChartSpline",[["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["path",{d:"M7 16c.5-2 1.5-7 4-7 2 0 2 3 4 3 2.5 0 4.5-5 5-7",key:"lw07rv"}]]);/** * @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 nF=te("CheckCheck",[["path",{d:"M18 6 7 17l-5-5",key:"116fxf"}],["path",{d:"m22 10-7.5 7.5L13 16",key:"ke71qq"}]]);/** * @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 va=te("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 tY=te("ChefHat",[["path",{d:"M17 21a1 1 0 0 0 1-1v-5.35c0-.457.316-.844.727-1.041a4 4 0 0 0-2.134-7.589 5 5 0 0 0-9.186 0 4 4 0 0 0-2.134 7.588c.411.198.727.585.727 1.041V20a1 1 0 0 0 1 1Z",key:"1qvrer"}],["path",{d:"M6 17h12",key:"1jwigz"}]]);/** * @license lucide-react v0.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 sY=te("Cherry",[["path",{d:"M2 17a5 5 0 0 0 10 0c0-2.76-2.5-5-5-3-2.5-2-5 .24-5 3Z",key:"cvxqlc"}],["path",{d:"M12 17a5 5 0 0 0 10 0c0-2.76-2.5-5-5-3-2.5-2-5 .24-5 3Z",key:"1ostrc"}],["path",{d:"M7 14c3.22-2.91 4.29-8.75 5-12 1.66 2.38 4.94 9 5 12",key:"hqx58h"}],["path",{d:"M22 9c-4.29 0-7.14-2.33-10-7 5.71 0 10 4.67 10 7Z",key:"eykp1o"}]]);/** * @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=te("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 rY=te("ChevronFirst",[["path",{d:"m17 18-6-6 6-6",key:"1yerx2"}],["path",{d:"M7 6v12",key:"1p53r6"}]]);/** * @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 nY=te("ChevronLast",[["path",{d:"m7 18 6-6-6-6",key:"lwmzdw"}],["path",{d:"M17 6v12",key:"1o0aio"}]]);/** * @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 fl=te("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 $a=te("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 cx=te("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 aY=te("ChevronsDownUp",[["path",{d:"m7 20 5-5 5 5",key:"13a0gw"}],["path",{d:"m7 4 5 5 5-5",key:"1kwcof"}]]);/** * @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 iY=te("ChevronsDown",[["path",{d:"m7 6 5 5 5-5",key:"1lc07p"}],["path",{d:"m7 13 5 5 5-5",key:"1d48rs"}]]);/** * @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 oY=te("ChevronsLeftRightEllipsis",[["path",{d:"m18 8 4 4-4 4",key:"1ak13k"}],["path",{d:"m6 8-4 4 4 4",key:"15zrgr"}],["path",{d:"M8 12h.01",key:"czm47f"}],["path",{d:"M12 12h.01",key:"1mp3jc"}],["path",{d:"M16 12h.01",key:"1l6xoz"}]]);/** * @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 lY=te("ChevronsLeftRight",[["path",{d:"m9 7-5 5 5 5",key:"j5w590"}],["path",{d:"m15 7 5 5-5 5",key:"1bl6da"}]]);/** * @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 cY=te("ChevronsLeft",[["path",{d:"m11 17-5-5 5-5",key:"13zhaf"}],["path",{d:"m18 17-5-5 5-5",key:"h8a8et"}]]);/** * @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 dY=te("ChevronsRightLeft",[["path",{d:"m20 17-5-5 5-5",key:"30x0n2"}],["path",{d:"m4 17 5-5-5-5",key:"16spf4"}]]);/** * @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 uY=te("ChevronsRight",[["path",{d:"m6 17 5-5-5-5",key:"xnjwq"}],["path",{d:"m13 17 5-5-5-5",key:"17xmmf"}]]);/** * @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 d0=te("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 hY=te("ChevronsUp",[["path",{d:"m17 11-5-5-5 5",key:"e8nh98"}],["path",{d:"m17 18-5-5-5 5",key:"2avn1x"}]]);/** * @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 fE=te("Chrome",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["line",{x1:"21.17",x2:"12",y1:"8",y2:"8",key:"a0cw5f"}],["line",{x1:"3.95",x2:"8.54",y1:"6.06",y2:"14",key:"1kftof"}],["line",{x1:"10.88",x2:"15.46",y1:"21.94",y2:"14",key:"1ymyh8"}]]);/** * @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 mY=te("Church",[["path",{d:"M10 9h4",key:"u4k05v"}],["path",{d:"M12 7v5",key:"ma6bk"}],["path",{d:"M14 22v-4a2 2 0 0 0-4 0v4",key:"1pdhuj"}],["path",{d:"M18 22V5.618a1 1 0 0 0-.553-.894l-4.553-2.277a2 2 0 0 0-1.788 0L6.553 4.724A1 1 0 0 0 6 5.618V22",key:"1rkokr"}],["path",{d:"m18 7 3.447 1.724a1 1 0 0 1 .553.894V20a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V9.618a1 1 0 0 1 .553-.894L6 7",key:"1w6esw"}]]);/** * @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 fY=te("CigaretteOff",[["path",{d:"M12 12H3a1 1 0 0 0-1 1v2a1 1 0 0 0 1 1h13",key:"1gdiyg"}],["path",{d:"M18 8c0-2.5-2-2.5-2-5",key:"1il607"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M21 12a1 1 0 0 1 1 1v2a1 1 0 0 1-.5.866",key:"166zjj"}],["path",{d:"M22 8c0-2.5-2-2.5-2-5",key:"1gah44"}],["path",{d:"M7 12v4",key:"jqww69"}]]);/** * @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 pY=te("Cigarette",[["path",{d:"M17 12H3a1 1 0 0 0-1 1v2a1 1 0 0 0 1 1h14",key:"1mb5g1"}],["path",{d:"M18 8c0-2.5-2-2.5-2-5",key:"1il607"}],["path",{d:"M21 16a1 1 0 0 0 1-1v-2a1 1 0 0 0-1-1",key:"1yl5r7"}],["path",{d:"M22 8c0-2.5-2-2.5-2-5",key:"1gah44"}],["path",{d:"M7 12v4",key:"jqww69"}]]);/** * @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 wo=te("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 zC=te("CircleArrowDown",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 8v8",key:"napkw2"}],["path",{d:"m8 12 4 4 4-4",key:"k98ssh"}]]);/** * @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 $C=te("CircleArrowLeft",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M16 12H8",key:"1fr5h0"}],["path",{d:"m12 8-4 4 4 4",key:"15vm53"}]]);/** * @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 UC=te("CircleArrowOutDownLeft",[["path",{d:"M2 12a10 10 0 1 1 10 10",key:"1yn6ov"}],["path",{d:"m2 22 10-10",key:"28ilpk"}],["path",{d:"M8 22H2v-6",key:"sulq54"}]]);/** * @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 qC=te("CircleArrowOutDownRight",[["path",{d:"M12 22a10 10 0 1 1 10-10",key:"130bv5"}],["path",{d:"M22 22 12 12",key:"131aw7"}],["path",{d:"M22 16v6h-6",key:"1gvm70"}]]);/** * @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 VC=te("CircleArrowOutUpLeft",[["path",{d:"M2 8V2h6",key:"hiwtdz"}],["path",{d:"m2 2 10 10",key:"1oh8rs"}],["path",{d:"M12 2A10 10 0 1 1 2 12",key:"rrk4fa"}]]);/** * @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 HC=te("CircleArrowOutUpRight",[["path",{d:"M22 12A10 10 0 1 1 12 2",key:"1fm58d"}],["path",{d:"M22 2 12 12",key:"yg2myt"}],["path",{d:"M16 2h6v6",key:"zan5cs"}]]);/** * @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=te("CircleArrowRight",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 12h8",key:"1wcyev"}],["path",{d:"m12 16 4-4-4-4",key:"1i9zcv"}]]);/** * @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 WC=te("CircleArrowUp",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m16 12-4-4-4 4",key:"177agl"}],["path",{d:"M12 16V8",key:"1sbj14"}]]);/** * @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 zi=te("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 ea=te("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 KC=te("CircleChevronDown",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m16 10-4 4-4-4",key:"894hmk"}]]);/** * @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=te("CircleChevronLeft",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m14 16-4-4 4-4",key:"ojs7w8"}]]);/** * @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 ZC=te("CircleChevronRight",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m10 8 4 4-4 4",key:"1wy4r4"}]]);/** * @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 XC=te("CircleChevronUp",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m8 14 4-4 4 4",key:"fy2ptz"}]]);/** * @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 gY=te("CircleDashed",[["path",{d:"M10.1 2.182a10 10 0 0 1 3.8 0",key:"5ilxe3"}],["path",{d:"M13.9 21.818a10 10 0 0 1-3.8 0",key:"11zvb9"}],["path",{d:"M17.609 3.721a10 10 0 0 1 2.69 2.7",key:"1iw5b2"}],["path",{d:"M2.182 13.9a10 10 0 0 1 0-3.8",key:"c0bmvh"}],["path",{d:"M20.279 17.609a10 10 0 0 1-2.7 2.69",key:"1ruxm7"}],["path",{d:"M21.818 10.1a10 10 0 0 1 0 3.8",key:"qkgqxc"}],["path",{d:"M3.721 6.391a10 10 0 0 1 2.7-2.69",key:"1mcia2"}],["path",{d:"M6.391 20.279a10 10 0 0 1-2.69-2.7",key:"1fvljs"}]]);/** * @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 QC=te("CircleDivide",[["line",{x1:"8",x2:"16",y1:"12",y2:"12",key:"1jonct"}],["line",{x1:"12",x2:"12",y1:"16",y2:"16",key:"aqc6ln"}],["line",{x1:"12",x2:"12",y1:"8",y2:"8",key:"1mkcni"}],["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 xY=te("CircleDollarSign",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M16 8h-6a2 2 0 1 0 0 4h4a2 2 0 1 1 0 4H8",key:"1h4pet"}],["path",{d:"M12 18V6",key:"zqpxq5"}]]);/** * @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 yY=te("CircleDotDashed",[["path",{d:"M10.1 2.18a9.93 9.93 0 0 1 3.8 0",key:"1qdqn0"}],["path",{d:"M17.6 3.71a9.95 9.95 0 0 1 2.69 2.7",key:"1bq7p6"}],["path",{d:"M21.82 10.1a9.93 9.93 0 0 1 0 3.8",key:"1rlaqf"}],["path",{d:"M20.29 17.6a9.95 9.95 0 0 1-2.7 2.69",key:"1xk03u"}],["path",{d:"M13.9 21.82a9.94 9.94 0 0 1-3.8 0",key:"l7re25"}],["path",{d:"M6.4 20.29a9.95 9.95 0 0 1-2.69-2.7",key:"1v18p6"}],["path",{d:"M2.18 13.9a9.93 9.93 0 0 1 0-3.8",key:"xdo6bj"}],["path",{d:"M3.71 6.4a9.95 9.95 0 0 1 2.7-2.69",key:"1jjmaz"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}]]);/** * @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 vY=te("CircleDot",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}]]);/** * @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 bY=te("CircleEllipsis",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M17 12h.01",key:"1m0b6t"}],["path",{d:"M12 12h.01",key:"1mp3jc"}],["path",{d:"M7 12h.01",key:"eqddd0"}]]);/** * @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 _Y=te("CircleEqual",[["path",{d:"M7 10h10",key:"1101jm"}],["path",{d:"M7 14h10",key:"1mhdw3"}],["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 wY=te("CircleFadingArrowUp",[["path",{d:"M12 2a10 10 0 0 1 7.38 16.75",key:"175t95"}],["path",{d:"m16 12-4-4-4 4",key:"177agl"}],["path",{d:"M12 16V8",key:"1sbj14"}],["path",{d:"M2.5 8.875a10 10 0 0 0-.5 3",key:"1vce0s"}],["path",{d:"M2.83 16a10 10 0 0 0 2.43 3.4",key:"o3fkw4"}],["path",{d:"M4.636 5.235a10 10 0 0 1 .891-.857",key:"1szpfk"}],["path",{d:"M8.644 21.42a10 10 0 0 0 7.631-.38",key:"9yhvd4"}]]);/** * @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 jY=te("CircleFadingPlus",[["path",{d:"M12 2a10 10 0 0 1 7.38 16.75",key:"175t95"}],["path",{d:"M12 8v8",key:"napkw2"}],["path",{d:"M16 12H8",key:"1fr5h0"}],["path",{d:"M2.5 8.875a10 10 0 0 0-.5 3",key:"1vce0s"}],["path",{d:"M2.83 16a10 10 0 0 0 2.43 3.4",key:"o3fkw4"}],["path",{d:"M4.636 5.235a10 10 0 0 1 .891-.857",key:"1szpfk"}],["path",{d:"M8.644 21.42a10 10 0 0 0 7.631-.38",key:"9yhvd4"}]]);/** * @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 JC=te("CircleGauge",[["path",{d:"M15.6 2.7a10 10 0 1 0 5.7 5.7",key:"1e0p6d"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}],["path",{d:"M13.4 10.6 19 5",key:"1kr7tw"}]]);/** * @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 v2=te("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 e3=te("CircleMinus",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 12h8",key:"1wcyev"}]]);/** * @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 NY=te("CircleOff",[["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M8.35 2.69A10 10 0 0 1 21.3 15.65",key:"1pfsoa"}],["path",{d:"M19.08 19.08A10 10 0 1 1 4.92 4.92",key:"1ablyi"}]]);/** * @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 t3=te("CircleParkingOff",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m5 5 14 14",key:"11anup"}],["path",{d:"M13 13a3 3 0 1 0 0-6H9v2",key:"uoagbd"}],["path",{d:"M9 17v-2.34",key:"a9qo08"}]]);/** * @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 s3=te("CircleParking",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M9 17V7h4a3 3 0 0 1 0 6H9",key:"1dfk2c"}]]);/** * @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 r3=te("CirclePause",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"10",x2:"10",y1:"15",y2:"9",key:"c1nkhi"}],["line",{x1:"14",x2:"14",y1:"15",y2:"9",key:"h65svq"}]]);/** * @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 n3=te("CirclePercent",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"M9 9h.01",key:"1q5me6"}],["path",{d:"M15 15h.01",key:"lqbp3k"}]]);/** * @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 cg=te("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 a3=te("CirclePlus",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 12h8",key:"1wcyev"}],["path",{d:"M12 8v8",key:"napkw2"}]]);/** * @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 i3=te("CirclePower",[["path",{d:"M12 7v4",key:"xawao1"}],["path",{d:"M7.998 9.003a5 5 0 1 0 8-.005",key:"1pek45"}],["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 o3=te("CircleSlash2",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M22 2 2 22",key:"y4kqgn"}]]);/** * @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 kY=te("CircleSlash",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"9",x2:"15",y1:"15",y2:"9",key:"1dfufj"}]]);/** * @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 l3=te("CircleStop",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["rect",{x:"9",y:"9",width:"6",height:"6",rx:"1",key:"1ssd4o"}]]);/** * @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 c3=te("CircleUserRound",[["path",{d:"M18 20a6 6 0 0 0-12 0",key:"1qehca"}],["circle",{cx:"12",cy:"10",r:"4",key:"1h16sb"}],["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 d3=te("CircleUser",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"10",r:"3",key:"ilqhr7"}],["path",{d:"M7 20.662V19a2 2 0 0 1 2-2h6a2 2 0 0 1 2 2v1.662",key:"154egf"}]]);/** * @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 kd=te("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 Gu=te("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 SY=te("CircuitBoard",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M11 9h4a2 2 0 0 0 2-2V3",key:"1ve2rv"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"M7 21v-4a2 2 0 0 1 2-2h4",key:"1fwkro"}],["circle",{cx:"15",cy:"15",r:"2",key:"3i40o0"}]]);/** * @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 CY=te("Citrus",[["path",{d:"M21.66 17.67a1.08 1.08 0 0 1-.04 1.6A12 12 0 0 1 4.73 2.38a1.1 1.1 0 0 1 1.61-.04z",key:"4ite01"}],["path",{d:"M19.65 15.66A8 8 0 0 1 8.35 4.34",key:"1gxipu"}],["path",{d:"m14 10-5.5 5.5",key:"92pfem"}],["path",{d:"M14 17.85V10H6.15",key:"xqmtsk"}]]);/** * @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 TY=te("Clapperboard",[["path",{d:"M20.2 6 3 11l-.9-2.4c-.3-1.1.3-2.2 1.3-2.5l13.5-4c1.1-.3 2.2.3 2.5 1.3Z",key:"1tn4o7"}],["path",{d:"m6.2 5.3 3.1 3.9",key:"iuk76l"}],["path",{d:"m12.4 3.4 3.1 4",key:"6hsd6n"}],["path",{d:"M3 11h18v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2Z",key:"ltgou9"}]]);/** * @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 PI=te("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 EY=te("ClipboardCopy",[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1",key:"tgr4d6"}],["path",{d:"M8 4H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-2",key:"4jdomd"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v4",key:"3hqy98"}],["path",{d:"M21 14H11",key:"1bme5i"}],["path",{d:"m15 10-4 4 4 4",key:"5dvupr"}]]);/** * @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 Fk=te("ClipboardList",[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1",key:"tgr4d6"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2",key:"116196"}],["path",{d:"M12 11h4",key:"1jrz19"}],["path",{d:"M12 16h4",key:"n85exb"}],["path",{d:"M8 11h.01",key:"1dfujw"}],["path",{d:"M8 16h.01",key:"18s6g9"}]]);/** * @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 AY=te("ClipboardMinus",[["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 14h6",key:"159ibu"}]]);/** * @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 MY=te("ClipboardPaste",[["path",{d:"M15 2H9a1 1 0 0 0-1 1v2c0 .6.4 1 1 1h6c.6 0 1-.4 1-1V3c0-.6-.4-1-1-1Z",key:"1pp7kr"}],["path",{d:"M8 4H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2M16 4h2a2 2 0 0 1 2 2v2M11 14h10",key:"2ik1ml"}],["path",{d:"m17 10 4 4-4 4",key:"vp2hj1"}]]);/** * @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 u3=te("ClipboardPenLine",[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",key:"1oijnt"}],["path",{d:"M8 4H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-.5",key:"1but9f"}],["path",{d:"M16 4h2a2 2 0 0 1 1.73 1",key:"1p8n7l"}],["path",{d:"M8 18h1",key:"13wk12"}],["path",{d:"M21.378 12.626a1 1 0 0 0-3.004-3.004l-4.01 4.012a2 2 0 0 0-.506.854l-.837 2.87a.5.5 0 0 0 .62.62l2.87-.837a2 2 0 0 0 .854-.506z",key:"2t3380"}]]);/** * @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 h3=te("ClipboardPen",[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",key:"1oijnt"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-5.5",key:"cereej"}],["path",{d:"M4 13.5V6a2 2 0 0 1 2-2h2",key:"5ua5vh"}],["path",{d:"M13.378 15.626a1 1 0 1 0-3.004-3.004l-5.01 5.012a2 2 0 0 0-.506.854l-.837 2.87a.5.5 0 0 0 .62.62l2.87-.837a2 2 0 0 0 .854-.506z",key:"1y4qbx"}]]);/** * @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 IY=te("ClipboardPlus",[["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 14h6",key:"159ibu"}],["path",{d:"M12 17v-6",key:"1y8rbf"}]]);/** * @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 PY=te("ClipboardType",[["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 12v-1h6v1",key:"iehl6m"}],["path",{d:"M11 17h2",key:"12w5me"}],["path",{d:"M12 11v6",key:"1bwqyc"}]]);/** * @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 LY=te("ClipboardX",[["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:"m15 11-6 6",key:"1toa9n"}],["path",{d:"m9 11 6 6",key:"wlibny"}]]);/** * @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 DY=te("Clipboard",[["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"}]]);/** * @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 RY=te("Clock1",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polyline",{points:"12 6 12 12 14.5 8",key:"12zbmj"}]]);/** * @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 OY=te("Clock10",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polyline",{points:"12 6 12 12 8 10",key:"atfzqc"}]]);/** * @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 FY=te("Clock11",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polyline",{points:"12 6 12 12 9.5 8",key:"l5bg6f"}]]);/** * @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 BY=te("Clock12",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polyline",{points:"12 6 12 12",key:"1fub01"}]]);/** * @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 zY=te("Clock2",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polyline",{points:"12 6 12 12 16 10",key:"1g230d"}]]);/** * @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 $Y=te("Clock3",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polyline",{points:"12 6 12 12 16.5 12",key:"1aq6pp"}]]);/** * @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 UY=te("Clock4",[["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 qY=te("Clock5",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polyline",{points:"12 6 12 12 14.5 16",key:"1pcbox"}]]);/** * @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 VY=te("Clock6",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polyline",{points:"12 6 12 12 12 16.5",key:"hb2qv6"}]]);/** * @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 HY=te("Clock7",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polyline",{points:"12 6 12 12 9.5 16",key:"ka3394"}]]);/** * @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 GY=te("Clock8",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polyline",{points:"12 6 12 12 8 14",key:"tmc9b4"}]]);/** * @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 WY=te("Clock9",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polyline",{points:"12 6 12 12 7.5 12",key:"1k60p0"}]]);/** * @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 KY=te("ClockAlert",[["path",{d:"M12 6v6l4 2",key:"mmk7yg"}],["path",{d:"M16 21.16a10 10 0 1 1 5-13.516",key:"cxo92l"}],["path",{d:"M20 11.5v6",key:"2ei3xq"}],["path",{d:"M20 21.5h.01",key:"1r2dzp"}]]);/** * @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 YY=te("ClockArrowDown",[["path",{d:"M12.338 21.994A10 10 0 1 1 21.925 13.227",key:"1i7shu"}],["path",{d:"M12 6v6l2 1",key:"19cm8n"}],["path",{d:"m14 18 4 4 4-4",key:"1waygx"}],["path",{d:"M18 14v8",key:"irew45"}]]);/** * @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 ZY=te("ClockArrowUp",[["path",{d:"M13.228 21.925A10 10 0 1 1 21.994 12.338",key:"1fzlyi"}],["path",{d:"M12 6v6l1.562.781",key:"1ujuk9"}],["path",{d:"m14 18 4-4 4 4",key:"ftkppy"}],["path",{d:"M18 22v-8",key:"su0gjh"}]]);/** * @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 Pn=te("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 XY=te("CloudAlert",[["path",{d:"M12 12v4",key:"tww15h"}],["path",{d:"M12 20h.01",key:"zekei9"}],["path",{d:"M17 18h.5a1 1 0 0 0 0-9h-1.79A7 7 0 1 0 7 17.708",key:"xsb5ju"}]]);/** * @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 QY=te("CloudCog",[["circle",{cx:"12",cy:"17",r:"3",key:"1spfwm"}],["path",{d:"M4.2 15.1A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.2",key:"zaobp"}],["path",{d:"m15.7 18.4-.9-.3",key:"4qxpbn"}],["path",{d:"m9.2 15.9-.9-.3",key:"17q7o2"}],["path",{d:"m10.6 20.7.3-.9",key:"1pf4s2"}],["path",{d:"m13.1 14.2.3-.9",key:"1mnuqm"}],["path",{d:"m13.6 20.7-.4-1",key:"1jpd1m"}],["path",{d:"m10.8 14.3-.4-1",key:"17ugyy"}],["path",{d:"m8.3 18.6 1-.4",key:"s42vdx"}],["path",{d:"m14.7 15.8 1-.4",key:"2wizun"}]]);/** * @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 m3=te("CloudDownload",[["path",{d:"M12 13v8l-4-4",key:"1f5nwf"}],["path",{d:"m12 21 4-4",key:"1lfcce"}],["path",{d:"M4.393 15.269A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.436 8.284",key:"ui1hmy"}]]);/** * @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 JY=te("CloudDrizzle",[["path",{d:"M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242",key:"1pljnt"}],["path",{d:"M8 19v1",key:"1dk2by"}],["path",{d:"M8 14v1",key:"84yxot"}],["path",{d:"M16 19v1",key:"v220m7"}],["path",{d:"M16 14v1",key:"g12gj6"}],["path",{d:"M12 21v1",key:"q8vafk"}],["path",{d:"M12 16v1",key:"1mx6rx"}]]);/** * @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 eZ=te("CloudFog",[["path",{d:"M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242",key:"1pljnt"}],["path",{d:"M16 17H7",key:"pygtm1"}],["path",{d:"M17 21H9",key:"1u2q02"}]]);/** * @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 tZ=te("CloudHail",[["path",{d:"M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242",key:"1pljnt"}],["path",{d:"M16 14v2",key:"a1is7l"}],["path",{d:"M8 14v2",key:"1e9m6t"}],["path",{d:"M16 20h.01",key:"xwek51"}],["path",{d:"M8 20h.01",key:"1vjney"}],["path",{d:"M12 16v2",key:"z66u1j"}],["path",{d:"M12 22h.01",key:"1urd7a"}]]);/** * @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 sZ=te("CloudLightning",[["path",{d:"M6 16.326A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 .5 8.973",key:"1cez44"}],["path",{d:"m13 12-3 5h4l-3 5",key:"1t22er"}]]);/** * @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 rZ=te("CloudMoonRain",[["path",{d:"M10.188 8.5A6 6 0 0 1 16 4a1 1 0 0 0 6 6 6 6 0 0 1-3 5.197",key:"erj67n"}],["path",{d:"M11 20v2",key:"174qtz"}],["path",{d:"M3 20a5 5 0 1 1 8.9-4H13a3 3 0 0 1 2 5.24",key:"1qmrp3"}],["path",{d:"M7 19v2",key:"12npes"}]]);/** * @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 nZ=te("CloudMoon",[["path",{d:"M10.188 8.5A6 6 0 0 1 16 4a1 1 0 0 0 6 6 6 6 0 0 1-3 5.197",key:"erj67n"}],["path",{d:"M13 16a3 3 0 1 1 0 6H7a5 5 0 1 1 4.9-6Z",key:"p44pc9"}]]);/** * @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 aZ=te("CloudOff",[["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M5.782 5.782A7 7 0 0 0 9 19h8.5a4.5 4.5 0 0 0 1.307-.193",key:"yfwify"}],["path",{d:"M21.532 16.5A4.5 4.5 0 0 0 17.5 10h-1.79A7.008 7.008 0 0 0 10 5.07",key:"jlfiyv"}]]);/** * @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 iZ=te("CloudRainWind",[["path",{d:"M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242",key:"1pljnt"}],["path",{d:"m9.2 22 3-7",key:"sb5f6j"}],["path",{d:"m9 13-3 7",key:"500co5"}],["path",{d:"m17 13-3 7",key:"8t2fiy"}]]);/** * @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 oZ=te("CloudRain",[["path",{d:"M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242",key:"1pljnt"}],["path",{d:"M16 14v6",key:"1j4efv"}],["path",{d:"M8 14v6",key:"17c4r9"}],["path",{d:"M12 16v6",key:"c8a4gj"}]]);/** * @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 lZ=te("CloudSnow",[["path",{d:"M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242",key:"1pljnt"}],["path",{d:"M8 15h.01",key:"a7atzg"}],["path",{d:"M8 19h.01",key:"puxtts"}],["path",{d:"M12 17h.01",key:"p32p05"}],["path",{d:"M12 21h.01",key:"h35vbk"}],["path",{d:"M16 15h.01",key:"rnfrdf"}],["path",{d:"M16 19h.01",key:"1vcnzz"}]]);/** * @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 cZ=te("CloudSunRain",[["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"m4.93 4.93 1.41 1.41",key:"149t6j"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"m19.07 4.93-1.41 1.41",key:"1shlcs"}],["path",{d:"M15.947 12.65a4 4 0 0 0-5.925-4.128",key:"dpwdj0"}],["path",{d:"M3 20a5 5 0 1 1 8.9-4H13a3 3 0 0 1 2 5.24",key:"1qmrp3"}],["path",{d:"M11 20v2",key:"174qtz"}],["path",{d:"M7 19v2",key:"12npes"}]]);/** * @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 dZ=te("CloudSun",[["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"m4.93 4.93 1.41 1.41",key:"149t6j"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"m19.07 4.93-1.41 1.41",key:"1shlcs"}],["path",{d:"M15.947 12.65a4 4 0 0 0-5.925-4.128",key:"dpwdj0"}],["path",{d:"M13 22H7a5 5 0 1 1 4.9-6H13a3 3 0 0 1 0 6Z",key:"s09mg5"}]]);/** * @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 f3=te("CloudUpload",[["path",{d:"M12 13v8",key:"1l5pq0"}],["path",{d:"M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242",key:"1pljnt"}],["path",{d:"m8 17 4-4 4 4",key:"1quai1"}]]);/** * @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 uZ=te("Cloud",[["path",{d:"M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z",key:"p7xjir"}]]);/** * @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=te("Cloudy",[["path",{d:"M17.5 21H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z",key:"gqqjvc"}],["path",{d:"M22 10a3 3 0 0 0-3-3h-2.207a5.502 5.502 0 0 0-10.702.5",key:"1p2s76"}]]);/** * @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 M2=te("Clover",[["path",{d:"M16.17 7.83 2 22",key:"t58vo8"}],["path",{d:"M4.02 12a2.827 2.827 0 1 1 3.81-4.17A2.827 2.827 0 1 1 12 4.02a2.827 2.827 0 1 1 4.17 3.81A2.827 2.827 0 1 1 19.98 12a2.827 2.827 0 1 1-3.81 4.17A2.827 2.827 0 1 1 12 19.98a2.827 2.827 0 1 1-4.17-3.81A1 1 0 1 1 4 12",key:"17k36q"}],["path",{d:"m7.83 7.83 8.34 8.34",key:"1d7sxk"}]]);/** * @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 mZ=te("Club",[["path",{d:"M17.28 9.05a5.5 5.5 0 1 0-10.56 0A5.5 5.5 0 1 0 12 17.66a5.5 5.5 0 1 0 5.28-8.6Z",key:"27yuqz"}],["path",{d:"M12 17.66L12 22",key:"ogfahf"}]]);/** * @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 b2=te("CodeXml",[["path",{d:"m18 16 4-4-4-4",key:"1inbqp"}],["path",{d:"m6 8-4 4 4 4",key:"15zrgr"}],["path",{d:"m14.5 4-5 16",key:"e7oirm"}]]);/** * @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 pE=te("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 fZ=te("Codepen",[["polygon",{points:"12 2 22 8.5 22 15.5 12 22 2 15.5 2 8.5 12 2",key:"srzb37"}],["line",{x1:"12",x2:"12",y1:"22",y2:"15.5",key:"1t73f2"}],["polyline",{points:"22 8.5 12 15.5 2 8.5",key:"ajlxae"}],["polyline",{points:"2 15.5 12 8.5 22 15.5",key:"susrui"}],["line",{x1:"12",x2:"12",y1:"2",y2:"8.5",key:"2cldga"}]]);/** * @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 pZ=te("Codesandbox",[["path",{d:"M21 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.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z",key:"yt0hxn"}],["polyline",{points:"7.5 4.21 12 6.81 16.5 4.21",key:"fabo96"}],["polyline",{points:"7.5 19.79 7.5 14.6 3 12",key:"z377f1"}],["polyline",{points:"21 12 16.5 14.6 16.5 19.79",key:"9nrev1"}],["polyline",{points:"3.27 6.96 12 12.01 20.73 6.96",key:"1180pa"}],["line",{x1:"12",x2:"12",y1:"22.08",y2:"12",key:"3z3uq6"}]]);/** * @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 gE=te("Coffee",[["path",{d:"M10 2v2",key:"7u0qdc"}],["path",{d:"M14 2v2",key:"6buw04"}],["path",{d:"M16 8a1 1 0 0 1 1 1v8a4 4 0 0 1-4 4H7a4 4 0 0 1-4-4V9a1 1 0 0 1 1-1h14a4 4 0 1 1 0 8h-1",key:"pwadti"}],["path",{d:"M6 2v2",key:"colzsn"}]]);/** * @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=te("Cog",[["path",{d:"M12 20a8 8 0 1 0 0-16 8 8 0 0 0 0 16Z",key:"sobvz5"}],["path",{d:"M12 14a2 2 0 1 0 0-4 2 2 0 0 0 0 4Z",key:"11i496"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 22v-2",key:"1osdcq"}],["path",{d:"m17 20.66-1-1.73",key:"eq3orb"}],["path",{d:"M11 10.27 7 3.34",key:"16pf9h"}],["path",{d:"m20.66 17-1.73-1",key:"sg0v6f"}],["path",{d:"m3.34 7 1.73 1",key:"1ulond"}],["path",{d:"M14 12h8",key:"4f43i9"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"m20.66 7-1.73 1",key:"1ow05n"}],["path",{d:"m3.34 17 1.73-1",key:"nuk764"}],["path",{d:"m17 3.34-1 1.73",key:"2wel8s"}],["path",{d:"m11 13.73-4 6.93",key:"794ttg"}]]);/** * @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 aF=te("Coins",[["circle",{cx:"8",cy:"8",r:"6",key:"3yglwk"}],["path",{d:"M18.09 10.37A6 6 0 1 1 10.34 18",key:"t5s6rm"}],["path",{d:"M7 6h1v4",key:"1obek4"}],["path",{d:"m16.71 13.88.7.71-2.82 2.82",key:"1rbuyh"}]]);/** * @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 p3=te("Columns2",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M12 3v18",key:"108xh3"}]]);/** * @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 g3=te("Columns3",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["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 xZ=te("Columns4",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M7.5 3v18",key:"w0wo6v"}],["path",{d:"M12 3v18",key:"108xh3"}],["path",{d:"M16.5 3v18",key:"10tjh1"}]]);/** * @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 yZ=te("Combine",[["path",{d:"M10 18H5a3 3 0 0 1-3-3v-1",key:"ru65g8"}],["path",{d:"M14 2a2 2 0 0 1 2 2v4a2 2 0 0 1-2 2",key:"e30een"}],["path",{d:"M20 2a2 2 0 0 1 2 2v4a2 2 0 0 1-2 2",key:"2ahx8o"}],["path",{d:"m7 21 3-3-3-3",key:"127cv2"}],["rect",{x:"14",y:"14",width:"8",height:"8",rx:"2",key:"1b0bso"}],["rect",{x:"2",y:"2",width:"8",height:"8",rx:"2",key:"1x09vl"}]]);/** * @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 vZ=te("Command",[["path",{d:"M15 6v12a3 3 0 1 0 3-3H6a3 3 0 1 0 3 3V6a3 3 0 1 0-3 3h12a3 3 0 1 0-3-3",key:"11bfej"}]]);/** * @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 LI=te("Compass",[["path",{d:"m16.24 7.76-1.804 5.411a2 2 0 0 1-1.265 1.265L7.76 16.24l1.804-5.411a2 2 0 0 1 1.265-1.265z",key:"9ktpf1"}],["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 bZ=te("Component",[["path",{d:"M15.536 11.293a1 1 0 0 0 0 1.414l2.376 2.377a1 1 0 0 0 1.414 0l2.377-2.377a1 1 0 0 0 0-1.414l-2.377-2.377a1 1 0 0 0-1.414 0z",key:"1uwlt4"}],["path",{d:"M2.297 11.293a1 1 0 0 0 0 1.414l2.377 2.377a1 1 0 0 0 1.414 0l2.377-2.377a1 1 0 0 0 0-1.414L6.088 8.916a1 1 0 0 0-1.414 0z",key:"10291m"}],["path",{d:"M8.916 17.912a1 1 0 0 0 0 1.415l2.377 2.376a1 1 0 0 0 1.414 0l2.377-2.376a1 1 0 0 0 0-1.415l-2.377-2.376a1 1 0 0 0-1.414 0z",key:"1tqoq1"}],["path",{d:"M8.916 4.674a1 1 0 0 0 0 1.414l2.377 2.376a1 1 0 0 0 1.414 0l2.377-2.376a1 1 0 0 0 0-1.414l-2.377-2.377a1 1 0 0 0-1.414 0z",key:"1x6lto"}]]);/** * @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 _Z=te("Computer",[["rect",{width:"14",height:"8",x:"5",y:"2",rx:"2",key:"wc9tft"}],["rect",{width:"20",height:"8",x:"2",y:"14",rx:"2",key:"w68u3i"}],["path",{d:"M6 18h2",key:"rwmk9e"}],["path",{d:"M12 18h6",key:"aqd8w3"}]]);/** * @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=te("ConciergeBell",[["path",{d:"M3 20a1 1 0 0 1-1-1v-1a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v1a1 1 0 0 1-1 1Z",key:"1pvr1r"}],["path",{d:"M20 16a8 8 0 1 0-16 0",key:"1pa543"}],["path",{d:"M12 4v4",key:"1bq03y"}],["path",{d:"M10 4h4",key:"1xpv9s"}]]);/** * @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 jZ=te("Cone",[["path",{d:"m20.9 18.55-8-15.98a1 1 0 0 0-1.8 0l-8 15.98",key:"53pte7"}],["ellipse",{cx:"12",cy:"19",rx:"9",ry:"3",key:"1ji25f"}]]);/** * @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 NZ=te("Construction",[["rect",{x:"2",y:"6",width:"20",height:"8",rx:"1",key:"1estib"}],["path",{d:"M17 14v7",key:"7m2elx"}],["path",{d:"M7 14v7",key:"1cm7wv"}],["path",{d:"M17 3v3",key:"1v4jwn"}],["path",{d:"M7 3v3",key:"7o6guu"}],["path",{d:"M10 14 2.3 6.3",key:"1023jk"}],["path",{d:"m14 6 7.7 7.7",key:"1s8pl2"}],["path",{d:"m8 6 8 8",key:"hl96qh"}]]);/** * @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 x3=te("ContactRound",[["path",{d:"M16 2v2",key:"scm5qe"}],["path",{d:"M17.915 22a6 6 0 0 0-12 0",key:"suqz9p"}],["path",{d:"M8 2v2",key:"pbkmx"}],["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["rect",{x:"3",y:"4",width:"18",height:"18",rx:"2",key:"12vinp"}]]);/** * @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 xE=te("Contact",[["path",{d:"M16 2v2",key:"scm5qe"}],["path",{d:"M7 22v-2a2 2 0 0 1 2-2h6a2 2 0 0 1 2 2v2",key:"1waht3"}],["path",{d:"M8 2v2",key:"pbkmx"}],["circle",{cx:"12",cy:"11",r:"3",key:"itu57m"}],["rect",{x:"3",y:"4",width:"18",height:"18",rx:"2",key:"12vinp"}]]);/** * @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=te("Container",[["path",{d:"M22 7.7c0-.6-.4-1.2-.8-1.5l-6.3-3.9a1.72 1.72 0 0 0-1.7 0l-10.3 6c-.5.2-.9.8-.9 1.4v6.6c0 .5.4 1.2.8 1.5l6.3 3.9a1.72 1.72 0 0 0 1.7 0l10.3-6c.5-.3.9-1 .9-1.5Z",key:"1t2lqe"}],["path",{d:"M10 21.9V14L2.1 9.1",key:"o7czzq"}],["path",{d:"m10 14 11.9-6.9",key:"zm5e20"}],["path",{d:"M14 19.8v-8.1",key:"159ecu"}],["path",{d:"M18 17.5V9.4",key:"11uown"}]]);/** * @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 SZ=te("Contrast",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 18a6 6 0 0 0 0-12v12z",key:"j4l70d"}]]);/** * @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 CZ=te("Cookie",[["path",{d:"M12 2a10 10 0 1 0 10 10 4 4 0 0 1-5-5 4 4 0 0 1-5-5",key:"laymnq"}],["path",{d:"M8.5 8.5v.01",key:"ue8clq"}],["path",{d:"M16 15.5v.01",key:"14dtrp"}],["path",{d:"M12 12v.01",key:"u5ubse"}],["path",{d:"M11 17v.01",key:"1hyl5a"}],["path",{d:"M7 14v.01",key:"uct60s"}]]);/** * @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 TZ=te("CookingPot",[["path",{d:"M2 12h20",key:"9i4pu4"}],["path",{d:"M20 12v8a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2v-8",key:"u0tga0"}],["path",{d:"m4 8 16-4",key:"16g0ng"}],["path",{d:"m8.86 6.78-.45-1.81a2 2 0 0 1 1.45-2.43l1.94-.48a2 2 0 0 1 2.43 1.46l.45 1.8",key:"12cejc"}]]);/** * @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 EZ=te("CopyCheck",[["path",{d:"m12 15 2 2 4-4",key:"2c609p"}],["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 AZ=te("CopyMinus",[["line",{x1:"12",x2:"18",y1:"15",y2:"15",key:"1nscbv"}],["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 MZ=te("CopyPlus",[["line",{x1:"15",x2:"15",y1:"12",y2:"18",key:"1p7wdc"}],["line",{x1:"12",x2:"18",y1:"15",y2:"15",key:"1nscbv"}],["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 IZ=te("CopySlash",[["line",{x1:"12",x2:"18",y1:"18",y2:"12",key:"ebkxgr"}],["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 PZ=te("CopyX",[["line",{x1:"12",x2:"18",y1:"12",y2:"18",key:"1rg63v"}],["line",{x1:"12",x2:"18",y1:"18",y2:"12",key:"ebkxgr"}],["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 ui=te("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 LZ=te("Copyleft",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M9.17 14.83a4 4 0 1 0 0-5.66",key:"1sveal"}]]);/** * @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 DZ=te("Copyright",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M14.83 14.83a4 4 0 1 1 0-5.66",key:"1i56pz"}]]);/** * @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 RZ=te("CornerDownLeft",[["polyline",{points:"9 10 4 15 9 20",key:"r3jprv"}],["path",{d:"M20 4v7a4 4 0 0 1-4 4H4",key:"6o5b7l"}]]);/** * @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 OZ=te("CornerDownRight",[["polyline",{points:"15 10 20 15 15 20",key:"1q7qjw"}],["path",{d:"M4 4v7a4 4 0 0 0 4 4h12",key:"z08zvw"}]]);/** * @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 FZ=te("CornerLeftDown",[["polyline",{points:"14 15 9 20 4 15",key:"nkc4i"}],["path",{d:"M20 4h-7a4 4 0 0 0-4 4v12",key:"nbpdq2"}]]);/** * @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 BZ=te("CornerLeftUp",[["polyline",{points:"14 9 9 4 4 9",key:"m9oyvo"}],["path",{d:"M20 20h-7a4 4 0 0 1-4-4V4",key:"1blwi3"}]]);/** * @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 zZ=te("CornerRightDown",[["polyline",{points:"10 15 15 20 20 15",key:"axus6l"}],["path",{d:"M4 4h7a4 4 0 0 1 4 4v12",key:"wcbgct"}]]);/** * @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 $Z=te("CornerRightUp",[["polyline",{points:"10 9 15 4 20 9",key:"1lr6px"}],["path",{d:"M4 20h7a4 4 0 0 0 4-4V4",key:"1plgdj"}]]);/** * @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 UZ=te("CornerUpLeft",[["polyline",{points:"9 14 4 9 9 4",key:"881910"}],["path",{d:"M20 20v-7a4 4 0 0 0-4-4H4",key:"1nkjon"}]]);/** * @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=te("CornerUpRight",[["polyline",{points:"15 14 20 9 15 4",key:"1tbx3s"}],["path",{d:"M4 20v-7a4 4 0 0 1 4-4h12",key:"1lu4f8"}]]);/** * @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 VZ=te("Cpu",[["rect",{width:"16",height:"16",x:"4",y:"4",rx:"2",key:"14l7u7"}],["rect",{width:"6",height:"6",x:"9",y:"9",rx:"1",key:"5aljv4"}],["path",{d:"M15 2v2",key:"13l42r"}],["path",{d:"M15 20v2",key:"15mkzm"}],["path",{d:"M2 15h2",key:"1gxd5l"}],["path",{d:"M2 9h2",key:"1bbxkp"}],["path",{d:"M20 15h2",key:"19e6y8"}],["path",{d:"M20 9h2",key:"19tzq7"}],["path",{d:"M9 2v2",key:"165o2o"}],["path",{d:"M9 20v2",key:"i2bqo8"}]]);/** * @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=te("CreativeCommons",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M10 9.3a2.8 2.8 0 0 0-3.5 1 3.1 3.1 0 0 0 0 3.4 2.7 2.7 0 0 0 3.5 1",key:"1ss3eq"}],["path",{d:"M17 9.3a2.8 2.8 0 0 0-3.5 1 3.1 3.1 0 0 0 0 3.4 2.7 2.7 0 0 0 3.5 1",key:"1od56t"}]]);/** * @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 u0=te("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 GZ=te("Croissant",[["path",{d:"m4.6 13.11 5.79-3.21c1.89-1.05 4.79 1.78 3.71 3.71l-3.22 5.81C8.8 23.16.79 15.23 4.6 13.11Z",key:"1ozxlb"}],["path",{d:"m10.5 9.5-1-2.29C9.2 6.48 8.8 6 8 6H4.5C2.79 6 2 6.5 2 8.5a7.71 7.71 0 0 0 2 4.83",key:"ffuyb5"}],["path",{d:"M8 6c0-1.55.24-4-2-4-2 0-2.5 2.17-2.5 4",key:"osnpzi"}],["path",{d:"m14.5 13.5 2.29 1c.73.3 1.21.7 1.21 1.5v3.5c0 1.71-.5 2.5-2.5 2.5a7.71 7.71 0 0 1-4.83-2",key:"1vubaw"}],["path",{d:"M18 16c1.55 0 4-.24 4 2 0 2-2.17 2.5-4 2.5",key:"wxr772"}]]);/** * @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=te("Crop",[["path",{d:"M6 2v14a2 2 0 0 0 2 2h14",key:"ron5a4"}],["path",{d:"M18 22V8a2 2 0 0 0-2-2H2",key:"7s9ehn"}]]);/** * @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=te("Cross",[["path",{d:"M4 9a2 2 0 0 0-2 2v2a2 2 0 0 0 2 2h4a1 1 0 0 1 1 1v4a2 2 0 0 0 2 2h2a2 2 0 0 0 2-2v-4a1 1 0 0 1 1-1h4a2 2 0 0 0 2-2v-2a2 2 0 0 0-2-2h-4a1 1 0 0 1-1-1V4a2 2 0 0 0-2-2h-2a2 2 0 0 0-2 2v4a1 1 0 0 1-1 1z",key:"1xbrqy"}]]);/** * @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 YZ=te("Crosshair",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"22",x2:"18",y1:"12",y2:"12",key:"l9bcsi"}],["line",{x1:"6",x2:"2",y1:"12",y2:"12",key:"13hhkx"}],["line",{x1:"12",x2:"12",y1:"6",y2:"2",key:"10w3f3"}],["line",{x1:"12",x2:"12",y1:"22",y2:"18",key:"15g9kq"}]]);/** * @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 zf=te("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 ZZ=te("Cuboid",[["path",{d:"m21.12 6.4-6.05-4.06a2 2 0 0 0-2.17-.05L2.95 8.41a2 2 0 0 0-.95 1.7v5.82a2 2 0 0 0 .88 1.66l6.05 4.07a2 2 0 0 0 2.17.05l9.95-6.12a2 2 0 0 0 .95-1.7V8.06a2 2 0 0 0-.88-1.66Z",key:"1u2ovd"}],["path",{d:"M10 22v-8L2.25 9.15",key:"11pn4q"}],["path",{d:"m10 14 11.77-6.87",key:"1kt1wh"}]]);/** * @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 XZ=te("CupSoda",[["path",{d:"m6 8 1.75 12.28a2 2 0 0 0 2 1.72h4.54a2 2 0 0 0 2-1.72L18 8",key:"8166m8"}],["path",{d:"M5 8h14",key:"pcz4l3"}],["path",{d:"M7 15a6.47 6.47 0 0 1 5 0 6.47 6.47 0 0 0 5 0",key:"yjz344"}],["path",{d:"m12 8 1-6h2",key:"3ybfa4"}]]);/** * @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=te("Currency",[["circle",{cx:"12",cy:"12",r:"8",key:"46899m"}],["line",{x1:"3",x2:"6",y1:"3",y2:"6",key:"1jkytn"}],["line",{x1:"21",x2:"18",y1:"3",y2:"6",key:"14zfjt"}],["line",{x1:"3",x2:"6",y1:"21",y2:"18",key:"iusuec"}],["line",{x1:"21",x2:"18",y1:"21",y2:"18",key:"yj2dd7"}]]);/** * @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 JZ=te("Cylinder",[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5v14a9 3 0 0 0 18 0V5",key:"aqi0yr"}]]);/** * @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 eX=te("Dam",[["path",{d:"M11 11.31c1.17.56 1.54 1.69 3.5 1.69 2.5 0 2.5-2 5-2 1.3 0 1.9.5 2.5 1",key:"157kva"}],["path",{d:"M11.75 18c.35.5 1.45 1 2.75 1 2.5 0 2.5-2 5-2 1.3 0 1.9.5 2.5 1",key:"d7q6m6"}],["path",{d:"M2 10h4",key:"l0bgd4"}],["path",{d:"M2 14h4",key:"1gsvsf"}],["path",{d:"M2 18h4",key:"1bu2t1"}],["path",{d:"M2 6h4",key:"aawbzj"}],["path",{d:"M7 3a1 1 0 0 0-1 1v16a1 1 0 0 0 1 1h4a1 1 0 0 0 1-1L10 4a1 1 0 0 0-1-1z",key:"pr6s65"}]]);/** * @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 tX=te("DatabaseBackup",[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 12a9 3 0 0 0 5 2.69",key:"1ui2ym"}],["path",{d:"M21 9.3V5",key:"6k6cib"}],["path",{d:"M3 5v14a9 3 0 0 0 6.47 2.88",key:"i62tjy"}],["path",{d:"M12 12v4h4",key:"1bxaet"}],["path",{d:"M13 20a5 5 0 0 0 9-3 4.5 4.5 0 0 0-4.5-4.5c-1.33 0-2.54.54-3.41 1.41L12 16",key:"1f4ei9"}]]);/** * @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=te("DatabaseZap",[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 15 21.84",key:"14ibmq"}],["path",{d:"M21 5V8",key:"1marbg"}],["path",{d:"M21 12L18 17H22L19 22",key:"zafso"}],["path",{d:"M3 12A9 3 0 0 0 14.59 14.87",key:"1y4wr8"}]]);/** * @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 iF=te("Database",[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 21 19V5",key:"1wlel7"}],["path",{d:"M3 12A9 3 0 0 0 21 12",key:"mv7ke4"}]]);/** * @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 rX=te("Delete",[["path",{d:"M10 5a2 2 0 0 0-1.344.519l-6.328 5.74a1 1 0 0 0 0 1.481l6.328 5.741A2 2 0 0 0 10 19h10a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2z",key:"1yo7s0"}],["path",{d:"m12 9 6 6",key:"anjzzh"}],["path",{d:"m18 9-6 6",key:"1fp51s"}]]);/** * @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 nX=te("Dessert",[["circle",{cx:"12",cy:"4",r:"2",key:"muu5ef"}],["path",{d:"M10.2 3.2C5.5 4 2 8.1 2 13a2 2 0 0 0 4 0v-1a2 2 0 0 1 4 0v4a2 2 0 0 0 4 0v-4a2 2 0 0 1 4 0v1a2 2 0 0 0 4 0c0-4.9-3.5-9-8.2-9.8",key:"lfo06j"}],["path",{d:"M3.2 14.8a9 9 0 0 0 17.6 0",key:"12xarc"}]]);/** * @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 aX=te("Diameter",[["circle",{cx:"19",cy:"19",r:"2",key:"17f5cg"}],["circle",{cx:"5",cy:"5",r:"2",key:"1gwv83"}],["path",{d:"M6.48 3.66a10 10 0 0 1 13.86 13.86",key:"xr8kdq"}],["path",{d:"m6.41 6.41 11.18 11.18",key:"uhpjw7"}],["path",{d:"M3.66 6.48a10 10 0 0 0 13.86 13.86",key:"cldpwv"}]]);/** * @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=te("DiamondMinus",[["path",{d:"M2.7 10.3a2.41 2.41 0 0 0 0 3.41l7.59 7.59a2.41 2.41 0 0 0 3.41 0l7.59-7.59a2.41 2.41 0 0 0 0-3.41L13.7 2.71a2.41 2.41 0 0 0-3.41 0z",key:"1ey20j"}],["path",{d:"M8 12h8",key:"1wcyev"}]]);/** * @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 y3=te("DiamondPercent",[["path",{d:"M2.7 10.3a2.41 2.41 0 0 0 0 3.41l7.59 7.59a2.41 2.41 0 0 0 3.41 0l7.59-7.59a2.41 2.41 0 0 0 0-3.41L13.7 2.71a2.41 2.41 0 0 0-3.41 0Z",key:"1tpxz2"}],["path",{d:"M9.2 9.2h.01",key:"1b7bvt"}],["path",{d:"m14.5 9.5-5 5",key:"17q4r4"}],["path",{d:"M14.7 14.8h.01",key:"17nsh4"}]]);/** * @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 oX=te("DiamondPlus",[["path",{d:"M12 8v8",key:"napkw2"}],["path",{d:"M2.7 10.3a2.41 2.41 0 0 0 0 3.41l7.59 7.59a2.41 2.41 0 0 0 3.41 0l7.59-7.59a2.41 2.41 0 0 0 0-3.41L13.7 2.71a2.41 2.41 0 0 0-3.41 0z",key:"1ey20j"}],["path",{d:"M8 12h8",key:"1wcyev"}]]);/** * @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 lX=te("Diamond",[["path",{d:"M2.7 10.3a2.41 2.41 0 0 0 0 3.41l7.59 7.59a2.41 2.41 0 0 0 3.41 0l7.59-7.59a2.41 2.41 0 0 0 0-3.41l-7.59-7.59a2.41 2.41 0 0 0-3.41 0Z",key:"1f1r0c"}]]);/** * @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 cX=te("Dice1",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["path",{d:"M12 12h.01",key:"1mp3jc"}]]);/** * @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 dX=te("Dice2",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["path",{d:"M15 9h.01",key:"x1ddxp"}],["path",{d:"M9 15h.01",key:"fzyn71"}]]);/** * @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 uX=te("Dice3",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["path",{d:"M16 8h.01",key:"cr5u4v"}],["path",{d:"M12 12h.01",key:"1mp3jc"}],["path",{d:"M8 16h.01",key:"18s6g9"}]]);/** * @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 hX=te("Dice4",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["path",{d:"M16 8h.01",key:"cr5u4v"}],["path",{d:"M8 8h.01",key:"1e4136"}],["path",{d:"M8 16h.01",key:"18s6g9"}],["path",{d:"M16 16h.01",key:"1f9h7w"}]]);/** * @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 mX=te("Dice5",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["path",{d:"M16 8h.01",key:"cr5u4v"}],["path",{d:"M8 8h.01",key:"1e4136"}],["path",{d:"M8 16h.01",key:"18s6g9"}],["path",{d:"M16 16h.01",key:"1f9h7w"}],["path",{d:"M12 12h.01",key:"1mp3jc"}]]);/** * @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 fX=te("Dice6",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["path",{d:"M16 8h.01",key:"cr5u4v"}],["path",{d:"M16 12h.01",key:"1l6xoz"}],["path",{d:"M16 16h.01",key:"1f9h7w"}],["path",{d:"M8 8h.01",key:"1e4136"}],["path",{d:"M8 12h.01",key:"czm47f"}],["path",{d:"M8 16h.01",key:"18s6g9"}]]);/** * @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 pX=te("Dices",[["rect",{width:"12",height:"12",x:"2",y:"10",rx:"2",ry:"2",key:"6agr2n"}],["path",{d:"m17.92 14 3.5-3.5a2.24 2.24 0 0 0 0-3l-5-4.92a2.24 2.24 0 0 0-3 0L10 6",key:"1o487t"}],["path",{d:"M6 18h.01",key:"uhywen"}],["path",{d:"M10 14h.01",key:"ssrbsk"}],["path",{d:"M15 6h.01",key:"cblpky"}],["path",{d:"M18 9h.01",key:"2061c0"}]]);/** * @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 gX=te("Diff",[["path",{d:"M12 3v14",key:"7cf3v8"}],["path",{d:"M5 10h14",key:"elsbfy"}],["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 xX=te("Disc2",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M12 12h.01",key:"1mp3jc"}]]);/** * @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 yX=te("Disc3",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M6 12c0-1.7.7-3.2 1.8-4.2",key:"oqkarx"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}],["path",{d:"M18 12c0 1.7-.7 3.2-1.8 4.2",key:"1eah9h"}]]);/** * @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 vX=te("DiscAlbum",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["circle",{cx:"12",cy:"12",r:"5",key:"nd82uf"}],["path",{d:"M12 12h.01",key:"1mp3jc"}]]);/** * @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 bX=te("Disc",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["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 _X=te("Divide",[["circle",{cx:"12",cy:"6",r:"1",key:"1bh7o1"}],["line",{x1:"5",x2:"19",y1:"12",y2:"12",key:"13b5wn"}],["circle",{cx:"12",cy:"18",r:"1",key:"lqb9t5"}]]);/** * @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 wX=te("DnaOff",[["path",{d:"M15 2c-1.35 1.5-2.092 3-2.5 4.5L14 8",key:"1bivrr"}],["path",{d:"m17 6-2.891-2.891",key:"xu6p2f"}],["path",{d:"M2 15c3.333-3 6.667-3 10-3",key:"nxix30"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"m20 9 .891.891",key:"3xwk7g"}],["path",{d:"M22 9c-1.5 1.35-3 2.092-4.5 2.5l-1-1",key:"18cutr"}],["path",{d:"M3.109 14.109 4 15",key:"q76aoh"}],["path",{d:"m6.5 12.5 1 1",key:"cs35ky"}],["path",{d:"m7 18 2.891 2.891",key:"1sisit"}],["path",{d:"M9 22c1.35-1.5 2.092-3 2.5-4.5L10 16",key:"rlvei3"}]]);/** * @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 jX=te("Dna",[["path",{d:"m10 16 1.5 1.5",key:"11lckj"}],["path",{d:"m14 8-1.5-1.5",key:"1ohn8i"}],["path",{d:"M15 2c-1.798 1.998-2.518 3.995-2.807 5.993",key:"80uv8i"}],["path",{d:"m16.5 10.5 1 1",key:"696xn5"}],["path",{d:"m17 6-2.891-2.891",key:"xu6p2f"}],["path",{d:"M2 15c6.667-6 13.333 0 20-6",key:"1pyr53"}],["path",{d:"m20 9 .891.891",key:"3xwk7g"}],["path",{d:"M3.109 14.109 4 15",key:"q76aoh"}],["path",{d:"m6.5 12.5 1 1",key:"cs35ky"}],["path",{d:"m7 18 2.891 2.891",key:"1sisit"}],["path",{d:"M9 22c1.798-1.998 2.518-3.995 2.807-5.993",key:"q3hbxp"}]]);/** * @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 NX=te("Dock",[["path",{d:"M2 8h20",key:"d11cs7"}],["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}],["path",{d:"M6 16h12",key:"u522kt"}]]);/** * @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 kX=te("Dog",[["path",{d:"M11.25 16.25h1.5L12 17z",key:"w7jh35"}],["path",{d:"M16 14v.5",key:"1lajdz"}],["path",{d:"M4.42 11.247A13.152 13.152 0 0 0 4 14.556C4 18.728 7.582 21 12 21s8-2.272 8-6.444a11.702 11.702 0 0 0-.493-3.309",key:"u7s9ue"}],["path",{d:"M8 14v.5",key:"1nzgdb"}],["path",{d:"M8.5 8.5c-.384 1.05-1.083 2.028-2.344 2.5-1.931.722-3.576-.297-3.656-1-.113-.994 1.177-6.53 4-7 1.923-.321 3.651.845 3.651 2.235A7.497 7.497 0 0 1 14 5.277c0-1.39 1.844-2.598 3.767-2.277 2.823.47 4.113 6.006 4 7-.08.703-1.725 1.722-3.656 1-1.261-.472-1.855-1.45-2.239-2.5",key:"v8hric"}]]);/** * @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 oc=te("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 SX=te("Donut",[["path",{d:"M20.5 10a2.5 2.5 0 0 1-2.4-3H18a2.95 2.95 0 0 1-2.6-4.4 10 10 0 1 0 6.3 7.1c-.3.2-.8.3-1.2.3",key:"19sr3x"}],["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 CX=te("DoorClosed",[["path",{d:"M18 20V6a2 2 0 0 0-2-2H8a2 2 0 0 0-2 2v14",key:"36qu9e"}],["path",{d:"M2 20h20",key:"owomy5"}],["path",{d:"M14 12v.01",key:"xfcn54"}]]);/** * @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 m_=te("DoorOpen",[["path",{d:"M13 4h3a2 2 0 0 1 2 2v14",key:"hrm0s9"}],["path",{d:"M2 20h3",key:"1gaodv"}],["path",{d:"M13 20h9",key:"s90cdi"}],["path",{d:"M10 12v.01",key:"vx6srw"}],["path",{d:"M13 4.562v16.157a1 1 0 0 1-1.242.97L5 20V5.562a2 2 0 0 1 1.515-1.94l4-1A2 2 0 0 1 13 4.561Z",key:"199qr4"}]]);/** * @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 TX=te("Dot",[["circle",{cx:"12.1",cy:"12.1",r:"1",key:"18d7e5"}]]);/** * @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 hi=te("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 EX=te("DraftingCompass",[["path",{d:"m12.99 6.74 1.93 3.44",key:"iwagvd"}],["path",{d:"M19.136 12a10 10 0 0 1-14.271 0",key:"ppmlo4"}],["path",{d:"m21 21-2.16-3.84",key:"vylbct"}],["path",{d:"m3 21 8.02-14.26",key:"1ssaw4"}],["circle",{cx:"12",cy:"5",r:"2",key:"f1ur92"}]]);/** * @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 AX=te("Drama",[["path",{d:"M10 11h.01",key:"d2at3l"}],["path",{d:"M14 6h.01",key:"k028ub"}],["path",{d:"M18 6h.01",key:"1v4wsw"}],["path",{d:"M6.5 13.1h.01",key:"1748ia"}],["path",{d:"M22 5c0 9-4 12-6 12s-6-3-6-12c0-2 2-3 6-3s6 1 6 3",key:"172yzv"}],["path",{d:"M17.4 9.9c-.8.8-2 .8-2.8 0",key:"1obv0w"}],["path",{d:"M10.1 7.1C9 7.2 7.7 7.7 6 8.6c-3.5 2-4.7 3.9-3.7 5.6 4.5 7.8 9.5 8.4 11.2 7.4.9-.5 1.9-2.1 1.9-4.7",key:"rqjl8i"}],["path",{d:"M9.1 16.5c.3-1.1 1.4-1.7 2.4-1.4",key:"1mr6wy"}]]);/** * @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 MX=te("Dribbble",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M19.13 5.09C15.22 9.14 10 10.44 2.25 10.94",key:"hpej1"}],["path",{d:"M21.75 12.84c-6.62-1.41-12.14 1-16.38 6.32",key:"1tr44o"}],["path",{d:"M8.56 2.75c4.37 6 6 9.42 8 17.72",key:"kbh691"}]]);/** * @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=te("Drill",[["path",{d:"M10 18a1 1 0 0 1 1 1v2a1 1 0 0 1-1 1H5a3 3 0 0 1-3-3 1 1 0 0 1 1-1z",key:"ioqxb1"}],["path",{d:"M13 10H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a1 1 0 0 1 1 1v6a1 1 0 0 1-1 1l-.81 3.242a1 1 0 0 1-.97.758H8",key:"1rs59n"}],["path",{d:"M14 4h3a1 1 0 0 1 1 1v2a1 1 0 0 1-1 1h-3",key:"105ega"}],["path",{d:"M18 6h4",key:"66u95g"}],["path",{d:"m5 10-2 8",key:"xt2lic"}],["path",{d:"m7 18 2-8",key:"1bzku2"}]]);/** * @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 PX=te("Droplet",[["path",{d:"M12 22a7 7 0 0 0 7-7c0-2-1-3.9-3-5.5s-3.5-4-4-6.5c-.5 2.5-2 4.9-4 6.5C6 11.1 5 13 5 15a7 7 0 0 0 7 7z",key:"c7niix"}]]);/** * @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 y1=te("Droplets",[["path",{d:"M7 16.3c2.2 0 4-1.83 4-4.05 0-1.16-.57-2.26-1.71-3.19S7.29 6.75 7 5.3c-.29 1.45-1.14 2.84-2.29 3.76S3 11.1 3 12.25c0 2.22 1.8 4.05 4 4.05z",key:"1ptgy4"}],["path",{d:"M12.56 6.6A10.97 10.97 0 0 0 14 3.02c.5 2.5 2 4.9 4 6.5s3 3.5 3 5.5a6.98 6.98 0 0 1-11.91 4.97",key:"1sl1rz"}]]);/** * @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 LX=te("Drum",[["path",{d:"m2 2 8 8",key:"1v6059"}],["path",{d:"m22 2-8 8",key:"173r8a"}],["ellipse",{cx:"12",cy:"9",rx:"10",ry:"5",key:"liohsx"}],["path",{d:"M7 13.4v7.9",key:"1yi6u9"}],["path",{d:"M12 14v8",key:"1tn2tj"}],["path",{d:"M17 13.4v7.9",key:"eqz2v3"}],["path",{d:"M2 9v8a10 5 0 0 0 20 0V9",key:"1750ul"}]]);/** * @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 DX=te("Drumstick",[["path",{d:"M15.4 15.63a7.875 6 135 1 1 6.23-6.23 4.5 3.43 135 0 0-6.23 6.23",key:"1dtqwm"}],["path",{d:"m8.29 12.71-2.6 2.6a2.5 2.5 0 1 0-1.65 4.65A2.5 2.5 0 1 0 8.7 18.3l2.59-2.59",key:"1oq1fw"}]]);/** * @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 RX=te("Dumbbell",[["path",{d:"M14.4 14.4 9.6 9.6",key:"ic80wn"}],["path",{d:"M18.657 21.485a2 2 0 1 1-2.829-2.828l-1.767 1.768a2 2 0 1 1-2.829-2.829l6.364-6.364a2 2 0 1 1 2.829 2.829l-1.768 1.767a2 2 0 1 1 2.828 2.829z",key:"nnl7wr"}],["path",{d:"m21.5 21.5-1.4-1.4",key:"1f1ice"}],["path",{d:"M3.9 3.9 2.5 2.5",key:"1evmna"}],["path",{d:"M6.404 12.768a2 2 0 1 1-2.829-2.829l1.768-1.767a2 2 0 1 1-2.828-2.829l2.828-2.828a2 2 0 1 1 2.829 2.828l1.767-1.768a2 2 0 1 1 2.829 2.829z",key:"yhosts"}]]);/** * @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 OX=te("EarOff",[["path",{d:"M6 18.5a3.5 3.5 0 1 0 7 0c0-1.57.92-2.52 2.04-3.46",key:"1qngmn"}],["path",{d:"M6 8.5c0-.75.13-1.47.36-2.14",key:"b06bma"}],["path",{d:"M8.8 3.15A6.5 6.5 0 0 1 19 8.5c0 1.63-.44 2.81-1.09 3.76",key:"g10hsz"}],["path",{d:"M12.5 6A2.5 2.5 0 0 1 15 8.5M10 13a2 2 0 0 0 1.82-1.18",key:"ygzou7"}],["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}]]);/** * @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 FX=te("Ear",[["path",{d:"M6 8.5a6.5 6.5 0 1 1 13 0c0 6-6 6-6 10a3.5 3.5 0 1 1-7 0",key:"1dfaln"}],["path",{d:"M15 8.5a2.5 2.5 0 0 0-5 0v1a2 2 0 1 1 0 4",key:"1qnva7"}]]);/** * @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 BX=te("EarthLock",[["path",{d:"M7 3.34V5a3 3 0 0 0 3 3",key:"w732o8"}],["path",{d:"M11 21.95V18a2 2 0 0 0-2-2 2 2 0 0 1-2-2v-1a2 2 0 0 0-2-2H2.05",key:"f02343"}],["path",{d:"M21.54 15H17a2 2 0 0 0-2 2v4.54",key:"1djwo0"}],["path",{d:"M12 2a10 10 0 1 0 9.54 13",key:"zjsr6q"}],["path",{d:"M20 6V4a2 2 0 1 0-4 0v2",key:"1of5e8"}],["rect",{width:"8",height:"5",x:"14",y:"6",rx:"1",key:"1fmf51"}]]);/** * @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 v3=te("Earth",[["path",{d:"M21.54 15H17a2 2 0 0 0-2 2v4.54",key:"1djwo0"}],["path",{d:"M7 3.34V5a3 3 0 0 0 3 3a2 2 0 0 1 2 2c0 1.1.9 2 2 2a2 2 0 0 0 2-2c0-1.1.9-2 2-2h3.17",key:"1tzkfa"}],["path",{d:"M11 21.95V18a2 2 0 0 0-2-2a2 2 0 0 1-2-2v-1a2 2 0 0 0-2-2H2.05",key:"14pb5j"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]]);/** * @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 zX=te("Eclipse",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 2a7 7 0 1 0 10 10",key:"1yuj32"}]]);/** * @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 $X=te("EggFried",[["circle",{cx:"11.5",cy:"12.5",r:"3.5",key:"1cl1mi"}],["path",{d:"M3 8c0-3.5 2.5-6 6.5-6 5 0 4.83 3 7.5 5s5 2 5 6c0 4.5-2.5 6.5-7 6.5-2.5 0-2.5 2.5-6 2.5s-7-2-7-5.5c0-3 1.5-3 1.5-5C3.5 10 3 9 3 8Z",key:"165ef9"}]]);/** * @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 UX=te("EggOff",[["path",{d:"M6.399 6.399C5.362 8.157 4.65 10.189 4.5 12c-.37 4.43 1.27 9.95 7.5 10 3.256-.026 5.259-1.547 6.375-3.625",key:"6et380"}],["path",{d:"M19.532 13.875A14.07 14.07 0 0 0 19.5 12c-.36-4.34-3.95-9.96-7.5-10-1.04.012-2.082.502-3.046 1.297",key:"gcdc3f"}],["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}]]);/** * @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 DI=te("Egg",[["path",{d:"M12 22c6.23-.05 7.87-5.57 7.5-10-.36-4.34-3.95-9.96-7.5-10-3.55.04-7.14 5.66-7.5 10-.37 4.43 1.27 9.95 7.5 10z",key:"1c39pg"}]]);/** * @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 Ay=te("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 Jx=te("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 qX=te("EqualApproximately",[["path",{d:"M5 15a6.5 6.5 0 0 1 7 0 6.5 6.5 0 0 0 7 0",key:"yrdkhy"}],["path",{d:"M5 9a6.5 6.5 0 0 1 7 0 6.5 6.5 0 0 0 7 0",key:"gzkvyz"}]]);/** * @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 VX=te("EqualNot",[["line",{x1:"5",x2:"19",y1:"9",y2:"9",key:"1nwqeh"}],["line",{x1:"5",x2:"19",y1:"15",y2:"15",key:"g8yjpy"}],["line",{x1:"19",x2:"5",y1:"5",y2:"19",key:"1x9vlm"}]]);/** * @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 HX=te("Equal",[["line",{x1:"5",x2:"19",y1:"9",y2:"9",key:"1nwqeh"}],["line",{x1:"5",x2:"19",y1:"15",y2:"15",key:"g8yjpy"}]]);/** * @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 GX=te("Eraser",[["path",{d:"m7 21-4.3-4.3c-1-1-1-2.5 0-3.4l9.6-9.6c1-1 2.5-1 3.4 0l5.6 5.6c1 1 1 2.5 0 3.4L13 21",key:"182aya"}],["path",{d:"M22 21H7",key:"t4ddhn"}],["path",{d:"m5 11 9 9",key:"1mo9qw"}]]);/** * @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 WX=te("EthernetPort",[["path",{d:"m15 20 3-3h2a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h2l3 3z",key:"rbahqx"}],["path",{d:"M6 8v1",key:"1636ez"}],["path",{d:"M10 8v1",key:"1talb4"}],["path",{d:"M14 8v1",key:"1rsfgr"}],["path",{d:"M18 8v1",key:"gnkwox"}]]);/** * @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 KX=te("Euro",[["path",{d:"M4 10h12",key:"1y6xl8"}],["path",{d:"M4 14h9",key:"1loblj"}],["path",{d:"M19 6a7.7 7.7 0 0 0-5.2-2A7.9 7.9 0 0 0 6 12c0 4.4 3.5 8 7.8 8 2 0 3.8-.8 5.2-2",key:"1j6lzo"}]]);/** * @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 YX=te("Expand",[["path",{d:"m21 21-6-6m6 6v-4.8m0 4.8h-4.8",key:"1c15vz"}],["path",{d:"M3 16.2V21m0 0h4.8M3 21l6-6",key:"1fsnz2"}],["path",{d:"M21 7.8V3m0 0h-4.8M21 3l-6 6",key:"hawz9i"}],["path",{d:"M3 7.8V3m0 0h4.8M3 3l6 6",key:"u9ee12"}]]);/** * @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 gn=te("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 ZX=te("EyeClosed",[["path",{d:"m15 18-.722-3.25",key:"1j64jw"}],["path",{d:"M2 8a10.645 10.645 0 0 0 20 0",key:"1e7gxb"}],["path",{d:"m20 15-1.726-2.05",key:"1cnuld"}],["path",{d:"m4 15 1.726-2.05",key:"1dsqqd"}],["path",{d:"m9 18 .722-3.25",key:"ypw2yx"}]]);/** * @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 $f=te("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 Bn=te("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 fh=te("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 XX=te("Factory",[["path",{d:"M2 20a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V8l-7 5V8l-7 5V4a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2Z",key:"159hny"}],["path",{d:"M17 18h1",key:"uldtlt"}],["path",{d:"M12 18h1",key:"s9uhes"}],["path",{d:"M7 18h1",key:"1neino"}]]);/** * @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 QX=te("Fan",[["path",{d:"M10.827 16.379a6.082 6.082 0 0 1-8.618-7.002l5.412 1.45a6.082 6.082 0 0 1 7.002-8.618l-1.45 5.412a6.082 6.082 0 0 1 8.618 7.002l-5.412-1.45a6.082 6.082 0 0 1-7.002 8.618l1.45-5.412Z",key:"484a7f"}],["path",{d:"M12 12v.01",key:"u5ubse"}]]);/** * @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 JX=te("FastForward",[["polygon",{points:"13 19 22 12 13 5 13 19",key:"587y9g"}],["polygon",{points:"2 19 11 12 2 5 2 19",key:"3pweh0"}]]);/** * @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 eQ=te("Feather",[["path",{d:"M12.67 19a2 2 0 0 0 1.416-.588l6.154-6.172a6 6 0 0 0-8.49-8.49L5.586 9.914A2 2 0 0 0 5 11.328V18a1 1 0 0 0 1 1z",key:"18jl4k"}],["path",{d:"M16 8 2 22",key:"vp34q"}],["path",{d:"M17.5 15H9",key:"1oz8nu"}]]);/** * @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 tQ=te("Fence",[["path",{d:"M4 3 2 5v15c0 .6.4 1 1 1h2c.6 0 1-.4 1-1V5Z",key:"1n2rgs"}],["path",{d:"M6 8h4",key:"utf9t1"}],["path",{d:"M6 18h4",key:"12yh4b"}],["path",{d:"m12 3-2 2v15c0 .6.4 1 1 1h2c.6 0 1-.4 1-1V5Z",key:"3ha7mj"}],["path",{d:"M14 8h4",key:"1r8wg2"}],["path",{d:"M14 18h4",key:"1t3kbu"}],["path",{d:"m20 3-2 2v15c0 .6.4 1 1 1h2c.6 0 1-.4 1-1V5Z",key:"dfd4e2"}]]);/** * @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 sQ=te("FerrisWheel",[["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}],["path",{d:"M12 2v4",key:"3427ic"}],["path",{d:"m6.8 15-3.5 2",key:"hjy98k"}],["path",{d:"m20.7 7-3.5 2",key:"f08gto"}],["path",{d:"M6.8 9 3.3 7",key:"1aevh4"}],["path",{d:"m20.7 17-3.5-2",key:"1liqo3"}],["path",{d:"m9 22 3-8 3 8",key:"wees03"}],["path",{d:"M8 22h8",key:"rmew8v"}],["path",{d:"M18 18.7a9 9 0 1 0-12 0",key:"dhzg4g"}]]);/** * @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 rQ=te("Figma",[["path",{d:"M5 5.5A3.5 3.5 0 0 1 8.5 2H12v7H8.5A3.5 3.5 0 0 1 5 5.5z",key:"1340ok"}],["path",{d:"M12 2h3.5a3.5 3.5 0 1 1 0 7H12V2z",key:"1hz3m3"}],["path",{d:"M12 12.5a3.5 3.5 0 1 1 7 0 3.5 3.5 0 1 1-7 0z",key:"1oz8n2"}],["path",{d:"M5 19.5A3.5 3.5 0 0 1 8.5 16H12v3.5a3.5 3.5 0 1 1-7 0z",key:"1ff65i"}],["path",{d:"M5 12.5A3.5 3.5 0 0 1 8.5 9H12v7H8.5A3.5 3.5 0 0 1 5 12.5z",key:"pdip6e"}]]);/** * @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 nQ=te("FileArchive",[["path",{d:"M10 12v-1",key:"v7bkov"}],["path",{d:"M10 18v-2",key:"1cjy8d"}],["path",{d:"M10 7V6",key:"dljcrl"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M15.5 22H18a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v16a2 2 0 0 0 .274 1.01",key:"gkbcor"}],["circle",{cx:"10",cy:"20",r:"2",key:"1xzdoj"}]]);/** * @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 aQ=te("FileAudio2",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v2",key:"17k7jt"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["circle",{cx:"3",cy:"17",r:"1",key:"vo6nti"}],["path",{d:"M2 17v-3a4 4 0 0 1 8 0v3",key:"1ggdre"}],["circle",{cx:"9",cy:"17",r:"1",key:"bc1fq4"}]]);/** * @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 iQ=te("FileAudio",[["path",{d:"M17.5 22h.5a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v3",key:"rslqgf"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M2 19a2 2 0 1 1 4 0v1a2 2 0 1 1-4 0v-4a6 6 0 0 1 12 0v4a2 2 0 1 1-4 0v-1a2 2 0 1 1 4 0",key:"9f7x3i"}]]);/** * @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 b3=te("FileAxis3d",[["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 18 4-4",key:"12zab0"}],["path",{d:"M8 10v8h8",key:"tlaukw"}]]);/** * @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 oQ=te("FileBadge2",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["circle",{cx:"12",cy:"10",r:"3",key:"ilqhr7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"m14 12.5 1 5.5-3-1-3 1 1-5.5",key:"14xlky"}]]);/** * @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 lQ=te("FileBadge",[["path",{d:"M12 22h6a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v3",key:"12ixgl"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M5 17a3 3 0 1 0 0-6 3 3 0 0 0 0 6Z",key:"u0c8gj"}],["path",{d:"M7 16.5 8 22l-3-1-3 1 1-5.5",key:"5gm2nr"}]]);/** * @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 cQ=te("FileBox",[["path",{d:"M14.5 22H18a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4",key:"16lz6z"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M3 13.1a2 2 0 0 0-1 1.76v3.24a2 2 0 0 0 .97 1.78L6 21.7a2 2 0 0 0 2.03.01L11 19.9a2 2 0 0 0 1-1.76V14.9a2 2 0 0 0-.97-1.78L8 11.3a2 2 0 0 0-2.03-.01Z",key:"99pj1s"}],["path",{d:"M7 17v5",key:"1yj1jh"}],["path",{d:"M11.7 14.2 7 17l-4.7-2.8",key:"1yk8tc"}]]);/** * @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 _3=te("FileChartColumnIncreasing",[["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 18v-2",key:"qcmpov"}],["path",{d:"M12 18v-4",key:"q1q25u"}],["path",{d:"M16 18v-6",key:"15y0np"}]]);/** * @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 w3=te("FileChartColumn",[["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 18v-1",key:"zg0ygc"}],["path",{d:"M12 18v-6",key:"17g6i2"}],["path",{d:"M16 18v-3",key:"j5jt4h"}]]);/** * @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 j3=te("FileChartLine",[["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:"m16 13-3.5 3.5-2-2L8 17",key:"zz7yod"}]]);/** * @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 N3=te("FileChartPie",[["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M16 22h2a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v3.5",key:"13ddob"}],["path",{d:"M4.017 11.512a6 6 0 1 0 8.466 8.475",key:"s6vs5t"}],["path",{d:"M9 16a1 1 0 0 1-1-1v-4c0-.552.45-1.008.995-.917a6 6 0 0 1 4.922 4.922c.091.544-.365.995-.917.995z",key:"1dl6s6"}]]);/** * @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 dQ=te("FileCheck2",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4",key:"1pf5j1"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"m3 15 2 2 4-4",key:"1lhrkk"}]]);/** * @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=te("FileCheck",[["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:"m9 15 2 2 4-4",key:"1grp1n"}]]);/** * @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 uQ=te("FileClock",[["path",{d:"M16 22h2a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v3",key:"37hlfg"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["circle",{cx:"8",cy:"16",r:"6",key:"10v15b"}],["path",{d:"M9.5 17.5 8 16.25V14",key:"1o80t2"}]]);/** * @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 hQ=te("FileCode2",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4",key:"1pf5j1"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"m5 12-3 3 3 3",key:"oke12k"}],["path",{d:"m9 18 3-3-3-3",key:"112psh"}]]);/** * @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 mQ=te("FileCode",[["path",{d:"M10 12.5 8 15l2 2.5",key:"1tg20x"}],["path",{d:"m14 12.5 2 2.5-2 2.5",key:"yinavb"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7z",key:"1mlx9k"}]]);/** * @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 k3=te("FileCog",[["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"m3.2 12.9-.9-.4",key:"1i3dj5"}],["path",{d:"m3.2 15.1-.9.4",key:"1fvgj0"}],["path",{d:"M4.677 21.5a2 2 0 0 0 1.313.5H18a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v2.5",key:"1yo3oz"}],["path",{d:"m4.9 11.2-.4-.9",key:"otmhb9"}],["path",{d:"m4.9 16.8-.4.9",key:"1b8z07"}],["path",{d:"m7.5 10.3-.4.9",key:"11k65u"}],["path",{d:"m7.5 17.7-.4-.9",key:"431x55"}],["path",{d:"m9.7 12.5-.9.4",key:"87sjan"}],["path",{d:"m9.7 15.5-.9-.4",key:"khqm91"}],["circle",{cx:"6",cy:"14",r:"3",key:"a1xfv6"}]]);/** * @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 fQ=te("FileDiff",[["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:"M9 10h6",key:"9gxzsh"}],["path",{d:"M12 13V7",key:"h0r20n"}],["path",{d:"M9 17h6",key:"r8uit2"}]]);/** * @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 pQ=te("FileDigit",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4",key:"1pf5j1"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["rect",{width:"4",height:"6",x:"2",y:"12",rx:"2",key:"jm304g"}],["path",{d:"M10 12h2v6",key:"12zw74"}],["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 yE=te("FileDown",[["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:"M12 18v-6",key:"17g6i2"}],["path",{d:"m9 15 3 3 3-3",key:"1npd3o"}]]);/** * @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 gQ=te("FileHeart",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v2",key:"17k7jt"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M10.29 10.7a2.43 2.43 0 0 0-2.66-.52c-.29.12-.56.3-.78.53l-.35.34-.35-.34a2.43 2.43 0 0 0-2.65-.53c-.3.12-.56.3-.79.53-.95.94-1 2.53.2 3.74L6.5 18l3.6-3.55c1.2-1.21 1.14-2.8.19-3.74Z",key:"1c1fso"}]]);/** * @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 z2=te("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 xQ=te("FileInput",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4",key:"1pf5j1"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M2 15h10",key:"jfw4w8"}],["path",{d:"m9 18 3-3-3-3",key:"112psh"}]]);/** * @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 yQ=te("FileJson2",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4",key:"1pf5j1"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M4 12a1 1 0 0 0-1 1v1a1 1 0 0 1-1 1 1 1 0 0 1 1 1v1a1 1 0 0 0 1 1",key:"fq0c9t"}],["path",{d:"M8 18a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1 1 1 0 0 1-1-1v-1a1 1 0 0 0-1-1",key:"4gibmv"}]]);/** * @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 vQ=te("FileJson",[["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 12a1 1 0 0 0-1 1v1a1 1 0 0 1-1 1 1 1 0 0 1 1 1v1a1 1 0 0 0 1 1",key:"1oajmo"}],["path",{d:"M14 18a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1 1 1 0 0 1-1-1v-1a1 1 0 0 0-1-1",key:"mpwhp6"}]]);/** * @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 bQ=te("FileKey2",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v6",key:"rc0qvx"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["circle",{cx:"4",cy:"16",r:"2",key:"1ehqvc"}],["path",{d:"m10 10-4.5 4.5",key:"7fwrp6"}],["path",{d:"m9 11 1 1",key:"wa6s5q"}]]);/** * @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 _Q=te("FileKey",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["circle",{cx:"10",cy:"16",r:"2",key:"4ckbqe"}],["path",{d:"m16 10-4.5 4.5",key:"7p3ebg"}],["path",{d:"m15 11 1 1",key:"1bsyx3"}]]);/** * @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 wQ=te("FileLock2",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v1",key:"jmtmu2"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["rect",{width:"8",height:"5",x:"2",y:"13",rx:"1",key:"10y5wo"}],["path",{d:"M8 13v-2a2 2 0 1 0-4 0v2",key:"1pdxzg"}]]);/** * @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 jQ=te("FileLock",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["rect",{width:"8",height:"6",x:"8",y:"12",rx:"1",key:"3yr8at"}],["path",{d:"M10 12v-2a2 2 0 1 1 4 0v2",key:"j4i8d"}]]);/** * @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 NQ=te("FileMinus2",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4",key:"1pf5j1"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M3 15h6",key:"4e2qda"}]]);/** * @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 kQ=te("FileMinus",[["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:"M9 15h6",key:"cctwl0"}]]);/** * @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 SQ=te("FileMusic",[["path",{d:"M10.5 22H18a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v8.4",key:"1d3kfm"}],["path",{d:"M8 18v-7.7L16 9v7",key:"1oie6o"}],["circle",{cx:"14",cy:"16",r:"2",key:"1bzzi3"}],["circle",{cx:"6",cy:"18",r:"2",key:"1fncim"}]]);/** * @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 CQ=te("FileOutput",[["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M4 7V4a2 2 0 0 1 2-2 2 2 0 0 0-2 2",key:"1vk7w2"}],["path",{d:"M4.063 20.999a2 2 0 0 0 2 1L18 22a2 2 0 0 0 2-2V7l-5-5H6",key:"1jink5"}],["path",{d:"m5 11-3 3",key:"1dgrs4"}],["path",{d:"m5 17-3-3h10",key:"1mvvaf"}]]);/** * @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 S3=te("FilePenLine",[["path",{d:"m18 5-2.414-2.414A2 2 0 0 0 14.172 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2",key:"142zxg"}],["path",{d:"M21.378 12.626a1 1 0 0 0-3.004-3.004l-4.01 4.012a2 2 0 0 0-.506.854l-.837 2.87a.5.5 0 0 0 .62.62l2.87-.837a2 2 0 0 0 .854-.506z",key:"2t3380"}],["path",{d:"M8 18h1",key:"13wk12"}]]);/** * @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 C3=te("FilePen",[["path",{d:"M12.5 22H18a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v9.5",key:"1couwa"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M13.378 15.626a1 1 0 1 0-3.004-3.004l-5.01 5.012a2 2 0 0 0-.506.854l-.837 2.87a.5.5 0 0 0 .62.62l2.87-.837a2 2 0 0 0 .854-.506z",key:"1y4qbx"}]]);/** * @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 TQ=te("FilePlus2",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4",key:"1pf5j1"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M3 15h6",key:"4e2qda"}],["path",{d:"M6 12v6",key:"1u72j0"}]]);/** * @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 EQ=te("FilePlus",[["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:"M9 15h6",key:"cctwl0"}],["path",{d:"M12 18v-6",key:"17g6i2"}]]);/** * @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 AQ=te("FileQuestion",[["path",{d:"M12 17h.01",key:"p32p05"}],["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7z",key:"1mlx9k"}],["path",{d:"M9.1 9a3 3 0 0 1 5.82 1c0 2-3 3-3 3",key:"mhlwft"}]]);/** * @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 MQ=te("FileScan",[["path",{d:"M20 10V7l-5-5H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h4",key:"1rdf37"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M16 14a2 2 0 0 0-2 2",key:"ceaadl"}],["path",{d:"M20 14a2 2 0 0 1 2 2",key:"1ny6zw"}],["path",{d:"M20 22a2 2 0 0 0 2-2",key:"1l9q4k"}],["path",{d:"M16 22a2 2 0 0 1-2-2",key:"1wqh5n"}]]);/** * @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 IQ=te("FileSearch2",[["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:"11.5",cy:"14.5",r:"2.5",key:"1bq0ko"}],["path",{d:"M13.3 16.3 15 18",key:"2quom7"}]]);/** * @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 PQ=te("FileSearch",[["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M4.268 21a2 2 0 0 0 1.727 1H18a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v3",key:"ms7g94"}],["path",{d:"m9 18-1.5-1.5",key:"1j6qii"}],["circle",{cx:"5",cy:"14",r:"3",key:"ufru5t"}]]);/** * @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 LQ=te("FileSliders",[["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 12h8",key:"1wcyev"}],["path",{d:"M10 11v2",key:"1s651w"}],["path",{d:"M8 17h8",key:"wh5c61"}],["path",{d:"M14 16v2",key:"12fp5e"}]]);/** * @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 $2=te("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 lF=te("FileStack",[["path",{d:"M21 7h-3a2 2 0 0 1-2-2V2",key:"9rb54x"}],["path",{d:"M21 6v6.5c0 .8-.7 1.5-1.5 1.5h-7c-.8 0-1.5-.7-1.5-1.5v-9c0-.8.7-1.5 1.5-1.5H17Z",key:"1059l0"}],["path",{d:"M7 8v8.8c0 .3.2.6.4.8.2.2.5.4.8.4H15",key:"16874u"}],["path",{d:"M3 12v8.8c0 .3.2.6.4.8.2.2.5.4.8.4H11",key:"k2ox98"}]]);/** * @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 DQ=te("FileSymlink",[["path",{d:"m10 18 3-3-3-3",key:"18f6ys"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M4 11V4a2 2 0 0 1 2-2h9l5 5v13a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2v-3a2 2 0 0 1 2-2h7",key:"50q2rw"}]]);/** * @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 RQ=te("FileTerminal",[["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 16 2-2-2-2",key:"10vzyd"}],["path",{d:"M12 18h4",key:"1wd2n7"}]]);/** * @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 kn=te("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 OQ=te("FileType2",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4",key:"1pf5j1"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M2 13v-1h6v1",key:"1dh9dg"}],["path",{d:"M5 12v6",key:"150t9c"}],["path",{d:"M4 18h2",key:"1xrofg"}]]);/** * @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 FQ=te("FileType",[["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:"M9 13v-1h6v1",key:"1bb014"}],["path",{d:"M12 12v6",key:"3ahymv"}],["path",{d:"M11 18h2",key:"12mj7e"}]]);/** * @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 BQ=te("FileUp",[["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:"M12 12v6",key:"3ahymv"}],["path",{d:"m15 15-3-3-3 3",key:"15xj92"}]]);/** * @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 zQ=te("FileUser",[["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M15 18a3 3 0 1 0-6 0",key:"16awa0"}],["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7z",key:"1mlx9k"}],["circle",{cx:"12",cy:"13",r:"2",key:"1c1ljs"}]]);/** * @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 $Q=te("FileVideo2",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4",key:"1pf5j1"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["rect",{width:"8",height:"6",x:"2",y:"12",rx:"1",key:"1a6c1e"}],["path",{d:"m10 15.5 4 2.5v-6l-4 2.5",key:"t7cp39"}]]);/** * @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 cF=te("FileVideo",[["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 11 5 3-5 3v-6Z",key:"7ntvm4"}]]);/** * @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 UQ=te("FileVolume2",[["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 15h.01",key:"a7atzg"}],["path",{d:"M11.5 13.5a2.5 2.5 0 0 1 0 3",key:"1fccat"}],["path",{d:"M15 12a5 5 0 0 1 0 6",key:"ps46cm"}]]);/** * @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 qQ=te("FileVolume",[["path",{d:"M11 11a5 5 0 0 1 0 6",key:"193qb2"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M4 6.765V4a2 2 0 0 1 2-2h9l5 5v13a2 2 0 0 1-2 2H6a2 2 0 0 1-.93-.23",key:"ifyjnl"}],["path",{d:"M7 10.51a.5.5 0 0 0-.826-.38l-1.893 1.628A1 1 0 0 1 3.63 12H2.5a.5.5 0 0 0-.5.5v3a.5.5 0 0 0 .5.5h1.129a1 1 0 0 1 .652.242l1.893 1.63a.5.5 0 0 0 .826-.38z",key:"mk8rxu"}]]);/** * @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 VQ=te("FileWarning",[["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:"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 HQ=te("FileX2",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4",key:"1pf5j1"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"m8 12.5-5 5",key:"b853mi"}],["path",{d:"m3 12.5 5 5",key:"1qls4r"}]]);/** * @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 GQ=te("FileX",[["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:"m14.5 12.5-5 5",key:"b62r18"}],["path",{d:"m9.5 12.5 5 5",key:"1rk7el"}]]);/** * @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 RI=te("File",[["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"}]]);/** * @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 WQ=te("Files",[["path",{d:"M20 7h-3a2 2 0 0 1-2-2V2",key:"x099mo"}],["path",{d:"M9 18a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h7l4 4v10a2 2 0 0 1-2 2Z",key:"18t6ie"}],["path",{d:"M3 7.6v12.8A1.6 1.6 0 0 0 4.6 22h9.8",key:"1nja0z"}]]);/** * @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 Qm=te("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 KQ=te("FilterX",[["path",{d:"M13.013 3H2l8 9.46V19l4 2v-8.54l.9-1.055",key:"1fi1da"}],["path",{d:"m22 3-5 5",key:"12jva0"}],["path",{d:"m17 3 5 5",key:"k36vhe"}]]);/** * @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 v1=te("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 YQ=te("Fingerprint",[["path",{d:"M12 10a2 2 0 0 0-2 2c0 1.02-.1 2.51-.26 4",key:"1nerag"}],["path",{d:"M14 13.12c0 2.38 0 6.38-1 8.88",key:"o46ks0"}],["path",{d:"M17.29 21.02c.12-.6.43-2.3.5-3.02",key:"ptglia"}],["path",{d:"M2 12a10 10 0 0 1 18-6",key:"ydlgp0"}],["path",{d:"M2 16h.01",key:"1gqxmh"}],["path",{d:"M21.8 16c.2-2 .131-5.354 0-6",key:"drycrb"}],["path",{d:"M5 19.5C5.5 18 6 15 6 12a6 6 0 0 1 .34-2",key:"1tidbn"}],["path",{d:"M8.65 22c.21-.66.45-1.32.57-2",key:"13wd9y"}],["path",{d:"M9 6.8a6 6 0 0 1 9 5.2v2",key:"1fr1j5"}]]);/** * @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 ZQ=te("FireExtinguisher",[["path",{d:"M15 6.5V3a1 1 0 0 0-1-1h-2a1 1 0 0 0-1 1v3.5",key:"sqyvz"}],["path",{d:"M9 18h8",key:"i7pszb"}],["path",{d:"M18 3h-3",key:"7idoqj"}],["path",{d:"M11 3a6 6 0 0 0-6 6v11",key:"1v5je3"}],["path",{d:"M5 13h4",key:"svpcxo"}],["path",{d:"M17 10a4 4 0 0 0-8 0v10a2 2 0 0 0 2 2h4a2 2 0 0 0 2-2Z",key:"vsjego"}]]);/** * @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 XQ=te("FishOff",[["path",{d:"M18 12.47v.03m0-.5v.47m-.475 5.056A6.744 6.744 0 0 1 15 18c-3.56 0-7.56-2.53-8.5-6 .348-1.28 1.114-2.433 2.121-3.38m3.444-2.088A8.802 8.802 0 0 1 15 6c3.56 0 6.06 2.54 7 6-.309 1.14-.786 2.177-1.413 3.058",key:"1j1hse"}],["path",{d:"M7 10.67C7 8 5.58 5.97 2.73 5.5c-1 1.5-1 5 .23 6.5-1.24 1.5-1.24 5-.23 6.5C5.58 18.03 7 16 7 13.33m7.48-4.372A9.77 9.77 0 0 1 16 6.07m0 11.86a9.77 9.77 0 0 1-1.728-3.618",key:"1q46z8"}],["path",{d:"m16.01 17.93-.23 1.4A2 2 0 0 1 13.8 21H9.5a5.96 5.96 0 0 0 1.49-3.98M8.53 3h5.27a2 2 0 0 1 1.98 1.67l.23 1.4M2 2l20 20",key:"1407gh"}]]);/** * @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 QQ=te("FishSymbol",[["path",{d:"M2 16s9-15 20-4C11 23 2 8 2 8",key:"h4oh4o"}]]);/** * @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 JQ=te("Fish",[["path",{d:"M6.5 12c.94-3.46 4.94-6 8.5-6 3.56 0 6.06 2.54 7 6-.94 3.47-3.44 6-7 6s-7.56-2.53-8.5-6Z",key:"15baut"}],["path",{d:"M18 12v.5",key:"18hhni"}],["path",{d:"M16 17.93a9.77 9.77 0 0 1 0-11.86",key:"16dt7o"}],["path",{d:"M7 10.67C7 8 5.58 5.97 2.73 5.5c-1 1.5-1 5 .23 6.5-1.24 1.5-1.24 5-.23 6.5C5.58 18.03 7 16 7 13.33",key:"l9di03"}],["path",{d:"M10.46 7.26C10.2 5.88 9.17 4.24 8 3h5.8a2 2 0 0 1 1.98 1.67l.23 1.4",key:"1kjonw"}],["path",{d:"m16.01 17.93-.23 1.4A2 2 0 0 1 13.8 21H9.5a5.96 5.96 0 0 0 1.49-3.98",key:"1zlm23"}]]);/** * @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 eJ=te("FlagOff",[["path",{d:"M8 2c3 0 5 2 8 2s4-1 4-1v11",key:"9rwyz9"}],["path",{d:"M4 22V4",key:"1plyxx"}],["path",{d:"M4 15s1-1 4-1 5 2 8 2",key:"1myooe"}],["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}]]);/** * @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 tJ=te("FlagTriangleLeft",[["path",{d:"M17 22V2L7 7l10 5",key:"1rmf0r"}]]);/** * @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 sJ=te("FlagTriangleRight",[["path",{d:"M7 22V2l10 5-10 5",key:"17n18y"}]]);/** * @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 U2=te("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 rJ=te("FlameKindling",[["path",{d:"M12 2c1 3 2.5 3.5 3.5 4.5A5 5 0 0 1 17 10a5 5 0 1 1-10 0c0-.3 0-.6.1-.9a2 2 0 1 0 3.3-2C8 4.5 11 2 12 2Z",key:"1ir223"}],["path",{d:"m5 22 14-4",key:"1brv4h"}],["path",{d:"m5 18 14 4",key:"lgyyje"}]]);/** * @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 od=te("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 nJ=te("FlashlightOff",[["path",{d:"M16 16v4a2 2 0 0 1-2 2h-4a2 2 0 0 1-2-2V10c0-2-2-2-2-4",key:"1r120k"}],["path",{d:"M7 2h11v4c0 2-2 2-2 4v1",key:"dz1920"}],["line",{x1:"11",x2:"18",y1:"6",y2:"6",key:"bi1vpe"}],["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}]]);/** * @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=te("Flashlight",[["path",{d:"M18 6c0 2-2 2-2 4v10a2 2 0 0 1-2 2h-4a2 2 0 0 1-2-2V10c0-2-2-2-2-4V2h12z",key:"1orkel"}],["line",{x1:"6",x2:"18",y1:"6",y2:"6",key:"1z11jq"}],["line",{x1:"12",x2:"12",y1:"12",y2:"12",key:"1f4yc1"}]]);/** * @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 iJ=te("FlaskConicalOff",[["path",{d:"M10 10 4.72 20.55a1 1 0 0 0 .9 1.45h12.76a1 1 0 0 0 .9-1.45l-1.272-2.542",key:"59ek9y"}],["path",{d:"M10 2v2.343",key:"15t272"}],["path",{d:"M14 2v6.343",key:"sxr80q"}],["path",{d:"M8.5 2h7",key:"csnxdl"}],["path",{d:"M7 16h9",key:"t5njau"}],["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}]]);/** * @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 Bk=te("FlaskConical",[["path",{d:"M10 2v7.527a2 2 0 0 1-.211.896L4.72 20.55a1 1 0 0 0 .9 1.45h12.76a1 1 0 0 0 .9-1.45l-5.069-10.127A2 2 0 0 1 14 9.527V2",key:"pzvekw"}],["path",{d:"M8.5 2h7",key:"csnxdl"}],["path",{d:"M7 16h10",key:"wp8him"}]]);/** * @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 oJ=te("FlaskRound",[["path",{d:"M10 2v7.31",key:"5d1hyh"}],["path",{d:"M14 9.3V1.99",key:"14k4l0"}],["path",{d:"M8.5 2h7",key:"csnxdl"}],["path",{d:"M14 9.3a6.5 6.5 0 1 1-4 0",key:"1r8fvy"}],["path",{d:"M5.52 16h12.96",key:"46hh1i"}]]);/** * @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 lJ=te("FlipHorizontal2",[["path",{d:"m3 7 5 5-5 5V7",key:"couhi7"}],["path",{d:"m21 7-5 5 5 5V7",key:"6ouia7"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"M12 14v2",key:"8jcxud"}],["path",{d:"M12 8v2",key:"1woqiv"}],["path",{d:"M12 2v2",key:"tus03m"}]]);/** * @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 dF=te("FlipHorizontal",[["path",{d:"M8 3H5a2 2 0 0 0-2 2v14c0 1.1.9 2 2 2h3",key:"1i73f7"}],["path",{d:"M16 3h3a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-3",key:"saxlbk"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"M12 14v2",key:"8jcxud"}],["path",{d:"M12 8v2",key:"1woqiv"}],["path",{d:"M12 2v2",key:"tus03m"}]]);/** * @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 cJ=te("FlipVertical2",[["path",{d:"m17 3-5 5-5-5h10",key:"1ftt6x"}],["path",{d:"m17 21-5-5-5 5h10",key:"1m0wmu"}],["path",{d:"M4 12H2",key:"rhcxmi"}],["path",{d:"M10 12H8",key:"s88cx1"}],["path",{d:"M16 12h-2",key:"10asgb"}],["path",{d:"M22 12h-2",key:"14jgyd"}]]);/** * @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 dJ=te("FlipVertical",[["path",{d:"M21 8V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v3",key:"14bfxa"}],["path",{d:"M21 16v3a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-3",key:"14rx03"}],["path",{d:"M4 12H2",key:"rhcxmi"}],["path",{d:"M10 12H8",key:"s88cx1"}],["path",{d:"M16 12h-2",key:"10asgb"}],["path",{d:"M22 12h-2",key:"14jgyd"}]]);/** * @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 u1=te("Flower2",[["path",{d:"M12 5a3 3 0 1 1 3 3m-3-3a3 3 0 1 0-3 3m3-3v1M9 8a3 3 0 1 0 3 3M9 8h1m5 0a3 3 0 1 1-3 3m3-3h-1m-2 3v-1",key:"3pnvol"}],["circle",{cx:"12",cy:"8",r:"2",key:"1822b1"}],["path",{d:"M12 10v12",key:"6ubwww"}],["path",{d:"M12 22c4.2 0 7-1.667 7-5-4.2 0-7 1.667-7 5Z",key:"9hd38g"}],["path",{d:"M12 22c-4.2 0-7-1.667-7-5 4.2 0 7 1.667 7 5Z",key:"ufn41s"}]]);/** * @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 uJ=te("Flower",[["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}],["path",{d:"M12 16.5A4.5 4.5 0 1 1 7.5 12 4.5 4.5 0 1 1 12 7.5a4.5 4.5 0 1 1 4.5 4.5 4.5 4.5 0 1 1-4.5 4.5",key:"14wa3c"}],["path",{d:"M12 7.5V9",key:"1oy5b0"}],["path",{d:"M7.5 12H9",key:"eltsq1"}],["path",{d:"M16.5 12H15",key:"vk5kw4"}],["path",{d:"M12 16.5V15",key:"k7eayi"}],["path",{d:"m8 8 1.88 1.88",key:"nxy4qf"}],["path",{d:"M14.12 9.88 16 8",key:"1lst6k"}],["path",{d:"m8 16 1.88-1.88",key:"h2eex1"}],["path",{d:"M14.12 14.12 16 16",key:"uqkrx3"}]]);/** * @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 hJ=te("Focus",[["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}],["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}]]);/** * @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 mJ=te("FoldHorizontal",[["path",{d:"M2 12h6",key:"1wqiqv"}],["path",{d:"M22 12h-6",key:"1eg9hc"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 8v2",key:"1woqiv"}],["path",{d:"M12 14v2",key:"8jcxud"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"m19 9-3 3 3 3",key:"12ol22"}],["path",{d:"m5 15 3-3-3-3",key:"1kdhjc"}]]);/** * @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 fJ=te("FoldVertical",[["path",{d:"M12 22v-6",key:"6o8u61"}],["path",{d:"M12 8V2",key:"1wkif3"}],["path",{d:"M4 12H2",key:"rhcxmi"}],["path",{d:"M10 12H8",key:"s88cx1"}],["path",{d:"M16 12h-2",key:"10asgb"}],["path",{d:"M22 12h-2",key:"14jgyd"}],["path",{d:"m15 19-3-3-3 3",key:"e37ymu"}],["path",{d:"m15 5-3 3-3-3",key:"19d6lf"}]]);/** * @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 pJ=te("FolderArchive",[["circle",{cx:"15",cy:"19",r:"2",key:"u2pros"}],["path",{d:"M20.9 19.8A2 2 0 0 0 22 18V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2h5.1",key:"1jj40k"}],["path",{d:"M15 11v-1",key:"cntcp"}],["path",{d:"M15 17v-2",key:"1279jj"}]]);/** * @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 gJ=te("FolderCheck",[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}],["path",{d:"m9 13 2 2 4-4",key:"6343dt"}]]);/** * @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 xJ=te("FolderClock",[["circle",{cx:"16",cy:"16",r:"6",key:"qoo3c4"}],["path",{d:"M7 20H4a2 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.9H20a2 2 0 0 1 2 2",key:"1urifu"}],["path",{d:"M16 14v2l1 1",key:"xth2jh"}]]);/** * @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 yJ=te("FolderClosed",[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}],["path",{d:"M2 10h20",key:"1ir3d8"}]]);/** * @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 vJ=te("FolderCode",[["path",{d:"M10 10.5 8 13l2 2.5",key:"m4t9c1"}],["path",{d:"m14 10.5 2 2.5-2 2.5",key:"14w2eb"}],["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2z",key:"1u1bxd"}]]);/** * @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 T3=te("FolderCog",[["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}],["path",{d:"M10.3 20H4a2 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.9H20a2 2 0 0 1 2 2v3.3",key:"1k8050"}],["path",{d:"m21.7 19.4-.9-.3",key:"1qgwi9"}],["path",{d:"m15.2 16.9-.9-.3",key:"1t7mvx"}],["path",{d:"m16.6 21.7.3-.9",key:"1j67ps"}],["path",{d:"m19.1 15.2.3-.9",key:"18r7jp"}],["path",{d:"m19.6 21.7-.4-1",key:"z2vh2"}],["path",{d:"m16.8 15.3-.4-1",key:"1ei7r6"}],["path",{d:"m14.3 19.6 1-.4",key:"11sv9r"}],["path",{d:"m20.7 16.8 1-.4",key:"19m87a"}]]);/** * @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 bJ=te("FolderDot",[["path",{d:"M4 20h16a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.93a2 2 0 0 1-1.66-.9l-.82-1.2A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13c0 1.1.9 2 2 2Z",key:"1fr9dc"}],["circle",{cx:"12",cy:"13",r:"1",key:"49l61u"}]]);/** * @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 _J=te("FolderDown",[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}],["path",{d:"M12 10v6",key:"1bos4e"}],["path",{d:"m15 13-3 3-3-3",key:"6j2sf0"}]]);/** * @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 wJ=te("FolderGit2",[["path",{d:"M9 20H4a2 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.9H20a2 2 0 0 1 2 2v5",key:"1w6njk"}],["circle",{cx:"13",cy:"12",r:"2",key:"1j92g6"}],["path",{d:"M18 19c-2.8 0-5-2.2-5-5v8",key:"pkpw2h"}],["circle",{cx:"20",cy:"19",r:"2",key:"1obnsp"}]]);/** * @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 jJ=te("FolderGit",[["circle",{cx:"12",cy:"13",r:"2",key:"1c1ljs"}],["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}],["path",{d:"M14 13h3",key:"1dgedf"}],["path",{d:"M7 13h3",key:"1pygq7"}]]);/** * @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 NJ=te("FolderHeart",[["path",{d:"M11 20H4a2 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.9H20a2 2 0 0 1 2 2v1.5",key:"6hud8k"}],["path",{d:"M13.9 17.45c-1.2-1.2-1.14-2.8-.2-3.73a2.43 2.43 0 0 1 3.44 0l.36.34.34-.34a2.43 2.43 0 0 1 3.45-.01c.95.95 1 2.53-.2 3.74L17.5 21Z",key:"wpff58"}]]);/** * @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 kJ=te("FolderInput",[["path",{d:"M2 9V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H20a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2v-1",key:"fm4g5t"}],["path",{d:"M2 13h10",key:"pgb2dq"}],["path",{d:"m9 16 3-3-3-3",key:"6m91ic"}]]);/** * @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 SJ=te("FolderKanban",[["path",{d:"M4 20h16a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.93a2 2 0 0 1-1.66-.9l-.82-1.2A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13c0 1.1.9 2 2 2Z",key:"1fr9dc"}],["path",{d:"M8 10v4",key:"tgpxqk"}],["path",{d:"M12 10v2",key:"hh53o1"}],["path",{d:"M16 10v6",key:"1d6xys"}]]);/** * @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 CJ=te("FolderKey",[["circle",{cx:"16",cy:"20",r:"2",key:"1vifvg"}],["path",{d:"M10 20H4a2 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.9H20a2 2 0 0 1 2 2v2",key:"3hgo9p"}],["path",{d:"m22 14-4.5 4.5",key:"1ef6z8"}],["path",{d:"m21 15 1 1",key:"1ejcpy"}]]);/** * @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 TJ=te("FolderLock",[["rect",{width:"8",height:"5",x:"14",y:"17",rx:"1",key:"19aais"}],["path",{d:"M10 20H4a2 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.9H20a2 2 0 0 1 2 2v2.5",key:"1w6v7t"}],["path",{d:"M20 17v-2a2 2 0 1 0-4 0v2",key:"pwaxnr"}]]);/** * @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 EJ=te("FolderMinus",[["path",{d:"M9 13h6",key:"1uhe8q"}],["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}]]);/** * @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=te("FolderOpenDot",[["path",{d:"m6 14 1.45-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.55 6a2 2 0 0 1-1.94 1.5H4a2 2 0 0 1-2-2V5c0-1.1.9-2 2-2h3.93a2 2 0 0 1 1.66.9l.82 1.2a2 2 0 0 0 1.66.9H18a2 2 0 0 1 2 2v2",key:"1nmvlm"}],["circle",{cx:"14",cy:"15",r:"1",key:"1gm4qj"}]]);/** * @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 Uf=te("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 MJ=te("FolderOutput",[["path",{d:"M2 7.5V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H20a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H4a2 2 0 0 1-2-1.5",key:"1yk7aj"}],["path",{d:"M2 13h10",key:"pgb2dq"}],["path",{d:"m5 10-3 3 3 3",key:"1r8ie0"}]]);/** * @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 E3=te("FolderPen",[["path",{d:"M2 11.5V5a2 2 0 0 1 2-2h3.9c.7 0 1.3.3 1.7.9l.8 1.2c.4.6 1 .9 1.7.9H20a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2h-9.5",key:"a8xqs0"}],["path",{d:"M11.378 13.626a1 1 0 1 0-3.004-3.004l-5.01 5.012a2 2 0 0 0-.506.854l-.837 2.87a.5.5 0 0 0 .62.62l2.87-.837a2 2 0 0 0 .854-.506z",key:"1saktj"}]]);/** * @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 IJ=te("FolderPlus",[["path",{d:"M12 10v6",key:"1bos4e"}],["path",{d:"M9 13h6",key:"1uhe8q"}],["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}]]);/** * @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 PJ=te("FolderRoot",[["path",{d:"M4 20h16a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.93a2 2 0 0 1-1.66-.9l-.82-1.2A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13c0 1.1.9 2 2 2Z",key:"1fr9dc"}],["circle",{cx:"12",cy:"13",r:"2",key:"1c1ljs"}],["path",{d:"M12 15v5",key:"11xva1"}]]);/** * @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 LJ=te("FolderSearch2",[["circle",{cx:"11.5",cy:"12.5",r:"2.5",key:"1ea5ju"}],["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}],["path",{d:"M13.3 14.3 15 16",key:"1y4v1n"}]]);/** * @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 DJ=te("FolderSearch",[["path",{d:"M10.7 20H4a2 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.9H20a2 2 0 0 1 2 2v4.1",key:"1bw5m7"}],["path",{d:"m21 21-1.9-1.9",key:"1g2n9r"}],["circle",{cx:"17",cy:"17",r:"3",key:"18b49y"}]]);/** * @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 RJ=te("FolderSymlink",[["path",{d:"M2 9V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H20a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2v-3a2 2 0 0 1 2-2h7",key:"x1c07l"}],["path",{d:"m8 16 3-3-3-3",key:"rlqrt1"}]]);/** * @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 OJ=te("FolderSync",[["path",{d:"M9 20H4a2 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.9H20a2 2 0 0 1 2 2v.5",key:"1dkoa9"}],["path",{d:"M12 10v4h4",key:"1czhmt"}],["path",{d:"m12 14 1.535-1.605a5 5 0 0 1 8 1.5",key:"lvuxfi"}],["path",{d:"M22 22v-4h-4",key:"1ewp4q"}],["path",{d:"m22 18-1.535 1.605a5 5 0 0 1-8-1.5",key:"14ync0"}]]);/** * @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 FJ=te("FolderTree",[["path",{d:"M20 10a1 1 0 0 0 1-1V6a1 1 0 0 0-1-1h-2.5a1 1 0 0 1-.8-.4l-.9-1.2A1 1 0 0 0 15 3h-2a1 1 0 0 0-1 1v5a1 1 0 0 0 1 1Z",key:"hod4my"}],["path",{d:"M20 21a1 1 0 0 0 1-1v-3a1 1 0 0 0-1-1h-2.9a1 1 0 0 1-.88-.55l-.42-.85a1 1 0 0 0-.92-.6H13a1 1 0 0 0-1 1v5a1 1 0 0 0 1 1Z",key:"w4yl2u"}],["path",{d:"M3 5a2 2 0 0 0 2 2h3",key:"f2jnh7"}],["path",{d:"M3 3v13a2 2 0 0 0 2 2h3",key:"k8epm1"}]]);/** * @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 BJ=te("FolderUp",[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}],["path",{d:"M12 10v6",key:"1bos4e"}],["path",{d:"m9 13 3-3 3 3",key:"1pxg3c"}]]);/** * @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 zJ=te("FolderX",[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}],["path",{d:"m9.5 10.5 5 5",key:"ra9qjz"}],["path",{d:"m14.5 10.5-5 5",key:"l2rkpq"}]]);/** * @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 $J=te("Folder",[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}]]);/** * @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 UJ=te("Folders",[["path",{d:"M20 17a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-3.9a2 2 0 0 1-1.69-.9l-.81-1.2a2 2 0 0 0-1.67-.9H8a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2Z",key:"4u7rpt"}],["path",{d:"M2 8v11a2 2 0 0 0 2 2h14",key:"1eicx1"}]]);/** * @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 qJ=te("Footprints",[["path",{d:"M4 16v-2.38C4 11.5 2.97 10.5 3 8c.03-2.72 1.49-6 4.5-6C9.37 2 10 3.8 10 5.5c0 3.11-2 5.66-2 8.68V16a2 2 0 1 1-4 0Z",key:"1dudjm"}],["path",{d:"M20 20v-2.38c0-2.12 1.03-3.12 1-5.62-.03-2.72-1.49-6-4.5-6C14.63 6 14 7.8 14 9.5c0 3.11 2 5.66 2 8.68V20a2 2 0 1 0 4 0Z",key:"l2t8xc"}],["path",{d:"M16 17h4",key:"1dejxt"}],["path",{d:"M4 13h4",key:"1bwh8b"}]]);/** * @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 VJ=te("Forklift",[["path",{d:"M12 12H5a2 2 0 0 0-2 2v5",key:"7zsz91"}],["circle",{cx:"13",cy:"19",r:"2",key:"wjnkru"}],["circle",{cx:"5",cy:"19",r:"2",key:"v8kfzx"}],["path",{d:"M8 19h3m5-17v17h6M6 12V7c0-1.1.9-2 2-2h3l5 5",key:"13bk1p"}]]);/** * @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 HJ=te("Forward",[["polyline",{points:"15 17 20 12 15 7",key:"1w3sku"}],["path",{d:"M4 18v-2a4 4 0 0 1 4-4h12",key:"jmiej9"}]]);/** * @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 GJ=te("Frame",[["line",{x1:"22",x2:"2",y1:"6",y2:"6",key:"15w7dq"}],["line",{x1:"22",x2:"2",y1:"18",y2:"18",key:"1ip48p"}],["line",{x1:"6",x2:"6",y1:"2",y2:"22",key:"a2lnyx"}],["line",{x1:"18",x2:"18",y1:"2",y2:"22",key:"8vb6jd"}]]);/** * @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 WJ=te("Framer",[["path",{d:"M5 16V9h14V2H5l14 14h-7m-7 0 7 7v-7m-7 0h7",key:"1a2nng"}]]);/** * @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 KJ=te("Frown",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M16 16s-1.5-2-4-2-4 2-4 2",key:"epbg0q"}],["line",{x1:"9",x2:"9.01",y1:"9",y2:"9",key:"yxxnd0"}],["line",{x1:"15",x2:"15.01",y1:"9",y2:"9",key:"1p4y9e"}]]);/** * @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 YJ=te("Fuel",[["line",{x1:"3",x2:"15",y1:"22",y2:"22",key:"xegly4"}],["line",{x1:"4",x2:"14",y1:"9",y2:"9",key:"xcnuvu"}],["path",{d:"M14 22V4a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v18",key:"16j0yd"}],["path",{d:"M14 13h2a2 2 0 0 1 2 2v2a2 2 0 0 0 2 2a2 2 0 0 0 2-2V9.83a2 2 0 0 0-.59-1.42L18 5",key:"7cu91f"}]]);/** * @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 ZJ=te("Fullscreen",[["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}],["rect",{width:"10",height:"8",x:"7",y:"8",rx:"1",key:"vys8me"}]]);/** * @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 XJ=te("GalleryHorizontalEnd",[["path",{d:"M2 7v10",key:"a2pl2d"}],["path",{d:"M6 5v14",key:"1kq3d7"}],["rect",{width:"12",height:"18",x:"10",y:"3",rx:"2",key:"13i7bc"}]]);/** * @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 QJ=te("GalleryHorizontal",[["path",{d:"M2 3v18",key:"pzttux"}],["rect",{width:"12",height:"18",x:"6",y:"3",rx:"2",key:"btr8bg"}],["path",{d:"M22 3v18",key:"6jf3v"}]]);/** * @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 JJ=te("GalleryThumbnails",[["rect",{width:"18",height:"14",x:"3",y:"3",rx:"2",key:"74y24f"}],["path",{d:"M4 21h1",key:"16zlid"}],["path",{d:"M9 21h1",key:"15o7lz"}],["path",{d:"M14 21h1",key:"v9vybs"}],["path",{d:"M19 21h1",key:"edywat"}]]);/** * @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 eee=te("GalleryVerticalEnd",[["path",{d:"M7 2h10",key:"nczekb"}],["path",{d:"M5 6h14",key:"u2x4p"}],["rect",{width:"18",height:"12",x:"3",y:"10",rx:"2",key:"l0tzu3"}]]);/** * @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 tee=te("GalleryVertical",[["path",{d:"M3 2h18",key:"15qxfx"}],["rect",{width:"18",height:"12",x:"3",y:"6",rx:"2",key:"1439r6"}],["path",{d:"M3 22h18",key:"8prr45"}]]);/** * @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 see=te("Gamepad2",[["line",{x1:"6",x2:"10",y1:"11",y2:"11",key:"1gktln"}],["line",{x1:"8",x2:"8",y1:"9",y2:"13",key:"qnk9ow"}],["line",{x1:"15",x2:"15.01",y1:"12",y2:"12",key:"krot7o"}],["line",{x1:"18",x2:"18.01",y1:"10",y2:"10",key:"1lcuu1"}],["path",{d:"M17.32 5H6.68a4 4 0 0 0-3.978 3.59c-.006.052-.01.101-.017.152C2.604 9.416 2 14.456 2 16a3 3 0 0 0 3 3c1 0 1.5-.5 2-1l1.414-1.414A2 2 0 0 1 9.828 16h4.344a2 2 0 0 1 1.414.586L17 18c.5.5 1 1 2 1a3 3 0 0 0 3-3c0-1.545-.604-6.584-.685-7.258-.007-.05-.011-.1-.017-.151A4 4 0 0 0 17.32 5z",key:"mfqc10"}]]);/** * @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 ree=te("Gamepad",[["line",{x1:"6",x2:"10",y1:"12",y2:"12",key:"161bw2"}],["line",{x1:"8",x2:"8",y1:"10",y2:"14",key:"1i6ji0"}],["line",{x1:"15",x2:"15.01",y1:"13",y2:"13",key:"dqpgro"}],["line",{x1:"18",x2:"18.01",y1:"11",y2:"11",key:"meh2c"}],["rect",{width:"20",height:"12",x:"2",y:"6",rx:"2",key:"9lu3g6"}]]);/** * @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 nee=te("Gauge",[["path",{d:"m12 14 4-4",key:"9kzdfg"}],["path",{d:"M3.34 19a10 10 0 1 1 17.32 0",key:"19p75a"}]]);/** * @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 aee=te("Gavel",[["path",{d:"m14.5 12.5-8 8a2.119 2.119 0 1 1-3-3l8-8",key:"15492f"}],["path",{d:"m16 16 6-6",key:"vzrcl6"}],["path",{d:"m8 8 6-6",key:"18bi4p"}],["path",{d:"m9 7 8 8",key:"5jnvq1"}],["path",{d:"m21 11-8-8",key:"z4y7zo"}]]);/** * @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 iee=te("Gem",[["path",{d:"M6 3h12l4 6-10 13L2 9Z",key:"1pcd5k"}],["path",{d:"M11 3 8 9l4 13 4-13-3-6",key:"1fcu3u"}],["path",{d:"M2 9h20",key:"16fsjt"}]]);/** * @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 vE=te("Ghost",[["path",{d:"M9 10h.01",key:"qbtxuw"}],["path",{d:"M15 10h.01",key:"1qmjsl"}],["path",{d:"M12 2a8 8 0 0 0-8 8v12l3-3 2.5 2.5L12 19l2.5 2.5L17 19l3 3V10a8 8 0 0 0-8-8z",key:"uwwb07"}]]);/** * @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 Di=te("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 oee=te("GitBranchPlus",[["path",{d:"M6 3v12",key:"qpgusn"}],["path",{d:"M18 9a3 3 0 1 0 0-6 3 3 0 0 0 0 6z",key:"1d02ji"}],["path",{d:"M6 21a3 3 0 1 0 0-6 3 3 0 0 0 0 6z",key:"chk6ph"}],["path",{d:"M15 6a9 9 0 0 0-9 9",key:"or332x"}],["path",{d:"M18 15v6",key:"9wciyi"}],["path",{d:"M21 18h-6",key:"139f0c"}]]);/** * @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 lee=te("GitBranch",[["line",{x1:"6",x2:"6",y1:"3",y2:"15",key:"17qcm7"}],["circle",{cx:"18",cy:"6",r:"3",key:"1h7g24"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}],["path",{d:"M18 9a9 9 0 0 1-9 9",key:"n2h4wq"}]]);/** * @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 A3=te("GitCommitHorizontal",[["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}],["line",{x1:"3",x2:"9",y1:"12",y2:"12",key:"1dyftd"}],["line",{x1:"15",x2:"21",y1:"12",y2:"12",key:"oup4p8"}]]);/** * @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 cee=te("GitCommitVertical",[["path",{d:"M12 3v6",key:"1holv5"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}],["path",{d:"M12 15v6",key:"a9ows0"}]]);/** * @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 dee=te("GitCompareArrows",[["circle",{cx:"5",cy:"6",r:"3",key:"1qnov2"}],["path",{d:"M12 6h5a2 2 0 0 1 2 2v7",key:"1yj91y"}],["path",{d:"m15 9-3-3 3-3",key:"1lwv8l"}],["circle",{cx:"19",cy:"18",r:"3",key:"1qljk2"}],["path",{d:"M12 18H7a2 2 0 0 1-2-2V9",key:"16sdep"}],["path",{d:"m9 15 3 3-3 3",key:"1m3kbl"}]]);/** * @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 uee=te("GitCompare",[["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}],["circle",{cx:"6",cy:"6",r:"3",key:"1lh9wr"}],["path",{d:"M13 6h3a2 2 0 0 1 2 2v7",key:"1yeb86"}],["path",{d:"M11 18H8a2 2 0 0 1-2-2V9",key:"19pyzm"}]]);/** * @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 hee=te("GitFork",[["circle",{cx:"12",cy:"18",r:"3",key:"1mpf1b"}],["circle",{cx:"6",cy:"6",r:"3",key:"1lh9wr"}],["circle",{cx:"18",cy:"6",r:"3",key:"1h7g24"}],["path",{d:"M18 9v2c0 .6-.4 1-1 1H7c-.6 0-1-.4-1-1V9",key:"1uq4wg"}],["path",{d:"M12 12v3",key:"158kv8"}]]);/** * @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 mee=te("GitGraph",[["circle",{cx:"5",cy:"6",r:"3",key:"1qnov2"}],["path",{d:"M5 9v6",key:"158jrl"}],["circle",{cx:"5",cy:"18",r:"3",key:"104gr9"}],["path",{d:"M12 3v18",key:"108xh3"}],["circle",{cx:"19",cy:"6",r:"3",key:"108a5v"}],["path",{d:"M16 15.7A9 9 0 0 0 19 9",key:"1e3vqb"}]]);/** * @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 fee=te("GitMerge",[["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}],["circle",{cx:"6",cy:"6",r:"3",key:"1lh9wr"}],["path",{d:"M6 21V9a9 9 0 0 0 9 9",key:"7kw0sc"}]]);/** * @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 pee=te("GitPullRequestArrow",[["circle",{cx:"5",cy:"6",r:"3",key:"1qnov2"}],["path",{d:"M5 9v12",key:"ih889a"}],["circle",{cx:"19",cy:"18",r:"3",key:"1qljk2"}],["path",{d:"m15 9-3-3 3-3",key:"1lwv8l"}],["path",{d:"M12 6h5a2 2 0 0 1 2 2v7",key:"1yj91y"}]]);/** * @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 gee=te("GitPullRequestClosed",[["circle",{cx:"6",cy:"6",r:"3",key:"1lh9wr"}],["path",{d:"M6 9v12",key:"1sc30k"}],["path",{d:"m21 3-6 6",key:"16nqsk"}],["path",{d:"m21 9-6-6",key:"9j17rh"}],["path",{d:"M18 11.5V15",key:"65xf6f"}],["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}]]);/** * @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 xee=te("GitPullRequestCreateArrow",[["circle",{cx:"5",cy:"6",r:"3",key:"1qnov2"}],["path",{d:"M5 9v12",key:"ih889a"}],["path",{d:"m15 9-3-3 3-3",key:"1lwv8l"}],["path",{d:"M12 6h5a2 2 0 0 1 2 2v3",key:"1rbwk6"}],["path",{d:"M19 15v6",key:"10aioa"}],["path",{d:"M22 18h-6",key:"1d5gi5"}]]);/** * @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 yee=te("GitPullRequestCreate",[["circle",{cx:"6",cy:"6",r:"3",key:"1lh9wr"}],["path",{d:"M6 9v12",key:"1sc30k"}],["path",{d:"M13 6h3a2 2 0 0 1 2 2v3",key:"1jb6z3"}],["path",{d:"M18 15v6",key:"9wciyi"}],["path",{d:"M21 18h-6",key:"139f0c"}]]);/** * @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 vee=te("GitPullRequestDraft",[["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}],["circle",{cx:"6",cy:"6",r:"3",key:"1lh9wr"}],["path",{d:"M18 6V5",key:"1oao2s"}],["path",{d:"M18 11v-1",key:"11c8tz"}],["line",{x1:"6",x2:"6",y1:"9",y2:"21",key:"rroup"}]]);/** * @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 bee=te("GitPullRequest",[["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}],["circle",{cx:"6",cy:"6",r:"3",key:"1lh9wr"}],["path",{d:"M13 6h3a2 2 0 0 1 2 2v7",key:"1yeb86"}],["line",{x1:"6",x2:"6",y1:"9",y2:"21",key:"rroup"}]]);/** * @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 _ee=te("Github",[["path",{d:"M15 22v-4a4.8 4.8 0 0 0-1-3.5c3 0 6-2 6-5.5.08-1.25-.27-2.48-1-3.5.28-1.15.28-2.35 0-3.5 0 0-1 0-3 1.5-2.64-.5-5.36-.5-8 0C6 2 5 2 5 2c-.3 1.15-.3 2.35 0 3.5A5.403 5.403 0 0 0 4 9c0 3.5 3 5.5 6 5.5-.39.49-.68 1.05-.85 1.65-.17.6-.22 1.23-.15 1.85v4",key:"tonef"}],["path",{d:"M9 18c-4.51 2-5-2-7-2",key:"9comsn"}]]);/** * @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 wee=te("Gitlab",[["path",{d:"m22 13.29-3.33-10a.42.42 0 0 0-.14-.18.38.38 0 0 0-.22-.11.39.39 0 0 0-.23.07.42.42 0 0 0-.14.18l-2.26 6.67H8.32L6.1 3.26a.42.42 0 0 0-.1-.18.38.38 0 0 0-.26-.08.39.39 0 0 0-.23.07.42.42 0 0 0-.14.18L2 13.29a.74.74 0 0 0 .27.83L12 21l9.69-6.88a.71.71 0 0 0 .31-.83Z",key:"148pdi"}]]);/** * @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 jee=te("GlassWater",[["path",{d:"M5.116 4.104A1 1 0 0 1 6.11 3h11.78a1 1 0 0 1 .994 1.105L17.19 20.21A2 2 0 0 1 15.2 22H8.8a2 2 0 0 1-2-1.79z",key:"p55z4y"}],["path",{d:"M6 12a5 5 0 0 1 6 0 5 5 0 0 0 6 0",key:"mjntcy"}]]);/** * @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 Nee=te("Glasses",[["circle",{cx:"6",cy:"15",r:"4",key:"vux9w4"}],["circle",{cx:"18",cy:"15",r:"4",key:"18o8ve"}],["path",{d:"M14 15a2 2 0 0 0-2-2 2 2 0 0 0-2 2",key:"1ag4bs"}],["path",{d:"M2.5 13 5 7c.7-1.3 1.4-2 3-2",key:"1hm1gs"}],["path",{d:"M21.5 13 19 7c-.7-1.3-1.5-2-3-2",key:"1r31ai"}]]);/** * @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 kee=te("GlobeLock",[["path",{d:"M15.686 15A14.5 14.5 0 0 1 12 22a14.5 14.5 0 0 1 0-20 10 10 0 1 0 9.542 13",key:"qkt0x6"}],["path",{d:"M2 12h8.5",key:"ovaggd"}],["path",{d:"M20 6V4a2 2 0 1 0-4 0v2",key:"1of5e8"}],["rect",{width:"8",height:"5",x:"14",y:"6",rx:"1",key:"1fmf51"}]]);/** * @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 ld=te("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 See=te("Goal",[["path",{d:"M12 13V2l8 4-8 4",key:"5wlwwj"}],["path",{d:"M20.561 10.222a9 9 0 1 1-12.55-5.29",key:"1c0wjv"}],["path",{d:"M8.002 9.997a5 5 0 1 0 8.9 2.02",key:"gb1g7m"}]]);/** * @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 Cee=te("Grab",[["path",{d:"M18 11.5V9a2 2 0 0 0-2-2a2 2 0 0 0-2 2v1.4",key:"edstyy"}],["path",{d:"M14 10V8a2 2 0 0 0-2-2a2 2 0 0 0-2 2v2",key:"19wdwo"}],["path",{d:"M10 9.9V9a2 2 0 0 0-2-2a2 2 0 0 0-2 2v5",key:"1lugqo"}],["path",{d:"M6 14a2 2 0 0 0-2-2a2 2 0 0 0-2 2",key:"1hbeus"}],["path",{d:"M18 11a2 2 0 1 1 4 0v3a8 8 0 0 1-8 8h-4a8 8 0 0 1-8-8 2 2 0 1 1 4 0",key:"1etffm"}]]);/** * @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=te("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 Tee=te("Grape",[["path",{d:"M22 5V2l-5.89 5.89",key:"1eenpo"}],["circle",{cx:"16.6",cy:"15.89",r:"3",key:"xjtalx"}],["circle",{cx:"8.11",cy:"7.4",r:"3",key:"u2fv6i"}],["circle",{cx:"12.35",cy:"11.65",r:"3",key:"i6i8g7"}],["circle",{cx:"13.91",cy:"5.85",r:"3",key:"6ye0dv"}],["circle",{cx:"18.15",cy:"10.09",r:"3",key:"snx9no"}],["circle",{cx:"6.56",cy:"13.2",r:"3",key:"17x4xg"}],["circle",{cx:"10.8",cy:"17.44",r:"3",key:"1hogw9"}],["circle",{cx:"5",cy:"19",r:"3",key:"1sn6vo"}]]);/** * @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 Eee=te("Grid2x2Check",[["path",{d:"M12 3v17a1 1 0 0 1-1 1H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v6a1 1 0 0 1-1 1H3",key:"11za1p"}],["path",{d:"m16 19 2 2 4-4",key:"1b14m6"}]]);/** * @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 M3=te("Grid2x2Plus",[["path",{d:"M12 3v17a1 1 0 0 1-1 1H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v6a1 1 0 0 1-1 1H3",key:"11za1p"}],["path",{d:"M16 19h6",key:"xwg31i"}],["path",{d:"M19 22v-6",key:"qhmiwi"}]]);/** * @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 Aee=te("Grid2x2X",[["path",{d:"M12 3v17a1 1 0 0 1-1 1H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v6a1 1 0 0 1-1 1H3",key:"11za1p"}],["path",{d:"m16 16 5 5",key:"8tpb07"}],["path",{d:"m16 21 5-5",key:"193jll"}]]);/** * @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 I3=te("Grid2x2",[["path",{d:"M12 3v18",key:"108xh3"}],["path",{d:"M3 12h18",key:"1i2n21"}],["rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",key:"h1oib"}]]);/** * @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 by=te("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 Mee=te("GripHorizontal",[["circle",{cx:"12",cy:"9",r:"1",key:"124mty"}],["circle",{cx:"19",cy:"9",r:"1",key:"1ruzo2"}],["circle",{cx:"5",cy:"9",r:"1",key:"1a8b28"}],["circle",{cx:"12",cy:"15",r:"1",key:"1e56xg"}],["circle",{cx:"19",cy:"15",r:"1",key:"1a92ep"}],["circle",{cx:"5",cy:"15",r:"1",key:"5r1jwy"}]]);/** * @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 Oh=te("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 Iee=te("Grip",[["circle",{cx:"12",cy:"5",r:"1",key:"gxeob9"}],["circle",{cx:"19",cy:"5",r:"1",key:"w8mnmm"}],["circle",{cx:"5",cy:"5",r:"1",key:"lttvr7"}],["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"}],["circle",{cx:"12",cy:"19",r:"1",key:"lyex9k"}],["circle",{cx:"19",cy:"19",r:"1",key:"shf9b7"}],["circle",{cx:"5",cy:"19",r:"1",key:"bfqh0e"}]]);/** * @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 Pee=te("Group",[["path",{d:"M3 7V5c0-1.1.9-2 2-2h2",key:"adw53z"}],["path",{d:"M17 3h2c1.1 0 2 .9 2 2v2",key:"an4l38"}],["path",{d:"M21 17v2c0 1.1-.9 2-2 2h-2",key:"144t0e"}],["path",{d:"M7 21H5c-1.1 0-2-.9-2-2v-2",key:"rtnfgi"}],["rect",{width:"7",height:"5",x:"7",y:"7",rx:"1",key:"1eyiv7"}],["rect",{width:"7",height:"5",x:"10",y:"12",rx:"1",key:"1qlmkx"}]]);/** * @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 Lee=te("Guitar",[["path",{d:"m11.9 12.1 4.514-4.514",key:"109xqo"}],["path",{d:"M20.1 2.3a1 1 0 0 0-1.4 0l-1.114 1.114A2 2 0 0 0 17 4.828v1.344a2 2 0 0 1-.586 1.414A2 2 0 0 1 17.828 7h1.344a2 2 0 0 0 1.414-.586L21.7 5.3a1 1 0 0 0 0-1.4z",key:"txyc8t"}],["path",{d:"m6 16 2 2",key:"16qmzd"}],["path",{d:"M8.2 9.9C8.7 8.8 9.8 8 11 8c2.8 0 5 2.2 5 5 0 1.2-.8 2.3-1.9 2.8l-.9.4A2 2 0 0 0 12 18a4 4 0 0 1-4 4c-3.3 0-6-2.7-6-6a4 4 0 0 1 4-4 2 2 0 0 0 1.8-1.2z",key:"1u8q3z"}],["circle",{cx:"11.5",cy:"12.5",r:".5",fill:"currentColor",key:"16onso"}]]);/** * @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 Dee=te("Ham",[["path",{d:"M13.144 21.144A7.274 10.445 45 1 0 2.856 10.856",key:"1k1t7q"}],["path",{d:"M13.144 21.144A7.274 4.365 45 0 0 2.856 10.856a7.274 4.365 45 0 0 10.288 10.288",key:"153t1g"}],["path",{d:"M16.565 10.435 18.6 8.4a2.501 2.501 0 1 0 1.65-4.65 2.5 2.5 0 1 0-4.66 1.66l-2.024 2.025",key:"gzrt0n"}],["path",{d:"m8.5 16.5-1-1",key:"otr954"}]]);/** * @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 uF=te("Hammer",[["path",{d:"m15 12-8.373 8.373a1 1 0 1 1-3-3L12 9",key:"eefl8a"}],["path",{d:"m18 15 4-4",key:"16gjal"}],["path",{d:"m21.5 11.5-1.914-1.914A2 2 0 0 1 19 8.172V7l-2.26-2.26a6 6 0 0 0-4.202-1.756L9 2.96l.92.82A6.18 6.18 0 0 1 12 8.4V10l2 2h1.172a2 2 0 0 1 1.414.586L18.5 14.5",key:"b7pghm"}]]);/** * @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 Ree=te("HandCoins",[["path",{d:"M11 15h2a2 2 0 1 0 0-4h-3c-.6 0-1.1.2-1.4.6L3 17",key:"geh8rc"}],["path",{d:"m7 21 1.6-1.4c.3-.4.8-.6 1.4-.6h4c1.1 0 2.1-.4 2.8-1.2l4.6-4.4a2 2 0 0 0-2.75-2.91l-4.2 3.9",key:"1fto5m"}],["path",{d:"m2 16 6 6",key:"1pfhp9"}],["circle",{cx:"16",cy:"9",r:"2.9",key:"1n0dlu"}],["circle",{cx:"6",cy:"5",r:"3",key:"151irh"}]]);/** * @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 Oee=te("HandHeart",[["path",{d:"M11 14h2a2 2 0 1 0 0-4h-3c-.6 0-1.1.2-1.4.6L3 16",key:"1ifwr1"}],["path",{d:"m7 20 1.6-1.4c.3-.4.8-.6 1.4-.6h4c1.1 0 2.1-.4 2.8-1.2l4.6-4.4a2 2 0 0 0-2.75-2.91l-4.2 3.9",key:"17abbs"}],["path",{d:"m2 15 6 6",key:"10dquu"}],["path",{d:"M19.5 8.5c.7-.7 1.5-1.6 1.5-2.7A2.73 2.73 0 0 0 16 4a2.78 2.78 0 0 0-5 1.8c0 1.2.8 2 1.5 2.8L16 12Z",key:"1h3036"}]]);/** * @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=te("HandHelping",[["path",{d:"M11 12h2a2 2 0 1 0 0-4h-3c-.6 0-1.1.2-1.4.6L3 14",key:"1j4xps"}],["path",{d:"m7 18 1.6-1.4c.3-.4.8-.6 1.4-.6h4c1.1 0 2.1-.4 2.8-1.2l4.6-4.4a2 2 0 0 0-2.75-2.91l-4.2 3.9",key:"uospg8"}],["path",{d:"m2 13 6 6",key:"16e5sb"}]]);/** * @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 Fee=te("HandMetal",[["path",{d:"M18 12.5V10a2 2 0 0 0-2-2a2 2 0 0 0-2 2v1.4",key:"wc6myp"}],["path",{d:"M14 11V9a2 2 0 1 0-4 0v2",key:"94qvcw"}],["path",{d:"M10 10.5V5a2 2 0 1 0-4 0v9",key:"m1ah89"}],["path",{d:"m7 15-1.76-1.76a2 2 0 0 0-2.83 2.82l3.6 3.6C7.5 21.14 9.2 22 12 22h2a8 8 0 0 0 8-8V7a2 2 0 1 0-4 0v5",key:"t1skq1"}]]);/** * @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 Bee=te("HandPlatter",[["path",{d:"M12 3V2",key:"ar7q03"}],["path",{d:"m15.4 17.4 3.2-2.8a2 2 0 1 1 2.8 2.9l-3.6 3.3c-.7.8-1.7 1.2-2.8 1.2h-4c-1.1 0-2.1-.4-2.8-1.2l-1.302-1.464A1 1 0 0 0 6.151 19H5",key:"n2g93r"}],["path",{d:"M2 14h12a2 2 0 0 1 0 4h-2",key:"1o2jem"}],["path",{d:"M4 10h16",key:"img6z1"}],["path",{d:"M5 10a7 7 0 0 1 14 0",key:"1ega1o"}],["path",{d:"M5 14v6a1 1 0 0 1-1 1H2",key:"1hescx"}]]);/** * @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 hF=te("Hand",[["path",{d:"M18 11V6a2 2 0 0 0-2-2a2 2 0 0 0-2 2",key:"1fvzgz"}],["path",{d:"M14 10V4a2 2 0 0 0-2-2a2 2 0 0 0-2 2v2",key:"1kc0my"}],["path",{d:"M10 10.5V6a2 2 0 0 0-2-2a2 2 0 0 0-2 2v8",key:"10h0bg"}],["path",{d:"M18 8a2 2 0 1 1 4 0v6a8 8 0 0 1-8 8h-2c-2.8 0-4.5-.86-5.99-2.34l-3.6-3.6a2 2 0 0 1 2.83-2.82L7 15",key:"1s1gnw"}]]);/** * @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 zk=te("Handshake",[["path",{d:"m11 17 2 2a1 1 0 1 0 3-3",key:"efffak"}],["path",{d:"m14 14 2.5 2.5a1 1 0 1 0 3-3l-3.88-3.88a3 3 0 0 0-4.24 0l-.88.88a1 1 0 1 1-3-3l2.81-2.81a5.79 5.79 0 0 1 7.06-.87l.47.28a2 2 0 0 0 1.42.25L21 4",key:"9pr0kb"}],["path",{d:"m21 3 1 11h-2",key:"1tisrp"}],["path",{d:"M3 3 2 14l6.5 6.5a1 1 0 1 0 3-3",key:"1uvwmv"}],["path",{d:"M3 4h8",key:"1ep09j"}]]);/** * @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 zee=te("HardDriveDownload",[["path",{d:"M12 2v8",key:"1q4o3n"}],["path",{d:"m16 6-4 4-4-4",key:"6wukr"}],["rect",{width:"20",height:"8",x:"2",y:"14",rx:"2",key:"w68u3i"}],["path",{d:"M6 18h.01",key:"uhywen"}],["path",{d:"M10 18h.01",key:"h775k"}]]);/** * @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 $ee=te("HardDriveUpload",[["path",{d:"m16 6-4-4-4 4",key:"13yo43"}],["path",{d:"M12 2v8",key:"1q4o3n"}],["rect",{width:"20",height:"8",x:"2",y:"14",rx:"2",key:"w68u3i"}],["path",{d:"M6 18h.01",key:"uhywen"}],["path",{d:"M10 18h.01",key:"h775k"}]]);/** * @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 mF=te("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 Uee=te("HardHat",[["path",{d:"M10 10V5a1 1 0 0 1 1-1h2a1 1 0 0 1 1 1v5",key:"1p9q5i"}],["path",{d:"M14 6a6 6 0 0 1 6 6v3",key:"1hnv84"}],["path",{d:"M4 15v-3a6 6 0 0 1 6-6",key:"9ciidu"}],["rect",{x:"2",y:"15",width:"20",height:"4",rx:"1",key:"g3x8cw"}]]);/** * @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 $k=te("Hash",[["line",{x1:"4",x2:"20",y1:"9",y2:"9",key:"4lhtct"}],["line",{x1:"4",x2:"20",y1:"15",y2:"15",key:"vyu0kd"}],["line",{x1:"10",x2:"8",y1:"3",y2:"21",key:"1ggp8o"}],["line",{x1:"16",x2:"14",y1:"3",y2:"21",key:"weycgp"}]]);/** * @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 qee=te("Haze",[["path",{d:"m5.2 6.2 1.4 1.4",key:"17imol"}],["path",{d:"M2 13h2",key:"13gyu8"}],["path",{d:"M20 13h2",key:"16rner"}],["path",{d:"m17.4 7.6 1.4-1.4",key:"t4xlah"}],["path",{d:"M22 17H2",key:"1gtaj3"}],["path",{d:"M22 21H2",key:"1gy6en"}],["path",{d:"M16 13a4 4 0 0 0-8 0",key:"1dyczq"}],["path",{d:"M12 5V2.5",key:"1vytko"}]]);/** * @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 Vee=te("HdmiPort",[["path",{d:"M22 9a1 1 0 0 0-1-1H3a1 1 0 0 0-1 1v4a1 1 0 0 0 1 1h1l2 2h12l2-2h1a1 1 0 0 0 1-1Z",key:"2128wb"}],["path",{d:"M7.5 12h9",key:"1t0ckc"}]]);/** * @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=te("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 FI=te("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 fF=te("Heading3",[["path",{d:"M4 12h8",key:"17cfdx"}],["path",{d:"M4 18V6",key:"1rz3zl"}],["path",{d:"M12 18V6",key:"zqpxq5"}],["path",{d:"M17.5 10.5c1.7-1 3.5 0 3.5 1.5a2 2 0 0 1-2 2",key:"68ncm8"}],["path",{d:"M17 17.5c2 1.5 4 .3 4-1.5a2 2 0 0 0-2-2",key:"1ejuhz"}]]);/** * @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 Hee=te("Heading4",[["path",{d:"M12 18V6",key:"zqpxq5"}],["path",{d:"M17 10v3a1 1 0 0 0 1 1h3",key:"tj5zdr"}],["path",{d:"M21 10v8",key:"1kdml4"}],["path",{d:"M4 12h8",key:"17cfdx"}],["path",{d:"M4 18V6",key:"1rz3zl"}]]);/** * @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 Gee=te("Heading5",[["path",{d:"M4 12h8",key:"17cfdx"}],["path",{d:"M4 18V6",key:"1rz3zl"}],["path",{d:"M12 18V6",key:"zqpxq5"}],["path",{d:"M17 13v-3h4",key:"1nvgqp"}],["path",{d:"M17 17.7c.4.2.8.3 1.3.3 1.5 0 2.7-1.1 2.7-2.5S19.8 13 18.3 13H17",key:"2nebdn"}]]);/** * @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 Wee=te("Heading6",[["path",{d:"M4 12h8",key:"17cfdx"}],["path",{d:"M4 18V6",key:"1rz3zl"}],["path",{d:"M12 18V6",key:"zqpxq5"}],["circle",{cx:"19",cy:"16",r:"2",key:"15mx69"}],["path",{d:"M20 10c-2 2-3 3.5-3 6",key:"f35dl0"}]]);/** * @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 Kee=te("Heading",[["path",{d:"M6 12h12",key:"8npq4p"}],["path",{d:"M6 20V4",key:"1w1bmo"}],["path",{d:"M18 20V4",key:"o2hl4u"}]]);/** * @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 Yee=te("HeadphoneOff",[["path",{d:"M21 14h-1.343",key:"1jdnxi"}],["path",{d:"M9.128 3.47A9 9 0 0 1 21 12v3.343",key:"6kipu2"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M20.414 20.414A2 2 0 0 1 19 21h-1a2 2 0 0 1-2-2v-3",key:"9x50f4"}],["path",{d:"M3 14h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-7a9 9 0 0 1 2.636-6.364",key:"1bkxnm"}]]);/** * @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 Zee=te("Headphones",[["path",{d:"M3 14h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-7a9 9 0 0 1 18 0v7a2 2 0 0 1-2 2h-1a2 2 0 0 1-2-2v-3a2 2 0 0 1 2-2h3",key:"1xhozi"}]]);/** * @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 Xee=te("Headset",[["path",{d:"M3 11h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-5Zm0 0a9 9 0 1 1 18 0m0 0v5a2 2 0 0 1-2 2h-1a2 2 0 0 1-2-2v-3a2 2 0 0 1 2-2h3Z",key:"12oyoe"}],["path",{d:"M21 16v2a4 4 0 0 1-4 4h-5",key:"1x7m43"}]]);/** * @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 Qee=te("HeartCrack",[["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"}],["path",{d:"m12 13-1-1 2-2-3-3 2-2",key:"xjdxli"}]]);/** * @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 Jee=te("HeartHandshake",[["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"}],["path",{d:"M12 5 9.04 7.96a2.17 2.17 0 0 0 0 3.08c.82.82 2.13.85 3 .07l2.07-1.9a2.82 2.82 0 0 1 3.79 0l2.96 2.66",key:"4oyue0"}],["path",{d:"m18 15-2-2",key:"60u0ii"}],["path",{d:"m15 18-2-2",key:"6p76be"}]]);/** * @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 ete=te("HeartOff",[["line",{x1:"2",y1:"2",x2:"22",y2:"22",key:"1w4vcy"}],["path",{d:"M16.5 16.5 12 21l-7-7c-1.5-1.45-3-3.2-3-5.5a5.5 5.5 0 0 1 2.14-4.35",key:"3mpagl"}],["path",{d:"M8.76 3.1c1.15.22 2.13.78 3.24 1.9 1.5-1.5 2.74-2 4.5-2A5.5 5.5 0 0 1 22 8.5c0 2.12-1.3 3.78-2.67 5.17",key:"1gh3v3"}]]);/** * @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 tte=te("HeartPulse",[["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"}],["path",{d:"M3.22 12H9.5l.5-1 2 4.5 2-7 1.5 3.5h5.27",key:"1uw2ng"}]]);/** * @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 Bi=te("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 ste=te("Heater",[["path",{d:"M11 8c2-3-2-3 0-6",key:"1ldv5m"}],["path",{d:"M15.5 8c2-3-2-3 0-6",key:"1otqoz"}],["path",{d:"M6 10h.01",key:"1lbq93"}],["path",{d:"M6 14h.01",key:"zudwn7"}],["path",{d:"M10 16v-4",key:"1c25yv"}],["path",{d:"M14 16v-4",key:"1dkbt8"}],["path",{d:"M18 16v-4",key:"1yg9me"}],["path",{d:"M20 6a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h3",key:"1ubg90"}],["path",{d:"M5 20v2",key:"1abpe8"}],["path",{d:"M19 20v2",key:"kqn6ft"}]]);/** * @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 rte=te("Hexagon",[["path",{d:"M21 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.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z",key:"yt0hxn"}]]);/** * @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 nte=te("Highlighter",[["path",{d:"m9 11-6 6v3h9l3-3",key:"1a3l36"}],["path",{d:"m22 12-4.6 4.6a2 2 0 0 1-2.8 0l-5.2-5.2a2 2 0 0 1 0-2.8L14 4",key:"14a9rk"}]]);/** * @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 BI=te("History",[["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"}],["path",{d:"M12 7v5l4 2",key:"1fdv2h"}]]);/** * @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 ate=te("HopOff",[["path",{d:"M10.82 16.12c1.69.6 3.91.79 5.18.85.28.01.53-.09.7-.27",key:"qyzcap"}],["path",{d:"M11.14 20.57c.52.24 2.44 1.12 4.08 1.37.46.06.86-.25.9-.71.12-1.52-.3-3.43-.5-4.28",key:"y078lb"}],["path",{d:"M16.13 21.05c1.65.63 3.68.84 4.87.91a.9.9 0 0 0 .7-.26",key:"1utre3"}],["path",{d:"M17.99 5.52a20.83 20.83 0 0 1 3.15 4.5.8.8 0 0 1-.68 1.13c-1.17.1-2.5.02-3.9-.25",key:"17o9hm"}],["path",{d:"M20.57 11.14c.24.52 1.12 2.44 1.37 4.08.04.3-.08.59-.31.75",key:"1d1n4p"}],["path",{d:"M4.93 4.93a10 10 0 0 0-.67 13.4c.35.43.96.4 1.17-.12.69-1.71 1.07-5.07 1.07-6.71 1.34.45 3.1.9 4.88.62a.85.85 0 0 0 .48-.24",key:"9uv3tt"}],["path",{d:"M5.52 17.99c1.05.95 2.91 2.42 4.5 3.15a.8.8 0 0 0 1.13-.68c.2-2.34-.33-5.3-1.57-8.28",key:"1292wz"}],["path",{d:"M8.35 2.68a10 10 0 0 1 9.98 1.58c.43.35.4.96-.12 1.17-1.5.6-4.3.98-6.07 1.05",key:"7ozu9p"}],["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 ite=te("Hop",[["path",{d:"M10.82 16.12c1.69.6 3.91.79 5.18.85.55.03 1-.42.97-.97-.06-1.27-.26-3.5-.85-5.18",key:"18lxf1"}],["path",{d:"M11.5 6.5c1.64 0 5-.38 6.71-1.07.52-.2.55-.82.12-1.17A10 10 0 0 0 4.26 18.33c.35.43.96.4 1.17-.12.69-1.71 1.07-5.07 1.07-6.71 1.34.45 3.1.9 4.88.62a.88.88 0 0 0 .73-.74c.3-2.14-.15-3.5-.61-4.88",key:"vtfxrw"}],["path",{d:"M15.62 16.95c.2.85.62 2.76.5 4.28a.77.77 0 0 1-.9.7 16.64 16.64 0 0 1-4.08-1.36",key:"13hl71"}],["path",{d:"M16.13 21.05c1.65.63 3.68.84 4.87.91a.9.9 0 0 0 .96-.96 17.68 17.68 0 0 0-.9-4.87",key:"1sl8oj"}],["path",{d:"M16.94 15.62c.86.2 2.77.62 4.29.5a.77.77 0 0 0 .7-.9 16.64 16.64 0 0 0-1.36-4.08",key:"19c6kt"}],["path",{d:"M17.99 5.52a20.82 20.82 0 0 1 3.15 4.5.8.8 0 0 1-.68 1.13c-2.33.2-5.3-.32-8.27-1.57",key:"85ghs3"}],["path",{d:"M4.93 4.93 3 3a.7.7 0 0 1 0-1",key:"x087yj"}],["path",{d:"M9.58 12.18c1.24 2.98 1.77 5.95 1.57 8.28a.8.8 0 0 1-1.13.68 20.82 20.82 0 0 1-4.5-3.15",key:"11xdqo"}]]);/** * @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 ote=te("Hospital",[["path",{d:"M12 6v4",key:"16clxf"}],["path",{d:"M14 14h-4",key:"esezmu"}],["path",{d:"M14 18h-4",key:"16mqa2"}],["path",{d:"M14 8h-4",key:"z8ypaz"}],["path",{d:"M18 12h2a2 2 0 0 1 2 2v6a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2v-9a2 2 0 0 1 2-2h2",key:"b1k337"}],["path",{d:"M18 22V4a2 2 0 0 0-2-2H8a2 2 0 0 0-2 2v18",key:"16g51d"}]]);/** * @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 lte=te("Hotel",[["path",{d:"M10 22v-6.57",key:"1wmca3"}],["path",{d:"M12 11h.01",key:"z322tv"}],["path",{d:"M12 7h.01",key:"1ivr5q"}],["path",{d:"M14 15.43V22",key:"1q2vjd"}],["path",{d:"M15 16a5 5 0 0 0-6 0",key:"o9wqvi"}],["path",{d:"M16 11h.01",key:"xkw8gn"}],["path",{d:"M16 7h.01",key:"1kdx03"}],["path",{d:"M8 11h.01",key:"1dfujw"}],["path",{d:"M8 7h.01",key:"1vti4s"}],["rect",{x:"4",y:"2",width:"16",height:"20",rx:"2",key:"1uxh74"}]]);/** * @license lucide-react v0.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 cte=te("Hourglass",[["path",{d:"M5 22h14",key:"ehvnwv"}],["path",{d:"M5 2h14",key:"pdyrp9"}],["path",{d:"M17 22v-4.172a2 2 0 0 0-.586-1.414L12 12l-4.414 4.414A2 2 0 0 0 7 17.828V22",key:"1d314k"}],["path",{d:"M7 2v4.172a2 2 0 0 0 .586 1.414L12 12l4.414-4.414A2 2 0 0 0 17 6.172V2",key:"1vvvr6"}]]);/** * @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 dte=te("HousePlug",[["path",{d:"M10 12V8.964",key:"1vll13"}],["path",{d:"M14 12V8.964",key:"1x3qvg"}],["path",{d:"M15 12a1 1 0 0 1 1 1v2a2 2 0 0 1-2 2h-4a2 2 0 0 1-2-2v-2a1 1 0 0 1 1-1z",key:"ppykja"}],["path",{d:"M8.5 21H5a2 2 0 0 1-2-2v-9a2 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 2h-5a2 2 0 0 1-2-2v-2",key:"1gvg2z"}]]);/** * @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 ute=te("HousePlus",[["path",{d:"M13.22 2.416a2 2 0 0 0-2.511.057l-7 5.999A2 2 0 0 0 3 10v9a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7.354",key:"5phn05"}],["path",{d:"M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8",key:"5wwlr5"}],["path",{d:"M15 6h6",key:"1jlkvy"}],["path",{d:"M18 3v6",key:"x1uolp"}]]);/** * @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 Fn=te("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 P3=te("IceCreamBowl",[["path",{d:"M12 17c5 0 8-2.69 8-6H4c0 3.31 3 6 8 6m-4 4h8m-4-3v3M5.14 11a3.5 3.5 0 1 1 6.71 0",key:"1uxfcu"}],["path",{d:"M12.14 11a3.5 3.5 0 1 1 6.71 0",key:"4k3m1s"}],["path",{d:"M15.5 6.5a3.5 3.5 0 1 0-7 0",key:"zmuahr"}]]);/** * @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 L3=te("IceCreamCone",[["path",{d:"m7 11 4.08 10.35a1 1 0 0 0 1.84 0L17 11",key:"1v6356"}],["path",{d:"M17 7A5 5 0 0 0 7 7",key:"151p3v"}],["path",{d:"M17 7a2 2 0 0 1 0 4H7a2 2 0 0 1 0-4",key:"1sdaij"}]]);/** * @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 hte=te("IdCard",[["path",{d:"M16 10h2",key:"8sgtl7"}],["path",{d:"M16 14h2",key:"epxaof"}],["path",{d:"M6.17 15a3 3 0 0 1 5.66 0",key:"n6f512"}],["circle",{cx:"9",cy:"11",r:"2",key:"yxgjnd"}],["rect",{x:"2",y:"5",width:"20",height:"14",rx:"2",key:"qneu4z"}]]);/** * @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 mte=te("ImageDown",[["path",{d:"M10.3 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v10l-3.1-3.1a2 2 0 0 0-2.814.014L6 21",key:"9csbqa"}],["path",{d:"m14 19 3 3v-5.5",key:"9ldu5r"}],["path",{d:"m17 22 3-3",key:"1nkfve"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}]]);/** * @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 fte=te("ImageMinus",[["path",{d:"M21 9v10a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7",key:"m87ecr"}],["line",{x1:"16",x2:"22",y1:"5",y2:"5",key:"ez7e4s"}],["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 pte=te("ImageOff",[["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}],["path",{d:"M10.41 10.41a2 2 0 1 1-2.83-2.83",key:"1bzlo9"}],["line",{x1:"13.5",x2:"6",y1:"13.5",y2:"21",key:"1q0aeu"}],["line",{x1:"18",x2:"21",y1:"12",y2:"15",key:"5mozeu"}],["path",{d:"M3.59 3.59A1.99 1.99 0 0 0 3 5v14a2 2 0 0 0 2 2h14c.55 0 1.052-.22 1.41-.59",key:"mmje98"}],["path",{d:"M21 15V5a2 2 0 0 0-2-2H9",key:"43el77"}]]);/** * @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 gte=te("ImagePlay",[["path",{d:"m11 16-5 5",key:"j5f7ct"}],["path",{d:"M11 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v6.5",key:"7s81lt"}],["path",{d:"M15.765 22a.5.5 0 0 1-.765-.424V13.38a.5.5 0 0 1 .765-.424l5.878 3.674a1 1 0 0 1 0 1.696z",key:"1omb6s"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}]]);/** * @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 f_=te("ImagePlus",[["path",{d:"M16 5h6",key:"1vod17"}],["path",{d:"M19 2v6",key:"4bpg5p"}],["path",{d:"M21 11.5V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7.5",key:"1ue2ih"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}]]);/** * @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 xte=te("ImageUp",[["path",{d:"M10.3 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v10l-3.1-3.1a2 2 0 0 0-2.814.014L6 21",key:"9csbqa"}],["path",{d:"m14 19.5 3-3 3 3",key:"9vmjn0"}],["path",{d:"M17 22v-5.5",key:"1aa6fl"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}]]);/** * @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 yte=te("ImageUpscale",[["path",{d:"M16 3h5v5",key:"1806ms"}],["path",{d:"M17 21h2a2 2 0 0 0 2-2",key:"130fy9"}],["path",{d:"M21 12v3",key:"1wzk3p"}],["path",{d:"m21 3-5 5",key:"1g5oa7"}],["path",{d:"M3 7V5a2 2 0 0 1 2-2",key:"kk3yz1"}],["path",{d:"m5 21 4.144-4.144a1.21 1.21 0 0 1 1.712 0L13 19",key:"fyekpt"}],["path",{d:"M9 3h3",key:"d52fa"}],["rect",{x:"3",y:"11",width:"10",height:"10",rx:"1",key:"1wpmix"}]]);/** * @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 wl=te("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 vte=te("Images",[["path",{d:"M18 22H4a2 2 0 0 1-2-2V6",key:"pblm9e"}],["path",{d:"m22 13-1.296-1.296a2.41 2.41 0 0 0-3.408 0L11 18",key:"nf6bnh"}],["circle",{cx:"12",cy:"8",r:"2",key:"1822b1"}],["rect",{width:"16",height:"16",x:"6",y:"2",rx:"2",key:"12espp"}]]);/** * @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 bte=te("Import",[["path",{d:"M12 3v12",key:"1x0j5s"}],["path",{d:"m8 11 4 4 4-4",key:"1dohi6"}],["path",{d:"M8 5H4a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2h-4",key:"1ywtjm"}]]);/** * @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 Uk=te("Inbox",[["polyline",{points:"22 12 16 12 14 15 10 15 8 12 2 12",key:"o97t9d"}],["path",{d:"M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z",key:"oot6mr"}]]);/** * @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 D3=te("IndentDecrease",[["path",{d:"M21 12H11",key:"wd7e0v"}],["path",{d:"M21 18H11",key:"4wu86t"}],["path",{d:"M21 6H11",key:"6dy1d6"}],["path",{d:"m7 8-4 4 4 4",key:"o5hrat"}]]);/** * @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 R3=te("IndentIncrease",[["path",{d:"M21 12H11",key:"wd7e0v"}],["path",{d:"M21 18H11",key:"4wu86t"}],["path",{d:"M21 6H11",key:"6dy1d6"}],["path",{d:"m3 8 4 4-4 4",key:"1a3j6y"}]]);/** * @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 _te=te("IndianRupee",[["path",{d:"M6 3h12",key:"ggurg9"}],["path",{d:"M6 8h12",key:"6g4wlu"}],["path",{d:"m6 13 8.5 8",key:"u1kupk"}],["path",{d:"M6 13h3",key:"wdp6ag"}],["path",{d:"M9 13c6.667 0 6.667-10 0-10",key:"1nkvk2"}]]);/** * @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 wte=te("Infinity",[["path",{d:"M12 12c-2-2.67-4-4-6-4a4 4 0 1 0 0 8c2 0 4-1.33 6-4Zm0 0c2 2.67 4 4 6 4a4 4 0 0 0 0-8c-2 0-4 1.33-6 4Z",key:"1z0uae"}]]);/** * @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 bE=te("Info",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]]);/** * @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 jte=te("InspectionPanel",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M7 7h.01",key:"7u93v4"}],["path",{d:"M17 7h.01",key:"14a9sn"}],["path",{d:"M7 17h.01",key:"19xn7k"}],["path",{d:"M17 17h.01",key:"1sd3ek"}]]);/** * @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 yu=te("Instagram",[["rect",{width:"20",height:"20",x:"2",y:"2",rx:"5",ry:"5",key:"2e1cvw"}],["path",{d:"M16 11.37A4 4 0 1 1 12.63 8 4 4 0 0 1 16 11.37z",key:"9exkf1"}],["line",{x1:"17.5",x2:"17.51",y1:"6.5",y2:"6.5",key:"r4j83e"}]]);/** * @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 qk=te("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 Nte=te("IterationCcw",[["path",{d:"M20 10c0-4.4-3.6-8-8-8s-8 3.6-8 8 3.6 8 8 8h8",key:"4znkd0"}],["polyline",{points:"16 14 20 18 16 22",key:"11njsm"}]]);/** * @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 kte=te("IterationCw",[["path",{d:"M4 10c0-4.4 3.6-8 8-8s8 3.6 8 8-3.6 8-8 8H4",key:"tuf4su"}],["polyline",{points:"8 22 4 18 8 14",key:"evkj9s"}]]);/** * @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 Ste=te("JapaneseYen",[["path",{d:"M12 9.5V21m0-11.5L6 3m6 6.5L18 3",key:"2ej80x"}],["path",{d:"M6 15h12",key:"1hwgt5"}],["path",{d:"M6 11h12",key:"wf4gp6"}]]);/** * @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 Cte=te("Joystick",[["path",{d:"M21 17a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v2a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-2Z",key:"jg2n2t"}],["path",{d:"M6 15v-2",key:"gd6mvg"}],["path",{d:"M12 15V9",key:"8c7uyn"}],["circle",{cx:"12",cy:"6",r:"3",key:"1gm2ql"}]]);/** * @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_=te("Kanban",[["path",{d:"M6 5v11",key:"mdvv1e"}],["path",{d:"M12 5v6",key:"14ar3b"}],["path",{d:"M18 5v14",key:"7ji314"}]]);/** * @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=te("KeyRound",[["path",{d:"M2.586 17.414A2 2 0 0 0 2 18.828V21a1 1 0 0 0 1 1h3a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h1a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h.172a2 2 0 0 0 1.414-.586l.814-.814a6.5 6.5 0 1 0-4-4z",key:"1s6t7t"}],["circle",{cx:"16.5",cy:"7.5",r:".5",fill:"currentColor",key:"w0ekpg"}]]);/** * @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 Tte=te("KeySquare",[["path",{d:"M12.4 2.7a2.5 2.5 0 0 1 3.4 0l5.5 5.5a2.5 2.5 0 0 1 0 3.4l-3.7 3.7a2.5 2.5 0 0 1-3.4 0L8.7 9.8a2.5 2.5 0 0 1 0-3.4z",key:"165ttr"}],["path",{d:"m14 7 3 3",key:"1r5n42"}],["path",{d:"m9.4 10.6-6.814 6.814A2 2 0 0 0 2 18.828V21a1 1 0 0 0 1 1h3a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h1a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h.172a2 2 0 0 0 1.414-.586l.814-.814",key:"1ubxi2"}]]);/** * @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 dx=te("Key",[["path",{d:"m15.5 7.5 2.3 2.3a1 1 0 0 0 1.4 0l2.1-2.1a1 1 0 0 0 0-1.4L19 4",key:"g0fldk"}],["path",{d:"m21 2-9.6 9.6",key:"1j0ho8"}],["circle",{cx:"7.5",cy:"15.5",r:"5.5",key:"yqb3hr"}]]);/** * @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 Ete=te("KeyboardMusic",[["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}],["path",{d:"M6 8h4",key:"utf9t1"}],["path",{d:"M14 8h.01",key:"1primd"}],["path",{d:"M18 8h.01",key:"emo2bl"}],["path",{d:"M2 12h20",key:"9i4pu4"}],["path",{d:"M6 12v4",key:"dy92yo"}],["path",{d:"M10 12v4",key:"1fxnav"}],["path",{d:"M14 12v4",key:"1hft58"}],["path",{d:"M18 12v4",key:"tjjnbz"}]]);/** * @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 Ate=te("KeyboardOff",[["path",{d:"M 20 4 A2 2 0 0 1 22 6",key:"1g1fkt"}],["path",{d:"M 22 6 L 22 16.41",key:"1qjg3w"}],["path",{d:"M 7 16 L 16 16",key:"n0yqwb"}],["path",{d:"M 9.69 4 L 20 4",key:"kbpcgx"}],["path",{d:"M14 8h.01",key:"1primd"}],["path",{d:"M18 8h.01",key:"emo2bl"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M20 20H4a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2",key:"s23sx2"}],["path",{d:"M6 8h.01",key:"x9i8wu"}],["path",{d:"M8 12h.01",key:"czm47f"}]]);/** * @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 Mte=te("Keyboard",[["path",{d:"M10 8h.01",key:"1r9ogq"}],["path",{d:"M12 12h.01",key:"1mp3jc"}],["path",{d:"M14 8h.01",key:"1primd"}],["path",{d:"M16 12h.01",key:"1l6xoz"}],["path",{d:"M18 8h.01",key:"emo2bl"}],["path",{d:"M6 8h.01",key:"x9i8wu"}],["path",{d:"M7 16h10",key:"wp8him"}],["path",{d:"M8 12h.01",key:"czm47f"}],["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}]]);/** * @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 Ite=te("LampCeiling",[["path",{d:"M12 2v5",key:"nd4vlx"}],["path",{d:"M6 7h12l4 9H2l4-9Z",key:"123d64"}],["path",{d:"M9.17 16a3 3 0 1 0 5.66 0",key:"1061mw"}]]);/** * @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 Pte=te("LampDesk",[["path",{d:"m14 5-3 3 2 7 8-8-7-2Z",key:"1b0msb"}],["path",{d:"m14 5-3 3-3-3 3-3 3 3Z",key:"1uemms"}],["path",{d:"M9.5 6.5 4 12l3 6",key:"1bx08v"}],["path",{d:"M3 22v-2c0-1.1.9-2 2-2h4a2 2 0 0 1 2 2v2H3Z",key:"wap775"}]]);/** * @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 Lte=te("LampFloor",[["path",{d:"M9 2h6l3 7H6l3-7Z",key:"wcx6mj"}],["path",{d:"M12 9v13",key:"3n1su1"}],["path",{d:"M9 22h6",key:"1rlq3v"}]]);/** * @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 Dte=te("LampWallDown",[["path",{d:"M11 13h6l3 7H8l3-7Z",key:"9n3qlo"}],["path",{d:"M14 13V8a2 2 0 0 0-2-2H8",key:"1hu4hb"}],["path",{d:"M4 9h2a2 2 0 0 0 2-2V5a2 2 0 0 0-2-2H4v6Z",key:"s053bc"}]]);/** * @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 Rte=te("LampWallUp",[["path",{d:"M11 4h6l3 7H8l3-7Z",key:"11x1ee"}],["path",{d:"M14 11v5a2 2 0 0 1-2 2H8",key:"eutp5o"}],["path",{d:"M4 15h2a2 2 0 0 1 2 2v2a2 2 0 0 1-2 2H4v-6Z",key:"1iuthr"}]]);/** * @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 Ote=te("Lamp",[["path",{d:"M8 2h8l4 10H4L8 2Z",key:"9dma5w"}],["path",{d:"M12 12v6",key:"3ahymv"}],["path",{d:"M8 22v-2c0-1.1.9-2 2-2h4a2 2 0 0 1 2 2v2H8Z",key:"mwf4oh"}]]);/** * @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 Fte=te("LandPlot",[["path",{d:"m12 8 6-3-6-3v10",key:"mvpnpy"}],["path",{d:"m8 11.99-5.5 3.14a1 1 0 0 0 0 1.74l8.5 4.86a2 2 0 0 0 2 0l8.5-4.86a1 1 0 0 0 0-1.74L16 12",key:"ek95tt"}],["path",{d:"m6.49 12.85 11.02 6.3",key:"1kt42w"}],["path",{d:"M17.51 12.85 6.5 19.15",key:"v55bdg"}]]);/** * @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 Bte=te("Landmark",[["line",{x1:"3",x2:"21",y1:"22",y2:"22",key:"j8o0r"}],["line",{x1:"6",x2:"6",y1:"18",y2:"11",key:"10tf0k"}],["line",{x1:"10",x2:"10",y1:"18",y2:"11",key:"54lgf6"}],["line",{x1:"14",x2:"14",y1:"18",y2:"11",key:"380y"}],["line",{x1:"18",x2:"18",y1:"18",y2:"11",key:"1kevvc"}],["polygon",{points:"12 2 20 7 4 7",key:"jkujk7"}]]);/** * @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 zte=te("Languages",[["path",{d:"m5 8 6 6",key:"1wu5hv"}],["path",{d:"m4 14 6-6 2-3",key:"1k1g8d"}],["path",{d:"M2 5h12",key:"or177f"}],["path",{d:"M7 2h1",key:"1t2jsx"}],["path",{d:"m22 22-5-10-5 10",key:"don7ne"}],["path",{d:"M14 18h6",key:"1m8k6r"}]]);/** * @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 $te=te("LaptopMinimalCheck",[["path",{d:"M2 20h20",key:"owomy5"}],["path",{d:"m9 10 2 2 4-4",key:"1gnqz4"}],["rect",{x:"3",y:"4",width:"18",height:"12",rx:"2",key:"8ur36m"}]]);/** * @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 O3=te("LaptopMinimal",[["rect",{width:"18",height:"12",x:"3",y:"4",rx:"2",ry:"2",key:"1qhy41"}],["line",{x1:"2",x2:"22",y1:"20",y2:"20",key:"ni3hll"}]]);/** * @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 Ute=te("Laptop",[["path",{d:"M20 16V7a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v9m16 0H4m16 0 1.28 2.55a1 1 0 0 1-.9 1.45H3.62a1 1 0 0 1-.9-1.45L4 16",key:"tarvll"}]]);/** * @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 qte=te("LassoSelect",[["path",{d:"M7 22a5 5 0 0 1-2-4",key:"umushi"}],["path",{d:"M7 16.93c.96.43 1.96.74 2.99.91",key:"ybbtv3"}],["path",{d:"M3.34 14A6.8 6.8 0 0 1 2 10c0-4.42 4.48-8 10-8s10 3.58 10 8a7.19 7.19 0 0 1-.33 2",key:"gt5e1w"}],["path",{d:"M5 18a2 2 0 1 0 0-4 2 2 0 0 0 0 4z",key:"bq3ynw"}],["path",{d:"M14.33 22h-.09a.35.35 0 0 1-.24-.32v-10a.34.34 0 0 1 .33-.34c.08 0 .15.03.21.08l7.34 6a.33.33 0 0 1-.21.59h-4.49l-2.57 3.85a.35.35 0 0 1-.28.14z",key:"72q637"}]]);/** * @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 Vte=te("Lasso",[["path",{d:"M7 22a5 5 0 0 1-2-4",key:"umushi"}],["path",{d:"M3.3 14A6.8 6.8 0 0 1 2 10c0-4.4 4.5-8 10-8s10 3.6 10 8-4.5 8-10 8a12 12 0 0 1-5-1",key:"146dds"}],["path",{d:"M5 18a2 2 0 1 0 0-4 2 2 0 0 0 0 4z",key:"bq3ynw"}]]);/** * @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 Hte=te("Laugh",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M18 13a6 6 0 0 1-6 5 6 6 0 0 1-6-5h12Z",key:"b2q4dd"}],["line",{x1:"9",x2:"9.01",y1:"9",y2:"9",key:"yxxnd0"}],["line",{x1:"15",x2:"15.01",y1:"9",y2:"9",key:"1p4y9e"}]]);/** * @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 Gte=te("Layers2",[["path",{d:"m16.02 12 5.48 3.13a1 1 0 0 1 0 1.74L13 21.74a2 2 0 0 1-2 0l-8.5-4.87a1 1 0 0 1 0-1.74L7.98 12",key:"1cuww1"}],["path",{d:"M13 13.74a2 2 0 0 1-2 0L2.5 8.87a1 1 0 0 1 0-1.74L11 2.26a2 2 0 0 1 2 0l8.5 4.87a1 1 0 0 1 0 1.74Z",key:"pdlvxu"}]]);/** * @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 Wte=te("Layers3",[["path",{d:"m12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83Z",key:"8b97xw"}],["path",{d:"m6.08 9.5-3.5 1.6a1 1 0 0 0 0 1.81l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9a1 1 0 0 0 0-1.83l-3.5-1.59",key:"1e5n1m"}],["path",{d:"m6.08 14.5-3.5 1.6a1 1 0 0 0 0 1.81l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9a1 1 0 0 0 0-1.83l-3.5-1.59",key:"1iwflc"}]]);/** * @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 pF=te("Layers",[["path",{d:"m12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83Z",key:"8b97xw"}],["path",{d:"m22 17.65-9.17 4.16a2 2 0 0 1-1.66 0L2 17.65",key:"dd6zsq"}],["path",{d:"m22 12.65-9.17 4.16a2 2 0 0 1-1.66 0L2 12.65",key:"ep9fru"}]]);/** * @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 wE=te("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 _g=te("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 Kte=te("LayoutList",[["rect",{width:"7",height:"7",x:"3",y:"3",rx:"1",key:"1g98yp"}],["rect",{width:"7",height:"7",x:"3",y:"14",rx:"1",key:"1bb6yr"}],["path",{d:"M14 4h7",key:"3xa0d5"}],["path",{d:"M14 9h7",key:"1icrd9"}],["path",{d:"M14 15h7",key:"1mj8o2"}],["path",{d:"M14 20h7",key:"11slyb"}]]);/** * @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 Yte=te("LayoutPanelLeft",[["rect",{width:"7",height:"18",x:"3",y:"3",rx:"1",key:"2obqm"}],["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"}]]);/** * @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 Zte=te("LayoutPanelTop",[["rect",{width:"18",height:"7",x:"3",y:"3",rx:"1",key:"f1a2em"}],["rect",{width:"7",height:"7",x:"3",y:"14",rx:"1",key:"1bb6yr"}],["rect",{width:"7",height:"7",x:"14",y:"14",rx:"1",key:"nxv5o0"}]]);/** * @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 jE=te("LayoutTemplate",[["rect",{width:"18",height:"7",x:"3",y:"3",rx:"1",key:"f1a2em"}],["rect",{width:"9",height:"7",x:"3",y:"14",rx:"1",key:"jqznyg"}],["rect",{width:"5",height:"7",x:"16",y:"14",rx:"1",key:"q5h2i8"}]]);/** * @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 Xte=te("Leaf",[["path",{d:"M11 20A7 7 0 0 1 9.8 6.1C15.5 5 17 4.48 19 2c1 2 2 4.18 2 8 0 5.5-4.78 10-10 10Z",key:"nnexq3"}],["path",{d:"M2 21c0-3 1.85-5.36 5.08-6C9.5 14.52 12 13 13 12",key:"mt58a7"}]]);/** * @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 Qte=te("LeafyGreen",[["path",{d:"M2 22c1.25-.987 2.27-1.975 3.9-2.2a5.56 5.56 0 0 1 3.8 1.5 4 4 0 0 0 6.187-2.353 3.5 3.5 0 0 0 3.69-5.116A3.5 3.5 0 0 0 20.95 8 3.5 3.5 0 1 0 16 3.05a3.5 3.5 0 0 0-5.831 1.373 3.5 3.5 0 0 0-5.116 3.69 4 4 0 0 0-2.348 6.155C3.499 15.42 4.409 16.712 4.2 18.1 3.926 19.743 3.014 20.732 2 22",key:"1134nt"}],["path",{d:"M2 22 17 7",key:"1q7jp2"}]]);/** * @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 Jte=te("Lectern",[["path",{d:"M16 12h3a2 2 0 0 0 1.902-1.38l1.056-3.333A1 1 0 0 0 21 6H3a1 1 0 0 0-.958 1.287l1.056 3.334A2 2 0 0 0 5 12h3",key:"13jjxg"}],["path",{d:"M18 6V3a1 1 0 0 0-1-1h-3",key:"1550fe"}],["rect",{width:"8",height:"12",x:"8",y:"10",rx:"1",key:"qmu8b6"}]]);/** * @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 ese=te("LetterText",[["path",{d:"M15 12h6",key:"upa0zy"}],["path",{d:"M15 6h6",key:"1jlkvy"}],["path",{d:"m3 13 3.553-7.724a.5.5 0 0 1 .894 0L11 13",key:"blevx4"}],["path",{d:"M3 18h18",key:"1h113x"}],["path",{d:"M4 11h6",key:"olkgv1"}]]);/** * @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 tse=te("LibraryBig",[["rect",{width:"8",height:"18",x:"3",y:"3",rx:"1",key:"oynpb5"}],["path",{d:"M7 3v18",key:"bbkbws"}],["path",{d:"M20.4 18.9c.2.5-.1 1.1-.6 1.3l-1.9.7c-.5.2-1.1-.1-1.3-.6L11.1 5.1c-.2-.5.1-1.1.6-1.3l1.9-.7c.5-.2 1.1.1 1.3.6Z",key:"1qboyk"}]]);/** * @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 NE=te("Library",[["path",{d:"m16 6 4 14",key:"ji33uf"}],["path",{d:"M12 6v14",key:"1n7gus"}],["path",{d:"M8 8v12",key:"1gg7y9"}],["path",{d:"M4 4v16",key:"6qkkli"}]]);/** * @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 zI=te("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 sse=te("Ligature",[["path",{d:"M8 20V8c0-2.2 1.8-4 4-4 1.5 0 2.8.8 3.5 2",key:"1rtphz"}],["path",{d:"M6 12h4",key:"a4o3ry"}],["path",{d:"M14 12h2v8",key:"c1fccl"}],["path",{d:"M6 20h4",key:"1i6q5t"}],["path",{d:"M14 20h4",key:"lzx1xo"}]]);/** * @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 rse=te("LightbulbOff",[["path",{d:"M16.8 11.2c.8-.9 1.2-2 1.2-3.2a6 6 0 0 0-9.3-5",key:"1fkcox"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M6.3 6.3a4.67 4.67 0 0 0 1.2 5.2c.7.7 1.3 1.5 1.5 2.5",key:"10m8kw"}],["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 q2=te("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 nse=te("Link2Off",[["path",{d:"M9 17H7A5 5 0 0 1 7 7",key:"10o201"}],["path",{d:"M15 7h2a5 5 0 0 1 4 8",key:"1d3206"}],["line",{x1:"8",x2:"12",y1:"12",y2:"12",key:"rvw6j4"}],["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}]]);/** * @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 ql=te("Link2",[["path",{d:"M9 17H7A5 5 0 0 1 7 7h2",key:"8i5ue5"}],["path",{d:"M15 7h2a5 5 0 1 1 0 10h-2",key:"1b9ql8"}],["line",{x1:"8",x2:"16",y1:"12",y2:"12",key:"1jonct"}]]);/** * @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 Jo=te("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 qf=te("Linkedin",[["path",{d:"M16 8a6 6 0 0 1 6 6v7h-4v-7a2 2 0 0 0-2-2 2 2 0 0 0-2 2v7h-4v-7a6 6 0 0 1 6-6z",key:"c2jq9f"}],["rect",{width:"4",height:"12",x:"2",y:"9",key:"mk3on5"}],["circle",{cx:"4",cy:"4",r:"2",key:"bt5ra8"}]]);/** * @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 ase=te("ListCheck",[["path",{d:"M11 18H3",key:"n3j2dh"}],["path",{d:"m15 18 2 2 4-4",key:"1szwhi"}],["path",{d:"M16 12H3",key:"1a2rj7"}],["path",{d:"M16 6H3",key:"1wxfjs"}]]);/** * @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 V2=te("ListChecks",[["path",{d:"m3 17 2 2 4-4",key:"1jhpwq"}],["path",{d:"m3 7 2 2 4-4",key:"1obspn"}],["path",{d:"M13 6h8",key:"15sg57"}],["path",{d:"M13 12h8",key:"h98zly"}],["path",{d:"M13 18h8",key:"oe0vm4"}]]);/** * @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 ise=te("ListCollapse",[["path",{d:"m3 10 2.5-2.5L3 5",key:"i6eama"}],["path",{d:"m3 19 2.5-2.5L3 14",key:"w2gmor"}],["path",{d:"M10 6h11",key:"c7qv1k"}],["path",{d:"M10 12h11",key:"6m4ad9"}],["path",{d:"M10 18h11",key:"11hvi2"}]]);/** * @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 ose=te("ListEnd",[["path",{d:"M16 12H3",key:"1a2rj7"}],["path",{d:"M16 6H3",key:"1wxfjs"}],["path",{d:"M10 18H3",key:"13769t"}],["path",{d:"M21 6v10a2 2 0 0 1-2 2h-5",key:"ilrcs8"}],["path",{d:"m16 16-2 2 2 2",key:"kkc6pm"}]]);/** * @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 gF=te("ListFilter",[["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M7 12h10",key:"b7w52i"}],["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 lse=te("ListMinus",[["path",{d:"M11 12H3",key:"51ecnj"}],["path",{d:"M16 6H3",key:"1wxfjs"}],["path",{d:"M16 18H3",key:"12xzn7"}],["path",{d:"M21 12h-6",key:"bt1uis"}]]);/** * @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 cse=te("ListMusic",[["path",{d:"M21 15V6",key:"h1cx4g"}],["path",{d:"M18.5 18a2.5 2.5 0 1 0 0-5 2.5 2.5 0 0 0 0 5Z",key:"8saifv"}],["path",{d:"M12 12H3",key:"18klou"}],["path",{d:"M16 6H3",key:"1wxfjs"}],["path",{d:"M12 18H3",key:"11ftsu"}]]);/** * @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 b1=te("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 dse=te("ListPlus",[["path",{d:"M11 12H3",key:"51ecnj"}],["path",{d:"M16 6H3",key:"1wxfjs"}],["path",{d:"M16 18H3",key:"12xzn7"}],["path",{d:"M18 9v6",key:"1twb98"}],["path",{d:"M21 12h-6",key:"bt1uis"}]]);/** * @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 use=te("ListRestart",[["path",{d:"M21 6H3",key:"1jwq7v"}],["path",{d:"M7 12H3",key:"13ou7f"}],["path",{d:"M7 18H3",key:"1sijw9"}],["path",{d:"M12 18a5 5 0 0 0 9-3 4.5 4.5 0 0 0-4.5-4.5c-1.33 0-2.54.54-3.41 1.41L11 14",key:"qth677"}],["path",{d:"M11 10v4h4",key:"172dkj"}]]);/** * @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 hse=te("ListStart",[["path",{d:"M16 12H3",key:"1a2rj7"}],["path",{d:"M16 18H3",key:"12xzn7"}],["path",{d:"M10 6H3",key:"lf8lx7"}],["path",{d:"M21 18V8a2 2 0 0 0-2-2h-5",key:"1hghli"}],["path",{d:"m16 8-2-2 2-2",key:"160uvd"}]]);/** * @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 mse=te("ListTodo",[["rect",{x:"3",y:"5",width:"6",height:"6",rx:"1",key:"1defrl"}],["path",{d:"m3 17 2 2 4-4",key:"1jhpwq"}],["path",{d:"M13 6h8",key:"15sg57"}],["path",{d:"M13 12h8",key:"h98zly"}],["path",{d:"M13 18h8",key:"oe0vm4"}]]);/** * @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 fse=te("ListTree",[["path",{d:"M21 12h-8",key:"1bmf0i"}],["path",{d:"M21 6H8",key:"1pqkrb"}],["path",{d:"M21 18h-8",key:"1tm79t"}],["path",{d:"M3 6v4c0 1.1.9 2 2 2h3",key:"1ywdgy"}],["path",{d:"M3 10v6c0 1.1.9 2 2 2h3",key:"2wc746"}]]);/** * @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 pse=te("ListVideo",[["path",{d:"M12 12H3",key:"18klou"}],["path",{d:"M16 6H3",key:"1wxfjs"}],["path",{d:"M12 18H3",key:"11ftsu"}],["path",{d:"m16 12 5 3-5 3v-6Z",key:"zpskkp"}]]);/** * @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 gse=te("ListX",[["path",{d:"M11 12H3",key:"51ecnj"}],["path",{d:"M16 6H3",key:"1wxfjs"}],["path",{d:"M16 18H3",key:"12xzn7"}],["path",{d:"m19 10-4 4",key:"1tz659"}],["path",{d:"m15 10 4 4",key:"1n7nei"}]]);/** * @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 Vf=te("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 is=te("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 xse=te("LoaderPinwheel",[["path",{d:"M22 12a1 1 0 0 1-10 0 1 1 0 0 0-10 0",key:"1lzz15"}],["path",{d:"M7 20.7a1 1 0 1 1 5-8.7 1 1 0 1 0 5-8.6",key:"1gnrpi"}],["path",{d:"M7 3.3a1 1 0 1 1 5 8.6 1 1 0 1 0 5 8.6",key:"u9yy5q"}],["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 yse=te("Loader",[["path",{d:"M12 2v4",key:"3427ic"}],["path",{d:"m16.2 7.8 2.9-2.9",key:"r700ao"}],["path",{d:"M18 12h4",key:"wj9ykh"}],["path",{d:"m16.2 16.2 2.9 2.9",key:"1bxg5t"}],["path",{d:"M12 18v4",key:"jadmvz"}],["path",{d:"m4.9 19.1 2.9-2.9",key:"bwix9q"}],["path",{d:"M2 12h4",key:"j09sii"}],["path",{d:"m4.9 4.9 2.9 2.9",key:"giyufr"}]]);/** * @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 vse=te("LocateFixed",[["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"}],["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 bse=te("LocateOff",[["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"}],["path",{d:"M7.11 7.11C5.83 8.39 5 10.1 5 12c0 3.87 3.13 7 7 7 1.9 0 3.61-.83 4.89-2.11",key:"1oh7ia"}],["path",{d:"M18.71 13.96c.19-.63.29-1.29.29-1.96 0-3.87-3.13-7-7-7-.67 0-1.33.1-1.96.29",key:"3qdecy"}],["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}]]);/** * @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=te("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 F3=te("LockKeyholeOpen",[["circle",{cx:"12",cy:"16",r:"1",key:"1au0dj"}],["rect",{width:"18",height:"12",x:"3",y:"10",rx:"2",key:"l0tzu3"}],["path",{d:"M7 10V7a5 5 0 0 1 9.33-2.5",key:"car5b7"}]]);/** * @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 _se=te("LockKeyhole",[["circle",{cx:"12",cy:"16",r:"1",key:"1au0dj"}],["rect",{x:"3",y:"10",width:"18",height:"12",rx:"2",key:"6s8ecr"}],["path",{d:"M7 10V7a5 5 0 0 1 10 0v3",key:"1pqi11"}]]);/** * @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 B3=te("LockOpen",[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 9.9-1",key:"1mm8w8"}]]);/** * @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=te("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 kE=te("LogIn",[["path",{d:"M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4",key:"u53s6r"}],["polyline",{points:"10 17 15 12 10 7",key:"1ail0h"}],["line",{x1:"15",x2:"3",y1:"12",y2:"12",key:"v6grx8"}]]);/** * @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 UI=te("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 wse=te("Logs",[["path",{d:"M13 12h8",key:"h98zly"}],["path",{d:"M13 18h8",key:"oe0vm4"}],["path",{d:"M13 6h8",key:"15sg57"}],["path",{d:"M3 12h1",key:"lp3yf2"}],["path",{d:"M3 18h1",key:"1eiwyy"}],["path",{d:"M3 6h1",key:"rgxa97"}],["path",{d:"M8 12h1",key:"1con00"}],["path",{d:"M8 18h1",key:"13wk12"}],["path",{d:"M8 6h1",key:"tn6mkg"}]]);/** * @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 jse=te("Lollipop",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["path",{d:"m21 21-4.3-4.3",key:"1qie3q"}],["path",{d:"M11 11a2 2 0 0 0 4 0 4 4 0 0 0-8 0 6 6 0 0 0 12 0",key:"107gwy"}]]);/** * @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 Nse=te("Luggage",[["path",{d:"M6 20a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2",key:"1m57jg"}],["path",{d:"M8 18V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v14",key:"1l99gc"}],["path",{d:"M10 20h4",key:"ni2waw"}],["circle",{cx:"16",cy:"20",r:"2",key:"1vifvg"}],["circle",{cx:"8",cy:"20",r:"2",key:"ckkr5m"}]]);/** * @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 kse=te("Magnet",[["path",{d:"m6 15-4-4 6.75-6.77a7.79 7.79 0 0 1 11 11L13 22l-4-4 6.39-6.36a2.14 2.14 0 0 0-3-3L6 15",key:"1i3lhw"}],["path",{d:"m5 8 4 4",key:"j6kj7e"}],["path",{d:"m12 15 4 4",key:"lnac28"}]]);/** * @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 Sse=te("MailCheck",[["path",{d:"M22 13V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v12c0 1.1.9 2 2 2h8",key:"12jkf8"}],["path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7",key:"1ocrg3"}],["path",{d:"m16 19 2 2 4-4",key:"1b14m6"}]]);/** * @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 Cse=te("MailMinus",[["path",{d:"M22 15V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v12c0 1.1.9 2 2 2h8",key:"fuxbkv"}],["path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7",key:"1ocrg3"}],["path",{d:"M16 19h6",key:"xwg31i"}]]);/** * @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 xF=te("MailOpen",[["path",{d:"M21.2 8.4c.5.38.8.97.8 1.6v10a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V10a2 2 0 0 1 .8-1.6l8-6a2 2 0 0 1 2.4 0l8 6Z",key:"1jhwl8"}],["path",{d:"m22 10-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 10",key:"1qfld7"}]]);/** * @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 yF=te("MailPlus",[["path",{d:"M22 13V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v12c0 1.1.9 2 2 2h8",key:"12jkf8"}],["path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7",key:"1ocrg3"}],["path",{d:"M19 16v6",key:"tddt3s"}],["path",{d:"M16 19h6",key:"xwg31i"}]]);/** * @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 Tse=te("MailQuestion",[["path",{d:"M22 10.5V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v12c0 1.1.9 2 2 2h12.5",key:"e61zoh"}],["path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7",key:"1ocrg3"}],["path",{d:"M18 15.28c.2-.4.5-.8.9-1a2.1 2.1 0 0 1 2.6.4c.3.4.5.8.5 1.3 0 1.3-2 2-2 2",key:"7z9rxb"}],["path",{d:"M20 22v.01",key:"12bgn6"}]]);/** * @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 Ese=te("MailSearch",[["path",{d:"M22 12.5V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v12c0 1.1.9 2 2 2h7.5",key:"w80f2v"}],["path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7",key:"1ocrg3"}],["path",{d:"M18 21a3 3 0 1 0 0-6 3 3 0 0 0 0 6Z",key:"8lzu5m"}],["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}],["path",{d:"m22 22-1.5-1.5",key:"1x83k4"}]]);/** * @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 Ase=te("MailWarning",[["path",{d:"M22 10.5V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v12c0 1.1.9 2 2 2h12.5",key:"e61zoh"}],["path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7",key:"1ocrg3"}],["path",{d:"M20 14v4",key:"1hm744"}],["path",{d:"M20 22v.01",key:"12bgn6"}]]);/** * @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 qI=te("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 er=te("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 Mse=te("Mailbox",[["path",{d:"M22 17a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V9.5C2 7 4 5 6.5 5H18c2.2 0 4 1.8 4 4v8Z",key:"1lbycx"}],["polyline",{points:"15,9 18,9 18,11",key:"1pm9c0"}],["path",{d:"M6.5 5C9 5 11 7 11 9.5V17a2 2 0 0 1-2 2",key:"15i455"}],["line",{x1:"6",x2:"7",y1:"10",y2:"10",key:"1e2scm"}]]);/** * @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 Ise=te("Mails",[["rect",{width:"16",height:"13",x:"6",y:"4",rx:"2",key:"1drq3f"}],["path",{d:"m22 7-7.1 3.78c-.57.3-1.23.3-1.8 0L6 7",key:"xn252p"}],["path",{d:"M2 8v11c0 1.1.9 2 2 2h14",key:"n13cji"}]]);/** * @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 Pse=te("MapPinCheckInside",[["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"}],["path",{d:"m9 10 2 2 4-4",key:"1gnqz4"}]]);/** * @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 Lse=te("MapPinCheck",[["path",{d:"M19.43 12.935c.357-.967.57-1.955.57-2.935a8 8 0 0 0-16 0c0 4.993 5.539 10.193 7.399 11.799a1 1 0 0 0 1.202 0 32.197 32.197 0 0 0 .813-.728",key:"1dq61d"}],["circle",{cx:"12",cy:"10",r:"3",key:"ilqhr7"}],["path",{d:"m16 18 2 2 4-4",key:"1mkfmb"}]]);/** * @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 Dse=te("MapPinHouse",[["path",{d:"M15 22a1 1 0 0 1-1-1v-4a1 1 0 0 1 .445-.832l3-2a1 1 0 0 1 1.11 0l3 2A1 1 0 0 1 22 17v4a1 1 0 0 1-1 1z",key:"1p1rcz"}],["path",{d:"M18 10a8 8 0 0 0-16 0c0 4.993 5.539 10.193 7.399 11.799a1 1 0 0 0 .601.2",key:"mcbcs9"}],["path",{d:"M18 22v-3",key:"1t1ugv"}],["circle",{cx:"10",cy:"10",r:"3",key:"1ns7v1"}]]);/** * @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 Rse=te("MapPinMinusInside",[["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"}],["path",{d:"M9 10h6",key:"9gxzsh"}]]);/** * @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 Ose=te("MapPinMinus",[["path",{d:"M18.977 14C19.6 12.701 20 11.343 20 10a8 8 0 0 0-16 0c0 4.993 5.539 10.193 7.399 11.799a1 1 0 0 0 1.202 0 32 32 0 0 0 .824-.738",key:"11uxia"}],["circle",{cx:"12",cy:"10",r:"3",key:"ilqhr7"}],["path",{d:"M16 18h6",key:"987eiv"}]]);/** * @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 Fse=te("MapPinOff",[["path",{d:"M12.75 7.09a3 3 0 0 1 2.16 2.16",key:"1d4wjd"}],["path",{d:"M17.072 17.072c-1.634 2.17-3.527 3.912-4.471 4.727a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 1.432-4.568",key:"12yil7"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M8.475 2.818A8 8 0 0 1 20 10c0 1.183-.31 2.377-.81 3.533",key:"lhrkcz"}],["path",{d:"M9.13 9.13a3 3 0 0 0 3.74 3.74",key:"13wojd"}]]);/** * @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 Bse=te("MapPinPlusInside",[["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"}],["path",{d:"M12 7v6",key:"lw1j43"}],["path",{d:"M9 10h6",key:"9gxzsh"}]]);/** * @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 zse=te("MapPinPlus",[["path",{d:"M19.914 11.105A7.298 7.298 0 0 0 20 10a8 8 0 0 0-16 0c0 4.993 5.539 10.193 7.399 11.799a1 1 0 0 0 1.202 0 32 32 0 0 0 .824-.738",key:"fcdtly"}],["circle",{cx:"12",cy:"10",r:"3",key:"ilqhr7"}],["path",{d:"M16 18h6",key:"987eiv"}],["path",{d:"M19 15v6",key:"10aioa"}]]);/** * @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 $se=te("MapPinXInside",[["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"}],["path",{d:"m14.5 7.5-5 5",key:"3lb6iw"}],["path",{d:"m9.5 7.5 5 5",key:"ko136h"}]]);/** * @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 Use=te("MapPinX",[["path",{d:"M19.752 11.901A7.78 7.78 0 0 0 20 10a8 8 0 0 0-16 0c0 4.993 5.539 10.193 7.399 11.799a1 1 0 0 0 1.202 0 19 19 0 0 0 .09-.077",key:"y0ewhp"}],["circle",{cx:"12",cy:"10",r:"3",key:"ilqhr7"}],["path",{d:"m21.5 15.5-5 5",key:"11iqnx"}],["path",{d:"m21.5 20.5-5-5",key:"1bylgx"}]]);/** * @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 Qa=te("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 qse=te("MapPinned",[["path",{d:"M18 8c0 3.613-3.869 7.429-5.393 8.795a1 1 0 0 1-1.214 0C9.87 15.429 6 11.613 6 8a6 6 0 0 1 12 0",key:"11u0oz"}],["circle",{cx:"12",cy:"8",r:"2",key:"1822b1"}],["path",{d:"M8.714 14h-3.71a1 1 0 0 0-.948.683l-2.004 6A1 1 0 0 0 3 22h18a1 1 0 0 0 .948-1.316l-2-6a1 1 0 0 0-.949-.684h-3.712",key:"q8zwxj"}]]);/** * @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 SE=te("Map",[["path",{d:"M14.106 5.553a2 2 0 0 0 1.788 0l3.659-1.83A1 1 0 0 1 21 4.619v12.764a1 1 0 0 1-.553.894l-4.553 2.277a2 2 0 0 1-1.788 0l-4.212-2.106a2 2 0 0 0-1.788 0l-3.659 1.83A1 1 0 0 1 3 19.381V6.618a1 1 0 0 1 .553-.894l4.553-2.277a2 2 0 0 1 1.788 0z",key:"169xi5"}],["path",{d:"M15 5.764v15",key:"1pn4in"}],["path",{d:"M9 3.236v15",key:"1uimfh"}]]);/** * @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 Vse=te("Martini",[["path",{d:"M8 22h8",key:"rmew8v"}],["path",{d:"M12 11v11",key:"ur9y6a"}],["path",{d:"m19 3-7 8-7-8Z",key:"1sgpiw"}]]);/** * @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 Hse=te("Maximize2",[["polyline",{points:"15 3 21 3 21 9",key:"mznyad"}],["polyline",{points:"9 21 3 21 3 15",key:"1avn1i"}],["line",{x1:"21",x2:"14",y1:"3",y2:"10",key:"ota7mn"}],["line",{x1:"3",x2:"10",y1:"21",y2:"14",key:"1atl0r"}]]);/** * @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 CE=te("Maximize",[["path",{d:"M8 3H5a2 2 0 0 0-2 2v3",key:"1dcmit"}],["path",{d:"M21 8V5a2 2 0 0 0-2-2h-3",key:"1e4gt3"}],["path",{d:"M3 16v3a2 2 0 0 0 2 2h3",key:"wsl5sc"}],["path",{d:"M16 21h3a2 2 0 0 0 2-2v-3",key:"18trek"}]]);/** * @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=te("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 Gse=te("MegaphoneOff",[["path",{d:"M9.26 9.26 3 11v3l14.14 3.14",key:"3429n"}],["path",{d:"M21 15.34V6l-7.31 2.03",key:"4o1dh8"}],["path",{d:"M11.6 16.8a3 3 0 1 1-5.8-1.6",key:"1yl0tm"}],["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}]]);/** * @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=te("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 Wse=te("Meh",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"8",x2:"16",y1:"15",y2:"15",key:"1xb1d9"}],["line",{x1:"9",x2:"9.01",y1:"9",y2:"9",key:"yxxnd0"}],["line",{x1:"15",x2:"15.01",y1:"9",y2:"9",key:"1p4y9e"}]]);/** * @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 Kse=te("MemoryStick",[["path",{d:"M6 19v-3",key:"1nvgqn"}],["path",{d:"M10 19v-3",key:"iu8nkm"}],["path",{d:"M14 19v-3",key:"kcehxu"}],["path",{d:"M18 19v-3",key:"1vh91z"}],["path",{d:"M8 11V9",key:"63erz4"}],["path",{d:"M16 11V9",key:"fru6f3"}],["path",{d:"M12 11V9",key:"ha00sb"}],["path",{d:"M2 15h20",key:"16ne18"}],["path",{d:"M2 7a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v1.1a2 2 0 0 0 0 3.837V17a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2v-5.1a2 2 0 0 0 0-3.837Z",key:"lhddv3"}]]);/** * @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 TE=te("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 Yse=te("Merge",[["path",{d:"m8 6 4-4 4 4",key:"ybng9g"}],["path",{d:"M12 2v10.3a4 4 0 0 1-1.172 2.872L4 22",key:"1hyw0i"}],["path",{d:"m20 22-5-5",key:"1m27yz"}]]);/** * @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 Zse=te("MessageCircleCode",[["path",{d:"M10 9.5 8 12l2 2.5",key:"3mjy60"}],["path",{d:"m14 9.5 2 2.5-2 2.5",key:"1bir2l"}],["path",{d:"M7.9 20A9 9 0 1 0 4 16.1L2 22z",key:"k85zhp"}]]);/** * @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 Xse=te("MessageCircleDashed",[["path",{d:"M13.5 3.1c-.5 0-1-.1-1.5-.1s-1 .1-1.5.1",key:"16ll65"}],["path",{d:"M19.3 6.8a10.45 10.45 0 0 0-2.1-2.1",key:"1nq77a"}],["path",{d:"M20.9 13.5c.1-.5.1-1 .1-1.5s-.1-1-.1-1.5",key:"1sf7wn"}],["path",{d:"M17.2 19.3a10.45 10.45 0 0 0 2.1-2.1",key:"x1hs5g"}],["path",{d:"M10.5 20.9c.5.1 1 .1 1.5.1s1-.1 1.5-.1",key:"19m18z"}],["path",{d:"M3.5 17.5 2 22l4.5-1.5",key:"1f36qi"}],["path",{d:"M3.1 10.5c0 .5-.1 1-.1 1.5s.1 1 .1 1.5",key:"1vz3ju"}],["path",{d:"M6.8 4.7a10.45 10.45 0 0 0-2.1 2.1",key:"19f9do"}]]);/** * @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 VI=te("MessageCircleHeart",[["path",{d:"M7.9 20A9 9 0 1 0 4 16.1L2 22Z",key:"vv11sd"}],["path",{d:"M15.8 9.2a2.5 2.5 0 0 0-3.5 0l-.3.4-.35-.3a2.42 2.42 0 1 0-3.2 3.6l3.6 3.5 3.6-3.5c1.2-1.2 1.1-2.7.2-3.7",key:"43lnbm"}]]);/** * @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 Qse=te("MessageCircleMore",[["path",{d:"M7.9 20A9 9 0 1 0 4 16.1L2 22Z",key:"vv11sd"}],["path",{d:"M8 12h.01",key:"czm47f"}],["path",{d:"M12 12h.01",key:"1mp3jc"}],["path",{d:"M16 12h.01",key:"1l6xoz"}]]);/** * @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 Jse=te("MessageCircleOff",[["path",{d:"M20.5 14.9A9 9 0 0 0 9.1 3.5",key:"1iebmn"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M5.6 5.6C3 8.3 2.2 12.5 4 16l-2 6 6-2c3.4 1.8 7.6 1.1 10.3-1.7",key:"1ov8ce"}]]);/** * @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 ere=te("MessageCirclePlus",[["path",{d:"M7.9 20A9 9 0 1 0 4 16.1L2 22Z",key:"vv11sd"}],["path",{d:"M8 12h8",key:"1wcyev"}],["path",{d:"M12 8v8",key:"napkw2"}]]);/** * @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 vF=te("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 tre=te("MessageCircleReply",[["path",{d:"M7.9 20A9 9 0 1 0 4 16.1L2 22Z",key:"vv11sd"}],["path",{d:"m10 15-3-3 3-3",key:"1pgupc"}],["path",{d:"M7 12h7a2 2 0 0 1 2 2v1",key:"1gheu4"}]]);/** * @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 sre=te("MessageCircleWarning",[["path",{d:"M7.9 20A9 9 0 1 0 4 16.1L2 22Z",key:"vv11sd"}],["path",{d:"M12 8v4",key:"1got3b"}],["path",{d:"M12 16h.01",key:"1drbdi"}]]);/** * @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 rre=te("MessageCircleX",[["path",{d:"M7.9 20A9 9 0 1 0 4 16.1L2 22Z",key:"vv11sd"}],["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 qc=te("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 nre=te("MessageSquareCode",[["path",{d:"M10 7.5 8 10l2 2.5",key:"xb17xw"}],["path",{d:"m14 7.5 2 2.5-2 2.5",key:"5rap1v"}],["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 are=te("MessageSquareDashed",[["path",{d:"M10 17H7l-4 4v-7",key:"1r71xu"}],["path",{d:"M14 17h1",key:"nufu4t"}],["path",{d:"M14 3h1",key:"1ec4yj"}],["path",{d:"M19 3a2 2 0 0 1 2 2",key:"18rm91"}],["path",{d:"M21 14v1a2 2 0 0 1-2 2",key:"29akq3"}],["path",{d:"M21 9v1",key:"mxsmne"}],["path",{d:"M3 9v1",key:"1r0deq"}],["path",{d:"M5 3a2 2 0 0 0-2 2",key:"y57alp"}],["path",{d:"M9 3h1",key:"1yesri"}]]);/** * @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 ire=te("MessageSquareDiff",[["path",{d:"m5 19-2 2V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2",key:"1xuzuj"}],["path",{d:"M9 10h6",key:"9gxzsh"}],["path",{d:"M12 7v6",key:"lw1j43"}],["path",{d:"M9 17h6",key:"r8uit2"}]]);/** * @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 ore=te("MessageSquareDot",[["path",{d:"M11.7 3H5a2 2 0 0 0-2 2v16l4-4h12a2 2 0 0 0 2-2v-2.7",key:"uodpkb"}],["circle",{cx:"18",cy:"6",r:"3",key:"1h7g24"}]]);/** * @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 lre=te("MessageSquareHeart",[["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"}],["path",{d:"M14.8 7.5a1.84 1.84 0 0 0-2.6 0l-.2.3-.3-.3a1.84 1.84 0 1 0-2.4 2.8L12 13l2.7-2.7c.9-.9.8-2.1.1-2.8",key:"1blaws"}]]);/** * @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 cre=te("MessageSquareLock",[["path",{d:"M19 15v-2a2 2 0 1 0-4 0v2",key:"h3d1vz"}],["path",{d:"M9 17H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v3.5",key:"xsnnhn"}],["rect",{x:"13",y:"15",width:"8",height:"5",rx:"1",key:"1ccwuk"}]]);/** * @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=te("MessageSquareMore",[["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"}],["path",{d:"M8 10h.01",key:"19clt8"}],["path",{d:"M12 10h.01",key:"1nrarc"}],["path",{d:"M16 10h.01",key:"1m94wz"}]]);/** * @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 dre=te("MessageSquareOff",[["path",{d:"M21 15V5a2 2 0 0 0-2-2H9",key:"43el77"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M3.6 3.6c-.4.3-.6.8-.6 1.4v16l4-4h10",key:"pwpm4a"}]]);/** * @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 t_=te("MessageSquarePlus",[["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"}],["path",{d:"M12 7v6",key:"lw1j43"}],["path",{d:"M9 10h6",key:"9gxzsh"}]]);/** * @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 HI=te("MessageSquareQuote",[["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"}],["path",{d:"M8 12a2 2 0 0 0 2-2V8H8",key:"1jfesj"}],["path",{d:"M14 12a2 2 0 0 0 2-2V8h-2",key:"1dq9mh"}]]);/** * @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 ure=te("MessageSquareReply",[["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"}],["path",{d:"m10 7-3 3 3 3",key:"1eugdv"}],["path",{d:"M17 13v-1a2 2 0 0 0-2-2H7",key:"ernfh3"}]]);/** * @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 hre=te("MessageSquareShare",[["path",{d:"M21 12v3a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h7",key:"tqtdkg"}],["path",{d:"M16 3h5v5",key:"1806ms"}],["path",{d:"m16 8 5-5",key:"15mbrl"}]]);/** * @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 mre=te("MessageSquareText",[["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"}],["path",{d:"M13 8H7",key:"14i4kc"}],["path",{d:"M17 12H7",key:"16if0g"}]]);/** * @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 fre=te("MessageSquareWarning",[["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"}],["path",{d:"M12 7v2",key:"stiyo7"}],["path",{d:"M12 13h.01",key:"y0uutt"}]]);/** * @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 pre=te("MessageSquareX",[["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"}],["path",{d:"m14.5 7.5-5 5",key:"3lb6iw"}],["path",{d:"m9.5 7.5 5 5",key:"ko136h"}]]);/** * @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 Gi=te("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 gre=te("MessagesSquare",[["path",{d:"M14 9a2 2 0 0 1-2 2H6l-4 4V4a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2z",key:"p1xzt8"}],["path",{d:"M18 9h2a2 2 0 0 1 2 2v11l-4-4h-6a2 2 0 0 1-2-2v-1",key:"1cx29u"}]]);/** * @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 xre=te("MicOff",[["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}],["path",{d:"M18.89 13.23A7.12 7.12 0 0 0 19 12v-2",key:"80xlxr"}],["path",{d:"M5 10v2a7 7 0 0 0 12 5",key:"p2k8kg"}],["path",{d:"M15 9.34V5a3 3 0 0 0-5.68-1.33",key:"1gzdoj"}],["path",{d:"M9 9v3a3 3 0 0 0 5.12 2.12",key:"r2i35w"}],["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 z3=te("MicVocal",[["path",{d:"m11 7.601-5.994 8.19a1 1 0 0 0 .1 1.298l.817.818a1 1 0 0 0 1.314.087L15.09 12",key:"80a601"}],["path",{d:"M16.5 21.174C15.5 20.5 14.372 20 13 20c-2.058 0-3.928 2.356-6 2-2.072-.356-2.775-3.369-1.5-4.5",key:"j0ngtp"}],["circle",{cx:"16",cy:"7",r:"5",key:"d08jfb"}]]);/** * @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 EE=te("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 yre=te("Microchip",[["path",{d:"M18 12h2",key:"quuxs7"}],["path",{d:"M18 16h2",key:"zsn3lv"}],["path",{d:"M18 20h2",key:"9x5y9y"}],["path",{d:"M18 4h2",key:"1luxfb"}],["path",{d:"M18 8h2",key:"nxqzg"}],["path",{d:"M4 12h2",key:"1ltxp0"}],["path",{d:"M4 16h2",key:"8a5zha"}],["path",{d:"M4 20h2",key:"27dk57"}],["path",{d:"M4 4h2",key:"10groj"}],["path",{d:"M4 8h2",key:"18vq6w"}],["path",{d:"M8 2a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V4a2 2 0 0 0-2-2h-1.5c-.276 0-.494.227-.562.495a2 2 0 0 1-3.876 0C9.994 2.227 9.776 2 9.5 2z",key:"1681fp"}]]);/** * @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 vre=te("Microscope",[["path",{d:"M6 18h8",key:"1borvv"}],["path",{d:"M3 22h18",key:"8prr45"}],["path",{d:"M14 22a7 7 0 1 0 0-14h-1",key:"1jwaiy"}],["path",{d:"M9 14h2",key:"197e7h"}],["path",{d:"M9 12a2 2 0 0 1-2-2V6h6v4a2 2 0 0 1-2 2Z",key:"1bmzmy"}],["path",{d:"M12 6V3a1 1 0 0 0-1-1H9a1 1 0 0 0-1 1v3",key:"1drr47"}]]);/** * @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 bre=te("Microwave",[["rect",{width:"20",height:"15",x:"2",y:"4",rx:"2",key:"2no95f"}],["rect",{width:"8",height:"7",x:"6",y:"8",rx:"1",key:"zh9wx"}],["path",{d:"M18 8v7",key:"o5zi4n"}],["path",{d:"M6 19v2",key:"1loha6"}],["path",{d:"M18 19v2",key:"1dawf0"}]]);/** * @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 _re=te("Milestone",[["path",{d:"M12 13v8",key:"1l5pq0"}],["path",{d:"M12 3v3",key:"1n5kay"}],["path",{d:"M4 6a1 1 0 0 0-1 1v5a1 1 0 0 0 1 1h13a2 2 0 0 0 1.152-.365l3.424-2.317a1 1 0 0 0 0-1.635l-3.424-2.318A2 2 0 0 0 17 6z",key:"1btarq"}]]);/** * @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 wre=te("MilkOff",[["path",{d:"M8 2h8",key:"1ssgc1"}],["path",{d:"M9 2v1.343M15 2v2.789a4 4 0 0 0 .672 2.219l.656.984a4 4 0 0 1 .672 2.22v1.131M7.8 7.8l-.128.192A4 4 0 0 0 7 10.212V20a2 2 0 0 0 2 2h6a2 2 0 0 0 2-2v-3",key:"y0ejgx"}],["path",{d:"M7 15a6.47 6.47 0 0 1 5 0 6.472 6.472 0 0 0 3.435.435",key:"iaxqsy"}],["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}]]);/** * @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 jre=te("Milk",[["path",{d:"M8 2h8",key:"1ssgc1"}],["path",{d:"M9 2v2.789a4 4 0 0 1-.672 2.219l-.656.984A4 4 0 0 0 7 10.212V20a2 2 0 0 0 2 2h6a2 2 0 0 0 2-2v-9.789a4 4 0 0 0-.672-2.219l-.656-.984A4 4 0 0 1 15 4.788V2",key:"qtp12x"}],["path",{d:"M7 15a6.472 6.472 0 0 1 5 0 6.47 6.47 0 0 0 5 0",key:"ygeh44"}]]);/** * @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 Nre=te("Minimize2",[["polyline",{points:"4 14 10 14 10 20",key:"11kfnr"}],["polyline",{points:"20 10 14 10 14 4",key:"rlmsce"}],["line",{x1:"14",x2:"21",y1:"10",y2:"3",key:"o5lafz"}],["line",{x1:"3",x2:"10",y1:"21",y2:"14",key:"1atl0r"}]]);/** * @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 kre=te("Minimize",[["path",{d:"M8 3v3a2 2 0 0 1-2 2H3",key:"hohbtr"}],["path",{d:"M21 8h-3a2 2 0 0 1-2-2V3",key:"5jw1f3"}],["path",{d:"M3 16h3a2 2 0 0 1 2 2v3",key:"198tvr"}],["path",{d:"M16 21v-3a2 2 0 0 1 2-2h3",key:"ph8mxp"}]]);/** * @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_=te("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 Sre=te("MonitorCheck",[["path",{d:"m9 10 2 2 4-4",key:"1gnqz4"}],["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2",key:"48i651"}],["path",{d:"M12 17v4",key:"1riwvh"}],["path",{d:"M8 21h8",key:"1ev6f3"}]]);/** * @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 Cre=te("MonitorCog",[["path",{d:"M12 17v4",key:"1riwvh"}],["path",{d:"m15.2 4.9-.9-.4",key:"12wd2u"}],["path",{d:"m15.2 7.1-.9.4",key:"1r2vl7"}],["path",{d:"m16.9 3.2-.4-.9",key:"3zbo91"}],["path",{d:"m16.9 8.8-.4.9",key:"1qr2dn"}],["path",{d:"m19.5 2.3-.4.9",key:"1rjrkq"}],["path",{d:"m19.5 9.7-.4-.9",key:"heryx5"}],["path",{d:"m21.7 4.5-.9.4",key:"17fqt1"}],["path",{d:"m21.7 7.5-.9-.4",key:"14zyni"}],["path",{d:"M22 13v2a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7",key:"1tnzv8"}],["path",{d:"M8 21h8",key:"1ev6f3"}],["circle",{cx:"18",cy:"6",r:"3",key:"1h7g24"}]]);/** * @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 Tre=te("MonitorDot",[["circle",{cx:"19",cy:"6",r:"3",key:"108a5v"}],["path",{d:"M22 12v3a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h9",key:"1fet9y"}],["path",{d:"M12 17v4",key:"1riwvh"}],["path",{d:"M8 21h8",key:"1ev6f3"}]]);/** * @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 Ere=te("MonitorDown",[["path",{d:"M12 13V7",key:"h0r20n"}],["path",{d:"m15 10-3 3-3-3",key:"lzhmyn"}],["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2",key:"48i651"}],["path",{d:"M12 17v4",key:"1riwvh"}],["path",{d:"M8 21h8",key:"1ev6f3"}]]);/** * @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 Are=te("MonitorOff",[["path",{d:"M17 17H4a2 2 0 0 1-2-2V5c0-1.5 1-2 1-2",key:"k0q8oc"}],["path",{d:"M22 15V5a2 2 0 0 0-2-2H9",key:"cp1ac0"}],["path",{d:"M8 21h8",key:"1ev6f3"}],["path",{d:"M12 17v4",key:"1riwvh"}],["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 Mre=te("MonitorPause",[["path",{d:"M10 13V7",key:"1u13u9"}],["path",{d:"M14 13V7",key:"1vj9om"}],["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2",key:"48i651"}],["path",{d:"M12 17v4",key:"1riwvh"}],["path",{d:"M8 21h8",key:"1ev6f3"}]]);/** * @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 _F=te("MonitorPlay",[["path",{d:"M10 7.75a.75.75 0 0 1 1.142-.638l3.664 2.249a.75.75 0 0 1 0 1.278l-3.664 2.25a.75.75 0 0 1-1.142-.64z",key:"1pctta"}],["path",{d:"M12 17v4",key:"1riwvh"}],["path",{d:"M8 21h8",key:"1ev6f3"}],["rect",{x:"2",y:"3",width:"20",height:"14",rx:"2",key:"x3v2xh"}]]);/** * @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 Ire=te("MonitorSmartphone",[["path",{d:"M18 8V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v7a2 2 0 0 0 2 2h8",key:"10dyio"}],["path",{d:"M10 19v-3.96 3.15",key:"1irgej"}],["path",{d:"M7 19h5",key:"qswx4l"}],["rect",{width:"6",height:"10",x:"16",y:"12",rx:"2",key:"1egngj"}]]);/** * @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 Pre=te("MonitorSpeaker",[["path",{d:"M5.5 20H8",key:"1k40s5"}],["path",{d:"M17 9h.01",key:"1j24nn"}],["rect",{width:"10",height:"16",x:"12",y:"4",rx:"2",key:"ixliua"}],["path",{d:"M8 6H4a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2h4",key:"1mp6e1"}],["circle",{cx:"17",cy:"15",r:"1",key:"tqvash"}]]);/** * @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 Lre=te("MonitorStop",[["path",{d:"M12 17v4",key:"1riwvh"}],["path",{d:"M8 21h8",key:"1ev6f3"}],["rect",{x:"2",y:"3",width:"20",height:"14",rx:"2",key:"x3v2xh"}],["rect",{x:"9",y:"7",width:"6",height:"6",rx:"1",key:"5m2oou"}]]);/** * @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 AE=te("MonitorUp",[["path",{d:"m9 10 3-3 3 3",key:"11gsxs"}],["path",{d:"M12 13V7",key:"h0r20n"}],["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2",key:"48i651"}],["path",{d:"M12 17v4",key:"1riwvh"}],["path",{d:"M8 21h8",key:"1ev6f3"}]]);/** * @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 Dre=te("MonitorX",[["path",{d:"m14.5 12.5-5-5",key:"1jahn5"}],["path",{d:"m9.5 12.5 5-5",key:"1k2t7b"}],["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2",key:"48i651"}],["path",{d:"M12 17v4",key:"1riwvh"}],["path",{d:"M8 21h8",key:"1ev6f3"}]]);/** * @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 Vk=te("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 Rre=te("MoonStar",[["path",{d:"M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9",key:"4ay0iu"}],["path",{d:"M20 3v4",key:"1olli1"}],["path",{d:"M22 5h-4",key:"1gvqau"}]]);/** * @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 Ore=te("Moon",[["path",{d:"M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z",key:"a7tn18"}]]);/** * @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 Fre=te("MountainSnow",[["path",{d:"m8 3 4 8 5-5 5 15H2L8 3z",key:"otkl63"}],["path",{d:"M4.14 15.08c2.62-1.57 5.24-1.43 7.86.42 2.74 1.94 5.49 2 8.23.19",key:"1pvmmp"}]]);/** * @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 Bre=te("Mountain",[["path",{d:"m8 3 4 8 5-5 5 15H2L8 3z",key:"otkl63"}]]);/** * @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 zre=te("MouseOff",[["path",{d:"M12 6v.343",key:"1gyhex"}],["path",{d:"M18.218 18.218A7 7 0 0 1 5 15V9a7 7 0 0 1 .782-3.218",key:"ukzz01"}],["path",{d:"M19 13.343V9A7 7 0 0 0 8.56 2.902",key:"104jy9"}],["path",{d:"M22 22 2 2",key:"1r8tn9"}]]);/** * @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 $re=te("MousePointer2",[["path",{d:"M4.037 4.688a.495.495 0 0 1 .651-.651l16 6.5a.5.5 0 0 1-.063.947l-6.124 1.58a2 2 0 0 0-1.438 1.435l-1.579 6.126a.5.5 0 0 1-.947.063z",key:"edeuup"}]]);/** * @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 Ure=te("MousePointerBan",[["path",{d:"M2.034 2.681a.498.498 0 0 1 .647-.647l9 3.5a.5.5 0 0 1-.033.944L8.204 7.545a1 1 0 0 0-.66.66l-1.066 3.443a.5.5 0 0 1-.944.033z",key:"11pp1i"}],["circle",{cx:"16",cy:"16",r:"6",key:"qoo3c4"}],["path",{d:"m11.8 11.8 8.4 8.4",key:"oogvdj"}]]);/** * @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 Kd=te("MousePointerClick",[["path",{d:"M14 4.1 12 6",key:"ita8i4"}],["path",{d:"m5.1 8-2.9-.8",key:"1go3kf"}],["path",{d:"m6 12-1.9 2",key:"mnht97"}],["path",{d:"M7.2 2.2 8 5.1",key:"1cfko1"}],["path",{d:"M9.037 9.69a.498.498 0 0 1 .653-.653l11 4.5a.5.5 0 0 1-.074.949l-4.349 1.041a1 1 0 0 0-.74.739l-1.04 4.35a.5.5 0 0 1-.95.074z",key:"s0h3yz"}]]);/** * @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 lm=te("MousePointer",[["path",{d:"M12.586 12.586 19 19",key:"ea5xo7"}],["path",{d:"M3.688 3.037a.497.497 0 0 0-.651.651l6.5 15.999a.501.501 0 0 0 .947-.062l1.569-6.083a2 2 0 0 1 1.448-1.479l6.124-1.579a.5.5 0 0 0 .063-.947z",key:"277e5u"}]]);/** * @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 qre=te("Mouse",[["rect",{x:"5",y:"2",width:"14",height:"20",rx:"7",key:"11ol66"}],["path",{d:"M12 6v4",key:"16clxf"}]]);/** * @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 $3=te("Move3d",[["path",{d:"M5 3v16h16",key:"1mqmf9"}],["path",{d:"m5 19 6-6",key:"jh6hbb"}],["path",{d:"m2 6 3-3 3 3",key:"tkyvxa"}],["path",{d:"m18 16 3 3-3 3",key:"1d4glt"}]]);/** * @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 Vre=te("MoveDiagonal2",[["path",{d:"M19 13v6h-6",key:"1hxl6d"}],["path",{d:"M5 11V5h6",key:"12e2xe"}],["path",{d:"m5 5 14 14",key:"11anup"}]]);/** * @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 Hre=te("MoveDiagonal",[["path",{d:"M11 19H5v-6",key:"8awifj"}],["path",{d:"M13 5h6v6",key:"7voy1q"}],["path",{d:"M19 5 5 19",key:"wwaj1z"}]]);/** * @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 Gre=te("MoveDownLeft",[["path",{d:"M11 19H5V13",key:"1akmht"}],["path",{d:"M19 5L5 19",key:"72u4yj"}]]);/** * @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 Wre=te("MoveDownRight",[["path",{d:"M19 13V19H13",key:"10vkzq"}],["path",{d:"M5 5L19 19",key:"5zm2fv"}]]);/** * @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 Kre=te("MoveDown",[["path",{d:"M8 18L12 22L16 18",key:"cskvfv"}],["path",{d:"M12 2V22",key:"r89rzk"}]]);/** * @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 Yre=te("MoveHorizontal",[["path",{d:"m18 8 4 4-4 4",key:"1ak13k"}],["path",{d:"M2 12h20",key:"9i4pu4"}],["path",{d:"m6 8-4 4 4 4",key:"15zrgr"}]]);/** * @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 Zre=te("MoveLeft",[["path",{d:"M6 8L2 12L6 16",key:"kyvwex"}],["path",{d:"M2 12H22",key:"1m8cig"}]]);/** * @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 Xre=te("MoveRight",[["path",{d:"M18 8L22 12L18 16",key:"1r0oui"}],["path",{d:"M2 12H22",key:"1m8cig"}]]);/** * @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 Qre=te("MoveUpLeft",[["path",{d:"M5 11V5H11",key:"3q78g9"}],["path",{d:"M5 5L19 19",key:"5zm2fv"}]]);/** * @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 Jre=te("MoveUpRight",[["path",{d:"M13 5H19V11",key:"1n1gyv"}],["path",{d:"M19 5L5 19",key:"72u4yj"}]]);/** * @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 ene=te("MoveUp",[["path",{d:"M8 6L12 2L16 6",key:"1yvkyx"}],["path",{d:"M12 2V22",key:"r89rzk"}]]);/** * @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 tne=te("MoveVertical",[["path",{d:"M12 2v20",key:"t6zp3m"}],["path",{d:"m8 18 4 4 4-4",key:"bh5tu3"}],["path",{d:"m8 6 4-4 4 4",key:"ybng9g"}]]);/** * @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 sne=te("Move",[["path",{d:"M12 2v20",key:"t6zp3m"}],["path",{d:"m15 19-3 3-3-3",key:"11eu04"}],["path",{d:"m19 9 3 3-3 3",key:"1mg7y2"}],["path",{d:"M2 12h20",key:"9i4pu4"}],["path",{d:"m5 9-3 3 3 3",key:"j64kie"}],["path",{d:"m9 5 3-3 3 3",key:"l8vdw6"}]]);/** * @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 rne=te("Music2",[["circle",{cx:"8",cy:"18",r:"4",key:"1fc0mg"}],["path",{d:"M12 18V2l7 4",key:"g04rme"}]]);/** * @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 nne=te("Music3",[["circle",{cx:"12",cy:"18",r:"4",key:"m3r9ws"}],["path",{d:"M16 18V2",key:"40x2m5"}]]);/** * @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 ane=te("Music4",[["path",{d:"M9 18V5l12-2v13",key:"1jmyc2"}],["path",{d:"m9 9 12-2",key:"1e64n2"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}],["circle",{cx:"18",cy:"16",r:"3",key:"1hluhg"}]]);/** * @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 GI=te("Music",[["path",{d:"M9 18V5l12-2v13",key:"1jmyc2"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}],["circle",{cx:"18",cy:"16",r:"3",key:"1hluhg"}]]);/** * @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 ine=te("Navigation2Off",[["path",{d:"M9.31 9.31 5 21l7-4 7 4-1.17-3.17",key:"qoq2o2"}],["path",{d:"M14.53 8.88 12 2l-1.17 3.17",key:"k3sjzy"}],["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}]]);/** * @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 one=te("Navigation2",[["polygon",{points:"12 2 19 21 12 17 5 21 12 2",key:"x8c0qg"}]]);/** * @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 lne=te("NavigationOff",[["path",{d:"M8.43 8.43 3 11l8 2 2 8 2.57-5.43",key:"1vdtb7"}],["path",{d:"M17.39 11.73 22 2l-9.73 4.61",key:"tya3r6"}],["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}]]);/** * @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 wF=te("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 cne=te("Network",[["rect",{x:"16",y:"16",width:"6",height:"6",rx:"1",key:"4q2zg0"}],["rect",{x:"2",y:"16",width:"6",height:"6",rx:"1",key:"8cvhb9"}],["rect",{x:"9",y:"2",width:"6",height:"6",rx:"1",key:"1egb70"}],["path",{d:"M5 16v-3a1 1 0 0 1 1-1h12a1 1 0 0 1 1 1v3",key:"1jsf9p"}],["path",{d:"M12 12V8",key:"2874zd"}]]);/** * @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 x_=te("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 dne=te("Nfc",[["path",{d:"M6 8.32a7.43 7.43 0 0 1 0 7.36",key:"9iaqei"}],["path",{d:"M9.46 6.21a11.76 11.76 0 0 1 0 11.58",key:"1yha7l"}],["path",{d:"M12.91 4.1a15.91 15.91 0 0 1 .01 15.8",key:"4iu2gk"}],["path",{d:"M16.37 2a20.16 20.16 0 0 1 0 20",key:"sap9u2"}]]);/** * @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 une=te("NotebookPen",[["path",{d:"M13.4 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-7.4",key:"re6nr2"}],["path",{d:"M2 6h4",key:"aawbzj"}],["path",{d:"M2 10h4",key:"l0bgd4"}],["path",{d:"M2 14h4",key:"1gsvsf"}],["path",{d:"M2 18h4",key:"1bu2t1"}],["path",{d:"M21.378 5.626a1 1 0 1 0-3.004-3.004l-5.01 5.012a2 2 0 0 0-.506.854l-.837 2.87a.5.5 0 0 0 .62.62l2.87-.837a2 2 0 0 0 .854-.506z",key:"pqwjuv"}]]);/** * @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 hne=te("NotebookTabs",[["path",{d:"M2 6h4",key:"aawbzj"}],["path",{d:"M2 10h4",key:"l0bgd4"}],["path",{d:"M2 14h4",key:"1gsvsf"}],["path",{d:"M2 18h4",key:"1bu2t1"}],["rect",{width:"16",height:"20",x:"4",y:"2",rx:"2",key:"1nb95v"}],["path",{d:"M15 2v20",key:"dcj49h"}],["path",{d:"M15 7h5",key:"1xj5lc"}],["path",{d:"M15 12h5",key:"w5shd9"}],["path",{d:"M15 17h5",key:"1qaofu"}]]);/** * @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 mne=te("NotebookText",[["path",{d:"M2 6h4",key:"aawbzj"}],["path",{d:"M2 10h4",key:"l0bgd4"}],["path",{d:"M2 14h4",key:"1gsvsf"}],["path",{d:"M2 18h4",key:"1bu2t1"}],["rect",{width:"16",height:"20",x:"4",y:"2",rx:"2",key:"1nb95v"}],["path",{d:"M9.5 8h5",key:"11mslq"}],["path",{d:"M9.5 12H16",key:"ktog6x"}],["path",{d:"M9.5 16H14",key:"p1seyn"}]]);/** * @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 fne=te("Notebook",[["path",{d:"M2 6h4",key:"aawbzj"}],["path",{d:"M2 10h4",key:"l0bgd4"}],["path",{d:"M2 14h4",key:"1gsvsf"}],["path",{d:"M2 18h4",key:"1bu2t1"}],["rect",{width:"16",height:"20",x:"4",y:"2",rx:"2",key:"1nb95v"}],["path",{d:"M16 2v20",key:"rotuqe"}]]);/** * @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 pne=te("NotepadTextDashed",[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M12 2v4",key:"3427ic"}],["path",{d:"M16 2v4",key:"4m81vk"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v2",key:"j91f56"}],["path",{d:"M20 12v2",key:"w8o0tu"}],["path",{d:"M20 18v2a2 2 0 0 1-2 2h-1",key:"1c9ggx"}],["path",{d:"M13 22h-2",key:"191ugt"}],["path",{d:"M7 22H6a2 2 0 0 1-2-2v-2",key:"1rt9px"}],["path",{d:"M4 14v-2",key:"1v0sqh"}],["path",{d:"M4 8V6a2 2 0 0 1 2-2h2",key:"1mwabg"}],["path",{d:"M8 10h6",key:"3oa6kw"}],["path",{d:"M8 14h8",key:"1fgep2"}],["path",{d:"M8 18h5",key:"17enja"}]]);/** * @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 gne=te("NotepadText",[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M12 2v4",key:"3427ic"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"16",height:"18",x:"4",y:"4",rx:"2",key:"1u9h20"}],["path",{d:"M8 10h6",key:"3oa6kw"}],["path",{d:"M8 14h8",key:"1fgep2"}],["path",{d:"M8 18h5",key:"17enja"}]]);/** * @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 xne=te("NutOff",[["path",{d:"M12 4V2",key:"1k5q1u"}],["path",{d:"M5 10v4a7.004 7.004 0 0 0 5.277 6.787c.412.104.802.292 1.102.592L12 22l.621-.621c.3-.3.69-.488 1.102-.592a7.01 7.01 0 0 0 4.125-2.939",key:"1xcvy9"}],["path",{d:"M19 10v3.343",key:"163tfc"}],["path",{d:"M12 12c-1.349-.573-1.905-1.005-2.5-2-.546.902-1.048 1.353-2.5 2-1.018-.644-1.46-1.08-2-2-1.028.71-1.69.918-3 1 1.081-1.048 1.757-2.03 2-3 .194-.776.84-1.551 1.79-2.21m11.654 5.997c.887-.457 1.28-.891 1.556-1.787 1.032.916 1.683 1.157 3 1-1.297-1.036-1.758-2.03-2-3-.5-2-4-4-8-4-.74 0-1.461.068-2.15.192",key:"17914v"}],["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}]]);/** * @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 yne=te("Nut",[["path",{d:"M12 4V2",key:"1k5q1u"}],["path",{d:"M5 10v4a7.004 7.004 0 0 0 5.277 6.787c.412.104.802.292 1.102.592L12 22l.621-.621c.3-.3.69-.488 1.102-.592A7.003 7.003 0 0 0 19 14v-4",key:"1tgyif"}],["path",{d:"M12 4C8 4 4.5 6 4 8c-.243.97-.919 1.952-2 3 1.31-.082 1.972-.29 3-1 .54.92.982 1.356 2 2 1.452-.647 1.954-1.098 2.5-2 .595.995 1.151 1.427 2.5 2 1.31-.621 1.862-1.058 2.5-2 .629.977 1.162 1.423 2.5 2 1.209-.548 1.68-.967 2-2 1.032.916 1.683 1.157 3 1-1.297-1.036-1.758-2.03-2-3-.5-2-4-4-8-4Z",key:"tnsqj"}]]);/** * @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 _2=te("OctagonAlert",[["path",{d:"M12 16h.01",key:"1drbdi"}],["path",{d:"M12 8v4",key:"1got3b"}],["path",{d:"M15.312 2a2 2 0 0 1 1.414.586l4.688 4.688A2 2 0 0 1 22 8.688v6.624a2 2 0 0 1-.586 1.414l-4.688 4.688a2 2 0 0 1-1.414.586H8.688a2 2 0 0 1-1.414-.586l-4.688-4.688A2 2 0 0 1 2 15.312V8.688a2 2 0 0 1 .586-1.414l4.688-4.688A2 2 0 0 1 8.688 2z",key:"1fd625"}]]);/** * @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 vne=te("OctagonMinus",[["path",{d:"M2.586 16.726A2 2 0 0 1 2 15.312V8.688a2 2 0 0 1 .586-1.414l4.688-4.688A2 2 0 0 1 8.688 2h6.624a2 2 0 0 1 1.414.586l4.688 4.688A2 2 0 0 1 22 8.688v6.624a2 2 0 0 1-.586 1.414l-4.688 4.688a2 2 0 0 1-1.414.586H8.688a2 2 0 0 1-1.414-.586z",key:"2d38gg"}],["path",{d:"M8 12h8",key:"1wcyev"}]]);/** * @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 U3=te("OctagonPause",[["path",{d:"M10 15V9",key:"1lckn7"}],["path",{d:"M14 15V9",key:"1muqhk"}],["path",{d:"M2.586 16.726A2 2 0 0 1 2 15.312V8.688a2 2 0 0 1 .586-1.414l4.688-4.688A2 2 0 0 1 8.688 2h6.624a2 2 0 0 1 1.414.586l4.688 4.688A2 2 0 0 1 22 8.688v6.624a2 2 0 0 1-.586 1.414l-4.688 4.688a2 2 0 0 1-1.414.586H8.688a2 2 0 0 1-1.414-.586z",key:"2d38gg"}]]);/** * @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 q3=te("OctagonX",[["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"M2.586 16.726A2 2 0 0 1 2 15.312V8.688a2 2 0 0 1 .586-1.414l4.688-4.688A2 2 0 0 1 8.688 2h6.624a2 2 0 0 1 1.414.586l4.688 4.688A2 2 0 0 1 22 8.688v6.624a2 2 0 0 1-.586 1.414l-4.688 4.688a2 2 0 0 1-1.414.586H8.688a2 2 0 0 1-1.414-.586z",key:"2d38gg"}],["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 bne=te("Octagon",[["path",{d:"M2.586 16.726A2 2 0 0 1 2 15.312V8.688a2 2 0 0 1 .586-1.414l4.688-4.688A2 2 0 0 1 8.688 2h6.624a2 2 0 0 1 1.414.586l4.688 4.688A2 2 0 0 1 22 8.688v6.624a2 2 0 0 1-.586 1.414l-4.688 4.688a2 2 0 0 1-1.414.586H8.688a2 2 0 0 1-1.414-.586z",key:"2d38gg"}]]);/** * @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 _ne=te("Omega",[["path",{d:"M3 20h4.5a.5.5 0 0 0 .5-.5v-.282a.52.52 0 0 0-.247-.437 8 8 0 1 1 8.494-.001.52.52 0 0 0-.247.438v.282a.5.5 0 0 0 .5.5H21",key:"1x94xo"}]]);/** * @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 wne=te("Option",[["path",{d:"M3 3h6l6 18h6",key:"ph9rgk"}],["path",{d:"M14 3h7",key:"16f0ms"}]]);/** * @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 jne=te("Orbit",[["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}],["circle",{cx:"19",cy:"5",r:"2",key:"mhkx31"}],["circle",{cx:"5",cy:"19",r:"2",key:"v8kfzx"}],["path",{d:"M10.4 21.9a10 10 0 0 0 9.941-15.416",key:"eohfx2"}],["path",{d:"M13.5 2.1a10 10 0 0 0-9.841 15.416",key:"19pvbm"}]]);/** * @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 Nne=te("Origami",[["path",{d:"M12 12V4a1 1 0 0 1 1-1h6.297a1 1 0 0 1 .651 1.759l-4.696 4.025",key:"1bx4vc"}],["path",{d:"m12 21-7.414-7.414A2 2 0 0 1 4 12.172V6.415a1.002 1.002 0 0 1 1.707-.707L20 20.009",key:"1h3km6"}],["path",{d:"m12.214 3.381 8.414 14.966a1 1 0 0 1-.167 1.199l-1.168 1.163a1 1 0 0 1-.706.291H6.351a1 1 0 0 1-.625-.219L3.25 18.8a1 1 0 0 1 .631-1.781l4.165.027",key:"1hj4wg"}]]);/** * @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 kne=te("Package2",[["path",{d:"M3 9h18v10a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V9Z",key:"1ront0"}],["path",{d:"m3 9 2.45-4.9A2 2 0 0 1 7.24 3h9.52a2 2 0 0 1 1.8 1.1L21 9",key:"19h2x1"}],["path",{d:"M12 3v6",key:"1holv5"}]]);/** * @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 Sne=te("PackageCheck",[["path",{d:"m16 16 2 2 4-4",key:"gfu2re"}],["path",{d:"M21 10V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l2-1.14",key:"e7tb2h"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["line",{x1:"12",x2:"12",y1:"22",y2:"12",key:"a4e8g8"}]]);/** * @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 Cne=te("PackageMinus",[["path",{d:"M16 16h6",key:"100bgy"}],["path",{d:"M21 10V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l2-1.14",key:"e7tb2h"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["line",{x1:"12",x2:"12",y1:"22",y2:"12",key:"a4e8g8"}]]);/** * @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 Tne=te("PackageOpen",[["path",{d:"M12 22v-9",key:"x3hkom"}],["path",{d:"M15.17 2.21a1.67 1.67 0 0 1 1.63 0L21 4.57a1.93 1.93 0 0 1 0 3.36L8.82 14.79a1.655 1.655 0 0 1-1.64 0L3 12.43a1.93 1.93 0 0 1 0-3.36z",key:"2ntwy6"}],["path",{d:"M20 13v3.87a2.06 2.06 0 0 1-1.11 1.83l-6 3.08a1.93 1.93 0 0 1-1.78 0l-6-3.08A2.06 2.06 0 0 1 4 16.87V13",key:"1pmm1c"}],["path",{d:"M21 12.43a1.93 1.93 0 0 0 0-3.36L8.83 2.2a1.64 1.64 0 0 0-1.63 0L3 4.57a1.93 1.93 0 0 0 0 3.36l12.18 6.86a1.636 1.636 0 0 0 1.63 0z",key:"12ttoo"}]]);/** * @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 Ene=te("PackagePlus",[["path",{d:"M16 16h6",key:"100bgy"}],["path",{d:"M19 13v6",key:"85cyf1"}],["path",{d:"M21 10V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l2-1.14",key:"e7tb2h"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["line",{x1:"12",x2:"12",y1:"22",y2:"12",key:"a4e8g8"}]]);/** * @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 Ane=te("PackageSearch",[["path",{d:"M21 10V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l2-1.14",key:"e7tb2h"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["line",{x1:"12",x2:"12",y1:"22",y2:"12",key:"a4e8g8"}],["circle",{cx:"18.5",cy:"15.5",r:"2.5",key:"b5zd12"}],["path",{d:"M20.27 17.27 22 19",key:"1l4muz"}]]);/** * @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 Mne=te("PackageX",[["path",{d:"M21 10V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l2-1.14",key:"e7tb2h"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["line",{x1:"12",x2:"12",y1:"22",y2:"12",key:"a4e8g8"}],["path",{d:"m17 13 5 5m-5 0 5-5",key:"im3w4b"}]]);/** * @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=te("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 Ine=te("PaintBucket",[["path",{d:"m19 11-8-8-8.6 8.6a2 2 0 0 0 0 2.8l5.2 5.2c.8.8 2 .8 2.8 0L19 11Z",key:"irua1i"}],["path",{d:"m5 2 5 5",key:"1lls2c"}],["path",{d:"M2 13h15",key:"1hkzvu"}],["path",{d:"M22 20a2 2 0 1 1-4 0c0-1.6 1.7-2.4 2-4 .3 1.6 2 2.4 2 4Z",key:"xk76lq"}]]);/** * @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 Pne=te("PaintRoller",[["rect",{width:"16",height:"6",x:"2",y:"2",rx:"2",key:"jcyz7m"}],["path",{d:"M10 16v-2a2 2 0 0 1 2-2h8a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2h-2",key:"1b9h7c"}],["rect",{width:"4",height:"6",x:"8",y:"16",rx:"1",key:"d6e7yl"}]]);/** * @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 V3=te("PaintbrushVertical",[["path",{d:"M10 2v2",key:"7u0qdc"}],["path",{d:"M14 2v4",key:"qmzblu"}],["path",{d:"M17 2a1 1 0 0 1 1 1v9H6V3a1 1 0 0 1 1-1z",key:"ycvu00"}],["path",{d:"M6 12a1 1 0 0 0-1 1v1a2 2 0 0 0 2 2h2a1 1 0 0 1 1 1v2.9a2 2 0 1 0 4 0V17a1 1 0 0 1 1-1h2a2 2 0 0 0 2-2v-1a1 1 0 0 0-1-1",key:"iw4wnp"}]]);/** * @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 Lne=te("Paintbrush",[["path",{d:"m14.622 17.897-10.68-2.913",key:"vj2p1u"}],["path",{d:"M18.376 2.622a1 1 0 1 1 3.002 3.002L17.36 9.643a.5.5 0 0 0 0 .707l.944.944a2.41 2.41 0 0 1 0 3.408l-.944.944a.5.5 0 0 1-.707 0L8.354 7.348a.5.5 0 0 1 0-.707l.944-.944a2.41 2.41 0 0 1 3.408 0l.944.944a.5.5 0 0 0 .707 0z",key:"18tc5c"}],["path",{d:"M9 8c-1.804 2.71-3.97 3.46-6.583 3.948a.507.507 0 0 0-.302.819l7.32 8.883a1 1 0 0 0 1.185.204C12.735 20.405 16 16.792 16 15",key:"ytzfxy"}]]);/** * @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 pl=te("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 Dne=te("PanelBottomClose",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 15h18",key:"5xshup"}],["path",{d:"m15 8-3 3-3-3",key:"1oxy1z"}]]);/** * @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 H3=te("PanelBottomDashed",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M14 15h1",key:"171nev"}],["path",{d:"M19 15h2",key:"1vnucp"}],["path",{d:"M3 15h2",key:"8bym0q"}],["path",{d:"M9 15h1",key:"1tg3ks"}]]);/** * @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 Rne=te("PanelBottomOpen",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 15h18",key:"5xshup"}],["path",{d:"m9 10 3-3 3 3",key:"11gsxs"}]]);/** * @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 One=te("PanelBottom",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 15h18",key:"5xshup"}]]);/** * @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 G3=te("PanelLeftClose",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"m16 15-3-3 3-3",key:"14y99z"}]]);/** * @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 W3=te("PanelLeftDashed",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 14v1",key:"askpd8"}],["path",{d:"M9 19v2",key:"16tejx"}],["path",{d:"M9 3v2",key:"1noubl"}],["path",{d:"M9 9v1",key:"19ebxg"}]]);/** * @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 K3=te("PanelLeftOpen",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"m14 9 3 3-3 3",key:"8010ee"}]]);/** * @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 Y3=te("PanelLeft",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]]);/** * @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 Fne=te("PanelRightClose",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}],["path",{d:"m8 9 3 3-3 3",key:"12hl5m"}]]);/** * @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 Z3=te("PanelRightDashed",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 14v1",key:"ilsfch"}],["path",{d:"M15 19v2",key:"1fst2f"}],["path",{d:"M15 3v2",key:"z204g4"}],["path",{d:"M15 9v1",key:"z2a8b1"}]]);/** * @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 Bne=te("PanelRightOpen",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}],["path",{d:"m10 15-3-3 3-3",key:"1pgupc"}]]);/** * @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 zne=te("PanelRight",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["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 $ne=te("PanelTopClose",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 9h18",key:"1pudct"}],["path",{d:"m9 16 3-3 3 3",key:"1idcnm"}]]);/** * @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 X3=te("PanelTopDashed",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M14 9h1",key:"l0svgy"}],["path",{d:"M19 9h2",key:"te2zfg"}],["path",{d:"M3 9h2",key:"1h4ldw"}],["path",{d:"M9 9h1",key:"15jzuz"}]]);/** * @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 Une=te("PanelTopOpen",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 9h18",key:"1pudct"}],["path",{d:"m15 14-3 3-3-3",key:"g215vf"}]]);/** * @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 qne=te("PanelTop",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 9h18",key:"1pudct"}]]);/** * @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 Vne=te("PanelsLeftBottom",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"M9 15h12",key:"5ijen5"}]]);/** * @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 Hne=te("PanelsRightBottom",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 15h12",key:"1wkqb3"}],["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 w2=te("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 Hk=te("Paperclip",[["path",{d:"m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 18 8.84l-8.59 8.57a2 2 0 0 1-2.83-2.83l8.49-8.48",key:"1u3ebp"}]]);/** * @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 Gne=te("Parentheses",[["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"}]]);/** * @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 Wne=te("ParkingMeter",[["path",{d:"M11 15h2",key:"199qp6"}],["path",{d:"M12 12v3",key:"158kv8"}],["path",{d:"M12 19v3",key:"npa21l"}],["path",{d:"M15.282 19a1 1 0 0 0 .948-.68l2.37-6.988a7 7 0 1 0-13.2 0l2.37 6.988a1 1 0 0 0 .948.68z",key:"1jofit"}],["path",{d:"M9 9a3 3 0 1 1 6 0",key:"jdoeu8"}]]);/** * @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 gh=te("PartyPopper",[["path",{d:"M5.8 11.3 2 22l10.7-3.79",key:"gwxi1d"}],["path",{d:"M4 3h.01",key:"1vcuye"}],["path",{d:"M22 8h.01",key:"1mrtc2"}],["path",{d:"M15 2h.01",key:"1cjtqr"}],["path",{d:"M22 20h.01",key:"1mrys2"}],["path",{d:"m22 2-2.24.75a2.9 2.9 0 0 0-1.96 3.12c.1.86-.57 1.63-1.45 1.63h-.38c-.86 0-1.6.6-1.76 1.44L14 10",key:"hbicv8"}],["path",{d:"m22 13-.82-.33c-.86-.34-1.82.2-1.98 1.11c-.11.7-.72 1.22-1.43 1.22H17",key:"1i94pl"}],["path",{d:"m11 2 .33.82c.34.86-.2 1.82-1.11 1.98C9.52 4.9 9 5.52 9 6.23V7",key:"1cofks"}],["path",{d:"M11 13c1.93 1.93 2.83 4.17 2 5-.83.83-3.07-.07-5-2-1.93-1.93-2.83-4.17-2-5 .83-.83 3.07.07 5 2Z",key:"4kbmks"}]]);/** * @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 Hf=te("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 Kne=te("PawPrint",[["circle",{cx:"11",cy:"4",r:"2",key:"vol9p0"}],["circle",{cx:"18",cy:"8",r:"2",key:"17gozi"}],["circle",{cx:"20",cy:"16",r:"2",key:"1v9bxh"}],["path",{d:"M9 10a5 5 0 0 1 5 5v3.5a3.5 3.5 0 0 1-6.84 1.045Q6.52 17.48 4.46 16.84A3.5 3.5 0 0 1 5.5 10Z",key:"1ydw1z"}]]);/** * @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 Yne=te("PcCase",[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",key:"1uq1d7"}],["path",{d:"M15 14h.01",key:"1kp3bh"}],["path",{d:"M9 6h6",key:"dgm16u"}],["path",{d:"M9 10h6",key:"9gxzsh"}]]);/** * @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 Gb=te("PenLine",[["path",{d:"M12 20h9",key:"t2du7b"}],["path",{d:"M16.376 3.622a1 1 0 0 1 3.002 3.002L7.368 18.635a2 2 0 0 1-.855.506l-2.872.838a.5.5 0 0 1-.62-.62l.838-2.872a2 2 0 0 1 .506-.854z",key:"1ykcvy"}]]);/** * @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 Zne=te("PenOff",[["path",{d:"m10 10-6.157 6.162a2 2 0 0 0-.5.833l-1.322 4.36a.5.5 0 0 0 .622.624l4.358-1.323a2 2 0 0 0 .83-.5L14 13.982",key:"bjo8r8"}],["path",{d:"m12.829 7.172 4.359-4.346a1 1 0 1 1 3.986 3.986l-4.353 4.353",key:"16h5ne"}],["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 Gk=te("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 Wb=te("Pen",[["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"}]]);/** * @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 Xne=te("PencilLine",[["path",{d:"M12 20h9",key:"t2du7b"}],["path",{d:"M16.376 3.622a1 1 0 0 1 3.002 3.002L7.368 18.635a2 2 0 0 1-.855.506l-2.872.838a.5.5 0 0 1-.62-.62l.838-2.872a2 2 0 0 1 .506-.854z",key:"1ykcvy"}],["path",{d:"m15 5 3 3",key:"1w25hb"}]]);/** * @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 Qne=te("PencilOff",[["path",{d:"m10 10-6.157 6.162a2 2 0 0 0-.5.833l-1.322 4.36a.5.5 0 0 0 .622.624l4.358-1.323a2 2 0 0 0 .83-.5L14 13.982",key:"bjo8r8"}],["path",{d:"m12.829 7.172 4.359-4.346a1 1 0 1 1 3.986 3.986l-4.353 4.353",key:"16h5ne"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}],["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 Jne=te("PencilRuler",[["path",{d:"M13 7 8.7 2.7a2.41 2.41 0 0 0-3.4 0L2.7 5.3a2.41 2.41 0 0 0 0 3.4L7 13",key:"orapub"}],["path",{d:"m8 6 2-2",key:"115y1s"}],["path",{d:"m18 16 2-2",key:"ee94s4"}],["path",{d:"m17 11 4.3 4.3c.94.94.94 2.46 0 3.4l-2.6 2.6c-.94.94-2.46.94-3.4 0L11 17",key:"cfq27r"}],["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 ni=te("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 eae=te("Pentagon",[["path",{d:"M10.83 2.38a2 2 0 0 1 2.34 0l8 5.74a2 2 0 0 1 .73 2.25l-3.04 9.26a2 2 0 0 1-1.9 1.37H7.04a2 2 0 0 1-1.9-1.37L2.1 10.37a2 2 0 0 1 .73-2.25z",key:"2hea0t"}]]);/** * @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 ME=te("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 tae=te("PersonStanding",[["circle",{cx:"12",cy:"5",r:"1",key:"gxeob9"}],["path",{d:"m9 20 3-6 3 6",key:"se2kox"}],["path",{d:"m6 8 6 2 6-2",key:"4o3us4"}],["path",{d:"M12 10v4",key:"1kjpxc"}]]);/** * @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 sae=te("PhilippinePeso",[["path",{d:"M20 11H4",key:"6ut86h"}],["path",{d:"M20 7H4",key:"zbl0bi"}],["path",{d:"M7 21V4a1 1 0 0 1 1-1h4a1 1 0 0 1 0 12H7",key:"1ana5r"}]]);/** * @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 rae=te("PhoneCall",[["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"}],["path",{d:"M14.05 2a9 9 0 0 1 8 7.94",key:"vmijpz"}],["path",{d:"M14.05 6A5 5 0 0 1 18 10",key:"13nbpp"}]]);/** * @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 nae=te("PhoneForwarded",[["polyline",{points:"18 2 22 6 18 10",key:"6vjanh"}],["line",{x1:"14",x2:"22",y1:"6",y2:"6",key:"1jsywh"}],["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 aae=te("PhoneIncoming",[["polyline",{points:"16 2 16 8 22 8",key:"1ygljm"}],["line",{x1:"22",x2:"16",y1:"2",y2:"8",key:"1xzwqn"}],["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 iae=te("PhoneMissed",[["line",{x1:"22",x2:"16",y1:"2",y2:"8",key:"1xzwqn"}],["line",{x1:"16",x2:"22",y1:"2",y2:"8",key:"13zxdn"}],["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 oae=te("PhoneOff",[["path",{d:"M10.68 13.31a16 16 0 0 0 3.41 2.6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7 2 2 0 0 1 1.72 2v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.42 19.42 0 0 1-3.33-2.67m-2.67-3.34a19.79 19.79 0 0 1-3.07-8.63A2 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.91",key:"z86iuo"}],["line",{x1:"22",x2:"2",y1:"2",y2:"22",key:"11kh81"}]]);/** * @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 lae=te("PhoneOutgoing",[["polyline",{points:"22 8 22 2 16 2",key:"1g204g"}],["line",{x1:"16",x2:"22",y1:"8",y2:"2",key:"1ggias"}],["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 Yn=te("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 cae=te("Pi",[["line",{x1:"9",x2:"9",y1:"4",y2:"20",key:"ovs5a5"}],["path",{d:"M4 7c0-1.7 1.3-3 3-3h13",key:"10pag4"}],["path",{d:"M18 20c-1.7 0-3-1.3-3-3V4",key:"1gaosr"}]]);/** * @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 dae=te("Piano",[["path",{d:"M18.5 8c-1.4 0-2.6-.8-3.2-2A6.87 6.87 0 0 0 2 9v11a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-8.5C22 9.6 20.4 8 18.5 8",key:"lag0yf"}],["path",{d:"M2 14h20",key:"myj16y"}],["path",{d:"M6 14v4",key:"9ng0ue"}],["path",{d:"M10 14v4",key:"1v8uk5"}],["path",{d:"M14 14v4",key:"1tqops"}],["path",{d:"M18 14v4",key:"18uqwm"}]]);/** * @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 uae=te("Pickaxe",[["path",{d:"M14.531 12.469 6.619 20.38a1 1 0 1 1-3-3l7.912-7.912",key:"we99rg"}],["path",{d:"M15.686 4.314A12.5 12.5 0 0 0 5.461 2.958 1 1 0 0 0 5.58 4.71a22 22 0 0 1 6.318 3.393",key:"1w6hck"}],["path",{d:"M17.7 3.7a1 1 0 0 0-1.4 0l-4.6 4.6a1 1 0 0 0 0 1.4l2.6 2.6a1 1 0 0 0 1.4 0l4.6-4.6a1 1 0 0 0 0-1.4z",key:"15hgfx"}],["path",{d:"M19.686 8.314a12.501 12.501 0 0 1 1.356 10.225 1 1 0 0 1-1.751-.119 22 22 0 0 0-3.393-6.319",key:"452b4h"}]]);/** * @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 hae=te("PictureInPicture2",[["path",{d:"M21 9V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v10c0 1.1.9 2 2 2h4",key:"daa4of"}],["rect",{width:"10",height:"7",x:"12",y:"13",rx:"2",key:"1nb8gs"}]]);/** * @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 mae=te("PictureInPicture",[["path",{d:"M8 4.5v5H3m-1-6 6 6m13 0v-3c0-1.16-.84-2-2-2h-7m-9 9v2c0 1.05.95 2 2 2h3",key:"bcd8fb"}],["rect",{width:"10",height:"7",x:"12",y:"13.5",ry:"2",key:"136fx3"}]]);/** * @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 fae=te("PiggyBank",[["path",{d:"M19 5c-1.5 0-2.8 1.4-3 2-3.5-1.5-11-.3-11 5 0 1.8 0 3 2 4.5V20h4v-2h3v2h4v-4c1-.5 1.7-1 2-2h2v-4h-2c0-1-.5-1.5-1-2V5z",key:"1ivx2i"}],["path",{d:"M2 9v1c0 1.1.9 2 2 2h1",key:"nm575m"}],["path",{d:"M16 11h.01",key:"xkw8gn"}]]);/** * @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 pae=te("PilcrowLeft",[["path",{d:"M14 3v11",key:"mlfb7b"}],["path",{d:"M14 9h-3a3 3 0 0 1 0-6h9",key:"1ulc19"}],["path",{d:"M18 3v11",key:"1phi0r"}],["path",{d:"M22 18H2l4-4",key:"yt65j9"}],["path",{d:"m6 22-4-4",key:"6jgyf5"}]]);/** * @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 gae=te("PilcrowRight",[["path",{d:"M10 3v11",key:"o3l5kj"}],["path",{d:"M10 9H7a1 1 0 0 1 0-6h8",key:"1wb1nc"}],["path",{d:"M14 3v11",key:"mlfb7b"}],["path",{d:"m18 14 4 4H2",key:"4r8io1"}],["path",{d:"m22 18-4 4",key:"1hjjrd"}]]);/** * @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 xae=te("Pilcrow",[["path",{d:"M13 4v16",key:"8vvj80"}],["path",{d:"M17 4v16",key:"7dpous"}],["path",{d:"M19 4H9.5a4.5 4.5 0 0 0 0 9H13",key:"sh4n9v"}]]);/** * @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 yae=te("PillBottle",[["path",{d:"M18 11h-4a1 1 0 0 0-1 1v5a1 1 0 0 0 1 1h4",key:"17ldeb"}],["path",{d:"M6 7v13a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V7",key:"nc37y6"}],["rect",{width:"16",height:"5",x:"4",y:"2",rx:"1",key:"3jeezo"}]]);/** * @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 vae=te("Pill",[["path",{d:"m10.5 20.5 10-10a4.95 4.95 0 1 0-7-7l-10 10a4.95 4.95 0 1 0 7 7Z",key:"wa1lgi"}],["path",{d:"m8.5 8.5 7 7",key:"rvfmvr"}]]);/** * @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 jF=te("PinOff",[["path",{d:"M12 17v5",key:"bb1du9"}],["path",{d:"M15 9.34V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H7.89",key:"znwnzq"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M9 9v1.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V16a1 1 0 0 0 1 1h11",key:"c9qhm2"}]]);/** * @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 Wk=te("Pin",[["path",{d:"M12 17v5",key:"bb1du9"}],["path",{d:"M9 10.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V16a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-.76a2 2 0 0 0-1.11-1.79l-1.78-.9A2 2 0 0 1 15 10.76V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H8a2 2 0 0 0 0 4 1 1 0 0 1 1 1z",key:"1nkz8b"}]]);/** * @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 bae=te("Pipette",[["path",{d:"m2 22 1-1h3l9-9",key:"1sre89"}],["path",{d:"M3 21v-3l9-9",key:"hpe2y6"}],["path",{d:"m15 6 3.4-3.4a2.1 2.1 0 1 1 3 3L18 9l.4.4a2.1 2.1 0 1 1-3 3l-3.8-3.8a2.1 2.1 0 1 1 3-3l.4.4Z",key:"196du1"}]]);/** * @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 _ae=te("Pizza",[["path",{d:"m12 14-1 1",key:"11onhr"}],["path",{d:"m13.75 18.25-1.25 1.42",key:"1yisr3"}],["path",{d:"M17.775 5.654a15.68 15.68 0 0 0-12.121 12.12",key:"1qtqk6"}],["path",{d:"M18.8 9.3a1 1 0 0 0 2.1 7.7",key:"fbbbr2"}],["path",{d:"M21.964 20.732a1 1 0 0 1-1.232 1.232l-18-5a1 1 0 0 1-.695-1.232A19.68 19.68 0 0 1 15.732 2.037a1 1 0 0 1 1.232.695z",key:"1hyfdd"}]]);/** * @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 wae=te("PlaneLanding",[["path",{d:"M2 22h20",key:"272qi7"}],["path",{d:"M3.77 10.77 2 9l2-4.5 1.1.55c.55.28.9.84.9 1.45s.35 1.17.9 1.45L8 8.5l3-6 1.05.53a2 2 0 0 1 1.09 1.52l.72 5.4a2 2 0 0 0 1.09 1.52l4.4 2.2c.42.22.78.55 1.01.96l.6 1.03c.49.88-.06 1.98-1.06 2.1l-1.18.15c-.47.06-.95-.02-1.37-.24L4.29 11.15a2 2 0 0 1-.52-.38Z",key:"1ma21e"}]]);/** * @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 jae=te("PlaneTakeoff",[["path",{d:"M2 22h20",key:"272qi7"}],["path",{d:"M6.36 17.4 4 17l-2-4 1.1-.55a2 2 0 0 1 1.8 0l.17.1a2 2 0 0 0 1.8 0L8 12 5 6l.9-.45a2 2 0 0 1 2.09.2l4.02 3a2 2 0 0 0 2.1.2l4.19-2.06a2.41 2.41 0 0 1 1.73-.17L21 7a1.4 1.4 0 0 1 .87 1.99l-.38.76c-.23.46-.6.84-1.07 1.08L7.58 17.2a2 2 0 0 1-1.22.18Z",key:"fkigj9"}]]);/** * @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 NF=te("Plane",[["path",{d:"M17.8 19.2 16 11l3.5-3.5C21 6 21.5 4 21 3c-1-.5-3 0-4.5 1.5L13 8 4.8 6.2c-.5-.1-.9.1-1.1.5l-.3.5c-.2.5-.1 1 .3 1.3L9 12l-2 3H4l-1 1 3 2 2 3 1-1v-3l3-2 3.5 5.3c.3.4.8.5 1.3.3l.5-.2c.4-.3.6-.7.5-1.2z",key:"1v9wt8"}]]);/** * @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 El=te("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 Nae=te("Plug2",[["path",{d:"M9 2v6",key:"17ngun"}],["path",{d:"M15 2v6",key:"s7yy2p"}],["path",{d:"M12 17v5",key:"bb1du9"}],["path",{d:"M5 8h14",key:"pcz4l3"}],["path",{d:"M6 11V8h12v3a6 6 0 1 1-12 0Z",key:"wtfw2c"}]]);/** * @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 Q3=te("PlugZap",[["path",{d:"M6.3 20.3a2.4 2.4 0 0 0 3.4 0L12 18l-6-6-2.3 2.3a2.4 2.4 0 0 0 0 3.4Z",key:"goz73y"}],["path",{d:"m2 22 3-3",key:"19mgm9"}],["path",{d:"M7.5 13.5 10 11",key:"7xgeeb"}],["path",{d:"M10.5 16.5 13 14",key:"10btkg"}],["path",{d:"m18 3-4 4h6l-4 4",key:"16psg9"}]]);/** * @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 IE=te("Plug",[["path",{d:"M12 22v-5",key:"1ega77"}],["path",{d:"M9 8V2",key:"14iosj"}],["path",{d:"M15 8V2",key:"18g5xt"}],["path",{d:"M18 8v5a4 4 0 0 1-4 4h-4a4 4 0 0 1-4-4V8Z",key:"osxo6l"}]]);/** * @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 Ys=te("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 kae=te("PocketKnife",[["path",{d:"M3 2v1c0 1 2 1 2 2S3 6 3 7s2 1 2 2-2 1-2 2 2 1 2 2",key:"19w3oe"}],["path",{d:"M18 6h.01",key:"1v4wsw"}],["path",{d:"M6 18h.01",key:"uhywen"}],["path",{d:"M20.83 8.83a4 4 0 0 0-5.66-5.66l-12 12a4 4 0 1 0 5.66 5.66Z",key:"6fykxj"}],["path",{d:"M18 11.66V22a4 4 0 0 0 4-4V6",key:"1utzek"}]]);/** * @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 Sae=te("Pocket",[["path",{d:"M4 3h16a2 2 0 0 1 2 2v6a10 10 0 0 1-10 10A10 10 0 0 1 2 11V5a2 2 0 0 1 2-2z",key:"1mz881"}],["polyline",{points:"8 10 12 14 16 10",key:"w4mbv5"}]]);/** * @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 Cae=te("Podcast",[["path",{d:"M16.85 18.58a9 9 0 1 0-9.7 0",key:"d71mpg"}],["path",{d:"M8 14a5 5 0 1 1 8 0",key:"fc81rn"}],["circle",{cx:"12",cy:"11",r:"1",key:"1gvufo"}],["path",{d:"M13 17a1 1 0 1 0-2 0l.5 4.5a.5.5 0 1 0 1 0Z",key:"za5kbj"}]]);/** * @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 Tae=te("PointerOff",[["path",{d:"M10 4.5V4a2 2 0 0 0-2.41-1.957",key:"jsi14n"}],["path",{d:"M13.9 8.4a2 2 0 0 0-1.26-1.295",key:"hirc7f"}],["path",{d:"M21.7 16.2A8 8 0 0 0 22 14v-3a2 2 0 1 0-4 0v-1a2 2 0 0 0-3.63-1.158",key:"1jxb2e"}],["path",{d:"m7 15-1.8-1.8a2 2 0 0 0-2.79 2.86L6 19.7a7.74 7.74 0 0 0 6 2.3h2a8 8 0 0 0 5.657-2.343",key:"10r7hm"}],["path",{d:"M6 6v8",key:"tv5xkp"}],["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 Eae=te("Pointer",[["path",{d:"M22 14a8 8 0 0 1-8 8",key:"56vcr3"}],["path",{d:"M18 11v-1a2 2 0 0 0-2-2a2 2 0 0 0-2 2",key:"1agjmk"}],["path",{d:"M14 10V9a2 2 0 0 0-2-2a2 2 0 0 0-2 2v1",key:"wdbh2u"}],["path",{d:"M10 9.5V4a2 2 0 0 0-2-2a2 2 0 0 0-2 2v10",key:"1ibuk9"}],["path",{d:"M18 11a2 2 0 1 1 4 0v3a8 8 0 0 1-8 8h-2c-2.8 0-4.5-.86-5.99-2.34l-3.6-3.6a2 2 0 0 1 2.83-2.82L7 15",key:"g6ys72"}]]);/** * @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 Aae=te("Popcorn",[["path",{d:"M18 8a2 2 0 0 0 0-4 2 2 0 0 0-4 0 2 2 0 0 0-4 0 2 2 0 0 0-4 0 2 2 0 0 0 0 4",key:"10td1f"}],["path",{d:"M10 22 9 8",key:"yjptiv"}],["path",{d:"m14 22 1-14",key:"8jwc8b"}],["path",{d:"M20 8c.5 0 .9.4.8 1l-2.6 12c-.1.5-.7 1-1.2 1H7c-.6 0-1.1-.4-1.2-1L3.2 9c-.1-.6.3-1 .8-1Z",key:"1qo33t"}]]);/** * @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 Mae=te("Popsicle",[["path",{d:"M18.6 14.4c.8-.8.8-2 0-2.8l-8.1-8.1a4.95 4.95 0 1 0-7.1 7.1l8.1 8.1c.9.7 2.1.7 2.9-.1Z",key:"1o68ps"}],["path",{d:"m22 22-5.5-5.5",key:"17o70y"}]]);/** * @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 Iae=te("PoundSterling",[["path",{d:"M18 7c0-5.333-8-5.333-8 0",key:"1prm2n"}],["path",{d:"M10 7v14",key:"18tmcs"}],["path",{d:"M6 21h12",key:"4dkmi1"}],["path",{d:"M6 13h10",key:"ybwr4a"}]]);/** * @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 Pae=te("PowerOff",[["path",{d:"M18.36 6.64A9 9 0 0 1 20.77 15",key:"dxknvb"}],["path",{d:"M6.16 6.16a9 9 0 1 0 12.68 12.68",key:"1x7qb5"}],["path",{d:"M12 2v4",key:"3427ic"}],["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 kF=te("Power",[["path",{d:"M12 2v10",key:"mnfbl"}],["path",{d:"M18.4 6.6a9 9 0 1 1-12.77.04",key:"obofu9"}]]);/** * @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 _1=te("Presentation",[["path",{d:"M2 3h20",key:"91anmk"}],["path",{d:"M21 3v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V3",key:"2k9sn8"}],["path",{d:"m7 21 5-5 5 5",key:"bip4we"}]]);/** * @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 Lae=te("PrinterCheck",[["path",{d:"M13.5 22H7a1 1 0 0 1-1-1v-6a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v.5",key:"qeb09x"}],["path",{d:"m16 19 2 2 4-4",key:"1b14m6"}],["path",{d:"M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v2",key:"1md90i"}],["path",{d:"M6 9V3a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v6",key:"1itne7"}]]);/** * @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=te("Printer",[["path",{d:"M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2",key:"143wyd"}],["path",{d:"M6 9V3a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v6",key:"1itne7"}],["rect",{x:"6",y:"14",width:"12",height:"8",rx:"1",key:"1ue0tg"}]]);/** * @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 Dae=te("Projector",[["path",{d:"M5 7 3 5",key:"1yys58"}],["path",{d:"M9 6V3",key:"1ptz9u"}],["path",{d:"m13 7 2-2",key:"1w3vmq"}],["circle",{cx:"9",cy:"13",r:"3",key:"1mma13"}],["path",{d:"M11.83 12H20a2 2 0 0 1 2 2v4a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2v-4a2 2 0 0 1 2-2h2.17",key:"2frwzc"}],["path",{d:"M16 16h2",key:"dnq2od"}]]);/** * @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 Rae=te("Proportions",[["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}],["path",{d:"M12 9v11",key:"1fnkrn"}],["path",{d:"M2 9h13a2 2 0 0 1 2 2v9",key:"11z3ex"}]]);/** * @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 Oae=te("Puzzle",[["path",{d:"M15.39 4.39a1 1 0 0 0 1.68-.474 2.5 2.5 0 1 1 3.014 3.015 1 1 0 0 0-.474 1.68l1.683 1.682a2.414 2.414 0 0 1 0 3.414L19.61 15.39a1 1 0 0 1-1.68-.474 2.5 2.5 0 1 0-3.014 3.015 1 1 0 0 1 .474 1.68l-1.683 1.682a2.414 2.414 0 0 1-3.414 0L8.61 19.61a1 1 0 0 0-1.68.474 2.5 2.5 0 1 1-3.014-3.015 1 1 0 0 0 .474-1.68l-1.683-1.682a2.414 2.414 0 0 1 0-3.414L4.39 8.61a1 1 0 0 1 1.68.474 2.5 2.5 0 1 0 3.014-3.015 1 1 0 0 1-.474-1.68l1.683-1.682a2.414 2.414 0 0 1 3.414 0z",key:"w46dr5"}]]);/** * @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 Fae=te("Pyramid",[["path",{d:"M2.5 16.88a1 1 0 0 1-.32-1.43l9-13.02a1 1 0 0 1 1.64 0l9 13.01a1 1 0 0 1-.32 1.44l-8.51 4.86a2 2 0 0 1-1.98 0Z",key:"aenxs0"}],["path",{d:"M12 2v20",key:"t6zp3m"}]]);/** * @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 y_=te("QrCode",[["rect",{width:"5",height:"5",x:"3",y:"3",rx:"1",key:"1tu5fj"}],["rect",{width:"5",height:"5",x:"16",y:"3",rx:"1",key:"1v8r4q"}],["rect",{width:"5",height:"5",x:"3",y:"16",rx:"1",key:"1x03jg"}],["path",{d:"M21 16h-3a2 2 0 0 0-2 2v3",key:"177gqh"}],["path",{d:"M21 21v.01",key:"ents32"}],["path",{d:"M12 7v3a2 2 0 0 1-2 2H7",key:"8crl2c"}],["path",{d:"M3 12h.01",key:"nlz23k"}],["path",{d:"M12 3h.01",key:"n36tog"}],["path",{d:"M12 16v.01",key:"133mhm"}],["path",{d:"M16 12h1",key:"1slzba"}],["path",{d:"M21 12v.01",key:"1lwtk9"}],["path",{d:"M12 21v-1",key:"1880an"}]]);/** * @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 Kk=te("Quote",[["path",{d:"M16 3a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2 1 1 0 0 1 1 1v1a2 2 0 0 1-2 2 1 1 0 0 0-1 1v2a1 1 0 0 0 1 1 6 6 0 0 0 6-6V5a2 2 0 0 0-2-2z",key:"rib7q0"}],["path",{d:"M5 3a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2 1 1 0 0 1 1 1v1a2 2 0 0 1-2 2 1 1 0 0 0-1 1v2a1 1 0 0 0 1 1 6 6 0 0 0 6-6V5a2 2 0 0 0-2-2z",key:"1ymkrd"}]]);/** * @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 Bae=te("Rabbit",[["path",{d:"M13 16a3 3 0 0 1 2.24 5",key:"1epib5"}],["path",{d:"M18 12h.01",key:"yjnet6"}],["path",{d:"M18 21h-8a4 4 0 0 1-4-4 7 7 0 0 1 7-7h.2L9.6 6.4a1 1 0 1 1 2.8-2.8L15.8 7h.2c3.3 0 6 2.7 6 6v1a2 2 0 0 1-2 2h-1a3 3 0 0 0-3 3",key:"ue9ozu"}],["path",{d:"M20 8.54V4a2 2 0 1 0-4 0v3",key:"49iql8"}],["path",{d:"M7.612 12.524a3 3 0 1 0-1.6 4.3",key:"1e33i0"}]]);/** * @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 WI=te("Radar",[["path",{d:"M19.07 4.93A10 10 0 0 0 6.99 3.34",key:"z3du51"}],["path",{d:"M4 6h.01",key:"oypzma"}],["path",{d:"M2.29 9.62A10 10 0 1 0 21.31 8.35",key:"qzzz0"}],["path",{d:"M16.24 7.76A6 6 0 1 0 8.23 16.67",key:"1yjesh"}],["path",{d:"M12 18h.01",key:"mhygvu"}],["path",{d:"M17.99 11.66A6 6 0 0 1 15.77 16.67",key:"1u2y91"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}],["path",{d:"m13.41 10.59 5.66-5.66",key:"mhq4k0"}]]);/** * @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 zae=te("Radiation",[["path",{d:"M12 12h.01",key:"1mp3jc"}],["path",{d:"M7.5 4.2c-.3-.5-.9-.7-1.3-.4C3.9 5.5 2.3 8.1 2 11c-.1.5.4 1 1 1h5c0-1.5.8-2.8 2-3.4-1.1-1.9-2-3.5-2.5-4.4z",key:"wy49g3"}],["path",{d:"M21 12c.6 0 1-.4 1-1-.3-2.9-1.8-5.5-4.1-7.1-.4-.3-1.1-.2-1.3.3-.6.9-1.5 2.5-2.6 4.3 1.2.7 2 2 2 3.5h5z",key:"vklnvr"}],["path",{d:"M7.5 19.8c-.3.5-.1 1.1.4 1.3 2.6 1.2 5.6 1.2 8.2 0 .5-.2.7-.8.4-1.3-.5-.9-1.4-2.5-2.5-4.3-1.2.7-2.8.7-4 0-1.1 1.8-2 3.4-2.5 4.3z",key:"wkdf1o"}]]);/** * @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 $ae=te("Radical",[["path",{d:"M3 12h3.28a1 1 0 0 1 .948.684l2.298 7.934a.5.5 0 0 0 .96-.044L13.82 4.771A1 1 0 0 1 14.792 4H21",key:"1mqj8i"}]]);/** * @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 Uae=te("RadioReceiver",[["path",{d:"M5 16v2",key:"g5qcv5"}],["path",{d:"M19 16v2",key:"1gbaio"}],["rect",{width:"20",height:"8",x:"2",y:"8",rx:"2",key:"vjsjur"}],["path",{d:"M18 12h.01",key:"yjnet6"}]]);/** * @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 qae=te("RadioTower",[["path",{d:"M4.9 16.1C1 12.2 1 5.8 4.9 1.9",key:"s0qx1y"}],["path",{d:"M7.8 4.7a6.14 6.14 0 0 0-.8 7.5",key:"1idnkw"}],["circle",{cx:"12",cy:"9",r:"2",key:"1092wv"}],["path",{d:"M16.2 4.8c2 2 2.26 5.11.8 7.47",key:"ojru2q"}],["path",{d:"M19.1 1.9a9.96 9.96 0 0 1 0 14.1",key:"rhi7fg"}],["path",{d:"M9.5 18h5",key:"mfy3pd"}],["path",{d:"m8 22 4-11 4 11",key:"25yftu"}]]);/** * @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=te("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 Vae=te("Radius",[["path",{d:"M20.34 17.52a10 10 0 1 0-2.82 2.82",key:"fydyku"}],["circle",{cx:"19",cy:"19",r:"2",key:"17f5cg"}],["path",{d:"m13.41 13.41 4.18 4.18",key:"1gqbwc"}],["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 Hae=te("RailSymbol",[["path",{d:"M5 15h14",key:"m0yey3"}],["path",{d:"M5 9h14",key:"7tsvo6"}],["path",{d:"m14 20-5-5 6-6-5-5",key:"1jo42i"}]]);/** * @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 Gae=te("Rainbow",[["path",{d:"M22 17a10 10 0 0 0-20 0",key:"ozegv"}],["path",{d:"M6 17a6 6 0 0 1 12 0",key:"5giftw"}],["path",{d:"M10 17a2 2 0 0 1 4 0",key:"gnsikk"}]]);/** * @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 Wae=te("Rat",[["path",{d:"M17 5c0-1.7-1.3-3-3-3s-3 1.3-3 3c0 .8.3 1.5.8 2H11c-3.9 0-7 3.1-7 7c0 2.2 1.8 4 4 4",key:"1wq71c"}],["path",{d:"M16.8 3.9c.3-.3.6-.5 1-.7 1.5-.6 3.3.1 3.9 1.6.6 1.5-.1 3.3-1.6 3.9l1.6 2.8c.2.3.2.7.2 1-.2.8-.9 1.2-1.7 1.1 0 0-1.6-.3-2.7-.6H17c-1.7 0-3 1.3-3 3",key:"1crdmb"}],["path",{d:"M13.2 18a3 3 0 0 0-2.2-5",key:"1ol3lk"}],["path",{d:"M13 22H4a2 2 0 0 1 0-4h12",key:"bt3f23"}],["path",{d:"M16 9h.01",key:"1bdo4e"}]]);/** * @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 Kae=te("Ratio",[["rect",{width:"12",height:"20",x:"6",y:"2",rx:"2",key:"1oxtiu"}],["rect",{width:"20",height:"12",x:"2",y:"6",rx:"2",key:"9lu3g6"}]]);/** * @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 Yae=te("ReceiptCent",[["path",{d:"M4 2v20l2-1 2 1 2-1 2 1 2-1 2 1 2-1 2 1V2l-2 1-2-1-2 1-2-1-2 1-2-1-2 1Z",key:"q3az6g"}],["path",{d:"M12 6.5v11",key:"ecfhkf"}],["path",{d:"M15 9.4a4 4 0 1 0 0 5.2",key:"1makmb"}]]);/** * @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 Zae=te("ReceiptEuro",[["path",{d:"M4 2v20l2-1 2 1 2-1 2 1 2-1 2 1 2-1 2 1V2l-2 1-2-1-2 1-2-1-2 1-2-1-2 1Z",key:"q3az6g"}],["path",{d:"M8 12h5",key:"1g6qi8"}],["path",{d:"M16 9.5a4 4 0 1 0 0 5.2",key:"b2px4r"}]]);/** * @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 Xae=te("ReceiptIndianRupee",[["path",{d:"M4 2v20l2-1 2 1 2-1 2 1 2-1 2 1 2-1 2 1V2l-2 1-2-1-2 1-2-1-2 1-2-1-2 1Z",key:"q3az6g"}],["path",{d:"M8 7h8",key:"i86dvs"}],["path",{d:"M12 17.5 8 15h1a4 4 0 0 0 0-8",key:"grpkl4"}],["path",{d:"M8 11h8",key:"vwpz6n"}]]);/** * @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 Qae=te("ReceiptJapaneseYen",[["path",{d:"M4 2v20l2-1 2 1 2-1 2 1 2-1 2 1 2-1 2 1V2l-2 1-2-1-2 1-2-1-2 1-2-1-2 1Z",key:"q3az6g"}],["path",{d:"m12 10 3-3",key:"1mc12w"}],["path",{d:"m9 7 3 3v7.5",key:"39i0xv"}],["path",{d:"M9 11h6",key:"1fldmi"}],["path",{d:"M9 15h6",key:"cctwl0"}]]);/** * @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 Jae=te("ReceiptPoundSterling",[["path",{d:"M4 2v20l2-1 2 1 2-1 2 1 2-1 2 1 2-1 2 1V2l-2 1-2-1-2 1-2-1-2 1-2-1-2 1Z",key:"q3az6g"}],["path",{d:"M8 13h5",key:"1k9z8w"}],["path",{d:"M10 17V9.5a2.5 2.5 0 0 1 5 0",key:"1dzgp0"}],["path",{d:"M8 17h7",key:"8mjdqu"}]]);/** * @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 eie=te("ReceiptRussianRuble",[["path",{d:"M4 2v20l2-1 2 1 2-1 2 1 2-1 2 1 2-1 2 1V2l-2 1-2-1-2 1-2-1-2 1-2-1-2 1Z",key:"q3az6g"}],["path",{d:"M8 15h5",key:"vxg57a"}],["path",{d:"M8 11h5a2 2 0 1 0 0-4h-3v10",key:"1usi5u"}]]);/** * @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 tie=te("ReceiptSwissFranc",[["path",{d:"M4 2v20l2-1 2 1 2-1 2 1 2-1 2 1 2-1 2 1V2l-2 1-2-1-2 1-2-1-2 1-2-1-2 1Z",key:"q3az6g"}],["path",{d:"M10 17V7h5",key:"k7jq18"}],["path",{d:"M10 11h4",key:"1i0mka"}],["path",{d:"M8 15h5",key:"vxg57a"}]]);/** * @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 sie=te("ReceiptText",[["path",{d:"M4 2v20l2-1 2 1 2-1 2 1 2-1 2 1 2-1 2 1V2l-2 1-2-1-2 1-2-1-2 1-2-1-2 1Z",key:"q3az6g"}],["path",{d:"M14 8H8",key:"1l3xfs"}],["path",{d:"M16 12H8",key:"1fr5h0"}],["path",{d:"M13 16H8",key:"wsln4y"}]]);/** * @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 rie=te("Receipt",[["path",{d:"M4 2v20l2-1 2 1 2-1 2 1 2-1 2 1 2-1 2 1V2l-2 1-2-1-2 1-2-1-2 1-2-1-2 1Z",key:"q3az6g"}],["path",{d:"M16 8h-6a2 2 0 1 0 0 4h4a2 2 0 1 1 0 4H8",key:"1h4pet"}],["path",{d:"M12 17.5v-11",key:"1jc1ny"}]]);/** * @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 J3=te("RectangleEllipsis",[["rect",{width:"20",height:"12",x:"2",y:"6",rx:"2",key:"9lu3g6"}],["path",{d:"M12 12h.01",key:"1mp3jc"}],["path",{d:"M17 12h.01",key:"1m0b6t"}],["path",{d:"M7 12h.01",key:"eqddd0"}]]);/** * @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 nie=te("RectangleHorizontal",[["rect",{width:"20",height:"12",x:"2",y:"6",rx:"2",key:"9lu3g6"}]]);/** * @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 aie=te("RectangleVertical",[["rect",{width:"12",height:"20",x:"6",y:"2",rx:"2",key:"1oxtiu"}]]);/** * @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 iie=te("Recycle",[["path",{d:"M7 19H4.815a1.83 1.83 0 0 1-1.57-.881 1.785 1.785 0 0 1-.004-1.784L7.196 9.5",key:"x6z5xu"}],["path",{d:"M11 19h8.203a1.83 1.83 0 0 0 1.556-.89 1.784 1.784 0 0 0 0-1.775l-1.226-2.12",key:"1x4zh5"}],["path",{d:"m14 16-3 3 3 3",key:"f6jyew"}],["path",{d:"M8.293 13.596 7.196 9.5 3.1 10.598",key:"wf1obh"}],["path",{d:"m9.344 5.811 1.093-1.892A1.83 1.83 0 0 1 11.985 3a1.784 1.784 0 0 1 1.546.888l3.943 6.843",key:"9tzpgr"}],["path",{d:"m13.378 9.633 4.096 1.098 1.097-4.096",key:"1oe83g"}]]);/** * @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 oie=te("Redo2",[["path",{d:"m15 14 5-5-5-5",key:"12vg1m"}],["path",{d:"M20 9H9.5A5.5 5.5 0 0 0 4 14.5A5.5 5.5 0 0 0 9.5 20H13",key:"6uklza"}]]);/** * @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 lie=te("RedoDot",[["circle",{cx:"12",cy:"17",r:"1",key:"1ixnty"}],["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 Yk=te("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 cie=te("RefreshCcwDot",[["path",{d:"M3 2v6h6",key:"18ldww"}],["path",{d:"M21 12A9 9 0 0 0 6 5.3L3 8",key:"1pbrqz"}],["path",{d:"M21 22v-6h-6",key:"usdfbe"}],["path",{d:"M3 12a9 9 0 0 0 15 6.7l3-2.7",key:"1hosoe"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}]]);/** * @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 KI=te("RefreshCcw",[["path",{d:"M21 12a9 9 0 0 0-9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"14sxne"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M3 12a9 9 0 0 0 9 9 9.75 9.75 0 0 0 6.74-2.74L21 16",key:"1hlbsb"}],["path",{d:"M16 16h5v5",key:"ccwih5"}]]);/** * @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 die=te("RefreshCwOff",[["path",{d:"M21 8L18.74 5.74A9.75 9.75 0 0 0 12 3C11 3 10.03 3.16 9.13 3.47",key:"1krf6h"}],["path",{d:"M8 16H3v5",key:"1cv678"}],["path",{d:"M3 12C3 9.51 4 7.26 5.64 5.64",key:"ruvoct"}],["path",{d:"m3 16 2.26 2.26A9.75 9.75 0 0 0 12 21c2.49 0 4.74-1 6.36-2.64",key:"19q130"}],["path",{d:"M21 12c0 1-.16 1.97-.47 2.87",key:"4w8emr"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M22 22 2 2",key:"1r8tn9"}]]);/** * @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 po=te("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 uie=te("Refrigerator",[["path",{d:"M5 6a4 4 0 0 1 4-4h6a4 4 0 0 1 4 4v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6Z",key:"fpq118"}],["path",{d:"M5 10h14",key:"elsbfy"}],["path",{d:"M15 7v6",key:"1nx30x"}]]);/** * @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 hie=te("Regex",[["path",{d:"M17 3v10",key:"15fgeh"}],["path",{d:"m12.67 5.5 8.66 5",key:"1gpheq"}],["path",{d:"m12.67 10.5 8.66-5",key:"1dkfa6"}],["path",{d:"M9 17a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v2a2 2 0 0 0 2 2h2a2 2 0 0 0 2-2v-2z",key:"swwfx4"}]]);/** * @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 mie=te("RemoveFormatting",[["path",{d:"M4 7V4h16v3",key:"9msm58"}],["path",{d:"M5 20h6",key:"1h6pxn"}],["path",{d:"M13 4 8 20",key:"kqq6aj"}],["path",{d:"m15 15 5 5",key:"me55sn"}],["path",{d:"m20 15-5 5",key:"11p7ol"}]]);/** * @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 fie=te("Repeat1",[["path",{d:"m17 2 4 4-4 4",key:"nntrym"}],["path",{d:"M3 11v-1a4 4 0 0 1 4-4h14",key:"84bu3i"}],["path",{d:"m7 22-4-4 4-4",key:"1wqhfi"}],["path",{d:"M21 13v1a4 4 0 0 1-4 4H3",key:"1rx37r"}],["path",{d:"M11 10h1v4",key:"70cz1p"}]]);/** * @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 pie=te("Repeat2",[["path",{d:"m2 9 3-3 3 3",key:"1ltn5i"}],["path",{d:"M13 18H7a2 2 0 0 1-2-2V6",key:"1r6tfw"}],["path",{d:"m22 15-3 3-3-3",key:"4rnwn2"}],["path",{d:"M11 6h6a2 2 0 0 1 2 2v10",key:"2f72bc"}]]);/** * @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 CF=te("Repeat",[["path",{d:"m17 2 4 4-4 4",key:"nntrym"}],["path",{d:"M3 11v-1a4 4 0 0 1 4-4h14",key:"84bu3i"}],["path",{d:"m7 22-4-4 4-4",key:"1wqhfi"}],["path",{d:"M21 13v1a4 4 0 0 1-4 4H3",key:"1rx37r"}]]);/** * @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 gie=te("ReplaceAll",[["path",{d:"M14 14a2 2 0 0 1 2 2v4a2 2 0 0 1-2 2",key:"1yyzbs"}],["path",{d:"M14 4a2 2 0 0 1 2-2",key:"1w2hp7"}],["path",{d:"M16 10a2 2 0 0 1-2-2",key:"shjach"}],["path",{d:"M20 14a2 2 0 0 1 2 2v4a2 2 0 0 1-2 2",key:"zfj4xr"}],["path",{d:"M20 2a2 2 0 0 1 2 2",key:"188mtx"}],["path",{d:"M22 8a2 2 0 0 1-2 2",key:"ddf4tu"}],["path",{d:"m3 7 3 3 3-3",key:"x25e72"}],["path",{d:"M6 10V5a 3 3 0 0 1 3-3h1",key:"1ageje"}],["rect",{x:"2",y:"14",width:"8",height:"8",rx:"2",key:"4rksxw"}]]);/** * @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 xie=te("Replace",[["path",{d:"M14 4a2 2 0 0 1 2-2",key:"1w2hp7"}],["path",{d:"M16 10a2 2 0 0 1-2-2",key:"shjach"}],["path",{d:"M20 2a2 2 0 0 1 2 2",key:"188mtx"}],["path",{d:"M22 8a2 2 0 0 1-2 2",key:"ddf4tu"}],["path",{d:"m3 7 3 3 3-3",key:"x25e72"}],["path",{d:"M6 10V5a3 3 0 0 1 3-3h1",key:"3y3t5z"}],["rect",{x:"2",y:"14",width:"8",height:"8",rx:"2",key:"4rksxw"}]]);/** * @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 yie=te("ReplyAll",[["polyline",{points:"7 17 2 12 7 7",key:"t83bqg"}],["polyline",{points:"12 17 7 12 12 7",key:"1g4ajm"}],["path",{d:"M22 18v-2a4 4 0 0 0-4-4H7",key:"1fcyog"}]]);/** * @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=te("Reply",[["polyline",{points:"9 17 4 12 9 7",key:"hvgpf2"}],["path",{d:"M20 18v-2a4 4 0 0 0-4-4H4",key:"5vmcpk"}]]);/** * @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 vie=te("Rewind",[["polygon",{points:"11 19 2 12 11 5 11 19",key:"14yba5"}],["polygon",{points:"22 19 13 12 22 5 22 19",key:"1pi1cj"}]]);/** * @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 bie=te("Ribbon",[["path",{d:"M12 11.22C11 9.997 10 9 10 8a2 2 0 0 1 4 0c0 1-.998 2.002-2.01 3.22",key:"1rnhq3"}],["path",{d:"m12 18 2.57-3.5",key:"116vt7"}],["path",{d:"M6.243 9.016a7 7 0 0 1 11.507-.009",key:"10dq0b"}],["path",{d:"M9.35 14.53 12 11.22",key:"tdsyp2"}],["path",{d:"M9.35 14.53C7.728 12.246 6 10.221 6 7a6 5 0 0 1 12 0c-.005 3.22-1.778 5.235-3.43 7.5l3.557 4.527a1 1 0 0 1-.203 1.43l-1.894 1.36a1 1 0 0 1-1.384-.215L12 18l-2.679 3.593a1 1 0 0 1-1.39.213l-1.865-1.353a1 1 0 0 1-.203-1.422z",key:"nmifey"}]]);/** * @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 v_=te("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 _ie=te("RockingChair",[["polyline",{points:"3.5 2 6.5 12.5 18 12.5",key:"y3iy52"}],["line",{x1:"9.5",x2:"5.5",y1:"12.5",y2:"20",key:"19vg5i"}],["line",{x1:"15",x2:"18.5",y1:"12.5",y2:"20",key:"1inpmv"}],["path",{d:"M2.75 18a13 13 0 0 0 18.5 0",key:"1nquas"}]]);/** * @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 wie=te("RollerCoaster",[["path",{d:"M6 19V5",key:"1r845m"}],["path",{d:"M10 19V6.8",key:"9j2tfs"}],["path",{d:"M14 19v-7.8",key:"10s8qv"}],["path",{d:"M18 5v4",key:"1tajlv"}],["path",{d:"M18 19v-6",key:"ielfq3"}],["path",{d:"M22 19V9",key:"158nzp"}],["path",{d:"M2 19V9a4 4 0 0 1 4-4c2 0 4 1.33 6 4s4 4 6 4a4 4 0 1 0-3-6.65",key:"1930oh"}]]);/** * @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 e5=te("Rotate3d",[["path",{d:"M16.466 7.5C15.643 4.237 13.952 2 12 2 9.239 2 7 6.477 7 12s2.239 10 5 10c.342 0 .677-.069 1-.2",key:"10n0gc"}],["path",{d:"m15.194 13.707 3.814 1.86-1.86 3.814",key:"16shm9"}],["path",{d:"M19 15.57c-1.804.885-4.274 1.43-7 1.43-5.523 0-10-2.239-10-5s4.477-5 10-5c4.838 0 8.873 1.718 9.8 4",key:"1lxi77"}]]);/** * @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 jie=te("RotateCcwSquare",[["path",{d:"M20 9V7a2 2 0 0 0-2-2h-6",key:"19z8uc"}],["path",{d:"m15 2-3 3 3 3",key:"177bxs"}],["path",{d:"M20 13v5a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2h2",key:"d36hnl"}]]);/** * @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 qy=te("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 Nie=te("RotateCwSquare",[["path",{d:"M12 5H6a2 2 0 0 0-2 2v3",key:"l96uqu"}],["path",{d:"m9 8 3-3-3-3",key:"1gzgc3"}],["path",{d:"M4 14v4a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2h-2",key:"1w2k5h"}]]);/** * @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 PE=te("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 kie=te("RouteOff",[["circle",{cx:"6",cy:"19",r:"3",key:"1kj8tv"}],["path",{d:"M9 19h8.5c.4 0 .9-.1 1.3-.2",key:"1effex"}],["path",{d:"M5.2 5.2A3.5 3.53 0 0 0 6.5 12H12",key:"k9y2ds"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M21 15.3a3.5 3.5 0 0 0-3.3-3.3",key:"11nlu2"}],["path",{d:"M15 5h-4.3",key:"6537je"}],["circle",{cx:"18",cy:"5",r:"3",key:"gq8acd"}]]);/** * @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 Sie=te("Route",[["circle",{cx:"6",cy:"19",r:"3",key:"1kj8tv"}],["path",{d:"M9 19h8.5a3.5 3.5 0 0 0 0-7h-11a3.5 3.5 0 0 1 0-7H15",key:"1d8sl"}],["circle",{cx:"18",cy:"5",r:"3",key:"gq8acd"}]]);/** * @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 Cie=te("Router",[["rect",{width:"20",height:"8",x:"2",y:"14",rx:"2",key:"w68u3i"}],["path",{d:"M6.01 18H6",key:"19vcac"}],["path",{d:"M10.01 18H10",key:"uamcmx"}],["path",{d:"M15 10v4",key:"qjz1xs"}],["path",{d:"M17.84 7.17a4 4 0 0 0-5.66 0",key:"1rif40"}],["path",{d:"M20.66 4.34a8 8 0 0 0-11.31 0",key:"6a5xfq"}]]);/** * @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 t5=te("Rows2",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 12h18",key:"1i2n21"}]]);/** * @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 s5=te("Rows3",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M21 9H3",key:"1338ky"}],["path",{d:"M21 15H3",key:"9uk58r"}]]);/** * @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 Tie=te("Rows4",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M21 7.5H3",key:"1hm9pq"}],["path",{d:"M21 12H3",key:"2avoz0"}],["path",{d:"M21 16.5H3",key:"n7jzkj"}]]);/** * @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 Eie=te("Rss",[["path",{d:"M4 11a9 9 0 0 1 9 9",key:"pv89mb"}],["path",{d:"M4 4a16 16 0 0 1 16 16",key:"k0647b"}],["circle",{cx:"5",cy:"19",r:"1",key:"bfqh0e"}]]);/** * @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 LE=te("Ruler",[["path",{d:"M21.3 15.3a2.4 2.4 0 0 1 0 3.4l-2.6 2.6a2.4 2.4 0 0 1-3.4 0L2.7 8.7a2.41 2.41 0 0 1 0-3.4l2.6-2.6a2.41 2.41 0 0 1 3.4 0Z",key:"icamh8"}],["path",{d:"m14.5 12.5 2-2",key:"inckbg"}],["path",{d:"m11.5 9.5 2-2",key:"fmmyf7"}],["path",{d:"m8.5 6.5 2-2",key:"vc6u1g"}],["path",{d:"m17.5 15.5 2-2",key:"wo5hmg"}]]);/** * @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 Aie=te("RussianRuble",[["path",{d:"M6 11h8a4 4 0 0 0 0-8H9v18",key:"18ai8t"}],["path",{d:"M6 15h8",key:"1y8f6l"}]]);/** * @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 Mie=te("Sailboat",[["path",{d:"M22 18H2a4 4 0 0 0 4 4h12a4 4 0 0 0 4-4Z",key:"1404fh"}],["path",{d:"M21 14 10 2 3 14h18Z",key:"1nzg7v"}],["path",{d:"M10 2v16",key:"1labyt"}]]);/** * @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 Iie=te("Salad",[["path",{d:"M7 21h10",key:"1b0cd5"}],["path",{d:"M12 21a9 9 0 0 0 9-9H3a9 9 0 0 0 9 9Z",key:"4rw317"}],["path",{d:"M11.38 12a2.4 2.4 0 0 1-.4-4.77 2.4 2.4 0 0 1 3.2-2.77 2.4 2.4 0 0 1 3.47-.63 2.4 2.4 0 0 1 3.37 3.37 2.4 2.4 0 0 1-1.1 3.7 2.51 2.51 0 0 1 .03 1.1",key:"10xrj0"}],["path",{d:"m13 12 4-4",key:"1hckqy"}],["path",{d:"M10.9 7.25A3.99 3.99 0 0 0 4 10c0 .73.2 1.41.54 2",key:"1p4srx"}]]);/** * @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 Pie=te("Sandwich",[["path",{d:"m2.37 11.223 8.372-6.777a2 2 0 0 1 2.516 0l8.371 6.777",key:"f1wd0e"}],["path",{d:"M21 15a1 1 0 0 1 1 1v2a1 1 0 0 1-1 1h-5.25",key:"1pfu07"}],["path",{d:"M3 15a1 1 0 0 0-1 1v2a1 1 0 0 0 1 1h9",key:"1oq9qw"}],["path",{d:"m6.67 15 6.13 4.6a2 2 0 0 0 2.8-.4l3.15-4.2",key:"1fnwu5"}],["rect",{width:"20",height:"4",x:"2",y:"11",rx:"1",key:"itshg"}]]);/** * @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 Lie=te("SatelliteDish",[["path",{d:"M4 10a7.31 7.31 0 0 0 10 10Z",key:"1fzpp3"}],["path",{d:"m9 15 3-3",key:"88sc13"}],["path",{d:"M17 13a6 6 0 0 0-6-6",key:"15cc6u"}],["path",{d:"M21 13A10 10 0 0 0 11 3",key:"11nf8s"}]]);/** * @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 Die=te("Satellite",[["path",{d:"M13 7 9 3 5 7l4 4",key:"vyckw6"}],["path",{d:"m17 11 4 4-4 4-4-4",key:"rchckc"}],["path",{d:"m8 12 4 4 6-6-4-4Z",key:"1sshf7"}],["path",{d:"m16 8 3-3",key:"x428zp"}],["path",{d:"M9 21a6 6 0 0 0-6-6",key:"1iajcf"}]]);/** * @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 Rie=te("SaveAll",[["path",{d:"M10 2v3a1 1 0 0 0 1 1h5",key:"1xspal"}],["path",{d:"M18 18v-6a1 1 0 0 0-1-1h-6a1 1 0 0 0-1 1v6",key:"1ra60u"}],["path",{d:"M18 22H4a2 2 0 0 1-2-2V6",key:"pblm9e"}],["path",{d:"M8 18a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9.172a2 2 0 0 1 1.414.586l2.828 2.828A2 2 0 0 1 22 6.828V16a2 2 0 0 1-2.01 2z",key:"1yve0x"}]]);/** * @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 Oie=te("SaveOff",[["path",{d:"M13 13H8a1 1 0 0 0-1 1v7",key:"h8g396"}],["path",{d:"M14 8h1",key:"1lfen6"}],["path",{d:"M17 21v-4",key:"1yknxs"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M20.41 20.41A2 2 0 0 1 19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 .59-1.41",key:"1t4vdl"}],["path",{d:"M29.5 11.5s5 5 4 5",key:"zzn4i6"}],["path",{d:"M9 3h6.2a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V15",key:"24cby9"}]]);/** * @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 vc=te("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 r5=te("Scale3d",[["path",{d:"M5 7v11a1 1 0 0 0 1 1h11",key:"13dt1j"}],["path",{d:"M5.293 18.707 11 13",key:"ezgbsx"}],["circle",{cx:"19",cy:"19",r:"2",key:"17f5cg"}],["circle",{cx:"5",cy:"5",r:"2",key:"1gwv83"}]]);/** * @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 EF=te("Scale",[["path",{d:"m16 16 3-8 3 8c-.87.65-1.92 1-3 1s-2.13-.35-3-1Z",key:"7g6ntu"}],["path",{d:"m2 16 3-8 3 8c-.87.65-1.92 1-3 1s-2.13-.35-3-1Z",key:"ijws7r"}],["path",{d:"M7 21h10",key:"1b0cd5"}],["path",{d:"M12 3v18",key:"108xh3"}],["path",{d:"M3 7h2c2 0 5-1 7-2 2 1 5 2 7 2h2",key:"3gwbw2"}]]);/** * @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 Fie=te("Scaling",[["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:"M14 15H9v-5",key:"pi4jk9"}],["path",{d:"M16 3h5v5",key:"1806ms"}],["path",{d:"M21 3 9 15",key:"15kdhq"}]]);/** * @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 Bie=te("ScanBarcode",[["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}],["path",{d:"M8 7v10",key:"23sfjj"}],["path",{d:"M12 7v10",key:"jspqdw"}],["path",{d:"M17 7v10",key:"578dap"}]]);/** * @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 zie=te("ScanEye",[["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["path",{d:"M18.944 12.33a1 1 0 0 0 0-.66 7.5 7.5 0 0 0-13.888 0 1 1 0 0 0 0 .66 7.5 7.5 0 0 0 13.888 0",key:"11ak4c"}]]);/** * @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 $ie=te("ScanFace",[["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}],["path",{d:"M8 14s1.5 2 4 2 4-2 4-2",key:"1y1vjs"}],["path",{d:"M9 9h.01",key:"1q5me6"}],["path",{d:"M15 9h.01",key:"x1ddxp"}]]);/** * @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 Uie=te("ScanLine",[["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}],["path",{d:"M7 12h10",key:"b7w52i"}]]);/** * @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 qie=te("ScanQrCode",[["path",{d:"M17 12v4a1 1 0 0 1-1 1h-4",key:"uk4fdo"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M17 8V7",key:"q2g9wo"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M7 17h.01",key:"19xn7k"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}],["rect",{x:"7",y:"7",width:"5",height:"5",rx:"1",key:"m9kyts"}]]);/** * @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 Vie=te("ScanSearch",[["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}],["path",{d:"m16 16-1.9-1.9",key:"1dq9hf"}]]);/** * @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 Hie=te("ScanText",[["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}],["path",{d:"M7 8h8",key:"1jbsf9"}],["path",{d:"M7 12h10",key:"b7w52i"}],["path",{d:"M7 16h6",key:"1vyc9m"}]]);/** * @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 Gie=te("Scan",[["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}]]);/** * @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 Wie=te("School",[["path",{d:"M14 22v-4a2 2 0 1 0-4 0v4",key:"hhkicm"}],["path",{d:"m18 10 3.447 1.724a1 1 0 0 1 .553.894V20a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2v-7.382a1 1 0 0 1 .553-.894L6 10",key:"1xqip1"}],["path",{d:"M18 5v17",key:"1sw6gf"}],["path",{d:"m4 6 7.106-3.553a2 2 0 0 1 1.788 0L20 6",key:"9d2mlk"}],["path",{d:"M6 5v17",key:"1xfsm0"}],["circle",{cx:"12",cy:"9",r:"2",key:"1092wv"}]]);/** * @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 Kie=te("ScissorsLineDashed",[["path",{d:"M5.42 9.42 8 12",key:"12pkuq"}],["circle",{cx:"4",cy:"8",r:"2",key:"107mxr"}],["path",{d:"m14 6-8.58 8.58",key:"gvzu5l"}],["circle",{cx:"4",cy:"16",r:"2",key:"1ehqvc"}],["path",{d:"M10.8 14.8 14 18",key:"ax7m9r"}],["path",{d:"M16 12h-2",key:"10asgb"}],["path",{d:"M22 12h-2",key:"14jgyd"}]]);/** * @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 Yie=te("Scissors",[["circle",{cx:"6",cy:"6",r:"3",key:"1lh9wr"}],["path",{d:"M8.12 8.12 12 12",key:"1alkpv"}],["path",{d:"M20 4 8.12 15.88",key:"xgtan2"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}],["path",{d:"M14.8 14.8 20 20",key:"ptml3r"}]]);/** * @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 Zie=te("ScreenShareOff",[["path",{d:"M13 3H4a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-3",key:"i8wdob"}],["path",{d:"M8 21h8",key:"1ev6f3"}],["path",{d:"M12 17v4",key:"1riwvh"}],["path",{d:"m22 3-5 5",key:"12jva0"}],["path",{d:"m17 3 5 5",key:"k36vhe"}]]);/** * @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 Xie=te("ScreenShare",[["path",{d:"M13 3H4a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-3",key:"i8wdob"}],["path",{d:"M8 21h8",key:"1ev6f3"}],["path",{d:"M12 17v4",key:"1riwvh"}],["path",{d:"m17 8 5-5",key:"fqif7o"}],["path",{d:"M17 3h5v5",key:"1o3tu8"}]]);/** * @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 Qie=te("ScrollText",[["path",{d:"M15 12h-5",key:"r7krc0"}],["path",{d:"M15 8h-5",key:"1khuty"}],["path",{d:"M19 17V5a2 2 0 0 0-2-2H4",key:"zz82l3"}],["path",{d:"M8 21h12a2 2 0 0 0 2-2v-1a1 1 0 0 0-1-1H11a1 1 0 0 0-1 1v1a2 2 0 1 1-4 0V5a2 2 0 1 0-4 0v2a1 1 0 0 0 1 1h3",key:"1ph1d7"}]]);/** * @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 Jie=te("Scroll",[["path",{d:"M19 17V5a2 2 0 0 0-2-2H4",key:"zz82l3"}],["path",{d:"M8 21h12a2 2 0 0 0 2-2v-1a1 1 0 0 0-1-1H11a1 1 0 0 0-1 1v1a2 2 0 1 1-4 0V5a2 2 0 1 0-4 0v2a1 1 0 0 0 1 1h3",key:"1ph1d7"}]]);/** * @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=te("SearchCheck",[["path",{d:"m8 11 2 2 4-4",key:"1sed1v"}],["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 toe=te("SearchCode",[["path",{d:"m13 13.5 2-2.5-2-2.5",key:"1rvxrh"}],["path",{d:"m21 21-4.3-4.3",key:"1qie3q"}],["path",{d:"M9 8.5 7 11l2 2.5",key:"6ffwbx"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]]);/** * @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=te("SearchSlash",[["path",{d:"m13.5 8.5-5 5",key:"1cs55j"}],["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 AF=te("SearchX",[["path",{d:"m13.5 8.5-5 5",key:"1cs55j"}],["path",{d:"m8.5 8.5 5 5",key:"a8mexj"}],["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 Mn=te("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 roe=te("Section",[["path",{d:"M16 5a4 3 0 0 0-8 0c0 4 8 3 8 7a4 3 0 0 1-8 0",key:"vqan6v"}],["path",{d:"M8 19a4 3 0 0 0 8 0c0-4-8-3-8-7a4 3 0 0 1 8 0",key:"wdjd8o"}]]);/** * @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=te("SendHorizontal",[["path",{d:"M3.714 3.048a.498.498 0 0 0-.683.627l2.843 7.627a2 2 0 0 1 0 1.396l-2.842 7.627a.498.498 0 0 0 .682.627l18-8.5a.5.5 0 0 0 0-.904z",key:"117uat"}],["path",{d:"M6 12h16",key:"s4cdu5"}]]);/** * @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=te("SendToBack",[["rect",{x:"14",y:"14",width:"8",height:"8",rx:"2",key:"1b0bso"}],["rect",{x:"2",y:"2",width:"8",height:"8",rx:"2",key:"1x09vl"}],["path",{d:"M7 14v1a2 2 0 0 0 2 2h1",key:"pao6x6"}],["path",{d:"M14 7h1a2 2 0 0 1 2 2v1",key:"19tdru"}]]);/** * @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 yn=te("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 aoe=te("SeparatorHorizontal",[["line",{x1:"3",x2:"21",y1:"12",y2:"12",key:"10d38w"}],["polyline",{points:"8 8 12 4 16 8",key:"zo8t4w"}],["polyline",{points:"16 16 12 20 8 16",key:"1oyrid"}]]);/** * @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=te("SeparatorVertical",[["line",{x1:"12",x2:"12",y1:"3",y2:"21",key:"1efggb"}],["polyline",{points:"8 8 4 12 8 16",key:"bnfmv4"}],["polyline",{points:"16 16 20 12 16 8",key:"u90052"}]]);/** * @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=te("ServerCog",[["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}],["path",{d:"M4.5 10H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v4a2 2 0 0 1-2 2h-.5",key:"tn8das"}],["path",{d:"M4.5 14H4a2 2 0 0 0-2 2v4a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-4a2 2 0 0 0-2-2h-.5",key:"1g2pve"}],["path",{d:"M6 6h.01",key:"1utrut"}],["path",{d:"M6 18h.01",key:"uhywen"}],["path",{d:"m15.7 13.4-.9-.3",key:"1jwmzr"}],["path",{d:"m9.2 10.9-.9-.3",key:"qapnim"}],["path",{d:"m10.6 15.7.3-.9",key:"quwk0k"}],["path",{d:"m13.6 15.7-.4-1",key:"cb9xp7"}],["path",{d:"m10.8 9.3-.4-1",key:"1uaiz5"}],["path",{d:"m8.3 13.6 1-.4",key:"s6srou"}],["path",{d:"m14.7 10.8 1-.4",key:"4d31cq"}],["path",{d:"m13.4 8.3-.3.9",key:"1bm987"}]]);/** * @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=te("ServerCrash",[["path",{d:"M6 10H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v4a2 2 0 0 1-2 2h-2",key:"4b9dqc"}],["path",{d:"M6 14H4a2 2 0 0 0-2 2v4a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-4a2 2 0 0 0-2-2h-2",key:"22nnkd"}],["path",{d:"M6 6h.01",key:"1utrut"}],["path",{d:"M6 18h.01",key:"uhywen"}],["path",{d:"m13 6-4 6h6l-4 6",key:"14hqih"}]]);/** * @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=te("ServerOff",[["path",{d:"M7 2h13a2 2 0 0 1 2 2v4a2 2 0 0 1-2 2h-5",key:"bt2siv"}],["path",{d:"M10 10 2.5 2.5C2 2 2 2.5 2 5v3a2 2 0 0 0 2 2h6z",key:"1hjrv1"}],["path",{d:"M22 17v-1a2 2 0 0 0-2-2h-1",key:"1iynyr"}],["path",{d:"M4 14a2 2 0 0 0-2 2v4a2 2 0 0 0 2 2h16.5l1-.5.5.5-8-8H4z",key:"161ggg"}],["path",{d:"M6 18h.01",key:"uhywen"}],["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 doe=te("Server",[["rect",{width:"20",height:"8",x:"2",y:"2",rx:"2",ry:"2",key:"ngkwjq"}],["rect",{width:"20",height:"8",x:"2",y:"14",rx:"2",ry:"2",key:"iecqi9"}],["line",{x1:"6",x2:"6.01",y1:"6",y2:"6",key:"16zg32"}],["line",{x1:"6",x2:"6.01",y1:"18",y2:"18",key:"nzw8ys"}]]);/** * @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 MF=te("Settings2",[["path",{d:"M20 7h-9",key:"3s1dr2"}],["path",{d:"M14 17H5",key:"gfn3mx"}],["circle",{cx:"17",cy:"17",r:"3",key:"18b49y"}],["circle",{cx:"7",cy:"7",r:"3",key:"dfmy0x"}]]);/** * @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=te("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 uoe=te("Shapes",[["path",{d:"M8.3 10a.7.7 0 0 1-.626-1.079L11.4 3a.7.7 0 0 1 1.198-.043L16.3 8.9a.7.7 0 0 1-.572 1.1Z",key:"1bo67w"}],["rect",{x:"3",y:"14",width:"7",height:"7",rx:"1",key:"1bkyp8"}],["circle",{cx:"17.5",cy:"17.5",r:"3.5",key:"w3z12y"}]]);/** * @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=te("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 IF=te("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 hoe=te("Sheet",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["line",{x1:"3",x2:"21",y1:"9",y2:"9",key:"1vqk6q"}],["line",{x1:"3",x2:"21",y1:"15",y2:"15",key:"o2sbyz"}],["line",{x1:"9",x2:"9",y1:"9",y2:"21",key:"1ib60c"}],["line",{x1:"15",x2:"15",y1:"9",y2:"21",key:"1n26ft"}]]);/** * @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=te("Shell",[["path",{d:"M14 11a2 2 0 1 1-4 0 4 4 0 0 1 8 0 6 6 0 0 1-12 0 8 8 0 0 1 16 0 10 10 0 1 1-20 0 11.93 11.93 0 0 1 2.42-7.22 2 2 0 1 1 3.16 2.44",key:"1cn552"}]]);/** * @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 PF=te("ShieldAlert",[["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:"M12 8v4",key:"1got3b"}],["path",{d:"M12 16h.01",key:"1drbdi"}]]);/** * @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=te("ShieldBan",[["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:"m4.243 5.21 14.39 12.472",key:"1c9a7c"}]]);/** * @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 w1=te("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 poe=te("ShieldEllipsis",[["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:"M8 12h.01",key:"czm47f"}],["path",{d:"M12 12h.01",key:"1mp3jc"}],["path",{d:"M16 12h.01",key:"1l6xoz"}]]);/** * @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=te("ShieldHalf",[["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:"M12 22V2",key:"zs6s6o"}]]);/** * @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=te("ShieldMinus",[["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 12h6",key:"1c52cq"}]]);/** * @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 DE=te("ShieldOff",[["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M5 5a1 1 0 0 0-1 1v7c0 5 3.5 7.5 7.67 8.94a1 1 0 0 0 .67.01c2.35-.82 4.48-1.97 5.9-3.71",key:"1jlk70"}],["path",{d:"M9.309 3.652A12.252 12.252 0 0 0 11.24 2.28a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1v7a9.784 9.784 0 0 1-.08 1.264",key:"18rp1v"}]]);/** * @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=te("ShieldPlus",[["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 12h6",key:"1c52cq"}],["path",{d:"M12 9v6",key:"199k2o"}]]);/** * @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=te("ShieldQuestion",[["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.1 9a3 3 0 0 1 5.82 1c0 2-3 3-3 3",key:"mhlwft"}],["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 a5=te("ShieldX",[["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:"m14.5 9.5-5 5",key:"17q4r4"}],["path",{d:"m9.5 9.5 5 5",key:"18nt4w"}]]);/** * @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 Fh=te("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 boe=te("ShipWheel",[["circle",{cx:"12",cy:"12",r:"8",key:"46899m"}],["path",{d:"M12 2v7.5",key:"1e5rl5"}],["path",{d:"m19 5-5.23 5.23",key:"1ezxxf"}],["path",{d:"M22 12h-7.5",key:"le1719"}],["path",{d:"m19 19-5.23-5.23",key:"p3fmgn"}],["path",{d:"M12 14.5V22",key:"dgcmos"}],["path",{d:"M10.23 13.77 5 19",key:"qwopd4"}],["path",{d:"M9.5 12H2",key:"r7bup8"}],["path",{d:"M10.23 10.23 5 5",key:"k2y7lj"}],["circle",{cx:"12",cy:"12",r:"2.5",key:"ix0uyj"}]]);/** * @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=te("Ship",[["path",{d:"M12 10.189V14",key:"1p8cqu"}],["path",{d:"M12 2v3",key:"qbqxhf"}],["path",{d:"M19 13V7a2 2 0 0 0-2-2H7a2 2 0 0 0-2 2v6",key:"qpkstq"}],["path",{d:"M19.38 20A11.6 11.6 0 0 0 21 14l-8.188-3.639a2 2 0 0 0-1.624 0L3 14a11.6 11.6 0 0 0 2.81 7.76",key:"7tigtc"}],["path",{d:"M2 21c.6.5 1.2 1 2.5 1 2.5 0 2.5-2 5-2 1.3 0 1.9.5 2.5 1s1.2 1 2.5 1c2.5 0 2.5-2 5-2 1.3 0 1.9.5 2.5 1",key:"1924j5"}]]);/** * @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=te("Shirt",[["path",{d:"M20.38 3.46 16 2a4 4 0 0 1-8 0L3.62 3.46a2 2 0 0 0-1.34 2.23l.58 3.47a1 1 0 0 0 .99.84H6v10c0 1.1.9 2 2 2h8a2 2 0 0 0 2-2V10h2.15a1 1 0 0 0 .99-.84l.58-3.47a2 2 0 0 0-1.34-2.23z",key:"1wgbhj"}]]);/** * @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 b_=te("ShoppingBag",[["path",{d:"M6 2 3 6v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6l-3-4Z",key:"hou9p0"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M16 10a4 4 0 0 1-8 0",key:"1ltviw"}]]);/** * @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=te("ShoppingBasket",[["path",{d:"m15 11-1 9",key:"5wnq3a"}],["path",{d:"m19 11-4-7",key:"cnml18"}],["path",{d:"M2 11h20",key:"3eubbj"}],["path",{d:"m3.5 11 1.6 7.4a2 2 0 0 0 2 1.6h9.8a2 2 0 0 0 2-1.6l1.7-7.4",key:"yiazzp"}],["path",{d:"M4.5 15.5h15",key:"13mye1"}],["path",{d:"m5 11 4-7",key:"116ra9"}],["path",{d:"m9 11 1 9",key:"1ojof7"}]]);/** * @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=te("ShoppingCart",[["circle",{cx:"8",cy:"21",r:"1",key:"jimo8o"}],["circle",{cx:"19",cy:"21",r:"1",key:"13723u"}],["path",{d:"M2.05 2.05h2l2.66 12.42a2 2 0 0 0 2 1.58h9.78a2 2 0 0 0 1.95-1.57l1.65-7.43H5.12",key:"9zh506"}]]);/** * @license lucide-react v0.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=te("Shovel",[["path",{d:"M2 22v-5l5-5 5 5-5 5z",key:"1fh25c"}],["path",{d:"M9.5 14.5 16 8",key:"1smz5x"}],["path",{d:"m17 2 5 5-.5.5a3.53 3.53 0 0 1-5 0s0 0 0 0a3.53 3.53 0 0 1 0-5L17 2",key:"1q8uv5"}]]);/** * @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=te("ShowerHead",[["path",{d:"m4 4 2.5 2.5",key:"uv2vmf"}],["path",{d:"M13.5 6.5a4.95 4.95 0 0 0-7 7",key:"frdkwv"}],["path",{d:"M15 5 5 15",key:"1ag8rq"}],["path",{d:"M14 17v.01",key:"eokfpp"}],["path",{d:"M10 16v.01",key:"14uyyl"}],["path",{d:"M13 13v.01",key:"1v1k97"}],["path",{d:"M16 10v.01",key:"5169yg"}],["path",{d:"M11 20v.01",key:"cj92p8"}],["path",{d:"M17 14v.01",key:"11cswd"}],["path",{d:"M20 11v.01",key:"19e0od"}]]);/** * @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=te("Shrink",[["path",{d:"m15 15 6 6m-6-6v4.8m0-4.8h4.8",key:"17vawe"}],["path",{d:"M9 19.8V15m0 0H4.2M9 15l-6 6",key:"chjx8e"}],["path",{d:"M15 4.2V9m0 0h4.8M15 9l6-6",key:"lav6yq"}],["path",{d:"M9 4.2V9m0 0H4.2M9 9 3 3",key:"1pxi2q"}]]);/** * @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=te("Shrub",[["path",{d:"M12 22v-7l-2-2",key:"eqv9mc"}],["path",{d:"M17 8v.8A6 6 0 0 1 13.8 20H10A6.5 6.5 0 0 1 7 8a5 5 0 0 1 10 0Z",key:"ubcgy"}],["path",{d:"m14 14-2 2",key:"847xa2"}]]);/** * @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 RE=te("Shuffle",[["path",{d:"m18 14 4 4-4 4",key:"10pe0f"}],["path",{d:"m18 2 4 4-4 4",key:"pucp1d"}],["path",{d:"M2 18h1.973a4 4 0 0 0 3.3-1.7l5.454-8.6a4 4 0 0 1 3.3-1.7H22",key:"1ailkh"}],["path",{d:"M2 6h1.972a4 4 0 0 1 3.6 2.2",key:"km57vx"}],["path",{d:"M22 18h-6.041a4 4 0 0 1-3.3-1.8l-.359-.45",key:"os18l9"}]]);/** * @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=te("Sigma",[["path",{d:"M18 7V5a1 1 0 0 0-1-1H6.5a.5.5 0 0 0-.4.8l4.5 6a2 2 0 0 1 0 2.4l-4.5 6a.5.5 0 0 0 .4.8H17a1 1 0 0 0 1-1v-2",key:"wuwx1p"}]]);/** * @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=te("SignalHigh",[["path",{d:"M2 20h.01",key:"4haj6o"}],["path",{d:"M7 20v-4",key:"j294jx"}],["path",{d:"M12 20v-8",key:"i3yub9"}],["path",{d:"M17 20V8",key:"1tkaf5"}]]);/** * @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=te("SignalLow",[["path",{d:"M2 20h.01",key:"4haj6o"}],["path",{d:"M7 20v-4",key:"j294jx"}]]);/** * @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=te("SignalMedium",[["path",{d:"M2 20h.01",key:"4haj6o"}],["path",{d:"M7 20v-4",key:"j294jx"}],["path",{d:"M12 20v-8",key:"i3yub9"}]]);/** * @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=te("SignalZero",[["path",{d:"M2 20h.01",key:"4haj6o"}]]);/** * @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=te("Signal",[["path",{d:"M2 20h.01",key:"4haj6o"}],["path",{d:"M7 20v-4",key:"j294jx"}],["path",{d:"M12 20v-8",key:"i3yub9"}],["path",{d:"M17 20V8",key:"1tkaf5"}],["path",{d:"M22 4v16",key:"sih9yq"}]]);/** * @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=te("Signature",[["path",{d:"m21 17-2.156-1.868A.5.5 0 0 0 18 15.5v.5a1 1 0 0 1-1 1h-2a1 1 0 0 1-1-1c0-2.545-3.991-3.97-8.5-4a1 1 0 0 0 0 5c4.153 0 4.745-11.295 5.708-13.5a2.5 2.5 0 1 1 3.31 3.284",key:"y32ogt"}],["path",{d:"M3 21h18",key:"itz85i"}]]);/** * @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=te("SignpostBig",[["path",{d:"M10 9H4L2 7l2-2h6",key:"1hq7x2"}],["path",{d:"M14 5h6l2 2-2 2h-6",key:"bv62ej"}],["path",{d:"M10 22V4a2 2 0 1 1 4 0v18",key:"eqpcf2"}],["path",{d:"M8 22h8",key:"rmew8v"}]]);/** * @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=te("Signpost",[["path",{d:"M12 13v8",key:"1l5pq0"}],["path",{d:"M12 3v3",key:"1n5kay"}],["path",{d:"M18 6a2 2 0 0 1 1.387.56l2.307 2.22a1 1 0 0 1 0 1.44l-2.307 2.22A2 2 0 0 1 18 13H6a2 2 0 0 1-1.387-.56l-2.306-2.22a1 1 0 0 1 0-1.44l2.306-2.22A2 2 0 0 1 6 6z",key:"gqqp9m"}]]);/** * @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=te("Siren",[["path",{d:"M7 18v-6a5 5 0 1 1 10 0v6",key:"pcx96s"}],["path",{d:"M5 21a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-1a2 2 0 0 0-2-2H7a2 2 0 0 0-2 2z",key:"1b4s83"}],["path",{d:"M21 12h1",key:"jtio3y"}],["path",{d:"M18.5 4.5 18 5",key:"g5sp9y"}],["path",{d:"M2 12h1",key:"1uaihz"}],["path",{d:"M12 2v1",key:"11qlp1"}],["path",{d:"m4.929 4.929.707.707",key:"1i51kw"}],["path",{d:"M12 12v6",key:"3ahymv"}]]);/** * @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=te("SkipBack",[["polygon",{points:"19 20 9 12 19 4 19 20",key:"o2sva"}],["line",{x1:"5",x2:"5",y1:"19",y2:"5",key:"1ocqjk"}]]);/** * @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=te("SkipForward",[["polygon",{points:"5 4 15 12 5 20 5 4",key:"16p6eg"}],["line",{x1:"19",x2:"19",y1:"5",y2:"19",key:"futhcm"}]]);/** * @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 zoe=te("Skull",[["path",{d:"m12.5 17-.5-1-.5 1h1z",key:"3me087"}],["path",{d:"M15 22a1 1 0 0 0 1-1v-1a2 2 0 0 0 1.56-3.25 8 8 0 1 0-11.12 0A2 2 0 0 0 8 20v1a1 1 0 0 0 1 1z",key:"1o5pge"}],["circle",{cx:"15",cy:"12",r:"1",key:"1tmaij"}],["circle",{cx:"9",cy:"12",r:"1",key:"1vctgf"}]]);/** * @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=te("Slack",[["rect",{width:"3",height:"8",x:"13",y:"2",rx:"1.5",key:"diqz80"}],["path",{d:"M19 8.5V10h1.5A1.5 1.5 0 1 0 19 8.5",key:"183iwg"}],["rect",{width:"3",height:"8",x:"8",y:"14",rx:"1.5",key:"hqg7r1"}],["path",{d:"M5 15.5V14H3.5A1.5 1.5 0 1 0 5 15.5",key:"76g71w"}],["rect",{width:"8",height:"3",x:"14",y:"13",rx:"1.5",key:"1kmz0a"}],["path",{d:"M15.5 19H14v1.5a1.5 1.5 0 1 0 1.5-1.5",key:"jc4sz0"}],["rect",{width:"8",height:"3",x:"2",y:"8",rx:"1.5",key:"1omvl4"}],["path",{d:"M8.5 5H10V3.5A1.5 1.5 0 1 0 8.5 5",key:"16f3cl"}]]);/** * @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=te("Slash",[["path",{d:"M22 2 2 22",key:"y4kqgn"}]]);/** * @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 qoe=te("Slice",[["path",{d:"M11 16.586V19a1 1 0 0 1-1 1H2L18.37 3.63a1 1 0 1 1 3 3l-9.663 9.663a1 1 0 0 1-1.414 0L8 14",key:"1sllp5"}]]);/** * @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=te("SlidersHorizontal",[["line",{x1:"21",x2:"14",y1:"4",y2:"4",key:"obuewd"}],["line",{x1:"10",x2:"3",y1:"4",y2:"4",key:"1q6298"}],["line",{x1:"21",x2:"12",y1:"12",y2:"12",key:"1iu8h1"}],["line",{x1:"8",x2:"3",y1:"12",y2:"12",key:"ntss68"}],["line",{x1:"21",x2:"16",y1:"20",y2:"20",key:"14d8ph"}],["line",{x1:"12",x2:"3",y1:"20",y2:"20",key:"m0wm8r"}],["line",{x1:"14",x2:"14",y1:"2",y2:"6",key:"14e1ph"}],["line",{x1:"8",x2:"8",y1:"10",y2:"14",key:"1i6ji0"}],["line",{x1:"16",x2:"16",y1:"18",y2:"22",key:"1lctlv"}]]);/** * @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 i5=te("SlidersVertical",[["line",{x1:"4",x2:"4",y1:"21",y2:"14",key:"1p332r"}],["line",{x1:"4",x2:"4",y1:"10",y2:"3",key:"gb41h5"}],["line",{x1:"12",x2:"12",y1:"21",y2:"12",key:"hf2csr"}],["line",{x1:"12",x2:"12",y1:"8",y2:"3",key:"1kfi7u"}],["line",{x1:"20",x2:"20",y1:"21",y2:"16",key:"1lhrwl"}],["line",{x1:"20",x2:"20",y1:"12",y2:"3",key:"16vvfq"}],["line",{x1:"2",x2:"6",y1:"14",y2:"14",key:"1uebub"}],["line",{x1:"10",x2:"14",y1:"8",y2:"8",key:"1yglbp"}],["line",{x1:"18",x2:"22",y1:"16",y2:"16",key:"1jxqpz"}]]);/** * @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=te("SmartphoneCharging",[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2",key:"1yt0o3"}],["path",{d:"M12.667 8 10 12h4l-2.667 4",key:"h9lk2d"}]]);/** * @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=te("SmartphoneNfc",[["rect",{width:"7",height:"12",x:"2",y:"6",rx:"1",key:"5nje8w"}],["path",{d:"M13 8.32a7.43 7.43 0 0 1 0 7.36",key:"1g306n"}],["path",{d:"M16.46 6.21a11.76 11.76 0 0 1 0 11.58",key:"uqvjvo"}],["path",{d:"M19.91 4.1a15.91 15.91 0 0 1 .01 15.8",key:"ujntz3"}]]);/** * @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 Vy=te("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 Goe=te("SmilePlus",[["path",{d:"M22 11v1a10 10 0 1 1-9-10",key:"ew0xw9"}],["path",{d:"M8 14s1.5 2 4 2 4-2 4-2",key:"1y1vjs"}],["line",{x1:"9",x2:"9.01",y1:"9",y2:"9",key:"yxxnd0"}],["line",{x1:"15",x2:"15.01",y1:"9",y2:"9",key:"1p4y9e"}],["path",{d:"M16 5h6",key:"1vod17"}],["path",{d:"M19 2v6",key:"4bpg5p"}]]);/** * @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=te("Smile",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 14s1.5 2 4 2 4-2 4-2",key:"1y1vjs"}],["line",{x1:"9",x2:"9.01",y1:"9",y2:"9",key:"yxxnd0"}],["line",{x1:"15",x2:"15.01",y1:"9",y2:"9",key:"1p4y9e"}]]);/** * @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=te("Snail",[["path",{d:"M2 13a6 6 0 1 0 12 0 4 4 0 1 0-8 0 2 2 0 0 0 4 0",key:"hneq2s"}],["circle",{cx:"10",cy:"13",r:"8",key:"194lz3"}],["path",{d:"M2 21h12c4.4 0 8-3.6 8-8V7a2 2 0 1 0-4 0v6",key:"ixqyt7"}],["path",{d:"M18 3 19.1 5.2",key:"9tjm43"}],["path",{d:"M22 3 20.9 5.2",key:"j3odrs"}]]);/** * @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 h1=te("Snowflake",[["line",{x1:"2",x2:"22",y1:"12",y2:"12",key:"1dnqot"}],["line",{x1:"12",x2:"12",y1:"2",y2:"22",key:"7eqyqh"}],["path",{d:"m20 16-4-4 4-4",key:"rquw4f"}],["path",{d:"m4 8 4 4-4 4",key:"12s3z9"}],["path",{d:"m16 4-4 4-4-4",key:"1tumq1"}],["path",{d:"m8 20 4-4 4 4",key:"9p200w"}]]);/** * @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=te("Sofa",[["path",{d:"M20 9V6a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v3",key:"1dgpiv"}],["path",{d:"M2 16a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-5a2 2 0 0 0-4 0v1.5a.5.5 0 0 1-.5.5h-11a.5.5 0 0 1-.5-.5V11a2 2 0 0 0-4 0z",key:"xacw8m"}],["path",{d:"M4 18v2",key:"jwo5n2"}],["path",{d:"M20 18v2",key:"1ar1qi"}],["path",{d:"M12 4v9",key:"oqhhn3"}]]);/** * @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 Zoe=te("Soup",[["path",{d:"M12 21a9 9 0 0 0 9-9H3a9 9 0 0 0 9 9Z",key:"4rw317"}],["path",{d:"M7 21h10",key:"1b0cd5"}],["path",{d:"M19.5 12 22 6",key:"shfsr5"}],["path",{d:"M16.25 3c.27.1.8.53.75 1.36-.06.83-.93 1.2-1 2.02-.05.78.34 1.24.73 1.62",key:"rpc6vp"}],["path",{d:"M11.25 3c.27.1.8.53.74 1.36-.05.83-.93 1.2-.98 2.02-.06.78.33 1.24.72 1.62",key:"1lf63m"}],["path",{d:"M6.25 3c.27.1.8.53.75 1.36-.06.83-.93 1.2-1 2.02-.05.78.34 1.24.74 1.62",key:"97tijn"}]]);/** * @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=te("Space",[["path",{d:"M22 17v1c0 .5-.5 1-1 1H3c-.5 0-1-.5-1-1v-1",key:"lt2kga"}]]);/** * @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 Qoe=te("Spade",[["path",{d:"M5 9c-1.5 1.5-3 3.2-3 5.5A5.5 5.5 0 0 0 7.5 20c1.8 0 3-.5 4.5-2 1.5 1.5 2.7 2 4.5 2a5.5 5.5 0 0 0 5.5-5.5c0-2.3-1.5-4-3-5.5l-7-7-7 7Z",key:"40bo9n"}],["path",{d:"M12 18v4",key:"jadmvz"}]]);/** * @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=te("Sparkle",[["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"}]]);/** * @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 Lr=te("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 ele=te("Speaker",[["rect",{width:"16",height:"20",x:"4",y:"2",rx:"2",key:"1nb95v"}],["path",{d:"M12 6h.01",key:"1vi96p"}],["circle",{cx:"12",cy:"14",r:"4",key:"1jruaj"}],["path",{d:"M12 14h.01",key:"1etili"}]]);/** * @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 tle=te("Speech",[["path",{d:"M8.8 20v-4.1l1.9.2a2.3 2.3 0 0 0 2.164-2.1V8.3A5.37 5.37 0 0 0 2 8.25c0 2.8.656 3.054 1 4.55a5.77 5.77 0 0 1 .029 2.758L2 20",key:"11atix"}],["path",{d:"M19.8 17.8a7.5 7.5 0 0 0 .003-10.603",key:"yol142"}],["path",{d:"M17 15a3.5 3.5 0 0 0-.025-4.975",key:"ssbmkc"}]]);/** * @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 sle=te("SpellCheck2",[["path",{d:"m6 16 6-12 6 12",key:"1b4byz"}],["path",{d:"M8 12h8",key:"1wcyev"}],["path",{d:"M4 21c1.1 0 1.1-1 2.3-1s1.1 1 2.3 1c1.1 0 1.1-1 2.3-1 1.1 0 1.1 1 2.3 1 1.1 0 1.1-1 2.3-1 1.1 0 1.1 1 2.3 1 1.1 0 1.1-1 2.3-1",key:"8mdmtu"}]]);/** * @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 rle=te("SpellCheck",[["path",{d:"m6 16 6-12 6 12",key:"1b4byz"}],["path",{d:"M8 12h8",key:"1wcyev"}],["path",{d:"m16 20 2 2 4-4",key:"13tcca"}]]);/** * @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 nle=te("Spline",[["circle",{cx:"19",cy:"5",r:"2",key:"mhkx31"}],["circle",{cx:"5",cy:"19",r:"2",key:"v8kfzx"}],["path",{d:"M5 17A12 12 0 0 1 17 5",key:"1okkup"}]]);/** * @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 ale=te("Split",[["path",{d:"M16 3h5v5",key:"1806ms"}],["path",{d:"M8 3H3v5",key:"15dfkv"}],["path",{d:"M12 22v-8.3a4 4 0 0 0-1.172-2.872L3 3",key:"1qrqzj"}],["path",{d:"m15 9 6-6",key:"ko1vev"}]]);/** * @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 ile=te("SprayCan",[["path",{d:"M3 3h.01",key:"159qn6"}],["path",{d:"M7 5h.01",key:"1hq22a"}],["path",{d:"M11 7h.01",key:"1osv80"}],["path",{d:"M3 7h.01",key:"1xzrh3"}],["path",{d:"M7 9h.01",key:"19b3jx"}],["path",{d:"M3 11h.01",key:"1eifu7"}],["rect",{width:"4",height:"4",x:"15",y:"5",key:"mri9e4"}],["path",{d:"m19 9 2 2v10c0 .6-.4 1-1 1h-6c-.6 0-1-.4-1-1V11l2-2",key:"aib6hk"}],["path",{d:"m13 14 8-2",key:"1d7bmk"}],["path",{d:"m13 19 8-2",key:"1y2vml"}]]);/** * @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 FE=te("Sprout",[["path",{d:"M7 20h10",key:"e6iznv"}],["path",{d:"M10 20c5.5-2.5.8-6.4 3-10",key:"161w41"}],["path",{d:"M9.5 9.4c1.1.8 1.8 2.2 2.3 3.7-2 .4-3.5.4-4.8-.3-1.2-.6-2.3-1.9-3-4.2 2.8-.5 4.4 0 5.5.8z",key:"9gtqwd"}],["path",{d:"M14.1 6a7 7 0 0 0-1.1 4c1.9-.1 3.3-.6 4.3-1.4 1-1 1.6-2.3 1.7-4.6-2.7.1-4 1-4.9 2z",key:"bkxnd2"}]]);/** * @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 o5=te("SquareActivity",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M17 12h-2l-2 5-2-10-2 5H7",key:"15hlnc"}]]);/** * @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 l5=te("SquareArrowDownLeft",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"m16 8-8 8",key:"166keh"}],["path",{d:"M16 16H8V8",key:"1w2ppm"}]]);/** * @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=te("SquareArrowDownRight",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"m8 8 8 8",key:"1imecy"}],["path",{d:"M16 8v8H8",key:"1lbpgo"}]]);/** * @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 d5=te("SquareArrowDown",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M12 8v8",key:"napkw2"}],["path",{d:"m8 12 4 4 4-4",key:"k98ssh"}]]);/** * @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 u5=te("SquareArrowLeft",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"m12 8-4 4 4 4",key:"15vm53"}],["path",{d:"M16 12H8",key:"1fr5h0"}]]);/** * @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 h5=te("SquareArrowOutDownLeft",[["path",{d:"M13 21h6a2 2 0 0 0 2-2V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v6",key:"14qz4y"}],["path",{d:"m3 21 9-9",key:"1jfql5"}],["path",{d:"M9 21H3v-6",key:"wtvkvv"}]]);/** * @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 m5=te("SquareArrowOutDownRight",[["path",{d:"M21 11V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h6",key:"14rsvq"}],["path",{d:"m21 21-9-9",key:"1et2py"}],["path",{d:"M21 15v6h-6",key:"1jko0i"}]]);/** * @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 f5=te("SquareArrowOutUpLeft",[["path",{d:"M13 3h6a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-6",key:"14mv1t"}],["path",{d:"m3 3 9 9",key:"rks13r"}],["path",{d:"M3 9V3h6",key:"ira0h2"}]]);/** * @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 p5=te("SquareArrowOutUpRight",[["path",{d:"M21 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h6",key:"y09zxi"}],["path",{d:"m21 3-9 9",key:"mpx6sq"}],["path",{d:"M15 3h6v6",key:"1q9fwt"}]]);/** * @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 g5=te("SquareArrowRight",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M8 12h8",key:"1wcyev"}],["path",{d:"m12 16 4-4-4-4",key:"1i9zcv"}]]);/** * @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 x5=te("SquareArrowUpLeft",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M8 16V8h8",key:"19xb1h"}],["path",{d:"M16 16 8 8",key:"1qdy8n"}]]);/** * @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 y5=te("SquareArrowUpRight",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M8 8h8v8",key:"b65dnt"}],["path",{d:"m8 16 8-8",key:"13b9ih"}]]);/** * @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 v5=te("SquareArrowUp",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"m16 12-4-4-4 4",key:"177agl"}],["path",{d:"M12 16V8",key:"1sbj14"}]]);/** * @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 b5=te("SquareAsterisk",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M12 8v8",key:"napkw2"}],["path",{d:"m8.5 14 7-4",key:"12hpby"}],["path",{d:"m8.5 10 7 4",key:"wwy2dy"}]]);/** * @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 _5=te("SquareBottomDashedScissors",[["path",{d:"M4 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v16a2 2 0 0 1-2 2",key:"1vzg26"}],["path",{d:"M10 22H8",key:"euku7a"}],["path",{d:"M16 22h-2",key:"18d249"}],["circle",{cx:"8",cy:"8",r:"2",key:"14cg06"}],["path",{d:"M9.414 9.414 12 12",key:"qz4lzr"}],["path",{d:"M14.8 14.8 18 18",key:"11flf1"}],["circle",{cx:"8",cy:"16",r:"2",key:"1acxsx"}],["path",{d:"m18 6-8.586 8.586",key:"11kzk1"}]]);/** * @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 Pb=te("SquareChartGantt",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 8h7",key:"kbo1nt"}],["path",{d:"M8 12h6",key:"ikassy"}],["path",{d:"M11 16h5",key:"oq65wt"}]]);/** * @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 j2=te("SquareCheckBig",[["path",{d:"M21 10.5V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h12.5",key:"1uzm8b"}],["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 w5=te("SquareCheck",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["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 j5=te("SquareChevronDown",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"m16 10-4 4-4-4",key:"894hmk"}]]);/** * @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=te("SquareChevronLeft",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"m14 16-4-4 4-4",key:"ojs7w8"}]]);/** * @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=te("SquareChevronRight",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"m10 8 4 4-4 4",key:"1wy4r4"}]]);/** * @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 S5=te("SquareChevronUp",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"m8 14 4-4 4 4",key:"fy2ptz"}]]);/** * @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=te("SquareCode",[["path",{d:"M10 9.5 8 12l2 2.5",key:"3mjy60"}],["path",{d:"m14 9.5 2 2.5-2 2.5",key:"1bir2l"}],["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 ole=te("SquareDashedBottomCode",[["path",{d:"M10 9.5 8 12l2 2.5",key:"3mjy60"}],["path",{d:"M14 21h1",key:"v9vybs"}],["path",{d:"m14 9.5 2 2.5-2 2.5",key:"1bir2l"}],["path",{d:"M5 21a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2",key:"as5y1o"}],["path",{d:"M9 21h1",key:"15o7lz"}]]);/** * @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 lle=te("SquareDashedBottom",[["path",{d:"M5 21a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2",key:"as5y1o"}],["path",{d:"M9 21h1",key:"15o7lz"}],["path",{d:"M14 21h1",key:"v9vybs"}]]);/** * @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 T5=te("SquareDashedKanban",[["path",{d:"M8 7v7",key:"1x2jlm"}],["path",{d:"M12 7v4",key:"xawao1"}],["path",{d:"M16 7v9",key:"1hp2iy"}],["path",{d:"M5 3a2 2 0 0 0-2 2",key:"y57alp"}],["path",{d:"M9 3h1",key:"1yesri"}],["path",{d:"M14 3h1",key:"1ec4yj"}],["path",{d:"M19 3a2 2 0 0 1 2 2",key:"18rm91"}],["path",{d:"M21 9v1",key:"mxsmne"}],["path",{d:"M21 14v1",key:"169vum"}],["path",{d:"M21 19a2 2 0 0 1-2 2",key:"1j7049"}],["path",{d:"M14 21h1",key:"v9vybs"}],["path",{d:"M9 21h1",key:"15o7lz"}],["path",{d:"M5 21a2 2 0 0 1-2-2",key:"sbafld"}],["path",{d:"M3 14v1",key:"vnatye"}],["path",{d:"M3 9v1",key:"1r0deq"}]]);/** * @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 E5=te("SquareDashedMousePointer",[["path",{d:"M12.034 12.681a.498.498 0 0 1 .647-.647l9 3.5a.5.5 0 0 1-.033.943l-3.444 1.068a1 1 0 0 0-.66.66l-1.067 3.443a.5.5 0 0 1-.943.033z",key:"xwnzip"}],["path",{d:"M5 3a2 2 0 0 0-2 2",key:"y57alp"}],["path",{d:"M19 3a2 2 0 0 1 2 2",key:"18rm91"}],["path",{d:"M5 21a2 2 0 0 1-2-2",key:"sbafld"}],["path",{d:"M9 3h1",key:"1yesri"}],["path",{d:"M9 21h2",key:"1qve2z"}],["path",{d:"M14 3h1",key:"1ec4yj"}],["path",{d:"M3 9v1",key:"1r0deq"}],["path",{d:"M21 9v2",key:"p14lih"}],["path",{d:"M3 14v1",key:"vnatye"}]]);/** * @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 A5=te("SquareDashed",[["path",{d:"M5 3a2 2 0 0 0-2 2",key:"y57alp"}],["path",{d:"M19 3a2 2 0 0 1 2 2",key:"18rm91"}],["path",{d:"M21 19a2 2 0 0 1-2 2",key:"1j7049"}],["path",{d:"M5 21a2 2 0 0 1-2-2",key:"sbafld"}],["path",{d:"M9 3h1",key:"1yesri"}],["path",{d:"M9 21h1",key:"15o7lz"}],["path",{d:"M14 3h1",key:"1ec4yj"}],["path",{d:"M14 21h1",key:"v9vybs"}],["path",{d:"M3 9v1",key:"1r0deq"}],["path",{d:"M21 9v1",key:"mxsmne"}],["path",{d:"M3 14v1",key:"vnatye"}],["path",{d:"M21 14v1",key:"169vum"}]]);/** * @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 M5=te("SquareDivide",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["line",{x1:"8",x2:"16",y1:"12",y2:"12",key:"1jonct"}],["line",{x1:"12",x2:"12",y1:"16",y2:"16",key:"aqc6ln"}],["line",{x1:"12",x2:"12",y1:"8",y2:"8",key:"1mkcni"}]]);/** * @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 I5=te("SquareDot",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}]]);/** * @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 P5=te("SquareEqual",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M7 10h10",key:"1101jm"}],["path",{d:"M7 14h10",key:"1mhdw3"}]]);/** * @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 L5=te("SquareFunction",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["path",{d:"M9 17c2 0 2.8-1 2.8-2.8V10c0-2 1-3.3 3.2-3",key:"m1af9g"}],["path",{d:"M9 11.2h5.7",key:"3zgcl2"}]]);/** * @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 D5=te("SquareKanban",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M8 7v7",key:"1x2jlm"}],["path",{d:"M12 7v4",key:"xawao1"}],["path",{d:"M16 7v9",key:"1hp2iy"}]]);/** * @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 R5=te("SquareLibrary",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M7 7v10",key:"d5nglc"}],["path",{d:"M11 7v10",key:"pptsnr"}],["path",{d:"m15 7 2 10",key:"1m7qm5"}]]);/** * @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 O5=te("SquareM",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M8 16V8l4 4 4-4v8",key:"141u4e"}]]);/** * @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 F5=te("SquareMenu",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M7 8h10",key:"1jw688"}],["path",{d:"M7 12h10",key:"b7w52i"}],["path",{d:"M7 16h10",key:"wp8him"}]]);/** * @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 B5=te("SquareMinus",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M8 12h8",key:"1wcyev"}]]);/** * @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 z5=te("SquareMousePointer",[["path",{d:"M12.034 12.681a.498.498 0 0 1 .647-.647l9 3.5a.5.5 0 0 1-.033.943l-3.444 1.068a1 1 0 0 0-.66.66l-1.067 3.443a.5.5 0 0 1-.943.033z",key:"xwnzip"}],["path",{d:"M21 11V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h6",key:"14rsvq"}]]);/** * @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 $5=te("SquareParkingOff",[["path",{d:"M3.6 3.6A2 2 0 0 1 5 3h14a2 2 0 0 1 2 2v14a2 2 0 0 1-.59 1.41",key:"9l1ft6"}],["path",{d:"M3 8.7V19a2 2 0 0 0 2 2h10.3",key:"17knke"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M13 13a3 3 0 1 0 0-6H9v2",key:"uoagbd"}],["path",{d:"M9 17v-2.3",key:"1jxgo2"}]]);/** * @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 U5=te("SquareParking",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 17V7h4a3 3 0 0 1 0 6H9",key:"1dfk2c"}]]);/** * @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=te("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 q5=te("SquarePercent",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"M9 9h.01",key:"1q5me6"}],["path",{d:"M15 15h.01",key:"lqbp3k"}]]);/** * @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 V5=te("SquarePi",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M7 7h10",key:"udp07y"}],["path",{d:"M10 7v10",key:"i1d9ee"}],["path",{d:"M16 17a2 2 0 0 1-2-2V7",key:"ftwdc7"}]]);/** * @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 H5=te("SquarePilcrow",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M12 12H9.5a2.5 2.5 0 0 1 0-5H17",key:"1l9586"}],["path",{d:"M12 7v10",key:"jspqdw"}],["path",{d:"M16 7v10",key:"lavkr4"}]]);/** * @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 G5=te("SquarePlay",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"m9 8 6 4-6 4Z",key:"f1r3lt"}]]);/** * @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 W5=te("SquarePlus",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M8 12h8",key:"1wcyev"}],["path",{d:"M12 8v8",key:"napkw2"}]]);/** * @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=te("SquarePower",[["path",{d:"M12 7v4",key:"xawao1"}],["path",{d:"M7.998 9.003a5 5 0 1 0 8-.005",key:"1pek45"}],["rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",key:"h1oib"}]]);/** * @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 cle=te("SquareRadical",[["path",{d:"M7 12h2l2 5 2-10h4",key:"1fxv6h"}],["rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",key:"h1oib"}]]);/** * @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 Y5=te("SquareScissors",[["rect",{width:"20",height:"20",x:"2",y:"2",rx:"2",key:"1btzen"}],["circle",{cx:"8",cy:"8",r:"2",key:"14cg06"}],["path",{d:"M9.414 9.414 12 12",key:"qz4lzr"}],["path",{d:"M14.8 14.8 18 18",key:"11flf1"}],["circle",{cx:"8",cy:"16",r:"2",key:"1acxsx"}],["path",{d:"m18 6-8.586 8.586",key:"11kzk1"}]]);/** * @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 Z5=te("SquareSigma",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M16 8.9V7H8l4 5-4 5h8v-1.9",key:"9nih0i"}]]);/** * @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 X5=te("SquareSlash",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["line",{x1:"9",x2:"15",y1:"15",y2:"9",key:"1dfufj"}]]);/** * @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 Q5=te("SquareSplitHorizontal",[["path",{d:"M8 19H5c-1 0-2-1-2-2V7c0-1 1-2 2-2h3",key:"lubmu8"}],["path",{d:"M16 5h3c1 0 2 1 2 2v10c0 1-1 2-2 2h-3",key:"1ag34g"}],["line",{x1:"12",x2:"12",y1:"4",y2:"20",key:"1tx1rr"}]]);/** * @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 J5=te("SquareSplitVertical",[["path",{d:"M5 8V5c0-1 1-2 2-2h10c1 0 2 1 2 2v3",key:"1pi83i"}],["path",{d:"M19 16v3c0 1-1 2-2 2H7c-1 0-2-1-2-2v-3",key:"ido5k7"}],["line",{x1:"4",x2:"20",y1:"12",y2:"12",key:"1e0a9i"}]]);/** * @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 dle=te("SquareSquare",[["rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",key:"h1oib"}],["rect",{x:"8",y:"8",width:"8",height:"8",rx:"1",key:"z9xiuo"}]]);/** * @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 ule=te("SquareStack",[["path",{d:"M4 10c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h4c1.1 0 2 .9 2 2",key:"4i38lg"}],["path",{d:"M10 16c-1.1 0-2-.9-2-2v-4c0-1.1.9-2 2-2h4c1.1 0 2 .9 2 2",key:"mlte4a"}],["rect",{width:"8",height:"8",x:"14",y:"14",rx:"2",key:"1fa9i4"}]]);/** * @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 eT=te("SquareTerminal",[["path",{d:"m7 11 2-2-2-2",key:"1lz0vl"}],["path",{d:"M11 13h4",key:"1p7l4v"}],["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}]]);/** * @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 tT=te("SquareUserRound",[["path",{d:"M18 21a6 6 0 0 0-12 0",key:"kaz2du"}],["circle",{cx:"12",cy:"11",r:"4",key:"1gt34v"}],["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 sT=te("SquareUser",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["circle",{cx:"12",cy:"10",r:"3",key:"ilqhr7"}],["path",{d:"M7 21v-2a2 2 0 0 1 2-2h6a2 2 0 0 1 2 2v2",key:"1m6ac2"}]]);/** * @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 rT=te("SquareX",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["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 Hy=te("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 hle=te("Squircle",[["path",{d:"M12 3c7.2 0 9 1.8 9 9s-1.8 9-9 9-9-1.8-9-9 1.8-9 9-9",key:"garfkc"}]]);/** * @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 mle=te("Squirrel",[["path",{d:"M15.236 22a3 3 0 0 0-2.2-5",key:"21bitc"}],["path",{d:"M16 20a3 3 0 0 1 3-3h1a2 2 0 0 0 2-2v-2a4 4 0 0 0-4-4V4",key:"oh0fg0"}],["path",{d:"M18 13h.01",key:"9veqaj"}],["path",{d:"M18 6a4 4 0 0 0-4 4 7 7 0 0 0-7 7c0-5 4-5 4-10.5a4.5 4.5 0 1 0-9 0 2.5 2.5 0 0 0 5 0C7 10 3 11 3 17c0 2.8 2.2 5 5 5h10",key:"980v8a"}]]);/** * @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 fle=te("Stamp",[["path",{d:"M5 22h14",key:"ehvnwv"}],["path",{d:"M19.27 13.73A2.5 2.5 0 0 0 17.5 13h-11A2.5 2.5 0 0 0 4 15.5V17a1 1 0 0 0 1 1h14a1 1 0 0 0 1-1v-1.5c0-.66-.26-1.3-.73-1.77Z",key:"1sy9ra"}],["path",{d:"M14 13V8.5C14 7 15 7 15 5a3 3 0 0 0-3-3c-1.66 0-3 1-3 3s1 2 1 3.5V13",key:"cnxgux"}]]);/** * @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 ple=te("StarHalf",[["path",{d:"M12 18.338a2.1 2.1 0 0 0-.987.244L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.12 2.12 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.12 2.12 0 0 0 1.597-1.16l2.309-4.679A.53.53 0 0 1 12 2",key:"2ksp49"}]]);/** * @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 gle=te("StarOff",[["path",{d:"M8.34 8.34 2 9.27l5 4.87L5.82 21 12 17.77 18.18 21l-.59-3.43",key:"16m0ql"}],["path",{d:"M18.42 12.76 22 9.27l-6.91-1L12 2l-1.44 2.91",key:"1vt8nq"}],["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}]]);/** * @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 ya=te("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 xle=te("StepBack",[["line",{x1:"18",x2:"18",y1:"20",y2:"4",key:"cun8e5"}],["polygon",{points:"14,20 4,12 14,4",key:"ypakod"}]]);/** * @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 yle=te("StepForward",[["line",{x1:"6",x2:"6",y1:"4",y2:"20",key:"fy8qot"}],["polygon",{points:"10,4 20,12 10,20",key:"1mc1pf"}]]);/** * @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 vle=te("Stethoscope",[["path",{d:"M11 2v2",key:"1539x4"}],["path",{d:"M5 2v2",key:"1yf1q8"}],["path",{d:"M5 3H4a2 2 0 0 0-2 2v4a6 6 0 0 0 12 0V5a2 2 0 0 0-2-2h-1",key:"rb5t3r"}],["path",{d:"M8 15a6 6 0 0 0 12 0v-3",key:"x18d4x"}],["circle",{cx:"20",cy:"10",r:"2",key:"ts1r5v"}]]);/** * @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 ble=te("Sticker",[["path",{d:"M15.5 3H5a2 2 0 0 0-2 2v14c0 1.1.9 2 2 2h14a2 2 0 0 0 2-2V8.5L15.5 3Z",key:"1wis1t"}],["path",{d:"M14 3v4a2 2 0 0 0 2 2h4",key:"36rjfy"}],["path",{d:"M8 13h.01",key:"1sbv64"}],["path",{d:"M16 13h.01",key:"wip0gl"}],["path",{d:"M10 16s.8 1 2 1c1.3 0 2-1 2-1",key:"1vvgv3"}]]);/** * @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 _le=te("StickyNote",[["path",{d:"M16 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V8Z",key:"qazsjp"}],["path",{d:"M15 3v4a2 2 0 0 0 2 2h4",key:"40519r"}]]);/** * @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 wle=te("Store",[["path",{d:"m2 7 4.41-4.41A2 2 0 0 1 7.83 2h8.34a2 2 0 0 1 1.42.59L22 7",key:"ztvudi"}],["path",{d:"M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8",key:"1b2hhj"}],["path",{d:"M15 22v-4a2 2 0 0 0-2-2h-2a2 2 0 0 0-2 2v4",key:"2ebpfo"}],["path",{d:"M2 7h20",key:"1fcdvo"}],["path",{d:"M22 7v3a2 2 0 0 1-2 2a2.7 2.7 0 0 1-1.59-.63.7.7 0 0 0-.82 0A2.7 2.7 0 0 1 16 12a2.7 2.7 0 0 1-1.59-.63.7.7 0 0 0-.82 0A2.7 2.7 0 0 1 12 12a2.7 2.7 0 0 1-1.59-.63.7.7 0 0 0-.82 0A2.7 2.7 0 0 1 8 12a2.7 2.7 0 0 1-1.59-.63.7.7 0 0 0-.82 0A2.7 2.7 0 0 1 4 12a2 2 0 0 1-2-2V7",key:"6c3vgh"}]]);/** * @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 jle=te("StretchHorizontal",[["rect",{width:"20",height:"6",x:"2",y:"4",rx:"2",key:"qdearl"}],["rect",{width:"20",height:"6",x:"2",y:"14",rx:"2",key:"1xrn6j"}]]);/** * @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 Nle=te("StretchVertical",[["rect",{width:"6",height:"20",x:"4",y:"2",rx:"2",key:"19qu7m"}],["rect",{width:"6",height:"20",x:"14",y:"2",rx:"2",key:"24v0nk"}]]);/** * @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 LF=te("Strikethrough",[["path",{d:"M16 4H9a3 3 0 0 0-2.83 4",key:"43sutm"}],["path",{d:"M14 12a4 4 0 0 1 0 8H6",key:"nlfj13"}],["line",{x1:"4",x2:"20",y1:"12",y2:"12",key:"1e0a9i"}]]);/** * @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 kle=te("Subscript",[["path",{d:"m4 5 8 8",key:"1eunvl"}],["path",{d:"m12 5-8 8",key:"1ah0jp"}],["path",{d:"M20 19h-4c0-1.5.44-2 1.5-2.5S20 15.33 20 14c0-.47-.17-.93-.48-1.29a2.11 2.11 0 0 0-2.62-.44c-.42.24-.74.62-.9 1.07",key:"e8ta8j"}]]);/** * @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 Sle=te("SunDim",[["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M12 4h.01",key:"1ujb9j"}],["path",{d:"M20 12h.01",key:"1ykeid"}],["path",{d:"M12 20h.01",key:"zekei9"}],["path",{d:"M4 12h.01",key:"158zrr"}],["path",{d:"M17.657 6.343h.01",key:"31pqzk"}],["path",{d:"M17.657 17.657h.01",key:"jehnf4"}],["path",{d:"M6.343 17.657h.01",key:"gdk6ow"}],["path",{d:"M6.343 6.343h.01",key:"1uurf0"}]]);/** * @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 Cle=te("SunMedium",[["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M12 3v1",key:"1asbbs"}],["path",{d:"M12 20v1",key:"1wcdkc"}],["path",{d:"M3 12h1",key:"lp3yf2"}],["path",{d:"M20 12h1",key:"1vloll"}],["path",{d:"m18.364 5.636-.707.707",key:"1hakh0"}],["path",{d:"m6.343 17.657-.707.707",key:"18m9nf"}],["path",{d:"m5.636 5.636.707.707",key:"1xv1c5"}],["path",{d:"m17.657 17.657.707.707",key:"vl76zb"}]]);/** * @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 Tle=te("SunMoon",[["path",{d:"M12 8a2.83 2.83 0 0 0 4 4 4 4 0 1 1-4-4",key:"1fu5g2"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"m4.9 4.9 1.4 1.4",key:"b9915j"}],["path",{d:"m17.7 17.7 1.4 1.4",key:"qc3ed3"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"m6.3 17.7-1.4 1.4",key:"5gca6"}],["path",{d:"m19.1 4.9-1.4 1.4",key:"wpu9u6"}]]);/** * @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 Ele=te("SunSnow",[["path",{d:"M10 9a3 3 0 1 0 0 6",key:"6zmtdl"}],["path",{d:"M2 12h1",key:"1uaihz"}],["path",{d:"M14 21V3",key:"1llu3z"}],["path",{d:"M10 4V3",key:"pkzwkn"}],["path",{d:"M10 21v-1",key:"1u8rkd"}],["path",{d:"m3.64 18.36.7-.7",key:"105rm9"}],["path",{d:"m4.34 6.34-.7-.7",key:"d3unjp"}],["path",{d:"M14 12h8",key:"4f43i9"}],["path",{d:"m17 4-3 3",key:"15jcng"}],["path",{d:"m14 17 3 3",key:"6tlq38"}],["path",{d:"m21 15-3-3 3-3",key:"1nlnje"}]]);/** * @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=te("Sun",[["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"m4.93 4.93 1.41 1.41",key:"149t6j"}],["path",{d:"m17.66 17.66 1.41 1.41",key:"ptbguv"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"m6.34 17.66-1.41 1.41",key:"1m8zz5"}],["path",{d:"m19.07 4.93-1.41 1.41",key:"1shlcs"}]]);/** * @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 Ale=te("Sunrise",[["path",{d:"M12 2v8",key:"1q4o3n"}],["path",{d:"m4.93 10.93 1.41 1.41",key:"2a7f42"}],["path",{d:"M2 18h2",key:"j10viu"}],["path",{d:"M20 18h2",key:"wocana"}],["path",{d:"m19.07 10.93-1.41 1.41",key:"15zs5n"}],["path",{d:"M22 22H2",key:"19qnx5"}],["path",{d:"m8 6 4-4 4 4",key:"ybng9g"}],["path",{d:"M16 18a4 4 0 0 0-8 0",key:"1lzouq"}]]);/** * @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 Mle=te("Sunset",[["path",{d:"M12 10V2",key:"16sf7g"}],["path",{d:"m4.93 10.93 1.41 1.41",key:"2a7f42"}],["path",{d:"M2 18h2",key:"j10viu"}],["path",{d:"M20 18h2",key:"wocana"}],["path",{d:"m19.07 10.93-1.41 1.41",key:"15zs5n"}],["path",{d:"M22 22H2",key:"19qnx5"}],["path",{d:"m16 6-4 4-4-4",key:"6wukr"}],["path",{d:"M16 18a4 4 0 0 0-8 0",key:"1lzouq"}]]);/** * @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 Ile=te("Superscript",[["path",{d:"m4 19 8-8",key:"hr47gm"}],["path",{d:"m12 19-8-8",key:"1dhhmo"}],["path",{d:"M20 12h-4c0-1.5.442-2 1.5-2.5S20 8.334 20 7.002c0-.472-.17-.93-.484-1.29a2.105 2.105 0 0 0-2.617-.436c-.42.239-.738.614-.899 1.06",key:"1dfcux"}]]);/** * @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 Ple=te("SwatchBook",[["path",{d:"M11 17a4 4 0 0 1-8 0V5a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2Z",key:"1ldrpk"}],["path",{d:"M16.7 13H19a2 2 0 0 1 2 2v4a2 2 0 0 1-2 2H7",key:"11i5po"}],["path",{d:"M 7 17h.01",key:"1euzgo"}],["path",{d:"m11 8 2.3-2.3a2.4 2.4 0 0 1 3.404.004L18.6 7.6a2.4 2.4 0 0 1 .026 3.434L9.9 19.8",key:"o2gii7"}]]);/** * @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 Lle=te("SwissFranc",[["path",{d:"M10 21V3h8",key:"br2l0g"}],["path",{d:"M6 16h9",key:"2py0wn"}],["path",{d:"M10 9.5h7",key:"13dmhz"}]]);/** * @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 Dle=te("SwitchCamera",[["path",{d:"M11 19H4a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2h5",key:"mtk2lu"}],["path",{d:"M13 5h7a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2h-5",key:"120jsl"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}],["path",{d:"m18 22-3-3 3-3",key:"kgdoj7"}],["path",{d:"m6 2 3 3-3 3",key:"1fnbkv"}]]);/** * @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 Rle=te("Sword",[["polyline",{points:"14.5 17.5 3 6 3 3 6 3 17.5 14.5",key:"1hfsw2"}],["line",{x1:"13",x2:"19",y1:"19",y2:"13",key:"1vrmhu"}],["line",{x1:"16",x2:"20",y1:"16",y2:"20",key:"1bron3"}],["line",{x1:"19",x2:"21",y1:"21",y2:"19",key:"13pww6"}]]);/** * @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 Ole=te("Swords",[["polyline",{points:"14.5 17.5 3 6 3 3 6 3 17.5 14.5",key:"1hfsw2"}],["line",{x1:"13",x2:"19",y1:"19",y2:"13",key:"1vrmhu"}],["line",{x1:"16",x2:"20",y1:"16",y2:"20",key:"1bron3"}],["line",{x1:"19",x2:"21",y1:"21",y2:"19",key:"13pww6"}],["polyline",{points:"14.5 6.5 18 3 21 3 21 6 17.5 9.5",key:"hbey2j"}],["line",{x1:"5",x2:"9",y1:"14",y2:"18",key:"1hf58s"}],["line",{x1:"7",x2:"4",y1:"17",y2:"20",key:"pidxm4"}],["line",{x1:"3",x2:"5",y1:"19",y2:"21",key:"1pehsh"}]]);/** * @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 Fle=te("Syringe",[["path",{d:"m18 2 4 4",key:"22kx64"}],["path",{d:"m17 7 3-3",key:"1w1zoj"}],["path",{d:"M19 9 8.7 19.3c-1 1-2.5 1-3.4 0l-.6-.6c-1-1-1-2.5 0-3.4L15 5",key:"1exhtz"}],["path",{d:"m9 11 4 4",key:"rovt3i"}],["path",{d:"m5 19-3 3",key:"59f2uf"}],["path",{d:"m14 4 6 6",key:"yqp9t2"}]]);/** * @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 YI=te("Table2",[["path",{d:"M9 3H5a2 2 0 0 0-2 2v4m6-6h10a2 2 0 0 1 2 2v4M9 3v18m0 0h10a2 2 0 0 0 2-2V9M9 21H5a2 2 0 0 1-2-2V9m0 0h18",key:"gugj83"}]]);/** * @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 Ble=te("TableCellsMerge",[["path",{d:"M12 21v-6",key:"lihzve"}],["path",{d:"M12 9V3",key:"da5inc"}],["path",{d:"M3 15h18",key:"5xshup"}],["path",{d:"M3 9h18",key:"1pudct"}],["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 zle=te("TableCellsSplit",[["path",{d:"M12 15V9",key:"8c7uyn"}],["path",{d:"M3 15h18",key:"5xshup"}],["path",{d:"M3 9h18",key:"1pudct"}],["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 $le=te("TableColumnsSplit",[["path",{d:"M14 14v2",key:"w2a1xv"}],["path",{d:"M14 20v2",key:"1lq872"}],["path",{d:"M14 2v2",key:"6buw04"}],["path",{d:"M14 8v2",key:"i67w9a"}],["path",{d:"M2 15h8",key:"82wtch"}],["path",{d:"M2 3h6a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H2",key:"up0l64"}],["path",{d:"M2 9h8",key:"yelfik"}],["path",{d:"M22 15h-4",key:"1es58f"}],["path",{d:"M22 3h-2a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h2",key:"pdjoqf"}],["path",{d:"M22 9h-4",key:"1luja7"}],["path",{d:"M5 3v18",key:"14hmio"}]]);/** * @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 Ule=te("TableOfContents",[["path",{d:"M16 12H3",key:"1a2rj7"}],["path",{d:"M16 18H3",key:"12xzn7"}],["path",{d:"M16 6H3",key:"1wxfjs"}],["path",{d:"M21 12h.01",key:"msek7k"}],["path",{d:"M21 18h.01",key:"1e8rq1"}],["path",{d:"M21 6h.01",key:"1koanj"}]]);/** * @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 qle=te("TableProperties",[["path",{d:"M15 3v18",key:"14nvp0"}],["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M21 9H3",key:"1338ky"}],["path",{d:"M21 15H3",key:"9uk58r"}]]);/** * @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 Vle=te("TableRowsSplit",[["path",{d:"M14 10h2",key:"1lstlu"}],["path",{d:"M15 22v-8",key:"1fwwgm"}],["path",{d:"M15 2v4",key:"1044rn"}],["path",{d:"M2 10h2",key:"1r8dkt"}],["path",{d:"M20 10h2",key:"1ug425"}],["path",{d:"M3 19h18",key:"awlh7x"}],["path",{d:"M3 22v-6a2 2 135 0 1 2-2h14a2 2 45 0 1 2 2v6",key:"ibqhof"}],["path",{d:"M3 2v2a2 2 45 0 0 2 2h14a2 2 135 0 0 2-2V2",key:"1uenja"}],["path",{d:"M8 10h2",key:"66od0"}],["path",{d:"M9 22v-8",key:"fmnu31"}],["path",{d:"M9 2v4",key:"j1yeou"}]]);/** * @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 ZI=te("Table",[["path",{d:"M12 3v18",key:"108xh3"}],["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"}]]);/** * @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 Hle=te("TabletSmartphone",[["rect",{width:"10",height:"14",x:"3",y:"8",rx:"2",key:"1vrsiq"}],["path",{d:"M5 4a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v16a2 2 0 0 1-2 2h-2.4",key:"1j4zmg"}],["path",{d:"M8 18h.01",key:"lrp35t"}]]);/** * @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 Gle=te("Tablet",[["rect",{width:"16",height:"20",x:"4",y:"2",rx:"2",ry:"2",key:"76otgf"}],["line",{x1:"12",x2:"12.01",y1:"18",y2:"18",key:"1dp563"}]]);/** * @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 Wle=te("Tablets",[["circle",{cx:"7",cy:"7",r:"5",key:"x29byf"}],["circle",{cx:"17",cy:"17",r:"5",key:"1op1d2"}],["path",{d:"M12 17h10",key:"ls21zv"}],["path",{d:"m3.46 10.54 7.08-7.08",key:"1rehiu"}]]);/** * @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 xm=te("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 Kle=te("Tags",[["path",{d:"m15 5 6.3 6.3a2.4 2.4 0 0 1 0 3.4L17 19",key:"1cbfv1"}],["path",{d:"M9.586 5.586A2 2 0 0 0 8.172 5H3a1 1 0 0 0-1 1v5.172a2 2 0 0 0 .586 1.414L8.29 18.29a2.426 2.426 0 0 0 3.42 0l3.58-3.58a2.426 2.426 0 0 0 0-3.42z",key:"135mg7"}],["circle",{cx:"6.5",cy:"9.5",r:".5",fill:"currentColor",key:"5pm5xn"}]]);/** * @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 Yle=te("Tally1",[["path",{d:"M4 4v16",key:"6qkkli"}]]);/** * @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 Zle=te("Tally2",[["path",{d:"M4 4v16",key:"6qkkli"}],["path",{d:"M9 4v16",key:"81ygyz"}]]);/** * @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 Xle=te("Tally3",[["path",{d:"M4 4v16",key:"6qkkli"}],["path",{d:"M9 4v16",key:"81ygyz"}],["path",{d:"M14 4v16",key:"12vmem"}]]);/** * @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 Qle=te("Tally4",[["path",{d:"M4 4v16",key:"6qkkli"}],["path",{d:"M9 4v16",key:"81ygyz"}],["path",{d:"M14 4v16",key:"12vmem"}],["path",{d:"M19 4v16",key:"8ij5ei"}]]);/** * @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 Jle=te("Tally5",[["path",{d:"M4 4v16",key:"6qkkli"}],["path",{d:"M9 4v16",key:"81ygyz"}],["path",{d:"M14 4v16",key:"12vmem"}],["path",{d:"M19 4v16",key:"8ij5ei"}],["path",{d:"M22 6 2 18",key:"h9moai"}]]);/** * @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 ece=te("Tangent",[["circle",{cx:"17",cy:"4",r:"2",key:"y5j2s2"}],["path",{d:"M15.59 5.41 5.41 15.59",key:"l0vprr"}],["circle",{cx:"4",cy:"17",r:"2",key:"9p4efm"}],["path",{d:"M12 22s-4-9-1.5-11.5S22 12 22 12",key:"1twk4o"}]]);/** * @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 Wu=te("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 tce=te("Telescope",[["path",{d:"m10.065 12.493-6.18 1.318a.934.934 0 0 1-1.108-.702l-.537-2.15a1.07 1.07 0 0 1 .691-1.265l13.504-4.44",key:"k4qptu"}],["path",{d:"m13.56 11.747 4.332-.924",key:"19l80z"}],["path",{d:"m16 21-3.105-6.21",key:"7oh9d"}],["path",{d:"M16.485 5.94a2 2 0 0 1 1.455-2.425l1.09-.272a1 1 0 0 1 1.212.727l1.515 6.06a1 1 0 0 1-.727 1.213l-1.09.272a2 2 0 0 1-2.425-1.455z",key:"m7xp4m"}],["path",{d:"m6.158 8.633 1.114 4.456",key:"74o979"}],["path",{d:"m8 21 3.105-6.21",key:"1fvxut"}],["circle",{cx:"12",cy:"13",r:"2",key:"1c1ljs"}]]);/** * @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 sce=te("TentTree",[["circle",{cx:"4",cy:"4",r:"2",key:"bt5ra8"}],["path",{d:"m14 5 3-3 3 3",key:"1sorif"}],["path",{d:"m14 10 3-3 3 3",key:"1jyi9h"}],["path",{d:"M17 14V2",key:"8ymqnk"}],["path",{d:"M17 14H7l-5 8h20Z",key:"13ar7p"}],["path",{d:"M8 14v8",key:"1ghmqk"}],["path",{d:"m9 14 5 8",key:"13pgi6"}]]);/** * @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 rce=te("Tent",[["path",{d:"M3.5 21 14 3",key:"1szst5"}],["path",{d:"M20.5 21 10 3",key:"1310c3"}],["path",{d:"M15.5 21 12 15l-3.5 6",key:"1ddtfw"}],["path",{d:"M2 21h20",key:"1nyx9w"}]]);/** * @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 nce=te("Terminal",[["polyline",{points:"4 17 10 11 4 5",key:"akl6gq"}],["line",{x1:"12",x2:"20",y1:"19",y2:"19",key:"q2wloq"}]]);/** * @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 nT=te("TestTubeDiagonal",[["path",{d:"M21 7 6.82 21.18a2.83 2.83 0 0 1-3.99-.01a2.83 2.83 0 0 1 0-4L17 3",key:"1ub6xw"}],["path",{d:"m16 2 6 6",key:"1gw87d"}],["path",{d:"M12 16H4",key:"1cjfip"}]]);/** * @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 ace=te("TestTube",[["path",{d:"M14.5 2v17.5c0 1.4-1.1 2.5-2.5 2.5c-1.4 0-2.5-1.1-2.5-2.5V2",key:"125lnx"}],["path",{d:"M8.5 2h7",key:"csnxdl"}],["path",{d:"M14.5 16h-5",key:"1ox875"}]]);/** * @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 ice=te("TestTubes",[["path",{d:"M9 2v17.5A2.5 2.5 0 0 1 6.5 22A2.5 2.5 0 0 1 4 19.5V2",key:"1hjrqt"}],["path",{d:"M20 2v17.5a2.5 2.5 0 0 1-2.5 2.5a2.5 2.5 0 0 1-2.5-2.5V2",key:"16lc8n"}],["path",{d:"M3 2h7",key:"7s29d5"}],["path",{d:"M14 2h7",key:"7sicin"}],["path",{d:"M9 16H4",key:"1bfye3"}],["path",{d:"M20 16h-5",key:"ddnjpe"}]]);/** * @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 oce=te("TextCursorInput",[["path",{d:"M5 4h1a3 3 0 0 1 3 3 3 3 0 0 1 3-3h1",key:"18xjzo"}],["path",{d:"M13 20h-1a3 3 0 0 1-3-3 3 3 0 0 1-3 3H5",key:"fj48gi"}],["path",{d:"M5 16H4a2 2 0 0 1-2-2v-4a2 2 0 0 1 2-2h1",key:"1n9rhb"}],["path",{d:"M13 8h7a2 2 0 0 1 2 2v4a2 2 0 0 1-2 2h-7",key:"13ksps"}],["path",{d:"M9 7v10",key:"1vc8ob"}]]);/** * @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 lce=te("TextCursor",[["path",{d:"M17 22h-1a4 4 0 0 1-4-4V6a4 4 0 0 1 4-4h1",key:"uvaxm9"}],["path",{d:"M7 22h1a4 4 0 0 0 4-4v-1",key:"11xy8d"}],["path",{d:"M7 2h1a4 4 0 0 1 4 4v1",key:"1uw06m"}]]);/** * @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 cce=te("TextQuote",[["path",{d:"M17 6H3",key:"16j9eg"}],["path",{d:"M21 12H8",key:"scolzb"}],["path",{d:"M21 18H8",key:"1wfozv"}],["path",{d:"M3 12v6",key:"fv4c87"}]]);/** * @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 dce=te("TextSearch",[["path",{d:"M21 6H3",key:"1jwq7v"}],["path",{d:"M10 12H3",key:"1ulcyk"}],["path",{d:"M10 18H3",key:"13769t"}],["circle",{cx:"17",cy:"15",r:"3",key:"1upz2a"}],["path",{d:"m21 19-1.9-1.9",key:"dwi7p8"}]]);/** * @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 aT=te("TextSelect",[["path",{d:"M5 3a2 2 0 0 0-2 2",key:"y57alp"}],["path",{d:"M19 3a2 2 0 0 1 2 2",key:"18rm91"}],["path",{d:"M21 19a2 2 0 0 1-2 2",key:"1j7049"}],["path",{d:"M5 21a2 2 0 0 1-2-2",key:"sbafld"}],["path",{d:"M9 3h1",key:"1yesri"}],["path",{d:"M9 21h1",key:"15o7lz"}],["path",{d:"M14 3h1",key:"1ec4yj"}],["path",{d:"M14 21h1",key:"v9vybs"}],["path",{d:"M3 9v1",key:"1r0deq"}],["path",{d:"M21 9v1",key:"mxsmne"}],["path",{d:"M3 14v1",key:"vnatye"}],["path",{d:"M21 14v1",key:"169vum"}],["line",{x1:"7",x2:"15",y1:"8",y2:"8",key:"1758g8"}],["line",{x1:"7",x2:"17",y1:"12",y2:"12",key:"197423"}],["line",{x1:"7",x2:"13",y1:"16",y2:"16",key:"37cgm6"}]]);/** * @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 uce=te("Text",[["path",{d:"M17 6.1H3",key:"wptmhv"}],["path",{d:"M21 12.1H3",key:"1j38uz"}],["path",{d:"M15.1 18H3",key:"1nb16a"}]]);/** * @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 hce=te("Theater",[["path",{d:"M2 10s3-3 3-8",key:"3xiif0"}],["path",{d:"M22 10s-3-3-3-8",key:"ioaa5q"}],["path",{d:"M10 2c0 4.4-3.6 8-8 8",key:"16fkpi"}],["path",{d:"M14 2c0 4.4 3.6 8 8 8",key:"b9eulq"}],["path",{d:"M2 10s2 2 2 5",key:"1au1lb"}],["path",{d:"M22 10s-2 2-2 5",key:"qi2y5e"}],["path",{d:"M8 15h8",key:"45n4r"}],["path",{d:"M2 22v-1a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v1",key:"1vsc2m"}],["path",{d:"M14 22v-1a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v1",key:"hrha4u"}]]);/** * @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 mce=te("ThermometerSnowflake",[["path",{d:"M2 12h10",key:"19562f"}],["path",{d:"M9 4v16",key:"81ygyz"}],["path",{d:"m3 9 3 3-3 3",key:"1sas0l"}],["path",{d:"M12 6 9 9 6 6",key:"pfrgxu"}],["path",{d:"m6 18 3-3 1.5 1.5",key:"1e277p"}],["path",{d:"M20 4v10.54a4 4 0 1 1-4 0V4a2 2 0 0 1 4 0Z",key:"iof6y5"}]]);/** * @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 fce=te("ThermometerSun",[["path",{d:"M12 9a4 4 0 0 0-2 7.5",key:"1jvsq6"}],["path",{d:"M12 3v2",key:"1w22ol"}],["path",{d:"m6.6 18.4-1.4 1.4",key:"w2yidj"}],["path",{d:"M20 4v10.54a4 4 0 1 1-4 0V4a2 2 0 0 1 4 0Z",key:"iof6y5"}],["path",{d:"M4 13H2",key:"118le4"}],["path",{d:"M6.34 7.34 4.93 5.93",key:"1brd51"}]]);/** * @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 pce=te("Thermometer",[["path",{d:"M14 4v10.54a4 4 0 1 1-4 0V4a2 2 0 0 1 4 0Z",key:"17jzev"}]]);/** * @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 DF=te("ThumbsDown",[["path",{d:"M17 14V2",key:"8ymqnk"}],["path",{d:"M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22a3.13 3.13 0 0 1-3-3.88Z",key:"m61m77"}]]);/** * @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=te("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 gce=te("TicketCheck",[["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:"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 xce=te("TicketMinus",[["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:"M9 12h6",key:"1c52cq"}]]);/** * @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 yce=te("TicketPercent",[["path",{d:"M2 9a3 3 0 1 1 0 6v2a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-2a3 3 0 1 1 0-6V7a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2Z",key:"1l48ns"}],["path",{d:"M9 9h.01",key:"1q5me6"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"M15 15h.01",key:"lqbp3k"}]]);/** * @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 vce=te("TicketPlus",[["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:"M9 12h6",key:"1c52cq"}],["path",{d:"M12 9v6",key:"199k2o"}]]);/** * @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 bce=te("TicketSlash",[["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:"m9.5 14.5 5-5",key:"qviqfa"}]]);/** * @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 _ce=te("TicketX",[["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:"m9.5 14.5 5-5",key:"qviqfa"}],["path",{d:"m9.5 9.5 5 5",key:"18nt4w"}]]);/** * @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=te("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 wce=te("TicketsPlane",[["path",{d:"M10.5 17h1.227a2 2 0 0 0 1.345-.52L18 12",key:"16muxl"}],["path",{d:"m12 13.5 3.75.5",key:"1i9qhk"}],["path",{d:"m4.5 8 10.58-5.06a1 1 0 0 1 1.342.488L18.5 8",key:"12lg5p"}],["path",{d:"M6 10V8",key:"1y41hn"}],["path",{d:"M6 14v1",key:"cao2tf"}],["path",{d:"M6 19v2",key:"1loha6"}],["rect",{x:"2",y:"8",width:"20",height:"13",rx:"2",key:"p3bz5l"}]]);/** * @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 jce=te("Tickets",[["path",{d:"m4.5 8 10.58-5.06a1 1 0 0 1 1.342.488L18.5 8",key:"12lg5p"}],["path",{d:"M6 10V8",key:"1y41hn"}],["path",{d:"M6 14v1",key:"cao2tf"}],["path",{d:"M6 19v2",key:"1loha6"}],["rect",{x:"2",y:"8",width:"20",height:"13",rx:"2",key:"p3bz5l"}]]);/** * @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 Nce=te("TimerOff",[["path",{d:"M10 2h4",key:"n1abiw"}],["path",{d:"M4.6 11a8 8 0 0 0 1.7 8.7 8 8 0 0 0 8.7 1.7",key:"10he05"}],["path",{d:"M7.4 7.4a8 8 0 0 1 10.3 1 8 8 0 0 1 .9 10.2",key:"15f7sh"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M12 12v-2",key:"fwoke6"}]]);/** * @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 kce=te("TimerReset",[["path",{d:"M10 2h4",key:"n1abiw"}],["path",{d:"M12 14v-4",key:"1evpnu"}],["path",{d:"M4 13a8 8 0 0 1 8-7 8 8 0 1 1-5.3 14L4 17.6",key:"1ts96g"}],["path",{d:"M9 17H4v5",key:"8t5av"}]]);/** * @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 Sce=te("Timer",[["line",{x1:"10",x2:"14",y1:"2",y2:"2",key:"14vaq8"}],["line",{x1:"12",x2:"15",y1:"14",y2:"11",key:"17fdiu"}],["circle",{cx:"12",cy:"14",r:"8",key:"1e1u0o"}]]);/** * @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 Cce=te("ToggleLeft",[["rect",{width:"20",height:"12",x:"2",y:"6",rx:"6",ry:"6",key:"f2vt7d"}],["circle",{cx:"8",cy:"12",r:"2",key:"1nvbw3"}]]);/** * @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 Tce=te("ToggleRight",[["rect",{width:"20",height:"12",x:"2",y:"6",rx:"6",ry:"6",key:"f2vt7d"}],["circle",{cx:"16",cy:"12",r:"2",key:"4ma0v8"}]]);/** * @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 Ece=te("Toilet",[["path",{d:"M7 12h13a1 1 0 0 1 1 1 5 5 0 0 1-5 5h-.598a.5.5 0 0 0-.424.765l1.544 2.47a.5.5 0 0 1-.424.765H5.402a.5.5 0 0 1-.424-.765L7 18",key:"kc4kqr"}],["path",{d:"M8 18a5 5 0 0 1-5-5V4a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v8",key:"1tqs57"}]]);/** * @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 Ace=te("Tornado",[["path",{d:"M21 4H3",key:"1hwok0"}],["path",{d:"M18 8H6",key:"41n648"}],["path",{d:"M19 12H9",key:"1g4lpz"}],["path",{d:"M16 16h-6",key:"1j5d54"}],["path",{d:"M11 20H9",key:"39obr8"}]]);/** * @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 Mce=te("Torus",[["ellipse",{cx:"12",cy:"11",rx:"3",ry:"2",key:"1b2qxu"}],["ellipse",{cx:"12",cy:"12.5",rx:"10",ry:"8.5",key:"h8emeu"}]]);/** * @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 Ice=te("TouchpadOff",[["path",{d:"M4 4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h16",key:"lnt0bk"}],["path",{d:"M2 14h12",key:"d8icqz"}],["path",{d:"M22 14h-2",key:"jrx26d"}],["path",{d:"M12 20v-6",key:"1rm09r"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M22 16V6a2 2 0 0 0-2-2H10",key:"11y8e4"}]]);/** * @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 Pce=te("Touchpad",[["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}],["path",{d:"M2 14h20",key:"myj16y"}],["path",{d:"M12 20v-6",key:"1rm09r"}]]);/** * @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 Lce=te("TowerControl",[["path",{d:"M18.2 12.27 20 6H4l1.8 6.27a1 1 0 0 0 .95.73h10.5a1 1 0 0 0 .96-.73Z",key:"1pledb"}],["path",{d:"M8 13v9",key:"hmv0ci"}],["path",{d:"M16 22v-9",key:"ylnf1u"}],["path",{d:"m9 6 1 7",key:"dpdgam"}],["path",{d:"m15 6-1 7",key:"ls7zgu"}],["path",{d:"M12 6V2",key:"1pj48d"}],["path",{d:"M13 2h-2",key:"mj6ths"}]]);/** * @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 Dce=te("ToyBrick",[["rect",{width:"18",height:"12",x:"3",y:"8",rx:"1",key:"158fvp"}],["path",{d:"M10 8V5c0-.6-.4-1-1-1H6a1 1 0 0 0-1 1v3",key:"s0042v"}],["path",{d:"M19 8V5c0-.6-.4-1-1-1h-3a1 1 0 0 0-1 1v3",key:"9wmeh2"}]]);/** * @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 Rce=te("Tractor",[["path",{d:"m10 11 11 .9a1 1 0 0 1 .8 1.1l-.665 4.158a1 1 0 0 1-.988.842H20",key:"she1j9"}],["path",{d:"M16 18h-5",key:"bq60fd"}],["path",{d:"M18 5a1 1 0 0 0-1 1v5.573",key:"1kv8ia"}],["path",{d:"M3 4h8.129a1 1 0 0 1 .99.863L13 11.246",key:"1q1ert"}],["path",{d:"M4 11V4",key:"9ft8pt"}],["path",{d:"M7 15h.01",key:"k5ht0j"}],["path",{d:"M8 10.1V4",key:"1jgyzo"}],["circle",{cx:"18",cy:"18",r:"2",key:"1emm8v"}],["circle",{cx:"7",cy:"15",r:"5",key:"ddtuc"}]]);/** * @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 Oce=te("TrafficCone",[["path",{d:"M9.3 6.2a4.55 4.55 0 0 0 5.4 0",key:"flyxqv"}],["path",{d:"M7.9 10.7c.9.8 2.4 1.3 4.1 1.3s3.2-.5 4.1-1.3",key:"1nlxxg"}],["path",{d:"M13.9 3.5a1.93 1.93 0 0 0-3.8-.1l-3 10c-.1.2-.1.4-.1.6 0 1.7 2.2 3 5 3s5-1.3 5-3c0-.2 0-.4-.1-.5Z",key:"vz7x1l"}],["path",{d:"m7.5 12.2-4.7 2.7c-.5.3-.8.7-.8 1.1s.3.8.8 1.1l7.6 4.5c.9.5 2.1.5 3 0l7.6-4.5c.7-.3 1-.7 1-1.1s-.3-.8-.8-1.1l-4.7-2.8",key:"1xfzlw"}]]);/** * @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 Fce=te("TrainFrontTunnel",[["path",{d:"M2 22V12a10 10 0 1 1 20 0v10",key:"o0fyp0"}],["path",{d:"M15 6.8v1.4a3 2.8 0 1 1-6 0V6.8",key:"m8q3n9"}],["path",{d:"M10 15h.01",key:"44in9x"}],["path",{d:"M14 15h.01",key:"5mohn5"}],["path",{d:"M10 19a4 4 0 0 1-4-4v-3a6 6 0 1 1 12 0v3a4 4 0 0 1-4 4Z",key:"hckbmu"}],["path",{d:"m9 19-2 3",key:"iij7hm"}],["path",{d:"m15 19 2 3",key:"npx8sa"}]]);/** * @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 Bce=te("TrainFront",[["path",{d:"M8 3.1V7a4 4 0 0 0 8 0V3.1",key:"1v71zp"}],["path",{d:"m9 15-1-1",key:"1yrq24"}],["path",{d:"m15 15 1-1",key:"1t0d6s"}],["path",{d:"M9 19c-2.8 0-5-2.2-5-5v-4a8 8 0 0 1 16 0v4c0 2.8-2.2 5-5 5Z",key:"1p0hjs"}],["path",{d:"m8 19-2 3",key:"13i0xs"}],["path",{d:"m16 19 2 3",key:"xo31yx"}]]);/** * @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 zce=te("TrainTrack",[["path",{d:"M2 17 17 2",key:"18b09t"}],["path",{d:"m2 14 8 8",key:"1gv9hu"}],["path",{d:"m5 11 8 8",key:"189pqp"}],["path",{d:"m8 8 8 8",key:"1imecy"}],["path",{d:"m11 5 8 8",key:"ummqn6"}],["path",{d:"m14 2 8 8",key:"1vk7dn"}],["path",{d:"M7 22 22 7",key:"15mb1i"}]]);/** * @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 iT=te("TramFront",[["rect",{width:"16",height:"16",x:"4",y:"3",rx:"2",key:"1wxw4b"}],["path",{d:"M4 11h16",key:"mpoxn0"}],["path",{d:"M12 3v8",key:"1h2ygw"}],["path",{d:"m8 19-2 3",key:"13i0xs"}],["path",{d:"m18 22-2-3",key:"1p0ohu"}],["path",{d:"M8 15h.01",key:"a7atzg"}],["path",{d:"M16 15h.01",key:"rnfrdf"}]]);/** * @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 Dr=te("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 $ce=te("Trash",[["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"}]]);/** * @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 Uce=te("TreeDeciduous",[["path",{d:"M8 19a4 4 0 0 1-2.24-7.32A3.5 3.5 0 0 1 9 6.03V6a3 3 0 1 1 6 0v.04a3.5 3.5 0 0 1 3.24 5.65A4 4 0 0 1 16 19Z",key:"oadzkq"}],["path",{d:"M12 19v3",key:"npa21l"}]]);/** * @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 oT=te("TreePalm",[["path",{d:"M13 8c0-2.76-2.46-5-5.5-5S2 5.24 2 8h2l1-1 1 1h4",key:"foxbe7"}],["path",{d:"M13 7.14A5.82 5.82 0 0 1 16.5 6c3.04 0 5.5 2.24 5.5 5h-3l-1-1-1 1h-3",key:"18arnh"}],["path",{d:"M5.89 9.71c-2.15 2.15-2.3 5.47-.35 7.43l4.24-4.25.7-.7.71-.71 2.12-2.12c-1.95-1.96-5.27-1.8-7.42.35",key:"ywahnh"}],["path",{d:"M11 15.5c.5 2.5-.17 4.5-1 6.5h4c2-5.5-.5-12-1-14",key:"ft0feo"}]]);/** * @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 Zk=te("TreePine",[["path",{d:"m17 14 3 3.3a1 1 0 0 1-.7 1.7H4.7a1 1 0 0 1-.7-1.7L7 14h-.3a1 1 0 0 1-.7-1.7L9 9h-.2A1 1 0 0 1 8 7.3L12 3l4 4.3a1 1 0 0 1-.8 1.7H15l3 3.3a1 1 0 0 1-.7 1.7H17Z",key:"cpyugq"}],["path",{d:"M12 22v-3",key:"kmzjlo"}]]);/** * @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 qce=te("Trees",[["path",{d:"M10 10v.2A3 3 0 0 1 8.9 16H5a3 3 0 0 1-1-5.8V10a3 3 0 0 1 6 0Z",key:"1l6gj6"}],["path",{d:"M7 16v6",key:"1a82de"}],["path",{d:"M13 19v3",key:"13sx9i"}],["path",{d:"M12 19h8.3a1 1 0 0 0 .7-1.7L18 14h.3a1 1 0 0 0 .7-1.7L16 9h.2a1 1 0 0 0 .8-1.7L13 3l-1.4 1.5",key:"1sj9kv"}]]);/** * @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 Vce=te("Trello",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["rect",{width:"3",height:"9",x:"7",y:"7",key:"14n3xi"}],["rect",{width:"3",height:"5",x:"14",y:"7",key:"s4azjd"}]]);/** * @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=te("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 Hce=te("TrendingUpDown",[["path",{d:"M14.828 14.828 21 21",key:"ar5fw7"}],["path",{d:"M21 16v5h-5",key:"1ck2sf"}],["path",{d:"m21 3-9 9-4-4-6 6",key:"1h02xo"}],["path",{d:"M21 8V3h-5",key:"1qoq8a"}]]);/** * @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 al=te("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 uu=te("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 Gce=te("TriangleRight",[["path",{d:"M22 18a2 2 0 0 1-2 2H3c-1.1 0-1.3-.6-.4-1.3L20.4 4.3c.9-.7 1.6-.4 1.6.7Z",key:"183wce"}]]);/** * @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 Wce=te("Triangle",[["path",{d:"M13.73 4a2 2 0 0 0-3.46 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3Z",key:"14u9p9"}]]);/** * @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 To=te("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 OF=te("Truck",[["path",{d:"M14 18V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v11a1 1 0 0 0 1 1h2",key:"wrbu53"}],["path",{d:"M15 18H9",key:"1lyqi6"}],["path",{d:"M19 18h2a1 1 0 0 0 1-1v-3.65a1 1 0 0 0-.22-.624l-3.48-4.35A1 1 0 0 0 17.52 8H14",key:"lysw3i"}],["circle",{cx:"17",cy:"18",r:"2",key:"332jqn"}],["circle",{cx:"7",cy:"18",r:"2",key:"19iecd"}]]);/** * @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 Kce=te("Turtle",[["path",{d:"m12 10 2 4v3a1 1 0 0 0 1 1h2a1 1 0 0 0 1-1v-3a8 8 0 1 0-16 0v3a1 1 0 0 0 1 1h2a1 1 0 0 0 1-1v-3l2-4h4Z",key:"1lbbv7"}],["path",{d:"M4.82 7.9 8 10",key:"m9wose"}],["path",{d:"M15.18 7.9 12 10",key:"p8dp2u"}],["path",{d:"M16.93 10H20a2 2 0 0 1 0 4H2",key:"12nsm7"}]]);/** * @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 Yce=te("TvMinimalPlay",[["path",{d:"M10 7.75a.75.75 0 0 1 1.142-.638l3.664 2.249a.75.75 0 0 1 0 1.278l-3.664 2.25a.75.75 0 0 1-1.142-.64z",key:"1pctta"}],["path",{d:"M7 21h10",key:"1b0cd5"}],["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2",key:"48i651"}]]);/** * @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 lT=te("TvMinimal",[["path",{d:"M7 21h10",key:"1b0cd5"}],["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2",key:"48i651"}]]);/** * @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 Zce=te("Tv",[["rect",{width:"20",height:"15",x:"2",y:"7",rx:"2",ry:"2",key:"10ag99"}],["polyline",{points:"17 2 12 7 7 2",key:"11pgbg"}]]);/** * @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 Xce=te("Twitch",[["path",{d:"M21 2H3v16h5v4l4-4h5l4-4V2zm-10 9V7m5 4V7",key:"c0yzno"}]]);/** * @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 Qce=te("Twitter",[["path",{d:"M22 4s-.7 2.1-2 3.4c1.6 10-9.4 17.3-18 11.6 2.2.1 4.4-.6 6-2C3 15.5.5 9.6 3 5c2.2 2.6 5.6 4.1 9 4-.9-4.2 4-6.6 7-3.8 1.1 0 3-1.2 3-1.2z",key:"pff0z6"}]]);/** * @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 Jce=te("TypeOutline",[["path",{d:"M14 16.5a.5.5 0 0 0 .5.5h.5a2 2 0 0 1 0 4H9a2 2 0 0 1 0-4h.5a.5.5 0 0 0 .5-.5v-9a.5.5 0 0 0-.5-.5h-3a.5.5 0 0 0-.5.5V8a2 2 0 0 1-4 0V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v3a2 2 0 0 1-4 0v-.5a.5.5 0 0 0-.5-.5h-3a.5.5 0 0 0-.5.5Z",key:"1reda3"}]]);/** * @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 ede=te("Type",[["polyline",{points:"4 7 4 4 20 4 20 7",key:"1nosan"}],["line",{x1:"9",x2:"15",y1:"20",y2:"20",key:"swin9y"}],["line",{x1:"12",x2:"12",y1:"4",y2:"20",key:"1tx1rr"}]]);/** * @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 tde=te("UmbrellaOff",[["path",{d:"M12 2v1",key:"11qlp1"}],["path",{d:"M15.5 21a1.85 1.85 0 0 1-3.5-1v-8H2a10 10 0 0 1 3.428-6.575",key:"eki10q"}],["path",{d:"M17.5 12H22A10 10 0 0 0 9.004 3.455",key:"n2ayka"}],["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 sde=te("Umbrella",[["path",{d:"M22 12a10.06 10.06 1 0 0-20 0Z",key:"1teyop"}],["path",{d:"M12 12v8a2 2 0 0 0 4 0",key:"ulpmoc"}],["path",{d:"M12 2v1",key:"11qlp1"}]]);/** * @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 XI=te("Underline",[["path",{d:"M6 4v6a6 6 0 0 0 12 0V4",key:"9kb039"}],["line",{x1:"4",x2:"20",y1:"20",y2:"20",key:"nun2al"}]]);/** * @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 rde=te("Undo2",[["path",{d:"M9 14 4 9l5-5",key:"102s5s"}],["path",{d:"M4 9h10.5a5.5 5.5 0 0 1 5.5 5.5a5.5 5.5 0 0 1-5.5 5.5H11",key:"f3b9sd"}]]);/** * @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 nde=te("UndoDot",[["path",{d:"M21 17a9 9 0 0 0-15-6.7L3 13",key:"8mp6z9"}],["path",{d:"M3 7v6h6",key:"1v2h90"}],["circle",{cx:"12",cy:"17",r:"1",key:"1ixnty"}]]);/** * @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 Xk=te("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 ade=te("UnfoldHorizontal",[["path",{d:"M16 12h6",key:"15xry1"}],["path",{d:"M8 12H2",key:"1jqql6"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 8v2",key:"1woqiv"}],["path",{d:"M12 14v2",key:"8jcxud"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"m19 15 3-3-3-3",key:"wjy7rq"}],["path",{d:"m5 9-3 3 3 3",key:"j64kie"}]]);/** * @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 ide=te("UnfoldVertical",[["path",{d:"M12 22v-6",key:"6o8u61"}],["path",{d:"M12 8V2",key:"1wkif3"}],["path",{d:"M4 12H2",key:"rhcxmi"}],["path",{d:"M10 12H8",key:"s88cx1"}],["path",{d:"M16 12h-2",key:"10asgb"}],["path",{d:"M22 12h-2",key:"14jgyd"}],["path",{d:"m15 19-3 3-3-3",key:"11eu04"}],["path",{d:"m15 5-3-3-3 3",key:"itvq4r"}]]);/** * @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 ode=te("Ungroup",[["rect",{width:"8",height:"6",x:"5",y:"4",rx:"1",key:"nzclkv"}],["rect",{width:"8",height:"6",x:"11",y:"14",rx:"1",key:"4tytwb"}]]);/** * @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 cT=te("University",[["circle",{cx:"12",cy:"10",r:"1",key:"1gnqs8"}],["path",{d:"M22 20V8h-4l-6-4-6 4H2v12a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2",key:"1qj5sn"}],["path",{d:"M6 17v.01",key:"roodi6"}],["path",{d:"M6 13v.01",key:"67c122"}],["path",{d:"M18 17v.01",key:"12ktxm"}],["path",{d:"M18 13v.01",key:"tn1rt1"}],["path",{d:"M14 22v-5a2 2 0 0 0-2-2a2 2 0 0 0-2 2v5",key:"11g7fi"}]]);/** * @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 lde=te("Unlink2",[["path",{d:"M15 7h2a5 5 0 0 1 0 10h-2m-6 0H7A5 5 0 0 1 7 7h2",key:"1re2ne"}]]);/** * @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 BE=te("Unlink",[["path",{d:"m18.84 12.25 1.72-1.71h-.02a5.004 5.004 0 0 0-.12-7.07 5.006 5.006 0 0 0-6.95 0l-1.72 1.71",key:"yqzxt4"}],["path",{d:"m5.17 11.75-1.71 1.71a5.004 5.004 0 0 0 .12 7.07 5.006 5.006 0 0 0 6.95 0l1.71-1.71",key:"4qinb0"}],["line",{x1:"8",x2:"8",y1:"2",y2:"5",key:"1041cp"}],["line",{x1:"2",x2:"5",y1:"8",y2:"8",key:"14m1p5"}],["line",{x1:"16",x2:"16",y1:"19",y2:"22",key:"rzdirn"}],["line",{x1:"19",x2:"22",y1:"16",y2:"16",key:"ox905f"}]]);/** * @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 cde=te("Unplug",[["path",{d:"m19 5 3-3",key:"yk6iyv"}],["path",{d:"m2 22 3-3",key:"19mgm9"}],["path",{d:"M6.3 20.3a2.4 2.4 0 0 0 3.4 0L12 18l-6-6-2.3 2.3a2.4 2.4 0 0 0 0 3.4Z",key:"goz73y"}],["path",{d:"M7.5 13.5 10 11",key:"7xgeeb"}],["path",{d:"M10.5 16.5 13 14",key:"10btkg"}],["path",{d:"m12 6 6 6 2.3-2.3a2.4 2.4 0 0 0 0-3.4l-2.6-2.6a2.4 2.4 0 0 0-3.4 0Z",key:"1snsnr"}]]);/** * @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 Ea=te("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 dde=te("Usb",[["circle",{cx:"10",cy:"7",r:"1",key:"dypaad"}],["circle",{cx:"4",cy:"20",r:"1",key:"22iqad"}],["path",{d:"M4.7 19.3 19 5",key:"1enqfc"}],["path",{d:"m21 3-3 1 2 2Z",key:"d3ov82"}],["path",{d:"M9.26 7.68 5 12l2 5",key:"1esawj"}],["path",{d:"m10 14 5 2 3.5-3.5",key:"v8oal5"}],["path",{d:"m18 12 1-1 1 1-1 1Z",key:"1bh22v"}]]);/** * @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 j1=te("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 FF=te("UserCog",[["circle",{cx:"18",cy:"15",r:"3",key:"gjjjvw"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["path",{d:"M10 15H6a4 4 0 0 0-4 4v2",key:"1nfge6"}],["path",{d:"m21.7 16.4-.9-.3",key:"12j9ji"}],["path",{d:"m15.2 13.9-.9-.3",key:"1fdjdi"}],["path",{d:"m16.6 18.7.3-.9",key:"heedtr"}],["path",{d:"m19.1 12.2.3-.9",key:"1af3ki"}],["path",{d:"m19.6 18.7-.4-1",key:"1x9vze"}],["path",{d:"m16.8 12.3-.4-1",key:"vqeiwj"}],["path",{d:"m14.3 16.6 1-.4",key:"1qlj63"}],["path",{d:"m20.7 13.8 1-.4",key:"1v5t8k"}]]);/** * @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=te("UserMinus",[["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:"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 ude=te("UserPen",[["path",{d:"M11.5 15H7a4 4 0 0 0-4 4v2",key:"15lzij"}],["path",{d:"M21.378 16.626a1 1 0 0 0-3.004-3.004l-4.01 4.012a2 2 0 0 0-.506.854l-.837 2.87a.5.5 0 0 0 .62.62l2.87-.837a2 2 0 0 0 .854-.506z",key:"1817ys"}],["circle",{cx:"10",cy:"7",r:"4",key:"e45bow"}]]);/** * @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 Vl=te("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 dT=te("UserRoundCheck",[["path",{d:"M2 21a8 8 0 0 1 13.292-6",key:"bjp14o"}],["circle",{cx:"10",cy:"8",r:"5",key:"o932ke"}],["path",{d:"m16 19 2 2 4-4",key:"1b14m6"}]]);/** * @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 uT=te("UserRoundCog",[["path",{d:"M2 21a8 8 0 0 1 10.434-7.62",key:"1yezr2"}],["circle",{cx:"10",cy:"8",r:"5",key:"o932ke"}],["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}],["path",{d:"m19.5 14.3-.4.9",key:"1eb35c"}],["path",{d:"m16.9 20.8-.4.9",key:"dfjc4z"}],["path",{d:"m21.7 19.5-.9-.4",key:"q4dx6b"}],["path",{d:"m15.2 16.9-.9-.4",key:"1r0w5f"}],["path",{d:"m21.7 16.5-.9.4",key:"1knoei"}],["path",{d:"m15.2 19.1-.9.4",key:"j188fs"}],["path",{d:"m19.5 21.7-.4-.9",key:"1tonu5"}],["path",{d:"m16.9 15.2-.4-.9",key:"699xu"}]]);/** * @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 hT=te("UserRoundMinus",[["path",{d:"M2 21a8 8 0 0 1 13.292-6",key:"bjp14o"}],["circle",{cx:"10",cy:"8",r:"5",key:"o932ke"}],["path",{d:"M22 19h-6",key:"vcuq98"}]]);/** * @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 hde=te("UserRoundPen",[["path",{d:"M2 21a8 8 0 0 1 10.821-7.487",key:"1c8h7z"}],["path",{d:"M21.378 16.626a1 1 0 0 0-3.004-3.004l-4.01 4.012a2 2 0 0 0-.506.854l-.837 2.87a.5.5 0 0 0 .62.62l2.87-.837a2 2 0 0 0 .854-.506z",key:"1817ys"}],["circle",{cx:"10",cy:"8",r:"5",key:"o932ke"}]]);/** * @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=te("UserRoundPlus",[["path",{d:"M2 21a8 8 0 0 1 13.292-6",key:"bjp14o"}],["circle",{cx:"10",cy:"8",r:"5",key:"o932ke"}],["path",{d:"M19 16v6",key:"tddt3s"}],["path",{d:"M22 19h-6",key:"vcuq98"}]]);/** * @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 mde=te("UserRoundSearch",[["circle",{cx:"10",cy:"8",r:"5",key:"o932ke"}],["path",{d:"M2 21a8 8 0 0 1 10.434-7.62",key:"1yezr2"}],["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}],["path",{d:"m22 22-1.9-1.9",key:"1e5ubv"}]]);/** * @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 fT=te("UserRoundX",[["path",{d:"M2 21a8 8 0 0 1 11.873-7",key:"74fkxq"}],["circle",{cx:"10",cy:"8",r:"5",key:"o932ke"}],["path",{d:"m17 17 5 5",key:"p7ous7"}],["path",{d:"m22 17-5 5",key:"gqnmv0"}]]);/** * @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=te("UserRound",[["circle",{cx:"12",cy:"8",r:"5",key:"1hypcn"}],["path",{d:"M20 21a8 8 0 0 0-16 0",key:"rfgkzh"}]]);/** * @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 fde=te("UserSearch",[["circle",{cx:"10",cy:"7",r:"4",key:"e45bow"}],["path",{d:"M10.3 15H7a4 4 0 0 0-4 4v2",key:"3bnktk"}],["circle",{cx:"17",cy:"17",r:"3",key:"18b49y"}],["path",{d:"m21 21-1.9-1.9",key:"1g2n9r"}]]);/** * @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 pde=te("UserX",[["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:"17",x2:"22",y1:"8",y2:"13",key:"3nzzx3"}],["line",{x1:"22",x2:"17",y1:"8",y2:"13",key:"1swrse"}]]);/** * @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=te("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 gT=te("UsersRound",[["path",{d:"M18 21a8 8 0 0 0-16 0",key:"3ypg7q"}],["circle",{cx:"10",cy:"8",r:"5",key:"o932ke"}],["path",{d:"M22 20c0-3.37-2-6.5-4-8a5 5 0 0 0-.45-8.3",key:"10s06x"}]]);/** * @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 Ar=te("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 xT=te("UtensilsCrossed",[["path",{d:"m16 2-2.3 2.3a3 3 0 0 0 0 4.2l1.8 1.8a3 3 0 0 0 4.2 0L22 8",key:"n7qcjb"}],["path",{d:"M15 15 3.3 3.3a4.2 4.2 0 0 0 0 6l7.3 7.3c.7.7 2 .7 2.8 0L15 15Zm0 0 7 7",key:"d0u48b"}],["path",{d:"m2.1 21.8 6.4-6.3",key:"yn04lh"}],["path",{d:"m19 5-7 7",key:"194lzd"}]]);/** * @license lucide-react v0.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=te("Utensils",[["path",{d:"M3 2v7c0 1.1.9 2 2 2h4a2 2 0 0 0 2-2V2",key:"cjf0a3"}],["path",{d:"M7 2v20",key:"1473qp"}],["path",{d:"M21 15V2a5 5 0 0 0-5 5v6c0 1.1.9 2 2 2h3Zm0 0v7",key:"j28e5"}]]);/** * @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 gde=te("UtilityPole",[["path",{d:"M12 2v20",key:"t6zp3m"}],["path",{d:"M2 5h20",key:"1fs1ex"}],["path",{d:"M3 3v2",key:"9imdir"}],["path",{d:"M7 3v2",key:"n0os7"}],["path",{d:"M17 3v2",key:"1l2re6"}],["path",{d:"M21 3v2",key:"1duuac"}],["path",{d:"m19 5-7 7-7-7",key:"133zxf"}]]);/** * @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 QI=te("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 xde=te("Vault",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["circle",{cx:"7.5",cy:"7.5",r:".5",fill:"currentColor",key:"kqv944"}],["path",{d:"m7.9 7.9 2.7 2.7",key:"hpeyl3"}],["circle",{cx:"16.5",cy:"7.5",r:".5",fill:"currentColor",key:"w0ekpg"}],["path",{d:"m13.4 10.6 2.7-2.7",key:"264c1n"}],["circle",{cx:"7.5",cy:"16.5",r:".5",fill:"currentColor",key:"nkw3mc"}],["path",{d:"m7.9 16.1 2.7-2.7",key:"p81g5e"}],["circle",{cx:"16.5",cy:"16.5",r:".5",fill:"currentColor",key:"fubopw"}],["path",{d:"m13.4 13.4 2.7 2.7",key:"abhel3"}],["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 yde=te("Vegan",[["path",{d:"M16 8q6 0 6-6-6 0-6 6",key:"qsyyc4"}],["path",{d:"M17.41 3.59a10 10 0 1 0 3 3",key:"41m9h7"}],["path",{d:"M2 2a26.6 26.6 0 0 1 10 20c.9-6.82 1.5-9.5 4-14",key:"qiv7li"}]]);/** * @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 vde=te("VenetianMask",[["path",{d:"M18 11c-1.5 0-2.5.5-3 2",key:"1fod00"}],["path",{d:"M4 6a2 2 0 0 0-2 2v4a5 5 0 0 0 5 5 8 8 0 0 1 5 2 8 8 0 0 1 5-2 5 5 0 0 0 5-5V8a2 2 0 0 0-2-2h-3a8 8 0 0 0-5 2 8 8 0 0 0-5-2z",key:"d70hit"}],["path",{d:"M6 11c1.5 0 2.5.5 3 2",key:"136fht"}]]);/** * @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 bde=te("VibrateOff",[["path",{d:"m2 8 2 2-2 2 2 2-2 2",key:"sv1b1"}],["path",{d:"m22 8-2 2 2 2-2 2 2 2",key:"101i4y"}],["path",{d:"M8 8v10c0 .55.45 1 1 1h6c.55 0 1-.45 1-1v-2",key:"1hbad5"}],["path",{d:"M16 10.34V6c0-.55-.45-1-1-1h-4.34",key:"1x5tf0"}],["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}]]);/** * @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 _de=te("Vibrate",[["path",{d:"m2 8 2 2-2 2 2 2-2 2",key:"sv1b1"}],["path",{d:"m22 8-2 2 2 2-2 2 2 2",key:"101i4y"}],["rect",{width:"8",height:"14",x:"8",y:"5",rx:"1",key:"1oyrl4"}]]);/** * @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 wde=te("VideoOff",[["path",{d:"M10.66 6H14a2 2 0 0 1 2 2v2.5l5.248-3.062A.5.5 0 0 1 22 7.87v8.196",key:"w8jjjt"}],["path",{d:"M16 16a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h2",key:"1xawa7"}],["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 xn=te("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 jde=te("Videotape",[["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}],["path",{d:"M2 8h20",key:"d11cs7"}],["circle",{cx:"8",cy:"14",r:"2",key:"1k2qr5"}],["path",{d:"M8 12h8",key:"1wcyev"}],["circle",{cx:"16",cy:"14",r:"2",key:"14k7lr"}]]);/** * @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 Nde=te("View",[["path",{d:"M21 17v2a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-2",key:"mrq65r"}],["path",{d:"M21 7V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v2",key:"be3xqs"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["path",{d:"M18.944 12.33a1 1 0 0 0 0-.66 7.5 7.5 0 0 0-13.888 0 1 1 0 0 0 0 .66 7.5 7.5 0 0 0 13.888 0",key:"11ak4c"}]]);/** * @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 kde=te("Voicemail",[["circle",{cx:"6",cy:"12",r:"4",key:"1ehtga"}],["circle",{cx:"18",cy:"12",r:"4",key:"4vafl8"}],["line",{x1:"6",x2:"18",y1:"16",y2:"16",key:"pmt8us"}]]);/** * @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 Sde=te("Volleyball",[["path",{d:"M11.1 7.1a16.55 16.55 0 0 1 10.9 4",key:"2880wi"}],["path",{d:"M12 12a12.6 12.6 0 0 1-8.7 5",key:"113sja"}],["path",{d:"M16.8 13.6a16.55 16.55 0 0 1-9 7.5",key:"1qmsgl"}],["path",{d:"M20.7 17a12.8 12.8 0 0 0-8.7-5 13.3 13.3 0 0 1 0-10",key:"1bmeqp"}],["path",{d:"M6.3 3.8a16.55 16.55 0 0 0 1.9 11.5",key:"iekzv9"}],["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 Cde=te("Volume1",[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z",key:"uqj9uw"}],["path",{d:"M16 9a5 5 0 0 1 0 6",key:"1q6k2b"}]]);/** * @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 zF=te("Volume2",[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z",key:"uqj9uw"}],["path",{d:"M16 9a5 5 0 0 1 0 6",key:"1q6k2b"}],["path",{d:"M19.364 18.364a9 9 0 0 0 0-12.728",key:"ijwkga"}]]);/** * @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 Tde=te("VolumeOff",[["path",{d:"M16 9a5 5 0 0 1 .95 2.293",key:"1fgyg8"}],["path",{d:"M19.364 5.636a9 9 0 0 1 1.889 9.96",key:"l3zxae"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"m7 7-.587.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298V11",key:"1gbwow"}],["path",{d:"M9.828 4.172A.686.686 0 0 1 11 4.657v.686",key:"s2je0y"}]]);/** * @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 $F=te("VolumeX",[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z",key:"uqj9uw"}],["line",{x1:"22",x2:"16",y1:"9",y2:"15",key:"1ewh16"}],["line",{x1:"16",x2:"22",y1:"9",y2:"15",key:"5ykzw1"}]]);/** * @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 Ede=te("Volume",[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z",key:"uqj9uw"}]]);/** * @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 Ade=te("Vote",[["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}],["path",{d:"M5 7c0-1.1.9-2 2-2h10a2 2 0 0 1 2 2v12H5V7Z",key:"1ezoue"}],["path",{d:"M22 19H2",key:"nuriw5"}]]);/** * @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 Mde=te("WalletCards",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 9a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2",key:"4125el"}],["path",{d:"M3 11h3c.8 0 1.6.3 2.1.9l1.1.9c1.6 1.6 4.1 1.6 5.7 0l1.1-.9c.5-.5 1.3-.9 2.1-.9H21",key:"1dpki6"}]]);/** * @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 vT=te("WalletMinimal",[["path",{d:"M17 14h.01",key:"7oqj8z"}],["path",{d:"M7 7h12a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h14",key:"u1rqew"}]]);/** * @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 UF=te("Wallet",[["path",{d:"M19 7V4a1 1 0 0 0-1-1H5a2 2 0 0 0 0 4h15a1 1 0 0 1 1 1v4h-3a2 2 0 0 0 0 4h3a1 1 0 0 0 1-1v-2a1 1 0 0 0-1-1",key:"18etb6"}],["path",{d:"M3 5v14a2 2 0 0 0 2 2h15a1 1 0 0 0 1-1v-4",key:"xoc0q4"}]]);/** * @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 Ide=te("Wallpaper",[["circle",{cx:"8",cy:"9",r:"2",key:"gjzl9d"}],["path",{d:"m9 17 6.1-6.1a2 2 0 0 1 2.81.01L22 15V5a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2",key:"69xh40"}],["path",{d:"M8 21h8",key:"1ev6f3"}],["path",{d:"M12 17v4",key:"1riwvh"}]]);/** * @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 My=te("WandSparkles",[["path",{d:"m21.64 3.64-1.28-1.28a1.21 1.21 0 0 0-1.72 0L2.36 18.64a1.21 1.21 0 0 0 0 1.72l1.28 1.28a1.2 1.2 0 0 0 1.72 0L21.64 5.36a1.2 1.2 0 0 0 0-1.72",key:"ul74o6"}],["path",{d:"m14 7 3 3",key:"1r5n42"}],["path",{d:"M5 6v4",key:"ilb8ba"}],["path",{d:"M19 14v4",key:"blhpug"}],["path",{d:"M10 2v2",key:"7u0qdc"}],["path",{d:"M7 8H3",key:"zfb6yr"}],["path",{d:"M21 16h-4",key:"1cnmox"}],["path",{d:"M11 3H9",key:"1obp7u"}]]);/** * @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 Pde=te("Wand",[["path",{d:"M15 4V2",key:"z1p9b7"}],["path",{d:"M15 16v-2",key:"px0unx"}],["path",{d:"M8 9h2",key:"1g203m"}],["path",{d:"M20 9h2",key:"19tzq7"}],["path",{d:"M17.8 11.8 19 13",key:"yihg8r"}],["path",{d:"M15 9h.01",key:"x1ddxp"}],["path",{d:"M17.8 6.2 19 5",key:"fd4us0"}],["path",{d:"m3 21 9-9",key:"1jfql5"}],["path",{d:"M12.2 6.2 11 5",key:"i3da3b"}]]);/** * @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 Lde=te("Warehouse",[["path",{d:"M22 8.35V20a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V8.35A2 2 0 0 1 3.26 6.5l8-3.2a2 2 0 0 1 1.48 0l8 3.2A2 2 0 0 1 22 8.35Z",key:"gksnxg"}],["path",{d:"M6 18h12",key:"9pbo8z"}],["path",{d:"M6 14h12",key:"4cwo0f"}],["rect",{width:"12",height:"12",x:"6",y:"10",key:"apd30q"}]]);/** * @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 Dde=te("WashingMachine",[["path",{d:"M3 6h3",key:"155dbl"}],["path",{d:"M17 6h.01",key:"e2y6kg"}],["rect",{width:"18",height:"20",x:"3",y:"2",rx:"2",key:"od3kk9"}],["circle",{cx:"12",cy:"13",r:"5",key:"nlbqau"}],["path",{d:"M12 18a2.5 2.5 0 0 0 0-5 2.5 2.5 0 0 1 0-5",key:"17lach"}]]);/** * @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 Rde=te("Watch",[["circle",{cx:"12",cy:"12",r:"6",key:"1vlfrh"}],["polyline",{points:"12 10 12 12 13 13",key:"19dquz"}],["path",{d:"m16.13 7.66-.81-4.05a2 2 0 0 0-2-1.61h-2.68a2 2 0 0 0-2 1.61l-.78 4.05",key:"18k57s"}],["path",{d:"m7.88 16.36.8 4a2 2 0 0 0 2 1.61h2.72a2 2 0 0 0 2-1.61l.81-4.05",key:"16ny36"}]]);/** * @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 Ode=te("Waves",[["path",{d:"M2 6c.6.5 1.2 1 2.5 1C7 7 7 5 9.5 5c2.6 0 2.4 2 5 2 2.5 0 2.5-2 5-2 1.3 0 1.9.5 2.5 1",key:"knzxuh"}],["path",{d:"M2 12c.6.5 1.2 1 2.5 1 2.5 0 2.5-2 5-2 2.6 0 2.4 2 5 2 2.5 0 2.5-2 5-2 1.3 0 1.9.5 2.5 1",key:"2jd2cc"}],["path",{d:"M2 18c.6.5 1.2 1 2.5 1 2.5 0 2.5-2 5-2 2.6 0 2.4 2 5 2 2.5 0 2.5-2 5-2 1.3 0 1.9.5 2.5 1",key:"rd2r6e"}]]);/** * @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 Fde=te("Waypoints",[["circle",{cx:"12",cy:"4.5",r:"2.5",key:"r5ysbb"}],["path",{d:"m10.2 6.3-3.9 3.9",key:"1nzqf6"}],["circle",{cx:"4.5",cy:"12",r:"2.5",key:"jydg6v"}],["path",{d:"M7 12h10",key:"b7w52i"}],["circle",{cx:"19.5",cy:"12",r:"2.5",key:"1piiel"}],["path",{d:"m13.8 17.7 3.9-3.9",key:"1wyg1y"}],["circle",{cx:"12",cy:"19.5",r:"2.5",key:"13o1pw"}]]);/** * @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 Bde=te("Webcam",[["circle",{cx:"12",cy:"10",r:"8",key:"1gshiw"}],["circle",{cx:"12",cy:"10",r:"3",key:"ilqhr7"}],["path",{d:"M7 22h10",key:"10w4w3"}],["path",{d:"M12 22v-4",key:"1utk9m"}]]);/** * @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 zde=te("WebhookOff",[["path",{d:"M17 17h-5c-1.09-.02-1.94.92-2.5 1.9A3 3 0 1 1 2.57 15",key:"1tvl6x"}],["path",{d:"M9 3.4a4 4 0 0 1 6.52.66",key:"q04jfq"}],["path",{d:"m6 17 3.1-5.8a2.5 2.5 0 0 0 .057-2.05",key:"azowf0"}],["path",{d:"M20.3 20.3a4 4 0 0 1-2.3.7",key:"5joiws"}],["path",{d:"M18.6 13a4 4 0 0 1 3.357 3.414",key:"cangb8"}],["path",{d:"m12 6 .6 1",key:"tpjl1n"}],["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 $de=te("Webhook",[["path",{d:"M18 16.98h-5.99c-1.1 0-1.95.94-2.48 1.9A4 4 0 0 1 2 17c.01-.7.2-1.4.57-2",key:"q3hayz"}],["path",{d:"m6 17 3.13-5.78c.53-.97.1-2.18-.5-3.1a4 4 0 1 1 6.89-4.06",key:"1go1hn"}],["path",{d:"m12 6 3.13 5.73C15.66 12.7 16.9 13 18 13a4 4 0 0 1 0 8",key:"qlwsc0"}]]);/** * @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 Ude=te("Weight",[["circle",{cx:"12",cy:"5",r:"3",key:"rqqgnr"}],["path",{d:"M6.5 8a2 2 0 0 0-1.905 1.46L2.1 18.5A2 2 0 0 0 4 21h16a2 2 0 0 0 1.925-2.54L19.4 9.5A2 2 0 0 0 17.48 8Z",key:"56o5sh"}]]);/** * @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 qde=te("WheatOff",[["path",{d:"m2 22 10-10",key:"28ilpk"}],["path",{d:"m16 8-1.17 1.17",key:"1qqm82"}],["path",{d:"M3.47 12.53 5 11l1.53 1.53a3.5 3.5 0 0 1 0 4.94L5 19l-1.53-1.53a3.5 3.5 0 0 1 0-4.94Z",key:"1rdhi6"}],["path",{d:"m8 8-.53.53a3.5 3.5 0 0 0 0 4.94L9 15l1.53-1.53c.55-.55.88-1.25.98-1.97",key:"4wz8re"}],["path",{d:"M10.91 5.26c.15-.26.34-.51.56-.73L13 3l1.53 1.53a3.5 3.5 0 0 1 .28 4.62",key:"rves66"}],["path",{d:"M20 2h2v2a4 4 0 0 1-4 4h-2V6a4 4 0 0 1 4-4Z",key:"19rau1"}],["path",{d:"M11.47 17.47 13 19l-1.53 1.53a3.5 3.5 0 0 1-4.94 0L5 19l1.53-1.53a3.5 3.5 0 0 1 4.94 0Z",key:"tc8ph9"}],["path",{d:"m16 16-.53.53a3.5 3.5 0 0 1-4.94 0L9 15l1.53-1.53a3.49 3.49 0 0 1 1.97-.98",key:"ak46r"}],["path",{d:"M18.74 13.09c.26-.15.51-.34.73-.56L21 11l-1.53-1.53a3.5 3.5 0 0 0-4.62-.28",key:"1tw520"}],["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}]]);/** * @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 Vde=te("Wheat",[["path",{d:"M2 22 16 8",key:"60hf96"}],["path",{d:"M3.47 12.53 5 11l1.53 1.53a3.5 3.5 0 0 1 0 4.94L5 19l-1.53-1.53a3.5 3.5 0 0 1 0-4.94Z",key:"1rdhi6"}],["path",{d:"M7.47 8.53 9 7l1.53 1.53a3.5 3.5 0 0 1 0 4.94L9 15l-1.53-1.53a3.5 3.5 0 0 1 0-4.94Z",key:"1sdzmb"}],["path",{d:"M11.47 4.53 13 3l1.53 1.53a3.5 3.5 0 0 1 0 4.94L13 11l-1.53-1.53a3.5 3.5 0 0 1 0-4.94Z",key:"eoatbi"}],["path",{d:"M20 2h2v2a4 4 0 0 1-4 4h-2V6a4 4 0 0 1 4-4Z",key:"19rau1"}],["path",{d:"M11.47 17.47 13 19l-1.53 1.53a3.5 3.5 0 0 1-4.94 0L5 19l1.53-1.53a3.5 3.5 0 0 1 4.94 0Z",key:"tc8ph9"}],["path",{d:"M15.47 13.47 17 15l-1.53 1.53a3.5 3.5 0 0 1-4.94 0L9 15l1.53-1.53a3.5 3.5 0 0 1 4.94 0Z",key:"2m8kc5"}],["path",{d:"M19.47 9.47 21 11l-1.53 1.53a3.5 3.5 0 0 1-4.94 0L13 11l1.53-1.53a3.5 3.5 0 0 1 4.94 0Z",key:"vex3ng"}]]);/** * @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 Hde=te("WholeWord",[["circle",{cx:"7",cy:"12",r:"3",key:"12clwm"}],["path",{d:"M10 9v6",key:"17i7lo"}],["circle",{cx:"17",cy:"12",r:"3",key:"gl7c2s"}],["path",{d:"M14 7v8",key:"dl84cr"}],["path",{d:"M22 17v1c0 .5-.5 1-1 1H3c-.5 0-1-.5-1-1v-1",key:"lt2kga"}]]);/** * @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 Gde=te("WifiHigh",[["path",{d:"M12 20h.01",key:"zekei9"}],["path",{d:"M5 12.859a10 10 0 0 1 14 0",key:"1x1e6c"}],["path",{d:"M8.5 16.429a5 5 0 0 1 7 0",key:"1bycff"}]]);/** * @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 Wde=te("WifiLow",[["path",{d:"M12 20h.01",key:"zekei9"}],["path",{d:"M8.5 16.429a5 5 0 0 1 7 0",key:"1bycff"}]]);/** * @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 Kde=te("WifiOff",[["path",{d:"M12 20h.01",key:"zekei9"}],["path",{d:"M8.5 16.429a5 5 0 0 1 7 0",key:"1bycff"}],["path",{d:"M5 12.859a10 10 0 0 1 5.17-2.69",key:"1dl1wf"}],["path",{d:"M19 12.859a10 10 0 0 0-2.007-1.523",key:"4k23kn"}],["path",{d:"M2 8.82a15 15 0 0 1 4.177-2.643",key:"1grhjp"}],["path",{d:"M22 8.82a15 15 0 0 0-11.288-3.764",key:"z3jwby"}],["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 Yde=te("WifiZero",[["path",{d:"M12 20h.01",key:"zekei9"}]]);/** * @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 Zde=te("Wifi",[["path",{d:"M12 20h.01",key:"zekei9"}],["path",{d:"M2 8.82a15 15 0 0 1 20 0",key:"dnpr2z"}],["path",{d:"M5 12.859a10 10 0 0 1 14 0",key:"1x1e6c"}],["path",{d:"M8.5 16.429a5 5 0 0 1 7 0",key:"1bycff"}]]);/** * @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 Xde=te("WindArrowDown",[["path",{d:"M10 2v8",key:"d4bbey"}],["path",{d:"M12.8 21.6A2 2 0 1 0 14 18H2",key:"19kp1d"}],["path",{d:"M17.5 10a2.5 2.5 0 1 1 2 4H2",key:"19kpjc"}],["path",{d:"m6 6 4 4 4-4",key:"k13n16"}]]);/** * @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 Qde=te("Wind",[["path",{d:"M12.8 19.6A2 2 0 1 0 14 16H2",key:"148xed"}],["path",{d:"M17.5 8a2.5 2.5 0 1 1 2 4H2",key:"1u4tom"}],["path",{d:"M9.8 4.4A2 2 0 1 1 11 8H2",key:"75valh"}]]);/** * @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 Jde=te("WineOff",[["path",{d:"M8 22h8",key:"rmew8v"}],["path",{d:"M7 10h3m7 0h-1.343",key:"v48bem"}],["path",{d:"M12 15v7",key:"t2xh3l"}],["path",{d:"M7.307 7.307A12.33 12.33 0 0 0 7 10a5 5 0 0 0 7.391 4.391M8.638 2.981C8.75 2.668 8.872 2.34 9 2h6c1.5 4 2 6 2 8 0 .407-.05.809-.145 1.198",key:"1ymjlu"}],["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}]]);/** * @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 eue=te("Wine",[["path",{d:"M8 22h8",key:"rmew8v"}],["path",{d:"M7 10h10",key:"1101jm"}],["path",{d:"M12 15v7",key:"t2xh3l"}],["path",{d:"M12 15a5 5 0 0 0 5-5c0-2-.5-4-2-8H9c-1.5 4-2 6-2 8a5 5 0 0 0 5 5Z",key:"10ffi3"}]]);/** * @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 qF=te("Workflow",[["rect",{width:"8",height:"8",x:"3",y:"3",rx:"2",key:"by2w9f"}],["path",{d:"M7 11v4a2 2 0 0 0 2 2h4",key:"xkn7yn"}],["rect",{width:"8",height:"8",x:"13",y:"13",rx:"2",key:"1cgmvn"}]]);/** * @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 tue=te("Worm",[["path",{d:"m19 12-1.5 3",key:"9bcu4o"}],["path",{d:"M19.63 18.81 22 20",key:"121v98"}],["path",{d:"M6.47 8.23a1.68 1.68 0 0 1 2.44 1.93l-.64 2.08a6.76 6.76 0 0 0 10.16 7.67l.42-.27a1 1 0 1 0-2.73-4.21l-.42.27a1.76 1.76 0 0 1-2.63-1.99l.64-2.08A6.66 6.66 0 0 0 3.94 3.9l-.7.4a1 1 0 1 0 2.55 4.34z",key:"1tij6q"}]]);/** * @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 sue=te("WrapText",[["line",{x1:"3",x2:"21",y1:"6",y2:"6",key:"4m8b97"}],["path",{d:"M3 12h15a3 3 0 1 1 0 6h-4",key:"1cl7v7"}],["polyline",{points:"16 16 14 18 16 20",key:"1jznyi"}],["line",{x1:"3",x2:"10",y1:"18",y2:"18",key:"1h33wv"}]]);/** * @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 N1=te("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 Rr=te("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 rue=te("Youtube",[["path",{d:"M2.5 17a24.12 24.12 0 0 1 0-10 2 2 0 0 1 1.4-1.4 49.56 49.56 0 0 1 16.2 0A2 2 0 0 1 21.5 7a24.12 24.12 0 0 1 0 10 2 2 0 0 1-1.4 1.4 49.55 49.55 0 0 1-16.2 0A2 2 0 0 1 2.5 17",key:"1q2vi4"}],["path",{d:"m10 15 5-3-5-3z",key:"1jp15x"}]]);/** * @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 nue=te("ZapOff",[["path",{d:"M10.513 4.856 13.12 2.17a.5.5 0 0 1 .86.46l-1.377 4.317",key:"193nxd"}],["path",{d:"M15.656 10H20a1 1 0 0 1 .78 1.63l-1.72 1.773",key:"27a7lr"}],["path",{d:"M16.273 16.273 10.88 21.83a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14H4a1 1 0 0 1-.78-1.63l4.507-4.643",key:"1e0qe9"}],["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 ym=te("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 Qk=te("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 JI=te("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"}]]);/** * @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 ZSt=Object.freeze(Object.defineProperty({__proto__:null,AArrowDown:BV,AArrowUp:zV,ALargeSmall:$V,Accessibility:UV,Activity:ef,AirVent:qV,Airplay:VV,AlarmClock:GV,AlarmClockCheck:hC,AlarmClockMinus:mC,AlarmClockOff:HV,AlarmClockPlus:fC,AlarmSmoke:WV,Album:KV,AlignCenter:dE,AlignCenterHorizontal:YV,AlignCenterVertical:ZV,AlignEndHorizontal:XV,AlignEndVertical:QV,AlignHorizontalDistributeCenter:JV,AlignHorizontalDistributeEnd:eH,AlignHorizontalDistributeStart:tH,AlignHorizontalJustifyCenter:sH,AlignHorizontalJustifyEnd:rH,AlignHorizontalJustifyStart:nH,AlignHorizontalSpaceAround:aH,AlignHorizontalSpaceBetween:iH,AlignJustify:oH,AlignLeft:uE,AlignRight:hE,AlignStartHorizontal:lH,AlignStartVertical:cH,AlignVerticalDistributeCenter:dH,AlignVerticalDistributeEnd:uH,AlignVerticalDistributeStart:hH,AlignVerticalJustifyCenter:mH,AlignVerticalJustifyEnd:fH,AlignVerticalJustifyStart:pH,AlignVerticalSpaceAround:gH,AlignVerticalSpaceBetween:xH,Ambulance:yH,Ampersand:vH,Ampersands:bH,Amphora:_H,Anchor:wH,Angry:jH,Annoyed:NH,Antenna:kH,Anvil:SH,Aperture:CH,AppWindow:KO,AppWindowMac:TH,Apple:EH,Archive:Rk,ArchiveRestore:AI,ArchiveX:AH,Armchair:MH,ArrowBigDown:PH,ArrowBigDownDash:IH,ArrowBigLeft:DH,ArrowBigLeftDash:LH,ArrowBigRight:OH,ArrowBigRightDash:RH,ArrowBigUp:BH,ArrowBigUpDash:FH,ArrowDown:fm,ArrowDown01:zH,ArrowDown10:$H,ArrowDownAZ:pC,ArrowDownFromLine:UH,ArrowDownLeft:qH,ArrowDownNarrowWide:VH,ArrowDownRight:YO,ArrowDownToDot:HH,ArrowDownToLine:GH,ArrowDownUp:WH,ArrowDownWideNarrow:gC,ArrowDownZA:xC,ArrowLeft:za,ArrowLeftFromLine:KH,ArrowLeftRight:YH,ArrowLeftToLine:ZH,ArrowRight:bi,ArrowRightFromLine:XH,ArrowRightLeft:F2,ArrowRightToLine:QH,ArrowUp:Hu,ArrowUp01:JH,ArrowUp10:eG,ArrowUpAZ:yC,ArrowUpDown:qu,ArrowUpFromDot:tG,ArrowUpFromLine:sG,ArrowUpLeft:rG,ArrowUpNarrowWide:vC,ArrowUpRight:ZO,ArrowUpToLine:nG,ArrowUpWideNarrow:aG,ArrowUpZA:bC,ArrowsUpFromLine:iG,Asterisk:oG,AtSign:lG,Atom:cG,AudioLines:dG,AudioWaveform:uG,Award:Bc,Axe:hG,Axis3d:_C,Baby:mG,Backpack:fG,Badge:AG,BadgeAlert:pG,BadgeCent:gG,BadgeCheck:wC,BadgeDollarSign:xG,BadgeEuro:yG,BadgeHelp:vG,BadgeIndianRupee:bG,BadgeInfo:_G,BadgeJapaneseYen:wG,BadgeMinus:jG,BadgePercent:NG,BadgePlus:kG,BadgePoundSterling:SG,BadgeRussianRuble:CG,BadgeSwissFranc:TG,BadgeX:EG,BaggageClaim:MG,Ban:XO,Banana:IG,Bandage:PG,Banknote:LG,Barcode:DG,Baseline:RG,Bath:_p,Battery:UG,BatteryCharging:OG,BatteryFull:FG,BatteryLow:BG,BatteryMedium:zG,BatteryWarning:$G,Beaker:qG,Bean:HG,BeanOff:VG,Bed:x1,BedDouble:B2,BedSingle:GG,Beef:WG,Beer:YG,BeerOff:KG,Bell:wp,BellDot:ZG,BellElectric:XG,BellMinus:QG,BellOff:u_,BellPlus:JG,BellRing:QO,BetweenHorizontalEnd:jC,BetweenHorizontalStart:NC,BetweenVerticalEnd:eW,BetweenVerticalStart:tW,BicepsFlexed:sW,Bike:rW,Binary:nW,Binoculars:aW,Biohazard:iW,Bird:oW,Bitcoin:lW,Blend:cW,Blinds:dW,Blocks:uW,Bluetooth:pW,BluetoothConnected:hW,BluetoothOff:mW,BluetoothSearching:fW,Bold:Ok,Bolt:gW,Bomb:xW,Bone:yW,Book:zW,BookA:vW,BookAudio:bW,BookCheck:_W,BookCopy:wW,BookDashed:kC,BookDown:jW,BookHeadphones:NW,BookHeart:kW,BookImage:SW,BookKey:CW,BookLock:TW,BookMarked:EW,BookMinus:AW,BookOpen:tf,BookOpenCheck:MW,BookOpenText:IW,BookPlus:PW,BookText:LW,BookType:DW,BookUp:OW,BookUp2:RW,BookUser:FW,BookX:BW,Bookmark:Uy,BookmarkCheck:$W,BookmarkMinus:UW,BookmarkPlus:JO,BookmarkX:qW,BoomBox:VW,Bot:MI,BotMessageSquare:HW,BotOff:GW,Box:WW,Boxes:KW,Braces:SC,Brackets:YW,Brain:eF,BrainCircuit:ZW,BrainCog:XW,BrickWall:QW,Briefcase:pm,BriefcaseBusiness:JW,BriefcaseConveyorBelt:eK,BriefcaseMedical:tK,BringToFront:sK,Brush:rK,Bug:iK,BugOff:nK,BugPlay:aK,Building:mE,Building2:Xa,Bus:lK,BusFront:oK,Cable:dK,CableCar:cK,Cake:gm,CakeSlice:uK,Calculator:II,Calendar:Nn,Calendar1:hK,CalendarArrowDown:mK,CalendarArrowUp:fK,CalendarCheck:tF,CalendarCheck2:pK,CalendarClock:h_,CalendarCog:gK,CalendarDays:xu,CalendarFold:xK,CalendarHeart:sF,CalendarMinus:vK,CalendarMinus2:yK,CalendarOff:rF,CalendarPlus:A2,CalendarPlus2:bK,CalendarRange:_K,CalendarSearch:wK,CalendarSync:jK,CalendarX:kK,CalendarX2:NK,Camera:lx,CameraOff:SK,Candy:EK,CandyCane:CK,CandyOff:TK,Cannabis:AK,Captions:CC,CaptionsOff:MK,Car:LK,CarFront:IK,CarTaxiFront:PK,Caravan:DK,Carrot:RK,CaseLower:OK,CaseSensitive:FK,CaseUpper:BK,CassetteTape:zK,Cast:$K,Castle:UK,Cat:qK,Cctv:VK,ChartArea:TC,ChartBar:AC,ChartBarBig:EC,ChartBarDecreasing:HK,ChartBarIncreasing:GK,ChartBarStacked:WK,ChartCandlestick:MC,ChartColumn:Bo,ChartColumnBig:IC,ChartColumnDecreasing:KK,ChartColumnIncreasing:PC,ChartColumnStacked:YK,ChartGantt:ZK,ChartLine:LC,ChartNetwork:XK,ChartNoAxesColumn:RC,ChartNoAxesColumnDecreasing:QK,ChartNoAxesColumnIncreasing:DC,ChartNoAxesCombined:JK,ChartNoAxesGantt:OC,ChartPie:FC,ChartScatter:BC,ChartSpline:eY,Check:va,CheckCheck:nF,ChefHat:tY,Cherry:sY,ChevronDown:Io,ChevronFirst:rY,ChevronLast:nY,ChevronLeft:fl,ChevronRight:$a,ChevronUp:cx,ChevronsDown:iY,ChevronsDownUp:aY,ChevronsLeft:cY,ChevronsLeftRight:lY,ChevronsLeftRightEllipsis:oY,ChevronsRight:uY,ChevronsRightLeft:dY,ChevronsUp:hY,ChevronsUpDown:d0,Chrome:fE,Church:mY,Cigarette:pY,CigaretteOff:fY,Circle:Gu,CircleAlert:wo,CircleArrowDown:zC,CircleArrowLeft:$C,CircleArrowOutDownLeft:UC,CircleArrowOutDownRight:qC,CircleArrowOutUpLeft:VC,CircleArrowOutUpRight:HC,CircleArrowRight:GC,CircleArrowUp:WC,CircleCheck:ea,CircleCheckBig:zi,CircleChevronDown:KC,CircleChevronLeft:YC,CircleChevronRight:ZC,CircleChevronUp:XC,CircleDashed:gY,CircleDivide:QC,CircleDollarSign:xY,CircleDot:vY,CircleDotDashed:yY,CircleEllipsis:bY,CircleEqual:_Y,CircleFadingArrowUp:wY,CircleFadingPlus:jY,CircleGauge:JC,CircleHelp:v2,CircleMinus:e3,CircleOff:NY,CircleParking:s3,CircleParkingOff:t3,CirclePause:r3,CirclePercent:n3,CirclePlay:cg,CirclePlus:a3,CirclePower:i3,CircleSlash:kY,CircleSlash2:o3,CircleStop:l3,CircleUser:d3,CircleUserRound:c3,CircleX:kd,CircuitBoard:SY,Citrus:CY,Clapperboard:TY,Clipboard:DY,ClipboardCheck:PI,ClipboardCopy:EY,ClipboardList:Fk,ClipboardMinus:AY,ClipboardPaste:MY,ClipboardPen:h3,ClipboardPenLine:u3,ClipboardPlus:IY,ClipboardType:PY,ClipboardX:LY,Clock:Pn,Clock1:RY,Clock10:OY,Clock11:FY,Clock12:BY,Clock2:zY,Clock3:$Y,Clock4:UY,Clock5:qY,Clock6:VY,Clock7:HY,Clock8:GY,Clock9:WY,ClockAlert:KY,ClockArrowDown:YY,ClockArrowUp:ZY,Cloud:uZ,CloudAlert:XY,CloudCog:QY,CloudDownload:m3,CloudDrizzle:JY,CloudFog:eZ,CloudHail:tZ,CloudLightning:sZ,CloudMoon:nZ,CloudMoonRain:rZ,CloudOff:aZ,CloudRain:oZ,CloudRainWind:iZ,CloudSnow:lZ,CloudSun:dZ,CloudSunRain:cZ,CloudUpload:f3,Cloudy:hZ,Clover:M2,Club:mZ,Code:pE,CodeXml:b2,Codepen:fZ,Codesandbox:pZ,Coffee:gE,Cog:gZ,Coins:aF,Columns2:p3,Columns3:g3,Columns4:xZ,Combine:yZ,Command:vZ,Compass:LI,Component:bZ,Computer:_Z,ConciergeBell:wZ,Cone:jZ,Construction:NZ,Contact:xE,ContactRound:x3,Container:kZ,Contrast:SZ,Cookie:CZ,CookingPot:TZ,Copy:ui,CopyCheck:EZ,CopyMinus:AZ,CopyPlus:MZ,CopySlash:IZ,CopyX:PZ,Copyleft:LZ,Copyright:DZ,CornerDownLeft:RZ,CornerDownRight:OZ,CornerLeftDown:FZ,CornerLeftUp:BZ,CornerRightDown:zZ,CornerRightUp:$Z,CornerUpLeft:UZ,CornerUpRight:qZ,Cpu:VZ,CreativeCommons:HZ,CreditCard:u0,Croissant:GZ,Crop:WZ,Cross:KZ,Crosshair:YZ,Crown:zf,Cuboid:ZZ,CupSoda:XZ,Currency:QZ,Cylinder:JZ,Dam:eX,Database:iF,DatabaseBackup:tX,DatabaseZap:sX,Delete:rX,Dessert:nX,Diameter:aX,Diamond:lX,DiamondMinus:iX,DiamondPercent:y3,DiamondPlus:oX,Dice1:cX,Dice2:dX,Dice3:uX,Dice4:hX,Dice5:mX,Dice6:fX,Dices:pX,Diff:gX,Disc:bX,Disc2:xX,Disc3:yX,DiscAlbum:vX,Divide:_X,Dna:jX,DnaOff:wX,Dock:NX,Dog:kX,DollarSign:oc,Donut:SX,DoorClosed:CX,DoorOpen:m_,Dot:TX,Download:hi,DraftingCompass:EX,Drama:AX,Dribbble:MX,Drill:IX,Droplet:PX,Droplets:y1,Drum:LX,Drumstick:DX,Dumbbell:RX,Ear:FX,EarOff:OX,Earth:v3,EarthLock:BX,Eclipse:zX,Egg:DI,EggFried:$X,EggOff:UX,Ellipsis:Jx,EllipsisVertical:Ay,Equal:HX,EqualApproximately:qX,EqualNot:VX,Eraser:GX,EthernetPort:WX,Euro:KX,Expand:YX,ExternalLink:gn,Eye:Bn,EyeClosed:ZX,EyeOff:$f,Facebook:fh,Factory:XX,Fan:QX,FastForward:JX,Feather:eQ,Fence:tQ,FerrisWheel:sQ,Figma:rQ,File:RI,FileArchive:nQ,FileAudio:iQ,FileAudio2:aQ,FileAxis3d:b3,FileBadge:lQ,FileBadge2:oQ,FileBox:cQ,FileChartColumn:w3,FileChartColumnIncreasing:_3,FileChartLine:j3,FileChartPie:N3,FileCheck:oF,FileCheck2:dQ,FileClock:uQ,FileCode:mQ,FileCode2:hQ,FileCog:k3,FileDiff:fQ,FileDigit:pQ,FileDown:yE,FileHeart:gQ,FileImage:z2,FileInput:xQ,FileJson:vQ,FileJson2:yQ,FileKey:_Q,FileKey2:bQ,FileLock:jQ,FileLock2:wQ,FileMinus:kQ,FileMinus2:NQ,FileMusic:SQ,FileOutput:CQ,FilePen:C3,FilePenLine:S3,FilePlus:EQ,FilePlus2:TQ,FileQuestion:AQ,FileScan:MQ,FileSearch:PQ,FileSearch2:IQ,FileSliders:LQ,FileSpreadsheet:$2,FileStack:lF,FileSymlink:DQ,FileTerminal:RQ,FileText:kn,FileType:FQ,FileType2:OQ,FileUp:BQ,FileUser:zQ,FileVideo:cF,FileVideo2:$Q,FileVolume:qQ,FileVolume2:UQ,FileWarning:VQ,FileX:GQ,FileX2:HQ,Files:WQ,Film:Qm,Filter:v1,FilterX:KQ,Fingerprint:YQ,FireExtinguisher:ZQ,Fish:JQ,FishOff:XQ,FishSymbol:QQ,Flag:U2,FlagOff:eJ,FlagTriangleLeft:tJ,FlagTriangleRight:sJ,Flame:od,FlameKindling:rJ,Flashlight:aJ,FlashlightOff:nJ,FlaskConical:Bk,FlaskConicalOff:iJ,FlaskRound:oJ,FlipHorizontal:dF,FlipHorizontal2:lJ,FlipVertical:dJ,FlipVertical2:cJ,Flower:uJ,Flower2:u1,Focus:hJ,FoldHorizontal:mJ,FoldVertical:fJ,Folder:$J,FolderArchive:pJ,FolderCheck:gJ,FolderClock:xJ,FolderClosed:yJ,FolderCode:vJ,FolderCog:T3,FolderDot:bJ,FolderDown:_J,FolderGit:jJ,FolderGit2:wJ,FolderHeart:NJ,FolderInput:kJ,FolderKanban:SJ,FolderKey:CJ,FolderLock:TJ,FolderMinus:EJ,FolderOpen:Uf,FolderOpenDot:AJ,FolderOutput:MJ,FolderPen:E3,FolderPlus:IJ,FolderRoot:PJ,FolderSearch:DJ,FolderSearch2:LJ,FolderSymlink:RJ,FolderSync:OJ,FolderTree:FJ,FolderUp:BJ,FolderX:zJ,Folders:UJ,Footprints:qJ,Forklift:VJ,Forward:HJ,Frame:GJ,Framer:WJ,Frown:KJ,Fuel:YJ,Fullscreen:ZJ,GalleryHorizontal:QJ,GalleryHorizontalEnd:XJ,GalleryThumbnails:JJ,GalleryVertical:tee,GalleryVerticalEnd:eee,Gamepad:ree,Gamepad2:see,Gauge:nee,Gavel:aee,Gem:iee,Ghost:vE,Gift:Di,GitBranch:lee,GitBranchPlus:oee,GitCommitHorizontal:A3,GitCommitVertical:cee,GitCompare:uee,GitCompareArrows:dee,GitFork:hee,GitGraph:mee,GitMerge:fee,GitPullRequest:bee,GitPullRequestArrow:pee,GitPullRequestClosed:gee,GitPullRequestCreate:yee,GitPullRequestCreateArrow:xee,GitPullRequestDraft:vee,Github:_ee,Gitlab:wee,GlassWater:jee,Glasses:Nee,Globe:ld,GlobeLock:kee,Goal:See,Grab:Cee,GraduationCap:Vu,Grape:Tee,Grid2x2:I3,Grid2x2Check:Eee,Grid2x2Plus:M3,Grid2x2X:Aee,Grid3x3:by,Grip:Iee,GripHorizontal:Mee,GripVertical:Oh,Group:Pee,Guitar:Lee,Ham:Dee,Hammer:uF,Hand:hF,HandCoins:Ree,HandHeart:Oee,HandHelping:i1,HandMetal:Fee,HandPlatter:Bee,Handshake:zk,HardDrive:mF,HardDriveDownload:zee,HardDriveUpload:$ee,HardHat:Uee,Hash:$k,Haze:qee,HdmiPort:Vee,Heading:Kee,Heading1:OI,Heading2:FI,Heading3:fF,Heading4:Hee,Heading5:Gee,Heading6:Wee,HeadphoneOff:Yee,Headphones:Zee,Headset:Xee,Heart:Bi,HeartCrack:Qee,HeartHandshake:Jee,HeartOff:ete,HeartPulse:tte,Heater:ste,Hexagon:rte,Highlighter:nte,History:BI,Hop:ite,HopOff:ate,Hospital:ote,Hotel:lte,Hourglass:cte,House:Fn,HousePlug:dte,HousePlus:ute,IceCreamBowl:P3,IceCreamCone:L3,IdCard:hte,Image:wl,ImageDown:mte,ImageMinus:fte,ImageOff:pte,ImagePlay:gte,ImagePlus:f_,ImageUp:xte,ImageUpscale:yte,Images:vte,Import:bte,Inbox:Uk,IndentDecrease:D3,IndentIncrease:R3,IndianRupee:_te,Infinity:wte,Info:bE,InspectionPanel:jte,Instagram:yu,Italic:qk,IterationCcw:Nte,IterationCw:kte,JapaneseYen:Ste,Joystick:Cte,Kanban:p_,Key:dx,KeyRound:_E,KeySquare:Tte,Keyboard:Mte,KeyboardMusic:Ete,KeyboardOff:Ate,Lamp:Ote,LampCeiling:Ite,LampDesk:Pte,LampFloor:Lte,LampWallDown:Dte,LampWallUp:Rte,LandPlot:Fte,Landmark:Bte,Languages:zte,Laptop:Ute,LaptopMinimal:O3,LaptopMinimalCheck:$te,Lasso:Vte,LassoSelect:qte,Laugh:Hte,Layers:pF,Layers2:Gte,Layers3:Wte,LayoutDashboard:wE,LayoutGrid:_g,LayoutList:Kte,LayoutPanelLeft:Yte,LayoutPanelTop:Zte,LayoutTemplate:jE,Leaf:Xte,LeafyGreen:Qte,Lectern:Jte,LetterText:ese,Library:NE,LibraryBig:tse,LifeBuoy:zI,Ligature:sse,Lightbulb:q2,LightbulbOff:rse,Link:Jo,Link2:ql,Link2Off:nse,Linkedin:qf,List:Vf,ListCheck:ase,ListChecks:V2,ListCollapse:ise,ListEnd:ose,ListFilter:gF,ListMinus:lse,ListMusic:cse,ListOrdered:b1,ListPlus:dse,ListRestart:use,ListStart:hse,ListTodo:mse,ListTree:fse,ListVideo:pse,ListX:gse,Loader:yse,LoaderCircle:is,LoaderPinwheel:xse,Locate:$I,LocateFixed:vse,LocateOff:bse,Lock:Td,LockKeyhole:_se,LockKeyholeOpen:F3,LockOpen:B3,LogIn:kE,LogOut:UI,Logs:wse,Lollipop:jse,Luggage:Nse,Magnet:kse,Mail:er,MailCheck:Sse,MailMinus:Cse,MailOpen:xF,MailPlus:yF,MailQuestion:Tse,MailSearch:Ese,MailWarning:Ase,MailX:qI,Mailbox:Mse,Mails:Ise,Map:SE,MapPin:Qa,MapPinCheck:Lse,MapPinCheckInside:Pse,MapPinHouse:Dse,MapPinMinus:Ose,MapPinMinusInside:Rse,MapPinOff:Fse,MapPinPlus:zse,MapPinPlusInside:Bse,MapPinX:Use,MapPinXInside:$se,MapPinned:qse,Martini:Vse,Maximize:CE,Maximize2:Hse,Medal:H2,Megaphone:ph,MegaphoneOff:Gse,Meh:Wse,MemoryStick:Kse,Menu:TE,Merge:Yse,MessageCircle:qc,MessageCircleCode:Zse,MessageCircleDashed:Xse,MessageCircleHeart:VI,MessageCircleMore:Qse,MessageCircleOff:Jse,MessageCirclePlus:ere,MessageCircleQuestion:vF,MessageCircleReply:tre,MessageCircleWarning:sre,MessageCircleX:rre,MessageSquare:Gi,MessageSquareCode:nre,MessageSquareDashed:are,MessageSquareDiff:ire,MessageSquareDot:ore,MessageSquareHeart:lre,MessageSquareLock:cre,MessageSquareMore:bF,MessageSquareOff:dre,MessageSquarePlus:t_,MessageSquareQuote:HI,MessageSquareReply:ure,MessageSquareShare:hre,MessageSquareText:mre,MessageSquareWarning:fre,MessageSquareX:pre,MessagesSquare:gre,Mic:EE,MicOff:xre,MicVocal:z3,Microchip:yre,Microscope:vre,Microwave:bre,Milestone:_re,Milk:jre,MilkOff:wre,Minimize:kre,Minimize2:Nre,Minus:g_,Monitor:Vk,MonitorCheck:Sre,MonitorCog:Cre,MonitorDot:Tre,MonitorDown:Ere,MonitorOff:Are,MonitorPause:Mre,MonitorPlay:_F,MonitorSmartphone:Ire,MonitorSpeaker:Pre,MonitorStop:Lre,MonitorUp:AE,MonitorX:Dre,Moon:Ore,MoonStar:Rre,Mountain:Bre,MountainSnow:Fre,Mouse:qre,MouseOff:zre,MousePointer:lm,MousePointer2:$re,MousePointerBan:Ure,MousePointerClick:Kd,Move:sne,Move3d:$3,MoveDiagonal:Hre,MoveDiagonal2:Vre,MoveDown:Kre,MoveDownLeft:Gre,MoveDownRight:Wre,MoveHorizontal:Yre,MoveLeft:Zre,MoveRight:Xre,MoveUp:ene,MoveUpLeft:Qre,MoveUpRight:Jre,MoveVertical:tne,Music:GI,Music2:rne,Music3:nne,Music4:ane,Navigation:wF,Navigation2:one,Navigation2Off:ine,NavigationOff:lne,Network:cne,Newspaper:x_,Nfc:dne,Notebook:fne,NotebookPen:une,NotebookTabs:hne,NotebookText:mne,NotepadText:gne,NotepadTextDashed:pne,Nut:yne,NutOff:xne,Octagon:bne,OctagonAlert:_2,OctagonMinus:vne,OctagonPause:U3,OctagonX:q3,Omega:_ne,Option:wne,Orbit:jne,Origami:Nne,Package:yc,Package2:kne,PackageCheck:Sne,PackageMinus:Cne,PackageOpen:Tne,PackagePlus:Ene,PackageSearch:Ane,PackageX:Mne,PaintBucket:Ine,PaintRoller:Pne,Paintbrush:Lne,PaintbrushVertical:V3,Palette:pl,PanelBottom:One,PanelBottomClose:Dne,PanelBottomDashed:H3,PanelBottomOpen:Rne,PanelLeft:Y3,PanelLeftClose:G3,PanelLeftDashed:W3,PanelLeftOpen:K3,PanelRight:zne,PanelRightClose:Fne,PanelRightDashed:Z3,PanelRightOpen:Bne,PanelTop:qne,PanelTopClose:$ne,PanelTopDashed:X3,PanelTopOpen:Une,PanelsLeftBottom:Vne,PanelsRightBottom:Hne,PanelsTopLeft:w2,Paperclip:Hk,Parentheses:Gne,ParkingMeter:Wne,PartyPopper:gh,Pause:Hf,PawPrint:Kne,PcCase:Yne,Pen:Wb,PenLine:Gb,PenOff:Zne,PenTool:Gk,Pencil:ni,PencilLine:Xne,PencilOff:Qne,PencilRuler:Jne,Pentagon:eae,Percent:ME,PersonStanding:tae,PhilippinePeso:sae,Phone:Yn,PhoneCall:rae,PhoneForwarded:nae,PhoneIncoming:aae,PhoneMissed:iae,PhoneOff:oae,PhoneOutgoing:lae,Pi:cae,Piano:dae,Pickaxe:uae,PictureInPicture:mae,PictureInPicture2:hae,PiggyBank:fae,Pilcrow:xae,PilcrowLeft:pae,PilcrowRight:gae,Pill:vae,PillBottle:yae,Pin:Wk,PinOff:jF,Pipette:bae,Pizza:_ae,Plane:NF,PlaneLanding:wae,PlaneTakeoff:jae,Play:El,Plug:IE,Plug2:Nae,PlugZap:Q3,Plus:Ys,Pocket:Sae,PocketKnife:kae,Podcast:Cae,Pointer:Eae,PointerOff:Tae,Popcorn:Aae,Popsicle:Mae,PoundSterling:Iae,Power:kF,PowerOff:Pae,Presentation:_1,Printer:SF,PrinterCheck:Lae,Projector:Dae,Proportions:Rae,Puzzle:Oae,Pyramid:Fae,QrCode:y_,Quote:Kk,Rabbit:Bae,Radar:WI,Radiation:zae,Radical:$ae,Radio:G2,RadioReceiver:Uae,RadioTower:qae,Radius:Vae,RailSymbol:Hae,Rainbow:Gae,Rat:Wae,Ratio:Kae,Receipt:rie,ReceiptCent:Yae,ReceiptEuro:Zae,ReceiptIndianRupee:Xae,ReceiptJapaneseYen:Qae,ReceiptPoundSterling:Jae,ReceiptRussianRuble:eie,ReceiptSwissFranc:tie,ReceiptText:sie,RectangleEllipsis:J3,RectangleHorizontal:nie,RectangleVertical:aie,Recycle:iie,Redo:Yk,Redo2:oie,RedoDot:lie,RefreshCcw:KI,RefreshCcwDot:cie,RefreshCw:po,RefreshCwOff:die,Refrigerator:uie,Regex:hie,RemoveFormatting:mie,Repeat:CF,Repeat1:fie,Repeat2:pie,Replace:xie,ReplaceAll:gie,Reply:TF,ReplyAll:yie,Rewind:vie,Ribbon:bie,Rocket:v_,RockingChair:_ie,RollerCoaster:wie,Rotate3d:e5,RotateCcw:qy,RotateCcwSquare:jie,RotateCw:PE,RotateCwSquare:Nie,Route:Sie,RouteOff:kie,Router:Cie,Rows2:t5,Rows3:s5,Rows4:Tie,Rss:Eie,Ruler:LE,RussianRuble:Aie,Sailboat:Mie,Salad:Iie,Sandwich:Pie,Satellite:Die,SatelliteDish:Lie,Save:vc,SaveAll:Rie,SaveOff:Oie,Scale:EF,Scale3d:r5,Scaling:Fie,Scan:Gie,ScanBarcode:Bie,ScanEye:zie,ScanFace:$ie,ScanLine:Uie,ScanQrCode:qie,ScanSearch:Vie,ScanText:Hie,School:Wie,Scissors:Yie,ScissorsLineDashed:Kie,ScreenShare:Xie,ScreenShareOff:Zie,Scroll:Jie,ScrollText:Qie,Search:Mn,SearchCheck:eoe,SearchCode:toe,SearchSlash:soe,SearchX:AF,Section:roe,Send:yn,SendHorizontal:n5,SendToBack:noe,SeparatorHorizontal:aoe,SeparatorVertical:ioe,Server:doe,ServerCog:ooe,ServerCrash:loe,ServerOff:coe,Settings:Go,Settings2:MF,Shapes:uoe,Share:IF,Share2:cd,Sheet:hoe,Shell:moe,Shield:Fh,ShieldAlert:PF,ShieldBan:foe,ShieldCheck:w1,ShieldEllipsis:poe,ShieldHalf:goe,ShieldMinus:xoe,ShieldOff:DE,ShieldPlus:yoe,ShieldQuestion:voe,ShieldX:a5,Ship:_oe,ShipWheel:boe,Shirt:woe,ShoppingBag:b_,ShoppingBasket:joe,ShoppingCart:sx,Shovel:Noe,ShowerHead:koe,Shrink:Soe,Shrub:Coe,Shuffle:RE,Sigma:Toe,Signal:Poe,SignalHigh:Eoe,SignalLow:Aoe,SignalMedium:Moe,SignalZero:Ioe,Signature:Loe,Signpost:Roe,SignpostBig:Doe,Siren:Ooe,SkipBack:Foe,SkipForward:Boe,Skull:zoe,Slack:$oe,Slash:Uoe,Slice:qoe,SlidersHorizontal:OE,SlidersVertical:i5,Smartphone:Vy,SmartphoneCharging:Voe,SmartphoneNfc:Hoe,Smile:Woe,SmilePlus:Goe,Snail:Koe,Snowflake:h1,Sofa:Yoe,Soup:Zoe,Space:Xoe,Spade:Qoe,Sparkle:Joe,Sparkles:Lr,Speaker:ele,Speech:tle,SpellCheck:rle,SpellCheck2:sle,Spline:nle,Split:ale,SprayCan:ile,Sprout:FE,Square:Hy,SquareActivity:o5,SquareArrowDown:d5,SquareArrowDownLeft:l5,SquareArrowDownRight:c5,SquareArrowLeft:u5,SquareArrowOutDownLeft:h5,SquareArrowOutDownRight:m5,SquareArrowOutUpLeft:f5,SquareArrowOutUpRight:p5,SquareArrowRight:g5,SquareArrowUp:v5,SquareArrowUpLeft:x5,SquareArrowUpRight:y5,SquareAsterisk:b5,SquareBottomDashedScissors:_5,SquareChartGantt:Pb,SquareCheck:w5,SquareCheckBig:j2,SquareChevronDown:j5,SquareChevronLeft:N5,SquareChevronRight:k5,SquareChevronUp:S5,SquareCode:C5,SquareDashed:A5,SquareDashedBottom:lle,SquareDashedBottomCode:ole,SquareDashedKanban:T5,SquareDashedMousePointer:E5,SquareDivide:M5,SquareDot:I5,SquareEqual:P5,SquareFunction:L5,SquareKanban:D5,SquareLibrary:R5,SquareM:O5,SquareMenu:F5,SquareMinus:B5,SquareMousePointer:z5,SquareParking:U5,SquareParkingOff:$5,SquarePen:ou,SquarePercent:q5,SquarePi:V5,SquarePilcrow:H5,SquarePlay:G5,SquarePlus:W5,SquarePower:K5,SquareRadical:cle,SquareScissors:Y5,SquareSigma:Z5,SquareSlash:X5,SquareSplitHorizontal:Q5,SquareSplitVertical:J5,SquareSquare:dle,SquareStack:ule,SquareTerminal:eT,SquareUser:sT,SquareUserRound:tT,SquareX:rT,Squircle:hle,Squirrel:mle,Stamp:fle,Star:ya,StarHalf:ple,StarOff:gle,StepBack:xle,StepForward:yle,Stethoscope:vle,Sticker:ble,StickyNote:_le,Store:wle,StretchHorizontal:jle,StretchVertical:Nle,Strikethrough:LF,Subscript:kle,Sun:W2,SunDim:Sle,SunMedium:Cle,SunMoon:Tle,SunSnow:Ele,Sunrise:Ale,Sunset:Mle,Superscript:Ile,SwatchBook:Ple,SwissFranc:Lle,SwitchCamera:Dle,Sword:Rle,Swords:Ole,Syringe:Fle,Table:ZI,Table2:YI,TableCellsMerge:Ble,TableCellsSplit:zle,TableColumnsSplit:$le,TableOfContents:Ule,TableProperties:qle,TableRowsSplit:Vle,Tablet:Gle,TabletSmartphone:Hle,Tablets:Wle,Tag:xm,Tags:Kle,Tally1:Yle,Tally2:Zle,Tally3:Xle,Tally4:Qle,Tally5:Jle,Tangent:ece,Target:Wu,Telescope:tce,Tent:rce,TentTree:sce,Terminal:nce,TestTube:ace,TestTubeDiagonal:nT,TestTubes:ice,Text:uce,TextCursor:lce,TextCursorInput:oce,TextQuote:cce,TextSearch:dce,TextSelect:aT,Theater:hce,Thermometer:pce,ThermometerSnowflake:mce,ThermometerSun:fce,ThumbsDown:DF,ThumbsUp:sf,Ticket:RF,TicketCheck:gce,TicketMinus:xce,TicketPercent:yce,TicketPlus:vce,TicketSlash:bce,TicketX:_ce,Tickets:jce,TicketsPlane:wce,Timer:Sce,TimerOff:Nce,TimerReset:kce,ToggleLeft:Cce,ToggleRight:Tce,Toilet:Ece,Tornado:Ace,Torus:Mce,Touchpad:Pce,TouchpadOff:Ice,TowerControl:Lce,ToyBrick:Dce,Tractor:Rce,TrafficCone:Oce,TrainFront:Bce,TrainFrontTunnel:Fce,TrainTrack:zce,TramFront:iT,Trash:$ce,Trash2:Dr,TreeDeciduous:Uce,TreePalm:oT,TreePine:Zk,Trees:qce,Trello:Vce,TrendingDown:K2,TrendingUp:al,TrendingUpDown:Hce,Triangle:Wce,TriangleAlert:uu,TriangleRight:Gce,Trophy:To,Truck:OF,Turtle:Kce,Tv:Zce,TvMinimal:lT,TvMinimalPlay:Yce,Twitch:Xce,Twitter:Qce,Type:ede,TypeOutline:Jce,Umbrella:sde,UmbrellaOff:tde,Underline:XI,Undo:Xk,Undo2:rde,UndoDot:nde,UnfoldHorizontal:ade,UnfoldVertical:ide,Ungroup:ode,University:cT,Unlink:BE,Unlink2:lde,Unplug:cde,Upload:Ea,Usb:dde,User:io,UserCheck:j1,UserCog:FF,UserMinus:BF,UserPen:ude,UserPlus:Vl,UserRound:pT,UserRoundCheck:dT,UserRoundCog:uT,UserRoundMinus:hT,UserRoundPen:hde,UserRoundPlus:mT,UserRoundSearch:mde,UserRoundX:fT,UserSearch:fde,UserX:pde,Users:Ar,UsersRound:gT,Utensils:yT,UtensilsCrossed:xT,UtilityPole:gde,Variable:QI,Vault:xde,Vegan:yde,VenetianMask:vde,Vibrate:_de,VibrateOff:bde,Video:xn,VideoOff:wde,Videotape:jde,View:Nde,Voicemail:kde,Volleyball:Sde,Volume:Ede,Volume1:Cde,Volume2:zF,VolumeOff:Tde,VolumeX:$F,Vote:Ade,Wallet:UF,WalletCards:Mde,WalletMinimal:vT,Wallpaper:Ide,Wand:Pde,WandSparkles:My,Warehouse:Lde,WashingMachine:Dde,Watch:Rde,Waves:Ode,Waypoints:Fde,Webcam:Bde,Webhook:$de,WebhookOff:zde,Weight:Ude,Wheat:Vde,WheatOff:qde,WholeWord:Hde,Wifi:Zde,WifiHigh:Gde,WifiLow:Wde,WifiOff:Kde,WifiZero:Yde,Wind:Qde,WindArrowDown:Xde,Wine:eue,WineOff:Jde,Workflow:qF,Worm:tue,WrapText:sue,Wrench:N1,X:Rr,Youtube:rue,Zap:ym,ZapOff:nue,ZoomIn:Qk,ZoomOut:JI},Symbol.toStringTag,{value:"Module"}));/** * @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 Vpe=Object.freeze(Object.defineProperty({__proto__:null,AArrowDown:BV,AArrowDownIcon:BV,AArrowUp:zV,AArrowUpIcon:zV,ALargeSmall:$V,ALargeSmallIcon:$V,Accessibility:UV,AccessibilityIcon:UV,Activity:ef,ActivityIcon:ef,ActivitySquare:o5,ActivitySquareIcon:o5,AirVent:qV,AirVentIcon:qV,Airplay:VV,AirplayIcon:VV,AlarmCheck:hC,AlarmCheckIcon:hC,AlarmClock:GV,AlarmClockCheck:hC,AlarmClockCheckIcon:hC,AlarmClockIcon:GV,AlarmClockMinus:mC,AlarmClockMinusIcon:mC,AlarmClockOff:HV,AlarmClockOffIcon:HV,AlarmClockPlus:fC,AlarmClockPlusIcon:fC,AlarmMinus:mC,AlarmMinusIcon:mC,AlarmPlus:fC,AlarmPlusIcon:fC,AlarmSmoke:WV,AlarmSmokeIcon:WV,Album:KV,AlbumIcon:KV,AlertCircle:wo,AlertCircleIcon:wo,AlertOctagon:_2,AlertOctagonIcon:_2,AlertTriangle:uu,AlertTriangleIcon:uu,AlignCenter:dE,AlignCenterHorizontal:YV,AlignCenterHorizontalIcon:YV,AlignCenterIcon:dE,AlignCenterVertical:ZV,AlignCenterVerticalIcon:ZV,AlignEndHorizontal:XV,AlignEndHorizontalIcon:XV,AlignEndVertical:QV,AlignEndVerticalIcon:QV,AlignHorizontalDistributeCenter:JV,AlignHorizontalDistributeCenterIcon:JV,AlignHorizontalDistributeEnd:eH,AlignHorizontalDistributeEndIcon:eH,AlignHorizontalDistributeStart:tH,AlignHorizontalDistributeStartIcon:tH,AlignHorizontalJustifyCenter:sH,AlignHorizontalJustifyCenterIcon:sH,AlignHorizontalJustifyEnd:rH,AlignHorizontalJustifyEndIcon:rH,AlignHorizontalJustifyStart:nH,AlignHorizontalJustifyStartIcon:nH,AlignHorizontalSpaceAround:aH,AlignHorizontalSpaceAroundIcon:aH,AlignHorizontalSpaceBetween:iH,AlignHorizontalSpaceBetweenIcon:iH,AlignJustify:oH,AlignJustifyIcon:oH,AlignLeft:uE,AlignLeftIcon:uE,AlignRight:hE,AlignRightIcon:hE,AlignStartHorizontal:lH,AlignStartHorizontalIcon:lH,AlignStartVertical:cH,AlignStartVerticalIcon:cH,AlignVerticalDistributeCenter:dH,AlignVerticalDistributeCenterIcon:dH,AlignVerticalDistributeEnd:uH,AlignVerticalDistributeEndIcon:uH,AlignVerticalDistributeStart:hH,AlignVerticalDistributeStartIcon:hH,AlignVerticalJustifyCenter:mH,AlignVerticalJustifyCenterIcon:mH,AlignVerticalJustifyEnd:fH,AlignVerticalJustifyEndIcon:fH,AlignVerticalJustifyStart:pH,AlignVerticalJustifyStartIcon:pH,AlignVerticalSpaceAround:gH,AlignVerticalSpaceAroundIcon:gH,AlignVerticalSpaceBetween:xH,AlignVerticalSpaceBetweenIcon:xH,Ambulance:yH,AmbulanceIcon:yH,Ampersand:vH,AmpersandIcon:vH,Ampersands:bH,AmpersandsIcon:bH,Amphora:_H,AmphoraIcon:_H,Anchor:wH,AnchorIcon:wH,Angry:jH,AngryIcon:jH,Annoyed:NH,AnnoyedIcon:NH,Antenna:kH,AntennaIcon:kH,Anvil:SH,AnvilIcon:SH,Aperture:CH,ApertureIcon:CH,AppWindow:KO,AppWindowIcon:KO,AppWindowMac:TH,AppWindowMacIcon:TH,Apple:EH,AppleIcon:EH,Archive:Rk,ArchiveIcon:Rk,ArchiveRestore:AI,ArchiveRestoreIcon:AI,ArchiveX:AH,ArchiveXIcon:AH,AreaChart:TC,AreaChartIcon:TC,Armchair:MH,ArmchairIcon:MH,ArrowBigDown:PH,ArrowBigDownDash:IH,ArrowBigDownDashIcon:IH,ArrowBigDownIcon:PH,ArrowBigLeft:DH,ArrowBigLeftDash:LH,ArrowBigLeftDashIcon:LH,ArrowBigLeftIcon:DH,ArrowBigRight:OH,ArrowBigRightDash:RH,ArrowBigRightDashIcon:RH,ArrowBigRightIcon:OH,ArrowBigUp:BH,ArrowBigUpDash:FH,ArrowBigUpDashIcon:FH,ArrowBigUpIcon:BH,ArrowDown:fm,ArrowDown01:zH,ArrowDown01Icon:zH,ArrowDown10:$H,ArrowDown10Icon:$H,ArrowDownAZ:pC,ArrowDownAZIcon:pC,ArrowDownAz:pC,ArrowDownAzIcon:pC,ArrowDownCircle:zC,ArrowDownCircleIcon:zC,ArrowDownFromLine:UH,ArrowDownFromLineIcon:UH,ArrowDownIcon:fm,ArrowDownLeft:qH,ArrowDownLeftFromCircle:UC,ArrowDownLeftFromCircleIcon:UC,ArrowDownLeftFromSquare:h5,ArrowDownLeftFromSquareIcon:h5,ArrowDownLeftIcon:qH,ArrowDownLeftSquare:l5,ArrowDownLeftSquareIcon:l5,ArrowDownNarrowWide:VH,ArrowDownNarrowWideIcon:VH,ArrowDownRight:YO,ArrowDownRightFromCircle:qC,ArrowDownRightFromCircleIcon:qC,ArrowDownRightFromSquare:m5,ArrowDownRightFromSquareIcon:m5,ArrowDownRightIcon:YO,ArrowDownRightSquare:c5,ArrowDownRightSquareIcon:c5,ArrowDownSquare:d5,ArrowDownSquareIcon:d5,ArrowDownToDot:HH,ArrowDownToDotIcon:HH,ArrowDownToLine:GH,ArrowDownToLineIcon:GH,ArrowDownUp:WH,ArrowDownUpIcon:WH,ArrowDownWideNarrow:gC,ArrowDownWideNarrowIcon:gC,ArrowDownZA:xC,ArrowDownZAIcon:xC,ArrowDownZa:xC,ArrowDownZaIcon:xC,ArrowLeft:za,ArrowLeftCircle:$C,ArrowLeftCircleIcon:$C,ArrowLeftFromLine:KH,ArrowLeftFromLineIcon:KH,ArrowLeftIcon:za,ArrowLeftRight:YH,ArrowLeftRightIcon:YH,ArrowLeftSquare:u5,ArrowLeftSquareIcon:u5,ArrowLeftToLine:ZH,ArrowLeftToLineIcon:ZH,ArrowRight:bi,ArrowRightCircle:GC,ArrowRightCircleIcon:GC,ArrowRightFromLine:XH,ArrowRightFromLineIcon:XH,ArrowRightIcon:bi,ArrowRightLeft:F2,ArrowRightLeftIcon:F2,ArrowRightSquare:g5,ArrowRightSquareIcon:g5,ArrowRightToLine:QH,ArrowRightToLineIcon:QH,ArrowUp:Hu,ArrowUp01:JH,ArrowUp01Icon:JH,ArrowUp10:eG,ArrowUp10Icon:eG,ArrowUpAZ:yC,ArrowUpAZIcon:yC,ArrowUpAz:yC,ArrowUpAzIcon:yC,ArrowUpCircle:WC,ArrowUpCircleIcon:WC,ArrowUpDown:qu,ArrowUpDownIcon:qu,ArrowUpFromDot:tG,ArrowUpFromDotIcon:tG,ArrowUpFromLine:sG,ArrowUpFromLineIcon:sG,ArrowUpIcon:Hu,ArrowUpLeft:rG,ArrowUpLeftFromCircle:VC,ArrowUpLeftFromCircleIcon:VC,ArrowUpLeftFromSquare:f5,ArrowUpLeftFromSquareIcon:f5,ArrowUpLeftIcon:rG,ArrowUpLeftSquare:x5,ArrowUpLeftSquareIcon:x5,ArrowUpNarrowWide:vC,ArrowUpNarrowWideIcon:vC,ArrowUpRight:ZO,ArrowUpRightFromCircle:HC,ArrowUpRightFromCircleIcon:HC,ArrowUpRightFromSquare:p5,ArrowUpRightFromSquareIcon:p5,ArrowUpRightIcon:ZO,ArrowUpRightSquare:y5,ArrowUpRightSquareIcon:y5,ArrowUpSquare:v5,ArrowUpSquareIcon:v5,ArrowUpToLine:nG,ArrowUpToLineIcon:nG,ArrowUpWideNarrow:aG,ArrowUpWideNarrowIcon:aG,ArrowUpZA:bC,ArrowUpZAIcon:bC,ArrowUpZa:bC,ArrowUpZaIcon:bC,ArrowsUpFromLine:iG,ArrowsUpFromLineIcon:iG,Asterisk:oG,AsteriskIcon:oG,AsteriskSquare:b5,AsteriskSquareIcon:b5,AtSign:lG,AtSignIcon:lG,Atom:cG,AtomIcon:cG,AudioLines:dG,AudioLinesIcon:dG,AudioWaveform:uG,AudioWaveformIcon:uG,Award:Bc,AwardIcon:Bc,Axe:hG,AxeIcon:hG,Axis3D:_C,Axis3DIcon:_C,Axis3d:_C,Axis3dIcon:_C,Baby:mG,BabyIcon:mG,Backpack:fG,BackpackIcon:fG,Badge:AG,BadgeAlert:pG,BadgeAlertIcon:pG,BadgeCent:gG,BadgeCentIcon:gG,BadgeCheck:wC,BadgeCheckIcon:wC,BadgeDollarSign:xG,BadgeDollarSignIcon:xG,BadgeEuro:yG,BadgeEuroIcon:yG,BadgeHelp:vG,BadgeHelpIcon:vG,BadgeIcon:AG,BadgeIndianRupee:bG,BadgeIndianRupeeIcon:bG,BadgeInfo:_G,BadgeInfoIcon:_G,BadgeJapaneseYen:wG,BadgeJapaneseYenIcon:wG,BadgeMinus:jG,BadgeMinusIcon:jG,BadgePercent:NG,BadgePercentIcon:NG,BadgePlus:kG,BadgePlusIcon:kG,BadgePoundSterling:SG,BadgePoundSterlingIcon:SG,BadgeRussianRuble:CG,BadgeRussianRubleIcon:CG,BadgeSwissFranc:TG,BadgeSwissFrancIcon:TG,BadgeX:EG,BadgeXIcon:EG,BaggageClaim:MG,BaggageClaimIcon:MG,Ban:XO,BanIcon:XO,Banana:IG,BananaIcon:IG,Bandage:PG,BandageIcon:PG,Banknote:LG,BanknoteIcon:LG,BarChart:DC,BarChart2:RC,BarChart2Icon:RC,BarChart3:Bo,BarChart3Icon:Bo,BarChart4:PC,BarChart4Icon:PC,BarChartBig:IC,BarChartBigIcon:IC,BarChartHorizontal:AC,BarChartHorizontalBig:EC,BarChartHorizontalBigIcon:EC,BarChartHorizontalIcon:AC,BarChartIcon:DC,Barcode:DG,BarcodeIcon:DG,Baseline:RG,BaselineIcon:RG,Bath:_p,BathIcon:_p,Battery:UG,BatteryCharging:OG,BatteryChargingIcon:OG,BatteryFull:FG,BatteryFullIcon:FG,BatteryIcon:UG,BatteryLow:BG,BatteryLowIcon:BG,BatteryMedium:zG,BatteryMediumIcon:zG,BatteryWarning:$G,BatteryWarningIcon:$G,Beaker:qG,BeakerIcon:qG,Bean:HG,BeanIcon:HG,BeanOff:VG,BeanOffIcon:VG,Bed:x1,BedDouble:B2,BedDoubleIcon:B2,BedIcon:x1,BedSingle:GG,BedSingleIcon:GG,Beef:WG,BeefIcon:WG,Beer:YG,BeerIcon:YG,BeerOff:KG,BeerOffIcon:KG,Bell:wp,BellDot:ZG,BellDotIcon:ZG,BellElectric:XG,BellElectricIcon:XG,BellIcon:wp,BellMinus:QG,BellMinusIcon:QG,BellOff:u_,BellOffIcon:u_,BellPlus:JG,BellPlusIcon:JG,BellRing:QO,BellRingIcon:QO,BetweenHorizonalEnd:jC,BetweenHorizonalEndIcon:jC,BetweenHorizonalStart:NC,BetweenHorizonalStartIcon:NC,BetweenHorizontalEnd:jC,BetweenHorizontalEndIcon:jC,BetweenHorizontalStart:NC,BetweenHorizontalStartIcon:NC,BetweenVerticalEnd:eW,BetweenVerticalEndIcon:eW,BetweenVerticalStart:tW,BetweenVerticalStartIcon:tW,BicepsFlexed:sW,BicepsFlexedIcon:sW,Bike:rW,BikeIcon:rW,Binary:nW,BinaryIcon:nW,Binoculars:aW,BinocularsIcon:aW,Biohazard:iW,BiohazardIcon:iW,Bird:oW,BirdIcon:oW,Bitcoin:lW,BitcoinIcon:lW,Blend:cW,BlendIcon:cW,Blinds:dW,BlindsIcon:dW,Blocks:uW,BlocksIcon:uW,Bluetooth:pW,BluetoothConnected:hW,BluetoothConnectedIcon:hW,BluetoothIcon:pW,BluetoothOff:mW,BluetoothOffIcon:mW,BluetoothSearching:fW,BluetoothSearchingIcon:fW,Bold:Ok,BoldIcon:Ok,Bolt:gW,BoltIcon:gW,Bomb:xW,BombIcon:xW,Bone:yW,BoneIcon:yW,Book:zW,BookA:vW,BookAIcon:vW,BookAudio:bW,BookAudioIcon:bW,BookCheck:_W,BookCheckIcon:_W,BookCopy:wW,BookCopyIcon:wW,BookDashed:kC,BookDashedIcon:kC,BookDown:jW,BookDownIcon:jW,BookHeadphones:NW,BookHeadphonesIcon:NW,BookHeart:kW,BookHeartIcon:kW,BookIcon:zW,BookImage:SW,BookImageIcon:SW,BookKey:CW,BookKeyIcon:CW,BookLock:TW,BookLockIcon:TW,BookMarked:EW,BookMarkedIcon:EW,BookMinus:AW,BookMinusIcon:AW,BookOpen:tf,BookOpenCheck:MW,BookOpenCheckIcon:MW,BookOpenIcon:tf,BookOpenText:IW,BookOpenTextIcon:IW,BookPlus:PW,BookPlusIcon:PW,BookTemplate:kC,BookTemplateIcon:kC,BookText:LW,BookTextIcon:LW,BookType:DW,BookTypeIcon:DW,BookUp:OW,BookUp2:RW,BookUp2Icon:RW,BookUpIcon:OW,BookUser:FW,BookUserIcon:FW,BookX:BW,BookXIcon:BW,Bookmark:Uy,BookmarkCheck:$W,BookmarkCheckIcon:$W,BookmarkIcon:Uy,BookmarkMinus:UW,BookmarkMinusIcon:UW,BookmarkPlus:JO,BookmarkPlusIcon:JO,BookmarkX:qW,BookmarkXIcon:qW,BoomBox:VW,BoomBoxIcon:VW,Bot:MI,BotIcon:MI,BotMessageSquare:HW,BotMessageSquareIcon:HW,BotOff:GW,BotOffIcon:GW,Box:WW,BoxIcon:WW,BoxSelect:A5,BoxSelectIcon:A5,Boxes:KW,BoxesIcon:KW,Braces:SC,BracesIcon:SC,Brackets:YW,BracketsIcon:YW,Brain:eF,BrainCircuit:ZW,BrainCircuitIcon:ZW,BrainCog:XW,BrainCogIcon:XW,BrainIcon:eF,BrickWall:QW,BrickWallIcon:QW,Briefcase:pm,BriefcaseBusiness:JW,BriefcaseBusinessIcon:JW,BriefcaseConveyorBelt:eK,BriefcaseConveyorBeltIcon:eK,BriefcaseIcon:pm,BriefcaseMedical:tK,BriefcaseMedicalIcon:tK,BringToFront:sK,BringToFrontIcon:sK,Brush:rK,BrushIcon:rK,Bug:iK,BugIcon:iK,BugOff:nK,BugOffIcon:nK,BugPlay:aK,BugPlayIcon:aK,Building:mE,Building2:Xa,Building2Icon:Xa,BuildingIcon:mE,Bus:lK,BusFront:oK,BusFrontIcon:oK,BusIcon:lK,Cable:dK,CableCar:cK,CableCarIcon:cK,CableIcon:dK,Cake:gm,CakeIcon:gm,CakeSlice:uK,CakeSliceIcon:uK,Calculator:II,CalculatorIcon:II,Calendar:Nn,Calendar1:hK,Calendar1Icon:hK,CalendarArrowDown:mK,CalendarArrowDownIcon:mK,CalendarArrowUp:fK,CalendarArrowUpIcon:fK,CalendarCheck:tF,CalendarCheck2:pK,CalendarCheck2Icon:pK,CalendarCheckIcon:tF,CalendarClock:h_,CalendarClockIcon:h_,CalendarCog:gK,CalendarCogIcon:gK,CalendarDays:xu,CalendarDaysIcon:xu,CalendarFold:xK,CalendarFoldIcon:xK,CalendarHeart:sF,CalendarHeartIcon:sF,CalendarIcon:Nn,CalendarMinus:vK,CalendarMinus2:yK,CalendarMinus2Icon:yK,CalendarMinusIcon:vK,CalendarOff:rF,CalendarOffIcon:rF,CalendarPlus:A2,CalendarPlus2:bK,CalendarPlus2Icon:bK,CalendarPlusIcon:A2,CalendarRange:_K,CalendarRangeIcon:_K,CalendarSearch:wK,CalendarSearchIcon:wK,CalendarSync:jK,CalendarSyncIcon:jK,CalendarX:kK,CalendarX2:NK,CalendarX2Icon:NK,CalendarXIcon:kK,Camera:lx,CameraIcon:lx,CameraOff:SK,CameraOffIcon:SK,CandlestickChart:MC,CandlestickChartIcon:MC,Candy:EK,CandyCane:CK,CandyCaneIcon:CK,CandyIcon:EK,CandyOff:TK,CandyOffIcon:TK,Cannabis:AK,CannabisIcon:AK,Captions:CC,CaptionsIcon:CC,CaptionsOff:MK,CaptionsOffIcon:MK,Car:LK,CarFront:IK,CarFrontIcon:IK,CarIcon:LK,CarTaxiFront:PK,CarTaxiFrontIcon:PK,Caravan:DK,CaravanIcon:DK,Carrot:RK,CarrotIcon:RK,CaseLower:OK,CaseLowerIcon:OK,CaseSensitive:FK,CaseSensitiveIcon:FK,CaseUpper:BK,CaseUpperIcon:BK,CassetteTape:zK,CassetteTapeIcon:zK,Cast:$K,CastIcon:$K,Castle:UK,CastleIcon:UK,Cat:qK,CatIcon:qK,Cctv:VK,CctvIcon:VK,ChartArea:TC,ChartAreaIcon:TC,ChartBar:AC,ChartBarBig:EC,ChartBarBigIcon:EC,ChartBarDecreasing:HK,ChartBarDecreasingIcon:HK,ChartBarIcon:AC,ChartBarIncreasing:GK,ChartBarIncreasingIcon:GK,ChartBarStacked:WK,ChartBarStackedIcon:WK,ChartCandlestick:MC,ChartCandlestickIcon:MC,ChartColumn:Bo,ChartColumnBig:IC,ChartColumnBigIcon:IC,ChartColumnDecreasing:KK,ChartColumnDecreasingIcon:KK,ChartColumnIcon:Bo,ChartColumnIncreasing:PC,ChartColumnIncreasingIcon:PC,ChartColumnStacked:YK,ChartColumnStackedIcon:YK,ChartGantt:ZK,ChartGanttIcon:ZK,ChartLine:LC,ChartLineIcon:LC,ChartNetwork:XK,ChartNetworkIcon:XK,ChartNoAxesColumn:RC,ChartNoAxesColumnDecreasing:QK,ChartNoAxesColumnDecreasingIcon:QK,ChartNoAxesColumnIcon:RC,ChartNoAxesColumnIncreasing:DC,ChartNoAxesColumnIncreasingIcon:DC,ChartNoAxesCombined:JK,ChartNoAxesCombinedIcon:JK,ChartNoAxesGantt:OC,ChartNoAxesGanttIcon:OC,ChartPie:FC,ChartPieIcon:FC,ChartScatter:BC,ChartScatterIcon:BC,ChartSpline:eY,ChartSplineIcon:eY,Check:va,CheckCheck:nF,CheckCheckIcon:nF,CheckCircle:zi,CheckCircle2:ea,CheckCircle2Icon:ea,CheckCircleIcon:zi,CheckIcon:va,CheckSquare:j2,CheckSquare2:w5,CheckSquare2Icon:w5,CheckSquareIcon:j2,ChefHat:tY,ChefHatIcon:tY,Cherry:sY,CherryIcon:sY,ChevronDown:Io,ChevronDownCircle:KC,ChevronDownCircleIcon:KC,ChevronDownIcon:Io,ChevronDownSquare:j5,ChevronDownSquareIcon:j5,ChevronFirst:rY,ChevronFirstIcon:rY,ChevronLast:nY,ChevronLastIcon:nY,ChevronLeft:fl,ChevronLeftCircle:YC,ChevronLeftCircleIcon:YC,ChevronLeftIcon:fl,ChevronLeftSquare:N5,ChevronLeftSquareIcon:N5,ChevronRight:$a,ChevronRightCircle:ZC,ChevronRightCircleIcon:ZC,ChevronRightIcon:$a,ChevronRightSquare:k5,ChevronRightSquareIcon:k5,ChevronUp:cx,ChevronUpCircle:XC,ChevronUpCircleIcon:XC,ChevronUpIcon:cx,ChevronUpSquare:S5,ChevronUpSquareIcon:S5,ChevronsDown:iY,ChevronsDownIcon:iY,ChevronsDownUp:aY,ChevronsDownUpIcon:aY,ChevronsLeft:cY,ChevronsLeftIcon:cY,ChevronsLeftRight:lY,ChevronsLeftRightEllipsis:oY,ChevronsLeftRightEllipsisIcon:oY,ChevronsLeftRightIcon:lY,ChevronsRight:uY,ChevronsRightIcon:uY,ChevronsRightLeft:dY,ChevronsRightLeftIcon:dY,ChevronsUp:hY,ChevronsUpDown:d0,ChevronsUpDownIcon:d0,ChevronsUpIcon:hY,Chrome:fE,ChromeIcon:fE,Church:mY,ChurchIcon:mY,Cigarette:pY,CigaretteIcon:pY,CigaretteOff:fY,CigaretteOffIcon:fY,Circle:Gu,CircleAlert:wo,CircleAlertIcon:wo,CircleArrowDown:zC,CircleArrowDownIcon:zC,CircleArrowLeft:$C,CircleArrowLeftIcon:$C,CircleArrowOutDownLeft:UC,CircleArrowOutDownLeftIcon:UC,CircleArrowOutDownRight:qC,CircleArrowOutDownRightIcon:qC,CircleArrowOutUpLeft:VC,CircleArrowOutUpLeftIcon:VC,CircleArrowOutUpRight:HC,CircleArrowOutUpRightIcon:HC,CircleArrowRight:GC,CircleArrowRightIcon:GC,CircleArrowUp:WC,CircleArrowUpIcon:WC,CircleCheck:ea,CircleCheckBig:zi,CircleCheckBigIcon:zi,CircleCheckIcon:ea,CircleChevronDown:KC,CircleChevronDownIcon:KC,CircleChevronLeft:YC,CircleChevronLeftIcon:YC,CircleChevronRight:ZC,CircleChevronRightIcon:ZC,CircleChevronUp:XC,CircleChevronUpIcon:XC,CircleDashed:gY,CircleDashedIcon:gY,CircleDivide:QC,CircleDivideIcon:QC,CircleDollarSign:xY,CircleDollarSignIcon:xY,CircleDot:vY,CircleDotDashed:yY,CircleDotDashedIcon:yY,CircleDotIcon:vY,CircleEllipsis:bY,CircleEllipsisIcon:bY,CircleEqual:_Y,CircleEqualIcon:_Y,CircleFadingArrowUp:wY,CircleFadingArrowUpIcon:wY,CircleFadingPlus:jY,CircleFadingPlusIcon:jY,CircleGauge:JC,CircleGaugeIcon:JC,CircleHelp:v2,CircleHelpIcon:v2,CircleIcon:Gu,CircleMinus:e3,CircleMinusIcon:e3,CircleOff:NY,CircleOffIcon:NY,CircleParking:s3,CircleParkingIcon:s3,CircleParkingOff:t3,CircleParkingOffIcon:t3,CirclePause:r3,CirclePauseIcon:r3,CirclePercent:n3,CirclePercentIcon:n3,CirclePlay:cg,CirclePlayIcon:cg,CirclePlus:a3,CirclePlusIcon:a3,CirclePower:i3,CirclePowerIcon:i3,CircleSlash:kY,CircleSlash2:o3,CircleSlash2Icon:o3,CircleSlashIcon:kY,CircleSlashed:o3,CircleSlashedIcon:o3,CircleStop:l3,CircleStopIcon:l3,CircleUser:d3,CircleUserIcon:d3,CircleUserRound:c3,CircleUserRoundIcon:c3,CircleX:kd,CircleXIcon:kd,CircuitBoard:SY,CircuitBoardIcon:SY,Citrus:CY,CitrusIcon:CY,Clapperboard:TY,ClapperboardIcon:TY,Clipboard:DY,ClipboardCheck:PI,ClipboardCheckIcon:PI,ClipboardCopy:EY,ClipboardCopyIcon:EY,ClipboardEdit:h3,ClipboardEditIcon:h3,ClipboardIcon:DY,ClipboardList:Fk,ClipboardListIcon:Fk,ClipboardMinus:AY,ClipboardMinusIcon:AY,ClipboardPaste:MY,ClipboardPasteIcon:MY,ClipboardPen:h3,ClipboardPenIcon:h3,ClipboardPenLine:u3,ClipboardPenLineIcon:u3,ClipboardPlus:IY,ClipboardPlusIcon:IY,ClipboardSignature:u3,ClipboardSignatureIcon:u3,ClipboardType:PY,ClipboardTypeIcon:PY,ClipboardX:LY,ClipboardXIcon:LY,Clock:Pn,Clock1:RY,Clock10:OY,Clock10Icon:OY,Clock11:FY,Clock11Icon:FY,Clock12:BY,Clock12Icon:BY,Clock1Icon:RY,Clock2:zY,Clock2Icon:zY,Clock3:$Y,Clock3Icon:$Y,Clock4:UY,Clock4Icon:UY,Clock5:qY,Clock5Icon:qY,Clock6:VY,Clock6Icon:VY,Clock7:HY,Clock7Icon:HY,Clock8:GY,Clock8Icon:GY,Clock9:WY,Clock9Icon:WY,ClockAlert:KY,ClockAlertIcon:KY,ClockArrowDown:YY,ClockArrowDownIcon:YY,ClockArrowUp:ZY,ClockArrowUpIcon:ZY,ClockIcon:Pn,Cloud:uZ,CloudAlert:XY,CloudAlertIcon:XY,CloudCog:QY,CloudCogIcon:QY,CloudDownload:m3,CloudDownloadIcon:m3,CloudDrizzle:JY,CloudDrizzleIcon:JY,CloudFog:eZ,CloudFogIcon:eZ,CloudHail:tZ,CloudHailIcon:tZ,CloudIcon:uZ,CloudLightning:sZ,CloudLightningIcon:sZ,CloudMoon:nZ,CloudMoonIcon:nZ,CloudMoonRain:rZ,CloudMoonRainIcon:rZ,CloudOff:aZ,CloudOffIcon:aZ,CloudRain:oZ,CloudRainIcon:oZ,CloudRainWind:iZ,CloudRainWindIcon:iZ,CloudSnow:lZ,CloudSnowIcon:lZ,CloudSun:dZ,CloudSunIcon:dZ,CloudSunRain:cZ,CloudSunRainIcon:cZ,CloudUpload:f3,CloudUploadIcon:f3,Cloudy:hZ,CloudyIcon:hZ,Clover:M2,CloverIcon:M2,Club:mZ,ClubIcon:mZ,Code:pE,Code2:b2,Code2Icon:b2,CodeIcon:pE,CodeSquare:C5,CodeSquareIcon:C5,CodeXml:b2,CodeXmlIcon:b2,Codepen:fZ,CodepenIcon:fZ,Codesandbox:pZ,CodesandboxIcon:pZ,Coffee:gE,CoffeeIcon:gE,Cog:gZ,CogIcon:gZ,Coins:aF,CoinsIcon:aF,Columns:p3,Columns2:p3,Columns2Icon:p3,Columns3:g3,Columns3Icon:g3,Columns4:xZ,Columns4Icon:xZ,ColumnsIcon:p3,Combine:yZ,CombineIcon:yZ,Command:vZ,CommandIcon:vZ,Compass:LI,CompassIcon:LI,Component:bZ,ComponentIcon:bZ,Computer:_Z,ComputerIcon:_Z,ConciergeBell:wZ,ConciergeBellIcon:wZ,Cone:jZ,ConeIcon:jZ,Construction:NZ,ConstructionIcon:NZ,Contact:xE,Contact2:x3,Contact2Icon:x3,ContactIcon:xE,ContactRound:x3,ContactRoundIcon:x3,Container:kZ,ContainerIcon:kZ,Contrast:SZ,ContrastIcon:SZ,Cookie:CZ,CookieIcon:CZ,CookingPot:TZ,CookingPotIcon:TZ,Copy:ui,CopyCheck:EZ,CopyCheckIcon:EZ,CopyIcon:ui,CopyMinus:AZ,CopyMinusIcon:AZ,CopyPlus:MZ,CopyPlusIcon:MZ,CopySlash:IZ,CopySlashIcon:IZ,CopyX:PZ,CopyXIcon:PZ,Copyleft:LZ,CopyleftIcon:LZ,Copyright:DZ,CopyrightIcon:DZ,CornerDownLeft:RZ,CornerDownLeftIcon:RZ,CornerDownRight:OZ,CornerDownRightIcon:OZ,CornerLeftDown:FZ,CornerLeftDownIcon:FZ,CornerLeftUp:BZ,CornerLeftUpIcon:BZ,CornerRightDown:zZ,CornerRightDownIcon:zZ,CornerRightUp:$Z,CornerRightUpIcon:$Z,CornerUpLeft:UZ,CornerUpLeftIcon:UZ,CornerUpRight:qZ,CornerUpRightIcon:qZ,Cpu:VZ,CpuIcon:VZ,CreativeCommons:HZ,CreativeCommonsIcon:HZ,CreditCard:u0,CreditCardIcon:u0,Croissant:GZ,CroissantIcon:GZ,Crop:WZ,CropIcon:WZ,Cross:KZ,CrossIcon:KZ,Crosshair:YZ,CrosshairIcon:YZ,Crown:zf,CrownIcon:zf,Cuboid:ZZ,CuboidIcon:ZZ,CupSoda:XZ,CupSodaIcon:XZ,CurlyBraces:SC,CurlyBracesIcon:SC,Currency:QZ,CurrencyIcon:QZ,Cylinder:JZ,CylinderIcon:JZ,Dam:eX,DamIcon:eX,Database:iF,DatabaseBackup:tX,DatabaseBackupIcon:tX,DatabaseIcon:iF,DatabaseZap:sX,DatabaseZapIcon:sX,Delete:rX,DeleteIcon:rX,Dessert:nX,DessertIcon:nX,Diameter:aX,DiameterIcon:aX,Diamond:lX,DiamondIcon:lX,DiamondMinus:iX,DiamondMinusIcon:iX,DiamondPercent:y3,DiamondPercentIcon:y3,DiamondPlus:oX,DiamondPlusIcon:oX,Dice1:cX,Dice1Icon:cX,Dice2:dX,Dice2Icon:dX,Dice3:uX,Dice3Icon:uX,Dice4:hX,Dice4Icon:hX,Dice5:mX,Dice5Icon:mX,Dice6:fX,Dice6Icon:fX,Dices:pX,DicesIcon:pX,Diff:gX,DiffIcon:gX,Disc:bX,Disc2:xX,Disc2Icon:xX,Disc3:yX,Disc3Icon:yX,DiscAlbum:vX,DiscAlbumIcon:vX,DiscIcon:bX,Divide:_X,DivideCircle:QC,DivideCircleIcon:QC,DivideIcon:_X,DivideSquare:M5,DivideSquareIcon:M5,Dna:jX,DnaIcon:jX,DnaOff:wX,DnaOffIcon:wX,Dock:NX,DockIcon:NX,Dog:kX,DogIcon:kX,DollarSign:oc,DollarSignIcon:oc,Donut:SX,DonutIcon:SX,DoorClosed:CX,DoorClosedIcon:CX,DoorOpen:m_,DoorOpenIcon:m_,Dot:TX,DotIcon:TX,DotSquare:I5,DotSquareIcon:I5,Download:hi,DownloadCloud:m3,DownloadCloudIcon:m3,DownloadIcon:hi,DraftingCompass:EX,DraftingCompassIcon:EX,Drama:AX,DramaIcon:AX,Dribbble:MX,DribbbleIcon:MX,Drill:IX,DrillIcon:IX,Droplet:PX,DropletIcon:PX,Droplets:y1,DropletsIcon:y1,Drum:LX,DrumIcon:LX,Drumstick:DX,DrumstickIcon:DX,Dumbbell:RX,DumbbellIcon:RX,Ear:FX,EarIcon:FX,EarOff:OX,EarOffIcon:OX,Earth:v3,EarthIcon:v3,EarthLock:BX,EarthLockIcon:BX,Eclipse:zX,EclipseIcon:zX,Edit:ou,Edit2:Wb,Edit2Icon:Wb,Edit3:Gb,Edit3Icon:Gb,EditIcon:ou,Egg:DI,EggFried:$X,EggFriedIcon:$X,EggIcon:DI,EggOff:UX,EggOffIcon:UX,Ellipsis:Jx,EllipsisIcon:Jx,EllipsisVertical:Ay,EllipsisVerticalIcon:Ay,Equal:HX,EqualApproximately:qX,EqualApproximatelyIcon:qX,EqualIcon:HX,EqualNot:VX,EqualNotIcon:VX,EqualSquare:P5,EqualSquareIcon:P5,Eraser:GX,EraserIcon:GX,EthernetPort:WX,EthernetPortIcon:WX,Euro:KX,EuroIcon:KX,Expand:YX,ExpandIcon:YX,ExternalLink:gn,ExternalLinkIcon:gn,Eye:Bn,EyeClosed:ZX,EyeClosedIcon:ZX,EyeIcon:Bn,EyeOff:$f,EyeOffIcon:$f,Facebook:fh,FacebookIcon:fh,Factory:XX,FactoryIcon:XX,Fan:QX,FanIcon:QX,FastForward:JX,FastForwardIcon:JX,Feather:eQ,FeatherIcon:eQ,Fence:tQ,FenceIcon:tQ,FerrisWheel:sQ,FerrisWheelIcon:sQ,Figma:rQ,FigmaIcon:rQ,File:RI,FileArchive:nQ,FileArchiveIcon:nQ,FileAudio:iQ,FileAudio2:aQ,FileAudio2Icon:aQ,FileAudioIcon:iQ,FileAxis3D:b3,FileAxis3DIcon:b3,FileAxis3d:b3,FileAxis3dIcon:b3,FileBadge:lQ,FileBadge2:oQ,FileBadge2Icon:oQ,FileBadgeIcon:lQ,FileBarChart:_3,FileBarChart2:w3,FileBarChart2Icon:w3,FileBarChartIcon:_3,FileBox:cQ,FileBoxIcon:cQ,FileChartColumn:w3,FileChartColumnIcon:w3,FileChartColumnIncreasing:_3,FileChartColumnIncreasingIcon:_3,FileChartLine:j3,FileChartLineIcon:j3,FileChartPie:N3,FileChartPieIcon:N3,FileCheck:oF,FileCheck2:dQ,FileCheck2Icon:dQ,FileCheckIcon:oF,FileClock:uQ,FileClockIcon:uQ,FileCode:mQ,FileCode2:hQ,FileCode2Icon:hQ,FileCodeIcon:mQ,FileCog:k3,FileCog2:k3,FileCog2Icon:k3,FileCogIcon:k3,FileDiff:fQ,FileDiffIcon:fQ,FileDigit:pQ,FileDigitIcon:pQ,FileDown:yE,FileDownIcon:yE,FileEdit:C3,FileEditIcon:C3,FileHeart:gQ,FileHeartIcon:gQ,FileIcon:RI,FileImage:z2,FileImageIcon:z2,FileInput:xQ,FileInputIcon:xQ,FileJson:vQ,FileJson2:yQ,FileJson2Icon:yQ,FileJsonIcon:vQ,FileKey:_Q,FileKey2:bQ,FileKey2Icon:bQ,FileKeyIcon:_Q,FileLineChart:j3,FileLineChartIcon:j3,FileLock:jQ,FileLock2:wQ,FileLock2Icon:wQ,FileLockIcon:jQ,FileMinus:kQ,FileMinus2:NQ,FileMinus2Icon:NQ,FileMinusIcon:kQ,FileMusic:SQ,FileMusicIcon:SQ,FileOutput:CQ,FileOutputIcon:CQ,FilePen:C3,FilePenIcon:C3,FilePenLine:S3,FilePenLineIcon:S3,FilePieChart:N3,FilePieChartIcon:N3,FilePlus:EQ,FilePlus2:TQ,FilePlus2Icon:TQ,FilePlusIcon:EQ,FileQuestion:AQ,FileQuestionIcon:AQ,FileScan:MQ,FileScanIcon:MQ,FileSearch:PQ,FileSearch2:IQ,FileSearch2Icon:IQ,FileSearchIcon:PQ,FileSignature:S3,FileSignatureIcon:S3,FileSliders:LQ,FileSlidersIcon:LQ,FileSpreadsheet:$2,FileSpreadsheetIcon:$2,FileStack:lF,FileStackIcon:lF,FileSymlink:DQ,FileSymlinkIcon:DQ,FileTerminal:RQ,FileTerminalIcon:RQ,FileText:kn,FileTextIcon:kn,FileType:FQ,FileType2:OQ,FileType2Icon:OQ,FileTypeIcon:FQ,FileUp:BQ,FileUpIcon:BQ,FileUser:zQ,FileUserIcon:zQ,FileVideo:cF,FileVideo2:$Q,FileVideo2Icon:$Q,FileVideoIcon:cF,FileVolume:qQ,FileVolume2:UQ,FileVolume2Icon:UQ,FileVolumeIcon:qQ,FileWarning:VQ,FileWarningIcon:VQ,FileX:GQ,FileX2:HQ,FileX2Icon:HQ,FileXIcon:GQ,Files:WQ,FilesIcon:WQ,Film:Qm,FilmIcon:Qm,Filter:v1,FilterIcon:v1,FilterX:KQ,FilterXIcon:KQ,Fingerprint:YQ,FingerprintIcon:YQ,FireExtinguisher:ZQ,FireExtinguisherIcon:ZQ,Fish:JQ,FishIcon:JQ,FishOff:XQ,FishOffIcon:XQ,FishSymbol:QQ,FishSymbolIcon:QQ,Flag:U2,FlagIcon:U2,FlagOff:eJ,FlagOffIcon:eJ,FlagTriangleLeft:tJ,FlagTriangleLeftIcon:tJ,FlagTriangleRight:sJ,FlagTriangleRightIcon:sJ,Flame:od,FlameIcon:od,FlameKindling:rJ,FlameKindlingIcon:rJ,Flashlight:aJ,FlashlightIcon:aJ,FlashlightOff:nJ,FlashlightOffIcon:nJ,FlaskConical:Bk,FlaskConicalIcon:Bk,FlaskConicalOff:iJ,FlaskConicalOffIcon:iJ,FlaskRound:oJ,FlaskRoundIcon:oJ,FlipHorizontal:dF,FlipHorizontal2:lJ,FlipHorizontal2Icon:lJ,FlipHorizontalIcon:dF,FlipVertical:dJ,FlipVertical2:cJ,FlipVertical2Icon:cJ,FlipVerticalIcon:dJ,Flower:uJ,Flower2:u1,Flower2Icon:u1,FlowerIcon:uJ,Focus:hJ,FocusIcon:hJ,FoldHorizontal:mJ,FoldHorizontalIcon:mJ,FoldVertical:fJ,FoldVerticalIcon:fJ,Folder:$J,FolderArchive:pJ,FolderArchiveIcon:pJ,FolderCheck:gJ,FolderCheckIcon:gJ,FolderClock:xJ,FolderClockIcon:xJ,FolderClosed:yJ,FolderClosedIcon:yJ,FolderCode:vJ,FolderCodeIcon:vJ,FolderCog:T3,FolderCog2:T3,FolderCog2Icon:T3,FolderCogIcon:T3,FolderDot:bJ,FolderDotIcon:bJ,FolderDown:_J,FolderDownIcon:_J,FolderEdit:E3,FolderEditIcon:E3,FolderGit:jJ,FolderGit2:wJ,FolderGit2Icon:wJ,FolderGitIcon:jJ,FolderHeart:NJ,FolderHeartIcon:NJ,FolderIcon:$J,FolderInput:kJ,FolderInputIcon:kJ,FolderKanban:SJ,FolderKanbanIcon:SJ,FolderKey:CJ,FolderKeyIcon:CJ,FolderLock:TJ,FolderLockIcon:TJ,FolderMinus:EJ,FolderMinusIcon:EJ,FolderOpen:Uf,FolderOpenDot:AJ,FolderOpenDotIcon:AJ,FolderOpenIcon:Uf,FolderOutput:MJ,FolderOutputIcon:MJ,FolderPen:E3,FolderPenIcon:E3,FolderPlus:IJ,FolderPlusIcon:IJ,FolderRoot:PJ,FolderRootIcon:PJ,FolderSearch:DJ,FolderSearch2:LJ,FolderSearch2Icon:LJ,FolderSearchIcon:DJ,FolderSymlink:RJ,FolderSymlinkIcon:RJ,FolderSync:OJ,FolderSyncIcon:OJ,FolderTree:FJ,FolderTreeIcon:FJ,FolderUp:BJ,FolderUpIcon:BJ,FolderX:zJ,FolderXIcon:zJ,Folders:UJ,FoldersIcon:UJ,Footprints:qJ,FootprintsIcon:qJ,ForkKnife:yT,ForkKnifeCrossed:xT,ForkKnifeCrossedIcon:xT,ForkKnifeIcon:yT,Forklift:VJ,ForkliftIcon:VJ,FormInput:J3,FormInputIcon:J3,Forward:HJ,ForwardIcon:HJ,Frame:GJ,FrameIcon:GJ,Framer:WJ,FramerIcon:WJ,Frown:KJ,FrownIcon:KJ,Fuel:YJ,FuelIcon:YJ,Fullscreen:ZJ,FullscreenIcon:ZJ,FunctionSquare:L5,FunctionSquareIcon:L5,GalleryHorizontal:QJ,GalleryHorizontalEnd:XJ,GalleryHorizontalEndIcon:XJ,GalleryHorizontalIcon:QJ,GalleryThumbnails:JJ,GalleryThumbnailsIcon:JJ,GalleryVertical:tee,GalleryVerticalEnd:eee,GalleryVerticalEndIcon:eee,GalleryVerticalIcon:tee,Gamepad:ree,Gamepad2:see,Gamepad2Icon:see,GamepadIcon:ree,GanttChart:OC,GanttChartIcon:OC,GanttChartSquare:Pb,GanttChartSquareIcon:Pb,Gauge:nee,GaugeCircle:JC,GaugeCircleIcon:JC,GaugeIcon:nee,Gavel:aee,GavelIcon:aee,Gem:iee,GemIcon:iee,Ghost:vE,GhostIcon:vE,Gift:Di,GiftIcon:Di,GitBranch:lee,GitBranchIcon:lee,GitBranchPlus:oee,GitBranchPlusIcon:oee,GitCommit:A3,GitCommitHorizontal:A3,GitCommitHorizontalIcon:A3,GitCommitIcon:A3,GitCommitVertical:cee,GitCommitVerticalIcon:cee,GitCompare:uee,GitCompareArrows:dee,GitCompareArrowsIcon:dee,GitCompareIcon:uee,GitFork:hee,GitForkIcon:hee,GitGraph:mee,GitGraphIcon:mee,GitMerge:fee,GitMergeIcon:fee,GitPullRequest:bee,GitPullRequestArrow:pee,GitPullRequestArrowIcon:pee,GitPullRequestClosed:gee,GitPullRequestClosedIcon:gee,GitPullRequestCreate:yee,GitPullRequestCreateArrow:xee,GitPullRequestCreateArrowIcon:xee,GitPullRequestCreateIcon:yee,GitPullRequestDraft:vee,GitPullRequestDraftIcon:vee,GitPullRequestIcon:bee,Github:_ee,GithubIcon:_ee,Gitlab:wee,GitlabIcon:wee,GlassWater:jee,GlassWaterIcon:jee,Glasses:Nee,GlassesIcon:Nee,Globe:ld,Globe2:v3,Globe2Icon:v3,GlobeIcon:ld,GlobeLock:kee,GlobeLockIcon:kee,Goal:See,GoalIcon:See,Grab:Cee,GrabIcon:Cee,GraduationCap:Vu,GraduationCapIcon:Vu,Grape:Tee,GrapeIcon:Tee,Grid:by,Grid2X2:I3,Grid2X2Icon:I3,Grid2X2Plus:M3,Grid2X2PlusIcon:M3,Grid2x2:I3,Grid2x2Check:Eee,Grid2x2CheckIcon:Eee,Grid2x2Icon:I3,Grid2x2Plus:M3,Grid2x2PlusIcon:M3,Grid2x2X:Aee,Grid2x2XIcon:Aee,Grid3X3:by,Grid3X3Icon:by,Grid3x3:by,Grid3x3Icon:by,GridIcon:by,Grip:Iee,GripHorizontal:Mee,GripHorizontalIcon:Mee,GripIcon:Iee,GripVertical:Oh,GripVerticalIcon:Oh,Group:Pee,GroupIcon:Pee,Guitar:Lee,GuitarIcon:Lee,Ham:Dee,HamIcon:Dee,Hammer:uF,HammerIcon:uF,Hand:hF,HandCoins:Ree,HandCoinsIcon:Ree,HandHeart:Oee,HandHeartIcon:Oee,HandHelping:i1,HandHelpingIcon:i1,HandIcon:hF,HandMetal:Fee,HandMetalIcon:Fee,HandPlatter:Bee,HandPlatterIcon:Bee,Handshake:zk,HandshakeIcon:zk,HardDrive:mF,HardDriveDownload:zee,HardDriveDownloadIcon:zee,HardDriveIcon:mF,HardDriveUpload:$ee,HardDriveUploadIcon:$ee,HardHat:Uee,HardHatIcon:Uee,Hash:$k,HashIcon:$k,Haze:qee,HazeIcon:qee,HdmiPort:Vee,HdmiPortIcon:Vee,Heading:Kee,Heading1:OI,Heading1Icon:OI,Heading2:FI,Heading2Icon:FI,Heading3:fF,Heading3Icon:fF,Heading4:Hee,Heading4Icon:Hee,Heading5:Gee,Heading5Icon:Gee,Heading6:Wee,Heading6Icon:Wee,HeadingIcon:Kee,HeadphoneOff:Yee,HeadphoneOffIcon:Yee,Headphones:Zee,HeadphonesIcon:Zee,Headset:Xee,HeadsetIcon:Xee,Heart:Bi,HeartCrack:Qee,HeartCrackIcon:Qee,HeartHandshake:Jee,HeartHandshakeIcon:Jee,HeartIcon:Bi,HeartOff:ete,HeartOffIcon:ete,HeartPulse:tte,HeartPulseIcon:tte,Heater:ste,HeaterIcon:ste,HelpCircle:v2,HelpCircleIcon:v2,HelpingHand:i1,HelpingHandIcon:i1,Hexagon:rte,HexagonIcon:rte,Highlighter:nte,HighlighterIcon:nte,History:BI,HistoryIcon:BI,Home:Fn,HomeIcon:Fn,Hop:ite,HopIcon:ite,HopOff:ate,HopOffIcon:ate,Hospital:ote,HospitalIcon:ote,Hotel:lte,HotelIcon:lte,Hourglass:cte,HourglassIcon:cte,House:Fn,HouseIcon:Fn,HousePlug:dte,HousePlugIcon:dte,HousePlus:ute,HousePlusIcon:ute,IceCream:L3,IceCream2:P3,IceCream2Icon:P3,IceCreamBowl:P3,IceCreamBowlIcon:P3,IceCreamCone:L3,IceCreamConeIcon:L3,IceCreamIcon:L3,Icon:AQe,IdCard:hte,IdCardIcon:hte,Image:wl,ImageDown:mte,ImageDownIcon:mte,ImageIcon:wl,ImageMinus:fte,ImageMinusIcon:fte,ImageOff:pte,ImageOffIcon:pte,ImagePlay:gte,ImagePlayIcon:gte,ImagePlus:f_,ImagePlusIcon:f_,ImageUp:xte,ImageUpIcon:xte,ImageUpscale:yte,ImageUpscaleIcon:yte,Images:vte,ImagesIcon:vte,Import:bte,ImportIcon:bte,Inbox:Uk,InboxIcon:Uk,Indent:R3,IndentDecrease:D3,IndentDecreaseIcon:D3,IndentIcon:R3,IndentIncrease:R3,IndentIncreaseIcon:R3,IndianRupee:_te,IndianRupeeIcon:_te,Infinity:wte,InfinityIcon:wte,Info:bE,InfoIcon:bE,Inspect:z5,InspectIcon:z5,InspectionPanel:jte,InspectionPanelIcon:jte,Instagram:yu,InstagramIcon:yu,Italic:qk,ItalicIcon:qk,IterationCcw:Nte,IterationCcwIcon:Nte,IterationCw:kte,IterationCwIcon:kte,JapaneseYen:Ste,JapaneseYenIcon:Ste,Joystick:Cte,JoystickIcon:Cte,Kanban:p_,KanbanIcon:p_,KanbanSquare:D5,KanbanSquareDashed:T5,KanbanSquareDashedIcon:T5,KanbanSquareIcon:D5,Key:dx,KeyIcon:dx,KeyRound:_E,KeyRoundIcon:_E,KeySquare:Tte,KeySquareIcon:Tte,Keyboard:Mte,KeyboardIcon:Mte,KeyboardMusic:Ete,KeyboardMusicIcon:Ete,KeyboardOff:Ate,KeyboardOffIcon:Ate,Lamp:Ote,LampCeiling:Ite,LampCeilingIcon:Ite,LampDesk:Pte,LampDeskIcon:Pte,LampFloor:Lte,LampFloorIcon:Lte,LampIcon:Ote,LampWallDown:Dte,LampWallDownIcon:Dte,LampWallUp:Rte,LampWallUpIcon:Rte,LandPlot:Fte,LandPlotIcon:Fte,Landmark:Bte,LandmarkIcon:Bte,Languages:zte,LanguagesIcon:zte,Laptop:Ute,Laptop2:O3,Laptop2Icon:O3,LaptopIcon:Ute,LaptopMinimal:O3,LaptopMinimalCheck:$te,LaptopMinimalCheckIcon:$te,LaptopMinimalIcon:O3,Lasso:Vte,LassoIcon:Vte,LassoSelect:qte,LassoSelectIcon:qte,Laugh:Hte,LaughIcon:Hte,Layers:pF,Layers2:Gte,Layers2Icon:Gte,Layers3:Wte,Layers3Icon:Wte,LayersIcon:pF,Layout:w2,LayoutDashboard:wE,LayoutDashboardIcon:wE,LayoutGrid:_g,LayoutGridIcon:_g,LayoutIcon:w2,LayoutList:Kte,LayoutListIcon:Kte,LayoutPanelLeft:Yte,LayoutPanelLeftIcon:Yte,LayoutPanelTop:Zte,LayoutPanelTopIcon:Zte,LayoutTemplate:jE,LayoutTemplateIcon:jE,Leaf:Xte,LeafIcon:Xte,LeafyGreen:Qte,LeafyGreenIcon:Qte,Lectern:Jte,LecternIcon:Jte,LetterText:ese,LetterTextIcon:ese,Library:NE,LibraryBig:tse,LibraryBigIcon:tse,LibraryIcon:NE,LibrarySquare:R5,LibrarySquareIcon:R5,LifeBuoy:zI,LifeBuoyIcon:zI,Ligature:sse,LigatureIcon:sse,Lightbulb:q2,LightbulbIcon:q2,LightbulbOff:rse,LightbulbOffIcon:rse,LineChart:LC,LineChartIcon:LC,Link:Jo,Link2:ql,Link2Icon:ql,Link2Off:nse,Link2OffIcon:nse,LinkIcon:Jo,Linkedin:qf,LinkedinIcon:qf,List:Vf,ListCheck:ase,ListCheckIcon:ase,ListChecks:V2,ListChecksIcon:V2,ListCollapse:ise,ListCollapseIcon:ise,ListEnd:ose,ListEndIcon:ose,ListFilter:gF,ListFilterIcon:gF,ListIcon:Vf,ListMinus:lse,ListMinusIcon:lse,ListMusic:cse,ListMusicIcon:cse,ListOrdered:b1,ListOrderedIcon:b1,ListPlus:dse,ListPlusIcon:dse,ListRestart:use,ListRestartIcon:use,ListStart:hse,ListStartIcon:hse,ListTodo:mse,ListTodoIcon:mse,ListTree:fse,ListTreeIcon:fse,ListVideo:pse,ListVideoIcon:pse,ListX:gse,ListXIcon:gse,Loader:yse,Loader2:is,Loader2Icon:is,LoaderCircle:is,LoaderCircleIcon:is,LoaderIcon:yse,LoaderPinwheel:xse,LoaderPinwheelIcon:xse,Locate:$I,LocateFixed:vse,LocateFixedIcon:vse,LocateIcon:$I,LocateOff:bse,LocateOffIcon:bse,Lock:Td,LockIcon:Td,LockKeyhole:_se,LockKeyholeIcon:_se,LockKeyholeOpen:F3,LockKeyholeOpenIcon:F3,LockOpen:B3,LockOpenIcon:B3,LogIn:kE,LogInIcon:kE,LogOut:UI,LogOutIcon:UI,Logs:wse,LogsIcon:wse,Lollipop:jse,LollipopIcon:jse,LucideAArrowDown:BV,LucideAArrowUp:zV,LucideALargeSmall:$V,LucideAccessibility:UV,LucideActivity:ef,LucideActivitySquare:o5,LucideAirVent:qV,LucideAirplay:VV,LucideAlarmCheck:hC,LucideAlarmClock:GV,LucideAlarmClockCheck:hC,LucideAlarmClockMinus:mC,LucideAlarmClockOff:HV,LucideAlarmClockPlus:fC,LucideAlarmMinus:mC,LucideAlarmPlus:fC,LucideAlarmSmoke:WV,LucideAlbum:KV,LucideAlertCircle:wo,LucideAlertOctagon:_2,LucideAlertTriangle:uu,LucideAlignCenter:dE,LucideAlignCenterHorizontal:YV,LucideAlignCenterVertical:ZV,LucideAlignEndHorizontal:XV,LucideAlignEndVertical:QV,LucideAlignHorizontalDistributeCenter:JV,LucideAlignHorizontalDistributeEnd:eH,LucideAlignHorizontalDistributeStart:tH,LucideAlignHorizontalJustifyCenter:sH,LucideAlignHorizontalJustifyEnd:rH,LucideAlignHorizontalJustifyStart:nH,LucideAlignHorizontalSpaceAround:aH,LucideAlignHorizontalSpaceBetween:iH,LucideAlignJustify:oH,LucideAlignLeft:uE,LucideAlignRight:hE,LucideAlignStartHorizontal:lH,LucideAlignStartVertical:cH,LucideAlignVerticalDistributeCenter:dH,LucideAlignVerticalDistributeEnd:uH,LucideAlignVerticalDistributeStart:hH,LucideAlignVerticalJustifyCenter:mH,LucideAlignVerticalJustifyEnd:fH,LucideAlignVerticalJustifyStart:pH,LucideAlignVerticalSpaceAround:gH,LucideAlignVerticalSpaceBetween:xH,LucideAmbulance:yH,LucideAmpersand:vH,LucideAmpersands:bH,LucideAmphora:_H,LucideAnchor:wH,LucideAngry:jH,LucideAnnoyed:NH,LucideAntenna:kH,LucideAnvil:SH,LucideAperture:CH,LucideAppWindow:KO,LucideAppWindowMac:TH,LucideApple:EH,LucideArchive:Rk,LucideArchiveRestore:AI,LucideArchiveX:AH,LucideAreaChart:TC,LucideArmchair:MH,LucideArrowBigDown:PH,LucideArrowBigDownDash:IH,LucideArrowBigLeft:DH,LucideArrowBigLeftDash:LH,LucideArrowBigRight:OH,LucideArrowBigRightDash:RH,LucideArrowBigUp:BH,LucideArrowBigUpDash:FH,LucideArrowDown:fm,LucideArrowDown01:zH,LucideArrowDown10:$H,LucideArrowDownAZ:pC,LucideArrowDownAz:pC,LucideArrowDownCircle:zC,LucideArrowDownFromLine:UH,LucideArrowDownLeft:qH,LucideArrowDownLeftFromCircle:UC,LucideArrowDownLeftFromSquare:h5,LucideArrowDownLeftSquare:l5,LucideArrowDownNarrowWide:VH,LucideArrowDownRight:YO,LucideArrowDownRightFromCircle:qC,LucideArrowDownRightFromSquare:m5,LucideArrowDownRightSquare:c5,LucideArrowDownSquare:d5,LucideArrowDownToDot:HH,LucideArrowDownToLine:GH,LucideArrowDownUp:WH,LucideArrowDownWideNarrow:gC,LucideArrowDownZA:xC,LucideArrowDownZa:xC,LucideArrowLeft:za,LucideArrowLeftCircle:$C,LucideArrowLeftFromLine:KH,LucideArrowLeftRight:YH,LucideArrowLeftSquare:u5,LucideArrowLeftToLine:ZH,LucideArrowRight:bi,LucideArrowRightCircle:GC,LucideArrowRightFromLine:XH,LucideArrowRightLeft:F2,LucideArrowRightSquare:g5,LucideArrowRightToLine:QH,LucideArrowUp:Hu,LucideArrowUp01:JH,LucideArrowUp10:eG,LucideArrowUpAZ:yC,LucideArrowUpAz:yC,LucideArrowUpCircle:WC,LucideArrowUpDown:qu,LucideArrowUpFromDot:tG,LucideArrowUpFromLine:sG,LucideArrowUpLeft:rG,LucideArrowUpLeftFromCircle:VC,LucideArrowUpLeftFromSquare:f5,LucideArrowUpLeftSquare:x5,LucideArrowUpNarrowWide:vC,LucideArrowUpRight:ZO,LucideArrowUpRightFromCircle:HC,LucideArrowUpRightFromSquare:p5,LucideArrowUpRightSquare:y5,LucideArrowUpSquare:v5,LucideArrowUpToLine:nG,LucideArrowUpWideNarrow:aG,LucideArrowUpZA:bC,LucideArrowUpZa:bC,LucideArrowsUpFromLine:iG,LucideAsterisk:oG,LucideAsteriskSquare:b5,LucideAtSign:lG,LucideAtom:cG,LucideAudioLines:dG,LucideAudioWaveform:uG,LucideAward:Bc,LucideAxe:hG,LucideAxis3D:_C,LucideAxis3d:_C,LucideBaby:mG,LucideBackpack:fG,LucideBadge:AG,LucideBadgeAlert:pG,LucideBadgeCent:gG,LucideBadgeCheck:wC,LucideBadgeDollarSign:xG,LucideBadgeEuro:yG,LucideBadgeHelp:vG,LucideBadgeIndianRupee:bG,LucideBadgeInfo:_G,LucideBadgeJapaneseYen:wG,LucideBadgeMinus:jG,LucideBadgePercent:NG,LucideBadgePlus:kG,LucideBadgePoundSterling:SG,LucideBadgeRussianRuble:CG,LucideBadgeSwissFranc:TG,LucideBadgeX:EG,LucideBaggageClaim:MG,LucideBan:XO,LucideBanana:IG,LucideBandage:PG,LucideBanknote:LG,LucideBarChart:DC,LucideBarChart2:RC,LucideBarChart3:Bo,LucideBarChart4:PC,LucideBarChartBig:IC,LucideBarChartHorizontal:AC,LucideBarChartHorizontalBig:EC,LucideBarcode:DG,LucideBaseline:RG,LucideBath:_p,LucideBattery:UG,LucideBatteryCharging:OG,LucideBatteryFull:FG,LucideBatteryLow:BG,LucideBatteryMedium:zG,LucideBatteryWarning:$G,LucideBeaker:qG,LucideBean:HG,LucideBeanOff:VG,LucideBed:x1,LucideBedDouble:B2,LucideBedSingle:GG,LucideBeef:WG,LucideBeer:YG,LucideBeerOff:KG,LucideBell:wp,LucideBellDot:ZG,LucideBellElectric:XG,LucideBellMinus:QG,LucideBellOff:u_,LucideBellPlus:JG,LucideBellRing:QO,LucideBetweenHorizonalEnd:jC,LucideBetweenHorizonalStart:NC,LucideBetweenHorizontalEnd:jC,LucideBetweenHorizontalStart:NC,LucideBetweenVerticalEnd:eW,LucideBetweenVerticalStart:tW,LucideBicepsFlexed:sW,LucideBike:rW,LucideBinary:nW,LucideBinoculars:aW,LucideBiohazard:iW,LucideBird:oW,LucideBitcoin:lW,LucideBlend:cW,LucideBlinds:dW,LucideBlocks:uW,LucideBluetooth:pW,LucideBluetoothConnected:hW,LucideBluetoothOff:mW,LucideBluetoothSearching:fW,LucideBold:Ok,LucideBolt:gW,LucideBomb:xW,LucideBone:yW,LucideBook:zW,LucideBookA:vW,LucideBookAudio:bW,LucideBookCheck:_W,LucideBookCopy:wW,LucideBookDashed:kC,LucideBookDown:jW,LucideBookHeadphones:NW,LucideBookHeart:kW,LucideBookImage:SW,LucideBookKey:CW,LucideBookLock:TW,LucideBookMarked:EW,LucideBookMinus:AW,LucideBookOpen:tf,LucideBookOpenCheck:MW,LucideBookOpenText:IW,LucideBookPlus:PW,LucideBookTemplate:kC,LucideBookText:LW,LucideBookType:DW,LucideBookUp:OW,LucideBookUp2:RW,LucideBookUser:FW,LucideBookX:BW,LucideBookmark:Uy,LucideBookmarkCheck:$W,LucideBookmarkMinus:UW,LucideBookmarkPlus:JO,LucideBookmarkX:qW,LucideBoomBox:VW,LucideBot:MI,LucideBotMessageSquare:HW,LucideBotOff:GW,LucideBox:WW,LucideBoxSelect:A5,LucideBoxes:KW,LucideBraces:SC,LucideBrackets:YW,LucideBrain:eF,LucideBrainCircuit:ZW,LucideBrainCog:XW,LucideBrickWall:QW,LucideBriefcase:pm,LucideBriefcaseBusiness:JW,LucideBriefcaseConveyorBelt:eK,LucideBriefcaseMedical:tK,LucideBringToFront:sK,LucideBrush:rK,LucideBug:iK,LucideBugOff:nK,LucideBugPlay:aK,LucideBuilding:mE,LucideBuilding2:Xa,LucideBus:lK,LucideBusFront:oK,LucideCable:dK,LucideCableCar:cK,LucideCake:gm,LucideCakeSlice:uK,LucideCalculator:II,LucideCalendar:Nn,LucideCalendar1:hK,LucideCalendarArrowDown:mK,LucideCalendarArrowUp:fK,LucideCalendarCheck:tF,LucideCalendarCheck2:pK,LucideCalendarClock:h_,LucideCalendarCog:gK,LucideCalendarDays:xu,LucideCalendarFold:xK,LucideCalendarHeart:sF,LucideCalendarMinus:vK,LucideCalendarMinus2:yK,LucideCalendarOff:rF,LucideCalendarPlus:A2,LucideCalendarPlus2:bK,LucideCalendarRange:_K,LucideCalendarSearch:wK,LucideCalendarSync:jK,LucideCalendarX:kK,LucideCalendarX2:NK,LucideCamera:lx,LucideCameraOff:SK,LucideCandlestickChart:MC,LucideCandy:EK,LucideCandyCane:CK,LucideCandyOff:TK,LucideCannabis:AK,LucideCaptions:CC,LucideCaptionsOff:MK,LucideCar:LK,LucideCarFront:IK,LucideCarTaxiFront:PK,LucideCaravan:DK,LucideCarrot:RK,LucideCaseLower:OK,LucideCaseSensitive:FK,LucideCaseUpper:BK,LucideCassetteTape:zK,LucideCast:$K,LucideCastle:UK,LucideCat:qK,LucideCctv:VK,LucideChartArea:TC,LucideChartBar:AC,LucideChartBarBig:EC,LucideChartBarDecreasing:HK,LucideChartBarIncreasing:GK,LucideChartBarStacked:WK,LucideChartCandlestick:MC,LucideChartColumn:Bo,LucideChartColumnBig:IC,LucideChartColumnDecreasing:KK,LucideChartColumnIncreasing:PC,LucideChartColumnStacked:YK,LucideChartGantt:ZK,LucideChartLine:LC,LucideChartNetwork:XK,LucideChartNoAxesColumn:RC,LucideChartNoAxesColumnDecreasing:QK,LucideChartNoAxesColumnIncreasing:DC,LucideChartNoAxesCombined:JK,LucideChartNoAxesGantt:OC,LucideChartPie:FC,LucideChartScatter:BC,LucideChartSpline:eY,LucideCheck:va,LucideCheckCheck:nF,LucideCheckCircle:zi,LucideCheckCircle2:ea,LucideCheckSquare:j2,LucideCheckSquare2:w5,LucideChefHat:tY,LucideCherry:sY,LucideChevronDown:Io,LucideChevronDownCircle:KC,LucideChevronDownSquare:j5,LucideChevronFirst:rY,LucideChevronLast:nY,LucideChevronLeft:fl,LucideChevronLeftCircle:YC,LucideChevronLeftSquare:N5,LucideChevronRight:$a,LucideChevronRightCircle:ZC,LucideChevronRightSquare:k5,LucideChevronUp:cx,LucideChevronUpCircle:XC,LucideChevronUpSquare:S5,LucideChevronsDown:iY,LucideChevronsDownUp:aY,LucideChevronsLeft:cY,LucideChevronsLeftRight:lY,LucideChevronsLeftRightEllipsis:oY,LucideChevronsRight:uY,LucideChevronsRightLeft:dY,LucideChevronsUp:hY,LucideChevronsUpDown:d0,LucideChrome:fE,LucideChurch:mY,LucideCigarette:pY,LucideCigaretteOff:fY,LucideCircle:Gu,LucideCircleAlert:wo,LucideCircleArrowDown:zC,LucideCircleArrowLeft:$C,LucideCircleArrowOutDownLeft:UC,LucideCircleArrowOutDownRight:qC,LucideCircleArrowOutUpLeft:VC,LucideCircleArrowOutUpRight:HC,LucideCircleArrowRight:GC,LucideCircleArrowUp:WC,LucideCircleCheck:ea,LucideCircleCheckBig:zi,LucideCircleChevronDown:KC,LucideCircleChevronLeft:YC,LucideCircleChevronRight:ZC,LucideCircleChevronUp:XC,LucideCircleDashed:gY,LucideCircleDivide:QC,LucideCircleDollarSign:xY,LucideCircleDot:vY,LucideCircleDotDashed:yY,LucideCircleEllipsis:bY,LucideCircleEqual:_Y,LucideCircleFadingArrowUp:wY,LucideCircleFadingPlus:jY,LucideCircleGauge:JC,LucideCircleHelp:v2,LucideCircleMinus:e3,LucideCircleOff:NY,LucideCircleParking:s3,LucideCircleParkingOff:t3,LucideCirclePause:r3,LucideCirclePercent:n3,LucideCirclePlay:cg,LucideCirclePlus:a3,LucideCirclePower:i3,LucideCircleSlash:kY,LucideCircleSlash2:o3,LucideCircleSlashed:o3,LucideCircleStop:l3,LucideCircleUser:d3,LucideCircleUserRound:c3,LucideCircleX:kd,LucideCircuitBoard:SY,LucideCitrus:CY,LucideClapperboard:TY,LucideClipboard:DY,LucideClipboardCheck:PI,LucideClipboardCopy:EY,LucideClipboardEdit:h3,LucideClipboardList:Fk,LucideClipboardMinus:AY,LucideClipboardPaste:MY,LucideClipboardPen:h3,LucideClipboardPenLine:u3,LucideClipboardPlus:IY,LucideClipboardSignature:u3,LucideClipboardType:PY,LucideClipboardX:LY,LucideClock:Pn,LucideClock1:RY,LucideClock10:OY,LucideClock11:FY,LucideClock12:BY,LucideClock2:zY,LucideClock3:$Y,LucideClock4:UY,LucideClock5:qY,LucideClock6:VY,LucideClock7:HY,LucideClock8:GY,LucideClock9:WY,LucideClockAlert:KY,LucideClockArrowDown:YY,LucideClockArrowUp:ZY,LucideCloud:uZ,LucideCloudAlert:XY,LucideCloudCog:QY,LucideCloudDownload:m3,LucideCloudDrizzle:JY,LucideCloudFog:eZ,LucideCloudHail:tZ,LucideCloudLightning:sZ,LucideCloudMoon:nZ,LucideCloudMoonRain:rZ,LucideCloudOff:aZ,LucideCloudRain:oZ,LucideCloudRainWind:iZ,LucideCloudSnow:lZ,LucideCloudSun:dZ,LucideCloudSunRain:cZ,LucideCloudUpload:f3,LucideCloudy:hZ,LucideClover:M2,LucideClub:mZ,LucideCode:pE,LucideCode2:b2,LucideCodeSquare:C5,LucideCodeXml:b2,LucideCodepen:fZ,LucideCodesandbox:pZ,LucideCoffee:gE,LucideCog:gZ,LucideCoins:aF,LucideColumns:p3,LucideColumns2:p3,LucideColumns3:g3,LucideColumns4:xZ,LucideCombine:yZ,LucideCommand:vZ,LucideCompass:LI,LucideComponent:bZ,LucideComputer:_Z,LucideConciergeBell:wZ,LucideCone:jZ,LucideConstruction:NZ,LucideContact:xE,LucideContact2:x3,LucideContactRound:x3,LucideContainer:kZ,LucideContrast:SZ,LucideCookie:CZ,LucideCookingPot:TZ,LucideCopy:ui,LucideCopyCheck:EZ,LucideCopyMinus:AZ,LucideCopyPlus:MZ,LucideCopySlash:IZ,LucideCopyX:PZ,LucideCopyleft:LZ,LucideCopyright:DZ,LucideCornerDownLeft:RZ,LucideCornerDownRight:OZ,LucideCornerLeftDown:FZ,LucideCornerLeftUp:BZ,LucideCornerRightDown:zZ,LucideCornerRightUp:$Z,LucideCornerUpLeft:UZ,LucideCornerUpRight:qZ,LucideCpu:VZ,LucideCreativeCommons:HZ,LucideCreditCard:u0,LucideCroissant:GZ,LucideCrop:WZ,LucideCross:KZ,LucideCrosshair:YZ,LucideCrown:zf,LucideCuboid:ZZ,LucideCupSoda:XZ,LucideCurlyBraces:SC,LucideCurrency:QZ,LucideCylinder:JZ,LucideDam:eX,LucideDatabase:iF,LucideDatabaseBackup:tX,LucideDatabaseZap:sX,LucideDelete:rX,LucideDessert:nX,LucideDiameter:aX,LucideDiamond:lX,LucideDiamondMinus:iX,LucideDiamondPercent:y3,LucideDiamondPlus:oX,LucideDice1:cX,LucideDice2:dX,LucideDice3:uX,LucideDice4:hX,LucideDice5:mX,LucideDice6:fX,LucideDices:pX,LucideDiff:gX,LucideDisc:bX,LucideDisc2:xX,LucideDisc3:yX,LucideDiscAlbum:vX,LucideDivide:_X,LucideDivideCircle:QC,LucideDivideSquare:M5,LucideDna:jX,LucideDnaOff:wX,LucideDock:NX,LucideDog:kX,LucideDollarSign:oc,LucideDonut:SX,LucideDoorClosed:CX,LucideDoorOpen:m_,LucideDot:TX,LucideDotSquare:I5,LucideDownload:hi,LucideDownloadCloud:m3,LucideDraftingCompass:EX,LucideDrama:AX,LucideDribbble:MX,LucideDrill:IX,LucideDroplet:PX,LucideDroplets:y1,LucideDrum:LX,LucideDrumstick:DX,LucideDumbbell:RX,LucideEar:FX,LucideEarOff:OX,LucideEarth:v3,LucideEarthLock:BX,LucideEclipse:zX,LucideEdit:ou,LucideEdit2:Wb,LucideEdit3:Gb,LucideEgg:DI,LucideEggFried:$X,LucideEggOff:UX,LucideEllipsis:Jx,LucideEllipsisVertical:Ay,LucideEqual:HX,LucideEqualApproximately:qX,LucideEqualNot:VX,LucideEqualSquare:P5,LucideEraser:GX,LucideEthernetPort:WX,LucideEuro:KX,LucideExpand:YX,LucideExternalLink:gn,LucideEye:Bn,LucideEyeClosed:ZX,LucideEyeOff:$f,LucideFacebook:fh,LucideFactory:XX,LucideFan:QX,LucideFastForward:JX,LucideFeather:eQ,LucideFence:tQ,LucideFerrisWheel:sQ,LucideFigma:rQ,LucideFile:RI,LucideFileArchive:nQ,LucideFileAudio:iQ,LucideFileAudio2:aQ,LucideFileAxis3D:b3,LucideFileAxis3d:b3,LucideFileBadge:lQ,LucideFileBadge2:oQ,LucideFileBarChart:_3,LucideFileBarChart2:w3,LucideFileBox:cQ,LucideFileChartColumn:w3,LucideFileChartColumnIncreasing:_3,LucideFileChartLine:j3,LucideFileChartPie:N3,LucideFileCheck:oF,LucideFileCheck2:dQ,LucideFileClock:uQ,LucideFileCode:mQ,LucideFileCode2:hQ,LucideFileCog:k3,LucideFileCog2:k3,LucideFileDiff:fQ,LucideFileDigit:pQ,LucideFileDown:yE,LucideFileEdit:C3,LucideFileHeart:gQ,LucideFileImage:z2,LucideFileInput:xQ,LucideFileJson:vQ,LucideFileJson2:yQ,LucideFileKey:_Q,LucideFileKey2:bQ,LucideFileLineChart:j3,LucideFileLock:jQ,LucideFileLock2:wQ,LucideFileMinus:kQ,LucideFileMinus2:NQ,LucideFileMusic:SQ,LucideFileOutput:CQ,LucideFilePen:C3,LucideFilePenLine:S3,LucideFilePieChart:N3,LucideFilePlus:EQ,LucideFilePlus2:TQ,LucideFileQuestion:AQ,LucideFileScan:MQ,LucideFileSearch:PQ,LucideFileSearch2:IQ,LucideFileSignature:S3,LucideFileSliders:LQ,LucideFileSpreadsheet:$2,LucideFileStack:lF,LucideFileSymlink:DQ,LucideFileTerminal:RQ,LucideFileText:kn,LucideFileType:FQ,LucideFileType2:OQ,LucideFileUp:BQ,LucideFileUser:zQ,LucideFileVideo:cF,LucideFileVideo2:$Q,LucideFileVolume:qQ,LucideFileVolume2:UQ,LucideFileWarning:VQ,LucideFileX:GQ,LucideFileX2:HQ,LucideFiles:WQ,LucideFilm:Qm,LucideFilter:v1,LucideFilterX:KQ,LucideFingerprint:YQ,LucideFireExtinguisher:ZQ,LucideFish:JQ,LucideFishOff:XQ,LucideFishSymbol:QQ,LucideFlag:U2,LucideFlagOff:eJ,LucideFlagTriangleLeft:tJ,LucideFlagTriangleRight:sJ,LucideFlame:od,LucideFlameKindling:rJ,LucideFlashlight:aJ,LucideFlashlightOff:nJ,LucideFlaskConical:Bk,LucideFlaskConicalOff:iJ,LucideFlaskRound:oJ,LucideFlipHorizontal:dF,LucideFlipHorizontal2:lJ,LucideFlipVertical:dJ,LucideFlipVertical2:cJ,LucideFlower:uJ,LucideFlower2:u1,LucideFocus:hJ,LucideFoldHorizontal:mJ,LucideFoldVertical:fJ,LucideFolder:$J,LucideFolderArchive:pJ,LucideFolderCheck:gJ,LucideFolderClock:xJ,LucideFolderClosed:yJ,LucideFolderCode:vJ,LucideFolderCog:T3,LucideFolderCog2:T3,LucideFolderDot:bJ,LucideFolderDown:_J,LucideFolderEdit:E3,LucideFolderGit:jJ,LucideFolderGit2:wJ,LucideFolderHeart:NJ,LucideFolderInput:kJ,LucideFolderKanban:SJ,LucideFolderKey:CJ,LucideFolderLock:TJ,LucideFolderMinus:EJ,LucideFolderOpen:Uf,LucideFolderOpenDot:AJ,LucideFolderOutput:MJ,LucideFolderPen:E3,LucideFolderPlus:IJ,LucideFolderRoot:PJ,LucideFolderSearch:DJ,LucideFolderSearch2:LJ,LucideFolderSymlink:RJ,LucideFolderSync:OJ,LucideFolderTree:FJ,LucideFolderUp:BJ,LucideFolderX:zJ,LucideFolders:UJ,LucideFootprints:qJ,LucideForkKnife:yT,LucideForkKnifeCrossed:xT,LucideForklift:VJ,LucideFormInput:J3,LucideForward:HJ,LucideFrame:GJ,LucideFramer:WJ,LucideFrown:KJ,LucideFuel:YJ,LucideFullscreen:ZJ,LucideFunctionSquare:L5,LucideGalleryHorizontal:QJ,LucideGalleryHorizontalEnd:XJ,LucideGalleryThumbnails:JJ,LucideGalleryVertical:tee,LucideGalleryVerticalEnd:eee,LucideGamepad:ree,LucideGamepad2:see,LucideGanttChart:OC,LucideGanttChartSquare:Pb,LucideGauge:nee,LucideGaugeCircle:JC,LucideGavel:aee,LucideGem:iee,LucideGhost:vE,LucideGift:Di,LucideGitBranch:lee,LucideGitBranchPlus:oee,LucideGitCommit:A3,LucideGitCommitHorizontal:A3,LucideGitCommitVertical:cee,LucideGitCompare:uee,LucideGitCompareArrows:dee,LucideGitFork:hee,LucideGitGraph:mee,LucideGitMerge:fee,LucideGitPullRequest:bee,LucideGitPullRequestArrow:pee,LucideGitPullRequestClosed:gee,LucideGitPullRequestCreate:yee,LucideGitPullRequestCreateArrow:xee,LucideGitPullRequestDraft:vee,LucideGithub:_ee,LucideGitlab:wee,LucideGlassWater:jee,LucideGlasses:Nee,LucideGlobe:ld,LucideGlobe2:v3,LucideGlobeLock:kee,LucideGoal:See,LucideGrab:Cee,LucideGraduationCap:Vu,LucideGrape:Tee,LucideGrid:by,LucideGrid2X2:I3,LucideGrid2X2Plus:M3,LucideGrid2x2:I3,LucideGrid2x2Check:Eee,LucideGrid2x2Plus:M3,LucideGrid2x2X:Aee,LucideGrid3X3:by,LucideGrid3x3:by,LucideGrip:Iee,LucideGripHorizontal:Mee,LucideGripVertical:Oh,LucideGroup:Pee,LucideGuitar:Lee,LucideHam:Dee,LucideHammer:uF,LucideHand:hF,LucideHandCoins:Ree,LucideHandHeart:Oee,LucideHandHelping:i1,LucideHandMetal:Fee,LucideHandPlatter:Bee,LucideHandshake:zk,LucideHardDrive:mF,LucideHardDriveDownload:zee,LucideHardDriveUpload:$ee,LucideHardHat:Uee,LucideHash:$k,LucideHaze:qee,LucideHdmiPort:Vee,LucideHeading:Kee,LucideHeading1:OI,LucideHeading2:FI,LucideHeading3:fF,LucideHeading4:Hee,LucideHeading5:Gee,LucideHeading6:Wee,LucideHeadphoneOff:Yee,LucideHeadphones:Zee,LucideHeadset:Xee,LucideHeart:Bi,LucideHeartCrack:Qee,LucideHeartHandshake:Jee,LucideHeartOff:ete,LucideHeartPulse:tte,LucideHeater:ste,LucideHelpCircle:v2,LucideHelpingHand:i1,LucideHexagon:rte,LucideHighlighter:nte,LucideHistory:BI,LucideHome:Fn,LucideHop:ite,LucideHopOff:ate,LucideHospital:ote,LucideHotel:lte,LucideHourglass:cte,LucideHouse:Fn,LucideHousePlug:dte,LucideHousePlus:ute,LucideIceCream:L3,LucideIceCream2:P3,LucideIceCreamBowl:P3,LucideIceCreamCone:L3,LucideIdCard:hte,LucideImage:wl,LucideImageDown:mte,LucideImageMinus:fte,LucideImageOff:pte,LucideImagePlay:gte,LucideImagePlus:f_,LucideImageUp:xte,LucideImageUpscale:yte,LucideImages:vte,LucideImport:bte,LucideInbox:Uk,LucideIndent:R3,LucideIndentDecrease:D3,LucideIndentIncrease:R3,LucideIndianRupee:_te,LucideInfinity:wte,LucideInfo:bE,LucideInspect:z5,LucideInspectionPanel:jte,LucideInstagram:yu,LucideItalic:qk,LucideIterationCcw:Nte,LucideIterationCw:kte,LucideJapaneseYen:Ste,LucideJoystick:Cte,LucideKanban:p_,LucideKanbanSquare:D5,LucideKanbanSquareDashed:T5,LucideKey:dx,LucideKeyRound:_E,LucideKeySquare:Tte,LucideKeyboard:Mte,LucideKeyboardMusic:Ete,LucideKeyboardOff:Ate,LucideLamp:Ote,LucideLampCeiling:Ite,LucideLampDesk:Pte,LucideLampFloor:Lte,LucideLampWallDown:Dte,LucideLampWallUp:Rte,LucideLandPlot:Fte,LucideLandmark:Bte,LucideLanguages:zte,LucideLaptop:Ute,LucideLaptop2:O3,LucideLaptopMinimal:O3,LucideLaptopMinimalCheck:$te,LucideLasso:Vte,LucideLassoSelect:qte,LucideLaugh:Hte,LucideLayers:pF,LucideLayers2:Gte,LucideLayers3:Wte,LucideLayout:w2,LucideLayoutDashboard:wE,LucideLayoutGrid:_g,LucideLayoutList:Kte,LucideLayoutPanelLeft:Yte,LucideLayoutPanelTop:Zte,LucideLayoutTemplate:jE,LucideLeaf:Xte,LucideLeafyGreen:Qte,LucideLectern:Jte,LucideLetterText:ese,LucideLibrary:NE,LucideLibraryBig:tse,LucideLibrarySquare:R5,LucideLifeBuoy:zI,LucideLigature:sse,LucideLightbulb:q2,LucideLightbulbOff:rse,LucideLineChart:LC,LucideLink:Jo,LucideLink2:ql,LucideLink2Off:nse,LucideLinkedin:qf,LucideList:Vf,LucideListCheck:ase,LucideListChecks:V2,LucideListCollapse:ise,LucideListEnd:ose,LucideListFilter:gF,LucideListMinus:lse,LucideListMusic:cse,LucideListOrdered:b1,LucideListPlus:dse,LucideListRestart:use,LucideListStart:hse,LucideListTodo:mse,LucideListTree:fse,LucideListVideo:pse,LucideListX:gse,LucideLoader:yse,LucideLoader2:is,LucideLoaderCircle:is,LucideLoaderPinwheel:xse,LucideLocate:$I,LucideLocateFixed:vse,LucideLocateOff:bse,LucideLock:Td,LucideLockKeyhole:_se,LucideLockKeyholeOpen:F3,LucideLockOpen:B3,LucideLogIn:kE,LucideLogOut:UI,LucideLogs:wse,LucideLollipop:jse,LucideLuggage:Nse,LucideMSquare:O5,LucideMagnet:kse,LucideMail:er,LucideMailCheck:Sse,LucideMailMinus:Cse,LucideMailOpen:xF,LucideMailPlus:yF,LucideMailQuestion:Tse,LucideMailSearch:Ese,LucideMailWarning:Ase,LucideMailX:qI,LucideMailbox:Mse,LucideMails:Ise,LucideMap:SE,LucideMapPin:Qa,LucideMapPinCheck:Lse,LucideMapPinCheckInside:Pse,LucideMapPinHouse:Dse,LucideMapPinMinus:Ose,LucideMapPinMinusInside:Rse,LucideMapPinOff:Fse,LucideMapPinPlus:zse,LucideMapPinPlusInside:Bse,LucideMapPinX:Use,LucideMapPinXInside:$se,LucideMapPinned:qse,LucideMartini:Vse,LucideMaximize:CE,LucideMaximize2:Hse,LucideMedal:H2,LucideMegaphone:ph,LucideMegaphoneOff:Gse,LucideMeh:Wse,LucideMemoryStick:Kse,LucideMenu:TE,LucideMenuSquare:F5,LucideMerge:Yse,LucideMessageCircle:qc,LucideMessageCircleCode:Zse,LucideMessageCircleDashed:Xse,LucideMessageCircleHeart:VI,LucideMessageCircleMore:Qse,LucideMessageCircleOff:Jse,LucideMessageCirclePlus:ere,LucideMessageCircleQuestion:vF,LucideMessageCircleReply:tre,LucideMessageCircleWarning:sre,LucideMessageCircleX:rre,LucideMessageSquare:Gi,LucideMessageSquareCode:nre,LucideMessageSquareDashed:are,LucideMessageSquareDiff:ire,LucideMessageSquareDot:ore,LucideMessageSquareHeart:lre,LucideMessageSquareLock:cre,LucideMessageSquareMore:bF,LucideMessageSquareOff:dre,LucideMessageSquarePlus:t_,LucideMessageSquareQuote:HI,LucideMessageSquareReply:ure,LucideMessageSquareShare:hre,LucideMessageSquareText:mre,LucideMessageSquareWarning:fre,LucideMessageSquareX:pre,LucideMessagesSquare:gre,LucideMic:EE,LucideMic2:z3,LucideMicOff:xre,LucideMicVocal:z3,LucideMicrochip:yre,LucideMicroscope:vre,LucideMicrowave:bre,LucideMilestone:_re,LucideMilk:jre,LucideMilkOff:wre,LucideMinimize:kre,LucideMinimize2:Nre,LucideMinus:g_,LucideMinusCircle:e3,LucideMinusSquare:B5,LucideMonitor:Vk,LucideMonitorCheck:Sre,LucideMonitorCog:Cre,LucideMonitorDot:Tre,LucideMonitorDown:Ere,LucideMonitorOff:Are,LucideMonitorPause:Mre,LucideMonitorPlay:_F,LucideMonitorSmartphone:Ire,LucideMonitorSpeaker:Pre,LucideMonitorStop:Lre,LucideMonitorUp:AE,LucideMonitorX:Dre,LucideMoon:Ore,LucideMoonStar:Rre,LucideMoreHorizontal:Jx,LucideMoreVertical:Ay,LucideMountain:Bre,LucideMountainSnow:Fre,LucideMouse:qre,LucideMouseOff:zre,LucideMousePointer:lm,LucideMousePointer2:$re,LucideMousePointerBan:Ure,LucideMousePointerClick:Kd,LucideMousePointerSquareDashed:E5,LucideMove:sne,LucideMove3D:$3,LucideMove3d:$3,LucideMoveDiagonal:Hre,LucideMoveDiagonal2:Vre,LucideMoveDown:Kre,LucideMoveDownLeft:Gre,LucideMoveDownRight:Wre,LucideMoveHorizontal:Yre,LucideMoveLeft:Zre,LucideMoveRight:Xre,LucideMoveUp:ene,LucideMoveUpLeft:Qre,LucideMoveUpRight:Jre,LucideMoveVertical:tne,LucideMusic:GI,LucideMusic2:rne,LucideMusic3:nne,LucideMusic4:ane,LucideNavigation:wF,LucideNavigation2:one,LucideNavigation2Off:ine,LucideNavigationOff:lne,LucideNetwork:cne,LucideNewspaper:x_,LucideNfc:dne,LucideNotebook:fne,LucideNotebookPen:une,LucideNotebookTabs:hne,LucideNotebookText:mne,LucideNotepadText:gne,LucideNotepadTextDashed:pne,LucideNut:yne,LucideNutOff:xne,LucideOctagon:bne,LucideOctagonAlert:_2,LucideOctagonMinus:vne,LucideOctagonPause:U3,LucideOctagonX:q3,LucideOmega:_ne,LucideOption:wne,LucideOrbit:jne,LucideOrigami:Nne,LucideOutdent:D3,LucidePackage:yc,LucidePackage2:kne,LucidePackageCheck:Sne,LucidePackageMinus:Cne,LucidePackageOpen:Tne,LucidePackagePlus:Ene,LucidePackageSearch:Ane,LucidePackageX:Mne,LucidePaintBucket:Ine,LucidePaintRoller:Pne,LucidePaintbrush:Lne,LucidePaintbrush2:V3,LucidePaintbrushVertical:V3,LucidePalette:pl,LucidePalmtree:oT,LucidePanelBottom:One,LucidePanelBottomClose:Dne,LucidePanelBottomDashed:H3,LucidePanelBottomInactive:H3,LucidePanelBottomOpen:Rne,LucidePanelLeft:Y3,LucidePanelLeftClose:G3,LucidePanelLeftDashed:W3,LucidePanelLeftInactive:W3,LucidePanelLeftOpen:K3,LucidePanelRight:zne,LucidePanelRightClose:Fne,LucidePanelRightDashed:Z3,LucidePanelRightInactive:Z3,LucidePanelRightOpen:Bne,LucidePanelTop:qne,LucidePanelTopClose:$ne,LucidePanelTopDashed:X3,LucidePanelTopInactive:X3,LucidePanelTopOpen:Une,LucidePanelsLeftBottom:Vne,LucidePanelsLeftRight:g3,LucidePanelsRightBottom:Hne,LucidePanelsTopBottom:s5,LucidePanelsTopLeft:w2,LucidePaperclip:Hk,LucideParentheses:Gne,LucideParkingCircle:s3,LucideParkingCircleOff:t3,LucideParkingMeter:Wne,LucideParkingSquare:U5,LucideParkingSquareOff:$5,LucidePartyPopper:gh,LucidePause:Hf,LucidePauseCircle:r3,LucidePauseOctagon:U3,LucidePawPrint:Kne,LucidePcCase:Yne,LucidePen:Wb,LucidePenBox:ou,LucidePenLine:Gb,LucidePenOff:Zne,LucidePenSquare:ou,LucidePenTool:Gk,LucidePencil:ni,LucidePencilLine:Xne,LucidePencilOff:Qne,LucidePencilRuler:Jne,LucidePentagon:eae,LucidePercent:ME,LucidePercentCircle:n3,LucidePercentDiamond:y3,LucidePercentSquare:q5,LucidePersonStanding:tae,LucidePhilippinePeso:sae,LucidePhone:Yn,LucidePhoneCall:rae,LucidePhoneForwarded:nae,LucidePhoneIncoming:aae,LucidePhoneMissed:iae,LucidePhoneOff:oae,LucidePhoneOutgoing:lae,LucidePi:cae,LucidePiSquare:V5,LucidePiano:dae,LucidePickaxe:uae,LucidePictureInPicture:mae,LucidePictureInPicture2:hae,LucidePieChart:FC,LucidePiggyBank:fae,LucidePilcrow:xae,LucidePilcrowLeft:pae,LucidePilcrowRight:gae,LucidePilcrowSquare:H5,LucidePill:vae,LucidePillBottle:yae,LucidePin:Wk,LucidePinOff:jF,LucidePipette:bae,LucidePizza:_ae,LucidePlane:NF,LucidePlaneLanding:wae,LucidePlaneTakeoff:jae,LucidePlay:El,LucidePlayCircle:cg,LucidePlaySquare:G5,LucidePlug:IE,LucidePlug2:Nae,LucidePlugZap:Q3,LucidePlugZap2:Q3,LucidePlus:Ys,LucidePlusCircle:a3,LucidePlusSquare:W5,LucidePocket:Sae,LucidePocketKnife:kae,LucidePodcast:Cae,LucidePointer:Eae,LucidePointerOff:Tae,LucidePopcorn:Aae,LucidePopsicle:Mae,LucidePoundSterling:Iae,LucidePower:kF,LucidePowerCircle:i3,LucidePowerOff:Pae,LucidePowerSquare:K5,LucidePresentation:_1,LucidePrinter:SF,LucidePrinterCheck:Lae,LucideProjector:Dae,LucideProportions:Rae,LucidePuzzle:Oae,LucidePyramid:Fae,LucideQrCode:y_,LucideQuote:Kk,LucideRabbit:Bae,LucideRadar:WI,LucideRadiation:zae,LucideRadical:$ae,LucideRadio:G2,LucideRadioReceiver:Uae,LucideRadioTower:qae,LucideRadius:Vae,LucideRailSymbol:Hae,LucideRainbow:Gae,LucideRat:Wae,LucideRatio:Kae,LucideReceipt:rie,LucideReceiptCent:Yae,LucideReceiptEuro:Zae,LucideReceiptIndianRupee:Xae,LucideReceiptJapaneseYen:Qae,LucideReceiptPoundSterling:Jae,LucideReceiptRussianRuble:eie,LucideReceiptSwissFranc:tie,LucideReceiptText:sie,LucideRectangleEllipsis:J3,LucideRectangleHorizontal:nie,LucideRectangleVertical:aie,LucideRecycle:iie,LucideRedo:Yk,LucideRedo2:oie,LucideRedoDot:lie,LucideRefreshCcw:KI,LucideRefreshCcwDot:cie,LucideRefreshCw:po,LucideRefreshCwOff:die,LucideRefrigerator:uie,LucideRegex:hie,LucideRemoveFormatting:mie,LucideRepeat:CF,LucideRepeat1:fie,LucideRepeat2:pie,LucideReplace:xie,LucideReplaceAll:gie,LucideReply:TF,LucideReplyAll:yie,LucideRewind:vie,LucideRibbon:bie,LucideRocket:v_,LucideRockingChair:_ie,LucideRollerCoaster:wie,LucideRotate3D:e5,LucideRotate3d:e5,LucideRotateCcw:qy,LucideRotateCcwSquare:jie,LucideRotateCw:PE,LucideRotateCwSquare:Nie,LucideRoute:Sie,LucideRouteOff:kie,LucideRouter:Cie,LucideRows:t5,LucideRows2:t5,LucideRows3:s5,LucideRows4:Tie,LucideRss:Eie,LucideRuler:LE,LucideRussianRuble:Aie,LucideSailboat:Mie,LucideSalad:Iie,LucideSandwich:Pie,LucideSatellite:Die,LucideSatelliteDish:Lie,LucideSave:vc,LucideSaveAll:Rie,LucideSaveOff:Oie,LucideScale:EF,LucideScale3D:r5,LucideScale3d:r5,LucideScaling:Fie,LucideScan:Gie,LucideScanBarcode:Bie,LucideScanEye:zie,LucideScanFace:$ie,LucideScanLine:Uie,LucideScanQrCode:qie,LucideScanSearch:Vie,LucideScanText:Hie,LucideScatterChart:BC,LucideSchool:Wie,LucideSchool2:cT,LucideScissors:Yie,LucideScissorsLineDashed:Kie,LucideScissorsSquare:Y5,LucideScissorsSquareDashedBottom:_5,LucideScreenShare:Xie,LucideScreenShareOff:Zie,LucideScroll:Jie,LucideScrollText:Qie,LucideSearch:Mn,LucideSearchCheck:eoe,LucideSearchCode:toe,LucideSearchSlash:soe,LucideSearchX:AF,LucideSection:roe,LucideSend:yn,LucideSendHorizonal:n5,LucideSendHorizontal:n5,LucideSendToBack:noe,LucideSeparatorHorizontal:aoe,LucideSeparatorVertical:ioe,LucideServer:doe,LucideServerCog:ooe,LucideServerCrash:loe,LucideServerOff:coe,LucideSettings:Go,LucideSettings2:MF,LucideShapes:uoe,LucideShare:IF,LucideShare2:cd,LucideSheet:hoe,LucideShell:moe,LucideShield:Fh,LucideShieldAlert:PF,LucideShieldBan:foe,LucideShieldCheck:w1,LucideShieldClose:a5,LucideShieldEllipsis:poe,LucideShieldHalf:goe,LucideShieldMinus:xoe,LucideShieldOff:DE,LucideShieldPlus:yoe,LucideShieldQuestion:voe,LucideShieldX:a5,LucideShip:_oe,LucideShipWheel:boe,LucideShirt:woe,LucideShoppingBag:b_,LucideShoppingBasket:joe,LucideShoppingCart:sx,LucideShovel:Noe,LucideShowerHead:koe,LucideShrink:Soe,LucideShrub:Coe,LucideShuffle:RE,LucideSidebar:Y3,LucideSidebarClose:G3,LucideSidebarOpen:K3,LucideSigma:Toe,LucideSigmaSquare:Z5,LucideSignal:Poe,LucideSignalHigh:Eoe,LucideSignalLow:Aoe,LucideSignalMedium:Moe,LucideSignalZero:Ioe,LucideSignature:Loe,LucideSignpost:Roe,LucideSignpostBig:Doe,LucideSiren:Ooe,LucideSkipBack:Foe,LucideSkipForward:Boe,LucideSkull:zoe,LucideSlack:$oe,LucideSlash:Uoe,LucideSlashSquare:X5,LucideSlice:qoe,LucideSliders:i5,LucideSlidersHorizontal:OE,LucideSlidersVertical:i5,LucideSmartphone:Vy,LucideSmartphoneCharging:Voe,LucideSmartphoneNfc:Hoe,LucideSmile:Woe,LucideSmilePlus:Goe,LucideSnail:Koe,LucideSnowflake:h1,LucideSofa:Yoe,LucideSortAsc:vC,LucideSortDesc:gC,LucideSoup:Zoe,LucideSpace:Xoe,LucideSpade:Qoe,LucideSparkle:Joe,LucideSparkles:Lr,LucideSpeaker:ele,LucideSpeech:tle,LucideSpellCheck:rle,LucideSpellCheck2:sle,LucideSpline:nle,LucideSplit:ale,LucideSplitSquareHorizontal:Q5,LucideSplitSquareVertical:J5,LucideSprayCan:ile,LucideSprout:FE,LucideSquare:Hy,LucideSquareActivity:o5,LucideSquareArrowDown:d5,LucideSquareArrowDownLeft:l5,LucideSquareArrowDownRight:c5,LucideSquareArrowLeft:u5,LucideSquareArrowOutDownLeft:h5,LucideSquareArrowOutDownRight:m5,LucideSquareArrowOutUpLeft:f5,LucideSquareArrowOutUpRight:p5,LucideSquareArrowRight:g5,LucideSquareArrowUp:v5,LucideSquareArrowUpLeft:x5,LucideSquareArrowUpRight:y5,LucideSquareAsterisk:b5,LucideSquareBottomDashedScissors:_5,LucideSquareChartGantt:Pb,LucideSquareCheck:w5,LucideSquareCheckBig:j2,LucideSquareChevronDown:j5,LucideSquareChevronLeft:N5,LucideSquareChevronRight:k5,LucideSquareChevronUp:S5,LucideSquareCode:C5,LucideSquareDashed:A5,LucideSquareDashedBottom:lle,LucideSquareDashedBottomCode:ole,LucideSquareDashedKanban:T5,LucideSquareDashedMousePointer:E5,LucideSquareDivide:M5,LucideSquareDot:I5,LucideSquareEqual:P5,LucideSquareFunction:L5,LucideSquareGanttChart:Pb,LucideSquareKanban:D5,LucideSquareLibrary:R5,LucideSquareM:O5,LucideSquareMenu:F5,LucideSquareMinus:B5,LucideSquareMousePointer:z5,LucideSquareParking:U5,LucideSquareParkingOff:$5,LucideSquarePen:ou,LucideSquarePercent:q5,LucideSquarePi:V5,LucideSquarePilcrow:H5,LucideSquarePlay:G5,LucideSquarePlus:W5,LucideSquarePower:K5,LucideSquareRadical:cle,LucideSquareScissors:Y5,LucideSquareSigma:Z5,LucideSquareSlash:X5,LucideSquareSplitHorizontal:Q5,LucideSquareSplitVertical:J5,LucideSquareSquare:dle,LucideSquareStack:ule,LucideSquareTerminal:eT,LucideSquareUser:sT,LucideSquareUserRound:tT,LucideSquareX:rT,LucideSquircle:hle,LucideSquirrel:mle,LucideStamp:fle,LucideStar:ya,LucideStarHalf:ple,LucideStarOff:gle,LucideStars:Lr,LucideStepBack:xle,LucideStepForward:yle,LucideStethoscope:vle,LucideSticker:ble,LucideStickyNote:_le,LucideStopCircle:l3,LucideStore:wle,LucideStretchHorizontal:jle,LucideStretchVertical:Nle,LucideStrikethrough:LF,LucideSubscript:kle,LucideSubtitles:CC,LucideSun:W2,LucideSunDim:Sle,LucideSunMedium:Cle,LucideSunMoon:Tle,LucideSunSnow:Ele,LucideSunrise:Ale,LucideSunset:Mle,LucideSuperscript:Ile,LucideSwatchBook:Ple,LucideSwissFranc:Lle,LucideSwitchCamera:Dle,LucideSword:Rle,LucideSwords:Ole,LucideSyringe:Fle,LucideTable:ZI,LucideTable2:YI,LucideTableCellsMerge:Ble,LucideTableCellsSplit:zle,LucideTableColumnsSplit:$le,LucideTableOfContents:Ule,LucideTableProperties:qle,LucideTableRowsSplit:Vle,LucideTablet:Gle,LucideTabletSmartphone:Hle,LucideTablets:Wle,LucideTag:xm,LucideTags:Kle,LucideTally1:Yle,LucideTally2:Zle,LucideTally3:Xle,LucideTally4:Qle,LucideTally5:Jle,LucideTangent:ece,LucideTarget:Wu,LucideTelescope:tce,LucideTent:rce,LucideTentTree:sce,LucideTerminal:nce,LucideTerminalSquare:eT,LucideTestTube:ace,LucideTestTube2:nT,LucideTestTubeDiagonal:nT,LucideTestTubes:ice,LucideText:uce,LucideTextCursor:lce,LucideTextCursorInput:oce,LucideTextQuote:cce,LucideTextSearch:dce,LucideTextSelect:aT,LucideTextSelection:aT,LucideTheater:hce,LucideThermometer:pce,LucideThermometerSnowflake:mce,LucideThermometerSun:fce,LucideThumbsDown:DF,LucideThumbsUp:sf,LucideTicket:RF,LucideTicketCheck:gce,LucideTicketMinus:xce,LucideTicketPercent:yce,LucideTicketPlus:vce,LucideTicketSlash:bce,LucideTicketX:_ce,LucideTickets:jce,LucideTicketsPlane:wce,LucideTimer:Sce,LucideTimerOff:Nce,LucideTimerReset:kce,LucideToggleLeft:Cce,LucideToggleRight:Tce,LucideToilet:Ece,LucideTornado:Ace,LucideTorus:Mce,LucideTouchpad:Pce,LucideTouchpadOff:Ice,LucideTowerControl:Lce,LucideToyBrick:Dce,LucideTractor:Rce,LucideTrafficCone:Oce,LucideTrain:iT,LucideTrainFront:Bce,LucideTrainFrontTunnel:Fce,LucideTrainTrack:zce,LucideTramFront:iT,LucideTrash:$ce,LucideTrash2:Dr,LucideTreeDeciduous:Uce,LucideTreePalm:oT,LucideTreePine:Zk,LucideTrees:qce,LucideTrello:Vce,LucideTrendingDown:K2,LucideTrendingUp:al,LucideTrendingUpDown:Hce,LucideTriangle:Wce,LucideTriangleAlert:uu,LucideTriangleRight:Gce,LucideTrophy:To,LucideTruck:OF,LucideTurtle:Kce,LucideTv:Zce,LucideTv2:lT,LucideTvMinimal:lT,LucideTvMinimalPlay:Yce,LucideTwitch:Xce,LucideTwitter:Qce,LucideType:ede,LucideTypeOutline:Jce,LucideUmbrella:sde,LucideUmbrellaOff:tde,LucideUnderline:XI,LucideUndo:Xk,LucideUndo2:rde,LucideUndoDot:nde,LucideUnfoldHorizontal:ade,LucideUnfoldVertical:ide,LucideUngroup:ode,LucideUniversity:cT,LucideUnlink:BE,LucideUnlink2:lde,LucideUnlock:B3,LucideUnlockKeyhole:F3,LucideUnplug:cde,LucideUpload:Ea,LucideUploadCloud:f3,LucideUsb:dde,LucideUser:io,LucideUser2:pT,LucideUserCheck:j1,LucideUserCheck2:dT,LucideUserCircle:d3,LucideUserCircle2:c3,LucideUserCog:FF,LucideUserCog2:uT,LucideUserMinus:BF,LucideUserMinus2:hT,LucideUserPen:ude,LucideUserPlus:Vl,LucideUserPlus2:mT,LucideUserRound:pT,LucideUserRoundCheck:dT,LucideUserRoundCog:uT,LucideUserRoundMinus:hT,LucideUserRoundPen:hde,LucideUserRoundPlus:mT,LucideUserRoundSearch:mde,LucideUserRoundX:fT,LucideUserSearch:fde,LucideUserSquare:sT,LucideUserSquare2:tT,LucideUserX:pde,LucideUserX2:fT,LucideUsers:Ar,LucideUsers2:gT,LucideUsersRound:gT,LucideUtensils:yT,LucideUtensilsCrossed:xT,LucideUtilityPole:gde,LucideVariable:QI,LucideVault:xde,LucideVegan:yde,LucideVenetianMask:vde,LucideVerified:wC,LucideVibrate:_de,LucideVibrateOff:bde,LucideVideo:xn,LucideVideoOff:wde,LucideVideotape:jde,LucideView:Nde,LucideVoicemail:kde,LucideVolleyball:Sde,LucideVolume:Ede,LucideVolume1:Cde,LucideVolume2:zF,LucideVolumeOff:Tde,LucideVolumeX:$F,LucideVote:Ade,LucideWallet:UF,LucideWallet2:vT,LucideWalletCards:Mde,LucideWalletMinimal:vT,LucideWallpaper:Ide,LucideWand:Pde,LucideWand2:My,LucideWandSparkles:My,LucideWarehouse:Lde,LucideWashingMachine:Dde,LucideWatch:Rde,LucideWaves:Ode,LucideWaypoints:Fde,LucideWebcam:Bde,LucideWebhook:$de,LucideWebhookOff:zde,LucideWeight:Ude,LucideWheat:Vde,LucideWheatOff:qde,LucideWholeWord:Hde,LucideWifi:Zde,LucideWifiHigh:Gde,LucideWifiLow:Wde,LucideWifiOff:Kde,LucideWifiZero:Yde,LucideWind:Qde,LucideWindArrowDown:Xde,LucideWine:eue,LucideWineOff:Jde,LucideWorkflow:qF,LucideWorm:tue,LucideWrapText:sue,LucideWrench:N1,LucideX:Rr,LucideXCircle:kd,LucideXOctagon:q3,LucideXSquare:rT,LucideYoutube:rue,LucideZap:ym,LucideZapOff:nue,LucideZoomIn:Qk,LucideZoomOut:JI,Luggage:Nse,LuggageIcon:Nse,MSquare:O5,MSquareIcon:O5,Magnet:kse,MagnetIcon:kse,Mail:er,MailCheck:Sse,MailCheckIcon:Sse,MailIcon:er,MailMinus:Cse,MailMinusIcon:Cse,MailOpen:xF,MailOpenIcon:xF,MailPlus:yF,MailPlusIcon:yF,MailQuestion:Tse,MailQuestionIcon:Tse,MailSearch:Ese,MailSearchIcon:Ese,MailWarning:Ase,MailWarningIcon:Ase,MailX:qI,MailXIcon:qI,Mailbox:Mse,MailboxIcon:Mse,Mails:Ise,MailsIcon:Ise,Map:SE,MapIcon:SE,MapPin:Qa,MapPinCheck:Lse,MapPinCheckIcon:Lse,MapPinCheckInside:Pse,MapPinCheckInsideIcon:Pse,MapPinHouse:Dse,MapPinHouseIcon:Dse,MapPinIcon:Qa,MapPinMinus:Ose,MapPinMinusIcon:Ose,MapPinMinusInside:Rse,MapPinMinusInsideIcon:Rse,MapPinOff:Fse,MapPinOffIcon:Fse,MapPinPlus:zse,MapPinPlusIcon:zse,MapPinPlusInside:Bse,MapPinPlusInsideIcon:Bse,MapPinX:Use,MapPinXIcon:Use,MapPinXInside:$se,MapPinXInsideIcon:$se,MapPinned:qse,MapPinnedIcon:qse,Martini:Vse,MartiniIcon:Vse,Maximize:CE,Maximize2:Hse,Maximize2Icon:Hse,MaximizeIcon:CE,Medal:H2,MedalIcon:H2,Megaphone:ph,MegaphoneIcon:ph,MegaphoneOff:Gse,MegaphoneOffIcon:Gse,Meh:Wse,MehIcon:Wse,MemoryStick:Kse,MemoryStickIcon:Kse,Menu:TE,MenuIcon:TE,MenuSquare:F5,MenuSquareIcon:F5,Merge:Yse,MergeIcon:Yse,MessageCircle:qc,MessageCircleCode:Zse,MessageCircleCodeIcon:Zse,MessageCircleDashed:Xse,MessageCircleDashedIcon:Xse,MessageCircleHeart:VI,MessageCircleHeartIcon:VI,MessageCircleIcon:qc,MessageCircleMore:Qse,MessageCircleMoreIcon:Qse,MessageCircleOff:Jse,MessageCircleOffIcon:Jse,MessageCirclePlus:ere,MessageCirclePlusIcon:ere,MessageCircleQuestion:vF,MessageCircleQuestionIcon:vF,MessageCircleReply:tre,MessageCircleReplyIcon:tre,MessageCircleWarning:sre,MessageCircleWarningIcon:sre,MessageCircleX:rre,MessageCircleXIcon:rre,MessageSquare:Gi,MessageSquareCode:nre,MessageSquareCodeIcon:nre,MessageSquareDashed:are,MessageSquareDashedIcon:are,MessageSquareDiff:ire,MessageSquareDiffIcon:ire,MessageSquareDot:ore,MessageSquareDotIcon:ore,MessageSquareHeart:lre,MessageSquareHeartIcon:lre,MessageSquareIcon:Gi,MessageSquareLock:cre,MessageSquareLockIcon:cre,MessageSquareMore:bF,MessageSquareMoreIcon:bF,MessageSquareOff:dre,MessageSquareOffIcon:dre,MessageSquarePlus:t_,MessageSquarePlusIcon:t_,MessageSquareQuote:HI,MessageSquareQuoteIcon:HI,MessageSquareReply:ure,MessageSquareReplyIcon:ure,MessageSquareShare:hre,MessageSquareShareIcon:hre,MessageSquareText:mre,MessageSquareTextIcon:mre,MessageSquareWarning:fre,MessageSquareWarningIcon:fre,MessageSquareX:pre,MessageSquareXIcon:pre,MessagesSquare:gre,MessagesSquareIcon:gre,Mic:EE,Mic2:z3,Mic2Icon:z3,MicIcon:EE,MicOff:xre,MicOffIcon:xre,MicVocal:z3,MicVocalIcon:z3,Microchip:yre,MicrochipIcon:yre,Microscope:vre,MicroscopeIcon:vre,Microwave:bre,MicrowaveIcon:bre,Milestone:_re,MilestoneIcon:_re,Milk:jre,MilkIcon:jre,MilkOff:wre,MilkOffIcon:wre,Minimize:kre,Minimize2:Nre,Minimize2Icon:Nre,MinimizeIcon:kre,Minus:g_,MinusCircle:e3,MinusCircleIcon:e3,MinusIcon:g_,MinusSquare:B5,MinusSquareIcon:B5,Monitor:Vk,MonitorCheck:Sre,MonitorCheckIcon:Sre,MonitorCog:Cre,MonitorCogIcon:Cre,MonitorDot:Tre,MonitorDotIcon:Tre,MonitorDown:Ere,MonitorDownIcon:Ere,MonitorIcon:Vk,MonitorOff:Are,MonitorOffIcon:Are,MonitorPause:Mre,MonitorPauseIcon:Mre,MonitorPlay:_F,MonitorPlayIcon:_F,MonitorSmartphone:Ire,MonitorSmartphoneIcon:Ire,MonitorSpeaker:Pre,MonitorSpeakerIcon:Pre,MonitorStop:Lre,MonitorStopIcon:Lre,MonitorUp:AE,MonitorUpIcon:AE,MonitorX:Dre,MonitorXIcon:Dre,Moon:Ore,MoonIcon:Ore,MoonStar:Rre,MoonStarIcon:Rre,MoreHorizontal:Jx,MoreHorizontalIcon:Jx,MoreVertical:Ay,MoreVerticalIcon:Ay,Mountain:Bre,MountainIcon:Bre,MountainSnow:Fre,MountainSnowIcon:Fre,Mouse:qre,MouseIcon:qre,MouseOff:zre,MouseOffIcon:zre,MousePointer:lm,MousePointer2:$re,MousePointer2Icon:$re,MousePointerBan:Ure,MousePointerBanIcon:Ure,MousePointerClick:Kd,MousePointerClickIcon:Kd,MousePointerIcon:lm,MousePointerSquareDashed:E5,MousePointerSquareDashedIcon:E5,Move:sne,Move3D:$3,Move3DIcon:$3,Move3d:$3,Move3dIcon:$3,MoveDiagonal:Hre,MoveDiagonal2:Vre,MoveDiagonal2Icon:Vre,MoveDiagonalIcon:Hre,MoveDown:Kre,MoveDownIcon:Kre,MoveDownLeft:Gre,MoveDownLeftIcon:Gre,MoveDownRight:Wre,MoveDownRightIcon:Wre,MoveHorizontal:Yre,MoveHorizontalIcon:Yre,MoveIcon:sne,MoveLeft:Zre,MoveLeftIcon:Zre,MoveRight:Xre,MoveRightIcon:Xre,MoveUp:ene,MoveUpIcon:ene,MoveUpLeft:Qre,MoveUpLeftIcon:Qre,MoveUpRight:Jre,MoveUpRightIcon:Jre,MoveVertical:tne,MoveVerticalIcon:tne,Music:GI,Music2:rne,Music2Icon:rne,Music3:nne,Music3Icon:nne,Music4:ane,Music4Icon:ane,MusicIcon:GI,Navigation:wF,Navigation2:one,Navigation2Icon:one,Navigation2Off:ine,Navigation2OffIcon:ine,NavigationIcon:wF,NavigationOff:lne,NavigationOffIcon:lne,Network:cne,NetworkIcon:cne,Newspaper:x_,NewspaperIcon:x_,Nfc:dne,NfcIcon:dne,Notebook:fne,NotebookIcon:fne,NotebookPen:une,NotebookPenIcon:une,NotebookTabs:hne,NotebookTabsIcon:hne,NotebookText:mne,NotebookTextIcon:mne,NotepadText:gne,NotepadTextDashed:pne,NotepadTextDashedIcon:pne,NotepadTextIcon:gne,Nut:yne,NutIcon:yne,NutOff:xne,NutOffIcon:xne,Octagon:bne,OctagonAlert:_2,OctagonAlertIcon:_2,OctagonIcon:bne,OctagonMinus:vne,OctagonMinusIcon:vne,OctagonPause:U3,OctagonPauseIcon:U3,OctagonX:q3,OctagonXIcon:q3,Omega:_ne,OmegaIcon:_ne,Option:wne,OptionIcon:wne,Orbit:jne,OrbitIcon:jne,Origami:Nne,OrigamiIcon:Nne,Outdent:D3,OutdentIcon:D3,Package:yc,Package2:kne,Package2Icon:kne,PackageCheck:Sne,PackageCheckIcon:Sne,PackageIcon:yc,PackageMinus:Cne,PackageMinusIcon:Cne,PackageOpen:Tne,PackageOpenIcon:Tne,PackagePlus:Ene,PackagePlusIcon:Ene,PackageSearch:Ane,PackageSearchIcon:Ane,PackageX:Mne,PackageXIcon:Mne,PaintBucket:Ine,PaintBucketIcon:Ine,PaintRoller:Pne,PaintRollerIcon:Pne,Paintbrush:Lne,Paintbrush2:V3,Paintbrush2Icon:V3,PaintbrushIcon:Lne,PaintbrushVertical:V3,PaintbrushVerticalIcon:V3,Palette:pl,PaletteIcon:pl,Palmtree:oT,PalmtreeIcon:oT,PanelBottom:One,PanelBottomClose:Dne,PanelBottomCloseIcon:Dne,PanelBottomDashed:H3,PanelBottomDashedIcon:H3,PanelBottomIcon:One,PanelBottomInactive:H3,PanelBottomInactiveIcon:H3,PanelBottomOpen:Rne,PanelBottomOpenIcon:Rne,PanelLeft:Y3,PanelLeftClose:G3,PanelLeftCloseIcon:G3,PanelLeftDashed:W3,PanelLeftDashedIcon:W3,PanelLeftIcon:Y3,PanelLeftInactive:W3,PanelLeftInactiveIcon:W3,PanelLeftOpen:K3,PanelLeftOpenIcon:K3,PanelRight:zne,PanelRightClose:Fne,PanelRightCloseIcon:Fne,PanelRightDashed:Z3,PanelRightDashedIcon:Z3,PanelRightIcon:zne,PanelRightInactive:Z3,PanelRightInactiveIcon:Z3,PanelRightOpen:Bne,PanelRightOpenIcon:Bne,PanelTop:qne,PanelTopClose:$ne,PanelTopCloseIcon:$ne,PanelTopDashed:X3,PanelTopDashedIcon:X3,PanelTopIcon:qne,PanelTopInactive:X3,PanelTopInactiveIcon:X3,PanelTopOpen:Une,PanelTopOpenIcon:Une,PanelsLeftBottom:Vne,PanelsLeftBottomIcon:Vne,PanelsLeftRight:g3,PanelsLeftRightIcon:g3,PanelsRightBottom:Hne,PanelsRightBottomIcon:Hne,PanelsTopBottom:s5,PanelsTopBottomIcon:s5,PanelsTopLeft:w2,PanelsTopLeftIcon:w2,Paperclip:Hk,PaperclipIcon:Hk,Parentheses:Gne,ParenthesesIcon:Gne,ParkingCircle:s3,ParkingCircleIcon:s3,ParkingCircleOff:t3,ParkingCircleOffIcon:t3,ParkingMeter:Wne,ParkingMeterIcon:Wne,ParkingSquare:U5,ParkingSquareIcon:U5,ParkingSquareOff:$5,ParkingSquareOffIcon:$5,PartyPopper:gh,PartyPopperIcon:gh,Pause:Hf,PauseCircle:r3,PauseCircleIcon:r3,PauseIcon:Hf,PauseOctagon:U3,PauseOctagonIcon:U3,PawPrint:Kne,PawPrintIcon:Kne,PcCase:Yne,PcCaseIcon:Yne,Pen:Wb,PenBox:ou,PenBoxIcon:ou,PenIcon:Wb,PenLine:Gb,PenLineIcon:Gb,PenOff:Zne,PenOffIcon:Zne,PenSquare:ou,PenSquareIcon:ou,PenTool:Gk,PenToolIcon:Gk,Pencil:ni,PencilIcon:ni,PencilLine:Xne,PencilLineIcon:Xne,PencilOff:Qne,PencilOffIcon:Qne,PencilRuler:Jne,PencilRulerIcon:Jne,Pentagon:eae,PentagonIcon:eae,Percent:ME,PercentCircle:n3,PercentCircleIcon:n3,PercentDiamond:y3,PercentDiamondIcon:y3,PercentIcon:ME,PercentSquare:q5,PercentSquareIcon:q5,PersonStanding:tae,PersonStandingIcon:tae,PhilippinePeso:sae,PhilippinePesoIcon:sae,Phone:Yn,PhoneCall:rae,PhoneCallIcon:rae,PhoneForwarded:nae,PhoneForwardedIcon:nae,PhoneIcon:Yn,PhoneIncoming:aae,PhoneIncomingIcon:aae,PhoneMissed:iae,PhoneMissedIcon:iae,PhoneOff:oae,PhoneOffIcon:oae,PhoneOutgoing:lae,PhoneOutgoingIcon:lae,Pi:cae,PiIcon:cae,PiSquare:V5,PiSquareIcon:V5,Piano:dae,PianoIcon:dae,Pickaxe:uae,PickaxeIcon:uae,PictureInPicture:mae,PictureInPicture2:hae,PictureInPicture2Icon:hae,PictureInPictureIcon:mae,PieChart:FC,PieChartIcon:FC,PiggyBank:fae,PiggyBankIcon:fae,Pilcrow:xae,PilcrowIcon:xae,PilcrowLeft:pae,PilcrowLeftIcon:pae,PilcrowRight:gae,PilcrowRightIcon:gae,PilcrowSquare:H5,PilcrowSquareIcon:H5,Pill:vae,PillBottle:yae,PillBottleIcon:yae,PillIcon:vae,Pin:Wk,PinIcon:Wk,PinOff:jF,PinOffIcon:jF,Pipette:bae,PipetteIcon:bae,Pizza:_ae,PizzaIcon:_ae,Plane:NF,PlaneIcon:NF,PlaneLanding:wae,PlaneLandingIcon:wae,PlaneTakeoff:jae,PlaneTakeoffIcon:jae,Play:El,PlayCircle:cg,PlayCircleIcon:cg,PlayIcon:El,PlaySquare:G5,PlaySquareIcon:G5,Plug:IE,Plug2:Nae,Plug2Icon:Nae,PlugIcon:IE,PlugZap:Q3,PlugZap2:Q3,PlugZap2Icon:Q3,PlugZapIcon:Q3,Plus:Ys,PlusCircle:a3,PlusCircleIcon:a3,PlusIcon:Ys,PlusSquare:W5,PlusSquareIcon:W5,Pocket:Sae,PocketIcon:Sae,PocketKnife:kae,PocketKnifeIcon:kae,Podcast:Cae,PodcastIcon:Cae,Pointer:Eae,PointerIcon:Eae,PointerOff:Tae,PointerOffIcon:Tae,Popcorn:Aae,PopcornIcon:Aae,Popsicle:Mae,PopsicleIcon:Mae,PoundSterling:Iae,PoundSterlingIcon:Iae,Power:kF,PowerCircle:i3,PowerCircleIcon:i3,PowerIcon:kF,PowerOff:Pae,PowerOffIcon:Pae,PowerSquare:K5,PowerSquareIcon:K5,Presentation:_1,PresentationIcon:_1,Printer:SF,PrinterCheck:Lae,PrinterCheckIcon:Lae,PrinterIcon:SF,Projector:Dae,ProjectorIcon:Dae,Proportions:Rae,ProportionsIcon:Rae,Puzzle:Oae,PuzzleIcon:Oae,Pyramid:Fae,PyramidIcon:Fae,QrCode:y_,QrCodeIcon:y_,Quote:Kk,QuoteIcon:Kk,Rabbit:Bae,RabbitIcon:Bae,Radar:WI,RadarIcon:WI,Radiation:zae,RadiationIcon:zae,Radical:$ae,RadicalIcon:$ae,Radio:G2,RadioIcon:G2,RadioReceiver:Uae,RadioReceiverIcon:Uae,RadioTower:qae,RadioTowerIcon:qae,Radius:Vae,RadiusIcon:Vae,RailSymbol:Hae,RailSymbolIcon:Hae,Rainbow:Gae,RainbowIcon:Gae,Rat:Wae,RatIcon:Wae,Ratio:Kae,RatioIcon:Kae,Receipt:rie,ReceiptCent:Yae,ReceiptCentIcon:Yae,ReceiptEuro:Zae,ReceiptEuroIcon:Zae,ReceiptIcon:rie,ReceiptIndianRupee:Xae,ReceiptIndianRupeeIcon:Xae,ReceiptJapaneseYen:Qae,ReceiptJapaneseYenIcon:Qae,ReceiptPoundSterling:Jae,ReceiptPoundSterlingIcon:Jae,ReceiptRussianRuble:eie,ReceiptRussianRubleIcon:eie,ReceiptSwissFranc:tie,ReceiptSwissFrancIcon:tie,ReceiptText:sie,ReceiptTextIcon:sie,RectangleEllipsis:J3,RectangleEllipsisIcon:J3,RectangleHorizontal:nie,RectangleHorizontalIcon:nie,RectangleVertical:aie,RectangleVerticalIcon:aie,Recycle:iie,RecycleIcon:iie,Redo:Yk,Redo2:oie,Redo2Icon:oie,RedoDot:lie,RedoDotIcon:lie,RedoIcon:Yk,RefreshCcw:KI,RefreshCcwDot:cie,RefreshCcwDotIcon:cie,RefreshCcwIcon:KI,RefreshCw:po,RefreshCwIcon:po,RefreshCwOff:die,RefreshCwOffIcon:die,Refrigerator:uie,RefrigeratorIcon:uie,Regex:hie,RegexIcon:hie,RemoveFormatting:mie,RemoveFormattingIcon:mie,Repeat:CF,Repeat1:fie,Repeat1Icon:fie,Repeat2:pie,Repeat2Icon:pie,RepeatIcon:CF,Replace:xie,ReplaceAll:gie,ReplaceAllIcon:gie,ReplaceIcon:xie,Reply:TF,ReplyAll:yie,ReplyAllIcon:yie,ReplyIcon:TF,Rewind:vie,RewindIcon:vie,Ribbon:bie,RibbonIcon:bie,Rocket:v_,RocketIcon:v_,RockingChair:_ie,RockingChairIcon:_ie,RollerCoaster:wie,RollerCoasterIcon:wie,Rotate3D:e5,Rotate3DIcon:e5,Rotate3d:e5,Rotate3dIcon:e5,RotateCcw:qy,RotateCcwIcon:qy,RotateCcwSquare:jie,RotateCcwSquareIcon:jie,RotateCw:PE,RotateCwIcon:PE,RotateCwSquare:Nie,RotateCwSquareIcon:Nie,Route:Sie,RouteIcon:Sie,RouteOff:kie,RouteOffIcon:kie,Router:Cie,RouterIcon:Cie,Rows:t5,Rows2:t5,Rows2Icon:t5,Rows3:s5,Rows3Icon:s5,Rows4:Tie,Rows4Icon:Tie,RowsIcon:t5,Rss:Eie,RssIcon:Eie,Ruler:LE,RulerIcon:LE,RussianRuble:Aie,RussianRubleIcon:Aie,Sailboat:Mie,SailboatIcon:Mie,Salad:Iie,SaladIcon:Iie,Sandwich:Pie,SandwichIcon:Pie,Satellite:Die,SatelliteDish:Lie,SatelliteDishIcon:Lie,SatelliteIcon:Die,Save:vc,SaveAll:Rie,SaveAllIcon:Rie,SaveIcon:vc,SaveOff:Oie,SaveOffIcon:Oie,Scale:EF,Scale3D:r5,Scale3DIcon:r5,Scale3d:r5,Scale3dIcon:r5,ScaleIcon:EF,Scaling:Fie,ScalingIcon:Fie,Scan:Gie,ScanBarcode:Bie,ScanBarcodeIcon:Bie,ScanEye:zie,ScanEyeIcon:zie,ScanFace:$ie,ScanFaceIcon:$ie,ScanIcon:Gie,ScanLine:Uie,ScanLineIcon:Uie,ScanQrCode:qie,ScanQrCodeIcon:qie,ScanSearch:Vie,ScanSearchIcon:Vie,ScanText:Hie,ScanTextIcon:Hie,ScatterChart:BC,ScatterChartIcon:BC,School:Wie,School2:cT,School2Icon:cT,SchoolIcon:Wie,Scissors:Yie,ScissorsIcon:Yie,ScissorsLineDashed:Kie,ScissorsLineDashedIcon:Kie,ScissorsSquare:Y5,ScissorsSquareDashedBottom:_5,ScissorsSquareDashedBottomIcon:_5,ScissorsSquareIcon:Y5,ScreenShare:Xie,ScreenShareIcon:Xie,ScreenShareOff:Zie,ScreenShareOffIcon:Zie,Scroll:Jie,ScrollIcon:Jie,ScrollText:Qie,ScrollTextIcon:Qie,Search:Mn,SearchCheck:eoe,SearchCheckIcon:eoe,SearchCode:toe,SearchCodeIcon:toe,SearchIcon:Mn,SearchSlash:soe,SearchSlashIcon:soe,SearchX:AF,SearchXIcon:AF,Section:roe,SectionIcon:roe,Send:yn,SendHorizonal:n5,SendHorizonalIcon:n5,SendHorizontal:n5,SendHorizontalIcon:n5,SendIcon:yn,SendToBack:noe,SendToBackIcon:noe,SeparatorHorizontal:aoe,SeparatorHorizontalIcon:aoe,SeparatorVertical:ioe,SeparatorVerticalIcon:ioe,Server:doe,ServerCog:ooe,ServerCogIcon:ooe,ServerCrash:loe,ServerCrashIcon:loe,ServerIcon:doe,ServerOff:coe,ServerOffIcon:coe,Settings:Go,Settings2:MF,Settings2Icon:MF,SettingsIcon:Go,Shapes:uoe,ShapesIcon:uoe,Share:IF,Share2:cd,Share2Icon:cd,ShareIcon:IF,Sheet:hoe,SheetIcon:hoe,Shell:moe,ShellIcon:moe,Shield:Fh,ShieldAlert:PF,ShieldAlertIcon:PF,ShieldBan:foe,ShieldBanIcon:foe,ShieldCheck:w1,ShieldCheckIcon:w1,ShieldClose:a5,ShieldCloseIcon:a5,ShieldEllipsis:poe,ShieldEllipsisIcon:poe,ShieldHalf:goe,ShieldHalfIcon:goe,ShieldIcon:Fh,ShieldMinus:xoe,ShieldMinusIcon:xoe,ShieldOff:DE,ShieldOffIcon:DE,ShieldPlus:yoe,ShieldPlusIcon:yoe,ShieldQuestion:voe,ShieldQuestionIcon:voe,ShieldX:a5,ShieldXIcon:a5,Ship:_oe,ShipIcon:_oe,ShipWheel:boe,ShipWheelIcon:boe,Shirt:woe,ShirtIcon:woe,ShoppingBag:b_,ShoppingBagIcon:b_,ShoppingBasket:joe,ShoppingBasketIcon:joe,ShoppingCart:sx,ShoppingCartIcon:sx,Shovel:Noe,ShovelIcon:Noe,ShowerHead:koe,ShowerHeadIcon:koe,Shrink:Soe,ShrinkIcon:Soe,Shrub:Coe,ShrubIcon:Coe,Shuffle:RE,ShuffleIcon:RE,Sidebar:Y3,SidebarClose:G3,SidebarCloseIcon:G3,SidebarIcon:Y3,SidebarOpen:K3,SidebarOpenIcon:K3,Sigma:Toe,SigmaIcon:Toe,SigmaSquare:Z5,SigmaSquareIcon:Z5,Signal:Poe,SignalHigh:Eoe,SignalHighIcon:Eoe,SignalIcon:Poe,SignalLow:Aoe,SignalLowIcon:Aoe,SignalMedium:Moe,SignalMediumIcon:Moe,SignalZero:Ioe,SignalZeroIcon:Ioe,Signature:Loe,SignatureIcon:Loe,Signpost:Roe,SignpostBig:Doe,SignpostBigIcon:Doe,SignpostIcon:Roe,Siren:Ooe,SirenIcon:Ooe,SkipBack:Foe,SkipBackIcon:Foe,SkipForward:Boe,SkipForwardIcon:Boe,Skull:zoe,SkullIcon:zoe,Slack:$oe,SlackIcon:$oe,Slash:Uoe,SlashIcon:Uoe,SlashSquare:X5,SlashSquareIcon:X5,Slice:qoe,SliceIcon:qoe,Sliders:i5,SlidersHorizontal:OE,SlidersHorizontalIcon:OE,SlidersIcon:i5,SlidersVertical:i5,SlidersVerticalIcon:i5,Smartphone:Vy,SmartphoneCharging:Voe,SmartphoneChargingIcon:Voe,SmartphoneIcon:Vy,SmartphoneNfc:Hoe,SmartphoneNfcIcon:Hoe,Smile:Woe,SmileIcon:Woe,SmilePlus:Goe,SmilePlusIcon:Goe,Snail:Koe,SnailIcon:Koe,Snowflake:h1,SnowflakeIcon:h1,Sofa:Yoe,SofaIcon:Yoe,SortAsc:vC,SortAscIcon:vC,SortDesc:gC,SortDescIcon:gC,Soup:Zoe,SoupIcon:Zoe,Space:Xoe,SpaceIcon:Xoe,Spade:Qoe,SpadeIcon:Qoe,Sparkle:Joe,SparkleIcon:Joe,Sparkles:Lr,SparklesIcon:Lr,Speaker:ele,SpeakerIcon:ele,Speech:tle,SpeechIcon:tle,SpellCheck:rle,SpellCheck2:sle,SpellCheck2Icon:sle,SpellCheckIcon:rle,Spline:nle,SplineIcon:nle,Split:ale,SplitIcon:ale,SplitSquareHorizontal:Q5,SplitSquareHorizontalIcon:Q5,SplitSquareVertical:J5,SplitSquareVerticalIcon:J5,SprayCan:ile,SprayCanIcon:ile,Sprout:FE,SproutIcon:FE,Square:Hy,SquareActivity:o5,SquareActivityIcon:o5,SquareArrowDown:d5,SquareArrowDownIcon:d5,SquareArrowDownLeft:l5,SquareArrowDownLeftIcon:l5,SquareArrowDownRight:c5,SquareArrowDownRightIcon:c5,SquareArrowLeft:u5,SquareArrowLeftIcon:u5,SquareArrowOutDownLeft:h5,SquareArrowOutDownLeftIcon:h5,SquareArrowOutDownRight:m5,SquareArrowOutDownRightIcon:m5,SquareArrowOutUpLeft:f5,SquareArrowOutUpLeftIcon:f5,SquareArrowOutUpRight:p5,SquareArrowOutUpRightIcon:p5,SquareArrowRight:g5,SquareArrowRightIcon:g5,SquareArrowUp:v5,SquareArrowUpIcon:v5,SquareArrowUpLeft:x5,SquareArrowUpLeftIcon:x5,SquareArrowUpRight:y5,SquareArrowUpRightIcon:y5,SquareAsterisk:b5,SquareAsteriskIcon:b5,SquareBottomDashedScissors:_5,SquareBottomDashedScissorsIcon:_5,SquareChartGantt:Pb,SquareChartGanttIcon:Pb,SquareCheck:w5,SquareCheckBig:j2,SquareCheckBigIcon:j2,SquareCheckIcon:w5,SquareChevronDown:j5,SquareChevronDownIcon:j5,SquareChevronLeft:N5,SquareChevronLeftIcon:N5,SquareChevronRight:k5,SquareChevronRightIcon:k5,SquareChevronUp:S5,SquareChevronUpIcon:S5,SquareCode:C5,SquareCodeIcon:C5,SquareDashed:A5,SquareDashedBottom:lle,SquareDashedBottomCode:ole,SquareDashedBottomCodeIcon:ole,SquareDashedBottomIcon:lle,SquareDashedIcon:A5,SquareDashedKanban:T5,SquareDashedKanbanIcon:T5,SquareDashedMousePointer:E5,SquareDashedMousePointerIcon:E5,SquareDivide:M5,SquareDivideIcon:M5,SquareDot:I5,SquareDotIcon:I5,SquareEqual:P5,SquareEqualIcon:P5,SquareFunction:L5,SquareFunctionIcon:L5,SquareGanttChart:Pb,SquareGanttChartIcon:Pb,SquareIcon:Hy,SquareKanban:D5,SquareKanbanIcon:D5,SquareLibrary:R5,SquareLibraryIcon:R5,SquareM:O5,SquareMIcon:O5,SquareMenu:F5,SquareMenuIcon:F5,SquareMinus:B5,SquareMinusIcon:B5,SquareMousePointer:z5,SquareMousePointerIcon:z5,SquareParking:U5,SquareParkingIcon:U5,SquareParkingOff:$5,SquareParkingOffIcon:$5,SquarePen:ou,SquarePenIcon:ou,SquarePercent:q5,SquarePercentIcon:q5,SquarePi:V5,SquarePiIcon:V5,SquarePilcrow:H5,SquarePilcrowIcon:H5,SquarePlay:G5,SquarePlayIcon:G5,SquarePlus:W5,SquarePlusIcon:W5,SquarePower:K5,SquarePowerIcon:K5,SquareRadical:cle,SquareRadicalIcon:cle,SquareScissors:Y5,SquareScissorsIcon:Y5,SquareSigma:Z5,SquareSigmaIcon:Z5,SquareSlash:X5,SquareSlashIcon:X5,SquareSplitHorizontal:Q5,SquareSplitHorizontalIcon:Q5,SquareSplitVertical:J5,SquareSplitVerticalIcon:J5,SquareSquare:dle,SquareSquareIcon:dle,SquareStack:ule,SquareStackIcon:ule,SquareTerminal:eT,SquareTerminalIcon:eT,SquareUser:sT,SquareUserIcon:sT,SquareUserRound:tT,SquareUserRoundIcon:tT,SquareX:rT,SquareXIcon:rT,Squircle:hle,SquircleIcon:hle,Squirrel:mle,SquirrelIcon:mle,Stamp:fle,StampIcon:fle,Star:ya,StarHalf:ple,StarHalfIcon:ple,StarIcon:ya,StarOff:gle,StarOffIcon:gle,Stars:Lr,StarsIcon:Lr,StepBack:xle,StepBackIcon:xle,StepForward:yle,StepForwardIcon:yle,Stethoscope:vle,StethoscopeIcon:vle,Sticker:ble,StickerIcon:ble,StickyNote:_le,StickyNoteIcon:_le,StopCircle:l3,StopCircleIcon:l3,Store:wle,StoreIcon:wle,StretchHorizontal:jle,StretchHorizontalIcon:jle,StretchVertical:Nle,StretchVerticalIcon:Nle,Strikethrough:LF,StrikethroughIcon:LF,Subscript:kle,SubscriptIcon:kle,Subtitles:CC,SubtitlesIcon:CC,Sun:W2,SunDim:Sle,SunDimIcon:Sle,SunIcon:W2,SunMedium:Cle,SunMediumIcon:Cle,SunMoon:Tle,SunMoonIcon:Tle,SunSnow:Ele,SunSnowIcon:Ele,Sunrise:Ale,SunriseIcon:Ale,Sunset:Mle,SunsetIcon:Mle,Superscript:Ile,SuperscriptIcon:Ile,SwatchBook:Ple,SwatchBookIcon:Ple,SwissFranc:Lle,SwissFrancIcon:Lle,SwitchCamera:Dle,SwitchCameraIcon:Dle,Sword:Rle,SwordIcon:Rle,Swords:Ole,SwordsIcon:Ole,Syringe:Fle,SyringeIcon:Fle,Table:ZI,Table2:YI,Table2Icon:YI,TableCellsMerge:Ble,TableCellsMergeIcon:Ble,TableCellsSplit:zle,TableCellsSplitIcon:zle,TableColumnsSplit:$le,TableColumnsSplitIcon:$le,TableIcon:ZI,TableOfContents:Ule,TableOfContentsIcon:Ule,TableProperties:qle,TablePropertiesIcon:qle,TableRowsSplit:Vle,TableRowsSplitIcon:Vle,Tablet:Gle,TabletIcon:Gle,TabletSmartphone:Hle,TabletSmartphoneIcon:Hle,Tablets:Wle,TabletsIcon:Wle,Tag:xm,TagIcon:xm,Tags:Kle,TagsIcon:Kle,Tally1:Yle,Tally1Icon:Yle,Tally2:Zle,Tally2Icon:Zle,Tally3:Xle,Tally3Icon:Xle,Tally4:Qle,Tally4Icon:Qle,Tally5:Jle,Tally5Icon:Jle,Tangent:ece,TangentIcon:ece,Target:Wu,TargetIcon:Wu,Telescope:tce,TelescopeIcon:tce,Tent:rce,TentIcon:rce,TentTree:sce,TentTreeIcon:sce,Terminal:nce,TerminalIcon:nce,TerminalSquare:eT,TerminalSquareIcon:eT,TestTube:ace,TestTube2:nT,TestTube2Icon:nT,TestTubeDiagonal:nT,TestTubeDiagonalIcon:nT,TestTubeIcon:ace,TestTubes:ice,TestTubesIcon:ice,Text:uce,TextCursor:lce,TextCursorIcon:lce,TextCursorInput:oce,TextCursorInputIcon:oce,TextIcon:uce,TextQuote:cce,TextQuoteIcon:cce,TextSearch:dce,TextSearchIcon:dce,TextSelect:aT,TextSelectIcon:aT,TextSelection:aT,TextSelectionIcon:aT,Theater:hce,TheaterIcon:hce,Thermometer:pce,ThermometerIcon:pce,ThermometerSnowflake:mce,ThermometerSnowflakeIcon:mce,ThermometerSun:fce,ThermometerSunIcon:fce,ThumbsDown:DF,ThumbsDownIcon:DF,ThumbsUp:sf,ThumbsUpIcon:sf,Ticket:RF,TicketCheck:gce,TicketCheckIcon:gce,TicketIcon:RF,TicketMinus:xce,TicketMinusIcon:xce,TicketPercent:yce,TicketPercentIcon:yce,TicketPlus:vce,TicketPlusIcon:vce,TicketSlash:bce,TicketSlashIcon:bce,TicketX:_ce,TicketXIcon:_ce,Tickets:jce,TicketsIcon:jce,TicketsPlane:wce,TicketsPlaneIcon:wce,Timer:Sce,TimerIcon:Sce,TimerOff:Nce,TimerOffIcon:Nce,TimerReset:kce,TimerResetIcon:kce,ToggleLeft:Cce,ToggleLeftIcon:Cce,ToggleRight:Tce,ToggleRightIcon:Tce,Toilet:Ece,ToiletIcon:Ece,Tornado:Ace,TornadoIcon:Ace,Torus:Mce,TorusIcon:Mce,Touchpad:Pce,TouchpadIcon:Pce,TouchpadOff:Ice,TouchpadOffIcon:Ice,TowerControl:Lce,TowerControlIcon:Lce,ToyBrick:Dce,ToyBrickIcon:Dce,Tractor:Rce,TractorIcon:Rce,TrafficCone:Oce,TrafficConeIcon:Oce,Train:iT,TrainFront:Bce,TrainFrontIcon:Bce,TrainFrontTunnel:Fce,TrainFrontTunnelIcon:Fce,TrainIcon:iT,TrainTrack:zce,TrainTrackIcon:zce,TramFront:iT,TramFrontIcon:iT,Trash:$ce,Trash2:Dr,Trash2Icon:Dr,TrashIcon:$ce,TreeDeciduous:Uce,TreeDeciduousIcon:Uce,TreePalm:oT,TreePalmIcon:oT,TreePine:Zk,TreePineIcon:Zk,Trees:qce,TreesIcon:qce,Trello:Vce,TrelloIcon:Vce,TrendingDown:K2,TrendingDownIcon:K2,TrendingUp:al,TrendingUpDown:Hce,TrendingUpDownIcon:Hce,TrendingUpIcon:al,Triangle:Wce,TriangleAlert:uu,TriangleAlertIcon:uu,TriangleIcon:Wce,TriangleRight:Gce,TriangleRightIcon:Gce,Trophy:To,TrophyIcon:To,Truck:OF,TruckIcon:OF,Turtle:Kce,TurtleIcon:Kce,Tv:Zce,Tv2:lT,Tv2Icon:lT,TvIcon:Zce,TvMinimal:lT,TvMinimalIcon:lT,TvMinimalPlay:Yce,TvMinimalPlayIcon:Yce,Twitch:Xce,TwitchIcon:Xce,Twitter:Qce,TwitterIcon:Qce,Type:ede,TypeIcon:ede,TypeOutline:Jce,TypeOutlineIcon:Jce,Umbrella:sde,UmbrellaIcon:sde,UmbrellaOff:tde,UmbrellaOffIcon:tde,Underline:XI,UnderlineIcon:XI,Undo:Xk,Undo2:rde,Undo2Icon:rde,UndoDot:nde,UndoDotIcon:nde,UndoIcon:Xk,UnfoldHorizontal:ade,UnfoldHorizontalIcon:ade,UnfoldVertical:ide,UnfoldVerticalIcon:ide,Ungroup:ode,UngroupIcon:ode,University:cT,UniversityIcon:cT,Unlink:BE,Unlink2:lde,Unlink2Icon:lde,UnlinkIcon:BE,Unlock:B3,UnlockIcon:B3,UnlockKeyhole:F3,UnlockKeyholeIcon:F3,Unplug:cde,UnplugIcon:cde,Upload:Ea,UploadCloud:f3,UploadCloudIcon:f3,UploadIcon:Ea,Usb:dde,UsbIcon:dde,User:io,User2:pT,User2Icon:pT,UserCheck:j1,UserCheck2:dT,UserCheck2Icon:dT,UserCheckIcon:j1,UserCircle:d3,UserCircle2:c3,UserCircle2Icon:c3,UserCircleIcon:d3,UserCog:FF,UserCog2:uT,UserCog2Icon:uT,UserCogIcon:FF,UserIcon:io,UserMinus:BF,UserMinus2:hT,UserMinus2Icon:hT,UserMinusIcon:BF,UserPen:ude,UserPenIcon:ude,UserPlus:Vl,UserPlus2:mT,UserPlus2Icon:mT,UserPlusIcon:Vl,UserRound:pT,UserRoundCheck:dT,UserRoundCheckIcon:dT,UserRoundCog:uT,UserRoundCogIcon:uT,UserRoundIcon:pT,UserRoundMinus:hT,UserRoundMinusIcon:hT,UserRoundPen:hde,UserRoundPenIcon:hde,UserRoundPlus:mT,UserRoundPlusIcon:mT,UserRoundSearch:mde,UserRoundSearchIcon:mde,UserRoundX:fT,UserRoundXIcon:fT,UserSearch:fde,UserSearchIcon:fde,UserSquare:sT,UserSquare2:tT,UserSquare2Icon:tT,UserSquareIcon:sT,UserX:pde,UserX2:fT,UserX2Icon:fT,UserXIcon:pde,Users:Ar,Users2:gT,Users2Icon:gT,UsersIcon:Ar,UsersRound:gT,UsersRoundIcon:gT,Utensils:yT,UtensilsCrossed:xT,UtensilsCrossedIcon:xT,UtensilsIcon:yT,UtilityPole:gde,UtilityPoleIcon:gde,Variable:QI,VariableIcon:QI,Vault:xde,VaultIcon:xde,Vegan:yde,VeganIcon:yde,VenetianMask:vde,VenetianMaskIcon:vde,Verified:wC,VerifiedIcon:wC,Vibrate:_de,VibrateIcon:_de,VibrateOff:bde,VibrateOffIcon:bde,Video:xn,VideoIcon:xn,VideoOff:wde,VideoOffIcon:wde,Videotape:jde,VideotapeIcon:jde,View:Nde,ViewIcon:Nde,Voicemail:kde,VoicemailIcon:kde,Volleyball:Sde,VolleyballIcon:Sde,Volume:Ede,Volume1:Cde,Volume1Icon:Cde,Volume2:zF,Volume2Icon:zF,VolumeIcon:Ede,VolumeOff:Tde,VolumeOffIcon:Tde,VolumeX:$F,VolumeXIcon:$F,Vote:Ade,VoteIcon:Ade,Wallet:UF,Wallet2:vT,Wallet2Icon:vT,WalletCards:Mde,WalletCardsIcon:Mde,WalletIcon:UF,WalletMinimal:vT,WalletMinimalIcon:vT,Wallpaper:Ide,WallpaperIcon:Ide,Wand:Pde,Wand2:My,Wand2Icon:My,WandIcon:Pde,WandSparkles:My,WandSparklesIcon:My,Warehouse:Lde,WarehouseIcon:Lde,WashingMachine:Dde,WashingMachineIcon:Dde,Watch:Rde,WatchIcon:Rde,Waves:Ode,WavesIcon:Ode,Waypoints:Fde,WaypointsIcon:Fde,Webcam:Bde,WebcamIcon:Bde,Webhook:$de,WebhookIcon:$de,WebhookOff:zde,WebhookOffIcon:zde,Weight:Ude,WeightIcon:Ude,Wheat:Vde,WheatIcon:Vde,WheatOff:qde,WheatOffIcon:qde,WholeWord:Hde,WholeWordIcon:Hde,Wifi:Zde,WifiHigh:Gde,WifiHighIcon:Gde,WifiIcon:Zde,WifiLow:Wde,WifiLowIcon:Wde,WifiOff:Kde,WifiOffIcon:Kde,WifiZero:Yde,WifiZeroIcon:Yde,Wind:Qde,WindArrowDown:Xde,WindArrowDownIcon:Xde,WindIcon:Qde,Wine:eue,WineIcon:eue,WineOff:Jde,WineOffIcon:Jde,Workflow:qF,WorkflowIcon:qF,Worm:tue,WormIcon:tue,WrapText:sue,WrapTextIcon:sue,Wrench:N1,WrenchIcon:N1,X:Rr,XCircle:kd,XCircleIcon:kd,XIcon:Rr,XOctagon:q3,XOctagonIcon:q3,XSquare:rT,XSquareIcon:rT,Youtube:rue,YoutubeIcon:rue,Zap:ym,ZapIcon:ym,ZapOff:nue,ZapOffIcon:nue,ZoomIn:Qk,ZoomInIcon:Qk,ZoomOut:JI,ZoomOutIcon:JI,createLucideIcon:te,icons:ZSt},Symbol.toStringTag,{value:"Module"})),b3e="-",XSt=s=>{const t=JSt(s),{conflictingClassGroups:r,conflictingClassGroupModifiers:n}=s;return{getClassGroupId:l=>{const o=l.split(b3e);return o[0]===""&&o.length!==1&&o.shift(),MQe(o,t)||QSt(l)},getConflictingClassGroupIds:(l,o)=>{const c=r[l]||[];return o&&n[l]?[...c,...n[l]]:c}}},MQe=(s,t)=>{var l;if(s.length===0)return t.classGroupId;const r=s[0],n=t.nextPart.get(r),a=n?MQe(s.slice(1),n):void 0;if(a)return a;if(t.validators.length===0)return;const i=s.join(b3e);return(l=t.validators.find(({validator:o})=>o(i)))==null?void 0:l.classGroupId},ERe=/^\[(.+)\]$/,QSt=s=>{if(ERe.test(s)){const t=ERe.exec(s)[1],r=t==null?void 0:t.substring(0,t.indexOf(":"));if(r)return"arbitrary.."+r}},JSt=s=>{const{theme:t,prefix:r}=s,n={nextPart:new Map,validators:[]};return t4t(Object.entries(s.classGroups),r).forEach(([i,l])=>{ije(l,n,i,t)}),n},ije=(s,t,r,n)=>{s.forEach(a=>{if(typeof a=="string"){const i=a===""?t:ARe(t,a);i.classGroupId=r;return}if(typeof a=="function"){if(e4t(a)){ije(a(n),t,r,n);return}t.validators.push({validator:a,classGroupId:r});return}Object.entries(a).forEach(([i,l])=>{ije(l,ARe(t,i),r,n)})})},ARe=(s,t)=>{let r=s;return t.split(b3e).forEach(n=>{r.nextPart.has(n)||r.nextPart.set(n,{nextPart:new Map,validators:[]}),r=r.nextPart.get(n)}),r},e4t=s=>s.isThemeGetter,t4t=(s,t)=>t?s.map(([r,n])=>{const a=n.map(i=>typeof i=="string"?t+i:typeof i=="object"?Object.fromEntries(Object.entries(i).map(([l,o])=>[t+l,o])):i);return[r,a]}):s,s4t=s=>{if(s<1)return{get:()=>{},set:()=>{}};let t=0,r=new Map,n=new Map;const a=(i,l)=>{r.set(i,l),t++,t>s&&(t=0,n=r,r=new Map)};return{get(i){let l=r.get(i);if(l!==void 0)return l;if((l=n.get(i))!==void 0)return a(i,l),l},set(i,l){r.has(i)?r.set(i,l):a(i,l)}}},IQe="!",r4t=s=>{const{separator:t,experimentalParseClassName:r}=s,n=t.length===1,a=t[0],i=t.length,l=o=>{const c=[];let d=0,h=0,m;for(let b=0;bh?m-h:void 0;return{modifiers:c,hasImportantModifier:x,baseClassName:y,maybePostfixModifierPosition:_}};return r?o=>r({className:o,parseClassName:l}):l},n4t=s=>{if(s.length<=1)return s;const t=[];let r=[];return s.forEach(n=>{n[0]==="["?(t.push(...r.sort(),n),r=[]):r.push(n)}),t.push(...r.sort()),t},a4t=s=>({cache:s4t(s.cacheSize),parseClassName:r4t(s),...XSt(s)}),i4t=/\s+/,o4t=(s,t)=>{const{parseClassName:r,getClassGroupId:n,getConflictingClassGroupIds:a}=t,i=[],l=s.trim().split(i4t);let o="";for(let c=l.length-1;c>=0;c-=1){const d=l[c],{modifiers:h,hasImportantModifier:m,baseClassName:p,maybePostfixModifierPosition:x}=r(d);let y=!!x,_=n(y?p.substring(0,x):p);if(!_){if(!y){o=d+(o.length>0?" "+o:o);continue}if(_=n(p),!_){o=d+(o.length>0?" "+o:o);continue}y=!1}const b=n4t(h).join(":"),j=m?b+IQe:b,k=j+_;if(i.includes(k))continue;i.push(k);const T=a(_,y);for(let E=0;E0?" "+o:o)}return o};function l4t(){let s=0,t,r,n="";for(;s{if(typeof s=="string")return s;let t,r="";for(let n=0;nm(h),s());return r=a4t(d),n=r.cache.get,a=r.cache.set,i=o,o(c)}function o(c){const d=n(c);if(d)return d;const h=o4t(c,r);return a(c,h),h}return function(){return i(l4t.apply(null,arguments))}}const vd=s=>{const t=r=>r[s]||[];return t.isThemeGetter=!0,t},LQe=/^\[(?:([a-z-]+):)?(.+)\]$/i,d4t=/^\d+\/\d+$/,u4t=new Set(["px","full","screen"]),h4t=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,m4t=/\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$/,f4t=/^(rgba?|hsla?|hwb|(ok)?(lab|lch))\(.+\)$/,p4t=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,g4t=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Qw=s=>eP(s)||u4t.has(s)||d4t.test(s),gN=s=>r8(s,"length",N4t),eP=s=>!!s&&!Number.isNaN(Number(s)),I1e=s=>r8(s,"number",eP),bR=s=>!!s&&Number.isInteger(Number(s)),x4t=s=>s.endsWith("%")&&eP(s.slice(0,-1)),Ao=s=>LQe.test(s),xN=s=>h4t.test(s),y4t=new Set(["length","size","percentage"]),v4t=s=>r8(s,y4t,DQe),b4t=s=>r8(s,"position",DQe),_4t=new Set(["image","url"]),w4t=s=>r8(s,_4t,S4t),j4t=s=>r8(s,"",k4t),_R=()=>!0,r8=(s,t,r)=>{const n=LQe.exec(s);return n?n[1]?typeof t=="string"?n[1]===t:t.has(n[1]):r(n[2]):!1},N4t=s=>m4t.test(s)&&!f4t.test(s),DQe=()=>!1,k4t=s=>p4t.test(s),S4t=s=>g4t.test(s),C4t=()=>{const s=vd("colors"),t=vd("spacing"),r=vd("blur"),n=vd("brightness"),a=vd("borderColor"),i=vd("borderRadius"),l=vd("borderSpacing"),o=vd("borderWidth"),c=vd("contrast"),d=vd("grayscale"),h=vd("hueRotate"),m=vd("invert"),p=vd("gap"),x=vd("gradientColorStops"),y=vd("gradientColorStopPositions"),_=vd("inset"),b=vd("margin"),j=vd("opacity"),k=vd("padding"),T=vd("saturate"),E=vd("scale"),A=vd("sepia"),D=vd("skew"),R=vd("space"),z=vd("translate"),O=()=>["auto","contain","none"],$=()=>["auto","hidden","clip","visible","scroll"],ee=()=>["auto",Ao,t],Z=()=>[Ao,t],J=()=>["",Qw,gN],K=()=>["auto",eP,Ao],re=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],ie=()=>["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"],ne=()=>["start","end","center","between","around","evenly","stretch"],le=()=>["","0",Ao],be=()=>["auto","avoid","all","avoid-page","page","left","right","column"],fe=()=>[eP,Ao];return{cacheSize:500,separator:":",theme:{colors:[_R],spacing:[Qw,gN],blur:["none","",xN,Ao],brightness:fe(),borderColor:[s],borderRadius:["none","","full",xN,Ao],borderSpacing:Z(),borderWidth:J(),contrast:fe(),grayscale:le(),hueRotate:fe(),invert:le(),gap:Z(),gradientColorStops:[s],gradientColorStopPositions:[x4t,gN],inset:ee(),margin:ee(),opacity:fe(),padding:Z(),saturate:fe(),scale:fe(),sepia:le(),skew:fe(),space:Z(),translate:Z()},classGroups:{aspect:[{aspect:["auto","square","video",Ao]}],container:["container"],columns:[{columns:[xN]}],"break-after":[{"break-after":be()}],"break-before":[{"break-before":be()}],"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:[...re(),Ao]}],overflow:[{overflow:$()}],"overflow-x":[{"overflow-x":$()}],"overflow-y":[{"overflow-y":$()}],overscroll:[{overscroll:O()}],"overscroll-x":[{"overscroll-x":O()}],"overscroll-y":[{"overscroll-y":O()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[_]}],"inset-x":[{"inset-x":[_]}],"inset-y":[{"inset-y":[_]}],start:[{start:[_]}],end:[{end:[_]}],top:[{top:[_]}],right:[{right:[_]}],bottom:[{bottom:[_]}],left:[{left:[_]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",bR,Ao]}],basis:[{basis:ee()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",Ao]}],grow:[{grow:le()}],shrink:[{shrink:le()}],order:[{order:["first","last","none",bR,Ao]}],"grid-cols":[{"grid-cols":[_R]}],"col-start-end":[{col:["auto",{span:["full",bR,Ao]},Ao]}],"col-start":[{"col-start":K()}],"col-end":[{"col-end":K()}],"grid-rows":[{"grid-rows":[_R]}],"row-start-end":[{row:["auto",{span:[bR,Ao]},Ao]}],"row-start":[{"row-start":K()}],"row-end":[{"row-end":K()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",Ao]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",Ao]}],gap:[{gap:[p]}],"gap-x":[{"gap-x":[p]}],"gap-y":[{"gap-y":[p]}],"justify-content":[{justify:["normal",...ne()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...ne(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...ne(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[k]}],px:[{px:[k]}],py:[{py:[k]}],ps:[{ps:[k]}],pe:[{pe:[k]}],pt:[{pt:[k]}],pr:[{pr:[k]}],pb:[{pb:[k]}],pl:[{pl:[k]}],m:[{m:[b]}],mx:[{mx:[b]}],my:[{my:[b]}],ms:[{ms:[b]}],me:[{me:[b]}],mt:[{mt:[b]}],mr:[{mr:[b]}],mb:[{mb:[b]}],ml:[{ml:[b]}],"space-x":[{"space-x":[R]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[R]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",Ao,t]}],"min-w":[{"min-w":[Ao,t,"min","max","fit"]}],"max-w":[{"max-w":[Ao,t,"none","full","min","max","fit","prose",{screen:[xN]},xN]}],h:[{h:[Ao,t,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[Ao,t,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[Ao,t,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[Ao,t,"auto","min","max","fit"]}],"font-size":[{text:["base",xN,gN]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",I1e]}],"font-family":[{font:[_R]}],"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",Ao]}],"line-clamp":[{"line-clamp":["none",eP,I1e]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",Qw,Ao]}],"list-image":[{"list-image":["none",Ao]}],"list-style-type":[{list:["none","disc","decimal",Ao]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[s]}],"placeholder-opacity":[{"placeholder-opacity":[j]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[s]}],"text-opacity":[{"text-opacity":[j]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...ie(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",Qw,gN]}],"underline-offset":[{"underline-offset":["auto",Qw,Ao]}],"text-decoration-color":[{decoration:[s]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:Z()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Ao]}],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",Ao]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[j]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...re(),b4t]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",v4t]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},w4t]}],"bg-color":[{bg:[s]}],"gradient-from-pos":[{from:[y]}],"gradient-via-pos":[{via:[y]}],"gradient-to-pos":[{to:[y]}],"gradient-from":[{from:[x]}],"gradient-via":[{via:[x]}],"gradient-to":[{to:[x]}],rounded:[{rounded:[i]}],"rounded-s":[{"rounded-s":[i]}],"rounded-e":[{"rounded-e":[i]}],"rounded-t":[{"rounded-t":[i]}],"rounded-r":[{"rounded-r":[i]}],"rounded-b":[{"rounded-b":[i]}],"rounded-l":[{"rounded-l":[i]}],"rounded-ss":[{"rounded-ss":[i]}],"rounded-se":[{"rounded-se":[i]}],"rounded-ee":[{"rounded-ee":[i]}],"rounded-es":[{"rounded-es":[i]}],"rounded-tl":[{"rounded-tl":[i]}],"rounded-tr":[{"rounded-tr":[i]}],"rounded-br":[{"rounded-br":[i]}],"rounded-bl":[{"rounded-bl":[i]}],"border-w":[{border:[o]}],"border-w-x":[{"border-x":[o]}],"border-w-y":[{"border-y":[o]}],"border-w-s":[{"border-s":[o]}],"border-w-e":[{"border-e":[o]}],"border-w-t":[{"border-t":[o]}],"border-w-r":[{"border-r":[o]}],"border-w-b":[{"border-b":[o]}],"border-w-l":[{"border-l":[o]}],"border-opacity":[{"border-opacity":[j]}],"border-style":[{border:[...ie(),"hidden"]}],"divide-x":[{"divide-x":[o]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[o]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[j]}],"divide-style":[{divide:ie()}],"border-color":[{border:[a]}],"border-color-x":[{"border-x":[a]}],"border-color-y":[{"border-y":[a]}],"border-color-s":[{"border-s":[a]}],"border-color-e":[{"border-e":[a]}],"border-color-t":[{"border-t":[a]}],"border-color-r":[{"border-r":[a]}],"border-color-b":[{"border-b":[a]}],"border-color-l":[{"border-l":[a]}],"divide-color":[{divide:[a]}],"outline-style":[{outline:["",...ie()]}],"outline-offset":[{"outline-offset":[Qw,Ao]}],"outline-w":[{outline:[Qw,gN]}],"outline-color":[{outline:[s]}],"ring-w":[{ring:J()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[s]}],"ring-opacity":[{"ring-opacity":[j]}],"ring-offset-w":[{"ring-offset":[Qw,gN]}],"ring-offset-color":[{"ring-offset":[s]}],shadow:[{shadow:["","inner","none",xN,j4t]}],"shadow-color":[{shadow:[_R]}],opacity:[{opacity:[j]}],"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:[c]}],"drop-shadow":[{"drop-shadow":["","none",xN,Ao]}],grayscale:[{grayscale:[d]}],"hue-rotate":[{"hue-rotate":[h]}],invert:[{invert:[m]}],saturate:[{saturate:[T]}],sepia:[{sepia:[A]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[r]}],"backdrop-brightness":[{"backdrop-brightness":[n]}],"backdrop-contrast":[{"backdrop-contrast":[c]}],"backdrop-grayscale":[{"backdrop-grayscale":[d]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[h]}],"backdrop-invert":[{"backdrop-invert":[m]}],"backdrop-opacity":[{"backdrop-opacity":[j]}],"backdrop-saturate":[{"backdrop-saturate":[T]}],"backdrop-sepia":[{"backdrop-sepia":[A]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":[l]}],"border-spacing-x":[{"border-spacing-x":[l]}],"border-spacing-y":[{"border-spacing-y":[l]}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["none","all","","colors","opacity","shadow","transform",Ao]}],duration:[{duration:fe()}],ease:[{ease:["linear","in","out","in-out",Ao]}],delay:[{delay:fe()}],animate:[{animate:["none","spin","ping","pulse","bounce",Ao]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[E]}],"scale-x":[{"scale-x":[E]}],"scale-y":[{"scale-y":[E]}],rotate:[{rotate:[bR,Ao]}],"translate-x":[{"translate-x":[z]}],"translate-y":[{"translate-y":[z]}],"skew-x":[{"skew-x":[D]}],"skew-y":[{"skew-y":[D]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",Ao]}],accent:[{accent:["auto",s]}],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",Ao]}],"caret-color":[{caret:[s]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":Z()}],"scroll-mx":[{"scroll-mx":Z()}],"scroll-my":[{"scroll-my":Z()}],"scroll-ms":[{"scroll-ms":Z()}],"scroll-me":[{"scroll-me":Z()}],"scroll-mt":[{"scroll-mt":Z()}],"scroll-mr":[{"scroll-mr":Z()}],"scroll-mb":[{"scroll-mb":Z()}],"scroll-ml":[{"scroll-ml":Z()}],"scroll-p":[{"scroll-p":Z()}],"scroll-px":[{"scroll-px":Z()}],"scroll-py":[{"scroll-py":Z()}],"scroll-ps":[{"scroll-ps":Z()}],"scroll-pe":[{"scroll-pe":Z()}],"scroll-pt":[{"scroll-pt":Z()}],"scroll-pr":[{"scroll-pr":Z()}],"scroll-pb":[{"scroll-pb":Z()}],"scroll-pl":[{"scroll-pl":Z()}],"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",Ao]}],fill:[{fill:[s,"none"]}],"stroke-w":[{stroke:[Qw,gN,I1e]}],stroke:[{stroke:[s,"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"]}}},T4t=c4t(C4t);function Ft(...s){return T4t(jo(s))}function sd(s,t=!1){return t&&s>=1e6?`$${(s/1e6).toFixed(1)}M`:t&&s>=1e3?`$${(s/1e3).toFixed(0)}K`:new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:0}).format(s)}function MRe(s){const t=new Date(s);return new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric"}).format(t)}function Q7(s){return s?s.replace(/<[^>]*>/g,""):""}const E4t=WSt,RQe=S.forwardRef(({className:s,...t},r)=>e.jsx(wQe,{ref:r,className:Ft("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]",s),...t}));RQe.displayName=wQe.displayName;const A4t=zA("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"}}),OQe=S.forwardRef(({className:s,variant:t,...r},n)=>e.jsx(jQe,{ref:n,className:Ft(A4t({variant:t}),s),...r}));OQe.displayName=jQe.displayName;const M4t=S.forwardRef(({className:s,...t},r)=>e.jsx(SQe,{ref:r,className:Ft("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",s),...t}));M4t.displayName=SQe.displayName;const FQe=S.forwardRef(({className:s,...t},r)=>e.jsx(CQe,{ref:r,className:Ft("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",s),"toast-close":"",...t,children:e.jsx(Rr,{className:"h-4 w-4"})}));FQe.displayName=CQe.displayName;const BQe=S.forwardRef(({className:s,...t},r)=>e.jsx(NQe,{ref:r,className:Ft("text-sm font-semibold",s),...t}));BQe.displayName=NQe.displayName;const zQe=S.forwardRef(({className:s,...t},r)=>e.jsx(kQe,{ref:r,className:Ft("text-sm opacity-90",s),...t}));zQe.displayName=kQe.displayName;function I4t(){const{toasts:s}=li();return e.jsxs(E4t,{children:[s.map(function({id:t,title:r,description:n,action:a,...i}){return e.jsxs(OQe,{...i,children:[e.jsxs("div",{className:"grid gap-1",children:[r&&e.jsx(BQe,{children:r}),n&&e.jsx(zQe,{children:n})]}),a,e.jsx(FQe,{})]},t)}),e.jsx(RQe,{})]})}var IRe=["light","dark"],P4t="(prefers-color-scheme: dark)",L4t=S.createContext(void 0),D4t={setTheme:s=>{},themes:[]},R4t=()=>{var s;return(s=S.useContext(L4t))!=null?s:D4t};S.memo(({forcedTheme:s,storageKey:t,attribute:r,enableSystem:n,enableColorScheme:a,defaultTheme:i,value:l,attrs:o,nonce:c})=>{let d=i==="system",h=r==="class"?`var d=document.documentElement,c=d.classList;${`c.remove(${o.map(y=>`'${y}'`).join(",")})`};`:`var d=document.documentElement,n='${r}',s='setAttribute';`,m=a?IRe.includes(i)&&i?`if(e==='light'||e==='dark'||!e)d.style.colorScheme=e||'${i}'`:"if(e==='light'||e==='dark')d.style.colorScheme=e":"",p=(y,_=!1,b=!0)=>{let j=l?l[y]:y,k=_?y+"|| ''":`'${j}'`,T="";return a&&b&&!_&&IRe.includes(y)&&(T+=`d.style.colorScheme = '${y}';`),r==="class"?_||j?T+=`c.add(${k})`:T+="null":j&&(T+=`d[s](n,${k})`),T},x=s?`!function(){${h}${p(s)}}()`:n?`!function(){try{${h}var e=localStorage.getItem('${t}');if('system'===e||(!e&&${d})){var t='${P4t}',m=window.matchMedia(t);if(m.media!==t||m.matches){${p("dark")}}else{${p("light")}}}else if(e){${l?`var x=${JSON.stringify(l)};`:""}${p(l?"x[e]":"e",!0)}}${d?"":"else{"+p(i,!1,!1)+"}"}${m}}catch(e){}}()`:`!function(){try{${h}var e=localStorage.getItem('${t}');if(e){${l?`var x=${JSON.stringify(l)};`:""}${p(l?"x[e]":"e",!0)}}else{${p(i,!1,!1)};}${m}}catch(t){}}();`;return S.createElement("script",{nonce:c,dangerouslySetInnerHTML:{__html:x}})});var O4t=s=>{switch(s){case"success":return z4t;case"info":return U4t;case"warning":return $4t;case"error":return q4t;default:return null}},F4t=Array(12).fill(0),B4t=({visible:s,className:t})=>Nt.createElement("div",{className:["sonner-loading-wrapper",t].filter(Boolean).join(" "),"data-visible":s},Nt.createElement("div",{className:"sonner-spinner"},F4t.map((r,n)=>Nt.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${n}`})))),z4t=Nt.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},Nt.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"})),$4t=Nt.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",height:"20",width:"20"},Nt.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"})),U4t=Nt.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},Nt.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"})),q4t=Nt.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},Nt.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"})),V4t=Nt.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"},Nt.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),Nt.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"})),H4t=()=>{let[s,t]=Nt.useState(document.hidden);return Nt.useEffect(()=>{let r=()=>{t(document.hidden)};return document.addEventListener("visibilitychange",r),()=>window.removeEventListener("visibilitychange",r)},[]),s},oje=1,G4t=class{constructor(){this.subscribe=t=>(this.subscribers.push(t),()=>{let r=this.subscribers.indexOf(t);this.subscribers.splice(r,1)}),this.publish=t=>{this.subscribers.forEach(r=>r(t))},this.addToast=t=>{this.publish(t),this.toasts=[...this.toasts,t]},this.create=t=>{var r;let{message:n,...a}=t,i=typeof(t==null?void 0:t.id)=="number"||((r=t.id)==null?void 0:r.length)>0?t.id:oje++,l=this.toasts.find(c=>c.id===i),o=t.dismissible===void 0?!0:t.dismissible;return this.dismissedToasts.has(i)&&this.dismissedToasts.delete(i),l?this.toasts=this.toasts.map(c=>c.id===i?(this.publish({...c,...t,id:i,title:n}),{...c,...t,id:i,dismissible:o,title:n}):c):this.addToast({title:n,...a,dismissible:o,id:i}),i},this.dismiss=t=>(this.dismissedToasts.add(t),t||this.toasts.forEach(r=>{this.subscribers.forEach(n=>n({id:r.id,dismiss:!0}))}),this.subscribers.forEach(r=>r({id:t,dismiss:!0})),t),this.message=(t,r)=>this.create({...r,message:t}),this.error=(t,r)=>this.create({...r,message:t,type:"error"}),this.success=(t,r)=>this.create({...r,type:"success",message:t}),this.info=(t,r)=>this.create({...r,type:"info",message:t}),this.warning=(t,r)=>this.create({...r,type:"warning",message:t}),this.loading=(t,r)=>this.create({...r,type:"loading",message:t}),this.promise=(t,r)=>{if(!r)return;let n;r.loading!==void 0&&(n=this.create({...r,promise:t,type:"loading",message:r.loading,description:typeof r.description!="function"?r.description:void 0}));let a=t instanceof Promise?t:t(),i=n!==void 0,l,o=a.then(async d=>{if(l=["resolve",d],Nt.isValidElement(d))i=!1,this.create({id:n,type:"default",message:d});else if(K4t(d)&&!d.ok){i=!1;let h=typeof r.error=="function"?await r.error(`HTTP error! status: ${d.status}`):r.error,m=typeof r.description=="function"?await r.description(`HTTP error! status: ${d.status}`):r.description;this.create({id:n,type:"error",message:h,description:m})}else if(r.success!==void 0){i=!1;let h=typeof r.success=="function"?await r.success(d):r.success,m=typeof r.description=="function"?await r.description(d):r.description;this.create({id:n,type:"success",message:h,description:m})}}).catch(async d=>{if(l=["reject",d],r.error!==void 0){i=!1;let h=typeof r.error=="function"?await r.error(d):r.error,m=typeof r.description=="function"?await r.description(d):r.description;this.create({id:n,type:"error",message:h,description:m})}}).finally(()=>{var d;i&&(this.dismiss(n),n=void 0),(d=r.finally)==null||d.call(r)}),c=()=>new Promise((d,h)=>o.then(()=>l[0]==="reject"?h(l[1]):d(l[1])).catch(h));return typeof n!="string"&&typeof n!="number"?{unwrap:c}:Object.assign(n,{unwrap:c})},this.custom=(t,r)=>{let n=(r==null?void 0:r.id)||oje++;return this.create({jsx:t(n),id:n,...r}),n},this.getActiveToasts=()=>this.toasts.filter(t=>!this.dismissedToasts.has(t.id)),this.subscribers=[],this.toasts=[],this.dismissedToasts=new Set}},Yg=new G4t,W4t=(s,t)=>{let r=(t==null?void 0:t.id)||oje++;return Yg.addToast({title:s,...t,id:r}),r},K4t=s=>s&&typeof s=="object"&&"ok"in s&&typeof s.ok=="boolean"&&"status"in s&&typeof s.status=="number",Y4t=W4t,Z4t=()=>Yg.toasts,X4t=()=>Yg.getActiveToasts(),he=Object.assign(Y4t,{success:Yg.success,info:Yg.info,warning:Yg.warning,error:Yg.error,custom:Yg.custom,message:Yg.message,promise:Yg.promise,dismiss:Yg.dismiss,loading:Yg.loading},{getHistory:Z4t,getToasts:X4t});function Q4t(s,{insertAt:t}={}){if(typeof document>"u")return;let r=document.head||document.getElementsByTagName("head")[0],n=document.createElement("style");n.type="text/css",t==="top"&&r.firstChild?r.insertBefore(n,r.firstChild):r.appendChild(n),n.styleSheet?n.styleSheet.cssText=s:n.appendChild(document.createTextNode(s))}Q4t(`: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 AU(s){return s.label!==void 0}var J4t=3,eCt="32px",tCt="16px",PRe=4e3,sCt=356,rCt=14,nCt=20,aCt=200;function qv(...s){return s.filter(Boolean).join(" ")}function iCt(s){let[t,r]=s.split("-"),n=[];return t&&n.push(t),r&&n.push(r),n}var oCt=s=>{var t,r,n,a,i,l,o,c,d,h,m;let{invert:p,toast:x,unstyled:y,interacting:_,setHeights:b,visibleToasts:j,heights:k,index:T,toasts:E,expanded:A,removeToast:D,defaultRichColors:R,closeButton:z,style:O,cancelButtonStyle:$,actionButtonStyle:ee,className:Z="",descriptionClassName:J="",duration:K,position:re,gap:ie,loadingIcon:ce,expandByDefault:ne,classNames:le,icons:be,closeButtonAriaLabel:fe="Close toast",pauseWhenPageIsHidden:je}=s,[ve,We]=Nt.useState(null),[Ve,Le]=Nt.useState(null),[Me,ze]=Nt.useState(!1),[Pe,Ie]=Nt.useState(!1),[De,pe]=Nt.useState(!1),[tt,ge]=Nt.useState(!1),[ct,Ue]=Nt.useState(!1),[et,Qe]=Nt.useState(0),[Ne,$e]=Nt.useState(0),it=Nt.useRef(x.duration||K||PRe),Je=Nt.useRef(null),st=Nt.useRef(null),mt=T===0,wt=T+1<=j,at=x.type,rt=x.dismissible!==!1,Et=x.className||"",hs=x.descriptionClassName||"",Is=Nt.useMemo(()=>k.findIndex($r=>$r.toastId===x.id)||0,[k,x.id]),lr=Nt.useMemo(()=>{var $r;return($r=x.closeButton)!=null?$r:z},[x.closeButton,z]),us=Nt.useMemo(()=>x.duration||K||PRe,[x.duration,K]),St=Nt.useRef(0),xs=Nt.useRef(0),kt=Nt.useRef(0),fs=Nt.useRef(null),[Gs,_s]=re.split("-"),br=Nt.useMemo(()=>k.reduce(($r,hn,Zn)=>Zn>=Is?$r:$r+hn.height,0),[k,Is]),zr=H4t(),Yr=x.invert||p,rn=at==="loading";xs.current=Nt.useMemo(()=>Is*ie+br,[Is,br]),Nt.useEffect(()=>{it.current=us},[us]),Nt.useEffect(()=>{ze(!0)},[]),Nt.useEffect(()=>{let $r=st.current;if($r){let hn=$r.getBoundingClientRect().height;return $e(hn),b(Zn=>[{toastId:x.id,height:hn,position:x.position},...Zn]),()=>b(Zn=>Zn.filter(cr=>cr.toastId!==x.id))}},[b,x.id]),Nt.useLayoutEffect(()=>{if(!Me)return;let $r=st.current,hn=$r.style.height;$r.style.height="auto";let Zn=$r.getBoundingClientRect().height;$r.style.height=hn,$e(Zn),b(cr=>cr.find(on=>on.toastId===x.id)?cr.map(on=>on.toastId===x.id?{...on,height:Zn}:on):[{toastId:x.id,height:Zn,position:x.position},...cr])},[Me,x.title,x.description,b,x.id]);let sn=Nt.useCallback(()=>{Ie(!0),Qe(xs.current),b($r=>$r.filter(hn=>hn.toastId!==x.id)),setTimeout(()=>{D(x)},aCt)},[x,D,b,xs]);Nt.useEffect(()=>{if(x.promise&&at==="loading"||x.duration===1/0||x.type==="loading")return;let $r;return A||_||je&&zr?(()=>{if(kt.current{var hn;(hn=x.onAutoClose)==null||hn.call(x,x),sn()},it.current)),()=>clearTimeout($r)},[A,_,x,at,je,zr,sn]),Nt.useEffect(()=>{x.delete&&sn()},[sn,x.delete]);function Vr(){var $r,hn,Zn;return be!=null&&be.loading?Nt.createElement("div",{className:qv(le==null?void 0:le.loader,($r=x==null?void 0:x.classNames)==null?void 0:$r.loader,"sonner-loader"),"data-visible":at==="loading"},be.loading):ce?Nt.createElement("div",{className:qv(le==null?void 0:le.loader,(hn=x==null?void 0:x.classNames)==null?void 0:hn.loader,"sonner-loader"),"data-visible":at==="loading"},ce):Nt.createElement(B4t,{className:qv(le==null?void 0:le.loader,(Zn=x==null?void 0:x.classNames)==null?void 0:Zn.loader),visible:at==="loading"})}return Nt.createElement("li",{tabIndex:0,ref:st,className:qv(Z,Et,le==null?void 0:le.toast,(t=x==null?void 0:x.classNames)==null?void 0:t.toast,le==null?void 0:le.default,le==null?void 0:le[at],(r=x==null?void 0:x.classNames)==null?void 0:r[at]),"data-sonner-toast":"","data-rich-colors":(n=x.richColors)!=null?n:R,"data-styled":!(x.jsx||x.unstyled||y),"data-mounted":Me,"data-promise":!!x.promise,"data-swiped":ct,"data-removed":Pe,"data-visible":wt,"data-y-position":Gs,"data-x-position":_s,"data-index":T,"data-front":mt,"data-swiping":De,"data-dismissible":rt,"data-type":at,"data-invert":Yr,"data-swipe-out":tt,"data-swipe-direction":Ve,"data-expanded":!!(A||ne&&Me),style:{"--index":T,"--toasts-before":T,"--z-index":E.length-T,"--offset":`${Pe?et:xs.current}px`,"--initial-height":ne?"auto":`${Ne}px`,...O,...x.style},onDragEnd:()=>{pe(!1),We(null),fs.current=null},onPointerDown:$r=>{rn||!rt||(Je.current=new Date,Qe(xs.current),$r.target.setPointerCapture($r.pointerId),$r.target.tagName!=="BUTTON"&&(pe(!0),fs.current={x:$r.clientX,y:$r.clientY}))},onPointerUp:()=>{var $r,hn,Zn,cr;if(tt||!rt)return;fs.current=null;let on=Number((($r=st.current)==null?void 0:$r.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),ds=Number(((hn=st.current)==null?void 0:hn.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),Na=new Date().getTime()-((Zn=Je.current)==null?void 0:Zn.getTime()),vn=ve==="x"?on:ds,_r=Math.abs(vn)/Na;if(Math.abs(vn)>=nCt||_r>.11){Qe(xs.current),(cr=x.onDismiss)==null||cr.call(x,x),Le(ve==="x"?on>0?"right":"left":ds>0?"down":"up"),sn(),ge(!0),Ue(!1);return}pe(!1),We(null)},onPointerMove:$r=>{var hn,Zn,cr,on;if(!fs.current||!rt||((hn=window.getSelection())==null?void 0:hn.toString().length)>0)return;let ds=$r.clientY-fs.current.y,Na=$r.clientX-fs.current.x,vn=(Zn=s.swipeDirections)!=null?Zn:iCt(re);!ve&&(Math.abs(Na)>1||Math.abs(ds)>1)&&We(Math.abs(Na)>Math.abs(ds)?"x":"y");let _r={x:0,y:0};ve==="y"?(vn.includes("top")||vn.includes("bottom"))&&(vn.includes("top")&&ds<0||vn.includes("bottom")&&ds>0)&&(_r.y=ds):ve==="x"&&(vn.includes("left")||vn.includes("right"))&&(vn.includes("left")&&Na<0||vn.includes("right")&&Na>0)&&(_r.x=Na),(Math.abs(_r.x)>0||Math.abs(_r.y)>0)&&Ue(!0),(cr=st.current)==null||cr.style.setProperty("--swipe-amount-x",`${_r.x}px`),(on=st.current)==null||on.style.setProperty("--swipe-amount-y",`${_r.y}px`)}},lr&&!x.jsx?Nt.createElement("button",{"aria-label":fe,"data-disabled":rn,"data-close-button":!0,onClick:rn||!rt?()=>{}:()=>{var $r;sn(),($r=x.onDismiss)==null||$r.call(x,x)},className:qv(le==null?void 0:le.closeButton,(a=x==null?void 0:x.classNames)==null?void 0:a.closeButton)},(i=be==null?void 0:be.close)!=null?i:V4t):null,x.jsx||S.isValidElement(x.title)?x.jsx?x.jsx:typeof x.title=="function"?x.title():x.title:Nt.createElement(Nt.Fragment,null,at||x.icon||x.promise?Nt.createElement("div",{"data-icon":"",className:qv(le==null?void 0:le.icon,(l=x==null?void 0:x.classNames)==null?void 0:l.icon)},x.promise||x.type==="loading"&&!x.icon?x.icon||Vr():null,x.type!=="loading"?x.icon||(be==null?void 0:be[at])||O4t(at):null):null,Nt.createElement("div",{"data-content":"",className:qv(le==null?void 0:le.content,(o=x==null?void 0:x.classNames)==null?void 0:o.content)},Nt.createElement("div",{"data-title":"",className:qv(le==null?void 0:le.title,(c=x==null?void 0:x.classNames)==null?void 0:c.title)},typeof x.title=="function"?x.title():x.title),x.description?Nt.createElement("div",{"data-description":"",className:qv(J,hs,le==null?void 0:le.description,(d=x==null?void 0:x.classNames)==null?void 0:d.description)},typeof x.description=="function"?x.description():x.description):null),S.isValidElement(x.cancel)?x.cancel:x.cancel&&AU(x.cancel)?Nt.createElement("button",{"data-button":!0,"data-cancel":!0,style:x.cancelButtonStyle||$,onClick:$r=>{var hn,Zn;AU(x.cancel)&&rt&&((Zn=(hn=x.cancel).onClick)==null||Zn.call(hn,$r),sn())},className:qv(le==null?void 0:le.cancelButton,(h=x==null?void 0:x.classNames)==null?void 0:h.cancelButton)},x.cancel.label):null,S.isValidElement(x.action)?x.action:x.action&&AU(x.action)?Nt.createElement("button",{"data-button":!0,"data-action":!0,style:x.actionButtonStyle||ee,onClick:$r=>{var hn,Zn;AU(x.action)&&((Zn=(hn=x.action).onClick)==null||Zn.call(hn,$r),!$r.defaultPrevented&&sn())},className:qv(le==null?void 0:le.actionButton,(m=x==null?void 0:x.classNames)==null?void 0:m.actionButton)},x.action.label):null))};function LRe(){if(typeof window>"u"||typeof document>"u")return"ltr";let s=document.documentElement.getAttribute("dir");return s==="auto"||!s?window.getComputedStyle(document.documentElement).direction:s}function lCt(s,t){let r={};return[s,t].forEach((n,a)=>{let i=a===1,l=i?"--mobile-offset":"--offset",o=i?tCt:eCt;function c(d){["top","right","bottom","left"].forEach(h=>{r[`${l}-${h}`]=typeof d=="number"?`${d}px`:d})}typeof n=="number"||typeof n=="string"?c(n):typeof n=="object"?["top","right","bottom","left"].forEach(d=>{n[d]===void 0?r[`${l}-${d}`]=o:r[`${l}-${d}`]=typeof n[d]=="number"?`${n[d]}px`:n[d]}):c(o)}),r}var cCt=S.forwardRef(function(s,t){let{invert:r,position:n="bottom-right",hotkey:a=["altKey","KeyT"],expand:i,closeButton:l,className:o,offset:c,mobileOffset:d,theme:h="light",richColors:m,duration:p,style:x,visibleToasts:y=J4t,toastOptions:_,dir:b=LRe(),gap:j=rCt,loadingIcon:k,icons:T,containerAriaLabel:E="Notifications",pauseWhenPageIsHidden:A}=s,[D,R]=Nt.useState([]),z=Nt.useMemo(()=>Array.from(new Set([n].concat(D.filter(je=>je.position).map(je=>je.position)))),[D,n]),[O,$]=Nt.useState([]),[ee,Z]=Nt.useState(!1),[J,K]=Nt.useState(!1),[re,ie]=Nt.useState(h!=="system"?h:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),ce=Nt.useRef(null),ne=a.join("+").replace(/Key/g,"").replace(/Digit/g,""),le=Nt.useRef(null),be=Nt.useRef(!1),fe=Nt.useCallback(je=>{R(ve=>{var We;return(We=ve.find(Ve=>Ve.id===je.id))!=null&&We.delete||Yg.dismiss(je.id),ve.filter(({id:Ve})=>Ve!==je.id)})},[]);return Nt.useEffect(()=>Yg.subscribe(je=>{if(je.dismiss){R(ve=>ve.map(We=>We.id===je.id?{...We,delete:!0}:We));return}setTimeout(()=>{f3e.flushSync(()=>{R(ve=>{let We=ve.findIndex(Ve=>Ve.id===je.id);return We!==-1?[...ve.slice(0,We),{...ve[We],...je},...ve.slice(We+1)]:[je,...ve]})})})}),[]),Nt.useEffect(()=>{if(h!=="system"){ie(h);return}if(h==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?ie("dark"):ie("light")),typeof window>"u")return;let je=window.matchMedia("(prefers-color-scheme: dark)");try{je.addEventListener("change",({matches:ve})=>{ie(ve?"dark":"light")})}catch{je.addListener(({matches:We})=>{try{ie(We?"dark":"light")}catch(Ve){console.error(Ve)}})}},[h]),Nt.useEffect(()=>{D.length<=1&&Z(!1)},[D]),Nt.useEffect(()=>{let je=ve=>{var We,Ve;a.every(Le=>ve[Le]||ve.code===Le)&&(Z(!0),(We=ce.current)==null||We.focus()),ve.code==="Escape"&&(document.activeElement===ce.current||(Ve=ce.current)!=null&&Ve.contains(document.activeElement))&&Z(!1)};return document.addEventListener("keydown",je),()=>document.removeEventListener("keydown",je)},[a]),Nt.useEffect(()=>{if(ce.current)return()=>{le.current&&(le.current.focus({preventScroll:!0}),le.current=null,be.current=!1)}},[ce.current]),Nt.createElement("section",{ref:t,"aria-label":`${E} ${ne}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},z.map((je,ve)=>{var We;let[Ve,Le]=je.split("-");return D.length?Nt.createElement("ol",{key:je,dir:b==="auto"?LRe():b,tabIndex:-1,ref:ce,className:o,"data-sonner-toaster":!0,"data-theme":re,"data-y-position":Ve,"data-lifted":ee&&D.length>1&&!i,"data-x-position":Le,style:{"--front-toast-height":`${((We=O[0])==null?void 0:We.height)||0}px`,"--width":`${sCt}px`,"--gap":`${j}px`,...x,...lCt(c,d)},onBlur:Me=>{be.current&&!Me.currentTarget.contains(Me.relatedTarget)&&(be.current=!1,le.current&&(le.current.focus({preventScroll:!0}),le.current=null))},onFocus:Me=>{Me.target instanceof HTMLElement&&Me.target.dataset.dismissible==="false"||be.current||(be.current=!0,le.current=Me.relatedTarget)},onMouseEnter:()=>Z(!0),onMouseMove:()=>Z(!0),onMouseLeave:()=>{J||Z(!1)},onDragEnd:()=>Z(!1),onPointerDown:Me=>{Me.target instanceof HTMLElement&&Me.target.dataset.dismissible==="false"||K(!0)},onPointerUp:()=>K(!1)},D.filter(Me=>!Me.position&&ve===0||Me.position===je).map((Me,ze)=>{var Pe,Ie;return Nt.createElement(oCt,{key:Me.id,icons:T,index:ze,toast:Me,defaultRichColors:m,duration:(Pe=_==null?void 0:_.duration)!=null?Pe:p,className:_==null?void 0:_.className,descriptionClassName:_==null?void 0:_.descriptionClassName,invert:r,visibleToasts:y,closeButton:(Ie=_==null?void 0:_.closeButton)!=null?Ie:l,interacting:J,position:je,style:_==null?void 0:_.style,unstyled:_==null?void 0:_.unstyled,classNames:_==null?void 0:_.classNames,cancelButtonStyle:_==null?void 0:_.cancelButtonStyle,actionButtonStyle:_==null?void 0:_.actionButtonStyle,removeToast:fe,toasts:D.filter(De=>De.position==Me.position),heights:O.filter(De=>De.position==Me.position),setHeights:$,expandByDefault:i,gap:j,loadingIcon:k,expanded:ee,pauseWhenPageIsHidden:A,swipeDirections:s.swipeDirections})})):null}))});const dCt=({...s})=>{const{theme:t="system"}=R4t();return e.jsx(cCt,{theme:t,position:"top-center",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"}},...s})};var uCt=jCe[" useId ".trim().toString()]||(()=>{}),hCt=0;function vm(s){const[t,r]=S.useState(uCt());return Ku(()=>{r(n=>n??String(hCt++))},[s]),t?`radix-${t}`:""}const mCt=["top","right","bottom","left"],fS=Math.min,e0=Math.max,xhe=Math.round,MU=Math.floor,pS=s=>({x:s,y:s}),fCt={left:"right",right:"left",bottom:"top",top:"bottom"},pCt={start:"end",end:"start"};function lje(s,t,r){return e0(s,fS(t,r))}function aj(s,t){return typeof s=="function"?s(t):s}function ij(s){return s.split("-")[0]}function n8(s){return s.split("-")[1]}function _3e(s){return s==="x"?"y":"x"}function w3e(s){return s==="y"?"height":"width"}function gS(s){return["top","bottom"].includes(ij(s))?"y":"x"}function j3e(s){return _3e(gS(s))}function gCt(s,t,r){r===void 0&&(r=!1);const n=n8(s),a=j3e(s),i=w3e(a);let l=a==="x"?n===(r?"end":"start")?"right":"left":n==="start"?"bottom":"top";return t.reference[i]>t.floating[i]&&(l=yhe(l)),[l,yhe(l)]}function xCt(s){const t=yhe(s);return[cje(s),t,cje(t)]}function cje(s){return s.replace(/start|end/g,t=>pCt[t])}function yCt(s,t,r){const n=["left","right"],a=["right","left"],i=["top","bottom"],l=["bottom","top"];switch(s){case"top":case"bottom":return r?t?a:n:t?n:a;case"left":case"right":return t?i:l;default:return[]}}function vCt(s,t,r,n){const a=n8(s);let i=yCt(ij(s),r==="start",n);return a&&(i=i.map(l=>l+"-"+a),t&&(i=i.concat(i.map(cje)))),i}function yhe(s){return s.replace(/left|right|bottom|top/g,t=>fCt[t])}function bCt(s){return{top:0,right:0,bottom:0,left:0,...s}}function $Qe(s){return typeof s!="number"?bCt(s):{top:s,right:s,bottom:s,left:s}}function vhe(s){const{x:t,y:r,width:n,height:a}=s;return{width:n,height:a,top:r,left:t,right:t+n,bottom:r+a,x:t,y:r}}function DRe(s,t,r){let{reference:n,floating:a}=s;const i=gS(t),l=j3e(t),o=w3e(l),c=ij(t),d=i==="y",h=n.x+n.width/2-a.width/2,m=n.y+n.height/2-a.height/2,p=n[o]/2-a[o]/2;let x;switch(c){case"top":x={x:h,y:n.y-a.height};break;case"bottom":x={x:h,y:n.y+n.height};break;case"right":x={x:n.x+n.width,y:m};break;case"left":x={x:n.x-a.width,y:m};break;default:x={x:n.x,y:n.y}}switch(n8(t)){case"start":x[l]-=p*(r&&d?-1:1);break;case"end":x[l]+=p*(r&&d?-1:1);break}return x}const _Ct=async(s,t,r)=>{const{placement:n="bottom",strategy:a="absolute",middleware:i=[],platform:l}=r,o=i.filter(Boolean),c=await(l.isRTL==null?void 0:l.isRTL(t));let d=await l.getElementRects({reference:s,floating:t,strategy:a}),{x:h,y:m}=DRe(d,n,c),p=n,x={},y=0;for(let _=0;_({name:"arrow",options:s,async fn(t){const{x:r,y:n,placement:a,rects:i,platform:l,elements:o,middlewareData:c}=t,{element:d,padding:h=0}=aj(s,t)||{};if(d==null)return{};const m=$Qe(h),p={x:r,y:n},x=j3e(a),y=w3e(x),_=await l.getDimensions(d),b=x==="y",j=b?"top":"left",k=b?"bottom":"right",T=b?"clientHeight":"clientWidth",E=i.reference[y]+i.reference[x]-p[x]-i.floating[y],A=p[x]-i.reference[x],D=await(l.getOffsetParent==null?void 0:l.getOffsetParent(d));let R=D?D[T]:0;(!R||!await(l.isElement==null?void 0:l.isElement(D)))&&(R=o.floating[T]||i.floating[y]);const z=E/2-A/2,O=R/2-_[y]/2-1,$=fS(m[j],O),ee=fS(m[k],O),Z=$,J=R-_[y]-ee,K=R/2-_[y]/2+z,re=lje(Z,K,J),ie=!c.arrow&&n8(a)!=null&&K!==re&&i.reference[y]/2-(KK<=0)){var ee,Z;const K=(((ee=i.flip)==null?void 0:ee.index)||0)+1,re=R[K];if(re)return{data:{index:K,overflows:$},reset:{placement:re}};let ie=(Z=$.filter(ce=>ce.overflows[0]<=0).sort((ce,ne)=>ce.overflows[1]-ne.overflows[1])[0])==null?void 0:Z.placement;if(!ie)switch(x){case"bestFit":{var J;const ce=(J=$.filter(ne=>{if(D){const le=gS(ne.placement);return le===k||le==="y"}return!0}).map(ne=>[ne.placement,ne.overflows.filter(le=>le>0).reduce((le,be)=>le+be,0)]).sort((ne,le)=>ne[1]-le[1])[0])==null?void 0:J[0];ce&&(ie=ce);break}case"initialPlacement":ie=o;break}if(a!==ie)return{reset:{placement:ie}}}return{}}}};function RRe(s,t){return{top:s.top-t.height,right:s.right-t.width,bottom:s.bottom-t.height,left:s.left-t.width}}function ORe(s){return mCt.some(t=>s[t]>=0)}const NCt=function(s){return s===void 0&&(s={}),{name:"hide",options:s,async fn(t){const{rects:r}=t,{strategy:n="referenceHidden",...a}=aj(s,t);switch(n){case"referenceHidden":{const i=await J7(t,{...a,elementContext:"reference"}),l=RRe(i,r.reference);return{data:{referenceHiddenOffsets:l,referenceHidden:ORe(l)}}}case"escaped":{const i=await J7(t,{...a,altBoundary:!0}),l=RRe(i,r.floating);return{data:{escapedOffsets:l,escaped:ORe(l)}}}default:return{}}}}};async function kCt(s,t){const{placement:r,platform:n,elements:a}=s,i=await(n.isRTL==null?void 0:n.isRTL(a.floating)),l=ij(r),o=n8(r),c=gS(r)==="y",d=["left","top"].includes(l)?-1:1,h=i&&c?-1:1,m=aj(t,s);let{mainAxis:p,crossAxis:x,alignmentAxis:y}=typeof m=="number"?{mainAxis:m,crossAxis:0,alignmentAxis:null}:{mainAxis:m.mainAxis||0,crossAxis:m.crossAxis||0,alignmentAxis:m.alignmentAxis};return o&&typeof y=="number"&&(x=o==="end"?y*-1:y),c?{x:x*h,y:p*d}:{x:p*d,y:x*h}}const SCt=function(s){return s===void 0&&(s=0),{name:"offset",options:s,async fn(t){var r,n;const{x:a,y:i,placement:l,middlewareData:o}=t,c=await kCt(t,s);return l===((r=o.offset)==null?void 0:r.placement)&&(n=o.arrow)!=null&&n.alignmentOffset?{}:{x:a+c.x,y:i+c.y,data:{...c,placement:l}}}}},CCt=function(s){return s===void 0&&(s={}),{name:"shift",options:s,async fn(t){const{x:r,y:n,placement:a}=t,{mainAxis:i=!0,crossAxis:l=!1,limiter:o={fn:b=>{let{x:j,y:k}=b;return{x:j,y:k}}},...c}=aj(s,t),d={x:r,y:n},h=await J7(t,c),m=gS(ij(a)),p=_3e(m);let x=d[p],y=d[m];if(i){const b=p==="y"?"top":"left",j=p==="y"?"bottom":"right",k=x+h[b],T=x-h[j];x=lje(k,x,T)}if(l){const b=m==="y"?"top":"left",j=m==="y"?"bottom":"right",k=y+h[b],T=y-h[j];y=lje(k,y,T)}const _=o.fn({...t,[p]:x,[m]:y});return{..._,data:{x:_.x-r,y:_.y-n,enabled:{[p]:i,[m]:l}}}}}},TCt=function(s){return s===void 0&&(s={}),{options:s,fn(t){const{x:r,y:n,placement:a,rects:i,middlewareData:l}=t,{offset:o=0,mainAxis:c=!0,crossAxis:d=!0}=aj(s,t),h={x:r,y:n},m=gS(a),p=_3e(m);let x=h[p],y=h[m];const _=aj(o,t),b=typeof _=="number"?{mainAxis:_,crossAxis:0}:{mainAxis:0,crossAxis:0,..._};if(c){const T=p==="y"?"height":"width",E=i.reference[p]-i.floating[T]+b.mainAxis,A=i.reference[p]+i.reference[T]-b.mainAxis;xA&&(x=A)}if(d){var j,k;const T=p==="y"?"width":"height",E=["top","left"].includes(ij(a)),A=i.reference[m]-i.floating[T]+(E&&((j=l.offset)==null?void 0:j[m])||0)+(E?0:b.crossAxis),D=i.reference[m]+i.reference[T]+(E?0:((k=l.offset)==null?void 0:k[m])||0)-(E?b.crossAxis:0);yD&&(y=D)}return{[p]:x,[m]:y}}}},ECt=function(s){return s===void 0&&(s={}),{name:"size",options:s,async fn(t){var r,n;const{placement:a,rects:i,platform:l,elements:o}=t,{apply:c=()=>{},...d}=aj(s,t),h=await J7(t,d),m=ij(a),p=n8(a),x=gS(a)==="y",{width:y,height:_}=i.floating;let b,j;m==="top"||m==="bottom"?(b=m,j=p===(await(l.isRTL==null?void 0:l.isRTL(o.floating))?"start":"end")?"left":"right"):(j=m,b=p==="end"?"top":"bottom");const k=_-h.top-h.bottom,T=y-h.left-h.right,E=fS(_-h[b],k),A=fS(y-h[j],T),D=!t.middlewareData.shift;let R=E,z=A;if((r=t.middlewareData.shift)!=null&&r.enabled.x&&(z=T),(n=t.middlewareData.shift)!=null&&n.enabled.y&&(R=k),D&&!p){const $=e0(h.left,0),ee=e0(h.right,0),Z=e0(h.top,0),J=e0(h.bottom,0);x?z=y-2*($!==0||ee!==0?$+ee:e0(h.left,h.right)):R=_-2*(Z!==0||J!==0?Z+J:e0(h.top,h.bottom))}await c({...t,availableWidth:z,availableHeight:R});const O=await l.getDimensions(o.floating);return y!==O.width||_!==O.height?{reset:{rects:!0}}:{}}}};function Hpe(){return typeof window<"u"}function a8(s){return UQe(s)?(s.nodeName||"").toLowerCase():"#document"}function h0(s){var t;return(s==null||(t=s.ownerDocument)==null?void 0:t.defaultView)||window}function U_(s){var t;return(t=(UQe(s)?s.ownerDocument:s.document)||window.document)==null?void 0:t.documentElement}function UQe(s){return Hpe()?s instanceof Node||s instanceof h0(s).Node:!1}function E1(s){return Hpe()?s instanceof Element||s instanceof h0(s).Element:!1}function E_(s){return Hpe()?s instanceof HTMLElement||s instanceof h0(s).HTMLElement:!1}function FRe(s){return!Hpe()||typeof ShadowRoot>"u"?!1:s instanceof ShadowRoot||s instanceof h0(s).ShadowRoot}function OB(s){const{overflow:t,overflowX:r,overflowY:n,display:a}=A1(s);return/auto|scroll|overlay|hidden|clip/.test(t+n+r)&&!["inline","contents"].includes(a)}function ACt(s){return["table","td","th"].includes(a8(s))}function Gpe(s){return[":popover-open",":modal"].some(t=>{try{return s.matches(t)}catch{return!1}})}function N3e(s){const t=k3e(),r=E1(s)?A1(s):s;return r.transform!=="none"||r.perspective!=="none"||(r.containerType?r.containerType!=="normal":!1)||!t&&(r.backdropFilter?r.backdropFilter!=="none":!1)||!t&&(r.filter?r.filter!=="none":!1)||["transform","perspective","filter"].some(n=>(r.willChange||"").includes(n))||["paint","layout","strict","content"].some(n=>(r.contain||"").includes(n))}function MCt(s){let t=xS(s);for(;E_(t)&&!HP(t);){if(N3e(t))return t;if(Gpe(t))return null;t=xS(t)}return null}function k3e(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}function HP(s){return["html","body","#document"].includes(a8(s))}function A1(s){return h0(s).getComputedStyle(s)}function Wpe(s){return E1(s)?{scrollLeft:s.scrollLeft,scrollTop:s.scrollTop}:{scrollLeft:s.scrollX,scrollTop:s.scrollY}}function xS(s){if(a8(s)==="html")return s;const t=s.assignedSlot||s.parentNode||FRe(s)&&s.host||U_(s);return FRe(t)?t.host:t}function qQe(s){const t=xS(s);return HP(t)?s.ownerDocument?s.ownerDocument.body:s.body:E_(t)&&OB(t)?t:qQe(t)}function e9(s,t,r){var n;t===void 0&&(t=[]),r===void 0&&(r=!0);const a=qQe(s),i=a===((n=s.ownerDocument)==null?void 0:n.body),l=h0(a);if(i){const o=dje(l);return t.concat(l,l.visualViewport||[],OB(a)?a:[],o&&r?e9(o):[])}return t.concat(a,e9(a,[],r))}function dje(s){return s.parent&&Object.getPrototypeOf(s.parent)?s.frameElement:null}function VQe(s){const t=A1(s);let r=parseFloat(t.width)||0,n=parseFloat(t.height)||0;const a=E_(s),i=a?s.offsetWidth:r,l=a?s.offsetHeight:n,o=xhe(r)!==i||xhe(n)!==l;return o&&(r=i,n=l),{width:r,height:n,$:o}}function S3e(s){return E1(s)?s:s.contextElement}function tP(s){const t=S3e(s);if(!E_(t))return pS(1);const r=t.getBoundingClientRect(),{width:n,height:a,$:i}=VQe(t);let l=(i?xhe(r.width):r.width)/n,o=(i?xhe(r.height):r.height)/a;return(!l||!Number.isFinite(l))&&(l=1),(!o||!Number.isFinite(o))&&(o=1),{x:l,y:o}}const ICt=pS(0);function HQe(s){const t=h0(s);return!k3e()||!t.visualViewport?ICt:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function PCt(s,t,r){return t===void 0&&(t=!1),!r||t&&r!==h0(s)?!1:t}function oA(s,t,r,n){t===void 0&&(t=!1),r===void 0&&(r=!1);const a=s.getBoundingClientRect(),i=S3e(s);let l=pS(1);t&&(n?E1(n)&&(l=tP(n)):l=tP(s));const o=PCt(i,r,n)?HQe(i):pS(0);let c=(a.left+o.x)/l.x,d=(a.top+o.y)/l.y,h=a.width/l.x,m=a.height/l.y;if(i){const p=h0(i),x=n&&E1(n)?h0(n):n;let y=p,_=dje(y);for(;_&&n&&x!==y;){const b=tP(_),j=_.getBoundingClientRect(),k=A1(_),T=j.left+(_.clientLeft+parseFloat(k.paddingLeft))*b.x,E=j.top+(_.clientTop+parseFloat(k.paddingTop))*b.y;c*=b.x,d*=b.y,h*=b.x,m*=b.y,c+=T,d+=E,y=h0(_),_=dje(y)}}return vhe({width:h,height:m,x:c,y:d})}function LCt(s){let{elements:t,rect:r,offsetParent:n,strategy:a}=s;const i=a==="fixed",l=U_(n),o=t?Gpe(t.floating):!1;if(n===l||o&&i)return r;let c={scrollLeft:0,scrollTop:0},d=pS(1);const h=pS(0),m=E_(n);if((m||!m&&!i)&&((a8(n)!=="body"||OB(l))&&(c=Wpe(n)),E_(n))){const p=oA(n);d=tP(n),h.x=p.x+n.clientLeft,h.y=p.y+n.clientTop}return{width:r.width*d.x,height:r.height*d.y,x:r.x*d.x-c.scrollLeft*d.x+h.x,y:r.y*d.y-c.scrollTop*d.y+h.y}}function DCt(s){return Array.from(s.getClientRects())}function uje(s,t){const r=Wpe(s).scrollLeft;return t?t.left+r:oA(U_(s)).left+r}function RCt(s){const t=U_(s),r=Wpe(s),n=s.ownerDocument.body,a=e0(t.scrollWidth,t.clientWidth,n.scrollWidth,n.clientWidth),i=e0(t.scrollHeight,t.clientHeight,n.scrollHeight,n.clientHeight);let l=-r.scrollLeft+uje(s);const o=-r.scrollTop;return A1(n).direction==="rtl"&&(l+=e0(t.clientWidth,n.clientWidth)-a),{width:a,height:i,x:l,y:o}}function OCt(s,t){const r=h0(s),n=U_(s),a=r.visualViewport;let i=n.clientWidth,l=n.clientHeight,o=0,c=0;if(a){i=a.width,l=a.height;const d=k3e();(!d||d&&t==="fixed")&&(o=a.offsetLeft,c=a.offsetTop)}return{width:i,height:l,x:o,y:c}}function FCt(s,t){const r=oA(s,!0,t==="fixed"),n=r.top+s.clientTop,a=r.left+s.clientLeft,i=E_(s)?tP(s):pS(1),l=s.clientWidth*i.x,o=s.clientHeight*i.y,c=a*i.x,d=n*i.y;return{width:l,height:o,x:c,y:d}}function BRe(s,t,r){let n;if(t==="viewport")n=OCt(s,r);else if(t==="document")n=RCt(U_(s));else if(E1(t))n=FCt(t,r);else{const a=HQe(s);n={...t,x:t.x-a.x,y:t.y-a.y}}return vhe(n)}function GQe(s,t){const r=xS(s);return r===t||!E1(r)||HP(r)?!1:A1(r).position==="fixed"||GQe(r,t)}function BCt(s,t){const r=t.get(s);if(r)return r;let n=e9(s,[],!1).filter(o=>E1(o)&&a8(o)!=="body"),a=null;const i=A1(s).position==="fixed";let l=i?xS(s):s;for(;E1(l)&&!HP(l);){const o=A1(l),c=N3e(l);!c&&o.position==="fixed"&&(a=null),(i?!c&&!a:!c&&o.position==="static"&&!!a&&["absolute","fixed"].includes(a.position)||OB(l)&&!c&&GQe(s,l))?n=n.filter(h=>h!==l):a=o,l=xS(l)}return t.set(s,n),n}function zCt(s){let{element:t,boundary:r,rootBoundary:n,strategy:a}=s;const l=[...r==="clippingAncestors"?Gpe(t)?[]:BCt(t,this._c):[].concat(r),n],o=l[0],c=l.reduce((d,h)=>{const m=BRe(t,h,a);return d.top=e0(m.top,d.top),d.right=fS(m.right,d.right),d.bottom=fS(m.bottom,d.bottom),d.left=e0(m.left,d.left),d},BRe(t,o,a));return{width:c.right-c.left,height:c.bottom-c.top,x:c.left,y:c.top}}function $Ct(s){const{width:t,height:r}=VQe(s);return{width:t,height:r}}function UCt(s,t,r){const n=E_(t),a=U_(t),i=r==="fixed",l=oA(s,!0,i,t);let o={scrollLeft:0,scrollTop:0};const c=pS(0);if(n||!n&&!i)if((a8(t)!=="body"||OB(a))&&(o=Wpe(t)),n){const x=oA(t,!0,i,t);c.x=x.x+t.clientLeft,c.y=x.y+t.clientTop}else a&&(c.x=uje(a));let d=0,h=0;if(a&&!n&&!i){const x=a.getBoundingClientRect();h=x.top+o.scrollTop,d=x.left+o.scrollLeft-uje(a,x)}const m=l.left+o.scrollLeft-c.x-d,p=l.top+o.scrollTop-c.y-h;return{x:m,y:p,width:l.width,height:l.height}}function P1e(s){return A1(s).position==="static"}function zRe(s,t){if(!E_(s)||A1(s).position==="fixed")return null;if(t)return t(s);let r=s.offsetParent;return U_(s)===r&&(r=r.ownerDocument.body),r}function WQe(s,t){const r=h0(s);if(Gpe(s))return r;if(!E_(s)){let a=xS(s);for(;a&&!HP(a);){if(E1(a)&&!P1e(a))return a;a=xS(a)}return r}let n=zRe(s,t);for(;n&&ACt(n)&&P1e(n);)n=zRe(n,t);return n&&HP(n)&&P1e(n)&&!N3e(n)?r:n||MCt(s)||r}const qCt=async function(s){const t=this.getOffsetParent||WQe,r=this.getDimensions,n=await r(s.floating);return{reference:UCt(s.reference,await t(s.floating),s.strategy),floating:{x:0,y:0,width:n.width,height:n.height}}};function VCt(s){return A1(s).direction==="rtl"}const HCt={convertOffsetParentRelativeRectToViewportRelativeRect:LCt,getDocumentElement:U_,getClippingRect:zCt,getOffsetParent:WQe,getElementRects:qCt,getClientRects:DCt,getDimensions:$Ct,getScale:tP,isElement:E1,isRTL:VCt};function GCt(s,t){let r=null,n;const a=U_(s);function i(){var o;clearTimeout(n),(o=r)==null||o.disconnect(),r=null}function l(o,c){o===void 0&&(o=!1),c===void 0&&(c=1),i();const{left:d,top:h,width:m,height:p}=s.getBoundingClientRect();if(o||t(),!m||!p)return;const x=MU(h),y=MU(a.clientWidth-(d+m)),_=MU(a.clientHeight-(h+p)),b=MU(d),k={rootMargin:-x+"px "+-y+"px "+-_+"px "+-b+"px",threshold:e0(0,fS(1,c))||1};let T=!0;function E(A){const D=A[0].intersectionRatio;if(D!==c){if(!T)return l();D?l(!1,D):n=setTimeout(()=>{l(!1,1e-7)},1e3)}T=!1}try{r=new IntersectionObserver(E,{...k,root:a.ownerDocument})}catch{r=new IntersectionObserver(E,k)}r.observe(s)}return l(!0),i}function WCt(s,t,r,n){n===void 0&&(n={});const{ancestorScroll:a=!0,ancestorResize:i=!0,elementResize:l=typeof ResizeObserver=="function",layoutShift:o=typeof IntersectionObserver=="function",animationFrame:c=!1}=n,d=S3e(s),h=a||i?[...d?e9(d):[],...e9(t)]:[];h.forEach(j=>{a&&j.addEventListener("scroll",r,{passive:!0}),i&&j.addEventListener("resize",r)});const m=d&&o?GCt(d,r):null;let p=-1,x=null;l&&(x=new ResizeObserver(j=>{let[k]=j;k&&k.target===d&&x&&(x.unobserve(t),cancelAnimationFrame(p),p=requestAnimationFrame(()=>{var T;(T=x)==null||T.observe(t)})),r()}),d&&!c&&x.observe(d),x.observe(t));let y,_=c?oA(s):null;c&&b();function b(){const j=oA(s);_&&(j.x!==_.x||j.y!==_.y||j.width!==_.width||j.height!==_.height)&&r(),_=j,y=requestAnimationFrame(b)}return r(),()=>{var j;h.forEach(k=>{a&&k.removeEventListener("scroll",r),i&&k.removeEventListener("resize",r)}),m==null||m(),(j=x)==null||j.disconnect(),x=null,c&&cancelAnimationFrame(y)}}const KCt=SCt,YCt=CCt,ZCt=jCt,XCt=ECt,QCt=NCt,$Re=wCt,JCt=TCt,e3t=(s,t,r)=>{const n=new Map,a={platform:HCt,...r},i={...a.platform,_c:n};return _Ct(s,t,{...a,platform:i})};var aue=typeof document<"u"?S.useLayoutEffect:S.useEffect;function bhe(s,t){if(s===t)return!0;if(typeof s!=typeof t)return!1;if(typeof s=="function"&&s.toString()===t.toString())return!0;let r,n,a;if(s&&t&&typeof s=="object"){if(Array.isArray(s)){if(r=s.length,r!==t.length)return!1;for(n=r;n--!==0;)if(!bhe(s[n],t[n]))return!1;return!0}if(a=Object.keys(s),r=a.length,r!==Object.keys(t).length)return!1;for(n=r;n--!==0;)if(!{}.hasOwnProperty.call(t,a[n]))return!1;for(n=r;n--!==0;){const i=a[n];if(!(i==="_owner"&&s.$$typeof)&&!bhe(s[i],t[i]))return!1}return!0}return s!==s&&t!==t}function KQe(s){return typeof window>"u"?1:(s.ownerDocument.defaultView||window).devicePixelRatio||1}function URe(s,t){const r=KQe(s);return Math.round(t*r)/r}function L1e(s){const t=S.useRef(s);return aue(()=>{t.current=s}),t}function t3t(s){s===void 0&&(s={});const{placement:t="bottom",strategy:r="absolute",middleware:n=[],platform:a,elements:{reference:i,floating:l}={},transform:o=!0,whileElementsMounted:c,open:d}=s,[h,m]=S.useState({x:0,y:0,strategy:r,placement:t,middlewareData:{},isPositioned:!1}),[p,x]=S.useState(n);bhe(p,n)||x(n);const[y,_]=S.useState(null),[b,j]=S.useState(null),k=S.useCallback(ne=>{ne!==D.current&&(D.current=ne,_(ne))},[]),T=S.useCallback(ne=>{ne!==R.current&&(R.current=ne,j(ne))},[]),E=i||y,A=l||b,D=S.useRef(null),R=S.useRef(null),z=S.useRef(h),O=c!=null,$=L1e(c),ee=L1e(a),Z=L1e(d),J=S.useCallback(()=>{if(!D.current||!R.current)return;const ne={placement:t,strategy:r,middleware:p};ee.current&&(ne.platform=ee.current),e3t(D.current,R.current,ne).then(le=>{const be={...le,isPositioned:Z.current!==!1};K.current&&!bhe(z.current,be)&&(z.current=be,tx.flushSync(()=>{m(be)}))})},[p,t,r,ee,Z]);aue(()=>{d===!1&&z.current.isPositioned&&(z.current.isPositioned=!1,m(ne=>({...ne,isPositioned:!1})))},[d]);const K=S.useRef(!1);aue(()=>(K.current=!0,()=>{K.current=!1}),[]),aue(()=>{if(E&&(D.current=E),A&&(R.current=A),E&&A){if($.current)return $.current(E,A,J);J()}},[E,A,J,$,O]);const re=S.useMemo(()=>({reference:D,floating:R,setReference:k,setFloating:T}),[k,T]),ie=S.useMemo(()=>({reference:E,floating:A}),[E,A]),ce=S.useMemo(()=>{const ne={position:r,left:0,top:0};if(!ie.floating)return ne;const le=URe(ie.floating,h.x),be=URe(ie.floating,h.y);return o?{...ne,transform:"translate("+le+"px, "+be+"px)",...KQe(ie.floating)>=1.5&&{willChange:"transform"}}:{position:r,left:le,top:be}},[r,o,ie.floating,h.x,h.y]);return S.useMemo(()=>({...h,update:J,refs:re,elements:ie,floatingStyles:ce}),[h,J,re,ie,ce])}const s3t=s=>{function t(r){return{}.hasOwnProperty.call(r,"current")}return{name:"arrow",options:s,fn(r){const{element:n,padding:a}=typeof s=="function"?s(r):s;return n&&t(n)?n.current!=null?$Re({element:n.current,padding:a}).fn(r):{}:n?$Re({element:n,padding:a}).fn(r):{}}}},r3t=(s,t)=>({...KCt(s),options:[s,t]}),n3t=(s,t)=>({...YCt(s),options:[s,t]}),a3t=(s,t)=>({...JCt(s),options:[s,t]}),i3t=(s,t)=>({...ZCt(s),options:[s,t]}),o3t=(s,t)=>({...XCt(s),options:[s,t]}),l3t=(s,t)=>({...QCt(s),options:[s,t]}),c3t=(s,t)=>({...s3t(s),options:[s,t]});var d3t="Arrow",YQe=S.forwardRef((s,t)=>{const{children:r,width:n=10,height:a=5,...i}=s;return e.jsx(Vn.svg,{...i,ref:t,width:n,height:a,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:s.asChild?r:e.jsx("polygon",{points:"0,0 30,0 15,10"})})});YQe.displayName=d3t;var u3t=YQe;function FB(s){const[t,r]=S.useState(void 0);return Ku(()=>{if(s){r({width:s.offsetWidth,height:s.offsetHeight});const n=new ResizeObserver(a=>{if(!Array.isArray(a)||!a.length)return;const i=a[0];let l,o;if("borderBoxSize"in i){const c=i.borderBoxSize,d=Array.isArray(c)?c[0]:c;l=d.inlineSize,o=d.blockSize}else l=s.offsetWidth,o=s.offsetHeight;r({width:l,height:o})});return n.observe(s,{box:"border-box"}),()=>n.unobserve(s)}else r(void 0)},[s]),t}var C3e="Popper",[ZQe,q_]=_u(C3e),[h3t,XQe]=ZQe(C3e),QQe=s=>{const{__scopePopper:t,children:r}=s,[n,a]=S.useState(null);return e.jsx(h3t,{scope:t,anchor:n,onAnchorChange:a,children:r})};QQe.displayName=C3e;var JQe="PopperAnchor",eJe=S.forwardRef((s,t)=>{const{__scopePopper:r,virtualRef:n,...a}=s,i=XQe(JQe,r),l=S.useRef(null),o=_i(t,l);return S.useEffect(()=>{i.onAnchorChange((n==null?void 0:n.current)||l.current)}),n?null:e.jsx(Vn.div,{...a,ref:o})});eJe.displayName=JQe;var T3e="PopperContent",[m3t,f3t]=ZQe(T3e),tJe=S.forwardRef((s,t)=>{var Me,ze,Pe,Ie,De,pe;const{__scopePopper:r,side:n="bottom",sideOffset:a=0,align:i="center",alignOffset:l=0,arrowPadding:o=0,avoidCollisions:c=!0,collisionBoundary:d=[],collisionPadding:h=0,sticky:m="partial",hideWhenDetached:p=!1,updatePositionStrategy:x="optimized",onPlaced:y,..._}=s,b=XQe(T3e,r),[j,k]=S.useState(null),T=_i(t,tt=>k(tt)),[E,A]=S.useState(null),D=FB(E),R=(D==null?void 0:D.width)??0,z=(D==null?void 0:D.height)??0,O=n+(i!=="center"?"-"+i:""),$=typeof h=="number"?h:{top:0,right:0,bottom:0,left:0,...h},ee=Array.isArray(d)?d:[d],Z=ee.length>0,J={padding:$,boundary:ee.filter(g3t),altBoundary:Z},{refs:K,floatingStyles:re,placement:ie,isPositioned:ce,middlewareData:ne}=t3t({strategy:"fixed",placement:O,whileElementsMounted:(...tt)=>WCt(...tt,{animationFrame:x==="always"}),elements:{reference:b.anchor},middleware:[r3t({mainAxis:a+z,alignmentAxis:l}),c&&n3t({mainAxis:!0,crossAxis:!1,limiter:m==="partial"?a3t():void 0,...J}),c&&i3t({...J}),o3t({...J,apply:({elements:tt,rects:ge,availableWidth:ct,availableHeight:Ue})=>{const{width:et,height:Qe}=ge.reference,Ne=tt.floating.style;Ne.setProperty("--radix-popper-available-width",`${ct}px`),Ne.setProperty("--radix-popper-available-height",`${Ue}px`),Ne.setProperty("--radix-popper-anchor-width",`${et}px`),Ne.setProperty("--radix-popper-anchor-height",`${Qe}px`)}}),E&&c3t({element:E,padding:o}),x3t({arrowWidth:R,arrowHeight:z}),p&&l3t({strategy:"referenceHidden",...J})]}),[le,be]=nJe(ie),fe=Uu(y);Ku(()=>{ce&&(fe==null||fe())},[ce,fe]);const je=(Me=ne.arrow)==null?void 0:Me.x,ve=(ze=ne.arrow)==null?void 0:ze.y,We=((Pe=ne.arrow)==null?void 0:Pe.centerOffset)!==0,[Ve,Le]=S.useState();return Ku(()=>{j&&Le(window.getComputedStyle(j).zIndex)},[j]),e.jsx("div",{ref:K.setFloating,"data-radix-popper-content-wrapper":"",style:{...re,transform:ce?re.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:Ve,"--radix-popper-transform-origin":[(Ie=ne.transformOrigin)==null?void 0:Ie.x,(De=ne.transformOrigin)==null?void 0:De.y].join(" "),...((pe=ne.hide)==null?void 0:pe.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:s.dir,children:e.jsx(m3t,{scope:r,placedSide:le,onArrowChange:A,arrowX:je,arrowY:ve,shouldHideArrow:We,children:e.jsx(Vn.div,{"data-side":le,"data-align":be,..._,ref:T,style:{..._.style,animation:ce?void 0:"none"}})})})});tJe.displayName=T3e;var sJe="PopperArrow",p3t={top:"bottom",right:"left",bottom:"top",left:"right"},rJe=S.forwardRef(function(t,r){const{__scopePopper:n,...a}=t,i=f3t(sJe,n),l=p3t[i.placedSide];return e.jsx("span",{ref:i.onArrowChange,style:{position:"absolute",left:i.arrowX,top:i.arrowY,[l]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[i.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[i.placedSide],visibility:i.shouldHideArrow?"hidden":void 0},children:e.jsx(u3t,{...a,ref:r,style:{...a.style,display:"block"}})})});rJe.displayName=sJe;function g3t(s){return s!==null}var x3t=s=>({name:"transformOrigin",options:s,fn(t){var b,j,k;const{placement:r,rects:n,middlewareData:a}=t,l=((b=a.arrow)==null?void 0:b.centerOffset)!==0,o=l?0:s.arrowWidth,c=l?0:s.arrowHeight,[d,h]=nJe(r),m={start:"0%",center:"50%",end:"100%"}[h],p=(((j=a.arrow)==null?void 0:j.x)??0)+o/2,x=(((k=a.arrow)==null?void 0:k.y)??0)+c/2;let y="",_="";return d==="bottom"?(y=l?m:`${p}px`,_=`${-c}px`):d==="top"?(y=l?m:`${p}px`,_=`${n.floating.height+c}px`):d==="right"?(y=`${-c}px`,_=l?m:`${x}px`):d==="left"&&(y=`${n.floating.width+c}px`,_=l?m:`${x}px`),{data:{x:y,y:_}}}});function nJe(s){const[t,r="center"]=s.split("-");return[t,r]}var BB=QQe,i8=eJe,zB=tJe,$B=rJe,[Kpe,uZs]=_u("Tooltip",[q_]),Ype=q_(),aJe="TooltipProvider",y3t=700,hje="tooltip.open",[v3t,E3e]=Kpe(aJe),iJe=s=>{const{__scopeTooltip:t,delayDuration:r=y3t,skipDelayDuration:n=300,disableHoverableContent:a=!1,children:i}=s,l=S.useRef(!0),o=S.useRef(!1),c=S.useRef(0);return S.useEffect(()=>{const d=c.current;return()=>window.clearTimeout(d)},[]),e.jsx(v3t,{scope:t,isOpenDelayedRef:l,delayDuration:r,onOpen:S.useCallback(()=>{window.clearTimeout(c.current),l.current=!1},[]),onClose:S.useCallback(()=>{window.clearTimeout(c.current),c.current=window.setTimeout(()=>l.current=!0,n)},[n]),isPointerInTransitRef:o,onPointerInTransitChange:S.useCallback(d=>{o.current=d},[]),disableHoverableContent:a,children:i})};iJe.displayName=aJe;var t9="Tooltip",[b3t,Zpe]=Kpe(t9),oJe=s=>{const{__scopeTooltip:t,children:r,open:n,defaultOpen:a,onOpenChange:i,disableHoverableContent:l,delayDuration:o}=s,c=E3e(t9,s.__scopeTooltip),d=Ype(t),[h,m]=S.useState(null),p=vm(),x=S.useRef(0),y=l??c.disableHoverableContent,_=o??c.delayDuration,b=S.useRef(!1),[j,k]=af({prop:n,defaultProp:a??!1,onChange:R=>{R?(c.onOpen(),document.dispatchEvent(new CustomEvent(hje))):c.onClose(),i==null||i(R)},caller:t9}),T=S.useMemo(()=>j?b.current?"delayed-open":"instant-open":"closed",[j]),E=S.useCallback(()=>{window.clearTimeout(x.current),x.current=0,b.current=!1,k(!0)},[k]),A=S.useCallback(()=>{window.clearTimeout(x.current),x.current=0,k(!1)},[k]),D=S.useCallback(()=>{window.clearTimeout(x.current),x.current=window.setTimeout(()=>{b.current=!0,k(!0),x.current=0},_)},[_,k]);return S.useEffect(()=>()=>{x.current&&(window.clearTimeout(x.current),x.current=0)},[]),e.jsx(BB,{...d,children:e.jsx(b3t,{scope:t,contentId:p,open:j,stateAttribute:T,trigger:h,onTriggerChange:m,onTriggerEnter:S.useCallback(()=>{c.isOpenDelayedRef.current?D():E()},[c.isOpenDelayedRef,D,E]),onTriggerLeave:S.useCallback(()=>{y?A():(window.clearTimeout(x.current),x.current=0)},[A,y]),onOpen:E,onClose:A,disableHoverableContent:y,children:r})})};oJe.displayName=t9;var mje="TooltipTrigger",lJe=S.forwardRef((s,t)=>{const{__scopeTooltip:r,...n}=s,a=Zpe(mje,r),i=E3e(mje,r),l=Ype(r),o=S.useRef(null),c=_i(t,o,a.onTriggerChange),d=S.useRef(!1),h=S.useRef(!1),m=S.useCallback(()=>d.current=!1,[]);return S.useEffect(()=>()=>document.removeEventListener("pointerup",m),[m]),e.jsx(i8,{asChild:!0,...l,children:e.jsx(Vn.button,{"aria-describedby":a.open?a.contentId:void 0,"data-state":a.stateAttribute,...n,ref:c,onPointerMove:an(s.onPointerMove,p=>{p.pointerType!=="touch"&&!h.current&&!i.isPointerInTransitRef.current&&(a.onTriggerEnter(),h.current=!0)}),onPointerLeave:an(s.onPointerLeave,()=>{a.onTriggerLeave(),h.current=!1}),onPointerDown:an(s.onPointerDown,()=>{a.open&&a.onClose(),d.current=!0,document.addEventListener("pointerup",m,{once:!0})}),onFocus:an(s.onFocus,()=>{d.current||a.onOpen()}),onBlur:an(s.onBlur,a.onClose),onClick:an(s.onClick,a.onClose)})})});lJe.displayName=mje;var _3t="TooltipPortal",[hZs,w3t]=Kpe(_3t,{forceMount:void 0}),GP="TooltipContent",cJe=S.forwardRef((s,t)=>{const r=w3t(GP,s.__scopeTooltip),{forceMount:n=r.forceMount,side:a="top",...i}=s,l=Zpe(GP,s.__scopeTooltip);return e.jsx(vh,{present:n||l.open,children:l.disableHoverableContent?e.jsx(dJe,{side:a,...i,ref:t}):e.jsx(j3t,{side:a,...i,ref:t})})}),j3t=S.forwardRef((s,t)=>{const r=Zpe(GP,s.__scopeTooltip),n=E3e(GP,s.__scopeTooltip),a=S.useRef(null),i=_i(t,a),[l,o]=S.useState(null),{trigger:c,onClose:d}=r,h=a.current,{onPointerInTransitChange:m}=n,p=S.useCallback(()=>{o(null),m(!1)},[m]),x=S.useCallback((y,_)=>{const b=y.currentTarget,j={x:y.clientX,y:y.clientY},k=T3t(j,b.getBoundingClientRect()),T=E3t(j,k),E=A3t(_.getBoundingClientRect()),A=I3t([...T,...E]);o(A),m(!0)},[m]);return S.useEffect(()=>()=>p(),[p]),S.useEffect(()=>{if(c&&h){const y=b=>x(b,h),_=b=>x(b,c);return c.addEventListener("pointerleave",y),h.addEventListener("pointerleave",_),()=>{c.removeEventListener("pointerleave",y),h.removeEventListener("pointerleave",_)}}},[c,h,x,p]),S.useEffect(()=>{if(l){const y=_=>{const b=_.target,j={x:_.clientX,y:_.clientY},k=(c==null?void 0:c.contains(b))||(h==null?void 0:h.contains(b)),T=!M3t(j,l);k?p():T&&(p(),d())};return document.addEventListener("pointermove",y),()=>document.removeEventListener("pointermove",y)}},[c,h,l,d,p]),e.jsx(dJe,{...s,ref:i})}),[N3t,k3t]=Kpe(t9,{isInside:!1}),S3t=nQe("TooltipContent"),dJe=S.forwardRef((s,t)=>{const{__scopeTooltip:r,children:n,"aria-label":a,onEscapeKeyDown:i,onPointerDownOutside:l,...o}=s,c=Zpe(GP,r),d=Ype(r),{onClose:h}=c;return S.useEffect(()=>(document.addEventListener(hje,h),()=>document.removeEventListener(hje,h)),[h]),S.useEffect(()=>{if(c.trigger){const m=p=>{const x=p.target;x!=null&&x.contains(c.trigger)&&h()};return window.addEventListener("scroll",m,{capture:!0}),()=>window.removeEventListener("scroll",m,{capture:!0})}},[c.trigger,h]),e.jsx(PS,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:i,onPointerDownOutside:l,onFocusOutside:m=>m.preventDefault(),onDismiss:h,children:e.jsxs(zB,{"data-state":c.stateAttribute,...d,...o,ref:t,style:{...o.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:[e.jsx(S3t,{children:n}),e.jsx(N3t,{scope:r,isInside:!0,children:e.jsx(ESt,{id:c.contentId,role:"tooltip",children:a||n})})]})})});cJe.displayName=GP;var uJe="TooltipArrow",C3t=S.forwardRef((s,t)=>{const{__scopeTooltip:r,...n}=s,a=Ype(r);return k3t(uJe,r).isInside?null:e.jsx($B,{...a,...n,ref:t})});C3t.displayName=uJe;function T3t(s,t){const r=Math.abs(t.top-s.y),n=Math.abs(t.bottom-s.y),a=Math.abs(t.right-s.x),i=Math.abs(t.left-s.x);switch(Math.min(r,n,a,i)){case i:return"left";case a:return"right";case r:return"top";case n:return"bottom";default:throw new Error("unreachable")}}function E3t(s,t,r=5){const n=[];switch(t){case"top":n.push({x:s.x-r,y:s.y+r},{x:s.x+r,y:s.y+r});break;case"bottom":n.push({x:s.x-r,y:s.y-r},{x:s.x+r,y:s.y-r});break;case"left":n.push({x:s.x+r,y:s.y-r},{x:s.x+r,y:s.y+r});break;case"right":n.push({x:s.x-r,y:s.y-r},{x:s.x-r,y:s.y+r});break}return n}function A3t(s){const{top:t,right:r,bottom:n,left:a}=s;return[{x:a,y:t},{x:r,y:t},{x:r,y:n},{x:a,y:n}]}function M3t(s,t){const{x:r,y:n}=s;let a=!1;for(let i=0,l=t.length-1;in!=p>n&&r<(m-d)*(n-h)/(p-h)+d&&(a=!a)}return a}function I3t(s){const t=s.slice();return t.sort((r,n)=>r.xn.x?1:r.yn.y?1:0),P3t(t)}function P3t(s){if(s.length<=1)return s.slice();const t=[];for(let n=0;n=2;){const i=t[t.length-1],l=t[t.length-2];if((i.x-l.x)*(a.y-l.y)>=(i.y-l.y)*(a.x-l.x))t.pop();else break}t.push(a)}t.pop();const r=[];for(let n=s.length-1;n>=0;n--){const a=s[n];for(;r.length>=2;){const i=r[r.length-1],l=r[r.length-2];if((i.x-l.x)*(a.y-l.y)>=(i.y-l.y)*(a.x-l.x))r.pop();else break}r.push(a)}return r.pop(),t.length===1&&r.length===1&&t[0].x===r[0].x&&t[0].y===r[0].y?t:t.concat(r)}var L3t=iJe,D3t=oJe,R3t=lJe,hJe=cJe;const xj=L3t,rd=D3t,nd=R3t,Rc=S.forwardRef(({className:s,sideOffset:t=4,...r},n)=>e.jsx(hJe,{ref:n,sideOffset:t,className:Ft("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",s),...r}));Rc.displayName=hJe.displayName;var o8=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(s){return this.listeners.add(s),this.onSubscribe(),()=>{this.listeners.delete(s),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},lA=typeof window>"u"||"Deno"in globalThis;function og(){}function O3t(s,t){return typeof s=="function"?s(t):s}function fje(s){return typeof s=="number"&&s>=0&&s!==1/0}function mJe(s,t){return Math.max(s+(t||0)-Date.now(),0)}function Jk(s,t){return typeof s=="function"?s(t):s}function jy(s,t){return typeof s=="function"?s(t):s}function qRe(s,t){const{type:r="all",exact:n,fetchStatus:a,predicate:i,queryKey:l,stale:o}=s;if(l){if(n){if(t.queryHash!==A3e(l,t.options))return!1}else if(!s9(t.queryKey,l))return!1}if(r!=="all"){const c=t.isActive();if(r==="active"&&!c||r==="inactive"&&c)return!1}return!(typeof o=="boolean"&&t.isStale()!==o||a&&a!==t.state.fetchStatus||i&&!i(t))}function VRe(s,t){const{exact:r,status:n,predicate:a,mutationKey:i}=s;if(i){if(!t.options.mutationKey)return!1;if(r){if(cA(t.options.mutationKey)!==cA(i))return!1}else if(!s9(t.options.mutationKey,i))return!1}return!(n&&t.state.status!==n||a&&!a(t))}function A3e(s,t){return((t==null?void 0:t.queryKeyHashFn)||cA)(s)}function cA(s){return JSON.stringify(s,(t,r)=>pje(r)?Object.keys(r).sort().reduce((n,a)=>(n[a]=r[a],n),{}):r)}function s9(s,t){return s===t?!0:typeof s!=typeof t?!1:s&&t&&typeof s=="object"&&typeof t=="object"?Object.keys(t).every(r=>s9(s[r],t[r])):!1}function fJe(s,t){if(s===t)return s;const r=HRe(s)&&HRe(t);if(r||pje(s)&&pje(t)){const n=r?s:Object.keys(s),a=n.length,i=r?t:Object.keys(t),l=i.length,o=r?[]:{},c=new Set(n);let d=0;for(let h=0;h{setTimeout(t,s)})}function gje(s,t,r){return typeof r.structuralSharing=="function"?r.structuralSharing(s,t):r.structuralSharing!==!1?fJe(s,t):t}function B3t(s,t,r=0){const n=[...s,t];return r&&n.length>r?n.slice(1):n}function z3t(s,t,r=0){const n=[t,...s];return r&&n.length>r?n.slice(0,-1):n}var M3e=Symbol();function pJe(s,t){return!s.queryFn&&(t!=null&&t.initialPromise)?()=>t.initialPromise:!s.queryFn||s.queryFn===M3e?()=>Promise.reject(new Error(`Missing queryFn: '${s.queryHash}'`)):s.queryFn}function gJe(s,t){return typeof s=="function"?s(...t):!!s}var QT,ok,SP,PYe,$3t=(PYe=class extends o8{constructor(){super();Ai(this,QT);Ai(this,ok);Ai(this,SP);Pa(this,SP,t=>{if(!lA&&window.addEventListener){const r=()=>t();return window.addEventListener("visibilitychange",r,!1),()=>{window.removeEventListener("visibilitychange",r)}}})}onSubscribe(){Ds(this,ok)||this.setEventListener(Ds(this,SP))}onUnsubscribe(){var t;this.hasListeners()||((t=Ds(this,ok))==null||t.call(this),Pa(this,ok,void 0))}setEventListener(t){var r;Pa(this,SP,t),(r=Ds(this,ok))==null||r.call(this),Pa(this,ok,t(n=>{typeof n=="boolean"?this.setFocused(n):this.onFocus()}))}setFocused(t){Ds(this,QT)!==t&&(Pa(this,QT,t),this.onFocus())}onFocus(){const t=this.isFocused();this.listeners.forEach(r=>{r(t)})}isFocused(){var t;return typeof Ds(this,QT)=="boolean"?Ds(this,QT):((t=globalThis.document)==null?void 0:t.visibilityState)!=="hidden"}},QT=new WeakMap,ok=new WeakMap,SP=new WeakMap,PYe),I3e=new $3t,CP,lk,TP,LYe,U3t=(LYe=class extends o8{constructor(){super();Ai(this,CP,!0);Ai(this,lk);Ai(this,TP);Pa(this,TP,t=>{if(!lA&&window.addEventListener){const r=()=>t(!0),n=()=>t(!1);return window.addEventListener("online",r,!1),window.addEventListener("offline",n,!1),()=>{window.removeEventListener("online",r),window.removeEventListener("offline",n)}}})}onSubscribe(){Ds(this,lk)||this.setEventListener(Ds(this,TP))}onUnsubscribe(){var t;this.hasListeners()||((t=Ds(this,lk))==null||t.call(this),Pa(this,lk,void 0))}setEventListener(t){var r;Pa(this,TP,t),(r=Ds(this,lk))==null||r.call(this),Pa(this,lk,t(this.setOnline.bind(this)))}setOnline(t){Ds(this,CP)!==t&&(Pa(this,CP,t),this.listeners.forEach(n=>{n(t)}))}isOnline(){return Ds(this,CP)}},CP=new WeakMap,lk=new WeakMap,TP=new WeakMap,LYe),whe=new U3t;function xje(){let s,t;const r=new Promise((a,i)=>{s=a,t=i});r.status="pending",r.catch(()=>{});function n(a){Object.assign(r,a),delete r.resolve,delete r.reject}return r.resolve=a=>{n({status:"fulfilled",value:a}),s(a)},r.reject=a=>{n({status:"rejected",reason:a}),t(a)},r}function q3t(s){return Math.min(1e3*2**s,3e4)}function xJe(s){return(s??"online")==="online"?whe.isOnline():!0}var yJe=class extends Error{constructor(s){super("CancelledError"),this.revert=s==null?void 0:s.revert,this.silent=s==null?void 0:s.silent}};function D1e(s){return s instanceof yJe}function vJe(s){let t=!1,r=0,n=!1,a;const i=xje(),l=_=>{var b;n||(p(new yJe(_)),(b=s.abort)==null||b.call(s))},o=()=>{t=!0},c=()=>{t=!1},d=()=>I3e.isFocused()&&(s.networkMode==="always"||whe.isOnline())&&s.canRun(),h=()=>xJe(s.networkMode)&&s.canRun(),m=_=>{var b;n||(n=!0,(b=s.onSuccess)==null||b.call(s,_),a==null||a(),i.resolve(_))},p=_=>{var b;n||(n=!0,(b=s.onError)==null||b.call(s,_),a==null||a(),i.reject(_))},x=()=>new Promise(_=>{var b;a=j=>{(n||d())&&_(j)},(b=s.onPause)==null||b.call(s)}).then(()=>{var _;a=void 0,n||(_=s.onContinue)==null||_.call(s)}),y=()=>{if(n)return;let _;const b=r===0?s.initialPromise:void 0;try{_=b??s.fn()}catch(j){_=Promise.reject(j)}Promise.resolve(_).then(m).catch(j=>{var D;if(n)return;const k=s.retry??(lA?0:3),T=s.retryDelay??q3t,E=typeof T=="function"?T(r,j):T,A=k===!0||typeof k=="number"&&rd()?void 0:x()).then(()=>{t?p(j):y()})})};return{promise:i,cancel:l,continue:()=>(a==null||a(),i),cancelRetry:o,continueRetry:c,canStart:h,start:()=>(h()?y():x().then(y),i)}}var V3t=s=>setTimeout(s,0);function H3t(){let s=[],t=0,r=o=>{o()},n=o=>{o()},a=V3t;const i=o=>{t?s.push(o):a(()=>{r(o)})},l=()=>{const o=s;s=[],o.length&&a(()=>{n(()=>{o.forEach(c=>{r(c)})})})};return{batch:o=>{let c;t++;try{c=o()}finally{t--,t||l()}return c},batchCalls:o=>(...c)=>{i(()=>{o(...c)})},schedule:i,setNotifyFunction:o=>{r=o},setBatchNotifyFunction:o=>{n=o},setScheduler:o=>{a=o}}}var om=H3t(),JT,DYe,bJe=(DYe=class{constructor(){Ai(this,JT)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),fje(this.gcTime)&&Pa(this,JT,setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(s){this.gcTime=Math.max(this.gcTime||0,s??(lA?1/0:5*60*1e3))}clearGcTimeout(){Ds(this,JT)&&(clearTimeout(Ds(this,JT)),Pa(this,JT,void 0))}},JT=new WeakMap,DYe),EP,eE,wy,tE,mp,SB,sE,Qv,l2,RYe,G3t=(RYe=class extends bJe{constructor(t){super();Ai(this,Qv);Ai(this,EP);Ai(this,eE);Ai(this,wy);Ai(this,tE);Ai(this,mp);Ai(this,SB);Ai(this,sE);Pa(this,sE,!1),Pa(this,SB,t.defaultOptions),this.setOptions(t.options),this.observers=[],Pa(this,tE,t.client),Pa(this,wy,Ds(this,tE).getQueryCache()),this.queryKey=t.queryKey,this.queryHash=t.queryHash,Pa(this,EP,W3t(this.options)),this.state=t.state??Ds(this,EP),this.scheduleGc()}get meta(){return this.options.meta}get promise(){var t;return(t=Ds(this,mp))==null?void 0:t.promise}setOptions(t){this.options={...Ds(this,SB),...t},this.updateGcTime(this.options.gcTime)}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&Ds(this,wy).remove(this)}setData(t,r){const n=gje(this.state.data,t,this.options);return Ro(this,Qv,l2).call(this,{data:n,type:"success",dataUpdatedAt:r==null?void 0:r.updatedAt,manual:r==null?void 0:r.manual}),n}setState(t,r){Ro(this,Qv,l2).call(this,{type:"setState",state:t,setStateOptions:r})}cancel(t){var n,a;const r=(n=Ds(this,mp))==null?void 0:n.promise;return(a=Ds(this,mp))==null||a.cancel(t),r?r.then(og).catch(og):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(Ds(this,EP))}isActive(){return this.observers.some(t=>jy(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===M3e||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>Jk(t.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(t=>t.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(t=0){return this.state.data===void 0?!0:t==="static"?!1:this.state.isInvalidated?!0:!mJe(this.state.dataUpdatedAt,t)}onFocus(){var r;const t=this.observers.find(n=>n.shouldFetchOnWindowFocus());t==null||t.refetch({cancelRefetch:!1}),(r=Ds(this,mp))==null||r.continue()}onOnline(){var r;const t=this.observers.find(n=>n.shouldFetchOnReconnect());t==null||t.refetch({cancelRefetch:!1}),(r=Ds(this,mp))==null||r.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),Ds(this,wy).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){this.observers.includes(t)&&(this.observers=this.observers.filter(r=>r!==t),this.observers.length||(Ds(this,mp)&&(Ds(this,sE)?Ds(this,mp).cancel({revert:!0}):Ds(this,mp).cancelRetry()),this.scheduleGc()),Ds(this,wy).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||Ro(this,Qv,l2).call(this,{type:"invalidate"})}fetch(t,r){var d,h,m;if(this.state.fetchStatus!=="idle"){if(this.state.data!==void 0&&(r!=null&&r.cancelRefetch))this.cancel({silent:!0});else if(Ds(this,mp))return Ds(this,mp).continueRetry(),Ds(this,mp).promise}if(t&&this.setOptions(t),!this.options.queryFn){const p=this.observers.find(x=>x.options.queryFn);p&&this.setOptions(p.options)}const n=new AbortController,a=p=>{Object.defineProperty(p,"signal",{enumerable:!0,get:()=>(Pa(this,sE,!0),n.signal)})},i=()=>{const p=pJe(this.options,r),y=(()=>{const _={client:Ds(this,tE),queryKey:this.queryKey,meta:this.meta};return a(_),_})();return Pa(this,sE,!1),this.options.persister?this.options.persister(p,y,this):p(y)},o=(()=>{const p={fetchOptions:r,options:this.options,queryKey:this.queryKey,client:Ds(this,tE),state:this.state,fetchFn:i};return a(p),p})();(d=this.options.behavior)==null||d.onFetch(o,this),Pa(this,eE,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((h=o.fetchOptions)==null?void 0:h.meta))&&Ro(this,Qv,l2).call(this,{type:"fetch",meta:(m=o.fetchOptions)==null?void 0:m.meta});const c=p=>{var x,y,_,b;D1e(p)&&p.silent||Ro(this,Qv,l2).call(this,{type:"error",error:p}),D1e(p)||((y=(x=Ds(this,wy).config).onError)==null||y.call(x,p,this),(b=(_=Ds(this,wy).config).onSettled)==null||b.call(_,this.state.data,p,this)),this.scheduleGc()};return Pa(this,mp,vJe({initialPromise:r==null?void 0:r.initialPromise,fn:o.fetchFn,abort:n.abort.bind(n),onSuccess:p=>{var x,y,_,b;if(p===void 0){c(new Error(`${this.queryHash} data is undefined`));return}try{this.setData(p)}catch(j){c(j);return}(y=(x=Ds(this,wy).config).onSuccess)==null||y.call(x,p,this),(b=(_=Ds(this,wy).config).onSettled)==null||b.call(_,p,this.state.error,this),this.scheduleGc()},onError:c,onFail:(p,x)=>{Ro(this,Qv,l2).call(this,{type:"failed",failureCount:p,error:x})},onPause:()=>{Ro(this,Qv,l2).call(this,{type:"pause"})},onContinue:()=>{Ro(this,Qv,l2).call(this,{type:"continue"})},retry:o.options.retry,retryDelay:o.options.retryDelay,networkMode:o.options.networkMode,canRun:()=>!0})),Ds(this,mp).start()}},EP=new WeakMap,eE=new WeakMap,wy=new WeakMap,tE=new WeakMap,mp=new WeakMap,SB=new WeakMap,sE=new WeakMap,Qv=new WeakSet,l2=function(t){const r=n=>{switch(t.type){case"failed":return{...n,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...n,fetchStatus:"paused"};case"continue":return{...n,fetchStatus:"fetching"};case"fetch":return{...n,..._Je(n.data,this.options),fetchMeta:t.meta??null};case"success":return Pa(this,eE,void 0),{...n,data:t.data,dataUpdateCount:n.dataUpdateCount+1,dataUpdatedAt:t.dataUpdatedAt??Date.now(),error:null,isInvalidated:!1,status:"success",...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};case"error":const a=t.error;return D1e(a)&&a.revert&&Ds(this,eE)?{...Ds(this,eE),fetchStatus:"idle"}:{...n,error:a,errorUpdateCount:n.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:n.fetchFailureCount+1,fetchFailureReason:a,fetchStatus:"idle",status:"error"};case"invalidate":return{...n,isInvalidated:!0};case"setState":return{...n,...t.state}}};this.state=r(this.state),om.batch(()=>{this.observers.forEach(n=>{n.onQueryUpdate()}),Ds(this,wy).notify({query:this,type:"updated",action:t})})},RYe);function _Je(s,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:xJe(t.networkMode)?"fetching":"paused",...s===void 0&&{error:null,status:"pending"}}}function W3t(s){const t=typeof s.initialData=="function"?s.initialData():s.initialData,r=t!==void 0,n=r?typeof s.initialDataUpdatedAt=="function"?s.initialDataUpdatedAt():s.initialDataUpdatedAt:0;return{data:t,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 qb,OYe,K3t=(OYe=class extends o8{constructor(t={}){super();Ai(this,qb);this.config=t,Pa(this,qb,new Map)}build(t,r,n){const a=r.queryKey,i=r.queryHash??A3e(a,r);let l=this.get(i);return l||(l=new G3t({client:t,queryKey:a,queryHash:i,options:t.defaultQueryOptions(r),state:n,defaultOptions:t.getQueryDefaults(a)}),this.add(l)),l}add(t){Ds(this,qb).has(t.queryHash)||(Ds(this,qb).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){const r=Ds(this,qb).get(t.queryHash);r&&(t.destroy(),r===t&&Ds(this,qb).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){om.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return Ds(this,qb).get(t)}getAll(){return[...Ds(this,qb).values()]}find(t){const r={exact:!0,...t};return this.getAll().find(n=>qRe(r,n))}findAll(t={}){const r=this.getAll();return Object.keys(t).length>0?r.filter(n=>qRe(t,n)):r}notify(t){om.batch(()=>{this.listeners.forEach(r=>{r(t)})})}onFocus(){om.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){om.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},qb=new WeakMap,OYe),Vb,ng,rE,Hb,TN,FYe,Y3t=(FYe=class extends bJe{constructor(t){super();Ai(this,Hb);Ai(this,Vb);Ai(this,ng);Ai(this,rE);this.mutationId=t.mutationId,Pa(this,ng,t.mutationCache),Pa(this,Vb,[]),this.state=t.state||wJe(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){Ds(this,Vb).includes(t)||(Ds(this,Vb).push(t),this.clearGcTimeout(),Ds(this,ng).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){Pa(this,Vb,Ds(this,Vb).filter(r=>r!==t)),this.scheduleGc(),Ds(this,ng).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){Ds(this,Vb).length||(this.state.status==="pending"?this.scheduleGc():Ds(this,ng).remove(this))}continue(){var t;return((t=Ds(this,rE))==null?void 0:t.continue())??this.execute(this.state.variables)}async execute(t){var i,l,o,c,d,h,m,p,x,y,_,b,j,k,T,E,A,D,R,z;const r=()=>{Ro(this,Hb,TN).call(this,{type:"continue"})};Pa(this,rE,vJe({fn:()=>this.options.mutationFn?this.options.mutationFn(t):Promise.reject(new Error("No mutationFn found")),onFail:(O,$)=>{Ro(this,Hb,TN).call(this,{type:"failed",failureCount:O,error:$})},onPause:()=>{Ro(this,Hb,TN).call(this,{type:"pause"})},onContinue:r,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>Ds(this,ng).canRun(this)}));const n=this.state.status==="pending",a=!Ds(this,rE).canStart();try{if(n)r();else{Ro(this,Hb,TN).call(this,{type:"pending",variables:t,isPaused:a}),await((l=(i=Ds(this,ng).config).onMutate)==null?void 0:l.call(i,t,this));const $=await((c=(o=this.options).onMutate)==null?void 0:c.call(o,t));$!==this.state.context&&Ro(this,Hb,TN).call(this,{type:"pending",context:$,variables:t,isPaused:a})}const O=await Ds(this,rE).start();return await((h=(d=Ds(this,ng).config).onSuccess)==null?void 0:h.call(d,O,t,this.state.context,this)),await((p=(m=this.options).onSuccess)==null?void 0:p.call(m,O,t,this.state.context)),await((y=(x=Ds(this,ng).config).onSettled)==null?void 0:y.call(x,O,null,this.state.variables,this.state.context,this)),await((b=(_=this.options).onSettled)==null?void 0:b.call(_,O,null,t,this.state.context)),Ro(this,Hb,TN).call(this,{type:"success",data:O}),O}catch(O){try{throw await((k=(j=Ds(this,ng).config).onError)==null?void 0:k.call(j,O,t,this.state.context,this)),await((E=(T=this.options).onError)==null?void 0:E.call(T,O,t,this.state.context)),await((D=(A=Ds(this,ng).config).onSettled)==null?void 0:D.call(A,void 0,O,this.state.variables,this.state.context,this)),await((z=(R=this.options).onSettled)==null?void 0:z.call(R,void 0,O,t,this.state.context)),O}finally{Ro(this,Hb,TN).call(this,{type:"error",error:O})}}finally{Ds(this,ng).runNext(this)}}},Vb=new WeakMap,ng=new WeakMap,rE=new WeakMap,Hb=new WeakSet,TN=function(t){const r=n=>{switch(t.type){case"failed":return{...n,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...n,isPaused:!0};case"continue":return{...n,isPaused:!1};case"pending":return{...n,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:t.isPaused,status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...n,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...n,data:void 0,error:t.error,failureCount:n.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}};this.state=r(this.state),om.batch(()=>{Ds(this,Vb).forEach(n=>{n.onMutationUpdate(t)}),Ds(this,ng).notify({mutation:this,type:"updated",action:t})})},FYe);function wJe(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var N2,Jv,CB,BYe,Z3t=(BYe=class extends o8{constructor(t={}){super();Ai(this,N2);Ai(this,Jv);Ai(this,CB);this.config=t,Pa(this,N2,new Set),Pa(this,Jv,new Map),Pa(this,CB,0)}build(t,r,n){const a=new Y3t({mutationCache:this,mutationId:++dU(this,CB)._,options:t.defaultMutationOptions(r),state:n});return this.add(a),a}add(t){Ds(this,N2).add(t);const r=IU(t);if(typeof r=="string"){const n=Ds(this,Jv).get(r);n?n.push(t):Ds(this,Jv).set(r,[t])}this.notify({type:"added",mutation:t})}remove(t){if(Ds(this,N2).delete(t)){const r=IU(t);if(typeof r=="string"){const n=Ds(this,Jv).get(r);if(n)if(n.length>1){const a=n.indexOf(t);a!==-1&&n.splice(a,1)}else n[0]===t&&Ds(this,Jv).delete(r)}}this.notify({type:"removed",mutation:t})}canRun(t){const r=IU(t);if(typeof r=="string"){const n=Ds(this,Jv).get(r),a=n==null?void 0:n.find(i=>i.state.status==="pending");return!a||a===t}else return!0}runNext(t){var n;const r=IU(t);if(typeof r=="string"){const a=(n=Ds(this,Jv).get(r))==null?void 0:n.find(i=>i!==t&&i.state.isPaused);return(a==null?void 0:a.continue())??Promise.resolve()}else return Promise.resolve()}clear(){om.batch(()=>{Ds(this,N2).forEach(t=>{this.notify({type:"removed",mutation:t})}),Ds(this,N2).clear(),Ds(this,Jv).clear()})}getAll(){return Array.from(Ds(this,N2))}find(t){const r={exact:!0,...t};return this.getAll().find(n=>VRe(r,n))}findAll(t={}){return this.getAll().filter(r=>VRe(t,r))}notify(t){om.batch(()=>{this.listeners.forEach(r=>{r(t)})})}resumePausedMutations(){const t=this.getAll().filter(r=>r.state.isPaused);return om.batch(()=>Promise.all(t.map(r=>r.continue().catch(og))))}},N2=new WeakMap,Jv=new WeakMap,CB=new WeakMap,BYe);function IU(s){var t;return(t=s.options.scope)==null?void 0:t.id}function jhe(s){return{onFetch:(t,r)=>{var h,m,p,x,y;const n=t.options,a=(p=(m=(h=t.fetchOptions)==null?void 0:h.meta)==null?void 0:m.fetchMore)==null?void 0:p.direction,i=((x=t.state.data)==null?void 0:x.pages)||[],l=((y=t.state.data)==null?void 0:y.pageParams)||[];let o={pages:[],pageParams:[]},c=0;const d=async()=>{let _=!1;const b=T=>{Object.defineProperty(T,"signal",{enumerable:!0,get:()=>(t.signal.aborted?_=!0:t.signal.addEventListener("abort",()=>{_=!0}),t.signal)})},j=pJe(t.options,t.fetchOptions),k=async(T,E,A)=>{if(_)return Promise.reject();if(E==null&&T.pages.length)return Promise.resolve(T);const R=(()=>{const ee={client:t.client,queryKey:t.queryKey,pageParam:E,direction:A?"backward":"forward",meta:t.options.meta};return b(ee),ee})(),z=await j(R),{maxPages:O}=t.options,$=A?z3t:B3t;return{pages:$(T.pages,z,O),pageParams:$(T.pageParams,E,O)}};if(a&&i.length){const T=a==="backward",E=T?jJe:yje,A={pages:i,pageParams:l},D=E(n,A);o=await k(A,D,T)}else{const T=s??i.length;do{const E=c===0?l[0]??n.initialPageParam:yje(n,o);if(c>0&&E==null)break;o=await k(o,E),c++}while(c{var _,b;return(b=(_=t.options).persister)==null?void 0:b.call(_,d,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},r)}:t.fetchFn=d}}}function yje(s,{pages:t,pageParams:r}){const n=t.length-1;return t.length>0?s.getNextPageParam(t[n],t,r[n],r):void 0}function jJe(s,{pages:t,pageParams:r}){var n;return t.length>0?(n=s.getPreviousPageParam)==null?void 0:n.call(s,t[0],t,r[0],r):void 0}function X3t(s,t){return t?yje(s,t)!=null:!1}function Q3t(s,t){return!t||!s.getPreviousPageParam?!1:jJe(s,t)!=null}var Du,ck,dk,AP,MP,uk,IP,PP,zYe,J3t=(zYe=class{constructor(s={}){Ai(this,Du);Ai(this,ck);Ai(this,dk);Ai(this,AP);Ai(this,MP);Ai(this,uk);Ai(this,IP);Ai(this,PP);Pa(this,Du,s.queryCache||new K3t),Pa(this,ck,s.mutationCache||new Z3t),Pa(this,dk,s.defaultOptions||{}),Pa(this,AP,new Map),Pa(this,MP,new Map),Pa(this,uk,0)}mount(){dU(this,uk)._++,Ds(this,uk)===1&&(Pa(this,IP,I3e.subscribe(async s=>{s&&(await this.resumePausedMutations(),Ds(this,Du).onFocus())})),Pa(this,PP,whe.subscribe(async s=>{s&&(await this.resumePausedMutations(),Ds(this,Du).onOnline())})))}unmount(){var s,t;dU(this,uk)._--,Ds(this,uk)===0&&((s=Ds(this,IP))==null||s.call(this),Pa(this,IP,void 0),(t=Ds(this,PP))==null||t.call(this),Pa(this,PP,void 0))}isFetching(s){return Ds(this,Du).findAll({...s,fetchStatus:"fetching"}).length}isMutating(s){return Ds(this,ck).findAll({...s,status:"pending"}).length}getQueryData(s){var r;const t=this.defaultQueryOptions({queryKey:s});return(r=Ds(this,Du).get(t.queryHash))==null?void 0:r.state.data}ensureQueryData(s){const t=this.defaultQueryOptions(s),r=Ds(this,Du).build(this,t),n=r.state.data;return n===void 0?this.fetchQuery(s):(s.revalidateIfStale&&r.isStaleByTime(Jk(t.staleTime,r))&&this.prefetchQuery(t),Promise.resolve(n))}getQueriesData(s){return Ds(this,Du).findAll(s).map(({queryKey:t,state:r})=>{const n=r.data;return[t,n]})}setQueryData(s,t,r){const n=this.defaultQueryOptions({queryKey:s}),a=Ds(this,Du).get(n.queryHash),i=a==null?void 0:a.state.data,l=O3t(t,i);if(l!==void 0)return Ds(this,Du).build(this,n).setData(l,{...r,manual:!0})}setQueriesData(s,t,r){return om.batch(()=>Ds(this,Du).findAll(s).map(({queryKey:n})=>[n,this.setQueryData(n,t,r)]))}getQueryState(s){var r;const t=this.defaultQueryOptions({queryKey:s});return(r=Ds(this,Du).get(t.queryHash))==null?void 0:r.state}removeQueries(s){const t=Ds(this,Du);om.batch(()=>{t.findAll(s).forEach(r=>{t.remove(r)})})}resetQueries(s,t){const r=Ds(this,Du);return om.batch(()=>(r.findAll(s).forEach(n=>{n.reset()}),this.refetchQueries({type:"active",...s},t)))}cancelQueries(s,t={}){const r={revert:!0,...t},n=om.batch(()=>Ds(this,Du).findAll(s).map(a=>a.cancel(r)));return Promise.all(n).then(og).catch(og)}invalidateQueries(s,t={}){return om.batch(()=>(Ds(this,Du).findAll(s).forEach(r=>{r.invalidate()}),(s==null?void 0:s.refetchType)==="none"?Promise.resolve():this.refetchQueries({...s,type:(s==null?void 0:s.refetchType)??(s==null?void 0:s.type)??"active"},t)))}refetchQueries(s,t={}){const r={...t,cancelRefetch:t.cancelRefetch??!0},n=om.batch(()=>Ds(this,Du).findAll(s).filter(a=>!a.isDisabled()&&!a.isStatic()).map(a=>{let i=a.fetch(void 0,r);return r.throwOnError||(i=i.catch(og)),a.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(n).then(og)}fetchQuery(s){const t=this.defaultQueryOptions(s);t.retry===void 0&&(t.retry=!1);const r=Ds(this,Du).build(this,t);return r.isStaleByTime(Jk(t.staleTime,r))?r.fetch(t):Promise.resolve(r.state.data)}prefetchQuery(s){return this.fetchQuery(s).then(og).catch(og)}fetchInfiniteQuery(s){return s.behavior=jhe(s.pages),this.fetchQuery(s)}prefetchInfiniteQuery(s){return this.fetchInfiniteQuery(s).then(og).catch(og)}ensureInfiniteQueryData(s){return s.behavior=jhe(s.pages),this.ensureQueryData(s)}resumePausedMutations(){return whe.isOnline()?Ds(this,ck).resumePausedMutations():Promise.resolve()}getQueryCache(){return Ds(this,Du)}getMutationCache(){return Ds(this,ck)}getDefaultOptions(){return Ds(this,dk)}setDefaultOptions(s){Pa(this,dk,s)}setQueryDefaults(s,t){Ds(this,AP).set(cA(s),{queryKey:s,defaultOptions:t})}getQueryDefaults(s){const t=[...Ds(this,AP).values()],r={};return t.forEach(n=>{s9(s,n.queryKey)&&Object.assign(r,n.defaultOptions)}),r}setMutationDefaults(s,t){Ds(this,MP).set(cA(s),{mutationKey:s,defaultOptions:t})}getMutationDefaults(s){const t=[...Ds(this,MP).values()],r={};return t.forEach(n=>{s9(s,n.mutationKey)&&Object.assign(r,n.defaultOptions)}),r}defaultQueryOptions(s){if(s._defaulted)return s;const t={...Ds(this,dk).queries,...this.getQueryDefaults(s.queryKey),...s,_defaulted:!0};return t.queryHash||(t.queryHash=A3e(t.queryKey,t)),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!=="always"),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.queryFn===M3e&&(t.enabled=!1),t}defaultMutationOptions(s){return s!=null&&s._defaulted?s:{...Ds(this,dk).mutations,...(s==null?void 0:s.mutationKey)&&this.getMutationDefaults(s.mutationKey),...s,_defaulted:!0}}clear(){Ds(this,Du).clear(),Ds(this,ck).clear()}},Du=new WeakMap,ck=new WeakMap,dk=new WeakMap,AP=new WeakMap,MP=new WeakMap,uk=new WeakMap,IP=new WeakMap,PP=new WeakMap,zYe),Gg,ul,TB,ag,nE,LP,hk,mk,EB,DP,RP,aE,iE,fk,OP,ic,hO,vje,bje,_je,wje,jje,Nje,kje,kJe,$Ye,NJe=($Ye=class extends o8{constructor(t,r){super();Ai(this,ic);Ai(this,Gg);Ai(this,ul);Ai(this,TB);Ai(this,ag);Ai(this,nE);Ai(this,LP);Ai(this,hk);Ai(this,mk);Ai(this,EB);Ai(this,DP);Ai(this,RP);Ai(this,aE);Ai(this,iE);Ai(this,fk);Ai(this,OP,new Set);this.options=r,Pa(this,Gg,t),Pa(this,mk,null),Pa(this,hk,xje()),this.options.experimental_prefetchInRender||Ds(this,hk).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&&(Ds(this,ul).addObserver(this),WRe(Ds(this,ul),this.options)?Ro(this,ic,hO).call(this):this.updateResult(),Ro(this,ic,wje).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Sje(Ds(this,ul),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Sje(Ds(this,ul),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,Ro(this,ic,jje).call(this),Ro(this,ic,Nje).call(this),Ds(this,ul).removeObserver(this)}setOptions(t){const r=this.options,n=Ds(this,ul);if(this.options=Ds(this,Gg).defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof jy(this.options.enabled,Ds(this,ul))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");Ro(this,ic,kje).call(this),Ds(this,ul).setOptions(this.options),r._defaulted&&!_he(this.options,r)&&Ds(this,Gg).getQueryCache().notify({type:"observerOptionsUpdated",query:Ds(this,ul),observer:this});const a=this.hasListeners();a&&KRe(Ds(this,ul),n,this.options,r)&&Ro(this,ic,hO).call(this),this.updateResult(),a&&(Ds(this,ul)!==n||jy(this.options.enabled,Ds(this,ul))!==jy(r.enabled,Ds(this,ul))||Jk(this.options.staleTime,Ds(this,ul))!==Jk(r.staleTime,Ds(this,ul)))&&Ro(this,ic,vje).call(this);const i=Ro(this,ic,bje).call(this);a&&(Ds(this,ul)!==n||jy(this.options.enabled,Ds(this,ul))!==jy(r.enabled,Ds(this,ul))||i!==Ds(this,fk))&&Ro(this,ic,_je).call(this,i)}getOptimisticResult(t){const r=Ds(this,Gg).getQueryCache().build(Ds(this,Gg),t),n=this.createResult(r,t);return t5t(this,n)&&(Pa(this,ag,n),Pa(this,LP,this.options),Pa(this,nE,Ds(this,ul).state)),n}getCurrentResult(){return Ds(this,ag)}trackResult(t,r){return new Proxy(t,{get:(n,a)=>(this.trackProp(a),r==null||r(a),Reflect.get(n,a))})}trackProp(t){Ds(this,OP).add(t)}getCurrentQuery(){return Ds(this,ul)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){const r=Ds(this,Gg).defaultQueryOptions(t),n=Ds(this,Gg).getQueryCache().build(Ds(this,Gg),r);return n.fetch().then(()=>this.createResult(n,r))}fetch(t){return Ro(this,ic,hO).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),Ds(this,ag)))}createResult(t,r){var O;const n=Ds(this,ul),a=this.options,i=Ds(this,ag),l=Ds(this,nE),o=Ds(this,LP),d=t!==n?t.state:Ds(this,TB),{state:h}=t;let m={...h},p=!1,x;if(r._optimisticResults){const $=this.hasListeners(),ee=!$&&WRe(t,r),Z=$&&KRe(t,n,r,a);(ee||Z)&&(m={...m,..._Je(h.data,t.options)}),r._optimisticResults==="isRestoring"&&(m.fetchStatus="idle")}let{error:y,errorUpdatedAt:_,status:b}=m;x=m.data;let j=!1;if(r.placeholderData!==void 0&&x===void 0&&b==="pending"){let $;i!=null&&i.isPlaceholderData&&r.placeholderData===(o==null?void 0:o.placeholderData)?($=i.data,j=!0):$=typeof r.placeholderData=="function"?r.placeholderData((O=Ds(this,RP))==null?void 0:O.state.data,Ds(this,RP)):r.placeholderData,$!==void 0&&(b="success",x=gje(i==null?void 0:i.data,$,r),p=!0)}if(r.select&&x!==void 0&&!j)if(i&&x===(l==null?void 0:l.data)&&r.select===Ds(this,EB))x=Ds(this,DP);else try{Pa(this,EB,r.select),x=r.select(x),x=gje(i==null?void 0:i.data,x,r),Pa(this,DP,x),Pa(this,mk,null)}catch($){Pa(this,mk,$)}Ds(this,mk)&&(y=Ds(this,mk),x=Ds(this,DP),_=Date.now(),b="error");const k=m.fetchStatus==="fetching",T=b==="pending",E=b==="error",A=T&&k,D=x!==void 0,z={status:b,fetchStatus:m.fetchStatus,isPending:T,isSuccess:b==="success",isError:E,isInitialLoading:A,isLoading:A,data:x,dataUpdatedAt:m.dataUpdatedAt,error:y,errorUpdatedAt:_,failureCount:m.fetchFailureCount,failureReason:m.fetchFailureReason,errorUpdateCount:m.errorUpdateCount,isFetched:m.dataUpdateCount>0||m.errorUpdateCount>0,isFetchedAfterMount:m.dataUpdateCount>d.dataUpdateCount||m.errorUpdateCount>d.errorUpdateCount,isFetching:k,isRefetching:k&&!T,isLoadingError:E&&!D,isPaused:m.fetchStatus==="paused",isPlaceholderData:p,isRefetchError:E&&D,isStale:P3e(t,r),refetch:this.refetch,promise:Ds(this,hk),isEnabled:jy(r.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){const $=J=>{z.status==="error"?J.reject(z.error):z.data!==void 0&&J.resolve(z.data)},ee=()=>{const J=Pa(this,hk,z.promise=xje());$(J)},Z=Ds(this,hk);switch(Z.status){case"pending":t.queryHash===n.queryHash&&$(Z);break;case"fulfilled":(z.status==="error"||z.data!==Z.value)&&ee();break;case"rejected":(z.status!=="error"||z.error!==Z.reason)&&ee();break}}return z}updateResult(){const t=Ds(this,ag),r=this.createResult(Ds(this,ul),this.options);if(Pa(this,nE,Ds(this,ul).state),Pa(this,LP,this.options),Ds(this,nE).data!==void 0&&Pa(this,RP,Ds(this,ul)),_he(r,t))return;Pa(this,ag,r);const n=()=>{if(!t)return!0;const{notifyOnChangeProps:a}=this.options,i=typeof a=="function"?a():a;if(i==="all"||!i&&!Ds(this,OP).size)return!0;const l=new Set(i??Ds(this,OP));return this.options.throwOnError&&l.add("error"),Object.keys(Ds(this,ag)).some(o=>{const c=o;return Ds(this,ag)[c]!==t[c]&&l.has(c)})};Ro(this,ic,kJe).call(this,{listeners:n()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&Ro(this,ic,wje).call(this)}},Gg=new WeakMap,ul=new WeakMap,TB=new WeakMap,ag=new WeakMap,nE=new WeakMap,LP=new WeakMap,hk=new WeakMap,mk=new WeakMap,EB=new WeakMap,DP=new WeakMap,RP=new WeakMap,aE=new WeakMap,iE=new WeakMap,fk=new WeakMap,OP=new WeakMap,ic=new WeakSet,hO=function(t){Ro(this,ic,kje).call(this);let r=Ds(this,ul).fetch(this.options,t);return t!=null&&t.throwOnError||(r=r.catch(og)),r},vje=function(){Ro(this,ic,jje).call(this);const t=Jk(this.options.staleTime,Ds(this,ul));if(lA||Ds(this,ag).isStale||!fje(t))return;const n=mJe(Ds(this,ag).dataUpdatedAt,t)+1;Pa(this,aE,setTimeout(()=>{Ds(this,ag).isStale||this.updateResult()},n))},bje=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(Ds(this,ul)):this.options.refetchInterval)??!1},_je=function(t){Ro(this,ic,Nje).call(this),Pa(this,fk,t),!(lA||jy(this.options.enabled,Ds(this,ul))===!1||!fje(Ds(this,fk))||Ds(this,fk)===0)&&Pa(this,iE,setInterval(()=>{(this.options.refetchIntervalInBackground||I3e.isFocused())&&Ro(this,ic,hO).call(this)},Ds(this,fk)))},wje=function(){Ro(this,ic,vje).call(this),Ro(this,ic,_je).call(this,Ro(this,ic,bje).call(this))},jje=function(){Ds(this,aE)&&(clearTimeout(Ds(this,aE)),Pa(this,aE,void 0))},Nje=function(){Ds(this,iE)&&(clearInterval(Ds(this,iE)),Pa(this,iE,void 0))},kje=function(){const t=Ds(this,Gg).getQueryCache().build(Ds(this,Gg),this.options);if(t===Ds(this,ul))return;const r=Ds(this,ul);Pa(this,ul,t),Pa(this,TB,t.state),this.hasListeners()&&(r==null||r.removeObserver(this),t.addObserver(this))},kJe=function(t){om.batch(()=>{t.listeners&&this.listeners.forEach(r=>{r(Ds(this,ag))}),Ds(this,Gg).getQueryCache().notify({query:Ds(this,ul),type:"observerResultsUpdated"})})},$Ye);function e5t(s,t){return jy(t.enabled,s)!==!1&&s.state.data===void 0&&!(s.state.status==="error"&&t.retryOnMount===!1)}function WRe(s,t){return e5t(s,t)||s.state.data!==void 0&&Sje(s,t,t.refetchOnMount)}function Sje(s,t,r){if(jy(t.enabled,s)!==!1&&Jk(t.staleTime,s)!=="static"){const n=typeof r=="function"?r(s):r;return n==="always"||n!==!1&&P3e(s,t)}return!1}function KRe(s,t,r,n){return(s!==t||jy(n.enabled,s)===!1)&&(!r.suspense||s.state.status!=="error")&&P3e(s,r)}function P3e(s,t){return jy(t.enabled,s)!==!1&&s.isStaleByTime(Jk(t.staleTime,s))}function t5t(s,t){return!_he(s.getCurrentResult(),t)}var s5t=class extends NJe{constructor(s,t){super(s,t)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(s){super.setOptions({...s,behavior:jhe()})}getOptimisticResult(s){return s.behavior=jhe(),super.getOptimisticResult(s)}fetchNextPage(s){return this.fetch({...s,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(s){return this.fetch({...s,meta:{fetchMore:{direction:"backward"}}})}createResult(s,t){var y,_;const{state:r}=s,n=super.createResult(s,t),{isFetching:a,isRefetching:i,isError:l,isRefetchError:o}=n,c=(_=(y=r.fetchMeta)==null?void 0:y.fetchMore)==null?void 0:_.direction,d=l&&c==="forward",h=a&&c==="forward",m=l&&c==="backward",p=a&&c==="backward";return{...n,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:X3t(t,r.data),hasPreviousPage:Q3t(t,r.data),isFetchNextPageError:d,isFetchingNextPage:h,isFetchPreviousPageError:m,isFetchingPreviousPage:p,isRefetchError:o&&!d&&!m,isRefetching:i&&!h&&!p}}},pk,gk,Wg,k2,J2,iue,Cje,UYe,r5t=(UYe=class extends o8{constructor(r,n){super();Ai(this,J2);Ai(this,pk);Ai(this,gk);Ai(this,Wg);Ai(this,k2);Pa(this,pk,r),this.setOptions(n),this.bindMethods(),Ro(this,J2,iue).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(r){var a;const n=this.options;this.options=Ds(this,pk).defaultMutationOptions(r),_he(this.options,n)||Ds(this,pk).getMutationCache().notify({type:"observerOptionsUpdated",mutation:Ds(this,Wg),observer:this}),n!=null&&n.mutationKey&&this.options.mutationKey&&cA(n.mutationKey)!==cA(this.options.mutationKey)?this.reset():((a=Ds(this,Wg))==null?void 0:a.state.status)==="pending"&&Ds(this,Wg).setOptions(this.options)}onUnsubscribe(){var r;this.hasListeners()||(r=Ds(this,Wg))==null||r.removeObserver(this)}onMutationUpdate(r){Ro(this,J2,iue).call(this),Ro(this,J2,Cje).call(this,r)}getCurrentResult(){return Ds(this,gk)}reset(){var r;(r=Ds(this,Wg))==null||r.removeObserver(this),Pa(this,Wg,void 0),Ro(this,J2,iue).call(this),Ro(this,J2,Cje).call(this)}mutate(r,n){var a;return Pa(this,k2,n),(a=Ds(this,Wg))==null||a.removeObserver(this),Pa(this,Wg,Ds(this,pk).getMutationCache().build(Ds(this,pk),this.options)),Ds(this,Wg).addObserver(this),Ds(this,Wg).execute(r)}},pk=new WeakMap,gk=new WeakMap,Wg=new WeakMap,k2=new WeakMap,J2=new WeakSet,iue=function(){var n;const r=((n=Ds(this,Wg))==null?void 0:n.state)??wJe();Pa(this,gk,{...r,isPending:r.status==="pending",isSuccess:r.status==="success",isError:r.status==="error",isIdle:r.status==="idle",mutate:this.mutate,reset:this.reset})},Cje=function(r){om.batch(()=>{var n,a,i,l,o,c,d,h;if(Ds(this,k2)&&this.hasListeners()){const m=Ds(this,gk).variables,p=Ds(this,gk).context;(r==null?void 0:r.type)==="success"?((a=(n=Ds(this,k2)).onSuccess)==null||a.call(n,r.data,m,p),(l=(i=Ds(this,k2)).onSettled)==null||l.call(i,r.data,null,m,p)):(r==null?void 0:r.type)==="error"&&((c=(o=Ds(this,k2)).onError)==null||c.call(o,r.error,m,p),(h=(d=Ds(this,k2)).onSettled)==null||h.call(d,void 0,r.error,m,p))}this.listeners.forEach(m=>{m(Ds(this,gk))})})},UYe),SJe=S.createContext(void 0),ns=s=>{const t=S.useContext(SJe);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},n5t=({client:s,children:t})=>(S.useEffect(()=>(s.mount(),()=>{s.unmount()}),[s]),e.jsx(SJe.Provider,{value:s,children:t})),CJe=S.createContext(!1),a5t=()=>S.useContext(CJe);CJe.Provider;function i5t(){let s=!1;return{clearReset:()=>{s=!1},reset:()=>{s=!0},isReset:()=>s}}var o5t=S.createContext(i5t()),l5t=()=>S.useContext(o5t),c5t=(s,t)=>{(s.suspense||s.throwOnError||s.experimental_prefetchInRender)&&(t.isReset()||(s.retryOnMount=!1))},d5t=s=>{S.useEffect(()=>{s.clearReset()},[s])},u5t=({result:s,errorResetBoundary:t,throwOnError:r,query:n,suspense:a})=>s.isError&&!t.isReset()&&!s.isFetching&&n&&(a&&s.data===void 0||gJe(r,[s.error,n])),h5t=s=>{if(s.suspense){const t=n=>n==="static"?n:Math.max(n??1e3,1e3),r=s.staleTime;s.staleTime=typeof r=="function"?(...n)=>t(r(...n)):t(r),typeof s.gcTime=="number"&&(s.gcTime=Math.max(s.gcTime,1e3))}},m5t=(s,t)=>s.isLoading&&s.isFetching&&!t,f5t=(s,t)=>(s==null?void 0:s.suspense)&&t.isPending,YRe=(s,t,r)=>t.fetchOptimistic(s).catch(()=>{r.clearReset()});function TJe(s,t,r){var m,p,x,y,_;const n=a5t(),a=l5t(),i=ns(),l=i.defaultQueryOptions(s);(p=(m=i.getDefaultOptions().queries)==null?void 0:m._experimental_beforeQuery)==null||p.call(m,l),l._optimisticResults=n?"isRestoring":"optimistic",h5t(l),c5t(l,a),d5t(a);const o=!i.getQueryCache().get(l.queryHash),[c]=S.useState(()=>new t(i,l)),d=c.getOptimisticResult(l),h=!n&&s.subscribed!==!1;if(S.useSyncExternalStore(S.useCallback(b=>{const j=h?c.subscribe(om.batchCalls(b)):og;return c.updateResult(),j},[c,h]),()=>c.getCurrentResult(),()=>c.getCurrentResult()),S.useEffect(()=>{c.setOptions(l)},[l,c]),f5t(l,d))throw YRe(l,c,a);if(u5t({result:d,errorResetBoundary:a,throwOnError:l.throwOnError,query:i.getQueryCache().get(l.queryHash),suspense:l.suspense}))throw d.error;if((y=(x=i.getDefaultOptions().queries)==null?void 0:x._experimental_afterQuery)==null||y.call(x,l,d),l.experimental_prefetchInRender&&!lA&&m5t(d,n)){const b=o?YRe(l,c,a):(_=i.getQueryCache().get(l.queryHash))==null?void 0:_.promise;b==null||b.catch(og).finally(()=>{c.updateResult()})}return l.notifyOnChangeProps?d:c.trackResult(d)}function yt(s,t){return TJe(s,NJe)}function Pt(s,t){const r=ns(),[n]=S.useState(()=>new r5t(r,s));S.useEffect(()=>{n.setOptions(s)},[n,s]);const a=S.useSyncExternalStore(S.useCallback(l=>n.subscribe(om.batchCalls(l)),[n]),()=>n.getCurrentResult(),()=>n.getCurrentResult()),i=S.useCallback((l,o)=>{n.mutate(l,o).catch(og)},[n]);if(a.error&&gJe(n.options.throwOnError,[a.error]))throw a.error;return{...a,mutate:i,mutateAsync:a.mutate}}function p5t(s,t){return TJe(s,s5t)}/** * @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 r9(){return r9=Object.assign?Object.assign.bind():function(s){for(var t=1;t"u")throw new Error(t)}function EJe(s,t){if(!s){typeof console<"u"&&console.warn(t);try{throw new Error(t)}catch{}}}function x5t(){return Math.random().toString(36).substr(2,8)}function XRe(s,t){return{usr:s.state,key:s.key,idx:t}}function Tje(s,t,r,n){return r===void 0&&(r=null),r9({pathname:typeof s=="string"?s:s.pathname,search:"",hash:""},typeof t=="string"?l8(t):t,{state:r,key:t&&t.key||n||x5t()})}function Nhe(s){let{pathname:t="/",search:r="",hash:n=""}=s;return r&&r!=="?"&&(t+=r.charAt(0)==="?"?r:"?"+r),n&&n!=="#"&&(t+=n.charAt(0)==="#"?n:"#"+n),t}function l8(s){let t={};if(s){let r=s.indexOf("#");r>=0&&(t.hash=s.substr(r),s=s.substr(0,r));let n=s.indexOf("?");n>=0&&(t.search=s.substr(n),s=s.substr(0,n)),s&&(t.pathname=s)}return t}function y5t(s,t,r,n){n===void 0&&(n={});let{window:a=document.defaultView,v5Compat:i=!1}=n,l=a.history,o=vk.Pop,c=null,d=h();d==null&&(d=0,l.replaceState(r9({},l.state,{idx:d}),""));function h(){return(l.state||{idx:null}).idx}function m(){o=vk.Pop;let b=h(),j=b==null?null:b-d;d=b,c&&c({action:o,location:_.location,delta:j})}function p(b,j){o=vk.Push;let k=Tje(_.location,b,j);d=h()+1;let T=XRe(k,d),E=_.createHref(k);try{l.pushState(T,"",E)}catch(A){if(A instanceof DOMException&&A.name==="DataCloneError")throw A;a.location.assign(E)}i&&c&&c({action:o,location:_.location,delta:1})}function x(b,j){o=vk.Replace;let k=Tje(_.location,b,j);d=h();let T=XRe(k,d),E=_.createHref(k);l.replaceState(T,"",E),i&&c&&c({action:o,location:_.location,delta:0})}function y(b){let j=a.location.origin!=="null"?a.location.origin:a.location.href,k=typeof b=="string"?b:Nhe(b);return k=k.replace(/ $/,"%20"),xh(j,"No window.location.(origin|href) available to create URL for href: "+k),new URL(k,j)}let _={get action(){return o},get location(){return s(a,l)},listen(b){if(c)throw new Error("A history only accepts one active listener");return a.addEventListener(ZRe,m),c=b,()=>{a.removeEventListener(ZRe,m),c=null}},createHref(b){return t(a,b)},createURL:y,encodeLocation(b){let j=y(b);return{pathname:j.pathname,search:j.search,hash:j.hash}},push:p,replace:x,go(b){return l.go(b)}};return _}var QRe;(function(s){s.data="data",s.deferred="deferred",s.redirect="redirect",s.error="error"})(QRe||(QRe={}));function v5t(s,t,r){return r===void 0&&(r="/"),b5t(s,t,r,!1)}function b5t(s,t,r,n){let a=typeof t=="string"?l8(t):t,i=L3e(a.pathname||"/",r);if(i==null)return null;let l=AJe(s);_5t(l);let o=null;for(let c=0;o==null&&c{let c={relativePath:o===void 0?i.path||"":o,caseSensitive:i.caseSensitive===!0,childrenIndex:l,route:i};c.relativePath.startsWith("/")&&(xh(c.relativePath.startsWith(n),'Absolute route path "'+c.relativePath+'" nested under path '+('"'+n+'" is not valid. An absolute child route path ')+"must start with the combined path of all its parent routes."),c.relativePath=c.relativePath.slice(n.length));let d=eS([n,c.relativePath]),h=r.concat(c);i.children&&i.children.length>0&&(xh(i.index!==!0,"Index routes must not have child routes. Please remove "+('all child routes from route path "'+d+'".')),AJe(i.children,t,h,d)),!(i.path==null&&!i.index)&&t.push({path:d,score:T5t(d,i.index),routesMeta:h})};return s.forEach((i,l)=>{var o;if(i.path===""||!((o=i.path)!=null&&o.includes("?")))a(i,l);else for(let c of MJe(i.path))a(i,l,c)}),t}function MJe(s){let t=s.split("/");if(t.length===0)return[];let[r,...n]=t,a=r.endsWith("?"),i=r.replace(/\?$/,"");if(n.length===0)return a?[i,""]:[i];let l=MJe(n.join("/")),o=[];return o.push(...l.map(c=>c===""?i:[i,c].join("/"))),a&&o.push(...l),o.map(c=>s.startsWith("/")&&c===""?"/":c)}function _5t(s){s.sort((t,r)=>t.score!==r.score?r.score-t.score:E5t(t.routesMeta.map(n=>n.childrenIndex),r.routesMeta.map(n=>n.childrenIndex)))}const w5t=/^:[\w-]+$/,j5t=3,N5t=2,k5t=1,S5t=10,C5t=-2,JRe=s=>s==="*";function T5t(s,t){let r=s.split("/"),n=r.length;return r.some(JRe)&&(n+=C5t),t&&(n+=N5t),r.filter(a=>!JRe(a)).reduce((a,i)=>a+(w5t.test(i)?j5t:i===""?k5t:S5t),n)}function E5t(s,t){return s.length===t.length&&s.slice(0,-1).every((n,a)=>n===t[a])?s[s.length-1]-t[t.length-1]:0}function A5t(s,t,r){let{routesMeta:n}=s,a={},i="/",l=[];for(let o=0;o{let{paramName:p,isOptional:x}=h;if(p==="*"){let _=o[m]||"";l=i.slice(0,i.length-_.length).replace(/(.)\/+$/,"$1")}const y=o[m];return x&&!y?d[p]=void 0:d[p]=(y||"").replace(/%2F/g,"/"),d},{}),pathname:i,pathnameBase:l,pattern:s}}function M5t(s,t,r){t===void 0&&(t=!1),r===void 0&&(r=!0),EJe(s==="*"||!s.endsWith("*")||s.endsWith("/*"),'Route path "'+s+'" will be treated as if it were '+('"'+s.replace(/\*$/,"/*")+'" because the `*` character must ')+"always follow a `/` in the pattern. To get rid of this warning, "+('please change the route path to "'+s.replace(/\*$/,"/*")+'".'));let n=[],a="^"+s.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(l,o,c)=>(n.push({paramName:o,isOptional:c!=null}),c?"/?([^\\/]+)?":"/([^\\/]+)"));return s.endsWith("*")?(n.push({paramName:"*"}),a+=s==="*"||s==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):r?a+="\\/*$":s!==""&&s!=="/"&&(a+="(?:(?=\\/|$))"),[new RegExp(a,t?void 0:"i"),n]}function I5t(s){try{return s.split("/").map(t=>decodeURIComponent(t).replace(/\//g,"%2F")).join("/")}catch(t){return EJe(!1,'The URL path "'+s+'" could not be decoded because it is is a malformed URL segment. This is probably due to a bad percent '+("encoding ("+t+").")),s}}function L3e(s,t){if(t==="/")return s;if(!s.toLowerCase().startsWith(t.toLowerCase()))return null;let r=t.endsWith("/")?t.length-1:t.length,n=s.charAt(r);return n&&n!=="/"?null:s.slice(r)||"/"}function P5t(s,t){t===void 0&&(t="/");let{pathname:r,search:n="",hash:a=""}=typeof s=="string"?l8(s):s;return{pathname:r?r.startsWith("/")?r:L5t(r,t):t,search:O5t(n),hash:F5t(a)}}function L5t(s,t){let r=t.replace(/\/+$/,"").split("/");return s.split("/").forEach(a=>{a===".."?r.length>1&&r.pop():a!=="."&&r.push(a)}),r.length>1?r.join("/"):"/"}function R1e(s,t,r,n){return"Cannot include a '"+s+"' character in a manually specified "+("`to."+t+"` 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 D5t(s){return s.filter((t,r)=>r===0||t.route.path&&t.route.path.length>0)}function D3e(s,t){let r=D5t(s);return t?r.map((n,a)=>a===r.length-1?n.pathname:n.pathnameBase):r.map(n=>n.pathnameBase)}function R3e(s,t,r,n){n===void 0&&(n=!1);let a;typeof s=="string"?a=l8(s):(a=r9({},s),xh(!a.pathname||!a.pathname.includes("?"),R1e("?","pathname","search",a)),xh(!a.pathname||!a.pathname.includes("#"),R1e("#","pathname","hash",a)),xh(!a.search||!a.search.includes("#"),R1e("#","search","hash",a)));let i=s===""||a.pathname==="",l=i?"/":a.pathname,o;if(l==null)o=r;else{let m=t.length-1;if(!n&&l.startsWith("..")){let p=l.split("/");for(;p[0]==="..";)p.shift(),m-=1;a.pathname=p.join("/")}o=m>=0?t[m]:"/"}let c=P5t(a,o),d=l&&l!=="/"&&l.endsWith("/"),h=(i||l===".")&&r.endsWith("/");return!c.pathname.endsWith("/")&&(d||h)&&(c.pathname+="/"),c}const eS=s=>s.join("/").replace(/\/\/+/g,"/"),R5t=s=>s.replace(/\/+$/,"").replace(/^\/*/,"/"),O5t=s=>!s||s==="?"?"":s.startsWith("?")?s:"?"+s,F5t=s=>!s||s==="#"?"":s.startsWith("#")?s:"#"+s;function B5t(s){return s!=null&&typeof s.status=="number"&&typeof s.statusText=="string"&&typeof s.internal=="boolean"&&"data"in s}const IJe=["post","put","patch","delete"];new Set(IJe);const z5t=["get",...IJe];new Set(z5t);/** * 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 n9(){return n9=Object.assign?Object.assign.bind():function(s){for(var t=1;t{o.current=!0}),S.useCallback(function(d,h){if(h===void 0&&(h={}),!o.current)return;if(typeof d=="number"){n.go(d);return}let m=R3e(d,JSON.parse(l),i,h.relative==="path");s==null&&t!=="/"&&(m.pathname=m.pathname==="/"?t:eS([t,m.pathname])),(h.replace?n.replace:n.push)(m,h.state,h)},[t,n,l,i,s])}const V5t=S.createContext(null);function H5t(s){let t=S.useContext(V_).outlet;return t&&S.createElement(V5t.Provider,{value:s},t)}function Po(){let{matches:s}=S.useContext(V_),t=s[s.length-1];return t?t.params:{}}function DJe(s,t){let{relative:r}=t===void 0?{}:t,{future:n}=S.useContext(LS),{matches:a}=S.useContext(V_),{pathname:i}=Vc(),l=JSON.stringify(D3e(a,n.v7_relativeSplatPath));return S.useMemo(()=>R3e(s,JSON.parse(l),i,r==="path"),[s,l,i,r])}function G5t(s,t){return W5t(s,t)}function W5t(s,t,r,n){c8()||xh(!1);let{navigator:a}=S.useContext(LS),{matches:i}=S.useContext(V_),l=i[i.length-1],o=l?l.params:{};l&&l.pathname;let c=l?l.pathnameBase:"/";l&&l.route;let d=Vc(),h;if(t){var m;let b=typeof t=="string"?l8(t):t;c==="/"||(m=b.pathname)!=null&&m.startsWith(c)||xh(!1),h=b}else h=d;let p=h.pathname||"/",x=p;if(c!=="/"){let b=c.replace(/^\//,"").split("/");x="/"+p.replace(/^\//,"").split("/").slice(b.length).join("/")}let y=v5t(s,{pathname:x}),_=Q5t(y&&y.map(b=>Object.assign({},b,{params:Object.assign({},o,b.params),pathname:eS([c,a.encodeLocation?a.encodeLocation(b.pathname).pathname:b.pathname]),pathnameBase:b.pathnameBase==="/"?c:eS([c,a.encodeLocation?a.encodeLocation(b.pathnameBase).pathname:b.pathnameBase])})),i,r,n);return t&&_?S.createElement(Xpe.Provider,{value:{location:n9({pathname:"/",search:"",hash:"",state:null,key:"default"},h),navigationType:vk.Pop}},_):_}function K5t(){let s=sTt(),t=B5t(s)?s.status+" "+s.statusText:s instanceof Error?s.message:JSON.stringify(s),r=s instanceof Error?s.stack:null,a={padding:"0.5rem",backgroundColor:"rgba(200,200,200, 0.5)"};return S.createElement(S.Fragment,null,S.createElement("h2",null,"Unexpected Application Error!"),S.createElement("h3",{style:{fontStyle:"italic"}},t),r?S.createElement("pre",{style:a},r):null,null)}const Y5t=S.createElement(K5t,null);class Z5t extends S.Component{constructor(t){super(t),this.state={location:t.location,revalidation:t.revalidation,error:t.error}}static getDerivedStateFromError(t){return{error:t}}static getDerivedStateFromProps(t,r){return r.location!==t.location||r.revalidation!=="idle"&&t.revalidation==="idle"?{error:t.error,location:t.location,revalidation:t.revalidation}:{error:t.error!==void 0?t.error:r.error,location:r.location,revalidation:t.revalidation||r.revalidation}}componentDidCatch(t,r){console.error("React Router caught the following error during render",t,r)}render(){return this.state.error!==void 0?S.createElement(V_.Provider,{value:this.props.routeContext},S.createElement(PJe.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function X5t(s){let{routeContext:t,match:r,children:n}=s,a=S.useContext(O3e);return a&&a.static&&a.staticContext&&(r.route.errorElement||r.route.ErrorBoundary)&&(a.staticContext._deepestRenderedBoundaryId=r.route.id),S.createElement(V_.Provider,{value:t},n)}function Q5t(s,t,r,n){var a;if(t===void 0&&(t=[]),r===void 0&&(r=null),n===void 0&&(n=null),s==null){var i;if(!r)return null;if(r.errors)s=r.matches;else if((i=n)!=null&&i.v7_partialHydration&&t.length===0&&!r.initialized&&r.matches.length>0)s=r.matches;else return null}let l=s,o=(a=r)==null?void 0:a.errors;if(o!=null){let h=l.findIndex(m=>m.route.id&&(o==null?void 0:o[m.route.id])!==void 0);h>=0||xh(!1),l=l.slice(0,Math.min(l.length,h+1))}let c=!1,d=-1;if(r&&n&&n.v7_partialHydration)for(let h=0;h=0?l=l.slice(0,d+1):l=[l[0]];break}}}return l.reduceRight((h,m,p)=>{let x,y=!1,_=null,b=null;r&&(x=o&&m.route.id?o[m.route.id]:void 0,_=m.route.errorElement||Y5t,c&&(d<0&&p===0?(y=!0,b=null):d===p&&(y=!0,b=m.route.hydrateFallbackElement||null)));let j=t.concat(l.slice(0,p+1)),k=()=>{let T;return x?T=_:y?T=b:m.route.Component?T=S.createElement(m.route.Component,null):m.route.element?T=m.route.element:T=h,S.createElement(X5t,{match:m,routeContext:{outlet:h,matches:j,isDataRoute:r!=null},children:T})};return r&&(m.route.ErrorBoundary||m.route.errorElement||p===0)?S.createElement(Z5t,{location:r.location,revalidation:r.revalidation,component:_,error:x,children:k(),routeContext:{outlet:null,matches:j,isDataRoute:!0}}):k()},null)}var RJe=function(s){return s.UseBlocker="useBlocker",s.UseRevalidator="useRevalidator",s.UseNavigateStable="useNavigate",s}(RJe||{}),khe=function(s){return s.UseBlocker="useBlocker",s.UseLoaderData="useLoaderData",s.UseActionData="useActionData",s.UseRouteError="useRouteError",s.UseNavigation="useNavigation",s.UseRouteLoaderData="useRouteLoaderData",s.UseMatches="useMatches",s.UseRevalidator="useRevalidator",s.UseNavigateStable="useNavigate",s.UseRouteId="useRouteId",s}(khe||{});function J5t(s){let t=S.useContext(O3e);return t||xh(!1),t}function eTt(s){let t=S.useContext($5t);return t||xh(!1),t}function tTt(s){let t=S.useContext(V_);return t||xh(!1),t}function OJe(s){let t=tTt(),r=t.matches[t.matches.length-1];return r.route.id||xh(!1),r.route.id}function sTt(){var s;let t=S.useContext(PJe),r=eTt(khe.UseRouteError),n=OJe(khe.UseRouteError);return t!==void 0?t:(s=r.errors)==null?void 0:s[n]}function rTt(){let{router:s}=J5t(RJe.UseNavigateStable),t=OJe(khe.UseNavigateStable),r=S.useRef(!1);return LJe(()=>{r.current=!0}),S.useCallback(function(a,i){i===void 0&&(i={}),r.current&&(typeof a=="number"?s.navigate(a):s.navigate(a,n9({fromRouteId:t},i)))},[s,t])}function nTt(s,t){s==null||s.v7_startTransition,s==null||s.v7_relativeSplatPath}function O1e(s){let{to:t,replace:r,state:n,relative:a}=s;c8()||xh(!1);let{future:i,static:l}=S.useContext(LS),{matches:o}=S.useContext(V_),{pathname:c}=Vc(),d=Fr(),h=R3e(t,D3e(o,i.v7_relativeSplatPath),c,a==="path"),m=JSON.stringify(h);return S.useEffect(()=>d(JSON.parse(m),{replace:r,state:n,relative:a}),[d,m,a,r,n]),null}function aTt(s){return H5t(s.context)}function gs(s){xh(!1)}function iTt(s){let{basename:t="/",children:r=null,location:n,navigationType:a=vk.Pop,navigator:i,static:l=!1,future:o}=s;c8()&&xh(!1);let c=t.replace(/^\/*/,"/"),d=S.useMemo(()=>({basename:c,navigator:i,static:l,future:n9({v7_relativeSplatPath:!1},o)}),[c,o,i,l]);typeof n=="string"&&(n=l8(n));let{pathname:h="/",search:m="",hash:p="",state:x=null,key:y="default"}=n,_=S.useMemo(()=>{let b=L3e(h,c);return b==null?null:{location:{pathname:b,search:m,hash:p,state:x,key:y},navigationType:a}},[c,h,m,p,x,y,a]);return _==null?null:S.createElement(LS.Provider,{value:d},S.createElement(Xpe.Provider,{children:r,value:_}))}function She(s){let{children:t,location:r}=s;return G5t(Eje(t),r)}new Promise(()=>{});function Eje(s,t){t===void 0&&(t=[]);let r=[];return S.Children.forEach(s,(n,a)=>{if(!S.isValidElement(n))return;let i=[...t,a];if(n.type===S.Fragment){r.push.apply(r,Eje(n.props.children,i));return}n.type!==gs&&xh(!1),!n.props.index||!n.props.children||xh(!1);let l={id:n.props.id||i.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&&(l.children=Eje(n.props.children,i)),r.push(l)}),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 Aje(){return Aje=Object.assign?Object.assign.bind():function(s){for(var t=1;t=0)&&(r[a]=s[a]);return r}function lTt(s){return!!(s.metaKey||s.altKey||s.ctrlKey||s.shiftKey)}function cTt(s,t){return s.button===0&&(!t||t==="_self")&&!lTt(s)}function Mje(s){return s===void 0&&(s=""),new URLSearchParams(typeof s=="string"||Array.isArray(s)||s instanceof URLSearchParams?s:Object.keys(s).reduce((t,r)=>{let n=s[r];return t.concat(Array.isArray(n)?n.map(a=>[r,a]):[[r,n]])},[]))}function dTt(s,t){let r=Mje(s);return t&&t.forEach((n,a)=>{r.has(a)||t.getAll(a).forEach(i=>{r.append(a,i)})}),r}const uTt=["onClick","relative","reloadDocument","replace","state","target","to","preventScrollReset","viewTransition"],hTt="6";try{window.__reactRouterVersion=hTt}catch{}const mTt="startTransition",tOe=jCe[mTt];function fTt(s){let{basename:t,children:r,future:n,window:a}=s,i=S.useRef();i.current==null&&(i.current=g5t({window:a,v5Compat:!0}));let l=i.current,[o,c]=S.useState({action:l.action,location:l.location}),{v7_startTransition:d}=n||{},h=S.useCallback(m=>{d&&tOe?tOe(()=>c(m)):c(m)},[c,d]);return S.useLayoutEffect(()=>l.listen(h),[l,h]),S.useEffect(()=>nTt(n),[n]),S.createElement(iTt,{basename:t,children:r,location:o.location,navigationType:o.action,navigator:l,future:n})}const pTt=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",gTt=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,Xn=S.forwardRef(function(t,r){let{onClick:n,relative:a,reloadDocument:i,replace:l,state:o,target:c,to:d,preventScrollReset:h,viewTransition:m}=t,p=oTt(t,uTt),{basename:x}=S.useContext(LS),y,_=!1;if(typeof d=="string"&&gTt.test(d)&&(y=d,pTt))try{let T=new URL(window.location.href),E=d.startsWith("//")?new URL(T.protocol+d):new URL(d),A=L3e(E.pathname,x);E.origin===T.origin&&A!=null?d=A+E.search+E.hash:_=!0}catch{}let b=U5t(d,{relative:a}),j=xTt(d,{replace:l,state:o,target:c,preventScrollReset:h,relative:a,viewTransition:m});function k(T){n&&n(T),T.defaultPrevented||j(T)}return S.createElement("a",Aje({},p,{href:y||b,onClick:_||i?n:k,ref:r,target:c}))});var sOe;(function(s){s.UseScrollRestoration="useScrollRestoration",s.UseSubmit="useSubmit",s.UseSubmitFetcher="useSubmitFetcher",s.UseFetcher="useFetcher",s.useViewTransitionState="useViewTransitionState"})(sOe||(sOe={}));var rOe;(function(s){s.UseFetcher="useFetcher",s.UseFetchers="useFetchers",s.UseScrollRestoration="useScrollRestoration"})(rOe||(rOe={}));function xTt(s,t){let{target:r,replace:n,state:a,preventScrollReset:i,relative:l,viewTransition:o}=t===void 0?{}:t,c=Fr(),d=Vc(),h=DJe(s,{relative:l});return S.useCallback(m=>{if(cTt(m,r)){m.preventDefault();let p=n!==void 0?n:Nhe(d)===Nhe(h);c(s,{replace:p,state:a,preventScrollReset:i,relative:l,viewTransition:o})}},[d,c,h,n,a,r,s,i,l,o])}function Ed(s){let t=S.useRef(Mje(s)),r=S.useRef(!1),n=Vc(),a=S.useMemo(()=>dTt(n.search,r.current?null:t.current),[n.search]),i=Fr(),l=S.useCallback((o,c)=>{const d=Mje(typeof o=="function"?o(a):o);r.current=!0,i("?"+d,c)},[i,a]);return[a,l]}var yTt=typeof Element<"u",vTt=typeof Map=="function",bTt=typeof Set=="function",_Tt=typeof ArrayBuffer=="function"&&!!ArrayBuffer.isView;function oue(s,t){if(s===t)return!0;if(s&&t&&typeof s=="object"&&typeof t=="object"){if(s.constructor!==t.constructor)return!1;var r,n,a;if(Array.isArray(s)){if(r=s.length,r!=t.length)return!1;for(n=r;n--!==0;)if(!oue(s[n],t[n]))return!1;return!0}var i;if(vTt&&s instanceof Map&&t instanceof Map){if(s.size!==t.size)return!1;for(i=s.entries();!(n=i.next()).done;)if(!t.has(n.value[0]))return!1;for(i=s.entries();!(n=i.next()).done;)if(!oue(n.value[1],t.get(n.value[0])))return!1;return!0}if(bTt&&s instanceof Set&&t instanceof Set){if(s.size!==t.size)return!1;for(i=s.entries();!(n=i.next()).done;)if(!t.has(n.value[0]))return!1;return!0}if(_Tt&&ArrayBuffer.isView(s)&&ArrayBuffer.isView(t)){if(r=s.length,r!=t.length)return!1;for(n=r;n--!==0;)if(s[n]!==t[n])return!1;return!0}if(s.constructor===RegExp)return s.source===t.source&&s.flags===t.flags;if(s.valueOf!==Object.prototype.valueOf&&typeof s.valueOf=="function"&&typeof t.valueOf=="function")return s.valueOf()===t.valueOf();if(s.toString!==Object.prototype.toString&&typeof s.toString=="function"&&typeof t.toString=="function")return s.toString()===t.toString();if(a=Object.keys(s),r=a.length,r!==Object.keys(t).length)return!1;for(n=r;n--!==0;)if(!Object.prototype.hasOwnProperty.call(t,a[n]))return!1;if(yTt&&s instanceof Element)return!1;for(n=r;n--!==0;)if(!((a[n]==="_owner"||a[n]==="__v"||a[n]==="__o")&&s.$$typeof)&&!oue(s[a[n]],t[a[n]]))return!1;return!0}return s!==s&&t!==t}var wTt=function(t,r){try{return oue(t,r)}catch(n){if((n.message||"").match(/stack|recursion/i))return console.warn("react-fast-compare cannot handle circular refs"),!1;throw n}};const jTt=ol(wTt);var NTt=function(s,t,r,n,a,i,l,o){if(!s){var c;if(t===void 0)c=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var d=[r,n,a,i,l,o],h=0;c=new Error(t.replace(/%s/g,function(){return d[h++]})),c.name="Invariant Violation"}throw c.framesToPop=1,c}},kTt=NTt;const nOe=ol(kTt);var STt=function(t,r,n,a){var i=n?n.call(a,t,r):void 0;if(i!==void 0)return!!i;if(t===r)return!0;if(typeof t!="object"||!t||typeof r!="object"||!r)return!1;var l=Object.keys(t),o=Object.keys(r);if(l.length!==o.length)return!1;for(var c=Object.prototype.hasOwnProperty.bind(r),d=0;d(s.BASE="base",s.BODY="body",s.HEAD="head",s.HTML="html",s.LINK="link",s.META="meta",s.NOSCRIPT="noscript",s.SCRIPT="script",s.STYLE="style",s.TITLE="title",s.FRAGMENT="Symbol(react.fragment)",s))(FJe||{}),F1e={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"]}},aOe=Object.values(FJe),F3e={accesskey:"accessKey",charset:"charSet",class:"className",contenteditable:"contentEditable",contextmenu:"contextMenu","http-equiv":"httpEquiv",itemprop:"itemProp",tabindex:"tabIndex"},TTt=Object.entries(F3e).reduce((s,[t,r])=>(s[r]=t,s),{}),m1="data-rh",sP={DEFAULT_TITLE:"defaultTitle",DEFER:"defer",ENCODE_SPECIAL_CHARACTERS:"encodeSpecialCharacters",ON_CHANGE_CLIENT_STATE:"onChangeClientState",TITLE_TEMPLATE:"titleTemplate",PRIORITIZE_SEO_TAGS:"prioritizeSeoTags"},rP=(s,t)=>{for(let r=s.length-1;r>=0;r-=1){const n=s[r];if(Object.prototype.hasOwnProperty.call(n,t))return n[t]}return null},ETt=s=>{let t=rP(s,"title");const r=rP(s,sP.TITLE_TEMPLATE);if(Array.isArray(t)&&(t=t.join("")),r&&t)return r.replace(/%s/g,()=>t);const n=rP(s,sP.DEFAULT_TITLE);return t||n||void 0},ATt=s=>rP(s,sP.ON_CHANGE_CLIENT_STATE)||(()=>{}),B1e=(s,t)=>t.filter(r=>typeof r[s]<"u").map(r=>r[s]).reduce((r,n)=>({...r,...n}),{}),MTt=(s,t)=>t.filter(r=>typeof r.base<"u").map(r=>r.base).reverse().reduce((r,n)=>{if(!r.length){const a=Object.keys(n);for(let i=0;iconsole&&typeof console.warn=="function"&&console.warn(s),wR=(s,t,r)=>{const n={};return r.filter(a=>Array.isArray(a[s])?!0:(typeof a[s]<"u"&&ITt(`Helmet: ${s} should be of type "Array". Instead found type "${typeof a[s]}"`),!1)).map(a=>a[s]).reverse().reduce((a,i)=>{const l={};i.filter(c=>{let d;const h=Object.keys(c);for(let p=0;pa.push(c));const o=Object.keys(l);for(let c=0;c{if(Array.isArray(s)&&s.length){for(let r=0;r({baseTag:MTt(["href"],s),bodyAttributes:B1e("bodyAttributes",s),defer:rP(s,sP.DEFER),encode:rP(s,sP.ENCODE_SPECIAL_CHARACTERS),htmlAttributes:B1e("htmlAttributes",s),linkTags:wR("link",["rel","href"],s),metaTags:wR("meta",["name","charset","http-equiv","property","itemprop"],s),noscriptTags:wR("noscript",["innerHTML"],s),onChangeClientState:ATt(s),scriptTags:wR("script",["src","innerHTML"],s),styleTags:wR("style",["cssText"],s),title:ETt(s),titleAttributes:B1e("titleAttributes",s),prioritizeSeoTags:PTt(s,sP.PRIORITIZE_SEO_TAGS)}),BJe=s=>Array.isArray(s)?s.join(""):s,DTt=(s,t)=>{const r=Object.keys(s);for(let n=0;nArray.isArray(s)?s.reduce((r,n)=>(DTt(n,t)?r.priority.push(n):r.default.push(n),r),{priority:[],default:[]}):{default:s,priority:[]},iOe=(s,t)=>({...s,[t]:void 0}),RTt=["noscript","script","style"],Ije=(s,t=!0)=>t===!1?String(s):String(s).replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'"),zJe=s=>Object.keys(s).reduce((t,r)=>{const n=typeof s[r]<"u"?`${r}="${s[r]}"`:`${r}`;return t?`${t} ${n}`:n},""),OTt=(s,t,r,n)=>{const a=zJe(r),i=BJe(t);return a?`<${s} ${m1}="true" ${a}>${Ije(i,n)}`:`<${s} ${m1}="true">${Ije(i,n)}`},FTt=(s,t,r=!0)=>t.reduce((n,a)=>{const i=a,l=Object.keys(i).filter(d=>!(d==="innerHTML"||d==="cssText")).reduce((d,h)=>{const m=typeof i[h]>"u"?h:`${h}="${Ije(i[h],r)}"`;return d?`${d} ${m}`:m},""),o=i.innerHTML||i.cssText||"",c=RTt.indexOf(s)===-1;return`${n}<${s} ${m1}="true" ${l}${c?"/>":`>${o}`}`},""),$Je=(s,t={})=>Object.keys(s).reduce((r,n)=>{const a=F3e[n];return r[a||n]=s[n],r},t),BTt=(s,t,r)=>{const n={key:t,[m1]:!0},a=$Je(r,n);return[Nt.createElement("title",a,t)]},lue=(s,t)=>t.map((r,n)=>{const a={key:n,[m1]:!0};return Object.keys(r).forEach(i=>{const o=F3e[i]||i;if(o==="innerHTML"||o==="cssText"){const c=r.innerHTML||r.cssText;a.dangerouslySetInnerHTML={__html:c}}else a[o]=r[i]}),Nt.createElement(s,a)}),_y=(s,t,r=!0)=>{switch(s){case"title":return{toComponent:()=>BTt(s,t.title,t.titleAttributes),toString:()=>OTt(s,t.title,t.titleAttributes,r)};case"bodyAttributes":case"htmlAttributes":return{toComponent:()=>$Je(t),toString:()=>zJe(t)};default:return{toComponent:()=>lue(s,t),toString:()=>FTt(s,t,r)}}},zTt=({metaTags:s,linkTags:t,scriptTags:r,encode:n})=>{const a=z1e(s,F1e.meta),i=z1e(t,F1e.link),l=z1e(r,F1e.script);return{priorityMethods:{toComponent:()=>[...lue("meta",a.priority),...lue("link",i.priority),...lue("script",l.priority)],toString:()=>`${_y("meta",a.priority,n)} ${_y("link",i.priority,n)} ${_y("script",l.priority,n)}`},metaTags:a.default,linkTags:i.default,scriptTags:l.default}},$Tt=s=>{const{baseTag:t,bodyAttributes:r,encode:n=!0,htmlAttributes:a,noscriptTags:i,styleTags:l,title:o="",titleAttributes:c,prioritizeSeoTags:d}=s;let{linkTags:h,metaTags:m,scriptTags:p}=s,x={toComponent:()=>{},toString:()=>""};return d&&({priorityMethods:x,linkTags:h,metaTags:m,scriptTags:p}=zTt(s)),{priority:x,base:_y("base",t,n),bodyAttributes:_y("bodyAttributes",r,n),htmlAttributes:_y("htmlAttributes",a,n),link:_y("link",h,n),meta:_y("meta",m,n),noscript:_y("noscript",i,n),script:_y("script",p,n),style:_y("style",l,n),title:_y("title",{title:o,titleAttributes:c},n)}},Pje=$Tt,PU=[],UJe=!!(typeof window<"u"&&window.document&&window.document.createElement),Lje=class{constructor(s,t){ga(this,"instances",[]);ga(this,"canUseDOM",UJe);ga(this,"context");ga(this,"value",{setHelmet:s=>{this.context.helmet=s},helmetInstances:{get:()=>this.canUseDOM?PU:this.instances,add:s=>{(this.canUseDOM?PU:this.instances).push(s)},remove:s=>{const t=(this.canUseDOM?PU:this.instances).indexOf(s);(this.canUseDOM?PU:this.instances).splice(t,1)}}});this.context=s,this.canUseDOM=t||!1,t||(s.helmet=Pje({baseTag:[],bodyAttributes:{},encodeSpecialCharacters:!0,htmlAttributes:{},linkTags:[],metaTags:[],noscriptTags:[],scriptTags:[],styleTags:[],title:"",titleAttributes:{}}))}},UTt={},qJe=Nt.createContext(UTt),oE,VJe=(oE=class extends S.Component{constructor(r){super(r);ga(this,"helmetData");this.helmetData=new Lje(this.props.context||{},oE.canUseDOM)}render(){return Nt.createElement(qJe.Provider,{value:this.helmetData.value},this.props.children)}},ga(oE,"canUseDOM",UJe),oE),r6=(s,t)=>{const r=document.head||document.querySelector("head"),n=r.querySelectorAll(`${s}[${m1}]`),a=[].slice.call(n),i=[];let l;return t&&t.length&&t.forEach(o=>{const c=document.createElement(s);for(const d in o)if(Object.prototype.hasOwnProperty.call(o,d))if(d==="innerHTML")c.innerHTML=o.innerHTML;else if(d==="cssText")c.styleSheet?c.styleSheet.cssText=o.cssText:c.appendChild(document.createTextNode(o.cssText));else{const h=d,m=typeof o[h]>"u"?"":o[h];c.setAttribute(d,m)}c.setAttribute(m1,"true"),a.some((d,h)=>(l=h,c.isEqualNode(d)))?a.splice(l,1):i.push(c)}),a.forEach(o=>{var c;return(c=o.parentNode)==null?void 0:c.removeChild(o)}),i.forEach(o=>r.appendChild(o)),{oldTags:a,newTags:i}},Dje=(s,t)=>{const r=document.getElementsByTagName(s)[0];if(!r)return;const n=r.getAttribute(m1),a=n?n.split(","):[],i=[...a],l=Object.keys(t);for(const o of l){const c=t[o]||"";r.getAttribute(o)!==c&&r.setAttribute(o,c),a.indexOf(o)===-1&&a.push(o);const d=i.indexOf(o);d!==-1&&i.splice(d,1)}for(let o=i.length-1;o>=0;o-=1)r.removeAttribute(i[o]);a.length===i.length?r.removeAttribute(m1):r.getAttribute(m1)!==l.join(",")&&r.setAttribute(m1,l.join(","))},qTt=(s,t)=>{typeof s<"u"&&document.title!==s&&(document.title=BJe(s)),Dje("title",t)},oOe=(s,t)=>{const{baseTag:r,bodyAttributes:n,htmlAttributes:a,linkTags:i,metaTags:l,noscriptTags:o,onChangeClientState:c,scriptTags:d,styleTags:h,title:m,titleAttributes:p}=s;Dje("body",n),Dje("html",a),qTt(m,p);const x={baseTag:r6("base",r),linkTags:r6("link",i),metaTags:r6("meta",l),noscriptTags:r6("noscript",o),scriptTags:r6("script",d),styleTags:r6("style",h)},y={},_={};Object.keys(x).forEach(b=>{const{newTags:j,oldTags:k}=x[b];j.length&&(y[b]=j),k.length&&(_[b]=x[b].oldTags)}),t&&t(),c(s,y,_)},jR=null,VTt=s=>{jR&&cancelAnimationFrame(jR),s.defer?jR=requestAnimationFrame(()=>{oOe(s,()=>{jR=null})}):(oOe(s),jR=null)},HTt=VTt,lOe=class extends S.Component{constructor(){super(...arguments);ga(this,"rendered",!1)}shouldComponentUpdate(t){return!CTt(t,this.props)}componentDidUpdate(){this.emitChange()}componentWillUnmount(){const{helmetInstances:t}=this.props.context;t.remove(this),this.emitChange()}emitChange(){const{helmetInstances:t,setHelmet:r}=this.props.context;let n=null;const a=LTt(t.get().map(i=>{const l={...i.props};return delete l.context,l}));VJe.canUseDOM?HTt(a):Pje&&(n=Pje(a)),r(n)}init(){if(this.rendered)return;this.rendered=!0;const{helmetInstances:t}=this.props.context;t.add(this),this.emitChange()}render(){return this.init(),null}},c2e,el=(c2e=class extends S.Component{shouldComponentUpdate(s){return!jTt(iOe(this.props,"helmetData"),iOe(s,"helmetData"))}mapNestedChildrenToProps(s,t){if(!t)return null;switch(s.type){case"script":case"noscript":return{innerHTML:t};case"style":return{cssText:t};default:throw new Error(`<${s.type} /> elements are self-closing and can not contain children. Refer to our API for more information.`)}}flattenArrayTypeChildren(s,t,r,n){return{...t,[s.type]:[...t[s.type]||[],{...r,...this.mapNestedChildrenToProps(s,n)}]}}mapObjectTypeChildren(s,t,r,n){switch(s.type){case"title":return{...t,[s.type]:n,titleAttributes:{...r}};case"body":return{...t,bodyAttributes:{...r}};case"html":return{...t,htmlAttributes:{...r}};default:return{...t,[s.type]:{...r}}}}mapArrayTypeChildrenToProps(s,t){let r={...t};return Object.keys(s).forEach(n=>{r={...r,[n]:s[n]}}),r}warnOnInvalidChildren(s,t){return nOe(aOe.some(r=>s.type===r),typeof s.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 ${aOe.join(", ")} are allowed. Helmet does not support rendering <${s.type}> elements. Refer to our API for more information.`),nOe(!t||typeof t=="string"||Array.isArray(t)&&!t.some(r=>typeof r!="string"),`Helmet expects a string as a child of <${s.type}>. Did you forget to wrap your children in braces? ( <${s.type}>{\`\`} ) Refer to our API for more information.`),!0}mapChildrenToProps(s,t){let r={};return Nt.Children.forEach(s,n=>{if(!n||!n.props)return;const{children:a,...i}=n.props,l=Object.keys(i).reduce((c,d)=>(c[TTt[d]||d]=i[d],c),{});let{type:o}=n;switch(typeof o=="symbol"?o=o.toString():this.warnOnInvalidChildren(n,a),o){case"Symbol(react.fragment)":t=this.mapChildrenToProps(a,t);break;case"link":case"meta":case"noscript":case"script":case"style":r=this.flattenArrayTypeChildren(n,r,l,a);break;default:t=this.mapObjectTypeChildren(n,t,l,a);break}}),this.mapArrayTypeChildrenToProps(r,t)}render(){const{children:s,...t}=this.props;let r={...t},{helmetData:n}=t;if(s&&(r=this.mapChildrenToProps(s,r)),n&&!(n instanceof Lje)){const a=n;n=new Lje(a.context,!0),delete r.helmetData}return n?Nt.createElement(lOe,{...r,context:n.value}):Nt.createElement(qJe.Consumer,null,a=>Nt.createElement(lOe,{...r,context:a}))}},ga(c2e,"defaultProps",{defer:!0,encodeSpecialCharacters:!0,prioritizeSeoTags:!1}),c2e);const GTt=s=>{let t;return s?t=s:typeof fetch>"u"?t=(...r)=>Ti(async()=>{const{default:n}=await Promise.resolve().then(()=>d8);return{default:n}},void 0).then(({default:n})=>n(...r)):t=fetch,(...r)=>t(...r)};class B3e extends Error{constructor(t,r="FunctionsError",n){super(t),this.name=r,this.context=n}}class WTt extends B3e{constructor(t){super("Failed to send a request to the Edge Function","FunctionsFetchError",t)}}class KTt extends B3e{constructor(t){super("Relay Error invoking the Edge Function","FunctionsRelayError",t)}}class YTt extends B3e{constructor(t){super("Edge Function returned a non-2xx status code","FunctionsHttpError",t)}}var Rje;(function(s){s.Any="any",s.ApNortheast1="ap-northeast-1",s.ApNortheast2="ap-northeast-2",s.ApSouth1="ap-south-1",s.ApSoutheast1="ap-southeast-1",s.ApSoutheast2="ap-southeast-2",s.CaCentral1="ca-central-1",s.EuCentral1="eu-central-1",s.EuWest1="eu-west-1",s.EuWest2="eu-west-2",s.EuWest3="eu-west-3",s.SaEast1="sa-east-1",s.UsEast1="us-east-1",s.UsWest1="us-west-1",s.UsWest2="us-west-2"})(Rje||(Rje={}));var ZTt=function(s,t,r,n){function a(i){return i instanceof r?i:new r(function(l){l(i)})}return new(r||(r=Promise))(function(i,l){function o(h){try{d(n.next(h))}catch(m){l(m)}}function c(h){try{d(n.throw(h))}catch(m){l(m)}}function d(h){h.done?i(h.value):a(h.value).then(o,c)}d((n=n.apply(s,t||[])).next())})};class XTt{constructor(t,{headers:r={},customFetch:n,region:a=Rje.Any}={}){this.url=t,this.headers=r,this.region=a,this.fetch=GTt(n)}setAuth(t){this.headers.Authorization=`Bearer ${t}`}invoke(t,r={}){var n;return ZTt(this,void 0,void 0,function*(){try{const{headers:a,method:i,body:l}=r;let o={},{region:c}=r;c||(c=this.region),c&&c!=="any"&&(o["x-region"]=c);let d;l&&(a&&!Object.prototype.hasOwnProperty.call(a,"Content-Type")||!a)&&(typeof Blob<"u"&&l instanceof Blob||l instanceof ArrayBuffer?(o["Content-Type"]="application/octet-stream",d=l):typeof l=="string"?(o["Content-Type"]="text/plain",d=l):typeof FormData<"u"&&l instanceof FormData?d=l:(o["Content-Type"]="application/json",d=JSON.stringify(l)));const h=yield this.fetch(`${this.url}/${t}`,{method:i||"POST",headers:Object.assign(Object.assign(Object.assign({},o),this.headers),a),body:d}).catch(y=>{throw new WTt(y)}),m=h.headers.get("x-relay-error");if(m&&m==="true")throw new KTt(h);if(!h.ok)throw new YTt(h);let p=((n=h.headers.get("Content-Type"))!==null&&n!==void 0?n:"text/plain").split(";")[0].trim(),x;return p==="application/json"?x=yield h.json():p==="application/octet-stream"?x=yield h.blob():p==="text/event-stream"?x=h:p==="multipart/form-data"?x=yield h.formData():x=yield h.text(),{data:x,error:null}}catch(a){return{data:null,error:a}}})}}var Qg={},z3e={},Qpe={},UB={},Jpe={},ege={},QTt=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")},WP=QTt();const JTt=WP.fetch,HJe=WP.fetch.bind(WP),GJe=WP.Headers,eEt=WP.Request,tEt=WP.Response,d8=Object.freeze(Object.defineProperty({__proto__:null,Headers:GJe,Request:eEt,Response:tEt,default:HJe,fetch:JTt},Symbol.toStringTag,{value:"Module"})),sEt=Ajt(d8);var tge={};Object.defineProperty(tge,"__esModule",{value:!0});let rEt=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}};tge.default=rEt;var WJe=uh&&uh.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(ege,"__esModule",{value:!0});const nEt=WJe(sEt),aEt=WJe(tge);let iEt=class{constructor(t){this.shouldThrowOnError=!1,this.method=t.method,this.url=t.url,this.headers=t.headers,this.schema=t.schema,this.body=t.body,this.shouldThrowOnError=t.shouldThrowOnError,this.signal=t.signal,this.isMaybeSingle=t.isMaybeSingle,t.fetch?this.fetch=t.fetch:typeof fetch>"u"?this.fetch=nEt.default:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,r){return this.headers=Object.assign({},this.headers),this.headers[t]=r,this}then(t,r){this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers["Accept-Profile"]=this.schema:this.headers["Content-Profile"]=this.schema),this.method!=="GET"&&this.method!=="HEAD"&&(this.headers["Content-Type"]="application/json");const n=this.fetch;let a=n(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async i=>{var l,o,c;let d=null,h=null,m=null,p=i.status,x=i.statusText;if(i.ok){if(this.method!=="HEAD"){const j=await i.text();j===""||(this.headers.Accept==="text/csv"||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?h=j:h=JSON.parse(j))}const _=(l=this.headers.Prefer)===null||l===void 0?void 0:l.match(/count=(exact|planned|estimated)/),b=(o=i.headers.get("content-range"))===null||o===void 0?void 0:o.split("/");_&&b&&b.length>1&&(m=parseInt(b[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(h)&&(h.length>1?(d={code:"PGRST116",details:`Results contain ${h.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},h=null,m=null,p=406,x="Not Acceptable"):h.length===1?h=h[0]:h=null)}else{const _=await i.text();try{d=JSON.parse(_),Array.isArray(d)&&i.status===404&&(h=[],d=null,p=200,x="OK")}catch{i.status===404&&_===""?(p=204,x="No Content"):d={message:_}}if(d&&this.isMaybeSingle&&(!((c=d==null?void 0:d.details)===null||c===void 0)&&c.includes("0 rows"))&&(d=null,p=200,x="OK"),d&&this.shouldThrowOnError)throw new aEt.default(d)}return{error:d,data:h,count:m,status:p,statusText:x}});return this.shouldThrowOnError||(a=a.catch(i=>{var l,o,c;return{error:{message:`${(l=i==null?void 0:i.name)!==null&&l!==void 0?l:"FetchError"}: ${i==null?void 0:i.message}`,details:`${(o=i==null?void 0:i.stack)!==null&&o!==void 0?o:""}`,hint:"",code:`${(c=i==null?void 0:i.code)!==null&&c!==void 0?c:""}`},data:null,count:null,status:0,statusText:""}})),a.then(t,r)}returns(){return this}overrideTypes(){return this}};ege.default=iEt;var oEt=uh&&uh.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(Jpe,"__esModule",{value:!0});const lEt=oEt(ege);let cEt=class extends lEt.default{select(t){let r=!1;const n=(t??"*").split("").map(a=>/\s/.test(a)&&!r?"":(a==='"'&&(r=!r),a)).join("");return this.url.searchParams.set("select",n),this.headers.Prefer&&(this.headers.Prefer+=","),this.headers.Prefer+="return=representation",this}order(t,{ascending:r=!0,nullsFirst:n,foreignTable:a,referencedTable:i=a}={}){const l=i?`${i}.order`:"order",o=this.url.searchParams.get(l);return this.url.searchParams.set(l,`${o?`${o},`:""}${t}.${r?"asc":"desc"}${n===void 0?"":n?".nullsfirst":".nullslast"}`),this}limit(t,{foreignTable:r,referencedTable:n=r}={}){const a=typeof n>"u"?"limit":`${n}.limit`;return this.url.searchParams.set(a,`${t}`),this}range(t,r,{foreignTable:n,referencedTable:a=n}={}){const i=typeof a>"u"?"offset":`${a}.offset`,l=typeof a>"u"?"limit":`${a}.limit`;return this.url.searchParams.set(i,`${t}`),this.url.searchParams.set(l,`${r-t+1}`),this}abortSignal(t){return this.signal=t,this}single(){return this.headers.Accept="application/vnd.pgrst.object+json",this}maybeSingle(){return this.method==="GET"?this.headers.Accept="application/json":this.headers.Accept="application/vnd.pgrst.object+json",this.isMaybeSingle=!0,this}csv(){return this.headers.Accept="text/csv",this}geojson(){return this.headers.Accept="application/geo+json",this}explain({analyze:t=!1,verbose:r=!1,settings:n=!1,buffers:a=!1,wal:i=!1,format:l="text"}={}){var o;const c=[t?"analyze":null,r?"verbose":null,n?"settings":null,a?"buffers":null,i?"wal":null].filter(Boolean).join("|"),d=(o=this.headers.Accept)!==null&&o!==void 0?o:"application/json";return this.headers.Accept=`application/vnd.pgrst.plan+${l}; for="${d}"; options=${c};`,l==="json"?this:this}rollback(){var t;return((t=this.headers.Prefer)!==null&&t!==void 0?t:"").trim().length>0?this.headers.Prefer+=",tx=rollback":this.headers.Prefer="tx=rollback",this}returns(){return this}};Jpe.default=cEt;var dEt=uh&&uh.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(UB,"__esModule",{value:!0});const uEt=dEt(Jpe);let hEt=class extends uEt.default{eq(t,r){return this.url.searchParams.append(t,`eq.${r}`),this}neq(t,r){return this.url.searchParams.append(t,`neq.${r}`),this}gt(t,r){return this.url.searchParams.append(t,`gt.${r}`),this}gte(t,r){return this.url.searchParams.append(t,`gte.${r}`),this}lt(t,r){return this.url.searchParams.append(t,`lt.${r}`),this}lte(t,r){return this.url.searchParams.append(t,`lte.${r}`),this}like(t,r){return this.url.searchParams.append(t,`like.${r}`),this}likeAllOf(t,r){return this.url.searchParams.append(t,`like(all).{${r.join(",")}}`),this}likeAnyOf(t,r){return this.url.searchParams.append(t,`like(any).{${r.join(",")}}`),this}ilike(t,r){return this.url.searchParams.append(t,`ilike.${r}`),this}ilikeAllOf(t,r){return this.url.searchParams.append(t,`ilike(all).{${r.join(",")}}`),this}ilikeAnyOf(t,r){return this.url.searchParams.append(t,`ilike(any).{${r.join(",")}}`),this}is(t,r){return this.url.searchParams.append(t,`is.${r}`),this}in(t,r){const n=Array.from(new Set(r)).map(a=>typeof a=="string"&&new RegExp("[,()]").test(a)?`"${a}"`:`${a}`).join(",");return this.url.searchParams.append(t,`in.(${n})`),this}contains(t,r){return typeof r=="string"?this.url.searchParams.append(t,`cs.${r}`):Array.isArray(r)?this.url.searchParams.append(t,`cs.{${r.join(",")}}`):this.url.searchParams.append(t,`cs.${JSON.stringify(r)}`),this}containedBy(t,r){return typeof r=="string"?this.url.searchParams.append(t,`cd.${r}`):Array.isArray(r)?this.url.searchParams.append(t,`cd.{${r.join(",")}}`):this.url.searchParams.append(t,`cd.${JSON.stringify(r)}`),this}rangeGt(t,r){return this.url.searchParams.append(t,`sr.${r}`),this}rangeGte(t,r){return this.url.searchParams.append(t,`nxl.${r}`),this}rangeLt(t,r){return this.url.searchParams.append(t,`sl.${r}`),this}rangeLte(t,r){return this.url.searchParams.append(t,`nxr.${r}`),this}rangeAdjacent(t,r){return this.url.searchParams.append(t,`adj.${r}`),this}overlaps(t,r){return typeof r=="string"?this.url.searchParams.append(t,`ov.${r}`):this.url.searchParams.append(t,`ov.{${r.join(",")}}`),this}textSearch(t,r,{config:n,type:a}={}){let i="";a==="plain"?i="pl":a==="phrase"?i="ph":a==="websearch"&&(i="w");const l=n===void 0?"":`(${n})`;return this.url.searchParams.append(t,`${i}fts${l}.${r}`),this}match(t){return Object.entries(t).forEach(([r,n])=>{this.url.searchParams.append(r,`eq.${n}`)}),this}not(t,r,n){return this.url.searchParams.append(t,`not.${r}.${n}`),this}or(t,{foreignTable:r,referencedTable:n=r}={}){const a=n?`${n}.or`:"or";return this.url.searchParams.append(a,`(${t})`),this}filter(t,r,n){return this.url.searchParams.append(t,`${r}.${n}`),this}};UB.default=hEt;var mEt=uh&&uh.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(Qpe,"__esModule",{value:!0});const NR=mEt(UB);let fEt=class{constructor(t,{headers:r={},schema:n,fetch:a}){this.url=t,this.headers=r,this.schema=n,this.fetch=a}select(t,{head:r=!1,count:n}={}){const a=r?"HEAD":"GET";let i=!1;const l=(t??"*").split("").map(o=>/\s/.test(o)&&!i?"":(o==='"'&&(i=!i),o)).join("");return this.url.searchParams.set("select",l),n&&(this.headers.Prefer=`count=${n}`),new NR.default({method:a,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}insert(t,{count:r,defaultToNull:n=!0}={}){const a="POST",i=[];if(this.headers.Prefer&&i.push(this.headers.Prefer),r&&i.push(`count=${r}`),n||i.push("missing=default"),this.headers.Prefer=i.join(","),Array.isArray(t)){const l=t.reduce((o,c)=>o.concat(Object.keys(c)),[]);if(l.length>0){const o=[...new Set(l)].map(c=>`"${c}"`);this.url.searchParams.set("columns",o.join(","))}}return new NR.default({method:a,url:this.url,headers:this.headers,schema:this.schema,body:t,fetch:this.fetch,allowEmpty:!1})}upsert(t,{onConflict:r,ignoreDuplicates:n=!1,count:a,defaultToNull:i=!0}={}){const l="POST",o=[`resolution=${n?"ignore":"merge"}-duplicates`];if(r!==void 0&&this.url.searchParams.set("on_conflict",r),this.headers.Prefer&&o.push(this.headers.Prefer),a&&o.push(`count=${a}`),i||o.push("missing=default"),this.headers.Prefer=o.join(","),Array.isArray(t)){const c=t.reduce((d,h)=>d.concat(Object.keys(h)),[]);if(c.length>0){const d=[...new Set(c)].map(h=>`"${h}"`);this.url.searchParams.set("columns",d.join(","))}}return new NR.default({method:l,url:this.url,headers:this.headers,schema:this.schema,body:t,fetch:this.fetch,allowEmpty:!1})}update(t,{count:r}={}){const n="PATCH",a=[];return this.headers.Prefer&&a.push(this.headers.Prefer),r&&a.push(`count=${r}`),this.headers.Prefer=a.join(","),new NR.default({method:n,url:this.url,headers:this.headers,schema:this.schema,body:t,fetch:this.fetch,allowEmpty:!1})}delete({count:t}={}){const r="DELETE",n=[];return t&&n.push(`count=${t}`),this.headers.Prefer&&n.unshift(this.headers.Prefer),this.headers.Prefer=n.join(","),new NR.default({method:r,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}};Qpe.default=fEt;var sge={},rge={};Object.defineProperty(rge,"__esModule",{value:!0});rge.version=void 0;rge.version="0.0.0-automated";Object.defineProperty(sge,"__esModule",{value:!0});sge.DEFAULT_HEADERS=void 0;const pEt=rge;sge.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${pEt.version}`};var KJe=uh&&uh.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(z3e,"__esModule",{value:!0});const gEt=KJe(Qpe),xEt=KJe(UB),yEt=sge;let vEt=class YJe{constructor(t,{headers:r={},schema:n,fetch:a}={}){this.url=t,this.headers=Object.assign(Object.assign({},yEt.DEFAULT_HEADERS),r),this.schemaName=n,this.fetch=a}from(t){const r=new URL(`${this.url}/${t}`);return new gEt.default(r,{headers:Object.assign({},this.headers),schema:this.schemaName,fetch:this.fetch})}schema(t){return new YJe(this.url,{headers:this.headers,schema:t,fetch:this.fetch})}rpc(t,r={},{head:n=!1,get:a=!1,count:i}={}){let l;const o=new URL(`${this.url}/rpc/${t}`);let c;n||a?(l=n?"HEAD":"GET",Object.entries(r).filter(([h,m])=>m!==void 0).map(([h,m])=>[h,Array.isArray(m)?`{${m.join(",")}}`:`${m}`]).forEach(([h,m])=>{o.searchParams.append(h,m)})):(l="POST",c=r);const d=Object.assign({},this.headers);return i&&(d.Prefer=`count=${i}`),new xEt.default({method:l,url:o,headers:d,schema:this.schemaName,body:c,fetch:this.fetch,allowEmpty:!1})}};z3e.default=vEt;var u8=uh&&uh.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(Qg,"__esModule",{value:!0});Qg.PostgrestError=Qg.PostgrestBuilder=Qg.PostgrestTransformBuilder=Qg.PostgrestFilterBuilder=Qg.PostgrestQueryBuilder=Qg.PostgrestClient=void 0;const ZJe=u8(z3e);Qg.PostgrestClient=ZJe.default;const XJe=u8(Qpe);Qg.PostgrestQueryBuilder=XJe.default;const QJe=u8(UB);Qg.PostgrestFilterBuilder=QJe.default;const JJe=u8(Jpe);Qg.PostgrestTransformBuilder=JJe.default;const eet=u8(ege);Qg.PostgrestBuilder=eet.default;const tet=u8(tge);Qg.PostgrestError=tet.default;var bEt=Qg.default={PostgrestClient:ZJe.default,PostgrestQueryBuilder:XJe.default,PostgrestFilterBuilder:QJe.default,PostgrestTransformBuilder:JJe.default,PostgrestBuilder:eet.default,PostgrestError:tet.default};const{PostgrestClient:_Et,PostgrestQueryBuilder:vZs,PostgrestFilterBuilder:bZs,PostgrestTransformBuilder:_Zs,PostgrestBuilder:wZs,PostgrestError:jZs}=bEt;let Oje;typeof window>"u"?Oje=require("ws"):Oje=window.WebSocket;const wEt=Oje,jEt="2.11.10",NEt={"X-Client-Info":`realtime-js/${jEt}`},kEt="1.0.0",set=1e4,SEt=1e3;var nP;(function(s){s[s.connecting=0]="connecting",s[s.open=1]="open",s[s.closing=2]="closing",s[s.closed=3]="closed"})(nP||(nP={}));var rg;(function(s){s.closed="closed",s.errored="errored",s.joined="joined",s.joining="joining",s.leaving="leaving"})(rg||(rg={}));var t1;(function(s){s.close="phx_close",s.error="phx_error",s.join="phx_join",s.reply="phx_reply",s.leave="phx_leave",s.access_token="access_token"})(t1||(t1={}));var Fje;(function(s){s.websocket="websocket"})(Fje||(Fje={}));var TT;(function(s){s.Connecting="connecting",s.Open="open",s.Closing="closing",s.Closed="closed"})(TT||(TT={}));class CEt{constructor(){this.HEADER_LENGTH=1}decode(t,r){return t.constructor===ArrayBuffer?r(this._binaryDecode(t)):r(typeof t=="string"?JSON.parse(t):{})}_binaryDecode(t){const r=new DataView(t),n=new TextDecoder;return this._decodeBroadcast(t,r,n)}_decodeBroadcast(t,r,n){const a=r.getUint8(1),i=r.getUint8(2);let l=this.HEADER_LENGTH+2;const o=n.decode(t.slice(l,l+a));l=l+a;const c=n.decode(t.slice(l,l+i));l=l+i;const d=JSON.parse(n.decode(t.slice(l,t.byteLength)));return{ref:null,topic:o,event:c,payload:d}}}class ret{constructor(t,r){this.callback=t,this.timerCalc=r,this.timer=void 0,this.tries=0,this.callback=t,this.timerCalc=r}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}}var Qc;(function(s){s.abstime="abstime",s.bool="bool",s.date="date",s.daterange="daterange",s.float4="float4",s.float8="float8",s.int2="int2",s.int4="int4",s.int4range="int4range",s.int8="int8",s.int8range="int8range",s.json="json",s.jsonb="jsonb",s.money="money",s.numeric="numeric",s.oid="oid",s.reltime="reltime",s.text="text",s.time="time",s.timestamp="timestamp",s.timestamptz="timestamptz",s.timetz="timetz",s.tsrange="tsrange",s.tstzrange="tstzrange"})(Qc||(Qc={}));const cOe=(s,t,r={})=>{var n;const a=(n=r.skipTypes)!==null&&n!==void 0?n:[];return Object.keys(t).reduce((i,l)=>(i[l]=TEt(l,s,t,a),i),{})},TEt=(s,t,r,n)=>{const a=t.find(o=>o.name===s),i=a==null?void 0:a.type,l=r[s];return i&&!n.includes(i)?net(i,l):Bje(l)},net=(s,t)=>{if(s.charAt(0)==="_"){const r=s.slice(1,s.length);return IEt(t,r)}switch(s){case Qc.bool:return EEt(t);case Qc.float4:case Qc.float8:case Qc.int2:case Qc.int4:case Qc.int8:case Qc.numeric:case Qc.oid:return AEt(t);case Qc.json:case Qc.jsonb:return MEt(t);case Qc.timestamp:return PEt(t);case Qc.abstime:case Qc.date:case Qc.daterange:case Qc.int4range:case Qc.int8range:case Qc.money:case Qc.reltime:case Qc.text:case Qc.time:case Qc.timestamptz:case Qc.timetz:case Qc.tsrange:case Qc.tstzrange:return Bje(t);default:return Bje(t)}},Bje=s=>s,EEt=s=>{switch(s){case"t":return!0;case"f":return!1;default:return s}},AEt=s=>{if(typeof s=="string"){const t=parseFloat(s);if(!Number.isNaN(t))return t}return s},MEt=s=>{if(typeof s=="string")try{return JSON.parse(s)}catch(t){return console.log(`JSON parse error: ${t}`),s}return s},IEt=(s,t)=>{if(typeof s!="string")return s;const r=s.length-1,n=s[r];if(s[0]==="{"&&n==="}"){let i;const l=s.slice(1,r);try{i=JSON.parse("["+l+"]")}catch{i=l?l.split(","):[]}return i.map(o=>net(t,o))}return s},PEt=s=>typeof s=="string"?s.replace(" ","T"):s,aet=s=>{let t=s;return t=t.replace(/^ws/i,"http"),t=t.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),t.replace(/\/+$/,"")};class $1e{constructor(t,r,n={},a=set){this.channel=t,this.event=r,this.payload=n,this.timeout=a,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null}resend(t){this.timeout=t,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(t){this.payload=Object.assign(Object.assign({},this.payload),t)}receive(t,r){var n;return this._hasReceived(t)&&r((n=this.receivedResp)===null||n===void 0?void 0:n.response),this.recHooks.push({status:t,callback:r}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);const t=r=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=r,this._matchReceive(r)};this.channel._on(this.refEvent,{},t),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(t,r){this.refEvent&&this.channel._trigger(this.refEvent,{status:t,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:t,response:r}){this.recHooks.filter(n=>n.status===t).forEach(n=>n.callback(r))}_hasReceived(t){return this.receivedResp&&this.receivedResp.status===t}}var dOe;(function(s){s.SYNC="sync",s.JOIN="join",s.LEAVE="leave"})(dOe||(dOe={}));class VF{constructor(t,r){this.channel=t,this.state={},this.pendingDiffs=[],this.joinRef=null,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};const n=(r==null?void 0:r.events)||{state:"presence_state",diff:"presence_diff"};this.channel._on(n.state,{},a=>{const{onJoin:i,onLeave:l,onSync:o}=this.caller;this.joinRef=this.channel._joinRef(),this.state=VF.syncState(this.state,a,i,l),this.pendingDiffs.forEach(c=>{this.state=VF.syncDiff(this.state,c,i,l)}),this.pendingDiffs=[],o()}),this.channel._on(n.diff,{},a=>{const{onJoin:i,onLeave:l,onSync:o}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(a):(this.state=VF.syncDiff(this.state,a,i,l),o())}),this.onJoin((a,i,l)=>{this.channel._trigger("presence",{event:"join",key:a,currentPresences:i,newPresences:l})}),this.onLeave((a,i,l)=>{this.channel._trigger("presence",{event:"leave",key:a,currentPresences:i,leftPresences:l})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(t,r,n,a){const i=this.cloneDeep(t),l=this.transformState(r),o={},c={};return this.map(i,(d,h)=>{l[d]||(c[d]=h)}),this.map(l,(d,h)=>{const m=i[d];if(m){const p=h.map(b=>b.presence_ref),x=m.map(b=>b.presence_ref),y=h.filter(b=>x.indexOf(b.presence_ref)<0),_=m.filter(b=>p.indexOf(b.presence_ref)<0);y.length>0&&(o[d]=y),_.length>0&&(c[d]=_)}else o[d]=h}),this.syncDiff(i,{joins:o,leaves:c},n,a)}static syncDiff(t,r,n,a){const{joins:i,leaves:l}={joins:this.transformState(r.joins),leaves:this.transformState(r.leaves)};return n||(n=()=>{}),a||(a=()=>{}),this.map(i,(o,c)=>{var d;const h=(d=t[o])!==null&&d!==void 0?d:[];if(t[o]=this.cloneDeep(c),h.length>0){const m=t[o].map(x=>x.presence_ref),p=h.filter(x=>m.indexOf(x.presence_ref)<0);t[o].unshift(...p)}n(o,h,c)}),this.map(l,(o,c)=>{let d=t[o];if(!d)return;const h=c.map(m=>m.presence_ref);d=d.filter(m=>h.indexOf(m.presence_ref)<0),t[o]=d,a(o,d,c),d.length===0&&delete t[o]}),t}static map(t,r){return Object.getOwnPropertyNames(t).map(n=>r(n,t[n]))}static transformState(t){return t=this.cloneDeep(t),Object.getOwnPropertyNames(t).reduce((r,n)=>{const a=t[n];return"metas"in a?r[n]=a.metas.map(i=>(i.presence_ref=i.phx_ref,delete i.phx_ref,delete i.phx_ref_prev,i)):r[n]=a,r},{})}static cloneDeep(t){return JSON.parse(JSON.stringify(t))}onJoin(t){this.caller.onJoin=t}onLeave(t){this.caller.onLeave=t}onSync(t){this.caller.onSync=t}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}}var uOe;(function(s){s.ALL="*",s.INSERT="INSERT",s.UPDATE="UPDATE",s.DELETE="DELETE"})(uOe||(uOe={}));var hOe;(function(s){s.BROADCAST="broadcast",s.PRESENCE="presence",s.POSTGRES_CHANGES="postgres_changes",s.SYSTEM="system"})(hOe||(hOe={}));var m2;(function(s){s.SUBSCRIBED="SUBSCRIBED",s.TIMED_OUT="TIMED_OUT",s.CLOSED="CLOSED",s.CHANNEL_ERROR="CHANNEL_ERROR"})(m2||(m2={}));class $3e{constructor(t,r={config:{}},n){this.topic=t,this.params=r,this.socket=n,this.bindings={},this.state=rg.closed,this.joinedOnce=!1,this.pushBuffer=[],this.subTopic=t.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:""},private:!1},r.config),this.timeout=this.socket.timeout,this.joinPush=new $1e(this,t1.join,this.params,this.timeout),this.rejoinTimer=new ret(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=rg.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(a=>a.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=rg.closed,this.socket._remove(this)}),this._onError(a=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,a),this.state=rg.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=rg.errored,this.rejoinTimer.scheduleTimeout())}),this._on(t1.reply,{},(a,i)=>{this._trigger(this._replyEventName(i),a)}),this.presence=new VF(this),this.broadcastEndpointURL=aet(this.socket.endPoint)+"/api/broadcast",this.private=this.params.config.private||!1}subscribe(t,r=this.timeout){var n,a;if(this.socket.isConnected()||this.socket.connect(),this.joinedOnce)throw"tried to subscribe multiple times. 'subscribe' can only be called a single time per channel instance";{const{config:{broadcast:i,presence:l,private:o}}=this.params;this._onError(h=>t==null?void 0:t(m2.CHANNEL_ERROR,h)),this._onClose(()=>t==null?void 0:t(m2.CLOSED));const c={},d={broadcast:i,presence:l,postgres_changes:(a=(n=this.bindings.postgres_changes)===null||n===void 0?void 0:n.map(h=>h.filter))!==null&&a!==void 0?a:[],private:o};this.socket.accessTokenValue&&(c.access_token=this.socket.accessTokenValue),this.updateJoinPayload(Object.assign({config:d},c)),this.joinedOnce=!0,this._rejoin(r),this.joinPush.receive("ok",async({postgres_changes:h})=>{var m;if(this.socket.setAuth(),h===void 0){t==null||t(m2.SUBSCRIBED);return}else{const p=this.bindings.postgres_changes,x=(m=p==null?void 0:p.length)!==null&&m!==void 0?m:0,y=[];for(let _=0;_{this.state=rg.errored,t==null||t(m2.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(h).join(", ")||"error")))}).receive("timeout",()=>{t==null||t(m2.TIMED_OUT)})}return this}presenceState(){return this.presence.state}async track(t,r={}){return await this.send({type:"presence",event:"track",payload:t},r.timeout||this.timeout)}async untrack(t={}){return await this.send({type:"presence",event:"untrack"},t)}on(t,r,n){return this._on(t,r,n)}async send(t,r={}){var n,a;if(!this._canPush()&&t.type==="broadcast"){const{event:i,payload:l}=t,c={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:i,payload:l,private:this.private}]})};try{const d=await this._fetchWithTimeout(this.broadcastEndpointURL,c,(n=r.timeout)!==null&&n!==void 0?n:this.timeout);return await((a=d.body)===null||a===void 0?void 0:a.cancel()),d.ok?"ok":"error"}catch(d){return d.name==="AbortError"?"timed out":"error"}}else return new Promise(i=>{var l,o,c;const d=this._push(t.type,t,r.timeout||this.timeout);t.type==="broadcast"&&!(!((c=(o=(l=this.params)===null||l===void 0?void 0:l.config)===null||o===void 0?void 0:o.broadcast)===null||c===void 0)&&c.ack)&&i("ok"),d.receive("ok",()=>i("ok")),d.receive("error",()=>i("error")),d.receive("timeout",()=>i("timed out"))})}updateJoinPayload(t){this.joinPush.updatePayload(t)}unsubscribe(t=this.timeout){this.state=rg.leaving;const r=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(t1.close,"leave",this._joinRef())};return this.joinPush.destroy(),new Promise(n=>{const a=new $1e(this,t1.leave,{},t);a.receive("ok",()=>{r(),n("ok")}).receive("timeout",()=>{r(),n("timed out")}).receive("error",()=>{n("error")}),a.send(),this._canPush()||a.trigger("ok",{})})}teardown(){this.pushBuffer.forEach(t=>t.destroy()),this.rejoinTimer&&clearTimeout(this.rejoinTimer.timer),this.joinPush.destroy()}async _fetchWithTimeout(t,r,n){const a=new AbortController,i=setTimeout(()=>a.abort(),n),l=await this.socket.fetch(t,Object.assign(Object.assign({},r),{signal:a.signal}));return clearTimeout(i),l}_push(t,r,n=this.timeout){if(!this.joinedOnce)throw`tried to push '${t}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let a=new $1e(this,t,r,n);return this._canPush()?a.send():(a.startTimeout(),this.pushBuffer.push(a)),a}_onMessage(t,r,n){return r}_isMember(t){return this.topic===t}_joinRef(){return this.joinPush.ref}_trigger(t,r,n){var a,i;const l=t.toLocaleLowerCase(),{close:o,error:c,leave:d,join:h}=t1;if(n&&[o,c,d,h].indexOf(l)>=0&&n!==this._joinRef())return;let p=this._onMessage(l,r,n);if(r&&!p)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(l)?(a=this.bindings.postgres_changes)===null||a===void 0||a.filter(x=>{var y,_,b;return((y=x.filter)===null||y===void 0?void 0:y.event)==="*"||((b=(_=x.filter)===null||_===void 0?void 0:_.event)===null||b===void 0?void 0:b.toLocaleLowerCase())===l}).map(x=>x.callback(p,n)):(i=this.bindings[l])===null||i===void 0||i.filter(x=>{var y,_,b,j,k,T;if(["broadcast","presence","postgres_changes"].includes(l))if("id"in x){const E=x.id,A=(y=x.filter)===null||y===void 0?void 0:y.event;return E&&((_=r.ids)===null||_===void 0?void 0:_.includes(E))&&(A==="*"||(A==null?void 0:A.toLocaleLowerCase())===((b=r.data)===null||b===void 0?void 0:b.type.toLocaleLowerCase()))}else{const E=(k=(j=x==null?void 0:x.filter)===null||j===void 0?void 0:j.event)===null||k===void 0?void 0:k.toLocaleLowerCase();return E==="*"||E===((T=r==null?void 0:r.event)===null||T===void 0?void 0:T.toLocaleLowerCase())}else return x.type.toLocaleLowerCase()===l}).map(x=>{if(typeof p=="object"&&"ids"in p){const y=p.data,{schema:_,table:b,commit_timestamp:j,type:k,errors:T}=y;p=Object.assign(Object.assign({},{schema:_,table:b,commit_timestamp:j,eventType:k,new:{},old:{},errors:T}),this._getPayloadRecords(y))}x.callback(p,n)})}_isClosed(){return this.state===rg.closed}_isJoined(){return this.state===rg.joined}_isJoining(){return this.state===rg.joining}_isLeaving(){return this.state===rg.leaving}_replyEventName(t){return`chan_reply_${t}`}_on(t,r,n){const a=t.toLocaleLowerCase(),i={type:a,filter:r,callback:n};return this.bindings[a]?this.bindings[a].push(i):this.bindings[a]=[i],this}_off(t,r){const n=t.toLocaleLowerCase();return this.bindings[n]=this.bindings[n].filter(a=>{var i;return!(((i=a.type)===null||i===void 0?void 0:i.toLocaleLowerCase())===n&&$3e.isEqual(a.filter,r))}),this}static isEqual(t,r){if(Object.keys(t).length!==Object.keys(r).length)return!1;for(const n in t)if(t[n]!==r[n])return!1;return!0}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(t){this._on(t1.close,{},t)}_onError(t){this._on(t1.error,{},r=>t(r))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(t=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=rg.joining,this.joinPush.resend(t))}_getPayloadRecords(t){const r={new:{},old:{}};return(t.type==="INSERT"||t.type==="UPDATE")&&(r.new=cOe(t.columns,t.record)),(t.type==="UPDATE"||t.type==="DELETE")&&(r.old=cOe(t.columns,t.old_record)),r}}const mOe=()=>{},LEt=` addEventListener("message", (e) => { if (e.data.event === "start") { setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval); } });`;class DEt{constructor(t,r){var n;this.accessTokenValue=null,this.apiKey=null,this.channels=new Array,this.endPoint="",this.httpEndpoint="",this.headers=NEt,this.params={},this.timeout=set,this.heartbeatIntervalMs=25e3,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=mOe,this.ref=0,this.logger=mOe,this.conn=null,this.sendBuffer=[],this.serializer=new CEt,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._resolveFetch=i=>{let l;return i?l=i:typeof fetch>"u"?l=(...o)=>Ti(async()=>{const{default:c}=await Promise.resolve().then(()=>d8);return{default:c}},void 0).then(({default:c})=>c(...o)):l=fetch,(...o)=>l(...o)},this.endPoint=`${t}/${Fje.websocket}`,this.httpEndpoint=aet(t),r!=null&&r.transport?this.transport=r.transport:this.transport=null,r!=null&&r.params&&(this.params=r.params),r!=null&&r.headers&&(this.headers=Object.assign(Object.assign({},this.headers),r.headers)),r!=null&&r.timeout&&(this.timeout=r.timeout),r!=null&&r.logger&&(this.logger=r.logger),(r!=null&&r.logLevel||r!=null&&r.log_level)&&(this.logLevel=r.logLevel||r.log_level,this.params=Object.assign(Object.assign({},this.params),{log_level:this.logLevel})),r!=null&&r.heartbeatIntervalMs&&(this.heartbeatIntervalMs=r.heartbeatIntervalMs);const a=(n=r==null?void 0:r.params)===null||n===void 0?void 0:n.apikey;if(a&&(this.accessTokenValue=a,this.apiKey=a),this.reconnectAfterMs=r!=null&&r.reconnectAfterMs?r.reconnectAfterMs:i=>[1e3,2e3,5e3,1e4][i-1]||1e4,this.encode=r!=null&&r.encode?r.encode:(i,l)=>l(JSON.stringify(i)),this.decode=r!=null&&r.decode?r.decode:this.serializer.decode.bind(this.serializer),this.reconnectTimer=new ret(async()=>{this.disconnect(),this.connect()},this.reconnectAfterMs),this.fetch=this._resolveFetch(r==null?void 0:r.fetch),r!=null&&r.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.worker=(r==null?void 0:r.worker)||!1,this.workerUrl=r==null?void 0:r.workerUrl}this.accessToken=(r==null?void 0:r.accessToken)||null}connect(){if(!this.conn){if(this.transport||(this.transport=wEt),this.transport){typeof window<"u"&&this.transport===window.WebSocket?this.conn=new this.transport(this.endpointURL()):this.conn=new this.transport(this.endpointURL(),void 0,{headers:this.headers}),this.setupConnection();return}this.conn=new REt(this.endpointURL(),void 0,{close:()=>{this.conn=null}})}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:kEt}))}disconnect(t,r){this.conn&&(this.conn.onclose=function(){},t?this.conn.close(t,r??""):this.conn.close(),this.conn=null,this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.reset(),this.channels.forEach(n=>n.teardown()))}getChannels(){return this.channels}async removeChannel(t){const r=await t.unsubscribe();return this.channels=this.channels.filter(n=>n._joinRef!==t._joinRef),this.channels.length===0&&this.disconnect(),r}async removeAllChannels(){const t=await Promise.all(this.channels.map(r=>r.unsubscribe()));return this.channels=[],this.disconnect(),t}log(t,r,n){this.logger(t,r,n)}connectionState(){switch(this.conn&&this.conn.readyState){case nP.connecting:return TT.Connecting;case nP.open:return TT.Open;case nP.closing:return TT.Closing;default:return TT.Closed}}isConnected(){return this.connectionState()===TT.Open}channel(t,r={config:{}}){const n=`realtime:${t}`,a=this.getChannels().find(i=>i.topic===n);if(a)return a;{const i=new $3e(`realtime:${t}`,r,this);return this.channels.push(i),i}}push(t){const{topic:r,event:n,payload:a,ref:i}=t,l=()=>{this.encode(t,o=>{var c;(c=this.conn)===null||c===void 0||c.send(o)})};this.log("push",`${r} ${n} (${i})`,a),this.isConnected()?l():this.sendBuffer.push(l)}async setAuth(t=null){let r=t||this.accessToken&&await this.accessToken()||this.accessTokenValue;this.accessTokenValue!=r&&(this.accessTokenValue=r,this.channels.forEach(n=>{r&&n.updateJoinPayload({access_token:r,version:this.headers&&this.headers["X-Client-Info"]}),n.joinedOnce&&n._isJoined()&&n._push(t1.access_token,{access_token:r})}))}async sendHeartbeat(){var t;if(!this.isConnected()){this.heartbeatCallback("disconnected");return}if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection"),this.heartbeatCallback("timeout"),(t=this.conn)===null||t===void 0||t.close(SEt,"hearbeat timeout");return}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.heartbeatCallback("sent"),await this.setAuth()}onHeartbeat(t){this.heartbeatCallback=t}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(t=>t()),this.sendBuffer=[])}_makeRef(){let t=this.ref+1;return t===this.ref?this.ref=0:this.ref=t,this.ref.toString()}_leaveOpenTopic(t){let r=this.channels.find(n=>n.topic===t&&(n._isJoined()||n._isJoining()));r&&(this.log("transport",`leaving duplicate topic "${t}"`),r.unsubscribe())}_remove(t){this.channels=this.channels.filter(r=>r.topic!==t.topic)}setupConnection(){this.conn&&(this.conn.binaryType="arraybuffer",this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=t=>this._onConnError(t),this.conn.onmessage=t=>this._onConnMessage(t),this.conn.onclose=t=>this._onConnClose(t))}_onConnMessage(t){this.decode(t.data,r=>{let{topic:n,event:a,payload:i,ref:l}=r;n==="phoenix"&&a==="phx_reply"&&this.heartbeatCallback(r.payload.status=="ok"?"ok":"error"),l&&l===this.pendingHeartbeatRef&&(this.pendingHeartbeatRef=null),this.log("receive",`${i.status||""} ${n} ${a} ${l&&"("+l+")"||""}`,i),Array.from(this.channels).filter(o=>o._isMember(n)).forEach(o=>o._trigger(a,i,l)),this.stateChangeCallbacks.message.forEach(o=>o(r))})}_onConnOpen(){if(this.log("transport",`connected to ${this.endpointURL()}`),this.flushSendBuffer(),this.reconnectTimer.reset(),!this.worker)this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this.sendHeartbeat(),this.heartbeatIntervalMs);else{this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");const t=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(t),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})}this.stateChangeCallbacks.open.forEach(t=>t())}_onConnClose(t){this.log("transport","close",t),this._triggerChanError(),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.scheduleTimeout(),this.stateChangeCallbacks.close.forEach(r=>r(t))}_onConnError(t){this.log("transport",t.message),this._triggerChanError(),this.stateChangeCallbacks.error.forEach(r=>r(t))}_triggerChanError(){this.channels.forEach(t=>t._trigger(t1.error))}_appendParams(t,r){if(Object.keys(r).length===0)return t;const n=t.match(/\?/)?"&":"?",a=new URLSearchParams(r);return`${t}${n}${a}`}_workerObjectUrl(t){let r;if(t)r=t;else{const n=new Blob([LEt],{type:"application/javascript"});r=URL.createObjectURL(n)}return r}}class REt{constructor(t,r,n){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=nP.connecting,this.send=()=>{},this.url=null,this.url=t,this.close=n.close}}class U3e extends Error{constructor(t){super(t),this.__isStorageError=!0,this.name="StorageError"}}function Gm(s){return typeof s=="object"&&s!==null&&"__isStorageError"in s}class OEt extends U3e{constructor(t,r){super(t),this.name="StorageApiError",this.status=r}toJSON(){return{name:this.name,message:this.message,status:this.status}}}class zje extends U3e{constructor(t,r){super(t),this.name="StorageUnknownError",this.originalError=r}}var FEt=function(s,t,r,n){function a(i){return i instanceof r?i:new r(function(l){l(i)})}return new(r||(r=Promise))(function(i,l){function o(h){try{d(n.next(h))}catch(m){l(m)}}function c(h){try{d(n.throw(h))}catch(m){l(m)}}function d(h){h.done?i(h.value):a(h.value).then(o,c)}d((n=n.apply(s,t||[])).next())})};const iet=s=>{let t;return s?t=s:typeof fetch>"u"?t=(...r)=>Ti(async()=>{const{default:n}=await Promise.resolve().then(()=>d8);return{default:n}},void 0).then(({default:n})=>n(...r)):t=fetch,(...r)=>t(...r)},BEt=()=>FEt(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield Ti(()=>Promise.resolve().then(()=>d8),void 0)).Response:Response}),$je=s=>{if(Array.isArray(s))return s.map(r=>$je(r));if(typeof s=="function"||s!==Object(s))return s;const t={};return Object.entries(s).forEach(([r,n])=>{const a=r.replace(/([-_][a-z])/gi,i=>i.toUpperCase().replace(/[-_]/g,""));t[a]=$je(n)}),t};var $A=function(s,t,r,n){function a(i){return i instanceof r?i:new r(function(l){l(i)})}return new(r||(r=Promise))(function(i,l){function o(h){try{d(n.next(h))}catch(m){l(m)}}function c(h){try{d(n.throw(h))}catch(m){l(m)}}function d(h){h.done?i(h.value):a(h.value).then(o,c)}d((n=n.apply(s,t||[])).next())})};const U1e=s=>s.msg||s.message||s.error_description||s.error||JSON.stringify(s),zEt=(s,t,r)=>$A(void 0,void 0,void 0,function*(){const n=yield BEt();s instanceof n&&!(r!=null&&r.noResolveJson)?s.json().then(a=>{t(new OEt(U1e(a),s.status||500))}).catch(a=>{t(new zje(U1e(a),a))}):t(new zje(U1e(s),s))}),$Et=(s,t,r,n)=>{const a={method:s,headers:(t==null?void 0:t.headers)||{}};return s==="GET"?a:(a.headers=Object.assign({"Content-Type":"application/json"},t==null?void 0:t.headers),n&&(a.body=JSON.stringify(n)),Object.assign(Object.assign({},a),r))};function qB(s,t,r,n,a,i){return $A(this,void 0,void 0,function*(){return new Promise((l,o)=>{s(r,$Et(t,n,a,i)).then(c=>{if(!c.ok)throw c;return n!=null&&n.noResolveJson?c:c.json()}).then(c=>l(c)).catch(c=>zEt(c,o,n))})})}function Che(s,t,r,n){return $A(this,void 0,void 0,function*(){return qB(s,"GET",t,r,n)})}function zN(s,t,r,n,a){return $A(this,void 0,void 0,function*(){return qB(s,"POST",t,n,a,r)})}function UEt(s,t,r,n,a){return $A(this,void 0,void 0,function*(){return qB(s,"PUT",t,n,a,r)})}function qEt(s,t,r,n){return $A(this,void 0,void 0,function*(){return qB(s,"HEAD",t,Object.assign(Object.assign({},r),{noResolveJson:!0}),n)})}function oet(s,t,r,n,a){return $A(this,void 0,void 0,function*(){return qB(s,"DELETE",t,n,a,r)})}var Ug=function(s,t,r,n){function a(i){return i instanceof r?i:new r(function(l){l(i)})}return new(r||(r=Promise))(function(i,l){function o(h){try{d(n.next(h))}catch(m){l(m)}}function c(h){try{d(n.throw(h))}catch(m){l(m)}}function d(h){h.done?i(h.value):a(h.value).then(o,c)}d((n=n.apply(s,t||[])).next())})};const VEt={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},fOe={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};class HEt{constructor(t,r={},n,a){this.url=t,this.headers=r,this.bucketId=n,this.fetch=iet(a)}uploadOrUpdate(t,r,n,a){return Ug(this,void 0,void 0,function*(){try{let i;const l=Object.assign(Object.assign({},fOe),a);let o=Object.assign(Object.assign({},this.headers),t==="POST"&&{"x-upsert":String(l.upsert)});const c=l.metadata;typeof Blob<"u"&&n instanceof Blob?(i=new FormData,i.append("cacheControl",l.cacheControl),c&&i.append("metadata",this.encodeMetadata(c)),i.append("",n)):typeof FormData<"u"&&n instanceof FormData?(i=n,i.append("cacheControl",l.cacheControl),c&&i.append("metadata",this.encodeMetadata(c))):(i=n,o["cache-control"]=`max-age=${l.cacheControl}`,o["content-type"]=l.contentType,c&&(o["x-metadata"]=this.toBase64(this.encodeMetadata(c)))),a!=null&&a.headers&&(o=Object.assign(Object.assign({},o),a.headers));const d=this._removeEmptyFolders(r),h=this._getFinalPath(d),m=yield this.fetch(`${this.url}/object/${h}`,Object.assign({method:t,body:i,headers:o},l!=null&&l.duplex?{duplex:l.duplex}:{})),p=yield m.json();return m.ok?{data:{path:d,id:p.Id,fullPath:p.Key},error:null}:{data:null,error:p}}catch(i){if(Gm(i))return{data:null,error:i};throw i}})}upload(t,r,n){return Ug(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",t,r,n)})}uploadToSignedUrl(t,r,n,a){return Ug(this,void 0,void 0,function*(){const i=this._removeEmptyFolders(t),l=this._getFinalPath(i),o=new URL(this.url+`/object/upload/sign/${l}`);o.searchParams.set("token",r);try{let c;const d=Object.assign({upsert:fOe.upsert},a),h=Object.assign(Object.assign({},this.headers),{"x-upsert":String(d.upsert)});typeof Blob<"u"&&n instanceof Blob?(c=new FormData,c.append("cacheControl",d.cacheControl),c.append("",n)):typeof FormData<"u"&&n instanceof FormData?(c=n,c.append("cacheControl",d.cacheControl)):(c=n,h["cache-control"]=`max-age=${d.cacheControl}`,h["content-type"]=d.contentType);const m=yield this.fetch(o.toString(),{method:"PUT",body:c,headers:h}),p=yield m.json();return m.ok?{data:{path:i,fullPath:p.Key},error:null}:{data:null,error:p}}catch(c){if(Gm(c))return{data:null,error:c};throw c}})}createSignedUploadUrl(t,r){return Ug(this,void 0,void 0,function*(){try{let n=this._getFinalPath(t);const a=Object.assign({},this.headers);r!=null&&r.upsert&&(a["x-upsert"]="true");const i=yield zN(this.fetch,`${this.url}/object/upload/sign/${n}`,{},{headers:a}),l=new URL(this.url+i.url),o=l.searchParams.get("token");if(!o)throw new U3e("No token returned by API");return{data:{signedUrl:l.toString(),path:t,token:o},error:null}}catch(n){if(Gm(n))return{data:null,error:n};throw n}})}update(t,r,n){return Ug(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",t,r,n)})}move(t,r,n){return Ug(this,void 0,void 0,function*(){try{return{data:yield zN(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:t,destinationKey:r,destinationBucket:n==null?void 0:n.destinationBucket},{headers:this.headers}),error:null}}catch(a){if(Gm(a))return{data:null,error:a};throw a}})}copy(t,r,n){return Ug(this,void 0,void 0,function*(){try{return{data:{path:(yield zN(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:t,destinationKey:r,destinationBucket:n==null?void 0:n.destinationBucket},{headers:this.headers})).Key},error:null}}catch(a){if(Gm(a))return{data:null,error:a};throw a}})}createSignedUrl(t,r,n){return Ug(this,void 0,void 0,function*(){try{let a=this._getFinalPath(t),i=yield zN(this.fetch,`${this.url}/object/sign/${a}`,Object.assign({expiresIn:r},n!=null&&n.transform?{transform:n.transform}:{}),{headers:this.headers});const l=n!=null&&n.download?`&download=${n.download===!0?"":n.download}`:"";return i={signedUrl:encodeURI(`${this.url}${i.signedURL}${l}`)},{data:i,error:null}}catch(a){if(Gm(a))return{data:null,error:a};throw a}})}createSignedUrls(t,r,n){return Ug(this,void 0,void 0,function*(){try{const a=yield zN(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:r,paths:t},{headers:this.headers}),i=n!=null&&n.download?`&download=${n.download===!0?"":n.download}`:"";return{data:a.map(l=>Object.assign(Object.assign({},l),{signedUrl:l.signedURL?encodeURI(`${this.url}${l.signedURL}${i}`):null})),error:null}}catch(a){if(Gm(a))return{data:null,error:a};throw a}})}download(t,r){return Ug(this,void 0,void 0,function*(){const a=typeof(r==null?void 0:r.transform)<"u"?"render/image/authenticated":"object",i=this.transformOptsToQueryString((r==null?void 0:r.transform)||{}),l=i?`?${i}`:"";try{const o=this._getFinalPath(t);return{data:yield(yield Che(this.fetch,`${this.url}/${a}/${o}${l}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(o){if(Gm(o))return{data:null,error:o};throw o}})}info(t){return Ug(this,void 0,void 0,function*(){const r=this._getFinalPath(t);try{const n=yield Che(this.fetch,`${this.url}/object/info/${r}`,{headers:this.headers});return{data:$je(n),error:null}}catch(n){if(Gm(n))return{data:null,error:n};throw n}})}exists(t){return Ug(this,void 0,void 0,function*(){const r=this._getFinalPath(t);try{return yield qEt(this.fetch,`${this.url}/object/${r}`,{headers:this.headers}),{data:!0,error:null}}catch(n){if(Gm(n)&&n instanceof zje){const a=n.originalError;if([400,404].includes(a==null?void 0:a.status))return{data:!1,error:n}}throw n}})}getPublicUrl(t,r){const n=this._getFinalPath(t),a=[],i=r!=null&&r.download?`download=${r.download===!0?"":r.download}`:"";i!==""&&a.push(i);const o=typeof(r==null?void 0:r.transform)<"u"?"render/image":"object",c=this.transformOptsToQueryString((r==null?void 0:r.transform)||{});c!==""&&a.push(c);let d=a.join("&");return d!==""&&(d=`?${d}`),{data:{publicUrl:encodeURI(`${this.url}/${o}/public/${n}${d}`)}}}remove(t){return Ug(this,void 0,void 0,function*(){try{return{data:yield oet(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:t},{headers:this.headers}),error:null}}catch(r){if(Gm(r))return{data:null,error:r};throw r}})}list(t,r,n){return Ug(this,void 0,void 0,function*(){try{const a=Object.assign(Object.assign(Object.assign({},VEt),r),{prefix:t||""});return{data:yield zN(this.fetch,`${this.url}/object/list/${this.bucketId}`,a,{headers:this.headers},n),error:null}}catch(a){if(Gm(a))return{data:null,error:a};throw a}})}encodeMetadata(t){return JSON.stringify(t)}toBase64(t){return typeof Buffer<"u"?Buffer.from(t).toString("base64"):btoa(t)}_getFinalPath(t){return`${this.bucketId}/${t}`}_removeEmptyFolders(t){return t.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(t){const r=[];return t.width&&r.push(`width=${t.width}`),t.height&&r.push(`height=${t.height}`),t.resize&&r.push(`resize=${t.resize}`),t.format&&r.push(`format=${t.format}`),t.quality&&r.push(`quality=${t.quality}`),r.join("&")}}const GEt="2.7.1",WEt={"X-Client-Info":`storage-js/${GEt}`};var n6=function(s,t,r,n){function a(i){return i instanceof r?i:new r(function(l){l(i)})}return new(r||(r=Promise))(function(i,l){function o(h){try{d(n.next(h))}catch(m){l(m)}}function c(h){try{d(n.throw(h))}catch(m){l(m)}}function d(h){h.done?i(h.value):a(h.value).then(o,c)}d((n=n.apply(s,t||[])).next())})};class KEt{constructor(t,r={},n){this.url=t,this.headers=Object.assign(Object.assign({},WEt),r),this.fetch=iet(n)}listBuckets(){return n6(this,void 0,void 0,function*(){try{return{data:yield Che(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(t){if(Gm(t))return{data:null,error:t};throw t}})}getBucket(t){return n6(this,void 0,void 0,function*(){try{return{data:yield Che(this.fetch,`${this.url}/bucket/${t}`,{headers:this.headers}),error:null}}catch(r){if(Gm(r))return{data:null,error:r};throw r}})}createBucket(t,r={public:!1}){return n6(this,void 0,void 0,function*(){try{return{data:yield zN(this.fetch,`${this.url}/bucket`,{id:t,name:t,public:r.public,file_size_limit:r.fileSizeLimit,allowed_mime_types:r.allowedMimeTypes},{headers:this.headers}),error:null}}catch(n){if(Gm(n))return{data:null,error:n};throw n}})}updateBucket(t,r){return n6(this,void 0,void 0,function*(){try{return{data:yield UEt(this.fetch,`${this.url}/bucket/${t}`,{id:t,name:t,public:r.public,file_size_limit:r.fileSizeLimit,allowed_mime_types:r.allowedMimeTypes},{headers:this.headers}),error:null}}catch(n){if(Gm(n))return{data:null,error:n};throw n}})}emptyBucket(t){return n6(this,void 0,void 0,function*(){try{return{data:yield zN(this.fetch,`${this.url}/bucket/${t}/empty`,{},{headers:this.headers}),error:null}}catch(r){if(Gm(r))return{data:null,error:r};throw r}})}deleteBucket(t){return n6(this,void 0,void 0,function*(){try{return{data:yield oet(this.fetch,`${this.url}/bucket/${t}`,{},{headers:this.headers}),error:null}}catch(r){if(Gm(r))return{data:null,error:r};throw r}})}}class YEt extends KEt{constructor(t,r={},n){super(t,r,n)}from(t){return new HEt(this.url,this.headers,t,this.fetch)}}const ZEt="2.49.10";let mO="";typeof Deno<"u"?mO="deno":typeof document<"u"?mO="web":typeof navigator<"u"&&navigator.product==="ReactNative"?mO="react-native":mO="node";const XEt={"X-Client-Info":`supabase-js-${mO}/${ZEt}`},QEt={headers:XEt},JEt={schema:"public"},eAt={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},tAt={};var sAt=function(s,t,r,n){function a(i){return i instanceof r?i:new r(function(l){l(i)})}return new(r||(r=Promise))(function(i,l){function o(h){try{d(n.next(h))}catch(m){l(m)}}function c(h){try{d(n.throw(h))}catch(m){l(m)}}function d(h){h.done?i(h.value):a(h.value).then(o,c)}d((n=n.apply(s,t||[])).next())})};const rAt=s=>{let t;return s?t=s:typeof fetch>"u"?t=HJe:t=fetch,(...r)=>t(...r)},nAt=()=>typeof Headers>"u"?GJe:Headers,aAt=(s,t,r)=>{const n=rAt(r),a=nAt();return(i,l)=>sAt(void 0,void 0,void 0,function*(){var o;const c=(o=yield t())!==null&&o!==void 0?o:s;let d=new a(l==null?void 0:l.headers);return d.has("apikey")||d.set("apikey",s),d.has("Authorization")||d.set("Authorization",`Bearer ${c}`),n(i,Object.assign(Object.assign({},l),{headers:d}))})};var iAt=function(s,t,r,n){function a(i){return i instanceof r?i:new r(function(l){l(i)})}return new(r||(r=Promise))(function(i,l){function o(h){try{d(n.next(h))}catch(m){l(m)}}function c(h){try{d(n.throw(h))}catch(m){l(m)}}function d(h){h.done?i(h.value):a(h.value).then(o,c)}d((n=n.apply(s,t||[])).next())})};function oAt(s){return s.endsWith("/")?s:s+"/"}function lAt(s,t){var r,n;const{db:a,auth:i,realtime:l,global:o}=s,{db:c,auth:d,realtime:h,global:m}=t,p={db:Object.assign(Object.assign({},c),a),auth:Object.assign(Object.assign({},d),i),realtime:Object.assign(Object.assign({},h),l),global:Object.assign(Object.assign(Object.assign({},m),o),{headers:Object.assign(Object.assign({},(r=m==null?void 0:m.headers)!==null&&r!==void 0?r:{}),(n=o==null?void 0:o.headers)!==null&&n!==void 0?n:{})}),accessToken:()=>iAt(this,void 0,void 0,function*(){return""})};return s.accessToken?p.accessToken=s.accessToken:delete p.accessToken,p}const cet="2.69.1",F6=30*1e3,Uje=3,q1e=Uje*F6,cAt="http://localhost:9999",dAt="supabase.auth.token",uAt={"X-Client-Info":`gotrue-js/${cet}`},qje="X-Supabase-Api-Version",det={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},hAt=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,mAt=6e5;class q3e extends Error{constructor(t,r,n){super(t),this.__isAuthError=!0,this.name="AuthError",this.status=r,this.code=n}}function Mo(s){return typeof s=="object"&&s!==null&&"__isAuthError"in s}class fAt extends q3e{constructor(t,r,n){super(t,r,n),this.name="AuthApiError",this.status=r,this.code=n}}function pAt(s){return Mo(s)&&s.name==="AuthApiError"}class uet extends q3e{constructor(t,r){super(t),this.name="AuthUnknownError",this.originalError=r}}class DS extends q3e{constructor(t,r,n,a){super(t,n,a),this.name=r,this.status=n}}class EN extends DS{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function gAt(s){return Mo(s)&&s.name==="AuthSessionMissingError"}class V1e extends DS{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class LU extends DS{constructor(t){super(t,"AuthInvalidCredentialsError",400,void 0)}}class DU extends DS{constructor(t,r=null){super(t,"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 xAt(s){return Mo(s)&&s.name==="AuthImplicitGrantRedirectError"}class pOe extends DS{constructor(t,r=null){super(t,"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 Vje extends DS{constructor(t,r){super(t,"AuthRetryableFetchError",r,void 0)}}function H1e(s){return Mo(s)&&s.name==="AuthRetryableFetchError"}class gOe extends DS{constructor(t,r,n){super(t,"AuthWeakPasswordError",r,"weak_password"),this.reasons=n}}class HF extends DS{constructor(t){super(t,"AuthInvalidJwtError",400,"invalid_jwt")}}const xOe="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),yOe=` \r=`.split(""),yAt=(()=>{const s=new Array(128);for(let t=0;t-1)for(t.queue=t.queue<<6|n,t.queuedBits+=6;t.queuedBits>=8;)r(t.queue>>t.queuedBits-8&255),t.queuedBits-=8;else{if(n===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(s)}"`)}}function vOe(s){const t=[],r=l=>{t.push(String.fromCodePoint(l))},n={utf8seq:0,codepoint:0},a={queue:0,queuedBits:0},i=l=>{_At(l,n,r)};for(let l=0;l>6),t(128|s&63);return}else if(s<=65535){t(224|s>>12),t(128|s>>6&63),t(128|s&63);return}else if(s<=1114111){t(240|s>>18),t(128|s>>12&63),t(128|s>>6&63),t(128|s&63);return}throw new Error(`Unrecognized Unicode codepoint: ${s.toString(16)}`)}function bAt(s,t){for(let r=0;r55295&&n<=56319){const a=(n-55296)*1024&65535;n=(s.charCodeAt(r+1)-56320&65535|a)+65536,r+=1}vAt(n,t)}}function _At(s,t,r){if(t.utf8seq===0){if(s<=127){r(s);return}for(let n=1;n<6;n+=1)if(!(s>>7-n&1)){t.utf8seq=n;break}if(t.utf8seq===2)t.codepoint=s&31;else if(t.utf8seq===3)t.codepoint=s&15;else if(t.utf8seq===4)t.codepoint=s&7;else throw new Error("Invalid UTF-8 sequence");t.utf8seq-=1}else if(t.utf8seq>0){if(s<=127)throw new Error("Invalid UTF-8 sequence");t.codepoint=t.codepoint<<6|s&63,t.utf8seq-=1,t.utf8seq===0&&r(t.codepoint)}}function wAt(s){const t=[],r={queue:0,queuedBits:0},n=a=>{t.push(a)};for(let a=0;at.push(r)),new Uint8Array(t)}function NAt(s){return Math.round(Date.now()/1e3)+s}function kAt(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(s){const t=Math.random()*16|0;return(s=="x"?t:t&3|8).toString(16)})}const Lb=()=>typeof window<"u"&&typeof document<"u",Q4={tested:!1,writable:!1},GF=()=>{if(!Lb())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(Q4.tested)return Q4.writable;const s=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(s,s),globalThis.localStorage.removeItem(s),Q4.tested=!0,Q4.writable=!0}catch{Q4.tested=!0,Q4.writable=!1}return Q4.writable};function SAt(s){const t={},r=new URL(s);if(r.hash&&r.hash[0]==="#")try{new URLSearchParams(r.hash.substring(1)).forEach((a,i)=>{t[i]=a})}catch{}return r.searchParams.forEach((n,a)=>{t[a]=n}),t}const met=s=>{let t;return s?t=s:typeof fetch>"u"?t=(...r)=>Ti(async()=>{const{default:n}=await Promise.resolve().then(()=>d8);return{default:n}},void 0).then(({default:n})=>n(...r)):t=fetch,(...r)=>t(...r)},CAt=s=>typeof s=="object"&&s!==null&&"status"in s&&"ok"in s&&"json"in s&&typeof s.json=="function",fet=async(s,t,r)=>{await s.setItem(t,JSON.stringify(r))},RU=async(s,t)=>{const r=await s.getItem(t);if(!r)return null;try{return JSON.parse(r)}catch{return r}},OU=async(s,t)=>{await s.removeItem(t)};class nge{constructor(){this.promise=new nge.promiseConstructor((t,r)=>{this.resolve=t,this.reject=r})}}nge.promiseConstructor=Promise;function G1e(s){const t=s.split(".");if(t.length!==3)throw new HF("Invalid JWT structure");for(let n=0;n{setTimeout(()=>t(null),s)})}function EAt(s,t){return new Promise((n,a)=>{(async()=>{for(let i=0;i<1/0;i++)try{const l=await s(i);if(!t(i,null,l)){n(l);return}}catch(l){if(!t(i,l)){a(l);return}}})()})}function AAt(s){return("0"+s.toString(16)).substr(-2)}function MAt(){const t=new Uint32Array(56);if(typeof crypto>"u"){const r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",n=r.length;let a="";for(let i=0;i<56;i++)a+=r.charAt(Math.floor(Math.random()*n));return a}return crypto.getRandomValues(t),Array.from(t,AAt).join("")}async function IAt(s){const r=new TextEncoder().encode(s),n=await crypto.subtle.digest("SHA-256",r),a=new Uint8Array(n);return Array.from(a).map(i=>String.fromCharCode(i)).join("")}async function PAt(s){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."),s;const r=await IAt(s);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function a6(s,t,r=!1){const n=MAt();let a=n;r&&(a+="/PASSWORD_RECOVERY"),await fet(s,`${t}-code-verifier`,a);const i=await PAt(n);return[i,n===i?"plain":"s256"]}const LAt=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function DAt(s){const t=s.headers.get(qje);if(!t||!t.match(LAt))return null;try{return new Date(`${t}T00:00:00.0Z`)}catch{return null}}function RAt(s){if(!s)throw new Error("Missing exp claim");const t=Math.floor(Date.now()/1e3);if(s<=t)throw new Error("JWT has expired")}function OAt(s){switch(s){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")}}var FAt=function(s,t){var r={};for(var n in s)Object.prototype.hasOwnProperty.call(s,n)&&t.indexOf(n)<0&&(r[n]=s[n]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function")for(var a=0,n=Object.getOwnPropertySymbols(s);as.msg||s.message||s.error_description||s.error||JSON.stringify(s),BAt=[502,503,504];async function bOe(s){var t;if(!CAt(s))throw new Vje(bT(s),0);if(BAt.includes(s.status))throw new Vje(bT(s),s.status);let r;try{r=await s.json()}catch(i){throw new uet(bT(i),i)}let n;const a=DAt(s);if(a&&a.getTime()>=det["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 gOe(bT(r),s.status,((t=r.weak_password)===null||t===void 0?void 0:t.reasons)||[]);if(n==="session_not_found")throw new EN}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((i,l)=>i&&typeof l=="string",!0))throw new gOe(bT(r),s.status,r.weak_password.reasons);throw new fAt(bT(r),s.status||500,n)}const zAt=(s,t,r,n)=>{const a={method:s,headers:(t==null?void 0:t.headers)||{}};return s==="GET"?a:(a.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},t==null?void 0:t.headers),a.body=JSON.stringify(n),Object.assign(Object.assign({},a),r))};async function nl(s,t,r,n){var a;const i=Object.assign({},n==null?void 0:n.headers);i[qje]||(i[qje]=det["2024-01-01"].name),n!=null&&n.jwt&&(i.Authorization=`Bearer ${n.jwt}`);const l=(a=n==null?void 0:n.query)!==null&&a!==void 0?a:{};n!=null&&n.redirectTo&&(l.redirect_to=n.redirectTo);const o=Object.keys(l).length?"?"+new URLSearchParams(l).toString():"",c=await $At(s,t,r+o,{headers:i,noResolveJson:n==null?void 0:n.noResolveJson},{},n==null?void 0:n.body);return n!=null&&n.xform?n==null?void 0:n.xform(c):{data:Object.assign({},c),error:null}}async function $At(s,t,r,n,a,i){const l=zAt(t,n,a,i);let o;try{o=await s(r,Object.assign({},l))}catch(c){throw console.error(c),new Vje(bT(c),0)}if(o.ok||await bOe(o),n!=null&&n.noResolveJson)return o;try{return await o.json()}catch(c){await bOe(c)}}function AN(s){var t;let r=null;HAt(s)&&(r=Object.assign({},s),s.expires_at||(r.expires_at=NAt(s.expires_in)));const n=(t=s.user)!==null&&t!==void 0?t:s;return{data:{session:r,user:n},error:null}}function _Oe(s){const t=AN(s);return!t.error&&s.weak_password&&typeof s.weak_password=="object"&&Array.isArray(s.weak_password.reasons)&&s.weak_password.reasons.length&&s.weak_password.message&&typeof s.weak_password.message=="string"&&s.weak_password.reasons.reduce((r,n)=>r&&typeof n=="string",!0)&&(t.data.weak_password=s.weak_password),t}function ek(s){var t;return{data:{user:(t=s.user)!==null&&t!==void 0?t:s},error:null}}function UAt(s){return{data:s,error:null}}function qAt(s){const{action_link:t,email_otp:r,hashed_token:n,redirect_to:a,verification_type:i}=s,l=FAt(s,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),o={action_link:t,email_otp:r,hashed_token:n,redirect_to:a,verification_type:i},c=Object.assign({},l);return{data:{properties:o,user:c},error:null}}function VAt(s){return s}function HAt(s){return s.access_token&&s.refresh_token&&s.expires_in}var GAt=function(s,t){var r={};for(var n in s)Object.prototype.hasOwnProperty.call(s,n)&&t.indexOf(n)<0&&(r[n]=s[n]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function")for(var a=0,n=Object.getOwnPropertySymbols(s);a0&&(x.forEach(y=>{const _=parseInt(y.split(";")[0].split("=")[1].substring(0,1)),b=JSON.parse(y.split(";")[1].split("=")[1]);d[`${b}Page`]=_}),d.total=parseInt(p)),{data:Object.assign(Object.assign({},m),d),error:null}}catch(d){if(Mo(d))return{data:{users:[]},error:d};throw d}}async getUserById(t){try{return await nl(this.fetch,"GET",`${this.url}/admin/users/${t}`,{headers:this.headers,xform:ek})}catch(r){if(Mo(r))return{data:{user:null},error:r};throw r}}async updateUserById(t,r){try{return await nl(this.fetch,"PUT",`${this.url}/admin/users/${t}`,{body:r,headers:this.headers,xform:ek})}catch(n){if(Mo(n))return{data:{user:null},error:n};throw n}}async deleteUser(t,r=!1){try{return await nl(this.fetch,"DELETE",`${this.url}/admin/users/${t}`,{headers:this.headers,body:{should_soft_delete:r},xform:ek})}catch(n){if(Mo(n))return{data:{user:null},error:n};throw n}}async _listFactors(t){try{const{data:r,error:n}=await nl(this.fetch,"GET",`${this.url}/admin/users/${t.userId}/factors`,{headers:this.headers,xform:a=>({data:{factors:a},error:null})});return{data:r,error:n}}catch(r){if(Mo(r))return{data:null,error:r};throw r}}async _deleteFactor(t){try{return{data:await nl(this.fetch,"DELETE",`${this.url}/admin/users/${t.userId}/factors/${t.id}`,{headers:this.headers}),error:null}}catch(r){if(Mo(r))return{data:null,error:r};throw r}}}const KAt={getItem:s=>GF()?globalThis.localStorage.getItem(s):null,setItem:(s,t)=>{GF()&&globalThis.localStorage.setItem(s,t)},removeItem:s=>{GF()&&globalThis.localStorage.removeItem(s)}};function wOe(s={}){return{getItem:t=>s[t]||null,setItem:(t,r)=>{s[t]=r},removeItem:t=>{delete s[t]}}}function YAt(){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)}}const i6={debug:!!(globalThis&&GF()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};class pet extends Error{constructor(t){super(t),this.isAcquireTimeout=!0}}class ZAt extends pet{}async function XAt(s,t,r){i6.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",s,t);const n=new globalThis.AbortController;return t>0&&setTimeout(()=>{n.abort(),i6.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",s)},t),await Promise.resolve().then(()=>globalThis.navigator.locks.request(s,t===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:n.signal},async a=>{if(a){i6.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",s,a.name);try{return await r()}finally{i6.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",s,a.name)}}else{if(t===0)throw i6.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",s),new ZAt(`Acquiring an exclusive Navigator LockManager lock "${s}" immediately failed`);if(i6.debug)try{const i=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(i,null," "))}catch(i){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",i)}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()}}))}YAt();const QAt={url:cAt,storageKey:dAt,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:uAt,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1};async function jOe(s,t,r){return await r()}class a9{constructor(t){var r,n;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=a9.nextInstanceID,a9.nextInstanceID+=1,this.instanceID>0&&Lb()&&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 a=Object.assign(Object.assign({},QAt),t);if(this.logDebugMessages=!!a.debug,typeof a.debug=="function"&&(this.logger=a.debug),this.persistSession=a.persistSession,this.storageKey=a.storageKey,this.autoRefreshToken=a.autoRefreshToken,this.admin=new WAt({url:a.url,headers:a.headers,fetch:a.fetch}),this.url=a.url,this.headers=a.headers,this.fetch=met(a.fetch),this.lock=a.lock||jOe,this.detectSessionInUrl=a.detectSessionInUrl,this.flowType=a.flowType,this.hasCustomAuthorizationHeader=a.hasCustomAuthorizationHeader,a.lock?this.lock=a.lock:Lb()&&(!((r=globalThis==null?void 0:globalThis.navigator)===null||r===void 0)&&r.locks)?this.lock=XAt:this.lock=jOe,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)},this.persistSession?a.storage?this.storage=a.storage:GF()?this.storage=KAt:(this.memoryStorage={},this.storage=wOe(this.memoryStorage)):(this.memoryStorage={},this.storage=wOe(this.memoryStorage)),Lb()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(i){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",i)}(n=this.broadcastChannel)===null||n===void 0||n.addEventListener("message",async i=>{this._debug("received broadcast notification from other tab or client",i),await this._notifyAllSubscribers(i.data.event,i.data.session,!1)})}this.initialize()}_debug(...t){return this.logDebugMessages&&this.logger(`GoTrueClient@${this.instanceID} (${cet}) ${new Date().toISOString()}`,...t),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 t;try{const r=SAt(window.location.href);let n="none";if(this._isImplicitGrantCallback(r)?n="implicit":await this._isPKCECallback(r)&&(n="pkce"),Lb()&&this.detectSessionInUrl&&n!=="none"){const{data:a,error:i}=await this._getSessionFromURL(r,n);if(i){if(this._debug("#_initialize()","error detecting session from URL",i),xAt(i)){const c=(t=i.details)===null||t===void 0?void 0:t.code;if(c==="identity_already_exists"||c==="identity_not_found"||c==="single_identity_not_deletable")return{error:i}}return await this._removeSession(),{error:i}}const{session:l,redirectType:o}=a;return this._debug("#_initialize()","detected session in URL",l,"redirect type",o),await this._saveSession(l),setTimeout(async()=>{o==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",l):await this._notifyAllSubscribers("SIGNED_IN",l)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(r){return Mo(r)?{error:r}:{error:new uet("Unexpected error during initialization",r)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(t){var r,n,a;try{const i=await nl(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(n=(r=t==null?void 0:t.options)===null||r===void 0?void 0:r.data)!==null&&n!==void 0?n:{},gotrue_meta_security:{captcha_token:(a=t==null?void 0:t.options)===null||a===void 0?void 0:a.captchaToken}},xform:AN}),{data:l,error:o}=i;if(o||!l)return{data:{user:null,session:null},error:o};const c=l.session,d=l.user;return l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers("SIGNED_IN",c)),{data:{user:d,session:c},error:null}}catch(i){if(Mo(i))return{data:{user:null,session:null},error:i};throw i}}async signUp(t){var r,n,a;try{let i;if("email"in t){const{email:h,password:m,options:p}=t;let x=null,y=null;this.flowType==="pkce"&&([x,y]=await a6(this.storage,this.storageKey)),i=await nl(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:p==null?void 0:p.emailRedirectTo,body:{email:h,password:m,data:(r=p==null?void 0:p.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:p==null?void 0:p.captchaToken},code_challenge:x,code_challenge_method:y},xform:AN})}else if("phone"in t){const{phone:h,password:m,options:p}=t;i=await nl(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:h,password:m,data:(n=p==null?void 0:p.data)!==null&&n!==void 0?n:{},channel:(a=p==null?void 0:p.channel)!==null&&a!==void 0?a:"sms",gotrue_meta_security:{captcha_token:p==null?void 0:p.captchaToken}},xform:AN})}else throw new LU("You must provide either an email or phone number and a password");const{data:l,error:o}=i;if(o||!l)return{data:{user:null,session:null},error:o};const c=l.session,d=l.user;return l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers("SIGNED_IN",c)),{data:{user:d,session:c},error:null}}catch(i){if(Mo(i))return{data:{user:null,session:null},error:i};throw i}}async signInWithPassword(t){try{let r;if("email"in t){const{email:i,password:l,options:o}=t;r=await nl(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:i,password:l,gotrue_meta_security:{captcha_token:o==null?void 0:o.captchaToken}},xform:_Oe})}else if("phone"in t){const{phone:i,password:l,options:o}=t;r=await nl(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:i,password:l,gotrue_meta_security:{captcha_token:o==null?void 0:o.captchaToken}},xform:_Oe})}else throw new LU("You must provide either an email or phone number and a password");const{data:n,error:a}=r;return a?{data:{user:null,session:null},error:a}:!n||!n.session||!n.user?{data:{user:null,session:null},error:new V1e}:(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:a})}catch(r){if(Mo(r))return{data:{user:null,session:null},error:r};throw r}}async signInWithOAuth(t){var r,n,a,i;return await this._handleProviderSignIn(t.provider,{redirectTo:(r=t.options)===null||r===void 0?void 0:r.redirectTo,scopes:(n=t.options)===null||n===void 0?void 0:n.scopes,queryParams:(a=t.options)===null||a===void 0?void 0:a.queryParams,skipBrowserRedirect:(i=t.options)===null||i===void 0?void 0:i.skipBrowserRedirect})}async exchangeCodeForSession(t){return await this.initializePromise,this._acquireLock(-1,async()=>this._exchangeCodeForSession(t))}async _exchangeCodeForSession(t){const r=await RU(this.storage,`${this.storageKey}-code-verifier`),[n,a]=(r??"").split("/");try{const{data:i,error:l}=await nl(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:t,code_verifier:n},xform:AN});if(await OU(this.storage,`${this.storageKey}-code-verifier`),l)throw l;return!i||!i.session||!i.user?{data:{user:null,session:null,redirectType:null},error:new V1e}:(i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",i.session)),{data:Object.assign(Object.assign({},i),{redirectType:a??null}),error:l})}catch(i){if(Mo(i))return{data:{user:null,session:null,redirectType:null},error:i};throw i}}async signInWithIdToken(t){try{const{options:r,provider:n,token:a,access_token:i,nonce:l}=t,o=await nl(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:n,id_token:a,access_token:i,nonce:l,gotrue_meta_security:{captcha_token:r==null?void 0:r.captchaToken}},xform:AN}),{data:c,error:d}=o;return d?{data:{user:null,session:null},error:d}:!c||!c.session||!c.user?{data:{user:null,session:null},error:new V1e}:(c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),{data:c,error:d})}catch(r){if(Mo(r))return{data:{user:null,session:null},error:r};throw r}}async signInWithOtp(t){var r,n,a,i,l;try{if("email"in t){const{email:o,options:c}=t;let d=null,h=null;this.flowType==="pkce"&&([d,h]=await a6(this.storage,this.storageKey));const{error:m}=await nl(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:o,data:(r=c==null?void 0:c.data)!==null&&r!==void 0?r:{},create_user:(n=c==null?void 0:c.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:c==null?void 0:c.captchaToken},code_challenge:d,code_challenge_method:h},redirectTo:c==null?void 0:c.emailRedirectTo});return{data:{user:null,session:null},error:m}}if("phone"in t){const{phone:o,options:c}=t,{data:d,error:h}=await nl(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:o,data:(a=c==null?void 0:c.data)!==null&&a!==void 0?a:{},create_user:(i=c==null?void 0:c.shouldCreateUser)!==null&&i!==void 0?i:!0,gotrue_meta_security:{captcha_token:c==null?void 0:c.captchaToken},channel:(l=c==null?void 0:c.channel)!==null&&l!==void 0?l:"sms"}});return{data:{user:null,session:null,messageId:d==null?void 0:d.message_id},error:h}}throw new LU("You must provide either an email or phone number.")}catch(o){if(Mo(o))return{data:{user:null,session:null},error:o};throw o}}async verifyOtp(t){var r,n;try{let a,i;"options"in t&&(a=(r=t.options)===null||r===void 0?void 0:r.redirectTo,i=(n=t.options)===null||n===void 0?void 0:n.captchaToken);const{data:l,error:o}=await nl(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},t),{gotrue_meta_security:{captcha_token:i}}),redirectTo:a,xform:AN});if(o)throw o;if(!l)throw new Error("An error occurred on token verification.");const c=l.session,d=l.user;return c!=null&&c.access_token&&(await this._saveSession(c),await this._notifyAllSubscribers(t.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",c)),{data:{user:d,session:c},error:null}}catch(a){if(Mo(a))return{data:{user:null,session:null},error:a};throw a}}async signInWithSSO(t){var r,n,a;try{let i=null,l=null;return this.flowType==="pkce"&&([i,l]=await a6(this.storage,this.storageKey)),await nl(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in t?{provider_id:t.providerId}:null),"domain"in t?{domain:t.domain}:null),{redirect_to:(n=(r=t.options)===null||r===void 0?void 0:r.redirectTo)!==null&&n!==void 0?n:void 0}),!((a=t==null?void 0:t.options)===null||a===void 0)&&a.captchaToken?{gotrue_meta_security:{captcha_token:t.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:i,code_challenge_method:l}),headers:this.headers,xform:UAt})}catch(i){if(Mo(i))return{data:null,error:i};throw i}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async t=>{const{data:{session:r},error:n}=t;if(n)throw n;if(!r)throw new EN;const{error:a}=await nl(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:r.access_token});return{data:{user:null,session:null},error:a}})}catch(t){if(Mo(t))return{data:{user:null,session:null},error:t};throw t}}async resend(t){try{const r=`${this.url}/resend`;if("email"in t){const{email:n,type:a,options:i}=t,{error:l}=await nl(this.fetch,"POST",r,{headers:this.headers,body:{email:n,type:a,gotrue_meta_security:{captcha_token:i==null?void 0:i.captchaToken}},redirectTo:i==null?void 0:i.emailRedirectTo});return{data:{user:null,session:null},error:l}}else if("phone"in t){const{phone:n,type:a,options:i}=t,{data:l,error:o}=await nl(this.fetch,"POST",r,{headers:this.headers,body:{phone:n,type:a,gotrue_meta_security:{captcha_token:i==null?void 0:i.captchaToken}}});return{data:{user:null,session:null,messageId:l==null?void 0:l.message_id},error:o}}throw new LU("You must provide either an email or phone number and a type")}catch(r){if(Mo(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(t,r){this._debug("#_acquireLock","begin",t);try{if(this.lockAcquired){const n=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),a=(async()=>(await n,await r()))();return this.pendingInLock.push((async()=>{try{await a}catch{}})()),a}return await this.lock(`lock:${this.storageKey}`,t,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 a=[...this.pendingInLock];await Promise.all(a),this.pendingInLock.splice(0,a.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(t){this._debug("#_useSession","begin");try{const r=await this.__loadSession();return await t(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 t=null;const r=await RU(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",r),r!==null&&(this._isValidSession(r)?t=r:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!t)return{data:{session:null},error:null};const n=t.expires_at?t.expires_at*1e3-Date.now()(!l&&d==="user"&&(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."),l=!0,this.suppressGetSessionWarning=!0),Reflect.get(c,d,h))})}return{data:{session:t},error:null}}const{session:a,error:i}=await this._callRefreshToken(t.refresh_token);return i?{data:{session:null},error:i}:{data:{session:a},error:null}}finally{this._debug("#__loadSession()","end")}}async getUser(t){return t?await this._getUser(t):(await this.initializePromise,await this._acquireLock(-1,async()=>await this._getUser()))}async _getUser(t){try{return t?await nl(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:t,xform:ek}):await this._useSession(async r=>{var n,a,i;const{data:l,error:o}=r;if(o)throw o;return!(!((n=l.session)===null||n===void 0)&&n.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new EN}:await nl(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(i=(a=l.session)===null||a===void 0?void 0:a.access_token)!==null&&i!==void 0?i:void 0,xform:ek})})}catch(r){if(Mo(r))return gAt(r)&&(await this._removeSession(),await OU(this.storage,`${this.storageKey}-code-verifier`)),{data:{user:null},error:r};throw r}}async updateUser(t,r={}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._updateUser(t,r))}async _updateUser(t,r={}){try{return await this._useSession(async n=>{const{data:a,error:i}=n;if(i)throw i;if(!a.session)throw new EN;const l=a.session;let o=null,c=null;this.flowType==="pkce"&&t.email!=null&&([o,c]=await a6(this.storage,this.storageKey));const{data:d,error:h}=await nl(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:r==null?void 0:r.emailRedirectTo,body:Object.assign(Object.assign({},t),{code_challenge:o,code_challenge_method:c}),jwt:l.access_token,xform:ek});if(h)throw h;return l.user=d.user,await this._saveSession(l),await this._notifyAllSubscribers("USER_UPDATED",l),{data:{user:l.user},error:null}})}catch(n){if(Mo(n))return{data:{user:null},error:n};throw n}}async setSession(t){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._setSession(t))}async _setSession(t){try{if(!t.access_token||!t.refresh_token)throw new EN;const r=Date.now()/1e3;let n=r,a=!0,i=null;const{payload:l}=G1e(t.access_token);if(l.exp&&(n=l.exp,a=n<=r),a){const{session:o,error:c}=await this._callRefreshToken(t.refresh_token);if(c)return{data:{user:null,session:null},error:c};if(!o)return{data:{user:null,session:null},error:null};i=o}else{const{data:o,error:c}=await this._getUser(t.access_token);if(c)throw c;i={access_token:t.access_token,refresh_token:t.refresh_token,user:o.user,token_type:"bearer",expires_in:n-r,expires_at:n},await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)}return{data:{user:i.user,session:i},error:null}}catch(r){if(Mo(r))return{data:{session:null,user:null},error:r};throw r}}async refreshSession(t){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._refreshSession(t))}async _refreshSession(t){try{return await this._useSession(async r=>{var n;if(!t){const{data:l,error:o}=r;if(o)throw o;t=(n=l.session)!==null&&n!==void 0?n:void 0}if(!(t!=null&&t.refresh_token))throw new EN;const{session:a,error:i}=await this._callRefreshToken(t.refresh_token);return i?{data:{user:null,session:null},error:i}:a?{data:{user:a.user,session:a},error:null}:{data:{user:null,session:null},error:null}})}catch(r){if(Mo(r))return{data:{user:null,session:null},error:r};throw r}}async _getSessionFromURL(t,r){try{if(!Lb())throw new DU("No browser detected.");if(t.error||t.error_description||t.error_code)throw new DU(t.error_description||"Error in URL with unspecified error_description",{error:t.error||"unspecified_error",code:t.error_code||"unspecified_code"});switch(r){case"implicit":if(this.flowType==="pkce")throw new pOe("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new DU("Not a valid implicit grant flow url.");break;default:}if(r==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!t.code)throw new pOe("No code detected.");const{data:k,error:T}=await this._exchangeCodeForSession(t.code);if(T)throw T;const E=new URL(window.location.href);return E.searchParams.delete("code"),window.history.replaceState(window.history.state,"",E.toString()),{data:{session:k.session,redirectType:null},error:null}}const{provider_token:n,provider_refresh_token:a,access_token:i,refresh_token:l,expires_in:o,expires_at:c,token_type:d}=t;if(!i||!o||!l||!d)throw new DU("No session defined in URL");const h=Math.round(Date.now()/1e3),m=parseInt(o);let p=h+m;c&&(p=parseInt(c));const x=p-h;x*1e3<=F6&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${x}s, should have been closer to ${m}s`);const y=p-m;h-y>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",y,p,h):h-y<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",y,p,h);const{data:_,error:b}=await this._getUser(i);if(b)throw b;const j={provider_token:n,provider_refresh_token:a,access_token:i,expires_in:m,expires_at:p,refresh_token:l,token_type:d,user:_.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:j,redirectType:t.type},error:null}}catch(n){if(Mo(n))return{data:{session:null,redirectType:null},error:n};throw n}}_isImplicitGrantCallback(t){return!!(t.access_token||t.error_description)}async _isPKCECallback(t){const r=await RU(this.storage,`${this.storageKey}-code-verifier`);return!!(t.code&&r)}async signOut(t={scope:"global"}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._signOut(t))}async _signOut({scope:t}={scope:"global"}){return await this._useSession(async r=>{var n;const{data:a,error:i}=r;if(i)return{error:i};const l=(n=a.session)===null||n===void 0?void 0:n.access_token;if(l){const{error:o}=await this.admin.signOut(l,t);if(o&&!(pAt(o)&&(o.status===404||o.status===401||o.status===403)))return{error:o}}return t!=="others"&&(await this._removeSession(),await OU(this.storage,`${this.storageKey}-code-verifier`)),{error:null}})}onAuthStateChange(t){const r=kAt(),n={id:r,callback:t,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(t){return await this._useSession(async r=>{var n,a;try{const{data:{session:i},error:l}=r;if(l)throw l;await((n=this.stateChangeEmitters.get(t))===null||n===void 0?void 0:n.callback("INITIAL_SESSION",i)),this._debug("INITIAL_SESSION","callback id",t,"session",i)}catch(i){await((a=this.stateChangeEmitters.get(t))===null||a===void 0?void 0:a.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",t,"error",i),console.error(i)}})}async resetPasswordForEmail(t,r={}){let n=null,a=null;this.flowType==="pkce"&&([n,a]=await a6(this.storage,this.storageKey,!0));try{return await nl(this.fetch,"POST",`${this.url}/recover`,{body:{email:t,code_challenge:n,code_challenge_method:a,gotrue_meta_security:{captcha_token:r.captchaToken}},headers:this.headers,redirectTo:r.redirectTo})}catch(i){if(Mo(i))return{data:null,error:i};throw i}}async getUserIdentities(){var t;try{const{data:r,error:n}=await this.getUser();if(n)throw n;return{data:{identities:(t=r.user.identities)!==null&&t!==void 0?t:[]},error:null}}catch(r){if(Mo(r))return{data:null,error:r};throw r}}async linkIdentity(t){var r;try{const{data:n,error:a}=await this._useSession(async i=>{var l,o,c,d,h;const{data:m,error:p}=i;if(p)throw p;const x=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,t.provider,{redirectTo:(l=t.options)===null||l===void 0?void 0:l.redirectTo,scopes:(o=t.options)===null||o===void 0?void 0:o.scopes,queryParams:(c=t.options)===null||c===void 0?void 0:c.queryParams,skipBrowserRedirect:!0});return await nl(this.fetch,"GET",x,{headers:this.headers,jwt:(h=(d=m.session)===null||d===void 0?void 0:d.access_token)!==null&&h!==void 0?h:void 0})});if(a)throw a;return Lb()&&!(!((r=t.options)===null||r===void 0)&&r.skipBrowserRedirect)&&window.location.assign(n==null?void 0:n.url),{data:{provider:t.provider,url:n==null?void 0:n.url},error:null}}catch(n){if(Mo(n))return{data:{provider:t.provider,url:null},error:n};throw n}}async unlinkIdentity(t){try{return await this._useSession(async r=>{var n,a;const{data:i,error:l}=r;if(l)throw l;return await nl(this.fetch,"DELETE",`${this.url}/user/identities/${t.identity_id}`,{headers:this.headers,jwt:(a=(n=i.session)===null||n===void 0?void 0:n.access_token)!==null&&a!==void 0?a:void 0})})}catch(r){if(Mo(r))return{data:null,error:r};throw r}}async _refreshAccessToken(t){const r=`#_refreshAccessToken(${t.substring(0,5)}...)`;this._debug(r,"begin");try{const n=Date.now();return await EAt(async a=>(a>0&&await TAt(200*Math.pow(2,a-1)),this._debug(r,"refreshing attempt",a),await nl(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:t},headers:this.headers,xform:AN})),(a,i)=>{const l=200*Math.pow(2,a);return i&&H1e(i)&&Date.now()+l-n{try{await o.callback(t,r)}catch(c){i.push(c)}});if(await Promise.all(l),i.length>0){for(let o=0;othis._autoRefreshTokenTick(),F6);this.autoRefreshTicker=t,t&&typeof t=="object"&&typeof t.unref=="function"?t.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(t),setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");const t=this.autoRefreshTicker;this.autoRefreshTicker=null,t&&clearInterval(t)}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 t=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 a=Math.floor((n.expires_at*1e3-t)/F6);this._debug("#_autoRefreshTokenTick()",`access token expires in ${a} ticks, a tick lasts ${F6}ms, refresh threshold is ${Uje} ticks`),a<=Uje&&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(t){if(t.isAcquireTimeout||t instanceof pet)this._debug("auto refresh token tick lock not available");else throw t}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!Lb()||!(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(t){console.error("_handleVisibilityChange",t)}}async _onVisibilityChanged(t){const r=`#_onVisibilityChanged(${t})`;this._debug(r,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),t||(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(t,r,n){const a=[`provider=${encodeURIComponent(r)}`];if(n!=null&&n.redirectTo&&a.push(`redirect_to=${encodeURIComponent(n.redirectTo)}`),n!=null&&n.scopes&&a.push(`scopes=${encodeURIComponent(n.scopes)}`),this.flowType==="pkce"){const[i,l]=await a6(this.storage,this.storageKey),o=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(l)}`});a.push(o.toString())}if(n!=null&&n.queryParams){const i=new URLSearchParams(n.queryParams);a.push(i.toString())}return n!=null&&n.skipBrowserRedirect&&a.push(`skip_http_redirect=${n.skipBrowserRedirect}`),`${t}?${a.join("&")}`}async _unenroll(t){try{return await this._useSession(async r=>{var n;const{data:a,error:i}=r;return i?{data:null,error:i}:await nl(this.fetch,"DELETE",`${this.url}/factors/${t.factorId}`,{headers:this.headers,jwt:(n=a==null?void 0:a.session)===null||n===void 0?void 0:n.access_token})})}catch(r){if(Mo(r))return{data:null,error:r};throw r}}async _enroll(t){try{return await this._useSession(async r=>{var n,a;const{data:i,error:l}=r;if(l)return{data:null,error:l};const o=Object.assign({friendly_name:t.friendlyName,factor_type:t.factorType},t.factorType==="phone"?{phone:t.phone}:{issuer:t.issuer}),{data:c,error:d}=await nl(this.fetch,"POST",`${this.url}/factors`,{body:o,headers:this.headers,jwt:(n=i==null?void 0:i.session)===null||n===void 0?void 0:n.access_token});return d?{data:null,error:d}:(t.factorType==="totp"&&(!((a=c==null?void 0:c.totp)===null||a===void 0)&&a.qr_code)&&(c.totp.qr_code=`data:image/svg+xml;utf-8,${c.totp.qr_code}`),{data:c,error:null})})}catch(r){if(Mo(r))return{data:null,error:r};throw r}}async _verify(t){return this._acquireLock(-1,async()=>{try{return await this._useSession(async r=>{var n;const{data:a,error:i}=r;if(i)return{data:null,error:i};const{data:l,error:o}=await nl(this.fetch,"POST",`${this.url}/factors/${t.factorId}/verify`,{body:{code:t.code,challenge_id:t.challengeId},headers:this.headers,jwt:(n=a==null?void 0:a.session)===null||n===void 0?void 0:n.access_token});return o?{data:null,error:o}:(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+l.expires_in},l)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",l),{data:l,error:o})})}catch(r){if(Mo(r))return{data:null,error:r};throw r}})}async _challenge(t){return this._acquireLock(-1,async()=>{try{return await this._useSession(async r=>{var n;const{data:a,error:i}=r;return i?{data:null,error:i}:await nl(this.fetch,"POST",`${this.url}/factors/${t.factorId}/challenge`,{body:{channel:t.channel},headers:this.headers,jwt:(n=a==null?void 0:a.session)===null||n===void 0?void 0:n.access_token})})}catch(r){if(Mo(r))return{data:null,error:r};throw r}})}async _challengeAndVerify(t){const{data:r,error:n}=await this._challenge({factorId:t.factorId});return n?{data:null,error:n}:await this._verify({factorId:t.factorId,challengeId:r.id,code:t.code})}async _listFactors(){const{data:{user:t},error:r}=await this.getUser();if(r)return{data:null,error:r};const n=(t==null?void 0:t.factors)||[],a=n.filter(l=>l.factor_type==="totp"&&l.status==="verified"),i=n.filter(l=>l.factor_type==="phone"&&l.status==="verified");return{data:{all:n,totp:a,phone:i},error:null}}async _getAuthenticatorAssuranceLevel(){return this._acquireLock(-1,async()=>await this._useSession(async t=>{var r,n;const{data:{session:a},error:i}=t;if(i)return{data:null,error:i};if(!a)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const{payload:l}=G1e(a.access_token);let o=null;l.aal&&(o=l.aal);let c=o;((n=(r=a.user.factors)===null||r===void 0?void 0:r.filter(m=>m.status==="verified"))!==null&&n!==void 0?n:[]).length>0&&(c="aal2");const h=l.amr||[];return{data:{currentLevel:o,nextLevel:c,currentAuthenticationMethods:h},error:null}}))}async fetchJwk(t,r={keys:[]}){let n=r.keys.find(l=>l.kid===t);if(n||(n=this.jwks.keys.find(l=>l.kid===t),n&&this.jwks_cached_at+mAt>Date.now()))return n;const{data:a,error:i}=await nl(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(i)throw i;if(!a.keys||a.keys.length===0)throw new HF("JWKS is empty");if(this.jwks=a,this.jwks_cached_at=Date.now(),n=a.keys.find(l=>l.kid===t),!n)throw new HF("No matching signing key found in JWKS");return n}async getClaims(t,r={keys:[]}){try{let n=t;if(!n){const{data:x,error:y}=await this.getSession();if(y||!x.session)return{data:null,error:y};n=x.session.access_token}const{header:a,payload:i,signature:l,raw:{header:o,payload:c}}=G1e(n);if(RAt(i.exp),!a.kid||a.alg==="HS256"||!("crypto"in globalThis&&"subtle"in globalThis.crypto)){const{error:x}=await this.getUser(n);if(x)throw x;return{data:{claims:i,header:a,signature:l},error:null}}const d=OAt(a.alg),h=await this.fetchJwk(a.kid,r),m=await crypto.subtle.importKey("jwk",h,d,!0,["verify"]);if(!await crypto.subtle.verify(d,m,l,jAt(`${o}.${c}`)))throw new HF("Invalid JWT signature");return{data:{claims:i,header:a,signature:l},error:null}}catch(n){if(Mo(n))return{data:null,error:n};throw n}}}a9.nextInstanceID=0;const JAt=a9;class eMt extends JAt{constructor(t){super(t)}}var tMt=function(s,t,r,n){function a(i){return i instanceof r?i:new r(function(l){l(i)})}return new(r||(r=Promise))(function(i,l){function o(h){try{d(n.next(h))}catch(m){l(m)}}function c(h){try{d(n.throw(h))}catch(m){l(m)}}function d(h){h.done?i(h.value):a(h.value).then(o,c)}d((n=n.apply(s,t||[])).next())})};class sMt{constructor(t,r,n){var a,i,l;if(this.supabaseUrl=t,this.supabaseKey=r,!t)throw new Error("supabaseUrl is required.");if(!r)throw new Error("supabaseKey is required.");const o=oAt(t),c=new URL(o);this.realtimeUrl=new URL("realtime/v1",c),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",c),this.storageUrl=new URL("storage/v1",c),this.functionsUrl=new URL("functions/v1",c);const d=`sb-${c.hostname.split(".")[0]}-auth-token`,h={db:JEt,realtime:tAt,auth:Object.assign(Object.assign({},eAt),{storageKey:d}),global:QEt},m=lAt(n??{},h);this.storageKey=(a=m.auth.storageKey)!==null&&a!==void 0?a:"",this.headers=(i=m.global.headers)!==null&&i!==void 0?i:{},m.accessToken?(this.accessToken=m.accessToken,this.auth=new Proxy({},{get:(p,x)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(x)} is not possible`)}})):this.auth=this._initSupabaseAuthClient((l=m.auth)!==null&&l!==void 0?l:{},this.headers,m.global.fetch),this.fetch=aAt(r,this._getAccessToken.bind(this),m.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers,accessToken:this._getAccessToken.bind(this)},m.realtime)),this.rest=new _Et(new URL("rest/v1",c).href,{headers:this.headers,schema:m.db.schema,fetch:this.fetch}),m.accessToken||this._listenForAuthEvents()}get functions(){return new XTt(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}get storage(){return new YEt(this.storageUrl.href,this.headers,this.fetch)}from(t){return this.rest.from(t)}schema(t){return this.rest.schema(t)}rpc(t,r={},n={}){return this.rest.rpc(t,r,n)}channel(t,r={config:{}}){return this.realtime.channel(t,r)}getChannels(){return this.realtime.getChannels()}removeChannel(t){return this.realtime.removeChannel(t)}removeAllChannels(){return this.realtime.removeAllChannels()}_getAccessToken(){var t,r;return tMt(this,void 0,void 0,function*(){if(this.accessToken)return yield this.accessToken();const{data:n}=yield this.auth.getSession();return(r=(t=n.session)===null||t===void 0?void 0:t.access_token)!==null&&r!==void 0?r:null})}_initSupabaseAuthClient({autoRefreshToken:t,persistSession:r,detectSessionInUrl:n,storage:a,storageKey:i,flowType:l,lock:o,debug:c},d,h){const m={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new eMt({url:this.authUrl.href,headers:Object.assign(Object.assign({},m),d),storageKey:i,autoRefreshToken:t,persistSession:r,detectSessionInUrl:n,storage:a,flowType:l,lock:o,debug:c,fetch:h,hasCustomAuthorizationHeader:"Authorization"in this.headers})}_initRealtimeClient(t){return new DEt(this.realtimeUrl.href,Object.assign(Object.assign({},t),{params:Object.assign({apikey:this.supabaseKey},t==null?void 0:t.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((r,n)=>{this._handleTokenChanged(r,"CLIENT",n==null?void 0:n.access_token)})}_handleTokenChanged(t,r,n){(t==="TOKEN_REFRESHED"||t==="SIGNED_IN")&&this.changedAccessToken!==n?this.changedAccessToken=n:t==="SIGNED_OUT"&&(this.realtime.setAuth(),r=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}}const rMt=(s,t,r)=>new sMt(s,t,r),nMt="https://relzejiswnotikjgvjhz.supabase.co",aMt="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJlbHplamlzd25vdGlramd2amh6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE5NTAzNDQsImV4cCI6MjA3NzUyNjM0NH0.dzIkIr_oFSbFE3oWS0ktIr83iKHHkZxt40Gc7SpC_mM",V=rMt(nMt,aMt,{auth:{storage:localStorage,persistSession:!0,autoRefreshToken:!0}}),iMt=Object.freeze(Object.defineProperty({__proto__:null,supabase:V},Symbol.toStringTag,{value:"Module"})),get=S.createContext(void 0),oMt=({children:s})=>{const[t,r]=S.useState(null),[n,a]=S.useState(null),[i,l]=S.useState(!0),[o,c]=S.useState(!0),[d,h]=S.useState(!1),[m,p]=S.useState(!1),[x,y]=S.useState(!1),[_,b]=S.useState(null),[j,k]=S.useState([]),[T,E]=S.useState(null),A=S.useRef(null),D=S.useRef(!1),R=S.useRef(!1),z=Fr(),O=()=>{h(!1),p(!1),y(!1),b(null),k([]),E(null),A.current=null,D.current=!1},$=async K=>{if(!(D.current&&A.current===K)&&!R.current){R.current=!0,c(!0);try{console.log("Checking roles via RPC for user:",K);const[{data:re,error:ie},{data:ce,error:ne},{data:le,error:be}]=await Promise.all([V.rpc("has_role",{_user_id:K,_role:"admin"}),V.rpc("has_role",{_user_id:K,_role:"brokerage_manager"}),V.rpc("has_role",{_user_id:K,_role:"coach"})]);if(ie||ne)console.error("Role RPC errors:",{isAdminError:ie,isBrokerError:ne,isCoachError:be}),h(!1),p(!1),y(!1);else{const ve=!!re,We=!!ce,Ve=!!le;console.log("RPC roles result:",{adminValue:ve,brokerValue:We,coachValue:Ve}),h(ve),p(We),y(Ve)}const{data:fe,error:je}=await V.from("profiles").select("brokerage_id").eq("id",K).single();if(b(!je&&fe?fe.brokerage_id:null),ce){console.log("Fetching managed brokerages for user:",K);const{data:ve,error:We}=await V.from("brokerage_manager_assignments").select("brokerage_id").eq("user_id",K);if(console.log("Managed brokerage assignments result:",{assignments:ve,assignmentsError:We}),We||!ve){console.error("Error fetching managed brokerage assignments:",We),k([]);return}const Ve=Array.from(new Set(ve.map(Pe=>Pe.brokerage_id).filter(Boolean)));if(Ve.length===0){k([]);return}const{data:Le,error:Me}=await V.from("brokerages").select("id, name").in("id",Ve);if(console.log("Managed brokerages details result:",{brokeragesData:Le,brokeragesError:Me}),Me||!Le){console.error("Error fetching managed brokerages details:",Me),k([]);return}const ze=Le.map(Pe=>({id:Pe.id,name:Pe.name})).sort((Pe,Ie)=>Ve.indexOf(Pe.id)-Ve.indexOf(Ie.id));console.log("Parsed managed brokerages:",ze),k(ze),ze.length>0&&E(Pe=>Pe??ze[0].id)}else console.log("User is not a brokerage manager, skipping managed brokerages fetch"),k([]);A.current=K,D.current=!0}catch(re){console.error("Unexpected error in checkRoles:",re),O()}finally{R.current=!1,c(!1)}}};S.useEffect(()=>{let K=!0,re=!1;const ie=()=>{!K||re||(re=!0,l(!1))},{data:{subscription:ce}}=V.auth.onAuthStateChange((be,fe)=>{console.log("Auth event:",be),K&&(a(fe),r((fe==null?void 0:fe.user)??null),ie(),be==="PASSWORD_RECOVERY"&&(console.log("Password recovery detected, redirecting to profile"),setTimeout(()=>{z("/profile?reset=true")},100)),fe!=null&&fe.user?(!D.current||A.current!==fe.user.id)&&setTimeout(()=>{$(fe.user.id)},0):(O(),c(!1)))}),ne=window.setTimeout(()=>{console.warn("Auth initialization timeout reached. Continuing without blocking UI."),ie()},4e3);return(async()=>{try{const{data:{session:be}}=await V.auth.getSession();if(!K)return;a(be),r((be==null?void 0:be.user)??null),be!=null&&be.user?await $(be.user.id):O()}catch(be){console.error("Error restoring auth session:",be),K&&(a(null),r(null),O())}finally{ie()}})(),()=>{K=!1,window.clearTimeout(ne),ce.unsubscribe()}},[]);const ee=async(K,re)=>{const{error:ie}=await V.auth.signInWithPassword({email:K,password:re});if(ie)throw he.error(ie.message),ie;he.success("Welcome back!");const ce=sessionStorage.getItem("redirectAfterLogin")||"/dashboard";sessionStorage.removeItem("redirectAfterLogin"),z(ce)},Z=async(K,re,ie)=>{var fe;const ce=`${window.location.origin}/dashboard`,ne=localStorage.getItem("levelup_referral_code")||null,{data:le,error:be}=await V.auth.signUp({email:K,password:re,options:{emailRedirectTo:ce,data:{name:ie,referred_by_code:ne}}});if(be)throw he.error(be.message),be;if(ne&&((fe=le.user)!=null&&fe.id))try{await V.from("profiles").update({referred_by_code:ne}).eq("id",le.user.id),localStorage.removeItem("levelup_referral_code")}catch(je){console.warn("Failed to attach referral code to profile",je)}he.success("Account created! Welcome to LevelUp."),z("/dashboard")},J=async()=>{try{const{data:{session:K}}=await V.auth.getSession();if(K){const{error:re}=await V.auth.signOut();re?re.message==="Auth session missing!"?console.warn("Sign out warning (ignored):",re.message):(console.error("Sign out error:",re),he.error(re.message)):he.success("Signed out successfully")}else console.log("No active session found, redirecting to auth");r(null),a(null),h(!1),p(!1),b(null),k([]),E(null),z("/auth")}catch(K){console.error("Unexpected sign out error:",K),z("/auth")}};return e.jsx(get.Provider,{value:{user:t,session:n,loading:i,rolesLoading:o,signIn:ee,signUp:Z,signOut:J,isAdmin:d,isBrokerageManager:m,isCoach:x,brokerageId:_,managedBrokerages:j,selectedBrokerageId:T,setSelectedBrokerageId:E},children:s})},Ms=()=>{const s=S.useContext(get);if(s===void 0)throw new Error("useAuth must be used within an AuthProvider");return s},xet=S.createContext({onlineUsers:[],totalOnline:0}),lMt=async s=>{try{const{data:t}=await V.storage.from("avatars").list(`${s}`);if(t&&t.length>0){const{data:r}=V.storage.from("avatars").getPublicUrl(`${s}/${t[0].name}`);return r.publicUrl}}catch{}},cMt=({children:s})=>{const{user:t,brokerageId:r,isAdmin:n}=Ms(),[a,i]=S.useState([]),[l,o]=S.useState(null);S.useEffect(()=>{if(!t)return;let d=!1;V.auth.getSession().then(({data:m})=>{var x;const p=(x=m.session)==null?void 0:x.access_token;if(p)try{V.realtime.setAuth(p)}catch{}});const h=V.channel("app-presence-v2",{config:{presence:{key:t.id},broadcast:{self:!0}}});return h.on("presence",{event:"sync"},()=>{const m=h.presenceState(),p=[];Object.entries(m).forEach(([x,y])=>{if(y&&y.length>0){const _=y[0];p.push({id:x,name:_.name||"Unknown",avatarUrl:_.avatarUrl,brokerageId:_.brokerageId,onlineSince:_.onlineSince})}}),console.log("[Presence] sync, users:",p.length,p),i(p)}).on("presence",{event:"join"},({key:m,newPresences:p})=>{console.log("[Presence] join",m,p)}).on("presence",{event:"leave"},({key:m})=>{console.log("[Presence] leave",m)}).subscribe(async(m,p)=>{var x;if(console.log("[Presence] subscribe status:",m,p),m==="SUBSCRIBED"&&!d){const{data:y}=await V.from("profiles").select("name, brokerage_id").eq("id",t.id).maybeSingle(),_=await lMt(t.id),b=await h.track({name:(y==null?void 0:y.name)||((x=t.email)==null?void 0:x.split("@")[0])||"User",avatarUrl:_,brokerageId:y==null?void 0:y.brokerage_id,onlineSince:new Date().toISOString()});console.log("[Presence] track result:",b)}}),o(h),()=>{d=!0;try{h.untrack()}catch{}V.removeChannel(h)}},[t==null?void 0:t.id]);const c=a.filter(d=>d.id===(t==null?void 0:t.id)?!1:!!(n||r&&d.brokerageId===r||!r&&!d.brokerageId));return e.jsx(xet.Provider,{value:{onlineUsers:c,totalOnline:a.length},children:s})},yet=()=>S.useContext(xet),vet=S.createContext(void 0),J4="levelup_admin_session",yN="levelup_impersonation",W1e="levelup_impersonation_return",dMt=({children:s})=>{const[t,r]=S.useState(!1),[n,a]=S.useState(null),[i,l]=S.useState(!1);S.useEffect(()=>{const d=sessionStorage.getItem(yN);if(d)try{const h=JSON.parse(d);r(!0),a(h)}catch{sessionStorage.removeItem(yN)}},[]);const o=async(d,h)=>{l(!0);try{const{data:{session:m}}=await V.auth.getSession();if(!m)return he.error("No active session found"),!1;const p={access_token:m.access_token,refresh_token:m.refresh_token};sessionStorage.setItem(J4,JSON.stringify(p)),h&&sessionStorage.setItem(W1e,h);const x=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/impersonate-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${m.access_token}`},body:JSON.stringify({targetUserId:d})}),y=await x.json();if(!x.ok)throw new Error(y.error||"Failed to impersonate user");const _={id:y.targetUser.id,name:y.targetUser.name,email:y.targetUser.email};if(sessionStorage.setItem(yN,JSON.stringify(_)),y.method==="session"){const{error:b}=await V.auth.setSession({access_token:y.access_token,refresh_token:y.refresh_token});if(b)throw console.error("Set session error:",b),sessionStorage.removeItem(J4),sessionStorage.removeItem(yN),new Error("Failed to establish impersonation session")}else{const b=y.type||"recovery",{error:j}=await V.auth.verifyOtp({token_hash:y.token_hash,type:b});if(j)throw console.error("Verify OTP error:",j),sessionStorage.removeItem(J4),sessionStorage.removeItem(yN),new Error("Failed to establish impersonation session")}return r(!0),a(_),he.success(`Now viewing as ${_.name}`),window.location.href="/dashboard",!0}catch(m){return console.error("Impersonation error:",m),he.error(m.message||"Failed to impersonate user"),sessionStorage.removeItem(J4),sessionStorage.removeItem(yN),!1}finally{l(!1)}},c=async()=>{l(!0);try{const d=sessionStorage.getItem(J4);if(!d){await V.auth.signOut(),window.location.href="/auth";return}const h=JSON.parse(d);await V.auth.signOut();const{error:m}=await V.auth.setSession({access_token:h.access_token,refresh_token:h.refresh_token});if(sessionStorage.removeItem(J4),sessionStorage.removeItem(yN),m){console.error("Failed to restore admin session:",m),he.error("Admin session expired, please sign in again"),window.location.href="/auth";return}r(!1),a(null),he.success("Returned to your account");const p=sessionStorage.getItem(W1e)||"/admin/members";sessionStorage.removeItem(W1e),window.location.href=p}catch(d){console.error("Stop impersonation error:",d),he.error("Failed to restore admin session"),sessionStorage.removeItem(J4),sessionStorage.removeItem(yN),window.location.href="/auth"}finally{l(!1)}};return e.jsx(vet.Provider,{value:{isImpersonating:t,impersonatedUser:n,startImpersonation:o,stopImpersonation:c,isLoading:i},children:s})},age=()=>{const s=S.useContext(vet);if(s===void 0)throw new Error("useImpersonation must be used within an ImpersonationProvider");return s},KP=zA("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-full px-8",icon:"h-10 w-10"}},defaultVariants:{variant:"default",size:"default"}}),H=S.forwardRef(({className:s,variant:t,size:r,asChild:n=!1,...a},i)=>{const l=n?p3e:"button";return e.jsx(l,{className:Ft(KP({variant:t,size:r,className:s})),ref:i,...a})});H.displayName="Button";const uMt=()=>{const{isImpersonating:s,impersonatedUser:t,stopImpersonation:r,isLoading:n}=age();return!s||!t?null:e.jsx("div",{className:"fixed top-0 left-0 right-0 z-[100] bg-amber-500 text-amber-950 px-4 py-2 shadow-lg",children:e.jsxs("div",{className:"container mx-auto flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(uu,{className:"h-5 w-5 flex-shrink-0"}),e.jsxs("span",{className:"font-medium text-sm md:text-base",children:[e.jsx("span",{className:"hidden sm:inline",children:"You are viewing as "}),e.jsx("strong",{children:t.name}),e.jsxs("span",{className:"hidden md:inline text-amber-800",children:[" (",t.email,")"]})]})]}),e.jsx(H,{size:"sm",variant:"secondary",onClick:r,disabled:n,className:"bg-amber-100 hover:bg-amber-200 text-amber-950 border-0",children:n?e.jsx(is,{className:"h-4 w-4 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(Rr,{className:"h-4 w-4 mr-1"}),e.jsx("span",{className:"hidden sm:inline",children:"Exit Impersonation"}),e.jsx("span",{className:"sm:hidden",children:"Exit"})]})})]})})},bet=S.createContext(void 0),o6="levelup_acting_as",FU="levelup_acting_as_self",hMt=({children:s})=>{const{user:t}=Ms(),[r,n]=S.useState(!1),[a,i]=S.useState([]),[l,o]=S.useState(null),[c,d]=S.useState({}),[h,m]=S.useState(!0),[p,x]=S.useState(()=>sessionStorage.getItem(FU)==="true");S.useEffect(()=>{if(!(t!=null&&t.id)){n(!1),i([]),o(null),d({}),m(!1);return}(async()=>{m(!0);try{const{data:T}=await V.rpc("has_role",{_user_id:t.id,_role:"assistant"});if(!T){n(!1),i([]),o(null),d({}),m(!1);return}n(!0);const{data:E,error:A}=await V.from("agent_assistant_assignments").select("agent_id, permissions").eq("assistant_id",t.id);if(A||!E||E.length===0){i([]),m(!1);return}const D=E.map(O=>O.agent_id),{data:R}=await V.from("profiles").select("id, name, email, avatar_url").in("id",D),z=(R||[]).map(O=>({id:O.id,name:O.name||O.email||"Unknown",email:O.email||"",avatar_url:O.avatar_url}));if(i(z),sessionStorage.getItem(FU)==="true")x(!0),o(null),d({});else{const O=sessionStorage.getItem(o6);if(O){const $=z.find(ee=>ee.id===O);if($){o($);const ee=E.find(Z=>Z.agent_id===O);d((ee==null?void 0:ee.permissions)||{})}else if(z.length>0){o(z[0]);const ee=E.find(Z=>Z.agent_id===z[0].id);d((ee==null?void 0:ee.permissions)||{}),sessionStorage.setItem(o6,z[0].id)}}else if(z.length>0){o(z[0]);const $=E.find(ee=>ee.agent_id===z[0].id);d(($==null?void 0:$.permissions)||{}),sessionStorage.setItem(o6,z[0].id)}}}catch(T){console.error("Error loading assistant data:",T)}finally{m(!1)}})()},[t==null?void 0:t.id]);const y=k=>{o(k),x(!1),sessionStorage.removeItem(FU),k?(sessionStorage.setItem(o6,k.id),V.from("agent_assistant_assignments").select("permissions").eq("assistant_id",(t==null?void 0:t.id)||"").eq("agent_id",k.id).single().then(({data:T})=>{d((T==null?void 0:T.permissions)||{})})):(sessionStorage.removeItem(o6),d({}))},_=()=>{x(!0),o(null),d({}),sessionStorage.setItem(FU,"true"),sessionStorage.removeItem(o6)},b=k=>!r||p?!0:c[k]===!0,j=r&&l&&!p?l.id:(t==null?void 0:t.id)||null;return e.jsx(bet.Provider,{value:{isAssistant:r,assignedAgents:a,actingAsAgent:l,setActingAsAgent:y,effectiveUserId:j,permissions:c,hasPermission:b,isLoading:h,isActingAsSelf:p,setActingAsSelf:_},children:s})},V3e=()=>{const s=S.useContext(bet);if(s===void 0)throw new Error("useActingAs must be used within an ActingAsProvider");return s},ba=()=>{const{effectiveUserId:s}=V3e();return s};var _et={exports:{}},wet={};/** * @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 YP=S;function mMt(s,t){return s===t&&(s!==0||1/s===1/t)||s!==s&&t!==t}var fMt=typeof Object.is=="function"?Object.is:mMt,pMt=YP.useState,gMt=YP.useEffect,xMt=YP.useLayoutEffect,yMt=YP.useDebugValue;function vMt(s,t){var r=t(),n=pMt({inst:{value:r,getSnapshot:t}}),a=n[0].inst,i=n[1];return xMt(function(){a.value=r,a.getSnapshot=t,K1e(a)&&i({inst:a})},[s,r,t]),gMt(function(){return K1e(a)&&i({inst:a}),s(function(){K1e(a)&&i({inst:a})})},[s]),yMt(r),r}function K1e(s){var t=s.getSnapshot;s=s.value;try{var r=t();return!fMt(s,r)}catch{return!0}}function bMt(s,t){return t()}var _Mt=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?bMt:vMt;wet.useSyncExternalStore=YP.useSyncExternalStore!==void 0?YP.useSyncExternalStore:_Mt;_et.exports=wet;var wMt=_et.exports;function jMt(){return wMt.useSyncExternalStore(NMt,()=>!0,()=>!1)}function NMt(){return()=>{}}var H3e="Avatar",[kMt,NZs]=_u(H3e),[SMt,jet]=kMt(H3e),Net=S.forwardRef((s,t)=>{const{__scopeAvatar:r,...n}=s,[a,i]=S.useState("idle");return e.jsx(SMt,{scope:r,imageLoadingStatus:a,onImageLoadingStatusChange:i,children:e.jsx(Vn.span,{...n,ref:t})})});Net.displayName=H3e;var ket="AvatarImage",Cet=S.forwardRef((s,t)=>{const{__scopeAvatar:r,src:n,onLoadingStatusChange:a=()=>{},...i}=s,l=jet(ket,r),o=CMt(n,i),c=Uu(d=>{a(d),l.onImageLoadingStatusChange(d)});return Ku(()=>{o!=="idle"&&c(o)},[o,c]),o==="loaded"?e.jsx(Vn.img,{...i,ref:t,src:n}):null});Cet.displayName=ket;var Tet="AvatarFallback",Eet=S.forwardRef((s,t)=>{const{__scopeAvatar:r,delayMs:n,...a}=s,i=jet(Tet,r),[l,o]=S.useState(n===void 0);return S.useEffect(()=>{if(n!==void 0){const c=window.setTimeout(()=>o(!0),n);return()=>window.clearTimeout(c)}},[n]),l&&i.imageLoadingStatus!=="loaded"?e.jsx(Vn.span,{...a,ref:t}):null});Eet.displayName=Tet;function NOe(s,t){return s?t?(s.src!==t&&(s.src=t),s.complete&&s.naturalWidth>0?"loaded":"loading"):"error":"idle"}function CMt(s,{referrerPolicy:t,crossOrigin:r}){const n=jMt(),a=S.useRef(null),i=n?(a.current||(a.current=new window.Image),a.current):null,[l,o]=S.useState(()=>NOe(i,s));return Ku(()=>{o(NOe(i,s))},[i,s]),Ku(()=>{const c=m=>()=>{o(m)};if(!i)return;const d=c("loaded"),h=c("error");return i.addEventListener("load",d),i.addEventListener("error",h),t&&(i.referrerPolicy=t),typeof r=="string"&&(i.crossOrigin=r),()=>{i.removeEventListener("load",d),i.removeEventListener("error",h)}},[i,r,t]),l}var Aet=Net,Met=Cet,Iet=Eet;const Un=S.forwardRef(({className:s,...t},r)=>e.jsx(Aet,{ref:r,className:Ft("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",s),...t}));Un.displayName=Aet.displayName;const Ka=S.forwardRef(({className:s,...t},r)=>e.jsx(Met,{ref:r,className:Ft("aspect-square h-full w-full",s),...t}));Ka.displayName=Met.displayName;const qn=S.forwardRef(({className:s,...t},r)=>e.jsx(Iet,{ref:r,className:Ft("flex h-full w-full items-center justify-center rounded-full bg-muted",s),...t}));qn.displayName=Iet.displayName;const TMt=zA("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 Xe({className:s,variant:t,...r}){return e.jsx("div",{className:Ft(TMt({variant:t}),s),...r})}var EMt=S.createContext(void 0);function RS(s){const t=S.useContext(EMt);return s||t||"ltr"}var Y1e=0;function ige(){S.useEffect(()=>{const s=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",s[0]??kOe()),document.body.insertAdjacentElement("beforeend",s[1]??kOe()),Y1e++,()=>{Y1e===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),Y1e--}},[])}function kOe(){const s=document.createElement("span");return s.setAttribute("data-radix-focus-guard",""),s.tabIndex=0,s.style.outline="none",s.style.opacity="0",s.style.position="fixed",s.style.pointerEvents="none",s}var Z1e="focusScope.autoFocusOnMount",X1e="focusScope.autoFocusOnUnmount",SOe={bubbles:!1,cancelable:!0},AMt="FocusScope",VB=S.forwardRef((s,t)=>{const{loop:r=!1,trapped:n=!1,onMountAutoFocus:a,onUnmountAutoFocus:i,...l}=s,[o,c]=S.useState(null),d=Uu(a),h=Uu(i),m=S.useRef(null),p=_i(t,_=>c(_)),x=S.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;S.useEffect(()=>{if(n){let _=function(T){if(x.paused||!o)return;const E=T.target;o.contains(E)?m.current=E:MN(m.current,{select:!0})},b=function(T){if(x.paused||!o)return;const E=T.relatedTarget;E!==null&&(o.contains(E)||MN(m.current,{select:!0}))},j=function(T){if(document.activeElement===document.body)for(const A of T)A.removedNodes.length>0&&MN(o)};document.addEventListener("focusin",_),document.addEventListener("focusout",b);const k=new MutationObserver(j);return o&&k.observe(o,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",_),document.removeEventListener("focusout",b),k.disconnect()}}},[n,o,x.paused]),S.useEffect(()=>{if(o){TOe.add(x);const _=document.activeElement;if(!o.contains(_)){const j=new CustomEvent(Z1e,SOe);o.addEventListener(Z1e,d),o.dispatchEvent(j),j.defaultPrevented||(MMt(RMt(Pet(o)),{select:!0}),document.activeElement===_&&MN(o))}return()=>{o.removeEventListener(Z1e,d),setTimeout(()=>{const j=new CustomEvent(X1e,SOe);o.addEventListener(X1e,h),o.dispatchEvent(j),j.defaultPrevented||MN(_??document.body,{select:!0}),o.removeEventListener(X1e,h),TOe.remove(x)},0)}}},[o,d,h,x]);const y=S.useCallback(_=>{if(!r&&!n||x.paused)return;const b=_.key==="Tab"&&!_.altKey&&!_.ctrlKey&&!_.metaKey,j=document.activeElement;if(b&&j){const k=_.currentTarget,[T,E]=IMt(k);T&&E?!_.shiftKey&&j===E?(_.preventDefault(),r&&MN(T,{select:!0})):_.shiftKey&&j===T&&(_.preventDefault(),r&&MN(E,{select:!0})):j===k&&_.preventDefault()}},[r,n,x.paused]);return e.jsx(Vn.div,{tabIndex:-1,...l,ref:p,onKeyDown:y})});VB.displayName=AMt;function MMt(s,{select:t=!1}={}){const r=document.activeElement;for(const n of s)if(MN(n,{select:t}),document.activeElement!==r)return}function IMt(s){const t=Pet(s),r=COe(t,s),n=COe(t.reverse(),s);return[r,n]}function Pet(s){const t=[],r=document.createTreeWalker(s,NodeFilter.SHOW_ELEMENT,{acceptNode:n=>{const a=n.tagName==="INPUT"&&n.type==="hidden";return n.disabled||n.hidden||a?NodeFilter.FILTER_SKIP:n.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;r.nextNode();)t.push(r.currentNode);return t}function COe(s,t){for(const r of s)if(!PMt(r,{upTo:t}))return r}function PMt(s,{upTo:t}){if(getComputedStyle(s).visibility==="hidden")return!0;for(;s;){if(t!==void 0&&s===t)return!1;if(getComputedStyle(s).display==="none")return!0;s=s.parentElement}return!1}function LMt(s){return s instanceof HTMLInputElement&&"select"in s}function MN(s,{select:t=!1}={}){if(s&&s.focus){const r=document.activeElement;s.focus({preventScroll:!0}),s!==r&&LMt(s)&&t&&s.select()}}var TOe=DMt();function DMt(){let s=[];return{add(t){const r=s[0];t!==r&&(r==null||r.pause()),s=EOe(s,t),s.unshift(t)},remove(t){var r;s=EOe(s,t),(r=s[0])==null||r.resume()}}}function EOe(s,t){const r=[...s],n=r.indexOf(t);return n!==-1&&r.splice(n,1),r}function RMt(s){return s.filter(t=>t.tagName!=="A")}var Q1e="rovingFocusGroup.onEntryFocus",OMt={bubbles:!1,cancelable:!0},HB="RovingFocusGroup",[Hje,Let,FMt]=DB(HB),[BMt,OS]=_u(HB,[FMt]),[zMt,$Mt]=BMt(HB),Det=S.forwardRef((s,t)=>e.jsx(Hje.Provider,{scope:s.__scopeRovingFocusGroup,children:e.jsx(Hje.Slot,{scope:s.__scopeRovingFocusGroup,children:e.jsx(UMt,{...s,ref:t})})}));Det.displayName=HB;var UMt=S.forwardRef((s,t)=>{const{__scopeRovingFocusGroup:r,orientation:n,loop:a=!1,dir:i,currentTabStopId:l,defaultCurrentTabStopId:o,onCurrentTabStopIdChange:c,onEntryFocus:d,preventScrollOnEntryFocus:h=!1,...m}=s,p=S.useRef(null),x=_i(t,p),y=RS(i),[_,b]=af({prop:l,defaultProp:o??null,onChange:c,caller:HB}),[j,k]=S.useState(!1),T=Uu(d),E=Let(r),A=S.useRef(!1),[D,R]=S.useState(0);return S.useEffect(()=>{const z=p.current;if(z)return z.addEventListener(Q1e,T),()=>z.removeEventListener(Q1e,T)},[T]),e.jsx(zMt,{scope:r,orientation:n,dir:y,loop:a,currentTabStopId:_,onItemFocus:S.useCallback(z=>b(z),[b]),onItemShiftTab:S.useCallback(()=>k(!0),[]),onFocusableItemAdd:S.useCallback(()=>R(z=>z+1),[]),onFocusableItemRemove:S.useCallback(()=>R(z=>z-1),[]),children:e.jsx(Vn.div,{tabIndex:j||D===0?-1:0,"data-orientation":n,...m,ref:x,style:{outline:"none",...s.style},onMouseDown:an(s.onMouseDown,()=>{A.current=!0}),onFocus:an(s.onFocus,z=>{const O=!A.current;if(z.target===z.currentTarget&&O&&!j){const $=new CustomEvent(Q1e,OMt);if(z.currentTarget.dispatchEvent($),!$.defaultPrevented){const ee=E().filter(ie=>ie.focusable),Z=ee.find(ie=>ie.active),J=ee.find(ie=>ie.id===_),re=[Z,J,...ee].filter(Boolean).map(ie=>ie.ref.current);Fet(re,h)}}A.current=!1}),onBlur:an(s.onBlur,()=>k(!1))})})}),Ret="RovingFocusGroupItem",Oet=S.forwardRef((s,t)=>{const{__scopeRovingFocusGroup:r,focusable:n=!0,active:a=!1,tabStopId:i,children:l,...o}=s,c=vm(),d=i||c,h=$Mt(Ret,r),m=h.currentTabStopId===d,p=Let(r),{onFocusableItemAdd:x,onFocusableItemRemove:y,currentTabStopId:_}=h;return S.useEffect(()=>{if(n)return x(),()=>y()},[n,x,y]),e.jsx(Hje.ItemSlot,{scope:r,id:d,focusable:n,active:a,children:e.jsx(Vn.span,{tabIndex:m?0:-1,"data-orientation":h.orientation,...o,ref:t,onMouseDown:an(s.onMouseDown,b=>{n?h.onItemFocus(d):b.preventDefault()}),onFocus:an(s.onFocus,()=>h.onItemFocus(d)),onKeyDown:an(s.onKeyDown,b=>{if(b.key==="Tab"&&b.shiftKey){h.onItemShiftTab();return}if(b.target!==b.currentTarget)return;const j=HMt(b,h.orientation,h.dir);if(j!==void 0){if(b.metaKey||b.ctrlKey||b.altKey||b.shiftKey)return;b.preventDefault();let T=p().filter(E=>E.focusable).map(E=>E.ref.current);if(j==="last")T.reverse();else if(j==="prev"||j==="next"){j==="prev"&&T.reverse();const E=T.indexOf(b.currentTarget);T=h.loop?GMt(T,E+1):T.slice(E+1)}setTimeout(()=>Fet(T))}}),children:typeof l=="function"?l({isCurrentTabStop:m,hasTabStop:_!=null}):l})})});Oet.displayName=Ret;var qMt={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function VMt(s,t){return t!=="rtl"?s:s==="ArrowLeft"?"ArrowRight":s==="ArrowRight"?"ArrowLeft":s}function HMt(s,t,r){const n=VMt(s.key,r);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(n))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(n)))return qMt[n]}function Fet(s,t=!1){const r=document.activeElement;for(const n of s)if(n===r||(n.focus({preventScroll:t}),document.activeElement!==r))return}function GMt(s,t){return s.map((r,n)=>s[(t+n)%s.length])}var oge=Det,lge=Oet,WMt=function(s){if(typeof document>"u")return null;var t=Array.isArray(s)?s[0]:s;return t.ownerDocument.body},l6=new WeakMap,BU=new WeakMap,zU={},J1e=0,Bet=function(s){return s&&(s.host||Bet(s.parentNode))},KMt=function(s,t){return t.map(function(r){if(s.contains(r))return r;var n=Bet(r);return n&&s.contains(n)?n:(console.error("aria-hidden",r,"in not contained inside",s,". Doing nothing"),null)}).filter(function(r){return!!r})},YMt=function(s,t,r,n){var a=KMt(t,Array.isArray(s)?s:[s]);zU[r]||(zU[r]=new WeakMap);var i=zU[r],l=[],o=new Set,c=new Set(a),d=function(m){!m||o.has(m)||(o.add(m),d(m.parentNode))};a.forEach(d);var h=function(m){!m||c.has(m)||Array.prototype.forEach.call(m.children,function(p){if(o.has(p))h(p);else try{var x=p.getAttribute(n),y=x!==null&&x!=="false",_=(l6.get(p)||0)+1,b=(i.get(p)||0)+1;l6.set(p,_),i.set(p,b),l.push(p),_===1&&y&&BU.set(p,!0),b===1&&p.setAttribute(r,"true"),y||p.setAttribute(n,"true")}catch(j){console.error("aria-hidden: cannot operate on ",p,j)}})};return h(t),o.clear(),J1e++,function(){l.forEach(function(m){var p=l6.get(m)-1,x=i.get(m)-1;l6.set(m,p),i.set(m,x),p||(BU.has(m)||m.removeAttribute(n),BU.delete(m)),x||m.removeAttribute(r)}),J1e--,J1e||(l6=new WeakMap,l6=new WeakMap,BU=new WeakMap,zU={})}},cge=function(s,t,r){r===void 0&&(r="data-aria-hidden");var n=Array.from(Array.isArray(s)?s:[s]),a=WMt(s);return a?(n.push.apply(n,Array.from(a.querySelectorAll("[aria-live]"))),YMt(n,a,r,"aria-hidden")):function(){return null}},Xb=function(){return Xb=Object.assign||function(t){for(var r,n=1,a=arguments.length;n"u")return h6t;var t=m6t(s),r=document.documentElement.clientWidth,n=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,n-r+t[2]-t[0])}},p6t=qet(),aP="data-scroll-locked",g6t=function(s,t,r,n){var a=s.left,i=s.top,l=s.right,o=s.gap;return r===void 0&&(r="margin"),` .`.concat(XMt,` { overflow: hidden `).concat(n,`; padding-right: `).concat(o,"px ").concat(n,`; } body[`).concat(aP,`] { overflow: hidden `).concat(n,`; overscroll-behavior: contain; `).concat([t&&"position: relative ".concat(n,";"),r==="margin"&&` padding-left: `.concat(a,`px; padding-top: `).concat(i,`px; padding-right: `).concat(l,`px; margin-left:0; margin-top:0; margin-right: `).concat(o,"px ").concat(n,`; `),r==="padding"&&"padding-right: ".concat(o,"px ").concat(n,";")].filter(Boolean).join(""),` } .`).concat(cue,` { right: `).concat(o,"px ").concat(n,`; } .`).concat(due,` { margin-right: `).concat(o,"px ").concat(n,`; } .`).concat(cue," .").concat(cue,` { right: 0 `).concat(n,`; } .`).concat(due," .").concat(due,` { margin-right: 0 `).concat(n,`; } body[`).concat(aP,`] { `).concat(QMt,": ").concat(o,`px; } `)},MOe=function(){var s=parseInt(document.body.getAttribute(aP)||"0",10);return isFinite(s)?s:0},x6t=function(){S.useEffect(function(){return document.body.setAttribute(aP,(MOe()+1).toString()),function(){var s=MOe()-1;s<=0?document.body.removeAttribute(aP):document.body.setAttribute(aP,s.toString())}},[])},y6t=function(s){var t=s.noRelative,r=s.noImportant,n=s.gapMode,a=n===void 0?"margin":n;x6t();var i=S.useMemo(function(){return f6t(a)},[a]);return S.createElement(p6t,{styles:g6t(i,!t,a,r?"":"!important")})},Gje=!1;if(typeof window<"u")try{var $U=Object.defineProperty({},"passive",{get:function(){return Gje=!0,!0}});window.addEventListener("test",$U,$U),window.removeEventListener("test",$U,$U)}catch{Gje=!1}var c6=Gje?{passive:!1}:!1,v6t=function(s){return s.tagName==="TEXTAREA"},Vet=function(s,t){if(!(s instanceof Element))return!1;var r=window.getComputedStyle(s);return r[t]!=="hidden"&&!(r.overflowY===r.overflowX&&!v6t(s)&&r[t]==="visible")},b6t=function(s){return Vet(s,"overflowY")},_6t=function(s){return Vet(s,"overflowX")},IOe=function(s,t){var r=t.ownerDocument,n=t;do{typeof ShadowRoot<"u"&&n instanceof ShadowRoot&&(n=n.host);var a=Het(s,n);if(a){var i=Get(s,n),l=i[1],o=i[2];if(l>o)return!0}n=n.parentNode}while(n&&n!==r.body);return!1},w6t=function(s){var t=s.scrollTop,r=s.scrollHeight,n=s.clientHeight;return[t,r,n]},j6t=function(s){var t=s.scrollLeft,r=s.scrollWidth,n=s.clientWidth;return[t,r,n]},Het=function(s,t){return s==="v"?b6t(t):_6t(t)},Get=function(s,t){return s==="v"?w6t(t):j6t(t)},N6t=function(s,t){return s==="h"&&t==="rtl"?-1:1},k6t=function(s,t,r,n,a){var i=N6t(s,window.getComputedStyle(t).direction),l=i*n,o=r.target,c=t.contains(o),d=!1,h=l>0,m=0,p=0;do{if(!o)break;var x=Get(s,o),y=x[0],_=x[1],b=x[2],j=_-b-i*y;(y||j)&&Het(s,o)&&(m+=j,p+=y);var k=o.parentNode;o=k&&k.nodeType===Node.DOCUMENT_FRAGMENT_NODE?k.host:k}while(!c&&o!==document.body||c&&(t.contains(o)||t===o));return(h&&(Math.abs(m)<1||!a)||!h&&(Math.abs(p)<1||!a))&&(d=!0),d},UU=function(s){return"changedTouches"in s?[s.changedTouches[0].clientX,s.changedTouches[0].clientY]:[0,0]},POe=function(s){return[s.deltaX,s.deltaY]},LOe=function(s){return s&&"current"in s?s.current:s},S6t=function(s,t){return s[0]===t[0]&&s[1]===t[1]},C6t=function(s){return` .block-interactivity-`.concat(s,` {pointer-events: none;} .allow-interactivity-`).concat(s,` {pointer-events: all;} `)},T6t=0,d6=[];function E6t(s){var t=S.useRef([]),r=S.useRef([0,0]),n=S.useRef(),a=S.useState(T6t++)[0],i=S.useState(qet)[0],l=S.useRef(s);S.useEffect(function(){l.current=s},[s]),S.useEffect(function(){if(s.inert){document.body.classList.add("block-interactivity-".concat(a));var _=ZMt([s.lockRef.current],(s.shards||[]).map(LOe),!0).filter(Boolean);return _.forEach(function(b){return b.classList.add("allow-interactivity-".concat(a))}),function(){document.body.classList.remove("block-interactivity-".concat(a)),_.forEach(function(b){return b.classList.remove("allow-interactivity-".concat(a))})}}},[s.inert,s.lockRef.current,s.shards]);var o=S.useCallback(function(_,b){if("touches"in _&&_.touches.length===2||_.type==="wheel"&&_.ctrlKey)return!l.current.allowPinchZoom;var j=UU(_),k=r.current,T="deltaX"in _?_.deltaX:k[0]-j[0],E="deltaY"in _?_.deltaY:k[1]-j[1],A,D=_.target,R=Math.abs(T)>Math.abs(E)?"h":"v";if("touches"in _&&R==="h"&&D.type==="range")return!1;var z=IOe(R,D);if(!z)return!0;if(z?A=R:(A=R==="v"?"h":"v",z=IOe(R,D)),!z)return!1;if(!n.current&&"changedTouches"in _&&(T||E)&&(n.current=A),!A)return!0;var O=n.current||A;return k6t(O,b,_,O==="h"?T:E,!0)},[]),c=S.useCallback(function(_){var b=_;if(!(!d6.length||d6[d6.length-1]!==i)){var j="deltaY"in b?POe(b):UU(b),k=t.current.filter(function(A){return A.name===b.type&&(A.target===b.target||b.target===A.shadowParent)&&S6t(A.delta,j)})[0];if(k&&k.should){b.cancelable&&b.preventDefault();return}if(!k){var T=(l.current.shards||[]).map(LOe).filter(Boolean).filter(function(A){return A.contains(b.target)}),E=T.length>0?o(b,T[0]):!l.current.noIsolation;E&&b.cancelable&&b.preventDefault()}}},[]),d=S.useCallback(function(_,b,j,k){var T={name:_,delta:b,target:j,should:k,shadowParent:A6t(j)};t.current.push(T),setTimeout(function(){t.current=t.current.filter(function(E){return E!==T})},1)},[]),h=S.useCallback(function(_){r.current=UU(_),n.current=void 0},[]),m=S.useCallback(function(_){d(_.type,POe(_),_.target,o(_,s.lockRef.current))},[]),p=S.useCallback(function(_){d(_.type,UU(_),_.target,o(_,s.lockRef.current))},[]);S.useEffect(function(){return d6.push(i),s.setCallbacks({onScrollCapture:m,onWheelCapture:m,onTouchMoveCapture:p}),document.addEventListener("wheel",c,c6),document.addEventListener("touchmove",c,c6),document.addEventListener("touchstart",h,c6),function(){d6=d6.filter(function(_){return _!==i}),document.removeEventListener("wheel",c,c6),document.removeEventListener("touchmove",c,c6),document.removeEventListener("touchstart",h,c6)}},[]);var x=s.removeScrollBar,y=s.inert;return S.createElement(S.Fragment,null,y?S.createElement(i,{styles:C6t(a)}):null,x?S.createElement(y6t,{noRelative:s.noRelative,gapMode:s.gapMode}):null)}function A6t(s){for(var t=null;s!==null;)s instanceof ShadowRoot&&(t=s.host,s=s.host),s=s.parentNode;return t}const M6t=a6t(Uet,E6t);var GB=S.forwardRef(function(s,t){return S.createElement(dge,Xb({},s,{ref:t,sideCar:M6t}))});GB.classNames=dge.classNames;var Wje=["Enter"," "],I6t=["ArrowDown","PageUp","Home"],Wet=["ArrowUp","PageDown","End"],P6t=[...I6t,...Wet],L6t={ltr:[...Wje,"ArrowRight"],rtl:[...Wje,"ArrowLeft"]},D6t={ltr:["ArrowLeft"],rtl:["ArrowRight"]},WB="Menu",[i9,R6t,O6t]=DB(WB),[UA,Ket]=_u(WB,[O6t,q_,OS]),uge=q_(),Yet=OS(),[F6t,qA]=UA(WB),[B6t,KB]=UA(WB),Zet=s=>{const{__scopeMenu:t,open:r=!1,children:n,dir:a,onOpenChange:i,modal:l=!0}=s,o=uge(t),[c,d]=S.useState(null),h=S.useRef(!1),m=Uu(i),p=RS(a);return S.useEffect(()=>{const x=()=>{h.current=!0,document.addEventListener("pointerdown",y,{capture:!0,once:!0}),document.addEventListener("pointermove",y,{capture:!0,once:!0})},y=()=>h.current=!1;return document.addEventListener("keydown",x,{capture:!0}),()=>{document.removeEventListener("keydown",x,{capture:!0}),document.removeEventListener("pointerdown",y,{capture:!0}),document.removeEventListener("pointermove",y,{capture:!0})}},[]),e.jsx(BB,{...o,children:e.jsx(F6t,{scope:t,open:r,onOpenChange:m,content:c,onContentChange:d,children:e.jsx(B6t,{scope:t,onClose:S.useCallback(()=>m(!1),[m]),isUsingKeyboardRef:h,dir:p,modal:l,children:n})})})};Zet.displayName=WB;var z6t="MenuAnchor",G3e=S.forwardRef((s,t)=>{const{__scopeMenu:r,...n}=s,a=uge(r);return e.jsx(i8,{...a,...n,ref:t})});G3e.displayName=z6t;var W3e="MenuPortal",[$6t,Xet]=UA(W3e,{forceMount:void 0}),Qet=s=>{const{__scopeMenu:t,forceMount:r,children:n,container:a}=s,i=qA(W3e,t);return e.jsx($6t,{scope:t,forceMount:r,children:e.jsx(vh,{present:r||i.open,children:e.jsx(s8,{asChild:!0,container:a,children:n})})})};Qet.displayName=W3e;var Gy="MenuContent",[U6t,K3e]=UA(Gy),Jet=S.forwardRef((s,t)=>{const r=Xet(Gy,s.__scopeMenu),{forceMount:n=r.forceMount,...a}=s,i=qA(Gy,s.__scopeMenu),l=KB(Gy,s.__scopeMenu);return e.jsx(i9.Provider,{scope:s.__scopeMenu,children:e.jsx(vh,{present:n||i.open,children:e.jsx(i9.Slot,{scope:s.__scopeMenu,children:l.modal?e.jsx(q6t,{...a,ref:t}):e.jsx(V6t,{...a,ref:t})})})})}),q6t=S.forwardRef((s,t)=>{const r=qA(Gy,s.__scopeMenu),n=S.useRef(null),a=_i(t,n);return S.useEffect(()=>{const i=n.current;if(i)return cge(i)},[]),e.jsx(Y3e,{...s,ref:a,trapFocus:r.open,disableOutsidePointerEvents:r.open,disableOutsideScroll:!0,onFocusOutside:an(s.onFocusOutside,i=>i.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>r.onOpenChange(!1)})}),V6t=S.forwardRef((s,t)=>{const r=qA(Gy,s.__scopeMenu);return e.jsx(Y3e,{...s,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>r.onOpenChange(!1)})}),H6t=mS("MenuContent.ScrollLock"),Y3e=S.forwardRef((s,t)=>{const{__scopeMenu:r,loop:n=!1,trapFocus:a,onOpenAutoFocus:i,onCloseAutoFocus:l,disableOutsidePointerEvents:o,onEntryFocus:c,onEscapeKeyDown:d,onPointerDownOutside:h,onFocusOutside:m,onInteractOutside:p,onDismiss:x,disableOutsideScroll:y,..._}=s,b=qA(Gy,r),j=KB(Gy,r),k=uge(r),T=Yet(r),E=R6t(r),[A,D]=S.useState(null),R=S.useRef(null),z=_i(t,R,b.onContentChange),O=S.useRef(0),$=S.useRef(""),ee=S.useRef(0),Z=S.useRef(null),J=S.useRef("right"),K=S.useRef(0),re=y?GB:S.Fragment,ie=y?{as:H6t,allowPinchZoom:!0}:void 0,ce=le=>{var Me,ze;const be=$.current+le,fe=E().filter(Pe=>!Pe.disabled),je=document.activeElement,ve=(Me=fe.find(Pe=>Pe.ref.current===je))==null?void 0:Me.textValue,We=fe.map(Pe=>Pe.textValue),Ve=rIt(We,be,ve),Le=(ze=fe.find(Pe=>Pe.textValue===Ve))==null?void 0:ze.ref.current;(function Pe(Ie){$.current=Ie,window.clearTimeout(O.current),Ie!==""&&(O.current=window.setTimeout(()=>Pe(""),1e3))})(be),Le&&setTimeout(()=>Le.focus())};S.useEffect(()=>()=>window.clearTimeout(O.current),[]),ige();const ne=S.useCallback(le=>{var fe,je;return J.current===((fe=Z.current)==null?void 0:fe.side)&&aIt(le,(je=Z.current)==null?void 0:je.area)},[]);return e.jsx(U6t,{scope:r,searchRef:$,onItemEnter:S.useCallback(le=>{ne(le)&&le.preventDefault()},[ne]),onItemLeave:S.useCallback(le=>{var be;ne(le)||((be=R.current)==null||be.focus(),D(null))},[ne]),onTriggerLeave:S.useCallback(le=>{ne(le)&&le.preventDefault()},[ne]),pointerGraceTimerRef:ee,onPointerGraceIntentChange:S.useCallback(le=>{Z.current=le},[]),children:e.jsx(re,{...ie,children:e.jsx(VB,{asChild:!0,trapped:a,onMountAutoFocus:an(i,le=>{var be;le.preventDefault(),(be=R.current)==null||be.focus({preventScroll:!0})}),onUnmountAutoFocus:l,children:e.jsx(PS,{asChild:!0,disableOutsidePointerEvents:o,onEscapeKeyDown:d,onPointerDownOutside:h,onFocusOutside:m,onInteractOutside:p,onDismiss:x,children:e.jsx(oge,{asChild:!0,...T,dir:j.dir,orientation:"vertical",loop:n,currentTabStopId:A,onCurrentTabStopIdChange:D,onEntryFocus:an(c,le=>{j.isUsingKeyboardRef.current||le.preventDefault()}),preventScrollOnEntryFocus:!0,children:e.jsx(zB,{role:"menu","aria-orientation":"vertical","data-state":ptt(b.open),"data-radix-menu-content":"",dir:j.dir,...k,..._,ref:z,style:{outline:"none",..._.style},onKeyDown:an(_.onKeyDown,le=>{const fe=le.target.closest("[data-radix-menu-content]")===le.currentTarget,je=le.ctrlKey||le.altKey||le.metaKey,ve=le.key.length===1;fe&&(le.key==="Tab"&&le.preventDefault(),!je&&ve&&ce(le.key));const We=R.current;if(le.target!==We||!P6t.includes(le.key))return;le.preventDefault();const Le=E().filter(Me=>!Me.disabled).map(Me=>Me.ref.current);Wet.includes(le.key)&&Le.reverse(),tIt(Le)}),onBlur:an(s.onBlur,le=>{le.currentTarget.contains(le.target)||(window.clearTimeout(O.current),$.current="")}),onPointerMove:an(s.onPointerMove,o9(le=>{const be=le.target,fe=K.current!==le.clientX;if(le.currentTarget.contains(be)&&fe){const je=le.clientX>K.current?"right":"left";J.current=je,K.current=le.clientX}}))})})})})})})});Jet.displayName=Gy;var G6t="MenuGroup",Z3e=S.forwardRef((s,t)=>{const{__scopeMenu:r,...n}=s;return e.jsx(Vn.div,{role:"group",...n,ref:t})});Z3e.displayName=G6t;var W6t="MenuLabel",ett=S.forwardRef((s,t)=>{const{__scopeMenu:r,...n}=s;return e.jsx(Vn.div,{...n,ref:t})});ett.displayName=W6t;var The="MenuItem",DOe="menu.itemSelect",hge=S.forwardRef((s,t)=>{const{disabled:r=!1,onSelect:n,...a}=s,i=S.useRef(null),l=KB(The,s.__scopeMenu),o=K3e(The,s.__scopeMenu),c=_i(t,i),d=S.useRef(!1),h=()=>{const m=i.current;if(!r&&m){const p=new CustomEvent(DOe,{bubbles:!0,cancelable:!0});m.addEventListener(DOe,x=>n==null?void 0:n(x),{once:!0}),g3e(m,p),p.defaultPrevented?d.current=!1:l.onClose()}};return e.jsx(ttt,{...a,ref:c,disabled:r,onClick:an(s.onClick,h),onPointerDown:m=>{var p;(p=s.onPointerDown)==null||p.call(s,m),d.current=!0},onPointerUp:an(s.onPointerUp,m=>{var p;d.current||(p=m.currentTarget)==null||p.click()}),onKeyDown:an(s.onKeyDown,m=>{const p=o.searchRef.current!=="";r||p&&m.key===" "||Wje.includes(m.key)&&(m.currentTarget.click(),m.preventDefault())})})});hge.displayName=The;var ttt=S.forwardRef((s,t)=>{const{__scopeMenu:r,disabled:n=!1,textValue:a,...i}=s,l=K3e(The,r),o=Yet(r),c=S.useRef(null),d=_i(t,c),[h,m]=S.useState(!1),[p,x]=S.useState("");return S.useEffect(()=>{const y=c.current;y&&x((y.textContent??"").trim())},[i.children]),e.jsx(i9.ItemSlot,{scope:r,disabled:n,textValue:a??p,children:e.jsx(lge,{asChild:!0,...o,focusable:!n,children:e.jsx(Vn.div,{role:"menuitem","data-highlighted":h?"":void 0,"aria-disabled":n||void 0,"data-disabled":n?"":void 0,...i,ref:d,onPointerMove:an(s.onPointerMove,o9(y=>{n?l.onItemLeave(y):(l.onItemEnter(y),y.defaultPrevented||y.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:an(s.onPointerLeave,o9(y=>l.onItemLeave(y))),onFocus:an(s.onFocus,()=>m(!0)),onBlur:an(s.onBlur,()=>m(!1))})})})}),K6t="MenuCheckboxItem",stt=S.forwardRef((s,t)=>{const{checked:r=!1,onCheckedChange:n,...a}=s;return e.jsx(ott,{scope:s.__scopeMenu,checked:r,children:e.jsx(hge,{role:"menuitemcheckbox","aria-checked":Ehe(r)?"mixed":r,...a,ref:t,"data-state":Q3e(r),onSelect:an(a.onSelect,()=>n==null?void 0:n(Ehe(r)?!0:!r),{checkForDefaultPrevented:!1})})})});stt.displayName=K6t;var rtt="MenuRadioGroup",[Y6t,Z6t]=UA(rtt,{value:void 0,onValueChange:()=>{}}),ntt=S.forwardRef((s,t)=>{const{value:r,onValueChange:n,...a}=s,i=Uu(n);return e.jsx(Y6t,{scope:s.__scopeMenu,value:r,onValueChange:i,children:e.jsx(Z3e,{...a,ref:t})})});ntt.displayName=rtt;var att="MenuRadioItem",itt=S.forwardRef((s,t)=>{const{value:r,...n}=s,a=Z6t(att,s.__scopeMenu),i=r===a.value;return e.jsx(ott,{scope:s.__scopeMenu,checked:i,children:e.jsx(hge,{role:"menuitemradio","aria-checked":i,...n,ref:t,"data-state":Q3e(i),onSelect:an(n.onSelect,()=>{var l;return(l=a.onValueChange)==null?void 0:l.call(a,r)},{checkForDefaultPrevented:!1})})})});itt.displayName=att;var X3e="MenuItemIndicator",[ott,X6t]=UA(X3e,{checked:!1}),ltt=S.forwardRef((s,t)=>{const{__scopeMenu:r,forceMount:n,...a}=s,i=X6t(X3e,r);return e.jsx(vh,{present:n||Ehe(i.checked)||i.checked===!0,children:e.jsx(Vn.span,{...a,ref:t,"data-state":Q3e(i.checked)})})});ltt.displayName=X3e;var Q6t="MenuSeparator",ctt=S.forwardRef((s,t)=>{const{__scopeMenu:r,...n}=s;return e.jsx(Vn.div,{role:"separator","aria-orientation":"horizontal",...n,ref:t})});ctt.displayName=Q6t;var J6t="MenuArrow",dtt=S.forwardRef((s,t)=>{const{__scopeMenu:r,...n}=s,a=uge(r);return e.jsx($B,{...a,...n,ref:t})});dtt.displayName=J6t;var eIt="MenuSub",[kZs,utt]=UA(eIt),fO="MenuSubTrigger",htt=S.forwardRef((s,t)=>{const r=qA(fO,s.__scopeMenu),n=KB(fO,s.__scopeMenu),a=utt(fO,s.__scopeMenu),i=K3e(fO,s.__scopeMenu),l=S.useRef(null),{pointerGraceTimerRef:o,onPointerGraceIntentChange:c}=i,d={__scopeMenu:s.__scopeMenu},h=S.useCallback(()=>{l.current&&window.clearTimeout(l.current),l.current=null},[]);return S.useEffect(()=>h,[h]),S.useEffect(()=>{const m=o.current;return()=>{window.clearTimeout(m),c(null)}},[o,c]),e.jsx(G3e,{asChild:!0,...d,children:e.jsx(ttt,{id:a.triggerId,"aria-haspopup":"menu","aria-expanded":r.open,"aria-controls":a.contentId,"data-state":ptt(r.open),...s,ref:nj(t,a.onTriggerChange),onClick:m=>{var p;(p=s.onClick)==null||p.call(s,m),!(s.disabled||m.defaultPrevented)&&(m.currentTarget.focus(),r.open||r.onOpenChange(!0))},onPointerMove:an(s.onPointerMove,o9(m=>{i.onItemEnter(m),!m.defaultPrevented&&!s.disabled&&!r.open&&!l.current&&(i.onPointerGraceIntentChange(null),l.current=window.setTimeout(()=>{r.onOpenChange(!0),h()},100))})),onPointerLeave:an(s.onPointerLeave,o9(m=>{var x,y;h();const p=(x=r.content)==null?void 0:x.getBoundingClientRect();if(p){const _=(y=r.content)==null?void 0:y.dataset.side,b=_==="right",j=b?-5:5,k=p[b?"left":"right"],T=p[b?"right":"left"];i.onPointerGraceIntentChange({area:[{x:m.clientX+j,y:m.clientY},{x:k,y:p.top},{x:T,y:p.top},{x:T,y:p.bottom},{x:k,y:p.bottom}],side:_}),window.clearTimeout(o.current),o.current=window.setTimeout(()=>i.onPointerGraceIntentChange(null),300)}else{if(i.onTriggerLeave(m),m.defaultPrevented)return;i.onPointerGraceIntentChange(null)}})),onKeyDown:an(s.onKeyDown,m=>{var x;const p=i.searchRef.current!=="";s.disabled||p&&m.key===" "||L6t[n.dir].includes(m.key)&&(r.onOpenChange(!0),(x=r.content)==null||x.focus(),m.preventDefault())})})})});htt.displayName=fO;var mtt="MenuSubContent",ftt=S.forwardRef((s,t)=>{const r=Xet(Gy,s.__scopeMenu),{forceMount:n=r.forceMount,...a}=s,i=qA(Gy,s.__scopeMenu),l=KB(Gy,s.__scopeMenu),o=utt(mtt,s.__scopeMenu),c=S.useRef(null),d=_i(t,c);return e.jsx(i9.Provider,{scope:s.__scopeMenu,children:e.jsx(vh,{present:n||i.open,children:e.jsx(i9.Slot,{scope:s.__scopeMenu,children:e.jsx(Y3e,{id:o.contentId,"aria-labelledby":o.triggerId,...a,ref:d,align:"start",side:l.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:h=>{var m;l.isUsingKeyboardRef.current&&((m=c.current)==null||m.focus()),h.preventDefault()},onCloseAutoFocus:h=>h.preventDefault(),onFocusOutside:an(s.onFocusOutside,h=>{h.target!==o.trigger&&i.onOpenChange(!1)}),onEscapeKeyDown:an(s.onEscapeKeyDown,h=>{l.onClose(),h.preventDefault()}),onKeyDown:an(s.onKeyDown,h=>{var x;const m=h.currentTarget.contains(h.target),p=D6t[l.dir].includes(h.key);m&&p&&(i.onOpenChange(!1),(x=o.trigger)==null||x.focus(),h.preventDefault())})})})})})});ftt.displayName=mtt;function ptt(s){return s?"open":"closed"}function Ehe(s){return s==="indeterminate"}function Q3e(s){return Ehe(s)?"indeterminate":s?"checked":"unchecked"}function tIt(s){const t=document.activeElement;for(const r of s)if(r===t||(r.focus(),document.activeElement!==t))return}function sIt(s,t){return s.map((r,n)=>s[(t+n)%s.length])}function rIt(s,t,r){const a=t.length>1&&Array.from(t).every(d=>d===t[0])?t[0]:t,i=r?s.indexOf(r):-1;let l=sIt(s,Math.max(i,0));a.length===1&&(l=l.filter(d=>d!==r));const c=l.find(d=>d.toLowerCase().startsWith(a.toLowerCase()));return c!==r?c:void 0}function nIt(s,t){const{x:r,y:n}=s;let a=!1;for(let i=0,l=t.length-1;in!=p>n&&r<(m-d)*(n-h)/(p-h)+d&&(a=!a)}return a}function aIt(s,t){if(!t)return!1;const r={x:s.clientX,y:s.clientY};return nIt(r,t)}function o9(s){return t=>t.pointerType==="mouse"?s(t):void 0}var iIt=Zet,oIt=G3e,lIt=Qet,cIt=Jet,dIt=Z3e,uIt=ett,hIt=hge,mIt=stt,fIt=ntt,pIt=itt,gIt=ltt,xIt=ctt,yIt=dtt,vIt=htt,bIt=ftt,mge="DropdownMenu",[_It,SZs]=_u(mge,[Ket]),Tg=Ket(),[wIt,gtt]=_It(mge),xtt=s=>{const{__scopeDropdownMenu:t,children:r,dir:n,open:a,defaultOpen:i,onOpenChange:l,modal:o=!0}=s,c=Tg(t),d=S.useRef(null),[h,m]=af({prop:a,defaultProp:i??!1,onChange:l,caller:mge});return e.jsx(wIt,{scope:t,triggerId:vm(),triggerRef:d,contentId:vm(),open:h,onOpenChange:m,onOpenToggle:S.useCallback(()=>m(p=>!p),[m]),modal:o,children:e.jsx(iIt,{...c,open:h,onOpenChange:m,dir:n,modal:o,children:r})})};xtt.displayName=mge;var ytt="DropdownMenuTrigger",vtt=S.forwardRef((s,t)=>{const{__scopeDropdownMenu:r,disabled:n=!1,...a}=s,i=gtt(ytt,r),l=Tg(r);return e.jsx(oIt,{asChild:!0,...l,children:e.jsx(Vn.button,{type:"button",id:i.triggerId,"aria-haspopup":"menu","aria-expanded":i.open,"aria-controls":i.open?i.contentId:void 0,"data-state":i.open?"open":"closed","data-disabled":n?"":void 0,disabled:n,...a,ref:nj(t,i.triggerRef),onPointerDown:an(s.onPointerDown,o=>{!n&&o.button===0&&o.ctrlKey===!1&&(i.onOpenToggle(),i.open||o.preventDefault())}),onKeyDown:an(s.onKeyDown,o=>{n||(["Enter"," "].includes(o.key)&&i.onOpenToggle(),o.key==="ArrowDown"&&i.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(o.key)&&o.preventDefault())})})})});vtt.displayName=ytt;var jIt="DropdownMenuPortal",btt=s=>{const{__scopeDropdownMenu:t,...r}=s,n=Tg(t);return e.jsx(lIt,{...n,...r})};btt.displayName=jIt;var _tt="DropdownMenuContent",wtt=S.forwardRef((s,t)=>{const{__scopeDropdownMenu:r,...n}=s,a=gtt(_tt,r),i=Tg(r),l=S.useRef(!1);return e.jsx(cIt,{id:a.contentId,"aria-labelledby":a.triggerId,...i,...n,ref:t,onCloseAutoFocus:an(s.onCloseAutoFocus,o=>{var c;l.current||(c=a.triggerRef.current)==null||c.focus(),l.current=!1,o.preventDefault()}),onInteractOutside:an(s.onInteractOutside,o=>{const c=o.detail.originalEvent,d=c.button===0&&c.ctrlKey===!0,h=c.button===2||d;(!a.modal||h)&&(l.current=!0)}),style:{...s.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)"}})});wtt.displayName=_tt;var NIt="DropdownMenuGroup",kIt=S.forwardRef((s,t)=>{const{__scopeDropdownMenu:r,...n}=s,a=Tg(r);return e.jsx(dIt,{...a,...n,ref:t})});kIt.displayName=NIt;var SIt="DropdownMenuLabel",jtt=S.forwardRef((s,t)=>{const{__scopeDropdownMenu:r,...n}=s,a=Tg(r);return e.jsx(uIt,{...a,...n,ref:t})});jtt.displayName=SIt;var CIt="DropdownMenuItem",Ntt=S.forwardRef((s,t)=>{const{__scopeDropdownMenu:r,...n}=s,a=Tg(r);return e.jsx(hIt,{...a,...n,ref:t})});Ntt.displayName=CIt;var TIt="DropdownMenuCheckboxItem",ktt=S.forwardRef((s,t)=>{const{__scopeDropdownMenu:r,...n}=s,a=Tg(r);return e.jsx(mIt,{...a,...n,ref:t})});ktt.displayName=TIt;var EIt="DropdownMenuRadioGroup",AIt=S.forwardRef((s,t)=>{const{__scopeDropdownMenu:r,...n}=s,a=Tg(r);return e.jsx(fIt,{...a,...n,ref:t})});AIt.displayName=EIt;var MIt="DropdownMenuRadioItem",Stt=S.forwardRef((s,t)=>{const{__scopeDropdownMenu:r,...n}=s,a=Tg(r);return e.jsx(pIt,{...a,...n,ref:t})});Stt.displayName=MIt;var IIt="DropdownMenuItemIndicator",Ctt=S.forwardRef((s,t)=>{const{__scopeDropdownMenu:r,...n}=s,a=Tg(r);return e.jsx(gIt,{...a,...n,ref:t})});Ctt.displayName=IIt;var PIt="DropdownMenuSeparator",Ttt=S.forwardRef((s,t)=>{const{__scopeDropdownMenu:r,...n}=s,a=Tg(r);return e.jsx(xIt,{...a,...n,ref:t})});Ttt.displayName=PIt;var LIt="DropdownMenuArrow",DIt=S.forwardRef((s,t)=>{const{__scopeDropdownMenu:r,...n}=s,a=Tg(r);return e.jsx(yIt,{...a,...n,ref:t})});DIt.displayName=LIt;var RIt="DropdownMenuSubTrigger",Ett=S.forwardRef((s,t)=>{const{__scopeDropdownMenu:r,...n}=s,a=Tg(r);return e.jsx(vIt,{...a,...n,ref:t})});Ett.displayName=RIt;var OIt="DropdownMenuSubContent",Att=S.forwardRef((s,t)=>{const{__scopeDropdownMenu:r,...n}=s,a=Tg(r);return e.jsx(bIt,{...a,...n,ref:t,style:{...s.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)"}})});Att.displayName=OIt;var FIt=xtt,BIt=vtt,zIt=btt,Mtt=wtt,Itt=jtt,Ptt=Ntt,Ltt=ktt,Dtt=Stt,Rtt=Ctt,Ott=Ttt,Ftt=Ett,Btt=Att;const Xu=FIt,Qu=BIt,$It=S.forwardRef(({className:s,inset:t,children:r,...n},a)=>e.jsxs(Ftt,{ref:a,className:Ft("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",t&&"pl-8",s),...n,children:[r,e.jsx($a,{className:"ml-auto h-4 w-4"})]}));$It.displayName=Ftt.displayName;const UIt=S.forwardRef(({className:s,...t},r)=>e.jsx(Btt,{ref:r,className:Ft("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",s),...t}));UIt.displayName=Btt.displayName;const wu=S.forwardRef(({className:s,sideOffset:t=4,...r},n)=>e.jsx(zIt,{children:e.jsx(Mtt,{ref:n,sideOffset:t,className:Ft("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",s),...r})}));wu.displayName=Mtt.displayName;const di=S.forwardRef(({className:s,inset:t,...r},n)=>e.jsx(Ptt,{ref:n,className:Ft("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",t&&"pl-8",s),...r}));di.displayName=Ptt.displayName;const qIt=S.forwardRef(({className:s,children:t,checked:r,...n},a)=>e.jsxs(Ltt,{ref:a,className:Ft("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",s),checked:r,...n,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(Rtt,{children:e.jsx(va,{className:"h-4 w-4"})})}),t]}));qIt.displayName=Ltt.displayName;const VIt=S.forwardRef(({className:s,children:t,...r},n)=>e.jsxs(Dtt,{ref:n,className:Ft("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",s),...r,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(Rtt,{children:e.jsx(Gu,{className:"h-2 w-2 fill-current"})})}),t]}));VIt.displayName=Dtt.displayName;const l9=S.forwardRef(({className:s,inset:t,...r},n)=>e.jsx(Itt,{ref:n,className:Ft("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",s),...r}));l9.displayName=Itt.displayName;const A_=S.forwardRef(({className:s,...t},r)=>e.jsx(Ott,{ref:r,className:Ft("-mx-1 my-1 h-px bg-muted",s),...t}));A_.displayName=Ott.displayName;const HIt=()=>{const{isAssistant:s,actingAsAgent:t,assignedAgents:r,setActingAsAgent:n,isActingAsSelf:a,setActingAsSelf:i}=V3e();if(!s)return null;const l=o=>o.split(" ").map(c=>c[0]).join("").toUpperCase().slice(0,2);return e.jsx("div",{className:"fixed top-0 left-0 right-0 z-[2147483647] bg-primary text-primary-foreground px-4 py-1.5 shadow-lg",style:{height:"40px"},children:e.jsxs("div",{className:"container mx-auto flex items-center justify-between gap-4 h-full",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[a?e.jsxs(e.Fragment,{children:[e.jsx(io,{className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"font-medium text-sm",children:"My Account"})]}):e.jsxs(e.Fragment,{children:[e.jsx(Ar,{className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"font-medium text-sm",children:"Acting as"})]}),e.jsxs(Xu,{children:[e.jsx(Qu,{asChild:!0,children:e.jsxs(H,{variant:"secondary",size:"sm",className:"gap-2 bg-primary-foreground/20 hover:bg-primary-foreground/30 text-primary-foreground border-0",children:[a?e.jsxs(e.Fragment,{children:[e.jsx(io,{className:"h-4 w-4"}),e.jsx("strong",{children:"My Account"})]}):t?e.jsxs(e.Fragment,{children:[e.jsxs(Un,{className:"h-5 w-5",children:[e.jsx(Ka,{src:t.avatar_url||void 0}),e.jsx(qn,{className:"text-[10px] bg-primary-foreground/30",children:l(t.name)})]}),e.jsx("strong",{children:t.name})]}):e.jsx("strong",{children:"Select..."}),e.jsx(Io,{className:"h-3 w-3"})]})}),e.jsxs(wu,{align:"start",className:"z-[2147483647]",children:[e.jsxs(di,{onClick:i,className:"gap-2",children:[e.jsx(io,{className:"h-4 w-4"}),e.jsx("span",{children:"My Account"}),a&&e.jsx(Xe,{variant:"secondary",className:"ml-auto text-[10px]",children:"Current"})]}),e.jsx(A_,{}),r.map(o=>e.jsxs(di,{onClick:()=>n(o),className:"gap-2",children:[e.jsxs(Un,{className:"h-6 w-6",children:[e.jsx(Ka,{src:o.avatar_url||void 0}),e.jsx(qn,{className:"text-[10px]",children:l(o.name)})]}),e.jsx("span",{children:o.name}),!a&&o.id===(t==null?void 0:t.id)&&e.jsx(Xe,{variant:"secondary",className:"ml-auto text-[10px]",children:"Current"})]},o.id))]})]})]}),e.jsx(Xe,{variant:"secondary",className:"bg-primary-foreground/20 text-primary-foreground border-0 text-xs",children:a?"Personal Mode":"Assistant Mode"})]})})},ar=({children:s,requireAdmin:t=!1,requireBrokerageManager:r=!1})=>{const{user:n,loading:a,rolesLoading:i,isAdmin:l,isBrokerageManager:o}=Ms(),c=Vc();if(a||(t||r)&&i)return e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent mx-auto mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:"Loading..."})]})});if(!n){const d=c.pathname+c.search+c.hash;return d&&d!=="/auth"&&sessionStorage.setItem("redirectAfterLogin",d),e.jsx(O1e,{to:"/auth",replace:!0})}return t&&!l?e.jsx(O1e,{to:"/dashboard",replace:!0}):r&&!o&&!l?e.jsx(O1e,{to:"/dashboard",replace:!0}):e.jsx(e.Fragment,{children:s})};var J3e={};(function s(t,r,n,a){var i=!!(t.Worker&&t.Blob&&t.Promise&&t.OffscreenCanvas&&t.OffscreenCanvasRenderingContext2D&&t.HTMLCanvasElement&&t.HTMLCanvasElement.prototype.transferControlToOffscreen&&t.URL&&t.URL.createObjectURL),l=typeof Path2D=="function"&&typeof DOMMatrix=="function",o=function(){if(!t.OffscreenCanvas)return!1;try{var be=new OffscreenCanvas(1,1),fe=be.getContext("2d");fe.fillRect(0,0,1,1);var je=be.transferToImageBitmap();fe.createPattern(je,"no-repeat")}catch{return!1}return!0}();function c(){}function d(be){var fe=r.exports.Promise,je=fe!==void 0?fe:t.Promise;return typeof je=="function"?new je(be):(be(c,c),null)}var h=function(be,fe){return{transform:function(je){if(be)return je;if(fe.has(je))return fe.get(je);var ve=new OffscreenCanvas(je.width,je.height),We=ve.getContext("2d");return We.drawImage(je,0,0),fe.set(je,ve),ve},clear:function(){fe.clear()}}}(o,new Map),m=function(){var be=Math.floor(16.666666666666668),fe,je,ve={},We=0;return typeof requestAnimationFrame=="function"&&typeof cancelAnimationFrame=="function"?(fe=function(Ve){var Le=Math.random();return ve[Le]=requestAnimationFrame(function Me(ze){We===ze||We+be-1{const{data:t,error:r}=await V.from("celebration_queue").select("*").eq("user_id",s.id).is("seen_at",null).order("created_at",{ascending:!0});if(r)throw r;return t},enabled:!!(s!=null&&s.id),refetchOnWindowFocus:!0,staleTime:0})}function WIt(){const s=ns();return Pt({mutationFn:async t=>{const{error:r}=await V.from("celebration_queue").update({seen_at:new Date().toISOString()}).eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["celebrations"]})}})}function KIt(){const s=ns(),{user:t}=Ms();return Pt({mutationFn:async r=>{const{error:n}=await V.from("celebration_queue").insert({user_id:r.user_id,celebration_type:r.celebration_type,title:r.title,message:r.message||null,points_amount:r.points_amount||null,created_by:t==null?void 0:t.id});if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["celebrations"]})}})}var fge="Dialog",[ztt,$tt]=_u(fge),[YIt,L1]=ztt(fge),Utt=s=>{const{__scopeDialog:t,children:r,open:n,defaultOpen:a,onOpenChange:i,modal:l=!0}=s,o=S.useRef(null),c=S.useRef(null),[d,h]=af({prop:n,defaultProp:a??!1,onChange:i,caller:fge});return e.jsx(YIt,{scope:t,triggerRef:o,contentRef:c,contentId:vm(),titleId:vm(),descriptionId:vm(),open:d,onOpenChange:h,onOpenToggle:S.useCallback(()=>h(m=>!m),[h]),modal:l,children:r})};Utt.displayName=fge;var qtt="DialogTrigger",Vtt=S.forwardRef((s,t)=>{const{__scopeDialog:r,...n}=s,a=L1(qtt,r),i=_i(t,a.triggerRef);return e.jsx(Vn.button,{type:"button","aria-haspopup":"dialog","aria-expanded":a.open,"aria-controls":a.contentId,"data-state":s5e(a.open),...n,ref:i,onClick:an(s.onClick,a.onOpenToggle)})});Vtt.displayName=qtt;var e5e="DialogPortal",[ZIt,Htt]=ztt(e5e,{forceMount:void 0}),Gtt=s=>{const{__scopeDialog:t,forceMount:r,children:n,container:a}=s,i=L1(e5e,t);return e.jsx(ZIt,{scope:t,forceMount:r,children:S.Children.map(n,l=>e.jsx(vh,{present:r||i.open,children:e.jsx(s8,{asChild:!0,container:a,children:l})}))})};Gtt.displayName=e5e;var Ahe="DialogOverlay",Wtt=S.forwardRef((s,t)=>{const r=Htt(Ahe,s.__scopeDialog),{forceMount:n=r.forceMount,...a}=s,i=L1(Ahe,s.__scopeDialog);return i.modal?e.jsx(vh,{present:n||i.open,children:e.jsx(QIt,{...a,ref:t})}):null});Wtt.displayName=Ahe;var XIt=mS("DialogOverlay.RemoveScroll"),QIt=S.forwardRef((s,t)=>{const{__scopeDialog:r,...n}=s,a=L1(Ahe,r);return e.jsx(GB,{as:XIt,allowPinchZoom:!0,shards:[a.contentRef],children:e.jsx(Vn.div,{"data-state":s5e(a.open),...n,ref:t,style:{pointerEvents:"auto",...n.style}})})}),dA="DialogContent",Ktt=S.forwardRef((s,t)=>{const r=Htt(dA,s.__scopeDialog),{forceMount:n=r.forceMount,...a}=s,i=L1(dA,s.__scopeDialog);return e.jsx(vh,{present:n||i.open,children:i.modal?e.jsx(JIt,{...a,ref:t}):e.jsx(ePt,{...a,ref:t})})});Ktt.displayName=dA;var JIt=S.forwardRef((s,t)=>{const r=L1(dA,s.__scopeDialog),n=S.useRef(null),a=_i(t,r.contentRef,n);return S.useEffect(()=>{const i=n.current;if(i)return cge(i)},[]),e.jsx(Ytt,{...s,ref:a,trapFocus:r.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:an(s.onCloseAutoFocus,i=>{var l;i.preventDefault(),(l=r.triggerRef.current)==null||l.focus()}),onPointerDownOutside:an(s.onPointerDownOutside,i=>{const l=i.detail.originalEvent,o=l.button===0&&l.ctrlKey===!0;(l.button===2||o)&&i.preventDefault()}),onFocusOutside:an(s.onFocusOutside,i=>i.preventDefault())})}),ePt=S.forwardRef((s,t)=>{const r=L1(dA,s.__scopeDialog),n=S.useRef(!1),a=S.useRef(!1);return e.jsx(Ytt,{...s,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{var l,o;(l=s.onCloseAutoFocus)==null||l.call(s,i),i.defaultPrevented||(n.current||(o=r.triggerRef.current)==null||o.focus(),i.preventDefault()),n.current=!1,a.current=!1},onInteractOutside:i=>{var c,d;(c=s.onInteractOutside)==null||c.call(s,i),i.defaultPrevented||(n.current=!0,i.detail.originalEvent.type==="pointerdown"&&(a.current=!0));const l=i.target;((d=r.triggerRef.current)==null?void 0:d.contains(l))&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&a.current&&i.preventDefault()}})}),Ytt=S.forwardRef((s,t)=>{const{__scopeDialog:r,trapFocus:n,onOpenAutoFocus:a,onCloseAutoFocus:i,...l}=s,o=L1(dA,r),c=S.useRef(null),d=_i(t,c);return ige(),e.jsxs(e.Fragment,{children:[e.jsx(VB,{asChild:!0,loop:!0,trapped:n,onMountAutoFocus:a,onUnmountAutoFocus:i,children:e.jsx(PS,{role:"dialog",id:o.contentId,"aria-describedby":o.descriptionId,"aria-labelledby":o.titleId,"data-state":s5e(o.open),...l,ref:d,onDismiss:()=>o.onOpenChange(!1)})}),e.jsxs(e.Fragment,{children:[e.jsx(sPt,{titleId:o.titleId}),e.jsx(nPt,{contentRef:c,descriptionId:o.descriptionId})]})]})}),t5e="DialogTitle",Ztt=S.forwardRef((s,t)=>{const{__scopeDialog:r,...n}=s,a=L1(t5e,r);return e.jsx(Vn.h2,{id:a.titleId,...n,ref:t})});Ztt.displayName=t5e;var Xtt="DialogDescription",Qtt=S.forwardRef((s,t)=>{const{__scopeDialog:r,...n}=s,a=L1(Xtt,r);return e.jsx(Vn.p,{id:a.descriptionId,...n,ref:t})});Qtt.displayName=Xtt;var Jtt="DialogClose",est=S.forwardRef((s,t)=>{const{__scopeDialog:r,...n}=s,a=L1(Jtt,r);return e.jsx(Vn.button,{type:"button",...n,ref:t,onClick:an(s.onClick,()=>a.onOpenChange(!1))})});est.displayName=Jtt;function s5e(s){return s?"open":"closed"}var tst="DialogTitleWarning",[tPt,sst]=aSt(tst,{contentName:dA,titleName:t5e,docsSlug:"dialog"}),sPt=({titleId:s})=>{const t=sst(tst),r=`\`${t.contentName}\` requires a \`${t.titleName}\` for the component to be accessible for screen reader users. If you want to hide the \`${t.titleName}\`, you can wrap it with our VisuallyHidden component. For more information, see https://radix-ui.com/primitives/docs/components/${t.docsSlug}`;return S.useEffect(()=>{s&&(document.getElementById(s)||console.error(r))},[r,s]),null},rPt="DialogDescriptionWarning",nPt=({contentRef:s,descriptionId:t})=>{const n=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${sst(rPt).contentName}}.`;return S.useEffect(()=>{var i;const a=(i=s.current)==null?void 0:i.getAttribute("aria-describedby");t&&a&&(document.getElementById(t)||console.warn(n))},[n,s,t]),null},pge=Utt,r5e=Vtt,gge=Gtt,h8=Wtt,m8=Ktt,YB=Ztt,ZB=Qtt,XB=est;const bs=pge,Qi=r5e,aPt=gge,CZs=XB,rst=S.forwardRef(({className:s,...t},r)=>e.jsx(h8,{ref:r,className:Ft("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",s),...t}));rst.displayName=h8.displayName;const vs=S.forwardRef(({className:s,children:t,overlayClassName:r,...n},a)=>e.jsxs(aPt,{children:[e.jsx(rst,{className:r}),e.jsxs(m8,{ref:a,className:Ft("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",s),...n,children:[t,e.jsxs(XB,{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:[e.jsx(Rr,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));vs.displayName=m8.displayName;const Cs=({className:s,...t})=>e.jsx("div",{className:Ft("flex flex-col space-y-1.5 text-center sm:text-left",s),...t});Cs.displayName="DialogHeader";const wn=({className:s,...t})=>e.jsx("div",{className:Ft("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",s),...t});wn.displayName="DialogFooter";const Ns=S.forwardRef(({className:s,...t},r)=>e.jsx(YB,{ref:r,className:Ft("text-lg font-semibold leading-none tracking-tight",s),...t}));Ns.displayName=YB.displayName;const nn=S.forwardRef(({className:s,...t},r)=>e.jsx(ZB,{ref:r,className:Ft("text-sm text-muted-foreground",s),...t}));nn.displayName=ZB.displayName;const iPt={points_earned:To,listing_created:Fn,deal_closed:oc,custom:ya},OOe={points_earned:"from-amber-500 to-orange-500",listing_created:"from-emerald-500 to-teal-500",deal_closed:"from-green-500 to-emerald-500",custom:"from-purple-500 to-pink-500"},FOe=()=>{const s=window.location.hostname;return s.startsWith("cards.")||s.startsWith("cardstudio.")||s.startsWith("listings.")||s.startsWith("presentations.")||s.startsWith("guestbook.")||s.startsWith("clients.")||s.startsWith("booking.")||s.startsWith("contacts.")};function oPt(){const{user:s}=Ms(),t=ns(),{data:r}=GIt(),n=WIt(),[a,i]=S.useState(null),[l,o]=S.useState(!1),c=S.useCallback(()=>{const x=Date.now()+3e3,y={startVelocity:30,spread:360,ticks:60,zIndex:9999},_=(j,k)=>Math.random()*(k-j)+j,b=setInterval(()=>{const j=x-Date.now();if(j<=0){clearInterval(b);return}const k=50*(j/3e3);ROe({...y,particleCount:k,origin:{x:_(.1,.3),y:Math.random()-.2},colors:["#ff6b6b","#feca57","#48dbfb","#ff9ff3","#54a0ff","#5f27cd"]}),ROe({...y,particleCount:k,origin:{x:_(.7,.9),y:Math.random()-.2},colors:["#ff6b6b","#feca57","#48dbfb","#ff9ff3","#54a0ff","#5f27cd"]})},250)},[]);S.useEffect(()=>{FOe()||r&&r.length>0&&!a&&(i(r[0]),o(!0),setTimeout(c,100))},[r,a,c]);const d=async()=>{if(a){const p=a.id;o(!1),i(null),t.setQueryData(["celebrations","pending",s==null?void 0:s.id],x=>(x==null?void 0:x.filter(y=>y.id!==p))??[]),await n.mutateAsync(p)}};if(FOe()||!a)return null;const h=iPt[a.celebration_type]||ya,m=OOe[a.celebration_type]||OOe.custom;return e.jsx(bs,{open:l,onOpenChange:p=>!p&&d(),children:e.jsxs(vs,{className:"sm:max-w-md text-center border-0 overflow-hidden",children:[e.jsx("div",{className:`absolute inset-0 bg-gradient-to-br ${m} opacity-10`}),e.jsxs("div",{className:"relative z-10 py-6",children:[e.jsx("div",{className:"flex justify-center mb-4",children:e.jsx("div",{className:`w-20 h-20 rounded-full bg-gradient-to-br ${m} flex items-center justify-center animate-bounce`,children:e.jsx(h,{className:"w-10 h-10 text-white"})})}),e.jsxs("div",{className:"flex justify-center gap-1 mb-4",children:[e.jsx(Lr,{className:"w-5 h-5 text-yellow-500 animate-pulse"}),e.jsx(Lr,{className:"w-5 h-5 text-yellow-500 animate-pulse delay-75"}),e.jsx(Lr,{className:"w-5 h-5 text-yellow-500 animate-pulse delay-150"})]}),e.jsxs("h2",{className:"text-2xl font-bold mb-2 bg-gradient-to-r from-primary to-secondary bg-clip-text text-transparent",children:["🎉 ",a.title]}),a.points_amount&&a.points_amount>0&&e.jsxs("div",{className:"text-4xl font-bold text-primary mb-2",children:["+",a.points_amount," points!"]}),a.message&&e.jsx("p",{className:"text-muted-foreground mb-6",children:a.message}),e.jsx(H,{onClick:d,className:"w-full",size:"lg",children:"Awesome! 🙌"}),r&&r.length>1&&e.jsxs("p",{className:"text-sm text-muted-foreground mt-3",children:["+",r.length-1," more celebration",r.length>2?"s":""," waiting"]})]})]})})}const n5e="/assets/levelup-logo-horizontal-DEFNc0ms.png",a5e="/assets/levelup-logo-white-C2RAgAoG.png",lPt="/assets/listings-hero-BI9Ki9Dq.jpg",Se=S.forwardRef(({className:s,type:t,...r},n)=>e.jsx("input",{type:t,className:Ft("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",s),ref:n,...r}));Se.displayName="Input";var nst={exports:{}};(function(s,t){(function(r,n){s.exports=n()})(uh,function(){let r,n,a;function i(o,c){if(!r)r=c;else if(!n)n=c;else{const d={};r(d),a=c(d);const h="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+")(undefined, sharedChunk); self.onerror = null;";typeof window<"u"&&window&&window.URL&&window.URL.createObjectURL&&(a.workerUrl=window.URL.createObjectURL(new Blob([h],{type:"text/javascript"})))}}i(["exports"],function(o){var c=1e-6,d=typeof Float32Array<"u"?Float32Array:Array;function h(v,u){var f=u[0],w=u[1],C=u[2],I=u[3],L=f*I-C*w;return L?(v[0]=I*(L=1/L),v[1]=-w*L,v[2]=-C*L,v[3]=f*L,v):null}function m(){var v=new d(9);return d!=Float32Array&&(v[1]=0,v[2]=0,v[3]=0,v[5]=0,v[6]=0,v[7]=0),v[0]=1,v[4]=1,v[8]=1,v}function p(v,u){var f=u[0],w=u[1],C=u[2],I=u[3],L=u[4],B=u[5],U=u[6],Y=u[7],se=u[8];return v[0]=L*se-B*Y,v[1]=C*Y-w*se,v[2]=w*B-C*L,v[3]=B*U-I*se,v[4]=f*se-C*U,v[5]=C*I-f*B,v[6]=I*Y-L*U,v[7]=w*U-f*Y,v[8]=f*L-w*I,v}function x(v,u,f){var w=u[0],C=u[1],I=u[2],L=u[3],B=u[4],U=u[5],Y=u[6],se=u[7],oe=u[8],de=f[0],xe=f[1],we=f[2],Ce=f[3],Re=f[4],qe=f[5],nt=f[6],Ze=f[7],ut=f[8];return v[0]=de*w+xe*L+we*Y,v[1]=de*C+xe*B+we*se,v[2]=de*I+xe*U+we*oe,v[3]=Ce*w+Re*L+qe*Y,v[4]=Ce*C+Re*B+qe*se,v[5]=Ce*I+Re*U+qe*oe,v[6]=nt*w+Ze*L+ut*Y,v[7]=nt*C+Ze*B+ut*se,v[8]=nt*I+Ze*U+ut*oe,v}function y(){var v=new d(16);return d!=Float32Array&&(v[1]=0,v[2]=0,v[3]=0,v[4]=0,v[6]=0,v[7]=0,v[8]=0,v[9]=0,v[11]=0,v[12]=0,v[13]=0,v[14]=0),v[0]=1,v[5]=1,v[10]=1,v[15]=1,v}function _(v){var u=new d(16);return u[0]=v[0],u[1]=v[1],u[2]=v[2],u[3]=v[3],u[4]=v[4],u[5]=v[5],u[6]=v[6],u[7]=v[7],u[8]=v[8],u[9]=v[9],u[10]=v[10],u[11]=v[11],u[12]=v[12],u[13]=v[13],u[14]=v[14],u[15]=v[15],u}function b(v){return v[0]=1,v[1]=0,v[2]=0,v[3]=0,v[4]=0,v[5]=1,v[6]=0,v[7]=0,v[8]=0,v[9]=0,v[10]=1,v[11]=0,v[12]=0,v[13]=0,v[14]=0,v[15]=1,v}function j(v,u){var f=u[0],w=u[1],C=u[2],I=u[3],L=u[4],B=u[5],U=u[6],Y=u[7],se=u[8],oe=u[9],de=u[10],xe=u[11],we=u[12],Ce=u[13],Re=u[14],qe=u[15],nt=f*B-w*L,Ze=f*U-C*L,ut=f*Y-I*L,xt=w*U-C*B,bt=w*Y-I*B,Ht=C*Y-I*U,Rt=se*Ce-oe*we,Vt=se*Re-de*we,Bt=se*qe-xe*we,$t=oe*Re-de*Ce,js=oe*qe-xe*Ce,Es=de*qe-xe*Re,zs=nt*Es-Ze*js+ut*$t+xt*Bt-bt*Vt+Ht*Rt;return zs?(v[0]=(B*Es-U*js+Y*$t)*(zs=1/zs),v[1]=(C*js-w*Es-I*$t)*zs,v[2]=(Ce*Ht-Re*bt+qe*xt)*zs,v[3]=(de*bt-oe*Ht-xe*xt)*zs,v[4]=(U*Bt-L*Es-Y*Vt)*zs,v[5]=(f*Es-C*Bt+I*Vt)*zs,v[6]=(Re*ut-we*Ht-qe*Ze)*zs,v[7]=(se*Ht-de*ut+xe*Ze)*zs,v[8]=(L*js-B*Bt+Y*Rt)*zs,v[9]=(w*Bt-f*js-I*Rt)*zs,v[10]=(we*bt-Ce*ut+qe*nt)*zs,v[11]=(oe*ut-se*bt-xe*nt)*zs,v[12]=(B*Vt-L*$t-U*Rt)*zs,v[13]=(f*$t-w*Vt+C*Rt)*zs,v[14]=(Ce*Ze-we*xt-Re*nt)*zs,v[15]=(se*xt-oe*Ze+de*nt)*zs,v):null}function k(v,u,f){var w=u[0],C=u[1],I=u[2],L=u[3],B=u[4],U=u[5],Y=u[6],se=u[7],oe=u[8],de=u[9],xe=u[10],we=u[11],Ce=u[12],Re=u[13],qe=u[14],nt=u[15],Ze=f[0],ut=f[1],xt=f[2],bt=f[3];return v[0]=Ze*w+ut*B+xt*oe+bt*Ce,v[1]=Ze*C+ut*U+xt*de+bt*Re,v[2]=Ze*I+ut*Y+xt*xe+bt*qe,v[3]=Ze*L+ut*se+xt*we+bt*nt,v[4]=(Ze=f[4])*w+(ut=f[5])*B+(xt=f[6])*oe+(bt=f[7])*Ce,v[5]=Ze*C+ut*U+xt*de+bt*Re,v[6]=Ze*I+ut*Y+xt*xe+bt*qe,v[7]=Ze*L+ut*se+xt*we+bt*nt,v[8]=(Ze=f[8])*w+(ut=f[9])*B+(xt=f[10])*oe+(bt=f[11])*Ce,v[9]=Ze*C+ut*U+xt*de+bt*Re,v[10]=Ze*I+ut*Y+xt*xe+bt*qe,v[11]=Ze*L+ut*se+xt*we+bt*nt,v[12]=(Ze=f[12])*w+(ut=f[13])*B+(xt=f[14])*oe+(bt=f[15])*Ce,v[13]=Ze*C+ut*U+xt*de+bt*Re,v[14]=Ze*I+ut*Y+xt*xe+bt*qe,v[15]=Ze*L+ut*se+xt*we+bt*nt,v}function T(v,u,f){var w,C,I,L,B,U,Y,se,oe,de,xe,we,Ce=f[0],Re=f[1],qe=f[2];return u===v?(v[12]=u[0]*Ce+u[4]*Re+u[8]*qe+u[12],v[13]=u[1]*Ce+u[5]*Re+u[9]*qe+u[13],v[14]=u[2]*Ce+u[6]*Re+u[10]*qe+u[14],v[15]=u[3]*Ce+u[7]*Re+u[11]*qe+u[15]):(C=u[1],I=u[2],L=u[3],B=u[4],U=u[5],Y=u[6],se=u[7],oe=u[8],de=u[9],xe=u[10],we=u[11],v[0]=w=u[0],v[1]=C,v[2]=I,v[3]=L,v[4]=B,v[5]=U,v[6]=Y,v[7]=se,v[8]=oe,v[9]=de,v[10]=xe,v[11]=we,v[12]=w*Ce+B*Re+oe*qe+u[12],v[13]=C*Ce+U*Re+de*qe+u[13],v[14]=I*Ce+Y*Re+xe*qe+u[14],v[15]=L*Ce+se*Re+we*qe+u[15]),v}function E(v,u,f){var w=f[0],C=f[1],I=f[2];return v[0]=u[0]*w,v[1]=u[1]*w,v[2]=u[2]*w,v[3]=u[3]*w,v[4]=u[4]*C,v[5]=u[5]*C,v[6]=u[6]*C,v[7]=u[7]*C,v[8]=u[8]*I,v[9]=u[9]*I,v[10]=u[10]*I,v[11]=u[11]*I,v[12]=u[12],v[13]=u[13],v[14]=u[14],v[15]=u[15],v}function A(v,u,f){var w=Math.sin(f),C=Math.cos(f),I=u[4],L=u[5],B=u[6],U=u[7],Y=u[8],se=u[9],oe=u[10],de=u[11];return u!==v&&(v[0]=u[0],v[1]=u[1],v[2]=u[2],v[3]=u[3],v[12]=u[12],v[13]=u[13],v[14]=u[14],v[15]=u[15]),v[4]=I*C+Y*w,v[5]=L*C+se*w,v[6]=B*C+oe*w,v[7]=U*C+de*w,v[8]=Y*C-I*w,v[9]=se*C-L*w,v[10]=oe*C-B*w,v[11]=de*C-U*w,v}function D(v,u,f){var w=Math.sin(f),C=Math.cos(f),I=u[0],L=u[1],B=u[2],U=u[3],Y=u[8],se=u[9],oe=u[10],de=u[11];return u!==v&&(v[4]=u[4],v[5]=u[5],v[6]=u[6],v[7]=u[7],v[12]=u[12],v[13]=u[13],v[14]=u[14],v[15]=u[15]),v[0]=I*C-Y*w,v[1]=L*C-se*w,v[2]=B*C-oe*w,v[3]=U*C-de*w,v[8]=I*w+Y*C,v[9]=L*w+se*C,v[10]=B*w+oe*C,v[11]=U*w+de*C,v}function R(v,u,f){var w=Math.sin(f),C=Math.cos(f),I=u[0],L=u[1],B=u[2],U=u[3],Y=u[4],se=u[5],oe=u[6],de=u[7];return u!==v&&(v[8]=u[8],v[9]=u[9],v[10]=u[10],v[11]=u[11],v[12]=u[12],v[13]=u[13],v[14]=u[14],v[15]=u[15]),v[0]=I*C+Y*w,v[1]=L*C+se*w,v[2]=B*C+oe*w,v[3]=U*C+de*w,v[4]=Y*C-I*w,v[5]=se*C-L*w,v[6]=oe*C-B*w,v[7]=de*C-U*w,v}function z(v,u){return v[0]=u[0],v[1]=0,v[2]=0,v[3]=0,v[4]=0,v[5]=u[1],v[6]=0,v[7]=0,v[8]=0,v[9]=0,v[10]=u[2],v[11]=0,v[12]=0,v[13]=0,v[14]=0,v[15]=1,v}function O(v,u,f){var w,C,I,L=f[0],B=f[1],U=f[2],Y=Math.sqrt(L*L+B*B+U*U);return Y0&&(I=1/Math.sqrt(I)),v[0]=u[0]*I,v[1]=u[1]*I,v[2]=u[2]*I,v}function Ie(v,u){return v[0]*u[0]+v[1]*u[1]+v[2]*u[2]}function De(v,u,f){var w=u[0],C=u[1],I=u[2],L=f[0],B=f[1],U=f[2];return v[0]=C*U-I*B,v[1]=I*L-w*U,v[2]=w*B-C*L,v}function pe(v,u,f,w){var C=u[0],I=u[1],L=u[2];return v[0]=C+w*(f[0]-C),v[1]=I+w*(f[1]-I),v[2]=L+w*(f[2]-L),v}function tt(v,u,f){var w=u[0],C=u[1],I=u[2],L=f[3]*w+f[7]*C+f[11]*I+f[15];return v[0]=(f[0]*w+f[4]*C+f[8]*I+f[12])/(L=L||1),v[1]=(f[1]*w+f[5]*C+f[9]*I+f[13])/L,v[2]=(f[2]*w+f[6]*C+f[10]*I+f[14])/L,v}function ge(v,u,f){var w=u[0],C=u[1],I=u[2];return v[0]=w*f[0]+C*f[3]+I*f[6],v[1]=w*f[1]+C*f[4]+I*f[7],v[2]=w*f[2]+C*f[5]+I*f[8],v}function ct(v,u,f){var w=f[0],C=f[1],I=f[2],L=f[3],B=u[0],U=u[1],Y=u[2],se=C*Y-I*U,oe=I*B-w*Y,de=w*U-C*B;return v[0]=B+L*(se+=se)+C*(de+=de)-I*(oe+=oe),v[1]=U+L*oe+I*se-w*de,v[2]=Y+L*de+w*oe-C*se,v}function Ue(v){return v[0]=0,v[1]=0,v[2]=0,v}function et(v,u){return v[0]===u[0]&&v[1]===u[1]&&v[2]===u[2]}var Qe=le,Ne=be,$e=re;function it(){var v=new d(4);return d!=Float32Array&&(v[0]=0,v[1]=0,v[2]=0,v[3]=0),v}function Je(v,u,f){return v[0]=u[0]*f,v[1]=u[1]*f,v[2]=u[2]*f,v[3]=u[3]*f,v}function st(v,u){var f=u[0],w=u[1],C=u[2],I=u[3],L=f*f+w*w+C*C+I*I;return L>0&&(L=1/Math.sqrt(L)),v[0]=f*L,v[1]=w*L,v[2]=C*L,v[3]=I*L,v}function mt(v,u){return v[0]*u[0]+v[1]*u[1]+v[2]*u[2]+v[3]*u[3]}function wt(v,u,f){var w=u[0],C=u[1],I=u[2],L=u[3];return v[0]=f[0]*w+f[4]*C+f[8]*I+f[12]*L,v[1]=f[1]*w+f[5]*C+f[9]*I+f[13]*L,v[2]=f[2]*w+f[6]*C+f[10]*I+f[14]*L,v[3]=f[3]*w+f[7]*C+f[11]*I+f[15]*L,v}function at(){var v=new d(4);return d!=Float32Array&&(v[0]=0,v[1]=0,v[2]=0),v[3]=1,v}function rt(v){return v[0]=0,v[1]=0,v[2]=0,v[3]=1,v}function Et(v,u,f){f*=.5;var w=u[0],C=u[1],I=u[2],L=u[3],B=Math.sin(f),U=Math.cos(f);return v[0]=w*U+L*B,v[1]=C*U+I*B,v[2]=I*U-C*B,v[3]=L*U-w*B,v}function hs(v,u,f){f*=.5;var w=u[0],C=u[1],I=u[2],L=u[3],B=Math.sin(f),U=Math.cos(f);return v[0]=w*U-I*B,v[1]=C*U+L*B,v[2]=I*U+w*B,v[3]=L*U-C*B,v}J(),it();var Is,lr,us,St=st,xs=(Is=J(),lr=ie(1,0,0),us=ie(0,1,0),function(v,u,f){var w=Ie(u,f);return w<-.999999?(De(Is,lr,u),$e(Is)<1e-6&&De(Is,us,u),Pe(Is,Is),function(C,I,L){L*=.5;var B=Math.sin(L);C[0]=B*I[0],C[1]=B*I[1],C[2]=B*I[2],C[3]=Math.cos(L)}(v,Is,Math.PI),v):w>.999999?(v[0]=0,v[1]=0,v[2]=0,v[3]=1,v):(De(Is,u,f),v[0]=Is[0],v[1]=Is[1],v[2]=Is[2],v[3]=1+w,St(v,v))});function kt(){var v=new d(2);return d!=Float32Array&&(v[0]=0,v[1]=0),v}function fs(v,u){var f=new d(2);return f[0]=v,f[1]=u,f}function Gs(v,u,f){return v[0]=u,v[1]=f,v}function _s(v,u,f){return v[0]=u[0]+f[0],v[1]=u[1]+f[1],v}function br(v,u,f){return v[0]=u[0]-f[0],v[1]=u[1]-f[1],v}function zr(v,u,f){return v[0]=u[0]*f,v[1]=u[1]*f,v}function Yr(v){var u=v[0],f=v[1];return Math.sqrt(u*u+f*f)}function rn(v,u){var f=u[0],w=u[1],C=f*f+w*w;return C>0&&(C=1/Math.sqrt(C)),v[0]=u[0]*C,v[1]=u[1]*C,v}function sn(v,u){return v[0]*u[0]+v[1]*u[1]}at(),at(),m();var Vr,$r,hn=br;function Zn(v){return v&&v.__esModule&&Object.prototype.hasOwnProperty.call(v,"default")?v.default:v}kt();var cr=function(){if($r)return Vr;function v(u,f,w,C){this.cx=3*u,this.bx=3*(w-u)-this.cx,this.ax=1-this.cx-this.bx,this.cy=3*f,this.by=3*(C-f)-this.cy,this.ay=1-this.cy-this.by,this.p1x=u,this.p1y=f,this.p2x=w,this.p2y=C}return $r=1,Vr=v,v.prototype={sampleCurveX:function(u){return((this.ax*u+this.bx)*u+this.cx)*u},sampleCurveY:function(u){return((this.ay*u+this.by)*u+this.cy)*u},sampleCurveDerivativeX:function(u){return(3*this.ax*u+2*this.bx)*u+this.cx},solveCurveX:function(u,f){if(f===void 0&&(f=1e-6),u<0)return 0;if(u>1)return 1;for(var w=u,C=0;C<8;C++){var I=this.sampleCurveX(w)-u;if(Math.abs(I)I?B=w:U=w,w=.5*(U-B)+B;return w},solve:function(u,f){return this.sampleCurveY(this.solveCurveX(u,f))}},Vr}(),on=Zn(cr);function ds(v,u){this.x=v,this.y=u}function Na(v,u){if(Array.isArray(v)){if(!Array.isArray(u)||v.length!==u.length)return!1;for(let f=0;f=1)return 1;const u=v*v,f=u*v;return 4*(v<.5?f:3*(v-u)+f-.75)}function Gt(v,u,f,w){const C=new on(v,u,f,w);return function(I){return C.solve(I)}}const Ee=Gt(.25,.1,.25,1);function He(v,u,f){return Math.min(f,Math.max(u,v))}function ot(v,u,f){return(f=He((f-v)/(u-v),0,1))*f*(3-2*f)}function jt(v,u,f){const w=f-u,C=((v-u)%w+w)%w+u;return C===u?f:C}function Dt(v,u,f){if(!v.length)return f(null,[]);let w=v.length;const C=new Array(v.length);let I=null;v.forEach((L,B)=>{u(L,(U,Y)=>{U&&(I=U),C[B]=Y,--w===0&&f(I,C)})})}let qt=1;function ss(){return qt++}function Yt(v){return v<=1?1:Math.pow(2,Math.ceil(Math.log2(v)))}function ls(v,u){v.forEach(f=>{u[f]&&(u[f]=u[f].bind(u))})}function Xs(v,u,f){const w={};for(const C in v)w[C]=u.call(this,v[C],C,v);return w}function Rs(v,u,f){const w={};for(const C in v)u.call(this,v[C],C,v)&&(w[C]=v[C]);return w}function Er(v){return Array.isArray(v)?v.map(Er):typeof v=="object"&&v?Xs(v,Er):v}function ln(v,u){for(let f=0;f=0)return!0;return!1}const mn={};function Gr(v){mn[v]||(typeof console<"u"&&console.warn(v),mn[v]=!0)}function fn(v,u,f){return(f.y-v.y)*(u.x-v.x)>(u.y-v.y)*(f.x-v.x)}function pn(v){let u=0;for(let f,w,C=0,I=v.length,L=I-1;C@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)(?:\=(?:([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)|(?:\"((?:[^"\\]|\\.)*)\")))?/g,(f,w,C,I)=>{const L=C||I;return u[w]=!L||L.toLowerCase(),""}),u["max-age"]){const f=parseInt(u["max-age"],10);isNaN(f)?delete u["max-age"]:u["max-age"]=f}return u}let fo,ai=null;function Cn(v,u){return[v[4*u],v[4*u+1],v[4*u+2],v[4*u+3]]}function Wi(v,u,f,w){for(;u>1;v[C]>1;v[C]<=w?u=C+1:f=C}return u}function ii(v){return v>0?1/(1.001-v):1+v}function Ji(v){return v>0?1-1/(1.001-v):-v}function co(v,u,f){return(v-u.min)*(f.max-f.min)/(u.max-u.min)+f.min}const ia={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(!ia.API_URL)return null;try{const v=new URL(ia.API_URL);return v.hostname==="api.mapbox.cn"?"https://events.mapbox.cn/events/v2":v.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:"/mapbox-gl-js/draco_decoder_gltf_v1.5.6.wasm",MESHOPT_URL:"/mapbox-gl-js/meshopt_base_v0.20.wasm",MESHOPT_SIMD_URL:"/mapbox-gl-js/meshopt_simd_v0.20.wasm",BUILDING_GEN_URL:"/mapbox-gl-js/building-gen/building_gen_v1.2.4.wasm",GLYPHS_URL:"mapbox://fonts/mapbox/{fontstack}/{range}.pbf",TILES3D_URL_PREFIX:"3dtiles/v1",TILE_PROVIDER_URLS:Object.assign(Object.create(null),{pmtiles:"/mapbox-gl-js/mapbox-gl-pmtiles-provider-v0.0.1.js"})};function hr(){return new URL(ia.DRACO_URL,ia.API_URL).href}function Sa(){if(typeof WebAssembly!="object")throw new Error("WebAssembly not supported, cannot instantiate meshoptimizer");return new URL(function(){if(fo===void 0){if(typeof WebAssembly!="object")return!1;const v=new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,3,2,0,0,5,3,1,0,1,12,1,0,10,22,2,12,0,65,0,65,0,65,0,252,10,0,0,11,7,0,65,0,253,15,26,11]);fo=WebAssembly.validate(v)}return fo}()?ia.MESHOPT_SIMD_URL:ia.MESHOPT_URL,ia.API_URL).href}function Yi(){return new URL(ia.BUILDING_GEN_URL,ia.API_URL).href}function $o(v){return ia.API_URL_REGEX.test(v)}function cl(v){return ia.API_SPRITE_REGEX.test(v)}let bo,md,Nu,Yf,ku,$h;function Su(){return bo==null&&(bo=self.OffscreenCanvas&&new OffscreenCanvas(1,1).getContext("2d")&&typeof self.createImageBitmap=="function"),bo}const Ad={now:()=>Yf!==void 0?Yf:performance.now(),setNow(v){Yf=v},restoreNow(){Yf=void 0},frame(v){const u=requestAnimationFrame(v);return{cancel:()=>cancelAnimationFrame(u)}},getImageData(v,u=0){const{width:f,height:w}=v;ku||(ku=document.createElement("canvas"));const C=ku.getContext("2d",{willReadFrequently:!0});if(!C)throw new Error("failed to create canvas 2d context");return(f>ku.width||w>ku.height)&&(ku.width=f,ku.height=w),C.clearRect(-u,-u,f+2*u,w+2*u),C.drawImage(v,0,0,f,w),C.getImageData(-u,-u,f+2*u,w+2*u)},resolveURL:v=>(md||(md=document.createElement("a")),md.href=v,md.href),get devicePixelRatio(){return window.devicePixelRatio},get prefersReducedMotion(){return!!window.matchMedia&&(Nu==null&&(Nu=window.matchMedia("(prefers-reduced-motion: reduce)")),Nu.matches)},hasCanvasFingerprintNoise(){if($h!==void 0)return $h;if(!Su())return $h=!1,!1;const v=new OffscreenCanvas(85,1),u=v.getContext("2d",{willReadFrequently:!0});let f=0;for(let C=0;C0?`?${I}`:""}`}const Uh="mapbox-tiles";let B0=500,z0=50;const Zf=["language","worldview","jobid"];let Ju;function Pp(){try{return caches}catch{}}function oo(){const v=Pp();v&&Ju==null&&(Ju=v.open(Uh))}let q1=1/0;const qh={supported:!1,testSupport:function(v){!Cu&&Lp&&(Uo?Qd(v):bh=v)}};let bh,Lp,Cu=!1,Uo=!1;const yx=typeof self<"u"?self:{};function Qd(v){const u=v.createTexture();v.bindTexture(v.TEXTURE_2D,u);try{if(v.texImage2D(v.TEXTURE_2D,0,v.RGBA,v.RGBA,v.UNSIGNED_BYTE,Lp),v.isContextLost())return;qh.supported=!0}catch{}v.deleteTexture(u),Cu=!0}yx.document&&(Lp=yx.document.createElement("img"),Lp.onload=function(){bh&&Qd(bh),bh=null,Uo=!0},Lp.onerror=function(){Cu=!0,bh=null},Lp.src="data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAQAAAAfQ//73v/+BiOh/AAA=");const vx={Unknown:"Unknown",Style:"Style",Source:"Source",Tile:"Tile",Glyphs:"Glyphs",SpriteImage:"SpriteImage",SpriteJSON:"SpriteJSON",Iconset:"Iconset",Image:"Image",Model:"Model"};Object.freeze(vx);class nw extends Error{constructor(u,f,w){f===401&&$o(w)&&(u+=": you may have provided an invalid Mapbox access token. See https://docs.mapbox.com/api/overview/#access-tokens-and-token-scopes"),super(u),this.status=f,this.url=w}toString(){return`${this.name}: ${this.message} (${this.status}): ${this.url}`}}function Xf(v){return typeof v=="object"&&v!==null&&"status"in v&&v.status===404}const Ua=Aa()?()=>self.worker.referrer:()=>(location.protocol==="blob:"?parent:self).location.href,$0=function(v,u){return/^file:/.test(f=v.url)||/^file:/.test(Ua())&&!/^\w+:/.test(f)?function(w,C){const I=new XMLHttpRequest;I.open(w.method||"GET",w.url,!0),w.type==="arrayBuffer"&&(I.responseType="arraybuffer");for(const L in w.headers)I.setRequestHeader(L,w.headers[L]);return w.type==="json"&&(I.responseType="text",I.setRequestHeader("Accept","application/json")),I.withCredentials=w.credentials==="include",I.onerror=()=>{C(new Error(I.statusText))},I.onload=()=>{if((I.status>=200&&I.status<300||I.status===0)&&I.response!==null){let L=I.response;if(w.type==="json")try{L=JSON.parse(I.response)}catch(U){return C(U)}const B=new Headers;I.getAllResponseHeaders().trim().split(/[\r\n]+/).forEach(U=>{const Y=U.split(": "),se=Y.shift(),oe=Y.join(": ");B.append(se,oe)}),C(null,L,B)}else C(new nw(I.statusText,I.status,w.url))},I.send(w.body),{cancel:()=>I.abort()}}(v,u):function(w,C){const I=new AbortController,L=new Request(w.url,{method:w.method||"GET",body:w.body,credentials:w.credentials,headers:w.headers,referrer:Ua(),referrerPolicy:w.referrerPolicy,signal:I.signal});let B=!1,U=!1;const Y=(se=L.url).indexOf("sku=")>0&&$o(se);var se;w.type==="json"&&L.headers.set("Accept","application/json");const oe=(xe,we,Ce)=>{if(U)return;if(xe&&xe.message!=="SecurityError"&&Gr(xe.toString()),we&&Ce)return de(we);const Re=Date.now();fetch(L).then(qe=>{if(qe.ok){const nt=Y?qe.clone():null;return de(qe,nt,Re)}return C(new nw(qe.statusText,qe.status,w.url))}).catch(qe=>{qe.name!=="AbortError"&&C(new Error(`${qe.message} ${w.url}`))})},de=(xe,we,Ce)=>{(w.type==="arrayBuffer"?xe.arrayBuffer():w.type==="json"?xe.json():xe.text()).then(Re=>{U||(we&&Ce&&function(qe,nt,Ze){if(oo(),Ju==null)return;const ut=vo(nt.headers.get("cache-control")||"");if(ut["no-store"])return;const xt={status:nt.status,statusText:nt.statusText,headers:new Headers};nt.headers.forEach((Bt,$t)=>xt.headers.set($t,Bt)),ut["max-age"]&&xt.headers.set("Expires",new Date(Ze+1e3*ut["max-age"]).toUTCString());const bt=xt.headers.get("expires");if(!bt||new Date(bt).getTime()-Ze<42e4)return;let Ht=rw(qe.url,{persistentParams:Zf});if(nt.status===206){const Bt=qe.headers.get("Range");if(!Bt)return;xt.status=200,Ht=uv(Ht,{range:Bt})}const Rt=new Response((Vt=nt.status)!==200&&Vt!==404&&[101,103,204,205,304].includes(Vt)?null:nt.body,xt);var Vt;oo(),Ju!=null&&Ju.then(Bt=>Bt.put(Ht,Rt)).catch(Bt=>Gr(Bt.message))}(L,we,Ce),B=!0,C(null,Re,xe.headers))}).catch(Re=>{U||C(new Error(Re.message))})};return Y?function(xe,we){if(oo(),Ju==null)return we(null);Ju.then(Ce=>{let Re=rw(xe.url,{persistentParams:Zf});const qe=xe.headers.get("Range");qe&&(Re=uv(Re,{range:qe})),Ce.match(Re).then(nt=>{const Ze=function(ut){if(!ut)return!1;const xt=new Date(ut.headers.get("expires")||0),bt=vo(ut.headers.get("cache-control")||"");return Number(xt)>Date.now()&&!bt["no-cache"]}(nt);Ce.delete(Re).catch(we),Ze&&Ce.put(Re,nt.clone()).catch(we),we(null,nt,Ze)}).catch(we)}).catch(we)}(L,oe):oe(null,null),{cancel:()=>{U=!0,B||I.abort()}}}(v,u);var f},U0=function(v,u){return $0(Object.assign(v,{type:"arrayBuffer"}),u)};function Cm(v){const u=document.createElement("a");return u.href=v,u.protocol===location.protocol&&u.host===location.host}let Tm,df;Tm=[],df=0;const Dp=function(v,u){if(qh.supported&&(v.headers||(v.headers={}),v.headers.accept="image/webp,*/*"),df>=ia.MAX_PARALLEL_IMAGE_REQUESTS){const I={requestParameters:v,callback:u,cancelled:!1,cancel(){this.cancelled=!0}};return Tm.push(I),I}df++;let f=!1;const w=()=>{if(!f)for(f=!0,df--;Tm.length&&df{w(),I?u(I):L&&function(U,Y){const se=new Blob([new Uint8Array(U)],{type:"image/png"});createImageBitmap(se).then(oe=>{Y(null,oe)}).catch(oe=>{Y(new Error(`Could not load image because of ${oe.message}. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported.`))})}(L,(U,Y)=>u(U,Y,B))});return{cancel:()=>{C.cancel(),w()}}};var Eg,V1,uf,Em={exports:{}},Qf={exports:{}},q0={exports:{}},H1=function(){if(uf)return Em.exports;uf=1;var v=(Eg||(Eg=1,Qf.exports=function(f,w){var C,I,L,B,U,Y,se,oe;for(I=f.length-(C=3&f.length),L=w,U=3432918353,Y=461845907,oe=0;oe>>16)*U&65535)<<16)&4294967295)<<15|se>>>17))*Y+(((se>>>16)*Y&65535)<<16)&4294967295)<<13|L>>>19))+((5*(L>>>16)&65535)<<16)&4294967295))+(((B>>>16)+58964&65535)<<16);switch(se=0,C){case 3:se^=(255&f.charCodeAt(oe+2))<<16;case 2:se^=(255&f.charCodeAt(oe+1))<<8;case 1:L^=se=(65535&(se=(se=(65535&(se^=255&f.charCodeAt(oe)))*U+(((se>>>16)*U&65535)<<16)&4294967295)<<15|se>>>17))*Y+(((se>>>16)*Y&65535)<<16)&4294967295}return L^=f.length,L=2246822507*(65535&(L^=L>>>16))+((2246822507*(L>>>16)&65535)<<16)&4294967295,L=3266489909*(65535&(L^=L>>>13))+((3266489909*(L>>>16)&65535)<<16)&4294967295,(L^=L>>>16)>>>0}),Qf.exports),u=(V1||(V1=1,q0.exports=function(f,w){for(var C,I=f.length,L=w^I,B=0;I>=4;)C=1540483477*(65535&(C=255&f.charCodeAt(B)|(255&f.charCodeAt(++B))<<8|(255&f.charCodeAt(++B))<<16|(255&f.charCodeAt(++B))<<24))+((1540483477*(C>>>16)&65535)<<16),L=1540483477*(65535&L)+((1540483477*(L>>>16)&65535)<<16)^(C=1540483477*(65535&(C^=C>>>24))+((1540483477*(C>>>16)&65535)<<16)),I-=4,++B;switch(I){case 3:L^=(255&f.charCodeAt(B+2))<<16;case 2:L^=(255&f.charCodeAt(B+1))<<8;case 1:L=1540483477*(65535&(L^=255&f.charCodeAt(B)))+((1540483477*(L>>>16)&65535)<<16)}return L=1540483477*(65535&(L^=L>>>13))+((1540483477*(L>>>16)&65535)<<16),(L^=L>>>15)>>>0}),q0.exports);return Em.exports=v,Em.exports.murmur3=v,Em.exports.murmur2=u,Em.exports}(),fd=Zn(H1);class _c{constructor(u,...f){Object.assign(this,f[0]||{}),this.type=u}}class Am extends _c{constructor(u,f={}){super("error",Object.assign({error:u},f))}}function Ac(v,u,f){f[v]&&f[v].indexOf(u)!==-1||(f[v]=f[v]||[],f[v].push(u))}function Mm(v,u,f){if(f&&f[v]){const w=f[v].indexOf(u);w!==-1&&f[v].splice(w,1)}}class hf{on(u,f){return this._listeners=this._listeners||{},Ac(u,f,this._listeners),this}off(u,f){return Mm(u,f,this._listeners),Mm(u,f,this._oneTimeListeners),this}once(u,f){return f?(this._oneTimeListeners=this._oneTimeListeners||{},Ac(u,f,this._oneTimeListeners),this):new Promise(w=>{this.once(u,w)})}fire(u,f){const w=typeof u=="string"?new _c(u,f):u,C=w.type;if(this.listens(C)){w.target=this;const I=this._listeners&&this._listeners[C]?this._listeners[C].slice():[];for(const U of I)U.call(this,w);const L=this._oneTimeListeners&&this._oneTimeListeners[C]?this._oneTimeListeners[C].slice():[];for(const U of L)Mm(C,U,this._oneTimeListeners),U.call(this,w);const B=this._eventedParent;if(B){const U=typeof this._eventedParentData=="function"?this._eventedParentData():this._eventedParentData;Object.assign(w,U),B.fire(w)}}else w instanceof Am&&console.error(w.error);return this}listens(u){return!!(this._listeners&&this._listeners[u]&&this._listeners[u].length>0||this._oneTimeListeners&&this._oneTimeListeners[u]&&this._oneTimeListeners[u].length>0||this._eventedParent&&this._eventedParent.listens(u))}setEventedParent(u,f){return this._eventedParent=u,this._eventedParentData=f,this}}class Mt{constructor(u){typeof u=="string"?this.name=u:(this.name=u.name,this.iconsetId=u.iconsetId)}static from(u){return new Mt(u)}static toString(u){return u.iconsetId?`${u.name}${u.iconsetId}`:u.name}static parse(u){const[f,w]=u.split("");return new Mt({name:f,iconsetId:w})}static isEqual(u,f){return u.name===f.name&&u.iconsetId===f.iconsetId}toString(){return Mt.toString(this)}serialize(){return{name:this.name,iconsetId:this.iconsetId}}}var tr,kr={},bn=function(){if(tr)return kr;tr=1;var v={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 u(I){return(I=Math.round(I))<0?0:I>255?255:I}function f(I){return u(I[I.length-1]==="%"?parseFloat(I)/100*255:parseInt(I))}function w(I){return(L=I[I.length-1]==="%"?parseFloat(I)/100:parseFloat(I))<0?0:L>1?1:L;var L}function C(I,L,B){return B<0?B+=1:B>1&&(B-=1),6*B<1?I+(L-I)*B*6:2*B<1?L:3*B<2?I+(L-I)*(2/3-B)*6:I}try{kr.parseCSSColor=function(I){var L,B=I.replace(/ /g,"").toLowerCase();if(B in v)return v[B].slice();if(B[0]==="#")return B.length===4?(L=parseInt(B.substr(1),16))>=0&&L<=4095?[(3840&L)>>4|(3840&L)>>8,240&L|(240&L)>>4,15&L|(15&L)<<4,1]:null:B.length===7&&(L=parseInt(B.substr(1),16))>=0&&L<=16777215?[(16711680&L)>>16,(65280&L)>>8,255&L,1]:null;var U=B.indexOf("("),Y=B.indexOf(")");if(U!==-1&&Y+1===B.length){var se=B.substr(0,U),oe=B.substr(U+1,Y-(U+1)).split(","),de=1;switch(se){case"rgba":if(oe.length!==4)return null;de=w(oe.pop());case"rgb":return oe.length!==3?null:[f(oe[0]),f(oe[1]),f(oe[2]),de];case"hsla":if(oe.length!==4)return null;de=w(oe.pop());case"hsl":if(oe.length!==3)return null;var xe=(parseFloat(oe[0])%360+360)%360/360,we=w(oe[1]),Ce=w(oe[2]),Re=Ce<=.5?Ce*(we+1):Ce+we-Ce*we,qe=2*Ce-Re;return[u(255*C(qe,Re,xe+1/3)),u(255*C(qe,Re,xe)),u(255*C(qe,Re,xe-1/3)),de];default:return null}}return null}}catch{}return kr}();class Mr{constructor(u,f,w,C=1){this.r=u,this.g=f,this.b=w,this.a=C}static parse(u){if(!u)return;if(u instanceof Mr)return u;if(typeof u!="string")return;const f=bn.parseCSSColor(u);return f?new Mr(f[0]/255,f[1]/255,f[2]/255,f[3]):void 0}toString(){const[u,f,w,C]=[this.r,this.g,this.b,this.a];return`rgba(${Math.round(255*u)},${Math.round(255*f)},${Math.round(255*w)},${C})`}toNonPremultipliedRenderColor(u){const{r:f,g:w,b:C,a:I}=this;return new qa(u,f,w,C,I)}toPremultipliedRenderColor(u){const{r:f,g:w,b:C,a:I}=this;return new Ja(u,f*I,w*I,C*I,I)}clone(){return new Mr(this.r,this.g,this.b,this.a)}}class sa{constructor(u,f,w,C,I,L=!1){if(this.premultiplied=!1,this.premultiplied=L,u){const B=u.image.height,U=B*B;this.premultiplied?(f=I===0?0:f/I*(B-1),w=I===0?0:w/I*(B-1),C=I===0?0:C/I*(B-1)):(f*=B-1,w*=B-1,C*=B-1),f=Math.max(0,Math.min(B-1,f)),w=Math.max(0,Math.min(B-1,w)),C=Math.max(0,Math.min(B-1,C));const Y=Math.floor(f),se=Math.floor(w),oe=Math.floor(C),de=Math.ceil(f),xe=Math.ceil(w),we=Math.ceil(C),Ce=f-Y,Re=w-se,qe=C-oe,nt=u.image.data,Ze=4*(Y+se*U+oe*B),ut=4*(Y+se*U+we*B),xt=4*(Y+xe*U+oe*B),bt=4*(Y+xe*U+we*B),Ht=4*(de+se*U+oe*B),Rt=4*(de+se*U+we*B),Vt=4*(de+xe*U+oe*B),Bt=4*(de+xe*U+we*B);this.r=jn(jn(jn(nt[Ze],nt[ut],qe),jn(nt[xt],nt[bt],qe),Re),jn(jn(nt[Ht],nt[Rt],qe),jn(nt[Vt],nt[Bt],qe),Re),Ce)/255*(this.premultiplied?I:1),this.g=jn(jn(jn(nt[Ze+1],nt[ut+1],qe),jn(nt[xt+1],nt[bt+1],qe),Re),jn(jn(nt[Ht+1],nt[Rt+1],qe),jn(nt[Vt+1],nt[Bt+1],qe),Re),Ce)/255*(this.premultiplied?I:1),this.b=jn(jn(jn(nt[Ze+2],nt[ut+2],qe),jn(nt[xt+2],nt[bt+2],qe),Re),jn(jn(nt[Ht+2],nt[Rt+2],qe),jn(nt[Vt+2],nt[Bt+2],qe),Re),Ce)/255*(this.premultiplied?I:1),this.a=I}else this.r=f,this.g=w,this.b=C,this.a=I}toArray(){const{r:u,g:f,b:w,a:C}=this;return[255*u,255*f,255*w,C]}toHslaArray(){let{r:u,g:f,b:w,a:C}=this;if(this.premultiplied){if(C===0)return[0,0,0,0];const we=1/C;u*=we,f*=we,w*=we}const I=Math.min(Math.max(u,0),1),L=Math.min(Math.max(f,0),1),B=Math.min(Math.max(w,0),1),U=Math.min(I,L,B),Y=Math.max(I,L,B),se=Y-U,oe=.5*(U+Y);if(se===0)return[0,0,100*oe,C];const de=oe>.5?se/(2-Y-U):se/(Y+U);let xe;switch(Y){case I:xe=60*((L-B)/se+(Ljn(w,u[C],f))}Mr.black=new Mr(0,0,0,1),Mr.white=new Mr(1,1,1,1),Mr.transparent=new Mr(0,0,0,0),Mr.red=new Mr(1,0,0,1),Mr.blue=new Mr(0,0,1,1);var Vh=Object.freeze({__proto__:null,array:pd,color:function(v,u,f){return new Mr(jn(v.r,u.r,f),jn(v.g,u.g,f),jn(v.b,u.b,f),jn(v.a,u.a,f))},number:jn});class Tu extends Error{constructor(u,f){super(f),this.message=f,this.key=u}}class Ag{constructor(u,f=[]){this.parent=u,this.bindings={};for(const[w,C]of f)this.bindings[w]=C}concat(u){return new Ag(this,u)}get(u){if(this.bindings[u])return this.bindings[u];if(this.parent)return this.parent.get(u);throw new Error(`${u} not found in scope.`)}has(u){return!!this.bindings[u]||!!this.parent&&this.parent.has(u)}}const Jf={kind:"null"},un={kind:"number"},wi={kind:"string"},Oi={kind:"boolean"},_h={kind:"color"},Rp={kind:"object"},qi={kind:"value"},Op={kind:"collator"},V0={kind:"formatted"},G1={kind:"resolvedImage"};function Eu(v,u){return{kind:"array",itemType:v,N:u}}function Al(v){if(v.kind==="array"){const u=Al(v.itemType);return typeof v.N=="number"?`array<${u}, ${v.N}>`:v.itemType.kind==="value"?"array":`array<${u}>`}return v.kind}const iM=[Jf,un,wi,Oi,_h,V0,Rp,Eu(qi),G1];function H0(v,u){if(u.kind==="error")return null;if(v.kind==="array"){if(u.kind==="array"&&(u.N===0&&u.itemType.kind==="value"||!H0(v.itemType,u.itemType))&&(typeof v.N!="number"||v.N===u.N))return null}else{if(v.kind===u.kind)return null;if(v.kind==="value"){for(const f of iM)if(!H0(f,u))return null}}return`Expected ${Al(v)} but found ${Al(u)} instead.`}function W1(v,u){return u.some(f=>f.kind===v.kind)}function Fp(v,u){return u.some(f=>f==="null"?v===null:f==="array"?Array.isArray(v):f==="object"?v&&!Array.isArray(v)&&typeof v=="object":f===typeof v)}function Bp(v,u){return v.kind==="array"&&u.kind==="array"?v.N===u.N&&Bp(v.itemType,u.itemType):v.kind===u.kind}class aw{constructor(u,f,w){this.sensitivity=u?f?"variant":"case":f?"accent":"base",this.locale=w,this.collator=new Intl.Collator(this.locale?this.locale:[],{sensitivity:this.sensitivity,usage:"search"})}compare(u,f){return this.collator.compare(u,f)}resolvedLocale(){return new Intl.Collator(this.locale?this.locale:[]).resolvedOptions().locale}}class K1{constructor(u,f,w,C,I){this.text=u.normalize?u.normalize():u,this.image=f,this.scale=w,this.fontStack=C,this.textColor=I}}class Md{constructor(u){this.sections=u}static fromString(u){return new Md([new K1(u,null,null,null,null)])}isEmpty(){return this.sections.length===0||!this.sections.some(u=>u.text.length!==0||!!u.image&&u.image.hasPrimary())}static factory(u){return u instanceof Md?u:Md.fromString(u)}toString(){return this.sections.length===0?"":this.sections.map(u=>u.text).join("")}serialize(){const u=["format"];for(const f of this.sections){if(f.image){const C=f.image.getPrimary().id.toString();u.push(["image",C]);continue}u.push(f.text);const w={};f.fontStack&&(w["text-font"]=["literal",f.fontStack.split(",")]),f.scale&&(w["font-scale"]=f.scale),f.textColor&&(w["text-color"]=["rgba"].concat(f.textColor.toNonPremultipliedRenderColor(null).toArray())),u.push(w)}return u}}class Im{constructor(u,f={}){this.id=Mt.from(u),this.params=f.params,this.sx=f.sx||1,this.sy=f.sy||1}toString(){return JSON.stringify(this)}static parse(u){let f,w,C,I;try{({id:f,params:w,sx:C,sy:I}=JSON.parse(u)||{})}catch{return null}return f?new Im(f,{params:w,sx:C,sy:I}):null}scaleSelf(u,f=u){return this.sx*=u,this.sy*=f,this}}class Id{constructor(u,f,w,C,I=!1){this.primaryId=Mt.from(u),this.primaryOptions=f,w&&(this.secondaryId=Mt.from(w)),this.secondaryOptions=C,this.available=I}toString(){return this.primaryId&&this.secondaryId?`[${this.primaryId.name},${this.secondaryId.name}]`:this.primaryId.name}hasPrimary(){return!!this.primaryId}getPrimary(){return new Im(this.primaryId,this.primaryOptions)}hasSecondary(){return!!this.secondaryId}getSecondary(){return this.secondaryId?new Im(this.secondaryId,this.secondaryOptions):null}static from(u){return typeof u=="string"?Id.build({name:u}):u}static build(u,f,w,C){return!u||typeof u=="object"&&!("name"in u)?null:new Id(u,w,f,C)}}function mf(v,u,f,w){return typeof v=="number"&&v>=0&&v<=255&&typeof u=="number"&&u>=0&&u<=255&&typeof f=="number"&&f>=0&&f<=255?w===void 0||typeof w=="number"&&w>=0&&w<=1?null:`Invalid rgba value [${[v,u,f,w].join(", ")}]: 'a' must be between 0 and 1.`:`Invalid rgba value [${(typeof w=="number"?[v,u,f,w]:[v,u,f]).join(", ")}]: 'r', 'g', and 'b' must be between 0 and 255.`}function ep(v){if(v===null||typeof v=="string"||typeof v=="boolean"||typeof v=="number"||v instanceof Mr||v instanceof aw||v instanceof Md||v instanceof Id)return!0;if(Array.isArray(v)){for(const u of v)if(!ep(u))return!1;return!0}if(typeof v=="object"){for(const u in v)if(!ep(v[u]))return!1;return!0}return!1}function yl(v){if(v===null)return Jf;if(typeof v=="string")return wi;if(typeof v=="boolean")return Oi;if(typeof v=="number")return un;if(v instanceof Mr)return _h;if(v instanceof aw)return Op;if(v instanceof Md)return V0;if(v instanceof Id)return G1;if(Array.isArray(v)){const u=v.length;let f;for(const w of v){const C=yl(w);if(f){if(f===C)continue;f=qi;break}f=C}return Eu(f||qi,u)}return Rp}function zn(v){const u=typeof v;return v===null?"":u==="string"||u==="number"||u==="boolean"?String(v):v instanceof Md||v instanceof Id||v instanceof Mr?v.toString():JSON.stringify(v)}class Wr{constructor(u,f){this.type=u,this.value=f}static parse(u,f){if(u.length!==2)return f.error(`'literal' expression requires exactly one argument, but found ${u.length-1} instead.`);if(!ep(u[1]))return f.error("invalid value");const w=u[1];let C=yl(w);const I=f.expectedType;return C.kind!=="array"||C.N!==0||!I||I.kind!=="array"||typeof I.N=="number"&&I.N!==0||(C=I),new Wr(C,w)}evaluate(){return this.value}eachChild(){}outputDefined(){return!0}serialize(){return this.type.kind==="array"||this.type.kind==="object"?["literal",this.value]:this.value instanceof Mr?["rgba"].concat(this.value.toNonPremultipliedRenderColor(null).toArray()):this.value instanceof Md?this.value.serialize():this.value}}class sl{constructor(u){this.name="ExpressionEvaluationError",this.message=u}toJSON(){return this.message}}const Gn={string:wi,number:un,boolean:Oi,object:Rp};class Pm{constructor(u,f){this.type=u,this.args=f}static parse(u,f){if(u.length<2)return f.error("Expected at least one argument.");let w,C=1;const I=u[0];if(I==="array"){let B,U;if(u.length>2){const Y=u[1];if(typeof Y!="string"||!(Y in Gn)||Y==="object")return f.error('The item type argument of "array" must be one of string, number, boolean',1);B=Gn[Y],C++}else B=qi;if(u.length>3){if(u[2]!==null&&(typeof u[2]!="number"||u[2]<0||u[2]!==Math.floor(u[2])))return f.error('The length argument to "array" must be a positive integer literal',2);U=u[2],C++}w=Eu(B,U)}else w=Gn[I];const L=[];for(;Cu.outputDefined())}serialize(){const u=this.type,f=[u.kind];if(u.kind==="array"){const w=u.itemType;if(w.kind==="string"||w.kind==="number"||w.kind==="boolean"){f.push(w.kind);const C=u.N;(typeof C=="number"||this.args.length>1)&&f.push(C)}}return f.concat(this.args.map(w=>w.serialize()))}}class Hh{constructor(u){this.type=V0,this.sections=u}static parse(u,f){if(u.length<2)return f.error("Expected at least one argument.");const w=u[1];if(!Array.isArray(w)&&typeof w=="object")return f.error("First argument must be an image or text section.");const C=[];let I=!1;for(let L=1;L<=u.length-1;++L){const B=u[L];if(I&&typeof B=="object"&&!Array.isArray(B)){I=!1;let U=null;if(B["font-scale"]&&(U=f.parseObjectValue(B["font-scale"],L,"font-scale",un),!U))return null;let Y=null;if(B["text-font"]&&(Y=f.parseObjectValue(B["text-font"],L,"text-font",Eu(wi)),!Y))return null;let se=null;if(B["text-color"]&&(se=f.parseObjectValue(B["text-color"],L,"text-color",_h),!se))return null;const oe=C[C.length-1];oe.scale=U,oe.font=Y,oe.textColor=se}else{const U=f.parse(u[L],L,qi);if(!U)return null;const Y=U.type.kind;if(Y!=="string"&&Y!=="value"&&Y!=="null"&&Y!=="resolvedImage")return f.error("Formatted text type must be 'string', 'value', 'image' or 'null'.");I=!0,C.push({content:U,scale:null,font:null,textColor:null})}}return new Hh(C)}evaluate(u){return new Md(this.sections.map(f=>{const w=f.content.evaluate(u);return Bp(yl(w),G1)?new K1("",w,null,null,null):new K1(zn(w),null,f.scale?f.scale.evaluate(u):null,f.font?f.font.evaluate(u).join(","):null,f.textColor?f.textColor.evaluate(u):null)}))}eachChild(u){for(const f of this.sections)u(f.content),f.scale&&u(f.scale),f.font&&u(f.font),f.textColor&&u(f.textColor)}outputDefined(){return!1}serialize(){const u=["format"];for(const f of this.sections){u.push(f.content.serialize());const w={};f.scale&&(w["font-scale"]=f.scale.serialize()),f.font&&(w["text-font"]=f.font.serialize()),f.textColor&&(w["text-color"]=f.textColor.serialize()),u.push(w)}return u}}class _n{constructor(u,f,w,C){this._imageWarnHistory={},this.type=G1,this.namePrimary=u,this.nameSecondary=f,w&&(this.paramsPrimary=w.params,this.iconsetIdPrimary=w.iconset?w.iconset.id:void 0),C&&(this.paramsSecondary=C.params,this.iconsetIdSecondary=C.iconset?C.iconset.id:void 0)}static parse(u,f){if(u.length<2)return f.error("Expected two or more arguments.");let w=1;const C=[];function I(){if(wMt.isEqual(L,I)),C.available){const L=C.getSecondary()?C.getSecondary().id:null;L&&(C.available=u.availableImages.some(B=>Mt.isEqual(B,L)))}}return C}eachChild(u){if(u(this.namePrimary),this.paramsPrimary)for(const f in this.paramsPrimary)this.paramsPrimary[f]&&u(this.paramsPrimary[f]);if(this.nameSecondary&&(u(this.nameSecondary),this.paramsSecondary))for(const f in this.paramsSecondary)this.paramsSecondary[f]&&u(this.paramsSecondary[f])}outputDefined(){return!1}serializeOptions(u,f){const w={};if(f&&(w.iconset={id:f}),u){w.params={};for(const C in u)u[C]&&(w.params[C]=u[C].serialize())}return Object.keys(w).length>0?w:void 0}serialize(){const u=["image",this.namePrimary.serialize()];if(this.paramsPrimary||this.iconsetIdPrimary){const f=this.serializeOptions(this.paramsPrimary,this.iconsetIdPrimary);f&&u.push(f)}if(this.nameSecondary&&(u.push(this.nameSecondary.serialize()),this.paramsSecondary||this.iconsetIdSecondary)){const f=this.serializeOptions(this.paramsSecondary,this.iconsetIdSecondary);f&&u.push(f)}return u}}function G0(v){return hv(v)?"string":Y1(v)?"number":bx(v)?"boolean":Array.isArray(v)?"array":v===null?"null":iw(v)?"object":typeof v}function iw(v){return v!=null&&!Array.isArray(v)&&typeof v!="function"&&!(v instanceof String||v instanceof Number||v instanceof Boolean)&&typeof v=="object"}function hv(v){return typeof v=="string"||v instanceof String}function Y1(v){return typeof v=="number"||v instanceof Number}function bx(v){return typeof v=="boolean"||v instanceof Boolean}const tp={"to-boolean":Oi,"to-color":_h,"to-number":un,"to-string":wi};class Gh{constructor(u,f){this.type=u,this.args=f}static parse(u,f){if(u.length<2)return f.error("Expected at least one argument.");const w=u[0],C=[];let I=Jf;if(w==="to-array"){if(!Array.isArray(u[1]))return null;const L=u[1].length;if(f.expectedType){if(f.expectedType.kind!=="array")return f.error(`Expected ${f.expectedType.kind} but found array.`);I=Eu(f.expectedType.itemType,L)}else{if(!(L>0&&ep(u[1][0])))return null;I=Eu(yl(u[1][0]),L)}for(let B=0;B4?`Invalid rbga value ${JSON.stringify(f)}: expected an array containing either three or four numeric values.`:mf(f[0],f[1],f[2],f[3]),!w))return new Mr(f[0]/255,f[1]/255,f[2]/255,f[3])}throw new sl(w||`Could not parse color from value '${typeof f=="string"?f:String(JSON.stringify(f))}'`)}if(this.type.kind==="number"){let f=null;for(const w of this.args){if(f=w.evaluate(u),f===null)return 0;const C=Number(f);if(!isNaN(C))return C}throw new sl(`Could not convert ${JSON.stringify(f)} to number.`)}return this.type.kind==="formatted"?Md.fromString(zn(this.args[0].evaluate(u))):this.type.kind==="resolvedImage"?Id.build(zn(this.args[0].evaluate(u))):this.type.kind==="array"?this.args.map(f=>f.evaluate(u)):zn(this.args[0].evaluate(u))}eachChild(u){this.args.forEach(u)}outputDefined(){return this.args.every(u=>u.outputDefined())}serialize(){if(this.type.kind==="formatted")return new Hh([{content:this.args[0],scale:null,font:null,textColor:null}]).serialize();if(this.type.kind==="resolvedImage")return new _n(this.args[0]).serialize();const u=this.type.kind==="array"?[]:[`to-${this.type.kind}`];return this.eachChild(f=>{u.push(f.serialize())}),u}}const sp=["Unknown","Point","LineString","Polygon"];class Lm{constructor(u,f,w){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=u,this.options=f,this.iconImageUseTheme=w}id(){return this.feature&&this.feature.id!==void 0?this.feature.id:null}geometryType(){return this.feature?typeof this.feature.type=="number"?sp[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(u){return this.globals.brightness||0}distanceFromCenter(){if(this.featureTileCoord&&this.featureDistanceData){const u=this.featureDistanceData.center,f=this.featureDistanceData.scale,{x:w,y:C}=this.featureTileCoord;return this.featureDistanceData.bearing[0]*(w*f-u[0])+this.featureDistanceData.bearing[1]*(C*f-u[1])}return 0}parseColor(u){let f=this._parseColorCache[u];return f||(f=this._parseColorCache[u]=Mr.parse(u)),f}getConfig(u){return this.options?this.options.get(u):null}}class wc{constructor(u,f,w,C,I){this.name=u,this.type=f,this._evaluate=w,this.args=C,this._overloadIndex=I}evaluate(u){if(!this._evaluate){const f=wc.definitions[this.name];this._evaluate=Array.isArray(f)?f[2]:f.overloads[this._overloadIndex][1]}return this._evaluate(u,this.args)}eachChild(u){this.args.forEach(u)}outputDefined(){return!1}serialize(){return[this.name].concat(this.args.map(u=>u.serialize()))}static parse(u,f){const w=u[0],C=wc.definitions[w];if(!C)return f.error(`Unknown expression "${w}". If you wanted a literal array, use ["literal", [...]].`,0);const I=Array.isArray(C)?C[0]:C.type,L=Array.isArray(C)?[[C[1],C[2]]]:C.overloads,B=[];let U=null,Y=-1;for(const[se,oe]of L){if(Array.isArray(se)&&se.length!==u.length-1)continue;B.push(se),Y++,U=new yw(f.registry,f.path,null,f.scope,void 0,f._scope,f.options,f.iconImageUseTheme);const de=[];let xe=!1;for(let we=1;wede)).map(ff).join(" | "),oe=[];for(let de=1;def;){if(w-f>600){const U=w-f+1,Y=u-f+1,se=Math.log(U),oe=.5*Math.exp(2*se/3),de=.5*Math.sqrt(se*oe*(U-oe)/U)*(Y-U/2<0?-1:1);Tj(v,u,Math.max(f,Math.floor(u-Y*oe/U+de)),Math.min(w,Math.floor(u+(U-Y)*oe/U+de)),C)}const I=v[u];let L=f,B=w;for(Wl(v,f,u),C(v[w],I)>0&&Wl(v,f,w);L0;)B--}C(v[f],I)===0?Wl(v,f,B):(B++,Wl(v,B,w)),B<=u&&(f=B+1),u<=B&&(w=B-1)}}function Wl(v,u,f){const w=v[u];v[u]=v[f],v[f]=w}function mv(v,u){return vu?1:0}function Ej(v){let u=0;for(let f,w,C=0,I=v.length,L=I-1;C=u[2]||v[1]<=u[1]||v[3]>=u[3])}function i4(v,u,f){const w=v[0]-u[0],C=v[1]-u[1],I=v[0]-f[0],L=v[1]-f[1];return w*L-I*C===0&&w*I<=0&&C*L<=0}function _x(v,u,f){return u[1]>v[1]!=f[1]>v[1]&&v[0]<(f[0]-u[0])*(v[1]-u[1])/(f[1]-u[1])+u[0]}function Bl(v,u,f=!1){let w=!1;for(let C=0,I=u.length;C0&&B<0||L<0&&B>0}function Gc(v,u,f,w){return(C=[w[0]-f[0],w[1]-f[1]])[0]*(I=[u[0]-v[0],u[1]-v[1]])[1]-C[1]*I[0]!==0&&!(!Pd(v,u,f,w)||!Pd(f,w,v,u));var C,I}function Z1(v){const u=new ds(Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY),f=new ds(Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY);for(const w of v[0])u.x>w.x&&(u.x=w.x),u.y>w.y&&(u.y=w.y),f.xf[2]){const C=.5*w;let I=v[0]-f[0]>C?-w:f[0]-v[0]>C?w:0;I===0&&(I=v[0]-f[2]>C?-w:f[2]-v[0]>C?w:0),v[0]+=I}pf(u,v)}function pv(v,u,f,w){const C=Math.pow(2,w.z)*rp,I=[w.x*rp,w.y*rp],L=[];if(!v)return L;for(const B of v)for(const U of B){const Y=[U.x+I[0],U.y+I[1]];Mc(Y,u,f,C),L.push(Y)}return L}function dw(v,u,f,w){const C=Math.pow(2,w.z)*rp,I=[w.x*rp,w.y*rp],L=[];if(!v)return L;for(const U of v){const Y=[];for(const se of U){const oe=[se.x+I[0],se.y+I[1]];pf(u,oe),Y.push(oe)}L.push(Y)}if(u[2]-u[0]<=C/2){(B=u)[0]=B[1]=1/0,B[2]=B[3]=-1/0;for(const U of L)for(const Y of U)Mc(Y,u,f,C)}var B;return L}class Mg{constructor(u,f){this.type=Oi,this.geojson=u,this.geometries=f}static parse(u,f){if(u.length!==2)return f.error(`'within' expression requires exactly one argument, but found ${u.length-1} instead.`);if(ep(u[1])){const w=u[1];if(w.type==="FeatureCollection")for(let C=0;Cf)return uw(I,L,(f-(w-B))/B)}return u[u.length-1]}pointToSegmentDistance(u,f,w){let[C,I]=f,L=Dm(w[0]-C)*this.kx,B=(w[1]-I)*this.ky;if(L!==0||B!==0){const U=(Dm(u[0]-C)*this.kx*L+(u[1]-I)*this.ky*B)/(L*L+B*B);U>1?(C=w[0],I=w[1]):U>0&&(C+=L/this.kx*U,I+=B/this.ky*U)}return L=Dm(u[0]-C)*this.kx,B=(u[1]-I)*this.ky,Math.sqrt(L*L+B*B)}pointOnLine(u,f){let w=1/0,C=u[0][0],I=u[0][1],L=0,B=0;for(let U=0;U1?(Y=u[U+1][0],se=u[U+1][1]):xe>0&&(Y+=oe/this.kx*xe,se+=de/this.ky*xe)),oe=Dm(f[0]-Y)*this.kx,de=(f[1]-se)*this.ky;const we=oe*oe+de*de;weI.index||C.index===I.index&&C.t>I.t){const Y=C;C=I,I=Y}const L=[C.point],B=C.index+1,U=I.index;!Pj(w[B],L[0])&&B<=U&&L.push(w[B]);for(let Y=B+1;Y<=U;Y++)L.push(w[Y]);return Pj(w[U],I.point)||L.push(I.point),L}lineSliceAlong(u,f,w){let C=0;const I=[];for(let L=0;Lu&&I.length===0&&I.push(uw(B,U,(u-(C-Y))/Y)),C>=f)return I.push(uw(B,U,(f-(C-Y))/Y)),I;C>u&&I.push(U)}return I}bufferPoint(u,f){const w=f/this.ky,C=f/this.kx;return[u[0]-C,u[1]-w,u[0]+C,u[1]+w]}bufferBBox(u,f){const w=f/this.ky,C=f/this.kx;return[u[0]-C,u[1]-w,u[2]+C,u[3]+w]}insideBBox(u,f){return Dm(u[0]-f[0])>=0&&Dm(u[0]-f[2])<=0&&u[1]>=f[1]&&u[1]<=f[3]}}function Pj(v,u){return v[0]===u[0]&&v[1]===u[1]}function uw(v,u,f){const w=Dm(u[0]-v[0]);return[v[0]+w*f,v[1]+(u[1]-v[1])*f]}function Dm(v){for(;v<-180;)v+=360;for(;v>180;)v-=360;return v}class wx{constructor(u=[],f=(w,C)=>wC?1:0){if(this.data=u,this.length=this.data.length,this.compare=f,this.length>0)for(let w=(this.length>>1)-1;w>=0;w--)this._down(w)}push(u){this.data.push(u),this._up(this.length++)}pop(){if(this.length===0)return;const u=this.data[0],f=this.data.pop();return--this.length>0&&(this.data[0]=f,this._down(0)),u}peek(){return this.data[0]}_up(u){const{data:f,compare:w}=this,C=f[u];for(;u>0;){const I=u-1>>1,L=f[I];if(w(C,L)>=0)break;f[u]=L,u=I}f[u]=C}_down(u){const{data:f,compare:w}=this,C=this.length>>1,I=f[u];for(;u=0)break;f[u]=f[L],u=L}f[u]=I}}var Sr=8192;function hw(v,u){return u.dist-v.dist}function mw(v){const u=[1/0,1/0,-1/0,-1/0];if(u.length!==v.length)return!1;for(let f=0;f=v[0]&&v[1]v[1])return[null,null];const f=K0(v);if(u){if(f===2)return[v,null];const w=Math.floor(f/2);return[[v[0],v[0]+w],[v[0]+w,v[1]]]}{if(f===1)return[v,null];const w=Math.floor(f/2)-1;return[[v[0],v[0]+w],[v[0]+w+1,v[1]]]}}function jx(v,u){const f=[1/0,1/0,-1/0,-1/0];if(!gf(u,v.length))return f;for(let w=u[0];w<=u[1];++w)pf(f,v[w]);return f}function J1(v){const u=[1/0,1/0,-1/0,-1/0];for(let f=0;fu[2]&&(w=v[0]-u[2]),v[1]>u[3]&&(C=v[1]-u[3]),v[3]=w)return w;if(W0(C,I)){if(fw(v,u))return 0}else if(fw(u,v))return 0;let L=w;for(const B of v)for(let U=0,Y=B.length,se=Y-1;U=I)continue;const se=Y.range1;if(K0(se)<=B){if(!gf(se,v.length))return NaN;if(u){const oe=Ko(v,se,f,w);if((I=Math.min(I,oe))===0)return I}else for(let oe=se[0];oe<=se[1];++oe){const de=oM(v[oe],f,w);if((I=Math.min(I,de))===0)return I}}else{const oe=yv(se,u);if(oe[0]!==null){const de=vv(jx(v,oe[0]),U,w);de=L)continue;const oe=se.range1,de=se.range2;if(K0(oe)<=U&&K0(de)<=Y){if(!gf(oe,v.length)||!gf(de,f.length))return NaN;if(u&&w?L=Math.min(L,oD(v,oe,f,de,C)):u||w?u&&!w?L=Math.min(L,d4(f,de,v,oe,C)):!u&&w&&(L=Math.min(L,d4(v,oe,f,de,C))):L=Math.min(L,h4(v,oe,f,de,C)),L===0)return L}else{const xe=yv(oe,u),we=yv(de,w);Lj(B,L,C,v,f,xe[0],we[0]),Lj(B,L,C,v,f,xe[0],we[1]),Lj(B,L,C,v,f,xe[1],we[0]),Lj(B,L,C,v,f,xe[1],we[1])}}return L}function pw(v,u,f,w,C=1/0){let I=C;const L=jx(v,[0,v.length-1]);for(const B of f)if(!(I!==1/0&&vv(L,jx(B,[0,B.length-1]),w)>=I)&&(I=Math.min(I,ap(v,u,B,!0,w,I)),I===0))return I;return I}function bv(v,u,f,w,C=1/0){let I=C;const L=jx(v,[0,v.length-1]);for(const B of f){if(I!==1/0&&vv(L,J1(B),w)>=I)continue;const U=cD(v,u,B,w,I);if(isNaN(U))return U;if((I=Math.min(I,U))===0)return I}return I}function Dj(v){return v==="Point"||v==="MultiPoint"||v==="LineString"||v==="MultiLineString"||v==="Polygon"||v==="MultiPolygon"}class Y0{constructor(u,f){this.type=un,this.geojson=u,this.geometries=f}static parse(u,f){if(u.length!==2)return f.error(`'distance' expression requires either one argument, but found ' ${u.length-1} instead.`);if(ep(u[1])){const w=u[1];if(w.type==="FeatureCollection"){for(let C=0;C{u&&!Z0(f)&&(u=!1)}),u}function X0(v){if(v instanceof wc&&v.name==="feature-state")return!1;let u=!0;return v.eachChild(f=>{u&&!X0(f)&&(u=!1)}),u}function Wh(v,u){if(v instanceof wc&&u.indexOf(v.name)>=0)return!1;let f=!0;return v.eachChild(w=>{f&&!Wh(w,u)&&(f=!1)}),f}function Rj(v,u,f){return[v,u,f].filter(Boolean).join("")}function gw(v,u){switch(v){case"string":return zn(u);case"number":return+u;case"boolean":return!!u;case"color":return Mr.parse(u);case"formatted":return Md.fromString(zn(u));case"resolvedImage":return Id.build(zn(u))}return u}function lM(v,u,f,w){return w!==void 0&&(v=w*Math.round(v/w)),u!==void 0&&vf&&(v=f),v}class _v{constructor(u,f,w,C=!1){this.type=u,this.key=f,this.scope=w,this.featureConstant=C}static parse(u,f){let w=f.expectedType;if(w==null&&(w=qi),u.length<2||u.length>3)return f.error("Invalid number of arguments for 'config' expression.");const C=f.parse(u[1],1);if(!(C instanceof Wr))return f.error("Key name of 'config' expression must be a string literal.");let I,L=!0;const B=zn(C.value);if(u.length>=3){const U=f.parse(u[2],2);if(!(U instanceof Wr))return f.error("Scope of 'config' expression must be a string literal.");I=zn(U.value)}if(f.options){const U=Rj(B,I,f._scope),Y=f.options.get(U);Y&&(L=Z0(Y.value||Y.default))}return new _v(w,B,I,L)}evaluate(u){const f=Rj(this.key,this.scope,u.scope),w=u.getConfig(f);if(!w)return null;const{type:C,value:I,values:L,minValue:B,maxValue:U,stepValue:Y}=w,se=w.default.evaluate(u);let oe=se;if(I){const de=u.scope;u.scope=(de||"").split("").slice(1).join(""),oe=I.evaluate(u),u.scope=de}return C&&(oe=gw(C,oe)),oe===void 0||B===void 0&&U===void 0&&Y===void 0||(typeof oe=="number"?oe=lM(oe,B,U,Y):Array.isArray(oe)&&(oe=oe.map(de=>typeof de=="number"?lM(de,B,U,Y):de))),I!==void 0&&oe!==void 0&&L&&!L.includes(oe)&&(oe=se,C&&(oe=gw(C,oe))),(C&&C!==this.type||oe!==void 0&&!Bp(yl(oe),this.type))&&(oe=gw(this.type.kind,oe)),oe}eachChild(){}outputDefined(){return!1}serialize(){const u=["config",this.key];return this.scope&&u.concat(this.scope),u}}class xw{constructor(u,f){this.type=f.type,this.name=u,this.boundExpression=f}static parse(u,f){if(u.length!==2||typeof u[1]!="string")return f.error("'var' expression requires exactly one string literal argument.");const w=u[1];return f.scope.has(w)?new xw(w,f.scope.get(w)):f.error(`Unknown variable "${w}". Make sure "${w}" has been bound in an enclosing "let" expression before using it.`,1)}evaluate(u){return this.boundExpression.evaluate(u)}eachChild(){}outputDefined(){return!1}serialize(){return["var",this.name]}}class yw{constructor(u,f=[],w,C=new Ag,I=[],L,B,U){this.registry=u,this.path=f,this.key=f.map(Y=>typeof Y=="string"?`['${Y}']`:`[${Y}]`).join(""),this.scope=C,this.errors=I,this.expectedType=w,this._scope=L,this.options=B,this.iconImageUseTheme=U}parse(u,f,w,C,I={}){return f||w?this.concat(f,null,w,C)._parse(u,I):this._parse(u,I)}parseObjectValue(u,f,w,C,I,L={}){return this.concat(f,w,C,I)._parse(u,L)}_parse(u,f){function w(C,I,L){return L==="assert"?new Pm(I,[C]):L==="coerce"?new Gh(I,[C]):C}if(u!==null&&typeof u!="string"&&typeof u!="boolean"&&typeof u!="number"||(u=["literal",u]),Array.isArray(u)){if(u.length===0)return this.error('Expected an array with at least one element. If you wanted a literal array, use ["literal", []].');const C=typeof u[0]=="string"?this.registry[u[0]]:void 0;if(C){let I=C.parse(u,this);if(!I)return null;if(this.expectedType){const L=this.expectedType,B=I.type;if(L.kind!=="string"&&L.kind!=="number"&&L.kind!=="boolean"&&L.kind!=="object"&&L.kind!=="array"||B.kind!=="value")if(L.kind!=="color"&&L.kind!=="formatted"&&L.kind!=="resolvedImage"||B.kind!=="value"&&B.kind!=="string"){if(this.checkSubtype(L,B))return null}else I=w(I,L,f.typeAnnotation||"coerce");else I=w(I,L,f.typeAnnotation||"assert")}if(!(I instanceof Wr)&&I.type.kind!=="resolvedImage"&&Oj(I)){const L=new Lm(this._scope,this.options,this.iconImageUseTheme);try{I=new Wr(I.type,I.evaluate(L))}catch(B){return this.error(B.message),null}}return I}return Gh.parse(["to-array",u],this)}return this.error(u===void 0?"'undefined' value invalid. Use null instead.":typeof u=="object"?'Bare objects invalid. Use ["literal", {...}] instead.':`Expected an array, but found ${typeof u} instead.`)}concat(u,f,w,C){let I=typeof u=="number"?this.path.concat(u):this.path;I=typeof f=="string"?I.concat(f):I;const L=C?this.scope.concat(C):this.scope;return new yw(this.registry,I,w||null,L,this.errors,this._scope,this.options,this.iconImageUseTheme)}error(u,...f){const w=`${this.key}${f.map(C=>`[${C}]`).join("")}`;this.errors.push(new Tu(w,u))}checkSubtype(u,f){const w=H0(u,f);return w&&this.error(w),w}}function Oj(v){if(v instanceof xw)return Oj(v.boundExpression);if(v instanceof wc&&v.name==="error"||v instanceof ow||v instanceof Mg||v instanceof Y0||v instanceof _v)return!1;const u=v instanceof Gh||v instanceof Pm;let f=!0;return v.eachChild(w=>{f=u?f&&Oj(w):f&&w instanceof Wr}),!!f&&Z0(v)&&Wh(v,["zoom","heatmap-density","worldview","line-progress","raster-value","sky-radial-progress","accumulated","is-supported-script","pitch","distance-from-center","measure-light","raster-particle-speed","is-active-floor"])}function vw(v,u){const f=v.length-1;let w,C,I=0,L=f,B=0;for(;I<=L;)if(B=Math.floor((I+L)/2),w=v[B],C=v[B+1],w<=u){if(B===f||uu))throw new sl("Input is not a number.");L=B-1}return 0}class bw{constructor(u,f,w){this.type=u,this.input=f,this.labels=[],this.outputs=[];for(const[C,I]of w)this.labels.push(C),this.outputs.push(I)}static parse(u,f){if(u.length-1<4)return f.error(`Expected at least 4 arguments, but found only ${u.length-1}.`);if((u.length-1)%2!=0)return f.error("Expected an even number of arguments.");const w=f.parse(u[1],1,un);if(!w)return null;const C=[];let I=null;f.expectedType&&f.expectedType.kind!=="value"&&(I=f.expectedType);for(let L=1;L=B)return f.error('Input/output pairs for "step" expressions must be arranged with input values in strictly ascending order.',Y);const oe=f.parse(U,se,I);if(!oe)return null;I=I||oe.type,C.push([B,oe])}return new bw(I,w,C)}evaluate(u){const f=this.labels,w=this.outputs;if(f.length===1)return w[0].evaluate(u);const C=this.input.evaluate(u);if(C<=f[0])return w[0].evaluate(u);const I=f.length;return C>=f[I-1]?w[I-1].evaluate(u):w[vw(f,C)].evaluate(u)}eachChild(u){u(this.input);for(const f of this.outputs)u(f)}outputDefined(){return this.outputs.every(u=>u.outputDefined())}serialize(){const u=["step",this.input.serialize()];for(let f=0;f0&&u.push(this.labels[f]),u.push(this.outputs[f].serialize());return u}}const Kh=.95047,jh=1.08883,m4=4/29,wv=6/29,f4=3*wv*wv,cM=wv*wv*wv,dM=Math.PI/180,p4=180/Math.PI;function Fj(v){return v>cM?Math.pow(v,1/3):v/f4+m4}function _w(v){return v>wv?v*v*v:f4*(v-m4)}function eb(v){return 255*(v<=.0031308?12.92*v:1.055*Math.pow(v,1/2.4)-.055)}function jv(v){return(v/=255)<=.04045?v/12.92:Math.pow((v+.055)/1.055,2.4)}function ww(v){const u=jv(v.r),f=jv(v.g),w=jv(v.b),C=Fj((.4124564*u+.3575761*f+.1804375*w)/Kh),I=Fj((.2126729*u+.7151522*f+.072175*w)/1);return{l:116*I-16,a:500*(C-I),b:200*(I-Fj((.0193339*u+.119192*f+.9503041*w)/jh)),alpha:v.a}}function Bj(v){let u=(v.l+16)/116,f=isNaN(v.a)?u:u+v.a/500,w=isNaN(v.b)?u:u-v.b/200;return u=1*_w(u),f=Kh*_w(f),w=jh*_w(w),new Mr(eb(3.2404542*f-1.5371385*u-.4985314*w),eb(-.969266*f+1.8760108*u+.041556*w),eb(.0556434*f-.2040259*u+1.0572252*w),v.alpha)}function uM(v,u,f){const w=u-v;return v+f*(w>180||w<-180?w-360*Math.round(w/360):w)}const Nv={forward:ww,reverse:Bj,interpolate:function(v,u,f){return{l:jn(v.l,u.l,f),a:jn(v.a,u.a,f),b:jn(v.b,u.b,f),alpha:jn(v.alpha,u.alpha,f)}}},Nx={forward:function(v){const{l:u,a:f,b:w}=ww(v),C=Math.atan2(w,f)*p4;return{h:C<0?C+360:C,c:Math.sqrt(f*f+w*w),l:u,alpha:v.a}},reverse:function(v){const u=v.h*dM,f=v.c;return Bj({l:v.l,a:Math.cos(u)*f,b:Math.sin(u)*f,alpha:v.alpha})},interpolate:function(v,u,f){return{h:uM(v.h,u.h,f),c:jn(v.c,u.c,f),l:jn(v.l,u.l,f),alpha:jn(v.alpha,u.alpha,f)}}};var g4=Object.freeze({__proto__:null,hcl:Nx,lab:Nv});class Jd{constructor(u,f,w,C,I){this.type=u,this.operator=f,this.interpolation=w,this.input=C,this.labels=[],this.outputs=[];for(const[L,B]of I)this.labels.push(L),this.outputs.push(B)}static interpolationFactor(u,f,w,C){let I=0;if(u.name==="exponential")I=tb(f,u.base,w,C);else if(u.name==="linear")I=tb(f,1,w,C);else if(u.name==="cubic-bezier"){const L=u.controlPoints;I=new on(L[0],L[1],L[2],L[3]).solve(tb(f,1,w,C))}return I}static parse(u,f){let[w,C,I,...L]=u;if(!Array.isArray(C)||C.length===0)return f.error("Expected an interpolation type expression.",1);if(C[0]==="linear")C={name:"linear"};else if(C[0]==="exponential"){const Y=C[1];if(typeof Y!="number")return f.error("Exponential interpolation requires a numeric base.",1,1);C={name:"exponential",base:Y}}else{if(C[0]!=="cubic-bezier")return f.error(`Unknown interpolation type ${String(C[0])}`,1,0);{const Y=C.slice(1);if(Y.length!==4||Y.some(se=>typeof se!="number"||se<0||se>1))return f.error("Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.",1);C={name:"cubic-bezier",controlPoints:Y}}}if(u.length-1<4)return f.error(`Expected at least 4 arguments, but found only ${u.length-1}.`);if(u.length-1>3&&(u.length-1)%2!=0)return f.error("Expected an even number of arguments.");if(I=f.parse(I,2,un),!I)return null;const B=[];let U=null;w==="interpolate-hcl"||w==="interpolate-lab"?U=_h:f.expectedType&&f.expectedType.kind!=="value"&&(U=f.expectedType);for(let Y=0;Y=se)return f.error('Input/output pairs for "interpolate" expressions must be arranged with input values in strictly ascending order.',de);const we=f.parse(oe,xe,U);if(!we)return null;U=U||we.type,B.push([se,we])}return U.kind==="number"||U.kind==="color"||U.kind==="array"&&U.itemType.kind==="number"&&typeof U.N=="number"?new Jd(U,w,C,I,B):f.error(`Type ${Al(U)} is not interpolatable.`)}evaluate(u){const f=this.labels,w=this.outputs;if(f.length===1)return w[0].evaluate(u);const C=this.input.evaluate(u);if(C<=f[0])return w[0].evaluate(u);const I=f.length;if(C>=f[I-1])return w[I-1].evaluate(u);const L=vw(f,C),B=Jd.interpolationFactor(this.interpolation,C,f[L],f[L+1]),U=w[L].evaluate(u),Y=w[L+1].evaluate(u);return this.operator==="interpolate"?Vh[this.type.kind.toLowerCase()](U,Y,B):this.operator==="interpolate-hcl"?Nx.reverse(Nx.interpolate(Nx.forward(U),Nx.forward(Y),B)):Nv.reverse(Nv.interpolate(Nv.forward(U),Nv.forward(Y),B))}eachChild(u){u(this.input);for(const f of this.outputs)u(f)}outputDefined(){return this.outputs.every(u=>u.outputDefined())}serialize(){let u;u=this.interpolation.name==="linear"?["linear"]:this.interpolation.name==="exponential"?this.interpolation.base===1?["linear"]:["exponential",this.interpolation.base]:["cubic-bezier",...this.interpolation.controlPoints];const f=[this.operator,u,this.input.serialize()];for(let w=0;wH0(C,B.type));return new sb(L?qi:w,I)}evaluate(u){let f,w=null,C=0;for(const I of this.args){if(C++,w=I.evaluate(u),w&&w instanceof Id&&!w.available&&(f||(f=w),w=null,C===this.args.length))return f;if(w!==null)break}return w}eachChild(u){this.args.forEach(u)}outputDefined(){return this.args.every(u=>u.outputDefined())}serialize(){const u=["coalesce"];return this.eachChild(f=>{u.push(f.serialize())}),u}}class kv{constructor(u,f){this.type=f.type,this.bindings=[].concat(u),this.result=f}evaluate(u){return this.result.evaluate(u)}eachChild(u){for(const f of this.bindings)u(f[1]);u(this.result)}static parse(u,f){if(u.length<4)return f.error(`Expected at least 3 arguments, but found ${u.length-1} instead.`);const w=[];for(let I=1;I=w.length)throw new sl("Array index out of bounds: index exceeds array size");if(f!==Math.floor(f))throw new sl("Array index must be an integer. Use at-interpolated for fractional indices");return w[f]}eachChild(u){u(this.index),u(this.input)}outputDefined(){return!1}serialize(){return["at",this.index.serialize(),this.input.serialize()]}}class jw{constructor(u,f,w){this.type=u,this.index=f,this.input=w}static parse(u,f){if(u.length!==3)return f.error(`Expected 2 arguments, but found ${u.length-1} instead.`);const w=f.parse(u[1],1,un),C=f.parse(u[2],2,Eu(f.expectedType||qi));return w&&C?new jw(C.type.itemType,w,C):null}evaluate(u){const f=this.index.evaluate(u),w=this.input.evaluate(u);if(f<0)throw new sl(`Array index out of bounds: ${f} < 0.`);if(f>w.length-1)throw new sl(`Array index out of bounds: ${f} > ${w.length-1}.`);if(f===Math.floor(f))return w[f];const C=Math.floor(f),I=Math.ceil(f),L=w[C],B=w[I];if(typeof L!="number"||typeof B!="number")throw new sl(`Cannot interpolate between non-number values at index ${f}.`);const U=f-C;return L*(1-U)+B*U}eachChild(u){u(this.index),u(this.input)}outputDefined(){return!1}serialize(){return["at-interpolated",this.index.serialize(),this.input.serialize()]}}class Rm{constructor(u,f){this.type=Oi,this.needle=u,this.haystack=f}static parse(u,f){if(u.length!==3)return f.error(`Expected 2 arguments, but found ${u.length-1} instead.`),null;const w=f.parse(u[1],1,qi),C=f.parse(u[2],2,qi);return w&&C?W1(w.type,[Oi,wi,un,Jf,qi])?new Rm(w,C):(f.error(`Expected first argument to be of type boolean, string, number or null, but found ${Al(w.type)} instead`),null):null}evaluate(u){const f=this.needle.evaluate(u),w=this.haystack.evaluate(u);if(w==null)return!1;if(!Fp(f,["boolean","string","number","null"]))throw new sl(`Expected first argument to be of type boolean, string, number or null, but found ${Al(yl(f))} instead.`);if(!Fp(w,["string","array"]))throw new sl(`Expected second argument to be of type array or string, but found ${Al(yl(w))} instead.`);return w.indexOf(f)>=0}eachChild(u){u(this.needle),u(this.haystack)}outputDefined(){return!0}serialize(){return["in",this.needle.serialize(),this.haystack.serialize()]}}class Nw{constructor(u,f,w){this.type=un,this.needle=u,this.haystack=f,this.fromIndex=w}static parse(u,f){if(u.length<=2||u.length>=5)return f.error(`Expected 3 or 4 arguments, but found ${u.length-1} instead.`),null;const w=f.parse(u[1],1,qi),C=f.parse(u[2],2,qi);if(!w||!C)return null;if(!W1(w.type,[Oi,wi,un,Jf,qi]))return f.error(`Expected first argument to be of type boolean, string, number or null, but found ${Al(w.type)} instead`),null;if(u.length===4){const I=f.parse(u[3],3,un);return I?new Nw(w,C,I):null}return new Nw(w,C)}evaluate(u){const f=this.needle.evaluate(u),w=this.haystack.evaluate(u);if(!Fp(f,["boolean","string","number","null"]))throw new sl(`Expected first argument to be of type boolean, string, number or null, but found ${Al(yl(f))} instead.`);if(!Fp(w,["string","array"]))throw new sl(`Expected second argument to be of type array or string, but found ${Al(yl(w))} instead.`);if(this.fromIndex){const C=this.fromIndex.evaluate(u);return w.indexOf(f,C)}return w.indexOf(f)}eachChild(u){u(this.needle),u(this.haystack),this.fromIndex&&u(this.fromIndex)}outputDefined(){return!1}serialize(){if(this.fromIndex!=null&&this.fromIndex!==void 0){const u=this.fromIndex.serialize();return["index-of",this.needle.serialize(),this.haystack.serialize(),u]}return["index-of",this.needle.serialize(),this.haystack.serialize()]}}class Sv{constructor(u,f,w,C,I,L){this.inputType=u,this.type=f,this.input=w,this.cases=C,this.outputs=I,this.otherwise=L}static parse(u,f){if(u.length<5)return f.error(`Expected at least 4 arguments, but found only ${u.length-1}.`);if(u.length%2!=1)return f.error("Expected an even number of arguments.");let w,C;f.expectedType&&f.expectedType.kind!=="value"&&(C=f.expectedType);const I={},L=[];for(let Y=2;YNumber.MAX_SAFE_INTEGER)return de.error(`Branch labels must be integers no larger than ${Number.MAX_SAFE_INTEGER}.`);if(typeof we=="number"&&Math.floor(we)!==we)return de.error("Numeric branch labels must be integer values.");if(w){if(de.checkSubtype(w,yl(we)))return null}else w=yl(we);if(I[String(we)]!==void 0)return de.error("Branch labels must be unique.");I[String(we)]=L.length}const xe=f.parse(oe,Y,C);if(!xe)return null;C=C||xe.type,L.push(xe)}const B=f.parse(u[1],1,qi);if(!B)return null;const U=f.parse(u[u.length-1],u.length-1,C);return U?B.type.kind!=="value"&&f.concat(1).checkSubtype(w,B.type)?null:new Sv(w,C,B,I,L,U):null}evaluate(u){const f=this.input.evaluate(u);return(Bp(yl(f),this.inputType)&&this.outputs[this.cases[f]]||this.otherwise).evaluate(u)}eachChild(u){u(this.input),this.outputs.forEach(u),u(this.otherwise)}outputDefined(){return this.outputs.every(u=>u.outputDefined())&&this.otherwise.outputDefined()}serialize(){const u=["match",this.input.serialize()],f=Object.keys(this.cases).sort(),w=[],C={};for(const L of f){const B=C[this.cases[L]];B===void 0?(C[this.cases[L]]=w.length,w.push([this.cases[L],[L]])):w[B][1].push(L)}const I=L=>this.inputType.kind==="number"?Number(L):L;for(const[L,B]of w)u.push(B.length===1?I(B[0]):B.map(I)),u.push(this.outputs[L].serialize());return u.push(this.otherwise.serialize()),u}}class Q0{constructor(u,f,w){this.type=u,this.branches=f,this.otherwise=w}static parse(u,f){if(u.length<4)return f.error(`Expected at least 3 arguments, but found only ${u.length-1}.`),null;if(u.length%2!=0)return f.error("Expected an odd number of arguments."),null;let w;f.expectedType&&f.expectedType.kind!=="value"&&(w=f.expectedType);const C=[];for(let L=1;Lf.outputDefined())&&this.otherwise.outputDefined()}serialize(){const u=["case"];return this.eachChild(f=>{u.push(f.serialize())}),u}}class J0{constructor(u,f,w,C){this.type=u,this.input=f,this.beginIndex=w,this.endIndex=C}static parse(u,f){if(u.length<=2||u.length>=5)return f.error(`Expected 3 or 4 arguments, but found ${u.length-1} instead.`),null;const w=f.parse(u[1],1,qi),C=f.parse(u[2],2,un);if(!w||!C)return null;if(!W1(w.type,[Eu(qi),wi,qi]))return f.error(`Expected first argument to be of type array or string, but found ${Al(w.type)} instead`),null;if(u.length===4){const I=f.parse(u[3],3,un);return I?new J0(w.type,w,C,I):null}return new J0(w.type,w,C)}evaluate(u){const f=this.input.evaluate(u),w=this.beginIndex.evaluate(u);if(!Fp(f,["string","array"]))throw new sl(`Expected first argument to be of type array or string, but found ${Al(yl(f))} instead.`);if(this.endIndex){const C=this.endIndex.evaluate(u);return f.slice(w,C)}return f.slice(w)}eachChild(u){u(this.input),u(this.beginIndex),this.endIndex&&u(this.endIndex)}outputDefined(){return!1}serialize(){if(this.endIndex!=null&&this.endIndex!==void 0){const u=this.endIndex.serialize();return["slice",this.input.serialize(),this.beginIndex.serialize(),u]}return["slice",this.input.serialize(),this.beginIndex.serialize()]}}class rb{constructor(u,f){this.type=Eu(wi),this.str=u,this.delimiter=f}static parse(u,f){if(u.length!==3)return f.error(`Expected 2 arguments, but found ${u.length-1} instead.`);const w=f.parse(u[1],1,wi),C=f.parse(u[2],2,wi);return w&&C?new rb(w,C):void 0}evaluate(u){const f=this.str.evaluate(u),w=this.delimiter.evaluate(u);return f.split(w)}eachChild(u){u(this.str),u(this.delimiter)}outputDefined(){return!1}serialize(){return["split",this.str.serialize(),this.delimiter.serialize()]}}function x4(v,u){return v==="=="||v==="!="?u.kind==="boolean"||u.kind==="string"||u.kind==="number"||u.kind==="null"||u.kind==="value":u.kind==="string"||u.kind==="number"||u.kind==="value"}function nb(v,u,f,w){return w.compare(u,f)===0}function Wc(v,u,f){const w=v!=="=="&&v!=="!=";return class ast{constructor(I,L,B){this.type=Oi,this.lhs=I,this.rhs=L,this.collator=B,this.hasUntypedArgument=I.type.kind==="value"||L.type.kind==="value"}static parse(I,L){if(I.length!==3&&I.length!==4)return L.error("Expected two or three arguments.");const B=I[0];let U=L.parse(I[1],1,qi);if(!U)return null;if(!x4(B,U.type))return L.concat(1).error(`"${B}" comparisons are not supported for type '${Al(U.type)}'.`);let Y=L.parse(I[2],2,qi);if(!Y)return null;if(!x4(B,Y.type))return L.concat(2).error(`"${B}" comparisons are not supported for type '${Al(Y.type)}'.`);if(U.type.kind!==Y.type.kind&&U.type.kind!=="value"&&Y.type.kind!=="value")return L.error(`Cannot compare types '${Al(U.type)}' and '${Al(Y.type)}'.`);w&&(U.type.kind==="value"&&Y.type.kind!=="value"?U=new Pm(Y.type,[U]):U.type.kind!=="value"&&Y.type.kind==="value"&&(Y=new Pm(U.type,[Y])));let se=null;if(I.length===4){if(U.type.kind!=="string"&&Y.type.kind!=="string"&&U.type.kind!=="value"&&Y.type.kind!=="value")return L.error("Cannot use collator to compare non-string types.");if(se=L.parse(I[3],3,Op),!se)return null}return new ast(U,Y,se)}evaluate(I){const L=this.lhs.evaluate(I),B=this.rhs.evaluate(I);if(w&&this.hasUntypedArgument){const U=yl(L),Y=yl(B);if(U.kind!==Y.kind||U.kind!=="string"&&U.kind!=="number")throw new sl(`Expected arguments for "${v}" to be (string, string) or (number, number), but found (${U.kind}, ${Y.kind}) instead.`)}if(this.collator&&!w&&this.hasUntypedArgument){const U=yl(L),Y=yl(B);if(U.kind!=="string"||Y.kind!=="string")return u(I,L,B)}return this.collator?f(I,L,B,this.collator.evaluate(I)):u(I,L,B)}eachChild(I){I(this.lhs),I(this.rhs),this.collator&&I(this.collator)}outputDefined(){return!0}serialize(){const I=[v];return this.eachChild(L=>{I.push(L.serialize())}),I}}}const hM=Wc("==",function(v,u,f){return u===f},nb),zj=Wc("!=",function(v,u,f){return u!==f},function(v,u,f,w){return!nb(0,u,f,w)}),$j=Wc("<",function(v,u,f){return u",function(v,u,f){return u>f},function(v,u,f,w){return w.compare(u,f)>0}),dD=Wc("<=",function(v,u,f){return u<=f},function(v,u,f,w){return w.compare(u,f)<=0}),Ma=Wc(">=",function(v,u,f){return u>=f},function(v,u,f,w){return w.compare(u,f)>=0});class kx{constructor(u,f,w,C,I,L){this.type=wi,this.number=u,this.locale=f,this.currency=w,this.unit=C,this.minFractionDigits=I,this.maxFractionDigits=L}static parse(u,f){if(u.length!==3)return f.error("Expected two arguments.");const w=f.parse(u[1],1,un);if(!w)return null;const C=u[2];if(typeof C!="object"||Array.isArray(C))return f.error("NumberFormat options argument must be an object.");let I=null;if(C.locale&&(I=f.parseObjectValue(C.locale,2,"locale",wi),!I))return null;let L=null;if(C.currency&&(L=f.parseObjectValue(C.currency,2,"currency",wi),!L))return null;let B=null;if(C.unit&&(B=f.parseObjectValue(C.unit,2,"unit",wi),!B))return null;let U=null;if(C["min-fraction-digits"]&&(U=f.parseObjectValue(C["min-fraction-digits"],2,"min-fraction-digits",un),!U))return null;let Y=null;return C["max-fraction-digits"]&&(Y=f.parseObjectValue(C["max-fraction-digits"],2,"max-fraction-digits",un),!Y)?null:new kx(w,I,L,B,U,Y)}evaluate(u){return new Intl.NumberFormat(this.locale?this.locale.evaluate(u):[],{style:(this.currency?"currency":this.unit&&"unit")||"decimal",currency:this.currency?this.currency.evaluate(u):void 0,unit:this.unit?this.unit.evaluate(u):void 0,minimumFractionDigits:this.minFractionDigits?this.minFractionDigits.evaluate(u):void 0,maximumFractionDigits:this.maxFractionDigits?this.maxFractionDigits.evaluate(u):void 0}).format(this.number.evaluate(u))}eachChild(u){u(this.number),this.locale&&u(this.locale),this.currency&&u(this.currency),this.unit&&u(this.unit),this.minFractionDigits&&u(this.minFractionDigits),this.maxFractionDigits&&u(this.maxFractionDigits)}outputDefined(){return!1}serialize(){const u={};return this.locale&&(u.locale=this.locale.serialize()),this.currency&&(u.currency=this.currency.serialize()),this.unit&&(u.unit=this.unit.serialize()),this.minFractionDigits&&(u["min-fraction-digits"]=this.minFractionDigits.serialize()),this.maxFractionDigits&&(u["max-fraction-digits"]=this.maxFractionDigits.serialize()),["number-format",this.number.serialize(),u]}}class ab{constructor(u){this.type=un,this.input=u}static parse(u,f){if(u.length!==2)return f.error(`Expected 1 argument, but found ${u.length-1} instead.`),null;const w=f.parse(u[1],1);return w?w.type.kind!=="array"&&w.type.kind!=="string"&&w.type.kind!=="value"?(f.error(`Expected argument of type string or array, but found ${Al(w.type)} instead.`),null):new ab(w):null}evaluate(u){const f=this.input.evaluate(u);if(typeof f=="string"||Array.isArray(f))return f.length;throw new sl(`Expected value to be of type string or array, but found ${Al(yl(f))} instead.`)}eachChild(u){u(this.input)}outputDefined(){return!1}serialize(){const u=["length"];return this.eachChild(f=>{u.push(f.serialize())}),u}}function y4(v){return function(){v=1831565813+(v|=0)|0;let u=Math.imul(v^v>>>15,1|v);return u=u+Math.imul(u^u>>>7,61|u)^u,((u^u>>>14)>>>0)/4294967296}}const ib={"==":hM,"!=":zj,">":eh,"<":$j,">=":Ma,"<=":dD,array:Pm,at:xf,"at-interpolated":jw,boolean:Pm,case:Q0,coalesce:sb,collator:ow,format:Hh,image:_n,in:Rm,"index-of":Nw,interpolate:Jd,"interpolate-hcl":Jd,"interpolate-lab":Jd,length:ab,let:kv,literal:Wr,match:Sv,number:Pm,"number-format":kx,object:Pm,slice:J0,step:bw,string:Pm,"to-boolean":Gh,"to-color":Gh,"to-number":Gh,"to-string":Gh,var:xw,within:Mg,distance:Y0,config:_v,split:rb};function ob(v,[u,f,w,C]){u=u.evaluate(v),f=f.evaluate(v),w=w.evaluate(v);const I=C?C.evaluate(v):1,L=mf(u,f,w,I);if(L)throw new sl(L);return new Mr(u/255,f/255,w/255,I)}function kw(v,[u,f,w,C]){u=u.evaluate(v),f=f.evaluate(v),w=w.evaluate(v);const I=C?C.evaluate(v):1,L=function(Y,se,oe,de){return typeof Y=="number"&&Y>=0&&Y<=360?typeof se=="number"&&se>=0&&se<=100&&typeof oe=="number"&&oe>=0&&oe<=100?de===void 0||typeof de=="number"&&de>=0&&de<=1?null:`Invalid hsla value [${[Y,se,oe,de].join(", ")}]: 'a' must be between 0 and 1.`:`Invalid hsla value [${(typeof de=="number"?[Y,se,oe,de]:[Y,se,oe]).join(", ")}]: 's', and 'l' must be between 0 and 100.`:`Invalid hsla value [${(typeof de=="number"?[Y,se,oe,de]:[Y,se,oe]).join(", ")}]: 'h' must be between 0 and 360.`}(u,f,w,I);if(L)throw new sl(L);const B=`hsla(${u}, ${f}%, ${w}%, ${I})`,U=Mr.parse(B);if(!U)throw new sl(`Failed to parse HSLA color: ${B}`);return U}function Cv(v,u){return v in u}function Sw(v,u){const f=u[v];return f===void 0?null:f}function Sx(v){return{type:v}}function Cw(v){if(v instanceof _v)return new Set([v.key]);let u=new Set;return v.eachChild(f=>{u=new Set([...u,...Cw(f)])}),u}function lb(v){if(v instanceof wc&&v.name==="is-active-floor")return!0;let u=!1;return v.eachChild(f=>{!u&&lb(f)&&(u=!0)}),u}function Uj(v){return{result:"success",value:v}}function jc(v){return{result:"error",value:v}}function Yh(v,u){return!!v&&!!v.parameters&&v.parameters.indexOf(u)>-1}function yf(v){return v["property-type"]==="data-driven"}function qj(v){return Yh(v.expression,"measure-light")}function Vj(v){return Yh(v.expression,"zoom")}function Om(v){return!!v.expression&&v.expression.interpolated}function Hj(v){return typeof v=="object"&&v!==null&&!Array.isArray(v)}function zp(v){return v}function mM(v,u){const f=u.type==="color",w=v.stops&&typeof v.stops[0][0]=="object",C=w||!(w||v.property!==void 0),I=v.type||(Om(u)?"exponential":"interval");if(f&&((v=Object.assign({},v)).stops&&(v.stops=v.stops.map(Y=>[Y[0],Mr.parse(Y[1])])),v.default=Mr.parse(v.default?v.default:u.default)),v.colorSpace&&v.colorSpace!=="rgb"&&!g4[v.colorSpace])throw new Error(`Unknown color space: ${v.colorSpace}`);let L,B,U;if(I==="exponential")L=v4;else if(I==="interval")L=pM;else if(I==="categorical"){L=fM,B=Object.create(null);for(const Y of v.stops)B[Y[0]]=Y[1];U=typeof v.stops[0][0]}else{if(I!=="identity")throw new Error(`Unknown function type "${I}"`);L=Tw}if(w){const Y={},se=[];for(let xe=0;xexe[0]),evaluate:({zoom:xe},we)=>v4({stops:oe,base:v.base},u,xe).evaluate(xe,we)}}if(C){const Y=I==="exponential"?{name:"exponential",base:v.base!==void 0?v.base:1}:null;return{kind:"camera",interpolationType:Y,interpolationFactor:Jd.interpolationFactor.bind(void 0,Y),zoomStops:v.stops.map(se=>se[0]),evaluate:({zoom:se})=>L(v,u,se,B,U)}}return{kind:"source",evaluate(Y,se){const oe=se&&se.properties?se.properties[v.property]:void 0;return oe===void 0?$p(v.default,u.default):L(v,u,oe,B,U)}}}function $p(v,u,f){return v!==void 0?v:u!==void 0?u:f!==void 0?f:void 0}function fM(v,u,f,w,C){return $p(typeof f===C?w[f]:void 0,v.default,u.default)}function pM(v,u,f){if(!Y1(f))return $p(v.default,u.default);const w=v.stops.length;if(w===1||f<=v.stops[0][0])return v.stops[0][1];if(f>=v.stops[w-1][0])return v.stops[w-1][1];const C=vw(v.stops.map(I=>I[0]),f);return v.stops[C][1]}function v4(v,u,f){const w=v.base!==void 0?v.base:1;if(!Y1(f))return $p(v.default,u.default);const C=v.stops.length;if(C===1||f<=v.stops[0][0])return v.stops[0][1];if(f>=v.stops[C-1][0])return v.stops[C-1][1];const I=vw(v.stops.map(se=>se[0]),f),L=function(se,oe,de,xe){const we=xe-de,Ce=se-de;return we===0?0:oe===1?Ce/we:(Math.pow(oe,Ce)-1)/(Math.pow(oe,we)-1)}(f,w,v.stops[I][0],v.stops[I+1][0]),B=v.stops[I][1],U=v.stops[I+1][1];let Y=Vh[u.type]||zp;if(v.colorSpace&&v.colorSpace!=="rgb"){const se=g4[v.colorSpace];Y=(oe,de)=>se.reverse(se.interpolate(se.forward(oe),se.forward(de),L))}return typeof B.evaluate=="function"?{evaluate(...se){const oe=B.evaluate.apply(void 0,se),de=U.evaluate.apply(void 0,se);if(oe!==void 0&&de!==void 0)return Y(oe,de,L)}}:Y(B,U,L)}function Tw(v,u,f){return u.type==="color"?f=Mr.parse(f):u.type==="formatted"?f=Md.fromString(f.toString()):u.type==="resolvedImage"?f=Id.build(f.toString()):G0(f)===u.type||u.type==="enum"&&u.values[f]||(f=void 0),$p(f,v.default,u.default)}wc.register(ib,{error:[{kind:"error"},[wi],(v,[u])=>{throw new sl(u.evaluate(v))}],typeof:[wi,[qi],(v,[u])=>Al(yl(u.evaluate(v)))],"to-rgba":[Eu(un,4),[_h],(v,[u])=>u.evaluate(v).toNonPremultipliedRenderColor(null).toArray()],"to-hsla":[Eu(un,4),[_h],(v,[u])=>u.evaluate(v).toNonPremultipliedRenderColor(null).toHslaArray()],rgb:[_h,[un,un,un],ob],rgba:[_h,[un,un,un,un],ob],hsl:[_h,[un,un,un],kw],hsla:[_h,[un,un,un,un],kw],has:{type:Oi,overloads:[[[wi],(v,[u])=>Cv(u.evaluate(v),v.properties())],[[wi,Rp],(v,[u,f])=>Cv(u.evaluate(v),f.evaluate(v))]]},get:{type:qi,overloads:[[[wi],(v,[u])=>Sw(u.evaluate(v),v.properties())],[[wi,Rp],(v,[u,f])=>Sw(u.evaluate(v),f.evaluate(v))]]},"feature-state":[qi,[wi],(v,[u])=>Sw(u.evaluate(v),v.featureState||{})],properties:[Rp,[],v=>v.properties()],"geometry-type":[wi,[],v=>v.geometryType()],worldview:[wi,[],v=>v.globals.worldview||""],"is-active-floor":[Oi,Sx(wi),(v,u)=>{if(!(v.globals&&v.globals.activeFloors&&v.globals.activeFloors.size>0))return!1;if(u.length===0)return!0;const f=v.globals.activeFloors;return u.some(w=>{const C=w.evaluate(v);return f.has(C)})}],id:[qi,[],v=>v.id()],zoom:[un,[],v=>v.globals.zoom],pitch:[un,[],v=>v.globals.pitch||0],"distance-from-center":[un,[],v=>v.distanceFromCenter()],"measure-light":[un,[wi],(v,[u])=>v.measureLight(u.evaluate(v))],"heatmap-density":[un,[],v=>v.globals.heatmapDensity||0],"line-progress":[un,[],v=>v.globals.lineProgress||0],"raster-value":[un,[],v=>v.globals.rasterValue||0],"raster-particle-speed":[un,[],v=>v.globals.rasterParticleSpeed||0],"sky-radial-progress":[un,[],v=>v.globals.skyRadialProgress||0],accumulated:[qi,[],v=>v.globals.accumulated===void 0?null:v.globals.accumulated],"+":[un,Sx(un),(v,u)=>{let f=0;for(const w of u)f+=w.evaluate(v);return f}],"*":[un,Sx(un),(v,u)=>{let f=1;for(const w of u)f*=w.evaluate(v);return f}],"-":{type:un,overloads:[[[un,un],(v,[u,f])=>u.evaluate(v)-f.evaluate(v)],[[un],(v,[u])=>-u.evaluate(v)]]},"/":[un,[un,un],(v,[u,f])=>u.evaluate(v)/f.evaluate(v)],"%":[un,[un,un],(v,[u,f])=>u.evaluate(v)%f.evaluate(v)],ln2:[un,[],()=>Math.LN2],pi:[un,[],()=>Math.PI],e:[un,[],()=>Math.E],"^":[un,[un,un],(v,[u,f])=>Math.pow(u.evaluate(v),f.evaluate(v))],sqrt:[un,[un],(v,[u])=>Math.sqrt(u.evaluate(v))],log10:[un,[un],(v,[u])=>Math.log(u.evaluate(v))/Math.LN10],ln:[un,[un],(v,[u])=>Math.log(u.evaluate(v))],log2:[un,[un],(v,[u])=>Math.log2(u.evaluate(v))],sin:[un,[un],(v,[u])=>Math.sin(u.evaluate(v))],cos:[un,[un],(v,[u])=>Math.cos(u.evaluate(v))],tan:[un,[un],(v,[u])=>Math.tan(u.evaluate(v))],asin:[un,[un],(v,[u])=>Math.asin(u.evaluate(v))],acos:[un,[un],(v,[u])=>Math.acos(u.evaluate(v))],atan:[un,[un],(v,[u])=>Math.atan(u.evaluate(v))],min:[un,Sx(un),(v,u)=>Math.min(...u.map(f=>f.evaluate(v)))],max:[un,Sx(un),(v,u)=>Math.max(...u.map(f=>f.evaluate(v)))],abs:[un,[un],(v,[u])=>Math.abs(u.evaluate(v))],round:[un,[un],(v,[u])=>{const f=u.evaluate(v);return f<0?-Math.round(-f):Math.round(f)}],floor:[un,[un],(v,[u])=>Math.floor(u.evaluate(v))],ceil:[un,[un],(v,[u])=>Math.ceil(u.evaluate(v))],"filter-==":[Oi,[wi,qi],(v,[u,f])=>v.properties()[u.value]===f.value],"filter-id-==":[Oi,[qi],(v,[u])=>v.id()===u.value],"filter-type-==":[Oi,[wi],(v,[u])=>v.geometryType()===u.value],"filter-<":[Oi,[wi,qi],(v,[u,f])=>{const w=v.properties()[u.value],C=f.value;return typeof w==typeof C&&w{const f=v.id(),w=u.value;return typeof f==typeof w&&f":[Oi,[wi,qi],(v,[u,f])=>{const w=v.properties()[u.value],C=f.value;return typeof w==typeof C&&w>C}],"filter-id->":[Oi,[qi],(v,[u])=>{const f=v.id(),w=u.value;return typeof f==typeof w&&f>w}],"filter-<=":[Oi,[wi,qi],(v,[u,f])=>{const w=v.properties()[u.value],C=f.value;return typeof w==typeof C&&w<=C}],"filter-id-<=":[Oi,[qi],(v,[u])=>{const f=v.id(),w=u.value;return typeof f==typeof w&&f<=w}],"filter->=":[Oi,[wi,qi],(v,[u,f])=>{const w=v.properties()[u.value],C=f.value;return typeof w==typeof C&&w>=C}],"filter-id->=":[Oi,[qi],(v,[u])=>{const f=v.id(),w=u.value;return typeof f==typeof w&&f>=w}],"filter-has":[Oi,[qi],(v,[u])=>u.value in v.properties()],"filter-has-id":[Oi,[],v=>v.id()!==null&&v.id()!==void 0],"filter-type-in":[Oi,[Eu(wi)],(v,[u])=>u.value.indexOf(v.geometryType())>=0],"filter-id-in":[Oi,[Eu(qi)],(v,[u])=>u.value.indexOf(v.id())>=0],"filter-in-small":[Oi,[wi,Eu(qi)],(v,[u,f])=>f.value.indexOf(v.properties()[u.value])>=0],"filter-in-large":[Oi,[wi,Eu(qi)],(v,[u,f])=>function(w,C,I,L){for(;I<=L;){const B=I+L>>1;if(C[B]===w)return!0;C[B]>w?L=B-1:I=B+1}return!1}(v.properties()[u.value],f.value,0,f.value.length-1)],all:{type:Oi,overloads:[[[Oi,Oi],(v,[u,f])=>u.evaluate(v)&&f.evaluate(v)],[Sx(Oi),(v,u)=>{for(const f of u)if(!f.evaluate(v))return!1;return!0}]]},any:{type:Oi,overloads:[[[Oi,Oi],(v,[u,f])=>u.evaluate(v)||f.evaluate(v)],[Sx(Oi),(v,u)=>{for(const f of u)if(f.evaluate(v))return!0;return!1}]]},"!":[Oi,[Oi],(v,[u])=>!u.evaluate(v)],"is-supported-script":[Oi,[wi],(v,[u])=>{const f=v.globals&&v.globals.isSupportedScript;return!f||f(u.evaluate(v))}],upcase:[wi,[wi],(v,[u])=>u.evaluate(v).toUpperCase()],downcase:[wi,[wi],(v,[u])=>u.evaluate(v).toLowerCase()],concat:[wi,Sx(qi),(v,u)=>u.map(f=>zn(f.evaluate(v))).join("")],"resolved-locale":[wi,[Op],(v,[u])=>u.evaluate(v).resolvedLocale()],random:[un,[un,un,qi],(v,u)=>{const[f,w,C]=u.map(L=>L.evaluate(v));if(f>w||f===w)return f;let I;if(typeof C=="string")I=function(L){let B=0;if(L.length===0)return B;for(let U=0;UJSON.stringify(oe)).join(", ")}, but found ${JSON.stringify(se)} instead.`);return se}catch(se){const oe=se;return this._warningHistory[oe.message]||(this._warningHistory[oe.message]=!0,typeof console<"u"&&console.warn(`Failed to evaluate expression "${JSON.stringify(this.expression.serialize())}". ${oe.message}`)),this._defaultValue}}}function ey(v){return Array.isArray(v)&&v.length>0&&typeof v[0]=="string"&&v[0]in ib}function Up(v,u,f,w,C){const I=new yw(ib,[],u?function(B){const U={color:_h,string:wi,number:un,enum:wi,boolean:Oi,formatted:V0,resolvedImage:G1};return B.type==="array"?Eu(U[B.value]||qi,B.length):U[B.type]}(u):void 0,void 0,void 0,f,w,C),L=I.parse(v,void 0,void 0,void 0,u&&u.type==="string"?{typeAnnotation:"coerce"}:void 0);return L?Uj(new Tv(L,u,f,w,C)):jc(I.errors)}class Cx{constructor(u,f,w,C){this.kind=u,this._styleExpression=f,this.isLightConstant=w,this.isLineProgressConstant=C,this.isStateDependent=u!=="constant"&&!X0(f.expression),this.configDependencies=Cw(f.expression),this.isIndoorDependent=lb(f.expression)}evaluateWithoutErrorHandling(u,f,w,C,I,L){return this._styleExpression.evaluateWithoutErrorHandling(u,f,w,C,I,L)}evaluate(u,f,w,C,I,L,B){return this._styleExpression.evaluate(u,f,w,C,I,L,void 0,void 0,B)}}class qp{constructor(u,f,w,C,I,L){this.kind=u,this.zoomStops=w,this._styleExpression=f,this.isStateDependent=u!=="camera"&&!X0(f.expression),this.isIndoorDependent=lb(f.expression),this.isLightConstant=I,this.isLineProgressConstant=L,this.configDependencies=Cw(f.expression),this.interpolationType=C}evaluateWithoutErrorHandling(u,f,w,C,I,L){return this._styleExpression.evaluateWithoutErrorHandling(u,f,w,C,I,L)}evaluate(u,f,w,C,I,L){return this._styleExpression.evaluate(u,f,w,C,I,L)}interpolationFactor(u,f,w){return this.interpolationType?Jd.interpolationFactor(this.interpolationType,u,f,w):0}}function Ew(v,u,f,w,C){if((v=Up(v,u,f,w,C)).result==="error")return v;const I=v.value.expression,L=Z0(I);if(!L&&!yf(u))return jc([new Tu("","data expressions not supported")]);const B=Wh(I,["zoom","pitch","distance-from-center"]);if(!B&&!Vj(u))return jc([new Tu("","zoom expressions not supported")]);const U=Wh(I,["measure-light"]);if(!U&&!qj(u))return jc([new Tu("","measure-light expression not supported")]);const Y=Wh(I,["line-progress"]);if(!Y&&!function(de){return Yh(de.expression,"line-progress")}(u))return jc([new Tu("","line-progress expression not supported")]);const se=u.expression&&u.expression.relaxZoomRestriction,oe=vf(I);return oe||B||se?oe instanceof Tu?jc([oe]):oe instanceof Jd&&!Om(u)?jc([new Tu("",'"interpolate" expressions cannot be used with this property')]):Uj(oe?new qp(L&&Y?"camera":"composite",v.value,oe.labels,oe instanceof Jd?oe.interpolation:void 0,U,Y):new Cx(L&&Y?"constant":"source",v.value,U,Y)):jc([new Tu("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression, or in the properties of atmosphere.')])}class cb{constructor(u,f){this._parameters=u,this._specification=f,Object.assign(this,mM(this._parameters,this._specification))}static deserialize(u){return new cb(u._parameters,u._specification)}static serialize(u){return{_parameters:u._parameters,_specification:u._specification}}}function vf(v){let u=null;if(v instanceof kv)u=vf(v.result);else if(v instanceof sb){for(const f of v.args)if(u=vf(f),u)break}else(v instanceof bw||v instanceof Jd)&&v.input instanceof wc&&v.input.name==="zoom"&&(u=v);return u instanceof Tu||v.eachChild(f=>{const w=vf(f);w instanceof Tu?u=w:u&&w&&u!==w&&(u=new Tu("",'Only one zoom-based "step" or "interpolate" subexpression may be used in an expression.'))}),u}var Gj,Wj,Aw=function(){if(Wj)return Gj;Wj=1,Gj=u;var v=3;function u(f,w,C){var I=this.cells=[];if(f instanceof ArrayBuffer){this.arrayBuffer=f;var L=new Int32Array(this.arrayBuffer);f=L[0],this.d=(w=L[1])+2*(C=L[2]);for(var B=0;B=de[Ce+0]&&I>=de[Ce+1])?(U[we]=!0,B.push(oe[we])):U[we]=!1}}},u.prototype._forEachCell=function(f,w,C,I,L,B,U,Y){for(var se=this._convertToCellCoord(f),oe=this._convertToCellCoord(w),de=this._convertToCellCoord(C),xe=this._convertToCellCoord(I),we=se;we<=de;we++)for(var Ce=oe;Ce<=xe;Ce++){var Re=this.d*Ce+we;if((!Y||Y(this._convertFromCellCoord(we),this._convertFromCellCoord(Ce),this._convertFromCellCoord(we+1),this._convertFromCellCoord(Ce+1)))&&L.call(this,f,w,C,I,Re,B,U,Y))return}},u.prototype._convertFromCellCoord=function(f){return(f-this.padding)/this.scale},u.prototype._convertToCellCoord=function(f){return Math.max(0,Math.min(this.d-1,Math.floor(f*this.scale)+this.padding))},u.prototype.toArrayBuffer=function(){if(this.arrayBuffer)return this.arrayBuffer;for(var f=this.cells,w=v+this.cells.length+1+1,C=0,I=0;I=0||(C[I]=tc(v[I],u)));v instanceof Error&&(C.message=v.message)}if(C.$name)throw new Error("$name property is reserved for worker serialization logic.");return w!=="Object"&&(C.$name=w),C}throw new Error("can't serialize object of type "+typeof v)}function Kl(v){if(v==null||typeof v=="boolean"||typeof v=="number"||typeof v=="string"||v instanceof Boolean||v instanceof Number||v instanceof String||v instanceof Date||v instanceof RegExp||lo(v)||v instanceof ImageBitmap||ArrayBuffer.isView(v)||v instanceof ImageData)return v;if(Array.isArray(v))return v.map(Kl);if(typeof v=="object"){const u=v.$name||"Object";if(u==="Map"){const C=v.entries||[],I=new Map;for(let L=0;Lv>=1536&&v<=1791,Nh=v=>v>=1872&&v<=1919,Ax=v=>v>=2208&&v<=2303,Kc=v=>v>=11904&&v<=12031,bf=v=>v>=12032&&v<=12255,Mx=v=>v>=12272&&v<=12287,ty=v=>v>=12288&&v<=12351,Ev=v=>v>=12352&&v<=12447,Vp=v=>v>=12448&&v<=12543,kh=v=>v>=12544&&v<=12591,db=v=>v>=12704&&v<=12735,ip=v=>v>=12736&&v<=12783,Pg=v=>v>=12784&&v<=12799,Av=v=>v>=12800&&v<=13055,Mw=v=>v>=13056&&v<=13311,Iw=v=>v>=13312&&v<=19903,Hp=v=>v>=19968&&v<=40959,sy=v=>v>=40960&&v<=42127,Lg=v=>v>=42128&&v<=42191,ub=v=>v>=44032&&v<=55215,ry=v=>v>=63744&&v<=64255,Pw=v=>v>=64336&&v<=65023,Lw=v=>v>=65040&&v<=65055,hb=v=>v>=65072&&v<=65103,th=v=>v>=65104&&v<=65135,Dg=v=>v>=65136&&v<=65279,Fm=v=>v>=65280&&v<=65519;function Sh(v){for(const u of v)if(w4(u.charCodeAt(0)))return!0;return!1}function gM(v){for(const u of v)if(!b4(u.charCodeAt(0)))return!1;return!0}function b4(v){return!(Au(v)||Nh(v)||Ax(v)||Pw(v)||Dg(v))}function _4(v){return!(v<11904||!(db(v)||kh(v)||hb(v)||ry(v)||Mw(v)||Kc(v)||ip(v)||ty(v)||Iw(v)||Hp(v)||Av(v)||Fm(v)||Ev(v)||Mx(v)||bf(v)||Pg(v)||Vp(v)||Lw(v)||Lg(v)||sy(v)))}function w4(v){return!(v!==746&&v!==747&&(v<4352||!(db(v)||kh(v)||hb(v)&&!(v>=65097&&v<=65103)||ry(v)||Mw(v)||Kc(v)||ip(v)||!(!ty(v)||v>=12296&&v<=12305||v>=12308&&v<=12319||v===12336)||Iw(v)||Hp(v)||Av(v)||(u=>u>=12592&&u<=12687)(v)||(u=>u>=43360&&u<=43391)(v)||(u=>u>=55216&&u<=55295)(v)||(u=>u>=4352&&u<=4607)(v)||ub(v)||Ev(v)||Mx(v)||(u=>u>=12688&&u<=12703)(v)||bf(v)||Pg(v)||Vp(v)&&v!==12540||!(!Fm(v)||v===65288||v===65289||v===65293||v>=65306&&v<=65310||v===65339||v===65341||v===65343||v>=65371&&v<=65503||v===65507||v>=65512&&v<=65519)||!(!th(v)||v>=65112&&v<=65118||v>=65123&&v<=65126)||(u=>u>=5120&&u<=5759)(v)||(u=>u>=6320&&u<=6399)(v)||Lw(v)||(u=>u>=19904&&u<=19967)(v)||sy(v)||Lg(v))))}function Ix(v){return v===12312||v===12313||v===12316||v===12540||v===12448}function ny(v){return!(w4(v)||function(u){return!!((f=>f>=128&&f<=255)(u)&&(u===167||u===169||u===174||u===177||u===188||u===189||u===190||u===215||u===247)||(f=>f>=8192&&f<=8303)(u)&&(u===8214||u===8224||u===8225||u===8240||u===8241||u===8251||u===8252||u===8258||u===8263||u===8264||u===8265||u===8273)||(f=>f>=8448&&f<=8527)(u)||(f=>f>=8528&&f<=8591)(u)||(f=>f>=8960&&f<=9215)(u)&&(u>=8960&&u<=8967||u>=8972&&u<=8991||u>=8996&&u<=9e3||u===9003||u>=9085&&u<=9114||u>=9150&&u<=9165||u===9167||u>=9169&&u<=9179||u>=9186&&u<=9215)||(f=>f>=9216&&f<=9279)(u)&&u!==9251||(f=>f>=9280&&f<=9311)(u)||(f=>f>=9312&&f<=9471)(u)||(f=>f>=9632&&f<=9727)(u)||(f=>f>=9728&&f<=9983)(u)&&!(u>=9754&&u<=9759)||(f=>f>=11008&&f<=11263)(u)&&(u>=11026&&u<=11055||u>=11088&&u<=11097||u>=11192&&u<=11243)||ty(u)||Vp(u)||(f=>f>=57344&&f<=63743)(u)||hb(u)||th(u)||Fm(u)||u===8734||u===8756||u===8757||u>=9984&&u<=10087||u>=10102&&u<=10131||u===65532||u===65533)}(v))}function j4(v){return Au(v)||Nh(v)||Ax(v)||Pw(v)||Dg(v)}function Dw(v){return v>=1424&&v<=2303||Pw(v)||Dg(v)}function Rg(v,u){return!(!u&&Dw(v)||v>=2304&&v<=3583||v>=3840&&v<=4255||(f=>f>=6016&&f<=6143)(v))}function xM(v){for(const u of v)if(Dw(u.charCodeAt(0)))return!0;return!1}const Zh={unavailable:"unavailable",deferred:"deferred",loading:"loading",parsing:"parsing",parsed:"parsed",loaded:"loaded",error:"error"};let op=null,Ld=Zh.unavailable,_f=null;const yM=function(v){v&&typeof v=="string"&&v.indexOf("NetworkError")>-1&&(Ld=Zh.error),op&&op(v)};function Kj(){Yj.fire(new _c("pluginStateChange",{pluginStatus:Ld,pluginURL:_f}))}const Yj=new hf,Px=function(){return Ld},vM=function(){if(Ld!==Zh.deferred||!_f)throw new Error("rtl-text-plugin cannot be downloaded unless a pluginURL is specified");Ld=Zh.loading,Kj(),_f&&U0({url:_f},v=>{v?yM(v):(Ld=Zh.loaded,Kj())})},Xh={applyArabicShaping:null,processBidirectionalText:null,processStyledBidirectionalText:null,isLoaded:()=>Ld===Zh.loaded||Xh.applyArabicShaping!=null,isLoading:()=>Ld===Zh.loading,setState(v){Ld=v.pluginStatus,_f=v.pluginURL},isParsing:()=>Ld===Zh.parsing,isParsed:()=>Ld===Zh.parsed,getPluginURL:()=>_f},N4=function(){Xh.isLoading()||Xh.isLoaded()||Px()!=="deferred"||vM()};class wa{constructor(u,f){this.zoom=u,f?(this.now=f.now,this.fadeDuration=f.fadeDuration,this.transition=f.transition,this.pitch=f.pitch,this.brightness=f.brightness,this.worldview=f.worldview,this.activeFloors=f.activeFloors):(this.now=0,this.fadeDuration=0,this.transition={},this.pitch=0,this.brightness=0)}isSupportedScript(u){return function(f,w){for(const C of f)if(!Rg(C.charCodeAt(0),w))return!1;return!0}(u,Xh.isLoaded())}}class mb{constructor(u,f,w,C,I){this.property=u,this.value=f,this.expression=function(L,B,U,Y,se){if(Hj(L))return new cb(L,B);if(ey(L)||Array.isArray(L)&&L.length>0){const oe=Ew(L,B,U,Y,se);if(oe.result==="error")throw new Error(oe.value.map(de=>`${de.key}: ${de.message}`).join(", "));return oe.value}{let oe=L;return typeof L=="string"&&B.type==="color"&&(oe=Mr.parse(L)),{kind:"constant",configDependencies:new Set,isIndoorDependent:!1,evaluate:()=>oe}}}(f===void 0?u.specification.default:f,u.specification,w,C,I)}isIndoorDependent(){return this.expression.isIndoorDependent}isDataDriven(){return this.expression.kind==="source"||this.expression.kind==="composite"}possiblyEvaluate(u,f,w,C){return this.property.possiblyEvaluate(this,u,f,w,C)}}class Rw{constructor(u,f,w,C){this.property=u,this.value=new mb(u,void 0,f,w,C)}transitioned(u,f){return new fb(this.property,this.value,f,Object.assign({},u.transition,this.transition),u.now)}untransitioned(){return new fb(this.property,this.value,null,{},0)}}class Zj{constructor(u,f,w,C){this._properties=u,this._values=Object.create(u.defaultTransitionablePropertyValues),this._scope=f,this._options=w,this._iconImageUseTheme=C,this._isIndoorDependent=!1,this.configDependencies=new Set}getValue(u){return Er(this._values[u].value.value)}setValue(u,f){this._values.hasOwnProperty(u)||(this._values[u]=new Rw(this._values[u].property,this._scope,this._options,this._iconImageUseTheme)),this._values[u].value=new mb(this._values[u].property,f===null?void 0:Er(f),this._scope,this._options,this._iconImageUseTheme),this._values[u].value.expression.configDependencies&&(this.configDependencies=new Set([...this.configDependencies,...this._values[u].value.expression.configDependencies]),this._isIndoorDependent=this._isIndoorDependent||this._values[u].value.isIndoorDependent())}setTransitionOrValue(u,f){f&&(this._options=f);const w=this._properties.properties;if(u)for(const C in u){const I=u[C];if(C.endsWith("-transition")){const L=C.slice(0,-11);w[L]&&this.setTransition(L,I)}else w.hasOwnProperty(C)&&this.setValue(C,I)}}getTransition(u){return Er(this._values[u].transition)}setTransition(u,f){this._values.hasOwnProperty(u)||(this._values[u]=new Rw(this._values[u].property)),this._values[u].transition=Er(f)||void 0}serialize(){const u={};for(const f of Object.keys(this._values)){const w=this.getValue(f);w!==void 0&&(u[f]=w);const C=this.getTransition(f);C!==void 0&&(u[`${f}-transition`]=C)}return u}transitioned(u,f){const w=new Xj(this._properties);for(const C of Object.keys(this._values))w._values[C]=this._values[C].transitioned(u,f._values[C]);return w}untransitioned(){const u=new Xj(this._properties);for(const f of Object.keys(this._values))u._values[f]=this._values[f].untransitioned();return u}isIndoorDependent(){return this._isIndoorDependent}}class fb{constructor(u,f,w,C,I){const L=C.delay||0,B=C.duration||0;I=I||0,this.property=u,this.value=f,this.begin=I+L,this.end=this.begin+B,u.specification.transition&&(C.delay||C.duration)&&(this.prior=w)}possiblyEvaluate(u,f,w){const C=u.now||0,I=this.value.possiblyEvaluate(u,f,w),L=this.prior;if(L){if(C>this.end)return this.prior=null,I;if(this.value.isDataDriven())return this.prior=null,I;if(C":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-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]},"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-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]},"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},"line-blend-mode":{"type":"enum","values":{"default":1,"multiply":1,"additive":1},"default":"default","expression":{"parameters":["zoom"]}}},"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"]},"appearance":true,"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"]},"appearance":true,"property-type":"data-driven"},"icon-emissive-strength":{"type":"number","default":1,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light","feature-state"]},"appearance":true,"property-type":"data-driven"},"text-emissive-strength":{"type":"number","default":1,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light","feature-state"]},"appearance":true,"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"]},"appearance":true,"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"]},"appearance":true,"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"]},"appearance":true,"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"]},"appearance":true,"property-type":"data-driven"},"icon-translate":{"type":"array","value":"number","length":2,"default":[0,0],"transition":true,"appearance":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"]},"appearance":true,"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"]},"appearance":true,"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"]},"appearance":true,"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"]},"appearance":true,"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"]},"appearance":true,"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"]},"appearance":true,"property-type":"data-driven"},"text-translate":{"type":"array","value":"number","length":2,"default":[0,0],"transition":true,"appearance":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,"appearance":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"]}},"raster-elevation-reference":{"type":"enum","values":{"sea":1,"ground":1},"default":"sea","expression":{}}},"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":{}},"model-ignore-line-cutout":{"type":"boolean","default":false,"expression":{}}},"transition":{"duration":{"type":"number","default":300,"minimum":0},"delay":{"type":"number","default":0,"minimum":0}},"promoteId":{"*":{"type":"*"}}}');function Ow(v){return v instanceof Number||v instanceof String||v instanceof Boolean?v.valueOf():v}function pb(v){if(Array.isArray(v))return v.map(pb);if(v instanceof Object&&!(v instanceof Number||v instanceof String||v instanceof Boolean)){const u={};for(const f in v)u[f]=pb(v[f]);return u}return Ow(v)}function Fw(v){if(v===!0||v===!1)return!0;if(!Array.isArray(v)||v.length===0)return!1;switch(v[0]){case"has":return v.length>=2&&v[1]!=="$id"&&v[1]!=="$type";case"in":return v.length>=3&&(typeof v[1]!="string"||Array.isArray(v[2]));case"!in":case"!has":case"none":return!1;case"==":case"!=":case">":case">=":case"<":case"<=":return v.length!==3||Array.isArray(v[1])||Array.isArray(v[2]);case"any":case"all":for(const u of v.slice(1))if(!Fw(u)&&typeof u!="boolean")return!1;return!0;default:return!0}}function Jj(v,u="",f=null,w="fill"){if(v==null)return{filter:()=>!0,needGeometry:!1,needFeature:!1};Fw(v)||(v=tN(v));const C=v;let I=!0;try{I=function(se){if(!Iv(se))return se;let oe=pb(se);return S4(oe),oe=k4(oe),oe}(C)}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(C,null,2)} `)}let L=null,B=null;if(w!=="background"&&w!=="sky"&&w!=="slot"){B=es[`filter_${w}`];const se=Up(I,B,u,f);if(se.result==="error")throw new Error(se.value.map(oe=>`${oe.key}: ${oe.message}`).join(", "));L=(oe,de,xe)=>se.value.evaluate(oe,de,{},xe)}let U=null,Y=null;if(I!==C){const se=Up(C,B,u,f);if(se.result==="error")throw new Error(se.value.map(oe=>`${oe.key}: ${oe.message}`).join(", "));U=(oe,de,xe,we,Ce)=>se.value.evaluate(oe,de,{},xe,void 0,void 0,we,Ce),Y=!Z0(se.value.expression)}return{filter:L,dynamicFilter:U||void 0,needGeometry:bM(I),needFeature:!!Y}}function k4(v){if(!Array.isArray(v))return v;const u=function(f){if(C4.has(f[0])){for(let w=1;wk4(f))}function S4(v){let u=!1;const f=[];if(v[0]==="case"){for(let w=1;w",">=","<","<=","to-boolean"]);function eN(v,u){return vu?1:0}function bM(v){if(!Array.isArray(v))return!1;if(v[0]==="within"||v[0]==="distance")return!0;for(let u=1;u"||u==="<="||u===">="?W(v[1],v[2],u):u==="any"?(f=v.slice(1),["any"].concat(f.map(tN))):u==="all"?["all"].concat(v.slice(1).map(tN)):u==="none"?["all"].concat(v.slice(1).map(tN).map(Be)):u==="in"?X(v[1],v.slice(2)):u==="!in"?Be(X(v[1],v.slice(2))):u==="has"?_e(v[1]):u!=="!has"||Be(_e(v[1]));var f}function W(v,u,f){switch(v){case"$type":return[`filter-type-${f}`,u];case"$id":return[`filter-id-${f}`,u];default:return[`filter-${f}`,v,u]}}function X(v,u){if(u.length===0)return!1;switch(v){case"$type":return["filter-type-in",["literal",u]];case"$id":return["filter-id-in",["literal",u]];default:return u.length>200&&!u.some(f=>typeof f!=typeof u[0])?["filter-in-large",v,["literal",u.sort(eN)]]:["filter-in-small",v,["literal",u]]}}function _e(v){switch(v){case"$type":return!0;case"$id":return["filter-has-id"];default:return["filter-has",v]}}function Be(v){return["!",v]}const Ke="";function ft(v,u){return u?`${v}${Ke}${u}`:v}function Qt(v){const u=v.indexOf(Ke);return u>=0?v.slice(u+1):""}let rr;const Ir=()=>rr||(rr=new Lo({"icon-size":new dr(es.layout_symbol["icon-size"]),"icon-image":new dr(es.layout_symbol["icon-image"]),"icon-rotate":new dr(es.layout_symbol["icon-rotate"]),"icon-offset":new dr(es.layout_symbol["icon-offset"]),"text-size":new dr(es.layout_symbol["text-size"]),"text-rotate":new dr(es.layout_symbol["text-rotate"]),"text-offset":new dr(es.layout_symbol["text-offset"])}));let Tn;const Ia=()=>Tn||(Tn=new Lo({"icon-opacity":new dr(es.paint_symbol["icon-opacity"]),"icon-occlusion-opacity":new dr(es.paint_symbol["icon-occlusion-opacity"]),"icon-emissive-strength":new dr(es.paint_symbol["icon-emissive-strength"]),"text-emissive-strength":new dr(es.paint_symbol["text-emissive-strength"]),"icon-color":new dr(es.paint_symbol["icon-color"]),"icon-halo-color":new dr(es.paint_symbol["icon-halo-color"]),"icon-halo-width":new dr(es.paint_symbol["icon-halo-width"]),"icon-halo-blur":new dr(es.paint_symbol["icon-halo-blur"]),"icon-translate":new dr(es.paint_symbol["icon-translate"]),"text-opacity":new dr(es.paint_symbol["text-opacity"]),"text-occlusion-opacity":new dr(es.paint_symbol["text-occlusion-opacity"]),"text-color":new dr(es.paint_symbol["text-color"],{runtimeType:_h,getOverride:v=>v.textColor,hasOverride:v=>!!v.textColor}),"text-halo-color":new dr(es.paint_symbol["text-halo-color"]),"text-halo-width":new dr(es.paint_symbol["text-halo-width"]),"text-halo-blur":new dr(es.paint_symbol["text-halo-blur"]),"text-translate":new dr(es.paint_symbol["text-translate"]),"symbol-z-offset":new dr(es.paint_symbol["symbol-z-offset"]),"icon-color-use-theme":new dr({type:"string",default:"default","property-type":"data-driven"}),"icon-halo-color-use-theme":new dr({type:"string",default:"default","property-type":"data-driven"}),"text-color-use-theme":new dr({type:"string",default:"default","property-type":"data-driven"}),"text-halo-color-use-theme":new dr({type:"string",default:"default","property-type":"data-driven"})}));class eo{constructor(u,f,w,C,I,L){this._conditionSpec=u,this._propertiesSpec=w;const B=Up(u,es.appearance.condition);if(B.result==="success"&&(this.condition=B.value),this.name=f,w){this.layoutProperties=new Dd(Ir()),this.unevaluatedLayout=new Qj(Ir(),C,I,L),this.paintProperties=new Dd(Ia()),this.unevaluatedPaint=new Qj(Ia(),C,I,"");for(const U in w)U in this.unevaluatedLayout._values?this.unevaluatedLayout.setValue(U,w[U]):U in this.unevaluatedPaint._values&&this.unevaluatedPaint.setValue(U,w[U])}}isActive(u){return!(this.condition||!u.isHidden||this.name!=="hidden")||this.condition.evaluate(u.globals,u.feature,u.featureState,u.canonical)}getCondition(){return this.condition}getName(){return this.name}getLayoutProperty(u){return this.layoutProperties.get(u)}getPaintProperty(u){return this.paintProperties.get(u)}getUnevaluatedLayoutProperties(){return this.unevaluatedLayout}getUnevaluatedLayoutProperty(u){return this.unevaluatedLayout._values[u]}getUnevaluatedPaintProperty(u){return this.unevaluatedPaint._values[u]}recalculate(u,f,w){this.unevaluatedLayout&&(this.layoutProperties=this.unevaluatedLayout.possiblyEvaluate(u,void 0,f,w)),this.unevaluatedPaint&&(this.paintProperties=this.unevaluatedPaint.possiblyEvaluate(u,void 0,f,""))}serialize(){const u={};u.condition=this.condition.expression.serialize(),this.name&&(u.name=this.name);const f=this.unevaluatedLayout?this.unevaluatedLayout.serialize():{},w=this.unevaluatedPaint?this.unevaluatedPaint.serialize():{},C=Object.assign({},f,w);return Object.keys(C).length>0&&(u.properties=C),u}hasIconLayoutProperties(){const u=this.hasLayoutProperty("icon-image"),f=this.hasLayoutProperty("icon-size"),w=this.hasLayoutProperty("icon-offset"),C=this.hasLayoutProperty("icon-rotate");return u||f||w||C}hasTextLayoutProperties(){const u=this.hasLayoutProperty("text-size"),f=this.hasLayoutProperty("text-offset"),w=this.hasLayoutProperty("text-rotate");return u||f||w}hasIconPaintProperties(){return!!this.unevaluatedPaint&&Object.keys(this.unevaluatedPaint._values).filter(u=>!u.endsWith("-use-theme")).some(u=>(u.startsWith("icon-")||u==="symbol-z-offset")&&this.hasPaintProperty(u))}hasTextPaintProperties(){return!!this.unevaluatedPaint&&Object.keys(this.unevaluatedPaint._values).filter(u=>!u.endsWith("-use-theme")).some(u=>(u.startsWith("text-")||u==="symbol-z-offset")&&this.hasPaintProperty(u))}hasLayoutProperty(u){return this.unevaluatedLayout&&this.unevaluatedLayout._values[u].value!==void 0}hasPaintProperty(u){return this.unevaluatedPaint&&this.unevaluatedPaint._values[u].value!==void 0}}const ha="-transition",lc=new Set(["fill","line","background","hillshade","raster"]);class to extends hf{constructor(u,f,w,C,I,L){if(super(),this.id=u.id,this.fqid=ft(this.id,w),this.type=u.type,this.scope=w,this.lut=C,this.options=I,this.iconImageUseTheme=L,this.appearances=new Array,this.appearancesVersion=0,this._featureFilter={filter:()=>!0,needGeometry:!1,needFeature:!1},this._filterCompiled=!1,this.expressionDependencies={isIndoorDependent:!1,configDependencies:new Set},u.type!=="custom"){if(this.metadata=u.metadata,this.minzoom=u.minzoom,this.maxzoom=u.maxzoom,u.type&&u.type!=="background"&&u.type!=="sky"&&u.type!=="slot"){this.source=u.source,this.sourceLayer=u["source-layer"],this.filter=u.filter;const B=Up(this.filter,es[`filter_${u.type}`]);B.result!=="error"&&(this.expressionDependencies.configDependencies=new Set([...this.expressionDependencies.configDependencies,...B.value.configDependencies]),this.expressionDependencies.isIndoorDependent=this.expressionDependencies.isIndoorDependent||B.value.isIndoorDependent)}if(u.slot&&(this.slot=u.slot),u.appearances&&this.setAppearances(u.appearances),f.layout&&(this._unevaluatedLayout=new Qj(f.layout,this.scope,I,this.iconImageUseTheme),this.expressionDependencies.configDependencies=new Set([...this.expressionDependencies.configDependencies,...this._unevaluatedLayout.configDependencies]),this.expressionDependencies.isIndoorDependent=this.expressionDependencies.isIndoorDependent||this._unevaluatedLayout.isIndoorDependent()),f.paint){this._transitionablePaint=new Zj(f.paint,this.scope,I);for(const B in u.paint)this.setPaintProperty(B,u.paint[B]);for(const B in u.layout)this.setLayoutProperty(B,u.layout[B]);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 Dd(f.paint)}}}onAdd(u){}onRemove(u){}isDraped(u){return!this.is3D(!0)&&lc.has(this.type)}getLayoutProperty(u){return u==="visibility"?this.visibility:this._unevaluatedLayout.getValue(u)}setLayoutProperty(u,f){if(this.type==="custom"&&u==="visibility")return void(this.visibility=f);const w=this._unevaluatedLayout;w._properties.properties[u]&&(w.setValue(u,f),this.expressionDependencies.configDependencies=new Set([...this.expressionDependencies.configDependencies,...w.configDependencies]),this.expressionDependencies.isIndoorDependent=this.expressionDependencies.isIndoorDependent||w.isIndoorDependent(),u==="visibility"&&this.possiblyEvaluateVisibility())}setAppearances(u){this.appearances=[],u.forEach(f=>{this.appearances.push(new eo(f.condition,f.name,f.properties,this.scope,this.options,this.iconImageUseTheme))}),this.appearancesVersion++}possiblyEvaluateVisibility(){this._unevaluatedLayout._values.visibility&&(this.visibility=this._unevaluatedLayout._values.visibility.possiblyEvaluate({zoom:0}))}getPaintProperty(u){return u.endsWith(ha)?this._transitionablePaint.getTransition(u.slice(0,-11)):this._transitionablePaint.getValue(u)}isPaintProperty(u){return!!this._transitionablePaint._properties.properties[u]}setPaintProperty(u,f){const w=this._transitionablePaint,C=w._properties.properties;if(u.endsWith(ha)){const oe=u.slice(0,-11);return C[oe]&&w.setTransition(oe,f||void 0),!1}if(!C[u])return!1;const I=w._values[u],L=I.value.isDataDriven(),B=I.value;w.setValue(u,f),this.expressionDependencies.configDependencies=new Set([...this.expressionDependencies.configDependencies,...w.configDependencies]),this.expressionDependencies.isIndoorDependent=this.expressionDependencies.isIndoorDependent||w.isIndoorDependent(),this._handleSpecialPaintPropertyUpdate(u);const U=w._values[u].value,Y=U.isDataDriven(),se=u.endsWith("pattern")||u==="line-dasharray";return Y||L||se||this._handleOverridablePaintPropertyUpdate(u,B,U)}_handleSpecialPaintPropertyUpdate(u){}getProgramIds(){return null}getDefaultProgramParams(u,f,w){return null}_handleOverridablePaintPropertyUpdate(u,f,w){return!1}isHidden(u){return!!(this.minzoom&&u=this.maxzoom)||this.visibility==="none"}updateTransitions(u){this._transitioningPaint=this._transitionablePaint.transitioned(u,this._transitioningPaint)}hasTransition(){return this._transitioningPaint.hasTransition()}recalculate(u,f){this._unevaluatedLayout&&(this.layout=this._unevaluatedLayout.possiblyEvaluate(u,void 0,f,this.iconImageUseTheme)),this.paint=this._transitioningPaint.possiblyEvaluate(u,void 0,f)}serialize(){const u={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&&(u.appearances=this.appearances.map(f=>f.serialize())),Rs(u,(f,w)=>!(f===void 0||w==="layout"&&!Object.keys(f).length||w==="paint"&&!Object.keys(f).length))}is3D(u){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 u in this.paint._values){const f=this.paint.get(u);if(f instanceof Mv&&yf(f.property.specification)&&(f.value.kind==="source"||f.value.kind==="composite")&&f.value.isStateDependent)return!0}for(const u of this.appearances)if(!X0(u.condition.expression))return!0;return!1}compileFilter(u){this._filterCompiled||(this._featureFilter=Jj(this.filter,this.scope,u),this._filterCompiled=!0)}invalidateCompiledFilter(){this._filterCompiled=!1}dynamicFilter(){return this._featureFilter.dynamicFilter}dynamicFilterNeedsFeature(){return this._featureFilter.needFeature}dynamicFilterNeedsGeometry(){return this._featureFilter.needGeometry}getLayerRenderingStats(){return this._stats}resetLayerRenderingStats(u){this._stats&&(u.renderPass==="shadow"?this._stats.numRenderedVerticesInShadowPass=0:this._stats.numRenderedVerticesInTransparentPass=0)}getAppearances(){return this.appearances}queryRenderedFeatures(u,f,w){return{}}queryRadius(u){}queryIntersectsFeature(u,f,w,C,I,L,B,U,Y,se){}}const sh={Int8:Int8Array,Uint8:Uint8Array,Int16:Int16Array,Uint16:Uint16Array,Int32:Int32Array,Uint32:Uint32Array,Float32:Float32Array};class jf{constructor(u,f){this._structArray=u,this._pos1=f*this.size,this._pos2=this._pos1/2,this._pos4=this._pos1/4,this._pos8=this._pos1/8}}const Tr=new ArrayBuffer(0);class Ps{constructor(){this._reallocCount=0,this.capacity=0,this.length=0}static serialize(u,f){return u._trim(),f&&u.arrayBuffer&&f.add(u.arrayBuffer),{length:u.length,arrayBuffer:u.arrayBuffer}}static deserialize(u){const f=Object.create(this.prototype);return f.arrayBuffer=u.arrayBuffer,f.length=u.length,u.arrayBuffer?f.capacity=u.arrayBuffer.byteLength/f.bytesPerElement:(f.capacity=0,f.arrayBuffer=Tr),f._refreshViews(),f}_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(u){this.reserve(u),this.length=u}reserve(u){if(u>this.capacity){this._reallocCount++,this.capacity=Math.max(u,Math.floor(5*this.capacity),128),this.arrayBuffer=new ArrayBuffer(this.capacity*this.bytesPerElement);const f=this.uint8;this._refreshViews(),f&&this.uint8.set(f)}}reserveForAdditional(u){this.reserve(this.length+u)}_refreshViews(){throw new Error("StructArray#_refreshViews() must be implemented by each concrete StructArray layout")}emplace(...u){throw new Error("StructArray#emplace() must be implemented by each concrete StructArray layout")}emplaceBack(...u){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 Qs(v,u=1){let f=0,w=0;return{members:v.map(C=>{const I=sh[C.type].BYTES_PER_ELEMENT,L=f=ja(f,Math.max(u,I)),B=C.components||1;return w=Math.max(w,I),f+=I*B,{name:C.name,type:C.type,components:B,offset:L}}),size:ja(f,Math.max(w,u)),alignment:u}}function ja(v,u){return Math.ceil(v/u)*u}class Da extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(u,f){const w=this.length;return this.resize(w+1),this.emplace(w,u,f)}emplace(u,f,w){const C=2*u;return this.int16[C+0]=f,this.int16[C+1]=w,u}}Da.prototype.bytesPerElement=4,Pr(Da,"StructArrayLayout2i4");class Ei extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(u,f,w){const C=this.length;return this.resize(C+1),this.emplace(C,u,f,w)}emplace(u,f,w,C){const I=3*u;return this.int16[I+0]=f,this.int16[I+1]=w,this.int16[I+2]=C,u}}Ei.prototype.bytesPerElement=6,Pr(Ei,"StructArrayLayout3i6");class Ya extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(u,f,w,C){const I=this.length;return this.resize(I+1),this.emplace(I,u,f,w,C)}emplace(u,f,w,C,I){const L=4*u;return this.int16[L+0]=f,this.int16[L+1]=w,this.uint16[L+2]=C,this.uint16[L+3]=I,u}}Ya.prototype.bytesPerElement=8,Pr(Ya,"StructArrayLayout2i2ui8");class Zi extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(u){const f=this.length;return this.resize(f+1),this.emplace(f,u)}emplace(u,f){return this.float32[1*u+0]=f,u}}Zi.prototype.bytesPerElement=4,Pr(Zi,"StructArrayLayout1f4");class Rd extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(u,f,w){const C=this.length;return this.resize(C+1),this.emplace(C,u,f,w)}emplace(u,f,w,C){const I=4*u,L=2*u;return this.int16[I+0]=f,this.int16[I+1]=w,this.float32[L+1]=C,u}}Rd.prototype.bytesPerElement=8,Pr(Rd,"StructArrayLayout2i1f8");class qo extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(u,f,w){const C=this.length;return this.resize(C+1),this.emplace(C,u,f,w)}emplace(u,f,w,C){const I=4*u;return this.int16[I+0]=f,this.int16[I+1]=w,this.int16[I+2]=C,u}}qo.prototype.bytesPerElement=8,Pr(qo,"StructArrayLayout3i8");class Og extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(u,f,w,C){const I=this.length;return this.resize(I+1),this.emplace(I,u,f,w,C)}emplace(u,f,w,C,I){const L=4*u;return this.int16[L+0]=f,this.int16[L+1]=w,this.int16[L+2]=C,this.int16[L+3]=I,u}}Og.prototype.bytesPerElement=8,Pr(Og,"StructArrayLayout4i8");class T4 extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(u,f,w,C,I){const L=this.length;return this.resize(L+1),this.emplace(L,u,f,w,C,I)}emplace(u,f,w,C,I,L){const B=5*u;return this.int16[B+0]=f,this.int16[B+1]=w,this.int16[B+2]=C,this.int16[B+3]=I,this.int16[B+4]=L,u}}T4.prototype.bytesPerElement=10,Pr(T4,"StructArrayLayout5i10");class E4 extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(u,f,w,C,I,L,B){const U=this.length;return this.resize(U+1),this.emplace(U,u,f,w,C,I,L,B)}emplace(u,f,w,C,I,L,B,U){const Y=6*u,se=12*u,oe=3*u;return this.int16[Y+0]=f,this.int16[Y+1]=w,this.uint8[se+4]=C,this.uint8[se+5]=I,this.uint8[se+6]=L,this.uint8[se+7]=B,this.float32[oe+2]=U,u}}E4.prototype.bytesPerElement=12,Pr(E4,"StructArrayLayout2i4ub1f12");class Fg extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(u,f,w){const C=this.length;return this.resize(C+1),this.emplace(C,u,f,w)}emplace(u,f,w,C){const I=3*u;return this.float32[I+0]=f,this.float32[I+1]=w,this.float32[I+2]=C,u}}Fg.prototype.bytesPerElement=12,Pr(Fg,"StructArrayLayout3f12");class ay extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(u,f,w,C,I){const L=this.length;return this.resize(L+1),this.emplace(L,u,f,w,C,I)}emplace(u,f,w,C,I,L){const B=6*u,U=3*u;return this.uint16[B+0]=f,this.uint16[B+1]=w,this.uint16[B+2]=C,this.uint16[B+3]=I,this.float32[U+2]=L,u}}ay.prototype.bytesPerElement=12,Pr(ay,"StructArrayLayout4ui1f12");class sN extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(u,f,w,C){const I=this.length;return this.resize(I+1),this.emplace(I,u,f,w,C)}emplace(u,f,w,C,I){const L=4*u;return this.uint16[L+0]=f,this.uint16[L+1]=w,this.uint16[L+2]=C,this.uint16[L+3]=I,u}}sN.prototype.bytesPerElement=8,Pr(sN,"StructArrayLayout4ui8");class _M extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(u,f,w,C,I,L){const B=this.length;return this.resize(B+1),this.emplace(B,u,f,w,C,I,L)}emplace(u,f,w,C,I,L,B){const U=6*u;return this.int16[U+0]=f,this.int16[U+1]=w,this.int16[U+2]=C,this.int16[U+3]=I,this.int16[U+4]=L,this.int16[U+5]=B,u}}_M.prototype.bytesPerElement=12,Pr(_M,"StructArrayLayout6i12");class uD extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(u,f,w,C,I,L,B,U,Y,se,oe,de){const xe=this.length;return this.resize(xe+1),this.emplace(xe,u,f,w,C,I,L,B,U,Y,se,oe,de)}emplace(u,f,w,C,I,L,B,U,Y,se,oe,de,xe){const we=12*u;return this.int16[we+0]=f,this.int16[we+1]=w,this.int16[we+2]=C,this.int16[we+3]=I,this.uint16[we+4]=L,this.uint16[we+5]=B,this.uint16[we+6]=U,this.uint16[we+7]=Y,this.int16[we+8]=se,this.int16[we+9]=oe,this.int16[we+10]=de,this.int16[we+11]=xe,u}}uD.prototype.bytesPerElement=24,Pr(uD,"StructArrayLayout4i4ui4i24");class hD extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(u,f,w,C,I,L){const B=this.length;return this.resize(B+1),this.emplace(B,u,f,w,C,I,L)}emplace(u,f,w,C,I,L,B){const U=10*u,Y=5*u;return this.int16[U+0]=f,this.int16[U+1]=w,this.int16[U+2]=C,this.float32[Y+2]=I,this.float32[Y+3]=L,this.float32[Y+4]=B,u}}hD.prototype.bytesPerElement=20,Pr(hD,"StructArrayLayout3i3f20");class Pv extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(u,f,w,C){const I=this.length;return this.resize(I+1),this.emplace(I,u,f,w,C)}emplace(u,f,w,C,I){const L=4*u;return this.float32[L+0]=f,this.float32[L+1]=w,this.float32[L+2]=C,this.float32[L+3]=I,u}}Pv.prototype.bytesPerElement=16,Pr(Pv,"StructArrayLayout4f16");class A4 extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer)}emplaceBack(u){const f=this.length;return this.resize(f+1),this.emplace(f,u)}emplace(u,f){return this.uint32[1*u+0]=f,u}}A4.prototype.bytesPerElement=4,Pr(A4,"StructArrayLayout1ul4");class Bg extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(u,f){const w=this.length;return this.resize(w+1),this.emplace(w,u,f)}emplace(u,f,w){const C=2*u;return this.uint16[C+0]=f,this.uint16[C+1]=w,u}}Bg.prototype.bytesPerElement=4,Pr(Bg,"StructArrayLayout2ui4");class wM extends Ps{_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(u,f,w,C,I,L,B,U,Y,se,oe,de,xe){const we=this.length;return this.resize(we+1),this.emplace(we,u,f,w,C,I,L,B,U,Y,se,oe,de,xe)}emplace(u,f,w,C,I,L,B,U,Y,se,oe,de,xe,we){const Ce=20*u,Re=10*u;return this.int16[Ce+0]=f,this.int16[Ce+1]=w,this.int16[Ce+2]=C,this.int16[Ce+3]=I,this.int16[Ce+4]=L,this.float32[Re+3]=B,this.float32[Re+4]=U,this.float32[Re+5]=Y,this.float32[Re+6]=se,this.int16[Ce+14]=oe,this.uint32[Re+8]=de,this.uint16[Ce+18]=xe,this.uint16[Ce+19]=we,u}}wM.prototype.bytesPerElement=40,Pr(wM,"StructArrayLayout5i4f1i1ul2ui40");class M4 extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(u,f,w,C,I,L,B){const U=this.length;return this.resize(U+1),this.emplace(U,u,f,w,C,I,L,B)}emplace(u,f,w,C,I,L,B,U){const Y=8*u;return this.int16[Y+0]=f,this.int16[Y+1]=w,this.int16[Y+2]=C,this.int16[Y+4]=I,this.int16[Y+5]=L,this.int16[Y+6]=B,this.int16[Y+7]=U,u}}M4.prototype.bytesPerElement=16,Pr(M4,"StructArrayLayout3i2i2i16");class mD extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(u,f,w,C,I){const L=this.length;return this.resize(L+1),this.emplace(L,u,f,w,C,I)}emplace(u,f,w,C,I,L){const B=4*u,U=8*u;return this.float32[B+0]=f,this.float32[B+1]=w,this.float32[B+2]=C,this.int16[U+6]=I,this.int16[U+7]=L,u}}mD.prototype.bytesPerElement=16,Pr(mD,"StructArrayLayout2f1f2i16");class I4 extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(u,f,w,C,I,L){const B=this.length;return this.resize(B+1),this.emplace(B,u,f,w,C,I,L)}emplace(u,f,w,C,I,L,B){const U=20*u,Y=5*u;return this.uint8[U+0]=f,this.uint8[U+1]=w,this.float32[Y+1]=C,this.float32[Y+2]=I,this.float32[Y+3]=L,this.float32[Y+4]=B,u}}I4.prototype.bytesPerElement=20,Pr(I4,"StructArrayLayout2ub4f20");class Yl extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(u,f,w){const C=this.length;return this.resize(C+1),this.emplace(C,u,f,w)}emplace(u,f,w,C){const I=3*u;return this.uint16[I+0]=f,this.uint16[I+1]=w,this.uint16[I+2]=C,u}}Yl.prototype.bytesPerElement=6,Pr(Yl,"StructArrayLayout3ui6");class jM extends Ps{_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(u,f,w,C,I,L,B,U,Y,se,oe,de,xe,we,Ce,Re,qe,nt,Ze,ut,xt){const bt=this.length;return this.resize(bt+1),this.emplace(bt,u,f,w,C,I,L,B,U,Y,se,oe,de,xe,we,Ce,Re,qe,nt,Ze,ut,xt)}emplace(u,f,w,C,I,L,B,U,Y,se,oe,de,xe,we,Ce,Re,qe,nt,Ze,ut,xt,bt){const Ht=30*u,Rt=15*u,Vt=60*u;return this.int16[Ht+0]=f,this.int16[Ht+1]=w,this.int16[Ht+2]=C,this.float32[Rt+2]=I,this.float32[Rt+3]=L,this.uint16[Ht+8]=B,this.uint16[Ht+9]=U,this.uint32[Rt+5]=Y,this.uint32[Rt+6]=se,this.uint32[Rt+7]=oe,this.uint16[Ht+16]=de,this.uint16[Ht+17]=xe,this.uint16[Ht+18]=we,this.float32[Rt+10]=Ce,this.float32[Rt+11]=Re,this.uint8[Vt+48]=qe,this.uint8[Vt+49]=nt,this.uint8[Vt+50]=Ze,this.uint32[Rt+13]=ut,this.int16[Ht+28]=xt,this.uint8[Vt+58]=bt,u}}jM.prototype.bytesPerElement=60,Pr(jM,"StructArrayLayout3i2f2ui3ul3ui2f3ub1ul1i1ub60");class fD extends Ps{_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(u,f,w,C,I,L,B,U,Y,se,oe,de,xe,we,Ce,Re,qe,nt,Ze,ut,xt,bt,Ht,Rt,Vt,Bt,$t,js,Es,zs,Hs,$s,nr){const ys=this.length;return this.resize(ys+1),this.emplace(ys,u,f,w,C,I,L,B,U,Y,se,oe,de,xe,we,Ce,Re,qe,nt,Ze,ut,xt,bt,Ht,Rt,Vt,Bt,$t,js,Es,zs,Hs,$s,nr)}emplace(u,f,w,C,I,L,B,U,Y,se,oe,de,xe,we,Ce,Re,qe,nt,Ze,ut,xt,bt,Ht,Rt,Vt,Bt,$t,js,Es,zs,Hs,$s,nr,ys){const qs=20*u,Zs=40*u,ir=80*u;return this.float32[qs+0]=f,this.float32[qs+1]=w,this.int16[Zs+4]=C,this.int16[Zs+5]=I,this.int16[Zs+6]=L,this.int16[Zs+7]=B,this.int16[Zs+8]=U,this.int16[Zs+9]=Y,this.int16[Zs+10]=se,this.int16[Zs+11]=oe,this.int16[Zs+12]=de,this.uint16[Zs+13]=xe,this.uint16[Zs+14]=we,this.uint16[Zs+15]=Ce,this.uint16[Zs+16]=Re,this.uint16[Zs+17]=qe,this.uint16[Zs+18]=nt,this.uint16[Zs+19]=Ze,this.uint16[Zs+20]=ut,this.uint16[Zs+21]=xt,this.uint16[Zs+22]=bt,this.uint16[Zs+23]=Ht,this.uint16[Zs+24]=Rt,this.uint16[Zs+25]=Vt,this.uint16[Zs+26]=Bt,this.uint16[Zs+27]=$t,this.uint32[qs+14]=js,this.float32[qs+15]=Es,this.float32[qs+16]=zs,this.float32[qs+17]=Hs,this.float32[qs+18]=$s,this.uint8[ir+76]=nr,this.uint16[Zs+39]=ys,u}}fD.prototype.bytesPerElement=80,Pr(fD,"StructArrayLayout2f9i15ui1ul4f1ub1ui80");class NM extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(u,f,w,C,I,L){const B=this.length;return this.resize(B+1),this.emplace(B,u,f,w,C,I,L)}emplace(u,f,w,C,I,L,B){const U=6*u;return this.float32[U+0]=f,this.float32[U+1]=w,this.float32[U+2]=C,this.float32[U+3]=I,this.float32[U+4]=L,this.float32[U+5]=B,u}}NM.prototype.bytesPerElement=24,Pr(NM,"StructArrayLayout6f24");class Bw extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(u,f,w,C,I){const L=this.length;return this.resize(L+1),this.emplace(L,u,f,w,C,I)}emplace(u,f,w,C,I,L){const B=5*u;return this.float32[B+0]=f,this.float32[B+1]=w,this.float32[B+2]=C,this.float32[B+3]=I,this.float32[B+4]=L,u}}Bw.prototype.bytesPerElement=20,Pr(Bw,"StructArrayLayout5f20");class P4 extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(u,f,w,C,I,L,B){const U=this.length;return this.resize(U+1),this.emplace(U,u,f,w,C,I,L,B)}emplace(u,f,w,C,I,L,B,U){const Y=7*u;return this.float32[Y+0]=f,this.float32[Y+1]=w,this.float32[Y+2]=C,this.float32[Y+3]=I,this.float32[Y+4]=L,this.float32[Y+5]=B,this.float32[Y+6]=U,u}}P4.prototype.bytesPerElement=28,Pr(P4,"StructArrayLayout7f28");class pD extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(u,f,w,C,I,L,B,U,Y,se,oe){const de=this.length;return this.resize(de+1),this.emplace(de,u,f,w,C,I,L,B,U,Y,se,oe)}emplace(u,f,w,C,I,L,B,U,Y,se,oe,de){const xe=11*u;return this.float32[xe+0]=f,this.float32[xe+1]=w,this.float32[xe+2]=C,this.float32[xe+3]=I,this.float32[xe+4]=L,this.float32[xe+5]=B,this.float32[xe+6]=U,this.float32[xe+7]=Y,this.float32[xe+8]=se,this.float32[xe+9]=oe,this.float32[xe+10]=de,u}}pD.prototype.bytesPerElement=44,Pr(pD,"StructArrayLayout11f44");class gD extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(u,f,w,C,I,L,B,U,Y){const se=this.length;return this.resize(se+1),this.emplace(se,u,f,w,C,I,L,B,U,Y)}emplace(u,f,w,C,I,L,B,U,Y,se){const oe=9*u;return this.float32[oe+0]=f,this.float32[oe+1]=w,this.float32[oe+2]=C,this.float32[oe+3]=I,this.float32[oe+4]=L,this.float32[oe+5]=B,this.float32[oe+6]=U,this.float32[oe+7]=Y,this.float32[oe+8]=se,u}}gD.prototype.bytesPerElement=36,Pr(gD,"StructArrayLayout9f36");class zw extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(u,f){const w=this.length;return this.resize(w+1),this.emplace(w,u,f)}emplace(u,f,w){const C=2*u;return this.float32[C+0]=f,this.float32[C+1]=w,u}}zw.prototype.bytesPerElement=8,Pr(zw,"StructArrayLayout2f8");class xD extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(u,f,w,C){const I=this.length;return this.resize(I+1),this.emplace(I,u,f,w,C)}emplace(u,f,w,C,I){const L=6*u;return this.uint32[3*u+0]=f,this.uint16[L+2]=w,this.uint16[L+3]=C,this.uint16[L+4]=I,u}}xD.prototype.bytesPerElement=12,Pr(xD,"StructArrayLayout1ul3ui12");class $w extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(u){const f=this.length;return this.resize(f+1),this.emplace(f,u)}emplace(u,f){return this.uint16[1*u+0]=f,u}}$w.prototype.bytesPerElement=2,Pr($w,"StructArrayLayout1ui2");class yD extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(u,f,w,C,I,L,B,U,Y,se,oe,de,xe,we,Ce,Re){const qe=this.length;return this.resize(qe+1),this.emplace(qe,u,f,w,C,I,L,B,U,Y,se,oe,de,xe,we,Ce,Re)}emplace(u,f,w,C,I,L,B,U,Y,se,oe,de,xe,we,Ce,Re,qe){const nt=16*u;return this.float32[nt+0]=f,this.float32[nt+1]=w,this.float32[nt+2]=C,this.float32[nt+3]=I,this.float32[nt+4]=L,this.float32[nt+5]=B,this.float32[nt+6]=U,this.float32[nt+7]=Y,this.float32[nt+8]=se,this.float32[nt+9]=oe,this.float32[nt+10]=de,this.float32[nt+11]=xe,this.float32[nt+12]=we,this.float32[nt+13]=Ce,this.float32[nt+14]=Re,this.float32[nt+15]=qe,u}}yD.prototype.bytesPerElement=64,Pr(yD,"StructArrayLayout16f64");class kM extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(u,f,w,C,I,L,B){const U=this.length;return this.resize(U+1),this.emplace(U,u,f,w,C,I,L,B)}emplace(u,f,w,C,I,L,B,U){const Y=10*u,se=5*u;return this.uint16[Y+0]=f,this.uint16[Y+1]=w,this.uint16[Y+2]=C,this.uint16[Y+3]=I,this.float32[se+2]=L,this.float32[se+3]=B,this.float32[se+4]=U,u}}kM.prototype.bytesPerElement=20,Pr(kM,"StructArrayLayout4ui3f20");class SM extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(u){const f=this.length;return this.resize(f+1),this.emplace(f,u)}emplace(u,f){return this.int16[1*u+0]=f,u}}SM.prototype.bytesPerElement=2,Pr(SM,"StructArrayLayout1i2");class CM extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer)}emplaceBack(u){const f=this.length;return this.resize(f+1),this.emplace(f,u)}emplace(u,f){return this.uint8[1*u+0]=f,u}}CM.prototype.bytesPerElement=1,Pr(CM,"StructArrayLayout1ub1");class Gz extends jf{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]}}Gz.prototype.size=40;class vD extends wM{get(u){return new Gz(this,u)}}Pr(vD,"CollisionBoxArray");class Wz extends jf{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(u){this._structArray.uint8[this._pos1+49]=u}get hidden(){return this._structArray.uint8[this._pos1+50]}set hidden(u){this._structArray.uint8[this._pos1+50]=u}get crossTileID(){return this._structArray.uint32[this._pos4+13]}set crossTileID(u){this._structArray.uint32[this._pos4+13]=u}get associatedIconIndex(){return this._structArray.int16[this._pos2+28]}get flipState(){return this._structArray.uint8[this._pos1+58]}set flipState(u){this._structArray.uint8[this._pos1+58]=u}}Wz.prototype.size=60;class Kz extends jM{get(u){return new Wz(this,u)}}Pr(Kz,"PlacedSymbolArray");class L4 extends jf{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(u){this._structArray.uint32[this._pos4+14]=u}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(u){this._structArray.float32[this._pos4+18]=u}get hasIconTextFit(){return this._structArray.uint8[this._pos1+76]}get elevationFeatureIndex(){return this._structArray.uint16[this._pos2+39]}}L4.prototype.size=80;class Yz extends fD{get(u){return new L4(this,u)}}Pr(Yz,"SymbolInstanceArray");class Zz extends Zi{getoffsetX(u){return this.float32[1*u+0]}}Pr(Zz,"GlyphOffsetArray");class D4 extends Da{getx(u){return this.int16[2*u+0]}gety(u){return this.int16[2*u+1]}}Pr(D4,"SymbolLineVertexArray");class Xz extends jf{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]}}Xz.prototype.size=12;class bD extends xD{get(u){return new Xz(this,u)}}Pr(bD,"FeatureIndexArray");class Qz extends Bg{geta_centroid_pos0(u){return this.uint16[2*u+0]}geta_centroid_pos1(u){return this.uint16[2*u+1]}}Pr(Qz,"FillExtrusionCentroidArray");class _D extends jf{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]}}_D.prototype.size=6;class wD extends Ei{get(u){return new _D(this,u)}}Pr(wD,"FillExtrusionWallArray");const Jz=Qs([{name:"a_pos",components:2,type:"Int16"}],4),xye=Qs([{name:"a_circle_z_offset",components:1,type:"Float32"}],4),yye=Qs([{name:"a_pos_3",components:3,type:"Int16"},{name:"a_pos_normal_3",components:3,type:"Int16"}]);class No{constructor(u=[]){this.segments=u}_prepareSegment(u,f,w,C,I){let L=this.segments[this.segments.length-1];return u>No.MAX_VERTEX_ARRAY_LENGTH&&Gr(`Max vertices per segment is ${No.MAX_VERTEX_ARRAY_LENGTH}: bucket requested ${u}`),(!L||L.vertexLength+u>No.MAX_VERTEX_ARRAY_LENGTH||L.sortKey!==C||I!==void 0&&L&&L.batchIndex!==void 0&&L.batchIndex!==I)&&(L={vertexOffset:f,primitiveOffset:w,vertexLength:0,primitiveLength:0},C!==void 0&&(L.sortKey=C),I!==void 0&&(L.batchIndex=I),this.segments.push(L)),L}prepareSegment(u,f,w,C,I){return this._prepareSegment(u,f.length,w.length,C,I)}get(){return this.segments}destroy(){for(const u of this.segments)for(const f in u.vaos)u.vaos[f].destroy()}static simpleSegment(u,f,w,C){return new No([{vertexOffset:u,primitiveOffset:f,vertexLength:w,primitiveLength:C,vaos:{},sortKey:0}])}}function TM(v,u){return 256*(v=He(Math.floor(v),0,255))+He(Math.floor(u),0,255)}No.MAX_VERTEX_ARRAY_LENGTH=Math.pow(2,16)-1,Pr(No,"SegmentVector");const vye=Qs([{name:"a_pattern",components:4,type:"Uint16"},{name:"a_pixel_ratio",components:1,type:"Float32"}]),bye=Qs([{name:"a_pattern_b",components:4,type:"Uint16"}]),_ye=Qs([{name:"a_dash",components:4,type:"Uint16"}]);class R4{constructor(){this.ids=[],this.uniqueIds=[],this.positions=[],this.indexed=!1}add(u,f,w,C){this.ids.push(jD(u)),this.positions.push(f,w,C)}eachPosition(u,f){const w=jD(u);let C=0,I=this.ids.length-1;for(;C>1;this.ids[L]>=w?I=L:C=L+1}for(;this.ids[C]===w;)f(this.positions[3*C],this.positions[3*C+1],this.positions[3*C+2]),C++}static serialize(u,f){const w=new Float64Array(u.ids),C=new Uint32Array(u.positions);return O4(w,C,0,w.length-1),f&&(f.add(w.buffer),f.add(C.buffer)),{ids:w,positions:C}}static deserialize(u){const f=new R4;let w;f.ids=u.ids,f.positions=u.positions;for(const C of f.ids)C!==w&&f.uniqueIds.push(C),w=C;return f.indexed=!0,f}}function jD(v){const u=+v;return Number.isSafeInteger(u)?u:fd(String(v))}function O4(v,u,f,w){for(;f>1];let I=f-1,L=w+1;for(;;){do I++;while(v[I]C);if(I>=L)break;Gp(v,I,L),Gp(u,3*I,3*L),Gp(u,3*I+1,3*L+1),Gp(u,3*I+2,3*L+2)}L-f`u_${I}`),this.type=w,this.context=C}setUniform(u,f,w,C,I){const L=C.constantOr(this.value);f.set(u,I,L instanceof Mr?L.toPremultipliedRenderColor(this.lutExpression&&this.lutExpression.kind==="constant"&&this.lutExpression.value==="none"?null:this.context.lut):L)}getBinding(u,f){return this.type==="color"?new jye(u):new Yc(u)}}class ae{constructor(u,f){this.uniformNames=f.map(w=>`u_${w}`),this.pattern=null,this.patternTransition=null,this.pixelRatio=1}setConstantPatternPositions(u,f){this.pixelRatio=u.pixelRatio||1,this.pattern=u.tl.concat(u.br),this.patternTransition=f?f.tl.concat(f.br):this.pattern}setUniform(u,f,w,C,I){let L=null;I!=="u_pattern"&&I!=="u_dash"||(L=this.pattern),I==="u_pattern_b"&&(L=this.patternTransition),I==="u_pixel_ratio"&&(L=this.pixelRatio),L&&f.set(u,I,L)}getBinding(u,f){return f==="u_pattern"||f==="u_pattern_b"||f==="u_dash"?new wye(u):new Yc(u)}}class me{constructor(u,f,w,C){this.expression=u,this.type=w,this.maxValue=0,this.paintVertexAttributes=f.map(I=>({name:`a_${I}`,type:"Float32",components:w==="color"?2:1,offset:0})),this.paintVertexArray=new C}populatePaintArray(u,f,w,C,I,L,B,U){const Y=this.paintVertexArray.length,se=this.expression.kind==="composite"||this.expression.kind==="source"?this.expression.evaluate(new wa(0,{brightness:L,worldview:U}),f,{},I,C,B):this.expression.kind==="constant"&&this.expression.value,oe=G(this.lutExpression,f,{},C,I,L,B,U);this.paintVertexArray.resize(u),this._setPaintValue(Y,u,se,oe?null:this.context.lut)}updatePaintArray(u,f,w,C,I,L,B,U){const Y=this.expression.kind==="composite"||this.expression.kind==="source"?this.expression.evaluate({zoom:0,brightness:B,worldview:U},w,C,void 0,I):this.expression.kind==="constant"&&this.expression.value,se=G(this.lutExpression,w,C,I,void 0,B,void 0,U);this._setPaintValue(u,f,Y,se?null:this.context.lut)}_setPaintValue(u,f,w,C){if(this.type==="color"){const I=q(w.toPremultipliedRenderColor(C));for(let L=u;L`u_${B}_t`),this.type=w,this.useIntegerZoom=C,this.context=I,this.maxValue=0,this.paintVertexAttributes=f.map(B=>({name:`a_${B}`,type:"Float32",components:w==="color"?4:2,offset:0})),this.paintVertexArray=new L}populatePaintArray(u,f,w,C,I,L,B,U){const Y=this.expression.evaluate(new wa(this.context.zoom,{brightness:L,worldview:U}),f,{},I,C,B),se=this.expression.evaluate(new wa(this.context.zoom+1,{brightness:L,worldview:U}),f,{},I,C,B),oe=G(this.lutExpression,f,{},C,I,L,B,U),de=this.paintVertexArray.length;this.paintVertexArray.resize(u),this._setPaintValue(de,u,Y,se,oe?null:this.context.lut)}updatePaintArray(u,f,w,C,I,L,B,U){const Y=this.expression.evaluate({zoom:this.context.zoom,brightness:B,worldview:U},w,C,void 0,I),se=this.expression.evaluate({zoom:this.context.zoom+1,brightness:B,worldview:U},w,C,void 0,I),oe=G(this.lutExpression,w,C,I,void 0,B,void 0,U);this._setPaintValue(u,f,Y,se,oe?null:this.context.lut)}_setPaintValue(u,f,w,C,I){if(this.type==="color"){const L=q(w.toPremultipliedRenderColor(I)),B=q(C.toPremultipliedRenderColor(I));for(let U=u;U!0){this.binders={},this._buffers=[],this.context=f;const C=[],I=u;for(const L in u.paint._values){const B=I.paint.get(L);if(L.endsWith("-use-theme")||!w(L)||!(B instanceof Mv&&yf(B.property.specification)))continue;const U=Ge(L,u.type),Y=B.value,se=B.property.specification.type,oe=!!B.property.useIntegerZoom,de=L==="line-dasharray"||L.endsWith("pattern"),xe=I.paint.get(`${L}-use-theme`),we=L==="line-dasharray"&&I.layout.get("line-cap").value.kind!=="constant"||xe&&xe.value.kind!=="constant";if(Y.kind!=="constant"||we)if(Y.kind==="source"||we||de){const Ce=_t(L,se,"source");this.binders[L]=de?new Ae(Y,U,se,Ce,u.id):new me(Y,U,se,Ce),C.push(`/a_${L}`)}else{const Ce=_t(L,se,"composite");this.binders[L]=new ye(Y,U,se,oe,f,Ce),C.push(`/z_${L}`)}else this.binders[L]=de?new ae(Y.value,U):new Q(Y.value,U,se,f),C.push(`/u_${L}`);xe&&(this.binders[L].lutExpression=xe.value)}this.cacheKey=C.sort().join("")}getMaxValue(u){const f=this.binders[u];return f instanceof me||f instanceof ye?f.maxValue:0}populatePaintArrays(u,f,w,C,I,L,B,U){for(const Y in this.binders){const se=this.binders[Y];se.context=this.context,(se instanceof me||se instanceof ye||se instanceof Ae)&&se.populatePaintArray(u,f,w,C,I,L,B,U)}}setConstantPatternPositions(u,f){for(const w in this.binders){const C=this.binders[w];C instanceof ae&&C.setConstantPatternPositions(u,f)}}getPatternTransitionVertexBuffer(u){const f=this.binders[u];return f instanceof Ae?f.paintTransitionVertexBuffer:null}updatePaintArrays(u,f,w,C,I,L,B,U,Y,se){let oe=!1;const de=Object.keys(u),xe=de.length!==0&&!U,we=xe?de:f.uniqueIds;this.context.lut=I.lut;for(const Ce in this.binders){const Re=this.binders[Ce];if(Re.context=this.context,(Re instanceof me||Re instanceof ye||Re instanceof Ae)&&Re.expression&&Re.expression.kind&&Re.expression.kind!=="constant"&&(Re.expression.isStateDependent===!0||Re.expression.isLightConstant===!1)){const qe=I.paint.get(Ce);Re.expression=qe.value;for(const nt of we){const Ze=u[nt.toString()];f.eachPosition(nt,(ut,xt,bt)=>{const Ht=C.feature(ut);Re.updatePaintArray(xt,bt,Ht,Ze,L,B,Y,se)})}if(!xe)for(const nt of w.uniqueIds){const Ze=u[nt.toString()];w.eachPosition(nt,(ut,xt,bt)=>{const Ht=C.feature(ut);Re.updatePaintArray(xt,bt,Ht,Ze,L,B,Y,se)})}oe=!0}}return oe}defines(){const u=[];for(const f in this.binders){const w=this.binders[f];(w instanceof Q||w instanceof ae)&&u.push(...w.uniformNames.map(C=>`#define HAS_UNIFORM_${C}`))}return u}getPaintVertexBuffers(){return this._buffers}getUniforms(u){const f=[];for(const w in this.binders){const C=this.binders[w];if(C instanceof Q||C instanceof ae||C instanceof ye)for(const I of C.uniformNames)f.push({name:I,property:w,binding:C.getBinding(u,I)})}return f}setUniforms(u,f,w,C,I){for(const{name:L,property:B,binding:U}of w)this.binders[B].setUniform(u,U,I,C.get(B),L)}updatePaintBuffers(){this._buffers=[];for(const u in this.binders){const f=this.binders[u];(f instanceof me||f instanceof ye||f instanceof Ae)&&f.paintVertexBuffer&&this._buffers.push(f.paintVertexBuffer),f instanceof Ae&&f.paintTransitionVertexBuffer&&this._buffers.push(f.paintTransitionVertexBuffer)}}upload(u){for(const f in this.binders){const w=this.binders[f];(w instanceof me||w instanceof ye||w instanceof Ae)&&w.upload(u)}this.updatePaintBuffers()}destroy(){for(const u in this.binders){const f=this.binders[u];(f instanceof me||f instanceof ye||f instanceof Ae)&&f.destroy()}}}class Fe{constructor(u,f,w=()=>!0){this.programConfigurations={};for(const C of u)this.programConfigurations[C.id]=new Te(C,f,w);this.needsUpload=!1,this._featureMap=new R4,this._featureMapWithoutIds=new R4,this._bufferOffset=0,this._idlessCounter=0}populatePaintArrays(u,f,w,C,I,L,B,U,Y){for(const se in this.programConfigurations)this.programConfigurations[se].populatePaintArrays(u,f,C,I,L,B,U,Y);f.id!==void 0?this._featureMap.add(f.id,w,this._bufferOffset,u):(this._featureMapWithoutIds.add(this._idlessCounter,w,this._bufferOffset,u),this._idlessCounter+=1),this._bufferOffset=u,this.needsUpload=!0}updatePaintArrays(u,f,w,C,I,L,B,U){for(const Y of w)this.needsUpload=this.programConfigurations[Y.id].updatePaintArrays(u,this._featureMap,this._featureMapWithoutIds,f,Y,C,I,L,B||0,U)||this.needsUpload}get(u){return this.programConfigurations[u]}upload(u){if(this.needsUpload){for(const f in this.programConfigurations)this.programConfigurations[f].upload(u);this.needsUpload=!1}}destroy(){for(const u in this.programConfigurations)this.programConfigurations[u].destroy()}}const Ye={"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 Ge(v,u){return Ye[v]||[v.replace(`${u}-`,"").replace(/-/g,"_")]}const dt={"line-pattern":{source:ay,composite:ay},"fill-pattern":{source:ay,composite:ay},"fill-extrusion-pattern":{source:ay,composite:ay},"line-dasharray":{source:sN,composite:sN}},lt={color:{source:zw,composite:Pv},number:{source:Zi,composite:zw}};function _t(v,u,f){const w=dt[v];return w&&w[f]||lt[u][f]}Pr(Q,"ConstantBinder"),Pr(ae,"PatternConstantBinder"),Pr(me,"SourceExpressionBinder"),Pr(Ae,"PatternCompositeBinder"),Pr(ye,"CompositeExpressionBinder"),Pr(Te,"ProgramConfiguration",{omit:["_buffers"]}),Pr(Fe,"ProgramConfigurationSet");const Ct=Sr/Math.PI/2,ht=64,Kt=[ht,32,16],Lt=-Ct,Wt=Ct;function Tt(v,u,f,w=Ct){return f=Hr(f),[v*Math.sin(f)*w,-u*w,v*Math.cos(f)*w]}function It(v,u,f){return Tt(Math.cos(Hr(v)),Math.sin(Hr(v)),u,f)}const Ut=63710088e-1,rs=2*Math.PI*Ut;class Zt{constructor(u,f){if(isNaN(u)||isNaN(f))throw new Error(`Invalid LngLat object: (${u}, ${f})`);if(this.lng=+u,this.lat=+f,this.lat>90||this.lat<-90)throw new Error("Invalid LngLat latitude value: must be between -90 and 90")}wrap(){return new Zt(jt(this.lng,-180,180),this.lat)}toArray(){return[this.lng,this.lat]}toString(){return`LngLat(${this.lng}, ${this.lat})`}distanceTo(u){const f=Math.PI/180,w=this.lat*f,C=u.lat*f,I=Math.sin(w)*Math.sin(C)+Math.cos(w)*Math.cos(C)*Math.cos((u.lng-this.lng)*f);return Ut*Math.acos(Math.min(I,1))}toBounds(u=0){const f=360*u/40075017,w=f/Math.cos(Math.PI/180*this.lat);return new ks({lng:this.lng-w,lat:this.lat-f},{lng:this.lng+w,lat:this.lat+f})}toEcef(u){return It(this.lat,this.lng,Ct+u*Ct/Ut)}static convert(u){if(u instanceof Zt)return u;if(Array.isArray(u)&&(u.length===2||u.length===3))return new Zt(Number(u[0]),Number(u[1]));if(!Array.isArray(u)&&typeof u=="object"&&u!==null)return new Zt(Number("lng"in u?u.lng:u.lon),Number(u.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 ks{constructor(u,f){u&&(f?this.setSouthWest(u).setNorthEast(f):Array.isArray(u)&&u.length===4?this.setSouthWest([u[0],u[1]]).setNorthEast([u[2],u[3]]):this.setSouthWest(u[0]).setNorthEast(u[1]))}setNorthEast(u){return this._ne=u instanceof Zt?new Zt(u.lng,u.lat):Zt.convert(u),this}setSouthWest(u){return this._sw=u instanceof Zt?new Zt(u.lng,u.lat):Zt.convert(u),this}extend(u){const f=this._sw,w=this._ne;let C,I;if(u instanceof Zt)C=u,I=u;else{if(!(u instanceof ks))return Array.isArray(u)?u.length===4||u.every(Array.isArray)?this.extend(ks.convert(u)):this.extend(Zt.convert(u)):typeof u=="object"&&u!==null&&u.hasOwnProperty("lat")&&(u.hasOwnProperty("lon")||u.hasOwnProperty("lng"))?this.extend(Zt.convert(u)):this;if(C=u._sw,I=u._ne,!C||!I)return this}return f||w?(f.lng=Math.min(C.lng,f.lng),f.lat=Math.min(C.lat,f.lat),w.lng=Math.max(I.lng,w.lng),w.lat=Math.max(I.lat,w.lat)):(this._sw=new Zt(C.lng,C.lat),this._ne=new Zt(I.lng,I.lat)),this}getCenter(){return new Zt((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 Zt(this.getWest(),this.getNorth())}getSouthEast(){return new Zt(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(u){const{lng:f,lat:w}=Zt.convert(u);let C=this._sw.lng<=f&&f<=this._ne.lng;return this._sw.lng>this._ne.lng&&(C=this._sw.lng>=f&&f>=this._ne.lng),this._sw.lat<=w&&w<=this._ne.lat&&C}static convert(u){if(u)return u instanceof ks?u:new ks(u)}}function ms(v){return rs*Math.cos(v*Math.PI/180)}function Ws(v){return(180+v)/360}function sr(v){return(180-180/Math.PI*Math.log(Math.tan(Math.PI/4+v*Math.PI/360)))/360}function as(v,u){return v/ms(u)}function Xt(v){return 360*v-180}function ws(v){return 360/Math.PI*Math.atan(Math.exp((180-360*v)*Math.PI/180))-90}function Ts(v,u){return v*ms(ws(u))}const Ls=85.051129;function wr(v){return Math.cos(Hr(He(v,-85.051129,Ls)))}function mr(v,u){const f=He(u,0,25.5),w=Math.pow(2,f);return wr(v)*rs/(512*w)}function fr(v){return 1/Math.cos(v*Math.PI/180)}function Js(v,u=0){const f=Math.exp(Math.PI*(1-(v.y+u/Sr)/(1<=U?(dn(v,u,f,Y,se,I,oe,B,U),dn(v,Y,se,w,C,oe,L,B,U)):v.push(L)}function Kr(v,u,f){let w=v[0],C=w.x,I=w.y;u(w);const L=[w];for(let B=1;Bv.x+1||wv.y+1)&&Gr("Geometry exceeds allowed extent, reduce your vector tile buffer size"),v}function Ln(v,u,f){const w=v.loadGeometry(),C=v.extent,I=Sr/C;if(u&&f&&f.projection.isReprojectedInTileSpace){const L=1<{const xe=Xt((u.x+de.x/C)/L),we=ws((u.y+de.y/C)/L),Ce=se.project(xe,we);de.x=(Ce.x*B-U)*C,de.y=(Ce.y*B-Y)*C};for(let de=0;de=C||we.y<0||we.y>=C||(oe(we),xe.push(we));w[de]=xe}}for(const L of w)for(const B of L)Ra(B,I);return w}function Oa(v,u){return{type:v.type,id:v.id,properties:v.properties,geometry:u?Ln(v):[]}}class na{constructor(u,f,w,C,I){this.properties={},this.extent=w,this.type=0,this.id=void 0,this._pbf=u,this._geometry=-1,this._keys=C,this._values=I,u.readFields(ji,this,f)}loadGeometry(){const u=this._pbf;u.pos=this._geometry;const f=u.readVarint()+u.pos,w=[];let C,I=1,L=0,B=0,U=0;for(;u.pos>3}if(L--,I===1||I===2)B+=u.readSVarint(),U+=u.readSVarint(),I===1&&(C&&w.push(C),C=[]),C&&C.push(new ds(B,U));else{if(I!==7)throw new Error(`unknown command ${I}`);C&&C.push(C[0].clone())}}return C&&w.push(C),w}bbox(){const u=this._pbf;u.pos=this._geometry;const f=u.readVarint()+u.pos;let w=1,C=0,I=0,L=0,B=1/0,U=-1/0,Y=1/0,se=-1/0;for(;u.pos>3}if(C--,w===1||w===2)I+=u.readSVarint(),L+=u.readSVarint(),IU&&(U=I),Lse&&(se=L);else if(w!==7)throw new Error(`unknown command ${w}`)}return[B,Y,U,se]}toGeoJSON(u,f,w){const C=this.extent*Math.pow(2,w),I=this.extent*u,L=this.extent*f,B=this.loadGeometry();function U(de){return[360*(de.x+I)/C-180,360/Math.PI*Math.atan(Math.exp((1-2*(de.y+L)/C)*Math.PI))-90]}function Y(de){return de.map(U)}let se;if(this.type===1){const de=[];for(const we of B)de.push(we[0]);const xe=Y(de);se=de.length===1?{type:"Point",coordinates:xe[0]}:{type:"MultiPoint",coordinates:xe}}else if(this.type===2){const de=B.map(Y);se=de.length===1?{type:"LineString",coordinates:de[0]}:{type:"MultiLineString",coordinates:de}}else{if(this.type!==3)throw new Error("unknown feature type");{const de=function(we){const Ce=we.length;if(Ce<=1)return[we];const Re=[];let qe,nt;for(let Ze=0;Ze=this._features.length)throw new Error("feature index out of bounds");this._pbf.pos=this._features[u];const f=this._pbf.readVarint()+this._pbf.pos;return new na(this._pbf,f,this.extent,this._keys,this._values)}}function ko(v,u,f){v===15?u.version=f.readVarint():v===1?u.name=f.readString():v===5?u.extent=f.readVarint():v===2?u._features.push(f.pos):v===3?u._keys.push(f.readString()):v===4&&u._values.push(function(w){let C=null;const I=w.readVarint()+w.pos;for(;w.pos>3;C=L===1?w.readString():L===2?w.readFloat():L===3?w.readDouble():L===4?w.readVarint64():L===5?w.readVarint():L===6?w.readSVarint():L===7?w.readBoolean():null}if(C==null)throw new Error("unknown feature value");return C}(f))}class Ii{constructor(u,f){this.layers=u.readFields(Ca,{},f)}}function Ca(v,u,f){if(v===3){const w=new rl(f,f.readVarint()+f.pos);w.length&&(u[w.name]=w)}}const Ta="3d_elevation_id",So="level";class dl{constructor(){this._valid=!1}reset(u){return this.feature=u,this._valid=!0,this._geometry=u.loadGeometry(),this._geometry.length!==0&&this._geometry[0].length!==0||(this._valid=!1),this}geometry(u,f){return this._valid&&u(f(this._geometry)),this}require(u,f,w){return this.get(u,!0,f,w)}optional(u,f,w){return this.get(u,!1,f,w)}success(){return this._valid}get(u,f,w,C){const I=this.feature.properties.hasOwnProperty(u)?+this.feature.properties[u]:void 0;return this._valid&&I!==void 0&&!Number.isNaN(I)?w(C?C(I):I):f&&(this._valid=!1),this}}class Pi{constructor(u,f){this.featureFunc=u,this.vertexFunc=f}parseFeature(u,f,w){return this.featureFunc(u,f,w)}parseVertex(u,f,w){return this.vertexFunc(u,f,w)}}const ma=new Pi((v,u,f)=>v.reset(u).require(Ta,w=>{f.id=w}).optional("fixed_height_relative",w=>{f.constantHeight=w},ho.decodeRelativeHeight).geometry(w=>{f.bounds=w},Z1).success(),(v,u,f)=>v.reset(u).require(Ta,w=>{f.id=w}).require("elevation_idx",w=>{f.idx=w}).require("extent",w=>{f.extent=w}).require("height_relative",w=>{f.height=w},ho.decodeRelativeHeight).geometry(w=>{f.position=w},ho.getPoint).success()),Yo=new Pi((v,u,f)=>v.reset(u).require(Ta,w=>{f.id=w}).optional("fixed_height",w=>{f.constantHeight=w},ho.decodeMetricHeight).geometry(w=>{f.bounds=w},Z1).success(),(v,u,f)=>v.reset(u).require(Ta,w=>{f.id=w}).require("elevation_idx",w=>{f.idx=w}).require("extent",w=>{f.extent=w}).require("height",w=>{f.height=w},ho.decodeMetricHeight).geometry(w=>{f.position=w},ho.getPoint).success());class ho{static getPoint(u){return fs(u[0][0].x,u[0][0].y)}static decodeRelativeHeight(u){return 1e-4*u*5}static decodeMetricHeight(u){return 1e-4*u}static getVersionSchema(u){return u?u==="1.0.1"?Yo:void 0:ma}static parse(u){const f=[],w=[],C=u.length,I=new dl;for(let L=0;L=0);if(I===0)return 0;I!==u.length&&(f=!1)}return f?2:1}function Zc(v,u){for(const f of v.projections){const w=Ic(u,v.points[0],f.axis);if(f.projection[1]w[1])return 0}return 1}function eu(v,u){let f=0;const w=[0,0,0,0];for(let C=0;C=0&&f++;return f}class lp{constructor(u,f){this.points=u||new Array(8).fill([0,0,0]),this.planes=f||new Array(6).fill([0,0,0,0]),this.bounds=Vi.fromPoints(this.points),this.projections=[],this.frustumEdges=[Qe([],this.points[2],this.points[3]),Qe([],this.points[0],this.points[3]),Qe([],this.points[4],this.points[0]),Qe([],this.points[5],this.points[1]),Qe([],this.points[6],this.points[2]),Qe([],this.points[7],this.points[3])];for(const w of this.frustumEdges){const C=[0,-w[2],w[1]],I=[w[2],0,-w[0]];this.projections.push({axis:C,projection:Ic(this.points,this.points[0],C)}),this.projections.push({axis:I,projection:Ic(this.points,this.points[0],I)})}}static fromInvProjectionMatrix(u,f,w,C){const I=Math.pow(2,w),L=[[-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(Y=>{const se=wt([],Y,u),oe=1/se[3]/f*I;return(de=se)[0]=(xe=se)[0]*(we=[oe,oe,C?1/se[3]:oe,oe])[0],de[1]=xe[1]*we[1],de[2]=xe[2]*we[2],de[3]=xe[3]*we[3],de;var de,xe,we}),B=[[0,1,2],[6,5,4],[0,3,7],[2,1,5],[3,2,6],[0,4,5]].map(Y=>{const se=Pe([],De([],Qe([],L[Y[0]],L[Y[1]]),Qe([],L[Y[2]],L[Y[1]]))),oe=-Ie(se,L[Y[1]]);return se.concat(oe)}),U=[];for(let Y=0;YY[1]||Y[0]>U[1])return 0}return 1}containsPoint(u){for(const f of this.planes){const w=f[3];if(Ie([f[0],f[1],f[2]],u)+w<0)return!1}return!0}}class Vi{static fromPoints(u){const f=[1/0,1/0,1/0],w=[-1/0,-1/0,-1/0];for(const C of u)fe(f,f,C),je(w,w,C);return new Vi(f,w)}static fromTileIdAndHeight(u,f,w){const C=1<u.max[f]||u.min[f]>this.max[f])return!1;return!0}intersectsAabbXY(u){return!(this.min[0]>u.max[0]||u.min[0]>this.max[0]||this.min[1]>u.max[1]||u.min[1]>this.max[1])}encapsulate(u){for(let f=0;f<3;f++)this.min[f]=Math.min(this.min[f],u.min[f]),this.max[f]=Math.max(this.max[f],u.max[f])}encapsulatePoint(u){for(let f=0;f<3;f++)this.min[f]=Math.min(this.min[f],u[f]),this.max[f]=Math.max(this.max[f],u[f])}closestPoint(u){return[Math.max(Math.min(this.max[0],u[0]),this.min[0]),Math.max(Math.min(this.max[1],u[1]),this.min[1]),Math.max(Math.min(this.max[2],u[2]),this.min[2])]}}Pr(Vi,"Aabb");class Wp{constructor(u,f){this.feature=u,this.metersToTile=f,this.index=0}get(){const u=this.feature.vertices[this.index],f=this.feature.vertexProps[this.index].dir,w=f[1],C=-f[0],I=(u.extent+1)*this.metersToTile;return[new ds(Math.trunc(u.position[0]+w*I),Math.trunc(u.position[1]+C*I)),new ds(Math.trunc(u.position[0]-w*I),Math.trunc(u.position[1]-C*I))]}next(){this.index++}valid(){return this.index{return B.a0?ve(U,U,1/Y):ce(U,0,0,1)}getSafeArea(){return this.safeArea}isTunnel(){return this.heightRange.max<=-5}getClosestEdge(u){if(this.edges.length===0)return;let f=0,w=Number.POSITIVE_INFINITY,C=0;const[I,L,B,U,Y,se,oe]=this._tmpVec2;Gs(oe,u.x,u.y);const de=new cc(oe,null);for(let xe=0;xe0?sn(U,B)/ut:0,bt=He(xt,0,1),Ht=Math.abs((xt-bt)*this.edgeProps[xe].len);br(Y,oe,Re),Gs(se,Ce[1],-Ce[0]);const Rt=Ht+Math.abs(sn(Y,se));Rt=0;--L){const B=this.edges[L].a,U=this.edges[L].b,{position:Y,height:se,extent:oe}=this.vertices[B],{position:de,height:xe,extent:we}=this.vertices[U],Ce=this.vertexProps[B].dir,Re=this.vertexProps[U].dir;if(ce(f,Y[0]/u,Y[1]/u,se),ce(w,de[0]/u,de[1]/u,xe),ce(C,Ce[1],-Ce[0],0),ve(C,C,oe),ce(I,Re[1],-Re[0],0),ve(I,I,we),this.distSqLines(ie(f[0]+.5*C[0],f[1]+.5*C[1],f[2]+.5*C[2]),ie(w[0]-.5*I[0],w[1]-.5*I[1],w[2]-.5*I[2]),ie(f[0]-.5*C[0],f[1]-.5*C[1],f[2]-.5*C[2]),ie(w[0]+.5*I[0],w[1]+.5*I[1],w[2]+.5*I[2]))<=.0025000000000000005)continue;const qe=this.vertices.length,nt=_s(kt(),Y,de);this.vertices.push({position:zr(nt,nt,.5),height:.5*(se+xe),extent:.5*(oe+we)});const Ze=_s(kt(),Ce,Re);this.vertexProps.push({dir:rn(Ze,Ze)}),this.edges.splice(L,1),this.edgeProps.splice(L,1),this.edges.push({a:B,b:qe}),this.edges.push({a:qe,b:U});const ut=br(kt(),this.vertices[qe].position,Y),xt=Yr(ut),bt={vec:ut,dir:zr(kt(),ut,1/xt),len:xt};this.edgeProps.push(bt),this.edgeProps.push(bt)}}distSqLines(u,f,w,C){const I=le(J(),f,u),L=le(J(),C,w),B=le(J(),u,w),U=Ie(I,I),Y=Ie(I,L),se=Ie(I,B),oe=Ie(L,L),de=Ie(L,B),xe=U*oe-Y*Y;if(xe===0)return Le(pe(I,w,C,Ie(B,L)/Ie(L,L)),u);const we=(U*de-Y*se)/xe;return Le(pe(I,u,f,(Y*de-se*oe)/xe),pe(L,w,C,we))}}class Eo{static parseFrom(u,f){const w=ho.parse(u);if(!w)return[];let{vertices:C,features:I}=w;const L=1/Js(f);I.sort((se,oe)=>se.id-oe.id),C.sort((se,oe)=>se.id-oe.id||se.idx-oe.idx),C=C.filter((se,oe,de)=>oe===de.findIndex(xe=>xe.id===se.id&&xe.idx===se.idx));const B=new Array;let U=0;const Y=C.length;for(const se of I){if(se.constantHeight){B.push(new Kp(se.id,se.bounds,se.constantHeight));continue}for(;U!==Y&&C[U].idC.id===w)}}class Do{constructor(u,f){this.zScale=1,this.xOffset=0,this.yOffset=0,u.equals(f)||(this.zScale=Math.pow(2,f.z-u.z),this.xOffset=(u.x*this.zScale-f.x)*Sr,this.yOffset=(u.y*this.zScale-f.y)*Sr)}constantElevation(u,f){if(u.constantHeight!=null)return this.computeBiasedHeight(u.constantHeight,f)}pointElevation(u,f,w){const C=this.constantElevation(f,w);return C??(u.x=u.x*this.zScale+this.xOffset,u.y=u.y*this.zScale+this.yOffset,this.computeBiasedHeight(f.pointElevation(u),w))}computeBiasedHeight(u,f){return f<=0?u:u+f*ot(0,f,u>=0?u:Math.abs(.5*u))}}Pr(Kp,"ElevationFeature");class so{constructor(u){this.zoom=u.zoom,this.overscaling=u.overscaling,this.layers=u.layers,this.layerIds=this.layers.map(f=>f.fqid),this.index=u.index,this.hasPattern=!1,this.projection=u.projection,this.layoutVertexArray=new Da,this.indexArray=new Yl,this.segments=new No,this.programConfigurations=new Fe(u.layers,{zoom:u.zoom,lut:u.lut}),this.stateDependentLayerIds=this.layers.filter(f=>f.isStateDependent()).map(f=>f.id),this.elevationMode=this.layers[0].layout.get("circle-elevation-reference"),this.hasElevation=!1,this.elevationMode!=="none"&&(this.elevatedLayoutVertexArray=new Zi),this.worldview=u.worldview,this.hasAppearances=null}updateFootprints(u,f){}updateAppearances(u,f,w,C){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(u,f,w,C){const I=this.layers[0],L=[];let B=null;I.type==="circle"&&(B=I.layout.get("circle-sort-key"));for(const{feature:Y,id:se,index:oe,sourceLayerIndex:de}of u){const xe=this.layers[0]._featureFilter.needGeometry,we=Oa(Y,xe);if(!this.layers[0]._featureFilter.filter(new wa(this.zoom,{worldview:this.worldview,activeFloors:f.activeFloors}),we,w))continue;const Ce=B?B.evaluate(we,{},w):void 0,Re={id:se,properties:Y.properties,type:Y.type,sourceLayerIndex:de,index:oe,geometry:xe?we.geometry:Ln(Y,w,C),patterns:{},sortKey:Ce};L.push(Re)}B&&L.sort((Y,se)=>Y.sortKey-se.sortKey);let U=null;C.projection.name==="globe"&&(this.globeExtVertexArray=new _M,U=C.projection);for(const Y of L){const{geometry:se,index:oe,sourceLayerIndex:de}=Y,xe=u[oe].feature;this.addFeature(Y,se,oe,f.availableImages,w,U,f.brightness,f.elevationFeatures),f.featureIndex.insert(xe,se,oe,de,this.index)}this.hasElevation||(this.elevatedLayoutVertexArray=void 0)}update(u,f,w,C,I,L,B){this.programConfigurations.updatePaintArrays(u,f,I,w,C,L,B,this.worldview)}isEmpty(){return this.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload}upload(u){this.uploaded||(this.layoutVertexBuffer=u.createVertexBuffer(this.layoutVertexArray,Jz.members),this.indexBuffer=u.createIndexBuffer(this.indexArray),this.globeExtVertexArray&&(this.globeExtVertexBuffer=u.createVertexBuffer(this.globeExtVertexArray,yye.members)),this.elevatedLayoutVertexArray&&(this.elevatedLayoutVertexBuffer=u.createVertexBuffer(this.elevatedLayoutVertexArray,xye.members))),this.programConfigurations.upload(u),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(u,f,w,C,I,L,B,U){let Y;this.elevationMode!=="none"&&(Y=Eo.getElevationFeature(u,U));for(const se of f)for(const oe of se){const de=oe.x,xe=oe.y;if(de<0||de>=Sr||xe<0||xe>=Sr)continue;if(L){const Re=L.projectTilePoint(de,xe,I),qe=L.upVector(I,de,xe);this.addGlobeExtVertex(Re,qe),this.addGlobeExtVertex(Re,qe),this.addGlobeExtVertex(Re,qe),this.addGlobeExtVertex(Re,qe)}const we=this.segments.prepareSegment(4,this.layoutVertexArray,this.indexArray,u.sortKey),Ce=we.vertexLength;if(this.addCircleVertex(de,xe,-1,-1),this.addCircleVertex(de,xe,1,-1),this.addCircleVertex(de,xe,1,1),this.addCircleVertex(de,xe,-1,1),this.elevationMode!=="none"){const Re=Y?Y.pointElevation(new ds(de,xe)):0;this.hasElevation=this.hasElevation||Re!==0;for(let qe=0;qe<4;qe++)this.elevatedLayoutVertexArray.emplaceBack(Re)}this.indexArray.emplaceBack(Ce,Ce+1,Ce+2),this.indexArray.emplaceBack(Ce,Ce+2,Ce+3),we.vertexLength+=4,we.primitiveLength+=2}this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,u,w,{},C,I,B,void 0,this.worldview)}addCircleVertex(u,f,w,C){this.layoutVertexArray.emplaceBack(2*u+(w+1)/2,2*f+(C+1)/2)}addGlobeExtVertex(u,f){this.globeExtVertexArray.emplaceBack(u.x,u.y,u.z,f[0]*16384,f[1]*16384,f[2]*16384)}}function sc(v,u){for(let f=0;f1){if(gb(v,u))return!0;for(let w=0;w1?f:f.sub(u)._mult(C)._add(u))}function nN(v,u){let f,w,C,I=!1;for(let L=0;Lu.y!=C.y>u.y&&u.x<(C.x-w.x)*(u.y-w.y)/(C.y-w.y)+w.x&&(I=!I)}return I}function Nf(v,u){let f=!1;for(let w=0,C=v.length-1;wu.y!=L.y>u.y&&u.x<(L.x-I.x)*(u.y-I.y)/(L.y-I.y)+I.x&&(f=!f)}return f}function xb(v,u,f,w,C){for(const L of v)if(u<=L.x&&f<=L.y&&w>=L.x&&C>=L.y)return!0;const I=[new ds(u,f),new ds(u,C),new ds(w,C),new ds(w,f)];if(v.length>2){for(const L of I)if(Nf(v,L))return!0}for(let L=0;LC.x&&u.x>C.x||v.yC.y&&u.y>C.y)return!1;const I=fn(v,u,f[0]);return I!==fn(v,u,f[1])||I!==fn(v,u,f[2])||I!==fn(v,u,f[3])}function vb(v,u,f,w,C,I){let L=u.y-v.y,B=v.x-u.x;if(I=I||0){const U=L*L+B*B;if(U===0)return!0;const Y=Math.sqrt(U);L/=Y,B/=Y}return!((f.x-v.x)*L+(f.y-v.y)*B-I<0||(w.x-v.x)*L+(w.y-v.y)*B-I<0||(C.x-v.x)*L+(C.y-v.y)*B-I<0)}function AM(v,u,f,w,C,I,L){return!(vb(v,u,w,C,I,L)||vb(u,f,w,C,I,L)||vb(f,v,w,C,I,L)||vb(w,C,v,u,f,L)||vb(C,I,v,u,f,L)||vb(I,w,v,u,f,L))}function aN(v,u,f){const w=u.paint.get(v).value;return w.kind==="constant"?w.value:f.programConfigurations.get(u.id).getMaxValue(v)}function e$(v){return Math.sqrt(v[0]*v[0]+v[1]*v[1])}function J6e(v,u,f,w,C){if(!u[0]&&!u[1])return v;const I=ds.convert(u)._mult(C);f==="viewport"&&I._rotate(-w);const L=[];for(let B=0;B>f&&u.y===this.y>>f}url(u,f){const w=function(I,L,B){const U=2**B,Y=2*Math.PI*6378137,se=Y*(I/U-.5),oe=Y*(.5-(L+1)/U);return`${se},${oe},${se+Y/U},${oe+Y/U}`}(this.x,this.y,this.z),C=function(I,L,B){let U,Y="";for(let se=I;se>0;se--)U=1<this.canonical.z?new Bm(u,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y):new Bm(u,this.wrap,u,this.canonical.x>>f,this.canonical.y>>f)}calculateScaledKey(u,f=!0){if(this.overscaledZ===u&&f)return this.key;if(u>this.canonical.z)return MM(this.wrap*+f,u,this.canonical.z,this.canonical.x,this.canonical.y);{const w=this.canonical.z-u;return MM(this.wrap*+f,u,u,this.canonical.x>>w,this.canonical.y>>w)}}isChildOf(u){if(u.wrap!==this.wrap)return!1;const f=this.canonical.z-u.canonical.z;return u.overscaledZ===0||u.overscaledZ>f&&u.canonical.y===this.canonical.y>>f}children(u){if(this.overscaledZ>=u)return[new Bm(this.overscaledZ+1,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)];const f=this.canonical.z+1,w=2*this.canonical.x,C=2*this.canonical.y;return[new Bm(f,this.wrap,f,w,C),new Bm(f,this.wrap,f,w+1,C),new Bm(f,this.wrap,f,w,C+1),new Bm(f,this.wrap,f,w+1,C+1)]}isLessThan(u){return this.wrapu.wrap)&&(this.overscaledZu.overscaledZ)&&(this.canonical.xu.canonical.x)&&this.canonical.y{let u=v.canonical.x-1,f=v.wrap;return u<0&&(u=(1<{let u=v.canonical.x+1,f=v.wrap;return u===1<new Bm(v.overscaledZ,v.wrap,v.canonical.z,v.canonical.x,(v.canonical.y===0?1<new Bm(v.overscaledZ,v.wrap,v.canonical.z,v.canonical.x,v.canonical.y===(1<1?null:function(w,C,I,L){const B=Math.sin(I);return w*(Math.sin((1-L)*I)/B)+C*(Math.sin(L*I)/B)}(v.a[u],v.b[u],v.angle,He(f,0,1))+v.center[u]}function bb(v){if(v.z<=1)return Tbt[v.z+2*v.y+v.x];const u=kye(r$(v));return Vi.fromPoints(u)}function Vw(v,u,f){return ve(v,v,1-f),We(v,v,u,f)}function iIe(v,u){const f=Hw(u.zoom);if(f===0)return bb(v);const w=r$(v),C=kye(w),I=Ws(w.getWest())*u.worldSize,L=Ws(w.getEast())*u.worldSize,B=sr(w.getNorth())*u.worldSize,U=sr(w.getSouth())*u.worldSize,Y=[I,B,0],se=[L,B,0],oe=[I,U,0],de=[L,U,0],xe=j([],u.globeMatrix);return tt(Y,Y,xe),tt(se,se,xe),tt(oe,oe,xe),tt(de,de,xe),C[0]=Vw(C[0],oe,f),C[1]=Vw(C[1],de,f),C[2]=Vw(C[2],se,f),C[3]=Vw(C[3],Y,f),Vi.fromPoints(C)}function oIe(v,u,f){for(const w of v)tt(w,w,u),ve(w,w,f)}function lIe(v,u,f,w){const C=u/v.worldSize,I=v.globeMatrix;if(f.z<=1){const Vt=bb(f).getCorners();return oIe(Vt,I,C),Vi.fromPoints(Vt)}const L=r$(f,w),B=kye(L,Ct+s$(v._tileCoverLift));oIe(B,I,C);const U=Number.MAX_VALUE,Y=[-U,-U,-U],se=[U,U,U];if(L.contains(v.center)){for(const $t of B)fe(se,se,$t),je(Y,Y,$t);Y[2]=0;const Vt=v.point,Bt=[Vt.x*C,Vt.y*C,0];return fe(se,se,Bt),je(Y,Y,Bt),new Vi(se,Y)}if(v._tileCoverLift>0){for(const Vt of B)fe(se,se,Vt),je(Y,Y,Vt);return new Vi(se,Y)}const oe=[I[12]*C,I[13]*C,I[14]*C],de=L.getCenter(),xe=He(v.center.lat,-85.051129,Ls),we=He(de.lat,-85.051129,Ls),Ce=Ws(v.center.lng),Re=sr(xe);let qe=Ce-Ws(de.lng);const nt=Re-sr(we);qe>.5?qe-=1:qe<-.5&&(qe+=1);let Ze=0;Math.abs(qe)>Math.abs(nt)?Ze=qe>=0?1:3:(Ze=nt>=0?0:2,We(oe,oe,[I[4]*C,I[5]*C,I[6]*C],-Math.sin(Hr(nt>=0?L.getSouth():L.getNorth()))*Ct));const ut=B[Ze],xt=B[(Ze+1)%4],bt=new Ebt(ut,xt,oe),Ht=[Nye(bt,0)||ut[0],Nye(bt,1)||ut[1],Nye(bt,2)||ut[2]],Rt=Hw(v.zoom);if(Rt>0){const Vt=function({x:$t,y:js,z:Es},zs,Hs,$s,nr){const ys=1/(1<.5?Zr=-1:Nr<-.5&&(Zr=1),qs=((qs+Zr)*zs-($s*=zs))*Hs+$s,Zs=((Zs+Zr)*zs-$s)*Hs+$s,ir=(ir*zs-(nr*=zs))*Hs+nr,pr=(pr*zs-nr)*Hs+nr,[[qs,pr,0],[Zs,pr,0],[Zs,ir,0],[qs,ir,0]]}(f,u,v._pixelsPerMercatorPixel,Ce,Re);for(let $t=0;$tMath.PI/2*1.01}const mIe=Hr(85),Abt=Math.cos(mIe),Mbt=Math.sin(mIe),Ibt=y(),fIe=v=>{const u=[];return v.paint.get("circle-pitch-alignment")==="map"&&u.push("PITCH_WITH_MAP"),v.paint.get("circle-pitch-scale")==="map"&&u.push("SCALE_WITH_MAP"),u};function pIe(v,u,f,w,C,I,L,B,U){if(I&&v.queryGeometry.isAboveHorizon)return!1;I&&(U*=v.pixelToTileUnitsFactor);const Y=v.tileID.canonical,se=f.projection.upVectorScale(Y,f.center.lat,f.worldSize).metersToTile;for(const oe of u)for(const de of oe){const xe=de.add(B),we=C&&f.elevation?f.elevation.exaggeration()*C.getElevationAt(xe.x,xe.y,!0):0,Ce=f.projection.projectTilePoint(xe.x,xe.y,Y);if(we>0){const Ze=f.projection.upVector(Y,xe.x,xe.y);Ce.x+=Ze[0]*se*we,Ce.y+=Ze[1]*se*we,Ce.z+=Ze[2]*se*we}const Re=I?xe:Pbt(Ce.x,Ce.y,Ce.z,w),qe=I?v.tilespaceRays.map(Ze=>Dbt(Ze,we)):v.queryGeometry.screenGeometry,nt=wt([],[Ce.x,Ce.y,Ce.z,1],w);if(!L&&I?U*=nt[3]/f.cameraToCenterDistance:L&&!I&&(U*=f.cameraToCenterDistance/nt[3]),I){const Ze=ws((de.y/Sr+Y.y)/(1<v.width||C.height>v.height||f.x>v.width-C.width||f.y>v.height-C.height)throw new RangeError("out of range source coordinates for image copy");if(C.width>u.width||C.height>u.height||w.x>u.width-C.width||w.y>u.height-C.height)throw new RangeError("out of range destination coordinates for image copy");const U=v.data,Y=u.data,se=I===4&&B;for(let oe=0;oe{u[v.evaluationKey]=U;const Y=v.expression.evaluate(u),se=Y?Y.toNonPremultipliedRenderColor(null):null;se&&(C.data[L+B+0]=Math.floor(255*se.r),C.data[L+B+1]=Math.floor(255*se.g),C.data[L+B+2]=Math.floor(255*se.b),C.data[L+B+3]=Math.floor(255*se.a))};if(v.clips)for(let L=0,B=0;L80*f){B=v[0],U=v[1];let se=B,oe=U;for(let de=f;dese&&(se=xe),we>oe&&(oe=we)}Y=Math.max(se-B,oe-U),Y=Y!==0?32767/Y:0}return TD(I,L,f,B,U,Y,0),L}function kIe(v,u,f,w,C){let I;if(C===function(L,B,U,Y){let se=0;for(let oe=B,de=U-Y;oe0)for(let L=u;L=u;L-=w)I=EIe(L/w|0,v[L],v[L+1],I);return I&&PM(I,I.next)&&(MD(I),I=I.next),I}function $4(v,u){if(!v)return v;u||(u=v);let f,w=v;do if(f=!1,w.steiner||!PM(w,w.next)&&tu(w.prev,w,w.next)!==0)w=w.next;else{if(MD(w),w=u=w.prev,w===w.next)break;f=!0}while(f||w!==u);return u}function TD(v,u,f,w,C,I,L){if(!v)return;!L&&I&&function(U,Y,se,oe){let de=U;do de.z===0&&(de.z=Aye(de.x,de.y,Y,se,oe)),de.prevZ=de.prev,de.nextZ=de.next,de=de.next;while(de!==U);de.prevZ.nextZ=null,de.prevZ=null,function(xe){let we,Ce=1;do{let Re,qe=xe;xe=null;let nt=null;for(we=0;qe;){we++;let Ze=qe,ut=0;for(let bt=0;bt0||xt>0&&Ze;)ut!==0&&(xt===0||!Ze||qe.z<=Ze.z)?(Re=qe,qe=qe.nextZ,ut--):(Re=Ze,Ze=Ze.nextZ,xt--),nt?nt.nextZ=Re:xe=Re,Re.prevZ=nt,nt=Re;qe=Ze}nt.nextZ=null,Ce*=2}while(we>1)}(de)}(v,w,C,I);let B=v;for(;v.prev!==v.next;){const U=v.prev,Y=v.next;if(I?$bt(v,w,C,I):zbt(v))u.push(U.i,v.i,Y.i),MD(v),v=Y.next,B=Y.next;else if((v=Y)===B){L?L===1?TD(v=Ubt($4(v),u),u,f,w,C,I,2):L===2&&qbt(v,u,f,w,C,I):TD($4(v),u,f,w,C,I,1);break}}}function zbt(v){const u=v.prev,f=v,w=v.next;if(tu(u,f,w)>=0)return!1;const C=u.x,I=f.x,L=w.x,B=u.y,U=f.y,Y=w.y,se=Math.min(C,I,L),oe=Math.min(B,U,Y),de=Math.max(C,I,L),xe=Math.max(B,U,Y);let we=w.next;for(;we!==u;){if(we.x>=se&&we.x<=de&&we.y>=oe&&we.y<=xe&&ED(C,B,I,U,L,Y,we.x,we.y)&&tu(we.prev,we,we.next)>=0)return!1;we=we.next}return!0}function $bt(v,u,f,w){const C=v.prev,I=v,L=v.next;if(tu(C,I,L)>=0)return!1;const B=C.x,U=I.x,Y=L.x,se=C.y,oe=I.y,de=L.y,xe=Math.min(B,U,Y),we=Math.min(se,oe,de),Ce=Math.max(B,U,Y),Re=Math.max(se,oe,de),qe=Aye(xe,we,u,f,w),nt=Aye(Ce,Re,u,f,w);let Ze=v.prevZ,ut=v.nextZ;for(;Ze&&Ze.z>=qe&&ut&&ut.z<=nt;){if(Ze.x>=xe&&Ze.x<=Ce&&Ze.y>=we&&Ze.y<=Re&&Ze!==C&&Ze!==L&&ED(B,se,U,oe,Y,de,Ze.x,Ze.y)&&tu(Ze.prev,Ze,Ze.next)>=0||(Ze=Ze.prevZ,ut.x>=xe&&ut.x<=Ce&&ut.y>=we&&ut.y<=Re&&ut!==C&&ut!==L&&ED(B,se,U,oe,Y,de,ut.x,ut.y)&&tu(ut.prev,ut,ut.next)>=0))return!1;ut=ut.nextZ}for(;Ze&&Ze.z>=qe;){if(Ze.x>=xe&&Ze.x<=Ce&&Ze.y>=we&&Ze.y<=Re&&Ze!==C&&Ze!==L&&ED(B,se,U,oe,Y,de,Ze.x,Ze.y)&&tu(Ze.prev,Ze,Ze.next)>=0)return!1;Ze=Ze.prevZ}for(;ut&&ut.z<=nt;){if(ut.x>=xe&&ut.x<=Ce&&ut.y>=we&&ut.y<=Re&&ut!==C&&ut!==L&&ED(B,se,U,oe,Y,de,ut.x,ut.y)&&tu(ut.prev,ut,ut.next)>=0)return!1;ut=ut.nextZ}return!0}function Ubt(v,u){let f=v;do{const w=f.prev,C=f.next.next;!PM(w,C)&&CIe(w,f,f.next,C)&&AD(w,C)&&AD(C,w)&&(u.push(w.i,f.i,C.i),MD(f),MD(f.next),f=v=C),f=f.next}while(f!==v);return $4(f)}function qbt(v,u,f,w,C,I){let L=v;do{let B=L.next.next;for(;B!==L.prev;){if(L.i!==B.i&&Kbt(L,B)){let U=TIe(L,B);return L=$4(L,L.next),U=$4(U,U.next),TD(L,u,f,w,C,I,0),void TD(U,u,f,w,C,I,0)}B=B.next}L=L.next}while(L!==v)}function Vbt(v,u){let f=v.x-u.x;return f===0&&(f=v.y-u.y,f===0)&&(f=(v.next.y-v.y)/(v.next.x-v.x)-(u.next.y-u.y)/(u.next.x-u.x)),f}function Hbt(v,u){const f=function(C,I){let L=I;const B=C.x,U=C.y;let Y,se=-1/0;if(PM(C,L))return L;do{if(PM(C,L.next))return L.next;if(U<=L.y&&U>=L.next.y&&L.next.y!==L.y){const Ce=L.x+(U-L.y)*(L.next.x-L.x)/(L.next.y-L.y);if(Ce<=B&&Ce>se&&(se=Ce,Y=L.x=L.x&&L.x>=de&&B!==L.x&&SIe(UY.x||L.x===Y.x&&Gbt(Y,L)))&&(Y=L,we=Ce)}L=L.next}while(L!==oe);return Y}(v,u);if(!f)return u;const w=TIe(f,v);return $4(w,w.next),$4(f,f.next)}function Gbt(v,u){return tu(v.prev,v,u.prev)<0&&tu(u.next,v,v.next)<0}function Aye(v,u,f,w,C){return(v=1431655765&((v=858993459&((v=252645135&((v=16711935&((v=(v-f)*C|0)|v<<8))|v<<4))|v<<2))|v<<1))|(u=1431655765&((u=858993459&((u=252645135&((u=16711935&((u=(u-w)*C|0)|u<<8))|u<<4))|u<<2))|u<<1))<<1}function Wbt(v){let u=v,f=v;do(u.x=(v-L)*(I-B)&&(v-L)*(w-B)>=(f-L)*(u-B)&&(f-L)*(I-B)>=(C-L)*(w-B)}function ED(v,u,f,w,C,I,L,B){return!(v===L&&u===B)&&SIe(v,u,f,w,C,I,L,B)}function Kbt(v,u){return v.next.i!==u.i&&v.prev.i!==u.i&&!function(f,w){let C=f;do{if(C.i!==f.i&&C.next.i!==f.i&&C.i!==w.i&&C.next.i!==w.i&&CIe(C,C.next,f,w))return!0;C=C.next}while(C!==f);return!1}(v,u)&&(AD(v,u)&&AD(u,v)&&function(f,w){let C=f,I=!1;const L=(f.x+w.x)/2,B=(f.y+w.y)/2;do C.y>B!=C.next.y>B&&C.next.y!==C.y&&L<(C.next.x-C.x)*(B-C.y)/(C.next.y-C.y)+C.x&&(I=!I),C=C.next;while(C!==f);return I}(v,u)&&(tu(v.prev,v,u.prev)||tu(v,u.prev,u))||PM(v,u)&&tu(v.prev,v,v.next)>0&&tu(u.prev,u,u.next)>0)}function tu(v,u,f){return(u.y-v.y)*(f.x-u.x)-(u.x-v.x)*(f.y-u.y)}function PM(v,u){return v.x===u.x&&v.y===u.y}function CIe(v,u,f,w){const C=i$(tu(v,u,f)),I=i$(tu(v,u,w)),L=i$(tu(f,w,v)),B=i$(tu(f,w,u));return C!==I&&L!==B||!(C!==0||!a$(v,f,u))||!(I!==0||!a$(v,w,u))||!(L!==0||!a$(f,v,w))||!(B!==0||!a$(f,u,w))}function a$(v,u,f){return u.x<=Math.max(v.x,f.x)&&u.x>=Math.min(v.x,f.x)&&u.y<=Math.max(v.y,f.y)&&u.y>=Math.min(v.y,f.y)}function i$(v){return v>0?1:v<0?-1:0}function AD(v,u){return tu(v.prev,v,v.next)<0?tu(v,u,v.next)>=0&&tu(v,v.prev,u)>=0:tu(v,u,v.prev)<0||tu(v,v.next,u)<0}function TIe(v,u){const f=Mye(v.i,v.x,v.y),w=Mye(u.i,u.x,u.y),C=v.next,I=u.prev;return v.next=u,u.prev=v,f.next=C,C.prev=f,w.next=f,f.prev=w,I.next=w,w.prev=I,w}function EIe(v,u,f,w){const C=Mye(v,u,f);return w?(C.next=w.next,C.prev=w,w.next.prev=C,w.next=C):(C.prev=C,C.next=C),C}function MD(v){v.next.prev=v.prev,v.prev.next=v.next,v.prevZ&&(v.prevZ.nextZ=v.nextZ),v.nextZ&&(v.nextZ.prevZ=v.prevZ)}function Mye(v,u,f){return{i:v,x:u,y:f,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}function ID(v,u){const f=v.length;if(f<=1)return[v];const w=[];let C,I;for(let L=0;L1)for(let L=0;L=Sr&&f>=Sr}static evaluate(u){if(u.length===0)return new Gw;let f=[];for(const U of u)f.push(...U.portals);if(f.length===0)return new Gw;for(const U of f){const Y=U.va,se=U.vb;(Gw.isOnBorder(Y.x,se.x)||Gw.isOnBorder(Y.y,se.y))&&(U.type="border")}const w=f.filter(U=>U.type!=="unevaluated"),C=f.filter(U=>U.type==="unevaluated");if(C.length===0)return new Gw;C.sort((U,Y)=>U.hash===Y.hash?U.isTunnel===Y.isTunnel?0:U.isTunnel?-1:1:U.hashU.hashI!=="fill-tunnel-structure-color"),this.tunnelProgramConfigurations=new Fe(f,{zoom:w,lut:C},I=>I!=="fill-bridge-guard-rail-color")}addVertices(u,f){const w=this.unevalVertices.length;for(let C=0;C=I.min.x&&oe.x<=I.max.x&&oe.y>=I.min.y&&oe.y<=I.max.y||de.x>=I.min.x&&de.x<=I.max.x&&de.y>=I.min.y&&de.y<=I.max.y||yb(oe,de,B))||this.isOnBorder(oe.x,de.x)||this.isOnBorder(oe.y,de.y))continue;const xe=Yp.computeEdgeHash(this.unevalVertices[Y],this.unevalVertices[se]);let we,Ce=this.vertexHashLookup.get(Yp.computePosHash(oe));Ce!=null?we=Ce.next:(Ce=this.vertexHashLookup.get(Yp.computePosHash(de)),we=Ce!=null?Ce.prev:xe),this.unevalEdges.push({polygonIdx:u,a:Y,b:se,hash:xe,portalHash:we,isTunnel:C,type:"unevaluated",featureInfo:L})}}addPortalCandidates(u,f,w,C,I){if(f.length!==0){this.vertexHashLookup.clear();for(const L of f){if(L.length===0)continue;const B=L[0];let U=Yp.computeEdgeHash(B[B.length-2],B[B.length-1]);for(let Y=0;Y({vertexOffset:0,primitiveOffset:this.indexArray.length}),w=de=>{de.primitiveLength=this.indexArray.length-de.primitiveOffset},C=new Zbt(this.vertexPositions,this.vertexNormals,this.indexArray);this.prepareEdges(u.portals,this.unevalEdges);const I=f(),L=f(),B=f(),U=(de,xe)=>{de.sort((Ce,Re)=>Ce.type===xe&&Re.type!==xe?-1:Ce.type!==xe&&Re.type===xe?1:0);const we=de.findIndex(Ce=>Ce.type!==xe);return we>=0?we:de.length};let Y=0;this.unevalEdges.length>0&&(Y=U(this.unevalEdges,"none"),this.constructBridgeStructures(C,this.unevalVertices,this.unevalHeights,this.unevalEdges,{min:0,max:Y},this.tileToMeters)),w(B);const se=f(),oe=f();if(this.unevalEdges.length>0){const de=this.unevalEdges.splice(Y),xe=U(de,"tunnel")+Y;this.unevalEdges.push(...de),this.constructTunnelStructures(C,this.unevalVertices,this.unevalHeights,this.unevalEdges,{min:0,max:Y},{min:Y,max:xe})}w(se),C.addTriangles(this.unevalTriangles,this.unevalVertices,this.unevalHeights),w(oe),C.addTriangles(this.unevalTunnelTriangles,this.unevalVertices,this.unevalHeights),w(L),C.addTriangles(this.unevalTunnelTriangles,this.unevalVertices,[-.1]),w(I),this.maskSegments=No.simpleSegment(0,oe.primitiveOffset,0,oe.primitiveLength),this.depthSegments=No.simpleSegment(0,L.primitiveOffset,0,L.primitiveLength),this.renderableBridgeSegments=No.simpleSegment(0,B.primitiveOffset,0,B.primitiveLength),this.renderableTunnelSegments=No.simpleSegment(0,se.primitiveOffset,0,se.primitiveLength),this.shadowCasterSegments=No.simpleSegment(0,I.primitiveOffset,0,I.primitiveLength)}update(u,f,w,C,I,L,B,U){this.bridgeProgramConfigurations.updatePaintArrays(u,f,I,w,C,L,B,U),this.tunnelProgramConfigurations.updatePaintArrays(u,f,I,w,C,L,B,U)}upload(u){this.vertexBuffer||this.vertexPositions.length===0||this.vertexNormals.length===0||this.indexArray.length===0||(this.vertexBuffer=u.createVertexBuffer(this.vertexPositions,Fbt.members),this.vertexBufferNormal=u.createVertexBuffer(this.vertexNormals,Bbt.members),this.indexBuffer=u.createIndexBuffer(this.indexArray),this.bridgeProgramConfigurations.upload(u),this.tunnelProgramConfigurations.upload(u))}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(u,f,w,C,I){const L=(B,U)=>{for(let Y=0;Yce(Hs,f[$s].x,f[$s].y,w[$s]*U),oe=J(),de=J(),xe=J(),we=J(),Ce=J(),Re=(Hs,$s)=>{const nr=B.get(Yp.computePosHash(f[$s])),ys=nr.from,qs=nr.to;if(!ys||!qs)return;se(oe,ys),se(de,$s),se(xe,qs),Ue(we),et(oe,de)||(Qe(Ce,de,oe),Pe(we,Ce)),et(xe,de)||(Qe(Ce,xe,de),ne(we,we,Pe(Ce,Ce)));const Zs=$e(we);return Zs>0?ve(Hs,we,1/Zs):void 0};let qe=Number.POSITIVE_INFINITY;this.sortSubarray(C,I.min,I.max,(Hs,$s)=>Hs.featureInfo.featureIndex-$s.featureInfo.featureIndex);const nt=J(),Ze=J(),ut=J(),xt=J(),bt=J(),Ht=J(),Rt=J(),Vt=J(),Bt=J(),$t=[J(),J(),J(),J()],js=[J(),J(),J(),J()],Es=[{coord:new ds(0,0),height:0},{coord:new ds(0,0),height:0}],zs=(Hs,$s)=>Hs>$s;for(let Hs=I.min;Hsqe.featureInfo.featureIndex-nt.featureInfo.featureIndex;this.sortSubarray(C,I.min,I.max,U),this.sortSubarray(C,L.min,L.max,U);const Y=qe=>Pe(qe,qe),se=[{coord:new ds(0,0),height:0},{coord:new ds(0,0),height:0}],oe=(qe,nt)=>qeB.hash===U.hash?U.polygonIdx-B.polygonIdx:U.hash>B.hash?1:-1);let w=0,C=0,I=0,L=f[w].polygonIdx;do C++,(C===f.length||f[w].hash!==f[C].hash)&&((C-w===1||f[C-1].polygonIdx!==L)&&(IY.portalHashse.hash?B++:se.hash>Y.portalHash?U++:(Y.type=se.type,B++)}}}isOnBorder(u,f){return u<=0&&f<=0||u>=Sr&&f>=Sr}addFeatureSection(u,f,w,C){return u!==f&&(f=u,w.push({featureIndex:u,vertexStart:C.getVertexCount()}),C.clearVertexLookup()),f}sortSubarray(u,f,w,C){const I=u.slice(f,w);I.sort(C),u.splice(f,I.length,...I)}static computeEdgeHash(u,f){return(u.y===f.y&&u.x>f.x||u.y>f.y)&&([u,f]=[f,u]),BigInt(Yp.computePosHash(u))<<32n|BigInt(Yp.computePosHash(f))}static computePosHash(u){return((65535&u.x)<<16|65535&u.y)>>>0}}function Xbt(v,u){return v>u?1:v0))return f;f=f.left}}return null}contains(u){for(var f=this._root,w=this._compare;f;){var C=w(u,f.key);if(C===0)return!0;f=C<0?f.left:f.right}return!1}remove(u){var f=this.find(u);if(!f)return!1;if(this.splay(f),f.left)if(f.right){var w=this.minNode(f.right);w.parent!==f&&(this.replace(w,w.right),w.right=f.right,w.right.parent=w),this.replace(f,w),w.left=f.left,w.left.parent=w}else this.replace(f,f.left);else this.replace(f,f.right);return this._size--,!0}removeNode(u){if(!u)return!1;if(this.splay(u),u.left)if(u.right){var f=this.minNode(u.right);f.parent!==u&&(this.replace(f,f.right),f.right=u.right,f.right.parent=f),this.replace(u,f),f.left=u.left,f.left.parent=f}else this.replace(u,u.left);else this.replace(u,u.right);return this._size--,!0}erase(u){var f=this.find(u);if(f){this.splay(f);var w=f.left,C=f.right,I=null;w&&(w.parent=null,I=this.maxNode(w),this.splay(I),this._root=I),C&&(w?I.right=C:this._root=C,C.parent=I),this._size--}}pop(){var u=this._root,f=null;if(u){for(;u.left;)u=u.left;f={key:u.key,data:u.data},this.remove(u.key)}return f}next(u){var f=u;if(f)if(f.right)for(f=f.right;f&&f.left;)f=f.left;else for(f=u.parent;f&&f.right===u;)u=f,f=f.parent;return f}prev(u){var f=u;if(f)if(f.left)for(f=f.left;f&&f.right;)f=f.right;else for(f=u.parent;f&&f.left===u;)u=f,f=f.parent;return f}forEach(u){for(var f=this._root,w=[],C=!1,I=0;!C;)f?(w.push(f),f=f.left):w.length>0?(u(f=w.pop(),I++),f=f.right):C=!0;return this}range(u,f,w,C){const I=[],L=this._compare;let B,U=this._root;for(;I.length!==0||U;)if(U)I.push(U),U=U.left;else{if(U=I.pop(),B=L(U.key,f),B>0)break;if(L(U.key,u)>=0&&w.call(C,U))return this;U=U.right}return this}keys(){for(var u=this._root,f=[],w=[],C=!1;!C;)u?(f.push(u),u=u.left):f.length>0?(u=f.pop(),w.push(u.key),u=u.right):C=!0;return w}values(){for(var u=this._root,f=[],w=[],C=!1;!C;)u?(f.push(u),u=u.left):f.length>0?(u=f.pop(),w.push(u.data),u=u.right):C=!0;return w}at(u){for(var f=this._root,w=[],C=!1,I=0;!C;)if(f)w.push(f),f=f.left;else if(w.length>0){if(f=w.pop(),I===u)return f;I++,f=f.right}else C=!0;return null}load(u=[],f=[],w=!1){if(this._size!==0)throw new Error("bulk-load: tree is not empty");const C=u.length;return w&&Rye(u,f,0,C-1,this._compare),this._root=Dye(null,u,f,0,C),this._size=C,this}min(){var u=this.minNode(this._root);return u?u.key:null}max(){var u=this.maxNode(this._root);return u?u.key:null}isEmpty(){return this._root===null}get size(){return this._size}static createTree(u,f,w,C,I){return new Lye(w,I).load(u,f,C)}}function Dye(v,u,f,w,C){const I=C-w;if(I>0){const L=w+Math.floor(I/2),B={key:u[L],data:f[L],parent:v};return B.left=Dye(B,u,f,w,L),B.right=Dye(B,u,f,L+1,C),B}return null}function Rye(v,u,f,w,C){if(f>=w)return;const I=v[f+w>>1];let L=f-1,B=w+1;for(;;){do L++;while(C(v[L],I)<0);do B--;while(C(v[B],I)>0);if(L>=B)break;let U=v[L];v[L]=v[B],v[B]=U,U=u[L],u[L]=u[B],u[B]=U}Rye(v,u,f,B,C),Rye(v,u,B+1,w,C)}const MIe=11102230246251565e-32,dp=134217729,Qbt=(3+8*MIe)*MIe;function Oye(v,u,f,w,C){let I,L,B,U,Y=u[0],se=w[0],oe=0,de=0;se>Y==se>-Y?(I=Y,Y=u[++oe]):(I=se,se=w[++de]);let xe=0;if(oeY==se>-Y?(L=Y+I,B=I-(L-Y),Y=u[++oe]):(L=se+I,B=I-(L-se),se=w[++de]),I=L,B!==0&&(C[xe++]=B);oeY==se>-Y?(L=I+Y,U=L-I,B=I-(L-U)+(Y-U),Y=u[++oe]):(L=I+se,U=L-I,B=I-(L-U)+(se-U),se=w[++de]),I=L,B!==0&&(C[xe++]=B);for(;oe0:(w[0]-u[0])*(f[1]-u[1])-(f[0]-u[0])*(w[1]-u[1])>0}isAbove(u){return!this.isBelow(u)}isVertical(){return this.point[0]===this.otherEvent.point[0]}get inResult(){return this.resultTransition!==0}clone(){const u=new DM(this.point,this.left,this.otherEvent,this.isSubject,this.type);return u.contourId=this.contourId,u.resultTransition=this.resultTransition,u.prevInResult=this.prevInResult,u.isExteriorRing=this.isExteriorRing,u.inOut=this.inOut,u.otherInOut=this.otherInOut,u}}function _b(v,u){return v[0]===u[0]&&v[1]===u[1]}function Fye(v,u,f){const w=function(C,I,L,B,U,Y){const se=(I-Y)*(L-U),oe=(C-U)*(B-Y),de=se-oe;if(se===0||oe===0||se>0!=oe>0)return de;const xe=Math.abs(se+oe);return Math.abs(de)>=33306690738754716e-32*xe?de:-function(we,Ce,Re,qe,nt,Ze,ut){let xt,bt,Ht,Rt,Vt,Bt,$t,js,Es,zs,Hs,$s,nr,ys,qs,Zs,ir,pr;const Zr=we-nt,Nr=Re-nt,jr=Ce-Ze,gr=qe-Ze;ys=Zr*gr,Bt=dp*Zr,$t=Bt-(Bt-Zr),js=Zr-$t,Bt=dp*gr,Es=Bt-(Bt-gr),zs=gr-Es,qs=js*zs-(ys-$t*Es-js*Es-$t*zs),Zs=jr*Nr,Bt=dp*jr,$t=Bt-(Bt-jr),js=jr-$t,Bt=dp*Nr,Es=Bt-(Bt-Nr),zs=Nr-Es,ir=js*zs-(Zs-$t*Es-js*Es-$t*zs),Hs=qs-ir,Vt=qs-Hs,LM[0]=qs-(Hs+Vt)+(Vt-ir),$s=ys+Hs,Vt=$s-ys,nr=ys-($s-Vt)+(Hs-Vt),Hs=nr-Zs,Vt=nr-Hs,LM[1]=nr-(Hs+Vt)+(Vt-Zs),pr=$s+Hs,Vt=pr-$s,LM[2]=$s-(pr-Vt)+(Hs-Vt),LM[3]=pr;let qr=function(xi,pa){let vi=pa[0];for(let Fa=1;Fa<4;Fa++)vi+=pa[Fa];return vi}(0,LM),tn=22204460492503146e-32*ut;if(qr>=tn||-qr>=tn||(Vt=we-Zr,xt=we-(Zr+Vt)+(Vt-nt),Vt=Re-Nr,Ht=Re-(Nr+Vt)+(Vt-nt),Vt=Ce-jr,bt=Ce-(jr+Vt)+(Vt-Ze),Vt=qe-gr,Rt=qe-(gr+Vt)+(Vt-Ze),xt===0&&bt===0&&Ht===0&&Rt===0)||(tn=11093356479670487e-47*ut+Qbt*Math.abs(qr),qr+=Zr*Rt+gr*xt-(jr*Ht+Nr*bt),qr>=tn||-qr>=tn))return qr;ys=xt*gr,Bt=dp*xt,$t=Bt-(Bt-xt),js=xt-$t,Bt=dp*gr,Es=Bt-(Bt-gr),zs=gr-Es,qs=js*zs-(ys-$t*Es-js*Es-$t*zs),Zs=bt*Nr,Bt=dp*bt,$t=Bt-(Bt-bt),js=bt-$t,Bt=dp*Nr,Es=Bt-(Bt-Nr),zs=Nr-Es,ir=js*zs-(Zs-$t*Es-js*Es-$t*zs),Hs=qs-ir,Vt=qs-Hs,Zp[0]=qs-(Hs+Vt)+(Vt-ir),$s=ys+Hs,Vt=$s-ys,nr=ys-($s-Vt)+(Hs-Vt),Hs=nr-Zs,Vt=nr-Hs,Zp[1]=nr-(Hs+Vt)+(Vt-Zs),pr=$s+Hs,Vt=pr-$s,Zp[2]=$s-(pr-Vt)+(Hs-Vt),Zp[3]=pr;const In=Oye(4,LM,4,Zp,IIe);ys=Zr*Rt,Bt=dp*Zr,$t=Bt-(Bt-Zr),js=Zr-$t,Bt=dp*Rt,Es=Bt-(Bt-Rt),zs=Rt-Es,qs=js*zs-(ys-$t*Es-js*Es-$t*zs),Zs=jr*Ht,Bt=dp*jr,$t=Bt-(Bt-jr),js=jr-$t,Bt=dp*Ht,Es=Bt-(Bt-Ht),zs=Ht-Es,ir=js*zs-(Zs-$t*Es-js*Es-$t*zs),Hs=qs-ir,Vt=qs-Hs,Zp[0]=qs-(Hs+Vt)+(Vt-ir),$s=ys+Hs,Vt=$s-ys,nr=ys-($s-Vt)+(Hs-Vt),Hs=nr-Zs,Vt=nr-Hs,Zp[1]=nr-(Hs+Vt)+(Vt-Zs),pr=$s+Hs,Vt=pr-$s,Zp[2]=$s-(pr-Vt)+(Hs-Vt),Zp[3]=pr;const cn=Oye(In,IIe,4,Zp,PIe);ys=xt*Rt,Bt=dp*xt,$t=Bt-(Bt-xt),js=xt-$t,Bt=dp*Rt,Es=Bt-(Bt-Rt),zs=Rt-Es,qs=js*zs-(ys-$t*Es-js*Es-$t*zs),Zs=bt*Ht,Bt=dp*bt,$t=Bt-(Bt-bt),js=bt-$t,Bt=dp*Ht,Es=Bt-(Bt-Ht),zs=Ht-Es,ir=js*zs-(Zs-$t*Es-js*Es-$t*zs),Hs=qs-ir,Vt=qs-Hs,Zp[0]=qs-(Hs+Vt)+(Vt-ir),$s=ys+Hs,Vt=$s-ys,nr=ys-($s-Vt)+(Hs-Vt),Hs=nr-Zs,Vt=nr-Hs,Zp[1]=nr-(Hs+Vt)+(Vt-Zs),pr=$s+Hs,Vt=pr-$s,Zp[2]=$s-(pr-Vt)+(Hs-Vt),Zp[3]=pr;const fa=Oye(cn,PIe,4,Zp,LIe);return LIe[fa-1]}(C,I,L,B,U,Y,xe)}(v[0],v[1],u[0],u[1],f[0],f[1]);return w>0?-1:w<0?1:0}function oN(v,u){const f=v.point,w=u.point;return f[0]>w[0]?1:f[0]w[1]?1:-1:function(C,I,L){return C.left!==I.left?C.left?1:-1:Fye(L,C.otherEvent.point,I.otherEvent.point)!==0?C.isBelow(I.otherEvent.point)?-1:1:!C.isSubject&&I.isSubject?1:-1}(v,u,f)}function lN(v,u,f){const w=new DM(u,!1,v,v.isSubject),C=new DM(u,!0,v.otherEvent,v.isSubject);return _b(v.point,v.otherEvent.point)&&console.warn("what is that, a collapsed segment?",v),w.contourId=C.contourId=v.contourId,oN(C,v.otherEvent)>0&&(v.otherEvent.left=!0,C.left=!1),v.otherEvent.otherEvent=C,v.otherEvent=w,f.push(C),f.push(w),f}function o$(v,u){return v[0]*u[1]-v[1]*u[0]}function Bye(v,u){return v[0]*u[0]+v[1]*u[1]}function zye(v,u,f){const w=function(U,Y,se,oe){const de=[Y[0]-U[0],Y[1]-U[1]],xe=[oe[0]-se[0],oe[1]-se[1]];function we(Ht,Rt,Vt){return[Ht[0]+Rt*Vt[0],Ht[1]+Rt*Vt[1]]}const Ce=[se[0]-U[0],se[1]-U[1]];let Re=o$(de,xe),qe=Re*Re;const nt=Bye(de,de);if(qe>0){const Ht=o$(Ce,xe)/Re;if(Ht<0||Ht>1)return null;const Rt=o$(Ce,de)/Re;return Rt<0||Rt>1?null:Ht===0||Ht===1?[we(U,Ht,de)]:Rt===0||Rt===1?[we(se,Rt,xe)]:[we(U,Ht,de)]}if(Re=o$(Ce,de),qe=Re*Re,qe>0)return null;const Ze=Bye(de,Ce)/nt,ut=Ze+Bye(de,xe)/nt,xt=Math.min(Ze,ut),bt=Math.max(Ze,ut);return xt<=1&&bt>=0?xt===1?[we(U,xt>0?xt:0,de)]:bt===0?[we(U,bt<1?bt:1,de)]:[we(U,xt>0?xt:0,de),we(U,bt<1?bt:1,de)]:null}(v.point,v.otherEvent.point,u.point,u.otherEvent.point),C=w?w.length:0;if(C===0||C===1&&(_b(v.point,u.point)||_b(v.otherEvent.point,u.otherEvent.point))||C===2&&v.isSubject===u.isSubject)return 0;if(C===1)return!_b(v.point,w[0])&&!_b(v.otherEvent.point,w[0])&&lN(v,w[0],f),!_b(u.point,w[0])&&!_b(u.otherEvent.point,w[0])&&lN(u,w[0],f),1;const I=[];let L=!1,B=!1;return _b(v.point,u.point)?L=!0:oN(v,u)===1?I.push(u,v):I.push(v,u),_b(v.otherEvent.point,u.otherEvent.point)?B=!0:oN(v.otherEvent,u.otherEvent)===1?I.push(u.otherEvent,v.otherEvent):I.push(v.otherEvent,u.otherEvent),L&&B||L?(u.type=1,v.type=u.inOut===v.inOut?2:3,L&&!B&&lN(I[1].otherEvent,I[0].point,f),2):B?(lN(I[0],I[1].point,f),3):I[0]!==I[3].otherEvent?(lN(I[0],I[1].point,f),lN(I[1],I[2].point,f),3):(lN(I[0],I[1].point,f),lN(I[3].otherEvent,I[2].point,f),3)}function Jbt(v,u){if(v===u)return 0;if(Fye(v.point,v.otherEvent.point,u.point)!==0||Fye(v.point,v.otherEvent.point,u.otherEvent.point)!==0)return _b(v.point,u.point)?v.isBelow(u.otherEvent.point)?-1:1:v.point[0]===u.point[0]?v.point[1](u.contourId??0)?1:-1}return oN(v,u)===1?1:-1}class e_t{constructor(){this.points=[],this.holeIds=[],this.holeOf=null,this.depth=null}isExterior(){return this.holeOf==null}}function t_t(v,u,f,w){let C,I=v+1,L=u[v].point;const B=u.length;for(Iw;)I--;return I}function s_t(v,u,f){const w=new e_t;if(v.prevInResult!=null){const C=v.prevInResult,I=C.outputContourId;if(C.resultTransition>0){const L=u[I];if(L.holeOf!=null){const B=L.holeOf;u[B].holeIds.push(f),w.holeOf=B,w.depth=u[I].depth}else u[I].holeIds.push(f),w.holeOf=I,w.depth=u[I].depth+1}else w.holeOf=null,w.depth=u[I].depth}else w.holeOf=null,w.depth=0;return w}const RIe=Math.max,OIe=Math.min;let l$=0;function FIe(v,u,f,w,C,I){let L,B,U,Y,se,oe;for(L=0,B=v.length-1;L0?oe.left=!0:se.left=!0;const de=U[0],xe=U[1];C[0]=OIe(C[0],de),C[1]=OIe(C[1],xe),C[2]=RIe(C[2],de),C[3]=RIe(C[3],xe),w.push(se),w.push(oe)}}const c$=[];function BIe(v,u,f){let w=v,C=u;typeof v[0][0][0]=="number"&&(w=[v]),typeof u[0][0][0]=="number"&&(C=[u]);let I=function(de,xe,we){let Ce=null;return de.length*xe.length===0&&(we===0?Ce=c$:we===2?Ce=de:(we===1||we===3)&&(Ce=de.length===0?xe:de)),Ce}(w,C,f);if(I)return I===c$?null:I;const L=[1/0,1/0,-1/0,-1/0],B=[1/0,1/0,-1/0,-1/0],U=function(de,xe,we,Ce,Re){const qe=new wx(void 0,oN);let nt,Ze,ut,xt,bt,Ht;for(ut=0,xt=de.length;utCe[2]||Ce[0]>we[2]||we[1]>Ce[3]||Ce[1]>we[3])&&(Re===0?qe=c$:Re===2?qe=de:(Re===1||Re===3)&&(qe=de.concat(xe))),qe}(w,C,L,B,f),I)return I===c$?null:I;const Y=function(de,xe,we,Ce,Re,qe){const nt=new Lye(Jbt),Ze=[],ut=Math.min(Ce[2],Re[2]);let xt,bt,Ht;for(;de.length!==0;){let Rt=de.pop();if(Ze.push(Rt),qe===0&&Rt.point[0]>ut||qe===2&&Rt.point[0]>Ce[2])break;if(Rt.left){bt=xt=nt.insert(Rt),Ht=nt.minNode(),xt=xt!==Ht?nt.prev(xt):null,bt=nt.next(bt);const Vt=xt?xt.key:null;let Bt;if(LD(Rt,Vt,qe),bt&&zye(Rt,bt.key,de)===2&&(LD(Rt,Vt,qe),LD(bt.key,Rt,qe)),xt&&zye(xt.key,Rt,de)===2){let $t=xt;$t=$t!==Ht?nt.prev($t):null,Bt=$t?$t.key:null,LD(Vt,Bt,qe),LD(Rt,Vt,qe)}}else Rt=Rt.otherEvent,bt=xt=nt.find(Rt),xt&&bt&&(xt=xt!==Ht?nt.prev(xt):null,bt=nt.next(bt),nt.remove(Rt),bt&&xt&&zye(xt.key,bt.key,de))}return Ze}(U,0,0,L,B,f),se=function(de){let xe,we;const Ce=function(nt){let Ze,ut,xt,bt,Ht;const Rt=[];for(ut=0,xt=nt.length;ut{Re[Ht]=!0,Ht=Ce.length)&&Ce[xt];);qe.push(Ze)}return qe}(Y),oe=[];for(let de=0;de{L.push(new ds(oe,U+(oe-B)/(Y-B)*(se-U)))}:(L,B,U,Y,se,oe)=>{L.push(new ds(B+(oe-U)/(se-U)*(Y-B),oe))};for(const L of v){const B=[];for(const U of L){if(U.length<=2)continue;const Y=[];for(let de=0;deu&&I(Y,xe,we,Ce,Re,u):qe>f?nt=u&&I(Y,xe,we,Ce,Re,u),nt>f&&qe<=f&&I(Y,xe,we,Ce,Re,f)}let se=U[U.length-1];const oe=w===0?se.x:se.y;oe>=u&&oe<=f&&Y.push(se),Y.length&&(se=Y[Y.length-1],Y[0].x===se.x&&Y[0].y===se.y||Y.push(Y[0]),B.push(Y))}B.length&&C.push(B)}return C}function r_t(v,u){const f=BIe($ye(v),$ye([u]),0);return f==null?[]:zIe(f)}function n_t(v,u,f=0){let C=$ye(v,65536);const I=[];for(;u.valid();u.next()){const[L,B]=u.get();let U=L.x*65536,Y=L.y*65536,se=B.x*65536,oe=B.y*65536;const de=se-U,xe=oe-Y,we=Math.hypot(de,xe);if(we===0)continue;U-=de*f,Y-=xe*f,se+=de*f,oe+=xe*f;const Ce=Math.trunc(xe/we*3),Re=-Math.trunc(de/we*3);I.push([[[U,Y],[se,oe],[se+Ce,oe+Re],[U+Ce,Y+Re],[U,Y]]])}return I.length>0&&(C=BIe(C,I,2)),zIe(C,1/65536,128)}function $ye(v,u=1){return[v.map(f=>f.map(w=>[w.x*u,w.y*u]))]}function zIe(v,u=1,f){return v.map(w=>w.map((C,I)=>{const L=C.map(B=>{let U=B[0],Y=B[1];return f&&(U=Math.round(U/f)*f,Y=Math.round(Y/f)*f),new ds(U*u,Y*u)._round()});return I>0&&L.reverse(),L}))}class Uye{constructor(u,f){this.layoutVertexArray=new Da,this.indexArray=new Yl,this.lineIndexArray=new Bg,this.triangleSegments=new No,this.lineSegments=new No,this.programConfigurations=new Fe(u.layers,{zoom:u.zoom,lut:u.lut}),this.uploaded=!1,f&&(this.elevatedLayoutVertexArray=new Zi)}update(u,f,w,C,I,L,B,U){this.programConfigurations.updatePaintArrays(u,f,I,w,C,L,B,U)}isEmpty(){return this.layoutVertexArray.length===0}needsUpload(){return this.programConfigurations.needsUpload}upload(u){this.uploaded||(this.layoutVertexBuffer=u.createVertexBuffer(this.layoutVertexArray,Rbt.members),this.indexBuffer=u.createIndexBuffer(this.indexArray),this.lineIndexBuffer=u.createIndexBuffer(this.lineIndexArray),this.elevatedLayoutVertexArray&&this.elevatedLayoutVertexArray.length>0&&(this.elevatedLayoutVertexBuffer=u.createVertexBuffer(this.elevatedLayoutVertexArray,Obt.members))),this.programConfigurations.upload(u),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(u,f,w,C,I,L,B){this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,u,f,w,C,I,L,void 0,B)}}class u${constructor(u){this.zoom=u.zoom,this.pixelRatio=u.pixelRatio,this.overscaling=u.overscaling,this.layers=u.layers,this.layerIds=this.layers.map(f=>f.fqid),this.index=u.index,this.hasPattern=!1,this.patternFeatures=[],this.lut=u.lut,this.bufferData=new Uye(u,!1),this.elevationBufferData=new Uye(u,!0),this.stateDependentLayerIds=this.layers.filter(f=>f.isStateDependent()).map(f=>f.id),this.projection=u.projection,this.elevationMode=this.layers[0].layout.get("fill-elevation-reference"),this.sourceLayerIndex=u.sourceLayerIndex,this.worldview=u.worldview,this.hasAppearances=null}updateFootprints(u,f){}updateAppearances(u,f,w,C){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(u,f,w,C){this.hasPattern=Iye("fill",this.layers,this.pixelRatio,f);const I=this.layers[0].layout.get("fill-sort-key"),L=[];for(const{feature:B,id:U,index:Y,sourceLayerIndex:se}of u){const oe=this.layers[0]._featureFilter.needGeometry,de=Oa(B,oe);if(!this.layers[0]._featureFilter.filter(new wa(this.zoom,{worldview:this.worldview,activeFloors:f.activeFloors}),de,w))continue;const xe=I?I.evaluate(de,{},w,f.availableImages):void 0,we={id:U,properties:B.properties,type:B.type,sourceLayerIndex:se,index:Y,geometry:oe?de.geometry:Ln(B,w,C),patterns:{},sortKey:xe};L.push(we)}I&&L.sort((B,U)=>B.sortKey-U.sortKey);for(const B of L){const{geometry:U,index:Y,sourceLayerIndex:se}=B;if(this.hasPattern){const oe=Pye("fill",this.layers,B,this.zoom,this.pixelRatio,f);this.patternFeatures.push(oe)}else this.addFeature(B,U,Y,w,{},f.availableImages,f.brightness,f.elevationFeatures);f.featureIndex.insert(u[Y].feature,U,Y,se,this.index)}}update(u,f,w,C,I,L,B){this.bufferData.update(u,f,w,C,I,L,B,this.worldview),this.elevationBufferData.update(u,f,w,C,I,L,B,this.worldview),this.elevatedStructures&&this.elevatedStructures.update(u,f,w,C,I,L,B,this.worldview)}addFeatures(u,f,w,C,I,L){for(const B of this.patternFeatures)this.addFeature(B,B.geometry,B.index,f,w,C,L,u.elevationFeatures)}isEmpty(){return this.bufferData.isEmpty()&&this.elevationBufferData.isEmpty()}uploadPending(){return!this.uploaded||this.bufferData.needsUpload()||this.elevationBufferData.needsUpload()}upload(u){this.bufferData.upload(u),this.elevationBufferData.upload(u),this.elevatedStructures&&this.elevatedStructures.upload(u)}destroy(){this.bufferData.destroy(),this.elevationBufferData.destroy(),this.elevatedStructures&&this.elevatedStructures.destroy()}addFeature(u,f,w,C,I,L=[],B,U){const Y=ID(f,500);this.elevationMode!=="none"?this.addElevatedRoadFeature(u,Y,C,w,U):this.addGeometry(Y,this.bufferData),this.bufferData.populatePaintArrays(u,w,I,L,C,B,this.worldview),this.elevationBufferData.populatePaintArrays(u,w,I,L,C,B,this.worldview)}getUnevaluatedPortalGraph(){return this.elevatedStructures?this.elevatedStructures.unevaluatedPortals:void 0}setEvaluatedPortalGraph(u,f,w,C,I){this.elevatedStructures&&(this.elevatedStructures.construct(u),this.elevatedStructures.populatePaintArrays(f,w,C,I,this.worldview))}addElevatedRoadFeature(u,f,w,C,I){const L=new Array,B=Eo.getElevationFeature(u,I);if(!B)return void this.addGeometry(f,this.bufferData);{const Y=this.clipPolygonsToTile(f,1);Y.length>0&&L.push({polygons:Y,elevationFeature:B,elevationTileID:w})}const U={guardRailEnabled:this.layers[0].layout.get("fill-construct-bridge-guard-rail").evaluate(u,{},w),featureIndex:C};for(const Y of L)if(Y.elevationFeature){if(this.elevationMode==="hd-road-base"){this.elevatedStructures||(this.elevatedStructures=new Yp(Y.elevationTileID,this.layers,this.zoom,this.lut));const oe=Y.elevationFeature.isTunnel();let de=0;u.properties.hasOwnProperty(So)&&(de=+u.properties[So]),this.elevatedStructures.addPortalCandidates(Y.elevationFeature.id,Y.polygons,oe,Y.elevationFeature,de)}Y.elevationFeature.constantHeight==null&&(Y.polygons=this.prepareElevatedPolygons(Y.polygons,Y.elevationFeature,Y.elevationTileID));const se=new Do(w,Y.elevationTileID);this.addElevatedGeometry(Y.polygons,se,Y.elevationFeature,this.elevationMode==="hd-road-base"?0:.05,C,U)}}addElevatedGeometry(u,f,w,C,I,L){const B={elevation:w,elevationSampler:f,bias:C,index:I,featureInfo:L},[U,Y]=this.addGeometry(u,this.elevationBufferData,B);this.elevationBufferData.heightRange==null?this.elevationBufferData.heightRange={min:U,max:Y}:(this.elevationBufferData.heightRange.min=Math.min(this.elevationBufferData.heightRange.min,U),this.elevationBufferData.heightRange.max=Math.max(this.elevationBufferData.heightRange.max,Y))}addGeometry(u,f,w){let C=Number.POSITIVE_INFINITY,I=Number.NEGATIVE_INFINITY,L=null;w&&(L=w.elevationSampler.constantElevation(w.elevation,w.bias),L!=null&&(C=L,I=L));const B=(U,Y,se)=>{if(w!=null)if(Y.push(U),L!=null)f.elevatedLayoutVertexArray.emplaceBack(L),se.push(L);else{const oe=w.elevationSampler.pointElevation(U,w.elevation,w.bias);f.elevatedLayoutVertexArray.emplaceBack(oe),se.push(oe),C=Math.min(C,oe),I=Math.max(I,oe)}};for(const U of u){let Y=0;for(const Ze of U)Y+=Ze.length;const se=f.triangleSegments.prepareSegment(Y,f.layoutVertexArray,f.indexArray),oe=se.vertexLength,de=[],xe=[],we=[],Ce=[],Re=[],qe=f.layoutVertexArray.length;for(const Ze of U){if(Ze.length===0)continue;Ze!==U[0]&&xe.push(de.length/2);const ut=f.lineSegments.prepareSegment(Ze.length,f.layoutVertexArray,f.lineIndexArray),xt=ut.vertexLength;w&&Re.push(f.layoutVertexArray.length-qe),B(Ze[0],we,Ce),f.layoutVertexArray.emplaceBack(Ze[0].x,Ze[0].y),f.lineIndexArray.emplaceBack(xt+Ze.length-1,xt),de.push(Ze[0].x),de.push(Ze[0].y);for(let bt=1;bt0&&w&&this.elevationMode==="hd-road-base"){const Ze=w.elevation.isTunnel(),ut=w.elevation.safeArea,xt=this.elevatedStructures.addVertices(we,Ce);this.elevatedStructures.addTriangles(nt,xt,Ze);const bt=Re.length;if(bt>0){for(let Ht=0;Ht=w&&xe.max.x<=I&&xe.min.y>=C&&xe.max.y<=L?U:Y).push(de)}if(U.length===u.length)return u;const se=[new ds(w,C),new ds(I,C),new ds(I,L),new ds(w,L),new ds(w,C)],oe=U;for(const de of Y)oe.push(...r_t(de,se));return oe}}let $Ie,UIe,qIe,VIe;Pr(u$,"FillBucket",{omit:["layers","patternFeatures"]}),Pr(Uye,"FillBufferData"),Pr(Yp,"ElevatedStructures");class h${constructor(u,f,w,C){if(this.triangleCount=f.length/3,this.min=new ds(0,0),this.max=new ds(0,0),this.xScale=0,this.yScale=0,this.cellsX=0,this.cellsY=0,this.cells=[],this.payload=[],this.triangleCount===0||u.length===0)return;const[I,L]=[u[0].clone(),u[0].clone()];for(let oe=1;oeoe.cellIdx-de.cellIdx||oe.triIdx-de.triIdx);let se=0;for(;sethis.max.x||this.min.x>u.x||u.y>this.max.y||this.min.y>u.y)return;const w=wb(u.x-this.min.x,this.xScale,this.cellsX),C=wb(u.y-this.min.y,this.yScale,this.cellsY),I=this.cells[C*this.cellsX+w];if(I){this._lazyInitLookup();for(let L=0;Lthis.max.x||this.min.x>f.x||u.y>this.max.y||this.min.y>f.y)return;this._lazyInitLookup();const C=wb(u.x-this.min.x,this.xScale,this.cellsX),I=wb(f.x-this.min.x,this.xScale,this.cellsX),L=wb(u.y-this.min.y,this.yScale,this.cellsY),B=wb(f.y-this.min.y,this.yScale,this.cellsY);for(let U=L;U<=B;U++)for(let Y=C;Y<=I;Y++){const se=this.cells[U*this.cellsX+Y];if(se)for(let oe=0;oef.fqid),this.index=u.index,this.hasPattern=!1,this.stateDependentLayerIds=this.layers.filter(f=>f.isStateDependent()).map(f=>f.id),this.footprints=[],this.worldview=u.worldview,this.hasAppearances=null}updateFootprints(u,f){for(const w of this.footprints)f.push({footprint:w,id:u})}updateAppearances(u,f,w,C){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(u,f,w,C){const I=[];for(const{feature:L,id:B,index:U,sourceLayerIndex:Y}of u){const se=this.layers[0]._featureFilter.needGeometry,oe=Oa(L,se);if(!this.layers[0]._featureFilter.filter(new wa(this.zoom,{worldview:this.worldview,activeFloors:f.activeFloors}),oe,w))continue;const de={id:B,properties:L.properties,type:L.type,sourceLayerIndex:Y,index:U,geometry:se?oe.geometry:Ln(L,w,C),patterns:{}};I.push(de)}for(const L of I){const{geometry:B,index:U,sourceLayerIndex:Y}=L;this.addFeature(L,B,U,w,{},f.availableImages,f.brightness),f.featureIndex.insert(u[U].feature,B,U,Y,this.index)}}isEmpty(){return this.footprints.length===0}uploadPending(){return!1}upload(u){}update(u,f,w,C,I,L,B){}destroy(){}addFeature(u,f,w,C,I,L=[],B){for(const U of ID(f,2)){const Y=[],se=[],oe=[],de=new ds(1/0,1/0),xe=new ds(-1/0,-1/0);for(const Re of U)if(Re.length!==0){Re!==U[0]&&oe.push(se.length/2);for(let qe=0;qeu.max.x||v.max.xu.max.y||v.max.ynew ds((U.x+I.x*Sr)*B-L.x*Sr,(U.y+I.y*Sr)*B-L.y*Sr))}return Vye(f,C,v.indices,0,v.indices.length,0,0)}function ZIe(v,u,f,w){const C=Math.pow(2,w.z-f.z);return new ds((v+f.x*Sr)*C-w.x*Sr,(u+f.y*Sr)*C-w.y*Sr)}function XIe(v,u){const f=[];u.grid.queryPoint(v,f);const w=u.indices,C=u.vertices;for(let I=0;I0&&(w.length>1&&f.push(w),w=[])}return w.length>1&&f.push(w),f}const Gye=na.types,p_t=["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"],g_t=["fill-extrusion-flood-light-ground-radius"],x_t=Math.pow(2,13),y_t=Math.pow(2,15)-1,g$=new ds(0,1),Ww=2147483648,x$=1073741824;function RD(v,u,f,w,C,I,L,B){v.emplaceBack((u<<1)+L,(f<<1)+I,(Math.floor(w*x_t)<<1)+C,Math.round(B))}function OD(v,u,f){v.emplaceBack(u.x*Sr,u.y*Sr,f?1:0)}function y$(v,u,f,w,C,I){v.emplaceBack(u.x,u.y,(f.x<<1)+w,(f.y<<1)+C,I)}function FD(v,u,f){v.emplaceBack(u.x,u.y,u.z,f[0]*16384,f[1]*16384,f[2]*16384)}class JIe{constructor(){this.vertexOffset=0,this.vertexCount=0,this.indexOffset=0,this.indexCount=0}}class Wye{constructor(){this.centroidXY=new ds(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 ds(Number.MAX_VALUE,Number.MAX_VALUE),this.max=new ds(-Number.MAX_VALUE,-Number.MAX_VALUE),this.height=0,this.buildingId=0,this.groupCentroidPos=new ds(0,0)}span(){return new ds(this.max.x-this.min.x,this.max.y-this.min.y)}}class Kye{constructor(){this.acc=new ds(0,0),this.accCount=0,this.centroidDataIndex=0}startRing(u,f){u.min.x===Number.MAX_VALUE&&(u.min.x=u.max.x=f.x,u.min.y=u.max.y=f.y)}appendEdge(u,f,w){this.accCount++,this.acc._add(f);let C=!!this.borders;f.xu.max.x&&(u.max.x=f.x,C=!0),f.yu.max.y&&(u.max.y=f.y,C=!0),((f.x===0||f.x===Sr)&&f.x===w.x)!=((f.y===0||f.y===Sr)&&f.y===w.y)&&this.processBorderOverlap(f,w),C&&this.checkBorderIntersection(f,w)}checkBorderIntersection(u,f){f.x<0!=u.x<0&&this.addBorderIntersection(0,jn(f.y,u.y,(0-f.x)/(u.x-f.x))),f.x>Sr!=u.x>Sr&&this.addBorderIntersection(1,jn(f.y,u.y,(Sr-f.x)/(u.x-f.x))),f.y<0!=u.y<0&&this.addBorderIntersection(2,jn(f.x,u.x,(0-f.y)/(u.y-f.y))),f.y>Sr!=u.y>Sr&&this.addBorderIntersection(3,jn(f.x,u.x,(Sr-f.y)/(u.y-f.y)))}addBorderIntersection(u,f){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 w=this.borders[u];fw[1]&&(w[1]=f)}processBorderOverlap(u,f){if(u.x===f.x){if(u.y===f.y)return;const w=u.x===0?0:1;this.addBorderIntersection(w,f.y),this.addBorderIntersection(w,u.y)}else{const w=u.y===0?2:3;this.addBorderIntersection(w,f.x),this.addBorderIntersection(w,u.x)}}centroid(){return this.accCount===0?new ds(0,0):new ds(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((u,f)=>u+ +(f[0]!==Number.MAX_VALUE),0):0}}function ePe(v,u){const f=v.add(u)._unit(),w=He(v.x*f.x+v.y*f.y,-1,1);var C,I,L;return L=Math.acos(w),Math.min(4,Math.max(-4,Math.tan(L)))/4*y_t*((C=v).x*(I=u).y-C.y*I.x<0?-1:1)}const v_t=[v=>v.x<0,v=>v.x>Sr,v=>v.y<0,v=>v.y>Sr];function b_t(v,u,f,w){const C=[4];if(w===0)return C;f._mult(w);const I=v.sub(f),L=u.sub(f),B=[v,u,I,L];for(let U=0;U<4;U++)for(const Y of B)if(v_t[U](Y)){C.push(U);break}return C}class Yye{constructor(u){this.groundRadiusArray=null,this.groundRadiusBuffer=null,this.vertexArray=new T4,this.indexArray=new Yl,this.programConfigurations=new Fe(u.layers,{zoom:u.zoom,lut:u.lut},f=>g_t.includes(f)),this._segments=new No,this.hiddenByLandmarkVertexArray=new CM,this._segmentToGroundQuads={},this._segmentToGroundQuads[0]=[],this._segmentToRegionTriCounts={},this._segmentToRegionTriCounts[0]=[0,0,0,0,0],this.regionSegments={},this.regionSegments[4]=new No}getDefaultSegment(){return this.regionSegments[4]}hasData(){return this.vertexArray.length!==0}addData(u,f,w,C=!1){const I=u.length;if(I>2){let L=Math.max(0,this._segments.get().length-1);const B=this._segments._prepareSegment(4*I,this.vertexArray.length,2*this._segmentToGroundQuads[L].length);let U;L!==this._segments.get().length-1&&(L++,this._segmentToGroundQuads[L]=[],this._segmentToRegionTriCounts[L]=[0,0,0,0,0]);{const Y=u[0],se=u[1];U=ePe(Y.sub(u[I-1])._perp()._unit(),se.sub(Y)._perp()._unit())}for(let Y=0;YC.region-I.region);for(let w=0;wU+Y,0);let B=0;for(let U=0;U<=4;U++){const Y=L[U];if(Y!==0){let se=this.regionSegments[U];se||(se=this.regionSegments[U]=new No);const oe={vertexOffset:I.vertexOffset,primitiveOffset:I.primitiveOffset+B,vertexLength:I.vertexLength,primitiveLength:Y};se.get().push(oe)}B+=Y}for(let U=0;U0?this.hiddenByLandmarkVertexBuffer=u.createVertexBuffer(this.hiddenByLandmarkVertexArray,d_t.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 u=0;u<=4;u++){const f=this.regionSegments[u];f&&f.destroy()}}}}class v${constructor(u){this.zoom=u.zoom,this.canonical=u.canonical,this.overscaling=u.overscaling,this.layers=u.layers,this.pixelRatio=u.pixelRatio,this.layerIds=this.layers.map(f=>f.fqid),this.index=u.index,this.hasPattern=!1,this.edgeRadius=0,this.projection=u.projection,this.activeReplacements=[],this.replacementUpdateTime=0,this.centroidData=[],this.footprintIndices=new Yl,this.footprintVertices=new Da,this.footprintSegments=[],this.layoutVertexArray=new Og,this.centroidVertexArray=new Qz,this.wallVertexArray=new wD,this.indexArray=new Yl,this.programConfigurations=new Fe(u.layers,{zoom:u.zoom,lut:u.lut},f=>p_t.includes(f)),this.segments=new No,this.stateDependentLayerIds=this.layers.filter(f=>f.isStateDependent()).map(f=>f.id),this.groundEffect=new Yye(u),this.maxHeight=0,this.partLookup={},this.triangleSubSegments=[],this.polygonSegments=[],this.buildingGroups=new Map,this.worldview=u.worldview,this.hasAppearances=null}updateFootprints(u,f){}updateAppearances(u,f,w,C){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(u,f,w,C){this.features=[],this.hasPattern=Iye("fill-extrusion",this.layers,this.pixelRatio,f),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=Js(w),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:I,id:L,index:B,sourceLayerIndex:U}of u){const Y=this.layers[0]._featureFilter.needGeometry,se=Oa(I,Y);if(!this.layers[0]._featureFilter.filter(new wa(this.zoom,{worldview:this.worldview,activeFloors:f.activeFloors}),se,w))continue;const oe={id:L,sourceLayerIndex:U,index:B,geometry:Y?se.geometry:Ln(I,w,C),properties:I.properties,type:I.type,patterns:{}},de=this.layoutVertexArray.length,xe=Gye[oe.type]==="Polygon";if(this.hasPattern)this.features.push({featureId:I.id,feature:Pye("fill-extrusion",this.layers,oe,this.zoom,this.pixelRatio,f)});else if(this.wallMode)for(const we of oe.geometry)for(const Ce of QIe(we,xe))this.addFeature(I.id,oe,[Ce],B,w,{},f.availableImages,C,f.brightness);else this.addFeature(I.id,oe,oe.geometry,B,w,{},f.availableImages,C,f.brightness);f.featureIndex.insert(I,oe.geometry,B,U,this.index,de)}this._finalizeBuildingGroups(),this.sortBorders(),this.projection.name==="mercator"&&this.splitToSubtiles(),this.groundEffect.prepareBorderSegments(),this.polygonSegments.length=0}addFeatures(u,f,w,C,I,L){for(const{featureId:B,feature:U}of this.features){const Y=Gye[U.type]==="Polygon",{geometry:se}=U;if(this.wallMode)for(const oe of se)for(const de of QIe(oe,Y))this.addFeature(B,U,[de],U.index,f,w,C,I,L);else this.addFeature(B,U,se,U.index,f,w,C,I,L)}this._finalizeBuildingGroups(),this.sortBorders(),this.projection.name==="mercator"&&this.splitToSubtiles()}update(u,f,w,C,I,L,B){this.programConfigurations.updatePaintArrays(u,f,I,w,C,L,B,this.worldview),this.groundEffect.update(u,f,I,w,C,L,B,this.worldview)}isEmpty(){return this.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload||this.groundEffect.programConfigurations.needsUpload}upload(u){this.uploaded||(this.layoutVertexBuffer=u.createVertexBuffer(this.layoutVertexArray,h_t),this.indexBuffer=u.createIndexBuffer(this.indexArray),this.wallVertexBuffer=u.createVertexBuffer(this.wallVertexArray,c_t.members),this.layoutVertexExtArray&&(this.layoutVertexExtBuffer=u.createVertexBuffer(this.layoutVertexExtArray,u_t.members,!0)),this.groundEffect.upload(u)),this.groundEffect.uploadPaintProperties(u),this.programConfigurations.upload(u),this.uploaded=!0}uploadCentroid(u){this.groundEffect.uploadHiddenByLandmark(u),this.needsCentroidUpdate&&(!this.centroidVertexBuffer&&this.centroidVertexArray.length>0?this.centroidVertexBuffer=u.createVertexBuffer(this.centroidVertexArray,l_t.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(u,f,w,C,I,L,B,U,Y){const se=this.layers[0].paint.get("fill-extrusion-flood-light-ground-radius").evaluate(f,{})/this.tileToMeter,oe=[new ds(0,0),new ds(Sr,Sr)],de=U.projection,xe=de.name==="globe",we=this.wallMode||Gye[f.type]==="Polygon",Ce=new Kye;Ce.centroidDataIndex=this.centroidData.length;const Re=new Wye;Re.buildingId=u,f.properties&&f.properties.hasOwnProperty("building_id")&&(Re.buildingId=Number(f.properties.building_id)),Ce.buildingId=Re.buildingId;const qe=this.layers[0].paint.get("fill-extrusion-base").evaluate(f,{},I)<=0,nt=this.layers[0].paint.get("fill-extrusion-height").evaluate(f,{},I);let Ze;if(Re.height=nt,Re.vertexArrayOffset=this.layoutVertexArray.length,Re.groundVertexArrayOffset=this.groundEffect.vertexArray.length,xe&&!this.layoutVertexExtArray&&(this.layoutVertexExtArray=new _M),this.wallMode){if(xe)return void Gr("Non zero fill-extrusion-line-width is not yet supported on globe.");if(w.length!==1)return;Ze=function(Bt){const $t=Bt[0].x===Bt[Bt.length-1].x&&Bt[0].y===Bt[Bt.length-1].y;(function(jr){let gr=0;const qr=jr.length;for(let tn=0;tn=0})(Bt)||(Bt=Bt.reverse());const Es={geometry:[],joinNormals:[],indices:[]},zs=[],Hs=[],$s=[];let nr=Bt.length;for(;nr>=2&&Bt[nr-1].equals(Bt[nr-2]);)nr--;if(nr<($t?3:2))return Es;let ys,qs,Zs,ir,pr,Zr=0;for(;Zr0;let cn="miter";const fa=2;cn==="miter"&&tn>fa&&(cn="bevel"),cn==="bevel"&&(tn>100&&(cn="flipbevel"),tn{const $i=new ds(pa.x,pa.y),ki=new ds(pa.x,pa.y);$i.x+=vi.x*Il,$i.y+=vi.y*Il,ki.x-=vi.x*Math.max(Fa,1),ki.y-=vi.y*Math.max(Fa,1),$s.push(vi),zs.push($i),Hs.push(ki)};if(cn==="miter")gr._mult(tn),xi(ys,gr,0,0);else if(cn==="flipbevel")gr=pr.mult(-1),xi(ys,gr,0,0),xi(ys,gr.mult(-1),0,0);else{const pa=-Math.sqrt(tn*tn-1),vi=In?pa:0,Fa=In?0:pa;qs&&xi(ys,ir,vi,Fa),Zs&&xi(ys,pr,vi,Fa)}}Es.geometry=[...zs,...Hs.reverse(),zs[0]],Es.joinNormals=[...$s,...$s.reverse(),$s[$s.length-1]];const Nr=Es.geometry.length-1;for(let jr=0;jrBt<($t.length-1)/2||Bt===$t.length-1,xt=this.wallMode?[w]:ID(w,500);for(let Bt=xt.length-1;Bt>=0;Bt--){const $t=xt[Bt];($t.length===0||w_t($t[0]))&&xt.splice(Bt,1)}let bt;if(xe)bt=oPe(xt,oe,I);else{bt=[];for(const Bt of xt)bt.push({polygon:Bt,bounds:oe})}const Ht=we?this.edgeRadius:0,Rt=Ht>0&&this.zoom<17,Vt=(Bt,$t)=>{if(Bt.length===0)return!1;const js=Bt[Bt.length-1];return $t.x===js.x&&$t.y===js.y};for(const{polygon:Bt,bounds:$t}of bt){let js=0,Es=0;for(const nr of Bt)we&&!nr[0].equals(nr[nr.length-1])&&nr.push(nr[0]),Es+=we?nr.length-1:nr.length;const zs=this.segments.prepareSegment((we?5:4)*Es,this.layoutVertexArray,this.indexArray);Re.footprintSegIdx<0&&(Re.footprintSegIdx=this.footprintSegments.length),Re.polygonSegIdx<0&&(Re.polygonSegIdx=this.polygonSegments.length);const Hs={triangleArrayOffset:this.indexArray.length,triangleCount:0,triangleSegIdx:this.segments.segments.length-1},$s=new JIe;if($s.vertexOffset=this.footprintVertices.length,$s.indexOffset=3*this.footprintIndices.length,$s.ringIndices=[],we){const nr=[],ys=[];js=zs.vertexLength;for(let Zs=0;Zs4&&nPe(ys[ys.length-2],ys[0],ys[1]),Zs=Ht?__t(ys[ys.length-2],ys[0],ys[1],Ht):0;const ir=[];let pr,Zr,Nr;Zr=ys[1].sub(ys[0])._perp()._unit();let jr=!0;for(let gr=1,qr=0;gr0?1:0,vi=tn.dist(In);if(qr+vi>32768&&(qr=0),Ht){Nr=cn.sub(In)._perp()._unit();let ki=sPe(tn,In,cn,tPe(Zr,Nr),Ht);isNaN(ki)&&(ki=0);const Co=In.sub(tn)._unit();tn=tn.add(Co.mult(Zs))._round(),In=In.add(Co.mult(-ki))._round(),Zs=ki,Zr=Nr,qe&&this.zoom>=17&&(Vt(ir,tn)||ir.push(tn),Vt(ir,In)||ir.push(In))}const Fa=zs.vertexLength,Il=ys.length>4&&nPe(tn,In,cn);let $i=aPe(qr,qs,jr);if(RD(this.layoutVertexArray,tn.x,tn.y,xi,pa,0,0,$i),RD(this.layoutVertexArray,tn.x,tn.y,xi,pa,0,1,$i),this.wallMode){const ki=ut(gr-1,ys),Co=Ze.joinNormals[gr-1];OD(this.wallVertexArray,Co,ki),OD(this.wallVertexArray,Co,ki)}if(qr+=vi,$i=aPe(qr,Il,!jr),qs=Il,RD(this.layoutVertexArray,In.x,In.y,xi,pa,0,0,$i),RD(this.layoutVertexArray,In.x,In.y,xi,pa,0,1,$i),this.wallMode){const ki=ut(gr,ys),Co=Ze.joinNormals[gr];OD(this.wallVertexArray,Co,ki),OD(this.wallVertexArray,Co,ki)}if(zs.vertexLength+=4,this.indexArray.emplaceBack(Fa+0,Fa+1,Fa+2),this.indexArray.emplaceBack(Fa+1,Fa+3,Fa+2),zs.primitiveLength+=2,Ht){const ki=js+(gr===1?ys.length-2:gr-2),Co=gr===1?js:ki+1;if(this.indexArray.emplaceBack(Fa+1,ki,Fa+3),this.indexArray.emplaceBack(ki,Co,Fa+3),zs.primitiveLength+=2,pr===void 0&&(pr=Fa),!Zye(cn,ys[gr],$t)){const vl=gr===ys.length-1?pr:zs.vertexLength;this.indexArray.emplaceBack(Fa+2,Fa+3,vl),this.indexArray.emplaceBack(Fa+3,vl+1,vl),this.indexArray.emplaceBack(Fa+3,Co,vl+1),zs.primitiveLength+=3}jr=!jr}if(xe){const ki=this.layoutVertexExtArray,Co=de.projectTilePoint(tn.x,tn.y,I),vl=de.projectTilePoint(In.x,In.y,I),Fd=de.upVector(I,tn.x,tn.y),bl=de.upVector(I,In.x,In.y);FD(ki,Co,Fd),FD(ki,Co,Fd),FD(ki,vl,bl),FD(ki,vl,bl)}}we&&(js+=ys.length-1),qe&&Ht&&this.zoom>=17&&(ir.length!==0&&Vt(ir,ir[0])&&ir.pop(),this.groundEffect.addData(ir,$t,se,Ht>0))}this.footprintSegments.push($s),Hs.triangleCount=this.indexArray.length-Hs.triangleArrayOffset,this.polygonSegments.push(Hs),++Re.footprintSegLen,++Re.polygonSegLen}if(Re.vertexCount=this.layoutVertexArray.length-Re.vertexArrayOffset,Re.groundVertexCount=this.groundEffect.vertexArray.length-Re.groundVertexArrayOffset,Re.vertexCount!==0){if(Re.centroidXY=Ce.borders?g$:this.encodeCentroid(Ce,Re),f.properties&&f.properties.hasOwnProperty("building_id")){const Bt=Re.buildingId;let $t=this.buildingGroups.get(Bt);$t||($t={accX:0,accY:0,accCount:0,mergedMin:new ds(Number.MAX_VALUE,Number.MAX_VALUE),mergedMax:new ds(-Number.MAX_VALUE,-Number.MAX_VALUE),partIndices:[]},this.buildingGroups.set(Bt,$t)),$t.accX+=Ce.acc.x,$t.accY+=Ce.acc.y,$t.accCount+=Ce.accCount,$t.mergedMin.x=Math.min($t.mergedMin.x,Re.min.x),$t.mergedMin.y=Math.min($t.mergedMin.y,Re.min.y),$t.mergedMax.x=Math.max($t.mergedMax.x,Re.max.x),$t.mergedMax.y=Math.max($t.mergedMax.y,Re.max.y),$t.partIndices.push(this.centroidData.length)}if(this.centroidData.push(Re),Ce.borders){this.featuresOnBorder.push(Ce);const Bt=this.featuresOnBorder.length-1;for(let $t=0;$tthis.featuresOnBorder[f].borders[u][0]-this.featuresOnBorder[w].borders[u][0])}splitToSubtiles(){const u=[];for(let B=0;BSr),se=2*Y+(+(U.min.x+U.max.x>Sr)^Y);for(let oe=0;oeB.triangleSegmentIdx===U.triangleSegmentIdx?B.subtile-U.subtile:B.triangleSegmentIdx-U.triangleSegmentIdx);let w=0,C=0,I=0;for(const B of u){if(B.triangleSegmentIdx!==w)break;I++}const L=u.length;for(;C!==u.length;){w=u[C].triangleSegmentIdx;let B=0,U=C,Y=C;for(let se=U;se0&&this.triangleSubSegments.push({segment:xe,min:oe,max:de}),U=Y;for(let we=U;we[Ce[0]*(1-qe[0])+Re[0]*qe[0],Ce[1]*(1-qe[1])+Re[1]*qe[1]],xe=[],we=[];for(const Ce of this.triangleSubSegments){xe[0]=Ce.min.x/Sr,xe[1]=Ce.min.y/Sr,we[0]=Ce.max.x/Sr,we[1]=Ce.max.y/Sr;const Re=de(se,oe,xe),qe=de(se,oe,we);if(new Vi([Re[0],Re[1],I],[qe[0],qe[1],L]).intersectsPrecise(w)===0){Y&&(C.segments.push(Y),Y=void 0);continue}const nt=Ce.segment;Y&&Y.vertexOffset!==nt.vertexOffset&&(C.segments.push(Y),Y=void 0),Y?(Y.vertexLength+=nt.vertexLength,Y.primitiveLength+=nt.primitiveLength):Y={vertexOffset:nt.vertexOffset,primitiveLength:nt.primitiveLength,vertexLength:nt.vertexLength,primitiveOffset:nt.primitiveOffset,sortKey:void 0,vaos:{}}}return Y&&C.segments.push(Y),C}encodeCentroid(u,f){const w=u.centroid(),C=f.span(),I=Math.min(7,Math.round(C.x*this.tileToMeter/10)),L=Math.min(6,Math.round(C.y*this.tileToMeter/10));return new ds(He(w.x,1,8191)<<3|I,He(w.y,1,8191)<<3|L)}encodeBorderCentroid(u){if(!u.borders)return new ds(0,0);const f=u.borders,w=Number.MAX_VALUE;if(f[0][0]!==w||f[1][0]!==w){const C=f[0][0]!==w?0:1;return new ds(6|(f[0][0]!==w?0:65528),(f[C][0]+f[C][1])/2<<3|6)}{const C=f[2][0]!==w?2:3;return new ds((f[C][0]+f[C][1])/2<<3|6,6|(f[2][0]!==w?0:65528))}}showCentroid(u){const f=this.centroidData[u.centroidDataIndex];if(f.flags&=Ww,f.groupCentroidPos.x!==0||f.groupCentroidPos.y!==0){const w=f.span(),C=Math.min(7,Math.round(w.x*this.tileToMeter/10)),I=Math.min(6,Math.round(w.y*this.tileToMeter/10));f.centroidXY=new ds(He(f.groupCentroidPos.x,1,8191)<<3|C,He(f.groupCentroidPos.y,1,8191)<<3|I)}else f.centroidXY=new ds(0,0);this.writeCentroidToBuffer(f)}writeCentroidToBuffer(u){this.groundEffect.updateHiddenByLandmark(u);const f=u.vertexArrayOffset,w=u.vertexCount+u.vertexArrayOffset,C=-1073741824&u.flags?g$:u.centroidXY,I=this.centroidVertexArray.geta_centroid_pos0(f);if(this.centroidVertexArray.geta_centroid_pos1(f)!==C.y||I!==C.x){for(let L=f;LU.max.x||U.min.x>L.max.x||L.min.y>U.max.y||U.min.y>L.max.y||L.footprint.buildingIds.has(U.buildingId)&&(U.flags|=L.clipMask!==p$.None?-1073741824:Ww);else for(const U of this.centroidData)if(!(U.flags&Ww||U.flags&x$||L.min.x>U.max.x||U.min.x>L.max.x||L.min.y>U.max.y||U.min.y>L.max.y))for(let Y=0;Yf!=xe>f&&u<(this.footprintVertices.int16[2*(se+L.vertexOffset)+0]-oe)*(f-de)/(xe-de)+oe&&(C=!C)}B=U}}return C}getHeightAtTileCoord(u,f){let w=Number.NEGATIVE_INFINITY,C=!0;const I=4*(u+Sr)*Sr+(f+Sr);if(this.partLookup.hasOwnProperty(I)){const L=this.partLookup[I];return L?{height:L.height,hidden:!!(L.flags&Ww)}:void 0}for(const L of this.centroidData)u>L.max.x||L.min.x>u||f>L.max.y||L.min.y>f||L.height<=w||this.footprintContainsPoint(u,f,L)&&(w=L.height,this.partLookup[I]=L,C=!!(L.flags&Ww));if(w!==Number.NEGATIVE_INFINITY)return{height:w,hidden:C};this.partLookup[I]=void 0}}function tPe(v,u){const f=v.add(u)._unit();return v.x*f.x+v.y*f.y}function __t(v,u,f,w){const C=u.sub(v)._perp()._unit(),I=f.sub(u)._perp()._unit();return sPe(v,u,f,tPe(C,I),w)}function sPe(v,u,f,w,C){const I=Math.sqrt(1-w*w);return Math.min(v.dist(u)/3,u.dist(f)/3,C*I/w)}function Zye(v,u,f){return v.xf[1].x&&u.x>f[1].x||v.yf[1].y&&u.y>f[1].y}function rPe(v,u){return v.xu[1].x||v.yu[1].y}function w_t(v){return v.every(u=>u.x<=0)||v.every(u=>u.x>=Sr)||v.every(u=>u.y<=0)||v.every(u=>u.y>=Sr)}function nPe(v,u,f){if(v.x<0||v.x>=Sr||u.x<0||u.x>=Sr||f.x<0||f.x>=Sr)return!1;const w=f.sub(u),C=w.perp(),I=v.sub(u);return(w.x*I.x+w.y*I.y)/Math.sqrt((w.x*w.x+w.y*w.y)*(I.x*I.x+I.y*I.y))>-.866&&C.x*I.x+C.y*I.y<0}function aPe(v,u,f){const w=u?2|v:-3&v;return f?1|w:-2&w}function iPe(){const v=Math.PI/32,u=Math.tan(v),f=Ut;return f*Math.sqrt(1+2*u*u)-f}function oPe(v,u,f){const w=1<{for(const Rt of bt)we.push({polygon:Rt,bounds:Ht})},Re=Math.ceil(Math.log2(se)),qe=Math.ceil(Math.log2(oe)),nt=Re-qe,Ze=[];for(let bt=0;bt0?0:1);for(let bt=0;btHt+1?xt.push({polygons:zs,bounds:$s,depth:Ht+1}):Ce(zs,$s)}if(Hs.length){const $s=[new ds(Rt===0?Es:Vt.x,Rt===1?Es:Vt.y),Bt];Ze.length>Ht+1?xt.push({polygons:Hs,bounds:$s,depth:Ht+1}):Ce(Hs,$s)}}return we}(v,u,Math.ceil((I-C)/11.25),Math.ceil((L-B)/11.25),1,(U,Y,se)=>{if(U===0)return .5*(Y+se);{const oe=ws((f.y+Y/Sr)/w);return(sr(.5*(ws((f.y+se/Sr)/w)+oe))*w-f.y)*Sr}})}function j_t(v,u,f,w,C,I){const L=Math.pow(2,w.z-C.z);for(let B=0;B=U[L]&&(B=u,U=v),B[L]C&&uPe(B,U,L,C),B[L]I&&uPe(U,B,L,I)}}function b$(v,u,f,w,C,I){const L=[];for(let B=0;B=w&&we.x>=w||(xe.x>=w?xe=new ds(w,xe.y+(w-xe.x)/(we.x-xe.x)*(we.y-xe.y))._round():we.x>=w&&(we=new ds(w,xe.y+(w-xe.x)/(we.x-xe.x)*(we.y-xe.y))._round()),xe.y>=C&&we.y>=C||(xe.y>=C?xe=new ds(xe.x+(C-xe.y)/(we.y-xe.y)*(we.x-xe.x),C)._round():we.y>=C&&(we=new ds(xe.x+(C-xe.y)/(we.y-xe.y)*(we.x-xe.x),C)._round()),Y&&xe.equals(Y[Y.length-1])||(Y=[xe],L.push(Y),I&&I.push({progress:{min:Re+mPe(qe,nt,xe)*Ce,max:1},parentIndex:B,prevPoint:qe,nextPoint:nt})),Y.push(we),I&&(I[I.length-1].progress.max=Re+mPe(qe,nt,we)*Ce,I[I.length-1].nextPoint=nt)))))}if(I&&oe>0)for(let de=se;deY.t-se.t);let L=0,B=0,U=[];for(w.push(U);L!==v.length;){if(B===I.length){for(;L!==v.length;)U.length!==0&&U[U.length-1].equals(v[L])||U.push(v[L]),L++;break}I[B].t<=L?(U.length!==0&&U[U.length-1].equals(I[B].point)||U.push(I[B].point),Math.trunc(I[B].t),B++):(U.length!==0&&U[U.length-1].equals(v[L])||U.push(v[L]),L++)}}function mPe(v,u,f){return v.x!==u.x?(f.x-v.x)/(u.x-v.x):v.y!==u.y?(f.y-v.y)/(u.y-v.y):0}function BD(v,u){return v.x*u.x+v.y*u.y}function fPe(v,u){if(v.length===1){let f=0;const w=u[f++];let C;for(;!C||w.equals(C);)if(C=u[f++],!C)return 1/0;for(;f{Es[0]=zs,Es[1]=Hs,Es[2]=$s,Es[3]=1},js=iPe();xe>0&&(xe+=js),we+=js;for(const Es of de){const zs=[],Hs=[];for(const $s of Es){const nr=$s.x+Ce.x,ys=$s.y+Ce.y,qs=oe.projection.projectTilePoint(nr,ys,xt),Zs=oe.projection.upVector(xt,$s.x,$s.y);let ir=xe,pr=we;if(qe){const Zr=xPe(nr,ys,xe,we,qe,nt,Ze,ut);ir+=Zr.base,pr+=Zr.top}xe!==0?$t(Vt,qs.x+Zs[0]*Rt*ir,qs.y+Zs[1]*Rt*ir,qs.z+Zs[2]*Rt*ir):$t(Vt,qs.x,qs.y,qs.z),$t(Bt,qs.x+Zs[0]*Rt*pr,qs.y+Zs[1]*Rt*pr,qs.z+Zs[2]*Rt*pr),tt(Vt,Vt,Re),tt(Bt,Bt,Re),zs.push(new U4(Vt[0],Vt[1],Vt[2])),Hs.push(new U4(Bt[0],Bt[1],Bt[2]))}bt.push(zs),Ht.push(Hs)}return[bt,Ht]}(v,u,f,w,C,I,L,B,U,Y,se):L?function(oe,de,xe,we,Ce,Re,qe,nt,Ze){const ut=[],xt=[],bt=[0,0,0,1];for(const Ht of oe){const Rt=[],Vt=[];for(const Bt of Ht){const $t=Bt.x+we.x,js=Bt.y+we.y,Es=xPe($t,js,de,xe,Re,qe,nt,Ze);bt[0]=$t,bt[1]=js,bt[2]=Es.base,bt[3]=1,wt(bt,bt,Ce),bt[3]=Math.max(bt[3],1e-5);const zs=new U4(bt[0]/bt[3],bt[1]/bt[3],bt[2]/bt[3]);bt[0]=$t,bt[1]=js,bt[2]=Es.top,bt[3]=1,wt(bt,bt,Ce),bt[3]=Math.max(bt[3],1e-5);const Hs=new U4(bt[0]/bt[3],bt[1]/bt[3],bt[2]/bt[3]);Rt.push(zs),Vt.push(Hs)}ut.push(Rt),xt.push(Vt)}return[ut,xt]}(u,f,w,C,I,L,B,U,Y):function(oe,de,xe,we,Ce){const Re=[],qe=[],nt=Ce[8]*de,Ze=Ce[9]*de,ut=Ce[10]*de,xt=Ce[11]*de,bt=Ce[8]*xe,Ht=Ce[9]*xe,Rt=Ce[10]*xe,Vt=Ce[11]*xe;for(const Bt of oe){const $t=[],js=[];for(const Es of Bt){const zs=Es.x+we.x,Hs=Es.y+we.y,$s=Ce[0]*zs+Ce[4]*Hs+Ce[12],nr=Ce[1]*zs+Ce[5]*Hs+Ce[13],ys=Ce[2]*zs+Ce[6]*Hs+Ce[14],qs=Ce[3]*zs+Ce[7]*Hs+Ce[15],Zs=$s+nt,ir=nr+Ze,pr=ys+ut,Zr=Math.max(qs+xt,1e-5),Nr=$s+bt,jr=nr+Ht,gr=ys+Rt,qr=Math.max(qs+Vt,1e-5);$t.push(new U4(Zs/Zr,ir/Zr,pr/Zr)),js.push(new U4(Nr/qr,jr/qr,gr/qr))}Re.push($t),qe.push(js)}return[Re,qe]}(u,f,w,C,I)}function xPe(v,u,f,w,C,I,L,B){const U=L*C.getElevationAt(v,u,!0,!0),Y=I[0]!==0,se=Y?I[1]===0?L*(I[0]/7-450):L*function(oe,de,xe){const we=Math.floor(de[0]/8),Ce=Math.floor(de[1]/8),Re=10*(de[0]-8*we),qe=10*(de[1]-8*Ce),nt=oe.getElevationAt(we,Ce,!0,!0),Ze=oe.getMeterToDEM(xe),ut=Math.floor(.5*(Re*Ze-1)),xt=Math.floor(.5*(qe*Ze-1)),bt=oe.tileCoordToPixel(we,Ce),Ht=2*ut+1,Rt=2*xt+1,Vt=function(Hs,$s,nr,ys,qs){return[Hs.getElevationAtPixel($s,nr,!0),Hs.getElevationAtPixel($s+qs,nr,!0),Hs.getElevationAtPixel($s,nr+qs,!0),Hs.getElevationAtPixel($s+ys,nr+qs,!0)]}(oe,bt.x-ut,bt.y-xt,Ht,Rt),Bt=Math.abs(Vt[0]-Vt[1]),$t=Math.abs(Vt[2]-Vt[3]),js=Math.abs(Vt[0]-Vt[2])+Math.abs(Vt[1]-Vt[3]),Es=Math.min(.25,.5*Ze*(Bt+$t)/Ht),zs=Math.min(.25,.5*Ze*js/Rt);return nt+Math.max(Es*Re,zs*qe)}(C,I,B):U;return{base:U+(f===0?-1:f),top:Y?Math.max(se+w,U+f+2):U+w}}const Xye=4096;class k_t{constructor(u){this.module=u,this.memoryStack=this.module.malloc(Xye),this.memoryStackNextFree=this.memoryStack}createIntArray(u){const f=this.memoryStackNextFree;return this.memoryStackNextFree+=u.length*Int32Array.BYTES_PER_ELEMENT,this.memoryStackNextFree-this.memoryStack>Xye?-1:(new Int32Array(this.module.heap32.buffer,f,u.length).set(u),f)}createFloatArray(u){const f=this.memoryStackNextFree;return this.memoryStackNextFree+=u.length*Float32Array.BYTES_PER_ELEMENT,this.memoryStackNextFree-this.memoryStack>Xye?-1:(new Float32Array(this.module.heapF32.buffer,f,u.length).set(u),f)}readStringBuffer(u){let f="";for(;this.module.heapU8[u]!==0;)f+=String.fromCharCode(this.module.heapU8[u]),++u;return f}setStyle(u){const f=u.normalScale;this.module.setStyle(f[0],f[1],f[2],u.tileToMeters)}setAOOptions(u,f){this.module.setAOOptions(u?1:0,f)}setMetricOptions(u,f){this.module.setMetricOptions(u?1:0,f)}setStructuralOptions(u){this.module.setStructuralOptions(u?1:0)}setFacadeOptions(u,f){this.module.setFacadeOptions(u,f?1:0)}setFauxFacadeOptions(u,f,w){this.module.setFauxFacadeOptions(u?1:0,f?1:0,w)}setFacadeClassifierOptions(u){this.module.setFacadeClassifierOptions(u)}generateMesh(u,f){this.memoryStackNextFree=this.memoryStack;for(const B of u){const U=this.createIntArray(B.ringIndices),Y=this.createFloatArray(B.coordinates);if(U===-1||Y===-1)return`building_gen: Out of stack memory: ${this.memoryStackNextFree-this.memoryStack}/4096`;this.module.addFeature(B.id,B.sourceId,B.minHeight,B.height,B.roofType,Y,U,B.ringIndices.length-1)}for(const B of f){let U;U=B.entrances?JSON.parse(B.entrances):[];const Y=this.createFloatArray(U),se=this.createFloatArray(B.coordinates);if(Y===-1||se===-1)return`building_gen: Out of stack memory: ${this.memoryStackNextFree-this.memoryStack}/4096`;this.module.addFacade(B.sourceId,B.crossPerc,B.distanceToRoad,Y,U.length,se,B.coordinates.length)}if(!this.module.generateMesh()){const B=this.module.getLastError();return this.readStringBuffer(B)}const w=this.module.getMeshCount(),C=new Array(w);for(let B=0;B>2)-3,Re=xe[we++]>>2;if(we++,C.json=JSON.parse(CPe.decode(xe.subarray(we,we+Re))),we+=Re,we>>0,Math.ceil(1.2*ut)),bt=Math.ceil((xt-ut)/65536);try{return Ce.grow(bt),Re(),!0}catch{return!1}},b:qe}};return(WebAssembly.instantiateStreaming?WebAssembly.instantiateStreaming(xe,nt):xe.then(Ze=>Ze.arrayBuffer()).then(Ze=>WebAssembly.instantiate(Ze,nt))).then(Ze=>{const{Rb:ut,Qb:xt,P:bt,T:Ht,X:Rt,Ja:Vt,La:Bt,Qa:$t,Va:js,Wa:Es,eb:zs,jb:Hs,f:$s,e:nr,yb:ys,zb:qs,Ab:Zs,Bb:ir,Db:pr,Gb:Zr}=Ze.instance.exports;Ce=nr;const Nr=(()=>{let jr=0,gr=0,qr=0,tn=0;return In=>{qr&&(ut(tn),ut(jr),gr+=qr,qr=jr=0),jr||(gr+=128,jr=xt(gr));const cn=In.length+7&-8;let fa=jr;cn>=gr&&(qr=cn,fa=tn=xt(cn));for(let xi=0;xi{Dv=xe,zD=void 0}))}()),de&&se.push(function(){if(Qye)return;const xe=function(we){let Ce;const Re=WebAssembly.instantiateStreaming(we,{}).then(Ze=>{Ce=Ze.instance,Ce.exports.__wasm_call_ctors()}),qe={NONE:"",OCTAHEDRAL:"meshopt_decodeFilterOct",QUATERNION:"meshopt_decodeFilterQuat",EXPONENTIAL:"meshopt_decodeFilterExp"},nt={ATTRIBUTES:"meshopt_decodeVertexBuffer",TRIANGLES:"meshopt_decodeIndexBuffer",INDICES:"meshopt_decodeIndexSequence"};return{ready:Re,supported:!0,decodeGltfBuffer(Ze,ut,xt,bt,Ht,Rt){(function(Vt,Bt,$t,js,Es,zs,Hs){const $s=Vt.exports.sbrk,nr=js+3&-4,ys=$s(nr*Es),qs=$s(zs.length),Zs=new Uint8Array(Vt.exports.memory.buffer);Zs.set(zs,qs);const ir=Bt(ys,js,Es,qs,zs.length);if(ir===0&&Hs&&Hs(ys,nr,Es),$t.set(Zs.subarray(ys,ys+js*Es)),$s(ys-$s(0)),ir!==0)throw new Error(`Malformed buffer data: ${ir}`)})(Ce,Ce.exports[nt[Ht]],Ze,ut,xt,bt,Ce.exports[qe[Rt]])}}}(fetch(Sa()));return xe.ready.then(()=>{Qye=xe})}()),L)for(let xe=0;xe{const B=$0(w,(U,Y)=>{U?L(U):I(Y)});C&&C.addEventListener("abort",()=>{B.cancel(),L(new DOMException("Aborted","AbortError"))},{once:!0})})}({url:v,type:"arrayBuffer"},u);return APe(f,0,v,u)}function eve(v){switch(v){case WebGL2RenderingContext.RGBA8:case WebGL2RenderingContext.RGBA16F: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 tve(v){switch(v){case WebGL2RenderingContext.RGBA8:return WebGL2RenderingContext.UNSIGNED_BYTE;case WebGL2RenderingContext.RGBA16F:return WebGL2RenderingContext.HALF_FLOAT;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 jb{constructor(u,f,w,C){this.context=u,this.format=w,this.useMipmap=C&&C.useMipmap,this.texture=u.gl.createTexture(),this.update(f,{premultiply:C&&C.premultiply})}update(u,f){const w=u&&u instanceof HTMLVideoElement&&u.width===0?u.videoWidth:u.width,C=u&&u instanceof HTMLVideoElement&&u.height===0?u.videoHeight:u.height,{context:I}=this,{gl:L}=I,{x:B,y:U}=f&&f.position?f.position:{x:0,y:0},Y=B+w,se=U+C;this.size&&(this.size[0]!==Y||this.size[1]!==se)&&(!f||f.recreateWhenResize===void 0||f.recreateWhenResize)&&(L.bindTexture(L.TEXTURE_2D,null),L.deleteTexture(this.texture),this.texture=L.createTexture(),this.size=null),L.bindTexture(L.TEXTURE_2D,this.texture),I.pixelStoreUnpackFlipY.set(!1),I.pixelStoreUnpack.set(1),I.pixelStoreUnpackPremultiplyAlpha.set(this.format===L.RGBA8&&(!f||f.premultiply!==!1));const oe=u instanceof HTMLImageElement||u instanceof HTMLCanvasElement||u instanceof HTMLVideoElement||u instanceof ImageData||ImageBitmap&&u instanceof ImageBitmap;if(!this.size&&Y>0&&se>0){const de=this.useMipmap?Math.floor(Math.log2(Math.max(Y,se)))+1:1;L.texStorage2D(L.TEXTURE_2D,de,this.format,Y,se),this.size=[Y,se]}this.size&&(oe?L.texSubImage2D(L.TEXTURE_2D,0,B,U,eve(this.format),tve(this.format),u):"data"in u&&u.data&&L.texSubImage2D(L.TEXTURE_2D,0,B,U,w,C,eve(this.format),tve(this.format),u.data)),this.useMipmap&&L.generateMipmap(L.TEXTURE_2D)}bind(u,f,w=!1){const{context:C}=this,{gl:I}=C;I.bindTexture(I.TEXTURE_2D,this.texture),u!==this.minFilter&&(I.texParameteri(I.TEXTURE_2D,I.TEXTURE_MAG_FILTER,u),I.texParameteri(I.TEXTURE_2D,I.TEXTURE_MIN_FILTER,this.useMipmap&&!w?u===I.NEAREST?I.NEAREST_MIPMAP_NEAREST:I.LINEAR_MIPMAP_LINEAR:u),this.minFilter=u),f!==this.wrapS&&(I.texParameteri(I.TEXTURE_2D,I.TEXTURE_WRAP_S,f),I.texParameteri(I.TEXTURE_2D,I.TEXTURE_WRAP_T,f),this.wrapS=f)}bindExtraParam(u,f,w,C,I){const{context:L}=this,{gl:B}=L;B.bindTexture(B.TEXTURE_2D,this.texture),f!==this.magFilter&&(B.texParameteri(B.TEXTURE_2D,B.TEXTURE_MAG_FILTER,f),this.magFilter=f),u!==this.minFilter&&(B.texParameteri(B.TEXTURE_2D,B.TEXTURE_MIN_FILTER,this.useMipmap?u===B.NEAREST?B.NEAREST_MIPMAP_NEAREST:B.LINEAR_MIPMAP_LINEAR:u),this.minFilter=u),w!==this.wrapS&&(B.texParameteri(B.TEXTURE_2D,B.TEXTURE_WRAP_S,w),this.wrapS=w),C!==this.wrapT&&(B.texParameteri(B.TEXTURE_2D,B.TEXTURE_WRAP_T,C),this.wrapT=C),I!==this.compareMode&&(I?(B.texParameteri(B.TEXTURE_2D,B.TEXTURE_COMPARE_MODE,B.COMPARE_REF_TO_TEXTURE),B.texParameteri(B.TEXTURE_2D,B.TEXTURE_COMPARE_FUNC,I)):B.texParameteri(B.TEXTURE_2D,B.TEXTURE_COMPARE_MODE,B.NONE),this.compareMode=I)}destroy(){const{gl:u}=this.context;u.deleteTexture(this.texture),this.texture=null}}class UD{constructor(u,f){this.context=u,this.texture=f}bind(u,f){const{context:w}=this,{gl:C}=w;C.bindTexture(C.TEXTURE_2D,this.texture),u!==this.minFilter&&(C.texParameteri(C.TEXTURE_2D,C.TEXTURE_MAG_FILTER,u),C.texParameteri(C.TEXTURE_2D,C.TEXTURE_MIN_FILTER,u),this.minFilter=u),f!==this.wrapS&&(C.texParameteri(C.TEXTURE_2D,C.TEXTURE_WRAP_S,f),C.texParameteri(C.TEXTURE_2D,C.TEXTURE_WRAP_T,f),this.wrapS=f)}}const I_t=Qs([{name:"a_pos_3f",components:3,type:"Float32"}]),P_t=Qs([{name:"a_color_3f",components:3,type:"Float32"}]),L_t=Qs([{name:"a_color_4f",components:4,type:"Float32"}]),D_t=Qs([{name:"a_uv_2f",components:2,type:"Float32"}]),R_t=Qs([{name:"a_normal_3f",components:3,type:"Float32"}]),O_t=Qs([{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"}]),F_t=Qs([{name:"a_pbr",components:4,type:"Uint16"},{name:"a_heightBasedEmissiveStrength",components:3,type:"Float32"}]);function IPe(v,u){const f=N$(v.projection,v.zoom,v.width,v.height),w=function(I,L,B,U,Y){const se=new Zt(B.lng-180*cN,B.lat),oe=new Zt(B.lng+180*cN,B.lat),de=I.project(se.lng,se.lat),xe=I.project(oe.lng,oe.lat),we=-Math.atan2(xe.y-de.y,xe.x-de.x),Ce=en.fromLngLat(B);Ce.y=He(Ce.y,-1+cN,1-cN);const Re=Ce.toLngLat(),qe=I.project(Re.lng,Re.lat),nt=en.fromLngLat(Re);nt.x+=cN;const Ze=nt.toLngLat(),ut=I.project(Ze.lng,Ze.lat),xt=LPe(ut.x-qe.x,ut.y-qe.y,we),bt=en.fromLngLat(Re);bt.y+=cN;const Ht=bt.toLngLat(),Rt=I.project(Ht.lng,Ht.lat),Vt=LPe(Rt.x-qe.x,Rt.y-qe.y,we),Bt=Math.abs(xt.x)/Math.abs(Vt.y),$t=b([]);R($t,$t,-we*(1-(Y?0:U)));const js=b([]);return E(js,js,[1,1-(1-Bt)*U,1]),js[4]=-Vt.x/Vt.y*U,R(js,js,we),k(js,$t,js),js}(v.projection,0,v.center,f,u),C=PPe(v);return E(w,w,[C,C,1]),w}function PPe(v){const u=v.projection,f=N$(v.projection,v.zoom,v.width,v.height),w=sve(u,v.center),C=sve(u,Zt.convert(u.center));return Math.pow(2,w*f+(1-f)*C)}function N$(v,u,f,w,C=1/0){const I=v.range;if(!I)return 0;const L=Math.min(C,Math.max(f,w)),B=Math.log2(L/1024);return ot(I[0]+B,I[1]+B,u)}const cN=1/4e4;function sve(v,u){const f=He(u.lat,-85.051129,Ls),w=new Zt(u.lng-180*cN,f),C=new Zt(u.lng+180*cN,f),I=v.project(w.lng,f),L=v.project(C.lng,f),B=en.fromLngLat(w),U=en.fromLngLat(C),Y=L.x-I.x,se=L.y-I.y,oe=U.x-B.x,de=U.y-B.y,xe=Math.sqrt((oe*oe+de*de)/(Y*Y+se*se));return Math.log2(xe)}function LPe(v,u,f){const w=Math.cos(f),C=Math.sin(f);return{x:v*w-u*C,y:v*C+u*w}}function DPe(v,u,f){b(v),R(v,v,Hr(u[2])),A(v,v,Hr(u[0])),D(v,v,Hr(u[1])),E(v,v,f),k(v,v,[1,0,0,0,0,0,1,0,0,1,0,0,0,0,0,1])}function k$(v,u,f,w,C,I,L,B){const U=[f[0]-u[0],f[1]-u[1],0],Y=[w[0]-u[0],w[1]-u[1],0];if(re(U)<1e-12||re(Y)<1e-12)return rt(v);const se=De([],U,Y);Pe(se,se),le(Y,w,u),U[2]=(I-C)*B,Y[2]=(L-C)*B;const oe=U;return De(oe,U,Y),Pe(oe,oe),xs(v,se,oe)}function S$(v,u,f=!1){const w=Hw(u.zoom),C=function(I,L,B){const U=L.worldSize,Y=[I[12],I[13],I[14]],se=ws(Y[1]/U),oe=Xt(Y[0]/U),de=b([]),xe=as(1,se)*U,we=as(1,0)*U*mr(se,L.zoom),Ce=1/Cye(U);let Re=we*Ce;if(B){const ut=N$(L.projection,L.zoom,L.width,L.height,1024);Re=Ce*L.projection.pixelSpaceConversion(L.center.lat,U,ut)}const qe=It(se,oe);ne(qe,qe,ve([],Pe([],qe),xe*Re*Y[2]));const nt=function(ut){const xt=[ut[0],ut[1],ut[2]];let bt=[0,1,0];const Ht=De([],bt,xt);return De(bt,xt,Ht),Me(bt)===0&&(bt=[0,1,0],De(Ht,xt,bt)),Pe(Ht,Ht),Pe(bt,bt),Pe(xt,xt),[Ht[0],Ht[1],Ht[2],0,bt[0],bt[1],bt[2],0,xt[0],xt[1],xt[2],0,ut[0],ut[1],ut[2],1]}(qe);E(de,de,[Re,Re,Re*xe]),T(de,de,[-Y[0],-Y[1],-Y[2]]);const Ze=k([],L.globeMatrix,nt);return k(Ze,Ze,de),k(Ze,Ze,I),Ze}(v,u,f);if(w>0){const I=function(L,B){const U=B.worldSize,Y=as(1,0)*U*mr(B.center.lat,B.zoom)/Cye(U),se=as(1,B.center.lat)*U,oe=b([]);D(oe,oe,Hr(B.center.lng)),A(oe,oe,Hr(B.center.lat)),T(oe,oe,[0,0,Ct]),E(oe,oe,[Y,Y,Y*se]);const de=B.point;return T(oe,oe,[-de.x,-de.y,0]),k(oe,oe,L),k(oe,B.globeMatrix,oe)}(v,u);return function(L,B,U){const Y=(we,Ce,Re)=>{const qe=re(we),nt=re(Ce),Ze=Vw(we,Ce,Re);return ve(Ze,Ze,1/re(Ze)*jn(qe,nt,Re))},se=Y([L[0],L[1],L[2]],[B[0],B[1],B[2]],U),oe=Y([L[4],L[5],L[6]],[B[4],B[5],B[6]],U),de=Y([L[8],L[9],L[10]],[B[8],B[9],B[10]],U),xe=Vw([L[12],L[13],L[14]],[B[12],B[13],B[14]],U);return[se[0],se[1],se[2],0,oe[0],oe[1],oe[2],0,de[0],de[1],de[2],0,xe[0],xe[1],xe[2],1]}(C,I,w)}return C}function rve(v,u,f,w){const C=Vi.projectAabbCorners(w,f);let I=Number.MAX_VALUE;for(let B=0;B0||Re===0&&we[0]*Ce[0]+we[1]*Ce[1]>=0&&we[0]*we[0]+we[1]*we[1]>Ce[0]*Ce[0]+Ce[1]*Ce[1])&&(se=xe)}oe=se}while(oe!==Y);return U.length>0&&U.push(U[0]),U}(C);if(sc(v,L))return I}const q4=64,OM={CoordinateSpaceTile:1,HasMapboxMeshFeatures:4,HasMeshoptCompression:8};function C$(v,u,f,w,C,I,L,B,U,Y=!1){const se=f.zoom,oe=f.project(w),de=mr(w.lat,se),xe=1/de;b(v),T(v,v,[oe.x+L[0]*xe,oe.y+L[1]*xe,L[2]]);let we=1,Ce=1;const Re=f.worldSize;if(Y){if(f.projection.name==="mercator"){let ut=0;f.elevation&&(ut=f.elevation.getAtPointOrZero(new en(oe.x/Re,oe.y/Re),0));const xt=wt([],[oe.x,oe.y,ut,1],f.projMatrix)[3]/f.cameraToCenterDistance;we=xt,Ce=xt*mr(f.center.lat,se)}else if(f.projection.name==="globe"){const ut=S$(v,f),xt=[0,0,0,1];wt(xt,xt,k([],f.projMatrix,ut));const bt=xt[3]/f.cameraToCenterDistance,Ht=Hw(se),Rt=f.projection.pixelsPerMeter(w.lat,Re)*mr(w.lat,se),Vt=f.projection.pixelsPerMeter(f.center.lat,Re)*mr(f.center.lat,se);we=bt/jn(Rt,wr(f.center.lat),Ht),Ce=bt*de/Rt,we*=Vt,Ce*=Vt}}else we=xe;E(v,v,[we,we,Ce]);const qe=[...v],nt=u.orientation,Ze=[];if(DPe(Ze,[nt[0]+(C?C[0]:0),nt[1]+(C?C[1]:0),nt[2]+(C?C[2]:0)],I),k(v,qe,Ze),B&&f.elevation){let ut=0;const xt=[];if(U&&f.elevation){ut=function(Ht,Rt,Vt,Bt,$t){const js=Rt.elevation;if(!js)return 0;const Es=Vi.projectAabbCorners(Vt,Bt),zs=as(1,$t.lat)*Rt.worldSize,Hs=function(gr,qr){const tn=[0,0,1],In=[{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 cn of In){const fa=gr[cn.corners[0]],xi=gr[cn.corners[1]],pa=gr[cn.corners[2]],vi=[xi[0]-fa[0],xi[1]-fa[1],qr*(xi[2]-fa[2])],Fa=De(vi,vi,[pa[0]-fa[0],pa[1]-fa[1],qr*(pa[2]-fa[2])]);Pe(Fa,Fa),cn.dotProductWithUp=Ie(Fa,tn)}return In.sort((cn,fa)=>cn.dotProductWithUp-fa.dotProductWithUp),In[0].corners}(Es,zs),$s=Es[Hs[0]],nr=Es[Hs[1]],ys=Es[Hs[2]],qs=Es[Hs[3]],Zs=js.getAtPointOrZero(new en($s[0]/Rt.worldSize,$s[1]/Rt.worldSize),0),ir=js.getAtPointOrZero(new en(nr[0]/Rt.worldSize,nr[1]/Rt.worldSize),0),pr=js.getAtPointOrZero(new en(ys[0]/Rt.worldSize,ys[1]/Rt.worldSize),0),Zr=js.getAtPointOrZero(new en(qs[0]/Rt.worldSize,qs[1]/Rt.worldSize),0),Nr=(Zs+Zr)/2,jr=(ir+pr)/2;return Nr>jr?ir=u.gl.NEAREST_MIPMAP_NEAREST}),v.uploaded=!0,v.image=null)}function B_t(v,u,f){v.indexBuffer=u.createIndexBuffer(v.indexArray,!1,!0),v.vertexBuffer=u.createVertexBuffer(v.vertexArray,I_t.members,!1,!0),v.normalArray&&(v.normalBuffer=u.createVertexBuffer(v.normalArray,R_t.members,!1,!0)),v.texcoordArray&&(v.texcoordBuffer=u.createVertexBuffer(v.texcoordArray,D_t.members,!1,!0)),v.colorArray&&(v.colorBuffer=u.createVertexBuffer(v.colorArray,(v.colorArray.bytesPerElement===12?P_t:L_t).members,!1,!0)),v.featureArray&&(v.pbrBuffer=u.createVertexBuffer(v.featureArray,F_t.members,!0)),v.segments=No.simpleSegment(0,0,v.vertexArray.length,v.indexArray.length);const w=v.material;w.pbrMetallicRoughness.baseColorTexture&&qD(w.pbrMetallicRoughness.baseColorTexture,u),w.pbrMetallicRoughness.metallicRoughnessTexture&&qD(w.pbrMetallicRoughness.metallicRoughnessTexture,u),w.normalTexture&&qD(w.normalTexture,u),w.occlusionTexture&&qD(w.occlusionTexture,u,f),w.emissionTexture&&qD(w.emissionTexture,u)}function nve(v,u,f){if(v.meshes)for(const w of v.meshes)B_t(w,u,f);if(v.children)for(const w of v.children)nve(w,u,f)}function T$(v){if(v.meshes)for(const u of v.meshes)u.indexArray.destroy(),u.vertexArray.destroy(),u.colorArray&&u.colorArray.destroy(),u.normalArray&&u.normalArray.destroy(),u.texcoordArray&&u.texcoordArray.destroy(),u.featureArray&&u.featureArray.destroy();if(v.children)for(const u of v.children)T$(u)}function z_t(v){v.pbrMetallicRoughness.baseColorTexture&&v.pbrMetallicRoughness.baseColorTexture.gfxTexture&&v.pbrMetallicRoughness.baseColorTexture.gfxTexture.destroy(),v.pbrMetallicRoughness.metallicRoughnessTexture&&v.pbrMetallicRoughness.metallicRoughnessTexture.gfxTexture&&v.pbrMetallicRoughness.metallicRoughnessTexture.gfxTexture.destroy(),v.normalTexture&&v.normalTexture.gfxTexture&&v.normalTexture.gfxTexture.destroy(),v.emissionTexture&&v.emissionTexture.gfxTexture&&v.emissionTexture.gfxTexture.destroy(),v.occlusionTexture&&v.occlusionTexture.gfxTexture&&v.occlusionTexture.gfxTexture.destroy()}function ave(v){if(v.meshes)for(const u of v.meshes)u.vertexBuffer&&(u.vertexBuffer.destroy(),u.indexBuffer.destroy(),u.normalBuffer&&u.normalBuffer.destroy(),u.texcoordBuffer&&u.texcoordBuffer.destroy(),u.colorBuffer&&u.colorBuffer.destroy(),u.pbrBuffer&&u.pbrBuffer.destroy(),u.segments.destroy(),u.material&&z_t(u.material));if(v.footprintDebugMesh&&(v.footprintDebugMesh.vertexBuffer.destroy(),v.footprintDebugMesh.indexBuffer.destroy(),v.footprintDebugMesh.segments.destroy()),v.children)for(const u of v.children)ave(u)}function V4(v,u){const f=v.json.bufferViews[u.bufferView],w=w$[u.componentType];return new w(v.buffers[f.buffer],(u.byteOffset||0)+(f.byteOffset||0),u.count*(f.byteStride&&f.byteStride!==$D[u.type]*w.BYTES_PER_ELEMENT?f.byteStride/w.BYTES_PER_ELEMENT:$D[u.type]))}function ive(v,u,f,w){const C=w$[u.componentType],I=function(se){switch(se){case Int8Array:return 1/127;case Uint8Array:return 1/255;case Int16Array:return 1/32767;case Uint16Array:return 1/65535;default:return 1}}(C),L=v.json.bufferViews[u.bufferView],B=L.byteStride?L.byteStride/C.BYTES_PER_ELEMENT:$D[u.type],U=f.float32,Y=U.length/f.capacity;for(let se=0,oe=0;se0){for(let Re=0;Re0){I.texcoordArray=new zw;const de=u.json.accessors[C.TEXCOORD_0];I.texcoordArray.resize(de.count);const xe=V4(u,de);ive(u,de,I.texcoordArray,xe)}if(C._FEATURE_ID_RGBA4444!==void 0){const de=u.json.accessors[C._FEATURE_ID_RGBA4444];u.json.extensionsUsed&&u.json.extensionsUsed.includes("EXT_meshopt_compression")&&(I.featureData=V4(u,de))}C._FEATURE_RGBA4444!==void 0&&(I.featureData=new Uint32Array(V4(u,u.json.accessors[C._FEATURE_RGBA4444]).buffer));const oe=v.material;return I.material=function(de,xe){const{emissiveFactor:we=[0,0,0],alphaMode:Ce="OPAQUE",alphaCutoff:Re=.5,normalTexture:qe,occlusionTexture:nt,emissiveTexture:Ze,doubleSided:ut,name:xt}=de,{baseColorFactor:bt=[1,1,1,1],metallicFactor:Ht=1,roughnessFactor:Rt=1,baseColorTexture:Vt,metallicRoughnessTexture:Bt}=de.pbrMetallicRoughness||{},$t=nt?xe[nt.index]:void 0;if(nt&&nt.extensions&&nt.extensions.KHR_texture_transform&&$t){const js=nt.extensions.KHR_texture_transform;$t.offsetScale=[js.offset[0],js.offset[1],js.scale[0],js.scale[1]]}return{name:xt,pbrMetallicRoughness:{baseColorFactor:new Mr(...bt),metallicFactor:Ht,roughnessFactor:Rt,baseColorTexture:Vt?xe[Vt.index]:void 0,metallicRoughnessTexture:Bt?xe[Bt.index]:void 0},doubleSided:ut,emissiveFactor:new Mr(...we),alphaMode:Ce,alphaCutoff:Re,normalTexture:qe?xe[qe.index]:void 0,occlusionTexture:$t,emissionTexture:Ze?xe[Ze.index]:void 0,defined:de.defined===void 0}}(oe!==void 0?u.json.materials[oe]:{defined:!1},f),I}function OPe(v,u,f){const{matrix:w,rotation:C,translation:I,scale:L,mesh:B,extras:U,children:Y,name:se}=v,oe={};if(oe.name=se,oe.localMatrix=w||function(de,xe,we,Ce){var Re=xe[0],qe=xe[1],nt=xe[2],Ze=xe[3],ut=Re+Re,xt=qe+qe,bt=nt+nt,Ht=Re*ut,Rt=Re*xt,Vt=Re*bt,Bt=qe*xt,$t=qe*bt,js=nt*bt,Es=Ze*ut,zs=Ze*xt,Hs=Ze*bt,$s=Ce[0],nr=Ce[1],ys=Ce[2];return de[0]=(1-(Bt+js))*$s,de[1]=(Rt+Hs)*$s,de[2]=(Vt-zs)*$s,de[3]=0,de[4]=(Rt-Hs)*nr,de[5]=(1-(Ht+js))*nr,de[6]=($t+Es)*nr,de[7]=0,de[8]=(Vt+zs)*ys,de[9]=($t-Es)*ys,de[10]=(1-(Ht+Bt))*ys,de[11]=0,de[12]=we[0],de[13]=we[1],de[14]=we[2],de[15]=1,de}([],C||[0,0,0,1],I||[0,0,0],L||[1,1,1]),oe.globalMatrix=_(oe.localMatrix),B!==void 0){oe.meshes=f[B];const de=oe.anchor=[0,0];for(const xe of oe.meshes){const{min:we,max:Ce}=xe.aabb;de[0]+=we[0]+Ce[0],de[1]+=we[1]+Ce[1]}de[0]=Math.floor(de[0]/oe.meshes.length/2),de[1]=Math.floor(de[1]/oe.meshes.length/2)}if(U&&(U.id&&(oe.id=U.id),U.lights&&(oe.lights=function(de){if(!de.length)return[];const xe=function(nt){const Ze=atob(nt),ut=new Uint8Array(Ze.length);for(let xt=0;xt1&&w[w.length-1].equals(w[0])&&w.pop();let C=0;for(let L=0;L0&&w.reverse();const I=IM(w.flatMap(L=>[L.x,L.y]),[]);return I.length===0?null:{vertices:w,indices:I}}function V_t(v,u){const f=[],w=[];let C=0;const I=[];for(const L of v){C=f.length;const B=L.vertexArray.float32,U=L.indexArray.uint16;for(let Y=0;Y0&&([w[L+1],w[L+2]]=[w[L+2],w[L+1]])}return{vertices:f,indices:w}}function ove(v){const u=function(U,Y){const se=[],oe=WebGL2RenderingContext;if(U.json.textures)for(const de of U.json.textures){const xe={magFilter:oe.LINEAR,minFilter:oe.NEAREST,wrapS:oe.REPEAT,wrapT:oe.REPEAT};de.sampler!==void 0&&Object.assign(xe,U.json.samplers[de.sampler]),se.push({image:Y[de.source],sampler:xe,uploaded:!1})}return se}(v,v.images),f=function(U,Y){const se=[];for(const oe of U.json.meshes){const de=[];for(const xe of oe.primitives)de.push($_t(xe,U,Y));se.push(de)}return se}(v,u),{scenes:w,scene:C,nodes:I}=v.json,L=w?w[C||0].nodes:[...I.keys()],B=[];for(const U of L)B.push(OPe(I[U],v,f));return function(U,Y,se){const oe={},de=new Set;for(let xe=0;xe0){const xe=Array.from(de.values()).sort((we,Ce)=>we-Ce);for(let we=xe.length-1;we>=0;we--)U.splice(xe[we],1)}}(B,L,v.json.nodes),B}function H_t(v){v.heightmap=new Float32Array(4096),v.heightmap.fill(-1);const u=v.vertexArray.float32,f=v.aabb.min[0]-1,w=v.aabb.min[1]-1,C=q4/(v.aabb.max[0]-f+2),I=q4/(v.aabb.max[1]-w+2);for(let L=0;Lv.heightmap[Y*q4+U]&&(v.heightmap[Y*q4+U]=B)}}function FPe(v,u,f,w,C){f.reserve(f.length+4*v.length),w.reserve(w.length+10*v.length),C.reserve(C.length+10*v.length);let I=w.length;for(const L of v){const B=Math.min(10,Math.max(4,1.3*L.height))*u,U=[-L.normal[1],L.normal[0],0],Y=Math.min(.29,.1*L.width/L.depth),se=L.width-2*L.depth*u*(Y+.01),oe=We([],L.pos,U,se/2),de=We([],L.pos,U,-se/2),xe=[oe[0],oe[1],oe[2]+L.height],we=[de[0],de[1],de[2]+L.height],Ce=We([],L.normal,U,Y);ve(Ce,Ce,B);const Re=We([],L.normal,U,-Y);ve(Re,Re,B),ne(Ce,oe,Ce),ne(Re,de,Re),oe[2]+=.1,de[2]+=.1,w.emplaceBack(Ce[0],Ce[1],Ce[2]),w.emplaceBack(Re[0],Re[1],Re[2]),w.emplaceBack(oe[0],oe[1],oe[2]),w.emplaceBack(de[0],de[1],de[2]),w.emplaceBack(xe[0],xe[1],xe[2]),w.emplaceBack(we[0],we[1],we[2]),w.emplaceBack(oe[0],oe[1],oe[2]),w.emplaceBack(de[0],de[1],de[2]),w.emplaceBack(Ce[0],Ce[1],Ce[2]),w.emplaceBack(Re[0],Re[1],Re[2]);const qe=se/B/2;C.emplaceBack(-qe-Y,-1,qe,.8),C.emplaceBack(qe+Y,-1,qe,.8),C.emplaceBack(-qe,0,qe,1.3),C.emplaceBack(qe,0,qe,1.3),C.emplaceBack(qe+Y,-.8,qe,.7),C.emplaceBack(qe+Y,-.8,qe,.7),C.emplaceBack(0,0,qe,1.3),C.emplaceBack(0,0,qe,1.3),C.emplaceBack(qe+Y,-1.2,qe,.8),C.emplaceBack(qe+Y,-1.2,qe,.8),f.emplaceBack(6+I,4+I,8+I),f.emplaceBack(7+I,9+I,5+I),f.emplaceBack(0+I,1+I,2+I),f.emplaceBack(1+I,3+I,2+I),I+=10}}function G_t(v,u){const f={};f.indexArray=new Yl,f.vertexArray=new Fg,f.colorArray=new Pv,FPe(v,u,f.indexArray,f.vertexArray,f.colorArray);const w={defined:!0};w.emissiveFactor=Mr.black;const C={};return C.baseColorFactor=Mr.white,w.pbrMetallicRoughness=C,f.material=w,f.aabb=new Vi([1/0,1/0,1/0],[-1/0,-1/0,-1/0]),f}const BPe=Qs([{name:"a_pos_3f",components:3,type:"Float32"}]),W_t=Qs([{name:"a_normal_3",components:3,type:"Int16"}]),K_t=Qs([{name:"a_centroid_3",components:3,type:"Int16"}]),zPe=Qs([{name:"a_part_color_emissive",components:2,type:"Uint16"}]),Y_t=Qs([{name:"a_faux_facade_color_emissive",components:2,type:"Uint16"}]),Z_t=Qs([{name:"a_faux_facade_data",components:4,type:"Uint16"}]),X_t=Qs([{name:"a_faux_facade_vertical_range",components:2,type:"Uint16"}]),Q_t=Qs([{name:"a_bloom_attenuation",components:4,type:"Float32"}]),J_t=Qs([{name:"a_flood_light_wall_radius_1i16",components:1,type:"Int16"}]),$Pe=na.types,E$=32767;function ewt(v,u){const f=Sr+u;for(const w of v)for(const C of w)if(C.x<-u||C.x>f||C.y<-u||C.y>f)return!1;return!0}function twt(v){switch(v){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: ${v}`)}}class lve{constructor(){this.layoutVertexArray=new Fg,this.layoutAttenuationArray=new Pv,this.layoutColorArray=new Bg,this.indexArray=new Yl,this.indexArrayForConflation=new Yl,this.segmentsBucket=new No}}class cve{constructor(u){this.layoutFacadePaintArray=null,this.layoutFacadeDataArray=null,this.layoutFacadeVerticalRangeArray=null,this.segmentsBucket=new No,this.entranceBloom=new lve;const f=66560;this.layoutVertexArray=new Fg,this.layoutVertexArray.reserve(f),this.layoutNormalArray=new Ei,this.layoutNormalArray.reserve(f),this.layoutCentroidArray=new Ei,this.layoutCentroidArray.reserve(f),this.layoutColorArray=new Bg,this.layoutColorArray.reserve(f),this.layoutFloodLightDataArray=new SM,this.layoutFloodLightDataArray.reserve(f),this.layoutAOArray=new CM,this.layoutAOArray.reserve(f),this.indexArray=new Yl,this.indexArray.reserve(66560),this.indexArrayForConflation=new Yl,this.segmentsBucket=new No,this.entranceBloom=new lve,u&&(this.layoutFacadePaintArray=new Bg,this.layoutFacadeDataArray=new sN,this.layoutFacadeVerticalRangeArray=new Bg)}reserve(u,f,w){this.layoutVertexArray.reserveForAdditional(u),this.layoutCentroidArray.reserveForAdditional(u),this.layoutFloodLightDataArray.reserveForAdditional(u),this.layoutNormalArray.reserveForAdditional(u),this.layoutAOArray.reserveForAdditional(u),this.layoutColorArray.reserveForAdditional(u),this.indexArray.reserveForAdditional(f),w&&(this.layoutFacadePaintArray.reserveForAdditional(u),this.layoutFacadeDataArray.reserveForAdditional(u),this.layoutFacadeVerticalRangeArray.reserveForAdditional(u))}}class UPe{constructor(u){this.colorBufferUploaded=!1,this.maxHeight=0,this.replacementUpdateTime=0,this.activeReplacements=[],this.footprints=[],this.footprintsVertices=new zw,this.footprintsIndices=new $w,this.footprintsMin=new ds(1/0,1/0),this.footprintsMax=new ds(-1/0,-1/0),this.featuresOnBorder=[],this.buildingWithoutFacade=new cve(!1),this.buildingWithFacade=new cve(!0),this.indexArrayForConflationUploaded=!1,this.featureFootprintLookup=new Map,this.buildingIds=new Set,this.footprintLookup={},this.zoom=u.zoom,this.canonical=u.canonical,this.layers=u.layers,this.layerIds=this.layers.map(f=>f.fqid),this.index=u.index,this.hasPattern=!1,this.worldview=u.worldview,this.lut=u.lut,this.programConfigurations=new Fe(u.layers,{zoom:u.zoom,lut:u.lut}),this.stateDependentLayerIds=this.layers.filter(f=>f.isStateDependent()).map(f=>f.id),this.projection=u.projection,this.groundEffect=new Yye(u),this.groundEffect.groundRadiusArray=new Zi,this.hasAppearances=null}updateFootprints(u,f){const w=new h$([],[],1),C={vertices:[],indices:new Uint32Array(0),grid:w,min:this.footprintsMin,max:this.footprintsMax,buildingIds:this.buildingIds};f.push({footprint:C,id:u})}updateAppearances(u,f,w,C){return{hasLayoutChanges:!1,hasUboChanges:!1}}prepare(){return function(){if(_$!=null||yPe!=null)return null;if(RM!=null)return RM;const u=fetch(Yi());return RM=function(f){let w,C,I,L,B;function U(){w=new Uint8Array(B.buffer),C=new Int16Array(B.buffer),I=new Int32Array(B.buffer),L=new Float32Array(B.buffer)}function Y(){throw new Error("Unexpected BuildingGen error.")}const se=()=>{},oe={a:{a:Y,f:function(de){const xe=w.length,we=Math.max(de>>>0,Math.ceil(1.2*xe)),Ce=Math.ceil((we-xe)/65536);try{return B.grow(Ce),U(),!0}catch{return!1}},g:Y,b:se,c:se,d:se,e:se}};return(WebAssembly.instantiateStreaming?WebAssembly.instantiateStreaming(f,oe):f.then(de=>de.arrayBuffer()).then(de=>WebAssembly.instantiate(de,oe))).then(de=>{const xe=de.instance.exports;return(0,xe.g)(),B=xe.f,U(),new k_t({setStyle:xe.h,setAOOptions:xe.i,setMetricOptions:xe.j,setStructuralOptions:xe.k,setFacadeOptions:xe.l,setFauxFacadeOptions:xe.m,setFacadeClassifierOptions:xe.n,addFeature:xe.o,addFacade:xe.p,generateMesh:xe.q,getLastError:xe.r,getOuterRingLength:xe.s,getMeshCount:xe.t,getPositionsPtr:xe.u,getPositionsLength:xe.v,getNormalsPtr:xe.w,getNormalsLength:xe.x,getAOPtr:xe.y,getAOLength:xe.z,getUVPtr:xe.A,getUVLength:xe.B,getFauxFacadePtr:xe.C,getFauxFacadeLength:xe.D,getIndicesPtr:xe.E,getIndicesLength:xe.F,getBuildingPart:xe.G,getRingCount:xe.H,getRingPtr:xe.I,getRingLength:xe.J,malloc:xe.K,free:xe.L,heapU8:w,heap16:C,heap32:I,heapF32:L})})}(u).then(f=>(RM=null,_$=f,_$)).catch(f=>{Gr("Could not load building-gen"),RM=null,yPe=f instanceof Error?f:new Error("Unknown error")}),RM}()}populate(u,f,w,C){const I=S_t();if(!I)return;const L=Js(w);this.tileToMeter=L,this.brightness=f.brightness,I.setStyle({normalScale:[1,-1,L],tileToMeters:L}),I.setAOOptions(!1,.3),I.setMetricOptions(!1,16),I.setStructuralOptions(!0),I.setFacadeClassifierOptions(3);const B=new Map,U=new Map;let Y=0;for(const{feature:qe}of u){if($Pe[qe.type]!=="LineString"){B.set(qe.id,qe.properties.source_id);continue}const nt=this.layers[0]._featureFilter.needGeometry;if(nt&&!this.layers[0]._featureFilter.filter(new wa(this.zoom),qe,w))continue;const Ze=Oa(qe,nt);if(!nt&&!this.layers[0]._featureFilter.filter(new wa(this.zoom),Ze,w))continue;const ut=nt?Ze.geometry:Ln(qe,w,C),xt=[];for(const Vt of ut)for(const Bt of Vt)xt.push(Bt.x),xt.push(Bt.y);const bt={coordinates:xt,crossPerc:qe.properties.cross_perc,distanceToRoad:qe.properties.distance_to_road,entrances:qe.properties.entrances,sourceId:0},Ht=qe.properties.source_id;let Rt=U.get(Ht);Rt||(Rt=[],U.set(Ht,Rt)),Rt.push(bt),++Y}this.maxHeight=0;const se=new Array,oe=new Set,de=qe=>{qe!=null&&oe.add(qe)},xe=(qe,nt)=>{qe!=null&&se.push({buildingId:qe,footprintIndex:nt})},we=64*(u.length-Y),Ce=we/2;this.buildingWithFacade.reserve(we,Ce,!0),this.buildingWithoutFacade.reserve(2*we,2*Ce,!1),this.footprintsIndices.reserve(16*(u.length-Y)),this.footprintsVertices.reserve(8*(u.length-Y));for(const{feature:qe,id:nt,index:Ze,sourceLayerIndex:ut}of u){if($Pe[qe.type]==="LineString")continue;const xt=this.layers[0]._featureFilter.needGeometry;if(xt&&!this.layers[0]._featureFilter.filter(new wa(this.zoom),qe,w))continue;let bt=null;if(qe.properties&&qe.properties.hasOwnProperty("building_id")&&(bt=Number(qe.properties.building_id),oe.has(bt)))continue;const Ht=Oa(qe,xt);if(!xt&&!this.layers[0]._featureFilter.filter(new wa(this.zoom),Ht,w))continue;const Rt=xt?Ht.geometry:Ln(qe,w,C),Vt=ID(Rt,500);let Bt=!1;for(const Za of Vt)if(Za.length!==1){Bt=!0;break}if(Bt){de(bt);continue}if(!ewt(Rt,163)){de(bt);continue}const $t=this.layers[0],js=twt($t.layout.get("building-roof-shape").evaluate(qe,{},w)),Es=$t.layout.get("building-base").evaluate(qe,{},w),zs=$t.layout.get("building-height").evaluate(qe,{},w),Hs=$t.layout.get("building-flood-light-ground-radius").evaluate(qe,{},w),$s=$t.paint.get("building-ambient-occlusion-intensity"),nr=Hs/this.tileToMeter;qe.properties["building-part"]="roof";const ys=$t.paint.get("building-color").evaluate(qe,{},this.canonical).toPremultipliedRenderColor(this.lut),qs=$t.paint.get("building-emissive-strength").evaluate(qe,{},this.canonical);qe.properties["building-part"]="wall";const Zs=$t.paint.get("building-color").evaluate(qe,{},this.canonical).toPremultipliedRenderColor(this.lut),ir=$t.paint.get("building-emissive-strength").evaluate(qe,{},this.canonical);qe.properties["building-part"]="window";const pr=$t.paint.get("building-color").evaluate(qe,{},this.canonical).toPremultipliedRenderColor(this.lut),Zr=$t.paint.get("building-emissive-strength").evaluate(qe,{},this.canonical);qe.properties["building-part"]="door";const Nr=$t.paint.get("building-color").evaluate(qe,{},this.canonical).toPremultipliedRenderColor(this.lut),jr=$t.paint.get("building-emissive-strength").evaluate(qe,{},this.canonical);let gr=$t.layout.get("building-flood-light-wall-radius").evaluate(qe,{},w);gr=He(gr,0,2048);const qr=gr/2048*E$,tn=B.get(nt),In=U.get(tn)||[],cn=In.length!==0&&$t.layout.get("building-facade").evaluate(qe,{},w);I.setFacadeOptions(4,!0),I.setFauxFacadeOptions(cn,!1,1);let fa=0,xi=0,pa=0,vi=0,Fa=0,Il=0,$i=0,ki=0,Co=0,vl=0,Fd=0;if(cn){let Za=Math.round($t.layout.get("building-facade-floors").evaluate(qe,{},w));if(Es===0){Za=Math.max(1,Za-(In.length>0?1:0));let Ql=4;if(zs>100){const xd=[10,13,15];Ql=xd[qe.id?qe.id%xd.length:0]}else zs<=10&&(Ql=3);I.setFacadeOptions(Ql,!0),Fa=(zs<15?1.3:1.61803)*Ql/L}else Fa=Es/L;Il=zs/L,Fa=Math.min(Fa,Il),pa=$t.layout.get("building-facade-unit-width").evaluate(qe,{},w)/L,vi=(Il-Fa)/Za,I.setFauxFacadeOptions(!0,!0,pa);const nu=$t.layout.get("building-facade-window").evaluate(qe,{},w);fa=nu[0],xi=nu[1],$i=Math.floor(65535*Math.min(1,Fa/Sr)),ki=Math.floor(65535*Math.min(1,Il/Sr)),Co=Math.floor(255*fa)<<8|Math.floor(255*xi),vl=Math.floor(65535*Math.min(1,pa/Sr)),Fd=Math.floor(65535*Math.min(1,vi/Sr))}const bl=Array(Vt.length),Zl={x:1/0,y:1/0},Nc={x:-1/0,y:-1/0},Xl={x:0,y:0};let nh=0;for(let Za=0;Za0){const Ql=[],xd=Array(nu.length+1);xd[0]=0;for(let Ox=0;OxSr||Zl.y<0||Nc.y>Sr)&&this.featuresOnBorder.push({featureId:qe.id,footprintIndex:this.footprints.length});{const Za=IM(Xw,null,2);this.footprintsIndices.resize(this.footprintsIndices.length+Za.length),this.footprintsIndices.uint16.set(Za,ZM),this.buildingIds.add(bt??qe.id),this.footprintsMin.x=Math.min(this.footprintsMin.x,Dx.x),this.footprintsMin.y=Math.min(this.footprintsMin.y,Dx.y),this.footprintsMax.x=Math.max(this.footprintsMax.x,Rx.x),this.footprintsMax.y=Math.max(this.footprintsMax.y,Rx.y);const nu={footprintVertexOffset:Zw,footprintVertexLength:this.footprintsVertices.length-Zw,footprintIndexOffset:ZM,footprintIndexLength:this.footprintsIndices.length-ZM,min:Dx,max:Rx,hiddenFlags:0,indicesOffset:nU,indicesLength:Jve,bloomIndicesOffset:ah,bloomIndicesLength:Pl,groundEffectVertexOffset:X4,groundEffectVertexLength:XM,hasFauxFacade:cn,height:YM,promoteId:nt,feature:Ht,parts:su,buildingBloom:$m},Ql=this.footprints.length;qe.id!==void 0&&this.featureFootprintLookup.set(qe.id,Ql),xe(bt,Ql),this.footprints.push(nu)}this.programConfigurations.populatePaintArrays(Va.layoutVertexArray.length,qe,Ze,{},f.availableImages,w,f.brightness),this.groundEffect.addPaintPropertiesData(qe,Ze,{},f.availableImages,w,f.brightness),f.featureIndex.insert(qe,Rt,Ze,ut,this.index,Qh)}se.forEach(({buildingId:qe,footprintIndex:nt})=>{oe.has(qe)&&(this.footprints[nt].hiddenFlags|=4)});const Re=new Set;this.buildingIds.forEach((qe,nt,Ze)=>{oe.has(qe)||Re.add(qe)}),this.buildingIds=Re,this.groundEffect.prepareBorderSegments()}update(u,f,w,C,I,L,B){this.programConfigurations.updatePaintArrays(u,f,I,w,C,L,B),this.groundEffect.update(u,f,I,w,C,L,B),this.evaluate(this.layers[0],u),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(u){const f=w=>{w.layoutVertexBuffer=u.createVertexBuffer(w.layoutVertexArray,BPe.members),w.layoutNormalBuffer=u.createVertexBuffer(w.layoutNormalArray,W_t.members),w.layoutCentroidBuffer=u.createVertexBuffer(w.layoutCentroidArray,K_t.members),w.layoutFloodLightDataBuffer=u.createVertexBuffer(w.layoutFloodLightDataArray,J_t.members),w.layoutFacadeDataArray&&w.layoutFacadeDataArray.length&&(w.layoutFacadeDataBuffer=u.createVertexBuffer(w.layoutFacadeDataArray,Z_t.members)),w.layoutFacadeVerticalRangeArray&&w.layoutFacadeVerticalRangeArray.length&&(w.layoutFacadeVerticalRangeBuffer=u.createVertexBuffer(w.layoutFacadeVerticalRangeArray,X_t.members)),w.entranceBloom.layoutVertexArray.length&&(w.entranceBloom.layoutVertexBuffer=u.createVertexBuffer(w.entranceBloom.layoutVertexArray,BPe.members),w.entranceBloom.layoutAttenuationBuffer=u.createVertexBuffer(w.entranceBloom.layoutAttenuationArray,Q_t.members)),this.uploadUpdatedColorBuffer(u),this.uploadUpdatedIndexBuffer(u)};this.uploaded||(f(this.buildingWithoutFacade),f(this.buildingWithFacade),this.groundEffect.upload(u)),this.groundEffect.uploadPaintProperties(u),this.programConfigurations.upload(u),this.uploaded=!0}destroy(){const u=f=>{f.layoutVertexBuffer&&(f.layoutVertexBuffer.destroy(),f.layoutNormalBuffer.destroy(),f.layoutColorBuffer.destroy(),f.segmentsBucket.destroy(),f.indexBuffer&&f.indexBuffer.destroy(),f.entranceBloom.layoutVertexBuffer&&(f.entranceBloom.layoutVertexBuffer.destroy(),f.entranceBloom.layoutColorBuffer.destroy(),f.entranceBloom.layoutAttenuationBuffer.destroy(),f.entranceBloom.indexBuffer.destroy(),f.entranceBloom.segmentsBucket.destroy()))};u(this.buildingWithoutFacade),u(this.buildingWithFacade),this.groundEffect.destroy(),this.programConfigurations.destroy()}updateFootprintHiddenFlags(u,f,w=!0){let C=!1;const I=w?f:0,L=0|(w?-1:~f);this.groundEffect.hiddenByLandmarkVertexArray.length===0&&this.groundEffect.hiddenByLandmarkVertexArray.resize(this.groundEffect.vertexArray.length);for(const B of u){const U=this.footprints[B],Y=U.hiddenFlags&L|I;U.hiddenFlags!==Y&&(U.hiddenFlags=Y,C=!0,this.groundEffect.updateHiddenByLandmarkRange(U.groundEffectVertexOffset,U.groundEffectVertexLength,U.hiddenFlags!==0))}return C&&(this.indexArrayForConflationUploaded=!1),C}uploadUpdatedIndexBuffer(u){if(this.groundEffect.uploadHiddenByLandmark(u),this.indexArrayForConflationUploaded)return;const f=C=>{C.indexArray.length!==0&&(C.indexArrayForConflation.resize(C.indexArray.length),C.indexArrayForConflation.uint16.set(C.indexArray.uint16),C.entranceBloom.indexArrayForConflation.resize(C.entranceBloom.indexArray.length),C.entranceBloom.indexArrayForConflation.uint16.set(C.entranceBloom.indexArray.uint16))};f(this.buildingWithoutFacade),f(this.buildingWithFacade);for(const C of this.footprints){const I=C.hasFauxFacade?this.buildingWithFacade:this.buildingWithoutFacade,L=C.indicesOffset+C.indicesLength;if(C.hiddenFlags!==0){for(let U=C.indicesOffset;U{C.indexArray.length!==0&&(C.indexBuffer?C.indexBuffer.updateData(C.indexArrayForConflation):C.indexBuffer=u.createIndexBuffer(C.indexArrayForConflation,!0),C.entranceBloom.indexBuffer?C.entranceBloom.indexBuffer.updateData(C.entranceBloom.indexArrayForConflation):C.entranceBloom.indexBuffer=u.createIndexBuffer(C.entranceBloom.indexArrayForConflation,!0))};w(this.buildingWithoutFacade),w(this.buildingWithFacade),this.indexArrayForConflationUploaded=!0}uploadUpdatedColorBuffer(u){const f=w=>{w.layoutColorBuffer?w.layoutColorBuffer.updateData(w.layoutColorArray):w.layoutColorBuffer=u.createVertexBuffer(w.layoutColorArray,zPe.members,!0),w.layoutFacadePaintArray&&(w.layoutFacadePaintBuffer?w.layoutFacadePaintBuffer.updateData(w.layoutFacadePaintArray):w.layoutFacadePaintBuffer=u.createVertexBuffer(w.layoutFacadePaintArray,Y_t.members,!0)),w.entranceBloom.layoutColorBuffer?w.entranceBloom.layoutColorBuffer.updateData(w.entranceBloom.layoutColorArray):w.entranceBloom.layoutColorBuffer=u.createVertexBuffer(w.entranceBloom.layoutColorArray,zPe.members,!0)};f(this.buildingWithoutFacade),f(this.buildingWithFacade),this.colorBufferUploaded=!0}evaluate(u,f){const w=u.paint.get("building-ambient-occlusion-intensity");for(const C of this.footprints){if(4&C.hiddenFlags)continue;const I=f[C.promoteId],L=C.feature;L.properties["building-part"]="roof";const B=u.paint.get("building-color").evaluate(L,I,this.canonical).toPremultipliedRenderColor(this.lut),U=u.paint.get("building-emissive-strength").evaluate(L,I,this.canonical);L.properties["building-part"]="wall";const Y=u.paint.get("building-color").evaluate(L,I,this.canonical).toPremultipliedRenderColor(this.lut),se=u.paint.get("building-emissive-strength").evaluate(L,I,this.canonical);L.properties["building-part"]="window";const oe=u.paint.get("building-color").evaluate(L,I,this.canonical).toPremultipliedRenderColor(this.lut),de=u.paint.get("building-emissive-strength").evaluate(L,I,this.canonical);L.properties["building-part"]="door";const xe=u.paint.get("building-color").evaluate(L,I,this.canonical).toPremultipliedRenderColor(this.lut),we=u.paint.get("building-emissive-strength").evaluate(L,I,this.canonical),Ce=C.hasFauxFacade?this.buildingWithFacade:this.buildingWithoutFacade;for(const qe of C.parts){let nt,Ze=B;qe.part===1?(Ze=B,nt=U):qe.part===0?(Ze=Y,nt=se):qe.part===2?(Ze=oe,nt=de):qe.part===3&&(Ze=xe,nt=we),nt=He(nt,0,1);for(let ut=0;utL.max.x||U.max.xL.max.y||U.max.yB.max.x||B.min.x>u||f>B.max.y||B.min.y>f||B.height<=w||swt(L,this.footprintsVertices.float32.subarray(2*B.footprintVertexOffset,2*(B.footprintVertexOffset+B.footprintVertexLength)),this.footprintsIndices.uint16.subarray(B.footprintIndexOffset,B.footprintIndexOffset+B.footprintIndexLength))&&(w=B.height,this.footprintLookup[I]=B,C=B.hiddenFlags!==0);if(w!==Number.NEGATIVE_INFINITY)return{height:w,hidden:C};this.footprintLookup[I]=void 0}}function swt(v,u,f){for(let w=0;w1&&(U=u[++B]);const se=Math.abs(Y-U.left),oe=Math.abs(Y-U.right),de=Math.min(se,oe);let xe;const we=I/w*(C+1);if(U.isDash){const Ce=C-Math.abs(we);xe=Math.sqrt(de*de+Ce*Ce)}else xe=C-Math.sqrt(de*de+we*we);this.image.data[L+Y]=Math.max(0,Math.min(255,xe+128))}}}addRegularDash(u,f){for(let U=u.length-1;U>=0;--U){const Y=u[U],se=u[U+1];Y.zeroLength?u.splice(U,1):se&&se.isDash===Y.isDash&&(se.left=Y.left,u.splice(U,1))}const w=u[0],C=u[u.length-1];w.isDash===C.isDash&&(w.left=C.left-this.width,C.right=w.right+this.width);const I=this.width*this.nextRow;let L=0,B=u[L];for(let U=0;U1&&(B=u[++L]);const Y=Math.abs(U-B.left),se=Math.abs(U-B.right),oe=Math.min(Y,se);this.image.data[I+U]=Math.max(0,Math.min(255,(B.isDash?oe:-oe)+f+128))}}addDash(u,f){const w=this.getKey(u,f);if(this.positions[w])return this.positions[w];const C=f==="round",I=C?7:0,L=2*I+1;if(this.nextRow+L>this.height)return Gr("LineAtlas out of space"),null;u.length===0&&u.push(1);let B=0;for(let oe=0;oef.fqid),this.index=u.index,this.projection=u.projection,this.hasPattern=!1,this.hasCrossSlope=!1,this.patternFeatures=[],this.lineClipsArray=[],this.gradients={},this.layers.forEach(f=>{this.gradients[f.id]={}}),this.layoutVertexArray=new E4,this.layoutVertexArray2=new Fg,this.patternVertexArray=new Fg,this.indexArray=new Yl,this.programConfigurations=new Fe(u.layers,{zoom:u.zoom,lut:u.lut}),this.segments=new No,this.maxLineLength=0,this.zOffsetVertexArray=new Fg,this.elevationGroundScaleVertexArray=new Zi,this.stateDependentLayerIds=this.layers.filter(f=>f.isStateDependent()).map(f=>f.id),this.tessellationStep=u.tessellationStep?u.tessellationStep:128,this.worldview=u.worldview,this.hasAppearances=null}updateFootprints(u,f){}updateAppearances(u,f,w,C){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(u,f,w,C){this.hasPattern=Iye("line",this.layers,this.pixelRatio,f);const I=this.layers[0].layout.get("line-sort-key");this.tileToMeter=Js(w);const L=this.layers[0].layout.get("line-elevation-reference");if(L==="hd-road-markup")this.elevationType="road";else{const de=this.layers[0].layout.get("line-z-offset"),xe=de.isConstant()&&!de.constantOr(0);this.elevationType=L!=="sea"&&L!=="ground"&&xe?"none":"offset",this.elevationType==="offset"&&L==="none"&&Gr(`line-elevation-reference: ground is used for the layer ${this.layerIds[0]} because non-zero line-z-offset value was found.`),this.isSeaLevelReference=L==="sea"}const B=this.layers[0].layout.get("line-cross-slope");this.hasCrossSlope=this.elevationType==="offset"&&B!==void 0;const U=[];for(const{feature:de,id:xe,index:we,sourceLayerIndex:Ce}of u){const Re=this.layers[0]._featureFilter.needGeometry,qe=Oa(de,Re);if(!this.layers[0]._featureFilter.filter(new wa(this.zoom,{worldview:this.worldview,activeFloors:f.activeFloors}),qe,w))continue;const nt=I?I.evaluate(qe,{},w):void 0,Ze={id:xe,properties:de.properties,type:de.type,sourceLayerIndex:Ce,index:we,geometry:Re?qe.geometry:Ln(de,w,C),patterns:{},sortKey:nt};U.push(Ze)}I&&U.sort((de,xe)=>de.sortKey-xe.sortKey);const{lineAtlas:Y,featureIndex:se}=f,oe=this.addConstantDashes(Y);for(const de of U){const{geometry:xe,index:we,sourceLayerIndex:Ce}=de;if(oe&&this.addFeatureDashes(de,Y),this.hasPattern){const Re=Pye("line",this.layers,de,this.zoom,this.pixelRatio,f);this.patternFeatures.push(Re)}else this.addFeature(de,xe,we,w,Y.positions,f.availableImages,f.brightness,f.elevationFeatures);se.insert(u[we].feature,xe,we,Ce,this.index)}}addConstantDashes(u){let f=!1;for(const w of this.layers){const C=w.paint.get("line-dasharray").value,I=w.layout.get("line-cap").value;if(C.kind!=="constant"||I.kind!=="constant")f=!0;else{const L=I.value,B=C.value;if(!B)continue;u.addDash(B,L)}}return f}addFeatureDashes(u,f){const w=this.zoom;for(const C of this.layers){const I=C.paint.get("line-dasharray").value,L=C.layout.get("line-cap").value;if(I.kind==="constant"&&L.kind==="constant")continue;let B,U;if(I.kind==="constant"){if(B=I.value,!B)continue}else B=I.evaluate({zoom:w},u);U=L.kind==="constant"?L.value:L.evaluate({zoom:w},u),f.addDash(B,U),u.patterns[C.id]=[f.getKey(B,U)]}}update(u,f,w,C,I,L,B,U,Y){this.programConfigurations.updatePaintArrays(u,f,I,w,C,L,B,Y)}addFeatures(u,f,w,C,I,L){for(const B of this.patternFeatures)this.addFeature(B,B.geometry,B.index,f,w,C,L,u.elevationFeatures)}isEmpty(){return this.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload}upload(u){this.uploaded||(this.layoutVertexArray2.length!==0&&(this.layoutVertexBuffer2=u.createVertexBuffer(this.layoutVertexArray2,cwt)),this.patternVertexArray.length!==0&&(this.patternVertexBuffer=u.createVertexBuffer(this.patternVertexArray,uwt)),!this.zOffsetVertexBuffer&&this.zOffsetVertexArray.length>0&&(this.zOffsetVertexBuffer=u.createVertexBuffer(this.zOffsetVertexArray,awt.members,!0)),!this.elevationGroundScaleVertexBuffer&&this.elevationGroundScaleVertexArray.length>0&&(this.elevationGroundScaleVertexBuffer=u.createVertexBuffer(this.elevationGroundScaleVertexArray,iwt.members,!0)),this.layoutVertexBuffer=u.createVertexBuffer(this.layoutVertexArray,owt),this.indexBuffer=u.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(u),this.uploaded=!0}destroy(){this.layoutVertexBuffer&&(this.zOffsetVertexBuffer&&this.zOffsetVertexBuffer.destroy(),this.elevationGroundScaleVertexBuffer&&this.elevationGroundScaleVertexBuffer.destroy(),this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy())}lineFeatureClips(u,f){let w,C;if(f&&f>0?(w=`mapbox_clip_start_${f}`,C=`mapbox_clip_end_${f}`):(w="mapbox_clip_start",C="mapbox_clip_end"),u.properties&&u.properties.hasOwnProperty(w)&&u.properties.hasOwnProperty(C))return{start:+u.properties[w],end:+u.properties[C]}}addFeature(u,f,w,C,I,L,B,U){const Y=this.layers[0].layout,se=Y.get("line-join").evaluate(u,{}),oe=Y.get("line-cap").evaluate(u,{}),de=Y.get("line-miter-limit"),xe=Y.get("line-round-limit");this.lineClips=this.lineFeatureClips(u),this.lineFeature=u;const we=!(!u.properties||!u.properties.hasOwnProperty("mapbox_line_metrics"))&&u.properties.mapbox_line_metrics;this.zOffsetValue=Y.get("line-z-offset").value;const Ce=this.layers[0].paint.get("line-width").value;if(Ce.kind!=="constant"&&Ce.isLineProgressConstant===!1&&(this.variableWidthValue=Ce),this.isSeaLevelReference){const Re=Y.get("line-elevation-ground-scale").value;Re.kind==="constant"&&Re.value===0||(this.elevationGroundScaleValue=Re)}if(this.elevationType==="road"){const Re=this.layoutVertexArray.length;if(!this.addElevatedRoadFeature(u,f,C,U,se,oe,de,xe)){const[qe,nt]=this.clipRuntimeLinesToTile(f,1);for(let Ze=0;Ze0?xt.parentIndex:null)}this.fillNonElevatedRoadSegment(Re)}}else for(let Re=0;Re0?Re:null);this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,u,w,I,L,C,B,void 0,this.worldview)}computeSegNextDir(u,f){return u.nextPoint.sub(f.at(-2)).unit()}computeSegPrevDir(u,f){return f[1].sub(u.prevPoint).unit()}clipLinesToTile(u,f){return b$(u,-f,-f,Sr+f,Sr+f)}clipRuntimeLinesToTile(u,f){const w=[];return[b$(u,-f,-f,Sr+f,Sr+f,w),w]}addElevatedRoadFeature(u,f,w,C,I,L,B,U){const Y=[],se=Eo.getElevationFeature(u,C);if(se){const oe=this.clipLinesToTile(f,1),de=this.prepareElevatedLines(oe,se,w);for(const xe of de)Y.push({geometry:xe,elevation:se,elevationTileID:w,segment:{progress:{min:0,max:1},nextDir:void 0,prevDir:void 0}})}if(Y.length===0)return!1;for(const oe of Y){const de=this.layoutVertexArray.length;this.addLine(oe.geometry,u,w,I,L,B,U);const xe=new Do(w,oe.elevationTileID);if(oe.elevation)for(let we=de;we>1,this.layoutVertexArray.int16[6*we+1]>>1),Re=xe.pointElevation(Ce,oe.elevation,.05);this.updateHeightRange(Re),this.zOffsetVertexArray.emplaceBack(Re,0,0)}else this.fillNonElevatedRoadSegment(de)}return!0}prepareElevatedLines(u,f,w){if(f.constantHeight!=null)return u;const C=[],I=1/Js(w);for(const L of u)N_t(L,new Wp(f,I),0,C);return C}fillNonElevatedRoadSegment(u){for(let f=u;f0,de=U&&U.progress.max<1;if(this.lineClips){let Vt={min:this.lineClips.start,max:this.lineClips.end},Bt=1;if(U){const Es=this.lineClips.end-this.lineClips.start;Vt=function(zs,Hs,$s){return{min:co(zs.min,Hs,$s),max:co(zs.max,Hs,$s)}}(U.progress,{min:0,max:1},Vt),Es>0&&(Bt=(Vt.max-Vt.min)/Es)}const $t=+f.properties.mapbox_clip_feature_len,js=+f.properties.mapbox_clip_seg_len;if(Number.isNaN($t)||Number.isNaN(js)){for(let zs=0;zs=2&&u[we-1].equals(u[we-2]);)we--;let Ce=0;for(;Ce0,qs=this.overscaling<=16?122880/(512*this.overscaling):0;if(Bt&&$t==="round"){if(HsL&&($t="bevel"),$t==="bevel"&&(Hs>2&&($t="flipbevel"),Hs2*qs){const pr=qe.sub(qe.sub(nt)._mult(qs/Zs)._round());this.updateDistance(nt,pr),this.addCurrentVertex(pr,ut,0,0,Re,Rt),nt=pr}this.updateDistance(nt,qe),Es._mult(Hs),this.addCurrentVertex(qe,Es,0,0,Re,Rt);const ir=qe.dist(Ze);if(ir>2*qs){const pr=qe.add(Ze.sub(qe)._mult(qs/ir)._round());this.updateDistance(qe,pr),this.addCurrentVertex(pr,xt,0,0,Re,Rt),qe=pr}}else Es._mult(Hs),this.addCurrentVertex(qe,Es,0,0,Re,Rt);else if($t==="flipbevel"){if(Hs>100)Es=xt.mult(-1);else{const Zs=Hs*ut.add(xt).mag()/ut.sub(xt).mag();Es._perp()._mult(Zs*(ys?-1:1))}this.addCurrentVertex(qe,Es,0,0,Re,Rt),this.addCurrentVertex(qe,Es.mult(-1),0,0,Re,Rt)}else if($t==="bevel"||$t==="fakeround"){const Zs=qe.dist(nt);let ir=1;if(this.elevationType==="offset"&&$t==="bevel"&&this.currentLineJoinType!=="round"&&!this.patternJoinNone&&Rt!=null&&nt&&Ze){const qr=4*qs;Zs1){this.lineSoFar=u.w;const Ce=(f.x-u.x)/oe,Re=(f.y-u.y)/oe,qe=(f.z-u.z)/oe,nt=(f.w-u.w)/oe,Ze=f.x-u.x,ut=f.y-u.y,xt=Math.sqrt(Ze*Ze+ut*ut);if(xt===0)return;const bt=-ut/xt,Ht=Ze/xt,Rt=bt,Vt=Ht,Bt=-bt,$t=-Ht;for(let js=1;js=0&&this.e2>=0&&(this.indexArray.emplaceBack(this.e1,this.e2,se),U.primitiveLength++),L?this.e2=se:this.e1=se,Y!=null&&this.zOffsetVertexArray.emplaceBack(Y.zOffset,Y.variableWidth,Y.variableWidth),this.elevationGroundScaleValue){const oe=Y?Y.elevationGroundScale:this.evaluateElevationGroundScale();this.elevationGroundScaleVertexArray.emplaceBack(oe)}}updateScaledDistance(){this.lineClips?(this.scaledDistance=this.distance/this.totalDistance,this.lineSoFar=this.totalFeatureLength*this.lineClips.start+this.distance):this.lineSoFar=this.distance}updateDistance(u,f){this.prevDistance=this.distance,this.distance+=u.dist(f),this.updateScaledDistance()}}function dve(v,u,f){return v.xf||v.yf}let GPe,WPe;function KPe(v,u,f){return u*(Sr/(v.tileSize*Math.pow(2,f-v.tileID.overscaledZ)))}Pr(A$,"LineBucket",{omit:["layers","patternFeatures","currentVertex","currentVertexIsOutside"]});const YPe=(v,u,f)=>(1-f)*v+f*u;function ZPe(v,u){return 1/KPe(v,1,u.tileZoom)}function XPe(v,u,f,w){return v.translatePosMatrix(w||u.tileID.projMatrix,u,f.paint.get("line-translate"),f.paint.get("line-translate-anchor"))}const QPe=v=>{const u=[];JPe(v)&&u.push("RENDER_LINE_DASH"),v.paint.get("line-gradient")&&u.push("RENDER_LINE_GRADIENT"),v.paint.get("line-blend-mode")==="multiply"&&u.push("LINE_BLEND_MULTIPLY");const f=v.paint.get("line-trim-offset");f[0]===0&&f[1]===0||u.push("RENDER_LINE_TRIM_OFFSET"),v.paint.get("line-border-width").constantOr(1)!==0&&u.push("RENDER_LINE_BORDER");const w=v.layout.get("line-join").constantOr("miter")==="none",C=!!v.paint.get("line-pattern").constantOr(1);return w&&C&&u.push("LINE_JOIN_NONE"),u};function JPe(v){const u=v.paint.get("line-dasharray").value;return u.kind!=="constant"||u.value}let uve;const eLe=()=>uve||(uve={layout:GPe||(GPe=new Lo({"line-cap":new dr(es.layout_line["line-cap"]),"line-join":new dr(es.layout_line["line-join"]),"line-miter-limit":new ur(es.layout_line["line-miter-limit"]),"line-round-limit":new ur(es.layout_line["line-round-limit"]),"line-sort-key":new dr(es.layout_line["line-sort-key"]),"line-z-offset":new dr(es.layout_line["line-z-offset"]),"line-elevation-reference":new ur(es.layout_line["line-elevation-reference"]),"line-cross-slope":new ur(es.layout_line["line-cross-slope"]),visibility:new ur(es.layout_line.visibility),"line-width-unit":new ur(es.layout_line["line-width-unit"]),"line-elevation-ground-scale":new dr(es.layout_line["line-elevation-ground-scale"])})),paint:WPe||(WPe=new Lo({"line-opacity":new dr(es.paint_line["line-opacity"]),"line-color":new dr(es.paint_line["line-color"]),"line-translate":new ur(es.paint_line["line-translate"]),"line-translate-anchor":new ur(es.paint_line["line-translate-anchor"]),"line-width":new dr(es.paint_line["line-width"]),"line-gap-width":new dr(es.paint_line["line-gap-width"]),"line-offset":new dr(es.paint_line["line-offset"]),"line-blur":new dr(es.paint_line["line-blur"]),"line-dasharray":new dr(es.paint_line["line-dasharray"]),"line-pattern":new dr(es.paint_line["line-pattern"]),"line-pattern-cross-fade":new ur(es.paint_line["line-pattern-cross-fade"]),"line-gradient":new wf(es.paint_line["line-gradient"]),"line-trim-offset":new ur(es.paint_line["line-trim-offset"]),"line-trim-fade-range":new ur(es.paint_line["line-trim-fade-range"]),"line-trim-color":new ur(es.paint_line["line-trim-color"]),"line-emissive-strength":new dr(es.paint_line["line-emissive-strength"]),"line-border-width":new dr(es.paint_line["line-border-width"]),"line-border-color":new dr(es.paint_line["line-border-color"]),"line-occlusion-opacity":new ur(es.paint_line["line-occlusion-opacity"]),"line-blend-mode":new ur(es.paint_line["line-blend-mode"]),"line-color-use-theme":new dr({type:"string",default:"default","property-type":"data-driven"}),"line-gradient-use-theme":new dr({type:"string",default:"default","property-type":"data-driven"}),"line-trim-color-use-theme":new dr({type:"string",default:"default","property-type":"data-driven"}),"line-border-color-use-theme":new dr({type:"string",default:"default","property-type":"data-driven"})}))},uve);class pwt extends dr{possiblyEvaluate(u,f){return f=new wa(Math.floor(f.zoom),{now:f.now,fadeDuration:f.fadeDuration,transition:f.transition,worldview:f.worldview}),super.possiblyEvaluate(u,f)}evaluate(u,f,w,C){return f=Object.assign({},f,{zoom:Math.floor(f.zoom)}),super.evaluate(u,f,w,C)}}let VD;function tLe(v,u){return u>0?u+2*v:v}const gwt=Qs([{name:"a_pos_offset",components:4,type:"Int16"},{name:"a_tex_size",components:4,type:"Uint16"},{name:"a_pixeloffset",components:4,type:"Int16"}],4),xwt=Qs([{name:"a_globe_anchor",components:3,type:"Int16"},{name:"a_globe_normal",components:3,type:"Float32"}],4),ywt=Qs([{name:"a_projected_pos",components:4,type:"Float32"}],4);Qs([{name:"a_fade_opacity",components:1,type:"Uint32"}],4);const vwt=Qs([{name:"a_auto_z_offset",components:1,type:"Float32"}],4),bwt=Qs([{name:"a_feature_index",components:1,type:"Float32"}],4),_wt=Qs([{name:"a_x_axis",components:3,type:"Float32"},{name:"a_y_axis",components:3,type:"Float32"}]),wwt=Qs([{name:"a_texb",components:2,type:"Uint16"}]),jwt=Qs([{name:"a_placed",components:2,type:"Uint8"},{name:"a_shift",components:2,type:"Float32"},{name:"a_elevation_from_sea",components:2,type:"Float32"}]),Nwt=Qs([{name:"a_size_scale",components:1,type:"Float32"},{name:"a_padding",components:2,type:"Float32"},{name:"a_auto_z_offset",components:1,type:"Float32"}]);Qs([{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 sLe=Qs([{name:"a_pos",components:3,type:"Int16"},{name:"a_anchor_pos",components:2,type:"Int16"},{name:"a_extrude",components:2,type:"Int16"}],4),kwt=Qs([{name:"a_pos_2f",components:2,type:"Float32"},{name:"a_radius",components:1,type:"Float32"},{name:"a_flags",components:2,type:"Int16"}],4);Qs([{name:"triangle",components:3,type:"Uint16"}]),Qs([{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"}]),Qs([{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"}]),Qs([{type:"Float32",name:"offsetX"}]),Qs([{type:"Int16",name:"x"},{type:"Int16",name:"y"}]);const hve=class uue{constructor(u=null,f=0,w=4096){this.batchIndex=f,this.headerBuffer=null,this.propertiesBuffer=null,this.blockIndicesBuffer=null,this.context=u||null,this.propsDwords=w,this.totalBytes=4*this.propsDwords,this.headerData=new Uint32Array(uue.HEADER_DWORDS),this.propertiesData=new Float32Array(this.propsDwords),this.blockIndicesData=new Uint32Array(this.propsDwords);for(let C=0;Cu.maxUniformBlockSize)throw new Error(`UBO size ${this.totalBytes} exceeds device limit ${u.maxUniformBlockSize}`);if(this.headerBuffer=f.createBuffer(),!this.headerBuffer)throw new Error("Failed to create header UBO buffer");if(f.bindBuffer(f.UNIFORM_BUFFER,this.headerBuffer),f.bufferData(f.UNIFORM_BUFFER,uue.HEADER_BYTES,f.DYNAMIC_DRAW),this.propertiesBuffer=f.createBuffer(),!this.propertiesBuffer)throw new Error("Failed to create properties UBO buffer");if(f.bindBuffer(f.UNIFORM_BUFFER,this.propertiesBuffer),f.bufferData(f.UNIFORM_BUFFER,this.totalBytes,f.DYNAMIC_DRAW),this.blockIndicesBuffer=f.createBuffer(),!this.blockIndicesBuffer)throw new Error("Failed to create block-indices UBO buffer");f.bindBuffer(f.UNIFORM_BUFFER,this.blockIndicesBuffer),f.bufferData(f.UNIFORM_BUFFER,this.totalBytes,f.DYNAMIC_DRAW),f.bindBuffer(f.UNIFORM_BUFFER,null)}writeHeader(u){const f=this.headerData;f[0]=u.dataDrivenMask,f[1]=u.zoomDependentMask,f[2]=u.dataDrivenBlockSizeVec4,f[3]=u.offsets[0],f[4]=u.offsets[1],f[5]=u.offsets[2],f[6]=u.offsets[3],f[7]=u.offsets[4],f[8]=u.offsets[5],f[9]=u.offsets[6],f[10]=u.offsets[7],f[11]=u.offsets[8]}writeDataDrivenBlock(u,f,w){const C=4*w.dataDrivenBlockSizeVec4;if(C===0)return;const I=f*C;if(I+C>this.propertiesData.length)throw new Error(`UBO write out of bounds: feature index ${f} exceeds propertiesData capacity`);for(let L=0;L<9;L++)w.dataDrivenMask&1<{if(!B)return;const Y=w.getUniformBlockIndex(f,L);Y!==w.INVALID_INDEX&&(w.uniformBlockBinding(f,Y,U),w.bindBufferBase(w.UNIFORM_BUFFER,U,B))},I=3*this.batchIndex;C("SymbolPaintPropertiesHeaderUniform",this.headerBuffer,I),C("SymbolPaintPropertiesUniform",this.propertiesBuffer,I+1),C("SymbolPaintPropertiesIndexUniform",this.blockIndicesBuffer,I+2)}destroy(){if(this.context){const u=this.context.gl;this.headerBuffer&&(u.deleteBuffer(this.headerBuffer),this.headerBuffer=null),this.propertiesBuffer&&(u.deleteBuffer(this.propertiesBuffer),this.propertiesBuffer=null),this.blockIndicesBuffer&&(u.deleteBuffer(this.blockIndicesBuffer),this.blockIndicesBuffer=null)}}};hve.HEADER_DWORDS=12,hve.HEADER_BYTES=48;let mve=hve;function fve(v,u,f,w){return[TM(255*v,255*u),TM(255*f,255*w)]}function rLe(v,u,f,w,C,I,L,B){return!!v&&(v.kind==="constant"?v.value==="none":v.kind==="composite"||v.kind==="source"?v.evaluate({zoom:0,brightness:I,worldview:B},u,f,C,w,L)==="none":typeof v=="string"&&v==="none")}Pr(mve,"SymbolPropertiesUBO",{omit:["headerBuffer","propertiesBuffer","blockIndicesBuffer"]});class pve{constructor(u,f,w,C,I="",L,B){this.layer=u,this.zoom=f,this.lut=w,this.isText=C,this.propDefs=this._getPropDefs(),this.worldview=I,this.maxUniformBufferBindings=L||24,this.uboSizeDwords=B||4096,this.featureVertexRangesFromId=new Map,this.allFeatures=[],this.ubos=[],this.featureCount=0,this.cachedHeader=null,this.maxFeaturesPerBatch=0,this.propertyHashToUBOIndex=new Map,this.canDeduplicate=this._checkIfAllPropertiesAreConstant(u,C),this.cachedParams=null,this.cachedParamsNext=null,this.cachedBrightness=void 0,this.cachedConstantUniforms=null,this.cachedConstantRenderZoom=null,this.cachedConstantBrightness=void 0,this.activeAppearanceByVtIndex=new Map}_getPropDefs(){const u=this.isText?"text":"icon";return[{name:`${u}-color`,useThemeName:`${u}-color-use-theme`,isColor:!0},{name:`${u}-halo-color`,useThemeName:`${u}-halo-color-use-theme`,isColor:!0},{name:`${u}-opacity`,useThemeName:null,isColor:!1},{name:`${u}-halo-width`,useThemeName:null,isColor:!1},{name:`${u}-halo-blur`,useThemeName:null,isColor:!1},{name:`${u}-emissive-strength`,useThemeName:null,isColor:!1},{name:`${u}-occlusion-opacity`,useThemeName:null,isColor:!1},{name:"symbol-z-offset",useThemeName:null,isColor:!1},{name:`${u}-translate`,useThemeName:null,isColor:!1,isVec2:!0}]}buildHeader(){const u=this.layer.paint,f=this.propDefs;let w=0,C=0,I=0,L=0;const B=[0,0,0,0,0,0,0,0,0];for(let U=0;U<9;U++){const{name:Y,isColor:se,isVec2:oe}=f[U],de=u.get(Y),xe=!(!de||typeof de.isConstant!="function"||de.isConstant()),we=this._appearancesHavePaintProperties(Y),Ce=xe||we,Re=!(!de||!de.value||de.value.kind!=="composite"),qe=this.layer._transitionablePaint._values[Y],nt=!Ce&&(qe&&qe.value&&qe.value.expression&&qe.value.expression.kind)==="camera";Ce?(w|=1<f.hasPaintProperty(u):this.isText?f=>f.hasTextPaintProperties():f=>f.hasIconPaintProperties())}_checkIfAllPropertiesAreConstant(u,f){const w=u.paint,C=f?"text":"icon",I=[`${C}-color`,`${C}-halo-color`,`${C}-opacity`,`${C}-halo-width`,`${C}-halo-blur`,`${C}-emissive-strength`,`${C}-occlusion-opacity`,"symbol-z-offset",`${C}-translate`];for(const L of I){const B=w.get(L);if(B&&typeof B=="object"&&"isConstant"in B&&!B.isConstant())return!1}return!this._appearancesHavePaintProperties()}_hashDataDrivenValues(u,f){if(f.dataDrivenMask===0)return"";const w=[];for(let C=0;C<9;C++){if(!(f.dataDrivenMask&1<=we){Gr(`Too many symbol features: batch ${de} requires binding points up to ${3*de+2}, device limit ${we}. Some features will render incorrectly.`);const Re={batchIndex:0,localFeatureIndex:0,vtFeatureIndex:f,featureId:U};return this.allFeatures.push(Re),U!=null&&(this.featureVertexRangesFromId.has(U)||this.featureVertexRangesFromId.set(U,[]),this.featureVertexRangesFromId.get(U).push(Re)),0}this.ubos[de]||(this.ubos[de]=new mve(B,de,this.uboSizeDwords),this.ubos[de].writeHeader(Y)),this.ubos[de].writeDataDrivenBlock(se,xe,Y);const Ce={batchIndex:de,localFeatureIndex:xe,vtFeatureIndex:f,featureId:U};return this.allFeatures.push(Ce),U!=null&&(this.featureVertexRangesFromId.has(U)||this.featureVertexRangesFromId.set(U,[]),this.featureVertexRangesFromId.get(U).push(Ce)),xe}updateFeatures(u,f,w,C,I,L,B){if(this.layer=f,this.cachedConstantUniforms=null,!this.cachedHeader)return;const U=this.cachedHeader;for(const Y of u){const se=this.featureVertexRangesFromId.get(Y);if(!se)continue;const oe=L[Y]||{};for(const de of se){if(!w)continue;const xe=w.feature(de.vtFeatureIndex);if(!xe)continue;const we={type:xe.type,id:Y,properties:xe.properties||{},geometry:[]},Ce=this.activeAppearanceByVtIndex?this.activeAppearanceByVtIndex.get(de.vtFeatureIndex):void 0,Re=this.evaluateAllProperties(we,oe,C,I,B,void 0,Ce);this.ubos[de.batchIndex]&&this.ubos[de.batchIndex].writeDataDrivenBlock(Re,de.localFeatureIndex,U)}}}updateDynamicExpressions(u,f,w,C,I,L){if(this.layer=u,this.cachedConstantUniforms=null,!this.cachedHeader)return;const B=this.cachedHeader;for(const U of this.allFeatures){if(!f)continue;const Y=f.feature(U.vtFeatureIndex);if(!Y)continue;const se=U.featureId!=null&&I[U.featureId]||{},oe={type:Y.type,id:U.featureId,properties:Y.properties||{},geometry:[]},de=this.activeAppearanceByVtIndex?this.activeAppearanceByVtIndex.get(U.vtFeatureIndex):void 0,xe=this.evaluateAllProperties(oe,se,w,C,L,void 0,de);this.ubos[U.batchIndex]&&this.ubos[U.batchIndex].writeDataDrivenBlock(xe,U.localFeatureIndex,B)}}updateFeaturePaintForAppearance(u,f,w,C,I,L,B){if(!this.layer||(this.activeAppearanceByVtIndex||(this.activeAppearanceByVtIndex=new Map),this.activeAppearanceByVtIndex.set(u,B||null),!this.cachedHeader))return!1;const U=this.cachedHeader;if(U.dataDrivenMask===0)return!1;let Y=!1;for(const se of this.allFeatures){if(se.vtFeatureIndex!==u)continue;const oe=this.evaluateAllProperties(f,w,C,I,L,void 0,B);this.ubos[se.batchIndex]&&(this.ubos[se.batchIndex].writeDataDrivenBlock(oe,se.localFeatureIndex,U),Y=!0)}return Y}getConstantUniformValues(u,f){const w=this.cachedHeader,C=!(!w||!w.cameraMask);if(this.cachedConstantUniforms&&this.cachedConstantBrightness===f&&(!C||this.cachedConstantRenderZoom===u))return this.cachedConstantUniforms;const I=this.layer.paint,L=this.propDefs,B=C?new wa(u,{brightness:f,worldview:this.worldview}):null,U={type:1,id:void 0,properties:{},geometry:[]},Y=de=>{const xe=L[de],we=I.get(xe.name);if(!we)return[0,0,0,1];const Ce=xe.useThemeName?I.get(xe.useThemeName):void 0,Re=rLe(Ce&&typeof Ce!="string"?Ce.value:void 0,U,{},[],void 0,f,void 0,this.worldview)?null:this.lut;let qe;qe=w&&w.cameraMask&1<{const we=I.get(L[de].name);if(!we)return xe;if(w&&w.cameraMask&1<{w.text=function(C,I,L){const B=I.layout.get("text-transform").evaluate(L,{});return B==="uppercase"?C=C.toLocaleUpperCase():B==="lowercase"&&(C=C.toLocaleLowerCase()),Xh.applyArabicShaping&&(C=Xh.applyArabicShaping(C)),C}(w.text,u,f)}),v}const HD={"!":"︕","#":"#",$:"$","%":"%","&":"&","(":"︵",")":"︶","*":"*","+":"+",",":"︐","-":"︲",".":"・","/":"/",":":"︓",";":"︔","<":"︿","=":"=",">":"﹀","?":"︖","@":"@","[":"﹇","\\":"\","]":"﹈","^":"^",_:"︳","`":"`","{":"︷","|":"―","}":"︸","~":"~","¢":"¢","£":"£","¥":"¥","¦":"¦","¬":"¬","¯":" ̄","–":"︲","—":"︱","‘":"﹃","’":"﹄","“":"﹁","”":"﹂","…":"︙","‧":"・","₩":"₩","、":"︑","。":"︒","〈":"︿","〉":"﹀","《":"︽","》":"︾","「":"﹁","」":"﹂","『":"﹃","』":"﹄","【":"︻","】":"︼","〔":"︹","〕":"︺","〖":"︗","〗":"︘","!":"︕","(":"︵",")":"︶",",":"︐","-":"︲",".":"・",":":"︓",";":"︔","<":"︿",">":"﹀","?":"︖","[":"﹇","]":"﹈","_":"︳","{":"︷","|":"―","}":"︸","⦅":"︵","⦆":"︶","。":"︒","「":"﹁","」":"﹂","←":"↑","→":"↓"};function Cwt(v){return v==="︶"||v==="﹈"||v==="︸"||v==="﹄"||v==="﹂"||v==="︾"||v==="︼"||v==="︺"||v==="︘"||v==="﹀"||v==="︐"||v==="︓"||v==="︔"||v==="`"||v===" ̄"||v==="︑"||v==="︒"}function Twt(v){return v==="︵"||v==="﹇"||v==="︷"||v==="﹃"||v==="﹁"||v==="︽"||v==="︻"||v==="︹"||v==="︗"||v==="︿"}const gve=4294967296,nLe=1/gve,aLe=typeof TextDecoder>"u"?null:new TextDecoder("utf-8");let M$=class{constructor(v=new Uint8Array(16)){this.buf=ArrayBuffer.isView(v)?v:new Uint8Array(v),this.dataView=new DataView(this.buf.buffer),this.pos=0,this.type=0,this.length=this.buf.length}readFields(v,u,f=this.length){for(;this.pos>3,I=this.pos;this.type=7&w,v(C,u,this),this.pos===I&&this.skip(w)}return u}readMessage(v,u){return this.readFields(v,u,this.readVarint()+this.pos)}readFixed32(){const v=this.dataView.getUint32(this.pos,!0);return this.pos+=4,v}readSFixed32(){const v=this.dataView.getInt32(this.pos,!0);return this.pos+=4,v}readFixed64(){const v=this.dataView.getUint32(this.pos,!0)+this.dataView.getUint32(this.pos+4,!0)*gve;return this.pos+=8,v}readSFixed64(){const v=this.dataView.getUint32(this.pos,!0)+this.dataView.getInt32(this.pos+4,!0)*gve;return this.pos+=8,v}readFloat(){const v=this.dataView.getFloat32(this.pos,!0);return this.pos+=4,v}readDouble(){const v=this.dataView.getFloat64(this.pos,!0);return this.pos+=8,v}readVarint(v){const u=this.buf;let f,w;return w=u[this.pos++],f=127&w,w<128?f:(w=u[this.pos++],f|=(127&w)<<7,w<128?f:(w=u[this.pos++],f|=(127&w)<<14,w<128?f:(w=u[this.pos++],f|=(127&w)<<21,w<128?f:(w=u[this.pos],f|=(15&w)<<28,function(C,I,L){const B=L.buf;let U,Y;if(Y=B[L.pos++],U=(112&Y)>>4,Y<128||(Y=B[L.pos++],U|=(127&Y)<<3,Y<128)||(Y=B[L.pos++],U|=(127&Y)<<10,Y<128)||(Y=B[L.pos++],U|=(127&Y)<<17,Y<128)||(Y=B[L.pos++],U|=(127&Y)<<24,Y<128)||(Y=B[L.pos++],U|=(1&Y)<<31,Y<128))return FM(C,U,I);throw new Error("Expected varint not more than 10 bytes")}(f,v,this)))))}readVarint64(){return this.readVarint(!0)}readSVarint(){const v=this.readVarint();return v%2==1?(v+1)/-2:v/2}readBoolean(){return!!this.readVarint()}readString(){const v=this.readVarint()+this.pos,u=this.pos;return this.pos=v,v-u>=12&&aLe?aLe.decode(this.buf.subarray(u,v)):function(f,w,C){let I="",L=w;for(;L239?4:B>223?3:B>191?2:1;if(L+de>C)break;de===1?B<128&&(oe=B):de===2?(U=f[L+1],(192&U)==128&&(oe=(31&B)<<6|63&U,oe<=127&&(oe=null))):de===3?(U=f[L+1],Y=f[L+2],(192&U)==128&&(192&Y)==128&&(oe=(15&B)<<12|(63&U)<<6|63&Y,(oe<=2047||oe>=55296&&oe<=57343)&&(oe=null))):de===4&&(U=f[L+1],Y=f[L+2],se=f[L+3],(192&U)==128&&(192&Y)==128&&(192&se)==128&&(oe=(15&B)<<18|(63&U)<<12|(63&Y)<<6|63&se,(oe<=65535||oe>=1114112)&&(oe=null))),oe===null?(oe=65533,de=1):oe>65535&&(oe-=65536,I+=String.fromCharCode(oe>>>10&1023|55296),oe=56320|1023&oe),I+=String.fromCharCode(oe),L+=de}return I}(this.buf,u,v)}readBytes(){const v=this.readVarint()+this.pos,u=this.buf.subarray(this.pos,v);return this.pos=v,u}readPackedVarint(v=[],u){const f=this.readPackedEnd();for(;this.pos127;);else if(u===2)this.pos=this.readVarint()+this.pos;else if(u===5)this.pos+=4;else{if(u!==1)throw new Error(`Unimplemented type: ${u}`);this.pos+=8}}writeTag(v,u){this.writeVarint(v<<3|u)}realloc(v){let u=this.length||16;for(;u268435455||v<0?function(u,f){let w,C;if(u>=0?(w=u%4294967296|0,C=u/4294967296|0):(w=~(-u%4294967296),C=~(-u/4294967296),4294967295^w?w=w+1|0:(w=0,C=C+1|0)),u>=18446744073709552e3||u<-18446744073709552e3)throw new Error("Given varint doesn't fit into 10 bytes");f.realloc(10),function(I,L,B){B.buf[B.pos++]=127&I|128,I>>>=7,B.buf[B.pos++]=127&I|128,I>>>=7,B.buf[B.pos++]=127&I|128,I>>>=7,B.buf[B.pos++]=127&I|128,B.buf[B.pos]=127&(I>>>=7)}(w,0,f),function(I,L){const B=(7&I)<<4;L.buf[L.pos++]|=B|((I>>>=3)?128:0),I&&(L.buf[L.pos++]=127&I|((I>>>=7)?128:0),I&&(L.buf[L.pos++]=127&I|((I>>>=7)?128:0),I&&(L.buf[L.pos++]=127&I|((I>>>=7)?128:0),I&&(L.buf[L.pos++]=127&I|((I>>>=7)?128:0),I&&(L.buf[L.pos++]=127&I)))))}(C,f)}(v,this):(this.realloc(4),this.buf[this.pos++]=127&v|(v>127?128:0),v<=127||(this.buf[this.pos++]=127&(v>>>=7)|(v>127?128:0),v<=127||(this.buf[this.pos++]=127&(v>>>=7)|(v>127?128:0),v<=127||(this.buf[this.pos++]=v>>>7&127))))}writeSVarint(v){this.writeVarint(v<0?2*-v-1:2*v)}writeBoolean(v){this.writeVarint(+v)}writeString(v){v=String(v),this.realloc(4*v.length),this.pos++;const u=this.pos;this.pos=function(w,C,I){for(let L,B,U=0;U55295&&L<57344){if(!B){L>56319||U+1===C.length?(w[I++]=239,w[I++]=191,w[I++]=189):B=L;continue}if(L<56320){w[I++]=239,w[I++]=191,w[I++]=189,B=L;continue}L=B-55296<<10|L-56320|65536,B=null}else B&&(w[I++]=239,w[I++]=191,w[I++]=189,B=null);L<128?w[I++]=L:(L<2048?w[I++]=L>>6|192:(L<65536?w[I++]=L>>12|224:(w[I++]=L>>18|240,w[I++]=L>>12&63|128),w[I++]=L>>6&63|128),w[I++]=63&L|128)}return I}(this.buf,v,this.pos);const f=this.pos-u;f>=128&&iLe(u,f,this),this.pos=u-1,this.writeVarint(f),this.pos+=f}writeFloat(v){this.realloc(4),this.dataView.setFloat32(this.pos,v,!0),this.pos+=4}writeDouble(v){this.realloc(8),this.dataView.setFloat64(this.pos,v,!0),this.pos+=8}writeBytes(v){const u=v.length;this.writeVarint(u),this.realloc(u);for(let f=0;f=128&&iLe(f,w,this),this.pos=f-1,this.writeVarint(w),this.pos+=w}writeMessage(v,u,f){this.writeTag(v,2),this.writeRawMessage(u,f)}writePackedVarint(v,u){u.length&&this.writeMessage(v,Ewt,u)}writePackedSVarint(v,u){u.length&&this.writeMessage(v,Awt,u)}writePackedBoolean(v,u){u.length&&this.writeMessage(v,Pwt,u)}writePackedFloat(v,u){u.length&&this.writeMessage(v,Mwt,u)}writePackedDouble(v,u){u.length&&this.writeMessage(v,Iwt,u)}writePackedFixed32(v,u){u.length&&this.writeMessage(v,Lwt,u)}writePackedSFixed32(v,u){u.length&&this.writeMessage(v,Dwt,u)}writePackedFixed64(v,u){u.length&&this.writeMessage(v,Rwt,u)}writePackedSFixed64(v,u){u.length&&this.writeMessage(v,Owt,u)}writeBytesField(v,u){this.writeTag(v,2),this.writeBytes(u)}writeFixed32Field(v,u){this.writeTag(v,5),this.writeFixed32(u)}writeSFixed32Field(v,u){this.writeTag(v,5),this.writeSFixed32(u)}writeFixed64Field(v,u){this.writeTag(v,1),this.writeFixed64(u)}writeSFixed64Field(v,u){this.writeTag(v,1),this.writeSFixed64(u)}writeVarintField(v,u){this.writeTag(v,0),this.writeVarint(u)}writeSVarintField(v,u){this.writeTag(v,0),this.writeSVarint(u)}writeStringField(v,u){this.writeTag(v,2),this.writeString(u)}writeFloatField(v,u){this.writeTag(v,5),this.writeFloat(u)}writeDoubleField(v,u){this.writeTag(v,1),this.writeDouble(u)}writeBooleanField(v,u){this.writeVarintField(v,+u)}};function FM(v,u,f){return f?4294967296*u+(v>>>0):4294967296*(u>>>0)+(v>>>0)}function iLe(v,u,f){const w=u<=16383?1:u<=2097151?2:u<=268435455?3:Math.floor(Math.log(u)/(7*Math.LN2));f.realloc(w);for(let C=f.pos-1;C>=v;C--)f.buf[C+w]=f.buf[C]}function Ewt(v,u){for(let f=0;f=0&&w>=u&&I$[this.text.charCodeAt(w)];w--)f--;this.text=this.text.substring(u,f),this.sectionIndex=this.sectionIndex.slice(u,f)}substring(u,f){const w=new BM;return w.text=this.text.substring(u,f),w.sectionIndex=this.sectionIndex.slice(u,f),w.sections=this.sections,w}toString(){return this.text}getMaxScale(){return this.sectionIndex.reduce((u,f)=>Math.max(u,this.sections[f].scale),0)}addTextSection(u,f){this.text+=u.text,this.sections.push(GD.forText(u.scale,u.fontStack||f));const w=this.sections.length-1;for(let C=0;C=63743?null:++this.imageSectionID:(this.imageSectionID=57344,this.imageSectionID)}}function xve(v,u,f,w,C,I,L,B,U,Y,se,oe,de,xe,we,Ce=1,Re=1){const qe=BM.fromFeature(v,C,Ce,Re);oe===Xp.vertical&&qe.verticalizePunctuation(de);let nt=[];const Ze=function(Rt,Vt,Bt,$t,js,Es,zs=1){if(!Rt)return[];const Hs=[],$s=function(qs,Zs,ir,pr,Zr,Nr,jr=1){let gr=0;for(let qr=0;qr=0;let ys=0;for(let qs=0;qs0&&Qh>Fa&&(Fa=Qh)}else{const su=Bt[vl.fontStack];if(!su)continue;su[bl]&&(Xl=su[bl]);const $m=Vt[vl.fontStack];if(!$m)continue;const ah=$m.glyphs[bl];if(!ah)continue;if(Nc=ah.metrics,Bd=bl!==8203?Od:0,jr){const Pl=$m.ascender!==void 0?Math.abs($m.ascender):0,Qh=$m.descender!==void 0?Math.abs($m.descender):0,ru=(Pl+Qh)*Zl;Il-f/2;){if(L--,L<0)return!1;B-=v[L].dist(I),I=v[L]}B+=v[L].dist(v[L+1]),L++;const U=[];let Y=0;for(;Bw;)Y-=U.shift().angleDelta;if(Y>C)return!1;L++,B+=se.dist(oe)}return!0}function gLe(v){let u=0;for(let f=0;fY){const we=(Y-U)/xe,Ce=jn(oe.x,de.x,we),Re=jn(oe.y,de.y,we),qe=new Yw(Ce,Re,0,de.angleTo(oe),se);return!L||pLe(v,qe,B,L,u)?qe:void 0}U+=xe}}function Vwt(v,u,f,w,C,I,L,B,U){const Y=xLe(w,I,L),se=yLe(w,C),oe=se*L,de=v[0].x===0||v[0].x===U||v[0].y===0||v[0].y===U;return u-oe=0&&ut=0&&xt=0&&de+Y<=se){const bt=new Yw(ut,xt,0,nt,we);w&&!pLe(v,bt,I,w,C)||xe.push(bt)}}oe+=qe}return B||xe.length||L||(xe=vLe(v,oe/2,f,w,C,I,L,!0,U)),xe}function bLe(v){let u=0,f=0;for(const L of v)u+=L.w*L.h,f=Math.max(f,L.w);v.sort((L,B)=>B.h-L.h);const w=[{x:0,y:0,w:Math.max(Math.ceil(Math.sqrt(u/.95)),f),h:1/0}];let C=0,I=0;for(const L of v)for(let B=w.length-1;B>=0;B--){const U=w[B];if(!(L.w>U.w||L.h>U.h)){if(L.x=U.x,L.y=U.y,I=Math.max(I,L.y+L.h),C=Math.max(C,L.x+L.w),L.w===U.w&&L.h===U.h){const Y=w.pop();Y&&Bu.id?1:v.versionu.version?1:v.sxu.sx?1:v.syu.sy?1:0}function wve(v){let u=0;for(let f=0;f0,_Le(u,w,this.iconDescriptors,I),_Le(f,w,this.patternDescriptors,I),this.iconDescriptors.sort(L$),this.patternDescriptors.sort(L$);let L=0;const B=C?C.data:"";B&&(L=Rv(L,wve(B))),L=Rv(L,1);for(const U of this.iconDescriptors)L=Rv(L,wve(U.id)),L=Rv(L,U.version),L=Rv(L,U.sx),L=Rv(L,U.sy);L=Rv(L,1);for(const U of this.patternDescriptors)L=Rv(L,wve(U.id)),L=Rv(L,U.version),L=Rv(L,U.sx),L=Rv(L,U.sy);this.hash=L}subsetOf(u){return this.isSubsetArray(this.iconDescriptors,u.iconDescriptors,L$)&&this.isSubsetArray(this.patternDescriptors,u.patternDescriptors,L$)}isSubsetArray(u,f,w){let C=0,I=0;if(u.length>f.length)return!1;for(;C{const L=C.variant.id.toString().localeCompare(I.variant.id.toString());return L!==0?L:C.variant.sx!==I.variant.sx?C.variant.sx-I.variant.sx:C.variant.sy!==I.variant.sy?C.variant.sy-I.variant.sy:0});const w=new Map;for(const C of f)w.set(C.key,C.value);return w}class wLe{constructor(u){this.sourceAtlasHash=u}}class jLe{constructor(u,f,w,C){const I=new Map,L=new Map;this.haveRenderCallbacks=[];const B=[],U=C!==void 0,Y=U?new Map:void 0,se=U?kve(u,Y):u,oe=U?kve(f,Y):f;this.addImages(se,I,1,B),this.addImages(oe,L,2,B);const{w:de,h:xe}=bLe(B),we=new Th({width:de||1,height:xe||1});for(const[Ce,Re]of se.entries()){const qe=I.get(Ce).paddedRect;Th.copy(Re.data,we,{x:0,y:0},{x:qe.x+1,y:qe.y+1},Re.data,null,Re.sdf)}for(const[Ce,Re]of oe.entries()){const qe=L.get(Ce),nt=qe.paddedRect;let Ze=qe.padding;const ut=nt.x+Ze,xt=nt.y+Ze,bt=Re.data.width,Ht=Re.data.height;Ze=Ze>1?Ze-1:Ze,Th.copy(Re.data,we,{x:0,y:0},{x:ut,y:xt},Re.data,w),Th.copy(Re.data,we,{x:0,y:Ht-Ze},{x:ut,y:xt-Ze},{width:bt,height:Ze},w),Th.copy(Re.data,we,{x:0,y:0},{x:ut,y:xt+Ht},{width:bt,height:Ze},w),Th.copy(Re.data,we,{x:bt-Ze,y:0},{x:ut-Ze,y:xt},{width:Ze,height:Ht},w),Th.copy(Re.data,we,{x:0,y:0},{x:ut+bt,y:xt},{width:Ze,height:Ht},w),Th.copy(Re.data,we,{x:bt-Ze,y:Ht-Ze},{x:ut-Ze,y:xt-Ze},{width:Ze,height:Ze},w),Th.copy(Re.data,we,{x:0,y:Ht-Ze},{x:ut+bt,y:xt-Ze},{width:Ze,height:Ze},w),Th.copy(Re.data,we,{x:0,y:0},{x:ut+bt,y:xt+Ht},{width:Ze,height:Ze},w),Th.copy(Re.data,we,{x:bt-Ze,y:0},{x:ut-Ze,y:xt+Ht},{width:Ze,height:Ze},w)}this.lut=w,this.image=we,this.iconPositions=I,this.patternPositions=L,U&&(this.contentDescriptor=new jve(se,oe,C,w,Y))}addImages(u,f,w,C){for(const[I,L]of u.entries()){const{bin:B,imagePosition:U,imageVariant:Y}=Nve(I,L,w);f.set(I,U),C.push(B),L.hasRenderCallback&&this.haveRenderCallbacks.push(Y.id)}}patchUpdatedImages(u,f,w,C){this.haveRenderCallbacks=this.haveRenderCallbacks.filter(I=>u.hasImage(I,w)),u.dispatchRenderCallbacks(this.haveRenderCallbacks,w);for(const I of u.getUpdatedImages(w)){for(const L of this.iconPositions.keys()){const B=Im.parse(L);if(Mt.isEqual(B.id,I)){const U=u.getImage(I,w);this.patchUpdatedImage(this.iconPositions.get(L),U,f,null)}}for(const L of this.patternPositions.keys()){const B=Im.parse(L);if(Mt.isEqual(B.id,I)){const U=u.getImage(I,w);this.patchUpdatedImage(this.patternPositions.get(L),U,f,C||this.lut)}}}}patchUpdatedImage(u,f,w,C=null){if(!u||!f||u.version===f.version)return;u.version=f.version;const[I,L]=u.tl,B=u.sdf;if(this.lut||B){const U={width:f.data.width,height:f.data.height},Y=new Th(U);Th.copy(f.data,Y,{x:0,y:0},{x:0,y:0},U,C,B),w.update(Y,{position:{x:I,y:L},recreateWhenResize:!1})}else w.update(f.data,{position:{x:I,y:L},recreateWhenResize:!1})}}Pr(WD,"ImagePosition"),Pr(jLe,"ImageAtlas",{omit:["lut"]}),Pr(wLe,"ImageAtlasReference");class KD{constructor(u){this.pendingRequests=new Map,this.cachedRanges=new Map,this.useServerFontComposition=!u||u.useServerFontComposition===void 0||u.useServerFontComposition}loadGlyphRange(u,f,w,C,I){if(this.useServerFontComposition)return void KD.loadGlyphRange(u,f,w,C,I);const L=u.split(",").map(B=>B.trim()).filter(B=>B.length>0);L.length!==0?L.length!==1?this._loadMultipleFonts(L,f,w,C,I):this._loadFont(L[0],f,w,C,I):I(new Error("Empty fontstack"))}_loadMultipleFonts(u,f,w,C,I){const L=u.map(()=>null),B={completed:0,firstError:null,callbackCalled:!1},U=(Y,se,oe)=>{if(!B.callbackCalled&&(se&&!B.firstError&&(B.firstError=se),oe&&(L[Y]=oe),B.completed++,B.completed===u.length)){B.callbackCalled=!0;const de=L.filter(we=>we!==null);if(de.length===0)return void I(B.firstError||new Error("All fonts failed to load"));const xe=this._composeGlyphs(de);I(null,xe)}};for(let Y=0;Y{U(Y,se,oe)})}_loadFont(u,f,w,C,I){const L=`${u}:${f}`;if(this.cachedRanges.has(L)){const U=this.cachedRanges.get(L);return void Ad.frame(()=>I(null,U))}const B=this.pendingRequests.get(L);B?B.push(I):(this.pendingRequests.set(L,[I]),KD.loadGlyphRange(u,f,w,C,(U,Y)=>{U||this.cachedRanges.set(L,Y||null);const se=this.pendingRequests.get(L);if(this.pendingRequests.delete(L),se)for(const oe of se)oe(U,Y)}))}_composeGlyphs(u){const f={};let w,C;for(const I of u)if(w===void 0&&I.ascender!==void 0&&(w=I.ascender),C===void 0&&I.descender!==void 0&&(C=I.descender),I.glyphs)for(const L in I.glyphs)f[L]===void 0&&(f[L]=I.glyphs[L]);return{glyphs:f,ascender:w,descender:C}}}KD.loadGlyphRange=function(v,u,f,w,C){const I=256*u,L=I+255,B=w.transformRequest(w.normalizeGlyphsURL(f).replace("{fontstack}",v).replace("{range}",`${I}-${L}`),vx.Glyphs);U0(B,(U,Y)=>{if(U)C(U);else if(Y){const se={},oe=function(de){return new M$(de).readFields(Fwt,{})}(Y);for(const de of oe.glyphs)se[de.id]=de;C(null,{glyphs:se,ascender:oe.ascender,descender:oe.descender})}})};const YD=1e20;function NLe(v,u,f,w,C,I,L,B,U){for(let Y=u;Y-1);U++,I[U]=B,L[U]=Y,L[U+1]=YD}for(let B=0,U=0;B{if(L){C.ascender=L.ascender,C.descender=L.descender;for(const B in L.glyphs)this._doesCharSupportLocalGlyph(+B)||(C.glyphs[+B]=L.glyphs[+B]);C.ranges[f]=!0}for(const B of C.requests[f]||[])B(I,L);delete C.requests[f]}))}getGlyphs(u,f){const w=[],C=this.url||ia.GLYPHS_URL;for(const I in u)for(const L of u[I])w.push({stack:I,id:L});Dt(w,({stack:I,id:L},B)=>{let U=this.entries[I];U||(U=this.entries[I]={glyphs:{},requests:{},ranges:{},ascender:void 0,descender:void 0});let Y=U.glyphs[L];if(Y!==void 0)return void B(null,{stack:I,id:L,glyph:Y});if(Y=this._tinySDF(U,I,L),Y)return U.glyphs[L]=Y,void B(null,{stack:I,id:L,glyph:Y});const se=Math.floor(L/256);if(256*se>65535)return Gr("glyphs > 65535 not supported"),void B(null,{stack:I,id:L,glyph:Y});if(U.ranges[se])return void B(null,{stack:I,id:L,glyph:Y});let oe=U.requests[se];oe||(oe=U.requests[se]=[],this.glyphLoader.loadGlyphRange(I,se,C,this.requestManager,(de,xe)=>{if(xe){U.ascender=xe.ascender,U.descender=xe.descender;for(const we in xe.glyphs)this._doesCharSupportLocalGlyph(+we)||(U.glyphs[+we]=xe.glyphs[+we]);U.ranges[se]=!0}for(const we of oe)we(de,xe);delete U.requests[se]})),oe.push((de,xe)=>{de?B(de):xe&&B(null,{stack:I,id:L,glyph:xe.glyphs[L]||null})})},(I,L)=>{if(I)f(I);else if(L){const B={};for(const{stack:U,id:Y,glyph:se}of L)B[U]===void 0&&(B[U]={}),B[U].glyphs===void 0&&(B[U].glyphs={}),B[U].glyphs[Y]=se&&{id:se.id,bitmap:se.bitmap.clone(),metrics:se.metrics},B[U].ascender=this.entries[U].ascender,B[U].descender=this.entries[U].descender;f(null,B)}})}_doesCharSupportLocalGlyph(u){return this.localGlyphMode!==Sve.none&&(this.localGlyphMode===Sve.all?!!this.localFontFamily:!!this.localFontFamily&&(Hp(u)||ub(u)||Ev(u)||Vp(u)||ty(u)||Iw(u)||(f=u)>=131072&&f<=173791||(w=>w>=66736&&w<=66815)(u)));var f}_tinySDF(u,f,w){const C=this.localFontFamily;if(!C||!this._doesCharSupportLocalGlyph(w))return;let I=u.tinySDF;if(!I){let Re="400";/bold/i.test(f)?Re="900":/medium/i.test(f)?Re="500":/light/i.test(f)&&(Re="200"),I=u.tinySDF=new D$.TinySDF({fontFamily:C,fontWeight:Re,fontSize:48,buffer:6,radius:16}),I.fontWeight=Re}const L=I.fontWeight;if(this.localGlyphs[L][w])return this.localGlyphs[L][w];const B=String.fromCodePoint(w),{data:U,width:Y,height:se,glyphWidth:oe,glyphHeight:de,glyphLeft:xe,glyphTop:we,glyphAdvance:Ce}=I.draw(B);return this.localGlyphs[L][w]={id:w,bitmap:new iN({width:Y,height:se},U),metrics:{width:oe/2,height:de/2,left:xe/2,top:we/2-27,advance:Ce/2,localGlyph:!0}}}}function SLe(v,u){return v+u[1]-u[0]}function Cve(v,u,f,w,C=1){const I=[],L=v.imagePrimary,B=L.pixelRatio,U=L.paddedRect.w-2,Y=L.paddedRect.h-2,se=(v.right-v.left)*C,oe=(v.bottom-v.top)*C,de=L.stretchX||[[0,U]],xe=L.stretchY||[[0,Y]],we=de.reduce(SLe,0),Ce=xe.reduce(SLe,0),Re=U-we,qe=Y-Ce;let nt=0,Ze=we,ut=0,xt=Ce,bt=0,Ht=Re,Rt=0,Vt=qe;if(L.content&&w){const $t=L.content;nt=R$(de,0,$t[0]),ut=R$(xe,0,$t[1]),Ze=R$(de,$t[0],$t[2]),xt=R$(xe,$t[1],$t[3]),bt=$t[0]-nt,Rt=$t[1]-ut,Ht=$t[2]-$t[0]-Ze,Vt=$t[3]-$t[1]-xt}const Bt=($t,js,Es,zs)=>{const Hs=O$($t.stretch-nt,Ze,se,v.left*C),$s=F$($t.fixed-bt,Ht,$t.stretch,we),nr=O$(js.stretch-ut,xt,oe,v.top*C),ys=F$(js.fixed-Rt,Vt,js.stretch,Ce),qs=O$(Es.stretch-nt,Ze,se,v.left*C),Zs=F$(Es.fixed-bt,Ht,Es.stretch,we),ir=O$(zs.stretch-ut,xt,oe,v.top*C),pr=F$(zs.fixed-Rt,Vt,zs.stretch,Ce),Zr=new ds(Hs,nr),Nr=new ds(qs,nr),jr=new ds(qs,ir),gr=new ds(Hs,ir),qr=new ds($s/B,ys/B),tn=new ds(Zs/B,pr/B),In=u*Math.PI/180;if(In){const Fa=Math.sin(In),Il=Math.cos(In),$i=[Il,-Fa,Fa,Il];Zr._matMult($i),Nr._matMult($i),gr._matMult($i),jr._matMult($i)}const cn=$t.stretch+$t.fixed,fa=Es.stretch+Es.fixed,xi=js.stretch+js.fixed,pa=zs.stretch+zs.fixed,vi=v.imageSecondary;return{tl:Zr,tr:Nr,bl:gr,br:jr,texPrimary:{x:L.paddedRect.x+1+cn,y:L.paddedRect.y+1+xi,w:fa-cn,h:pa-xi},texSecondary:vi?{x:vi.paddedRect.x+1+cn,y:vi.paddedRect.y+1+xi,w:fa-cn,h:pa-xi}:void 0,writingMode:void 0,glyphOffset:[0,0],sectionIndex:0,pixelOffsetTL:qr,pixelOffsetBR:tn,minFontScaleX:Ht/B/se,minFontScaleY:Vt/B/oe,isSDF:f}};if(L.stretchX||L.stretchY){const $t=CLe(de,Re,we),js=CLe(xe,qe,Ce);for(let Es=0;Es<$t.length-1;Es++){const zs=$t[Es],Hs=$t[Es+1];for(let $s=0;$s0?[nt,-Ze]:ut<0?[-nt,Ze]:nt===0?[Ze,nt]:[Ze,-nt]}(f);let xe=Math.abs(u.top-u.bottom);for(const qe of u.positionedLines)xe-=qe.lineOffset;const we=u.positionedLines.length,Ce=xe/we;let Re=u.top-f[1];for(let qe=0;qeI)&&(I=we.x),(!xe||we.y>L)&&(L=we.y)}const U=Math.min(I-w,L-C);let Y=U/2;const se=new wx([],Kwt);if(U===0)return new ds(w,C);for(let xe=w;xeoe.d||!oe.d)&&(oe=xe,f&&console.log("found best %d after %d probes",Math.round(1e4*xe.d)/1e4,de)),xe.max-oe.d<=u||(Y=xe.h/2,se.push(new $M(xe.p.x-Y,xe.p.y-Y,Y,v)),se.push(new $M(xe.p.x+Y,xe.p.y-Y,Y,v)),se.push(new $M(xe.p.x-Y,xe.p.y+Y,Y,v)),se.push(new $M(xe.p.x+Y,xe.p.y+Y,Y,v)),de+=4)}return f&&(console.log(`num probes: ${de}`),console.log(`best distance: ${oe.d}`)),oe.p}function Kwt(v,u){return u.max-v.max}D$.TinySDF=class{constructor({fontSize:v=24,buffer:u=3,radius:f=8,cutoff:w=.25,fontFamily:C="sans-serif",fontWeight:I="normal",fontStyle:L="normal",lang:B=null}={}){this.buffer=u,this.cutoff=w,this.radius=f,this.lang=B;const U=this.size=v+4*u,Y=this._createCanvas(U),se=this.ctx=Y.getContext("2d",{willReadFrequently:!0});se.font=`${L} ${I} ${v}px ${C}`,se.textBaseline="alphabetic",se.textAlign="left",se.fillStyle="black",this.gridOuter=new Float64Array(U*U),this.gridInner=new Float64Array(U*U),this.f=new Float64Array(U),this.z=new Float64Array(U+1),this.v=new Uint16Array(U)}_createCanvas(v){const u=document.createElement("canvas");return u.width=u.height=v,u}draw(v){const{width:u,actualBoundingBoxAscent:f,actualBoundingBoxDescent:w,actualBoundingBoxLeft:C,actualBoundingBoxRight:I}=this.ctx.measureText(v),L=Math.ceil(f),B=Math.max(0,Math.min(this.size-this.buffer,Math.ceil(I-C))),U=Math.min(this.size-this.buffer,L+Math.ceil(w)),Y=B+2*this.buffer,se=U+2*this.buffer,oe=Math.max(Y*se,0),de=new Uint8ClampedArray(oe),xe={data:de,width:Y,height:se,glyphWidth:B,glyphHeight:U,glyphTop:L,glyphLeft:0,glyphAdvance:u};if(B===0||U===0)return xe;const{ctx:we,buffer:Ce,gridInner:Re,gridOuter:qe}=this;this.lang&&(we.lang=this.lang),we.clearRect(Ce,Ce,B,U),we.fillText(v,Ce,Ce+L);const nt=we.getImageData(Ce,Ce,B,U);qe.fill(YD,0,oe),Re.fill(0,0,oe);for(let Ze=0;Ze0?Ht*Ht:0,Re[bt]=Ht<0?Ht*Ht:0}}NLe(qe,0,0,Y,se,Y,this.f,this.v,this.z),NLe(Re,Ce,Ce,B,U,Y,this.f,this.v,this.z);for(let Ze=0;ZeI.y!=Ce.y>I.y&&I.x<(Ce.x-we.x)*(I.y-we.y)/(Ce.y-we.y)+we.x&&(B=!B),U=Math.min(U,iy(I,we,Ce))}}return(B?1:-1)*Math.sqrt(U)}(this.p,C),this.max=this.d+this.h*Math.SQRT2}}const Ywt=Object.keys,Tve=Number.POSITIVE_INFINITY,Zwt=Math.sqrt(2);function dN(v,u,f,w,C,I){const L=vve(v)&&v.collisionPadding?v.collisionPadding:[0,0,0,0],B={top:v.top-L[1],bottom:v.bottom+L[3],left:v.left-L[0],right:v.right+L[2],scaled:!1};return w!==void 0&&function(U,Y){U.top*=Y,U.bottom*=Y,U.left*=Y,U.right*=Y,U.scaled=!0}(B,w),I&&(B.left+=I[0],B.right+=I[0],B.top+=I[1],B.bottom+=I[1]),f&&function(U,Y,se){if(!Y)return;const oe=Hr(Y),de=new ds(se?se[0]:0,se?se[1]:0),xe=new ds(U.left,U.top),we=new ds(U.right,U.top),Ce=new ds(U.left,U.bottom),Re=new ds(U.right,U.bottom);xe._rotateAround(oe,de),we._rotateAround(oe,de),Ce._rotateAround(oe,de),Re._rotateAround(oe,de),U.left=Math.min(xe.x,we.x,Ce.x,Re.x),U.right=Math.max(xe.x,we.x,Ce.x,Re.x),U.top=Math.min(xe.y,we.y,Ce.y,Re.y),U.bottom=Math.max(xe.y,we.y,Ce.y,Re.y)}(B,f,C),u?{top:Math.min(u.top,B.top),bottom:Math.max(u.bottom,B.bottom),left:Math.min(u.left,B.left),right:Math.max(u.right,B.right),scaled:u.scaled||B.scaled}:B}function ALe(v,[u,f]){let w=0,C=0;if(f===Tve){u<0&&(u=0);const I=u/Zwt;switch(v){case"top-right":case"top-left":C=I-7;break;case"bottom-right":case"bottom-left":C=7-I;break;case"bottom":C=7-u;break;case"top":C=u-7}switch(v){case"top-right":case"bottom-right":w=-I;break;case"top-left":case"bottom-left":w=I;break;case"left":w=u;break;case"right":w=-u}}else{switch(u=Math.abs(u),f=Math.abs(f),v){case"top-right":case"top-left":case"top":C=f-7;break;case"bottom-right":case"bottom-left":case"bottom":C=7-f}switch(v){case"top-right":case"bottom-right":case"right":w=-u;break;case"top-left":case"bottom-left":case"left":w=u}}return[w,C]}function Xwt(v,u,f,w,C,I,L,B,U,Y,se,oe,de,xe,we){const Ce=v.layers[0],Re=Ce.appearances;if(Re.length===0)return{iconBBox:null,iconVerticalBBox:null,textBBox:null,textVerticalBBox:null};const qe={iconBBox:null,iconVerticalBBox:null},nt={textBBox:null,textVerticalBBox:null},{baseIconRotate:Ze,baseTextRotate:ut,iconScaleFactor:xt}=function(Ht,Rt,Vt){const Bt=Ht.get("icon-rotate").evaluate(Rt,{},Vt),$t=Ht.get("text-rotate").evaluate(Rt,{},Vt),[js,Es]=Ht.get("icon-size-scale-range");return{baseIconRotate:Bt,baseTextRotate:$t,iconScaleFactor:He(1,js,Es)}}(w,C,I);u&&(qe.iconBBox=dN(u,qe.iconBBox,Ze),f)&&(qe.iconVerticalBBox=dN(f,qe.iconVerticalBBox,Ze+90));const bt=z$(oe.horizontal);bt&&(nt.textBBox=dN(bt,nt.textBBox,ut,1,xe)),oe.vertical&&(nt.textVerticalBBox=dN(oe.vertical,nt.textVerticalBBox,ut+90,1,xe));for(const Ht of Re)Ht.hasIconLayoutProperties()&&Qwt(qe,v,Ce,Ht,C,I,B,Ze,L,U,u,Y,xt,se,we),Ht.hasTextLayoutProperties()&&Jwt(nt,Ce,Ht,C,I,xe,ut,de,bt,oe.vertical);return{iconBBox:qe.iconBBox,iconVerticalBBox:qe.iconVerticalBBox,textBBox:nt.textBBox,textVerticalBBox:nt.textVerticalBBox}}function Qwt(v,u,f,w,C,I,L,B,U,Y,se,oe,de,xe,we){const{appearanceIconOffset:Ce,appearanceIconRotate:Re,appearanceIconSize:qe}=MLe(w,f,C,I,L,B,U,Y.iconScaleFactor);let nt=null,Ze=null,ut=null;w.hasLayoutProperty("icon-image")?ut=function(bt,Ht,Rt,Vt,Bt,$t,js,Es){let zs=null;const Hs=Ht.getAppearanceValueAndResolveTokens(Rt,"icon-image",Vt,Bt,Es);if(Hs){const $s=bt.getResolvedImageFromTokens(Hs),nr=Rt.hasLayoutProperty("icon-size")?Rt.getUnevaluatedLayoutProperty("icon-size"):Ht._unevaluatedLayout._values["icon-size"],ys=ZD($s,H4(bt.zoom,nr,bt.worldview,Es),nr,Bt,bt.zoom,Vt,bt.pixelRatio,js,bt.worldview,Es);zs=$t.get(ys.iconPrimary.toString())}return zs}(u,f,w,C,I,oe,de,we):se&&(ut=se.imagePrimary),ut&&(nt=P$(ut,null,Ce,xe),u.allowVerticalPlacement&&(Ze=P$(ut,null,Ce,xe)));const xt=U>0?qe/U:1;nt&&(v.iconBBox=dN(nt,v.iconBBox,Re,xt!==1?xt:void 0)),Ze&&(v.iconVerticalBBox=dN(Ze,v.iconVerticalBBox,Re+90,xt!==1?xt:void 0))}function MLe(v,u,f,w,C,I,L,B){const U=v.hasLayoutProperty("icon-offset")?u.getAppearanceValueAndResolveTokens(v,"icon-offset",f,w,[]):null,Y=U&&Array.isArray(U)?U:C,se=v.hasLayoutProperty("icon-rotate")?u.getAppearanceValueAndResolveTokens(v,"icon-rotate",f,w,[]):null,oe=typeof se=="number"?se:I,de=v.hasLayoutProperty("icon-size")?u.getAppearanceValueAndResolveTokens(v,"icon-size",f,w,[]):null;return{appearanceIconOffset:Y,appearanceIconRotate:oe,appearanceIconSize:typeof de=="number"?de*B:L}}function Jwt(v,u,f,w,C,I,L,B,U,Y){const{appearanceTextOffset:se,appearanceTextRotate:oe,appearanceTextSize:de}=ILe(f,u,w,C,I,L,B),xe=de/B,we=[(se[0]-I[0])*xe,(se[1]-I[1])*xe],Ce=we[0]!==0||we[1]!==0;U&&(v.textBBox=dN(U,v.textBBox,oe,xe,se,Ce?we:void 0)),Y&&(v.textVerticalBBox=dN(Y,v.textVerticalBBox,oe+90,xe,se,Ce?we:void 0))}function ILe(v,u,f,w,C,I,L){const B=v.hasLayoutProperty("text-offset")?u.getAppearanceValueAndResolveTokens(v,"text-offset",f,w,[]):null,U=B&&Array.isArray(B)?[B[0]*Od,B[1]*Od]:C,Y=v.hasLayoutProperty("text-rotate")?u.getAppearanceValueAndResolveTokens(v,"text-rotate",f,w,[]):null,se=typeof Y=="number"?Y:I,oe=v.hasLayoutProperty("text-size")?u.getAppearanceValueAndResolveTokens(v,"text-size",f,w,[]):null;return{appearanceTextOffset:U,appearanceTextRotate:se,appearanceTextSize:typeof oe=="number"?oe:L}}function B$(v,u,f,w,C,I,L,B,U){if(!u||!u.usvg)return;const Y=fLe(w),se=fLe(C),oe=I!=="both"&&I!=="width"||!hLe(w)?1:se.width/Y.width,de=I!=="both"&&I!=="height"||!mLe(w)?1:se.height/Y.height;f.scaleSelf(oe,de);const xe=f.toString();L.set(xe,f),B.set(xe,u);const{imagePosition:we}=Nve(xe,u,1);U.set(xe,we)}function PLe(v,u,f,w,C,I,L,B,U,Y){if(!v)return;const se=function(oe,de,xe,we,Ce,Re,qe){if(oe.kind==="camera")return oe.maxSize;if(oe.kind==="composite"){const nt=de.possiblyEvaluate(new wa(oe.maxZoom,{worldview:Re}),xe,qe).evaluate(Ce,{},xe,qe),Ze=de.possiblyEvaluate(new wa(oe.minZoom,{worldview:Re}),xe,qe).evaluate(Ce,{},xe,qe);return Math.max(nt,Ze)}return de.possiblyEvaluate(new wa(we,{worldview:Re}),xe,qe).evaluate(Ce,{},xe,qe)}(u,f,w,C,I,U,Y);return v.scaleSelf(se*B*L)}function ZD(v,u,f,w,C,I,L,B,U,Y){return{iconPrimary:PLe(v.getPrimary(),u,f,w,C,I,L,B,U,Y),iconSecondary:PLe(v.getSecondary(),u,f,w,C,I,L,B,U,Y)}}function e2t(v,u,f){if(!u)return;const w=f.get(v.toString()),C=f.get(u.toString());w&&C&&(w.paddedRect.w===C.paddedRect.w&&w.paddedRect.h===C.paddedRect.h||Gr(`Mismatch in icon variant sizes: ${v.toString()} and ${u.toString()}`),w.usvg!==C.usvg&&Gr(`Mismatch in icon variant image types: ${v.id} and ${u.id}`))}function LLe(v,u,f,w){if(!v)return;const C=u.get(f.toString());if(C&&(v.imagePrimary=C),w){const I=u.get(w.toString());v.imageSecondary=I}}function t2t(v,u){for(const f in v.horizontal)DLe(v.horizontal[f],u);DLe(v.vertical,u)}function DLe(v,u){if(v){for(const f of v.positionedLines)for(const w of f.positionedGlyphs)if(w.image!==null){const C=w.image.toString();w.rect=u.get(C).paddedRect}}}function Eve(v){switch(v){case"right":case"top-right":case"bottom-right":return"right";case"left":case"top-left":case"bottom-left":return"left"}return"center"}function s2t(v,u,f,w,C,I,L,B,U){const Y=z$(I.horizontal)||I.vertical,se=f.get("icon-text-fit-padding").evaluate(w,{},C);let oe,de=u;return u&&U!=="none"&&(v.allowVerticalPlacement&&I.vertical&&(oe=bve(u,I.vertical,U,se,B,L)),Y&&(de=bve(u,Y,U,se,B,L))),{defaultShapedIcon:de,verticallyShapedIcon:oe}}function RLe(v,u){return v*u/24}function r2t(v,u,f,w,C,I,L,B,U,Y,se,oe,de,xe,we,Ce,Re,qe,nt,Ze,ut,xt,bt,Ht){let Rt=L.textMaxSize.evaluate(u,{},de);Rt===void 0?Rt=B*L.textScaleFactor:Rt*=L.textScaleFactor;const Vt=v.layers[0].layout,Bt=RLe(B,L.textScaleFactor),$t=z$(f.horizontal)||f.vertical,js=v.hasAnyAppearanceLayoutProperty(["text-size","text-offset","text-rotate"]),Es=v.getAppearanceFeatureData(u.index);(Re!=="none"||js)&&Es&&(Es.textShaping=$t,Es.iconTextFitPadding=Vt.get("icon-text-fit-padding").evaluate(u,{},de),Es.fontScale=Bt,Es.textScaleFactor=L.textScaleFactor);const zs=xe.name==="globe",Hs=v.tilePixelRatio*Rt/24,$s=(pr=v.overscaling,v.zoom>18&&pr>2&&(pr>>=1),Math.max(Sr/(512*pr),1)*Vt.get("symbol-spacing")),nr=Vt.get("text-padding")*v.tilePixelRatio,ys=Vt.get("icon-padding")*v.tilePixelRatio,qs=Hr(Vt.get("text-max-angle")),Zs=Vt.get("icon-rotation-alignment")==="map"&&Ze!=="point",ir=$s/2;var pr;v.hasAnyIconTextFit===!1&&Re!=="none"&&(v.hasAnyIconTextFit=!0);const Zr=u.properties?+u.properties[Ta]:null,Nr=Zr&&v.elevationFeatureIdToIndex?v.elevationFeatureIdToIndex.get(Zr):65535,jr=(gr,qr,tn)=>{if(qr.x<0||qr.x>=Sr||qr.y<0||qr.y>=Sr)return;let In=null;if(zs){const{x:cn,y:fa,z:xi}=xe.projectTilePoint(qr.x,qr.y,tn);In={anchor:new Yw(cn,fa,xi,0,void 0),up:xe.upVector(tn,qr.x,qr.y)}}(function(cn,fa,xi,pa,vi,Fa,Il,$i,ki,Co,vl,Fd,bl,Zl,Nc,Xl,nh,Bd,Va,zm,rc,su,$m,ah,Pl,Qh,ru,nU,YM,kf,Jve,ZM){const Zw=cn.addToLineVertexArray(fa,pa);let Xw,Dx,Rx,X4,XM,Za,nu,Ql=0,xd=0,Ox=0,Qp=0,Jp=-1,eg=-1;const cy={};let aU=fd("");const zv=xi?xi.anchor:fa,QM=nU!=="none";let JM=0,Xc=0;if(ki._unevaluatedLayout.getValue("text-radial-offset")===void 0){const nc=ki.layout.get("text-offset").evaluate(rc,{},Pl);JM=nc[0]*Od,Xc=nc[1]*Od}else JM=ki.layout.get("text-radial-offset").evaluate(rc,{},Pl)*Od,Xc=Tve;if(cn.allowVerticalPlacement&&vi.vertical){const nc=vi.vertical;if(Nc)Za=Ive(nc),$i&&(nu=Ive($i));else{const Um=ki.layout.get("text-rotate").evaluate(rc,{},Pl)+90;Rx=$$(Co,zv,fa,vl,Fd,bl,nc,Zl,Um,Xl,ZM),$i&&(X4=$$(Co,zv,fa,vl,Fd,bl,$i,Bd,Um,null,Jve))}}if(Fa){const nc=ki.layout.get("icon-rotate").evaluate(rc,{},Pl),Um=Cve(Fa,nc,$m,QM,su.iconScaleFactor),Sf=$i?Cve($i,nc,$m,QM,su.iconScaleFactor):void 0;Dx=$$(Co,zv,fa,vl,Fd,bl,Fa,Bd,nc,null,kf);const uy=function($v,uR,e6,yjt,vjt,rDe,nDe,bjt,oZs,t1e){const aDe=$v.layers[0],iDe=aDe.appearances;let t6=uR.length;if(e6&&(t6=Math.max(t6,e6.length)),iDe.length===0)return t6;const[_jt,wjt]=yjt.get("icon-size-scale-range"),jjt=He(1,_jt,wjt);for(const cU of iDe)if(cU.hasLayoutProperty("icon-image")){const oDe=aDe.getAppearanceValueAndResolveTokens(cU,"icon-image",rDe,nDe,t1e);if(oDe){const lDe=$v.getResolvedImageFromTokens(oDe);if(lDe){const cDe=cU.hasLayoutProperty("icon-size")?cU.getUnevaluatedLayoutProperty("icon-size"):vjt._values["icon-size"],Njt=ZD(lDe,H4($v.zoom,cDe,$v.worldview,t1e),cDe,nDe,$v.zoom,rDe,$v.pixelRatio,jjt,$v.worldview,t1e),dDe=bjt.get(Njt.iconPrimary.toString());dDe&&(t6=Math.max(t6,Hwt(dDe)))}}}return t6}(cn,Um,Sf,ki.layout,ki._unevaluatedLayout,rc,Pl,cn.iconAtlasPositions,0,ah);Ql=4*uy;const iU=ki.layout.get("icon-size").evaluate(rc,{},Pl,ah),oU=su.compositeIconSizes?su.compositeIconSizes[0].evaluate(rc,{},Pl,ah):0,e1e=su.compositeIconSizes?su.compositeIconSizes[1].evaluate(rc,{},Pl,ah):0,lU=Mve(cn.layerIds[0],cn.iconSizeData,iU,su.iconScaleFactor,oU,e1e);cn.addSymbols(cn.icon,Um,lU,zm,Va,rc,void 0,xi,fa,Zw.lineStartIndex,Zw.lineLength,-1,ah,Pl,Qh,ru,cn.symbolInstances.length,uy),Jp=cn.icon.placedSymbolArray.length-1,Sf&&(xd=4*uy,cn.addSymbols(cn.icon,Sf,lU,zm,Va,rc,Xp.vertical,xi,fa,Zw.lineStartIndex,Zw.lineLength,-1,ah,Pl,Qh,ru,cn.symbolInstances.length,uy),eg=cn.icon.placedSymbolArray.length-1)}for(const nc in vi.horizontal){const Um=nc,Sf=vi.horizontal[Um];Xw||(aU=fd(Sf.text),Nc?XM=Ive(Sf):Xw=$$(Co,zv,fa,vl,Fd,bl,Sf,Zl,ki.layout.get("text-rotate").evaluate(rc,{},Pl),Xl,ZM));const uy=Sf.positionedLines.length===1;if(Ox+=OLe(cn,xi,fa,Sf,Il,ki,Nc,rc,Xl,Zw,vi.vertical?Xp.horizontal:Xp.horizontalOnly,uy?Ywt(vi.horizontal):[Um],cy,Jp,su,ah,Pl,cn.symbolInstances.length,Qh),uy)break}vi.vertical&&(Qp+=OLe(cn,xi,fa,vi.vertical,Il,ki,Nc,rc,Xl,Zw,Xp.vertical,["vertical"],cy,eg,su,ah,Pl,cn.symbolInstances.length,Qh));let Pc=-1;const yd=(nc,Um)=>nc?Math.max(nc,Um):Um;Pc=yd(XM,Pc),Pc=yd(Za,Pc),Pc=yd(nu,Pc);const dy=Pc>-1?1:0;cn.glyphOffsetArray.length>=65535&&Gr("Too many glyphs being rendered in a tile. See https://github.com/mapbox/mapbox-gl-js/issues/2907"),rc.sortKey!==void 0&&cn.addToSortKeyRanges(cn.symbolInstances.length,rc.sortKey),cn.symbolInstances.emplaceBack(fa.x,fa.y,zv.x,zv.y,zv.z,cy.right>=0?cy.right:-1,cy.center>=0?cy.center:-1,cy.left>=0?cy.left:-1,cy.vertical>=0?cy.vertical:-1,Jp,eg,aU,Xw!==void 0?Xw:cn.collisionBoxArray.length,Xw!==void 0?Xw+1:cn.collisionBoxArray.length,Rx!==void 0?Rx:cn.collisionBoxArray.length,Rx!==void 0?Rx+1:cn.collisionBoxArray.length,Dx!==void 0?Dx:cn.collisionBoxArray.length,Dx!==void 0?Dx+1:cn.collisionBoxArray.length,X4||cn.collisionBoxArray.length,X4?X4+1:cn.collisionBoxArray.length,vl,Ox,Qp,Ql,xd,dy,0,JM,Xc,Pc,0,QM?1:0,YM)})(v,qr,In,gr,f,w,I,C,v.layers[0],v.collisionBoxArray,u.index,u.sourceLayerIndex,v.index,nr,nt,Y,0,ys,Zs,qe,u,L,se,oe,de,we,Ce,Re,Nr,ut,xt,bt)};if(Ze==="line")for(const gr of b$(u.geometry,0,0,Sr,Sr)){const qr=Vwt(gr,$s,qs,f.vertical||$t,w,24,Hs,v.overscaling,Sr);for(const tn of qr)$t&&n2t(v,$t.text,ir,tn)||jr(gr,tn,de)}else if(Ze==="line-center"){for(const gr of u.geometry)if(gr.length>1){const qr=qwt(gr,qs,f.vertical||$t,w,24,Hs);qr&&jr(gr,qr,de)}}else if(u.type==="Polygon")for(const gr of ID(u.geometry,0)){const qr=Wwt(gr,16);jr(gr[0],new Yw(qr.x,qr.y,0,0,void 0),de)}else if(u.type==="LineString")for(const gr of u.geometry)jr(gr,new Yw(gr[0].x,gr[0].y,0,0,void 0),de);else if(u.type==="Point")for(const gr of u.geometry)for(const qr of gr)jr([qr],new Yw(qr.x,qr.y,0,0,void 0),de)}const Ave=255,G4=Ave*Kw;function OLe(v,u,f,w,C,I,L,B,U,Y,se,oe,de,xe,we,Ce,Re,qe,nt){const Ze=ELe(0,w,U,I,L,B,C,v.allowVerticalPlacement,void 0,we.textScaleFactor),ut=I.layout.get("text-size").evaluate(B,{},Re),xt=we.compositeTextSizes?we.compositeTextSizes[0].evaluate(B,{},Re):0,bt=we.compositeTextSizes?we.compositeTextSizes[1].evaluate(B,{},Re):0,Ht=Mve(v.layerIds[0],v.textSizeData,ut,we.textScaleFactor,xt,bt);v.addSymbols(v.text,Ze,Ht,U,L,B,se,u,f,Y.lineStartIndex,Y.lineLength,xe,Ce,Re,nt,!1,qe,Ze.length);for(const Rt of oe)de[Rt]=v.text.placedSymbolArray.length-1;return 4*Ze.length}function Mve(v,u,f,w,C,I){const L=u;let B=null;return L.kind==="source"?(B=[Kw*f*w],B[0]>G4&&Gr(`${v}: Value for "text-size" is >= ${Ave}. Reduce your "text-size".`)):L.kind==="composite"&&(B=[Kw*C*w,Kw*I*w],(B[0]>G4||B[1]>G4)&&Gr(`${v}: Value for "text-size" is >= ${Ave}. Reduce your "text-size".`)),B}function z$(v){for(const u in v)return v[u];return null}function $$(v,u,f,w,C,I,L,B,U,Y,se){let oe,de,xe,we;if(oe=se?se.top:L.top,de=se?se.bottom:L.bottom,xe=se?se.left:L.left,we=se?se.right:L.right,vve(L)&&L.collisionPadding){const Ce=L.collisionPadding;xe-=Ce[0],oe-=Ce[1],we+=Ce[2],de+=Ce[3]}if(U){const Ce=new ds(xe,oe),Re=new ds(we,oe),qe=new ds(xe,de),nt=new ds(we,de),Ze=Hr(U);let ut=new ds(0,0);Y&&(ut=new ds(Y[0],Y[1])),Ce._rotateAround(Ze,ut),Re._rotateAround(Ze,ut),qe._rotateAround(Ze,ut),nt._rotateAround(Ze,ut),xe=Math.min(Ce.x,Re.x,qe.x,nt.x),we=Math.max(Ce.x,Re.x,qe.x,nt.x),oe=Math.min(Ce.y,Re.y,qe.y,nt.y),de=Math.max(Ce.y,Re.y,qe.y,nt.y)}return v.emplaceBack(u.x,u.y,u.z,f.x,f.y,xe,oe,we,de,B,w,C,I),v.length-1}function Ive(v){vve(v)&&v.collisionPadding&&(v.top-=v.collisionPadding[1],v.bottom+=v.collisionPadding[3]);const u=v.bottom-v.top;return u>0?Math.max(10,u):null}function n2t(v,u,f,w){const C=v.compareText;if(u in C){const I=C[u];for(let L=I.length-1;L>=0;L--)if(w.dist(I[L])Ze&&(ut(bt,zs,Rt,Vt,js,Es),ut(zs,Ht,js,Es,Bt,$t))}ut(oe,de,w,I,C,I),ut(de,xe,C,I,C,L),ut(xe,we,C,L,w,L),ut(we,oe,w,L,w,I),Ce-=Ze,Re-=Ze,qe+=Ze,nt+=Ze;const xt=1/Math.max(qe-Ce,nt-Re);return{scale:xt,x:Ce*xt,y:Re*xt,x2:qe*xt,y2:nt*xt,projection:u}}function BLe(v,{x:u,y:f},w=0){return new ds(((u-w)*v.scale-v.x)*Sr,(f*v.scale-v.y)*Sr)}const a2t=b(new Float32Array(16));class uN{constructor(u){this.spec=u,this.name=u.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(u,f){return{x:0,y:0,z:0}}unproject(u,f){return new Zt(0,0)}projectTilePoint(u,f,w){return{x:u,y:f,z:0}}locationPoint(u,f,w,C=!0){return u._coordinatePoint(u.locationCoordinate(f,w),C)}pixelsPerMeter(u,f){return as(1,u)*f}pixelSpaceConversion(u,f,w){return 1}farthestPixelDistance(u){return FLe(u,u.pixelsPerMeter)}pointCoordinate(u,f,w,C){const I=u.horizonLineFromTop(!1),L=new ds(f,Math.max(I,w));return u.rayIntersectionCoordinate(u.pointRayIntersection(L,C))}pointCoordinate3D(u,f,w){const C=new ds(f,w);if(u.elevation)return u.elevation.pointCoordinate(C);{const I=this.pointCoordinate(u,C.x,C.y,0);return[I.x,I.y,I.z]}}isPointAboveHorizon(u,f){if(u.elevation&&u.elevation.visibleDemTiles.length)return!this.pointCoordinate3D(u,f.x,f.y);const w=u.horizonLineFromTop();return f.y0?f<-UM+w&&(f=-UM+w):f>UM-w&&(f=UM-w);const L=I/Math.pow(q$(f),C);let B=L*Math.sin(C*u),U=I-L*Math.cos(C*u);return B=.5*(B/Math.PI+.5),U=.5*(U/Math.PI+.5),{x:B,y:this.southernCenter?U:1-U,z:0}}unproject(u,f){u=(2*u-.5)*Math.PI,this.southernCenter&&(f=1-f),f=(2*(1-f)-.5)*Math.PI;const{n:w,f:C}=this,I=C-f,L=Math.sign(I),B=Math.sign(w)*Math.sqrt(u*u+I*I);let U=Math.atan2(u,Math.abs(I))*L;I*w<0&&(U-=Math.PI*Math.sign(u)*L);const Y=He(_a(U/w)+this.center[0],-180,180),se=He(_a(2*Math.atan(Math.pow(C/B,1/w))-UM),-85.051129,Ls);return new Zt(Y,this.southernCenter?-se:se)}}class zLe extends uN{constructor(u){super(u),this.wrap=!0,this.supportsWorldCopies=!0,this.supportsTerrain=!0,this.supportsFog=!0,this.supportsFreeCamera=!0,this.isReprojectedInTileSpace=!1,this.unsupportedLayers=[],this.range=null}project(u,f){return{x:Ws(u),y:sr(f),z:0}}unproject(u,f){const w=Xt(u),C=ws(f);return new Zt(w,C)}}const $Le=Hr(Ls);class d2t extends uN{project(u,f){const w=(f=Hr(f))*f,C=w*w;return{x:.5*((u=Hr(u))*(.8707-.131979*w+C*(C*(.003971*w-.001529*C)-.013791))/Math.PI+.5),y:1-.5*(f*(1.007226+w*(.015085+C*(.028874*w-.044475-.005916*C)))/Math.PI+1),z:0}}unproject(u,f){u=(2*u-.5)*Math.PI;let w=f=(2*(1-f)-1)*Math.PI,C=25,I=0,L=w*w;do{L=w*w;const Y=L*L;I=(w*(1.007226+L*(.015085+Y*(.028874*L-.044475-.005916*Y)))-f)/(1.007226+L*(.045255+Y*(.259866*L-.311325-.005916*11*Y))),w=He(w-I,-$Le,$Le)}while(Math.abs(I)>1e-6&&--C>0);L=w*w;const B=He(_a(u/(.8707+L*(L*(L*L*L*(.003971-.001529*L)-.013791)-.131979))),-180,180),U=_a(w);return new Zt(B,U)}}const ULe=Hr(Ls);class u2t extends uN{project(u,f){f=Hr(f),u=Hr(u);const w=Math.cos(f),C=2/Math.PI,I=Math.acos(w*Math.cos(u/2)),L=Math.sin(I)/I,B=.5*(u*C+2*w*Math.sin(u/2)/L)||0,U=.5*(f+Math.sin(f)/L)||0;return{x:.5*(B/Math.PI+.5),y:1-.5*(U/Math.PI+1),z:0}}unproject(u,f){let w=u=(2*u-.5)*Math.PI,C=f=(2*(1-f)-1)*Math.PI,I=25;const L=1e-6;let B=0,U=0;do{const Y=Math.cos(C),se=Math.sin(C),oe=2*se*Y,de=se*se,xe=Y*Y,we=Math.cos(w/2),Ce=Math.sin(w/2),Re=2*we*Ce,qe=Ce*Ce,nt=1-xe*we*we,Ze=nt?1/nt:0,ut=nt?Math.acos(Y*we)*Math.sqrt(1/nt):0,xt=.5*(2*ut*Y*Ce+2*w/Math.PI)-u,bt=.5*(ut*se+C)-f,Ht=.5*Ze*(xe*qe+ut*Y*we*de)+1/Math.PI,Rt=Ze*(Re*oe/4-ut*se*Ce),Vt=.125*Ze*(oe*Ce-ut*se*xe*Re),Bt=.5*Ze*(de*we+ut*qe*Y)+.5,$t=Rt*Vt-Bt*Ht;B=(bt*Rt-xt*Bt)/$t,U=(xt*Vt-bt*Ht)/$t,w=He(w-B,-Math.PI,Math.PI),C=He(C-U,-ULe,ULe)}while((Math.abs(B)>L||Math.abs(U)>L)&&--I>0);return new Zt(_a(w),_a(C))}}class qLe extends uN{constructor(u){super(u),this.center=u.center||[0,0],this.parallels=u.parallels||[0,0],this.cosPhi=Math.max(.01,Math.cos(Hr(this.parallels[0]))),this.scale=1/(2*Math.max(Math.PI*this.cosPhi,1/this.cosPhi)),this.wrap=!0,this.supportsWorldCopies=!0}project(u,f){const{scale:w,cosPhi:C}=this;return{x:Hr(u)*C*w+.5,y:-Math.sin(Hr(f))/C*w+.5,z:0}}unproject(u,f){const{scale:w,cosPhi:C}=this,I=-(f-.5)/w,L=He(_a((u-.5)/w)/C,-180,180),B=Math.asin(He(I*C,-1,1)),U=He(_a(B),-85.051129,Ls);return new Zt(L,U)}}class h2t extends zLe{constructor(u){super(u),this.requiresDraping=!0,this.supportsWorldCopies=!1,this.supportsFog=!0,this.zAxisUnit="pixels",this.unsupportedLayers=["debug"],this.range=[3,5]}projectTilePoint(u,f,w){const C=kD(u,f,w);return tt(C,C,SD(bb(w))),{x:C[0],y:C[1],z:C[2]}}locationPoint(u,f,w){const C=It(f.lat,f.lng),I=Pe([],C),L=w?u._centerAltitude+w:u.elevation?u.elevation.getAtPointOrZero(u.locationCoordinate(f),u._centerAltitude):u._centerAltitude;We(C,C,I,as(1,0)*Sr*L);const B=b(new Float64Array(16));return k(B,u.pixelMatrix,u.globeMatrix),tt(C,C,B),new ds(C[0],C[1])}pixelsPerMeter(u,f){return as(1,0)*f}pixelSpaceConversion(u,f,w){const C=as(1,u)*f,I=jn(as(1,45)*f,C,w);return this.pixelsPerMeter(u,f)/I}createTileMatrix(u,f,w){const C=Sye(bb(w.canonical));return k(new Float64Array(16),u.globeMatrix,C)}createInversionMatrix(u,f){const{center:w}=u,C=SD(bb(f));return D(C,C,Hr(w.lng)),A(C,C,Hr(w.lat)),E(C,C,[u._pixelsPerMercatorPixel,u._pixelsPerMercatorPixel,1]),Float32Array.from(C)}pointCoordinate(u,f,w,C){return aIe(u,f,w,!0)||new en(0,0)}pointCoordinate3D(u,f,w){const C=this.pointCoordinate(u,f,w,0);return[C.x,C.y,C.z]}isPointAboveHorizon(u,f){return!aIe(u,f.x,f.y,!1)}farthestPixelDistance(u){const f=function(C,I){const L=C.cameraToCenterDistance,B=C._centerAltitude*I,U=C._camera,Y=C._camera.forward(),se=ne([],ve([],Y,-L),[0,0,B]),oe=C.worldSize/(2*Math.PI),de=[0,0,-oe],xe=C.width/C.height,we=Math.tan(C.fovAboveCenter),Ce=ve([],U.up(),we),Re=ve([],U.right(),we*xe),qe=Pe([],ne([],ne([],Y,Ce),Re)),nt=[];let Ze;if(new ei(se,qe).closestPointOnSphere(de,oe,nt)){const ut=ne([],nt,de),xt=Qe([],ut,se);Ze=Math.cos(C.fovAboveCenter)*re(xt)}else{const ut=Qe([],se,de),xt=Qe([],de,se);Pe(xt,xt);const bt=re(ut)-oe;Ze=Math.sqrt(bt*(bt+2*oe));const Ht=Math.acos(Ze/(oe+bt))-Math.acos(Ie(Y,xt));Ze*=Math.cos(Ht)}return 1.01*Ze}(u,this.pixelsPerMeter(u.center.lat,u.worldSize)),w=Hw(u.zoom);if(w>0){const C=FLe(u,as(1,u.center.lat)*u.worldSize),I=u.worldSize/(2*Math.PI),L=Math.max(u.width,u.height)/u.worldSize*Math.PI;return jn(f,C+I*(1-Math.cos(L)),Math.pow(w,10))}return f}upVector(u,f,w){return kD(f,w,u,1)}upVectorScale(u){return{metersToTile:s$(n$(bb(u)))}}}function VLe(v){const u=v.parallels,f=!!u&&Math.abs(u[0]+u[1])<.01;switch(v.name){case"mercator":return new zLe(v);case"equirectangular":return new l2t(v);case"naturalEarth":return new d2t(v);case"equalEarth":return new o2t(v);case"winkelTripel":return new u2t(v);case"albers":return f?new qLe(v):new i2t(v);case"lambertConformalConic":return f?new qLe(v):new c2t(v);case"globe":return new h2t(v)}throw new Error(`Invalid projection name: ${v.name}`)}class m2t{constructor(u,f){this.lastParams=null,this.lastAllFeaturesIndex=-2,this.appearancesVersion=f,this.appearances=u;const w=u.map(C=>function(I){if(!I.condition)return{featureDependent:!1,stateDependent:!1,zoomDependent:!1,pitchDependent:!1,brightnessDependent:!1,worldviewDependent:!1};const L=I.condition.expression;return{featureDependent:!Z0(L),stateDependent:!X0(L),zoomDependent:!Wh(L,["zoom"]),pitchDependent:!Wh(L,["pitch"]),brightnessDependent:!Wh(L,["brightness","measure-light"]),worldviewDependent:!Wh(L,["worldview"])}}(C));this.anyFeatureDependent=w.some(C=>C.featureDependent),this.anyStateDependent=w.some(C=>C.stateDependent)}update(u,f){const w=this.lastParams,C=!w||w.zoom!==u.zoom||w.pitch!==(u.pitch||0)||w.brightness!==(u.brightness||0)||w.worldview!==u.worldview;this.lastParams={zoom:u.zoom,pitch:u.pitch||0,brightness:u.brightness||0,worldview:u.worldview};const I=f&&this.anyStateDependent;if(!C&&!I&&this.lastAllFeaturesIndex!==-2)return{kind:"no-changes"};if(!this.anyFeatureDependent&&!I){const L=this.evaluateAllFeatures(u);return L===this.lastAllFeaturesIndex?{kind:"no-changes"}:(this.lastAllFeaturesIndex=L,{kind:"all-features",appearanceIndex:L})}return{kind:"per-feature"}}evaluateAllFeatures(u){for(let f=0;f{for(let C=0;CL-B),I=new Map;for(const L of C){const B=w.get(L);I.set(L,new No(B))}return f&&(this.cachedBatchIndices=C,this.cachedBatchSegments=I),{batchIndices:C,batchSegments:I}}snapshotSymbolVertexData(u,f){const w=u*VM;return this.layoutVertexArray.uint16.slice(w,w+f*VM)}restoreSymbolVertexData(u,f){this.layoutVertexArray.uint16.set(f,u*VM)}updateSymbolVertexData(u,f,w,C,I,L,B,U,Y,se,oe,de,xe){const we=this.layoutVertexArray.uint16,Ce=u*VM;we[Ce]=f,we[Ce+1]=w,we[Ce+2]=C,we[Ce+3]=I,we[Ce+4]=L,we[Ce+5]=B,we[Ce+6]=U,we[Ce+7]=Y,we[Ce+8]=se,we[Ce+9]=oe,we[Ce+10]=de,we[Ce+11]=xe}upload(u,f,w,C,I,L){this.isEmpty()||(w&&(this.cachedBatchIndices=null,this.cachedBatchSegments=null,this.layoutVertexBuffer=u.createVertexBuffer(this.layoutVertexArray,gwt.members,!!L),this.indexBuffer=u.createIndexBuffer(this.indexArray,f),this.dynamicLayoutVertexBuffer=u.createVertexBuffer(this.dynamicLayoutVertexArray,ywt.members,!0),this.opacityVertexBuffer=u.createVertexBuffer(this.opacityVertexArray,p2t,!0),this.iconTransitioningVertexArray.length>0&&(this.iconTransitioningVertexBuffer=u.createVertexBuffer(this.iconTransitioningVertexArray,wwt.members,!0)),this.globeExtVertexArray.length>0&&(this.globeExtVertexBuffer=u.createVertexBuffer(this.globeExtVertexArray,xwt.members,!0)),!this.zOffsetVertexBuffer&&(this.zOffsetVertexArray.length>0||I)&&(this.zOffsetVertexBuffer=u.createVertexBuffer(this.zOffsetVertexArray,vwt.members,!0)),!this.orientationVertexBuffer&&this.orientationVertexArray&&this.orientationVertexArray.length>0&&(this.orientationVertexBuffer=u.createVertexBuffer(this.orientationVertexArray,_wt.members,!0)),this.opacityVertexBuffer.itemSize=1,this.featureIdArray&&this.featureIdArray.length>0&&(this.featureIdBuffer=u.createVertexBuffer(this.featureIdArray,bwt.members,!1))),(w||C)&&(this.programConfigurations.upload(u),this.uboBinder&&this.uboBinder.upload(u)))}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(),this.featureIdBuffer&&this.featureIdBuffer.destroy(),this.uboBinder&&this.uboBinder.destroy())}}Pr(Pve,"SymbolBuffers",{omit:["cachedBatchIndices","cachedBatchSegments"]});class Lve{constructor(u,f,w){this.layoutVertexArray=new u,this.layoutAttributes=f,this.indexArray=new w,this.segments=new No,this.collisionVertexArray=new I4,this.collisionVertexArrayExt=new Pv}upload(u){this.layoutVertexBuffer=u.createVertexBuffer(this.layoutVertexArray,this.layoutAttributes),this.indexBuffer=u.createIndexBuffer(this.indexArray),this.collisionVertexBuffer=u.createVertexBuffer(this.collisionVertexArray,jwt.members,!0),this.collisionVertexBufferExt=u.createVertexBuffer(this.collisionVertexArrayExt,Nwt.members,!0)}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.segments.destroy(),this.collisionVertexBuffer.destroy(),this.collisionVertexBufferExt.destroy())}}Pr(Lve,"CollisionBuffers");class Ov{constructor(u){this.collisionBoxArray=u.collisionBoxArray,this.zoom=u.zoom,this.overscaling=u.overscaling,this.layers=u.layers,this.layerIds=this.layers.map(L=>L.fqid),this.index=u.index,this.pixelRatio=u.pixelRatio,this.sourceLayerIndex=u.sourceLayerIndex,this.hasPattern=!1,this.hasRTLText=!1,this.fullyClipped=!1,this.hasAnyIconTextFit=!1,this.sortKeyRanges=[],this.collisionCircleArray=[],this.placementInvProjMatrix=b([]),this.placementViewportMatrix=b([]);const f=this.layers[0]._unevaluatedLayout._values;this.worldview=u.worldview,this.localizable=u.localizable,this.maxUniformBufferBindings=u.maxUniformBufferBindings,this.maxUniformBlockSizeDwords=u.maxUniformBlockSizeDwords,this.disableSymbolUBO=u.disableSymbolUBO,this.textSizeData=H4(this.zoom,f["text-size"],this.worldview,u.availableImages),this.iconSizeData=H4(this.zoom,f["icon-size"],this.worldview,u.availableImages);const w=this.layers[0].layout,C=w.get("symbol-sort-key"),I=w.get("symbol-z-order");this.lut=u.lut,this.canOverlap=w.get("text-allow-overlap")||w.get("icon-allow-overlap")||w.get("text-ignore-placement")||w.get("icon-ignore-placement"),this.sortFeaturesByKey=I!=="viewport-y"&&C.constantOr(1)!==void 0,this.sortFeaturesByY=(I==="viewport-y"||I==="auto"&&!this.sortFeaturesByKey)&&this.canOverlap,this.writingModes=w.get("text-writing-mode").map(L=>Xp[L]),this.stateDependentLayerIds=this.layers.filter(L=>L.isStateDependent()).map(L=>L.id),this.sourceID=u.sourceID,this.projection=u.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.featureAppearances=null,this.featureAppearanceData=new Map}hasAnyAppearanceLayoutProperty(u){const f=this.layers[0].getAppearances();if(!f||f.length===0)return!1;const w=Array.isArray(u)?u:[u];return f.some(C=>w.some(I=>C.hasLayoutProperty(I)))}getAppearanceFeatureData(u){return this.featureAppearanceData.get(u)}createArrays(){this.text=new Pve(new Fe(this.layers,{zoom:this.zoom,lut:this.lut},u=>u.startsWith("text")||u.startsWith("symbol"))),this.icon=new Pve(new Fe(this.layers,{zoom:this.zoom,lut:this.lut},u=>u.startsWith("icon")||u.startsWith("symbol"))),this.disableSymbolUBO||(this.text.uboBinder=new pve(this.layers[0],this.zoom,this.lut,!0,"",this.maxUniformBufferBindings,this.maxUniformBlockSizeDwords),this.icon.uboBinder=new pve(this.layers[0],this.zoom,this.lut,!1,"",this.maxUniformBufferBindings,this.maxUniformBlockSizeDwords)),this.glyphOffsetArray=new Zz,this.lineVertexArray=new D4,this.symbolInstances=new Yz}calculateGlyphDependencies(u,f,w,C,I){for(const L of u){const B=L.codePointAt(0);if(B===void 0)break;if(f[B]=!0,C&&I&&B<=65535){const U=HD[L];U&&(f[U.charCodeAt(0)]=!0)}}}calculateEffectiveAppearanceIconSize(u,f,w,C,I,L,B){if(!u.hasLayoutProperty("icon-size"))return B*L;let U=1;const Y=u.getUnevaluatedLayoutProperty("icon-size"),se=H4(this.zoom,Y,this.worldview,I),oe=zM(se,f);if(se.kind!=="constant"&&se.kind!=="camera"||(U=oe.uSize),se.kind==="composite"){const{minZoom:de,maxZoom:xe}=se,we=Y.possiblyEvaluate(new wa(de,{worldview:this.worldview}),C),Ce=Y.possiblyEvaluate(new wa(xe,{worldview:this.worldview}),C),Re=we.evaluate(w,{},C,I);U=Re+(Ce.evaluate(w,{},C,I)-Re)*oe.uSizeT}return se.kind==="source"&&(U=Y.possiblyEvaluate(new wa(this.zoom,{worldview:this.worldview}),C).evaluate(w,{},C,I)),U*L}updateFootprints(u,f){}updateReplacement(u,f){if(f.updateTime===this.replacementUpdateTime)return!1;this.replacementUpdateTime=f.updateTime;const w=f.getReplacementRegionsForTile(u.toUnwrapped(),!0);return!f$(this.activeReplacements,w)&&(this.activeReplacements=w,!0)}getResolvedImageFromTokens(u){return typeof u=="string"?Id.build(u):u}populate(u,f,w,C){const I=this.layers[0],L=I.layout,B=this.projection.name==="globe",U=L.get("text-font"),Y=L.get("text-field"),se=L.get("icon-image"),[oe,de]=L.get("icon-size-scale-range"),xe=He(f.scaleFactor||1,oe,de),[we,Ce]=L.get("text-size-scale-range"),Re=He(f.scaleFactor||1,we,Ce),qe=(Y.value.kind!=="constant"||Y.value.value instanceof Md&&!Y.value.value.isEmpty()||Y.value.value.toString().length>0)&&(U.value.kind!=="constant"||U.value.value.length>0),nt=se.value.kind!=="constant"||!!se.value.value||Object.keys(se.parameters).length>0,Ze=this.hasAnyAppearanceLayoutProperty("icon-image"),ut=L.get("symbol-sort-key");if(this.features=[],this.featureAppearanceData=new Map,!qe&&!nt&&!Ze)return;const xt=f.iconDependencies,bt=f.glyphDependencies,Ht=f.availableImages,Rt=new wa(this.zoom,{worldview:this.worldview,activeFloors:f.activeFloors}),Vt=Bt=>{const $t=Bt.id.toString();xt.has($t)?xt.get($t).push(Bt):xt.set($t,[Bt])};for(const Bt of u){const{feature:$t,id:js,index:Es,sourceLayerIndex:zs}=Bt,Hs=I._featureFilter.needGeometry,$s=Oa($t,Hs);if(!I._featureFilter.filter(Rt,$s,w))continue;if(Hs||($s.geometry=Ln($t,w,C)),B&&$t.type!==1&&w.z<=5){const Nr=$s.geometry,jr=.98078528056,gr=(qr,tn)=>Ie(kD(qr.x,qr.y,w,1),kD(tn.x,tn.y,w,1)){if(!Nr.getLayoutProperty("icon-image"))return;const jr=this.getCombinedIconPrimary(Nr,qs,$s,w,Ht,pr,xe);jr&&Vt(jr)}),nr){const Nr=U.evaluate($s,{},w).join(","),jr=L.get("text-rotation-alignment")==="map"&&L.get("symbol-placement")!=="point";this.allowVerticalPlacement=this.writingModes&&this.writingModes.indexOf(Xp.vertical)>=0;for(const gr of nr.sections)if(gr.image){const qr=gr.image.getPrimary().scaleSelf(this.pixelRatio*Re),tn=qr.id.toString(),In=xt.get(tn)||[];In.push(qr),xt.set(tn,In)}else{const qr=Sh(nr.toString()),tn=gr.fontStack||Nr,In=bt[tn]=bt[tn]||{};this.calculateGlyphDependencies(gr.text,In,jr,this.allowVerticalPlacement,qr)}}}if(L.get("symbol-placement")==="line"&&(this.features=function(Bt){const $t={},js={},Es=[];let zs=0;function Hs(qs){Es.push(Bt[qs]),zs++}function $s(qs,Zs,ir){const pr=js[qs];return delete js[qs],js[Zs]=pr,Es[pr].geometry[0].pop(),Es[pr].geometry[0]=Es[pr].geometry[0].concat(ir[0]),pr}function nr(qs,Zs,ir){const pr=$t[Zs];return delete $t[Zs],$t[qs]=pr,Es[pr].geometry[0].shift(),Es[pr].geometry[0]=ir[0].concat(Es[pr].geometry[0]),pr}function ys(qs,Zs,ir){const pr=ir?Zs[0][Zs[0].length-1]:Zs[0][0];return`${qs}:${pr.x}:${pr.y}`}for(let qs=0;qsqs.geometry)}(this.features)),L.get("symbol-elevation-reference")==="hd-road-markup"){if(this.elevationType="road",f.elevationFeatures){!this.elevationFeatures&&f.elevationFeatures.length>0&&(this.elevationFeatures=[],this.elevationFeatureIdToIndex=new Map);for(const Bt of f.elevationFeatures)this.elevationFeatureIdToIndex.set(Bt.id,this.elevationFeatures.length),this.elevationFeatures.push(Bt)}}else L.get("symbol-z-elevate")&&(this.elevationType="offset");this.elevationType!=="none"&&(this.zOffsetBuffersNeedUpload=!0),this.sortFeaturesByKey&&this.features.sort((Bt,$t)=>Bt.sortKey-$t.sortKey)}getCombinedIconPrimary(u,f,w,C,I,L,B){let U,Y;if(u.hasLayoutProperty("icon-image")){const se=f.getAppearanceValueAndResolveTokens(u,"icon-image",w,C,I);U=this.getResolvedImageFromTokens(se)}else{const se=f.getValueAndResolveTokens("icon-image",w,C,I);U=this.getResolvedImageFromTokens(se)}if(U){const se=u.hasLayoutProperty("icon-size")?u.getUnevaluatedLayoutProperty("icon-size"):f._unevaluatedLayout._values["icon-size"];Y=ZD(U,H4(this.zoom,se,this.worldview,I),se,C,this.zoom,L,this.pixelRatio,B,this.worldview,I).iconPrimary}return Y}updateSymbolInstanceIconVertices(u,f,w,C,I,L){const{canonical:B,availableImages:U,globalProperties:Y,layer:se,iconScaleFactor:oe,featureState:de,layoutIconOffset:xe,layoutIconSize:we,layoutIconRotate:Ce}=L;if(u.placedIconSymbolIndex<0)return{vertexOffsetDelta:0,hasChanges:!1};if(f.activeAppearanceIndex===w)return{vertexOffsetDelta:u.numIconVertices,hasChanges:!1};const Re=w>=0?se.appearances[w]:null;if(Re){const qe=this.getCombinedIconPrimary(Re,se,C,B,U,{sortKey:void 0,text:void 0,icon:null,index:u.featureIndex,sourceLayerIndex:u.featureIndex,geometry:[],properties:f.properties,type:"Point",id:f.id},oe);if(!qe)return{vertexOffsetDelta:0,hasChanges:!1};const nt=qe.toString(),Ze=this.iconAtlasPositions&&this.iconAtlasPositions.get(nt);if(Ze){const{appearanceIconOffset:ut,appearanceIconRotate:xt}=MLe(Re,se,C,B,xe,Ce,we,oe);let bt=P$(Ze,void 0,ut,se.layout.get("icon-anchor").evaluate(C,de,B));const Ht=Ze.sdf,Rt=se.layout.get("icon-text-fit").constantOr("none");Rt!=="none"&&f.textShaping&&f.iconTextFitPadding&&f.fontScale&&(bt=bve(bt,f.textShaping,Rt,f.iconTextFitPadding,ut,f.fontScale));const Vt=this.calculateEffectiveAppearanceIconSize(Re,Y.zoom,C,B,U,oe,we),Bt=0,$t=1+(Math.min(G4,Math.round(Vt*Kw))<<1),js=Cve(bt,xt,Ht,Rt!=="none",oe);f.isUsingAppearanceIconVertexData||(f.isUsingAppearanceIconVertexData=!0,f.layoutBasedIconVertexData=this.icon.snapshotSymbolVertexData(I,u.numIconVertices));const Es=Math.floor(u.numIconVertices/4),zs=Math.min(js.length,Es);let Hs=I;for(let nr=0;nr0||u.numVerticalGlyphVertices>0;if(!ut)return{vertexOffsetDelta:ut?u.numHorizontalGlyphVertices+u.numVerticalGlyphVertices:0,hasChanges:!1};if(f.activeAppearanceIndex===w)return{vertexOffsetDelta:u.numHorizontalGlyphVertices+u.numVerticalGlyphVertices,hasChanges:!1};const xt=w>=0?U.appearances[w]:null;if(xt&&f.textShaping){const{appearanceTextOffset:bt,appearanceTextRotate:Ht,appearanceTextSize:Rt}=ILe(xt,U,C,B,de,we,xe);f.fontScale=RLe(Rt,f.textScaleFactor);const Vt=xt.getUnevaluatedLayoutProperty("text-size");let Bt=this.textSizeData,$t=qe,js=nt;xt.hasLayoutProperty("text-size")&&(Bt=H4(this.zoom,Vt,this.worldview,Ze),$t=this.textSizeData.kind==="composite"?this.textSizeData.minZoom:0,js=this.textSizeData.kind==="composite"?this.textSizeData.maxZoom:0);const Es=f.textShaping.bottom-de[1],zs=f.textShaping.left-de[0],Hs=f.textShaping.right-de[0];f.textShaping.top=bt[1]+(f.textShaping.top-de[1]),f.textShaping.bottom=bt[1]+Es,f.textShaping.left=bt[0]+zs,f.textShaping.right=bt[0]+Hs;const $s=ELe(0,f.textShaping,bt,U,!1,C,se,this.allowVerticalPlacement,Ht),nr=Rt&&Bt.kind==="composite"?Vt.possiblyEvaluate(new wa($t,{}),B).evaluate(C,oe,B):Ce,ys=Rt&&Bt.kind==="composite"?Vt.possiblyEvaluate(new wa(js,{}),B).evaluate(C,oe,B):Re,qs=Mve(xt.name,Bt,Rt,Y,nr,ys),Zs=Array.isArray(qs)?qs[1]:Rt,ir=0,pr=1+(Math.min(G4,Math.round(Zs*Kw))<<1);f.isUsingAppearanceTextVertexData||(f.isUsingAppearanceTextVertexData=!0,f.layoutBasedTextVertexData=this.text.snapshotSymbolVertexData(I,u.numHorizontalGlyphVertices+u.numVerticalGlyphVertices));for(let Zr=0;Zr<$s.length&&Zr<(u.numHorizontalGlyphVertices+u.numVerticalGlyphVertices)/4;++Zr){const Nr=$s[Zr],jr=Nr.glyphOffset[1],gr=u.tileAnchorX,qr=u.tileAnchorY,tn=I+4*Zr;this.text.updateSymbolVertexData(tn,gr,qr,Math.round(32*Nr.tl.x),Math.round(32*(jr+Nr.tl.y)),Nr.texPrimary.x,Nr.texPrimary.y,ir,pr,Nr.pixelOffsetTL.x,Nr.pixelOffsetTL.y,Nr.minFontScaleX,Nr.minFontScaleY),this.text.updateSymbolVertexData(tn+1,gr,qr,Math.round(32*Nr.tr.x),Math.round(32*(jr+Nr.tr.y)),Nr.texPrimary.x+Nr.texPrimary.w,Nr.texPrimary.y,ir,pr,Nr.pixelOffsetBR.x,Nr.pixelOffsetTL.y,Nr.minFontScaleX,Nr.minFontScaleY),this.text.updateSymbolVertexData(tn+2,gr,qr,Math.round(32*Nr.bl.x),Math.round(32*(jr+Nr.bl.y)),Nr.texPrimary.x,Nr.texPrimary.y+Nr.texPrimary.h,ir,pr,Nr.pixelOffsetTL.x,Nr.pixelOffsetBR.y,Nr.minFontScaleX,Nr.minFontScaleY),this.text.updateSymbolVertexData(tn+3,gr,qr,Math.round(32*Nr.br.x),Math.round(32*(jr+Nr.br.y)),Nr.texPrimary.x+Nr.texPrimary.w,Nr.texPrimary.y+Nr.texPrimary.h,ir,pr,Nr.pixelOffsetBR.x,Nr.pixelOffsetBR.y,Nr.minFontScaleX,Nr.minFontScaleY)}return{vertexOffsetDelta:u.numHorizontalGlyphVertices+u.numVerticalGlyphVertices,hasChanges:!0}}return f.isUsingAppearanceTextVertexData?(this.text.restoreSymbolVertexData(I,f.layoutBasedTextVertexData),f.isUsingAppearanceTextVertexData=!1,{vertexOffsetDelta:f.layoutBasedTextVertexData.length/VM,hasChanges:!0}):{vertexOffsetDelta:u.numHorizontalGlyphVertices+u.numVerticalGlyphVertices,hasChanges:!1}}update(u,f,w,C,I,L,B,U){if(this.text.programConfigurations.updatePaintArrays(u,f,I,w,C,L,B,this.worldview),this.icon.programConfigurations.updatePaintArrays(u,f,I,w,C,L,B,this.worldview),U){if(L)this.text.uboBinder&&this.text.uboBinder.updateDynamicExpressions(I[0],f,U,w,u,B),this.icon.uboBinder&&this.icon.uboBinder.updateDynamicExpressions(I[0],f,U,w,u,B);else if(Object.keys(u).length>0){const Y=new Set(Object.keys(u).map(se=>{const oe=Number(se);return!isNaN(oe)&&Number.isSafeInteger(oe)&&String(oe)===se?oe:se}));this.text.uboBinder&&this.text.uboBinder.updateFeatures(Y,I[0],f,U,w,u,B),this.icon.uboBinder&&this.icon.uboBinder.updateFeatures(Y,I[0],f,U,w,u,B)}}}updateRoadElevation(u){if(this.elevationType!=="road"||!this.elevationFeatures||this.elevationStateComplete)return;this.elevationStateComplete=!0,this.hasAnyZOffset=!1;let f=!1;const w=Js(u),C=1/w;let I=!1,L=!1;for(let B=0;B0||de>0,Re=xe>0,qe=this.elevationFeatures[U.elevationFeatureIndex];if(qe){const nt=new ds(U.tileAnchorX,U.tileAnchorY),Ze=.075+qe.pointElevation(nt);U.zOffset!==Ze&&(f=!0,U.zOffset=Ze),Ze!==0&&(this.hasAnyZOffset=!0);const ut=qe.computeSlopeNormal(nt,C),xt=xs(at(),ie(0,0,1),ut);ct(Y,Y,xt),ct(se,se,xt),Y[2]*=w,se[2]*=w,Y[0]===1&&Y[1]===0&&Y[2]===0&&se[0]===0&&se[1]===1&&se[2]===0||(I=I||Ce,L=L||Re)}if(Ce&&(V$(this.text.orientationVertexArray,oe,Y,se),V$(this.text.orientationVertexArray,de,Y,se)),Re){const{placedIconSymbolIndex:nt,verticalPlacedIconSymbolIndex:Ze}=U;nt>=0&&V$(this.icon.orientationVertexArray,xe,Y,se),Ze>=0&&V$(this.icon.orientationVertexArray,we,Y,se)}}I||(this.text.orientationVertexArray=void 0),L||(this.icon.orientationVertexArray=void 0),f&&(this.zOffsetBuffersNeedUpload=!0,this.zOffsetSortDirty=!0)}updateZOffset(){const u=(I,L,B)=>{w+=L,w>I.length&&I.resize(w);for(let U=-L;U<0;U++)I.emplace(U+w,B)},f=(I,L,B)=>{C+=L,C>I.length&&I.resize(C);for(let U=-L;U<0;U++)I.emplace(U+C,B)};if(!this.zOffsetBuffersNeedUpload)return;this.zOffsetBuffersNeedUpload=!1;let w=0,C=0;for(let I=0;I0;if((B>0||U>0)&&(u(this.text.zOffsetVertexArray,B,se),u(this.text.zOffsetVertexArray,U,se)),oe){const{placedIconSymbolIndex:de,verticalPlacedIconSymbolIndex:xe}=L;de>=0&&f(this.icon.zOffsetVertexArray,Y,se),xe>=0&&f(this.icon.zOffsetVertexArray,L.numVerticalIconVertices,se)}}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(u,f,w,C,I){!this.uploaded&&this.hasDebugData()&&(this.textCollisionBox.upload(u),this.iconCollisionBox.upload(u)),this.text.upload(u,this.sortFeaturesByY,!this.uploaded,this.text.programConfigurations.needsUpload,this.zOffsetBuffersNeedUpload,this.hasAppearances),this.hasAppearances===null&&(this.hasAppearances=this.layers.some(L=>L.appearances&&L.appearances.length>0)),this.icon.upload(u,this.sortFeaturesByY,!this.uploaded,this.icon.programConfigurations.needsUpload,this.zOffsetBuffersNeedUpload,this.hasAppearances),this.uploaded=!0}updateAppearances(u,f,w,C,I,L=!1){const B={hasLayoutChanges:!1,hasUboChanges:!1};if(!u||!w||!this.featureAppearanceData)return B;const U=f||{},Y=this.icon.layoutVertexArray&&this.icon.layoutVertexArray.length>0&&this.icon.layoutVertexArray.arrayBuffer,se=this.text.layoutVertexArray&&this.text.layoutVertexArray.length>0&&this.text.layoutVertexArray.arrayBuffer;if(!Y&&!se)return B;const oe=this.layers[0],de=oe.layout;this.featureAppearances&&this.featureAppearances.appearancesVersion===oe.appearancesVersion||(this.featureAppearances=new m2t(oe.appearances,oe.appearancesVersion));const xe=this.featureAppearances.update(C,L);if(xe.kind==="no-changes")return B;let we=1,Ce=0,Re=!1,qe=!1;if(Y){const[bt,Ht]=de.get("icon-size-scale-range");we=He(1,bt,Ht)}let nt=1,Ze=0,ut=!1;if(se){const[bt,Ht]=de.get("text-size-scale-range");nt=He(1,bt,Ht)}const xt=new Map;if(I&&w)for(const bt of w){const Ht=I.getImage(bt,oe.scope);if(Ht){const Rt=new Im(bt.toString());xt.set(Rt.toString(),Ht)}}for(let bt=0;btHs.isActive({globals:C,feature:$t,canonical:u,featureState:Bt})):-1;js=zs>=0?zs:-1}const Es=Rt.activeAppearanceIndex!==js;if(se){const zs=de.get("text-size"),Hs=this.textSizeData.kind==="composite"?this.textSizeData.minZoom:0,$s=this.textSizeData.kind==="composite"?this.textSizeData.maxZoom:0,nr={canonical:u,layer:oe,featureState:Bt,availableImages:w,textScaleFactor:nt,imageMap:xt,layoutTextOffset:de.get("text-offset").evaluate($t,Bt,u).map(qs=>qs*Od),layoutTextSize:zs.evaluate($t,Bt,u),layoutTextRotate:de.get("text-rotate").evaluate($t,Bt,u),layoutMinZoomSize:zs.evaluate($t,{zoom:Hs},u),layoutMaxZoomSize:zs.evaluate($t,{zoom:$s},u),layoutTextSizeMinZoom:Hs,layoutTextSizeMaxZoom:$s},ys=this.updateSymbolInstanceTextVertices(Ht,Rt,js,$t,Ze,nr);Ze+=ys.vertexOffsetDelta,ut=ut||ys.hasChanges}if(Y){const zs={canonical:u,layer:oe,featureState:Bt,availableImages:w,globalProperties:C,iconScaleFactor:we,layoutIconOffset:de.get("icon-offset").evaluate($t,Bt,u),layoutIconSize:de.get("icon-size").evaluate($t,Bt,u,w),layoutIconRotate:de.get("icon-rotate").evaluate($t,Bt,u)},Hs=this.updateSymbolInstanceIconVertices(Ht,Rt,js,$t,Ce,zs);Ce+=Hs.vertexOffsetDelta,Re=Re||Hs.hasChanges}if(Es){const zs=Ht.featureIndex,Hs=C?C.brightness:null,$s=Bt||{},nr=js>=0?oe.appearances[js]:null;this.text.uboBinder&&(this.text.uboBinder.layer=oe,qe=this.text.uboBinder.updateFeaturePaintForAppearance(zs,$t,$s,u,w,Hs,nr)||qe),this.icon.uboBinder&&(this.icon.uboBinder.layer=oe,qe=this.icon.uboBinder.updateFeaturePaintForAppearance(zs,$t,$s,u,w,Hs,nr)||qe)}Rt.activeAppearanceIndex=js}return Re&&this.icon.layoutVertexBuffer&&this.icon.layoutVertexArray.arrayBuffer!==null&&this.icon.layoutVertexArray.length===this.icon.layoutVertexBuffer.length&&this.icon.layoutVertexBuffer.updateData(this.icon.layoutVertexArray),ut&&this.text.layoutVertexBuffer&&this.text.layoutVertexArray.arrayBuffer!==null&&this.text.layoutVertexArray.length===this.text.layoutVertexBuffer.length&&this.text.layoutVertexBuffer.updateData(this.text.layoutVertexArray),{hasLayoutChanges:Re||ut,hasUboChanges:qe}}destroyDebugData(){this.textCollisionBox.destroy(),this.iconCollisionBox.destroy()}getProjection(){return this.projectionInstance||(this.projectionInstance=VLe(this.projection)),this.projectionInstance}destroy(){this.text.destroy(),this.icon.destroy(),this.hasDebugData()&&this.destroyDebugData()}addToLineVertexArray(u,f){const w=this.lineVertexArray.length;if(u.segment!==void 0)for(const{x:C,y:I}of f)this.lineVertexArray.emplaceBack(C,I);return{lineStartIndex:w,lineLength:this.lineVertexArray.length-w}}addSymbols(u,f,w,C,I,L,B,U,Y,se,oe,de,xe,we,Ce,Re,qe,nt){const Ze=u.indexArray,ut=u.layoutVertexArray,xt=u.globeExtVertexArray,bt=nt,Ht=u.uboBinder?u.uboBinder.getCurrentBatchIndex():void 0,Rt=u.segments.prepareSegment(4*bt,ut,Ze,this.canOverlap?L.sortKey:void 0,Ht),Vt=this.glyphOffsetArray.length,Bt=Rt.vertexLength,$t=this.allowVerticalPlacement&&B===Xp.vertical?Math.PI/2:0,js=L.text&&L.text.sections;let Es=ut.length,zs=-1;for(let nr=0;nr=0)){const nr=4*Hs;for(let ys=0;ys=0?f.rightJustifiedTextSymbolIndex:f.centerJustifiedTextSymbolIndex>=0?f.centerJustifiedTextSymbolIndex:f.leftJustifiedTextSymbolIndex>=0?f.leftJustifiedTextSymbolIndex:f.verticalPlacedTextSymbolIndex>=0?f.verticalPlacedTextSymbolIndex:C),L=_ve(this.textSizeData,u,I)/Od;return this.tilePixelRatio*L}getSymbolInstanceIconSize(u,f,w){const C=this.icon.placedSymbolArray.get(w),I=_ve(this.iconSizeData,u,C);return this.tilePixelRatio*I}_commitDebugCollisionVertexUpdate(u,f,w,C){u.emplaceBack(f,-w,-w,C),u.emplaceBack(f,w,-w,C),u.emplaceBack(f,w,w,C),u.emplaceBack(f,-w,w,C)}_updateTextDebugCollisionBoxes(u,f,w,C,I,L,B){for(let U=C;U0}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(u,f){const w=u.placedSymbolArray.get(f),C=w.vertexStartIndex+4*w.numGlyphs;for(let I=w.vertexStartIndex;IC[B]-C[U]||I[U]-I[B]),L}getSortedIndexesByZOffset(){if(!this.zOffsetSortDirty)return this.symbolInstanceIndexesSortedZOffset;if(!this.symbolInstanceIndexesSortedZOffset){this.symbolInstanceIndexesSortedZOffset=[];for(let u=0;uthis.symbolInstances.get(f).zOffset-this.symbolInstances.get(u).zOffset)}addToSortKeyRanges(u,f){const w=this.sortKeyRanges[this.sortKeyRanges.length-1];w&&w.sortKey===f?w.symbolInstanceEnd=u+1:this.sortKeyRanges.push({sortKey:f,symbolInstanceStart:u,symbolInstanceEnd:u+1})}sortFeatures(u){if(this.sortFeaturesByY&&this.sortedAngle!==u)if(this.text.segments.get().length>1||this.icon.segments.get().length>1)this.sortFeaturesWithinSegments();else{this.symbolInstanceIndexes=this.getSortedSymbolIndexes(u),this.sortedAngle=u,this.text.indexArray.clear(),this.icon.indexArray.clear(),this.featureSortOrder=[];for(const f of this.symbolInstanceIndexes){const w=this.symbolInstances.get(f);this.featureSortOrder.push(w.featureIndex);const{rightJustifiedTextSymbolIndex:C,centerJustifiedTextSymbolIndex:I,leftJustifiedTextSymbolIndex:L,verticalPlacedTextSymbolIndex:B,placedIconSymbolIndex:U,verticalPlacedIconSymbolIndex:Y}=w;C>=0&&this.addIndicesForPlacedSymbol(this.text,C),I>=0&&I!==C&&this.addIndicesForPlacedSymbol(this.text,I),L>=0&&L!==I&&L!==C&&this.addIndicesForPlacedSymbol(this.text,L),B>=0&&this.addIndicesForPlacedSymbol(this.text,B),U>=0&&this.addIndicesForPlacedSymbol(this.icon,U),Y>=0&&this.addIndicesForPlacedSymbol(this.icon,Y)}this.text.indexBuffer&&this.text.indexBuffer.updateData(this.text.indexArray),this.icon.indexBuffer&&this.icon.indexBuffer.updateData(this.icon.indexArray)}}getOrCreateSortedSymbolsByBatch(u,f){const w=(this.text.uboBinder&&this.text.uboBinder.maxFeaturesPerBatch>0?this.text.uboBinder:this.icon.uboBinder&&this.icon.uboBinder.maxFeaturesPerBatch>0?this.icon.uboBinder:null).maxFeaturesPerBatch;if(this.symbolsByBatch)for(const C of this.symbolsByBatch.values())for(const I of C){const L=this.symbolInstances.get(I.index);I.rotatedY=0|Math.round(u*L.tileAnchorX+f*L.tileAnchorY)}else{this.symbolsByBatch=new Map;for(let C=0;CI.rotatedY-L.rotatedY||L.featureIndex-I.featureIndex);return this.symbolsByBatch}rebuildTextSegmentIndices(u,f){for(const w of u){const C=w.batchIndex;if(C===void 0)continue;const I=f.get(C);if(!I){w.primitiveOffset=this.text.indexArray.length,w.primitiveLength=0;continue}w.primitiveOffset=this.text.indexArray.length;const L=this.text.indexArray.length;for(const{index:B}of I){const U=this.symbolInstances.get(B),{rightJustifiedTextSymbolIndex:Y,centerJustifiedTextSymbolIndex:se,leftJustifiedTextSymbolIndex:oe,verticalPlacedTextSymbolIndex:de}=U;Y>=0&&this.addIndicesForPlacedSymbol(this.text,Y),se>=0&&se!==Y&&this.addIndicesForPlacedSymbol(this.text,se),oe>=0&&oe!==se&&oe!==Y&&this.addIndicesForPlacedSymbol(this.text,oe),de>=0&&this.addIndicesForPlacedSymbol(this.text,de)}w.primitiveLength=this.text.indexArray.length-L}}rebuildIconSegmentIndices(u,f){for(const w of u){const C=w.batchIndex;if(C===void 0)continue;const I=f.get(C);if(!I){w.primitiveOffset=this.icon.indexArray.length,w.primitiveLength=0;continue}w.primitiveOffset=this.icon.indexArray.length;const L=this.icon.indexArray.length;for(const{index:B}of I){const U=this.symbolInstances.get(B),{placedIconSymbolIndex:Y,verticalPlacedIconSymbolIndex:se}=U;Y>=0&&this.addIndicesForPlacedSymbol(this.icon,Y),se>=0&&this.addIndicesForPlacedSymbol(this.icon,se)}w.primitiveLength=this.icon.indexArray.length-L}}sortFeaturesWithinSegments(){this.featureSortOrder=[];const u=Math.sin(this.sortedAngle),f=Math.cos(this.sortedAngle),w=this.getOrCreateSortedSymbolsByBatch(u,f),C=Array.from(w.keys()).sort((I,L)=>I-L);for(const I of C){const L=w.get(I);for(const{index:B}of L){const U=this.symbolInstances.get(B);this.featureSortOrder.push(U.featureIndex)}}this.text.indexArray.clear(),this.icon.indexArray.clear(),this.rebuildTextSegmentIndices(this.text.segments.get(),w),this.rebuildIconSegmentIndices(this.icon.segments.get(),w),this.text.indexBuffer&&this.text.indexBuffer.updateData(this.text.indexArray),this.icon.indexBuffer&&this.icon.indexBuffer.updateData(this.icon.indexArray)}getElevationFeatureForText(u){const f=this.symbolInstances.get(this.text.symbolInstanceIndices[u]).elevationFeatureIndex;let w;return this.elevationFeatures&&fw in v?String(v[w]):"")}let GLe,WLe,Dve;Pr(Ov,"SymbolBucket",{omit:["layers","collisionBoxArray","compareText","features"]}),Ov.addDynamicAttributes=qM;class KLe{constructor(u){this.type=u.property.overrides?u.property.overrides.runtimeType:Jf,this.defaultValue=u}evaluate(u){if(u.formattedSection){const f=this.defaultValue.property.overrides;if(f&&f.hasOverride(u.formattedSection))return f.getOverride(u.formattedSection)}return u.feature&&u.featureState?this.defaultValue.evaluate(u.feature,u.featureState):this.defaultValue.property.specification.default}eachChild(u){this.defaultValue.isConstant()||u(this.defaultValue.value._styleExpression.expression)}outputDefined(){return!1}serialize(){return null}}Pr(KLe,"FormatSectionOverride",{omit:["defaultValue"]});const Rve=()=>Dve||(Dve={layout:GLe||(GLe=new Lo({"symbol-placement":new ur(es.layout_symbol["symbol-placement"]),"symbol-spacing":new ur(es.layout_symbol["symbol-spacing"]),"symbol-avoid-edges":new ur(es.layout_symbol["symbol-avoid-edges"]),"symbol-sort-key":new dr(es.layout_symbol["symbol-sort-key"]),"symbol-z-order":new ur(es.layout_symbol["symbol-z-order"]),"symbol-z-elevate":new ur(es.layout_symbol["symbol-z-elevate"]),"symbol-elevation-reference":new ur(es.layout_symbol["symbol-elevation-reference"]),"icon-allow-overlap":new ur(es.layout_symbol["icon-allow-overlap"]),"icon-ignore-placement":new ur(es.layout_symbol["icon-ignore-placement"]),"icon-optional":new ur(es.layout_symbol["icon-optional"]),"icon-rotation-alignment":new ur(es.layout_symbol["icon-rotation-alignment"]),"icon-size":new dr(es.layout_symbol["icon-size"]),"icon-size-scale-range":new ur(es.layout_symbol["icon-size-scale-range"]),"icon-text-fit":new dr(es.layout_symbol["icon-text-fit"]),"icon-text-fit-padding":new dr(es.layout_symbol["icon-text-fit-padding"]),"icon-image":new dr(es.layout_symbol["icon-image"]),"icon-image-use-theme":new ur({type:"string",default:"default","property-type":"data-constant"}),"icon-rotate":new dr(es.layout_symbol["icon-rotate"]),"icon-padding":new ur(es.layout_symbol["icon-padding"]),"icon-keep-upright":new ur(es.layout_symbol["icon-keep-upright"]),"icon-offset":new dr(es.layout_symbol["icon-offset"]),"icon-anchor":new dr(es.layout_symbol["icon-anchor"]),"icon-pitch-alignment":new ur(es.layout_symbol["icon-pitch-alignment"]),"text-pitch-alignment":new ur(es.layout_symbol["text-pitch-alignment"]),"text-rotation-alignment":new ur(es.layout_symbol["text-rotation-alignment"]),"text-field":new dr(es.layout_symbol["text-field"]),"text-font":new dr(es.layout_symbol["text-font"]),"text-size":new dr(es.layout_symbol["text-size"]),"text-size-scale-range":new ur(es.layout_symbol["text-size-scale-range"]),"text-max-width":new dr(es.layout_symbol["text-max-width"]),"text-line-height":new dr(es.layout_symbol["text-line-height"]),"text-letter-spacing":new dr(es.layout_symbol["text-letter-spacing"]),"text-justify":new dr(es.layout_symbol["text-justify"]),"text-radial-offset":new dr(es.layout_symbol["text-radial-offset"]),"text-variable-anchor":new ur(es.layout_symbol["text-variable-anchor"]),"text-anchor":new dr(es.layout_symbol["text-anchor"]),"text-max-angle":new ur(es.layout_symbol["text-max-angle"]),"text-writing-mode":new ur(es.layout_symbol["text-writing-mode"]),"text-rotate":new dr(es.layout_symbol["text-rotate"]),"text-padding":new ur(es.layout_symbol["text-padding"]),"text-keep-upright":new ur(es.layout_symbol["text-keep-upright"]),"text-transform":new dr(es.layout_symbol["text-transform"]),"text-offset":new dr(es.layout_symbol["text-offset"]),"text-allow-overlap":new ur(es.layout_symbol["text-allow-overlap"]),"text-ignore-placement":new ur(es.layout_symbol["text-ignore-placement"]),"text-optional":new ur(es.layout_symbol["text-optional"]),visibility:new ur(es.layout_symbol.visibility)})),paint:WLe||(WLe=new Lo({"icon-opacity":new dr(es.paint_symbol["icon-opacity"]),"icon-occlusion-opacity":new dr(es.paint_symbol["icon-occlusion-opacity"]),"icon-emissive-strength":new dr(es.paint_symbol["icon-emissive-strength"]),"text-emissive-strength":new dr(es.paint_symbol["text-emissive-strength"]),"icon-color":new dr(es.paint_symbol["icon-color"]),"icon-halo-color":new dr(es.paint_symbol["icon-halo-color"]),"icon-halo-width":new dr(es.paint_symbol["icon-halo-width"]),"icon-halo-blur":new dr(es.paint_symbol["icon-halo-blur"]),"icon-translate":new ur(es.paint_symbol["icon-translate"]),"icon-translate-anchor":new ur(es.paint_symbol["icon-translate-anchor"]),"icon-image-cross-fade":new ur(es.paint_symbol["icon-image-cross-fade"]),"text-opacity":new dr(es.paint_symbol["text-opacity"]),"text-occlusion-opacity":new dr(es.paint_symbol["text-occlusion-opacity"]),"text-color":new dr(es.paint_symbol["text-color"],{runtimeType:_h,getOverride:v=>v.textColor,hasOverride:v=>!!v.textColor}),"text-halo-color":new dr(es.paint_symbol["text-halo-color"]),"text-halo-width":new dr(es.paint_symbol["text-halo-width"]),"text-halo-blur":new dr(es.paint_symbol["text-halo-blur"]),"text-translate":new ur(es.paint_symbol["text-translate"]),"text-translate-anchor":new ur(es.paint_symbol["text-translate-anchor"]),"icon-color-saturation":new ur(es.paint_symbol["icon-color-saturation"]),"icon-color-contrast":new ur(es.paint_symbol["icon-color-contrast"]),"icon-color-brightness-min":new ur(es.paint_symbol["icon-color-brightness-min"]),"icon-color-brightness-max":new ur(es.paint_symbol["icon-color-brightness-max"]),"symbol-z-offset":new dr(es.paint_symbol["symbol-z-offset"]),"icon-color-use-theme":new dr({type:"string",default:"default","property-type":"data-driven"}),"icon-halo-color-use-theme":new dr({type:"string",default:"default","property-type":"data-driven"}),"text-color-use-theme":new dr({type:"string",default:"default","property-type":"data-driven"}),"text-halo-color-use-theme":new dr({type:"string",default:"default","property-type":"data-driven"})}))},Dve);class H$ extends to{constructor(u,f,w,C){super(u,Rve(),f,w,C,u.layout?u.layout["icon-image-use-theme"]:null),this._colorAdjustmentMatrix=b([]),this.hasOcclusionOpacityProperties=u.paint!==void 0&&("icon-occlusion-opacity"in u.paint||"text-occlusion-opacity"in u.paint)}_handleSpecialPaintPropertyUpdate(u){u!=="icon-occlusion-opacity"&&u!=="text-occlusion-opacity"||(this.hasOcclusionOpacityProperties=!0)}recalculate(u,f){super.recalculate(u,f),this.appearances&&this.appearances.forEach(C=>{C.recalculate(u,f,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 w=this.layout.get("text-writing-mode");if(w){const C=[];for(const I of w)C.indexOf(I)<0&&C.push(I);this.layout._values["text-writing-mode"]=C}else this.layout._values["text-writing-mode"]=this.layout.get("symbol-placement")==="point"?["horizontal"]:["horizontal","vertical"];this._setPaintOverrides()}getColorAdjustmentMatrix(u,f,w,C){return this._saturation===u&&this._contrast===f&&this._brightnessMin===w&&this._brightnessMax===C||(this._colorAdjustmentMatrix=function(I,L,B,U){I=Ji(I),L=ii(L);const Y=y(),se=I/3,oe=1-2*se,de=[oe,se,se,0,se,oe,se,0,se,se,oe,0,0,0,0,1],xe=.5-.5*L,we=U-B;return k(Y,[we,0,0,0,0,we,0,0,0,0,we,0,B,B,B,1],[L,0,0,0,0,L,0,0,0,0,L,0,xe,xe,xe,1]),k(Y,Y,de),Y}(u,f,w,C),this._saturation=u,this._contrast=f,this._brightnessMin=w,this._brightnessMax=C),this._colorAdjustmentMatrix}getValueAndResolveTokens(u,f,w,C){const I=this.layout.get(u).evaluate(f,{},w,C),L=this._unevaluatedLayout._values[u];return L.isDataDriven()||ey(L.value)||!I?I:HLe(f.properties,I)}getAppearanceValueAndResolveTokens(u,f,w,C,I){const L=u.getLayoutProperty(f);if(!L)return;const B=L.evaluate(w,{},C,I),U=u.getUnevaluatedLayoutProperties()._values[f];return U.isDataDriven()||ey(U.value)||!B||typeof B!="string"?B:HLe(w.properties,B)}createBucket(u){return new Ov(u)}queryRadius(){return 0}queryIntersectsFeature(){return!1}_setPaintOverrides(){for(const u of Rve().paint.overridableProperties){if(!H$.hasPaintOverride(this.layout,u))continue;const f=this.paint.get(u),w=new KLe(f),C=new Tv(w,f.property.specification,this.scope,this.options,this.layout.get("icon-image-use-theme"));let I=null;I=f.value.kind==="constant"||f.value.kind==="source"?new Cx("source",C):new qp("composite",C,f.value.zoomStops,f.value.interpolationType),this.paint._values[u]=new Mv(f.property,I,f.parameters)}}_handleOverridablePaintPropertyUpdate(u,f,w){return!(!this.layout||f.isDataDriven()||w.isDataDriven())&&H$.hasPaintOverride(this.layout,u)}static hasPaintOverride(u,f){const w=u.get("text-field"),C=Rve().paint.properties[f];let I=!1;const L=B=>{for(const U of B)if(C.overrides&&C.overrides.hasOverride(U))return void(I=!0)};if(w.value.kind==="constant"&&w.value.value instanceof Md)L(w.value.value.sections);else if(w.value.kind==="source"){const B=Y=>{I||(Y instanceof Wr&&yl(Y.value)===V0?L(Y.value.sections):Y instanceof Hh?L(Y.sections):Y.eachChild(B))},U=w.value;U._styleExpression&&B(U._styleExpression.expression)}return I}getProgramIds(){return["symbol"]}getDefaultProgramParams(u,f,w){return{config:new Te(this,{zoom:f,lut:w}),overrideFog:!1}}hasElevation(){return this.layout&&this.layout.get("symbol-elevation-reference")==="hd-road-markup"}}let YLe,ZLe,XLe,QLe;var G$=Qs([{name:"a_pos",type:"Int16",components:2},{name:"a_texture_pos",type:"Uint16",components:2}]);function W$(v,u,f,w,C,I,L,B){const U=[v,u,1,f,w,1,C,I,1],Y=[L,B,1],se=p([],U),[oe,de,xe]=ge(Y,Y,se);return x(U,U,[oe,0,0,0,de,0,0,0,xe])}function JLe(v,u,f,w,C,I,L,B){const U=function(Y,se,oe,de,xe,we,Ce,Re){const qe=W$(0,0,1,0,1,1,0,1),nt=W$(Y,se,oe,de,xe,we,Ce,Re);return x(nt,nt,p([],qe))}(v,u,f,w,C,I,L,B);return[U[2]/U[8]/Sr,U[5]/U[8]/Sr]}function K$(v){return[v[0],Math.min(Math.max(v[1],-85.051129),Ls)]}class e8e extends hf{constructor(u,f,w,C){super(),this.id=u,this.dispatcher=w,this.coordinates=f.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(C),this.options=f,this._dirty=!1}load(u,f){if(this._loaded=f||!1,this.fire(new _c("dataloading",{dataType:"source"})),this.url=this.options.url,!this.url)return u&&(this.coordinates=u),this._loaded=!0,void this._finishLoading();this._imageRequest=Dp(this.map._requestManager.transformRequest(this.url,vx.Image),(w,C)=>{this._imageRequest=null,this._loaded=!0,w?this.fire(new Am(w)):C&&(this.image=C,this._dirty=!0,this.width=this.image.width,this.height=this.image.height,u&&(this.coordinates=u),this._finishLoading())})}loaded(){return this._loaded}updateImage(u){return u.url?(this._imageRequest&&u.url!==this.options.url&&(this._imageRequest.cancel(),this._imageRequest=null),this.options.url=u.url,this.load(u.coordinates,this._loaded),this):this}setTexture(u){if(!(u.handle instanceof WebGLTexture))throw new Error("The provided handle is not a WebGLTexture instance");return this.texture=new UD(this.map.painter.context,u.handle),this.width=u.dimensions[0],this.height=u.dimensions[1],this._dirty=!1,this._loaded=!0,this._finishLoading(),this}_finishLoading(){this.map&&(this.setCoordinates(this.coordinates),this.fire(new _c("data",{dataType:"source",sourceDataType:"metadata"})))}onAdd(u){this.map=u,this.load()}onRemove(u){this._imageRequest&&(this._imageRequest.cancel(),this._imageRequest=null),!this.texture||this.texture instanceof UD||this.texture.destroy(),this.boundsBuffer&&(this.boundsBuffer.destroy(),this.elevatedGlobeVertexBuffer&&this.elevatedGlobeVertexBuffer.destroy(),this.elevatedGlobeIndexBuffer&&this.elevatedGlobeIndexBuffer.destroy())}setCoordinates(u){if(this.coordinates=u,this._boundsArray=void 0,this._unsupportedCoords=!1,!u.length)return this;this.onNorthPole=!1,this.onSouthPole=!1;let f=u[0][1],w=u[0][1];for(const I of u)I[1]>w&&(w=I[1]),I[1]Ls?this.onNorthPole=!0:C<-85.051129&&(this.onSouthPole=!0),!this.onNorthPole&&!this.onSouthPole){const I=u.map(en.fromLngLat);this.tileID=function(L){let B=1/0,U=1/0,Y=-1/0,se=-1/0;for(const Ce of L)B=Math.min(B,Ce.x),U=Math.min(U,Ce.y),Y=Math.max(Y,Ce.x),se=Math.max(se,Ce.y);const oe=Math.max(Y-B,se-U),de=Math.max(0,Math.floor(-Math.log2(oe))),xe=Math.pow(2,de);let we=Math.floor((B+Y)/2*xe);return we>1&&(we-=1),new z4(de,we,Math.floor((U+se)/2*xe))}(I),this.minzoom=this.maxzoom=this.tileID.z}return this.fire(new _c("data",{dataType:"source",sourceDataType:"content"})),this}_clear(){!this.texture||this.texture instanceof UD||(this.texture.destroy(),this._dirty=!0),this.texture=null,this._boundsArray=void 0,this._unsupportedCoords=!1}_prepareData(u){for(const Re in this.tiles){const qe=this.tiles[Re];qe.state!=="loaded"&&(qe.state="loaded",qe.texture=this.texture)}if(this._boundsArray||this.onNorthPole||this.onSouthPole||this._unsupportedCoords)return;const f=W4(new z4(0,0,0),this.map.transform.projection),w=[f.projection.project(this.coordinates[0][0],this.coordinates[0][1]),f.projection.project(this.coordinates[1][0],this.coordinates[1][1]),f.projection.project(this.coordinates[2][0],this.coordinates[2][1]),f.projection.project(this.coordinates[3][0],this.coordinates[3][1])];if(!function(Re){const qe=Re[1].x-Re[0].x,nt=Re[1].y-Re[0].y,Ze=Re[2].x-Re[1].x,ut=Re[2].y-Re[1].y,xt=Re[3].x-Re[2].x,bt=Re[3].y-Re[2].y,Ht=Re[0].x-Re[3].x,Rt=Re[0].y-Re[3].y,Vt=qe*ut-Ze*nt,Bt=Ze*bt-xt*ut,$t=xt*Rt-Ht*bt,js=Ht*nt-qe*Rt;return Vt>0&&Bt>0&&$t>0&&js>0||Vt<0&&Bt<0&&$t<0&&js<0}(w))return console.warn("Image source coordinates are defining non-convex area in the Mercator projection"),void(this._unsupportedCoords=!0);const C=W4(this.tileID,this.map.transform.projection),[I,L,B,U]=this.coordinates.map(Re=>{const qe=C.projection.project(Re[0],Re[1]);return BLe(C,qe)._round()});this.perspectiveTransform=JLe(I.x,I.y,L.x,L.y,B.x,B.y,U.x,U.y);const Y=this._boundsArray=new Ya;Y.emplaceBack(I.x,I.y,0,0),Y.emplaceBack(L.x,L.y,Sr,0),Y.emplaceBack(U.x,U.y,0,Sr),Y.emplaceBack(B.x,B.y,Sr,Sr),this.boundsBuffer&&(this.boundsBuffer.destroy(),this.elevatedGlobeVertexBuffer&&this.elevatedGlobeVertexBuffer.destroy(),this.elevatedGlobeIndexBuffer&&this.elevatedGlobeIndexBuffer.destroy()),this.boundsBuffer=u.createVertexBuffer(Y,G$.members),this.boundsSegments=No.simpleSegment(0,0,4,2);const se=[],oe=function(Re){return[K$(Re[0]),K$(Re[1]),K$(Re[2]),K$(Re[3])]}(this.coordinates),[de,xe,we,Ce]=function(Re){let qe=Re[0][0],nt=qe,Ze=Re[0][1],ut=Ze;for(let xt=1;xtnt&&(nt=Re[xt][0]),Re[xt][1]ut&&(ut=Re[xt][1]);return[qe,Ze,nt-qe,ut-Ze]}(oe);{const Re=new Ya,[qe,nt,Ze,ut]=function($s){let nr=$s[0].x,ys=nr,qs=$s[0].y,Zs=qs;for(let ir=1;ir<$s.length;ir++)$s[ir].xys&&(ys=$s[ir].x),$s[ir].yZs&&(Zs=$s[ir].y);return[nr,qs,ys-nr,Zs-qs]}(w),xt=$s=>[($s.x-qe)/Ze,($s.y-nt)/ut],[bt,Ht,Rt,Vt]=w.map(xt),Bt=function($s,nr,ys,qs,Zs,ir,pr,Zr){const Nr=W$(0,0,1,0,1,1,0,1);return x(Nr,Nr,p([],W$($s,nr,ys,qs,Zs,ir,pr,Zr)))}(bt[0],bt[1],Ht[0],Ht[1],Rt[0],Rt[1],Vt[0],Vt[1]);this.elevatedGlobePerspectiveTransform=JLe(bt[0],bt[1],Ht[0],Ht[1],Rt[0],Rt[1],Vt[0],Vt[1]);const $t=($s,nr)=>{se.push($s.lng);const ys=Math.round(($s.lng-de)/we*Sr),qs=Math.round(($s.lat-xe)/Ce*Sr),Zs=xt(nr),ir=ge([],[Zs[0],Zs[1],1],Bt),pr=Math.round(ir[0]/ir[2]*Sr),Zr=Math.round(ir[1]/ir[2]*Sr);Re.emplaceBack(ys,qs,pr,Zr)},js=w[3].x-w[0].x,Es=w[3].y-w[0].y,zs=w[2].x-w[1].x,Hs=w[2].y-w[1].y;for(let $s=0;$s<65;$s++){const nr=$s/64,ys=[w[0].x+nr*js,w[0].y+nr*Es],qs=[w[1].x+nr*zs,w[1].y+nr*Hs],Zs=qs[0]-ys[0],ir=qs[1]-ys[1];for(let pr=0;pr<65;pr++){const Zr=pr/64,Nr={x:ys[0]+Zs*Zr,y:ys[1]+ir*Zr};$t(f.projection.unproject(Nr.x,Nr.y),Nr)}}this.elevatedGlobeVertexBuffer=u.createVertexBuffer(Re,G$.members)}{this.maxLongitudeTriangleSize=0;let Re=[],qe=new Yl;const nt=(Ze,ut,xt)=>{qe.emplaceBack(Ze,ut,xt);const bt=se[Ze],Ht=se[ut],Rt=se[xt],Vt=Math.min(Math.min(bt,Ht),Rt),Bt=Math.max(Math.max(bt,Ht),Rt)-Vt;Bt>this.maxLongitudeTriangleSize&&(this.maxLongitudeTriangleSize=Bt),Re.push(Vt+Bt/2)};for(let Ze=0;Ze<64;Ze++)for(let ut=0;ut<64;ut++){const xt=65*Ze+ut,bt=xt+1,Ht=xt+65,Rt=Ht+1;nt(xt,Ht,bt),nt(bt,Ht,Rt)}[Re,qe]=function(Ze,ut){const xt=Array.from({length:Ze.length},(Rt,Vt)=>Vt);xt.sort((Rt,Vt)=>Ze[Rt]-Ze[Vt]);const bt=[],Ht=new Yl;for(let Rt=0;Rt{L.segments.push({vertexOffset:0,primitiveOffset:oe,vertexLength:f.segments[0].vertexLength,primitiveLength:de,sortKey:void 0,vaos:{}})},U=.51*this.maxLongitudeTriangleSize;if(Math.abs(w[0]-C)<=U){const oe=Ki(w,0,w.length,C+U);return oe===w.length||B(oe,Wi(w,oe+1,w.length,C+360-U)-oe),L}C0}}let s8e,r8e,n8e,a8e,i8e,o8e,l8e;class c8e extends to{constructor(u,f,w,C){super(u,{layout:s8e||(s8e=new Lo({visibility:new ur(es["layout_raster-particle"].visibility)})),paint:r8e||(r8e=new Lo({"raster-particle-array-band":new ur(es["paint_raster-particle"]["raster-particle-array-band"]),"raster-particle-count":new ur(es["paint_raster-particle"]["raster-particle-count"]),"raster-particle-color":new wf(es["paint_raster-particle"]["raster-particle-color"]),"raster-particle-max-speed":new ur(es["paint_raster-particle"]["raster-particle-max-speed"]),"raster-particle-speed-factor":new ur(es["paint_raster-particle"]["raster-particle-speed-factor"]),"raster-particle-fade-opacity-factor":new ur(es["paint_raster-particle"]["raster-particle-fade-opacity-factor"]),"raster-particle-reset-rate-factor":new ur(es["paint_raster-particle"]["raster-particle-reset-rate-factor"]),"raster-particle-elevation":new ur(es["paint_raster-particle"]["raster-particle-elevation"]),"raster-particle-color-use-theme":new dr({type:"string",default:"default","property-type":"data-driven"})}))},f,w,C),this._updateColorRamp(),this.lastInvalidatedAt=Ad.now()}_clear(){this.colorRampTexture&&(this.colorRampTexture.destroy(),this.colorRampTexture=null),this.tileFramebuffer&&(this.tileFramebuffer.destroy(),this.tileFramebuffer=null),this.particleFramebuffer&&(this.particleFramebuffer.destroy(),this.particleFramebuffer=null)}onRemove(u){this.colorRampTexture&&this.colorRampTexture.destroy(),this.tileFramebuffer&&this.tileFramebuffer.destroy(),this.particleFramebuffer&&this.particleFramebuffer.destroy()}hasColorMap(){return!!this._transitionablePaint._values["raster-particle-color"].value.value}getProgramIds(){return["rasterParticle"]}hasOffscreenPass(){return this.visibility!=="none"}isDraped(u){return!1}_handleSpecialPaintPropertyUpdate(u){u!=="raster-particle-color"&&u!=="raster-particle-max-speed"||(this._updateColorRamp(),this._invalidateAnimationState()),u==="raster-particle-count"&&this._invalidateAnimationState()}_updateColorRamp(){if(!this.hasColorMap())return;const u=this._transitionablePaint._values["raster-particle-color"].value.expression,f=this._transitionablePaint._values["raster-particle-max-speed"].value.expression.evaluate({zoom:0});this.colorRamp=CD({expression:u,evaluationKey:"rasterParticleSpeed",image:this.colorRamp,clips:[{start:0,end:f}],resolution:256}),this.colorRampTexture=null}_invalidateAnimationState(){this.lastInvalidatedAt=Ad.now()}tileCoverLift(){return this.paint.get("raster-particle-elevation")}}class y2t extends to{constructor(u,f){super(u,{},f,null),this.implementation=u,u.slot&&(this.slot=u.slot)}is3D(u){return this.implementation.renderingMode==="3d"}hasOffscreenPass(){return this.implementation.prerender!==void 0}isDraped(u){return this.implementation.renderToTile!==void 0}shouldRedrape(){return!!this.implementation.shouldRerenderTiles&&this.implementation.shouldRerenderTiles()}recalculate(){}updateTransitions(){}hasTransition(){return!1}serialize(){}onAdd(u){this.implementation.onAdd&&this.implementation.onAdd(u,u.painter.context.gl)}onRemove(u){this.implementation.onRemove&&this.implementation.onRemove(u,u.painter.context.gl)}}function Fve(v,u,f){const w=[0,0,1],C=rt([]);return hs(C,C,f?-Hr(v)+Math.PI:Hr(v)),Et(C,C,-Hr(u)),ct(w,w,C),Pe(w,w)}class Y${constructor(u,f,w,C){this.message=(u?`${u}: `:"")+w,C&&(this.identifier=C),f!=null&&f.__line__&&(this.line=f.__line__)}}function Bve(v,u){const f=v.indexOf("://")===-1;try{return new URL(v,f&&u?"http://example.com":void 0),!0}catch{return!1}}class d8e{constructor(u,f){this.feature=u,this.instancedDataOffset=f,this.instancedDataCount=0,this.rotation=[0,0,0],this.scale=[1,1,1],this.translation=[0,0,0]}}class u8e{constructor(){this.maxScale=1,this.maxXYTranslationDistance=0,this.instancedDataArray=new yD,this.instancesEvaluatedElevation=[],this.features=[],this.idToFeaturesIndex={}}colorForInstance(u){const f=16*u,w=this.instancedDataArray.float32;let C=Math.floor(w[f+2]);const I=1.05*(w[f+2]-C);return C/=100,[w[f]%1*1.05,w[f+1]%1*1.05,I,C]}tileCoordinatesForInstance(u){const f=16*u,w=this.instancedDataArray.float32;let C=w[f+0];return C=C>Sr?C-Sr:C,new ds(Math.trunc(C),Math.trunc(w[f+1]))}translationForInstance(u){const f=16*u,w=this.instancedDataArray.float32;return[w[f+4],w[f+5],w[f+6]]}rotationScaleForInstance(u){const f=16*u,w=this.instancedDataArray.float32;return[w[f+7],w[f+8],w[f+9],w[f+10],w[f+11],w[f+12],w[f+13],w[f+14],w[f+15]]}transformForInstance(u){const f=16*u,w=this.instancedDataArray.float32;return[w[f+7],w[f+8],w[f+9],w[f+4],w[f+10],w[f+11],w[f+12],w[f+5],w[f+13],w[f+14],w[f+15],w[f+6],0,0,0,1]}}class zve{constructor(u){this.zoom=u.zoom,this.canonical=u.canonical,this.overscaledZ=this.canonical.z+Math.log2(u.overscaling),this.layers=u.layers,this.layerIds=this.layers.map(f=>f.fqid),this.projection=u.projection,this.index=u.index,this.worldview=u.worldview,this.hasZoomDependentProperties=this.layers[0].isZoomDependent(),this.stateDependentLayerIds=this.layers.filter(f=>f.isStateDependent()).map(f=>f.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=u.styleDefinedModelURLs,this.hasAppearances=null}updateFootprints(u,f){}updateAppearances(u,f,w,C){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(u,f,w,C){this.tileToMeter=Js(w);const I=this.layers[0]._featureFilter.needGeometry;this.lookup=new Uint8Array(this.lookupDim*this.lookupDim);const L=this.layers[0].paint.get("model-elevation-reference")==="hd-road-markup"?f.elevationFeatures:void 0;for(const{feature:B,id:U,index:Y,sourceLayerIndex:se}of u){const oe=U??(B.properties&&B.properties.hasOwnProperty("id")?B.properties.id:void 0),de=Oa(B,I);if(!this.layers[0]._featureFilter.filter(new wa(this.zoom,{worldview:this.worldview,activeFloors:f.activeFloors}),de,w))continue;const xe={id:oe,sourceLayerIndex:se,index:Y,geometry:I?de.geometry:Ln(B,w,C),properties:B.properties,type:B.type,patterns:{}},we=this.addFeature(xe,xe.geometry,de,L,w);we&&f.featureIndex.insert(B,xe.geometry,Y,se,this.index,this.instancesPerModel[we].instancedDataArray.length,256)}this.lookup=null}evaluateQueryRenderedFeaturePadding(){const u=this.layers[0].modelManager,f=this.layers[0].scope;let w=0;for(const C of this.modelUris){const I=u.getModel(C,f);if(!I)continue;const L=this.instancesPerModel[C];if(L){const B=.5*Ve(I.aabb.max,I.aabb.min)*L.maxScale+L.maxXYTranslationDistance,U=Math.min(Sr,Math.max(B/this.tileToMeter,256));w=Math.max(U,w)}}return w}update(u,f,w,C){for(const I in this.instancesPerModel){const L=this.instancesPerModel[I];for(const B in u)L.idToFeaturesIndex.hasOwnProperty(B)&&(this.evaluate(L.features[L.idToFeaturesIndex[B]],u[B],L,!0),this.uploaded=!1)}this.maxHeight=0}updateZoomBasedPaintProperties(){if(!this.hasZoomDependentProperties)return!1;let u=!1;for(const f in this.instancesPerModel){const w=this.instancesPerModel[f];for(const C of w.features){const I=this.layers[0],L=C.feature,B=this.canonical,U=I.paint.get("model-rotation").evaluate(L,{},B),Y=I.paint.get("model-scale").evaluate(L,{},B),se=I.paint.get("model-translation").evaluate(L,{},B);et(C.rotation,U)&&et(C.scale,Y)&&et(C.translation,se)||(this.evaluate(C,C.featureStates,w,!0),u=!0)}}return u}updateReplacement(u,f,w,C){if(f.updateTime===this.replacementUpdateTime)return!1;this.replacementUpdateTime=f.updateTime;const I=f.getReplacementRegionsForTile(u.toUnwrapped(),!0);if(f$(this.activeReplacements,I))return!1;this.activeReplacements=I;let L=!1;for(const B in this.instancesPerModel){const U=this.instancesPerModel[B],Y=U.instancedDataArray;for(const se of U.features){const oe=se.instancedDataOffset,de=se.instancedDataCount;for(let xe=0;xeSr;Ce=Re?Ce-Sr:Ce;const qe=Math.floor(Ce),nt=Math.floor(Y.float32[we+1]);let Ze=!1;for(const ut of this.activeReplacements)if(!GIe(ut,w,p$.Model,C)&&!(ut.min.x>qe||qe>ut.max.x||ut.min.y>nt||nt>ut.max.y)&&(Ze=XIe(ZIe(qe,nt,u.canonical,ut.footprintTileId.canonical),ut.footprint),Ze))break;Y.float32[we]=Ze?Ce+Sr:Ce,L=L||Ze!==Re}}}return L}isEmpty(){for(const u in this.instancesPerModel)if(this.instancesPerModel[u].instancedDataArray.length!==0)return!1;return!0}uploadPending(){return!this.uploaded}upload(u){if(!this.uploaded)for(const f in this.instancesPerModel){const w=this.instancesPerModel[f];w.instancedDataArray.length<0||w.instancedDataArray.length===0||(w.instancedDataBuffer?w.instancedDataBuffer.updateData(w.instancedDataArray):w.instancedDataBuffer=u.createVertexBuffer(w.instancedDataArray,O_t.members,!0,void 0,this.instanceCount))}this.uploaded=!0}destroy(u){for(const w in this.instancesPerModel){const C=this.instancesPerModel[w];C.instancedDataArray.length!==0&&C.instancedDataBuffer&&C.instancedDataBuffer.destroy()}const f=this.layers[0].modelManager;if(u&&f&&this.modelUris&&this.modelsRequested)for(const w of this.modelUris)f.removeModel(w,"",!0)}addFeature(u,f,w,C,I){const L=this.layers[0],B=L.layout.get("model-id"),U=L.layout.get("model-allow-density-reduction"),Y=B.evaluate(w,{},this.canonical);if(!Y)return Gr(`modelId is not evaluated for layer ${L.id} and it is not going to get rendered.`),Y;(Bve(Y,!1)||this.styleDefinedModelURLs[Y]!==void 0)&&(this.modelUris.includes(Y)||this.modelUris.push(Y)),this.instancesPerModel[Y]||(this.instancesPerModel[Y]=new u8e);const se=this.instancesPerModel[Y],oe=se.instancedDataArray,de=new d8e(w,oe.length);let xe;C&&(xe=Eo.getElevationFeature(u,C));for(const we of f)for(const Ce of we){if(Ce.x<0||Ce.x>=Sr||Ce.y<0||Ce.y>=Sr)continue;if(this.lookupDim!==0&&U){const qe=(this.lookupDim-1)/Sr,nt=this.lookupDim*(Ce.y*qe|0)+Ce.x*qe|0;if(this.lookup){if(this.lookup[nt]!==0)continue;this.lookup[nt]=1}}this.instanceCount++;const Re=oe.length;if(oe.resize(Re+1),C){se.instancesRoadElevation||(se.instancesRoadElevation=[]);const qe=xe?xe.pointElevation(new ds(Ce.x,Ce.y)):0;se.instancesRoadElevation.push(qe)}se.instancesEvaluatedElevation.push(0),oe.float32[16*Re]=Ce.x,oe.float32[16*Re+1]=Ce.y}return de.instancedDataCount=se.instancedDataArray.length-de.instancedDataOffset,de.instancedDataCount>0&&(u.id&&(se.idToFeaturesIndex[u.id]=se.features.length),se.features.push(de),this.evaluate(de,{},se,!1)),Y}getModelUris(){return this.modelUris}evaluate(u,f,w,C){const I=this.layers[0],L=u.feature,B=this.canonical,U=u.rotation=I.paint.get("model-rotation").evaluate(L,f,B),Y=u.scale=I.paint.get("model-scale").evaluate(L,f,B),se=u.translation=I.paint.get("model-translation").evaluate(L,f,B),oe=Object.assign({},I.paint.get("model-color").evaluate(L,f,B));oe.a=I.paint.get("model-color-mix-intensity").evaluate(L,f,B);const de=[];this.maxVerticalOffset0?Math.sqrt(xe):0;w.maxScale=Math.max(Math.max(w.maxScale,Y[0]),Math.max(Y[1],Y[2])),w.maxXYTranslationDistance=Math.max(w.maxXYTranslationDistance,we),this.maxScale=Math.max(Math.max(this.maxScale,Y[0]),Math.max(Y[1],Y[2])),DPe(de,U,Y);const Ce=Math.round(100*oe.a)+oe.b/1.05;for(let Re=0;Re10?this.tileToMeter:Js(B,xt)),Ze[nt+4]=se[0],Ze[nt+5]=se[1],Ze[nt+6]=se[2]+(w.instancesRoadElevation?w.instancesRoadElevation[qe]:0)+ut,Ze[nt+7]=de[0],Ze[nt+8]=de[1],Ze[nt+9]=de[2],Ze[nt+10]=de[4],Ze[nt+11]=de[5],Ze[nt+12]=de[6],Ze[nt+13]=de[8],Ze[nt+14]=de[9],Ze[nt+15]=de[10],w.instancesEvaluatedElevation[qe]=se[2]}}}Pr(zve,"ModelBucket",{omit:["layers"]}),Pr(u8e,"PerModelAttributes"),Pr(d8e,"ModelFeature");class HM{constructor(u,f,w){this._demTile=u,this._dem=this._demTile.dem,this._scale=f,this._offset=w}static create(u,f,w){const C=w||u.findDEMTileFor(f);if(!C||!C.dem)return;const I=C.dem,L=C.tileID,B=1<Y.fqid),this.stateDependentLayerIds=this.layers.filter(Y=>Y.isStateDependent()).map(Y=>Y.id),this.modelTraits|=OM.CoordinateSpaceTile,this.uploaded=!1,this.hasPattern=!1,C&&(this.modelTraits|=OM.HasMapboxMeshFeatures),I&&(this.modelTraits|=OM.HasMeshoptCompression),this.zoom=-1,this.terrainExaggeration=1,this.projection={name:"mercator"},this.replacementUpdateTime=0,this.elevationReadFromZ=255,this.brightness=L,this.worldview=U,this.dirty=!0,this.needsUpload=!1,this.filter=null,this.nodesInfo=[];for(const Y of f)this.nodesInfo.push(new p8e(Y)),m8e(Y,B.featureIndexArray.length,B.grid),B.featureIndexArray.emplaceBack(this.nodesInfo.length-1,0,B.bucketLayerIDs.length-1,0);this.states={},this.hasAppearances=null}updateFootprints(u,f){for(const w of this.getNodesInfo()){const C=w.node;C.footprint&&f.push({footprint:C.footprint,id:u})}}updateAppearances(u,f,w,C){return{hasLayoutChanges:!1,hasUboChanges:!1}}update(u){const f=Object.keys(u).length!==0;if(f&&!this.stateDependentLayers.length)return;const w=f?this.stateDependentLayers:this.layers;if(!Na(u,this.states))for(const C of w)this.evaluate(C,u);this.states=structuredClone(u)}populate(){console.log("populate 3D model bucket")}uploadPending(){return!this.uploaded||this.needsUpload}upload(u){if(!this.needsUpload)return;const f=this.getNodesInfo();for(const w of f){const C=w.node;this.uploaded?this.updatePbrBuffer(C):nve(C,u,!0)}for(const w of f)T$(w.node);this.uploaded=!0,this.needsUpload=!1}updatePbrBuffer(u){let f=!1;if(!u.meshes)return f;for(const w of u.meshes)w.pbrBuffer&&(w.pbrBuffer.updateData(w.featureArray),f=!0);return f}needsReEvaluation(u,f,w){const C=u.transform.projectionOptions,I=u.style.getBrightness(),L=this.brightness!==I;if(!this.uploaded||this.dirty||C.name!==this.projection.name||nR(w.paint.get("model-color").value,L)||nR(w.paint.get("model-color-mix-intensity").value,L)||nR(w.paint.get("model-roughness").value,L)||nR(w.paint.get("model-emissive-strength").value,L)||nR(w.paint.get("model-height-based-emissive-strength-multiplier").value,L)){this.projection=C,this.brightness=I;const B=this.getNodesInfo();for(const U of B)U.state=null;return!0}return!1}evaluateTransform(u,f){if(u.transform.zoom===this.zoom)return;this.zoom=u.transform.zoom;const w=this.getNodesInfo(),C=this.id.canonical;for(const I of w){const L=I.feature;I.evaluatedTranslation=f.paint.get("model-translation").evaluate(L,{},C),I.evaluatedScale=f.paint.get("model-scale").evaluate(L,{},C)}}evaluate(u,f){const w=this.getNodesInfo();for(const C of w){if(!C.node.meshes)continue;const I=C.feature,L=f&&f[I.id];if(Na(L,C.state))continue;C.state=structuredClone(L);const B=C.node.meshes&&C.node.meshes[0].featureData,U=C.evaluatedColor[2],Y=C.evaluatedRMEA[2],se=this.id.canonical;if(C.hasTranslucentParts=!1,B){for(let oe=0;oe=bt)continue;const nr=$ve[$s],ys=Math.abs(nr);ys>$t&&(Bt=nr,$t=ys,js=Hs,Es=zs)}if($t>.1){const zs=1-(bt+.5*Math.abs(js*Es))/we;let Hs=f._dem.get(Rt,Ht)+Bt*zs;const $s=f._dem.get(Rt+js,Ht+Es),nr=f._dem.get(Rt-js,Ht-Es,!0);(Hs-$s)*(Hs-nr)>0&&(Hs=($s+nr)/2),$ve[Vt]=f._dem.set(Rt,Ht,Hs),K4[Vt]=bt}}}}}B&&(f._demTile.needsDEMTextureUpload=!0,f._dem._timestamp=Ad.now())}setFilter(u){this.filter=u?Jj(u):null}getNodesInfo(){return this.filter?this.nodesInfo.filter(u=>this.filter.filter(new wa(this.id.overscaledZ,{worldview:this.worldview}),u.feature,this.id.canonical)):this.nodesInfo}destroy(){const u=this.getNodesInfo();for(const f of u)T$(f.node),ave(f.node)}isEmpty(){return!this.nodesInfo.length}updateReplacement(u,f){if(f.updateTime===this.replacementUpdateTime)return;this.replacementUpdateTime=f.updateTime;const w=f.getReplacementRegionsForTile(u.toUnwrapped());for(const C of this.getNodesInfo()){const I=C.node.footprint;C.hiddenByReplacement=!!I&&!w.find(L=>L.footprint===I)}}getHeightAtTileCoord(u,f){const w=[],C=[0,0,0],I=b([]);for(const L of this.getNodesInfo()){const B=L.node.meshes[0],U=B.transformedAabb;if(uU.max[0]||f>U.max[1])continue;if(L.node.hidden===!0)return{height:1/0,maxHeight:L.feature.properties.height,hidden:!1,verticalScale:L.evaluatedScale[2]};j(I,L.node.globalMatrix),C[0]=u,C[1]=f,tt(C,C,I);const Y=(C[0]-B.aabb.min[0])/(B.aabb.max[0]-B.aabb.min[0])*q4|0,se=Math.min(63,(C[1]-B.aabb.min[1])/(B.aabb.max[1]-B.aabb.min[1])*q4|0)*q4+Math.min(63,Y),oe=B.heightmap[se];if(!(oe<0&&L.node.footprint))return L.hiddenByReplacement?void 0:{height:oe,maxHeight:L.feature.properties.height,hidden:!1,verticalScale:L.evaluatedScale[2]};if(L.node.footprint.grid.query(new ds(u,f),new ds(u,f),w),w.length>0)return{height:void 0,maxHeight:L.feature.properties.height,hidden:L.hiddenByReplacement,verticalScale:L.evaluatedScale[2]}}}}function nR(v,u){return v instanceof Cx&&!v.isLightConstant&&u}function v2t(v,u,f,w,C,I,L,B){let U=(61440&u|(61440&u)>>4)>>8,Y=(3840&u|(3840&u)>>4)>>4,se=240&u|(240&u)>>4;f[3]>0&&(U=jn(U,255*f[0],f[3]),Y=jn(Y,255*f[1],f[3]),se=jn(se,255*f[2],f[3]));const oe=U<<8|Y,de=se<<8|Math.floor(255*w[3]),xe=function(bt){const Ht=He(bt,0,2);return Math.min(Math.round(.5*Ht*255),255)}(w[2])<<8|15*w[0]<<4|15*w[1],we=He(C[0],0,1),Ce=He(C[1],0,1),Re=He(C[2],0,1),qe=He(C[3],0,1);let nt,Ze,ut,xt;if(we!==Ce&&L!==I&&Ce!==we){const bt=L-I;Ze=1/(bt*(Ce-we)),ut=-(I+bt*we)/(bt*(Ce-we));const Ht=He(C[4],-1,1);xt=Math.pow(10,Ht),nt=255*Re<<8|255*qe}else nt=65535,Ze=0,ut=1,xt=1;if(v.emplaceBack(oe,de,xe,nt,Ze,ut,xt),B){const bt=B.length;B.clear();for(let Ht=0;Ht>16&65535,se=I?U>>16&65535:65535&U,oe=(15&se)<8?15&se:0,de=v.evaluatedRMEA[oe],xe=v.evaluatedColor[oe],we=v.emissionHeightBasedParams[oe];let Ce;if(B&&oe===2&&w.lights&&(Ce=new kM,Ce.resize(10*w.lights.length)),v2t(L.featureArray,Y,xe,de,we,L.aabb.min[2],L.aabb.max[2],Ce),Ce&&B){B=!1;const Re=w.meshes[w.lightMeshIndex];Re.featureArray=Ce,Re.featureArray._trim()}}L.featureArray._trim(),C++}}Pr(Z$,"Tiled3dModelBucket",{omit:["layers"]}),Pr(p8e,"Tiled3dModelFeature");const _2t=["id","tile","layer","source","sourceLayer","state"];class Y4{constructor(u,f,w,C,I){this.type="Feature",this._vectorTileFeature=u,this._z=f,this._x=w,this._y=C,this.properties=u?u.properties:{},this.id=I}clone(){const u=new Y4(this._vectorTileFeature,this._z,this._x,this._y,this.id);return this.state&&(u.state=Object.assign({},this.state)),this.layer&&(u.layer=Object.assign({},this.layer)),this.source&&(u.source=this.source),this.sourceLayer&&(u.sourceLayer=this.sourceLayer),u}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(u){this._geometry=u}toJSON(){const u={type:"Feature",state:void 0,geometry:this.geometry,properties:this.properties};for(const f of _2t)this[f]!==void 0&&(u[f]=this[f]);return u}}class Z4 extends hf{constructor(u,f,w,C){super(),this.id=u,this.type="model",this.models=[],this._options=f,this._modelsInfo=new Map,this._abortController=null}cancelModelRequests(){this._abortController&&(this._abortController.abort(),this._abortController=null)}loadGLTFFromURI(u,f){return MPe(this.map._requestManager.transformRequest(u,vx.Model).url,f)}async loadModel(u,f,w){try{const C=await this.loadGLTFFromURI(f.uri,w);if(w.aborted)return;const I=this._modelsInfo.get(u);if(!I)return;const L=ove(C),B=I.modelSpec,U=new RPe(u,B.uri,B.position,B.orientation,L);Z4.applyModelSpecification(U,B),U.computeBoundsAndApplyParent(),this.models.push(U),I.model=U}catch(C){if(C instanceof Error&&C.name==="AbortError")return;const I=C instanceof Error?C.message:"Unknown error";this.fire(new Am(new Error(`Could not load model ${u} from ${f.uri}: ${I}`)))}}async load(){this._abortController||(this._abortController=new AbortController);const u=this._abortController.signal,f=[];for(const w in this._options.models){const C=this._options.models[w],I=this._modelsInfo.get(w);if(I&&I.model){I.modelSpec=C;const L=I.model;L.position=C.position!=null?new Zt(C.position[0],C.position[1]):new Zt(0,0),L.orientation=C.orientation!=null?C.orientation:[0,0,0],Z4.applyModelSpecification(L,C),L.computeBoundsAndApplyParent(),this.models.push(L)}else I?I.modelSpec=C:(this._modelsInfo.set(w,{modelSpec:C,model:null}),f.push(this.loadModel(w,C,u)))}f.length!==0?(await Promise.allSettled(f),u.aborted||this.fire(new _c("data",{dataType:"source",sourceDataType:"metadata"}))):this.loaded()&&this.fire(new _c("data",{dataType:"source",sourceDataType:"metadata"}))}static applyModelSpecification(u,f){f.nodeOverrides&&Z4.convertNodeOverrides(u,f.nodeOverrides),f.materialOverrides&&Z4.convertMaterialOverrides(u,f.materialOverrides),f.nodeOverrideNames&&(u.nodeOverrideNames=[...f.nodeOverrideNames]),f.materialOverrideNames&&(u.materialOverrideNames=[...f.materialOverrideNames]),f.featureProperties&&(u.featureProperties=f.featureProperties)}static convertNodeOverrides(u,f){if(Array.isArray(f)&&f.every(w=>typeof w=="string")){u.nodeOverrideNames=[];for(const w of f)u.nodeOverrideNames.push(w)}else Object.entries(f).forEach(([w,C])=>{const I={orientation:[0,0,0]};if(C.hasOwnProperty("orientation")){const L=C.orientation;L&&(I.orientation=L)}u.nodeOverrides.set(w,I)})}static convertMaterialOverrides(u,f){if(Array.isArray(f)&&f.every(w=>typeof w=="string")){u.materialOverrideNames=[];for(const w of f)u.materialOverrideNames.push(w)}else Object.entries(f).forEach(([w,C])=>{const I={color:new Mr(1,1,1),colorMix:0,emissionStrength:0,opacity:1},L=C["model-color"];L!==void 0&&(I.color.r=L[0],I.color.g=L[1],I.color.b=L[2]);const B=C["model-color-mix-intensity"];B!==void 0&&(I.colorMix=B);const U=C["model-emissive-strength"];U!==void 0&&(I.emissionStrength=U);const Y=C["model-opacity"];Y!==void 0&&(I.opacity=Y),u.materialOverrides.set(w,I)})}onAdd(u){this.map=u,this.load()}hasTransition(){return!1}loaded(){if(this._modelsInfo.size===0)return!0;for(const u of this._modelsInfo.values())if(u.model==null)return!1;return!0}getModels(){return this.models}loadTile(u,f){}serialize(){return this._options}setProperty(u,f){return!1}reload(){this.cancelModelRequests();const u=ft(this.id,this.scope);this.map.style.clearSource(u),this.models=[],this._modelsInfo.clear(),this.load()}onRemove(u){this.cancelModelRequests()}setModels(u){this.models=[];const f=new Map;for(const w in u){const C=u[w],I=this._modelsInfo.get(w);I&&I.modelSpec.uri===C.uri&&f.set(w,I)}if(this._modelsInfo.size!==f.size){this.cancelModelRequests();for(const[w,C]of f)C.model||f.delete(w)}this._modelsInfo=f,this._options.models=u,this.load()}}function Uve(v,u,f,w){const C=1<U>=xt.vertexArrayOffset&&Uut.polygon).flat());const Re=xe?B:null,[qe,nt]=gPe(I,w,oe,se,Y,L,Re,de,we,I.center.lat,v.tileID.canonical),Ze=v.queryGeometry;return pPe(qe,nt,Ze.isPointQuery()?Ze.screenBounds:Ze.screenGeometry)}},building:class extends to{constructor(v,u,f,w){super(v,{layout:qPe||(qPe=new Lo({visibility:new ur(es.layout_building.visibility),"building-facade":new dr(es.layout_building["building-facade"]),"building-facade-floors":new dr(es.layout_building["building-facade-floors"]),"building-facade-unit-width":new dr(es.layout_building["building-facade-unit-width"]),"building-facade-window":new dr(es.layout_building["building-facade-window"]),"building-roof-shape":new dr(es.layout_building["building-roof-shape"]),"building-height":new dr(es.layout_building["building-height"]),"building-base":new dr(es.layout_building["building-base"]),"building-flood-light-wall-radius":new dr(es.layout_building["building-flood-light-wall-radius"]),"building-flood-light-ground-radius":new dr(es.layout_building["building-flood-light-ground-radius"]),"building-flip-roof-orientation":new dr(es.layout_building["building-flip-roof-orientation"])})),paint:VPe||(VPe=new Lo({"building-opacity":new ur(es.paint_building["building-opacity"]),"building-ambient-occlusion-intensity":new ur(es.paint_building["building-ambient-occlusion-intensity"]),"building-ambient-occlusion-ground-intensity":new ur(es.paint_building["building-ambient-occlusion-ground-intensity"]),"building-ambient-occlusion-ground-radius":new ur(es.paint_building["building-ambient-occlusion-ground-radius"]),"building-ambient-occlusion-ground-attenuation":new ur(es.paint_building["building-ambient-occlusion-ground-attenuation"]),"building-vertical-scale":new ur(es.paint_building["building-vertical-scale"]),"building-cast-shadows":new ur(es.paint_building["building-cast-shadows"]),"building-color":new dr(es.paint_building["building-color"]),"building-emissive-strength":new dr(es.paint_building["building-emissive-strength"]),"building-facade-emissive-chance":new ur(es.paint_building["building-facade-emissive-chance"]),"building-cutoff-fade-range":new ur(es.paint_building["building-cutoff-fade-range"]),"building-front-cutoff":new ur(es.paint_building["building-front-cutoff"]),"building-flood-light-color":new ur(es.paint_building["building-flood-light-color"]),"building-flood-light-intensity":new ur(es.paint_building["building-flood-light-intensity"]),"building-flood-light-ground-attenuation":new ur(es.paint_building["building-flood-light-ground-attenuation"]),"building-color-use-theme":new dr({type:"string",default:"default","property-type":"data-driven"}),"building-flood-light-color-use-theme":new dr({type:"string",default:"default","property-type":"data-driven"})}))},u,f,w),this._stats={numRenderedVerticesInShadowPass:0,numRenderedVerticesInTransparentPass:0}}createBucket(v){return new UPe(v)}cutoffRange(){return this.paint.get("building-cutoff-fade-range")}hasShadowPass(){return this.paint.get("building-cast-shadows")}hasLightBeamPass(){return!0}canCastShadows(){return!0}is3D(v){return!0}queryRadius(v){return 0}queryIntersectsFeature(v,u,f,w,C,I,L,B,U,Y){let se=this.layout.get("building-height").evaluate(u,f);const oe=this.layout.get("building-base").evaluate(u,f),de=v.tile.getBucket(this).getFootprint(u);if(de){if(de.hiddenFlags!==0)return!1;se=de.height}const[xe,we]=gPe(I,w,oe,se,new ds(0,0),L,null,[0,0],1,I.center.lat,v.tileID.canonical),Ce=v.queryGeometry;return pPe(xe,we,Ce.isPointQuery()?Ce.screenBounds:Ce.screenGeometry)}},line:class extends to{constructor(v,u,f,w){const C=eLe();super(v,C,u,f,w),C.layout&&(this.layout=new Dd(C.layout)),this.gradientVersion=0,this.hasElevatedBuckets=!1,this.hasNonElevatedBuckets=!1}_handleSpecialPaintPropertyUpdate(v){if(v==="line-gradient"){const u=this._transitionablePaint._values["line-gradient"].value.expression;this.stepInterpolant=u._styleExpression&&u._styleExpression.expression instanceof bw,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(v,u){super.recalculate(v,u),this.paint._values["line-floorwidth"]=(()=>{if(VD)return VD;const f=eLe();return VD=new pwt(f.paint.properties["line-width"].specification),VD.useIntegerZoom=!0,VD})().possiblyEvaluate(this._transitioningPaint._values["line-width"].value,v)}createBucket(v){return new A$(v)}getProgramIds(){const v=[this.paint.get("line-pattern").constantOr(1)?"linePattern":"line"];return this.paint.get("line-blend-mode")!=="default"&&v.push("lineBlendComposite"),v}getDefaultProgramParams(v,u,f){if(v==="lineBlendComposite")return{};const w=QPe(this);return{config:new Te(this,{zoom:u,lut:f}),defines:w,overrideFog:!1}}queryRadius(v){const u=v,f=tLe(aN("line-width",this,u),aN("line-gap-width",this,u)),w=aN("line-offset",this,u);return f/2+Math.abs(w)+e$(this.paint.get("line-translate"))}queryIntersectsFeature(v,u,f,w,C,I){if(v.queryGeometry.isAboveHorizon)return!1;const L=J6e(v.tilespaceGeometry,this.paint.get("line-translate"),this.paint.get("line-translate-anchor"),I.angle,v.pixelToTileUnitsFactor),B=v.pixelToTileUnitsFactor/2*tLe(this.paint.get("line-width").evaluate(u,f),this.paint.get("line-gap-width").evaluate(u,f)),U=this.paint.get("line-offset").evaluate(u,f);return U&&(w=function(Y,se){const oe=[],de=new ds(0,0);for(let xe=0;xe=3){for(let we=0;we{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 g8e{constructor(u){this._stringToNumber={},this._numberToString=[];for(let f=0;f=0&&de[3]>=0&&Y.insert(U,de[0],de[1],de[2],de[3])}}loadVTLayers(){if(!this.vtLayers){this.vtLayers=new Ii(new M$(this.rawTileData)).layers,this.sourceLayerCoder=new g8e(this.vtLayers?Object.keys(this.vtLayers).sort():["_geojsonTileLayer"]),this.vtFeatures={};for(const u in this.vtLayers)this.vtFeatures[u]=[]}return this.vtLayers}query(u,f){const{tilespaceGeometry:w,transform:C,tileTransform:I,pixelPosMatrix:L,availableImages:B,worldview:U}=f;this.loadVTLayers(),this.serializedLayersCache.clear();const Y=f.queryRadius?f.queryRadius:0,se=w.bufferedTilespaceBounds,oe=this.grid.query(se.min.x,se.min.y,se.max.x,se.max.y,(Ce,Re,qe,nt)=>xb(w.bufferedTilespaceGeometry,Ce-Y,Re-Y,qe+Y,nt+Y));oe.sort(k2t);let de=null;C.elevation&&oe.length>0&&(de=HM.create(C.elevation,this.tileID));const xe={};let we;for(let Ce=0;Ce(nt||(nt=Ln(Ze,this.tileID.canonical,I)),ut.queryIntersectsFeature(w,Ze,xt,nt,this.z,C,L,de,bt,f.scope)))}return xe}loadMatchingFeature(u,f,w,C,I,L){const{featureIndex:B,bucketIndex:U,sourceLayerIndex:Y,layoutVertexArrayOffset:se}=f,oe=this.bucketLayerIDs[U],de=w.layers,xe=Object.keys(de);if(xe.length&&!ln(xe,oe))return;const we=w.sourceCache,Ce=this.sourceLayerCoder.decode(Y),Re=this.vtLayers[Ce].feature(B),qe=this.getId(Re,Ce);for(let nt=0;nt`${B.key}: ${B.message}`).join(", ");return void Gr(`Failed to create expression for promoteId: ${L}`)}this.promoteIdExpression=I.value}w=this.promoteIdExpression.evaluate({zoom:0},u)}else w=u.properties[C];typeof w=="boolean"&&(w=Number(w))}return w}}function y8e(v,u,f,w,C){return Xs(v,(I,L)=>{const B=u instanceof Dd?u.get(L):null;return B&&B.evaluate?B.evaluate(f,w,void 0,C):B})}function k2t(v,u){return u-v}function v8e(v,u){const f={};if(!u)return f;for(const w of v){const C=w.layerIds.map(I=>u.getLayer(I)).filter(Boolean);if(C.length!==0){w.layers=C,w.stateDependentLayerIds&&(w.stateDependentLayers=w.stateDependentLayerIds.map(I=>C.filter(L=>L.id===I)[0]));for(const I of C)f[I.fqid]=w}}return f}Pr(x8e,"FeatureIndex",{omit:["rawTileData","sourceLayerCoder"]});const oy=32,Nb=33,hN=new Uint16Array(8184);for(let v=0;v<2046;v++){let u=v+2,f=0,w=0,C=0,I=0,L=0,B=0;for(1&u?C=I=L=oy:f=w=B=oy;(u>>=1)>1;){const Y=f+C>>1,se=w+I>>1;1&u?(C=f,I=w,f=L,w=B):(f=C,w=I,C=L,I=B),L=Y,B=se}const U=4*v;hN[U+0]=f,hN[U+1]=w,hN[U+2]=C,hN[U+3]=I}const kb=new Uint16Array(2178),mN=new Uint8Array(1089),X$=new Uint16Array(1089);function b8e(v){return v===0?-.03125:v===32?.03125:0}const _8e={Other:0,Symbol:1,FillExtrusion:2},w8e={type:2,extent:Sr,loadGeometry:()=>[[new ds(0,0),new ds(8193,0),new ds(8193,8193),new ds(0,8193),new ds(0,0)]]};class S2t{constructor(){this.tasks={},this.taskQueue=[],ls(["process"],this),this.invoker=new N2t(this.process),this.nextId=0}add(u,f){const w=this.nextId++,C=function({type:I,renderSourceType:L,zoom:B}){B=B||0;const U=L===_8e.Symbol;return I==="message"?0:I!=="maybePrepare"||U?I!=="parseTile"||U?I==="parseTile"&&U?300-B:I==="maybePrepare"&&U?400-B:500:200-B:100-B}(f);if(C===0){try{u()}finally{}return null}return this.tasks[w]={fn:u,metadata:f,priority:C,id:w},this.taskQueue.push(w),this.invoker.trigger(),{cancel:()=>{delete this.tasks[w]}}}process(){try{if(this.taskQueue=this.taskQueue.filter(w=>!!this.tasks[w]),!this.taskQueue.length)return;const u=this.pick();if(u===null)return;const f=this.tasks[u];if(delete this.tasks[u],this.taskQueue.length&&this.invoker.trigger(),!f)return;f.fn()}finally{}}pick(){let u=null,f=1/0;for(let C=0;C>16&255)/255,(v>>8&255)/255,(255&v)/255,1)}function F2t(v,u,f){v===1?(u.rgb_color=eU(f.readVarint()),u.paint="rgb_color"):v===2?(u.linear_gradient_idx=f.readVarint(),u.paint="linear_gradient_idx"):v===3?(u.radial_gradient_idx=f.readVarint(),u.paint="radial_gradient_idx"):v===5?f.readPackedFloat(u.dasharray):v===6?u.dashoffset=f.readFloat():v===7?u.miterlimit=f.readFloat():v===8?u.opacity=f.readVarint():v===9?u.width=f.readFloat():v===10?u.linecap=f.readVarint():v===11&&(u.linejoin=f.readVarint())}function B2t(v,u,f){v===1?u.transform=J$(f,f.readVarint()+f.pos):v===2?u.spread_method=f.readVarint():v===3?u.stops.push(k8e(f,f.readVarint()+f.pos)):v===4?u.x1=f.readFloat():v===5?u.y1=f.readFloat():v===6?u.x2=f.readFloat():v===7&&(u.y2=f.readFloat())}function k8e(v,u){return v.readFields(z2t,{offset:0,opacity:255,rgb_color:qve},u)}function z2t(v,u,f){v===1?u.offset=f.readFloat():v===2?u.opacity=f.readVarint():v===3&&(u.rgb_color=eU(f.readVarint()))}function $2t(v,u,f){v===1?u.transform=J$(f,f.readVarint()+f.pos):v===2?u.spread_method=f.readVarint():v===3?u.stops.push(k8e(f,f.readVarint()+f.pos)):v===4?u.cx=f.readFloat():v===5?u.cy=f.readFloat():v===6?u.r=f.readFloat():v===7?u.fx=f.readFloat():v===8?u.fy=f.readFloat():v===9&&(u.fr=f.readFloat())}function U2t(v,u,f){v===1?u.transform=J$(f,f.readVarint()+f.pos):v===2?u.clip_path_idx=f.readVarint():v===3&&u.children.push(Q$(f,f.readVarint()+f.pos))}function q2t(v,u,f){v===1?u.left=u.top=f.readFloat():v===2?u.width=u.height=f.readFloat():v===3?u.top=f.readFloat():v===4?u.height=f.readFloat():v===5?u.mask_type=f.readVarint():v===6?u.mask_idx=f.readVarint():v===7&&u.children.push(Q$(f,f.readVarint()+f.pos))}class V2t{static calculate(u={},f=[]){const w=new Map,C=new Map;if(Object.keys(u).length===0)return w;f.forEach(I=>{C.set(I.name,I.rgb_color||new Mr(0,0,0))});for(const[I,L]of Object.entries(u))C.has(I)?w.set(C.get(I).toString(),L):console.warn(`Ignoring unknown image variable "${I}"`);return w}}function GM(v,u=255,f){const w=u/255,C=v.toString(),I=f.has(C)?f.get(C).clone():v.clone();return I.a*=w,I.toString()}function aR(v,u){if(!Su()){const f=document.createElement("canvas");return f.width=v,f.height=u,f}return new OffscreenCanvas(v,u)}let Vve,iR=null;function Hve(v,u,f,w,C){for(const I of w.children)S8e(v,u,f,I,C)}function S8e(v,u,f,w,C){w.group?(v.save(),function(I,L,B,U,Y){const se=U.mask_idx!=null?B.masks[U.mask_idx]:null,oe=U.clip_path_idx!=null?B.clip_paths[U.clip_path_idx]:null;if(U.transform&&(L=WM(U.transform).preMultiplySelf(L)),!function(we,Ce,Re){return we.opacity!==255||Ce||Re}(U,oe!=null,se!=null))return void Hve(I,L,B,U,Y);const de=aR(I.canvas.width,I.canvas.height),xe=de.getContext("2d");Hve(xe,L,B,U,Y),oe&&P8e(xe,L,B,oe),se&&L8e(xe,L,B,se,Y),I.globalAlpha=U.opacity/255,I.drawImage(de,0,0)}(v,u,f,w.group,C),v.restore()):w.path&&(v.save(),function(I,L,B,U,Y){I.setTransform(L),U.paint_order===1?(C8e(I,B,U,Y),E8e(I,B,U,Y)):(E8e(I,B,U,Y),C8e(I,B,U,Y))}(v,u,f,w.path,C),v.restore())}function C8e(v,u,f,w){const C=f.fill;if(!C)return;const I=C.opacity/255;switch(v.save(),v.beginPath(),D8e(f,v),C.paint){case"rgb_color":v.fillStyle=GM(C.rgb_color,C.opacity,w);break;case"linear_gradient_idx":{const L=u.linear_gradients[C.linear_gradient_idx];L.transform&&v.setTransform(WM(L.transform).preMultiplySelf(v.getTransform())),v.fillStyle=A8e(v,L,I,w);break}case"radial_gradient_idx":{const L=u.radial_gradients[C.radial_gradient_idx];L.transform&&v.setTransform(WM(L.transform).preMultiplySelf(v.getTransform())),v.fillStyle=M8e(v,L,I,w)}}v.fill(T8e(f)),v.restore()}function T8e(v){return v.rule===1?"nonzero":v.rule===2?"evenodd":void 0}function E8e(v,u,f,w){const C=f.stroke;if(!C)return;const I=R8e(f);v.lineWidth=C.width,v.miterLimit=C.miterlimit,v.setLineDash(C.dasharray),v.lineDashOffset=C.dashoffset;const L=C.opacity/255;switch(C.paint){case"rgb_color":v.strokeStyle=GM(C.rgb_color,C.opacity,w);break;case"linear_gradient_idx":v.strokeStyle=A8e(v,u.linear_gradients[C.linear_gradient_idx],L,w,!0);break;case"radial_gradient_idx":v.strokeStyle=M8e(v,u.radial_gradients[C.radial_gradient_idx],L,w,!0)}switch(C.linejoin){case 2:case 1:v.lineJoin="miter";break;case 3:v.lineJoin="round";break;case 4:v.lineJoin="bevel"}switch(C.linecap){case 1:v.lineCap="butt";break;case 2:v.lineCap="round";break;case 3:v.lineCap="square"}v.stroke(I)}function A8e(v,u,f,w,C=!1){if(u.stops.length===1){const de=u.stops[0];return GM(de.rgb_color,de.opacity*f,w)}const{x1:I,y1:L,x2:B,y2:U}=u;let Y=new DOMPoint(I,L),se=new DOMPoint(B,U);if(C){const de=WM(u.transform);Y=de.transformPoint(Y),se=de.transformPoint(se)}const oe=v.createLinearGradient(Y.x,Y.y,se.x,se.y);for(const de of u.stops)oe.addColorStop(de.offset,GM(de.rgb_color,de.opacity*f,w));return oe}function M8e(v,u,f,w,C=!1){if(u.stops.length===1){const qe=u.stops[0];return GM(qe.rgb_color,qe.opacity*f,w)}const I=WM(u.transform),{fx:L,fy:B,fr:U,cx:Y,cy:se,r:oe}=u;let de=new DOMPoint(L,B),xe=new DOMPoint(Y,se),we=U,Ce=oe;if(C){de=I.transformPoint(de),xe=I.transformPoint(xe);const qe=(I.a+I.d)/2;we=U*qe,Ce=u.r*qe}const Re=v.createRadialGradient(de.x,de.y,we,xe.x,xe.y,Ce);for(const qe of u.stops)Re.addColorStop(qe.offset,GM(qe.rgb_color,qe.opacity*f,w));return Re}function I8e(v,u,f,w){const C=w.transform?WM(w.transform).preMultiplySelf(u):u,I=aR(v.canvas.width,v.canvas.height),L=I.getContext("2d");for(const U of w.children)if(U.group)I8e(L,C,f,U.group);else if(U.path){const Y=U.path,se=new Path2D;se.addPath(R8e(Y),C),L.fill(se,T8e(Y))}const B=w.clip_path_idx!=null?f.clip_paths[w.clip_path_idx]:null;B&&P8e(L,C,f,B),v.globalCompositeOperation="source-over",v.drawImage(I,0,0)}function P8e(v,u,f,w){const C=aR(v.canvas.width,v.canvas.height);I8e(C.getContext("2d"),u,f,w),v.globalCompositeOperation="destination-in",v.drawImage(C,0,0)}function L8e(v,u,f,w,C){if(w.children.length===0)return;const I=w.mask_idx!=null?f.masks[w.mask_idx]:null;I&&L8e(v,u,f,I,C);const L=v.canvas.width,B=v.canvas.height,U=aR(L,B),Y=U.getContext("2d"),se=w.width,oe=w.height,de=w.left,xe=w.top,we=new Path2D,Ce=new Path2D;Ce.rect(de,xe,se,oe),we.addPath(Ce,u),Y.clip(we);for(const nt of w.children)S8e(Y,u,f,nt,C);const Re=Y.getImageData(0,0,L,B),qe=Re.data;if(w.mask_type===1)for(let nt=0;ntu[L])return null}else{const B=1/w[L];let U=(v[L]-f[L])*B,Y=(u[L]-f[L])*B;if(U>Y){const se=U;U=Y,Y=se}if(U>C&&(C=U),YI)return null}return C}function B8e(v,u,f,w,C,I,L,B,U,Y,se){const oe=w-v,de=C-u,xe=I-f,we=L-v,Ce=B-u,Re=U-f,qe=se[1]*Re-se[2]*Ce,nt=se[2]*we-se[0]*Re,Ze=se[0]*Ce-se[1]*we,ut=oe*qe+de*nt+xe*Ze;if(Math.abs(ut)<1e-15)return null;const xt=1/ut,bt=Y[0]-v,Ht=Y[1]-u,Rt=Y[2]-f,Vt=(bt*qe+Ht*nt+Rt*Ze)*xt;if(Vt<0||Vt>1)return null;const Bt=Ht*xe-Rt*de,$t=Rt*oe-bt*xe,js=bt*de-Ht*oe,Es=(se[0]*Bt+se[1]*$t+se[2]*js)*xt;return Es<0||Vt+Es>1?null:(we*Bt+Ce*$t+Re*js)*xt}function z8e(v,u,f){return(v-u)/(f-u)}function $8e(v,u,f,w,C,I,L,B,U){const Y=1<{const nt=Re?1:0,Ze=(xe+1)*Ce-nt,ut=we*Ce,xt=(we+1)*Ce-nt;qe[0]=xe*Ce,qe[1]=ut,qe[2]=Ze,qe[3]=xt};let oe=new O8e(U);const de=[];for(let xe=0;xe=1;U/=2){const xe=B[B.length-1];oe=new O8e(U);for(let we=0;we0;){const{idx:we,t:Ce,nodex:Re,nodey:qe,depth:nt}=xe.pop();if(this.leaves[we]){$8e(Re,qe,nt,u,f,w,C,oe,de);const ut=1<=$s[2])return Ce}continue}let Ze=0;for(let ut=0;ut=Y[se[Rt]]&&(se.splice(Rt,0,ut),Ht=!0);Ht||(se[Ze]=ut),Ze++}}for(let ut=0;ut=this.dim+1||f<-1||f>=this.dim+1)throw new RangeError("out of range source coordinates for DEM data");return(f+1)*this.stride+(u+1)}static pack(u,f){const w=[0,0,0,0],C=sU.getUnpackVector(f);let I=Math.floor((u+C[3])/C[2]);return w[2]=I%256,I=Math.floor(I/256),w[1]=I%256,I=Math.floor(I/256),w[0]=I,w}getPixels(){return new NIe({width:this.stride,height:this.stride},this.pixels)}backfillBorder(u,f,w){if(this.dim!==u.dim)throw new Error("dem dimension mismatch");let C=f*this.dim,I=f*this.dim+this.dim,L=w*this.dim,B=w*this.dim+this.dim;switch(f){case-1:C=I-1;break;case 1:I=C+1}switch(w){case-1:L=B-1;break;case 1:B=L+1}const U=-f*this.dim,Y=-w*this.dim;for(let se=L;se=1;w--){const C=w===1?1:0,I=w===2?1:0;for(let L=0;L>>1^-(1&v[u]);return v}function njt(v,u){switch(u){case"uint32":return v;case"uint16":for(let f=0;f>4|(61440&w)>>8|(240&C)<<4|61440&C,v[f+1]=15&w|(3840&w)>>4|(15&C)<<8|(3840&C)<<4}return v;case"uint8":for(let f=0;f>6|(192&C)>>4|(192&I)>>2|192&L,v[f+1]=(48&w)>>4|(48&C)>>2|48&I|(48&L)<<2,v[f+2]=(12&w)>>2|12&C|(12&I)<<2|(12&L)<<4,v[f+3]=3&w|(3&C)<<2|(3&I)<<4|(3&L)<<6}return v;default:throw new Error(`Invalid pixel format, "${u}"`)}}Pr(sU,"DEMData"),Pr(U8e,"DemMinMaxQuadTree",{omit:["dem"]});var Lx=Uint8Array,oR=Uint16Array,ajt=Int32Array,V8e=new Lx([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]),H8e=new Lx([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]),ijt=new Lx([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),G8e=function(v,u){for(var f=new oR(31),w=0;w<31;++w)f[w]=u+=1<>1|(21845&gd)<<1;Y8e[gd]=((65280&(KM=(61680&(KM=(52428&KM)>>2|(13107&KM)<<2))>>4|(3855&KM)<<4))>>8|(255&KM)<<8)>>1}var lR=function(v,u,f){for(var w=v.length,C=0,I=new oR(u);C>U]=Y;return L},cR=new Lx(288);for(gd=0;gd<144;++gd)cR[gd]=8;for(gd=144;gd<256;++gd)cR[gd]=9;for(gd=256;gd<280;++gd)cR[gd]=7;for(gd=280;gd<288;++gd)cR[gd]=8;var Z8e=new Lx(32);for(gd=0;gd<32;++gd)Z8e[gd]=5;var cjt=lR(cR,9),djt=lR(Z8e,5),Wve=function(v){for(var u=v[0],f=1;fu&&(u=v[f]);return u},Fv=function(v,u,f){var w=u/8|0;return(v[w]|v[w+1]<<8)>>(7&u)&f},Kve=function(v,u){var f=u/8|0;return(v[f]|v[f+1]<<8|v[f+2]<<16)>>(7&u)},ujt=function(v){return(v+7)/8|0},hjt=["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"],Bv=function(v,u,f){var w=new Error(u||hjt[v]);if(w.code=v,Error.captureStackTrace&&Error.captureStackTrace(w,Bv),!f)throw w;return w},mjt=new Lx(0),fjt=typeof TextDecoder<"u"&&new TextDecoder;try{fjt.decode(mjt,{stream:!0})}catch{}const pjt={gzip_data:"gzip"};class ly extends Error{constructor(u){super(u),this.name="MRTError"}}const gjt={0:"uint32",1:"uint32",2:"uint16",3:"uint8"},X8e={uint32:1,uint16:2,uint8:4},xjt={uint32:Uint32Array,uint16:Uint16Array,uint8:Uint8Array};let Yve;class rU{constructor(u=5){this.x=NaN,this.y=NaN,this.z=NaN,this.layers={},this._cacheSize=u}getLayer(u){const f=this.layers[u];if(!f)throw new ly(`Layer '${u}' not found`);return f}getHeaderLength(u){const f=new Uint8Array(u),w=new DataView(u);if(f[0]!==13)throw new ly("File is not a valid MRT.");return w.getUint32(1,!0)}parseHeader(u){const f=new Uint8Array(u),w=this.getHeaderLength(u);if(f.length= ${w} but got buffer of length ${f.length}`);const C=new Yve(f.subarray(0,w)).readFields(K2t,{headerLength:0,x:0,y:0,z:0,layers:[]},void 0);if(!isNaN(this.x)&&(this.x!==C.x||this.y!==C.y||this.z!==C.z))throw new ly(`Invalid attempt to parse header ${C.z}/${C.x}/${C.y} for tile ${this.z}/${this.x}/${this.y}`);this.x=C.x,this.y=C.y,this.z=C.z;for(const I of C.layers)this.layers[I.name]=new Q8e(I,{cacheSize:this._cacheSize});return this}createDecodingTask(u){const f=[],w=this.getLayer(u.layerName);for(let C of u.blockIndices){const I=w.dataIndex[C],L=I.firstByte-u.firstByte,B=I.lastByte-u.firstByte;if(w._blocksInProgress.has(C))continue;const U={layerName:w.name,firstByte:L,lastByte:B,pixelFormat:w.pixelFormat,blockIndex:C,blockShape:[I.bands.length].concat(w.bandShape),buffer:w.buffer,codec:I.codec.codec,filters:I.filters.map(Y=>Y.filter)};w._blocksInProgress.add(C),f.push(U)}return new J8e(f,()=>{f.forEach(C=>w._blocksInProgress.delete(C.blockIndex))},(C,I)=>{if(f.forEach(L=>w._blocksInProgress.delete(L.blockIndex)),C)throw C;I.forEach(L=>{this.getLayer(L.layerName).processDecodedData(L)})})}}class Q8e{constructor({version:u,name:f,units:w,tileSize:C,pixelFormat:I,buffer:L,dataIndex:B},U){if(this.version=u,this.version!==1)throw new ly(`Cannot parse raster layer encoded with MRT version ${u}`);this.name=f,this.units=w,this.tileSize=C,this.buffer=L,this.pixelFormat=gjt[I],this.dataIndex=B,this.bandShape=[C+2*L,C+2*L,X8e[this.pixelFormat]],this._decodedBlocks=new tU(U?U.cacheSize:5),this._blocksInProgress=new Set}get dimension(){return X8e[this.pixelFormat]}get cacheSize(){return this._decodedBlocks.capacity}getBandList(){return this.dataIndex.map(({bands:u})=>u).flat()}processDecodedData(u){const f=u.blockIndex.toString();this._decodedBlocks.get(f)||this._decodedBlocks.put(f,u.data)}getBlockForBand(u){let f=0;switch(typeof u){case"string":for(const[w,C]of this.dataIndex.entries()){for(const[I,L]of C.bands.entries())if(L===u)return{bandIndex:f+I,blockIndex:w,blockBandIndex:I};f+=C.bands.length}break;case"number":for(const[w,C]of this.dataIndex.entries()){if(u>=f&&uthis.cacheSize)throw new ly(`Number of blocks to decode (${I.size}) exceeds cache size (${this.cacheSize}).`);return{layerName:this.name,firstByte:f,lastByte:w,blockIndices:C}}hasBand(u){const{blockIndex:f}=this.getBlockForBand(u);return f>=0}hasDataForBand(u){const{blockIndex:f}=this.getBlockForBand(u);return f>=0&&!!this._decodedBlocks.get(f.toString())}getBandView(u){const{blockIndex:f,blockBandIndex:w}=this.getBlockForBand(u);if(f<0)throw new ly(`Band not found: ${JSON.stringify(u)}`);const C=this._decodedBlocks.get(f.toString());if(!C)throw new ly(`Data for band ${JSON.stringify(u)} of layer "${this.name}" not decoded.`);const I=this.dataIndex[f],L=this.bandShape.reduce((Y,se)=>Y*se,1),B=w*L,U=C.subarray(B,B+L);return{data:U,bytes:new Uint8Array(U.buffer).subarray(U.byteOffset,U.byteOffset+U.byteLength),tileSize:this.tileSize,buffer:this.buffer,pixelFormat:this.pixelFormat,dimension:this.dimension,offset:I.offset,scale:I.scale}}}rU.setPbf=function(v){Yve=v};class J8e{constructor(u,f,w){this.tasks=u,this._onCancel=f,this._onComplete=w,this._finalized=!1}cancel(){this._finalized||(this._onCancel(),this._finalized=!0)}complete(u,f){this._finalized||(this._onComplete(u,f),this._finalized=!0)}}rU.performDecoding=function(v,u){const f=new Uint8Array(v);return Promise.all(u.tasks.map(w=>{const{layerName:C,firstByte:I,lastByte:L,pixelFormat:B,blockShape:U,blockIndex:Y,filters:se,codec:oe}=w,de=f.subarray(I,L+1),xe=new Uint32Array(U[0]*U[1]*U[2]);let we;if(oe!=="gzip_data")throw new ly(`Unhandled codec: ${oe}`);return we=function(Ce,Re){if(!globalThis.DecompressionStream&&Re==="gzip_data")return Promise.resolve((xt=function(Rt){Rt[0]==31&&Rt[1]==139&&Rt[2]==8||Bv(6,"invalid gzip data");var Vt=Rt[3],Bt=10;4&Vt&&(Bt+=2+(Rt[10]|Rt[11]<<8));for(var $t=(Vt>>3&1)+(Vt>>4&1);$t>0;$t-=!Rt[Bt++]);return Bt+(2&Vt)}(qe=Ce),xt+8>qe.length&&Bv(6,"invalid gzip data"),function(Rt,Vt,Bt,$t){var js=Rt.length;if(!js||Vt.f&&!Vt.l)return Bt||new Lx(0);var Es=!Bt,zs=Es||Vt.i!=2,Hs=Vt.i;Es&&(Bt=new Lx(3*js));var $s=function(Pl){var Qh=Bt.length;if(Pl>Qh){var ru=new Lx(Math.max(2*Qh,Pl));ru.set(Bt),Bt=ru}},nr=Vt.f||0,ys=Vt.p||0,qs=Vt.b||0,Zs=Vt.l,ir=Vt.d,pr=Vt.m,Zr=Vt.n,Nr=8*js;do{if(!Zs){nr=Fv(Rt,ys,1);var jr=Fv(Rt,ys+1,3);if(ys+=3,!jr){var gr=Rt[($i=ujt(ys)+4)-4]|Rt[$i-3]<<8,qr=$i+gr;if(qr>js){Hs&&Bv(0);break}zs&&$s(qs+gr),Bt.set(Rt.subarray($i,qr),qs),Vt.b=qs+=gr,Vt.p=ys=8*qr,Vt.f=nr;continue}if(jr==1)Zs=cjt,ir=djt,pr=9,Zr=5;else if(jr==2){var tn=Fv(Rt,ys,31)+257,In=Fv(Rt,ys+10,15)+4,cn=tn+Fv(Rt,ys+5,31)+1;ys+=14;for(var fa=new Lx(cn),xi=new Lx(19),pa=0;pa>4)<16)fa[pa++]=$i;else{var Co=0,vl=0;for($i==16?(vl=3+Fv(Rt,ys,3),ys+=2,Co=fa[pa-1]):$i==17?(vl=3+Fv(Rt,ys,7),ys+=3):$i==18&&(vl=11+Fv(Rt,ys,127),ys+=7);vl--;)fa[pa++]=Co}}var Fd=fa.subarray(0,tn),bl=fa.subarray(tn);pr=Wve(Fd),Zr=Wve(bl),Zs=lR(Fd,pr),ir=lR(bl,Zr)}else Bv(1);if(ys>Nr){Hs&&Bv(0);break}}zs&&$s(qs+131072);for(var Zl=(1<>4;if((ys+=15&Co)>Nr){Hs&&Bv(0);break}if(Co||Bv(2),nh<256)Bt[qs++]=nh;else{if(nh==256){Xl=ys,Zs=null;break}var Bd=nh-254;nh>264&&(Bd=Fv(Rt,ys,(1<<(rc=V8e[pa=nh-257]))-1)+K8e[pa],ys+=rc);var Va=ir[Kve(Rt,ys)&Nc],zm=Va>>4;if(Va||Bv(3),ys+=15&Va,bl=ljt[zm],zm>3){var rc=H8e[zm];bl+=Kve(Rt,ys)&(1<Nr){Hs&&Bv(0);break}zs&&$s(qs+131072);var su=qs+Bd;if(qsPl.length)&&(ru=Pl.length),new Lx(Pl.subarray(0,ru))}(Bt,0,qs):Bt.subarray(0,qs)}(qe.subarray(xt,-8),{i:2},new Lx(((Ze=qe)[(ut=Ze.length)-4]|Ze[ut-3]<<8|Ze[ut-2]<<16|Ze[ut-1]<<24)>>>0),nt)));var qe,nt,Ze,ut,xt;const bt=pjt[Re];if(!bt)throw new Error(`Unhandled codec: ${Re}`);const Ht=new globalThis.DecompressionStream(bt);return new Response(new Blob([Ce]).stream().pipeThrough(Ht)).arrayBuffer().then(Rt=>new Uint8Array(Rt))}(de,oe).then(Ce=>(function(Re,qe){Re.readFields(ejt,qe)}(new Yve(Ce),xe),new xjt[B](xe.buffer))),we.then(Ce=>{for(let Re=se.length-1;Re>=0;Re--)switch(se[Re]){case"delta_filter":sjt(Ce,U);break;case"zigzag_filter":rjt(Ce);break;case"bitshuffle_filter":njt(Ce,B);break;default:throw new ly(`Unhandled filter "${se[Re]}"`)}return{layerName:C,blockIndex:Y,data:Ce}}).catch(Ce=>{throw Ce})}))},Pr(J8e,"MRTDecodingBatch",{omit:["_onCancel","_onComplete"]}),Pr(rU,"MapboxRasterTile"),Pr(Q8e,"MapboxRasterLayer",{omit:["_blocksInProgress"]});const eDe=[Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array];class Zve{static from(u){if(!(u instanceof ArrayBuffer))throw new Error("Data must be an instance of ArrayBuffer.");const[f,w]=new Uint8Array(u,0,2);if(f!==219)throw new Error("Data does not appear to be in a KDBush format.");const C=w>>4;if(C!==1)throw new Error(`Got v${C} data when expected v1.`);const I=eDe[15&w];if(!I)throw new Error("Unrecognized array type.");const[L]=new Uint16Array(u,2,1),[B]=new Uint32Array(u,4,1);return new Zve(B,L,I,u)}constructor(u,f=64,w=Float64Array,C){if(isNaN(u)||u<0)throw new Error(`Unpexpected numItems value: ${u}.`);this.numItems=+u,this.nodeSize=Math.min(Math.max(+f,2),65535),this.ArrayType=w,this.IndexArrayType=u<65536?Uint16Array:Uint32Array;const I=eDe.indexOf(this.ArrayType),L=2*u*this.ArrayType.BYTES_PER_ELEMENT,B=u*this.IndexArrayType.BYTES_PER_ELEMENT,U=(8-B%8)%8;if(I<0)throw new Error(`Unexpected typed array class: ${w}.`);C&&C instanceof ArrayBuffer?(this.data=C,this.ids=new this.IndexArrayType(this.data,8,u),this.coords=new this.ArrayType(this.data,8+B+U,2*u),this._pos=2*u,this._finished=!0):(this.data=new ArrayBuffer(8+L+B+U),this.ids=new this.IndexArrayType(this.data,8,u),this.coords=new this.ArrayType(this.data,8+B+U,2*u),this._pos=0,this._finished=!1,new Uint8Array(this.data,0,2).set([219,16+I]),new Uint16Array(this.data,2,1)[0]=f,new Uint32Array(this.data,4,1)[0]=u)}add(u,f){const w=this._pos>>1;return this.ids[w]=w,this.coords[this._pos++]=u,this.coords[this._pos++]=f,w}finish(){const u=this._pos>>1;if(u!==this.numItems)throw new Error(`Added ${u} items when expected ${this.numItems}.`);return Xve(this.ids,this.coords,this.nodeSize,0,this.numItems-1,0),this._finished=!0,this}range(u,f,w,C){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:I,coords:L,nodeSize:B}=this,U=[0,I.length-1,0],Y=[];for(;U.length;){const se=U.pop()||0,oe=U.pop()||0,de=U.pop()||0;if(oe-de<=B){for(let Re=de;Re<=oe;Re++){const qe=L[2*Re],nt=L[2*Re+1];qe>=u&&qe<=w&&nt>=f&&nt<=C&&Y.push(I[Re])}continue}const xe=de+oe>>1,we=L[2*xe],Ce=L[2*xe+1];we>=u&&we<=w&&Ce>=f&&Ce<=C&&Y.push(I[xe]),(se===0?u<=we:f<=Ce)&&(U.push(de),U.push(xe-1),U.push(1-se)),(se===0?w>=we:C>=Ce)&&(U.push(xe+1),U.push(oe),U.push(1-se))}return Y}within(u,f,w){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:C,coords:I,nodeSize:L}=this,B=[0,C.length-1,0],U=[],Y=w*w;for(;B.length;){const se=B.pop()||0,oe=B.pop()||0,de=B.pop()||0;if(oe-de<=L){for(let Re=de;Re<=oe;Re++)sDe(I[2*Re],I[2*Re+1],u,f)<=Y&&U.push(C[Re]);continue}const xe=de+oe>>1,we=I[2*xe],Ce=I[2*xe+1];sDe(we,Ce,u,f)<=Y&&U.push(C[xe]),(se===0?u-w<=we:f-w<=Ce)&&(B.push(de),B.push(xe-1),B.push(1-se)),(se===0?u+w>=we:f+w>=Ce)&&(B.push(xe+1),B.push(oe),B.push(1-se))}return U}}function Xve(v,u,f,w,C,I){if(C-w<=f)return;const L=w+C>>1;tDe(v,u,L,w,C,I),Xve(v,u,f,w,L-1,1-I),Xve(v,u,f,L+1,C,1-I)}function tDe(v,u,f,w,C,I){for(;C>w;){if(C-w>600){const Y=C-w+1,se=f-w+1,oe=Math.log(Y),de=.5*Math.exp(2*oe/3),xe=.5*Math.sqrt(oe*de*(Y-de)/Y)*(se-Y/2<0?-1:1);tDe(v,u,f,Math.max(w,Math.floor(f-se*de/Y+xe)),Math.min(C,Math.floor(f+(Y-se)*de/Y+xe)),I)}const L=u[2*f+I];let B=w,U=C;for(dR(v,u,w,f),u[2*C+I]>L&&dR(v,u,w,C);BL;)U--}u[2*w+I]===L?dR(v,u,w,U):(U++,dR(v,u,U,C)),U<=f&&(w=U+1),f<=U&&(C=U-1)}}function dR(v,u,f,w){Qve(v,f,w),Qve(u,2*f,2*w),Qve(u,2*f+1,2*w+1)}function Qve(v,u,f){const w=v[u];v[u]=v[f],v[f]=w}function sDe(v,u,f,w){const C=v-f,I=u-w;return C*C+I*I}o.$=X0,o.A=class{constructor(v,u,f){this.target=v,this.parent=u,this.mapId=f,this.callbacks={},this.cancelCallbacks={},ls(["receive"],this),this.target.addEventListener("message",this.receive,!1),this.scheduler=new S2t}send(v,u,f,w,C=!1,I){const L=Math.round(1e18*Math.random()).toString(36).substring(0,10);f&&(f.metadata=I,this.callbacks[L]=f);const B=new Set;return this.target.postMessage({id:L,type:v,hasCallback:!!f,targetMapId:w,mustQueue:C,sourceMapId:this.mapId,data:tc(u,B)},B),{cancel:()=>{f&&delete this.callbacks[L],this.target.postMessage({id:L,type:"",targetMapId:w,sourceMapId:this.mapId})}}}receive(v){const u=v.data;if(!u)return;const f=u.id;if(f&&(!u.targetMapId||this.mapId===u.targetMapId))if(u.type===""){const w=this.cancelCallbacks[f];delete this.cancelCallbacks[f],w&&w.cancel()}else if(u.mustQueue||Aa(self)){const w=this.callbacks[f],C=this.scheduler.add(()=>this.processTask(f,u),w&&w.metadata||{type:"message"});C&&(this.cancelCallbacks[f]=C)}else this.processTask(f,u)}processTask(v,u){if(delete this.cancelCallbacks[v],u.type===""){const f=this.callbacks[v];delete this.callbacks[v],f&&(u.error?f(Kl(u.error)):f(null,Kl(u.data)))}else{const f=new Set,w=u.hasCallback?(I,L)=>{this.target.postMessage({id:v,type:"",sourceMapId:this.mapId,error:I?tc(I):null,data:tc(L,f)},f)}:()=>{},C=Kl(u.data);if(this.parent[u.type])this.parent[u.type](u.sourceMapId,C,w);else if(this.parent.getWorkerSource){const I=u.type.split("."),{source:L,scope:B}=C;this.parent.getWorkerSource(u.sourceMapId,{type:I[0],source:L,scope:B,uid:0})[I[1]](C,w)}else w(new Error(`Could not find function ${u.type}`))}}remove(){this.scheduler.remove(),this.target.removeEventListener("message",this.receive,!1)}},o.B=Am,o.C=_c,o.D=Im,o.E=hf,o.F=ft,o.G=2,o.H=WD,o.I=Mt,o.J=bLe,o.K=iw,o.L=Ow,o.M=G0,o.N=Y1,o.O=Om,o.P=ds,o.Q=yf,o.R=vx,o.S=Vj,o.T=jb,o.U=ey,o.V=Y$,o.W=pb,o.X=Up,o.Y=Ew,o.Z=Wh,o._=Z0,o.a=function(v){return ia.API_CDN_URL_REGEX.test(v)},o.a$=M$,o.a0=wc,o.a1=bx,o.a2=hv,o.a3=bn,o.a4=Fw,o.a5=class extends Y${},o.a6=Hj,o.a7=qj,o.a8=es,o.a9=function(v){const u=v.value;return u?hv(u)?Bve(u,!0)?[]:[new Y$(v.key,u,`invalid url "${u}"`)]:[new Y$(v.key,u,`string expected, "${G0(u)}" found`)]:[]},o.aA=KPe,o.aB=function(v){let u=1/0,f=1/0,w=-1/0,C=-1/0;for(const I of v)u=Math.min(u,I.x),f=Math.min(f,I.y),w=Math.max(w,I.x),C=Math.max(C,I.y);return{min:new ds(u,f),max:new ds(w,C)}},o.aC=He,o.aD=k,o.aE=wt,o.aF=Ct,o.aG=Nf,o.aH=Ws,o.aI=Kr,o.aJ=function(v,u){const f={};for(let w=0;w=0?u.slice(f+1):""}catch{return""}},o.aN=class{constructor(v){this.entries={},this.scheduler=v}request(v,u,f,w){const C=this.entries[v]=this.entries[v]||{callbacks:[]};if(C.result){const[I,L]=C.result;return this.scheduler?this.scheduler.add(()=>{w(I,L)},u):w(I,L),()=>{}}return C.callbacks.push(w),C.cancel||(C.cancel=f((I,L)=>{C.result=[I,L];for(const B of C.callbacks)this.scheduler?this.scheduler.add(()=>{B(I,L)},u):B(I,L);setTimeout(()=>delete this.entries[v],3e3)})),()=>{C.result||(C.callbacks=C.callbacks.filter(I=>I!==w),C.callbacks.length||(C.cancel(),delete this.entries[v]))}}},o.aO=function(v,u,f){const w=JSON.stringify(v.request);return v.data&&(this.deduped.entries[w]={result:[null,v.data]}),this.deduped.request(w,{type:"parseTile",renderSourceType:v.renderSourceType,zoom:v.tileZoom},C=>{const I=U0(v.request,(L,B,U)=>{L?Xf(L)?C(null,null):C(L):B&&C(null,{rawData:B,vectorTile:f?void 0:new Ii(new M$(B)),responseHeaders:new Map(U.entries())})});return()=>{I.cancel(),C(null,null)}},u)},o.aP=function(v){return v?{cacheControl:v.get("cache-control"),expires:v.get("expires")}:{cacheControl:void 0,expires:void 0}},o.aQ=function(v){q1++,q1>z0&&(v.getActor().send("enforceCacheSizeLimit",B0),q1=0)},o.aR=Bm,o.aS=t8e,o.aT=c8e,o.aU=Zt,o.aV=e8e,o.aW=function(v,u){const f=document.createElement("video");f.muted=!0,f.onloadstart=function(){u(null,f)};for(let w=0;w{}}},o.aX=UD,o.aY=Z4,o.aZ=ls,o.a_=rU,o.aa=Zj,o.ab=Lo,o.ac=ur,o.ad=class{constructor(v){this.specification=v}possiblyEvaluate(v,u){return Sn(v.expression.evaluate(u))}interpolate(v,u,f){return{x:jn(v.x,u.x,f),y:jn(v.y,u.y,f),z:jn(v.z,u.z,f),azimuthal:jn(v.azimuthal,u.azimuthal,f),polar:jn(v.polar,u.polar,f)}}},o.ae=wa,o.af=qp,o.ag=en,o.ah=tt,o.ai=re,o.aj=ot,o.ak=Dd,o.al=Hw,o.am=jn,o.an=Sr,o.ao=pd,o.ap=Hr,o.aq=Mr,o.ar=class{constructor(v){this.specification=v}possiblyEvaluate(v,u){return function([f,w]){const C=Sn([1,f,w]);return{x:C.x,y:C.y,z:C.z}}(v.expression.evaluate(u))}interpolate(v,u,f){return{x:jn(v.x,u.x,f),y:jn(v.y,u.y,f),z:jn(v.z,u.z,f)}}},o.as=function(v,u,f=0,w=!0){const C=new ds(f,f),I=v.sub(C),L=u.add(C),B=[I,new ds(L.x,I.y),L,new ds(I.x,L.y)];return w&&B.push(I.clone()),B},o.at=function(v,u){const f=[];for(let w=0;wthis.buckets[oe].layers.some(de=>L.has(de.fqid))),U=Object.keys(this.buckets).some(oe=>this.buckets[oe].layers.some(de=>de.hasTransition&&de.hasTransition())),Y=this._firstPrepareComplete&&I!==this._lastAvailableImagesCount;this._hasAppearances===null&&(this._hasAppearances=this.hasAppearances(u));const se=this._lastUpdatedBrightness!==w;this._lastAvailableImagesCount=I,this._firstPrepareComplete=!0,(this._lastUpdatedBrightness||w||this._hasAppearances||B||U||Y)&&(!(this._hasAppearances||B||U||Y)&&this._lastUpdatedBrightness&&w&&Math.abs(this._lastUpdatedBrightness-w)<.001||(this.updateBuckets(u,se,void 0,Y||B||U,L,C),this._lastUpdatedBrightness=w))}evaluateQueryRenderedFeaturePadding(){let v=0;for(const u in this.buckets){const f=this.buckets[u];f.evaluateQueryRenderedFeaturePadding&&(v=Math.max(v,f.evaluateQueryRenderedFeaturePadding()))}return v}queryRenderedFeatures(v,u,f,w,C,I,L){if(!this.latestFeatureIndex||!this.latestFeatureIndex.rawTileData&&!this.latestFeatureIndex.is3DTile)return{};const B=this.evaluateQueryRenderedFeaturePadding(),U=function(Y,se){const oe=z([],[.5*Y.width,.5*-Y.height,1]);return T(oe,oe,[1,-1,0]),k(oe,oe,Y.calculateProjMatrix(se.toUnwrapped())),Float32Array.from(oe)}(C,this.tileID);return this.latestFeatureIndex.query(v,{tilespaceGeometry:u,pixelPosMatrix:U,transform:w,availableImages:f,tileTransform:this.tileTransform,worldview:this.worldview,queryRadius:B,scope:L})}querySourceFeatures(v,u){const f=this.latestFeatureIndex;if(!f||!f.rawTileData)return;const w=f.loadVTLayers(),C=u?u.sourceLayer:"",I=w._geojsonTileLayer||w[C];if(!I)return;const L=Jj(u&&u.filter),{z:B,x:U,y:Y}=this.tileID.canonical,se={z:B,x:U,y:Y};for(let oe=0;oef)w=!1;else if(u)if(this.expirationTimef.appearances&&f.appearances.length>0))return!0;return!1}updateBuckets(v,u,f,w,C,I){if(!this.latestFeatureIndex||!v.style)return;const L=I||v.style.listImages(),B=v.style.getBrightness(),U=C||new Set;for(const Y in this.buckets){if(!v.style.hasLayer(Y))continue;const se=this.buckets[Y],oe=se.layers[0],de=oe.sourceLayer||"_geojsonTileLayer",xe=v.style.getLayerSourceCache(oe),we=se.layers.some(xt=>U.has(xt.fqid)),Ce=(w||we)&&se instanceof Ov?v.style.getOwnLayer(Y):void 0;let Re=f&&f[de]||{};xe&&!f&&(Re=xe._state.getState(de,void 0));const qe=this.imageAtlas?Object.fromEntries(this.imageAtlas.patternPositions):{},nt=Object.keys(Re).length>0&&!u;se.hasAppearances=se.layers.some(xt=>xt.appearances&&xt.appearances.length>0);const Ze=nt?se.stateDependentLayers:se.layers;if(nt&&se.stateDependentLayers.length!==0||u||we||w){const xt=this.latestFeatureIndex.loadVTLayers()[de];if(se.update(Re,xt,L,qe,Ze,u,B,this.tileID.canonical),(w||we)&&!u&&se instanceof Ov&&Ce&&Ce.type==="symbol"){const bt=se;bt.text&&bt.text.uboBinder&&bt.text.uboBinder.updateDynamicExpressions(Ce,xt,this.tileID.canonical,L,Re,B),bt.icon&&bt.icon.uboBinder&&bt.icon.uboBinder.updateDynamicExpressions(Ce,xt,this.tileID.canonical,L,Re,B)}if(se instanceof Ov){const bt=se,Ht=v.context;bt.text&&bt.text.uboBinder&&bt.text.uboBinder.upload(Ht),bt.icon&&bt.icon.uboBinder&&bt.icon.uboBinder.upload(Ht)}}if(nt&&se.stateDependentLayers.length!==0||u||se.hasAppearances){const xt={zoom:v.transform.zoom,pitch:v.transform.pitch,brightness:v.style.getBrightness()||0,worldview:v.worldview},bt=se.updateAppearances(this.tileID.canonical,Re,L,xt,v.imageManager,nt&&se.stateDependentLayers.length!==0);if(bt&&bt.hasUboChanges){const Ht=v.context;se instanceof Ov&&se.text&&se.text.uboBinder&&se.text.uboBinder.upload(Ht),se instanceof Ov&&se.icon&&se.icon.uboBinder&&se.icon.uboBinder.upload(Ht)}}(se instanceof A$||se instanceof u$)&&v._terrain&&v._terrain.enabled&&xe&&se.uploadPending()&&v._terrain._clearRenderCacheForTile(xe.id,this.tileID);const ut=v&&v.style&&v.style.getOwnLayer(Y);ut&&(this.queryPadding=Math.max(this.queryPadding,ut.queryRadius(se)||0))}}holdingForFade(){return this.symbolFadeHoldUntil!==void 0}symbolFadeFinished(){return!this.symbolFadeHoldUntil||this.symbolFadeHoldUntil=0;Ce--){const Re=4*Ce,qe=hN[Re+0],nt=hN[Re+1],Ze=hN[Re+2],ut=hN[Re+3],xt=qe+Ze>>1,bt=nt+ut>>1,Ht=xt+bt-nt,Rt=bt+qe-xt,Vt=nt*Nb+qe,Bt=ut*Nb+Ze,$t=bt*Nb+xt,js=Math.hypot((kb[2*Vt+0]+kb[2*Bt+0])/2-kb[2*$t+0],(kb[2*Vt+1]+kb[2*Bt+1])/2-kb[2*$t+1])>=16;mN[$t]=mN[$t]||(js?1:0),Ce<1022&&(mN[$t]=mN[$t]||mN[(nt+Rt>>1)*Nb+(qe+Ht>>1)]||mN[(ut+Rt>>1)*Nb+(Ze+Ht>>1)])}const se=new Ya,oe=new Yl;let de=0;function xe(Ce,Re){const qe=Re*Nb+Ce;return X$[qe]===0&&(se.emplaceBack(kb[2*qe+0],kb[2*qe+1],Ce*Sr/oy,Re*Sr/oy),X$[qe]=++de),X$[qe]-1}function we(Ce,Re,qe,nt,Ze,ut){const xt=Ce+qe>>1,bt=Re+nt>>1;if(Math.abs(Ce-Ze)+Math.abs(Re-ut)>1&&mN[bt*Nb+xt])we(Ze,ut,Ce,Re,xt,bt),we(qe,nt,Ze,ut,xt,bt);else{const Ht=xe(Ce,Re),Rt=xe(qe,nt),Vt=xe(Ze,ut);oe.emplaceBack(Ht,Rt,Vt)}}return we(0,0,oy,oy,oy,0),we(oy,oy,0,0,0,oy),{vertices:se,indices:oe}}(this.tileID.canonical,u);w=I.vertices,C=I.indices}else{w=new Ya,C=new Yl;for(const{x:L,y:B}of f)w.emplaceBack(L,B,0,0);const I=IM(w.int16.subarray(0,4*w.length),void 0,4);for(let L=0;L0&&(L=j(new Float64Array(16),u.globeMatrix)),this._makeGlobeTileDebugBorderBuffer(v,w,u,C,L,I),this._makeGlobeTileDebugTextBuffer(v,w,u,C,L,I)}_globePoint(v,u,f,w,C,I,L){let B=kD(v,u,f);if(I){const U=1<.5?de=-1:oe<-.5&&(de=1);let xe=(v/Sr+f.x)/U+de,we=(u/Sr+f.y)/U;xe=(xe-Y)*w._pixelsPerMercatorPixel+Y,we=(we-se)*w._pixelsPerMercatorPixel+se;const Ce=[xe*w.worldSize,we*w.worldSize,0];tt(Ce,Ce,I),B=Vw(B,Ce,L)}return tt(B,B,C)}_makeGlobeTileDebugBorderBuffer(v,u,f,w,C,I){const L=new Da,B=new $w,U=new Ei,Y=(oe,de,xe,we,Ce)=>{const Re=(xe-oe)/(Ce-1),qe=(we-de)/(Ce-1),nt=L.length;for(let Ze=0;ZeY*oe+de;for(let oe=0;oe1)return!1;const f=u.getSource().maxzoom,w=1<1)return u;const C=w.getSource().maxzoom,I=1<{const B=this.getAtTileOffset(v,C,I,L),U=w.upVector(v.canonical,C.x,C.y);return ve(U,U,B*w.upVectorScale(v.canonical,u,f).metersToTile),U}}getForTilePoints(v,u,f,w){if(this.isUsingMockSource())return!1;const C=HM.create(this,v,w);return!!C&&(u.forEach(I=>{I[2]=this.exaggeration()*C.getElevationAt(I[0],I[1],f)}),!0)}getMinMaxForTile(v){if(this.isUsingMockSource())return null;const u=this.findDEMTileFor(v);if(!u||!u.dem)return null;const f=u.dem.tree,w=u.tileID,C=1<0&&(w+=(v[C]-0)*(v[C]-0)),u[C]<0&&(w+=(0-u[C])*(0-u[C]));return w},o.cL=function(v){return v*v*v*v*v},o.cM=ms,o.cN=45,o.cO=EM,o.cP=function(v,u,f){const w=Math.sqrt(v*v+u*u+f*f),C=w>0?Math.acos(f/w)*_r:0;let I=v!==0||u!==0?Math.atan2(-u,-v)*_r+90:0;return I<0&&(I+=360),[w,I,C]},o.cQ=ie,o.cR=Sn,o.cS=Js,o.cT=ne,o.cU=Vi,o.cV=le,o.cW=function(v){return[Math.pow(v[0],1/2.2),Math.pow(v[1],1/2.2),Math.pow(v[2],1/2.2)]},o.cX=MPe,o.cY=ove,o.cZ=RPe,o.c_=Bve,o.ca=2,o.cb=7,o.cc=6,o.cd=pe,o.ce=J,o.cf=K,o.cg=0,o.ch=1,o.ci=4,o.cj=5,o.ck=MM,o.cl=lp,o.cm=PPe,o.cn=z4,o.co=lIe,o.cp=function(v,u,f,w,C,I,L,B,U){if(U.name==="globe")return lIe(v,u,new z4(f,w,C),!1);const Y=W4({z:f,x:w,y:C},U);return new Vi([(I+Y.x/Y.scale)*u,u*(Y.y/Y.scale),L],[(I+Y.x2/Y.scale)*u,u*(Y.y2/Y.scale),B])},o.cq=function(v,u,f){return v[0]=Math.min(u[0],f[0]),v[1]=Math.min(u[1],f[1]),v[2]=Math.min(u[2],f[2]),v[3]=Math.min(u[3],f[3]),v},o.cr=function(v,u,f){return v[0]=Math.max(u[0],f[0]),v[1]=Math.max(u[1],f[1]),v[2]=Math.max(u[2],f[2]),v[3]=Math.max(u[3],f[3]),v},o.cs=function(v){const u=Math.round((v+45+360)%360/90)%4;return Jt[u]},o.ct=Ls,o.cu=Je,o.cv=6,o.cw=function(v){const u=b(new Float64Array(16));k(u,v.pixelMatrix,v.globeMatrix);const f=[0,Lt,0],w=[0,Wt,0];return tt(f,f,u),tt(w,w,u),[f[0]>0&&f[0]<=v.width&&f[1]>0&&f[1]<=v.height&&!Tye(v,new Zt(v.center.lat,90)),w[0]>0&&w[0]<=v.width&&w[1]>0&&w[1]<=v.height&&!Tye(v,new Zt(v.center.lat,-90))]},o.cx=function(v,u){const{scale:f}=v.tileTransform,w=f*Sr/(v.tileSize*Math.pow(2,u.zoom-v.tileID.overscaledZ+v.tileID.canonical.z));return function(C,I,L){var B=I[1],U=I[2],Y=I[3],se=L[0],oe=L[1];return C[0]=I[0]*se,C[1]=B*se,C[2]=U*oe,C[3]=Y*oe,C}(new Float32Array(4),u.inverseAdjustmentMatrix,[w,w])},o.cy=N$,o.cz=Z,o.d=function(v){return ia.API_TILEJSON_REGEX.test(v)},o.d$=Sbt,o.d0=Ml,o.d1=class{static calculate(v,u,f){const w=new Set,C=new Map,I=new Set,L=new Set;for(const U of Object.values(v))for(const[Y,se]of Object.entries(U.floors)){I.add(Y),se.isDefault&&L.add(Y),se.conflicts&&C.set(Y,se.conflicts);const oe=Y===u,de=se.connections&&u&&se.connections.has(u);(oe||de)&&w.add(Y)}const B=U=>{const Y=C.get(U)||new Set;for(const se of w)if((C.get(se)||new Set).has(U)||Y.has(se))return!0;return!1};if(f)for(const U of f)I.has(U)&&(B(U)||w.add(U));for(const U of L)w.has(U)||B(U)||w.add(U);return w}},o.d2=D$,o.d3=Sve,o.d4=Ua,o.d5=function(){return{API_URL:ia.API_URL,DRACO_URL:ia.DRACO_URL,MESHOPT_URL:ia.MESHOPT_URL,MESHOPT_SIMD_URL:ia.MESHOPT_SIMD_URL,BUILDING_GEN_URL:ia.BUILDING_GEN_URL}},o.d6=yM,o.d7=rw,o.d8=fd,o.d9=Er,o.dA=s$,o.dB=Da,o.dC=Yl,o.dD=function(v,u){return[Math.pow(v[0],2.2)*u,Math.pow(v[1],2.2)*u,Math.pow(v[2],2.2)*u]},o.dE=m,o.dF=function(v,u){var f=Math.sin(u),w=Math.cos(u);return v[0]=w,v[1]=f,v[2]=0,v[3]=-f,v[4]=w,v[5]=0,v[6]=0,v[7]=0,v[8]=1,v},o.dG=ge,o.dH=dIe,o.dI=ii,o.dJ=Ji,o.dK=Ove,o.dL=function(v,u){const f=[0,0,0];return tt(f,f,SD(bb(u.canonical))),tt(f,f,v),f},o.dM=v=>({u_matrix:new g(v),u_texsize:new $g(v),u_pixels_to_tile_units:new F(v),u_device_pixel_ratio:new Yc(v),u_width_scale:new Yc(v),u_floor_width_scale:new Yc(v),u_image:new F4(v),u_units_to_pixels:new $g(v),u_tile_units_to_pixels:new Yc(v),u_alpha_discard_threshold:new Yc(v),u_trim_offset:new $g(v),u_trim_fade_range:new $g(v),u_trim_gradient_mix_range:new $g(v),u_trim_color:new EM(v),u_zbias_factor:new Yc(v),u_tile_to_meter:new Yc(v),u_ground_shadow_factor:new B4(v),u_pattern_transition:new Yc(v)}),o.dN=v=>({u_matrix:new g(v),u_pixels_to_tile_units:new F(v),u_device_pixel_ratio:new Yc(v),u_width_scale:new Yc(v),u_floor_width_scale:new Yc(v),u_units_to_pixels:new $g(v),u_dash_image:new F4(v),u_gradient_image:new F4(v),u_image_height:new Yc(v),u_texsize:new $g(v),u_tile_units_to_pixels:new Yc(v),u_alpha_discard_threshold:new Yc(v),u_trim_offset:new $g(v),u_trim_fade_range:new $g(v),u_trim_gradient_mix_range:new $g(v),u_trim_color:new EM(v),u_zbias_factor:new Yc(v),u_tile_to_meter:new Yc(v),u_ground_shadow_factor:new B4(v)}),o.dO=v=>({u_camera_to_center_distance:new Yc(v),u_extrude_scale:new F(v),u_device_pixel_ratio:new Yc(v),u_matrix:new g(v),u_inv_rot_matrix:new g(v),u_merc_center:new $g(v),u_tile_id:new B4(v),u_zoom_transition:new Yc(v),u_up_dir:new B4(v),u_emissive_strength:new Yc(v)}),o.dP=mD,o.dQ=kwt,o.dR=class{constructor(v,u,f,w){this.context=v,this.format=w,this.size=f,this.texture=v.gl.createTexture();const[C,I,L]=this.size,{gl:B}=v;B.bindTexture(B.TEXTURE_3D,this.texture),v.pixelStoreUnpackFlipY.set(!1),v.pixelStoreUnpack.set(1),v.pixelStoreUnpackPremultiplyAlpha.set(!1),"data"in u&&u.data&&B.texImage3D(B.TEXTURE_3D,0,this.format,C,I,L,0,eve(this.format),tve(this.format),u.data)}bind(v,u){const{context:f}=this,{gl:w}=f;w.bindTexture(w.TEXTURE_3D,this.texture),v!==this.minFilter&&(w.texParameteri(w.TEXTURE_3D,w.TEXTURE_MAG_FILTER,v),w.texParameteri(w.TEXTURE_3D,w.TEXTURE_MIN_FILTER,v),this.minFilter=v),u!==this.wrapS&&(w.texParameteri(w.TEXTURE_3D,w.TEXTURE_WRAP_S,u),w.texParameteri(w.TEXTURE_3D,w.TEXTURE_WRAP_T,u),this.wrapS=u)}destroy(){const{gl:v}=this.context;v.deleteTexture(this.texture),this.texture=null}},o.dS=fIe,o.dT=(v,u,f,w,C,I)=>{const L=v.transform,B=L.projection.name==="globe";let U;if(I.paint.get("circle-pitch-alignment")==="map")if(B){const se=dIe(L.zoom,u.canonical)*L._pixelsPerMercatorPixel;U=Float32Array.from([se,0,0,se])}else U=L.calculatePixelsToTileUnitsMatrix(f);else U=new Float32Array([L.pixelsToGLUnits[0],0,0,L.pixelsToGLUnits[1]]);const Y={u_camera_to_center_distance:v.transform.getCameraToCenterDistance(L.projection),u_matrix:v.translatePosMatrix(u.projMatrix,f,I.paint.get("circle-translate"),I.paint.get("circle-translate-anchor")),u_device_pixel_ratio:Ad.devicePixelRatio,u_extrude_scale:U,u_inv_rot_matrix:Ibt,u_merc_center:[0,0],u_tile_id:[0,0,0],u_zoom_transition:0,u_up_dir:[0,0,0],u_emissive_strength:I.paint.get("circle-emissive-strength")};if(B){Y.u_inv_rot_matrix=w,Y.u_merc_center=C,Y.u_tile_id=[u.canonical.x,u.canonical.y,1<{const se=v.transform,oe=se.pitch<15?YPe(.07,.7,He((14-se.zoom)/5,0,1)):.07,de=f.paint.get("line-trim-color-use-theme").constantOr("default")==="none";return{u_matrix:XPe(v,u,f,w),u_texsize:u.imageAtlasTexture?u.imageAtlasTexture.size:[0,0],u_pixels_to_tile_units:se.calculatePixelsToTileUnitsMatrix(u),u_device_pixel_ratio:C,u_width_scale:I,u_floor_width_scale:L,u_image:0,u_tile_units_to_pixels:ZPe(u,se),u_units_to_pixels:[1/se.pixelsToGLUnits[0],1/se.pixelsToGLUnits[1]],u_alpha_discard_threshold:0,u_trim_offset:B,u_trim_fade_range:f.paint.get("line-trim-fade-range"),u_trim_gradient_mix_range:[1,1],u_trim_color:f.paint.get("line-trim-color").toPremultipliedRenderColor(de?null:f.lut).toArray01(),u_zbias_factor:oe,u_tile_to_meter:Js(u.tileID.canonical,0),u_ground_shadow_factor:U,u_pattern_transition:Y}},o.dX=(v,u,f,w,C,I,L,B,U,Y)=>{const se=v.transform,oe=se.calculatePixelsToTileUnitsMatrix(u),de=f.paint.get("line-trim-color-use-theme").constantOr("default")==="none",xe=se.pitch<15?YPe(.07,.7,He((14-se.zoom)/5,0,1)):.07;return{u_matrix:XPe(v,u,f,w),u_pixels_to_tile_units:oe,u_device_pixel_ratio:I,u_width_scale:L,u_floor_width_scale:B,u_units_to_pixels:[1/se.pixelsToGLUnits[0],1/se.pixelsToGLUnits[1]],u_dash_image:0,u_gradient_image:1,u_image_height:C,u_texsize:JPe(f)&&u.lineAtlasTexture?u.lineAtlasTexture.size:[0,0],u_tile_units_to_pixels:ZPe(u,v.transform),u_alpha_discard_threshold:0,u_trim_offset:U,u_trim_fade_range:f.paint.get("line-trim-fade-range"),u_trim_gradient_mix_range:[1,1],u_trim_color:f.paint.get("line-trim-color").toPremultipliedRenderColor(de?null:f.lut).toArray01(),u_zbias_factor:xe,u_tile_to_meter:Js(u.tileID.canonical,0),u_ground_shadow_factor:Y}},o.dY=Yt,o.dZ=CD,o.d_=Ts,o.da=function(v){const u=v.indexOf(Ke);return u>=0?v.slice(0,u):v},o.db=function(v){return v.indexOf(Ke)>=0},o.dc=function(v){const u=v.lastIndexOf(Ke);return u>=0?v.slice(u+1):""},o.dd=function(v){const u=[],f=v.id;return f===void 0&&u.push({message:`layers.${f}: missing required property "id"`}),v.render===void 0&&u.push({message:`layers.${f}: missing required method "render"`}),v.renderingMode&&v.renderingMode!=="2d"&&v.renderingMode!=="3d"&&u.push({message:`layers.${f}: property "renderingMode" must be either "2d" or "3d"`}),u},o.de=function(v,u,f,w){return v.type==="custom"?new y2t(v,u):new j2t[v.type](v,u,f,w)},o.df=Rs,o.dg=Jj,o.dh=Qt,o.di=class extends Y4{constructor(v,u){super(v._vectorTileFeature,v._z,v._x,v._y,v.id),v.state&&(this.state=Object.assign({},v.state)),this.target=u.target,this.namespace=u.namespace,u.properties&&(this.properties=u.properties),this.target&&("featuresetId"in this.target&&!this.target.importId||"layerId"in this.target)&&(this.source=v.source,this.sourceLayer=v.sourceLayer,this.layer=v.layer)}toJSON(){const v=super.toJSON();return v.target=this.target,v.namespace=this.namespace,v}},o.dj=Yj,o.dk=function(v){return v({pluginStatus:Ld,pluginURL:_f}),Yj.on("pluginStateChange",v),v},o.dl=jye,o.dm=class extends zg{constructor(v){super(v),this.current=N}set(v,u,f){if(this.fetchUniformLocation(v,u)){for(let w=0;w<9;w++)if(f[w]!==this.current[w]){this.current=f,this.gl.uniformMatrix3fv(this.location,!1,f);break}}}},o.dn=Cr,o.dp=function(v,u,f){const w=Hw(f.zoom),C=v.style.map._antialias,I=v.terrain&&v.terrain.exaggeration()>0;return w===0&&!C&&!I},o.dq=function(v){const u=v.pixelsPerMeter,f=u/as(1,v.center.lat),w=b(new Float64Array(16));return T(w,w,[v.point.x,v.point.y,0]),E(w,w,[f,f,u]),Float32Array.from(w)},o.dr=r$,o.ds=function(v){const u=80.051129;v=He(v,-80.051129,u)/u*90;const f=Math.pow(Math.abs(Math.sin(Hr(v))),3);return Math.round(f*(Kt.length-1))},o.dt=function(v,u,f,w){const C=u.getNorth(),I=u.getSouth(),L=u.getWest(),B=u.getEast(),U=1<0){const we=180/w;x(xe,xe,[we/Y+1,0,0,0,we/se+1,0,-.5*we/oe,.5*we/de,1])}return xe[2]=U,xe[5]=v.x,xe[8]=v.y,xe},o.du=SD,o.dv=bb,o.dw=function(v,u,f){const w=b(new Float64Array(16)),C=(u/(1<0&&++this._updateTime,this._activeRegions=[],this._prevRegions=[]}get updateTime(){return this._updateTime}getReplacementRegionsForTile(v,u=!1){const f=KIe(new ds(0,0),new ds(Sr,Sr),v),w=[];if(u&&!qye(f,this._globalClipBounds))return w;for(const C of this._activeRegions){if(C.hiddenByOverlap||!qye(f,C))continue;const I=f_t(C.min,C.max,v);w.push({min:I.min,max:I.max,sourceId:this._sourceIds[C.priority],footprint:C.footprint,footprintTileId:C.tileId,order:C.order,clipMask:C.clipMask,clipScope:C.clipScope})}return w}setSources(v){this._setSources(v.map(u=>({getSourceId:()=>u.cache.id,getFootprints:()=>{const f=[];for(const w of u.cache.getVisibleCoordinates()){const C=u.cache.getTile(w).buckets[u.layer];C&&C.updateFootprints(w.toUnwrapped(),f)}return f},getOrder:()=>u.order,getClipMask:()=>u.clipMask,getClipScope:()=>u.clipScope})))}_addSource(v){const u=v.getFootprints();if(u.length===0)return;const f=v.getOrder(),w=v.getClipMask(),C=v.getClipScope();for(const I of u){if(!I.footprint)continue;const L=KIe(I.footprint.min,I.footprint.max,I.id);this._activeRegions.push({min:L.min,max:L.max,hiddenByOverlap:!1,priority:this._sourceIds.length,tileId:I.id,footprint:I.footprint,order:f,clipMask:w,clipScope:C})}this._sourceIds.push(v.getSourceId())}_computeReplacement(){this._activeRegions.sort((u,f)=>u.priority-f.priority||m$(u.min,f.min)||m$(u.max,f.max)||u.order-f.order||u.clipMask-f.clipMask||function(w,C){const I=(L,B)=>L+B;return w.length-C.length||w.reduce(I,"").localeCompare(C.reduce(I,""))}(u.clipScope,f.clipScope));let v=this._activeRegions.length!==this._prevRegions.length;if(!v){let u=0;for(;!v&&u!==this._activeRegions.length;){const f=this._activeRegions[u],w=this._prevRegions[u];v=f.priority!==w.priority||!WIe(f,w)||f.order!==w.order||f.clipMask!==w.clipMask||!Na(f.clipScope,w.clipScope),this._activeRegions[u].hiddenByOverlap=w.hiddenByOverlap,++u}}if(v){++this._updateTime;for(const f of this._activeRegions)f.order!==DD&&(this._globalClipBounds.min.x=Math.min(this._globalClipBounds.min.x,f.min.x),this._globalClipBounds.min.y=Math.min(this._globalClipBounds.min.y,f.min.y),this._globalClipBounds.max.x=Math.max(this._globalClipBounds.max.x,f.max.x),this._globalClipBounds.max.y=Math.max(this._globalClipBounds.max.y,f.max.y));const u=f=>{const w=this._activeRegions;if(f>=w.length)return f;const C=w[f].priority;for(;f1){let f=0,w=u(f);for(;f!==w;){let C=f;const I=f;for(;C!==w;){const L=this._activeRegions[C];L.hiddenByOverlap=!1;for(let B=0;B=0;u--)this._addSource(v[u]);this._computeReplacement()}},o.eH=Ya,o.eI=G$,o.eJ=$w,o.eK=DD,o.eL=class{constructor(v){this._createGrid(v),this._createPoles(v)}destroy(){this._poleIndexBuffer.destroy(),this._gridBuffer.destroy(),this._gridIndexBuffer.destroy(),this._poleNorthVertexBuffer.destroy(),this._poleSouthVertexBuffer.destroy();for(const v of this._poleSegments)v.destroy();for(const v of this._gridSegments)v.withSkirts.destroy(),v.withoutSkirts.destroy()}_fillGridMeshWithLods(v,u){const f=new Da,w=new Yl,C=[],I=v+1+2,L=u[0]+1,B=u[0]+1+(1+u.length),U=(Y,se,oe)=>{let de=Y===I-1?Y-2:Y===0?Y:Y-1;return de+=oe?24575:0,[de,se]};for(let Y=0;Y>>=0,v=Math.imul(2747636419^v,2654435769)>>>0,v=Math.imul(v^v>>>16,2654435769)>>>0,(v=Math.imul(v^v>>>16,2654435769)>>>0)/4294967296},o.ec=iIe,o.ed=Sye,o.ee=Fg,o.ef=D,o.eg=function(v,u){return v[0]=u[0],v[1]=u[1],v[2]=u[2],v[3]=u[4],v[4]=u[5],v[5]=u[6],v[6]=u[8],v[7]=u[9],v[8]=u[10],v},o.eh=Bw,o.ei=P4,o.ej=function(v,u,f,w,C){return He((v-u)/(f-u)*(C-w)+w,w,C)},o.ek=hs,o.el=function(v,u){var f=u[0],w=u[1],C=u[2],I=u[3],L=u[4],B=u[5],U=u[6],Y=u[7],se=u[8],oe=se*L-B*Y,de=-se*I+B*U,xe=Y*I-L*U,we=f*oe+w*de+C*xe;return we?(v[0]=oe*(we=1/we),v[1]=(-se*w+C*Y)*we,v[2]=(B*w-C*L)*we,v[3]=de*we,v[4]=(se*f-C*U)*we,v[5]=(-B*f+C*I)*we,v[6]=xe*we,v[7]=(-Y*f+w*U)*we,v[8]=(L*f-w*I)*we,v):null},o.em=y4,o.en=2,o.eo=ze,o.ep=at,o.eq=$,o.er=function(v,u){var f=new d(3);$(f,u);var w=1/f[0],C=1/f[1],I=1/f[2],L=u[0]*w,B=u[1]*C,U=u[2]*I,Y=u[4]*w,se=u[5]*C,oe=u[6]*I,de=u[8]*w,xe=u[9]*C,we=u[10]*I,Ce=L+se+we,Re=0;return Ce>0?(Re=2*Math.sqrt(Ce+1),v[3]=.25*Re,v[0]=(oe-xe)/Re,v[1]=(de-U)/Re,v[2]=(B-Y)/Re):L>se&&L>we?(Re=2*Math.sqrt(1+L-se-we),v[3]=(oe-xe)/Re,v[0]=.25*Re,v[1]=(B+Y)/Re,v[2]=(de+U)/Re):se>we?(Re=2*Math.sqrt(1+se-L-we),v[3]=(de-U)/Re,v[0]=(B+Y)/Re,v[1]=.25*Re,v[2]=(oe+xe)/Re):(Re=2*Math.sqrt(1+we-L-se),v[3]=(B-Y)/Re,v[0]=(de+U)/Re,v[1]=(oe+xe)/Re,v[2]=.25*Re),v},o.es=function(v,u){var f=2*Math.acos(u[3]),w=Math.sin(f/2);return w>c?(v[0]=u[0]/w,v[1]=u[1]/w,v[2]=u[2]/w):(v[0]=1,v[1]=0,v[2]=0),f},o.et=Uve,o.eu=C$,o.ev=S$,o.ew=[1,1,1],o.ex=HM,o.ey=function(v,u,f,w){var C=u[0],I=u[1],L=u[2],B=u[3];return v[0]=C+w*(f[0]-C),v[1]=I+w*(f[1]-I),v[2]=L+w*(f[2]-L),v[3]=B+w*(f[3]-B),v},o.ez=OM,o.f=$o,o.f0=hIe,o.f1=function(v){const u=[0,0,0],f=b(new Float64Array(16));return k(f,v.pixelMatrix,v.globeMatrix),tt(u,u,f),new ds(u[0],u[1])},o.f2=Px,o.f3=function(v,u,f=!1){if(Ld===Zh.deferred||Ld===Zh.loading||Ld===Zh.loaded)throw new Error("setRTLTextPlugin cannot be called multiple times.");_f=Ad.resolveURL(v),Ld=Zh.deferred,op=u,Kj(),f||vM()},o.f4=Yi,o.f5=Sa,o.f6=hr,o.f7=function(v){const u=Pp();if(!u)return;const f=u.delete(Uh);v&&f.then(()=>v()).catch(v)},o.f8=Pr,o.f9=iN,o.fA=na,o.fB=function(v){let u=0;if(new Uint32Array(v,0,1)[0]!==SPe){const f=new Uint32Array(v,0,7),[,,w,C,I,L]=f;u=f.byteLength+C+I+L+I,(w!==v.byteLength||u>=v.byteLength)&&Gr("Invalid b3dm header information.")}return APe(v,u)},o.fC=function(v,u){const f=ove(v);for(const w of f){for(const C of w.meshes)H_t(C);w.lights&&(w.lightMeshIndex=w.meshes.length,w.meshes.push(G_t(w.lights,u)))}return f},o.fD=Z$,o.fE=Aa,o.fF=Xh,o.fG=Zh,o.fH=function(v){oo(),Ju!=null&&Ju.then(u=>{u.keys().then(f=>{for(let w=0;wGr(C.message))}).catch(f=>Gr(f.message))}).catch(u=>Gr(u.message))},o.fa=2,o.fb=Ig,o.fc=W4,o.fd=vD,o.fe=g8e,o.ff=x8e,o.fg=HPe,o.fh=Ta,o.fi="hd_road_elevation",o.fj=Eo,o.fk=Xs,o.fl=u$,o.fm=Gw,o.fn=Nve,o.fo=1,o.fp=Ov,o.fq=function(v,u,f,w,C,I,L,B=1,U,Y,se,oe){v.createArrays(),v.tilePixelRatio=Sr/(512*v.overscaling),v.compareText={},v.iconsNeedLinear=!1;const de=v.layers[0].layout,xe=v.layers[0]._unevaluatedLayout._values,we={};we.scaleFactor=B,we.textSizeScaleRange=de.get("text-size-scale-range"),we.iconSizeScaleRange=de.get("icon-size-scale-range");const[Ce,Re]=we.textSizeScaleRange,[qe,nt]=we.iconSizeScaleRange;we.textScaleFactor=He(we.scaleFactor,Ce,Re),we.iconScaleFactor=He(we.scaleFactor,qe,nt);const Ze=xe["text-size"],ut=xe["icon-size"];if(v.textSizeData.kind==="composite"){const{minZoom:Bt,maxZoom:$t}=v.textSizeData;we.compositeTextSizes=[Ze.possiblyEvaluate(new wa(Bt,{worldview:se}),I),Ze.possiblyEvaluate(new wa($t,{worldview:se}),I)]}if(v.iconSizeData.kind==="composite"){const{minZoom:Bt,maxZoom:$t}=v.iconSizeData;we.compositeIconSizes=[ut.possiblyEvaluate(new wa(Bt,{worldview:se}),I,oe),ut.possiblyEvaluate(new wa($t,{worldview:se}),I,oe)]}we.layoutTextSize=Ze.possiblyEvaluate(new wa(L+1,{worldview:se}),I),we.layoutIconSize=ut.possiblyEvaluate(new wa(L+1,{worldview:se}),I,oe),we.textMaxSize=Ze.possiblyEvaluate(new wa(18,{worldview:se}),I);const xt=de.get("symbol-placement"),bt=de.get("text-rotation-alignment")==="map"&&xt!=="point",Ht=de.get("text-size");let Rt=!1;const Vt=[];for(const Bt of v.features){const $t=de.get("text-font").evaluate(Bt,{},I).join(","),js=Ht.evaluate(Bt,{},I)*we.textScaleFactor,Es=we.layoutTextSize.evaluate(Bt,{},I)*we.textScaleFactor,zs=we.layoutIconSize.evaluate(Bt,{},I,oe)*we.iconScaleFactor,Hs={horizontal:{},vertical:void 0},$s=Bt.text;let nr,ys=[0,0];if($s){const Fa=$s.toString(),Il=de.get("text-letter-spacing").evaluate(Bt,{},I)*Od,$i=de.get("text-line-height").evaluate(Bt,{},I)*Od,ki=gM(Fa)?Il:0,Co=de.get("text-anchor").evaluate(Bt,{},I),vl=de.get("text-variable-anchor");if(!vl){const Xl=de.get("text-radial-offset").evaluate(Bt,{},I);if(Xl)ys=ALe(Co,[Xl*Od,Tve]);else{const nh=de.get("text-offset").evaluate(Bt,{},I);ys=[nh[0]*Od,nh[1]*Od]}}let Fd=bt?"center":de.get("text-justify").evaluate(Bt,{},I);const bl=xt==="point",Zl=bl?de.get("text-max-width").evaluate(Bt,{},I)*Od:1/0,Nc=Xl=>{v.allowVerticalPlacement&&Sh(Fa)&&(Hs.vertical=xve($s,u,f,C,$t,Zl,$i,Co,Xl,ki,ys,Xp.vertical,!0,Es,js,U,we.textScaleFactor))};if(!bt&&vl){const Xl=Fd==="auto"?vl.map(Bd=>Eve(Bd)):[Fd];let nh=!1;for(let Bd=0;Bd=0||!Sh(Fa)){const Xl=xve($s,u,f,C,$t,Zl,$i,Co,Fd,ki,ys,Xp.horizontal,!1,Es,js,U,we.textScaleFactor);Xl&&(Hs.horizontal[Fd]=Xl)}Nc(bl?"left":Fd)}}let qs,Zs,ir,pr,Zr,Nr,jr=!1;const gr=de.get("icon-text-fit").evaluate(Bt,{},I);if(Bt.icon&&Bt.icon.hasPrimary()){const Fa=ZD(Bt.icon,v.iconSizeData,xe["icon-size"],I,v.zoom,Bt,U,we.iconScaleFactor,se,oe);qs=Fa.iconPrimary,ir=Fa.iconSecondary;const Il=qs.toString();if(Zs=w.get(Il),Zs&&(Zr=de.get("icon-offset").evaluate(Bt,{},I),Nr=de.get("icon-anchor").evaluate(Bt,{},I),nr=P$(C.get(Il),ir?C.get(ir.toString()):void 0,Zr,Nr),jr=Zs.sdf,v.sdfIcons===void 0?v.sdfIcons=Zs.sdf:v.sdfIcons!==Zs.sdf&&Gr("Style sheet warning: Cannot mix SDF and non-SDF icons in one buffer"),(Zs.pixelRatio!==v.pixelRatio||de.get("icon-rotate").constantOr(1)!==0)&&(v.iconsNeedLinear=!0)),ir){const $i=ir.toString();pr=w.get($i)}}Rt=Rt||!(!Bt.icon||!Bt.icon.hasSecondary());const qr=z$(Hs.horizontal)||Hs.vertical;v.iconsInText||(v.iconsInText=!!qr&&qr.iconsInText);const tn=Es*we.textScaleFactor/Od,{defaultShapedIcon:In,verticallyShapedIcon:cn}=s2t(v,nr,de,Bt,I,Hs,tn,Zr,gr);gr!=="none"&&nr&&(hLe(nr)||mLe(nr))&&(B$(0,Zs,qs,nr,In,gr,Y,w,C),B$(0,pr,ir,nr,In,gr,Y,w,C),cn&&(B$(0,Zs,qs,nr,cn,gr,Y,w,C),B$(0,pr,ir,nr,cn,gr,Y,w,C))),nr=In;const{iconBBox:fa,iconVerticalBBox:xi,textBBox:pa,textVerticalBBox:vi}=Xwt(v,nr,cn,de,Bt,I,zs,Zr,we,C,Nr,Hs,Es,ys,oe);Vt.push({feature:Bt,shapedTextOrientations:Hs,shapedText:qr,shapedIcon:nr,iconPrimary:qs,iconSecondary:ir,iconOffset:Zr,iconAnchor:Nr,verticallyShapedIcon:cn,layoutTextSize:Es,layoutIconSize:zs,textOffset:ys,isSDFIcon:jr,iconTextFit:gr,iconCollisionBounds:fa,iconVerticalCollisionBounds:xi,textCollisionBounds:pa,textVerticalCollisionBounds:vi})}return{featureData:Vt,sizes:we,hasAnySecondaryIcon:Rt,textAlongLine:bt,symbolPlacement:xt}},o.fr=kve,o.fs=jve,o.ft=wLe,o.fu=jLe,o.fv=function(v,u,f,w,C,I,L,B,U,Y){v.iconAtlasPositions=Y.iconPositions;const{featureData:se,hasAnySecondaryIcon:oe,sizes:de,textAlongLine:xe,symbolPlacement:we}=u;for(const Ce of se){const{shapedIcon:Re,verticallyShapedIcon:qe,feature:nt,shapedTextOrientations:Ze,shapedText:ut,layoutTextSize:xt,textOffset:bt,isSDFIcon:Ht,iconPrimary:Rt,iconSecondary:Vt,iconTextFit:Bt,iconOffset:$t,iconCollisionBounds:js,iconVerticalCollisionBounds:Es,textCollisionBounds:zs}=Ce;LLe(Re,Y.iconPositions,Rt,Vt),LLe(qe,Y.iconPositions,Rt,Vt),t2t(Ze,Y.iconPositions),e2t(Rt,Vt,Y.iconPositions),(ut||Re)&&r2t(v,nt,Ze,Re,qe,U,de,xt,0,bt,Ht,w,C,L,B,oe,Bt,$t,xe,we,js,Es,zs)}f&&v.generateCollisionDebugBuffers(I,v.collisionBoxArray,de.textScaleFactor)},o.fw=A$,o.fx=Ii,o.fy=function(v){return v<=1?1:Math.pow(2,Math.floor(Math.log2(v)))},o.fz=sU,o.g=ia,o.h=function(v,u){return $0(Object.assign(v,{method:"GET"}),u)},o.i=function(v){return ia.API_STYLE_REGEX.test(v)&&!cl(v)},o.j=function(v){return btoa(encodeURIComponent(v).replace(/%([0-9A-F]{2})/g,(u,f)=>String.fromCharCode(+("0x"+f))))},o.k=qh,o.l=function(v){return decodeURIComponent(atob(v).split("").map(u=>"%"+("00"+u.charCodeAt(0).toString(16)).slice(-2)).join(""))},o.m=function(v,u){return $0(Object.assign(v,{type:"json"}),u)},o.n=Dp,o.o=Ad,o.p=function(v,u){return $0(Object.assign(v,{method:"POST"}),u)},o.q=Th,o.r=ss,o.s=function(v){try{const u=self[v];return u.setItem("_mapbox_test_",1),u.removeItem("_mapbox_test_"),!0}catch{return!1}},o.t=Dt,o.u=function(){return function v(u){return u?(u^Math.random()*(16>>u/4)).toString(16):([1e7]+-[1e3]+-4e3+-8e3+-1e11).replace(/[018]/g,v)}()},o.v=function(v){return!!v&&/^[0-9a-f]{8}-[0-9a-f]{4}-[4][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(v)},o.w=Gr,o.x=class{constructor(v){this.cache=new Map,this.textures=new Map,this.textureAccessTimes=new Map,this.textureMemoryUsed=0,this.maxTextureMemory=1024*(v&&v.maxTextureMemoryMB?v.maxTextureMemoryMB:256)*1024,this.finalizationRegistry=new FinalizationRegistry(u=>{this.cache.delete(u),this.clearExpiredTextures()})}calculateTextureMemory(v){return v.image?Math.ceil(v.image.width*v.image.height*4*(v.patternPositions.size>0?1.33:1)):0}evictTexture(v){const u=this.textures.get(v);if(u){const f=this.calculateTextureMemory(v);u.destroy(),this.textures.delete(v),this.textureAccessTimes.delete(v),this.textureMemoryUsed-=f}}evictTexturesIfNeeded(v){for(;this.textureMemoryUsed+v>this.maxTextureMemory&&this.textures.size>0;){let u=null,f=1/0;for(const[w]of this.textures.entries()){const C=this.textureAccessTimes.get(w)||0;Cthis._layers[Er.id]),ss=qt[0];if(ss.visibility==="none")continue;const Yt=ss.source||"";let ls=this.familiesBySource[Yt];ls||(ls=this.familiesBySource[Yt]=Object.create(null));const Xs=ss.sourceLayer||"_geojsonTileLayer";let Rs=ls[Xs];Rs||(Rs=ls[Xs]=[]),Rs.push(qt)}}}const y=1*c.fa;class _{constructor(Ee){const He={},ot=[];for(const ss in Ee){const Yt=Ee[ss],ls=He[ss]={};for(const Xs in Yt.glyphs){const Rs=Yt.glyphs[+Xs];if(!Rs||Rs.bitmap.width===0||Rs.bitmap.height===0)continue;const Er=Rs.metrics.localGlyph?y:1,ln={x:0,y:0,w:Rs.bitmap.width+2*Er,h:Rs.bitmap.height+2*Er};ot.push(ln),ls[Xs]=ln}}const{w:jt,h:Dt}=c.J(ot),qt=new c.f9({width:jt||1,height:Dt||1});for(const ss in Ee){const Yt=Ee[ss];for(const ls in Yt.glyphs){const Xs=Yt.glyphs[+ls];if(!Xs||Xs.bitmap.width===0||Xs.bitmap.height===0)continue;const Rs=He[ss][ls],Er=Xs.metrics.localGlyph?y:1;c.f9.copy(Xs.bitmap,qt,{x:0,y:0},{x:Rs.x+Er,y:Rs.y+Er},Xs.bitmap)}}this.image=qt,this.positions=He}}function b(Gt,Ee,He){Gt[Ee]?He&&(Gt[Ee].center=He):Gt[Ee]={floorIds:new Set,center:He||[0,0],floors:{}}}function j(Gt,Ee,He,ot){for(const jt of Ee)b(Gt,jt),Gt[jt].floors[He]=ot,Gt[jt].floorIds.add(He)}function k(Gt){return{id:Gt.properties.id.toString(),center:[Gt.properties.center_lon||0,Gt.properties.center_lat||0]}}function T(Gt,Ee){const He=Gt.properties.id.toString(),ot=!!Gt.properties.is_default&&Gt.properties.is_default,jt=Gt.properties.connected_floor_ids?new Set(Gt.properties.connected_floor_ids.toString().split(";")):new Set,Dt=Gt.properties.conflicted_floor_ids?new Set(Gt.properties.conflicted_floor_ids.toString().split(";")):new Set,qt=Gt.properties.structure_ids?new Set(Gt.properties.structure_ids.toString().split(";")):new Set,ss=Gt.properties.name.toString(),Yt=Gt.properties.z_index,ls=function(Xs,Rs){const Er=Xs.loadGeometry();if(!Er||Er.length===0)return;const ln=Er.map(mn=>mn.map(Gr=>c.fb(Gr,Rs,Xs.extent)));return ln.length===0?void 0:{type:"Polygon",coordinates:[ln[0]]}}(Gt,Ee);return{id:He,isDefault:ot,connections:jt,conflicts:Dt,buildings:qt,name:ss,zIndex:Yt,geometry:ls}}function E(Gt,Ee){return Ee.every(He=>Gt.properties&&Gt.properties[He]!=null)}function A(Gt){return E(Gt,["type","id","name"])&&Gt.properties.type==="structure"}function D(Gt){return E(Gt,["type","id","name","z_index"])&&Gt.properties.type==="floor"}c.f8(_,"GlyphAtlas");class R{constructor(Ee){this.tileID=new c.aR(Ee.tileID.overscaledZ,Ee.tileID.wrap,Ee.tileID.canonical.z,Ee.tileID.canonical.x,Ee.tileID.canonical.y),this.tileZoom=Ee.tileZoom,this.uid=Ee.uid,this.zoom=Ee.zoom,this.lut=Ee.lut,this.canonical=Ee.tileID.canonical,this.pixelRatio=Ee.pixelRatio,this.tileSize=Ee.tileSize,this.source=Ee.source,this.scope=Ee.scope,this.overscaling=this.tileID.overscaleFactor(),this.showCollisionBoxes=Ee.showCollisionBoxes,this.collectResourceTiming=!!Ee.request&&Ee.request.collectResourceTiming,this.promoteId=Ee.promoteId,this.renderSourceType=Ee.renderSourceType,this.tileTransform=c.fc(Ee.tileID.canonical,Ee.projection),this.projection=Ee.projection,this.worldview=Ee.worldview,this.localizableLayerIds=Ee.localizableLayerIds,this.brightness=Ee.brightness,this.extraShadowCaster=!!Ee.extraShadowCaster,this.tessellationStep=Ee.tessellationStep,this.scaleFactor=Ee.scaleFactor,this.worldview=Ee.worldview,this.indoor=Ee.indoor}parse(Ee,He,ot,jt,Dt,qt){this.status="parsing",this.data=Ee,this.collisionBoxArray=new c.fd;const ss=new c.fe(Object.keys(Ee.layers).sort()),Yt=new c.ff(this.tileID,this.promoteId);Yt.bucketLayerIDs=[];const ls={},Xs=new c.fg(256,256),Rs={featureIndex:Yt,iconDependencies:new Map,patternDependencies:new Map,glyphDependencies:{},lineAtlas:Xs,availableImages:ot,brightness:this.brightness,scaleFactor:this.scaleFactor,elevationFeatures:void 0,activeFloors:void 0};this.indoor&&(Rs.activeFloors=function(Gr,fn,pn,Sn){const Aa=fn.indoorState.activeFloorsVisible;if(!fn.sourceLayers)return Aa?fn.indoorState.activeFloors:void 0;const vo=function(Cn,Wi){if(!Cn)return c.w("No source layers defined in indoor specification"),Wi;if(Cn.size===0)return Wi;const Ki=Cn.difference(Wi);for(const ii of Ki)c.w(`Missing source layer required in indoor specification: ${ii}`);return Wi.intersection(Wi)}(fn.sourceLayers,new Set(Object.keys(Gr.layers))),fo=fn.indoorState,ai=function(Cn,Wi,Ki,ii,Ji){const co={};for(const ia of Wi){const hr=Cn.layers[ia];if(hr)for(let Sa=0;Sa=ii.maxzoom||ii.visibility==="none")continue;z(Ki,this.zoom,Rs.brightness,ot,this.worldview,Rs.activeFloors);const Ji=ls[ii.id]=ii.createBucket({index:Yt.bucketLayerIDs.length,layers:Ki,zoom:this.zoom,lut:this.lut,canonical:this.canonical,pixelRatio:this.pixelRatio,overscaling:this.overscaling,collisionBoxArray:this.collisionBoxArray,sourceLayerIndex:fo,sourceID:this.source,projection:this.projection.spec,tessellationStep:this.tessellationStep,styleDefinedModelURLs:jt,worldview:this.worldview,localizable:Cn,availableImages:ot,maxUniformBufferBindings:this.maxUniformBufferBindings,maxUniformBlockSizeDwords:this.maxUniformBlockSizeDwords,disableSymbolUBO:this.disableSymbolUBO});Yt.bucketLayerIDs.push(Ki.map(ia=>c.F(ia.id,ia.scope)));let co=Ji.prepare?Ji.prepare():null;co!=null?(co=co.then(()=>Ji.populate(ai,Rs,this.tileID.canonical,this.tileTransform)),Er.push(co)):Ji.populate(ai,Rs,this.tileID.canonical,this.tileTransform)}}const mn=()=>{Xs.trim();const Gr=!(!Rs.elevationFeatures||!Rs.elevationFeatures.some(ii=>ii.heightRange.min<0));let fn,pn,Sn,Aa,vo,fo,ai;const Cn={type:"maybePrepare",renderSourceType:this.renderSourceType,zoom:this.zoom},Wi=()=>{if(fn)return this.status="done",qt(fn);if(this.extraShadowCaster)this.status="done",qt(null,{buckets:Object.values(ls).filter(ii=>!ii.isEmpty()),featureIndex:Yt,collisionBoxArray:null,hasTunnelGeometry:Gr,glyphAtlasImage:null,lineAtlas:null,imageAtlas:null,brightness:Rs.brightness,glyphMap:null,iconMap:null,glyphPositions:null});else if(pn&&Sn&&Aa&&ai){const Ji=new _(pn),co=new Map;for(const[Sa,Yi]of Sn.entries()){const{imagePosition:$o}=c.fn(Sa,Yi,c.fo);co.set(Sa,$o)}const ia={};for(const Sa in ls){const Yi=ls[Sa];Yi instanceof c.fp&&(z(Yi.layers,this.zoom,Rs.brightness,ot,this.worldview,Rs.activeFloors),ia[Sa]=c.fq(Yi,pn,Ji.positions,Sn,co,this.tileID.canonical,this.tileZoom,this.scaleFactor,this.pixelRatio,vo,this.worldview,ot))}const hr={iconsPending:!0,patternsPending:!0};this.rasterizeIfNeeded(Dt,Sn,vo,()=>{hr.iconsPending=!1,Ki(ia,Ji,hr,void 0,ai)}),this.rasterizeIfNeeded(Dt,Aa,fo,()=>{hr.patternsPending=!1,Ki(ia,Ji,hr,void 0,ai)})}},Ki=(ii,Ji,co,ia,hr)=>{if(co.iconsPending||co.patternsPending)return;const Sa=Sn.size>0||Aa.size>0,Yi=Object.keys(ii).length>0;if(!Sa&&!Yi)return this.status="done",void qt(null,{buckets:Object.values(ls).filter(cl=>!cl.isEmpty()),featureIndex:Yt,collisionBoxArray:this.collisionBoxArray,hasTunnelGeometry:Gr,glyphAtlasImage:Ji.image,lineAtlas:Xs,imageAtlas:null,brightness:Rs.brightness});const $o=(cl,bo)=>{for(const md in ls){const Nu=ls[md];if(md in ii)c.fv(Nu,ii[md],this.showCollisionBoxes,ot,this.tileID.canonical,this.tileZoom,this.projection,this.brightness,Sn,bo);else if(Nu.hasPattern&&(Nu instanceof c.fw||Nu instanceof c.fl||Nu instanceof c.e0)){z(Nu.layers,this.zoom,Rs.brightness,ot,this.worldview,Rs.activeFloors);const Yf=Object.fromEntries(bo.patternPositions);Nu.addFeatures(Rs,this.tileID.canonical,Yf,ot,this.tileTransform,this.brightness)}}this.status="done",qt(null,{buckets:Object.values(ls).filter(md=>!md.isEmpty()),featureIndex:Yt,collisionBoxArray:this.collisionBoxArray,hasTunnelGeometry:Gr,glyphAtlasImage:Ji.image,lineAtlas:Xs,imageAtlas:cl,brightness:Rs.brightness})};if(Sa){const cl=new Map,bo=c.fr(Sn,cl),md=c.fr(Aa,cl),Nu=new c.fs(bo,md,hr,this.lut,cl);Dt.send("checkAtlasCache",{descriptor:Nu,scope:this.scope},(Yf,ku)=>{let $h,Su;if(Yf&&c.w(`[Worker] Error checking atlas cache: ${Yf.message}`),ku)$h=new c.ft(ku.sourceHash),Su=ku;else{const Ad=new c.fu(Sn,Aa,this.lut,hr);$h=Ad,Su=Ad}$o($h,Su)})}else $o(null,{iconPositions:new Map,patternPositions:new Map})};if(!this.extraShadowCaster){const ii=c.fk(Rs.glyphDependencies,ia=>Object.keys(ia).map(Number));Object.keys(ii).length?Dt.send("getGlyphs",{uid:this.uid,stacks:ii},(ia,hr)=>{fn||(fn=ia,pn=hr,Wi())},void 0,!1,Cn):pn={},ai=new Map;const Ji=Array.from(Rs.iconDependencies.keys()).map(ia=>c.I.parse(ia));Ji.length?Dt.send("getImages",{images:Ji,source:this.source,scope:this.scope,tileID:this.tileID,type:"icons"},(ia,hr)=>{if(!fn){fn=ia,Sn=new Map,vo=this.updateImageMapAndGetImageTaskQueue(Sn,hr.images,Rs.iconDependencies);for(const[Sa,Yi]of hr.versions.entries())ai.set(Sa,Yi);Wi()}},void 0,!1,Cn):(Sn=new Map,vo=new Map);const co=Array.from(Rs.patternDependencies.keys()).map(ia=>c.I.parse(ia));co.length?Dt.send("getImages",{images:co,source:this.source,scope:this.scope,tileID:this.tileID,type:"patterns"},(ia,hr)=>{if(!fn){fn=ia,Aa=new Map,fo=this.updateImageMapAndGetImageTaskQueue(Aa,hr.images,Rs.patternDependencies);for(const[Sa,Yi]of hr.versions.entries())ai.set(Sa,Yi);Wi()}},void 0,!1,Cn):(Aa=new Map,fo=new Map)}if(Rs.elevationFeatures&&Rs.elevationFeatures.length>0){const ii=[];for(const co of Object.values(ls))if(co instanceof c.fl){const ia=co.getUnevaluatedPortalGraph();ia&&ii.push(ia)}const Ji=c.fm.evaluate(ii);for(const co of Object.values(ls))if(co instanceof c.fl){const ia=Ee.layers[ss.decode(co.sourceLayerIndex)];co.setEvaluatedPortalGraph(Ji,ia,this.tileID.canonical,Rs.availableImages,Rs.brightness)}}Wi()};Er.length>0?Promise.allSettled(Er).then(mn).catch(qt):mn()}updateParameters(Ee){this.scaleFactor=Ee.scaleFactor,this.showCollisionBoxes=Ee.showCollisionBoxes,this.projection=Ee.projection,this.brightness=Ee.brightness,this.tileTransform=c.fc(Ee.tileID.canonical,Ee.projection),this.extraShadowCaster=Ee.extraShadowCaster,this.lut=Ee.lut,this.worldview=Ee.worldview,this.indoor=Ee.indoor}rasterizeIfNeeded(Ee,He,ot,jt){Array.from(He.values()).some(Dt=>Dt.usvg)?this.rasterize(Ee,He,ot,jt):jt()}updateImageMapAndGetImageTaskQueue(Ee,He,ot){const jt=new Map;for(const Dt of He.keys()){const qt=ot.get(Dt)||[];for(const ss of qt){const Yt=ss.toString(),ls=He.get(ss.id.toString());ls.usvg?jt.has(Yt)||(jt.set(Yt,ss),Ee.set(Yt,Object.assign({},ls))):Ee.set(Yt,ls)}}return jt}rasterize(Ee,He,ot,jt){this.rasterizeTask=Ee.send("rasterizeImages",{scope:this.scope,tasks:ot},(Dt,qt)=>{if(!Dt)for(const[ss,Yt]of qt.entries()){const ls=Object.assign(He.get(ss),{data:Yt});He.set(ss,ls)}jt()})}cancelRasterize(){this.rasterizeTask&&this.rasterizeTask.cancel()}}function z(Gt,Ee,He,ot,jt,Dt){const qt=new c.ae(Ee,{brightness:He,worldview:jt,activeFloors:Dt});for(const ss of Gt)ss.recalculate(qt,ot)}class O extends c.E{constructor({actor:Ee,layerIndex:He,availableImages:ot,availableModels:jt,isSpriteLoaded:Dt,tileProvider:qt,brightness:ss,maxUniformBufferBindings:Yt,maxUniformBlockSizeDwords:ls,disableSymbolUBO:Xs}){super(),this.actor=Ee,this.layerIndex=He,this.availableImages=ot,this.availableModels=jt,this.loadVectorData=c.aO,this.tileProvider=qt,this.loading={},this.loaded={},this.deduped=new c.aN(Ee.scheduler),this.isSpriteLoaded=Dt,this.scheduler=Ee.scheduler,this.brightness=ss,this.maxUniformBufferBindings=Yt,this.maxUniformBlockSizeDwords=ls,this.disableSymbolUBO=Xs}loadTileData(Ee,He){if(!this.tileProvider)return this.loadVectorData(Ee,He);const ot=new AbortController,{z:jt,x:Dt,y:qt}=Ee.tileID.canonical;return this.tileProvider.loadTile({z:jt,x:Dt,y:qt},{request:Ee.request,signal:ot.signal}).then(ss=>{if(ot.signal.aborted)return;if(ss==null){const ls=new Error("Tile not found");return ls.status=404,He(ls)}if(ss.data===null)return He(null,null);const Yt=new Map;ss.expires&&Yt.set("expires",ss.expires),ss.cacheControl&&Yt.set("cache-control",ss.cacheControl),He(null,{rawData:ss.data,responseHeaders:Yt})}).catch(ss=>{ot.signal.aborted||He(ss instanceof Error?ss:new Error(String(ss)))}),()=>ot.abort()}loadTile(Ee,He){const ot=Ee.uid,jt=Ee&&Ee.request,Dt=jt&&jt.collectResourceTiming,qt=this.loading[ot]=new R(Ee);qt.maxUniformBufferBindings=this.maxUniformBufferBindings,qt.maxUniformBlockSizeDwords=this.maxUniformBlockSizeDwords,qt.disableSymbolUBO=this.disableSymbolUBO,qt.abort=this.loadTileData(Ee,(ss,Yt)=>{const ls=!this.loading[ot];if(delete this.loading[ot],qt.cancelRasterize(),ls||ss||!Yt)return qt.status="done",ls||(this.loaded[ot]=qt),He(ss);const Xs=Yt.rawData,Rs={},Er=c.aP(Yt.responseHeaders);Er&&Er.expires&&(Rs.expires=Er.expires),Er&&Er.cacheControl&&(Rs.cacheControl=Er.cacheControl),qt.vectorTile=Yt.vectorTile||new c.fx(new c.a$(Xs));const ln=()=>{qt.parse(qt.vectorTile,this.layerIndex,this.availableImages,this.availableModels,this.actor,(mn,Gr)=>{if(mn||!Gr)return He(mn);const fn={};if(Dt){const pn=d(jt);pn.length>0&&(fn.resourceTiming=JSON.parse(JSON.stringify(pn)))}He(null,Object.assign({rawTileData:Xs.slice(0),responseHeaders:Yt.responseHeaders},Gr,Rs,fn))})};this.isSpriteLoaded?ln():this.once("isSpriteLoaded",()=>{this.scheduler?this.scheduler.add(ln,{type:"parseTile",renderSourceType:Ee.renderSourceType,zoom:Ee.tileZoom}):ln()}),this.loaded=this.loaded||{},this.loaded[ot]=qt})}reloadTile(Ee,He){const ot=this.loaded,jt=Ee.uid;if(ot&&ot[jt]){const Dt=ot[jt];Dt.updateParameters(Ee);const qt=(ss,Yt)=>{const ls=Dt.reloadCallback;ls&&(delete Dt.reloadCallback,Dt.parse(Dt.vectorTile,this.layerIndex,this.availableImages,this.availableModels,this.actor,ls)),He(ss,Yt)};Dt.status==="parsing"?Dt.reloadCallback=qt:Dt.status==="done"&&(Dt.vectorTile?Dt.parse(Dt.vectorTile,this.layerIndex,this.availableImages,this.availableModels,this.actor,qt):qt())}else He(null,void 0)}abortTile(Ee,He){const ot=Ee.uid,jt=this.loading[ot];jt&&(jt.abort&&jt.abort(),delete this.loading[ot]),He()}removeTile(Ee,He){const ot=this.loaded,jt=Ee.uid;ot&&ot[jt]&&delete ot[jt],He()}}class ${constructor(Ee){this.loading={}}loadTile(Ee,He){const ot=Ee.uid,{cancel:jt}=c.b1(Ee.request,(Dt,qt,ss)=>{const Yt=!this.loading[ot];if(delete this.loading[ot],Yt||Dt||!qt)return He(Dt);this.decodeTile(ot,qt,Ee.encoding).then(ls=>{const{expires:Xs,cacheControl:Rs}=c.aP(ss);He(null,Object.assign(ls,{expires:Xs,cacheControl:Rs}))}).catch(ls=>He(ls))});this.loading[ot]={cancel:jt}}async decodeTile(Ee,He,ot){const jt=await createImageBitmap(new Blob([new Uint8Array(He)],{type:"image/png"})),Dt=1-(jt.width-c.fy(jt.width))/2,qt=Dt<1,ss=this.getImageData(jt,Dt);return jt.close(),{dem:new c.fz(Ee,ss,ot,qt),borderReady:qt}}reloadTile(Ee,He){He(null,null)}abortTile(Ee,He){const ot=Ee.uid,jt=this.loading[ot];jt&&(jt.cancel(),delete this.loading[ot]),He()}removeTile(Ee,He){He()}getImageData(Ee,He){this.offscreenCanvas&&this.offscreenCanvasContext||(this.offscreenCanvas=new OffscreenCanvas(Ee.width,Ee.height),this.offscreenCanvasContext=this.offscreenCanvas.getContext("2d",{willReadFrequently:!0})),this.offscreenCanvas.width=Ee.width,this.offscreenCanvas.height=Ee.height,this.offscreenCanvasContext.drawImage(Ee,0,0,Ee.width,Ee.height);const ot=this.offscreenCanvasContext.getImageData(-He,-He,Ee.width+2*He,Ee.height+2*He);return this.offscreenCanvasContext.clearRect(0,0,this.offscreenCanvas.width,this.offscreenCanvas.height),ot}}c.a_.setPbf(c.a$);class ee{constructor(Ee){this._mrt=new c.a_(Ee.partial?30:1/0),this._isHeaderLoaded=!1,this.uid=Ee.uid,this.tileID=Ee.tileID,this.source=Ee.source}parse(Ee,He){const ot=this._mrt;this.status="parsing",this._entireBuffer=Ee;try{ot.parseHeader(Ee),this._isHeaderLoaded=!0;const jt=[];for(const Dt in ot.layers){const qt=ot.getLayer(Dt),ss=qt.getDataRange(qt.getBandList()),Yt=ot.createDecodingTask(ss),ls=Ee.slice(ss.firstByte,ss.lastByte+1),Xs=c.a_.performDecoding(ls,Yt).then(Rs=>Yt.complete(null,Rs)).catch(Rs=>Yt.complete(Rs,null));jt.push(Xs)}Promise.allSettled(jt).then(()=>He(null,ot)).catch(Dt=>He(Dt))}catch(jt){He(jt)}}}class Z{constructor({actor:Ee}){this.actor=Ee,this.loading={},this.loaded={}}loadTile(Ee,He){const ot=Ee.uid,jt=Ee.request,Dt=this.loading[ot]=new ee(Ee),{cancel:qt}=c.b1(jt,(ss,Yt,ls)=>{const Xs=!this.loading[ot];if(delete this.loading[ot],Xs||ss||!Yt)return Dt.status="done",Xs||(this.loaded[ot]=Dt),He(ss);Dt.parse(Yt,(Rs,Er)=>{if(Rs||!Er)return He(Rs);He(null,Er,ls)}),this.loaded[ot]=Dt});Dt.abort=qt}reloadTile(Ee,He){He(null,void 0)}abortTile(Ee,He){const ot=Ee.uid,jt=this.loading[ot];jt&&(jt.abort&&jt.abort(),delete this.loading[ot]),He()}removeTile(Ee,He){const ot=Ee.uid;this.loaded[ot]&&delete this.loaded[ot],He()}decodeRasterArray(Ee,He){c.a_.performDecoding(Ee.buffer,Ee.task).then(ot=>He(null,ot)).catch(ot=>He(ot))}}const J=c.fA.prototype.toGeoJSON;class K{constructor(Ee){this._feature=Ee,this.extent=c.an,this.type=Ee.type,this.properties=Ee.tags,"id"in Ee&&!isNaN(Ee.id)&&(this.id=parseInt(Ee.id,10))}loadGeometry(){if(this._feature.type===1){const Ee=[];for(const He of this._feature.geometry)Ee.push([new c.P(He[0],He[1])]);return Ee}{const Ee=[];for(const He of this._feature.geometry){const ot=[];for(const jt of He)ot.push(new c.P(jt[0],jt[1]));Ee.push(ot)}return Ee}}toGeoJSON(Ee,He,ot){return J.call(this,Ee,He,ot)}}class re{constructor(Ee,He){this.name=Ee,this.extent=c.an,this.length=He.length,this._jsonFeatures=He}feature(Ee){return new K(this._jsonFeatures[Ee])}}class ie{constructor(Ee){this.layers={},this.extent=c.an;for(const He of Object.keys(Ee))this.layers[He]=new re(He,Ee[He])}}const ce=64/4096;class ne{constructor(){this.features=new Map}clear(){this.features.clear()}load(Ee=[],He){for(const ot of Ee){const jt=ot.id;if(jt==null)continue;let Dt=this.features.get(jt);Dt&&this.updateCache(Dt,He),ot.geometry?(Dt=be(ot),this.updateCache(Dt,He),this.features.set(jt,Dt)):this.features.delete(jt),this.updateCache(Dt,He)}}updateCache(Ee,He){for(const{canonical:ot,uid:jt}of Object.values(He)){const{z:Dt,x:qt,y:ss}=ot;le(Ee,Math.pow(2,Dt),qt,ss)&&delete He[jt]}}getTile(Ee,He,ot){const jt=Math.pow(2,Ee),Dt=[];for(const qt of this.features.values())le(qt,jt,He,ot)&&Dt.push(We(qt,jt,He,ot));return{features:Dt}}getFeatures(){return[...this.features.values()]}}function le({minX:Gt,minY:Ee,maxX:He,maxY:ot},jt,Dt,qt){return Gt<(Dt+1+ce)/jt&&Ee<(qt+1+ce)/jt&&He>(Dt-ce)/jt&&ot>(qt-ce)/jt}function be(Gt){const{id:Ee,geometry:He,properties:ot}=Gt;if(!He)return;if(He.type==="GeometryCollection")throw new Error("GeometryCollection not supported in dynamic mode.");const{type:jt,coordinates:Dt}=He,qt={id:Ee,type:1,geometry:[],tags:ot,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0},ss=qt.geometry;if(jt==="Point")fe(Dt,ss,qt);else if(jt==="MultiPoint")for(const Yt of Dt)fe(Yt,ss,qt);else if(jt==="LineString")qt.type=2,je(Dt,ss,qt);else if(jt==="MultiLineString")qt.type=2,ve(Dt,ss,qt);else if(jt==="Polygon")qt.type=3,ve(Dt,ss,qt,!0);else{if(jt!=="MultiPolygon")throw new Error("Input data is not a valid GeoJSON object.");qt.type=3;for(const Yt of Dt)ve(Yt,ss,qt,!0)}return qt}function fe([Gt,Ee],He,ot){const jt=c.aH(Gt);let Dt=c.aL(Ee);Dt=Dt<0?0:Dt>1?1:Dt,He.push(jt,Dt),ot.minX=Math.min(ot.minX,jt),ot.minY=Math.min(ot.minY,Dt),ot.maxX=Math.max(ot.maxX,jt),ot.maxY=Math.max(ot.maxY,Dt)}function je(Gt,Ee,He,ot=!1,jt=!1){const Dt=[];for(const qt of Gt)fe(qt,Dt,He);Ee.push(Dt),ot&&function(qt,ss){let Yt=0;for(let ls=0,Xs=qt.length,Rs=Xs-2;ls0===ss)for(let ls=0,Xs=qt.length;ls=qt&&Rs>=qt||(ls>=qt?(Xs+=Math.round(mn*((qt-ls)/ln)),ls=qt):Rs>=qt&&(Er=Xs+Math.round(mn*((qt-ls)/ln)),Rs=qt),Xs>=qt&&Er>=qt||(Xs>=qt?(ls+=Math.round(ln*((qt-Xs)/mn)),Xs=qt):Er>=qt&&(Rs=ls+Math.round(ln*((qt-Xs)/mn)),Er=qt),ss&&ls===ss[ss.length-1][0]&&Xs===ss[ss.length-1][1]||(ss=[[ls,Xs]],jt.push(ss)),ss.push([Rs,Er])))))}}function Le(Gt,Ee,He,ot,jt){const Dt=(He-ce)/Ee,qt=(ot-ce)/Ee,ss=(He+1+ce)/Ee,Yt=(ot+1+ce)/Ee;function ls(Er,ln){let mn=0;return Erss&&(mn|=2),lnYt&&(mn|=8),mn}let Xs=[];for(let Er=1;Er<=8;Er*=2){let ln=Gt[Gt.length-2],mn=Gt[Gt.length-1],Gr=!(ls(ln,mn)&Er);for(let fn=0;fn>31}function pe(Gt,Ee){const{geometry:He,type:ot}=Gt;let jt=0,Dt=0;if(ot===1){Ee.writeVarint(Ie(1,He.length));for(const qt of He){const ss=qt[0]-jt,Yt=qt[1]-Dt;Ee.writeVarint(De(ss)),Ee.writeVarint(De(Yt)),jt+=ss,Dt+=Yt}}else for(const qt of He){if(qt.length===0)continue;Ee.writeVarint(Ie(1,1));const ss=qt.length-(ot===3?1:0);for(let Yt=0;YtGt},ct=Math.fround||(Ue=new Float32Array(1),Gt=>(Ue[0]=+Gt,Ue[0]));var Ue;class et{constructor(Ee){this.options=Object.assign(Object.create(ge),Ee),this.trees=new Array(this.options.maxZoom+1),this.stride=this.options.reduce?7:6,this.clusterProps=[]}load(Ee){const{log:He,minZoom:ot,maxZoom:jt}=this.options;He&&console.time("total time");const Dt=`prepare ${Ee.length} points`;He&&console.time(Dt),this.points=Ee;const qt=[];for(let Yt=0;Yt=ot;Yt--){const ls=+Date.now();ss=this.trees[Yt]=this._createTree(this._cluster(ss,Yt)),He&&console.log("z%d: %d clusters in %dms",Yt,ss.numItems,+Date.now()-ls)}return He&&console.timeEnd("total time"),this}getClusters(Ee,He){let ot=((Ee[0]+180)%360+360)%360-180;const jt=Math.max(-90,Math.min(90,Ee[1]));let Dt=Ee[2]===180?180:((Ee[2]+180)%360+360)%360-180;const qt=Math.max(-90,Math.min(90,Ee[3]));if(Ee[2]-Ee[0]>=360)ot=-180,Dt=180;else if(ot>Dt){const Rs=this.getClusters([ot,jt,180,qt],He),Er=this.getClusters([-180,jt,Dt,qt],He);return Rs.concat(Er)}const ss=this.trees[this._limitZoom(He)],Yt=ss.range($e(ot),it(qt),$e(Dt),it(jt)),ls=ss.data,Xs=[];for(const Rs of Yt){const Er=this.stride*Rs;Xs.push(ls[Er+5]>1?Qe(ls,Er,this.clusterProps):this.points[ls[Er+3]])}return Xs}getChildren(Ee){const He=this._getOriginId(Ee),ot=this._getOriginZoom(Ee),jt="No cluster with the specified id.",Dt=this.trees[ot];if(!Dt)throw new Error(jt);const qt=Dt.data;if(He*this.stride>=qt.length)throw new Error(jt);const ss=this.options.radius/(this.options.extent*Math.pow(2,ot-1)),Yt=Dt.within(qt[He*this.stride],qt[He*this.stride+1],ss),ls=[];for(const Xs of Yt){const Rs=Xs*this.stride;qt[Rs+4]===Ee&&ls.push(qt[Rs+5]>1?Qe(qt,Rs,this.clusterProps):this.points[qt[Rs+3]])}if(ls.length===0)throw new Error(jt);return ls}getLeaves(Ee,He,ot){const jt=[];return this._appendLeaves(jt,Ee,He=He||10,ot=ot||0,0),jt}getTile(Ee,He,ot){const jt=this.trees[this._limitZoom(Ee)],Dt=Math.pow(2,Ee),{extent:qt,radius:ss}=this.options,Yt=ss/qt,ls=(ot-Yt)/Dt,Xs=(ot+1+Yt)/Dt,Rs={features:[]};return this._addTileFeatures(jt.range((He-Yt)/Dt,ls,(He+1+Yt)/Dt,Xs),jt.data,He,ot,Dt,Rs),He===0&&this._addTileFeatures(jt.range(1-Yt/Dt,ls,1,Xs),jt.data,Dt,ot,Dt,Rs),He===Dt-1&&this._addTileFeatures(jt.range(0,ls,Yt/Dt,Xs),jt.data,-1,ot,Dt,Rs),Rs.features.length?Rs:null}getClusterExpansionZoom(Ee){let He=this._getOriginZoom(Ee)-1;for(;He<=this.options.maxZoom;){const ot=this.getChildren(Ee);if(He++,ot.length!==1)break;Ee=ot[0].properties.cluster_id}return He}_appendLeaves(Ee,He,ot,jt,Dt){const qt=this.getChildren(He);for(const ss of qt){const Yt=ss.properties;if(Yt&&Yt.cluster?Dt+Yt.point_count<=jt?Dt+=Yt.point_count:Dt=this._appendLeaves(Ee,Yt.cluster_id,ot,jt,Dt):Dt1;let Xs,Rs,Er;if(ls)Xs=Ne(He,Yt,this.clusterProps),Rs=He[Yt],Er=He[Yt+1];else{const Gr=this.points[He[Yt+3]];Xs=Gr.properties;const[fn,pn]=Gr.geometry.coordinates;Rs=$e(fn),Er=it(pn)}const ln={type:1,geometry:[[Math.round(this.options.extent*(Rs*Dt-ot)),Math.round(this.options.extent*(Er*Dt-jt))]],tags:Xs};let mn;mn=ls||this.options.generateId?He[Yt+3]:this.points[He[Yt+3]].id,mn!==void 0&&(ln.id=mn),qt.features.push(ln)}}_limitZoom(Ee){return Math.max(this.options.minZoom,Math.min(Math.floor(+Ee),this.options.maxZoom+1))}_cluster(Ee,He){const{radius:ot,extent:jt,reduce:Dt,minPoints:qt}=this.options,ss=ot/(jt*Math.pow(2,He)),Yt=Ee.data,ls=[],Xs=this.stride;for(let Rs=0;RsHe&&(fn+=Yt[Sn+5])}if(fn>Gr&&fn>=qt){let pn,Sn=Er*Gr,Aa=ln*Gr,vo=-1;const fo=(Rs/Xs<<5)+(He+1)+this.points.length;for(const ai of mn){const Cn=ai*Xs;if(Yt[Cn+2]<=He)continue;Yt[Cn+2]=He;const Wi=Yt[Cn+5];Sn+=Yt[Cn]*Wi,Aa+=Yt[Cn+1]*Wi,Yt[Cn+4]=fo,Dt&&(pn||(pn=this._map(Yt,Rs,!0),vo=this.clusterProps.length,this.clusterProps.push(pn)),Dt(pn,this._map(Yt,Cn)))}Yt[Rs+4]=fo,ls.push(Sn/fn,Aa/fn,1/0,fo,-1,fn),Dt&&ls.push(vo)}else{for(let pn=0;pn1)for(const pn of mn){const Sn=pn*Xs;if(!(Yt[Sn+2]<=He)){Yt[Sn+2]=He;for(let Aa=0;Aa>5}_getOriginZoom(Ee){return(Ee-this.points.length)%32}_map(Ee,He,ot){if(Ee[He+5]>1){const qt=this.clusterProps[Ee[He+6]];return ot?Object.assign({},qt):qt}const jt=this.points[Ee[He+3]].properties,Dt=this.options.map(jt);return ot&&Dt===jt?Object.assign({},Dt):Dt}}function Qe(Gt,Ee,He){return{type:"Feature",id:Gt[Ee+3],properties:Ne(Gt,Ee,He),geometry:{type:"Point",coordinates:[(ot=Gt[Ee],360*(ot-.5)),Je(Gt[Ee+1])]}};var ot}function Ne(Gt,Ee,He){const ot=Gt[Ee+5],jt=ot>=1e4?`${Math.round(ot/1e3)}k`:ot>=1e3?Math.round(ot/100)/10+"k":ot,Dt=Gt[Ee+6],qt=Dt===-1?{}:Object.assign({},He[Dt]);return Object.assign(qt,{cluster:!0,cluster_id:Gt[Ee+3],point_count:ot,point_count_abbreviated:jt})}function $e(Gt){return Gt/360+.5}function it(Gt){const Ee=Math.sin(Gt*Math.PI/180),He=.5-.25*Math.log((1+Ee)/(1-Ee))/Math.PI;return He<0?0:He>1?1:He}function Je(Gt){const Ee=(180-360*Gt)*Math.PI/180;return 360*Math.atan(Math.exp(Ee))/Math.PI-90}function st(Gt,Ee,He,ot){let jt=ot;const Dt=Ee+(He-Ee>>1);let qt,ss=He-Ee;const Yt=Gt[Ee],ls=Gt[Ee+1],Xs=Gt[He],Rs=Gt[He+1];for(let Er=Ee+3;Erjt)qt=Er,jt=ln;else if(ln===jt){const mn=Math.abs(Er-Dt);mnot&&(qt-Ee>3&&st(Gt,Ee,qt,ot),Gt[qt+2]=jt,He-qt>3&&st(Gt,qt,He,ot))}function mt(Gt,Ee,He,ot,jt,Dt){let qt=jt-He,ss=Dt-ot;if(qt!==0||ss!==0){const Yt=((Gt-He)*qt+(Ee-ot)*ss)/(qt*qt+ss*ss);Yt>1?(He=jt,ot=Dt):Yt>0&&(He+=qt*Yt,ot+=ss*Yt)}return qt=Gt-He,ss=Ee-ot,qt*qt+ss*ss}function wt(Gt,Ee,He,ot){const jt={id:Gt??null,type:Ee,geometry:He,tags:ot,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0};if(Ee==="Point"||Ee==="MultiPoint"||Ee==="LineString")at(jt,He);else if(Ee==="Polygon")at(jt,He[0]);else if(Ee==="MultiLineString")for(const Dt of He)at(jt,Dt);else if(Ee==="MultiPolygon")for(const Dt of He)at(jt,Dt[0]);return jt}function at(Gt,Ee){for(let He=0;He0&&(qt+=ot?(jt*Xs-ls*Dt)/2:Math.sqrt(Math.pow(ls-jt,2)+Math.pow(Xs-Dt,2))),jt=ls,Dt=Xs}const ss=Ee.length-3;Ee[2]=1,st(Ee,0,ss,He),Ee[ss+2]=1,Ee.size=Math.abs(qt),Ee.start=0,Ee.end=Ee.size}function Is(Gt,Ee,He,ot){for(let jt=0;jt1?1:He}function St(Gt,Ee,He,ot,jt,Dt,qt,ss){if(ot/=Ee,Dt>=(He/=Ee)&&qt=ot)return null;const Yt=[];for(const ls of Gt){const Xs=ls.geometry;let Rs=ls.type;const Er=jt===0?ls.minX:ls.minY,ln=jt===0?ls.maxX:ls.maxY;if(Er>=He&&ln=ot)continue;let mn=[];if(Rs==="Point"||Rs==="MultiPoint")xs(Xs,mn,He,ot,jt);else if(Rs==="LineString")kt(Xs,mn,He,ot,jt,!1,ss.lineMetrics);else if(Rs==="MultiLineString")Gs(Xs,mn,He,ot,jt,!1);else if(Rs==="Polygon")Gs(Xs,mn,He,ot,jt,!0);else if(Rs==="MultiPolygon")for(const Gr of Xs){const fn=[];Gs(Gr,fn,He,ot,jt,!0),fn.length&&mn.push(fn)}if(mn.length){if(ss.lineMetrics&&Rs==="LineString"){for(const Gr of mn)Yt.push(wt(ls.id,Rs,Gr,ls.tags));continue}Rs!=="LineString"&&Rs!=="MultiLineString"||(mn.length===1?(Rs="LineString",mn=mn[0]):Rs="MultiLineString"),Rs!=="Point"&&Rs!=="MultiPoint"||(Rs=mn.length===3?"Point":"MultiPoint"),Yt.push(wt(ls.id,Rs,mn,ls.tags))}}return Yt.length?Yt:null}function xs(Gt,Ee,He,ot,jt){for(let Dt=0;Dt=He&&qt<=ot&&_s(Ee,Gt[Dt],Gt[Dt+1],Gt[Dt+2])}}function kt(Gt,Ee,He,ot,jt,Dt,qt){let ss=fs(Gt);const Yt=jt===0?br:zr;let ls,Xs,Rs=Gt.start;for(let fn=0;fnHe&&(Xs=Yt(ss,pn,Sn,vo,fo,He),qt&&(ss.start=Rs+ls*Xs)):ai>ot?Cn=He&&(Xs=Yt(ss,pn,Sn,vo,fo,He),Wi=!0),Cn>ot&&ai<=ot&&(Xs=Yt(ss,pn,Sn,vo,fo,ot),Wi=!0),!Dt&&Wi&&(qt&&(ss.end=Rs+ls*Xs),Ee.push(ss),ss=fs(Gt)),qt&&(Rs+=ls)}let Er=Gt.length-3;const ln=Gt[Er],mn=Gt[Er+1],Gr=jt===0?ln:mn;Gr>=He&&Gr<=ot&&_s(ss,ln,mn,Gt[Er+2]),Er=ss.length-3,Dt&&Er>=3&&(ss[Er]!==ss[0]||ss[Er+1]!==ss[1])&&_s(ss,ss[0],ss[1],ss[2]),ss.length&&Ee.push(ss)}function fs(Gt){const Ee=[];return Ee.size=Gt.size,Ee.start=Gt.start,Ee.end=Gt.end,Ee}function Gs(Gt,Ee,He,ot,jt,Dt){for(const qt of Gt)kt(qt,Ee,He,ot,jt,Dt,!1)}function _s(Gt,Ee,He,ot){Gt.push(Ee,He,ot)}function br(Gt,Ee,He,ot,jt,Dt){const qt=(Dt-Ee)/(ot-Ee);return _s(Gt,Dt,He+(jt-He)*qt,1),qt}function zr(Gt,Ee,He,ot,jt,Dt){const qt=(Dt-He)/(jt-He);return _s(Gt,Ee+(ot-Ee)*qt,Dt,1),qt}function Yr(Gt,Ee){const He=[];for(let ot=0;ot0&&Ee.size<(jt?qt:ot))return void(He.numPoints+=Ee.length/3);const ss=[];for(let Yt=0;Ytqt)&&(He.numSimplified++,ss.push(Ee[Yt],Ee[Yt+1])),He.numPoints++;jt&&function(Yt,ls){let Xs=0;for(let Rs=0,Er=Yt.length,ln=Er-2;Rs0===ls)for(let Rs=0,Er=Yt.length;Rs24)throw new Error("maxZoom should be in the 0-24 range");if(He.promoteId&&He.generateId)throw new Error("promoteId and generateId cannot be used together.");let jt=function(Dt,qt){const ss=[];if(Dt.type==="FeatureCollection")for(let Yt=0;Yt1&&console.time("creation"),ln=this.tiles[Er]=$r(Ee,He,ot,jt,ls),this.tileCoords.push({z:He,x:ot,y:jt}),Xs)){Xs>1&&(console.log("tile z%d-%d-%d (features: %d, points: %d, simplified: %d)",He,ot,jt,ln.numFeatures,ln.numPoints,ln.numSimplified),console.timeEnd("creation"));const Wi=`z${He}`;this.stats[Wi]=(this.stats[Wi]||0)+1,this.total++}if(ln.source=Ee,Dt==null){if(He===ls.indexMaxZoom||ln.numPoints<=ls.indexMaxPoints)continue}else{if(He===ls.maxZoom||He===Dt)continue;if(Dt!=null){const Wi=Dt-He;if(ot!==qt>>Wi||jt!==ss>>Wi)continue}}if(ln.source=null,Ee.length===0)continue;Xs>1&&console.time("clipping");const mn=.5*ls.buffer/ls.extent,Gr=.5-mn,fn=.5+mn,pn=1+mn;let Sn=null,Aa=null,vo=null,fo=null,ai=St(Ee,Rs,ot-mn,ot+fn,0,ln.minX,ln.maxX,ls),Cn=St(Ee,Rs,ot+Gr,ot+pn,0,ln.minX,ln.maxX,ls);Ee=null,ai&&(Sn=St(ai,Rs,jt-mn,jt+fn,1,ln.minY,ln.maxY,ls),Aa=St(ai,Rs,jt+Gr,jt+pn,1,ln.minY,ln.maxY,ls),ai=null),Cn&&(vo=St(Cn,Rs,jt-mn,jt+fn,1,ln.minY,ln.maxY,ls),fo=St(Cn,Rs,jt+Gr,jt+pn,1,ln.minY,ln.maxY,ls),Cn=null),Xs>1&&console.timeEnd("clipping"),Yt.push(Sn||[],He+1,2*ot,2*jt),Yt.push(Aa||[],He+1,2*ot,2*jt+1),Yt.push(vo||[],He+1,2*ot+1,2*jt),Yt.push(fo||[],He+1,2*ot+1,2*jt+1)}}getTile(Ee,He,ot){Ee=+Ee,He=+He,ot=+ot;const jt=this.options,{extent:Dt,debug:qt}=jt;if(Ee<0||Ee>24)return null;const ss=1<1&&console.log("drilling down to z%d-%d-%d",Ee,He,ot);let ls,Xs=Ee,Rs=He,Er=ot;for(;!ls&&Xs>0;)Xs--,Rs>>=1,Er>>=1,ls=this.tiles[ds(Xs,Rs,Er)];return ls&&ls.source?(qt>1&&(console.log("found parent tile z%d-%d-%d",Xs,Rs,Er),console.time("drilling down")),this.splitTile(ls.source,Xs,Rs,Er,Ee,He,ot),qt>1&&console.timeEnd("drilling down"),this.tiles[Yt]?sn(this.tiles[Yt],Dt):null):null}}function ds(Gt,Ee,He){return 32*((1<ls.tags&&"3d_elevation_id"in ls.tags&&"source"in ls.tags&&ls.tags.source==="elevation",Dt=ot.features.filter(ls=>jt(ls));let qt={_geojsonTileLayer:ot.features};Dt.length>0&&(qt={_geojsonTileLayer:ot.features.filter(ls=>!jt(ls)),hd_road_elevation:Dt});const ss=new ie(qt),Yt=function(ls){const Xs=new c.a$;for(const Rs of Object.keys(ls))Xs.writeMessage(3,Me,{name:Rs,features:ls[Rs]});return Xs.finish()}(qt).buffer;Ee(null,{vectorTile:ss,rawData:Yt})}class vn extends O{constructor(Ee){super(Ee),this.loadVectorData=Na,this._dynamicIndex=new ne}loadData(Ee,He){const ot=Ee&&Ee.request,jt=ot&&ot.collectResourceTiming;this._geoJSONIndex=null,this.loadGeoJSON(Ee,(Dt,qt)=>{if(Dt||!qt)return He(Dt);if(typeof qt!="object")return He(new Error(`Input data given to '${Ee.source}' is not a valid GeoJSON object.`));{try{if(Ee.filter){const Yt=c.X(Ee.filter,{type:"boolean","property-type":"data-driven",overridable:!1,transition:!1});if(Yt.result==="error")throw new Error(Yt.value.map(ls=>`${ls.key}: ${ls.message}`).join(", "));qt.features=qt.features.filter(ls=>Yt.value.evaluate({zoom:0},ls))}Ee.dynamic?(qt.type==="Feature"&&(qt={type:"FeatureCollection",features:[qt]}),Ee.append||(this._dynamicIndex.clear(),this.loaded={}),this._dynamicIndex.load(qt.features,this.loaded),Ee.cluster&&(qt.features=this._dynamicIndex.getFeatures())):this.loaded={},this._geoJSONIndex=Ee.cluster?new et(function({superclusterOptions:Yt,clusterProperties:ls}){if(!ls||!Yt)return Yt;const Xs={},Rs={},Er={accumulated:null,zoom:0},ln={properties:null},mn=Object.keys(ls);for(const Gr of mn){const[fn,pn]=ls[Gr],Sn=c.X(pn),Aa=c.X(typeof fn=="string"?[fn,["accumulated"],["get",Gr]]:fn);Xs[Gr]=Sn.value,Rs[Gr]=Aa.value}return Yt.map=Gr=>{ln.properties=Gr;const fn={};for(const pn of mn)fn[pn]=Xs[pn].evaluate(Er,ln);return fn},Yt.reduce=(Gr,fn)=>{ln.properties=fn;for(const pn of mn)Er.accumulated=Gr[pn],Gr[pn]=Rs[pn].evaluate(Er,ln)},Yt}(Ee)).load(qt.features):Ee.dynamic?this._dynamicIndex:function(Yt,ls){return new on(Yt,ls)}(qt,Ee.geojsonVtOptions)}catch(Yt){return He(Yt)}const ss={};if(jt){const Yt=d(ot);Yt&&(ss.resourceTiming={},ss.resourceTiming[Ee.source]=JSON.parse(JSON.stringify(Yt)))}He(null,ss)}})}reloadTile(Ee,He){const ot=this.loaded;return ot&&ot[Ee.uid]?Ee.partial?He(null,void 0):super.reloadTile(Ee,He):this.loadTile(Ee,He)}loadGeoJSON(Ee,He){if(Ee.request)c.m(Ee.request,He);else{if(typeof Ee.data!="string")return He(new Error(`Input data given to '${Ee.source}' is not a valid GeoJSON object.`));setTimeout(()=>{try{return He(null,JSON.parse(Ee.data))}catch{return He(new Error(`Input data given to '${Ee.source}' is not a valid GeoJSON object.`))}},0)}}getClusterExpansionZoom(Ee,He){try{He(null,this._geoJSONIndex.getClusterExpansionZoom(Ee.clusterId))}catch(ot){He(ot)}}getClusterChildren(Ee,He){try{He(null,this._geoJSONIndex.getChildren(Ee.clusterId))}catch(ot){He(ot)}}getClusterLeaves(Ee,He){try{He(null,this._geoJSONIndex.getLeaves(Ee.clusterId,Ee.limit,Ee.offset))}catch(ot){He(ot)}}}class _r{constructor(Ee,He,ot){this.tileID=new c.aR(Ee.tileID.overscaledZ,Ee.tileID.wrap,Ee.tileID.canonical.z,Ee.tileID.canonical.x,Ee.tileID.canonical.y),this.tileZoom=Ee.tileZoom,this.uid=Ee.uid,this.zoom=Ee.zoom,this.canonical=Ee.tileID.canonical,this.pixelRatio=Ee.pixelRatio,this.tileSize=Ee.tileSize,this.source=Ee.source,this.overscaling=this.tileID.overscaleFactor(),this.projection=Ee.projection,this.brightness=He,this.worldview=ot}parse(Ee,He,ot,jt){this.status="parsing";const Dt=new c.aR(ot.tileID.overscaledZ,ot.tileID.wrap,ot.tileID.canonical.z,ot.tileID.canonical.x,ot.tileID.canonical.y),qt=[],ss=He.familiesBySource[ot.source],Yt=new c.ff(Dt,ot.promoteId);Yt.bucketLayerIDs=[],Yt.is3DTile=!0,c.fB(Ee).then(ls=>{const Xs=ls.json.extensionsUsed&&ls.json.extensionsUsed.includes("MAPBOX_mesh_features")||ls.json.asset.extras&&ls.json.asset.extras.MAPBOX_mesh_features,Rs=ls.json.extensionsUsed&&ls.json.extensionsUsed.includes("EXT_meshopt_compression"),Er=new c.ae(this.zoom,{brightness:this.brightness,worldview:this.worldview});for(const ln in ss)for(const mn of ss[ln]){const Gr=mn[0];Yt.bucketLayerIDs.push(mn.map(Sn=>c.F(Sn.id,Sn.scope))),Gr.recalculate(Er,[]);const fn=c.fC(ls,1/c.cS(ot.tileID.canonical)),pn=new c.fD(mn,fn,Dt,Xs,Rs,this.brightness,Yt,this.worldview);Xs||(pn.needsUpload=!0),qt.push(pn),pn.evaluate(Gr)}this.status="done",jt(null,{buckets:qt,featureIndex:Yt,collisionBoxArray:null,glyphAtlasImage:null,lineAtlas:null,imageAtlas:null,brightness:null})}).catch(ls=>jt(new Error(ls.message)))}}class Hr{constructor({actor:Ee,layerIndex:He,availableImages:ot,availableModels:jt,brightness:Dt,worldview:qt}){this.actor=Ee,this.layerIndex=He,this.availableImages=ot,this.availableModels=jt,this.brightness=Dt,this.loading={},this.loaded={},this.worldview=qt}loadTile(Ee,He){const ot=Ee.uid,jt=this.loading[ot]=new _r(Ee,this.brightness,this.worldview);c.b1(Ee.request,(Dt,qt)=>{const ss=!this.loading[ot];return delete this.loading[ot],ss||Dt?(jt.status="done",ss||(this.loaded[ot]=jt),He(Dt)):qt&&qt.byteLength!==0?void jt.parse(qt,this.layerIndex,Ee,(Yt,ls)=>{jt.status="done",this.loaded=this.loaded||{},this.loaded[ot]=jt,Yt||!ls?He(Yt):He(null,ls)}):(jt.status="done",this.loaded[ot]=jt,He())})}reloadTile(Ee,He){const ot=this.loaded,jt=Ee.uid;if(ot&&ot[jt]){const Dt=ot[jt];Dt.projection=Ee.projection,Dt.brightness=Ee.brightness;const qt=(ss,Yt)=>{Dt.reloadCallback&&(delete Dt.reloadCallback,this.loadTile(Ee,He)),He(ss,Yt)};Dt.status==="parsing"?Dt.reloadCallback=qt:Dt.status==="done"&&this.loadTile(Ee,He)}}abortTile(Ee,He){const ot=Ee.uid;this.loading[ot]&&delete this.loading[ot],He()}removeTile(Ee,He){const ot=this.loaded,jt=Ee.uid;ot&&ot[jt]&&delete ot[jt],He()}}const _a=new Map,Jt=new Map;class Cr{constructor(Ee){this.self=Ee,this.actor=new c.A(Ee,this),this.layerIndexes={},this.availableImages={},this.availableModels={},this.isSpriteLoaded={},this.imageRasterizer=new c.z,this.rtlPluginParsingListeners=[],this.projections={},this.defaultProjection=c.c0({name:"mercator"}),this.workerSourceTypes={vector:O,geojson:vn,"raster-dem":$,"raster-array":Z,"batched-model":Hr},this.workerSources={},this.self.registerWorkerSource=(He,ot)=>{if(this.workerSourceTypes[He])throw new Error(`Worker source with name "${He}" already registered.`);this.workerSourceTypes[He]=ot},this.self.registerRTLTextPlugin=He=>{if(c.fF.isParsed())throw new Error("RTL text plugin already registered.");c.fF.setState({pluginStatus:c.fG.parsed,pluginURL:c.fF.getPluginURL()}),c.fF.applyArabicShaping=He.applyArabicShaping,c.fF.processBidirectionalText=He.processBidirectionalText,c.fF.processStyledBidirectionalText=He.processStyledBidirectionalText;for(const ot of this.rtlPluginParsingListeners)ot(null,!0);this.rtlPluginParsingListeners=[]}}clearCaches(Ee,He,ot){delete this.layerIndexes[Ee],delete this.availableImages[Ee],delete this.availableModels[Ee],delete this.workerSources[Ee],ot()}checkIfReady(Ee,He,ot){ot()}setReferrer(Ee,He){this.referrer=He}spriteLoaded(Ee,He){this.isSpriteLoaded[Ee]||(this.isSpriteLoaded[Ee]={});const{scope:ot,isLoaded:jt}=He;if(this.isSpriteLoaded[Ee][ot]=jt,this.workerSources[Ee]&&this.workerSources[Ee][ot])for(const Dt in this.workerSources[Ee][ot]){const qt=this.workerSources[Ee][ot][Dt];for(const ss in qt){const Yt=qt[ss];Yt instanceof O&&(Yt.isSpriteLoaded=jt,Yt.fire(new c.C("isSpriteLoaded")))}}}setImages(Ee,He,ot){this.availableImages[Ee]||(this.availableImages[Ee]={});const{scope:jt,images:Dt}=He;if(this.availableImages[Ee][jt]=Dt,this.workerSources[Ee]&&this.workerSources[Ee][jt]){for(const qt in this.workerSources[Ee][jt]){const ss=this.workerSources[Ee][jt][qt];for(const Yt in ss)ss[Yt].availableImages=Dt}ot()}else ot()}setModels(Ee,{scope:He,models:ot},jt){if(this.availableModels[Ee]||(this.availableModels[Ee]={}),this.availableModels[Ee][He]=ot,this.workerSources[Ee]&&this.workerSources[Ee][He]){for(const Dt in this.workerSources[Ee][He]){const qt=this.workerSources[Ee][He][Dt];for(const ss in qt)qt[ss].availableModels=ot}jt()}else jt()}setProjection(Ee,He){this.projections[Ee]=c.c0(He)}setBrightness(Ee,He,ot){this.brightness=He,ot()}setContextParams(Ee,He,ot){this.maxUniformBufferBindings=He.maxBindingPoints,this.maxUniformBlockSizeDwords=He.maxUniformBlockSizeDwords,this.disableSymbolUBO=He.disableSymbolUBO,ot()}setWorldview(Ee,He,ot){this.worldview=He,ot()}setLayers(Ee,He,ot){this.getLayerIndex(Ee,He.scope).replace(He.layers,He.options),ot()}updateLayers(Ee,He,ot){this.getLayerIndex(Ee,He.scope).update(He.layers,He.removedIds,He.options),ot()}loadTile(Ee,He,ot){He.projection=this.projections[Ee]||this.defaultProjection,this.getWorkerSource(Ee,He).loadTile(He,ot)}decodeRasterArray(Ee,He,ot){this.getWorkerSource(Ee,He).decodeRasterArray(He,ot)}reloadTile(Ee,He,ot){He.projection=this.projections[Ee]||this.defaultProjection,this.getWorkerSource(Ee,He).reloadTile(He,ot)}abortTile(Ee,He,ot){this.getWorkerSource(Ee,He).abortTile(He,ot)}removeTile(Ee,He,ot){this.getWorkerSource(Ee,He).removeTile(He,ot)}removeSource(Ee,He,ot){if(!(this.workerSources[Ee]&&this.workerSources[Ee][He.scope]&&this.workerSources[Ee][He.scope][He.type]&&this.workerSources[Ee][He.scope][He.type][He.source]))return;const jt=this.workerSources[Ee][He.scope][He.type][He.source];delete this.workerSources[Ee][He.scope][He.type][He.source],jt.removeSource!==void 0?jt.removeSource(He,ot):ot()}loadTileProvider(Ee,He,ot){(async function(jt,Dt){const qt=Jt.get(jt);if(qt)return qt;const ss=_a.get(jt);if(ss!==void 0)return ss;const Yt=import(Dt).then(ls=>{const Xs=ls.default;if(typeof Xs!="function")throw new Error(`TileProvider "${jt}" module must default-export a class`);if(typeof Xs.prototype.loadTile!="function")throw new Error(`TileProvider "${jt}" class must have a loadTile method`);return Jt.set(jt,Xs),Xs}).finally(()=>{_a.delete(jt)});return _a.set(jt,Yt),Yt})(He.name,He.url).then(jt=>{const Dt=new jt(He.options);return this.getWorkerSource(Ee,{type:He.type,source:He.source,scope:He.scope},Dt),Dt.load&&He.request?Dt.load({request:He.request}):null}).then(jt=>ot(null,jt)).catch(jt=>ot(jt instanceof Error?jt:new Error(typeof jt=="string"?jt:"Unknown error")))}loadWorkerSource(Ee,He,ot){try{this.self.importScripts(He.url),ot()}catch(jt){ot(jt)}}syncRTLPluginState(Ee,He,ot){if(c.fF.isParsed())ot(null,!0);else if(c.fF.isParsing())this.rtlPluginParsingListeners.push(ot);else try{c.fF.setState(He);const jt=c.fF.getPluginURL();!c.fF.isLoaded()||c.fF.isParsed()||c.fF.isParsing()||jt==null||(c.fF.setState({pluginStatus:c.fG.parsing,pluginURL:c.fF.getPluginURL()}),this.self.importScripts(jt),c.fF.isParsed()?ot(null,!0):this.rtlPluginParsingListeners.push(ot))}catch(jt){ot(jt)}}setConfig(Ee,He){Object.assign(c.g,He)}getAvailableImages(Ee,He){this.availableImages[Ee]||(this.availableImages[Ee]={});let ot=this.availableImages[Ee][He];return ot||(ot=[]),ot}getAvailableModels(Ee,He){this.availableModels[Ee]||(this.availableModels[Ee]={});let ot=this.availableModels[Ee][He];return ot||(ot={}),ot}getLayerIndex(Ee,He){this.layerIndexes[Ee]||(this.layerIndexes[Ee]={});let ot=this.layerIndexes[Ee][He];return ot||(ot=this.layerIndexes[Ee][He]=new x,ot.scope=He),ot}getWorkerSource(Ee,He,ot){const{type:jt,source:Dt,scope:qt}=He,ss=this.workerSources;if(ss[Ee]||(ss[Ee]={}),ss[Ee][qt]||(ss[Ee][qt]={}),ss[Ee][qt][jt]||(ss[Ee][qt][jt]={}),this.isSpriteLoaded[Ee]||(this.isSpriteLoaded[Ee]={}),!ss[Ee][qt][jt][Dt]){const Yt={send:(Xs,Rs,Er,ln,mn,Gr)=>this.actor.send(Xs,Rs,Er,Ee,mn,Gr),scheduler:this.actor.scheduler},ls=this.workerSourceTypes[jt];if(!ls)throw new Error(`Unknown worker source type "${jt}".`);ss[Ee][qt][jt][Dt]=new ls({actor:Yt,layerIndex:this.getLayerIndex(Ee,qt),availableImages:this.getAvailableImages(Ee,qt),availableModels:this.getAvailableModels(Ee,qt),isSpriteLoaded:this.isSpriteLoaded[Ee][qt],tileProvider:ot,brightness:this.brightness,worldview:this.worldview,maxUniformBufferBindings:this.maxUniformBufferBindings,maxUniformBlockSizeDwords:this.maxUniformBlockSizeDwords,disableSymbolUBO:this.disableSymbolUBO})}return ss[Ee][qt][jt][Dt]}rasterizeImagesWorker(Ee,He,ot){const jt=new Map;for(const[Dt,{image:qt,imageVariant:ss}]of He.tasks.entries()){const Yt=this.imageRasterizer.rasterize(ss,qt,He.scope,Ee);jt.set(Dt,Yt)}ot(void 0,jt)}removeRasterizedImages(Ee,He,ot){this.imageRasterizer.removeImagesFromCacheByIds(He.imageIds,He.scope,Ee),ot()}enforceCacheSizeLimit(Ee,He){c.fH(He)}getWorkerPerformanceMetrics(Ee,He,ot){ot(void 0,void 0)}}return c.fE(self)&&(self.worker=new Cr(self)),Cr}),i(["./shared"],function(o){var c="3.22.0";const d={create:"create",load:"load",fullLoad:"fullLoad"},h={mark(M){performance.mark(M)},measure(M,g,N){performance.measure(M,g,N)}};function m(M){const g=M.name.split("?")[0];return o.a(g)&&g.includes("mapbox-gl.js")?"javascript":o.a(g)&&g.includes("mapbox-gl.css")?"css":o.b(g)?"fontRange":o.c(g)?"sprite":o.i(g)?"style":o.d(g)?"tilejson":"other"}var p,x={},y=function(){if(p)return x;function M(P){return!g(P)}function g(P){return typeof window>"u"||typeof document>"u"?"not a browser":function(){if(!("Worker"in window&&"Blob"in window&&"URL"in window))return!1;var q,G,Q=new Blob([""],{type:"text/javascript"}),ae=URL.createObjectURL(Q);try{G=new Worker(ae),q=!0}catch{q=!1}return G&&G.terminate(),URL.revokeObjectURL(ae),q}()?function(){var q=document.createElement("canvas");q.width=q.height=1;var G=q.getContext("2d");if(!G)return!1;var Q=G.getImageData(0,0,1,1);return Q&&Q.width===q.width}()?(N[F=P&&P.failIfMajorPerformanceCaveat]===void 0&&(N[F]=function(q){var G,Q=function(ae){var me=document.createElement("canvas"),ye=Object.create(M.webGLContextAttributes);return ye.failIfMajorPerformanceCaveat=ae,me.getContext("webgl2",ye)}(q);if(!Q)return!1;try{G=Q.createShader(Q.VERTEX_SHADER)}catch{return!1}return!(!G||Q.isContextLost())&&(Q.shaderSource(G,"void main() {}"),Q.compileShader(G),Q.getShaderParameter(G,Q.COMPILE_STATUS)===!0)}(F)),N[F]?document.documentMode?"insufficient ECMAScript 6 support":void 0:"insufficient WebGL2 support"):"insufficient Canvas/getImageData support":"insufficient worker support";var F}p=1,x.supported=M,x.notSupportedReason=g;var N={};return M.webGLContextAttributes={antialias:!1,alpha:!0,stencil:!0,depth:!0},x}();function _(M,g,N){const P=document.createElement(M);return g!=null&&(P.className=g),N&&N.appendChild(P),P}function b(M,g,N){const P=document.createElementNS("http://www.w3.org/2000/svg",M);for(const F of Object.keys(g))P.setAttributeNS(null,F,String(g[F]));return N&&N.appendChild(P),P}const j=typeof document<"u"?document.documentElement&&document.documentElement.style:null,k=j&&j.userSelect!==void 0?"userSelect":"WebkitUserSelect";let T;function E(){j&&k&&(T=j[k],j[k]="none")}function A(){j&&k&&(j[k]=T)}function D(M){M.preventDefault(),M.stopPropagation(),window.removeEventListener("click",D,!0)}function R(){window.addEventListener("click",D,!0),window.setTimeout(()=>{window.removeEventListener("click",D,!0)},0)}function z(M,g){const N=M.getBoundingClientRect();return ee(M,N,g)}function O(M,g){const N=M.getBoundingClientRect(),P=[];for(let F=0;Fthis._skuTokenExpiresAt}transformRequest(g,N){return this._transformRequestFn&&this._transformRequestFn(g,N)||{url:g}}normalizeStyleURL(g,N){if(!o.e(g))return g;const P=ie(g);return P.params.push(`sdk=js-${c}`),P.path=`/styles/v1${P.path}`,this._makeAPIURL(P,this._customAccessToken||N)}normalizeGlyphsURL(g,N){if(!o.e(g))return g;const P=ie(g);return P.path=`/fonts/v1${P.path}`,this._makeAPIURL(P,this._customAccessToken||N)}normalizeModelURL(g,N){if(!o.e(g))return g;const P=ie(g);return P.path=`/models/v1${P.path}`,this._makeAPIURL(P,this._customAccessToken||N)}normalizeSourceURL(g,N,P,F){if(!o.e(g))return g;const q=ie(g);return q.path=`/v4/${q.authority}.json`,q.params.push("secure"),P&&q.params.push(`language=${P}`),F&&q.params.push(`worldview=${F}`),this._makeAPIURL(q,this._customAccessToken||N)}normalizeIconsetURL(g,N){const P=ie(g);return o.e(g)?(P.path=`/styles/v1${P.path}/iconset.pbf`,this._makeAPIURL(P,this._customAccessToken||N)):ce(P)}normalizeSpriteURL(g,N,P,F){const q=ie(g);return o.e(g)?(q.path=`/styles/v1${q.path}/sprite${N}${P}`,this._makeAPIURL(q,this._customAccessToken||F)):(q.path+=`${N}${P}`,ce(q))}normalizeTileURL(g,N,P){if(this._isSkuTokenExpired()&&this._createSkuToken(),g&&!o.e(g))return g;const F=ie(g);F.path=F.path.replace(/(\.(png|jpg)\d*)(?=$)/,`${N||P&&F.authority!=="raster"&&P===512?"@2x":""}${o.k.supported?".webp":"$1"}`),F.authority==="raster"?F.path=`/${o.g.RASTER_URL_PREFIX}${F.path}`:F.authority==="rasterarrays"?F.path=`/${o.g.RASTERARRAYS_URL_PREFIX}${F.path}`:F.authority==="3dtiles"?F.path=`/${o.g.TILES3D_URL_PREFIX}${F.path}`:(F.path=F.path.replace(/^.+\/v4\//,"/"),F.path=`/${o.g.TILE_URL_VERSION}${F.path}`);const q=this._customAccessToken||function(G){for(const Q of G){const ae=Q.match(/^access_token=(.*)$/);if(ae)return ae[1]}return null}(F.params)||o.g.ACCESS_TOKEN;return o.g.REQUIRE_ACCESS_TOKEN&&q&&this._skuToken&&F.params.push(`sku=${this._skuToken}`),this._makeAPIURL(F,q)}canonicalizeTileURL(g,N){const P=ie(g);if(!P.path.match(/^(\/v4\/|\/(raster|rasterarrays)\/v1\/)/)||!P.path.match(/\.[\w]+$/))return g;let F="mapbox://";P.path.match(/^\/raster\/v1\//)?F+=`raster/${P.path.replace(`/${o.g.RASTER_URL_PREFIX}/`,"")}`:P.path.match(/^\/rasterarrays\/v1\//)?F+=`rasterarrays/${P.path.replace(`/${o.g.RASTERARRAYS_URL_PREFIX}/`,"")}`:F+=`tiles/${P.path.replace(`/${o.g.TILE_URL_VERSION}/`,"")}`;let q=P.params;return N&&(q=q.filter(G=>!G.match(/^access_token=/))),q.length&&(F+=`?${q.join("&")}`),F}canonicalizeTileset(g,N){const P=!!N&&o.e(N),F=[];for(const q of g.tiles||[])o.f(q)?F.push(this.canonicalizeTileURL(q,P)):F.push(q);return F}_makeAPIURL(g,N){const P="See https://docs.mapbox.com/api/overview/#access-tokens-and-token-scopes",F=ie(o.g.API_URL);if(g.protocol=F.protocol,g.authority=F.authority,g.protocol==="http"){const q=g.params.indexOf("secure");q>=0&&g.params.splice(q,1)}if(F.path!=="/"&&(g.path=`${F.path}${g.path}`),!o.g.REQUIRE_ACCESS_TOKEN)return ce(g);if(N=N||o.g.ACCESS_TOKEN,!this._silenceAuthErrors){if(!N)throw new Error(`An API access token is required to use Mapbox GL. ${P}`);if(N[0]==="s")throw new Error(`Use a public access token (pk.*) with Mapbox GL, not a secret access token (sk.*). ${P}`)}return g.params=g.params.filter(q=>q.indexOf("access_token")===-1),g.params.push(`access_token=${N||""}`),ce(g)}}const re=/^(\w+):\/\/([^/?]*)(\/[^?]+)?\??(.+)?/;function ie(M){const g=M.match(re);if(!g)throw new Error("Unable to parse URL object");return{protocol:g[1],authority:g[2],path:g[3]||"/",params:g[4]?g[4].split("&"):[]}}function ce(M){const g=M.params.length?`?${M.params.join("&")}`:"";return`${M.protocol}://${M.authority}${M.path}${g}`}const ne="mapbox.eventData";function le(M){if(!M)return null;const g=M.split(".");if(!g||g.length!==3)return null;try{return JSON.parse(o.l(g[1]))}catch{return null}}function be(M){return!(!o.g.EVENTS_URL||!M&&!o.g.ACCESS_TOKEN)}class fe{constructor(g){this.type=g,this.anonId=null,this.anonIdTimestamp=null,this.eventData={},this.queue=[],this.pendingRequest=null}getStorageKey(g){const N=le(o.g.ACCESS_TOKEN);let P="";return P=N&&N.u?o.j(N.u):o.g.ACCESS_TOKEN||"",g?`${ne}.${g}:${P}`:`${ne}:${P}`}fetchEventData(){const g=o.s("localStorage"),N=this.getStorageKey(),P=this.getStorageKey("uuid"),F=this.getStorageKey("uuidTimestamp");if(g)try{const q=localStorage.getItem(N);q&&(this.eventData=JSON.parse(q));const G=localStorage.getItem(P);G&&(this.anonId=G);const Q=localStorage.getItem(F);Q&&(this.anonIdTimestamp=Number(Q));const ae=Date.now()-864e5;(!this.anonIdTimestamp||this.anonIdTimestamp=1&&localStorage.setItem(N,JSON.stringify(this.eventData)),G&&localStorage.setItem(F,G.toString())}catch{o.w("Unable to write to LocalStorage")}}processRequests(g){}postEvent(g,N,P,F){if(!o.g.EVENTS_URL)return;const q=ie(o.g.EVENTS_URL);q.params.push(`access_token=${F||o.g.ACCESS_TOKEN||""}`);const G={event:this.type,created:new Date(g).toISOString()},Q=N?Object.assign(G,N):G,ae={url:ce(q),headers:{"Content-Type":"text/plain"},body:JSON.stringify([Q])};this.pendingRequest=o.p(ae,me=>{this.pendingRequest=null,P(me),this.saveEventData(),this.processRequests(F)})}queueRequest(g,N){this.queue.push(g),this.processRequests(N)}}class je extends fe{constructor(g){super("metrics"),g&&(this.data=g)}postMetricsEvent(g){if(!be(g))return;this.anonId||this.fetchEventData(),o.v(this.anonId)||this.refreshUUID();const N=Object.assign({},this.data,{sessionId:this.anonId});this.queueRequest({timestamp:Date.now(),payload:N},g)}processRequests(g){if(this.pendingRequest||this.queue.length===0)return;const{timestamp:N,payload:P}=this.queue.shift();this.postEvent(N,P,()=>{},g)}}const ve=new class extends fe{constructor(M){super("appUserTurnstile"),this._customAccessToken=M}postTurnstileEvent(M,g){be(g)&&Array.isArray(M)&&M.some(N=>o.e(N)||o.f(N))&&this.queueRequest(Date.now(),g)}processRequests(M){if(this.pendingRequest||this.queue.length===0)return;this.anonId&&this.anonIdTimestamp&&this.eventData.lastSuccess&&this.eventData.tokenU||this.fetchEventData();const g=le(o.g.ACCESS_TOKEN),N=g?g.u:o.g.ACCESS_TOKEN;let P=N!==this.eventData.tokenU;o.v(this.anonId)||(this.refreshUUID(),P=!0);const F=this.queue.shift();if(this.eventData.lastSuccess){const q=new Date(this.eventData.lastSuccess),G=new Date(F),Q=(F-this.eventData.lastSuccess)/864e5;P=P||Q>=1||Q<-1||q.getDate()!==G.getDate()}else P=!0;P?this.postEvent(F,{sdkIdentifier:"mapbox-gl-js",sdkVersion:c,skuId:Z,"enabled.telemetry":!1,userId:this.anonId},q=>{q||(this.eventData.lastSuccess=F,this.eventData.tokenU=N)},M):this.processRequests()}},We=ve.postTurnstileEvent.bind(ve),Ve=new class extends fe{constructor(){super("map.load"),this.success={},this.skuToken=""}postMapLoadEvent(M,g,N,P){this.skuToken=g,this.errorCb=P,o.g.EVENTS_URL&&(N||o.g.ACCESS_TOKEN?this.queueRequest({id:M,timestamp:Date.now()},N):this.errorCb(new Error(J)))}processRequests(M){if(this.pendingRequest||this.queue.length===0)return;const{id:g,timestamp:N}=this.queue.shift();g&&this.success[g]||(this.anonId&&this.anonIdTimestamp||this.fetchEventData(),o.v(this.anonId)||this.refreshUUID(),this.postEvent(N,{sdkIdentifier:"mapbox-gl-js",sdkVersion:c,skuId:Z,skuToken:this.skuToken,userId:this.anonId},P=>{P?this.errorCb(P):g&&(this.success[g]=!0)},M))}remove(){this.errorCb=null}},Le=Ve.postMapLoadEvent.bind(Ve),Me=new class extends fe{constructor(){super("style.load"),this.eventIdPerMapInstanceMap=new Map,this.mapInstanceIdMap=new WeakMap}getMapInstanceId(M){let g=this.mapInstanceIdMap.get(M);return g||(g=o.u(),this.mapInstanceIdMap.set(M,g)),g}getEventId(M){const g=this.eventIdPerMapInstanceMap.get(M)||0;return this.eventIdPerMapInstanceMap.set(M,g+1),g}postStyleLoadEvent(M,g){const{map:N,style:P,importedStyles:F}=g;if(!be(M))return;const q=this.getMapInstanceId(N),G={mapInstanceId:q,eventId:this.getEventId(q),style:P};F.length&&(G.importedStyles=F),this.queueRequest({timestamp:Date.now(),payload:G},M)}processRequests(M){if(this.pendingRequest||this.queue.length===0)return;const{timestamp:g,payload:N}=this.queue.shift();this.postEvent(g,N,()=>{},M)}},ze=Me.postStyleLoadEvent.bind(Me),Pe=new je({attributes:[{name:"maps/js/layer-animations/style-with-appearances"}]}),Ie=Pe.postMetricsEvent.bind(Pe),De=new je({attributes:[{name:"maps/js/layer-animations/runtime-appearances"}]}),pe=De.postMetricsEvent.bind(De),tt=new class extends fe{constructor(){super("gljs.performance")}postPerformanceEvent(M,g){be(M)&&this.queueRequest({timestamp:Date.now(),performanceData:g},M)}processRequests(M){if(this.pendingRequest||this.queue.length===0)return;const{timestamp:g,performanceData:N}=this.queue.shift(),P=function(F){const q=performance.getEntriesByType("resource"),G=performance.getEntriesByType("mark"),Q=function(Fe){const Ye={};if(Fe){for(const Ge in Fe)if(Ge!=="other")for(const dt of Fe[Ge]){const lt=`${Ge}ResolveRangeMin`,_t=`${Ge}ResolveRangeMax`,Ct=`${Ge}RequestCount`,ht=`${Ge}RequestCachedCount`;Ye[lt]=Math.min(Ye[lt]||1/0,dt.startTime),Ye[_t]=Math.max(Ye[_t]||-1/0,dt.responseEnd);const Kt=Lt=>{Ye[Lt]===void 0&&(Ye[Lt]=0),++Ye[Lt]};dt.transferSize!==void 0&&dt.transferSize===0&&Kt(ht),Kt(Ct)}}return Ye}(function(Fe,Ye){const Ge={};if(Fe)for(const dt of Fe){const lt=Ye(dt);Ge[lt]===void 0&&(Ge[lt]=[]),Ge[lt].push(dt)}return Ge}(q,m)),ae=window.devicePixelRatio,me=navigator.connection||navigator.mozConnection||navigator.webkitConnection,ye=me?me.effectiveType:void 0,Ae={counters:[],metadata:[],attributes:[]},Te=(Fe,Ye,Ge)=>{Ge!=null&&Fe.push({name:Ye,value:Ge.toString()})};for(const Fe in Q)Te(Ae.counters,Fe,Q[Fe]);if(F.interactionRange[0]!==1/0&&F.interactionRange[1]!==-1/0&&(Te(Ae.counters,"interactionRangeMin",F.interactionRange[0]),Te(Ae.counters,"interactionRangeMax",F.interactionRange[1])),G)for(const Fe of Object.values(d)){const Ye=G.find(Ge=>Ge.name===Fe);Ye&&Te(Ae.counters,Fe,Ye.startTime)}return Te(Ae.counters,"visibilityHidden",F.visibilityHidden),Te(Ae.attributes,"style",function(Fe){if(Fe)for(const Ye of Fe){const Ge=Ye.name.split("?")[0];if(o.i(Ge)){const dt=Ge.split("/").slice(-2);if(dt.length===2)return`mapbox://styles/${dt[0]}/${dt[1]}`}}}(q)),Te(Ae.attributes,"terrainEnabled",F.terrainEnabled?"true":"false"),Te(Ae.attributes,"fogEnabled",F.fogEnabled?"true":"false"),Te(Ae.attributes,"projection",F.projection),Te(Ae.attributes,"zoom",F.zoom),Te(Ae.metadata,"devicePixelRatio",ae),Te(Ae.metadata,"connectionEffectiveType",ye),Te(Ae.metadata,"navigatorUserAgent",navigator.userAgent),Te(Ae.metadata,"screenWidth",window.screen.width),Te(Ae.metadata,"screenHeight",window.screen.height),Te(Ae.metadata,"windowWidth",window.innerWidth),Te(Ae.metadata,"windowHeight",window.innerHeight),Te(Ae.metadata,"mapWidth",F.width/ae),Te(Ae.metadata,"mapHeight",F.height/ae),Te(Ae.metadata,"webglRenderer",F.renderer),Te(Ae.metadata,"webglVendor",F.vendor),Te(Ae.metadata,"sdkVersion",c),Te(Ae.metadata,"sdkIdentifier","mapbox-gl-js"),Ae}(N);for(const F of P.metadata);for(const F of P.counters);for(const F of P.attributes);this.postEvent(g,P,()=>{},M)}},ge=tt.postPerformanceEvent.bind(tt),ct=new class extends fe{constructor(){super("map.auth"),this.success={},this.skuToken=""}getSession(M,g,N,P){if(!o.g.API_URL||!o.g.SESSION_PATH)return;const F=ie(o.g.API_URL+o.g.SESSION_PATH);F.params.push(`sku=${g||""}`),F.params.push(`access_token=${P||o.g.ACCESS_TOKEN||""}`);const q={url:ce(F),headers:{"Content-Type":"text/plain"}};this.pendingRequest=o.h(q,G=>{this.pendingRequest=null,N(G),this.saveEventData(),this.processRequests(P)})}getSessionAPI(M,g,N,P){this.skuToken=g,this.errorCb=P,o.g.EVENTS_URL&&o.g.SESSION_PATH&&o.g.API_URL&&(N||o.g.ACCESS_TOKEN?this.queueRequest({id:M,timestamp:Date.now()},N):this.errorCb(new Error(J)))}processRequests(M){if(this.pendingRequest||this.queue.length===0)return;const{id:g,timestamp:N}=this.queue.shift();g&&this.success[g]||this.getSession(N,this.skuToken,P=>{P?this.errorCb(P):g&&(this.success[g]=!0)},M)}remove(){this.errorCb=null}},Ue=ct.getSessionAPI.bind(ct),et=new Set;function Qe(M,g){g?et.add(M):et.delete(M)}class Ne{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(g,N){this._updatedSourceCaches[g]=N,this.setDirty()}discardSourceCacheUpdate(g){delete this._updatedSourceCaches[g]}updateLayer(g){const N=g.scope;this._updatedLayers[N]=this._updatedLayers[N]||new Set,this._updatedLayers[N].add(g.id),this.setDirty()}removeLayer(g){const N=g.scope;this._removedLayers[N]=this._removedLayers[N]||{},this._updatedLayers[N]=this._updatedLayers[N]||new Set,this._removedLayers[N][g.id]=g,this._updatedLayers[N].delete(g.id),this._updatedPaintProps.delete(g.fqid),this.setDirty()}getRemovedLayer(g){return this._removedLayers[g.scope]?this._removedLayers[g.scope][g.id]:null}discardLayerRemoval(g){this._removedLayers[g.scope]&&delete this._removedLayers[g.scope][g.id]}getLayerUpdatesByScope(){const g={};for(const N in this._updatedLayers)g[N]=g[N]||{},g[N].updatedIds=Array.from(this._updatedLayers[N].values());for(const N in this._removedLayers)g[N]=g[N]||{},g[N].removedIds=Object.keys(this._removedLayers[N]);return g}getUpdatedPaintProperties(){return this._updatedPaintProps}updatePaintProperties(g){this._updatedPaintProps.add(g.fqid),this.setDirty()}getUpdatedImages(g){return this._updatedImages[g]?Array.from(this._updatedImages[g].values()):[]}updateImage(g,N){this._updatedImages[N]=this._updatedImages[N]||new Set,this._updatedImages[N].add(o.I.toString(g)),this.setDirty()}resetUpdatedImages(g){this._updatedImages[g]&&this._updatedImages[g].clear()}reset(){this._changed=!1,this._updatedLayers={},this._removedLayers={},this._updatedSourceCaches={},this._updatedPaintProps.clear(),this._updatedImages={}}}function $e(M){const{userImage:g}=M;return!!(g&&g.render&&g.render())&&(M.data.replace(new Uint8Array(g.data.buffer)),!0)}const it={workerUrl:"",workerClass:null,workerParams:void 0};function Je(M){return it.workerClass!=null?new it.workerClass:new self.Worker(it.workerUrl,Object.assign({name:M},it.workerParams))}const st="mapboxgl_preloaded_worker_pool";class mt{constructor(g){this.active={},this.name=g}acquire(g,N=mt.workerCount){if(!this.workers)for(this.workers=[];this.workers.length{N.terminate()}),this.workers=null)}isPreloaded(){return!!this.active[st]}numActive(){return Object.keys(this.active).length}}mt.workerCount=2;class wt{constructor(g,N,P="Worker",F=mt.workerCount){this.workerPool=g,this.actors=[],this.currentActor=0,this.id=o.r();const q=this.workerPool.acquire(this.id,F);for(let G=0;G{this.ready=!0})}broadcast(g,N,P){o.t(this.actors,(F,q)=>{F.send(g,N,q)},P=P||function(){})}getActor(){return this.currentActor=(this.currentActor+1)%this.actors.length,this.actors[this.currentActor]}remove(){this.actors.forEach(g=>{g.remove()}),this.actors=[],this.workerPool.release(this.id)}}let at,rt;function Et(){return at||(at=new mt),at}wt.Actor=o.A;class hs extends o.E{constructor(g){super(),this.imageProviders=new Map,this.images=new Map,this.updatedImages=new Map,this.callbackDispatchedThisFrame=new Map,this.imageVersions=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.imageAtlasCache=new o.x,this.dirty=!0,this.spriteFormat=g,g!=="raster"&&o.y()&&(this.imageRasterizerDispatcher=new wt((rt||(rt=new mt("ImageRasterizer")),rt),this,"Image Rasterizer Worker",1))}addScope(g){this.loaded.set(g,!1),this.imageProviders.set(g,new Map),this.images.set(g,new Map),this.updatedImages.set(g,new Set),this.callbackDispatchedThisFrame.set(g,new Set),this.imageVersions.set(g,new Map),this.patterns.set(g,new Map),this.atlasImage.set(g,new o.q({width:1,height:1}))}removeScope(g){this.loaded.delete(g),this.imageProviders.delete(g),this.images.delete(g),this.updatedImages.delete(g),this.callbackDispatchedThisFrame.delete(g),this.imageVersions.delete(g),this.patterns.delete(g),this.atlasImage.delete(g);const N=this.atlasTexture.get(g);N&&(N.destroy(),this.atlasTexture.delete(g))}addImageProvider(g,N){this.imageProviders.has(N)||this.imageProviders.set(N,new Map),this.imageProviders.get(N).set(g.id,g)}removeImageProvider(g,N){this.imageProviders.has(N)&&this.imageProviders.get(N).delete(g)}getPendingImageProviders(){const g=[];for(const N of this.imageProviders.values())for(const P of N.values())P.hasPendingRequests()&&g.push(P);return g}get imageRasterizer(){return this._imageRasterizer||(this._imageRasterizer=new o.z),this._imageRasterizer}isLoaded(){for(const g of this.loaded.keys())if(!this.loaded.get(g))return!1;return!0}setLoaded(g,N){if(this.loaded.get(N)!==g&&(this.loaded.set(N,g),g)){for(const{ids:P,callback:F}of this.requestors)this._notify(P,N,F);this.requestors=[]}}hasImage(g,N){return!!this.getImage(g,N)}getImage(g,N){return this.images.get(N).get(g.toString())}addImage(g,N,P){if(this._validate(g,P)){this.images.get(N).set(g.toString(),P);const F=this.imageVersions.get(N),q=F.get(g.toString())||0;F.set(g.toString(),q+1)}}_validate(g,N){let P=!0;return this._validateStretch(N.stretchX,N.data&&N.data.width)||(this.fire(new o.B(new Error(`Image "${g.name}" has invalid "stretchX" value`))),P=!1),this._validateStretch(N.stretchY,N.data&&N.data.height)||(this.fire(new o.B(new Error(`Image "${g.name}" has invalid "stretchY" value`))),P=!1),this._validateContent(N.content,N)||(this.fire(new o.B(new Error(`Image "${g.name}" has invalid "content" value`))),P=!1),P}_validateStretch(g,N){if(!g)return!0;let P=0;for(const F of g){if(F[0]o.I.from(N))}getImageVersions(g){const N=this.imageVersions.get(g);if(N)return N}getImages(g,N,P){const F=[],q=[],G=this.imageProviders.get(N);for(const ye of g){if(!ye.iconsetId){F.push(ye);continue}const Ae=G.get(ye.iconsetId);Ae&&(this.getImage(ye,N)?q.push(ye):Ae.addPendingRequest(ye))}if(F.length===0)return void this._notify(q,N,P);let Q=!0;const ae=!!this.loaded.get(N),me=this.images.get(N);if(!ae)for(const ye of F)me.has(ye.toString())||(Q=!1);ae||Q?this._notify(F,N,P):this.requestors.push({ids:F,scope:N,callback:P})}rasterizeImages(g,N){const P=new Map,{tasks:F,scope:q}=g;for(const[G,Q]of F.entries()){const ae=this.getImage(Q.id,q);ae&&P.set(G,{image:ae,imageVariant:Q})}this._rasterizeImages(q,P,N)}_rasterizeImages(g,N,P){if(o.y())this.imageRasterizerDispatcher.getActor().send("rasterizeImagesWorker",{tasks:N,scope:g},P);else{const F=new Map;for(const[q,{image:G,imageVariant:Q}]of N.entries())F.set(q,this.imageRasterizer.rasterize(Q,G,g,0));P(void 0,F)}}getUpdatedImages(g){return this.updatedImages.get(g)||new Set}_notify(g,N,P){const F=this.images.get(N),q=new Map;for(const G of g){if(!F.get(G.toString())){if(G.iconsetId)continue;this.fire(new o.C("styleimagemissing",{id:G.name}))}const Q=F.get(G.toString());if(!Q){o.w(`Image "${G.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 ae={data:Q.usvg?null:Q.data.clone(),pixelRatio:Q.pixelRatio,sdf:Q.sdf,usvg:Q.usvg,stretchX:Q.stretchX,stretchY:Q.stretchY,content:Q.content,hasRenderCallback:!!(Q.userImage&&Q.userImage.render)};Q.usvg&&Object.assign(ae,{width:Q.icon.usvg_tree.width,height:Q.icon.usvg_tree.height}),q.set(o.I.toString(G),ae)}P(null,{images:q,versions:this.getImageVersions(N)})}getPixelSize(g){const{width:N,height:P}=this.atlasImage.get(g);return{width:N,height:P}}getPattern(g,N,P){const F=g.toString(),q=this.patterns.get(N),G=q.get(F),Q=this.getImage(g,N);if(!Q)return null;if(G){if(G.position.version===Q.version)return G.position;G.position.version=Q.version}else{if(Q.usvg&&!Q.data){const ae=this.getPatternInFlightId(F,N);if(this.patternsInFlight.has(ae))return null;this.patternsInFlight.add(ae);const me=new o.D(g).scaleSelf(o.o.devicePixelRatio),ye=new Map([[me.toString(),{image:Q,imageVariant:me}]]);return this._rasterizeImages(N,ye,(Ae,Te)=>this.storePatternImage(me,N,Q,P,Te)),null}this.storePattern(g,N,Q)}return this._updatePatternAtlas(N,P),q.get(F).position}getPatternInFlightId(g,N){return o.F(g,N)}hasPatternsInFlight(){return this.patternsInFlight.size!==0}storePatternImage(g,N,P,F,q){const G=g.toString(),Q=q?q.get(G):void 0;Q&&(P.data=Q,this.storePattern(g.id,N,P),this._updatePatternAtlas(N,F),this.patternsInFlight.delete(this.getPatternInFlightId(g.id.toString(),N)))}storePattern(g,N,P){const F={w:P.data.width+2*o.G,h:P.data.height+2*o.G,x:0,y:0},q=new o.H(F,P,o.G);this.patterns.get(N).set(g.toString(),{bin:F,position:q})}destroyAtlasTextures(){for(const g of this.atlasTexture.values())g&&g.destroy();this.atlasTexture.clear()}bind(g,N){const P=g.gl;let F=this.atlasTexture.get(N);F?this.dirty&&(F.update(this.atlasImage.get(N)),this.dirty=!1):(F=new o.T(g,this.atlasImage.get(N),P.RGBA8),this.atlasTexture.set(N,F)),F.bind(P.LINEAR,P.CLAMP_TO_EDGE)}_updatePatternAtlas(g,N){const P=this.patterns.get(g),F=Array.from(P.values()).map(({bin:me})=>me),{w:q,h:G}=o.J(F),Q=this.atlasImage.get(g);Q.resize({width:q||1,height:G||1});const ae=this.images.get(g);for(const[me,{bin:ye,position:Ae}]of P.entries()){let Te=Ae.padding;const Fe=ye.x+Te,Ye=ye.y+Te,Ge=ae.get(me).data,dt=Ge.width,lt=Ge.height;Te=Te>1?Te-1:Te,o.q.copy(Ge,Q,{x:0,y:0},{x:Fe,y:Ye},{width:dt,height:lt},N),o.q.copy(Ge,Q,{x:0,y:lt-Te},{x:Fe,y:Ye-Te},{width:dt,height:Te},N),o.q.copy(Ge,Q,{x:0,y:0},{x:Fe,y:Ye+lt},{width:dt,height:Te},N),o.q.copy(Ge,Q,{x:dt-Te,y:0},{x:Fe-Te,y:Ye},{width:Te,height:lt},N),o.q.copy(Ge,Q,{x:0,y:0},{x:Fe+dt,y:Ye},{width:Te,height:lt},N),o.q.copy(Ge,Q,{x:dt-Te,y:lt-Te},{x:Fe-Te,y:Ye-Te},{width:Te,height:Te},N),o.q.copy(Ge,Q,{x:0,y:lt-Te},{x:Fe+dt,y:Ye-Te},{width:Te,height:Te},N),o.q.copy(Ge,Q,{x:0,y:0},{x:Fe+dt,y:Ye+lt},{width:Te,height:Te},N),o.q.copy(Ge,Q,{x:dt-Te,y:0},{x:Fe-Te,y:Ye+lt},{width:Te,height:Te},N)}this.dirty=!0}beginFrame(){for(const g of this.images.keys())this.callbackDispatchedThisFrame.set(g,new Set)}dispatchRenderCallbacks(g,N){const P=this.images.get(N);for(const F of g){if(this.callbackDispatchedThisFrame.get(N).has(F.toString()))continue;this.callbackDispatchedThisFrame.get(N).add(F.toString());const q=P.get(F.toString());$e(q)&&this.updateImage(F,N,q)}}destroy(){this.imageRasterizerDispatcher&&this.imageRasterizerDispatcher.remove()}}function Is(M){const g=M.value,N=M.valueSpec,P=M.style,F=M.styleSpec,q=M.key,G=M.arrayElementValidator||vn;if(!Array.isArray(g))return[new o.V(q,g,`array expected, ${o.M(g)} found`)];if(N.length&&g.length!==N.length)return[new o.V(q,g,`array length ${N.length} expected, length ${g.length} found`)];if(N["min-length"]&&g.lengthF)return[new o.V(g,N,`${N} is greater than the maximum value ${F}`)]}return[]}function us(M){const g=M.key,N=M.value;if(!o.K(N))return[new o.V(g,N,`object expected, ${o.M(N)} found`)];const P=M.valueSpec,F=o.L(N.type);let q,G,Q,ae={};const me=F!=="categorical"&&N.property===void 0,ye=!me,Ae=function(Ge){const dt=Ge.stops;return Array.isArray(dt)&&Array.isArray(dt[0])&&o.K(dt[0][0])}(N),Te=_r({key:M.key,value:M.value,valueSpec:M.styleSpec.function,style:M.style,styleSpec:M.styleSpec,objectElementValidators:{stops:function(Ge){if(F==="identity")return[new o.V(Ge.key,Ge.value,'identity function may not have a "stops" property')];let dt=[];const lt=Ge.value;return dt=dt.concat(Is({key:Ge.key,value:lt,valueSpec:Ge.valueSpec,style:Ge.style,styleSpec:Ge.styleSpec,arrayElementValidator:Fe})),Array.isArray(lt)&<.length===0&&dt.push(new o.V(Ge.key,lt,"array must have at least one stop")),dt},default:function(Ge){return vn({key:Ge.key,value:Ge.value,valueSpec:P,style:Ge.style,styleSpec:Ge.styleSpec})}}});return F==="identity"&&me&&Te.push(new o.V(M.key,M.value,'missing required property "property"')),F==="identity"||N.stops||Te.push(new o.V(M.key,M.value,'missing required property "stops"')),F==="exponential"&&P.expression&&!o.O(P)&&Te.push(new o.V(M.key,M.value,"exponential functions not supported")),M.styleSpec.$version>=8&&(ye&&!o.Q(P)?Te.push(new o.V(M.key,M.value,"property functions not supported")):me&&!o.S(P)&&Te.push(new o.V(M.key,M.value,"zoom functions not supported"))),F!=="categorical"&&!Ae||N.property!==void 0||Te.push(new o.V(M.key,M.value,'"property" property is required')),Te;function Fe(Ge){let dt=[];const lt=Ge.value,_t=Ge.key;if(!Array.isArray(lt))return[new o.V(_t,lt,`array expected, ${o.M(lt)} found`)];if(lt.length!==2)return[new o.V(_t,lt,`array length 2 expected, length ${lt.length} found`)];if(Ae){if(!o.K(lt[0]))return[new o.V(_t,lt,`object expected, ${o.M(lt[0])} found`)];const Ct=lt[0];if(Ct.zoom===void 0)return[new o.V(_t,lt,"object stop key must have zoom")];if(Ct.value===void 0)return[new o.V(_t,lt,"object stop key must have value")];const ht=o.L(Ct.zoom);if(typeof ht!="number")return[new o.V(_t,Ct.zoom,"stop zoom values must be numbers")];if(Q&&Q>ht)return[new o.V(_t,Ct.zoom,"stop zoom values must appear in ascending order")];ht!==Q&&(Q=ht,G=void 0,ae={}),dt=dt.concat(_r({key:`${_t}[0]`,value:lt[0],valueSpec:{zoom:{}},style:Ge.style,styleSpec:Ge.styleSpec,objectElementValidators:{zoom:lr,value:Ye}}))}else dt=dt.concat(Ye({key:`${_t}[0]`,value:lt[0],style:Ge.style,styleSpec:Ge.styleSpec},lt));return o.U(o.W(lt[1]))?dt.concat([new o.V(`${_t}[1]`,lt[1],"expressions are not allowed in function stops.")]):dt.concat(vn({key:`${_t}[1]`,value:lt[1],valueSpec:P,style:Ge.style,styleSpec:Ge.styleSpec}))}function Ye(Ge,dt){const lt=o.M(Ge.value),_t=o.L(Ge.value),Ct=Ge.value!==null?Ge.value:dt;if(q){if(lt!==q)return[new o.V(Ge.key,Ct,`${lt} stop domain type must match previous stop domain type ${q}`)]}else q=lt;if(lt!=="number"&<!=="string"&<!=="boolean"&&typeof _t!="number"&&typeof _t!="string"&&typeof _t!="boolean")return[new o.V(Ge.key,Ct,"stop domain value must be a number, string, or boolean")];if(lt!=="number"&&F!=="categorical"){let ht=`number expected, ${lt} found`;return o.Q(P)&&F===void 0&&(ht+='\nIf you intended to use a categorical function, specify `"type": "categorical"`.'),[new o.V(Ge.key,Ct,ht)]}return F!=="categorical"||lt!=="number"||typeof _t=="number"&&isFinite(_t)&&Math.floor(_t)===_t?F!=="categorical"&<==="number"&&typeof _t=="number"&&typeof G=="number"&&G!==void 0&&_tnew o.V(`${M.key}${P.key}`,M.value,P.message));const N=g.value.expression||g.value._styleExpression.expression;if(M.expressionContext==="property"&&M.propertyKey==="text-font"&&!N.outputDefined())return[new o.V(M.key,M.value,`Invalid data expression for "${M.propertyKey}". Output values must be contained as literals within the expression.`)];if(M.expressionContext==="property"&&M.propertyType==="layout"&&!o.$(N))return[new o.V(M.key,M.value,'"feature-state" data expressions are not supported with layout properties.')];if(M.expressionContext==="filter")return xs(N,M);if(M.expressionContext==="appearance")return kt(N,M);if(M.expressionContext&&M.expressionContext.indexOf("cluster")===0){if(!o.Z(N,["zoom","feature-state"]))return[new o.V(M.key,M.value,'"zoom" and "feature-state" expressions are not supported with cluster properties.')];if(M.expressionContext==="cluster-initial"&&!o._(N))return[new o.V(M.key,M.value,"Feature data expressions are not supported with initial expression part of cluster properties.")]}return[]}function xs(M,g){const N=new Set(["zoom","feature-state","pitch","distance-from-center"]);if(g.valueSpec&&g.valueSpec.expression)for(const F of g.valueSpec.expression.parameters)N.delete(F);if(N.size===0)return[];const P=[];return M instanceof o.a0&&N.has(M.name)?[new o.V(g.key,g.value,`["${M.name}"] expression is not supported in a filter for a ${g.object.type} layer with id: ${g.object.id}`)]:(M.eachChild(F=>{P.push(...xs(F,g))}),P)}function kt(M,g){const N=new Set;if(g.valueSpec&&g.valueSpec.expression)for(const F of g.valueSpec.expression.parameters)N.add(F);if(N.size===0)return[];const P=[];return M instanceof o.a0&&!N.has(M.name)?[new o.V(g.key,g.value,`["${M.name}"] is not an allowed parameter`)]:(M.eachChild(F=>{P.push(...kt(F,g))}),P)}function fs(M){const g=M.key,N=M.value,P=M.valueSpec,F=[];return Array.isArray(P.values)?P.values.indexOf(o.L(N))===-1&&F.push(new o.V(g,N,`expected one of [${P.values.join(", ")}], ${JSON.stringify(N)} found`)):Object.keys(P.values).indexOf(o.L(N))===-1&&F.push(new o.V(g,N,`expected one of [${Object.keys(P.values).join(", ")}], ${JSON.stringify(N)} found`)),F}function Gs(M){return o.a4(o.W(M.value))?St(Object.assign({},M,{expressionContext:"filter",valueSpec:M.styleSpec[`filter_${M.layerType||"fill"}`]})):_s(M)}function _s(M){const g=M.value,N=M.key;if(!Array.isArray(g))return[new o.V(N,g,`array expected, ${o.M(g)} found`)];if(g.length<1)return[new o.V(N,g,"filter array must have at least 1 element")];const P=M.styleSpec;let F=fs({key:`${N}[0]`,value:g[0],valueSpec:P.filter_operator});const q=()=>{g.length>=2&&(o.a2(g[1])||F.push(new o.V(`${N}[1]`,g[1],`string expected, ${o.M(g[1])} found`)));for(let G=2;G":case">=":g.length>=2&&o.L(g[1])==="$type"&&F.push(new o.V(N,g,`"$type" cannot be use with operator "${g[0]}"`)),g.length!==3&&F.push(new o.V(N,g,`filter array for operator "${g[0]}" must have 3 elements`)),q();break;case"==":case"!=":g.length!==3&&F.push(new o.V(N,g,`filter array for operator "${g[0]}" must have 3 elements`)),q();break;case"in":case"!in":q();break;case"any":case"all":case"none":for(let G=1;G{me in N&&g.push(new o.V(P,N[me],`"${me}" is prohibited for ref layers`))}),F.layers.forEach(me=>{o.L(me.id)===Q&&(ae=me)}),ae?ae.ref?g.push(new o.V(P,N.ref,"ref cannot reference another ref layer")):G=o.L(ae.type):typeof Q=="string"&&g.push(new o.V(P,N.ref,`ref layer "${Q}" not found`))}else if(G!=="background"&&G!=="sky"&&G!=="slot")if(N.source)if(o.a2(N.source)){const ae=F.sources&&F.sources[N.source],me=ae&&o.L(ae.type);ae?me==="vector"&&G==="raster"?g.push(new o.V(P,N.source,`layer "${N.id}" requires a raster source`)):me==="raster"&&G!=="raster"?g.push(new o.V(P,N.source,`layer "${N.id}" requires a vector source`)):me!=="vector"||N["source-layer"]?me==="raster-dem"&&G!=="hillshade"?g.push(new o.V(P,N.source,"raster-dem source can only be used with layer type 'hillshade'.")):me!=="raster-array"||["raster","raster-particle"].includes(G)?G==="line"&&N.paint&&(N.paint["line-gradient"]||N.paint["line-trim-offset"])&&me==="geojson"&&!ae.lineMetrics?g.push(new o.V(P,N,`layer "${N.id}" specifies a line-gradient, which requires the GeoJSON source to have \`lineMetrics\` enabled.`)):G==="raster-particle"&&me!=="raster-array"&&g.push(new o.V(P,N.source,`layer "${N.id}" requires a 'raster-array' source.`)):g.push(new o.V(P,N.source,"raster-array source can only be used with layer type 'raster'.")):g.push(new o.V(P,N,`layer "${N.id}" must specify a "source-layer"`)):g.push(new o.V(P,N.source,`source "${N.source}" not found`))}else g.push(new o.V(`${P}.source`,N.source,'"source" must be a string'));else g.push(new o.V(P,N,'missing required property "source"'));return g=g.concat(_r({key:P,value:N,valueSpec:q.layer,style:M.style,styleSpec:M.styleSpec,objectElementValidators:{"*":()=>[],type:()=>vn({key:`${P}.type`,value:N.type,valueSpec:q.layer.type,style:M.style,styleSpec:M.styleSpec,object:N,objectKey:"type"}),filter:ae=>Gs(Object.assign({layerType:G},ae)),layout:ae=>_r({layer:N,key:ae.key,value:ae.value,valueSpec:{},style:ae.style,styleSpec:ae.styleSpec,objectElementValidators:{"*":me=>Yr(Object.assign({layerType:G},me))}}),paint:ae=>_r({layer:N,key:ae.key,value:ae.value,valueSpec:{},style:ae.style,styleSpec:ae.styleSpec,objectElementValidators:{"*":me=>zr(Object.assign({layerType:G,layer:N},me))}}),appearances(ae){const me=Is({key:ae.key,value:ae.value,valueSpec:ae.valueSpec,style:ae.style,styleSpec:ae.styleSpec,arrayElementValidator:Te=>function(Fe){const{key:Ye,layer:Ge,layerType:dt}=Fe,lt=o.L(Fe.value),_t=o.L(lt.name),Ct=o.L(lt.condition),ht=_r({key:Ye,value:lt,valueSpec:Fe.styleSpec.appearance,style:Fe.style,styleSpec:Fe.styleSpec,objectElementValidators:{condition:Kt=>function(Lt){const Wt=[];return Wt.push(...St({key:Lt.key,value:Lt.object.condition,valueSpec:o.a8.appearance.condition,expressionContext:"appearance"})),Wt}(Object.assign({layer:Ge,layerType:dt},Kt)),properties:Kt=>function(Lt){const Wt=[],{styleSpec:Tt,layer:It,layerType:Ut}=Lt,rs=Tt[`paint_${Ut}`],Zt=Tt[`layout_${Ut}`],ks=Lt.object[Lt.objectKey];for(const ms in ks){const Ws=ms in rs?"paint":ms in Zt?"layout":void 0;if(!Ws){Wt.push(new o.V(Lt.key,ms,`unknown property "${ms}" for layer type "${Ut}"`));continue}const sr=Object.assign({},Lt,{key:`${Lt.key}.${ms}`,object:ks,objectKey:ms,layer:It,layerType:Ut,value:ks[ms],valueSpec:Ws==="paint"?rs[ms]:Zt[ms]});Wt.push(...br(sr,Ws))}return Wt}(Object.assign({layer:Ge,layerType:dt},Kt))}});return _t!=="hidden"&&Ct===void 0&&ht.push(new o.V(Fe.key,"name",'Appearance with name different than "hidden" must have a condition')),ht}(Object.assign({layerType:G,layer:N},Te))}),ye=Array.isArray(ae.value)?ae.value:[],Ae=new Set;return ye.forEach((Te,Fe)=>{const Ye=o.L(Te.name);if(Ye)if(Ae.has(Ye)){const Ge=o.L(N.id);me.push(new o.V(ae.key,Ye,`Duplicated appearance name "${Ye}" for layer "${Ge}"`))}else Ae.add(Ye)}),me}}})),g}function sn({key:M,value:g}){return o.a2(g)?[]:[new o.V(M,g,`string expected, ${o.M(g)} found`)]}const Vr={promoteId:function M({key:g,value:N}){if(o.a2(N))return sn({key:g,value:N});if(Array.isArray(N)){const F=[],q=o.W(N),G=o.X(q);return G.result==="error"?(G.value.forEach(Q=>{F.push(new o.V(`${g}${Q.key}`,null,`${Q.message}`))}),F):(o.Z(G.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"])||F.push(new o.V(`${g}`,null,"promoteId expression should be only feature dependent")),F)}if(!o.K(N))return[new o.V(g,N,`string, expression or object expected, "${o.M(N)}" found`)];const P=[];for(const F in N)P.push(...M({key:`${g}.${F}`,value:N[F]}));return P}};function $r(M){const g=M.value,N=M.key,P=M.styleSpec,F=M.style;if(!o.K(g))return[new o.V(N,g,`object expected, ${o.M(g)} found`)];if(!("type"in g))return[new o.V(N,g,'"type" is required')];const q=o.L(g.type);let G=[];switch(["vector","raster","raster-dem","raster-array"].includes(q)&&("url"in g||"tiles"in g||G.push(new o.a5(N,g,'Either "url" or "tiles" is required.'))),q){case"vector":case"raster":case"raster-dem":case"raster-array":return G=G.concat(_r({key:N,value:g,valueSpec:P[`source_${q.replace("-","_")}`],style:M.style,styleSpec:P,objectElementValidators:Vr})),G;case"geojson":if(G=_r({key:N,value:g,valueSpec:P.source_geojson,style:F,styleSpec:P,objectElementValidators:Vr}),"cluster"in g&&"clusterProperties"in g){if(!o.K(g.clusterProperties))return[new o.V(`${N}.clusterProperties`,g,`object expected, ${o.M(g)} found`)];for(const Q in g.clusterProperties){const ae=g.clusterProperties[Q];if(!Array.isArray(ae))return[new o.V(`${N}.clusterProperties.${Q}`,ae,"array expected")];const[me,ye]=ae,Ae=typeof me=="string"?[me,["accumulated"],["get",Q]]:me;G.push(...St({key:`${N}.${Q}.map`,value:ye,expressionContext:"cluster-map"})),G.push(...St({key:`${N}.${Q}.reduce`,value:Ae,expressionContext:"cluster-reduce"}))}}return G;case"video":return _r({key:N,value:g,valueSpec:P.source_video,style:F,styleSpec:P});case"image":return _r({key:N,value:g,valueSpec:P.source_image,style:F,styleSpec:P});case"canvas":return[new o.V(N,null,"Please use runtime APIs to add canvas sources, rather than including them in stylesheets.","source.canvas")];default:return fs({key:`${N}.type`,value:g.type,valueSpec:{values:hn(P)}})}}function hn(M){return M.source.reduce((g,N)=>{const P=M[N];return P.type.type==="enum"&&(g=g.concat(Object.keys(P.type.values||{}))),g},[])}function Zn(M){const g=M.value,N=M.styleSpec,P=N.light,F=M.style;if(g===void 0)return[];if(!o.K(g))return[new o.V("light",g,`object expected, ${o.M(g)} found`)];let q=[];for(const G in g){const Q=G.match(/^(.*)-transition$/),ae=G.match(/^(.*)-use-theme$/);q=q.concat(ae&&P[ae[1]]?vn({key:G,value:g[G],valueSpec:{type:"string"},style:F,styleSpec:N}):Q&&P[Q[1]]&&P[Q[1]].transition?vn({key:G,value:g[G],valueSpec:N.transition,style:F,styleSpec:N}):P[G]?vn({key:G,value:g[G],valueSpec:P[G],style:F,styleSpec:N}):[new o.V(G,g[G],`unknown property "${G}"`)])}return q}function cr(M){const g=M.value;if(!g)return[];const N=M.key;if(!o.K(g))return[new o.V(N,g,`object expected, ${o.M(g)} found`)];let P=[];const F=M.styleSpec,q=F["light-3d"],G=M.style,Q=M.style.lights;for(const ye of["type","id"])if(!(ye in g))return P=P.concat([new o.V(N,g,`missing property "${ye}"`)]),P;if(!o.a2(g.type))return P=P.concat([new o.V(`${N}.type`,g.type,"string expected")]),P;if(Q)for(let ye=0;ye[],array:Is,boolean:function(M){const g=M.value,N=M.key;return o.a1(g)?[]:[new o.V(N,g,`boolean expected, ${o.M(g)} found`)]},number:lr,color:function({key:M,value:g}){return o.a2(g)?o.a3.parseCSSColor(g)===null?[new o.V(M,g,`color expected, "${g}" found`)]:[]:[new o.V(M,g,`color expected, ${o.M(g)} found`)]},enum:fs,filter:Gs,function:us,layer:rn,object:_r,source:$r,model:o.a9,light:Zn,"light-3d":cr,terrain:on,fog:ds,string:sn,formatted:function(M){return sn(M).length===0?[]:St(M)},resolvedImage:function(M){return sn(M).length===0?[]:St(M)},projection:function(M){const g=M.value,N=M.styleSpec,P=N.projection,F=M.style;if(o.K(g)){let q=[];for(const G in g)q=q.concat(vn({key:G,value:g[G],valueSpec:P[G],style:F,styleSpec:N}));return q}return o.a2(g)?[]:[new o.V("projection",g,`object or string expected, ${o.M(g)} found`)]},import:function(M){const g=M.key,{value:N,styleSpec:P}=M;if(!o.K(N))return[new o.V(g,N,"import must be an object")];const{data:F,...q}=N;Object.defineProperty(q,"__line__",{value:N.__line__,enumerable:!1});let G=_r(Object.assign({},M,{value:q,valueSpec:P.import}));return o.L(q.id)===""&&G.push(new o.V(`${M.key}.id`,q,"import id can't be an empty string")),F&&(G=G.concat(_a(F,P,{key:`${M.key}.data`}))),G},iconset:function(M){const g=M.value,N=M.key,P=M.styleSpec,F=M.style;if(!o.K(g))return[new o.V(N,g,"object expected")];if(!g.type)return[new o.V(N,g,'"type" is required')];const q=o.L(g.type);let G=[];if(G=G.concat(_r({key:N,value:g,valueSpec:P[`iconset_${q}`],style:F,styleSpec:P})),function(Q,ae){return!(Q!=="source"||!ae.source)}(q,g)){const Q=F.sources&&F.sources[g.source],ae=Q&&o.L(Q.type);Q?ae!=="raster-array"&&G.push(new o.V(N,g.source,`iconset cannot be used with a source of type ${String(ae)}, it only be used with a "raster-array" source type`)):G.push(new o.V(N,g.source,`source "${g.source}" not found`))}return G}};function vn(M,g=!1){const N=M.value,P=M.valueSpec,F=M.styleSpec;if(P.expression){if(o.a6(o.L(N)))return us(M);if(o.U(o.W(N)))return St(M)}if(P.type&&Na[P.type]){const q=Na[P.type](M);return g===!0&&q.length>0&&Array.isArray(M.value)?St(M):q}return _r(Object.assign({},M,{valueSpec:P.type?F[P.type]:P}))}function _r(M){const g=M.key,N=M.value,P=M.valueSpec||{},F=M.objectElementValidators||{},q=M.style,G=M.styleSpec;if(!o.K(N))return[new o.V(g,N,`object expected, ${o.M(N)} found`)];let Q=[];for(const ae in N){const me=ae.split(".")[0];let ye;F[me]?ye=F[me]:P[me]?ye=vn:F["*"]?ye=F["*"]:P["*"]&&(ye=vn),ye?Q=Q.concat(ye({key:(g&&`${g}.`)+ae,value:N[ae],valueSpec:P[me]||P["*"],style:q,styleSpec:G,object:N,objectKey:ae},N)):Q.push(new o.a5(g,N[ae],`unknown property "${ae}"`))}for(const ae in P){if(F[ae])continue;const me=P[ae];me.required&&me.default===void 0&&N[ae]===void 0&&Q.push(new o.V(g,N,`missing required property "${ae}"`))}return Q}function Hr({key:M,value:g}){const N=sn({key:M,value:g});if(N.length)return N;const P=g;return P.indexOf("{fontstack}")===-1&&N.push(new o.V(M,g,'"glyphs" url must include a "{fontstack}" token')),P.indexOf("{range}")===-1&&N.push(new o.V(M,g,'"glyphs" url must include a "{range}" token')),N}function _a(M,g=o.a8,N={}){return _r({key:N.key||"",value:M,valueSpec:Object.assign(g.$root,{"*":{type:"*"}}),styleSpec:g,style:M,objectElementValidators:{glyphs:Hr}})}function Jt(M,g=o.a8){return Rs(_a(M,g))}const Cr=M=>Rs($r(M)),Gt=M=>Rs(Zn(M)),Ee=M=>Rs(cr(M)),He=M=>Rs(on(M)),ot=M=>Rs(ds(M)),jt=M=>Rs(function(g){const N=g.value,P=g.style,F=g.styleSpec,q=F.snow;if(N===void 0)return[];if(!o.K(N))return[new o.V("snow",N,`object expected, ${o.M(N)} found`)];let G=[];for(const Q in N){const ae=Q.match(/^(.*)-transition$/);G=G.concat(ae&&q[ae[1]]&&q[ae[1]].transition?vn({key:Q,value:N[Q],valueSpec:F.transition,style:P,styleSpec:F}):q[Q]?vn({key:Q,value:N[Q],valueSpec:q[Q],style:P,styleSpec:F}):[new o.a5(Q,N[Q],`unknown property "${Q}"`)])}return G}(M)),Dt=M=>Rs(function(g){const N=g.value,P=g.style,F=g.styleSpec,q=F.rain;if(N===void 0)return[];if(!o.K(N))return[new o.V("rain",N,`object expected, ${o.M(N)} found`)];let G=[];for(const Q in N){const ae=Q.match(/^(.*)-transition$/);G=G.concat(ae&&q[ae[1]]&&q[ae[1]].transition?vn({key:Q,value:N[Q],valueSpec:F.transition,style:P,styleSpec:F}):q[Q]?vn({key:Q,value:N[Q],valueSpec:q[Q],style:P,styleSpec:F}):[new o.a5(Q,N[Q],`unknown property "${Q}"`)])}return G}(M)),qt=M=>Rs(rn(M)),ss=M=>Rs(Gs(M)),Yt=M=>Rs(zr(M)),ls=M=>Rs(Yr(M)),Xs=M=>Rs(o.a9(M));function Rs(M){return M.slice().sort((g,N)=>g.line&&N.line?g.line-N.line:0)}function Er(M,g){let N=!1;if(g&&g.length)for(const P of g)P instanceof o.a5?o.w(P.message):(M.fire(new o.B(new Error(P.message))),N=!0);return N}const ln=o.a8.light;let mn;class Gr extends o.E{constructor(g,N="flat"){super(),this._transitionable=new o.aa(mn||(mn=new o.ab({anchor:new o.ac(ln.anchor),position:new o.ad(ln.position),color:new o.ac(ln.color),intensity:new o.ac(ln.intensity)}))),this.setLight(g,N),this._transitioning=this._transitionable.untransitioned()}getLight(){return this._transitionable.serialize()}setLight(g,N,P={}){this._validate(Gt,g,P)||(this._transitionable.setTransitionOrValue(g),this.id=N)}updateTransitions(g){this._transitioning=this._transitionable.transitioned(g,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(g){this.properties=this._transitioning.possiblyEvaluate(g)}_validate(g,N,P){return(!P||P.validate!==!1)&&Er(this,g.call(Jt,Object.assign({value:N,style:{glyphs:!0,sprite:!0},styleSpec:o.a8})))}}const fn=o.a8.terrain;let pn=class extends o.E{constructor(M,g,N,P,F){super(),this.scope=N,this._transitionable=new o.aa(new o.ab({source:new o.ac(fn.source),exaggeration:new o.ac(fn.exaggeration)}),N,P),this._transitionable.setTransitionOrValue(M,P),this._transitioning=this._transitionable.untransitioned(),this.drapeRenderMode=g,this.worldview=F}get(){return this._transitionable.serialize()}set(M,g){this._transitionable.setTransitionOrValue(M,g)}updateTransitions(M){this._transitioning=this._transitionable.transitioned(M,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(M){this.properties=this._transitioning.possiblyEvaluate(M)}getExaggeration(M){return this._transitioning.possiblyEvaluate(new o.ae(M,{worldview:this.worldview})).get("exaggeration")}getAttenuationRange(){if(!this.isZoomDependent())return null;const M=this._transitionable._values.exaggeration;if(!M)return null;const g=M.value.expression;if(!g)return null;let N=-1,P=-1,F=1;for(const q of g.zoomStops)F=g.evaluate(new o.ae(q,{worldview:this.worldview})),F>.01?(N=q,P=-1):P=q;return F<.01&&N>0&&P>N?[N,P]:null}isZoomDependent(){const M=this._transitionable._values.exaggeration;return M!=null&&M.value!=null&&M.value.expression!=null&&M.value.expression instanceof o.af}};const Sn=.05;function Aa(M,g,N,P){const F=o.aj(45,65,N),[q,G]=vo(M,P);let Q=1-Math.min(1,Math.exp((g-q)/(G-q)*-6));return Q*=Q*Q,Q=Math.min(1,1.00747*Q),Q*F*M.alpha}function vo(M,g){const N=.5/Math.tan(.5*g);return[M.range[0]+N,M.range[1]+N]}function fo(M,g,N,P,F){const q=o.ah([],[g,N,P],F.mercatorFogMatrix);return Aa(M,o.ai(q),F.pitch,F._fov)}function ai(M,g,N,P,F,q,G){const Q=[[N,P,0],[F,P,0],[F,q,0],[N,q,0]];let ae=Number.MAX_VALUE,me=-Number.MAX_VALUE;for(const ye of Q){const Ae=o.ah([],ye,g),Te=o.ai(Ae);ae=Math.min(ae,Te),me=Math.max(me,Te)}return[Aa(M,ae,G.pitch,G._fov),Aa(M,me,G.pitch,G._fov)]}const Cn=o.a8.fog;class Wi extends o.E{constructor(g,N,P,F){super();const q=new o.ab({range:new o.ac(Cn.range),color:new o.ac(Cn.color),"color-use-theme":new o.ac({type:"string","property-type":"data-constant",default:"default"}),"high-color":new o.ac(Cn["high-color"]),"high-color-use-theme":new o.ac({type:"string","property-type":"data-constant",default:"default"}),"space-color":new o.ac(Cn["space-color"]),"space-color-use-theme":new o.ac({type:"string","property-type":"data-constant",default:"default"}),"horizon-blend":new o.ac(Cn["horizon-blend"]),"star-intensity":new o.ac(Cn["star-intensity"]),"vertical-range":new o.ac(Cn["vertical-range"])});this._transitionable=new o.aa(q,P,new Map(F)),this.set(g,F),this._transitioning=this._transitionable.untransitioned(),this._transform=N,this.properties=new o.ak(q),this.scope=P}get state(){const g=this._transform,N=g.projection.name==="globe",P=o.al(g.zoom),F=this.properties.get("range"),q=[.5,3];return{range:N?[o.am(q[0],F[0],P),o.am(q[1],F[1],P)]:F,horizonBlend:this.properties.get("horizon-blend"),alpha:this.properties.get("color").a}}get(){return this._transitionable.serialize()}set(g,N,P={}){if(this._validate(ot,g,P))return;const F=Object.assign({},g);for(const q of Object.keys(Cn))F[q]===void 0&&(F[q]=Cn[q].default);this._options=F,this._transitionable.setTransitionOrValue(this._options,N)}getOpacity(g){if(!this._transform.projection.supportsFog)return 0;const N=this.properties&&this.properties.get("color")||1;return(this._transform.projection.name==="globe"?1:o.aj(45,65,g))*N.a}getOpacityAtLatLng(g,N){return this._transform.projection.supportsFog?function(P,F,q){const G=o.ag.fromLngLat(F),Q=q.elevation?q.elevation.getAtPointOrZero(G):0;return fo(P,G.x,G.y,Q,q)}(this.state,g,N):0}getOpacityForTile(g){if(!this._transform.projection.supportsFog)return[1,1];const N=this._transform.calculateFogTileMatrix(g.toUnwrapped());return ai(this.state,N,0,0,o.an,o.an,this._transform)}getOpacityForBounds(g,N,P,F,q){return this._transform.projection.supportsFog?ai(this.state,g,N,P,F,q,this._transform):[1,1]}getFovAdjustedRange(g){return this._transform.projection.supportsFog?vo(this.state,g):[0,1]}isVisibleOnFrustum(g){if(!this._transform.projection.supportsFog)return!1;const N=[4,5,6,7];for(const P of N){const F=g.points[P];let q;if(F[2]>=0)q=F;else{const G=g.points[P-4];q=o.ao(G,F,G[2]/(G[2]-F[2]))}if(fo(this.state,q[0],q[1],0,this._transform)>=Sn)return!0}return!1}updateConfig(g){this._transitionable.setTransitionOrValue(this._options,new Map(g))}updateTransitions(g){this._transitioning=this._transitionable.transitioned(g,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(g){this.properties=this._transitioning.possiblyEvaluate(g)}_validate(g,N,P){return(!P||P.validate!==!1)&&Er(this,g.call(Jt,Object.assign({value:N,style:{glyphs:!0,sprite:!0},styleSpec:o.a8})))}}let Ki,ii,Ji,co=class extends o.E{constructor(M,g,N,P){super();const F=Ki||(Ki=new o.ab({density:new o.ac(o.a8.snow.density),intensity:new o.ac(o.a8.snow.intensity),color:new o.ac(o.a8.snow.color),opacity:new o.ac(o.a8.snow.opacity),vignette:new o.ac(o.a8.snow.vignette),"vignette-color":new o.ac(o.a8.snow["vignette-color"]),"center-thinning":new o.ac(o.a8.snow["center-thinning"]),direction:new o.ac(o.a8.snow.direction),"flake-size":new o.ac(o.a8.snow["flake-size"])}));this._transitionable=new o.aa(F,N,new Map(P)),this.set(M,P),this._transitioning=this._transitionable.untransitioned(),this.properties=new o.ak(F),this.scope=N}get state(){const M=this.properties.get("opacity"),g=this.properties.get("color"),N=this.properties.get("direction"),P=o.ap(N[0]),F=-Math.max(o.ap(N[1]),.01),q=[Math.cos(P)*Math.cos(F),Math.sin(P)*Math.cos(F),Math.sin(F)],G=this.properties.get("vignette"),Q=this.properties.get("vignette-color");return Q.a=G,{density:this.properties.get("density"),intensity:this.properties.get("intensity"),color:new o.aq(g.r,g.g,g.b,g.a*M),direction:q,centerThinning:this.properties.get("center-thinning"),flakeSize:this.properties.get("flake-size"),vignetteColor:Q}}get(){return this._transitionable.serialize()}set(M,g,N={}){if(this._validate(jt,M,N))return;const P=Object.assign({},M),F=o.a8.snow;for(const q of Object.keys(F))P[q]===void 0&&(P[q]=F[q].default);this._options=P,this._transitionable.setTransitionOrValue(this._options,g)}updateConfig(M){this._transitionable.setTransitionOrValue(this._options,new Map(M))}updateTransitions(M){this._transitioning=this._transitionable.transitioned(M,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(M){this.properties=this._transitioning.possiblyEvaluate(M)}_validate(M,g,N){return(!N||N.validate!==!1)&&Er(this,M.call(Jt,Object.assign({value:g,style:{glyphs:!0,sprite:!0},styleSpec:o.a8})))}},ia=class extends o.E{constructor(M,g,N,P){super();const F=ii||(ii=new o.ab({density:new o.ac(o.a8.rain.density),intensity:new o.ac(o.a8.rain.intensity),color:new o.ac(o.a8.rain.color),opacity:new o.ac(o.a8.rain.opacity),vignette:new o.ac(o.a8.rain.vignette),"vignette-color":new o.ac(o.a8.rain["vignette-color"]),"center-thinning":new o.ac(o.a8.rain["center-thinning"]),direction:new o.ac(o.a8.rain.direction),"droplet-size":new o.ac(o.a8.rain["droplet-size"]),"distortion-strength":new o.ac(o.a8.rain["distortion-strength"])}));this._transitionable=new o.aa(F,N,new Map(P)),this.set(M,P),this._transitioning=this._transitionable.untransitioned(),this.properties=new o.ak(F),this.scope=N}get state(){const M=this.properties.get("opacity"),g=this.properties.get("color"),N=this.properties.get("direction"),P=o.ap(N[0]),F=-Math.max(o.ap(N[1]),.01),q=[Math.cos(P)*Math.cos(F),Math.sin(P)*Math.cos(F),Math.sin(F)],G=this.properties.get("vignette-color");return G.a=this.properties.get("vignette"),{density:this.properties.get("density"),intensity:this.properties.get("intensity"),color:new o.aq(g.r,g.g,g.b,g.a*M),direction:q,centerThinning:this.properties.get("center-thinning"),dropletSize:this.properties.get("droplet-size"),distortionStrength:this.properties.get("distortion-strength"),vignetteColor:G}}get(){return this._transitionable.serialize()}set(M,g,N={}){if(this._validate(Dt,M,N))return;const P=Object.assign({},M),F=o.a8.rain;for(const q of Object.keys(F))P[q]===void 0&&(P[q]=F[q].default);this._options=P,this._transitionable.setTransitionOrValue(this._options,g)}updateConfig(M){this._transitionable.setTransitionOrValue(this._options,new Map(M))}updateTransitions(M){this._transitioning=this._transitionable.transitioned(M,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(M){this.properties=this._transitioning.possiblyEvaluate(M)}_validate(M,g,N){return(!N||N.validate!==!1)&&Er(this,M.call(Jt,Object.assign({value:g,style:{glyphs:!0,sprite:!0},styleSpec:o.a8})))}};class hr extends o.E{constructor(g,N,P,F){super(),this.scope=P,this._options=g,this.properties=new o.ak(N),this._transitionable=new o.aa(N,P,new Map(F)),this._transitionable.setTransitionOrValue(g.properties),this._transitioning=this._transitionable.untransitioned()}updateConfig(g){this._transitionable.setTransitionOrValue(this._options.properties,new Map(g))}updateTransitions(g){this._transitioning=this._transitionable.transitioned(g,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(g){this.properties=this._transitioning.possiblyEvaluate(g)}get(){return this._options.properties=this._transitionable.serialize(),this._options}set(g,N){this._options=g,this._transitionable.setTransitionOrValue(g.properties,N)}shadowsEnabled(){return!!this.properties&&this.properties.get("cast-shadows")===!0}}const Sa=()=>Ji||(Ji=new o.ab({color:new o.ac(o.a8.properties_light_ambient.color),"color-use-theme":new o.ac({type:"string",default:"default","property-type":"data-constant"}),intensity:new o.ac(o.a8.properties_light_ambient.intensity)}));let Yi;const $o=()=>Yi||(Yi=new o.ab({direction:new o.ar(o.a8.properties_light_directional.direction),color:new o.ac(o.a8.properties_light_directional.color),"color-use-theme":new o.ac({type:"string",default:"default","property-type":"data-constant"}),intensity:new o.ac(o.a8.properties_light_directional.intensity),"cast-shadows":new o.ac(o.a8.properties_light_directional["cast-shadows"]),"shadow-quality":new o.ac(o.a8.properties_light_directional["shadow-quality"]),"shadow-intensity":new o.ac(o.a8.properties_light_directional["shadow-intensity"]),"shadow-draw-before-layer":new o.ac(o.a8.properties_light_directional["shadow-draw-before-layer"])}));class cl{constructor(g,N,P){this.screenBounds=g,this.cameraPoint=P.getCameraPoint(),this._screenRaycastCache={},this._cameraRaycastCache={},this.isAboveHorizon=N,this.screenGeometry=this.bufferedScreenGeometry(0),this.screenGeometryMercator=this._bufferedScreenMercator(0,P)}static createFromScreenPoints(g,N){let P,F;if(g instanceof o.P||typeof g[0]=="number"){const q=o.P.convert(g);P=[q],F=N.isPointAboveHorizon(q)}else{const q=o.P.convert(g[0]),G=o.P.convert(g[1]),Q=q.add(G)._div(2);P=[q,G],F=o.as(q,G).every(ae=>N.isPointAboveHorizon(ae))&&N.isPointAboveHorizon(Q)}return new cl(P,F,N)}isPointQuery(){return this.screenBounds.length===1}bufferedScreenGeometry(g){return o.as(this.screenBounds[0],this.screenBounds.length===1?this.screenBounds[0]:this.screenBounds[1],g)}bufferedCameraGeometry(g){const N=this.screenBounds[0],P=this.screenBounds.length===1?this.screenBounds[0].add(new o.P(1,1)):this.screenBounds[1],F=o.as(N,P,0,!1);return this.cameraPoint.y>P.y&&(this.cameraPoint.x>N.x&&this.cameraPoint.x=P.x?F[2]=this.cameraPoint:this.cameraPoint.x<=N.x&&(F[3]=this.cameraPoint)),o.at(F,g)}bufferedCameraGeometryGlobe(g){const N=this.screenBounds[0],P=this.screenBounds.length===1?this.screenBounds[0].add(new o.P(1,1)):this.screenBounds[1],F=o.as(N,P,g),q=this.cameraPoint.clone(),G=+(q.x>N.x)+ +(q.x>P.x);switch(3*(+(q.y>N.y)+ +(q.y>P.y))+G){case 0:F[0]=q,F[4]=q.clone();break;case 1:F.splice(1,0,q);break;case 2:F[1]=q;break;case 3:F.splice(4,0,q);break;case 5:F.splice(2,0,q);break;case 6:F[3]=q;break;case 7:F.splice(3,0,q);break;case 8:F[2]=q}return F}containsTile(g,N,P,F=0){const q=Math.max(g.queryPadding,g.evaluateQueryRenderedFeaturePadding())/N._pixelsPerMercatorPixel+1,G=P?this._bufferedCameraMercator(q,N):this._bufferedScreenMercator(q,N);let Q=g.tileID.wrap+(G.unwrapped?F:0);const ae=G.polygon.map(dt=>o.au(g.tileTransform,dt,Q));if(!o.av(ae,0,0,o.an,o.an))return;Q=g.tileID.wrap+(this.screenGeometryMercator.unwrapped?F:0);const me=this.screenGeometryMercator.polygon.map(dt=>o.aw(g.tileTransform,dt,Q)),ye=me.map(dt=>new o.P(dt[0],dt[1])),Ae=N.getFreeCameraOptions().position||new o.ag(0,0,0),Te=o.aw(g.tileTransform,Ae,Q),Fe=me.map(dt=>{const lt=o.ax(dt,dt,Te);return o.ay(lt,lt),new o.az(Te,lt)}),Ye=o.aA(g,1,N.zoom)*N._pixelsPerMercatorPixel;return{queryGeometry:this,tilespaceGeometry:ye,tilespaceRays:Fe,bufferedTilespaceGeometry:ae,bufferedTilespaceBounds:(Ge=o.aB(ae),Ge.min.x=o.aC(Ge.min.x,0,o.an),Ge.min.y=o.aC(Ge.min.y,0,o.an),Ge.max.x=o.aC(Ge.max.x,0,o.an),Ge.max.y=o.aC(Ge.max.y,0,o.an),Ge),tile:g,tileID:g.tileID,pixelToTileUnitsFactor:Ye};var Ge}_bufferedScreenMercator(g,N){const P=Nu(g);if(this._screenRaycastCache[P])return this._screenRaycastCache[P];{let F;return F=N.projection.name==="globe"?this._projectAndResample(this.bufferedScreenGeometry(g),N):{polygon:this.bufferedScreenGeometry(g).map(q=>N.pointCoordinate3D(q)),unwrapped:!0},this._screenRaycastCache[P]=F,F}}_bufferedCameraMercator(g,N){const P=Nu(g);if(this._cameraRaycastCache[P])return this._cameraRaycastCache[P];{let F;return F=N.projection.name==="globe"?this._projectAndResample(this.bufferedCameraGeometryGlobe(g),N):{polygon:this.bufferedCameraGeometry(g).map(q=>N.pointCoordinate3D(q)),unwrapped:!0},this._cameraRaycastCache[P]=F,F}}_projectAndResample(g,N){const P=function(q,G){const Q=o.aD([],G.pixelMatrix,G.globeMatrix),ae=[0,-o.aF,0,1],me=[0,o.aF,0,1],ye=[0,0,0,1];o.aE(ae,ae,Q),o.aE(me,me,Q),o.aE(ye,ye,Q);const Ae=new o.P(ae[0]/ae[3],ae[1]/ae[3]),Te=new o.P(me[0]/me[3],me[1]/me[3]),Fe=o.aG(q,Ae)&&ae[3]1?bo(q.slice(0,dt),G):[],Ct=dtnew o.P(md(Wt.x),Wt.y)),Ct=Ct.map(Wt=>new o.P(md(Wt.x),Wt.y));const ht=[..._t];ht.length===0&&ht.push(Ct[Ct.length-1]);const Kt=o.am(ht[ht.length-1].y,(Ct.length===0?_t[0]:Ct[0]).y,lt);let Lt;return Lt=Fe?[new o.P(0,Kt),new o.P(0,0),new o.P(1,0),new o.P(1,Kt)]:[new o.P(1,Kt),new o.P(1,1),new o.P(0,1),new o.P(0,Kt)],ht.push(...Lt),Ct.length===0?ht.push(_t[0]):ht.push(...Ct),{polygon:ht.map(Wt=>new o.ag(Wt.x,Wt.y)),unwrapped:!1}}(g,N);if(P)return P;const F=function(q,G){let Q=!1,ae=-1/0,me=0;for(let Ae=0;Aeae&&(ae=q[Ae].x,me=Ae);for(let Ae=0;Ae.5&&(Fe.x{Ae.x-=1}),{polygon:q,unwrapped:Q}}(bo(g,N).map(q=>new o.P(md(q.x),q.y)),N);return{polygon:F.polygon.map(q=>new o.ag(q.x,q.y)),unwrapped:F.unwrapped}}}function bo(M,g){return o.aI(M,N=>{const P=g.pointCoordinate3D(N);N.x=P.x,N.y=P.y},1/256)}function md(M){return M<0?1+M%1:M%1}function Nu(M){return 100*M|0}function Yf(M,g,N){try{g=function(F){if(!F.variants)return F;if(!Array.isArray(F.variants))throw new Error("variants must be an array");for(const q of F.variants){if(q==null||typeof q!="object"||q.constructor!==Object)throw new Error("variant must be an object");if(!Array.isArray(q.capabilities))throw new Error("capabilities must be an array");if(q.capabilities.length===1&&q.capabilities[0]==="meshopt")return Object.assign(F,q)}return F}(g)}catch(F){return new Error("Failed to process TileJSON variants",{cause:F})}const P=o.aJ(Object.assign({},g,M),["tilejson","tiles","minzoom","maxzoom","attribution","mapbox_logo","bounds","extra_bounds","scheme","tileSize","encoding","vector_layers","raster_layers","worldview_options","worldview_default","worldview"]);return M.url&&g.tiles&&M.tiles&&(P.tiles=g.tiles),P.tiles=N.canonicalizeTileset(P,M.url),P}function ku(M,g,N,P,F){const q=function(Q,ae){if(Q)return F(Q);if(ae){M.url&&ae.tiles&&M.tiles&&delete M.tiles;const me=Yf(M,ae,g);if(me instanceof Error)return F(me);F(null,me)}},G=function(Q,ae,me){if(!Q)return null;if(!ae&&!me)return Q;me=me||Q.worldview_default;const ye=Object.values(Q.language||{});if(ye.length===0)return null;const Ae=Object.values(Q.worldview||{});if(Ae.length===0)return null;const Te=ye.every(Ye=>Ye===ae),Fe=Ae.every(Ye=>Ye===me);return Te&&Fe?Q:ae in(Q.language_options||{})||me in(Q.worldview_options||{})?null:Q.language_options&&Q.worldview_options?Q:null}(M.data,N,P);return G?o.o.frame(()=>q(null,G)):M.url?o.m(g.transformRequest(g.normalizeSourceURL(M.url,null,N,P),o.R.Source),q):o.o.frame(()=>{const{data:Q,...ae}=M;q(null,ae)})}function $h(M,g){const N=Math.pow(2,g.z),P=Math.floor(o.aH(M.getWest())*N),F=Math.floor(o.aL(M.getNorth())*N),q=Math.ceil(o.aH(M.getEast())*N),G=Math.ceil(o.aL(M.getSouth())*N);return g.x>=P&&g.x=F&&g.ythis.maxzoom||g.z{this._tileJSONRequest=null,this._loaded=!0,G?(N&&console.warn(`Ensure that your requested language string is a valid BCP-47 code or list of codes. Found: ${N}`),P&&console.warn(`Requested worldview strings must be a valid ISO alpha-2 code. Found: ${P}`),this.fire(new o.B(G))):Q&&(this._setTileJSON(Q),We(Q.tiles,this.map._requestManager._customAccessToken),this.fire(new o.C("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new o.C("data",{dataType:"source",sourceDataType:"content"}))),g&&g(G)};this.provider=this._options.provider;const q=function(G){if("provider"in G&&!G.provider)return null;let Q=G.provider;if(!Q&&"url"in G&&G.url&&(Q=o.aM(G.url)),!Q)return null;const ae=o.g.TILE_PROVIDER_URLS[Q];if(!ae)return null;let me;try{me=new URL(ae,o.g.API_URL).href}catch{return o.w(`TileProvider "${Q}" has an invalid URL: "${ae}"`),null}return{name:Q,url:me}}(this._options);if(this.provider&&!q)return this._loaded=!0,this.fire(new o.B(new Error(`TileProvider "${this.provider}" is not registered`))),void(g&&g());this._tileJSONRequest=q?this._loadWithProvider(q,F):ku(this._options,this.map._requestManager,N,P,F)}_loadWithProvider(g,N){this.provider=g.name;const P=new AbortController,F=this._options.url&&!this._options.tiles?this.map._requestManager.transformRequest(this._options.url,o.R.Source):void 0,q=F?Object.assign({},this._options,{url:F.url}):this._options;return this.dispatcher.broadcast("loadTileProvider",{name:g.name,url:g.url,source:this.id,scope:this.scope,type:this.type,options:q,request:F},(G,Q)=>{if(P.signal.aborted)return;if(G)return void N(G);const ae=Q?Q.find(me=>me!=null):null;if(ae){const me=Yf(this._options,ae,this.map._requestManager);me instanceof Error?N(me):N(null,me)}else N(null,{tiles:this._options.tiles})}),{cancel:()=>{P.abort()}}}_setTileJSON(g){if(Object.assign(this,g),this.hasWorldviews=!!g.worldview_options,g.worldview_default&&(this.worldviewDefault=g.worldview_default),g.vector_layers){this.vectorLayers=g.vector_layers,this.vectorLayerIds=[],this.localizableLayerIds=new Set;for(const N of g.vector_layers)this.vectorLayerIds.push(N.id),g.worldview&&g.worldview[N.source]&&this.localizableLayerIds.add(N.id)}this.tileBounds=Su.fromTileJSON(g)}loaded(){return this._loaded}hasTile(g){return!this.tileBounds||this.tileBounds.contains(g.canonical)}onAdd(g){this.map=g,this.load()}reload(){this.cancelTileJSONRequest();const g=o.F(this.id,this.scope);this.load(()=>this.map.style.clearSource(g))}setTiles(g){return this._options.tiles=g,this.reload(),this}setUrl(g){return this.url=g,this._options.url=g,this.reload(),this}onRemove(g){this.cancelTileJSONRequest()}serialize(){return Object.assign({},this._options)}loadTile(g,N){const P=g.tileID.canonical.url(this.tiles,this.scheme),F=this.map._requestManager.normalizeTileURL(P),q=this.map._requestManager.transformRequest(F,o.R.Tile),G=this.map.style?this.map.style.getLut(this.scope):null,Q=G?{image:G.image.clone()}:null,ae={request:q,data:void 0,uid:g.uid,tileID:g.tileID,tileZoom:g.tileZoom,zoom:g.tileID.overscaledZ,maxZoom:this.maxzoom,lut:Q,tileSize:this.tileSize*g.tileID.overscaleFactor(),type:this.type,source:this.id,scope:this.scope,pixelRatio:o.o.devicePixelRatio,showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId,renderSourceType:g.renderSourceType,brightness:this.map.style&&this.map.style.getBrightness()||0,extraShadowCaster:g.isExtraShadowCaster,tessellationStep:this.map._tessellationStep,scaleFactor:this.map.getScaleFactor(),worldview:this.map.getWorldview()||this.worldviewDefault,indoor:this.map.getIndoorTileOptions(this.id,this.scope)};if(this.hasWorldviews&&o.e(P)&&(ae.localizableLayerIds=this.localizableLayerIds),ae.request.collectResourceTiming=this._collectResourceTiming,g.actor&&g.state!=="expired")g.state==="loading"?g.reloadCallback=N:g.request=g.actor.send("reloadTile",ae,me.bind(this));else if(g.actor=this._tileWorkers[F]=this._tileWorkers[F]||this.dispatcher.getActor(),this.dispatcher.ready||this.provider)g.request=g.actor.send("loadTile",ae,me.bind(this),void 0,!0);else{const ye=o.aO.call({deduped:this._deduped},ae,(Ae,Te)=>{if(Ae||!Te)me.call(this,Ae);else{const Fe=o.aP(Te.responseHeaders);ae.data={rawData:Te.rawData.slice(0),expires:Fe.expires,cacheControl:Fe.cacheControl},g.actor&&g.actor.send("loadTile",ae,me.bind(this),void 0,!0)}},!0);g.request={cancel:ye}}function me(ye,Ae){return delete g.request,g.aborted?N(null):ye?N(ye):(Ae&&Ae.resourceTiming&&(g.resourceTiming=Ae.resourceTiming),this.map._refreshExpiredTiles&&Ae&&g.setExpiryData(Ae),g.loadVectorData(Ae,this.map.painter),o.aQ(this.dispatcher),N(null,Ae),void(g.reloadCallback&&(this.loadTile(g,g.reloadCallback),g.reloadCallback=null)))}}abortTile(g){g.request&&(g.request.cancel(),delete g.request),g.actor&&g.actor.send("abortTile",{uid:g.uid,type:this.type,source:this.id,scope:this.scope})}unloadTile(g,N){g.actor&&g.actor.send("removeTile",{uid:g.uid,type:this.type,source:this.id,scope:this.scope}),g.destroy()}hasTransition(){return!1}afterUpdate(){this._tileWorkers={}}cancelTileJSONRequest(){this._tileJSONRequest&&(this._tileJSONRequest.cancel(),this._tileJSONRequest=null)}}class uv extends o.E{constructor(g,N,P,F){super(),this.id=g,this.dispatcher=P,this.setEventedParent(F),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"},N),Object.assign(this,o.aJ(N,["url","scheme","tileSize"]))}load(g){this._loaded=!1,this.fire(new o.C("dataloading",{dataType:"source"}));const N=this.map.getWorldview();this._tileJSONRequest=ku(this._options,this.map._requestManager,null,N,(P,F)=>{this._tileJSONRequest=null,this._loaded=!0,P?this.fire(new o.B(P)):F&&(Object.assign(this,F),F.raster_layers&&(this.rasterLayers=F.raster_layers,this.rasterLayerIds=this.rasterLayers.map(q=>q.id)),this.tileBounds=Su.fromTileJSON(F),We(F.tiles),this.fire(new o.C("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new o.C("data",{dataType:"source",sourceDataType:"content"}))),g&&g(P)})}loaded(){return this._loaded}onAdd(g){this.map=g,this.load()}reload(){this.cancelTileJSONRequest();const g=o.F(this.id,this.scope);this.load(()=>this.map.style.clearSource(g))}setTiles(g){return this._options.tiles=g,this.reload(),this}setUrl(g){return this.url=g,this._options.url=g,this.reload(),this}onRemove(g){this.cancelTileJSONRequest()}serialize(){return Object.assign({},this._options)}hasTile(g){return!this.tileBounds||this.tileBounds.contains(g.canonical)}loadTile(g,N){const P=o.o.devicePixelRatio>=2,F=this.map._requestManager.normalizeTileURL(g.tileID.canonical.url(this.tiles,this.scheme),P,this.tileSize);g.request=o.n(this.map._requestManager.transformRequest(F,o.R.Tile),(q,G,Q)=>{if(delete g.request,g.aborted)return g.state="unloaded",N(null);if(q)return g.state="errored",N(q);if(!G)return N(null);const ae=o.aP(Q);this.map._refreshExpiredTiles&&g.setExpiryData(ae),g.setTexture(G,this.map.painter),g.state="loaded",o.aQ(this.dispatcher),N(null)})}abortTile(g,N){g.request&&(g.request.cancel(),delete g.request),N&&N()}unloadTile(g,N){g.texture&&g.texture instanceof o.T?(g.destroy(!1),g.texture&&g.texture instanceof o.T&&this.map.painter.saveTileTexture(g.texture)):g.destroy(),N&&N()}hasTransition(){return!1}cancelTileJSONRequest(){this._tileJSONRequest&&(this._tileJSONRequest.cancel(),this._tileJSONRequest=null)}}function rw([M,g],N,P,{scaled:F=!0}={}){const{tileSize:q,buffer:G}=P,{x:Q,y:ae,z:me}=N;if(!isFinite(Q)||!isFinite(ae)||!isFinite(me))throw new Error("Invalid MRT header");const ye=2**me,Ae=ye*o.aH(M),Te=ye*o.aL(g);return function([Fe,Ye],Ge,{scaled:dt=!0}={}){if(!Ge)throw new Error("bandView is undefined");const{data:lt,tileSize:_t,buffer:Ct,offset:ht,scale:Kt,dimension:Lt}=Ge;if(Fe<-Ct||Fe>_t+Ct||Ye<-Ct||Ye>_t+Ct)throw new Error(`Point (${Fe}, ${Ye}) out of bounds for tileSize=${_t}, buffer=${Ct}`);const Wt=(Ye+Ct)*(_t+2*Ct)+(Fe+Ct);if(new Uint32Array(lt.buffer)[Wt]===4294967295)return null;let Tt=[];Tt=dt?[]:new Ge.data.constructor(Lt);for(let It=0;It{if(delete g.request,g.aborted)return g.state="unloaded",N(null);if(Q)return Q.name==="AbortError"?void 0:(g.state="errored",N(Q));if(this.map._refreshExpiredTiles&&ae){const ye=o.aP(me);g.setExpiryData(ye)}if(this.partial&&g.state!=="expired")g.state="empty";else if(!this.partial){if(!ae)return N(null);g.state="loaded",g._isHeaderLoaded=!0,g._mrt=ae}N(null)};g.request=this.partial?g.fetchHeader(void 0,G.bind(this)):g.actor.send("loadTile",q,G.bind(this),void 0,!0)}abortTile(g){g.request&&(g.request.cancel(),delete g.request),g.actor&&g.actor.send("abortTile",{uid:g.uid,type:this.type,source:this.id,scope:this.scope})}unloadTile(g,N){const P=g.texturePerLayer;if(g.flushAllQueues(),P.size){g.destroy(!1);for(const F of P.values())this.map.painter.saveTileTexture(F)}else g.destroy()}prepareTile(g,N,P,F){g._isHeaderLoaded&&(g.state!=="empty"&&(g.state="reloading"),g.fetchBandForRender(N,P,F,(q,G)=>{q?(g.state="errored",this.fire(new o.B(q))):G&&(g._isHeaderLoaded=!0,g.setTexturePerLayer(P,G,this.map.painter),g.state="loaded"),this.triggerRepaint(g)}))}getInitialBand(g){if(!this.rasterLayers)return 0;const N=this.rasterLayers.find(({id:q})=>q===g),P=N&&N.fields,F=P&&P.bands&&P.bands;return F?F[0]:0}getTextureDescriptor(g,N,P){if(!g)return;const F=N.sourceLayer||this.rasterLayerIds&&this.rasterLayerIds[0];if(!F)return;let q=null;N instanceof o.aS?q=N.paint.get("raster-array-band"):N instanceof o.aT&&(q=N.paint.get("raster-particle-array-band"));const G=q||this.getInitialBand(F);if(G==null)return;if(!g.textureDescriptorPerLayer.get(N.id))return void this.prepareTile(g,F,N.id,G);if(g.updateNeeded(N.id,G)&&!P)return;const Q=g.textureDescriptorPerLayer.get(N.id);return Object.assign({},Q,{texture:g.texturePerLayer.get(N.id)})}getImages(g,N){const P=new Map;for(const F of g)for(const q of N){const[G,Q]=q.split("/"),ae=F.getLayer(G);if(!ae||!ae.hasBand(Q)||!ae.hasDataForBand(Q))continue;const{bytes:me,tileSize:ye,buffer:Ae}=ae.getBandView(Q),Te=ye+2*Ae,Fe={data:new o.q({width:Te,height:Te},me),pixelRatio:2,sdf:!1,usvg:!1,version:0};P.set(q,Fe)}return P}queryRasterArrayValueByBandId(g,N,P){const F=N._mrt;return new Promise(q=>{const G={},Q=new Set;for(const[ae,me]of Object.entries(F.layers)){if(P.layerName&&ae!==P.layerName)continue;const ye={};G[ae]=ye;for(const{bands:Ae}of me.dataIndex)for(const Te of Ae)P.bands&&!P.bands.includes(Te)||(Q.add(o.F(ae,Te)),N.fetchBand(ae,null,Te,Fe=>{o.o.frame(()=>{ye[Te]=Fe?null:rw([g.lng,g.lat],F,me.getBandView(Te)),Q.delete(o.F(ae,Te)),Q.size===0&&q(G)})},!1))}Q.size===0&&q(G)})}_loadTileForQuery(g,N){if(this._loadTileLoaded[g.uid])return void N(null,g._mrt);if(this._loadTilePending[g.uid])return void this._loadTilePending[g.uid].push(N);this._loadTilePending[g.uid]=[N];const P=this.map._requestManager.normalizeTileURL(g.tileID.canonical.url(this.tiles,this.scheme),!1,this.tileSize),F=this.map._requestManager.transformRequest(P,o.R.Tile);g.actor.send("loadTile",{request:F,uid:g.uid,tileID:g.tileID,type:this.type,source:this.id,scope:this.scope,partial:!1},(q,G,Q)=>{if(q)return this._loadTilePending[g.uid].forEach(ae=>ae(q,null)),void delete this._loadTilePending[g.uid];if(!G)return this._loadTilePending[g.uid].forEach(ae=>ae(null,null)),void delete this._loadTilePending[g.uid];if(this.map._refreshExpiredTiles&&G){const ae=o.aP(Q);g.setExpiryData(ae)}g._mrt=G,g._isHeaderLoaded=!0,g.state="loaded",this._loadTilePending[g.uid].forEach(ae=>ae(null,G)),this._loadTileLoaded[g.uid]=!0,delete this._loadTilePending[g.uid]},void 0,!0)}queryRasterArrayValueByAllBands(g,N,P){return new Promise((F,q)=>{this._loadTileForQuery(N,(G,Q)=>{G?q(G):F(Q?this.queryRasterArrayValueByBandId(g,N,P):null)})})}queryRasterArrayValue(g,N){const P=o.aU.convert(g),F=this.findLoadedParent(P);return F&&F._mrt?N.bands||!this.partial?this.queryRasterArrayValueByBandId(P,F,N):this.queryRasterArrayValueByAllBands(P,F,N):Promise.resolve(null)}findLoadedParent(g){const N=o.ag.fromLngLat(g,this.map.transform.tileSize),P=this.maxzoom+1,F=1<0&&(Q[new o.aR(M.overscaledZ,F,g.z,P,g.y-1).key]={backfilled:!1},Q[new o.aR(M.overscaledZ,M.wrap,g.z,g.x,g.y-1).key]={backfilled:!1},Q[new o.aR(M.overscaledZ,G,g.z,q,g.y-1).key]={backfilled:!1}),g.y+1{if(this._loaded=!0,this._pendingLoad=null,P)this.fire(new o.B(P));else{const q={dataType:"source",sourceDataType:this._metadataFired?"content":"metadata"};this._collectResourceTiming&&F&&F.resourceTiming&&F.resourceTiming[this.id]&&(q.resourceTiming=F.resourceTiming[this.id]),M&&(this._partialReload=!0),this.fire(new o.C("data",q)),this._partialReload=!1,this._metadataFired=!0}this._coalesce&&(this._updateWorkerData(M),this._coalesce=!1)})}loaded(){return this._loaded}reload(){const M=o.F(this.id,this.scope);this.map.style.clearSource(M),this._updateWorkerData()}loadTile(M,g){const N=M.actor?"reloadTile":"loadTile";M.actor=this.actor;const P=this.map.style?this.map.style.getLut(this.scope):null,F=P?{image:P.image.clone()}:null,q=this._partialReload,G={type:this.type,uid:M.uid,tileID:M.tileID,tileZoom:M.tileZoom,zoom:M.tileID.overscaledZ,maxZoom:this.maxzoom,tileSize:this.tileSize,source:this.id,lut:F,scope:this.scope,pixelRatio:o.o.devicePixelRatio,showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId,brightness:this.map.style&&this.map.style.getBrightness()||0,extraShadowCaster:M.isExtraShadowCaster,scaleFactor:this.map.getScaleFactor(),partial:q,worldview:this.map.getWorldview(),indoor:this.map.getIndoorTileOptions(this.id,this.scope)};M.request=this.actor.send(N,G,(Q,ae)=>q&&!ae?(M.state="loaded",g(null)):(delete M.request,M.destroy(!1),M.aborted?g(null):Q?g(Q):(M.loadVectorData(ae,this.map.painter,N==="reloadTile"),g(null))),void 0,N==="loadTile")}abortTile(M){M.request&&(M.request.cancel(),delete M.request),M.aborted=!0}unloadTile(M,g){this.actor.send("removeTile",{uid:M.uid,type:this.type,source:this.id,scope:this.scope}),M.destroy()}onRemove(M){this._pendingLoad&&this._pendingLoad.cancel()}serialize(){return Object.assign({},this._options,{type:this.type,data:this._data})}hasTransition(){return!1}},video:class extends o.aV{constructor(M,g,N,P){super(M,g,N,P),this.roundZoom=!0,this.type="video",this.options=g}load(){this._loaded=!1;const M=this.options;this.urls=[];for(const g of M.urls)this.urls.push(this.map._requestManager.transformRequest(g,o.R.Source).url);o.aW(this.urls,(g,N)=>{this._loaded=!0,g?this.fire(new o.B(g)):N&&(this.video=N,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(M){if(this.video){const g=this.video.seekable;Mg.end(0)?this.fire(new o.B(new o.V(`sources.${this.id}`,null,`Playback for this video can be set only between the ${g.start(0)} and ${g.end(0)}-second mark.`))):this.video.currentTime=M}}getVideo(){return this.video}onAdd(M){this.map||(this.map=M,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 M=this.map.painter.context,g=M.gl;this.texture?this.video.paused||(this.texture.bind(g.LINEAR,g.CLAMP_TO_EDGE),g.texSubImage2D(g.TEXTURE_2D,0,0,0,g.RGBA,g.UNSIGNED_BYTE,this.video)):(this.texture=new o.T(M,this.video,g.RGBA8),this.texture.bind(g.LINEAR,g.CLAMP_TO_EDGE),this.width=this.video.videoWidth,this.height=this.video.videoHeight),this._prepareData(M)}serialize(){return{type:"video",urls:this.urls,coordinates:this.coordinates}}hasTransition(){return this.video&&!this.video.paused}},image:o.aV,model:o.aY,"batched-model":class extends o.E{constructor(M,g,N,P){super(),this.type="batched-model",this.id=M,this.tileSize=512,this._options=g,this.tiles=this._options.tiles,this.maxzoom=g.maxzoom||19,this.minzoom=g.minzoom||0,this.roundZoom=!0,this.usedInConflation=!0,this.dispatcher=N,this.reparseOverscaled=!1,this.scheme="xyz",this._loaded=!1,this.setEventedParent(P)}onAdd(M){this.map=M,this.load()}reload(){this.cancelTileJSONRequest();const M=o.F(this.id,this.scope);this.load(()=>this.map.style.clearSource(M))}cancelTileJSONRequest(){this._tileJSONRequest&&(this._tileJSONRequest.cancel(),this._tileJSONRequest=null)}load(M){this._loaded=!1,this.fire(new o.C("dataloading",{dataType:"source"}));const g=Array.isArray(this.map._language)?this.map._language.join():this.map._language,N=this.map.getWorldview();this._tileJSONRequest=ku(this._options,this.map._requestManager,g,N,(P,F)=>{this._tileJSONRequest=null,this._loaded=!0,P?(g&&console.warn(`Ensure that your requested language string is a valid BCP-47 code or list of codes. Found: ${g}`),N&&N.length!==2&&console.warn(`Requested worldview strings must be a valid ISO alpha-2 code. Found: ${N}`),this.fire(new o.B(P))):F&&(Object.assign(this,F),F.bounds&&(this.tileBounds=new Su(F.bounds,this.minzoom,this.maxzoom)),We(F.tiles,this.map._requestManager._customAccessToken),this.fire(new o.C("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new o.C("data",{dataType:"source",sourceDataType:"content"}))),M&&M(P)})}hasTransition(){return!1}hasTile(M){return!this.tileBounds||this.tileBounds.contains(M.canonical)}loaded(){return this._loaded}loadTile(M,g){const N=this.map._requestManager.normalizeTileURL(M.tileID.canonical.url(this.tiles,this.scheme)),P={request:this.map._requestManager.transformRequest(N,o.R.Tile),data:void 0,uid:M.uid,tileID:M.tileID,tileZoom:M.tileZoom,zoom:M.tileID.overscaledZ,tileSize:this.tileSize*M.tileID.overscaleFactor(),type:this.type,source:this.id,scope:this.scope,showCollisionBoxes:this.map.showCollisionBoxes,renderSourceType:M.renderSourceType,brightness:this.map.style&&this.map.style.getBrightness()||0,pixelRatio:o.o.devicePixelRatio,promoteId:this.promoteId};if(M.actor&&M.state!=="expired")if(M.state==="loading")M.reloadCallback=g;else{if(M.buckets){const q=Object.values(M.buckets);for(const G of q)G.dirty=!0;return void(M.state="loaded")}M.request=M.actor.send("reloadTile",P,F.bind(this))}else M.actor=this.dispatcher.getActor(),M.request=M.actor.send("loadTile",P,F.bind(this),void 0,!0);function F(q,G){return M.aborted?g(null):q&&q.status!==404?g(q):(this.map._refreshExpiredTiles&&G&&M.setExpiryData(G),M.loadModelData(G,this.map.painter),M.state="loaded",void g(null))}}serialize(){return Object.assign({},this._options)}},canvas:class extends o.aV{constructor(M,g,N,P){super(M,g,N,P),g.coordinates?Array.isArray(g.coordinates)&&g.coordinates.length===4&&!g.coordinates.some(F=>!Array.isArray(F)||F.length!==2||F.some(q=>typeof q!="number"))||this.fire(new o.B(new o.V(`sources.${M}`,null,'"coordinates" property must be an array of 4 longitude/latitude array pairs'))):this.fire(new o.B(new o.V(`sources.${M}`,null,'missing required property "coordinates"'))),g.animate&&typeof g.animate!="boolean"&&this.fire(new o.B(new o.V(`sources.${M}`,null,'optional "animate" property must be a boolean value'))),g.canvas?typeof g.canvas=="string"||g.canvas instanceof HTMLCanvasElement||this.fire(new o.B(new o.V(`sources.${M}`,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 o.B(new o.V(`sources.${M}`,null,'missing required property "canvas"'))),this.options=g,this.animate=g.animate===void 0||g.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 o.B(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(M){this.map=M,this.load(),this.canvas&&this.animate&&this.play()}onRemove(M){this.pause()}prepare(){let M=!1;if(this.canvas.width!==this.width&&(this.width=this.canvas.width,M=!0),this.canvas.height!==this.height&&(this.height=this.canvas.height,M=!0),this._hasInvalidDimensions()||Object.keys(this.tiles).length===0)return;const g=this.map.painter.context;this.texture?!M&&!this._playing||this.texture instanceof o.aX||this.texture.update(this.canvas,{premultiply:!0}):this.texture=new o.T(g,this.canvas,g.gl.RGBA8,{premultiply:!0}),this._prepareData(g)}serialize(){return{type:"canvas",coordinates:this.coordinates}}hasTransition(){return this._playing}_hasInvalidDimensions(){for(const M of[this.canvas.width,this.canvas.height])if(isNaN(M)||M<=0)return!0;return!1}},custom:class extends o.E{constructor(M,g,N,P){super(),this.id=M,this.type="custom",this._dataType="raster",this._dispatcher=N,this._implementation=g,this.setEventedParent(P),this.scheme="xyz",this.minzoom=0,this.maxzoom=22,this.tileSize=512,this._loaded=!1,this.roundZoom=!0,this._implementation||this.fire(new o.B(new Error(`Missing implementation for ${this.id} custom source`))),this._implementation.loadTile||this.fire(new o.B(new Error(`Missing loadTile implementation for ${this.id} custom source`))),this._implementation.bounds&&(this.tileBounds=new Su(this._implementation.bounds,this.minzoom,this.maxzoom));const F=g;F.update=this._update.bind(this),F.clearTiles=this._clearTiles.bind(this),F.coveringTiles=this._coveringTiles.bind(this),Object.assign(this,o.aJ(g,["dataType","scheme","minzoom","maxzoom","tileSize","attribution","minTileCacheSize","maxTileCacheSize"]))}serialize(){return o.aJ(this,["type","scheme","minzoom","maxzoom","tileSize","attribution"])}load(){this._loaded=!0,this.fire(new o.C("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new o.C("data",{dataType:"source",sourceDataType:"content"}))}loaded(){return this._loaded}onAdd(M){this.map=M,this._loaded=!1,this.fire(new o.C("dataloading",{dataType:"source"})),this._implementation.onAdd&&this._implementation.onAdd(M),this.load()}onRemove(M){this._implementation.onRemove&&this._implementation.onRemove(M)}hasTile(M){if(this._implementation.hasTile){const{x:g,y:N,z:P}=M.canonical;return this._implementation.hasTile({x:g,y:N,z:P})}return!this.tileBounds||this.tileBounds.contains(M.canonical)}loadTile(M,g){const{x:N,y:P,z:F}=M.tileID.canonical,q=new AbortController,G=Promise.resolve(this._implementation.loadTile({x:N,y:P,z:F},{signal:q.signal})).then((function(Q){return delete M.request,M.aborted?(M.state="unloaded",g(null)):Q===void 0?(M.state="errored",g(null)):Q===null?(this.loadTileData(M,{width:this.tileSize,height:this.tileSize,data:null}),M.state="loaded",g(null)):function(ae){return ae instanceof ImageData||ae instanceof HTMLCanvasElement||ae instanceof ImageBitmap||ae instanceof HTMLImageElement}(Q)?(this.loadTileData(M,Q),M.state="loaded",void g(null)):(M.state="errored",g(new Error(`Can't infer data type for ${this.id}, only raster data supported at the moment`)))}).bind(this)).catch(Q=>{Q.name!=="AbortError"&&(M.state="errored",g(Q))});G.cancel=()=>q.abort(),M.request=G}loadTileData(M,g){M.setTexture(g,this.map.painter)}unloadTile(M,g){if(M.texture&&M.texture instanceof o.T?(M.destroy(!1),M.texture&&M.texture instanceof o.T&&this.map.painter.saveTileTexture(M.texture)):M.destroy(),this._implementation.unloadTile){const{x:N,y:P,z:F}=M.tileID.canonical;this._implementation.unloadTile({x:N,y:P,z:F})}g&&g()}abortTile(M,g){M.request&&M.request.cancel&&(M.request.cancel(),delete M.request),g&&g()}hasTransition(){return!1}_coveringTiles(){return this.map.transform.coveringTiles({tileSize:this.tileSize,minzoom:this.minzoom,maxzoom:this.maxzoom,roundZoom:this.roundZoom}).map(M=>({x:M.canonical.x,y:M.canonical.y,z:M.canonical.z}))}_clearTiles(){const M=o.F(this.id,this.scope);this.map.style.clearSource(M)}_update(){this.fire(new o.C("data",{dataType:"source",sourceDataType:"content"}))}}},z0=function(M,g,N,P){const F=new B0[g.type](M,g,N,P);if(F.id!==M)throw new Error(`Expected Source id to be ${M} instead of ${F.id}`);return o.aZ(["load","abort","unload","serialize","prepare"],F),F};function Zf(M,g,N=""){return`${N}:${g.id||""}:${g.layer.id}:${function(P){if("layerId"in P)return`layer:${P.layerId}`;{const{featuresetId:F,importId:q}=P;return`featureset:${F}${q?`:import:${q}`:""}`}}(M.target)}`}function Ju(M,g,N,P=""){if(M.uniqueFeatureID){const F=Zf(M,g,P);if(N.has(F))return!0;N.add(F)}return!1}function Pp(M,g,N,P,F=!1,q=void 0){const G=g.sourceCache.transform,Q=g.sourceCache.tilesIn(M,g.has3DLayers,F);Q.sort(qh);const ae=[];for(const me of Q){const ye=me.tile.queryRenderedFeatures(g,me,N,P,G,F,q);Object.keys(ye).length&&ae.push({wrappedTileID:me.tile.tileID.wrapped().key,queryResults:ye})}for(const me in g.layers){const ye=g.layers[me];if(ye.styleLayer){const Ae=ye.styleLayer.queryRenderedFeatures(M,g.sourceCache,P);Object.keys(Ae).length&&ae.push({wrappedTileID:0,queryResults:Ae})}}return ae.length===0?{}:function(me){const ye={},Ae={};for(const Te of me){const Fe=Te.queryResults,Ye=Te.wrappedTileID,Ge=Ae[Ye]=Ae[Ye]||{};for(const dt in Fe){const lt=Fe[dt],_t=Ge[dt]=Ge[dt]||{},Ct=ye[dt]=ye[dt]||[];for(const ht of lt)_t[ht.featureIndex]||(_t[ht.featureIndex]=!0,Ct.push(ht))}}return ye}(ae)}function oo(M,g,N,P,F,q){const G={},Q=P.queryRenderedSymbols(M),ae=[];for(const me of Object.keys(Q).map(Number))ae.push(F[me]);ae.sort(qh);for(const me of ae){const ye=me.featureIndex.lookupSymbolFeatures(Q[me.bucketInstanceId],me.bucketIndex,me.sourceLayerIndex,g,N,q);for(const Ae in ye){const Te=G[Ae]=G[Ae]||[],Fe=ye[Ae];Fe.sort((Ye,Ge)=>{const dt=me.featureSortOrder;if(dt){const lt=dt.indexOf(Ye.featureIndex);return dt.indexOf(Ge.featureIndex)-lt}return Ge.featureIndex-Ye.featureIndex});for(const Ye of Fe)Te.push(Ye)}}return G}function q1(M,g){const N=M.getRenderableIds().map(q=>M.getTileByID(q)),P=[],F={};for(let q=0;q{if(q)N(q);else try{const ae=P.getHeaderLength(G);if(ae>g)return void(this.request=this.fetchHeader(ae,N));P.parseHeader(G),this._isHeaderLoaded=!0;let me=0;for(const ye of Object.values(P.layers))me=Math.max(me,ye.dataIndex[ye.dataIndex.length-1].lastByte);G.byteLength>=me&&(this.entireBuffer=G),N(null,this.entireBuffer||G,Q)}catch(ae){N(ae)}}),this.request}fetchBandForRender(g,N,P,F){this.fetchBand(g,N,P,q=>{if(q)return void F(q);this.updateTextureDescriptor(g,N,P);const G=this.textureDescriptorPerLayer.get(N);F(null,G?G.img:null)})}fetchBand(g,N,P,F,q=!0){const G=this._mrt;if(!this._isHeaderLoaded||!G)return void F(new Error("Tile header is not ready"));const Q=this.actor;if(!Q)return void F(new Error("Can't fetch tile band without an actor"));let ae;const me=o.F(String(P),o.F(this.tileID.key,g));let ye=this._taskQueue.get(me);ye?ye.add(F):(ye=new Set,ye.add(F),this._taskQueue.set(me,ye));const Ae=(Ge,dt)=>{ae.complete(Ge,dt),Ge?F(Ge):(ye.forEach(lt=>lt(null,dt)),this._taskQueue.delete(me))},Te=(Ge,dt)=>{if(Ge)return F(Ge);const lt=Q.send("decodeRasterArray",{type:"raster-array",source:this.source,scope:this.scope,tileID:this.tileID,uid:this.uid,buffer:dt,task:ae},Ae,void 0,!0);if(N!==null){const _t=this._workQueuePerLayer.get(N)||[];_t.push(()=>{lt&<.cancel(),ae.cancel()}),this._workQueuePerLayer.has(N)||this._workQueuePerLayer.set(N,_t)}};let Fe;try{Fe=G.getLayer(g)}catch(Ge){if(this.state==="reloading")return;throw Ge}if(!Fe)return void F(new Error(`Unknown sourceLayer "${g}"`));if(Fe.hasDataForBand(P))return ye.forEach(Ge=>Ge(null,null)),void this._taskQueue.delete(me);const Ye=Fe.getDataRange([P]);if(ae=G.createDecodingTask(Ye),!ae||ae.tasks.length)if(N!==null&&this.flushQueues(N),this.entireBuffer)Te(null,this.entireBuffer.slice(Ye.firstByte,Ye.lastByte+1));else{const Ge=Object.assign({},this.requestParams,{headers:{Range:`bytes=${Ye.firstByte}-${Ye.lastByte}`}}),dt=o.b1(Ge,Te);if(N!==null){const lt=this._fetchQueuePerLayer.get(N)||[];lt.push(()=>{dt.cancel(),ae.cancel()}),this._fetchQueuePerLayer.has(N)||this._fetchQueuePerLayer.set(N,lt)}}}updateNeeded(g,N){return(!this.textureDescriptorPerLayer.get(g)||this.textureDescriptorPerLayer.get(g).band!==N||this.refreshedUponExpiration)&&this.state!=="errored"}updateTextureDescriptor(g,N,P){if(!this._mrt)return;const F=this._mrt.getLayer(g);if(!F||!F.hasBand(P)||!F.hasDataForBand(P))return;const{bytes:q,tileSize:G,buffer:Q,offset:ae,scale:me}=F.getBandView(P),ye=G+2*Q,Ae=new o.q({width:ye,height:ye},q),Te=this.texturePerLayer.get(N);Te&&Te instanceof o.T&&Te.update(Ae,{premultiply:!1}),this.textureDescriptorPerLayer.set(N,{layer:g,band:P,img:Ae,buffer:Q,offset:ae,tileSize:G,format:F.pixelFormat,mix:[me,256*me,65536*me,16777216*me]})}destroy(g=!1){if(super.destroy(g),delete this._mrt,!g)for(const N of this.texturePerLayer.values())N&&N instanceof o.T&&N.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 Lp{constructor(g,N){this.max=g,this.onRemove=N,this.reset()}reset(){for(const g in this.data)for(const N of this.data[g])N.timeout&&clearTimeout(N.timeout),this.onRemove(N.value);return this.data={},this.order=[],this}add(g,N,P){const F=g.wrapped().key;this.data[F]===void 0&&(this.data[F]=[]);const q={value:N,timeout:void 0};if(P!==void 0&&(q.timeout=setTimeout(()=>{this.remove(g,q)},P)),this.data[F].push(q),this.order.push(F),this.order.length>this.max){const G=this._getAndRemoveByKey(this.order[0]);G&&this.onRemove(G)}return this}has(g){return g.wrapped().key in this.data}getAndRemove(g){return this.has(g)?this._getAndRemoveByKey(g.wrapped().key):null}_getAndRemoveByKey(g){const N=this.data[g].shift();return N.timeout&&clearTimeout(N.timeout),this.data[g].length===0&&delete this.data[g],this.order.splice(this.order.indexOf(g),1),N.value}getByKey(g){const N=this.data[g];return N?N[0].value:null}get(g){return this.has(g)?this.data[g.wrapped().key][0].value:null}remove(g,N){if(!this.has(g))return this;const P=g.wrapped().key,F=N===void 0?0:this.data[P].indexOf(N),q=this.data[P][F];return this.data[P].splice(F,1),q.timeout&&clearTimeout(q.timeout),this.data[P].length===0&&delete this.data[P],this.onRemove(q.value),this.order.splice(this.order.indexOf(P),1),this}setMaxSize(g){for(this.max=g;this.order.length>this.max;){const N=this._getAndRemoveByKey(this.order[0]);N&&this.onRemove(N)}return this}filter(g){const N=[];for(const P in this.data)for(const F of this.data[P])g(F.value)||N.push(F);for(const P of N)this.remove(P.value.tileID,P)}}class Cu{constructor(){this.state={},this.stateChanges={},this.deletedStates={}}updateState(g,N,P){const F=String(N);if(this.stateChanges[g]=this.stateChanges[g]||{},this.stateChanges[g][F]=this.stateChanges[g][F]||{},Object.assign(this.stateChanges[g][F],P),this.deletedStates[g]===null){this.deletedStates[g]={};for(const q in this.state[g])q!==F&&(this.deletedStates[g][q]=null)}else if(this.deletedStates[g]&&this.deletedStates[g][F]===null){this.deletedStates[g][F]={};for(const q in this.state[g][F])P[q]||(this.deletedStates[g][F][q]=null)}else for(const q in P)this.deletedStates[g]&&this.deletedStates[g][F]&&this.deletedStates[g][F][q]===null&&delete this.deletedStates[g][F][q]}removeFeatureState(g,N,P){if(this.deletedStates[g]===null)return;const F=String(N);if(this.deletedStates[g]=this.deletedStates[g]||{},P&&N!==void 0)this.deletedStates[g][F]!==null&&(this.deletedStates[g][F]=this.deletedStates[g][F]||{},this.deletedStates[g][F][P]=null);else if(N!==void 0)if(this.stateChanges[g]&&this.stateChanges[g][F])for(P in this.deletedStates[g][F]={},this.stateChanges[g][F])this.deletedStates[g][F][P]=null;else this.deletedStates[g][F]=null;else this.deletedStates[g]=null}getState(g,N){const P=this.state[g]||{},F=this.stateChanges[g]||{},q=this.deletedStates[g];if(q===null)return{};if(N!==void 0){const Q=String(N),ae=Object.assign({},P[Q],F[Q]);if(q){const me=q[N];if(me===null)return{};for(const ye in me)delete ae[ye]}return ae}const G=Object.assign({},P,F);if(q)for(const Q in q)delete G[Q];return G}initializeTileState(g,N){g.refreshFeatureState(N)}coalesceChanges(g,N){const P={};for(const F in this.stateChanges){this.state[F]=this.state[F]||{};const q={};for(const G in this.stateChanges[F])this.state[F][G]||(this.state[F][G]={}),Object.assign(this.state[F][G],this.stateChanges[F][G]),q[G]=this.state[F][G];P[F]=q}for(const F in this.deletedStates){this.state[F]=this.state[F]||{};const q={};if(this.deletedStates[F]===null)for(const G in this.state[F])q[G]={},this.state[F][G]={};else for(const G in this.deletedStates[F]){if(this.deletedStates[F][G]===null)this.state[F][G]={};else if(this.state[F][G])for(const Q of Object.keys(this.deletedStates[F][G]))delete this.state[F][G][Q];q[G]=this.state[F][G]}P[F]=P[F]||{},Object.assign(P[F],q)}if(this.stateChanges={},this.deletedStates={},Object.keys(P).length!==0)for(const F in g)g[F].refreshFeatureState(N,P)}}class Uo extends o.E{constructor(g,N,P){super(),this.id=g,this._renderSourceType=P,this._maxzoomOverride=null,N.on("data",F=>{F.dataType==="source"&&F.sourceDataType==="metadata"&&(this._sourceLoaded=!0),this._sourceLoaded&&!this._paused&&F.dataType==="source"&&F.sourceDataType==="content"&&(this.reload(),this.transform&&this.update(this.transform))}),N.on("error",()=>{this._sourceErrored=!0}),this._source=N,this._tiles={},this._cache=new Lp(0,this._unloadTile.bind(this)),this._timers={},this._cacheTimers={},this._minTileCacheSize=N.minTileCacheSize,this._maxTileCacheSize=N.maxTileCacheSize,this._loadedParentTiles={},this.castsShadows=!1,this.tileCoverLift=0,this._coveredTiles={},this._shadowCasterTiles={},this._state=new Cu,this._isRaster=this._source.type==="raster"||this._source.type==="raster-dem"||this._source.type==="raster-array"||this._source.type==="custom"&&"_dataType"in this._source&&this._source._dataType==="raster",this._supportsFading=this._source.type==="raster"||this._source.type==="raster-array"||this._source.type==="image"||this._source.type==="video"||this._source.type==="custom",this._isRasterElevatedOverTerrain=!1}onAdd(g){this.map=g,this._minTileCacheSize=this._minTileCacheSize===void 0&&g?g._minTileCacheSize:this._minTileCacheSize,this._maxTileCacheSize=this._maxTileCacheSize===void 0&&g?g._maxTileCacheSize:this._maxTileCacheSize}loaded(){if(this._sourceErrored)return!0;if(!this._sourceLoaded||!this._source.loaded())return!1;for(const g in this._tiles)if(!this._tiles[g].loaded())return!1;return!0}getSource(){return this._source}pause(){this._paused=!0}resume(){if(!this._paused)return;const g=this._shouldReloadOnResume;this._paused=!1,this._shouldReloadOnResume=!1,g&&this.reload(),this.transform&&this.update(this.transform)}setMaxzoomOverride(g){this._maxzoomOverride=g}_loadTile(g,N){return g.renderSourceType=this._renderSourceType,g.isExtraShadowCaster=this._shadowCasterTiles[g.tileID.key],this._source.loadTile(g,N)}_unloadTile(g){if(this._source.unloadTile)return this._source.unloadTile(g)}_abortTile(g){if(this._source.abortTile)return this._source.abortTile(g)}serialize(){return this._source.serialize()}prepare(g){this._source.prepare&&this._source.prepare(),this._state.coalesceChanges(this._tiles,this.map?this.map.painter:null);for(const N in this._tiles){const P=this._tiles[N];P.upload(g,this.map?this.map.painter:void 0),P.prepare(this.map.style.imageManager,this.map?this.map.painter:null,this._source.scope)}}getIds(){return Object.values(this._tiles).map(g=>g.tileID).sort(yx).map(g=>g.key)}getRenderableIds(g,N){const P=[];for(const F in this._tiles)this._isIdRenderable(+F,g,N)&&P.push(this._tiles[F]);return g?P.sort((F,q)=>{const G=F.tileID,Q=q.tileID,ae=new o.P(G.canonical.x,G.canonical.y)._rotate(this.transform.angle),me=new o.P(Q.canonical.x,Q.canonical.y)._rotate(this.transform.angle);return G.overscaledZ-Q.overscaledZ||me.y-ae.y||me.x-ae.x}).map(F=>F.tileID.key):P.map(F=>F.tileID).sort(yx).map(F=>F.key)}hasRenderableParent(g){const N=this.findLoadedParent(g,0);return!!N&&this._isIdRenderable(N.tileID.key)}_isIdRenderable(g,N,P){return this._tiles[g]&&this._tiles[g].hasData()&&!this._coveredTiles[g]&&(N||!this._tiles[g].holdingForFade())&&(P||!this._shadowCasterTiles[g])}reload(){if(this._paused)this._shouldReloadOnResume=!0;else{this._cache.reset();for(const g in this._tiles)this._tiles[g].state!=="errored"&&this._reloadTile(+g,"reloading")}}_reloadTile(g,N){const P=this._tiles[g];P&&(P.state!=="loading"&&(P.state=N),this._loadTile(P,this._tileLoaded.bind(this,P,g,N)))}_tileLoaded(g,N,P,F,q){if(F){if(g.state="errored",o.b2(F)){if(this._source.fire(new o.C("data",{dataType:"source",sourceDataType:"error",sourceId:this._source.id,tile:g})),!(g.tileID.key in this._loadedParentTiles))return;if(this._source.type==="raster-dem"&&this.usedForTerrain&&this.map.painter.terrain){const Q=this.map.painter.terrain;this.update(this.transform,Q.getScaledDemTileSize(),!0),Q.resetTileLookupCache(this.id)}else this.update(this.transform)}else this._source.fire(new o.B(F,{tile:g}));return}g.timeAdded=o.o.now(),P==="expired"&&(g.refreshedUponExpiration=!0),this._setTileReloadTimer(N,g),this._source.type==="raster-dem"&&g.dem&&this._backfillDEM(g),this._state.initializeTileState(g,this.map?this.map.painter:null);let G=new Map;q&&q.responseHeaders&&(G=q.responseHeaders),this._source.fire(new o.C("data",{dataType:"source",tile:g,coord:g.tileID,sourceCacheId:this.id,responseHeaders:G}))}_hasTunnelGeometry(){for(const g in this._tiles){const N=this._tiles[g];if(N&&N.hasTunnelGeometry)return!0}return!1}_backfillDEM(g){const N=this.getRenderableIds();for(let F=0;F1||(Math.abs(G)>1&&(Math.abs(G+ae)===1?G+=ae:Math.abs(G-ae)===1&&(G-=ae)),q.dem&&F.dem&&(F.dem.backfillBorder(q.dem,G,Q),F.neighboringTiles&&F.neighboringTiles[me]&&(F.neighboringTiles[me].backfilled=!0)))}}getTile(g){return this.getTileByID(g.key)}getTileByID(g){return this._tiles[g]}_retainLoadedChildren(g,N,P,F){for(const q in this._tiles){let G=this._tiles[q];if(F[q]||!G.hasData()||G.tileID.overscaledZ<=N||G.tileID.overscaledZ>P)continue;let Q=G.tileID;for(;G&&G.tileID.overscaledZ>N+1;){const me=G.tileID.scaledTo(G.tileID.overscaledZ-1);G=this._tiles[me.key],G&&G.hasData()&&(Q=me)}let ae=Q;for(;ae.overscaledZ>N;)if(ae=ae.scaledTo(ae.overscaledZ-1),g[ae.key]){F[Q.key]=Q;break}}}findLoadedParent(g,N){if(g.key in this._loadedParentTiles){const P=this._loadedParentTiles[g.key];return P&&P.tileID.overscaledZ>=N?P:null}for(let P=g.overscaledZ-1;P>=N;P--){const F=g.scaledTo(P),q=this._getLoadedTile(F);if(q)return q}}_getLoadedTile(g){const N=this._tiles[g.key];return N&&N.hasData()?N:this._cache.getByKey(this._source.reparseOverscaled?g.wrapped().key:g.canonical.key)}updateCacheSize(g,N){N=N||this._source.tileSize;const P=Math.ceil(g.width/N)+1,F=Math.ceil(g.height/N)+1,q=Math.floor(P*F*5),G=typeof this._minTileCacheSize=="number"?Math.max(this._minTileCacheSize,q):q,Q=typeof this._maxTileCacheSize=="number"?Math.min(this._maxTileCacheSize,G):G;this._cache.setMaxSize(Q)}handleWrapJump(g){const N=Math.round((g-(this._prevLng===void 0?g:this._prevLng))/360);if(this._prevLng=g,N){const P={};for(const F in this._tiles){const q=this._tiles[F];q.tileID=q.tileID.unwrapTo(q.tileID.wrap+N),P[q.tileID.key]=q}this._tiles=P;for(const F in this._timers)clearTimeout(this._timers[F]),delete this._timers[F];for(const F in this._tiles)this._setTileReloadTimer(+F,this._tiles[F])}}update(g,N,P,F,q){if(this.transform=g,!this._sourceLoaded||this._paused||this.transform.freezeTileCoverage||this.usedForTerrain&&!P)return;this.updateCacheSize(g,N),this.transform.projection.name!=="globe"&&this.handleWrapJump(this.transform.center.lng),this._shadowCasterTiles={},this._coveredTiles={};const G=this._source.type==="batched-model";let Q,ae=this._source.maxzoom;this._maxzoomOverride!==null&&(ae=Math.min(ae,this._maxzoomOverride));const me=this.map&&this.map.painter?this.map.painter._terrain:null;if(me&&me.sourceCache===this&&me.attenuationRange()){const Fe=me.attenuationRange()[0],Ye=Math.floor(Fe)-Math.log2(me.getDemUpscale());ae>Ye&&(ae=Ye)}const ye=this._maxzoomOverride===null&&this._source.reparseOverscaled;if(this.used||this.usedForTerrain){if(this._source.tileID)Q=g.getVisibleUnwrappedCoordinates(this._source.tileID).map(Fe=>new o.aR(Fe.canonical.z,Fe.wrap,Fe.canonical.z,Fe.canonical.x,Fe.canonical.y));else if(this.tileCoverLift!==0){const Fe=g.clone();Fe.tileCoverLift=this.tileCoverLift,Q=Fe.coveringTiles({tileSize:N||this._source.tileSize,minzoom:this._source.minzoom,maxzoom:ae,roundZoom:this._source.roundZoom&&!P,reparseOverscaled:ye,isTerrainDEM:this.usedForTerrain,calculateQuadrantVisibility:G}),this._source.minzoom<=1&&g.projection.name==="globe"&&(Q.push(new o.aR(1,0,1,0,0)),Q.push(new o.aR(1,0,1,1,0)),Q.push(new o.aR(1,0,1,0,1)),Q.push(new o.aR(1,0,1,1,1)))}else if(Q=g.coveringTiles({tileSize:N||this._source.tileSize,minzoom:this._source.minzoom,maxzoom:ae,roundZoom:this._source.roundZoom&&!P,reparseOverscaled:ye,isTerrainDEM:this.usedForTerrain,calculateQuadrantVisibility:G}),this._source.hasTile){const Fe=this._source.hasTile.bind(this._source);Q=Q.filter(Ye=>Fe(Ye))}}else Q=[];if(Q.length>0&&this.transform.projection.name!=="globe"&&!this.usedForTerrain&&!this._supportsFading){const Fe=g.coveringZoomLevel({tileSize:N||this._source.tileSize,roundZoom:this._source.roundZoom&&!P}),Ye=Math.min(Fe,ae);if(G){const Ge=g.extendTileCover(Q,Ye);for(const dt of Ge)Q.push(dt)}else if(q){const Ge=this.transform.getFrustum(Ye),dt=g.extendTileCoverToNearPlane(Q,Ge,Ye);for(const lt of dt)Q.push(lt);if(Ye>=18&&this._hasTunnelGeometry()){const lt=g.extendTileCoverForTunnels(Q,Ge,Ye,20);for(const _t of lt)Q.push(_t)}}else if(this.castsShadows&&F){const Ge=g.extendTileCover(Q,Ye,F,16);for(const dt of Ge)this._shadowCasterTiles[dt.key]=!0,Q.push(dt)}}const Ae=this._updateRetainedTiles(Q);if(this._supportsFading&&Q.length!==0){const Fe={},Ye={},Ge=o.o.now(),dt=Object.keys(Ae);for(const _t of dt){const Ct=Ae[_t],ht=this._tiles[_t];if(!ht||ht.fadeEndTime!==void 0&&ht.fadeEndTime<=Ge)continue;const Kt=this.findLoadedParent(Ct,Math.max(Ct.overscaledZ-Uo.maxOverzooming,this._source.minzoom));Kt&&(this._addTile(Kt.tileID),Fe[Kt.tileID.key]=Kt.tileID),Ye[_t]=Ct}const lt=Q[Q.length-1].overscaledZ;for(const _t in this._tiles){const Ct=this._tiles[_t];if(Ae[_t]||!Ct.hasData())continue;let ht=Ct.tileID;for(;ht.overscaledZ>lt;){ht=ht.scaledTo(ht.overscaledZ-1);const Kt=this._tiles[ht.key];if(Kt&&Kt.hasData()&&Ye[ht.key]){Ae[_t]=Ct.tileID;break}}}for(const _t in Fe)Ae[_t]||(this._coveredTiles[_t]=!0,Ae[_t]=Fe[_t])}for(const Fe in Ae)this._tiles[Fe].clearFadeHold();const Te=o.b3(this._tiles,Ae);for(const Fe of Te){const Ye=this._tiles[Fe];Ye.hasSymbolBuckets&&!Ye.holdingForFade()?Ye.setHoldDuration(this.map._fadeDuration):Ye.hasSymbolBuckets&&!Ye.symbolFadeFinished()||this._removeTile(+Fe)}this._updateLoadedParentTileCache(),this._renderSourceType===o.b4.Symbol&&this._source.afterUpdate&&this._source.afterUpdate()}releaseSymbolFadeTiles(){for(const g in this._tiles)this._tiles[g].holdingForFade()&&this._removeTile(+g)}_updateRetainedTiles(g){const N={};if(g.length===0)return N;const P={},F=g.reduce((me,ye)=>Math.min(me,ye.overscaledZ),1/0),q=g[0].overscaledZ,G=Math.max(q-Uo.maxOverzooming,this._source.minzoom),Q=Math.max(q+Uo.maxUnderzooming,this._source.minzoom),ae={};for(const me of g){const ye=this._addTile(me);N[me.key]=me,ye.hasData()||F=this._source.maxzoom){const Te=me.children(this._source.maxzoom)[0],Fe=this.getTile(Te);if(Fe&&Fe.hasData()){N[Te.key]=Te;continue}}else{const Te=me.children(this._source.maxzoom);if(N[Te[0].key]&&N[Te[1].key]&&N[Te[2].key]&&N[Te[3].key])continue}let Ae=ye.wasRequested();for(let Te=me.overscaledZ-1;Te>=G;--Te){const Fe=me.scaledTo(Te);if(P[Fe.key]||(P[Fe.key]=!0,ye=this.getTile(Fe),!ye&&Ae&&(ye=this._addTile(Fe)),ye&&(N[Fe.key]=Fe,Ae=ye.wasRequested(),ye.hasData())))break}}return N}_updateLoadedParentTileCache(){this._loadedParentTiles={};for(const g in this._tiles){const N=[];let P,F=this._tiles[g].tileID;for(;F.overscaledZ>0;){if(F.key in this._loadedParentTiles){P=this._loadedParentTiles[F.key];break}N.push(F.key);const q=F.scaledTo(F.overscaledZ-1);if(P=this._getLoadedTile(q),P)break;F=q}for(const q of N)this._loadedParentTiles[q]=P}}_addTile(g){let N=this._tiles[g.key];if(N)return N.isExtraShadowCaster!==!0||this._shadowCasterTiles[g.key]||this._reloadTile(g.key,"reloading"),N;N=this._cache.getAndRemove(g),N&&(this._setTileReloadTimer(g.key,N),N.tileID=g,this._state.initializeTileState(N,this.map?this.map.painter:null),this._cacheTimers[g.key]&&(clearTimeout(this._cacheTimers[g.key]),delete this._cacheTimers[g.key],this._setTileReloadTimer(g.key,N)));const P=!!N;if(!P){const F=this.map?this.map.painter:null,q=this._source.tileSize*g.overscaleFactor();N=this._source.type==="raster-array"?new bh(g,q,this.transform.tileZoom,F,this._isRaster):new o.b0(g,q,this.transform.tileZoom,F,this._isRaster,this._source.worldview),this._loadTile(N,this._tileLoaded.bind(this,N,g.key,N.state))}return N.uses++,this._tiles[g.key]=N,P||this._source.fire(new o.C("dataloading",{tile:N,coord:N.tileID,dataType:"source"})),N}_setTileReloadTimer(g,N){g in this._timers&&(clearTimeout(this._timers[g]),delete this._timers[g]);const P=N.getExpiryTimeout();P&&(this._timers[g]=setTimeout(()=>{this._reloadTile(g,"expired"),delete this._timers[g]},P))}_removeTile(g){const N=this._tiles[g];N&&(N.uses--,delete this._tiles[g],this._timers[g]&&(clearTimeout(this._timers[g]),delete this._timers[g]),N.uses>0||(N.hasData()&&N.state!=="reloading"||N.state==="empty"?this._cache.add(N.tileID,N,N.getExpiryTimeout()):(N.aborted=!0,this._abortTile(N),this._unloadTile(N))))}clearTiles(){this._shouldReloadOnResume=!1,this._paused=!1;for(const g in this._tiles)this._removeTile(+g);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(g,N,P){const F=[],q=this.transform;if(!q)return F;const G=q.projection.name==="globe",Q=o.aH(q.center.lng);for(const ae in this._tiles){const me=this._tiles[ae];if(P&&me.clearQueryDebugViz(),me.holdingForFade())continue;let ye;if(G){const Ae=me.tileID.canonical;if(Ae.z===0){const Te=[Math.abs(o.aC(Q,...Qd(Ae,-1))-Q),Math.abs(o.aC(Q,...Qd(Ae,1))-Q)];ye=[0,2*Te.indexOf(Math.min(...Te))-1]}else{const Te=[Math.abs(o.aC(Q,...Qd(Ae,-1))-Q),Math.abs(o.aC(Q,...Qd(Ae,0))-Q),Math.abs(o.aC(Q,...Qd(Ae,1))-Q)];ye=[Te.indexOf(Math.min(...Te))-1]}}else ye=[0];for(const Ae of ye){const Te=g.containsTile(me,q,N,Ae);Te&&F.push(Te)}}return F}getShadowCasterCoordinates(){return this._getRenderableCoordinates(!1,!0)}getVisibleCoordinates(g){return this._getRenderableCoordinates(g)}_getRenderableCoordinates(g,N){const P=this.getRenderableIds(g,N).map(q=>this._tiles[q].tileID),F=this.transform.projection.name==="globe";for(const q of P)q.projMatrix=this.transform.calculateProjMatrix(q.toUnwrapped()),q.expandedProjMatrix=F?this.transform.calculateProjMatrix(q.toUnwrapped(),!1,!0):q.projMatrix;return P}sortCoordinatesByDistance(g){const N=g.slice(),P=this.transform._camera.position,F=this.transform._camera.forward(),q={};for(const G of N){const Q=1/(1<q[G.key]-q[Q.key]),N}hasTransition(){if(this._source.hasTransition())return!0;if(this._supportsFading){const g=o.o.now();for(const N in this._tiles){const P=this._tiles[N];if(P.fadeEndTime!==void 0&&P.fadeEndTime>=g)return!0}}return!1}setFeatureState(g,N,P){this._state.updateState(g=g||"_geojsonTileLayer",N,P)}removeFeatureState(g,N,P){this._state.removeFeatureState(g=g||"_geojsonTileLayer",N,P)}getFeatureState(g,N){return this._state.getState(g=g||"_geojsonTileLayer",N)}setDependencies(g,N,P){const F=this._tiles[g];F&&F.setDependencies(N,P)}reloadTilesForDependencies(g,N){for(const P in this._tiles)this._tiles[P].hasDependency(g,N)&&this._reloadTile(+P,"reloading");this._cache.filter(P=>!P.hasDependency(g,N))}_preloadTiles(g,N){if(!this._sourceLoaded){const ae=()=>{this._sourceLoaded&&(this._source.off("data",ae),this._preloadTiles(g,N))};return void this._source.on("data",ae)}const P=new Map,F=Array.isArray(g)?g:[g],q=this.map.painter.terrain,G=this.usedForTerrain&&q?q.getScaledDemTileSize():this._source.tileSize;for(const ae of F){const me=ae.coveringTiles({tileSize:G,minzoom:this._source.minzoom,maxzoom:this._source.maxzoom,roundZoom:this._source.roundZoom&&!this.usedForTerrain,reparseOverscaled:this._source.reparseOverscaled,isTerrainDEM:this.usedForTerrain});for(const ye of me)P.set(ye.key,ye);this.usedForTerrain&&ae.updateElevation(!1)}const Q=Array.from(P.values());o.t(Q,(ae,me)=>{const ye=new o.b0(ae,this._source.tileSize*ae.overscaleFactor(),this.transform.tileZoom,this.map.painter,this._isRaster,this._source.worldview);this._loadTile(ye,Ae=>{this._source.type==="raster-dem"&&ye.dem&&this._backfillDEM(ye),me(Ae,ye)})},N)}}function yx(M,g){const N=Math.abs(2*M.wrap)-+(M.wrap<0),P=Math.abs(2*g.wrap)-+(g.wrap<0);return M.overscaledZ-g.overscaledZ||P-N||g.canonical.y-M.canonical.y||g.canonical.x-M.canonical.x}function Qd(M,g){const N=1<0:P.type==="building"?F=!P.isHidden(g)&&P.paint.get("building-opacity")>0:P.type==="model"&&(F=!P.isHidden(g)&&P.paint.get("model-opacity").constantOr(1)>0),this.layersGotHidden=this.layersGotHidden||!F&&N.visible,N.visible=F}}updateZOffset(g,N){this.currentBuildingBuckets=[];for(const F of this.layers){const q=F.layer,G=this.style.getLayerSourceCache(q);let Q=1;q.type==="fill-extrusion"?Q=F.visible?q.paint.get("fill-extrusion-vertical-scale"):0:q.type==="building"&&(Q=F.visible?q.paint.get("building-vertical-scale"):0);let ae=G?G.getTile(N):null;if(!ae&&G)for(const me in G._tiles){const ye=G._tiles[me];if(N.canonical.isChildOf(ye.tileID.canonical)){ae=ye;break}}this.currentBuildingBuckets.push({bucket:ae?ae.getBucket(q):null,tileID:ae?ae.tileID:N,verticalScale:Q})}g.hasAnyZOffset=!1;let P=!1;for(let F=0;F{P in g&&(N[P]=g[P])}),N}function Xf(M){M=M.slice();const g=Object.create(null);for(const N of M)g[N.id]=N;for(let N=0;N0?(F-G)/Q:0;return this.points[q].mult(1-ae).add(this.points[N].mult(ae))}}class q0{constructor(g,N,P){const F=this.boxCells=[],q=this.circleCells=[];this.xCellCount=Math.ceil(g/P),this.yCellCount=Math.ceil(N/P);for(let G=0;Gthis.width||F<0||N>this.height)return!q&&[];const Q=[];if(g<=0&&N<=0&&this.width<=P&&this.height<=F){if(q)return!0;for(let ae=0;ae0:Q}_queryCircle(g,N,P,F,q){const G=g-P,Q=g+P,ae=N-P,me=N+P;if(Q<0||G>this.width||me<0||ae>this.height)return!F&&[];const ye=[];return this._forEachCell(G,ae,Q,me,this._queryCellCircle,ye,{hitTest:F,circle:{x:g,y:N,radius:P},seenUids:{box:{},circle:{}}},q),F?ye.length>0:ye}query(g,N,P,F,q){return this._query(g,N,P,F,!1,q)}hitTest(g,N,P,F,q){return this._query(g,N,P,F,!0,q)}hitTestCircle(g,N,P,F){return this._queryCircle(g,N,P,!0,F)}_queryCell(g,N,P,F,q,G,Q,ae){const me=Q.seenUids,ye=this.boxCells[q];if(ye!==null){const Te=this.bboxes;for(const Fe of ye)if(!me.box[Fe]){me.box[Fe]=!0;const Ye=4*Fe;if(g<=Te[Ye+2]&&N<=Te[Ye+3]&&P>=Te[Ye+0]&&F>=Te[Ye+1]&&(!ae||ae(this.boxKeys[Fe]))){if(Q.hitTest)return G.push(!0),!0;G.push({key:this.boxKeys[Fe],x1:Te[Ye],y1:Te[Ye+1],x2:Te[Ye+2],y2:Te[Ye+3]})}}}const Ae=this.circleCells[q];if(Ae!==null){const Te=this.circles;for(const Fe of Ae)if(!me.circle[Fe]){me.circle[Fe]=!0;const Ye=3*Fe;if(this._circleAndRectCollide(Te[Ye],Te[Ye+1],Te[Ye+2],g,N,P,F)&&(!ae||ae(this.circleKeys[Fe]))){if(Q.hitTest)return G.push(!0),!0;{const Ge=Te[Ye],dt=Te[Ye+1],lt=Te[Ye+2];G.push({key:this.circleKeys[Fe],x1:Ge-lt,y1:dt-lt,x2:Ge+lt,y2:dt+lt})}}}}}_queryCellCircle(g,N,P,F,q,G,Q,ae){const me=Q.circle,ye=Q.seenUids,Ae=this.boxCells[q];if(Ae!==null){const Fe=this.bboxes;for(const Ye of Ae)if(!ye.box[Ye]){ye.box[Ye]=!0;const Ge=4*Ye;if(this._circleAndRectCollide(me.x,me.y,me.radius,Fe[Ge+0],Fe[Ge+1],Fe[Ge+2],Fe[Ge+3])&&(!ae||ae(this.boxKeys[Ye])))return G.push(!0),!0}}const Te=this.circleCells[q];if(Te!==null){const Fe=this.circles;for(const Ye of Te)if(!ye.circle[Ye]){ye.circle[Ye]=!0;const Ge=3*Ye;if(this._circlesCollide(Fe[Ge],Fe[Ge+1],Fe[Ge+2],me.x,me.y,me.radius)&&(!ae||ae(this.circleKeys[Ye])))return G.push(!0),!0}}}_forEachCell(g,N,P,F,q,G,Q,ae){const me=this._convertToXCellCoord(g),ye=this._convertToYCellCoord(N),Ae=this._convertToXCellCoord(P),Te=this._convertToYCellCoord(F);for(let Fe=me;Fe<=Ae;Fe++)for(let Ye=ye;Ye<=Te;Ye++)if(q.call(this,g,N,P,F,this.xCellCount*Ye+Fe,G,Q,ae))return}_convertToXCellCoord(g){return Math.max(0,Math.min(this.xCellCount-1,Math.floor(g*this.xScale)))}_convertToYCellCoord(g){return Math.max(0,Math.min(this.yCellCount-1,Math.floor(g*this.yScale)))}_circlesCollide(g,N,P,F,q,G){const Q=F-g,ae=q-N,me=P+G;return me*me>Q*Q+ae*ae}_circleAndRectCollide(g,N,P,F,q,G,Q){const ae=(G-F)/2,me=Math.abs(g-(F+ae));if(me>ae+P)return!1;const ye=(Q-q)/2,Ae=Math.abs(N-(q+ye));if(Ae>ye+P)return!1;if(me<=ae||Ae<=ye)return!0;const Te=me-ae,Fe=Ae-ye;return Te*Te+Fe*Fe<=P*P}}const H1=Math.tan(85*Math.PI/180);function fd(M,g,N,P,F,q,G){const Q=o.bb();if(N)if(q.name==="globe"){const ae=o.bc(F,g);o.aD(Q,Q,ae)}else{const ae=o.bd([],G);Q[0]=ae[0],Q[1]=ae[1],Q[4]=ae[2],Q[5]=ae[3],P||o.ba(Q,Q,F.angle)}else o.aD(Q,F.labelPlaneMatrix,M);return Q}function _c(M,g,N,P,F,q,G){const Q=fd(M,g,N,P,F,q,G);return q.name==="globe"&&N||(Q[2]=Q[6]=Q[10]=Q[14]=0),Q}function Am(M,g,N,P,F,q,G){if(N){if(q.name==="globe"){const Q=fd(M,g,N,P,F,q,G);return o.b7(Q,Q),o.aD(Q,M,Q),Q}{const Q=o.b8(M),ae=o.b9([]);return ae[0]=G[0],ae[1]=G[1],ae[4]=G[2],ae[5]=G[3],o.aD(Q,Q,ae),P||o.ba(Q,Q,-F.angle),Q}}return F.glCoordMatrix}function Ac(M,g,N,P){const F=[M,g,N,1];N?o.aE(F,F,P):jn(F,F,P);const q=F[3];return F[0]/=q,F[1]/=q,F[2]/=q,F}function Mm(M,g){return Math.min(.5+M/g*.5,1.5)}function hf(M,g){const N=M[0]/M[3],P=M[1]/M[3];return N>=-g[0]&&N<=g[0]&&P>=-g[1]&&P<=g[1]}function Mt(M,g,N,P,F,q,G,Q,ae,me,ye=1){const Ae=N.transform,Te=P?M.textSizeData:M.iconSizeData,Fe=o.bj(Te,N.transform.zoom,ye),Ye=Ae.projection.name==="globe",Ge=[256/N.width*2+1,256/N.height*2+1],dt=P?M.text.dynamicLayoutVertexArray:M.icon.dynamicLayoutVertexArray;dt.clear();let lt=null;Ye&&(lt=P?M.text.globeExtVertexArray:M.icon.globeExtVertexArray);const _t=M.lineVertexArray,Ct=P?M.text.placedSymbolArray:M.icon.placedSymbolArray,ht=N.transform.width/N.transform.height;let Kt,Lt=!1;for(let Wt=0;WtMath.abs(N)?{useVertical:!0}:M===o.bk.vertical?P>0?{needsFlipping:!0}:null:g!==0&&function(F,q){return F===0||Math.abs(q/F)>H1}(N,P)?g===1?{needsFlipping:!0}:null:N<0?{needsFlipping:!0}:null}function bn(M,g,N,P,F,q,G,Q,ae,me,ye,Ae,Te,Fe,Ye,Ge,dt,lt,_t,Ct){const ht=g/24,Kt=M.lineOffsetX*ht,Lt=M.lineOffsetY*ht,{lineStartIndex:Wt,glyphStartIndex:Tt,numGlyphs:It,segment:Ut,writingMode:rs,flipState:Zt}=M,ks=Wt+M.lineLength,ms=Ws=>{if(ye){const[ws,Ts,Ls]=Ws.up,wr=me.length;o.bm(ye,wr+0,ws,Ts,Ls),o.bm(ye,wr+1,ws,Ts,Ls),o.bm(ye,wr+2,ws,Ts,Ls),o.bm(ye,wr+3,ws,Ts,Ls)}const[sr,as,Xt]=Ws.point;o.bn(me,sr,as,Xt,Ws.angle)};if(It>1){const Ws=tr(ht,Q,Kt,Lt,N,Ae,Te,M,ae,q,Fe,Ge,!1,dt,lt,_t,Ct);if(!Ws)return{notEnoughRoom:!0};if(P&&!N){let[sr,as,Xt]=Ws.first.point,[ws,Ts,Ls]=Ws.last.point;[sr,as]=Ac(sr,as,Xt,G),[ws,Ts]=Ac(ws,Ts,Ls,G);const wr=kr(rs,Zt,(ws-sr)*Ye,Ts-as);if(M.flipState=wr&&wr.needsFlipping?1:2,wr)return wr}ms(Ws.first);for(let sr=Tt+1;sr0?ws:sa(Te,Xt,sr,1,F,void 0,dt,lt.canonical),Ls=kr(rs,Zt,(Ts[0]-sr[0])*Ye,Ts[1]-sr[1]);if(M.flipState=Ls&&Ls.needsFlipping?1:2,Ls)return Ls}const Ws=qa(ht*Q.getoffsetX(Tt),Kt,Lt,N,Ae,Te,Ut,Wt,ks,ae,q,Fe,Ge,!1,!1,dt,lt,_t,Ct);if(!Ws)return{notEnoughRoom:!0};ms(Ws)}return{}}function Mr(M,g,N,P,F){const{x:q,y:G,z:Q}=P.projectTilePoint(M.x,M.y,g);if(!F)return Ac(q,G,Q,N);const[ae,me,ye]=F.getElevation(M,F.elevation,F.elevationFeature);return Ac(q+ae,G+me,Q+ye,N)}function sa(M,g,N,P,F,q,G,Q){const ae=Mr(M.sub(g)._unit()._add(M),Q,F,G,q);return o.ax(ae,N,ae),o.ay(ae,ae),o.bg(ae,N,ae,P)}function qa(M,g,N,P,F,q,G,Q,ae,me,ye,Ae,Te,Fe,Ye,Ge,dt,lt,_t){const Ct=P?M-g:M+g;let ht=Ct>0?1:-1,Kt=0;P&&(ht*=-1,Kt=Math.PI),ht<0&&(Kt+=Math.PI);let Lt=Q+G+(ht>0?0:1)|0,Wt=F,Tt=F,It=0,Ut=0;const rs=Math.abs(Ct),Zt=[],ks=[];let ms=q,Ws=ms,sr=o.be([]);const as=()=>sa(Ws,ms,Tt,rs-It+1,ye,Te,Ge,dt.canonical);for(;It+Ut<=rs;){if(Lt+=ht,Lt=ae)return null;if(Tt=Wt,Ws=ms,Zt.push(Tt),Fe&&ks.push(Ws),ms=new o.P(me.getx(Lt),me.gety(Lt)),Wt=Ae[Lt],!Wt){const dn=Mr(ms,dt.canonical,ye,Ge,Te);Wt=dn[3]>0?Ae[Lt]=dn:as()}It+=Ut;const Js=o.ax([],Wt,Tt),en=o.bf(Tt,Wt);if(N&&en>0&&Ut>0&&o.bi(sr,Js)/(Ut*en)<_t)return null;Ut=en,sr=Js}Ye&&Te&&(Ae[Lt]&&(Wt=as(),Ut=o.bf(Tt,Wt),sr=o.ax([],Wt,Tt)),Ae[Lt]=Wt);const Xt=(rs-It)/Ut,ws=ms.sub(Ws)._mult(Xt)._add(Ws),Ts=o.bg([],Tt,sr,Xt);let Ls=[0,0,1],wr=sr[0],mr=sr[1];if(lt&&(Ls=Ge.upVector(dt.canonical,ws.x,ws.y),Ls[0]!==0||Ls[1]!==0||Ls[2]!==1)){const Js=[Ls[2],0,-Ls[0]],en=o.bh([],Ls,Js);o.ay(Js,Js),o.ay(en,en),wr=o.bi(sr,Js),mr=o.bi(sr,en)}if(N){const Js=o.bh([],Ls,sr);o.ay(Js,Js),o.bg(Ts,Ts,Js,N*ht)}const fr=Kt+Math.atan2(mr,wr);return Zt.push(Ts),Fe&&ks.push(ws),{point:Ts,angle:fr,path:Zt,tilePath:ks,up:Ls}}function Ja(M,g){const N=g.length,P=N+4*M;g.resize(P),g.float32.fill(-1/0,4*N,4*P)}function jn(M,g,N){const P=g[0],F=g[1];return M[0]=N[0]*P+N[4]*F+N[12],M[1]=N[1]*P+N[5]*F+N[13],M[3]=N[3]*P+N[7]*F+N[15],M}const pd=100;class Vh{constructor(g,N,P=new q0(g.width+200,g.height+200,25),F=new q0(g.width+200,g.height+200,25)){this.transform=g,this.grid=P,this.ignoredGrid=F,this.pitchfactor=Math.cos(g._pitch)*g.cameraToCenterDistance,this.screenRightBoundary=g.width+pd,this.screenBottomBoundary=g.height+pd,this.gridRightBoundary=g.width+200,this.gridBottomBoundary=g.height+200,this.fogState=N,this.clippedSymbols=new Map}clearClippedSymbolsForBucket(g){this.clippedSymbols.delete(g)}markSymbolAsClipped(g,N){let P=this.clippedSymbols.get(g);P||(P=new Set,this.clippedSymbols.set(g,P)),P.add(N)}placeCollisionBox(g,N,P,F,q,G,Q,ae,me,ye,Ae){let Te=P.projectedAnchorX,Fe=P.projectedAnchorY,Ye=P.projectedAnchorZ;const Ge=P.tileAnchorX,dt=P.tileAnchorY,lt=P.elevation,_t=P.tileID,Ct=g.getProjection();if(lt&&_t){const[ks,ms,Ws]=Ct.upVector(_t.canonical,P.tileAnchorX,P.tileAnchorY),sr=Ct.upVectorScale(_t.canonical,this.transform.center.lat,this.transform.worldSize).metersToTile;Te+=ks*lt*sr,Fe+=ms*lt*sr,Ye+=Ws*lt*sr}const ht=g.projection.name==="globe",Kt=g.projection.name==="globe"?o.al(this.transform.zoom):0;if(_t&&ht&&Kt<1&&!G){const ks=1<<_t.canonical.z,ms=o.bo(Ge,dt);o.bp(ms,ms,1/o.an),o.bq(ms,ms,o.bo(_t.canonical.x,_t.canonical.y)),o.bp(ms,ms,1/ks),o.br(ms,ms,o.bo(F[0],F[1])),ms[0]=o.bs(ms[0],-.5,.5),o.bp(ms,ms,o.an);const Ws=o.bt(ms[0],ms[1],o.an/(2*Math.PI),1);o.aE(Ws,Ws,q),Te=o.am(Te,Ws[0],Kt),Fe=o.am(Fe,Ws[1],Kt),Ye=o.am(Ye,Ws[2],Kt)}const Lt=this.projectAndGetPerspectiveRatio(ye,Te,Fe,Ye,P.tileID,Ct.name==="globe"||!!lt||this.transform.pitch>0,Ct),Wt=me*Lt.perspectiveRatio,Tt=(P.x1*N+Q.x-P.padding)*Wt+Lt.point.x,It=(P.y1*N+Q.y-P.padding)*Wt+Lt.point.y,Ut=(P.x2*N+Q.x+P.padding)*Wt+Lt.point.x,rs=(P.y2*N+Q.y+P.padding)*Wt+Lt.point.y,Zt=Lt.perspectiveRatio<=.55||Lt.occluded;return!this.isInsideGrid(Tt,It,Ut,rs)||!ae&&this.grid.hitTest(Tt,It,Ut,rs,Ae)||Zt?{box:[],offscreen:!1,occluded:Lt.occluded}:{box:[Tt,It,Ut,rs],offscreen:this.isOffscreen(Tt,It,Ut,rs),occluded:!1}}placeCollisionCircles(g,N,P,F,q,G,Q,ae,me,ye,Ae,Te,Fe,Ye,Ge,dt){const lt=[],_t=this.transform.elevation,Ct=g.getProjection(),ht=g.elevationType==="road",Kt=!!_t||ht,Lt=o.bu.getAtTileOffsetFunc(dt,this.transform.center.lat,this.transform.worldSize,Ct),Wt=new o.P(P.tileAnchorX,P.tileAnchorY),Tt=new o.P(P.tileAnchorX,P.tileAnchorY);let{x:It,y:Ut,z:rs}=Ct.projectTilePoint(Tt.x,Tt.y,dt.canonical),Zt=null;if(Kt){const en=ht?g.getElevationFeatureForText(F):null;Zt={getElevation:Lt,elevation:_t,elevationFeature:en};const[dn,Kr,Jr]=Lt(Wt,_t,en);It+=dn,Ut+=Kr,rs+=Jr}const ks=Ct.name==="globe",ms=this.projectAndGetPerspectiveRatio(ae,It,Ut,rs,dt,ks||!!_t||this.transform.pitch>0,Ct),{perspectiveRatio:Ws}=ms,sr=(Te?Q/Ws:Q*Ws)/o.by,as=Ac(It,Ut,rs,me),Xt=P.lineOffsetX*sr,ws=P.lineOffsetY*sr,Ts=o.ap(g.layers[0].layout.get("text-max-angle")),Ls=Math.cos(Ts),wr=ms.signedDistanceFromCamera>0?tr(sr,G,Xt,ws,ht&&P.flipState===1,as,Tt,P,q,me,{},Kt&&!Te?Zt:null,Te&&Kt,Ct,dt,Te,Ls):null;let mr=!1,fr=!1,Js=!0;if(wr&&!ms.occluded){const en=.5*Ye*Ws+Ge,dn=new o.P(-100,-100),Kr=new o.P(this.screenRightBoundary,this.screenBottomBoundary),Jr=new Qf,{first:$n,last:oa}=wr,ra=$n.path.length;let Ra=[];for(let na=ra-1;na>=1;na--)Ra.push($n.path[na]);for(let na=1;na(Kt&&!ks&&(uo=Lt(rlna[3]<=0)&&(Ra=[]));let Oa=[];if(Ra.length>0){let na=1/0,ji=-1/0,uo=1/0,rl=-1/0;for(const ko of Ra)na=Math.min(na,ko[0]),uo=Math.min(uo,ko[1]),ji=Math.max(ji,ko[0]),rl=Math.max(rl,ko[1]);ji>=dn.x&&na<=Kr.x&&rl>=dn.y&&uo<=Kr.y&&(Oa=[Ra.map(ko=>new o.P(ko[0],ko[1]))],(naKr.x||uoKr.y)&&(Oa=o.bv(Oa,dn.x,dn.y,Kr.x,Kr.y)))}for(const na of Oa){Jr.reset(na,.25*en);let ji=0;ji=Jr.length<=.5*en?1:Math.ceil(Jr.paddedLength/Ln)+1;for(let uo=0;uo0?(o.aE(ae,ae,g),this.fogState&&q&&Q.name!=="globe"&&(me=function(Te,Fe,Ye,Ge,dt,lt){const _t=lt.calculateFogTileMatrix(dt),Ct=[Fe,Ye,Ge];return o.ah(Ct,Ct,_t),Aa(Te,o.ai(Ct),lt.pitch,lt._fov)}(this.fogState,N,P,F,q.toUnwrapped(),this.transform)>.9)):jn(ae,ae,g);const ye=ae[3];return{point:new o.P((ae[0]/ye+1)/2*this.transform.width+pd,(-ae[1]/ye+1)/2*this.transform.height+pd),perspectiveRatio:Math.min(.5+this.transform.getCameraToCenterDistance(Q)/ye*.5,1.5),signedDistanceFromCamera:ye,occluded:G&&ae[2]>ye||me}}isOffscreen(g,N,P,F){return P=this.screenRightBoundary||Fthis.screenBottomBoundary}isInsideGrid(g,N,P,F){return P>=0&&g=0&&NP.collisionGroupID===N}}return this.collisionGroups[g]}}function _h(M,g,N,P,F){const{horizontalAlign:q,verticalAlign:G}=o.bF(M),Q=-(q-.5)*g,ae=-(G-.5)*N,me=o.bG(M,P);return new o.P(Q+me[0]*F,ae+me[1]*F)}function Rp(M,g,N,P,F){const q=new o.P(M,g);return N&&q._rotate(P?F:-F),q}class qi{constructor(g,N,P,F,q,G){this.transform=g.clone(),this.projection=g.projection.name,this.collisionIndex=new Vh(this.transform,q),this.buildingIndex=G,this.frontCutoffStart=0,this.placements={},this.opacities={},this.variableOffsets={},this.stale=!1,this.commitTime=0,this.fadeDuration=N,this.retainedQueryData={},this.collisionGroups=new Oi(P),this.collisionCircleArrays={},this.prevPlacement=F,F&&(F.prevPlacement=void 0),this.placedOrientations={},this.lastReplacementSourceUpdateTime=0}getBucketParts(g,N,P,F,q=1){const G=P.getBucket(N),Q=P.latestFeatureIndex;if(!G||!Q||N.fqid!==G.layerIds[0])return;const ae=G.layers[0].layout,me=G.layers[0].paint,ye=P.collisionBoxArray,Ae=Math.pow(2,this.transform.zoom-P.tileID.overscaledZ),Te=P.tileSize/o.an,Fe=P.tileID.toUnwrapped();this.transform.setProjection(G.projection);const Ye=(Ge=P.tileID,dt=G.getProjection(),lt=this.transform,dt.name===this.projection?lt.calculateProjMatrix(Ge.toUnwrapped()):V1(lt,dt,Ge));var Ge,dt,lt;const _t=ae.get("text-pitch-alignment")==="map",Ct=ae.get("text-rotation-alignment")==="map";N.compileFilter(N.options);const ht=N.dynamicFilter(),Kt=N.dynamicFilterNeedsFeature(),Lt=N.dynamicFilterNeedsGeometry(),Wt=this.transform.calculatePixelsToTileUnitsMatrix(P),Tt=_c(Ye,P.tileID.canonical,_t,Ct,this.transform,G.getProjection(),Wt);let It=null;const Ut=G.getProjection().createInversionMatrix(this.transform,P.tileID.canonical);if(_t){const ws=Am(Ye,P.tileID.canonical,_t,Ct,this.transform,G.getProjection(),Wt);It=o.aD([],this.transform.labelPlaneMatrix,ws)}let rs=null;ht&&P.latestFeatureIndex&&(rs={unwrappedTileID:Fe,dynamicFilter:ht,dynamicFilterNeedsFeature:Kt,needGeometry:Lt}),this.retainedQueryData[G.bucketInstanceId]=new wi(G.bucketInstanceId,Q,G.sourceLayerIndex,G.index,P.tileID);const[Zt,ks]=G.layers[0].layout.get("text-size-scale-range"),ms=o.aC(q,Zt,ks),[Ws,sr]=ae.get("icon-size-scale-range"),as=o.aC(q,Ws,sr),Xt={bucket:G,layout:ae,paint:me,posMatrix:Ye,invMatrix:Ut,mercatorCenter:[o.aH(this.transform.center.lng),o.aL(this.transform.center.lat)],textLabelPlaneMatrix:Tt,labelToScreenMatrix:It,clippingData:rs,scale:Ae,textPixelRatio:Te,holdingForFade:P.holdingForFade(),collisionBoxArray:ye,partiallyEvaluatedTextSize:o.bj(G.textSizeData,this.transform.zoom,ms),partiallyEvaluatedIconSize:o.bj(G.iconSizeData,this.transform.zoom,as),collisionGroup:this.collisionGroups.get(G.sourceID),latestFeatureIndex:P.latestFeatureIndex};if(F)for(const ws of G.sortKeyRanges){const{sortKey:Ts,symbolInstanceStart:Ls,symbolInstanceEnd:wr}=ws;g.push({sortKey:Ts,symbolInstanceStart:Ls,symbolInstanceEnd:wr,parameters:Xt})}else g.push({symbolInstanceStart:0,symbolInstanceEnd:G.symbolInstances.length,parameters:Xt})}attemptAnchorPlacement(g,N,P,F,q,G,Q,ae,me,ye,Ae,Te,Fe,Ye,Ge,dt,lt,_t,Ct,ht,Kt){const{textOffset0:Lt,textOffset1:Wt,crossTileID:Tt}=Ge,It=[Lt,Wt],Ut=_h(g,G,Q,It,ae),rs=this.collisionIndex.placeCollisionBox(lt,ae,N,P,F,q,Rp(Ut.x,Ut.y,me,ye,this.transform.angle),Ye,Ae,Te,Fe.predicate);if(Ct){const Zt=lt.getSymbolInstanceIconSize(Kt,this.transform.zoom,Ge.placedIconSymbolIndex);if(this.collisionIndex.placeCollisionBox(lt,Zt,Ct,P,F,q,Rp(Ut.x,Ut.y,me,ye,this.transform.angle),Ye,Ae,Te,Fe.predicate).box.length===0)return}if(rs.box.length>0){let Zt;return this.prevPlacement&&this.prevPlacement.variableOffsets[Tt]&&this.prevPlacement.placements[Tt]&&this.prevPlacement.placements[Tt].text&&(Zt=this.prevPlacement.variableOffsets[Tt].anchor),this.variableOffsets[Tt]={textOffset:It,width:G,height:Q,anchor:g,textScale:ae,prevAnchor:Zt},this.markUsedJustification(lt,g,Ge,_t),lt.allowVerticalPlacement&&(this.markUsedOrientation(lt,_t,Ge),this.placedOrientations[Tt]=_t),{shift:Ut,placedGlyphBoxes:rs}}}placeLayerBucketPart(g,N,P,F,q=1){const{bucket:G,layout:Q,paint:ae,posMatrix:me,textLabelPlaneMatrix:ye,labelToScreenMatrix:Ae,clippingData:Te,textPixelRatio:Fe,mercatorCenter:Ye,invMatrix:Ge,holdingForFade:dt,collisionBoxArray:lt,partiallyEvaluatedTextSize:_t,partiallyEvaluatedIconSize:Ct,collisionGroup:ht,latestFeatureIndex:Kt}=g.parameters,Lt=Q.get("text-optional"),Wt=Q.get("icon-optional"),Tt=Q.get("text-allow-overlap"),It=Q.get("icon-allow-overlap"),Ut=Q.get("text-rotation-alignment")==="map",rs=Q.get("icon-rotation-alignment")==="map",Zt=Q.get("text-pitch-alignment")==="map",ks=ae.get("symbol-z-offset"),ms=Q.get("symbol-elevation-reference")==="sea",Ws=Q.get("symbol-placement"),[sr,as]=Q.get("text-size-scale-range"),[Xt,ws]=Q.get("icon-size-scale-range"),Ts=o.aC(q,sr,as),Ls=o.aC(q,Xt,ws),wr=Q.get("text-variable-anchor"),mr=Ut&&Ws!=="point",fr=rs&&Ws!=="point",Js=wr&&G.hasTextData(),en=G.hasIconTextFit()&&Js&&G.hasIconData();this.transform.setProjection(G.projection);const dn=Js||mr,Kr=fr||en;let Jr=Tt&&(It||!G.hasIconData()||Wt),$n=It&&(Tt||!G.hasTextData()||Lt);const oa=!ks.isConstant();!G.collisionArrays&<&&G.deserializeCollisionBoxes(lt),P&&F&&G.updateCollisionDebugBuffers(this.transform.zoom,lt,Ts,Ls);const ra=(Ln,Oa,na)=>{const{crossTileID:ji,numVerticalGlyphVertices:uo}=Ln;let rl=null;if(Te&&Te.dynamicFilterNeedsFeature||oa){const Eo=this.retainedQueryData[G.bucketInstanceId],Do=Kt.loadFeature({featureIndex:Ln.featureIndex,bucketIndex:Eo.bucketIndex,sourceLayerIndex:Eo.sourceLayerIndex,layoutVertexArrayOffset:0}),so=Do.properties?Do.properties.worldview:null;if(G.localizable&&G.worldview&&typeof so=="string")if(so==="all")Do.properties.$localized=!0;else{if(!so.split(",").includes(G.worldview))return;Do.properties.$localized=!0,Do.properties.worldview=G.worldview}rl=Te&&Te.needGeometry?o.bD(Do,!0):Do}if(Te&&!(0,Te.dynamicFilter)({zoom:this.transform.zoom,pitch:this.transform.pitch,worldview:G.worldview},rl,this.retainedQueryData[G.bucketInstanceId].tileID.canonical,new o.P(Ln.tileAnchorX,Ln.tileAnchorY),this.transform.calculateDistanceTileData(Te.unwrappedTileID)))return this.placements[ji]=new Jf(!1,!1,!1,!0),void N.add(ji);const ko=ks.evaluate(rl,{});if((Ln.zOffset||0)+(ko||0)>0&&this.frontCutoffStart>0){const Eo=2*this.frontCutoffStart-1,Do=[Ln.tileAnchorX,Ln.tileAnchorY,0,1],so=o.aE(o.bE(),Do,me);if(so[1]/so[3]{Eo.tileID=this.retainedQueryData[G.bucketInstanceId].tileID;const Do=this.transform.elevation;Eo.elevation=ms?ko:ko+o.bu.getAtTileOffset(Eo.tileID,new o.P(Eo.tileAnchorX,Eo.tileAnchorY),Do,Zc),Eo.elevation+=Ln.zOffset},lp=na.textBox;if(lp){eu(lp);const Eo=so=>{let sc=o.bk.horizontal;if(G.allowVerticalPlacement&&!so&&this.prevPlacement){const Ch=this.prevPlacement.placedOrientations[ji];Ch&&(this.placedOrientations[ji]=Ch,sc=Ch,this.markUsedOrientation(G,sc,Ln))}return sc},Do=(so,sc)=>{if(G.allowVerticalPlacement&&uo>0&&na.verticalTextBox){for(const Ch of G.writingModes)if(Ch===o.bk.vertical?(ma=sc(),Yo=ma):ma=so(),ma&&ma.box&&ma.box.length)break}else ma=so()};if(wr){let so=wr;if(this.prevPlacement&&this.prevPlacement.variableOffsets[ji]){const Ml=this.prevPlacement.variableOffsets[ji];so.indexOf(Ml.anchor)>0&&(so=so.filter(cp=>cp!==Ml.anchor),so.unshift(Ml.anchor))}const sc=(Ml,cp,gb)=>{const Uw=G.getSymbolInstanceTextSize(_t,Ln,this.transform.zoom,Oa),qw=(Ml.x2-Ml.x1)*Uw+2*Ml.padding,rN=(Ml.y2-Ml.y1)*Uw+2*Ml.padding,Lv=Ln.hasIconTextFit&&!It?cp:null;Lv&&eu(Lv);let iy={box:[],offscreen:!1,occluded:!1};const nN=Tt?2*so.length:so.length;for(let Nf=0;Nf=so.length,Ln,Oa,G,gb,Lv,_t,Ct);if(xb&&(iy=xb.placedGlyphBoxes,iy&&iy.box&&iy.box.length)){Ii=!0,Pi=xb.shift;break}}return iy};Do(()=>sc(lp,na.iconBox,o.bk.horizontal),()=>{const Ml=na.verticalTextBox;return Ml&&eu(Ml),G.allowVerticalPlacement&&!(ma&&ma.box&&ma.box.length)&&uo>0&&Ml?sc(Ml,na.verticalIconBox,o.bk.vertical):{box:null,offscreen:null,occluded:null}}),ma&&(Ii=ma.box,Ta=ma.offscreen,So=ma.occluded);const Ch=Eo(!(!ma||!ma.box));if(!Ii&&this.prevPlacement){const Ml=this.prevPlacement.variableOffsets[ji];Ml&&(this.variableOffsets[ji]=Ml,this.markUsedJustification(G,Ml.anchor,Ln,Ch))}}else{const so=(sc,Ch)=>{const Ml=G.getSymbolInstanceTextSize(_t,Ln,this.transform.zoom,Oa),cp=this.collisionIndex.placeCollisionBox(G,Ml,sc,Ye,Ge,dn,new o.P(0,0),Tt,Fe,me,ht.predicate);return cp&&cp.box&&cp.box.length&&(this.markUsedOrientation(G,Ch,Ln),this.placedOrientations[ji]=Ch),cp};Do(()=>so(lp,o.bk.horizontal),()=>{const sc=na.verticalTextBox;return G.allowVerticalPlacement&&uo>0&&sc?(eu(sc),so(sc,o.bk.vertical)):{box:null,offscreen:null,occluded:null}}),Eo(!!(ma&&ma.box&&ma.box.length))}}if(ho=ma,Ii=ho&&ho.box&&ho.box.length>0,Ta=ho&&ho.offscreen,So=ho&&ho.occluded,Ln.useRuntimeCollisionCircles){const Eo=Ln.centerJustifiedTextSymbolIndex>=0?Ln.centerJustifiedTextSymbolIndex:Ln.verticalPlacedTextSymbolIndex,Do=G.text.placedSymbolArray.get(Eo),so=o.bl(G.textSizeData,_t,Do),sc=Q.get("text-padding");cc=this.collisionIndex.placeCollisionCircles(G,Tt,Do,Eo,G.lineVertexArray,G.glyphOffsetArray,so,me,ye,Ae,P,Zt,ht.predicate,Ln.collisionCircleDiameter*so/o.by,sc,this.retainedQueryData[G.bucketInstanceId].tileID),Ii=Tt||cc.circles.length>0&&!cc.collisionDetected,Ta=Ta&&cc.offscreen,So=cc.occluded}if(na.iconFeatureIndex&&(rh=na.iconFeatureIndex),na.iconBox){const Eo=Do=>{eu(Do);const so=Ln.hasIconTextFit&&Pi?Rp(Pi.x,Pi.y,Ut,Zt,this.transform.angle):new o.P(0,0),sc=G.getSymbolInstanceIconSize(Ct,this.transform.zoom,Ln.placedIconSymbolIndex);return this.collisionIndex.placeCollisionBox(G,sc,Do,Ye,Ge,Kr,so,It,Fe,me,ht.predicate)};Yo&&Yo.box&&Yo.box.length&&na.verticalIconBox?(ei=Eo(na.verticalIconBox),Ca=ei.box.length>0):(ei=Eo(na.iconBox),Ca=ei.box.length>0),Ta=Ta&&ei.offscreen,dl=ei.occluded}const Vi=Lt||Ln.numHorizontalGlyphVertices===0&&uo===0,Wp=Wt||Ln.numIconVertices===0;if(Vi||Wp?Wp?Vi||(Ca=Ca&&Ii):Ii=Ca&&Ii:Ca=Ii=Ca&&Ii,Ii&&ho&&ho.box&&this.collisionIndex.insertCollisionBox(ho.box,Q.get("text-ignore-placement"),G.bucketInstanceId,Yo&&Yo.box&&Ic?Ic:_o,ht.ID),Ca&&ei&&this.collisionIndex.insertCollisionBox(ei.box,Q.get("icon-ignore-placement"),G.bucketInstanceId,rh,ht.ID),cc&&(Ii&&this.collisionIndex.insertCollisionCircles(cc.circles,Q.get("text-ignore-placement"),G.bucketInstanceId,_o,ht.ID),P)){const Eo=G.bucketInstanceId;let Do=this.collisionCircleArrays[Eo];Do===void 0&&(Do=this.collisionCircleArrays[Eo]=new un);for(let so=0;so=0;--Oa){const na=Ln[Oa];ra(G.symbolInstances.get(na),na,G.collisionArrays[na])}G.hasAnyZOffset&&o.w(`${G.layerIds[0]} layer symbol-z-elevate: symbols are not sorted by elevation if symbol-z-order is evaluated to viewport-y`)}else if(G.hasAnyZOffset){const Ln=G.getSortedIndexesByZOffset();for(let Oa=0;Oa=0&&(g.text.placedSymbolArray.get(q).crossTileID=Ae>=0&&q!==Ae?0:me),G>=0&&(g.text.placedSymbolArray.get(G).crossTileID=Ae>=0&&G!==Ae?0:me),Q>=0&&(g.text.placedSymbolArray.get(Q).crossTileID=Ae>=0&&Q!==Ae?0:me),ae>=0&&(g.text.placedSymbolArray.get(ae).crossTileID=Ae>=0&&ae!==Ae?0:me)}markUsedOrientation(g,N,P){const F=N===o.bk.horizontal||N===o.bk.horizontalOnly?N:0,q=N===o.bk.vertical?N:0,{leftJustifiedTextSymbolIndex:G,centerJustifiedTextSymbolIndex:Q,rightJustifiedTextSymbolIndex:ae,verticalPlacedTextSymbolIndex:me}=P,ye=g.text.placedSymbolArray;G>=0&&(ye.get(G).placedOrientation=F),Q>=0&&(ye.get(Q).placedOrientation=F),ae>=0&&(ye.get(ae).placedOrientation=F),me>=0&&(ye.get(me).placedOrientation=q)}commit(g){this.commitTime=g,this.zoomAtLastRecencyCheck=this.transform.zoom;const N=this.prevPlacement;let P=!1;this.prevZoomAdjustment=N?N.zoomAdjustment(this.transform.zoom):0;const F=N?N.symbolFadeChange(g):1,q=N?N.opacities:{},G=N?N.variableOffsets:{},Q=N?N.placedOrientations:{};for(const ae in this.placements){const me=this.placements[ae],ye=q[ae];ye?(this.opacities[ae]=new Ag(ye,F,me.text,me.icon,null,me.clipped),P=P||me.text!==ye.text.placed||me.icon!==ye.icon.placed):(this.opacities[ae]=new Ag(null,F,me.text,me.icon,me.skipFade,me.clipped),P=P||me.text||me.icon)}for(const ae in q){const me=q[ae];if(!this.opacities[ae]){const ye=new Ag(me,F,!1,!1);ye.isHidden()||(this.opacities[ae]=ye,P=P||me.text.placed||me.icon.placed)}}for(const ae in G)this.variableOffsets[ae]||!this.opacities[ae]||this.opacities[ae].isHidden()||(this.variableOffsets[ae]=G[ae]);for(const ae in Q)this.placedOrientations[ae]||!this.opacities[ae]||this.opacities[ae].isHidden()||(this.placedOrientations[ae]=Q[ae]);P?this.lastPlacementChangeTime=g:typeof this.lastPlacementChangeTime!="number"&&(this.lastPlacementChangeTime=N?N.lastPlacementChangeTime:g)}updateLayerOpacities(g,N,P,F){F&&(this.lastReplacementSourceUpdateTime=F.updateTime);const q=new Set;for(const G of N){const Q=G.getBucket(g);Q&&G.latestFeatureIndex&&g.fqid===Q.layerIds[0]&&(this.updateBucketOpacities(Q,q,G,G.collisionBoxArray,P,F,G.tileID,g.scope),Q.elevationType==="offset"&&this.buildingIndex&&this.buildingIndex.updateZOffset(Q,G.tileID),Q.elevationType==="road"&&Q.updateRoadElevation(G.tileID.canonical),Q.updateZOffset())}}updateBucketOpacities(g,N,P,F,q,G,Q,ae){g.hasTextData()&&g.text.opacityVertexArray.clear(),g.hasIconData()&&g.icon.opacityVertexArray.clear(),g.hasIconCollisionBoxData()&&g.iconCollisionBox.collisionVertexArray.clear(),g.hasTextCollisionBoxData()&&g.textCollisionBox.collisionVertexArray.clear();const me=g.layers[0].layout,ye=g.layers[0].paint,Ae=!!g.layers[0].dynamicFilter(),Te=new Ag(null,0,!1,!1,!0),Fe=me.get("text-allow-overlap"),Ye=me.get("icon-allow-overlap"),Ge=me.get("text-variable-anchor"),dt=me.get("text-rotation-alignment")==="map",lt=me.get("text-pitch-alignment")==="map",_t=ye.get("symbol-z-offset"),Ct=me.get("symbol-elevation-reference")==="sea",ht=!_t.isConstant(),Kt=new Ag(null,0,Fe&&(Ye||!g.hasIconData()||me.get("icon-optional")),Ye&&(Fe||!g.hasTextData()||me.get("text-optional")),!0);!g.collisionArrays&&F&&(g.hasIconCollisionBoxData()||g.hasTextCollisionBoxData())&&g.deserializeCollisionBoxes(F);const Lt=(Tt,It,Ut)=>{for(let rs=0;rs0||rs>0,wr=ks>0,mr=this.placedOrientations[Zt],fr=mr===o.bk.vertical,Js=mr===o.bk.horizontal||mr===o.bk.horizontalOnly;!Ls&&!wr||Ts.isHidden()||Wt++;let en=!1;if((Ls||wr)&&G)for(const dn of g.activeReplacements){if(o.bz(dn,q,o.bA.Symbol,ae)||dn.min.x>ms||ms>dn.max.x||dn.min.y>Ws||Ws>dn.max.y)continue;const Kr=o.bB(ms,Ws,Q.canonical,dn.footprintTileId.canonical);if(en=o.bC(Kr,dn.footprint),en)break}if(en&&this.collisionIndex.markSymbolAsClipped(g.bucketInstanceId,It.featureIndex),Ls){const dn=en?Bp:Fp(Ts.text);Lt(g.text,Ut,fr?Bp:dn),Lt(g.text,rs,Js?Bp:dn);const Kr=Ts.text.isHidden(),{leftJustifiedTextSymbolIndex:Jr,centerJustifiedTextSymbolIndex:$n,rightJustifiedTextSymbolIndex:oa,verticalPlacedTextSymbolIndex:ra}=It,Ra=g.text.placedSymbolArray,Ln=Kr||fr?1:0;Jr>=0&&(Ra.get(Jr).hidden=Ln),$n>=0&&(Ra.get($n).hidden=Ln),oa>=0&&(Ra.get(oa).hidden=Ln),ra>=0&&(Ra.get(ra).hidden=Kr||Js?1:0);const Oa=this.variableOffsets[Zt];Oa&&this.markUsedJustification(g,Oa.anchor,It,mr);const na=this.placedOrientations[Zt];na&&(this.markUsedJustification(g,"left",It,na),this.markUsedOrientation(g,na,It))}if(wr){const dn=en?Bp:Fp(Ts.icon),{placedIconSymbolIndex:Kr,verticalPlacedIconSymbolIndex:Jr}=It,$n=g.icon.placedSymbolArray,oa=Ts.icon.isHidden()?1:0;Kr>=0&&(Lt(g.icon,ks,fr?Bp:dn),$n.get(Kr).hidden=oa),Jr>=0&&(Lt(g.icon,It.numVerticalIconVertices,Js?Bp:dn),$n.get(Jr).hidden=oa)}if(g.hasIconCollisionBoxData()||g.hasTextCollisionBoxData()){const dn=g.collisionArrays[Tt];if(dn){let Kr=new o.P(0,0),Jr=!0;if(dn.textBox||dn.verticalTextBox){if(Ge){const oa=this.variableOffsets[Zt];oa?(Kr=_h(oa.anchor,oa.width,oa.height,oa.textOffset,oa.textScale),dt&&Kr._rotate(lt?this.transform.angle:-this.transform.angle)):Jr=!1}Ae&&(Jr=!Ts.clipped),dn.textBox&&Op(g.textCollisionBox.collisionVertexArray,Ts.text.placed,!Jr||fr,Xt,Ct,Kr.x,Kr.y),dn.verticalTextBox&&Op(g.textCollisionBox.collisionVertexArray,Ts.text.placed,!Jr||Js,Xt,Ct,Kr.x,Kr.y)}const $n=Jr&&!!(!Js&&dn.verticalIconBox);dn.iconBox&&Op(g.iconCollisionBox.collisionVertexArray,Ts.icon.placed,$n,Xt,Ct,It.hasIconTextFit?Kr.x:0,It.hasIconTextFit?Kr.y:0),dn.verticalIconBox&&Op(g.iconCollisionBox.collisionVertexArray,Ts.icon.placed,!$n,Xt,Ct,It.hasIconTextFit?Kr.x:0,It.hasIconTextFit?Kr.y:0)}}}if(g.fullyClipped=Wt===0,g.sortFeatures(this.transform.angle),this.retainedQueryData[g.bucketInstanceId]&&(this.retainedQueryData[g.bucketInstanceId].featureSortOrder=g.featureSortOrder),g.hasTextData()&&g.text.opacityVertexBuffer&&g.text.opacityVertexBuffer.updateData(g.text.opacityVertexArray),g.hasIconData()&&g.icon.opacityVertexBuffer&&g.icon.opacityVertexBuffer.updateData(g.icon.opacityVertexArray),g.hasIconCollisionBoxData()&&g.iconCollisionBox.collisionVertexBuffer&&g.iconCollisionBox.collisionVertexBuffer.updateData(g.iconCollisionBox.collisionVertexArray),g.hasTextCollisionBoxData()&&g.textCollisionBox.collisionVertexBuffer&&g.textCollisionBox.collisionVertexBuffer.updateData(g.textCollisionBox.collisionVertexArray),g.bucketInstanceId in this.collisionCircleArrays){const Tt=this.collisionCircleArrays[g.bucketInstanceId];g.placementInvProjMatrix=Tt.invProjMatrix,g.placementViewportMatrix=Tt.viewportMatrix,g.collisionCircleArray=Tt.circles,delete this.collisionCircleArrays[g.bucketInstanceId]}}symbolFadeChange(g){return this.fadeDuration===0?1:(g-this.commitTime)/this.fadeDuration+this.prevZoomAdjustment}zoomAdjustment(g){return Math.max(0,(this.transform.zoom-g)/1.5)}hasTransitions(g){return g-this.lastPlacementChangeTimeg}isStale(){return this.stale}setStale(){this.stale=!0}}function Op(M,g,N,P,F,q,G){M.emplaceBack(g?1:0,N?1:0,q||0,G||0,P,F?1:0),M.emplaceBack(g?1:0,N?1:0,q||0,G||0,P,F?1:0),M.emplaceBack(g?1:0,N?1:0,q||0,G||0,P,F?1:0),M.emplaceBack(g?1:0,N?1:0,q||0,G||0,P,F?1:0)}const V0=Math.pow(2,25),G1=Math.pow(2,24),Eu=Math.pow(2,17),Al=Math.pow(2,16),iM=Math.pow(2,9),H0=Math.pow(2,8),W1=Math.pow(2,1);function Fp(M){if(M.opacity===0&&!M.placed)return 0;if(M.opacity===1&&M.placed)return 4294967295;const g=M.placed?1:0,N=Math.floor(127*M.opacity);return N*V0+g*G1+N*Eu+g*Al+N*iM+g*H0+N*W1+g}const Bp=0;class aw{constructor(g){this._sortAcrossTiles=g.layout.get("symbol-z-order")!=="viewport-y"&&g.layout.get("symbol-sort-key").constantOr(1)!==void 0,this._currentTileIndex=0,this._currentPartIndex=0,this._seenCrossTileIDs=new Set,this._bucketParts=[]}continuePlacement(g,N,P,F,q,G){const Q=this._bucketParts;for(;this._currentTileIndexae.sortKey-me.sortKey));this._currentPartIndex{const ae=o.o.now()-G;return!this.isFullPlacementRequested()&&this._fadeDuration!==0&&ae>2};for(;this._currentPlacementIndex>=0;){const ae=N[g[this._currentPlacementIndex]],me=this.placement.collisionIndex.transform.zoom;if(ae.type==="symbol"&&ae.visibility!=="none"&&(!ae.minzoom||ae.minzoom<=me)&&(!ae.maxzoom||ae.maxzoom>me)){const ye=ae,Ae=ye.layout.get("symbol-z-elevate"),Te=ye.layout.get("symbol-sort-key").constantOr(1)!==void 0,Fe=ye.layout.get("symbol-z-order"),Ye=Fe==="viewport-y"||Fe==="auto"&&!(Fe!=="viewport-y"&&Te),Ge=ye.layout.get("text-allow-overlap")||ye.layout.get("icon-allow-overlap")||ye.layout.get("text-ignore-placement")||ye.layout.get("icon-ignore-placement"),dt=Ye&&Ge,lt=this._inProgressLayer=this._inProgressLayer||new aw(ye),_t=o.F(ae.source,ae.scope);if(lt.continuePlacement(Ae||dt?F[_t]:P[_t],this.placement,this._showCollisionBoxes,ae,Q,q))return;delete this._inProgressLayer}this._currentPlacementIndex--}this._forceFullPlacement=!1,this._done=!0}commit(g){return this.placement.commit(g),this.placement}}const Md=512/o.an/2;class Im{constructor(g,N,P){this.tileID=g,this.bucketInstanceId=P,this.index=new o.bI(N.length,16,Int32Array),this.keys=[],this.crossTileIDs=[];const F=g.canonical.x*o.an,q=g.canonical.y*o.an;for(let G=0;Gdt-lt);for(const dt of Ge){const lt=this.crossTileIDs[dt];if(this.keys[dt]===ye&&!P.has(lt)){P.add(lt),me.crossTileID=lt;break}}}}}class Id{constructor(){this.maxCrossTileID=0}generate(){return++this.maxCrossTileID}}class mf{constructor(){this.indexes={},this.usedCrossTileIDs={},this.lng=0}handleWrapJump(g){const N=Math.round((g-this.lng)/360);if(N!==0)for(const P in this.indexes){const F=this.indexes[P],q={};for(const G in F){const Q=F[G];Q.tileID=Q.tileID.unwrapTo(Q.tileID.wrap+N),q[Q.tileID.key]=Q}this.indexes[P]=q}this.lng=g}addBucket(g,N,P){if(this.indexes[g.overscaledZ]&&this.indexes[g.overscaledZ][g.key]){if(this.indexes[g.overscaledZ][g.key].bucketInstanceId===N.bucketInstanceId)return!1;this.removeBucketCrossTileIDs(g.overscaledZ,this.indexes[g.overscaledZ][g.key])}for(let q=0;qg.overscaledZ)for(const Q in G){const ae=G[Q];ae.tileID.isChildOf(g)&&ae.findMatches(N.symbolInstances,g,F)}else{const Q=G[g.scaledTo(Number(q)).key];Q&&Q.findMatches(N.symbolInstances,g,F)}}for(let q=0;q{N[P]=!0});for(const P in this.layerIndexes)N[P]||delete this.layerIndexes[P]}}const yl=771;class zn{constructor(g,N,P,F){this.blendFunction=g,this.blendColor=N.toNonPremultipliedRenderColor(null),this.mask=P,this.blendEquation=F}}zn.Replace=[1,0,1,0],zn.disabled=new zn(zn.Replace,o.aq.transparent,[!1,!1,!1,!1]),zn.unblended=new zn(zn.Replace,o.aq.transparent,[!0,!0,!0,!0]),zn.alphaBlended=new zn([1,yl,1,yl],o.aq.transparent,[!0,!0,!0,!0]),zn.alphaBlendedNonPremultiplied=new zn([770,yl,770,yl],o.aq.transparent,[!0,!0,!0,!0]),zn.multiply=new zn([774,0,774,0],o.aq.transparent,[!0,!0,!0,!0]),zn.multiplyAccumulateAlpha=new zn([774,0,1,yl],o.aq.transparent,[!0,!0,!0,!0]),zn.additive=new zn([1,1,1,1],o.aq.transparent,[!0,!0,!0,!0]);class Wr{constructor(g,N,P){this.func=g,this.mask=N,this.range=P}}Wr.ReadOnly=!1,Wr.ReadWrite=!0,Wr.disabled=new Wr(519,Wr.ReadOnly,[0,1]);const sl=7680;class Gn{constructor(g,N,P,F,q,G){this.test=g,this.ref=N,this.mask=P,this.fail=F,this.depthFail=q,this.pass=G}}Gn.disabled=new Gn({func:519,mask:0},0,0,sl,sl,sl);const Pm=1029,Hh=2305;class _n{constructor(g,N,P){this.enable=g,this.mode=N,this.frontFace=P}}function G0(M,g){const N=o.bO(M,3);o.bR(M,g),o.bW(M,3,N)}function iw(M,g){const N=o.bL([]);return o.bM(N,N,-g),o.bN(N,N,-M),N}function hv(M,g){const N=[M[0],M[1],0],P=[g[0],g[1],0];if(o.ai(N)>=1e-15){const G=o.ay([],N);o.bJ(P,G,o.bi(P,G)),g[0]=P[0],g[1]=P[1]}const F=o.bh([],g,M);if(o.bK(F)<1e-15)return null;const q=Math.atan2(-F[1],F[0]);return iw(Math.atan2(Math.sqrt(M[0]*M[0]+M[1]*M[1]),-M[2]),q)}_n.disabled=new _n(!1,Pm,Hh),_n.backCCW=new _n(!0,Pm,Hh),_n.backCW=new _n(!0,Pm,2304),_n.frontCW=new _n(!0,1028,2304),_n.frontCCW=new _n(!0,1028,Hh);class Y1{constructor(g,N){this.position=g,this.orientation=N}get position(){return this._position}set position(g){if(g){const N=g instanceof o.ag?g:new o.ag(g[0],g[1],g[2]);this._renderWorldCopies&&(N.x=o.bs(N.x,0,1)),this._position=N}else this._position=null}lookAtPoint(g,N,P){if(this.orientation=null,!this.position)return;const F=this.position,q=P||(this._elevation?this._elevation.getAtPointOrZero(o.ag.fromLngLat(g)):0),G=o.ag.fromLngLat(g,q),Q=[G.x-F.x,G.y-F.y,G.z-F.z];N||(N=[0,0,1]),N[2]=Math.abs(N[2]),this.orientation=hv(Q,N)}setPitchBearing(g,N){this.orientation=iw(o.ap(g),o.ap(-N))}}class bx{constructor(g,N){this._transform=o.b9([]),this.orientation=N,this.position=g}get mercatorPosition(){const g=this.position;return new o.ag(g[0],g[1],g[2])}get position(){const g=o.bO(this._transform,3);return[g[0],g[1],g[2]]}set position(g){var N;g&&o.bW(this._transform,3,[(N=g)[0],N[1],N[2],1])}get orientation(){return this._orientation}set orientation(g){this._orientation=g||o.bL([]),g&&G0(this._transform,this._orientation)}getPitchBearing(){const g=this.forward(),N=this.right();return{bearing:Math.atan2(-N[1],N[0]),pitch:Math.atan2(Math.sqrt(g[0]*g[0]+g[1]*g[1]),-g[2])}}setPitchBearing(g,N){this._orientation=iw(g,N),G0(this._transform,this._orientation)}forward(){const g=o.bO(this._transform,2);return[-g[0],-g[1],-g[2]]}up(){const g=o.bO(this._transform,1);return[-g[0],-g[1],-g[2]]}right(){const g=o.bO(this._transform,0);return[g[0],g[1],g[2]]}getCameraToWorld(g,N){const P=new Float64Array(16);return o.b7(P,this.getWorldToCamera(g,N)),P}getCameraToWorldMercator(){return this._transform}getWorldToCameraPosition(g,N,P){const F=this.position;o.bJ(F,F,-g);const q=new Float64Array(16);return o.bP(q,[P,P,P]),o.bx(q,q,F),q[10]*=N,q}getWorldToCamera(g,N){const P=new Float64Array(16),F=new Float64Array(4),q=this.position;return o.bQ(F,this._orientation),o.bJ(q,q,-g),o.bR(P,F),o.bx(P,P,q),P[1]*=-1,P[5]*=-1,P[9]*=-1,P[13]*=-1,P[8]*=N,P[9]*=N,P[10]*=N,P[11]*=N,P}getCameraToClipPerspective(g,N,P,F){const q=new Float64Array(16);return o.bS(q,g,N,P,F),q}getCameraToClipOrthographic(g,N,P,F,q,G){const Q=new Float64Array(16);return o.bT(Q,g,N,P,F,q,G),Q}getDistanceToElevation(g,N=!1){const P=g===0?0:o.bU(g,N?o.bV(this.position[1]):this.position[1]),F=this.forward();return(P-this.position[2])/F[2]}clone(){return new bx([...this.position],[...this.orientation])}}const tp=(M,g)=>({u_matrix:M,u_ground_shadow_factor:g});class Gh{constructor(g=0,N=0,P=0,F=0){if(isNaN(g)||g<0||isNaN(N)||N<0||isNaN(P)||P<0||isNaN(F)||F<0)throw new Error("Invalid value for edge-insets, top, bottom, left and right must all be numbers");this.top=g,this.bottom=N,this.left=P,this.right=F}interpolate(g,N,P){return N.top!=null&&g.top!=null&&(this.top=o.am(g.top,N.top,P)),N.bottom!=null&&g.bottom!=null&&(this.bottom=o.am(g.bottom,N.bottom,P)),N.left!=null&&g.left!=null&&(this.left=o.am(g.left,N.left,P)),N.right!=null&&g.right!=null&&(this.right=o.am(g.right,N.right,P)),this}getCenter(g,N){const P=o.aC((this.left+g-this.right)/2,0,g),F=o.aC((this.top+N-this.bottom)/2,0,N);return new o.P(P,F)}equals(g){return this.top===g.top&&this.bottom===g.bottom&&this.left===g.left&&this.right===g.right}clone(){return new Gh(this.top,this.bottom,this.left,this.right)}toJSON(){return{top:this.top,bottom:this.bottom,left:this.left,right:this.right}}}const sp=15;class Lm{constructor(g,N,P,F,q,G,Q){this.tileSize=512,this._renderWorldCopies=q===void 0||q,this._minZoom=g||0,this._maxZoom=N||22,this._minPitch=P??0,this._maxPitch=F??60,this.setProjection(G),this.setMaxBounds(Q),this.width=0,this.height=0,this._center=new o.aU(0,0),this.zoom=0,this.angle=0,this._fov=.6435011087932844,this._pitch=0,this._nearZ=0,this._farZ=0,this._nearClipOffset=0,this._unmodified=!0,this._edgeInsets=new Gh,this._projMatrixCache={},this._alignedProjMatrixCache={},this._fogTileMatrixCache={},this._expandedProjMatrixCache={},this._distanceTileDataCache={},this._camera=new bx,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 g=new Lm(this._minZoom,this._maxZoom,this._minPitch,this.maxPitch,this._renderWorldCopies,this.getProjection(),this.maxBounds);return g._elevation=this._elevation,g._centerAltitude=this._centerAltitude,g._centerAltitudeValidForExaggeration=this._centerAltitudeValidForExaggeration,g.tileSize=this.tileSize,g.mercatorFromTransition=this.mercatorFromTransition,g.width=this.width,g.height=this.height,g.cameraElevationReference=this.cameraElevationReference,g._center=this._center,g._setZoom(this.zoom),g._seaLevelZoom=this._seaLevelZoom,g.angle=this.angle,g._fov=this._fov,g._pitch=this._pitch,g._nearZ=this._nearZ,g._farZ=this._farZ,g._nearClipOffset=this._nearClipOffset,g._averageElevation=this._averageElevation,g._orthographicProjectionAtLowPitch=this._orthographicProjectionAtLowPitch,g._unmodified=this._unmodified,g._edgeInsets=this._edgeInsets.clone(),g._camera=this._camera.clone(),g._calcMatrices(),g.freezeTileCoverage=this.freezeTileCoverage,g.frustumCorners=this.frustumCorners,g._allowWorldUnderZoom=this._allowWorldUnderZoom,g}get isOrthographic(){return this.projection.name!=="globe"&&this._orthographicProjectionAtLowPitch&&this.pitch0&&this.elevation.exaggeration()>0&&this._centerAltitudeValidForExaggeration;if(!this._elevation||g===Number.NEGATIVE_INFINITY&&(!N||!this._centerAltitude))return this._centerAltitude=0,this._seaLevelZoom=null,void(this._centerAltitudeValidForExaggeration=void 0);const P=this._elevation;N||this._centerAltitude&&this._centerAltitudeValidForExaggeration&&P.exaggeration()&&this._centerAltitudeValidForExaggeration!==P.exaggeration()?(this._centerAltitude=this._centerAltitude/this._centerAltitudeValidForExaggeration*P.exaggeration(),this._centerAltitudeValidForExaggeration=P.exaggeration()):(this._centerAltitude=g||0,this._centerAltitudeValidForExaggeration=P.exaggeration()),this._updateSeaLevelZoom()}_updateSeaLevelZoom(){if(this._centerAltitudeValidForExaggeration===void 0)return;const g=Math.max(0,(this.pixelsPerMeter*this._centerAltitude+this.cameraToCenterDistance)/this.worldSize);this._seaLevelZoom=this._zoomFromMercatorZ(g)}sampleAverageElevation(){if(!this._elevation)return 0;const g=this._elevation,N=[[.5,.2],[.3,.5],[.5,.5],[.7,.5],[.5,.8]],P=this.horizonLineFromTop();let F=0,q=0;for(let G=0;G{const dt=o.ck(Te,Ae,Fe,Ye,Ge);ae.has(dt)||(q.push(new o.aR(Ae,Te,Fe,Ye,Ge)),ae.add(dt))};for(let Ae=0;AeTe.canonical.z)continue;const Fe=Te.canonical,Ye=Te.overscaledZ,Ge=Te.wrap,dt=1<0,Ct=Fe.y+10,Kt=Te.wrap-(_t?0:1),Lt=Te.wrap+(lt?0:1),Wt=_t?Fe.x-1:dt-1,Tt=lt?Fe.x+1:0;if(G)P[0]<0?(me(Ye,Lt,Fe.z,Tt,Fe.y),P[1]<0&&Ct&&(me(Ye,Ge,Fe.z,Fe.x,Fe.y+1),me(Ye,Lt,Fe.z,Tt,Fe.y+1)),P[1]>0&&ht&&(me(Ye,Ge,Fe.z,Fe.x,Fe.y-1),me(Ye,Lt,Fe.z,Tt,Fe.y-1))):P[0]>0?(me(Ye,Kt,Fe.z,Wt,Fe.y),P[1]<0&&Ct&&(me(Ye,Ge,Fe.z,Fe.x,Fe.y+1),me(Ye,Kt,Fe.z,Wt,Fe.y+1)),P[1]>0&&ht&&(me(Ye,Ge,Fe.z,Fe.x,Fe.y-1),me(Ye,Kt,Fe.z,Wt,Fe.y-1))):P[1]<0&&Ct?me(Ye,Ge,Fe.z,Fe.x,Fe.y+1):ht&&me(Ye,Ge,Fe.z,Fe.x,Fe.y-1);else{const It=Te.visibleQuadrants;1&It&&(me(Ye,Kt,Fe.z,Wt,Fe.y),ht&&(me(Ye,Ge,Fe.z,Fe.x,Fe.y-1),me(Ye,Kt,Fe.z,Wt,Fe.y-1))),2&It&&(me(Ye,Lt,Fe.z,Tt,Fe.y),ht&&(me(Ye,Ge,Fe.z,Fe.x,Fe.y-1),me(Ye,Lt,Fe.z,Tt,Fe.y-1))),4&It&&(me(Ye,Kt,Fe.z,Wt,Fe.y),Ct&&(me(Ye,Ge,Fe.z,Fe.x,Fe.y+1),me(Ye,Kt,Fe.z,Wt,Fe.y+1))),8&It&&(me(Ye,Lt,Fe.z,Tt,Fe.y),Ct&&(me(Ye,Ge,Fe.z,Fe.x,Fe.y+1),me(Ye,Lt,Fe.z,Tt,Fe.y+1)))}}const ye=[];for(const Ae of q)q.some(Te=>Ae.isChildOf(Te))||ye.push(Ae);if(q=ye.filter(Ae=>!g.some(Te=>!!(Ae.overscaledZ{const lt=dt.canonical.x+.5-Fe[0],_t=dt.canonical.y+.5-Fe[1];return lt*lt+_t*_t{const Wt=o.ck(Ct,_t,ht,Kt,Lt);q.has(Wt)||(F.push(new o.aR(_t,Ct,ht,Kt,Lt)),q.add(Wt))},Q=g.reduce((_t,Ct)=>Math.max(_t,Ct.overscaledZ),P),ae=1<{const ht=Math.floor(_t[0]),Kt=Math.floor(_t[1]),Lt=(_t[0]-ht)*o.an,Wt=(_t[1]-Kt)*o.an,Tt=Math.floor(Ct[0]),It=Math.floor(Ct[1]),Ut=(Ct[0]-Tt)*o.an,rs=(Ct[1]-It)*o.an;for(let Zt=-1;Zt<=1;Zt++){const ks=ht+Zt;if(!(ks<0||ks>=ae)){ye.x=Lt-Zt*o.an,Ae.x=Ut-(ks-Tt)*o.an;for(let ms=-1;ms<=1;ms++){const Ws=Kt+ms;ye.y=Wt-ms*o.an,Ae.y=rs-(Ws-It)*o.an,o.cI(ye,Ae,me)&&G(Q,0,P,ks,Ws)}}}},Fe=N.points,Ye=Fe[o.c9],Ge=Fe[o.ca],dt=this._projectToGround(Ye,Fe[o.cb]),lt=this._projectToGround(Ge,Fe[o.cc]);return Te(Ye,dt),Te(Ge,lt),F}_projectToGround(g,N){return o.cd(o.ce(),g,N,g[2]/(g[2]-N[2]))}_projectToZ(g,N,P){const F=g[2]-N[2];return Math.abs(F)<1e-6?o.cf(g):o.cd(o.ce(),g,N,(g[2]-P)/F)}extendTileCoverForTunnels(g,N,P,F){if(P<18)return[];const q=N.points,G=q[o.cg],Q=q[o.ch],ae=q[o.ci],me=q[o.cj];if(ae[2]>=0&&me[2]>=0||G[2]<=0||Q[2]<=0)return[];const ye=ae[2]<0?this._projectToZ(G,ae,0):ae,Ae=me[2]<0?this._projectToZ(Q,me,0):me,Te=-F,Fe=ae[2]3&&(Ge.length=3),Ge}_findExtensionTilesInQuad(g,N,P,F){const q=[],G=new Set;for(const Tt of g)G.add(Tt.key);const Q=g.reduce((Tt,It)=>Math.max(Tt,It.overscaledZ),N),ae=1<{const Ut=Tt.canonical.x+.5-Lt,rs=Tt.canonical.y+.5-Wt,Zt=It.canonical.x+.5-Lt,ks=It.canonical.y+.5-Wt;return Ut*Ut+rs*rs-(Zt*Zt+ks*ks)||Tt.canonical.x-It.canonical.x||Tt.canonical.y-It.canonical.y}),q}coveringTiles(g){let N=this.coveringZoomLevel(g);const P=N,F=this.elevation&&this.elevation.exaggeration(),q=F&&!g.isTerrainDEM,G=this.projection.name==="mercator";if(g.minzoom!==void 0&&Ng.maxzoom&&(N=g.maxzoom);const Q=this.locationCoordinate(this.center),ae=this.center.lat,me=1<{const Ts=new o.ag(Xt.x+25e-6,Xt.y,Xt.z),Ls=new o.ag(Xt.x,Xt.y+25e-6,Xt.z),wr=Xt.toLngLat(),mr=Ts.toLngLat(),fr=Ls.toLngLat(),Js=this.locationCoordinate(wr),en=this.locationCoordinate(mr),dn=this.locationCoordinate(fr),Kr=Math.hypot(en.x-Js.x,en.y-Js.y),Jr=Math.hypot(dn.x-Js.x,dn.y-Js.y);return Math.sqrt(Kr*Jr)*Wt/25e-6},It=Xt=>{const ws=Kt,Ts=Lt;return{aabb:o.cp(this,me,0,0,0,Xt,Ts,ws,this.projection),zoom:0,x:0,y:0,minZ:Ts,maxZ:ws,wrap:Xt,fullyVisible:!1}},Ut=[];let rs=[];const Zt=N,ks=g.reparseOverscaled?P:N,ms=(dt-this._centerAltitude)*Ge,Ws=Xt=>{if(!this._elevation||!Xt.tileID||!G)return;const ws=this._elevation.getMinMaxForTile(Xt.tileID),Ts=Xt.aabb;ws?(Ts.min[2]=ws.min,Ts.max[2]=ws.max,Ts.center[2]=(Ts.min[2]+Ts.max[2])/2):(Xt.shouldSplit=as(Xt),Xt.shouldSplit||(Ts.min[2]=Ts.max[2]=Ts.center[2]=this._centerAltitude))},sr=(Xt,ws)=>{if(.707*ws{if(Xt.zoom=.9)return!0}else if(q&&(Ls=Xt.aabb.distanceZ(lt)*Ge),this.projection.isReprojectedInTileSpace&&P<=5){const Jr=Math.pow(2,Xt.zoom),$n=Tt(new o.ag((Xt.x+.5)/Jr,(Xt.y+.5)/Jr));wr=$n>.85?1:$n}if(!G&&!Ae){const Jr=Math.sqrt(ws*ws+Ts*Ts+Ls*Ls);let $n=(1<0;){const Xt=Ut.pop(),ws=Xt.x,Ts=Xt.y;let Ls=Xt.fullyVisible;const wr=()=>this.projection.name==="globe"&&(Xt.y===0||Xt.y===(1<mr)continue;let fr=0;if(!Ls){let Kr=_t?Xt.aabb.intersectsPrecise(Fe):Xt.aabb.intersectsPreciseFlat(Fe);if(Kr===0&&wr()){const Jr=new o.cn(Xt.zoom,ws,Ts);Kr=o.co(this,me,Jr,!0).intersectsPrecise(Fe)}if(Kr===0)continue;if(g.calculateQuadrantVisibility)if(Fe.containsPoint(Xt.aabb.center))fr=15;else for(let Jr=0;Jr<4;Jr++)Xt.aabb.quadrant(Jr).intersects(Fe)!==0&&(fr|=1<>1),en={aabb:G?Xt.aabb.quadrant(mr):o.cp(this,me,Xt.zoom+1,fr,Js,Xt.wrap,Xt.minZ,Xt.maxZ,this.projection),zoom:Xt.zoom+1,x:fr,y:Js,wrap:Xt.wrap,fullyVisible:Ls,tileID:void 0,shouldSplit:void 0,minZ:Xt.minZ,maxZ:Xt.maxZ};q&&!Ae&&(en.tileID=new o.aR(Xt.zoom+1===Zt?ks:Xt.zoom+1,Xt.wrap,Xt.zoom+1,fr,Js),Ws(en)),Ut.push(en)}}if(this.fogCullDistSq){const Xt=this.fogCullDistSq,ws=this.horizonLineFromTop();rs=rs.filter(Ts=>{const Ls=[0,0,0,1],wr=[o.an,o.an,0,1],mr=this.calculateFogTileMatrix(Ts.tileID.toUnwrapped());o.aE(Ls,Ls,mr),o.aE(wr,wr,mr);const fr=o.cq([],Ls,wr),Js=o.cr([],Ls,wr),en=o.cK(fr,Js);if(en===0)return!0;let dn=!1;const Kr=this._elevation;if(Kr&&en>Xt&&ws!==0){const Jr=this.calculateProjMatrix(Ts.tileID.toUnwrapped());let $n;g.isTerrainDEM||($n=Kr.getMinMaxForTile(Ts.tileID)),$n||($n={min:Lt,max:Kt});const oa=o.cs(this.rotation),ra=[oa[0]*o.an,oa[1]*o.an,$n.max];o.ah(ra,ra,Jr),dn=(1-ra[1])*this.height*.5Xt.distanceSq-ws.distanceSq).map(Xt=>Xt.tileID)}resize(g,N){this.width=g,this.height=N,this.pixelsToGLUnits=[2/g,-2/N],this._constrain(),this._calcMatrices()}get unmodified(){return this._unmodified}zoomScale(g){return Math.pow(2,g)}scaleZoom(g){return Math.log2(g)}project(g){const N=o.aC(g.lat,-o.ct,o.ct),P=this.projection.project(g.lng,N);return new o.P(P.x*this.worldSize,P.y*this.worldSize)}unproject(g){return this.projection.unproject(g.x/this.worldSize,g.y/this.worldSize)}get point(){return this.project(this.center)}get pointMerc(){return this.point._div(this.worldSize)}get pixelsPerMeterRatio(){return this.pixelsPerMeter/o.bU(1,this.center.lat)/this.worldSize}setLocationAtPoint(g,N){let P,F;const q=this.centerPoint;if(this.projection.name==="globe"){const Q=this.worldSize;P=(N.x-q.x)/Q,F=(N.y-q.y)/Q}else{const Q=this.pointCoordinate(N),ae=this.pointCoordinate(q);P=Q.x-ae.x,F=Q.y-ae.y}const G=this.locationCoordinate(g);this.setLocation(new o.ag(G.x-P,G.y-F))}setLocation(g){this.center=this.coordinateLocation(g),this.projection.wrap&&(this.center=this.center.wrap())}locationPoint(g,N){return this.projection.locationPoint(this,g,N)}locationPoint3D(g,N){return this.projection.locationPoint(this,g,N,!0)}pointLocation(g){return this.coordinateLocation(this.pointCoordinate(g))}pointLocation3D(g,N){return this.coordinateLocation(this.pointCoordinate3D(g,N))}locationCoordinate(g,N){const P=N?o.bU(N,g.lat):void 0,F=this.projection.project(g.lng,g.lat);return new o.ag(F.x,F.y,P)}coordinateLocation(g){return this.projection.unproject(g.x,g.y)}pointRayIntersection(g,N){const P=N??this._centerAltitude,F=[g.x,g.y,0,1],q=[g.x,g.y,1,1];o.aE(F,F,this.pixelMatrixInverse),o.aE(q,q,this.pixelMatrixInverse);const G=q[3];o.cu(F,F,1/F[3]),o.cu(q,q,1/G);const Q=F[2],ae=q[2];return{p0:F,p1:q,t:Q===ae?0:(P-Q)/(ae-Q)}}screenPointToMercatorRay(g){const N=[g.x,g.y,0,1],P=[g.x,g.y,1,1];return o.aE(N,N,this.pixelMatrixInverse),o.aE(P,P,this.pixelMatrixInverse),o.cu(N,N,1/N[3]),o.cu(P,P,1/P[3]),N[2]=o.bU(N[2],this._center.lat)*this.worldSize,P[2]=o.bU(P[2],this._center.lat)*this.worldSize,o.cu(N,N,1/this.worldSize),o.cu(P,P,1/this.worldSize),new o.az([N[0],N[1],N[2]],o.ay([],o.ax([],P,N)))}rayIntersectionCoordinate(g){const{p0:N,p1:P,t:F}=g,q=o.bU(N[2],this._center.lat),G=o.bU(P[2],this._center.lat);return new o.ag(o.am(N[0],P[0],F)/this.worldSize,o.am(N[1],P[1],F)/this.worldSize,o.am(q,G,F))}pointCoordinate(g,N=this._centerAltitude){return this.projection.pointCoordinate(this,g.x,g.y,N)}pointCoordinate3D(g,N){if(!this.elevation)return this.pointCoordinate(g,N);let P=this.projection.pointCoordinate3D(this,g.x,g.y);if(P)return new o.ag(P[0],P[1],P[2]);let F=0,q=this.horizonLineFromTop();if(g.y>q)return this.pointCoordinate(g,N);const G=.02*q,Q=g.clone();for(let ae=0;ae<10&&q-F>G;ae++){Q.y=o.am(F,q,.66);const me=this.projection.pointCoordinate3D(this,Q.x,Q.y);me?(q=Q.y,P=me):F=Q.y}return P?new o.ag(P[0],P[1],P[2]):this.pointCoordinate(g)}isPointAboveHorizon(g){return this.projection.isPointAboveHorizon(this,g)}isPointOnSurface(g){if(g.y<0||g.y>this.height||g.x<0||g.x>this.width)return!1;if(this.elevation||this.zoom>=o.cv)return!this.isPointAboveHorizon(g);const N=this.pointCoordinate(g);return N.y>=0&&N.y<=1}_coordinatePoint(g,N){const P=N&&this.elevation?this.elevation.getAtPointOrZero(g,this._centerAltitude):this._centerAltitude,F=[g.x*this.worldSize,g.y*this.worldSize,P+g.toAltitude(),1];return o.aE(F,F,this.pixelMatrix),F[3]>0?new o.P(F[0]/F[3],F[1]/F[3]):new o.P(Number.MAX_VALUE,Number.MAX_VALUE)}_getBoundsNonRectangular(){const{top:g,left:N}=this._edgeInsets,P=this.height-this._edgeInsets.bottom,F=this.width-this._edgeInsets.right,q=this.pointLocation3D(new o.P(N,g)),G=this.pointLocation3D(new o.P(F,g)),Q=this.pointLocation3D(new o.P(F,P)),ae=this.pointLocation3D(new o.P(N,P));let me=Math.min(q.lng,G.lng,Q.lng,ae.lng),ye=Math.max(q.lng,G.lng,Q.lng,ae.lng),Ae=Math.min(q.lat,G.lat,Q.lat,ae.lat),Te=Math.max(q.lat,G.lat,Q.lat,ae.lat);const Fe=Math.pow(2,-this.zoom)/16*270,Ye=this.projection.name==="globe"?1:4,Ge=(dt,lt,_t,Ct,ht)=>{const Kt=(dt+_t)/2,Lt=(lt+Ct)/2,Wt=new o.P(Kt,Lt),{lng:Tt,lat:It}=this.pointLocation3D(Wt),Ut=Math.max(0,me-Tt,Ae-It,Tt-ye,It-Te);me=Math.min(me,Tt),ye=Math.max(ye,Tt),Ae=Math.min(Ae,It),Te=Math.max(Te,It),(htFe)&&(Ge(dt,lt,Kt,Lt,ht+1),Ge(Kt,Lt,_t,Ct,ht+1))};if(Ge(N,g,F,g,1),Ge(F,g,F,P,1),Ge(F,P,N,P,1),Ge(N,P,N,g,1),this.projection.name==="globe"){const[dt,lt]=o.cw(this);dt?(Te=90,ye=180,me=-180):lt&&(Ae=-90,ye=180,me=-180)}return new o.aK(new o.aU(me,Ae),new o.aU(ye,Te))}_getBoundsRectangular(g,N){const{top:P,left:F}=this._edgeInsets,q=this.height-this._edgeInsets.bottom,G=this.width-this._edgeInsets.right,Q=new o.P(F,P),ae=new o.P(G,P),me=new o.P(G,q),ye=new o.P(F,q);let Ae=this.pointCoordinate(Q,g),Te=this.pointCoordinate(ae,g);const Fe=this.pointCoordinate(me,N),Ye=this.pointCoordinate(ye,N),Ge=(dt,lt)=>(lt.y-dt.y)/(lt.x-dt.x);return Ae.y>1&&Te.y>=0?Ae=new o.ag((1-Ye.y)/Ge(Ye,Ae)+Ye.x,1):Ae.y<0&&Te.y<=1&&(Ae=new o.ag(-Ye.y/Ge(Ye,Ae)+Ye.x,0)),Te.y>1&&Ae.y>=0?Te=new o.ag((1-Fe.y)/Ge(Fe,Te)+Fe.x,1):Te.y<0&&Ae.y<=1&&(Te=new o.ag(-Fe.y/Ge(Fe,Te)+Fe.x,0)),new o.aK().extend(this.coordinateLocation(Ae)).extend(this.coordinateLocation(Te)).extend(this.coordinateLocation(Ye)).extend(this.coordinateLocation(Fe))}_getBoundsRectangularTerrain(){const g=this.elevation;if(!g.visibleDemTiles.length||g.isUsingMockSource())return this._getBoundsRectangular(0,0);const N=g.visibleDemTiles.reduce((P,F)=>{if(F.dem){const q=F.dem.tree;P.min=Math.min(P.min,q.minimums[0]),P.max=Math.max(P.max,q.maximums[0])}return P},{min:Number.MAX_VALUE,max:0});return this._getBoundsRectangular(N.min*g.exaggeration(),N.max*g.exaggeration())}getBounds(){return this.projection.name==="mercator"||this.projection.name==="equirectangular"?this._terrainEnabled()?this._getBoundsRectangularTerrain():this._getBoundsRectangular(0,0):this._getBoundsNonRectangular()}horizonLineFromTop(g=!0){const N=this.height/2/Math.tan(this._fov/2)/Math.tan(Math.max(this._pitch,.1))-this.centerOffset.y,P=this.height/2-N*(1-this._horizonShift);return g?Math.max(0,P):P}getMaxBounds(){return this.maxBounds}setMaxBounds(g){this.maxBounds=g,this.minLat=-o.ct,this.maxLat=o.ct,this.minLng=-180,this.maxLng=180,g&&(this.minLat=g.getSouth(),this.maxLat=g.getNorth(),this.minLng=g.getWest(),this.maxLng=g.getEast(),this.maxLngAe&&(Q=Ae-me),Ae-yeFe&&(G=Fe-ae),Fe-Te{for(let as=0;as<16;as++)ks[as]=o.am(ms[as],Ws[as],sr)})(Q,Q,ae,o.cL(this.pitch>=sp?1:this.pitch/sp))}else Q=ae;const me=o.cz([],ae,G);let ye=o.cz([],Q,G);if(this.projection.isReprojectedInTileSpace){const It=this.locationCoordinate(this.center),Ut=o.b9([]);o.bx(Ut,Ut,[It.x*this.worldSize,It.y*this.worldSize,0]),o.aD(Ut,Ut,o.cA(this)),o.bx(Ut,Ut,[-It.x*this.worldSize,-It.y*this.worldSize,0]),o.aD(ye,ye,Ut),o.aD(me,me,Ut),this.inverseAdjustmentMatrix=o.cB(this)}else this.inverseAdjustmentMatrix=[1,0,0,1];if(this.mercatorMatrix=o.cC([],ye,[this.worldSize,this.worldSize,this.worldSize/q,1]),this.projMatrix=ye,this.invProjMatrix=o.b7(new Float64Array(16),this.projMatrix),N){const It=this._camera.getCameraToClipPerspective(this._fov,this.width/this.height,this._nearZ,1/0);It[8]=2*-g.x/this.width,It[9]=2*g.y/this.height,this.expandedFarZProjMatrix=o.cz([],It,G)}else this.expandedFarZProjMatrix=this.projMatrix;const Ae=o.b7([],Q);this.frustumCorners=o.cD.fromInvProjectionMatrix(Ae,this.horizonLineFromTop(),this.height),this.cameraFrustum=o.cl.fromInvProjectionMatrix(this.invProjMatrix,this.worldSize,0,!N);const Te=new Float32Array(16);o.b9(Te),o.cC(Te,Te,[1,-1,1]),o.cE(Te,Te,this._pitch),o.ba(Te,Te,this.angle);const Fe=o.bS(new Float32Array(16),this._fov,this.width/this.height,this._nearZ,this._farZ);this.starsProjMatrix=o.b8(Fe);const Ye=(Math.PI/2-this._pitch)*(this.height/this._fov)*this._horizonShift;Fe[8]=2*-g.x/this.width,Fe[9]=2*(g.y+Ye)/this.height,this.skyboxMatrix=o.aD(Te,Fe,Te);const Ge=this.point,dt=Ge.x,lt=Ge.y,_t=this.width%2/2,Ct=this.height%2/2,ht=Math.cos(this.angle),Kt=Math.sin(this.angle),Lt=dt-Math.round(dt)+ht*_t+Kt*Ct,Wt=lt-Math.round(lt)+ht*Ct+Kt*_t,Tt=new Float64Array(ye);if(o.bx(Tt,Tt,[Lt>.5?Lt-1:Lt,Wt>.5?Wt-1:Wt,0]),this.alignedProjMatrix=Tt,ye=o.bb(),o.cC(ye,ye,[this.width/2,-this.height/2,1]),o.bx(ye,ye,[1,-1,0]),this.labelPlaneMatrix=ye,ye=o.bb(),o.cC(ye,ye,[1,-1,1]),o.bx(ye,ye,[-1,-1,0]),o.cC(ye,ye,[2/this.width,2/this.height,1]),this.glCoordMatrix=ye,this.pixelMatrix=o.aD(new Float64Array(16),this.labelPlaneMatrix,me),this._calcFogMatrices(),this._distanceTileDataCache={},ye=o.b7(new Float64Array(16),this.pixelMatrix),!ye)throw new Error("failed to invert matrix");if(this.pixelMatrixInverse=ye,this.projection.name==="globe"||this.mercatorFromTransition){this.globeMatrix=o.cF(this);const It=[this.globeMatrix[12],this.globeMatrix[13],this.globeMatrix[14]];this.globeCenterInViewSpace=o.ah(It,It,G),this.globeRadius=this.worldSize/2/Math.PI-1}else this.globeMatrix=ye;this._projMatrixCache={},this._alignedProjMatrixCache={},this._pixelsToTileUnitsCache={},this._expandedProjMatrixCache={}}_calcFogMatrices(){this._fogTileMatrixCache={};const g=this.cameraWorldSizeForFog,N=this.cameraPixelsPerMeter,P=this._camera.position,F=1/this.height/this._pixelsPerMercatorPixel,q=[g,g,N];o.bJ(q,q,F),o.bJ(P,P,-1),o.cG(P,P,q);const G=o.bb();o.bx(G,G,P),o.cC(G,G,q),this.mercatorFogMatrix=G,this.worldToFogMatrix=this._camera.getWorldToCameraPosition(g,N,F)}_computeCameraPosition(g){const N=(g=g||this.pixelsPerMeter)/this.pixelsPerMeter,P=this._camera.forward(),F=this.point,q=this._mercatorZfromZoom(this._seaLevelZoom?this._seaLevelZoom:this._zoom)*N-g/this.worldSize*this._centerAltitude;return[F.x/this.worldSize-P[0]*q,F.y/this.worldSize-P[1]*q,g/this.worldSize*this._centerAltitude-P[2]*q]}_updateCameraState(){this.height&&(this._camera.setPitchBearing(this._pitch,this.angle),this._camera.position=this._computeCameraPosition())}_translateCameraConstrained(g){const N=this._maxCameraBoundsDistance()*Math.cos(this._pitch),P=this._camera.position[2],F=g[2];let q=1;this.projection.wrap&&(this.center=this.center.wrap()),F>0&&(q=Math.min((N-P)/F,1)),this._camera.position=o.bg([],this._camera.position,g,q),this._updateStateFromCamera()}_updateStateFromCamera(){const g=this._camera.position,N=this._camera.forward(),{pitch:P,bearing:F}=this._camera.getPitchBearing(),q=o.bU(this._centerAltitude,this.center.lat)*this._pixelsPerMercatorPixel,G=this._mercatorZfromZoom(this._maxZoom)*Math.cos(o.ap(this._maxPitch)),Q=Math.max((g[2]-q)/Math.cos(P),G),ae=this._zoomFromMercatorZ(Q);o.bg(g,g,N,Q),this._pitch=o.aC(P,o.ap(this.minPitch),o.ap(this.maxPitch)),this.angle=o.bs(F,-Math.PI,Math.PI),this._setZoom(o.aC(ae,this._minZoom,this._maxZoom)),this._updateSeaLevelZoom(),this._center=this.coordinateLocation(new o.ag(g[0],g[1],g[2])),this._unmodified=!1,this._constrain(),this._calcMatrices()}_worldSizeFromZoom(g){return Math.pow(2,g)*this.tileSize}_mercatorZfromZoom(g){return this.cameraToCenterDistance/this._worldSizeFromZoom(g)}_minimumHeightOverTerrain(){const g=Math.min(this._seaLevelZoom!=null?this._seaLevelZoom:this._zoom,this._maxZoom)+4;return this._mercatorZfromZoom(g)}_zoomFromMercatorZ(g){return this.scaleZoom(this.cameraToCenterDistance/(Math.max(0,g)*this.tileSize))}zoomFromMercatorZAdjusted(g){let N=0,P=o.cv,F=0,q=1/0;for(;P-N>1e-6&&P>N;){const G=N+.5*(P-N),Q=this.tileSize*Math.pow(2,G),ae=this.getCameraToCenterDistance(this.projection,G,Q),me=this.scaleZoom(ae/(Math.max(0,g)*this.tileSize)),ye=Math.abs(G-me);yeme||Te.y>1)return!0}return!1}isHorizonVisible(){return this.pitch+o.cH(this.fovAboveCenter)>88||this.anyCornerOffEdge(new o.P(0,0),new o.P(this.width,this.height))}zoomDeltaToMovement(g,N){const P=o.ai(o.ax([],this._camera.position,g)),F=this._zoomFromMercatorZ(P)+N;return P-this._mercatorZfromZoom(F)}getCameraPoint(){if(this.projection.name==="globe"){const g=function([N,P,F],q){const G=[N,P,F,1];o.aE(G,G,q);const Q=G[3]=Math.max(G[3],1e-6);return G[0]/=Q,G[1]/=Q,G[2]/=Q,G}([this.globeMatrix[12],this.globeMatrix[13],this.globeMatrix[14]],this.pixelMatrix);return new o.P(g[0],g[1])}{const g=Math.tan(this._pitch)*(this.cameraToCenterDistance||1);return this.centerPoint.add(new o.P(0,g))}}getCameraToCenterDistance(g,N=this.zoom,P=this.worldSize){const F=o.cy(g,N,this.width,this.height,1024),q=g.pixelSpaceConversion(this.center.lat,P,F);let G=.5/Math.tan(.5*this._fov)*this.height*q;return this.isOrthographic&&(G=o.am(1,G,o.cL(this.pitch>=sp?1:this.pitch/sp))),G}getWorldToCameraMatrix(){const g=this._camera.getWorldToCamera(this.worldSize,this.projection.zAxisUnit==="meters"?this.pixelsPerMeter:1);return this.projection.name==="globe"&&o.aD(g,g,this.globeMatrix),g}getFrustum(g){return o.cl.fromInvProjectionMatrix(this.invProjMatrix,this.worldSize,g,this.projection.zAxisUnit==="meters")}}const wc=(M,g)=>{if(g>0&&M.terrain&&o.w("Cutoff is currently disabled on terrain"),g<=0||M.terrain)return{shouldRenderCutoff:!1,uniformValues:{u_cutoff_params:[0,0,0,1]}};const N=M.transform,P=N.pitch,F=N.isLODDisabled(!1)?60:30;if(P0,uniformValues:{u_cutoff_params:[N._nearZ,N._farZ,(ye-N._nearZ)/q,(ye-Te-N._nearZ)/q]}}},ff=2048;class ow{constructor(g,N){this.aabb=g,this.lastCascade=N}}class Tj{add(g,N){const P=this.receivers[g.key];P!==void 0?(P.aabb.min[0]=Math.min(P.aabb.min[0],N.min[0]),P.aabb.min[1]=Math.min(P.aabb.min[1],N.min[1]),P.aabb.min[2]=Math.min(P.aabb.min[2],N.min[2]),P.aabb.max[0]=Math.max(P.aabb.max[0],N.max[0]),P.aabb.max[1]=Math.max(P.aabb.max[1],N.max[1]),P.aabb.max[2]=Math.max(P.aabb.max[2],N.max[2])):this.receivers[g.key]=new ow(N,null)}clear(){this.receivers={}}get(g){return this.receivers[g.key]}computeRequiredCascades(g,N,P){const F=o.cU.fromPoints(g.points);let q=0;for(const G in this.receivers){const Q=this.receivers[G];if(!Q||!F.intersectsAabb(Q.aabb))continue;Q.aabb.min=F.closestPoint(Q.aabb.min),Q.aabb.max=F.closestPoint(Q.aabb.max);const ae=Q.aabb.getCorners();for(let me=0;me1||Te[1]<-1||Te[1]>1){ye=!1;break}}if(Q.lastCascade=me,q=Math.max(q,me),ye)break}}return q+1}}class Wl{constructor(g){this.painter=g,this._enabled=!1,this._drawShadowAfterLayer=-1,this._numCascadesToRender=0,this._cascades=[],this._groundShadowTiles=[],this._receivers=new Tj,this._depthMode=new Wr(g.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 g of this._cascades)g.texture.destroy(),g.framebuffer.destroy();this._cascades=[]}updateShadowParameters(g,N){const P=this.painter;if(this._enabled=!1,this._drawShadowAfterLayer=-1,this._receivers.clear(),!N||!N.properties)return;const F=N.properties.get("shadow-intensity"),q=N.properties.get("shadow-draw-before-layer");if(!N.shadowsEnabled()||F<=0)return;let G=-1,Q=0;for(const lt of P.style.order){const _t=P.style._mergedLayers[lt];_t.hasShadowPass()&&!_t.isHidden(g.zoom)&&(G=Q),!q||q!==lt&&q!==_t.slot||(this._drawShadowAfterLayer=Q>0?Q-1:0),Q+=1}if(this._enabled=G>=0,!this.enabled)return;this._drawShadowAfterLayer<0&&(this._drawShadowAfterLayer=G);const ae=P.context,me=ff,ye=ff;if(this._cascades.length===0||ff!==this._cascades[0].texture.size[0]){this._cascades=[];for(let lt=0;lt<2;++lt){const _t=ae.gl,Ct=ae.createFramebuffer(me,ye,0,"texture"),ht=new o.T(ae,{width:me,height:ye,data:null},_t.DEPTH_COMPONENT16);Ct.depthAttachment.set(ht.texture),this._cascades.push({framebuffer:Ct,texture:ht,matrix:[],far:0,boundingSphereRadius:0,frustum:new o.cl,scale:0})}}this.shadowDirection=Ej(N);let Ae=0;if(g.elevation){const lt=g.elevation,_t=[1e4,-1e4];lt.visibleDemTiles.filter(Ct=>Ct.dem).forEach(Ct=>{const ht=Ct.dem.tree;_t[0]=Math.min(_t[0],ht.minimums[0]),_t[1]=Math.max(_t[1],ht.maximums[0])}),_t[0]!==1e4&&(Ae=(_t[1]-_t[0])*lt.exaggeration())}const Te=1.5*g.cameraToCenterDistance,Fe=3*Te,Ye=new Float64Array(16);for(let lt=0;lt=0)return{};const q=function(ae,me,ye){const Ae=ye/(1<0&&(o.cT(q[1],q[1],[F[0]*G,0,0]),o.cT(q[2],q[2],[F[0]*G,0,0])),F[1]<0?(o.cT(q[0],q[0],[0,F[1]*G,0]),o.cT(q[1],q[1],[0,F[1]*G,0])):F[1]>0&&(o.cT(q[2],q[2],[0,F[1]*G,0]),o.cT(q[3],q[3],[0,F[1]*G,0]));const Q={};return Q.vertices=q,Q.planes=[mv(q[1],q[0],q[4]),mv(q[2],q[1],q[5]),mv(q[3],q[2],q[6]),mv(q[0],q[3],q[7])],Q}addShadowReceiver(g,N,P){this._receivers.add(g,o.cU.fromTileIdAndHeight(g,N,P))}getMaxCascadeForTile(g){const N=this._receivers.get(g);return N&&N.lastCascade?N.lastCascade:0}}function mv(M,g,N){const P=o.ax([],N,g),F=o.ax([],M,g),q=o.bh([],P,F),G=o.ai(q);return G===0?[0,0,1,0]:(o.bJ(q,q,1/G),[q[0],q[1],q[2],-o.bi(q,g)])}function Ej(M){const g=M.properties.get("direction"),N=o.cP(g.x,g.y,g.z);N[2]=o.aC(N[2],0,75);const P=o.cR([N[0],N[1],N[2]]);return o.cQ(P.x,P.y,P.z)}function pf(M,g,N){const P=g.properties.get("color-use-theme")==="none",F=g.properties.get("color"),q=g.properties.get("intensity"),G=g.properties.get("direction"),Q=[G.x,G.y,G.z],ae=N.properties.get("color-use-theme")==="none",me=N.properties.get("color"),ye=N.properties.get("intensity"),Ae=Math.max(o.bi([0,0,1],Q),0),Te=[0,0,0];o.bJ(Te,me.toPremultipliedRenderColor(ae?null:M.getLut(g.scope)).toArray01Linear().slice(0,3),ye);const Fe=[0,0,0];return o.bJ(Fe,F.toPremultipliedRenderColor(P?null:M.getLut(N.scope)).toArray01Linear().slice(0,3),Ae*q),o.cW([Te[0]>0?Te[0]/(Te[0]+Fe[0]):0,Te[1]>0?Te[1]/(Te[1]+Fe[1]):0,Te[2]>0?Te[2]/(Te[2]+Fe[2]):0])}function W0(M,g,N,P,F,q){const G=M.zoom,Q=M.scale,ae=M.worldSize,me=1/ae,ye=M.aspect,Ae=Math.sqrt(1+ye*ye)*Math.tan(.5*M.fovX),Te=Ae*Ae,Fe=P-N,Ye=P+N;let Ge,dt;Te>Fe/Ye?(Ge=P,dt=P*Ae):(Ge=.5*Ye*(1+Te),dt=.5*Math.sqrt(Fe*Fe+2*(P*P+N*N)*Te+Ye*Ye*Te*Te));const lt=M.projection.pixelsPerMeter(M.center.lat,ae),_t=M._camera.getCameraToWorldMercator(),Ct=[0,0,-Ge*me];o.ah(Ct,Ct,_t);let ht=dt*me;const Kt=function(Ls){return Ls[0]/=Q,Ls[1]/=Q,Ls[2]=o.bU(Ls[2],M._center.lat),Ls},Lt=M._edgeInsets;if(!(Lt.left===0&&Lt.top===0&&Lt.right===0&&Lt.bottom===0||Lt.left===Lt.right&&Lt.top===Lt.bottom)){const Ls=M._camera.getWorldToCamera(M.worldSize,M.projection.zAxisUnit==="meters"?lt:1),wr=M._camera.getCameraToClipPerspective(M._fov,M.width/M.height,N,P);wr[8]=2*-M.centerOffset.x/M.width,wr[9]=2*M.centerOffset.y/M.height;const mr=new Float64Array(16);o.cz(mr,wr,Ls);const fr=new Float64Array(16);o.b7(fr,mr);const Js=o.cl.fromInvProjectionMatrix(fr,ae,G,!0);for(const en of Js.points){const dn=Kt(en);ht=Math.max(ht,o.bK(o.cV([],Ct,dn)))}}ht*=F/(F-1);const Wt=Math.acos(g[2]),Tt=Math.atan2(-g[0],-g[1]),It=new bx;It.position=Ct,It.setPitchBearing(Wt,Tt);const Ut=It.getWorldToCamera(ae,lt),rs=ht*ae,Zt=Math.min(M._mercatorZfromZoom(17)*ae*-2,-2*rs),ks=It.getCameraToClipOrthographic(-rs,rs,-rs,rs,Zt,(rs+q*lt)/g[2]),ms=new Float64Array(16);o.aD(ms,ks,Ut);const Ws=o.cQ(Math.floor(1e6*Ct[0])/1e6*ae,Math.floor(1e6*Ct[1])/1e6*ae,0),sr=.5*F,as=[0,0,0];o.ah(as,Ws,ms),o.bJ(as,as,sr);const Xt=[Math.floor(as[0]),Math.floor(as[1]),Math.floor(as[2])],ws=[0,0,0];o.ax(ws,as,Xt),o.bJ(ws,ws,-1/sr);const Ts=new Float64Array(16);return o.b9(Ts),o.bx(Ts,Ts,ws),o.aD(ms,Ts,ms),[ms,rs]}class i4 extends o.E{constructor(g){super(),this.requestManager=g,this.models={"":{}},this.modelUris={"":{}},this.modelByURL={},this.numModelsLoading={}}loadModel(g,N){return o.cX(this.requestManager.transformRequest(N,o.R.Model).url).then(P=>{const F=o.cY(P),q=new o.cZ(g,N,void 0,void 0,F);return q.computeBoundsAndApplyParent(),q}).catch(P=>{if(P&&P.status===404)return null;this.fire(new o.B(new Error(`Could not load model ${g} from ${N}: ${P.message}`)))})}load(g,N,P={forceReload:!1}){this.models[N]||(this.models[N]={});const F=Object.keys(g),q=[],G=[];for(const Q of F){const ae=g[Q];this.hasURLBeenRequested(ae)&&!P.forceReload||(this.modelByURL[ae]={modelId:Q,scope:N},q.push(this.loadModel(Q,ae)),G.push(Q)),this.models[N][Q]||(this.models[N][Q]={model:null,numReferences:1})}this.numModelsLoading[N]=(this.numModelsLoading[N]||0)+G.length,Promise.allSettled(q).then(Q=>{for(let ae=0;ae{this.fire(new o.B(new Error(`Could not load models: ${Q.message}`)))})}isLoaded(){for(const g in this.numModelsLoading)if(this.numModelsLoading[g]>0)return!1;return!0}hasModel(g,N,P={exactIdMatch:!1}){return!!(P.exactIdMatch?this.getModel(g,N):this.getModelByURL(this.modelUris[N][g]))}getModel(g,N){return this.models[N]||(this.models[N]={}),this.models[N][g]?this.models[N][g].model:void 0}getModelByURL(g){if(!g)return null;const N=this.modelByURL[g];return N?this.models[N.scope][N.modelId].model:null}hasModelBeenAdded(g,N){return this.models[N]&&this.models[N][g]!==void 0}getModelURIs(g){return this.modelUris[g]||{}}addModel(g,N,P){this.models[P]||(this.models[P]={}),this.modelUris[P]||(this.modelUris[P]={});const F=this.requestManager.normalizeModelURL(N);if((this.hasModel(g,P,{exactIdMatch:!0})||this.hasModelBeenAdded(g,P))&&this.modelUris[P][g]===F)this.models[P][g].numReferences++;else if(this.hasURLBeenRequested(F)){const{scope:q,modelId:G}=this.modelByURL[F];this.models[q][G].numReferences++}else this.modelUris[P][g]=F,this.load({[g]:this.modelUris[P][g]},P)}addModelURLs(g,N){this.models[N]||(this.models[N]={}),this.modelUris[N]||(this.modelUris[N]={});const P=this.modelUris[N];for(const F in g)P[F]=this.requestManager.normalizeModelURL(g[F])}reloadModels(g){this.load(this.modelUris[g],g,{forceReload:!0})}addModelsFromBucket(g,N){this.models[N]||(this.models[N]={}),this.modelUris[N]||(this.modelUris[N]={});const P={};for(const F of g)this.hasModel(F,N,{exactIdMatch:!0})||this.hasURLBeenRequested(F)?this.models[N][F].numReferences++:this.modelUris[N][F]&&!this.hasURLBeenRequested(F)?P[F]=this.modelUris[N][F]:!this.hasURLBeenRequested(F)&&o.c_(F,!1)&&(this.modelUris[N][F]=this.requestManager.normalizeModelURL(F),P[F]=this.modelUris[N][F]);this.load(P,N)}hasURLBeenRequested(g){return this.modelByURL[g]!==void 0}removeModel(g,N,P=!1,F=!1){if(this.models[N]&&this.models[N][g]&&(this.models[N][g].numReferences--,this.models[N][g].numReferences===0||F)){const q=this.modelUris[N][g];P||delete this.modelUris[N][g],delete this.modelByURL[q];const G=this.models[N][g].model;if(!G)return;delete this.models[N][g],G.destroy()}}destroy(){for(const g of Object.keys(this.models))for(const N of Object.keys(this.models[g])){const P=this.models[g][N].model;delete this.models[g][N],P&&P.destroy()}this.models={"":{}},this.modelUris={"":{}},this.modelByURL={},this.numModelsLoading={}}listModels(g){return this.models[g]||(this.models[g]={}),Object.keys(this.models[g])}upload(g,N){this.models[N]||(this.models[N]={});for(const P in this.models[N])this.models[N][P].model&&this.models[N][P].model.upload(g.context)}}const _x=o.a8.colorTheme,Bl=new o.ab({data:new o.ac(_x.data)});function Pd(M){if(!M.metadata||!M.metadata.content_area)return;const g=o.o.devicePixelRatio,{left:N,top:P,width:F,height:q}=M.metadata.content_area,G=N*g,Q=P*g;return[G,Q,G+F*g,Q+q*g]}function Gc(M){if(M)return M.map(([g,N])=>[g*o.o.devicePixelRatio,N*o.o.devicePixelRatio])}class Z1{constructor(g,N,P){this.id=g,this.scope=N,this.sourceCache=P,this.pendingRequests=new Set,this.missingRequests=new Set}addPendingRequest(g){this.missingRequests.has(g.name)||this.pendingRequests.has(g.name)||this.pendingRequests.add(g.name)}hasPendingRequests(){return this.pendingRequests.size>0}resolvePendingRequests(){const g=new Map;if(!this.sourceCache.loaded())return g;const N=this.sourceCache.getVisibleCoordinates();if(N.length===0)return g;const P=this.sourceCache.getSource();if(!(P instanceof Uh))return g;const F=N.map(G=>this.sourceCache.getTile(G)),q=P.getImages(F,Array.from(this.pendingRequests));for(const[G,Q]of q)g.set(o.I.from({name:G,iconsetId:this.id}),Q),this.pendingRequests.delete(G);for(const G of this.pendingRequests)this.missingRequests.add(G);return this.pendingRequests.clear(),g}}class rp{constructor(){this._previousClosestBuildingId=null,this._hysteresisRatio=.8,this._indoorMinimumZoom=16}findClosestBuilding(g,N,P,F,q){if(Pae*this._hysteresisRatio&&(G=this._previousClosestBuildingId):me&&!G&&(G=this._previousClosestBuildingId),this._previousClosestBuildingId=G,G}_calculateDistance(g,N){if(!N.center)return Number.MAX_VALUE;const P=g.lat-N.center[1],F=g.lng-N.center[0];return P*P+F*F}_isBuildingVisible(g,N,P){if(!P)return!1;for(const F of g.floorIds){const q=g.floors[F];if(!q.geometry)continue;const G=q.geometry;if(G.type==="Polygon"){const Q=this._convertRingToPoints(G.coordinates[0]);if(o.bw(Q,P))return!0}else if(G.type==="MultiPolygon"){const Q=this._convertMultiPolygonToPoints(G.coordinates);if(o.d0(P,Q))return!0}}return!1}_convertRingToPoints(g){return g.map(N=>new o.P(N[0],N[1]))}_convertMultiPolygonToPoints(g){return g.map(N=>N.length===0?[]:N[0].map(P=>new o.P(P[0],P[1])))}}class lw extends o.E{constructor(g){super(),this._style=g,this._buildings={},this._activeFloors=new Set,this._closestBuildingId=null,this._indoorState={selectedFloorId:null,activeFloorsVisible:!0,activeFloors:this._activeFloors},this._buildingDetectionStrategy=new rp,this._initialLoadDone=!1,o.aZ(["_updateUI"],this),this._style.on("style.load",()=>{this._style.isIndoorEnabled()&&(this._style.map.on("load",()=>{this._initialLoadDone=!0,this._indoorState&&this._indoorState.needsUpdate&&(this._indoorState.needsUpdate=!1,this._style.updateIndoorDependentLayers()),this._updateUI()}),this._style.map.on("move",this._updateUI),this._style.map.on("idle",this._updateUI))})}destroy(){this._buildings={},this._activeFloors=new Set,this._indoorState=null}selectFloor(g){g===this._selectedFloorId&&this._indoorState&&this._indoorState.activeFloorsVisible||(this._selectedFloorId=g,this._recalculateActiveFloors())}setActiveFloorsVisibility(g){this._updateActiveFloors(g),this._updateIndoorSelector()}setIndoorData(g){let N=!1;for(const[P,F]of Object.entries(g.buildings))if(this._buildings[P])for(const q of F.floorIds)this._buildings[P].floorIds.add(q),this._buildings[P].floors[q]?this._mergeFloors(this._buildings[P].floors[q],F.floors[q]):(this._buildings[P].floors[q]=F.floors[q],N=!0);else this._buildings[P]=F,N=!0;N&&this._recalculateActiveFloors()}getIndoorTileOptions(g,N){return this._indoorState?{sourceLayers:this._style.getIndoorSourceLayers(g,N),indoorState:this._indoorState}:null}getControlState(){const g=this._buildings,N=this._closestBuildingId,P=N&&g?g[N]:void 0;if(!P)return{selectedFloorId:null,activeFloorsVisible:!!this._indoorState&&this._indoorState.activeFloorsVisible,floors:[]};let F=null;for(const G of P.floorIds)if(this._activeFloors&&this._activeFloors.has(G)){F=G;break}const q=Array.from(P.floorIds).map(G=>({id:G,name:P.floors[G].name,zIndex:P.floors[G].zIndex})).sort((G,Q)=>Q.zIndex-G.zIndex).filter((G,Q,ae)=>Q===0||G.zIndex!==ae[Q-1].zIndex);return{selectedFloorId:F,activeFloorsVisible:!!this._indoorState&&this._indoorState.activeFloorsVisible,floors:q}}_updateUI(){this._initialLoadDone=!0;const g=this._style.map.transform,N=this._buildingDetectionStrategy.findClosestBuilding(this._buildings,g.center,g.zoom,g.getBounds(),this._makeViewportPolygon());if(N!==this._closestBuildingId){const P=this._closestBuildingId;this._closestBuildingId=N,this._onBuildingTransition(P,N),this._updateIndoorSelector()}}_onBuildingTransition(g,N){if(!this._indoorState)return;!N&&g?(this._indoorState.activeFloors=new Set,this._indoorState.activeFloorsVisible=!1,this._style.updateIndoorDependentLayers()):!!N&&!g&&(this._recalculateActiveFloors(),this._updateActiveFloors(!0))}_updateIndoorSelector(){this.fire(new o.C("selector-update",this.getControlState()))}_updateActiveFloors(g){this._indoorState={selectedFloorId:this._selectedFloorId,activeFloorsVisible:g,activeFloors:this._activeFloors},this._initialLoadDone?this._style.updateIndoorDependentLayers():this._indoorState.needsUpdate=!0}_recalculateActiveFloors(){if(!this._buildings)return;const g=o.d1.calculate(this._buildings,this._selectedFloorId,this._activeFloors);(function(N,P){if(N===P)return!0;if(!N||!P||N.size!==P.size)return!1;for(const F of N)if(!P.has(F))return!1;return!0})(g,this._activeFloors)||(this._activeFloors=g,this._updateActiveFloors(!!this._indoorState&&this._indoorState.activeFloorsVisible),this._updateIndoorSelector())}_mergeFloors(g,N){N.geometry&&(g.geometry?(g.geometry.type==="Polygon"&&(g.geometry={type:"MultiPolygon",coordinates:[g.geometry.coordinates]}),N.geometry.type==="Polygon"?g.geometry.coordinates.push(N.geometry.coordinates):N.geometry.type==="MultiPolygon"&&g.geometry.coordinates.push(...N.geometry.coordinates)):g.geometry=N.geometry)}_makeViewportPolygon(){const g=this._style.map.transform,N=g.width,P=g.height;return[g.pointLocation(new o.P(0,0)),g.pointLocation(new o.P(N,0)),g.pointLocation(new o.P(N,P)),g.pointLocation(new o.P(0,P))].map(F=>new o.P(F.lng,F.lat))}}const fv=(M,g)=>Er(M,g&&g.filter(N=>N.identifier!=="source.canvas")),wh=o.aJ(Ua,["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"]),Aj=o.aJ(Ua,["setCenter","setZoom","setBearing","setPitch"]),cw=new Set(["background","sky","slot","custom"]),X1={version:8,layers:[],sources:{}},np={duration:300,delay:0};class Mc extends o.E{constructor(g,N={}){if(super(),this.map=g,this.scope=N.scope||"",this.globalId=null,this.fragments=[],this.importDepth=N.importDepth||0,this.importsCache=N.importsCache||new Map,this.resolvedImports=N.resolvedImports||new Set,this.transition=Object.assign({},np),this._buildingIndex=new vx(this),this.crossTileSymbolIndex=new ep,this._mergedOrder=[],this._drapedFirstOrder=[],this._mergedLayers={},this._mergedIndoor={},this._mergedSourceCaches={},this._mergedOtherSourceCaches={},this._mergedSymbolSourceCaches={},this._mergedFillExtrusionSourceCaches={},this._clipLayerPresent=!1,this._hasAppearances=!1,this._has3DLayers=!1,this._hasCircleLayers=!1,this._hasSymbolLayers=!1,this._importedAsBasemap=!1,this._changes=N.styleChanges||new Ne,this._hasDataDrivenEmissive=!1,this.indoorManager=new lw(this),this.dispatcher=N.dispatcher?N.dispatcher:new wt(Et(),this),this.map.painter&&this.map.painter.context){const F=this.map.painter.context.maxUniformBufferBindings,q=Math.floor(this.map.painter.context.maxUniformBlockSize/4);this.dispatcher.broadcast("setContextParams",{maxBindingPoints:F,maxUniformBlockSizeDwords:q,disableSymbolUBO:this.map.painter.context.disableSymbolUBO})}N.imageManager?this.imageManager=N.imageManager:(this.imageManager=new hs(this.map._spriteFormat),this.imageManager.setEventedParent(this)),this.imageManager.addScope(this.scope),this.glyphManager=N.glyphManager?N.glyphManager:new o.d2(g._requestManager,N.localFontFamily?o.d3.all:N.localIdeographFontFamily?o.d3.ideographs:o.d3.none,N.localFontFamily||N.localIdeographFontFamily,N.useServerFontComposition),N.modelManager?this.modelManager=N.modelManager:(this.modelManager=new i4(g._requestManager),this.modelManager.setEventedParent(this)),this._layers={},this._sourceCaches={},this._otherSourceCaches={},this._symbolSourceCaches={},this._fillExtrusionSourceCaches={},this._loaded=!1,this._precompileDone=!1,this._shouldPrecompile=!1,this._availableImages=[],this._availableModels={},this._order=[],this._markersNeedUpdate=!1,this.options=N.configOptions?N.configOptions:new Map,this._configDependentLayers=N.configDependentLayers?N.configDependentLayers:new Set,this._indoorDependentLayers=N.indoorDependentLayers?N.indoorDependentLayers:new Set,this._config=N.config,this._styleColorTheme={lut:null,lutLoading:!1,lutLoadingCorrelationID:0,colorTheme:null,colorThemeOverride:N.colorThemeOverride},this._styleColorThemeForScope={},this._initialConfig=N.initialConfig,this.dispatcher.broadcast("setReferrer",o.d4()),this.dispatcher.broadcast("setConfig",o.d5());const P=this;this._rtlTextPluginCallback=Mc.registerForPluginStateChange(F=>{P.dispatcher.broadcast("syncRTLPluginState",{pluginStatus:F.pluginStatus,pluginURL:F.pluginURL},(q,G)=>{if(o.d6(q),G&&G.every(Q=>Q))for(const Q in P._sourceCaches){const ae=P._sourceCaches[Q],me=ae.getSource().type;me!=="vector"&&me!=="geojson"||ae.reload()}})}),this.on("data",F=>{if(F.dataType!=="source"||F.sourceDataType!=="metadata")return;const q=this.getOwnSource(F.sourceId);if(q&&q.vectorLayerIds)for(const G in this._layers){const Q=this._layers[G];Q.source===q.id&&this._validateLayer(Q)}})}load(g){return g?(typeof g=="string"?this.loadURL(g):this.loadJSON(g),this):this}_getGlobalId(g){if(!g)return null;if(typeof g=="string"){if(o.e(g))return g;const N=o.d7(g);if(!N.startsWith("http"))try{return new URL(N,location.href).toString()}catch{return N}return N}return`json://${o.d8(JSON.stringify(g))}`}_diffStyle(g,N,P){this.globalId=this._getGlobalId(g);const F=(q,G)=>{try{G(null,this.setState(q,P))}catch(Q){G(Q,!1)}};if(typeof g=="string"){const q=this.map._requestManager.normalizeStyleURL(g),G=this.map._requestManager.transformRequest(q,o.R.Style);o.m(G,(Q,ae)=>{Q?this.fire(new o.B(Q)):ae&&F(ae,N)})}else typeof g=="object"&&F(g,N)}loadURL(g,N={}){this.fire(new o.C("dataloading",{dataType:"style"}));const P=typeof N.validate=="boolean"?N.validate:!o.e(g);this.globalId=this._getGlobalId(g),g=this.map._requestManager.normalizeStyleURL(g,N.accessToken),this.resolvedImports.add(g);const F=this.importsCache.get(g);if(F)return this._load(F,P);const q=this.map._requestManager.transformRequest(g,o.R.Style);this._request=o.m(q,(G,Q)=>{if(this._request=null,G)this.fire(new o.B(G));else if(Q)return this.importsCache.set(g,Q),this._load(Q,P)})}loadJSON(g,N={}){this.fire(new o.C("dataloading",{dataType:"style"})),this.globalId=this._getGlobalId(g),this._request=o.o.frame(()=>{this._request=null,this._load(g,N.validate!==!1)})}loadEmpty(){this.fire(new o.C("dataloading",{dataType:"style"})),this._load(X1,!1)}_loadImports(g,N,P){if(this.importDepth>=4)return o.w("Style doesn't support nesting deeper than 5"),Promise.resolve();const F=[];for(const q of g){const G=this._createFragmentStyle(q),Q=new Promise(ye=>{G.once("style.import.load",ye),G.once("error",ye)}).then(()=>{this.mergeAll(),this.fire(new o.C("data",{dataType:"style"}))});if(F.push(Q),this.resolvedImports.has(q.url)){G.loadEmpty();continue}const ae=q.data||this.importsCache.get(q.url);ae?(q.data?(G.fire(new o.C("dataloading",{dataType:"style"})),G.globalId=G._getGlobalId(ae),queueMicrotask(()=>G._load(ae,N))):G.loadJSON(ae,{validate:N}),this._isInternalStyle(ae)&&(G.globalId=null)):q.url?G.loadURL(q.url,{validate:N}):G.loadEmpty();const me={style:G,id:q.id,config:q.config};if(P){const ye=this.fragments.findIndex(({id:Ae})=>Ae===P);this.fragments=this.fragments.slice(0,ye).concat(me).concat(this.fragments.slice(ye))}else this.fragments.push(me)}return Promise.allSettled(F)}getImportGlobalIds(g=this,N=new Set){for(const P of g.fragments)P.style.globalId&&N.add(P.style.globalId),this.getImportGlobalIds(P.style,N);return[...N.values()]}_createFragmentStyle(g){const N=this.scope?o.F(g.id,this.scope):g.id;let P;const F=this._initialConfig&&this._initialConfig[N];(g.config||F)&&(P=Object.assign({},g.config,F));const q=new Mc(this.map,{scope:N,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:P,configOptions:this.options,colorThemeOverride:g["color-theme"],configDependentLayers:this._configDependentLayers,indoorDependentLayers:this._indoorDependentLayers});return q.setEventedParent(this.map,{style:q}),q}_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(g){return this.isRootStyle()&&(g.fragment||!!g.schema&&g.fragment!==!1)}_load(g,N){if(this._isInternalStyle(g)){const q=Object.assign({},X1,{imports:[{id:"basemap",data:g,url:""}]},g.center?{center:g.center}:{},g.bearing?{bearing:g.bearing}:{},g.pitch?{pitch:g.pitch}:{},g.zoom?{zoom:g.zoom}:{},g.light?{light:g.light}:{});return this._importedAsBasemap=!0,void this._load(q,N)}if(this.updateConfig(this._config,g.schema),N&&fv(this,Jt(g)))return;this._loaded=!0;for(const q in g.sources)this.addSource(q,g.sources[q],{validate:!1,isInitialLoad:!0});this.stylesheet=o.d9(g);const P=()=>{if(g.iconsets)for(const ae in g.iconsets)this.addIconset(ae,g.iconsets[ae]);g.sprite?this._loadIconset(g.sprite):(this.imageManager.setLoaded(!0,this.scope),this.dispatcher.broadcast("spriteLoaded",{scope:this.scope,isLoaded:!0})),!this.glyphManager.url&&g.glyphs&&this.glyphManager.setURL(g.glyphs);const q=Xf(this.stylesheet.layers);if(this._order=q.map(ae=>ae.id),this.stylesheet.light&&o.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 ae=this.stylesheet.lights[0];this.light=new Gr(ae.properties,ae.id)}else this.setLights(this.stylesheet.lights);this.light||(this.light=new Gr(this.stylesheet.light)),this._layers={};for(const ae of q){const me=o.de(ae,this.scope,this._styleColorTheme.lut,this.options);me.expressionDependencies.configDependencies.size!==0&&this._configDependentLayers.add(me.fqid),me.expressionDependencies.isIndoorDependent&&this._indoorDependentLayers.add(me.fqid),this._hasAppearances=this._hasAppearances||me.getAppearances().length!==0,me.setEventedParent(this,{layer:{id:me.id}}),this._layers[me.id]=me;const ye=this.getOwnLayerSourceCache(me),Ae=!!this.directionalLight&&this.directionalLight.shadowsEnabled();ye&&me.canCastShadows()&&Ae&&(ye.castsShadows=!0)}if(this.glyphManager.url){const ae=new Set;for(const me in this._layers){const ye=this._layers[me];if(ye.type==="symbol"&&ye.layout){const Ae=ye.layout.get("text-font");Ae&&Ae.value&&Ae.value.kind==="constant"&&ae.add(Ae.value.value.join(","))}}for(const me of ae)this.glyphManager.prefetchRange(me,0)}this.stylesheet.featuresets&&this.setFeaturesetSelectors(this.stylesheet.featuresets),this.stylesheet.models&&this.addModelURLs(this.stylesheet.models);const G=this.stylesheet.terrain;G&&(this.checkCanvasFingerprintNoise(),this.disableElevatedTerrain||this.terrainSetForDrapingOnly()||this._createTerrain(G,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 o.C("data",{dataType:"style"}));const Q=this.isRootStyle();g.imports?this._loadImports(g.imports,N).then(()=>{this._reloadImports(),this.fire(new o.C(Q?"style.load":"style.import.load"))}).catch(ae=>{this.fire(new o.B(new Error("Failed to load imports",ae))),this.fire(new o.C(Q?"style.load":"style.import.load"))}):(this._reloadImports(),this.fire(new o.C(Q?"style.load":"style.import.load")))};this._styleColorTheme.colorTheme=this.stylesheet["color-theme"];const F=this._styleColorTheme.colorThemeOverride?this._styleColorTheme.colorThemeOverride:this._styleColorTheme.colorTheme;if(F){const q=this._evaluateColorThemeData(F);this._loadColorTheme(q).then(()=>{P()}).catch(G=>{o.w(`Couldn't load color theme from the stylesheet: ${G}`),P()})}else this._styleColorTheme.lut=null,P()}isRootStyle(){return this.importDepth===0}hasAppearances(){return this._hasAppearances||this.fragments.some(g=>g.style.hasAppearances())}mergeAll(){let g,N,P,F,q,G,Q,ae,me,ye;const Ae={};this.terrain&&this.terrain.scope!==this.scope&&delete this.terrain,this.forEachFragmentStyle(Te=>{if(Te.stylesheet){if(Te.light!=null&&(g=Te.light),Te.stylesheet.lights)for(const Fe of Te.stylesheet.lights)Fe.type==="ambient"&&Te.ambientLight!=null&&(N=Te.ambientLight),Fe.type==="directional"&&Te.directionalLight!=null&&(P=Te.directionalLight);F=this._prioritizeTerrain(F,Te.terrain,Te.stylesheet.terrain),Te.stylesheet.fog&&Te.fog!=null&&(q=Te.fog),Te.stylesheet.snow&&Te.snow!=null&&(G=Te.snow),Te.stylesheet.rain&&Te.rain!=null&&(Q=Te.rain),Te.stylesheet.camera!=null&&(ye=Te.stylesheet.camera),Te.stylesheet.projection!=null&&(ae=Te.stylesheet.projection),Te.stylesheet.transition!=null&&(me=Te.stylesheet.transition),Ae[Te.scope]=Te._styleColorTheme}}),this.light=g,this.ambientLight=N,this.directionalLight=P,this.fog=q,this.snow=G,this.rain=Q,this._styleColorThemeForScope=Ae,F===null?delete this.terrain:this.terrain=F,this.camera=ye||{"camera-projection":"perspective"},this.projection=ae||{name:"mercator"},this.transition=Object.assign({},np,me),this.mergeSources(),this.mergeLayers(),this.mergeIndoor()}forEachFragmentStyle(g){const N=P=>{for(const F of P.fragments)N(F.style);g(P)};N(this)}_prioritizeTerrain(g,N,P){const F=g&&g.drapeRenderMode===0;return P===null?N&&N.drapeRenderMode===0?N:F?g:null:N!=null&&(!g||F||N&&N.drapeRenderMode===1)?N:g}mergeTerrain(){let g;this.terrain&&this.terrain.scope!==this.scope&&delete this.terrain,this.forEachFragmentStyle(N=>{g=this._prioritizeTerrain(g,N.terrain,N.stylesheet.terrain)}),g===null?delete this.terrain:this.terrain=g}mergeProjection(){let g;this.forEachFragmentStyle(N=>{N.stylesheet.projection!=null&&(g=N.stylesheet.projection)}),this.projection=g||{name:"mercator"}}mergeSources(){const g={},N={},P={},F={};this.forEachFragmentStyle(q=>{for(const G in q._sourceCaches){const Q=o.F(G,q.scope);g[Q]=q._sourceCaches[G]}for(const G in q._otherSourceCaches){const Q=o.F(G,q.scope);N[Q]=q._otherSourceCaches[G]}for(const G in q._symbolSourceCaches){const Q=o.F(G,q.scope);P[Q]=q._symbolSourceCaches[G]}for(const G in q._fillExtrusionSourceCaches){const Q=o.F(G,q.scope);F[Q]=q._fillExtrusionSourceCaches[G]}}),this._mergedSourceCaches=g,this._mergedOtherSourceCaches=N,this._mergedSymbolSourceCaches=P,this._mergedFillExtrusionSourceCaches=F}mergeIndoor(){this.forEachFragmentStyle(g=>{if(g.stylesheet&&g.stylesheet.indoor)for(const N of Object.values(g.stylesheet.indoor)){const P=N,F=o.F(P.sourceId,g.scope);this._mergedIndoor[F]=new Set(P.sourceLayers||[])}})}mergeLayers(){const g={},N=[],P={};this._mergedSlots=[],this._has3DLayers=!1,this._hasCircleLayers=!1,this._hasSymbolLayers=!1,this.forEachFragmentStyle(G=>{for(const Q of G._order){const ae=G._layers[Q];if(ae.type==="slot"){const me=o.da(Q);if(g[me])continue;g[me]=[]}ae.slot&&g[ae.slot]?g[ae.slot].push(ae):N.push(ae)}}),this._mergedOrder=[];let F=-1;const q=(G=[])=>{for(const Q of G)if(Q.type==="slot"){const ae=o.da(Q.id);g[ae]&&q(g[ae]),this._mergedSlots.push(ae)}else{const ae=o.F(Q.id,Q.scope);this._mergedOrder.push(ae),P[ae]=Q,Q.is3D(!!this.terrain)&&(this._has3DLayers=!0,F=this._mergedOrder.length-1),Q.type==="circle"&&(this._hasCircleLayers=!0),Q.type==="symbol"&&(this._hasSymbolLayers=!0),Q.type==="clip"&&(this._clipLayerPresent=!0)}};if(q(N),this._has3DLayers){const G={};for(let Q=0;QG[Q]-G[ae])}this._mergedLayers=P,this.updateDrapeFirstLayers(),this._buildingIndex.processLayersChanged(),this._updateDataDrivenEmissiveStrength()}terrainSetForDrapingOnly(){return!!this.terrain&&this.terrain.drapeRenderMode===0}getCamera(){return this.stylesheet.camera}setCamera(g){return this.stylesheet.camera=Object.assign({},this.stylesheet.camera,g),this.camera=this.stylesheet.camera,this}_evaluateColorThemeData(g){return g.data?function(N,P,F){const q=Object.assign({},P);for(const Q of Object.keys(_x))q[Q]===void 0&&(q[Q]=_x[Q].default);const G=new o.aa(Bl,N,new Map(F));return G.setTransitionOrValue(q,F),G.untransitioned().possiblyEvaluate(new o.ae(0,{worldview:void 0}))}(this.scope,g,this.options).get("data"):null}_loadColorTheme(g){this._styleColorTheme.lutLoading=!0,this._styleColorTheme.lutLoadingCorrelationID+=1;const N=this._styleColorTheme.lutLoadingCorrelationID;return new Promise((P,F)=>{const q="data:image/png;base64,";if(!g||g.length===0)return this._styleColorTheme.lut=null,this._styleColorTheme.lutLoading=!1,void P();let G=g;G.startsWith(q)||(G=q+G);const Q=o.I.from("mapbox-reserved-lut"),ae=new Image;ae.src=G,ae.onerror=()=>{this._styleColorTheme.lutLoading=!1,F(new Error("Failed to load image data"))},ae.onload=()=>{if(this._styleColorTheme.lutLoadingCorrelationID!==N)return void P();this._styleColorTheme.lutLoading=!1;const{width:me,height:ye,data:Ae}=o.o.getImageData(ae);if(ye>32)return void F(new Error("The height of the image must be less than or equal to 32 pixels."));if(me!==ye*ye)return void F(new Error("The width of the image must be equal to the height squared."));this.getImage(Q)&&this.removeImage(Q),this.addImage(Q,{data:new o.q({width:me,height:ye},Ae),pixelRatio:1,sdf:!1,usvg:!1,version:0});const Te=this.imageManager.getImage(Q,this.scope);Te?(this._styleColorTheme.lut={image:Te.data,data:g},P()):F(new Error("Missing LUT image."))}})}getLut(g){const N=this._styleColorThemeForScope[g];return N?N.lut:null}setProjection(g){g?this.stylesheet.projection=g: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(g){this._spriteRequest=function(N,P,F){let q,G,Q;const ae=o.o.devicePixelRatio>1?"@2x":"";let me=o.m(P.transformRequest(P.normalizeSpriteURL(N,ae,".json"),o.R.SpriteJSON),(Te,Fe)=>{me=null,Q||(Q=Te,q=Fe,Ae())}),ye=o.n(P.transformRequest(P.normalizeSpriteURL(N,ae,".png"),o.R.SpriteImage),(Te,Fe)=>{ye=null,Q||(Q=Te,G=Fe,Ae())});function Ae(){if(Q)F(Q);else if(q&&G){const Te=o.o.getImageData(G),Fe={};for(const Ye in q){const{width:Ge,height:dt,x:lt,y:_t,sdf:Ct,pixelRatio:ht,stretchX:Kt,stretchY:Lt,content:Wt}=q[Ye],Tt=new o.q({width:Ge,height:dt});o.q.copy(Te,Tt,{x:lt,y:_t},{x:0,y:0},{width:Ge,height:dt},null),Fe[Ye]={data:Tt,pixelRatio:ht!==void 0?ht:1,sdf:Ct!==void 0&&Ct,stretchX:Kt,stretchY:Lt,content:Wt,usvg:!1,version:0}}F(null,Fe)}}return{cancel(){me&&(me.cancel(),me=null),ye&&(ye.cancel(),ye=null)}}}(g,this.map._requestManager,(N,P)=>{if(this._spriteRequest=null,N)this.fire(new o.B(N));else if(P){const F=new Map;for(const q in P)F.set(o.I.from(q),P[q]);this.addImages(F)}this.imageManager.setLoaded(!0,this.scope),this.dispatcher.broadcast("spriteLoaded",{scope:this.scope,isLoaded:!0}),this.fire(new o.C("data",{dataType:"style"}))})}addIconset(g,N){if(N.type==="sprite")return void this._loadSprite(N.url);const P=this.getOwnSourceCache(N.source);if(!P)return void this.fire(new o.B(new Error(`Source "${N.source}" as specified by iconset "${g}" does not exist and cannot be used as an iconset source`)));const F=P.getSource();if(F.type!=="raster-array")return void this.fire(new o.B(new Error(`Source "${N.source}" as specified by iconset "${g}" is not a "raster-array" source and cannot be used as an iconset source`)));F.partial=!1;const q=new Z1(g,this.scope,P);this.imageManager.addImageProvider(q,this.scope)}removeIconset(g){this.imageManager.removeImageProvider(g,this.scope)}_loadIconset(g){if(!o.e(g)&&this.map._spriteFormat!=="icon_set"||this.map._spriteFormat==="raster")return void this._loadSprite(g);const N=this.map._spriteFormat==="auto";var P,F;this._spriteRequest=(F=(q,G)=>{if(this._spriteRequest=null,q)N?this._loadSprite(g):this.fire(new o.B(q));else if(G){const Q=new Map;for(const ae in G)Q.set(o.I.from(ae),G[ae]);this.addImages(Q)}this.imageManager.setLoaded(!0,this.scope),this.dispatcher.broadcast("spriteLoaded",{scope:this.scope,isLoaded:!0}),this.fire(new o.C("data",{dataType:"style"}))},o.b1((P=this.map._requestManager).transformRequest(P.normalizeIconsetURL(g),o.R.Iconset),(q,G)=>{if(q)return void F(q);const Q={},ae=o.c$(new o.a$(G));for(const me of ae.icons){const ye={version:1,pixelRatio:o.o.devicePixelRatio,content:Pd(me),stretchX:me.metadata?Gc(me.metadata.stretch_x_areas):void 0,stretchY:me.metadata?Gc(me.metadata.stretch_y_areas):void 0,sdf:!1,usvg:!0,icon:me};Q[me.name]=ye}F(null,Q)}))}_validateLayer(g){const N=this.getOwnSource(g.source);if(!N)return;const P=g.sourceLayer;P&&(N.type==="geojson"||N.vectorLayerIds&&N.vectorLayerIds.indexOf(P)===-1)&&this.fire(new o.B(new Error(`Source layer "${P}" does not exist on source "${N.id}" as specified by style layer "${g.id}"`)))}loaded(){if(!this._loaded||Object.keys(this._changes.getUpdatedSourceCaches()).length)return!1;for(const g in this._sourceCaches)if(!this._sourceCaches[g].loaded())return!1;if(!this.imageManager.isLoaded()||this.imageManager.hasPatternsInFlight()||!this.modelManager.isLoaded()||this._styleColorTheme.lutLoading)return!1;for(const{style:g}of this.fragments)if(!g.loaded())return!1;return!0}_serializeImports(){if(this.stylesheet.imports)return this.stylesheet.imports.map((g,N)=>{const P=this.fragments[N];return P&&P.style&&(g.data=P.style.serialize()),g})}_serializeSources(){const g={};for(const N in this._sourceCaches){const P=this._sourceCaches[N].getSource();g[P.id]||(g[P.id]=P.serialize())}return g}_serializeLayers(g){const N=[];for(const P of g){const F=this._layers[P];F&&F.type!=="custom"&&N.push(F.serialize())}return N}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 g in this._sourceCaches)if(this._sourceCaches[g].hasTransition())return!0;for(const g in this._layers)if(this._layers[g].hasTransition())return!0;return!1}_updateDataDrivenEmissiveStrength(){for(const g in this._mergedLayers){const N=this._mergedLayers[g];if(N._transitionablePaint&&N._transitionablePaint._values){const P=N._transitionablePaint._values["line-emissive-strength"];if(P&&P.value&&P.value.isDataDriven())return void(this._hasDataDrivenEmissive=!0)}}this._hasDataDrivenEmissive=!1}hasDataDrivenEmissiveStrength(){return this._hasDataDrivenEmissive}get order(){return this.terrain?this._drapedFirstOrder:this._mergedOrder}_getOrder(g){return g?this.order:this._mergedOrder}isLayerDraped(g){return!!this.terrain&&g.isDraped(this.getLayerSourceCache(g))}_checkLoaded(){if(!this._loaded)throw new Error("Style is not done loading")}_checkLayer(g){const N=this.getOwnLayer(g);if(N)return N;this.fire(new o.B(new Error(`The layer '${g}' does not exist in the map's style.`)))}_checkSource(g){const N=this.getOwnSource(g);if(N)return N;this.fire(new o.B(new Error(`The source '${g}' does not exist in the map's style.`)))}precompilePrograms(g,N){const P=this.map.painter;if(P)for(let F=g.minzoom||0;F<(g.maxzoom||25.5);F++){const q=g.getProgramIds();if(q)for(const G of q){const Q=g.getDefaultProgramParams(G,N.zoom,this._styleColorTheme.lut);Q&&(P.style=this,this.fog&&(P._fogVisible=!0,Q.overrideFog=!0,P.getOrCreateProgram(G,Q)),P._fogVisible=!1,Q.overrideFog=!1,P.getOrCreateProgram(G,Q),(this.stylesheet.terrain||this.stylesheet.projection&&this.stylesheet.projection.name==="globe")&&(Q.overrideRtt=!0,P.getOrCreateProgram(G,Q)))}}}update(g){if(!this._loaded)return;this.ambientLight&&this.ambientLight.recalculate(g),this.directionalLight&&this.directionalLight.recalculate(g);const N=this.calculateLightsBrightness();g.brightness=N||0,N!==this._brightness&&(this._brightness=N,this.dispatcher.broadcast("setBrightness",N)),g.worldview!==this._worldview&&(this._worldview=g.worldview,this.dispatcher.broadcast("setWorldview",this._worldview));const P=this._changes.isDirty();let F=!1;if(this._changes.isDirty()){const ae=this._changes.getLayerUpdatesByScope();for(const me in ae){const{updatedIds:ye,removedIds:Ae}=ae[me];(ye||Ae)&&(this._updateWorkerLayers(me,ye,Ae),F=!0)}this.updateSourceCaches(),this._updateTilesForChangedImages(),this.updateLayers(g),this.light&&this.light.updateTransitions(g),this.ambientLight&&this.ambientLight.updateTransitions(g),this.directionalLight&&this.directionalLight.updateTransitions(g),this.fog&&this.fog.updateTransitions(g),this.snow&&this.snow.updateTransitions(g),this.rain&&this.rain.updateTransitions(g),this._changes.reset()}const q={};for(const ae in this._mergedSourceCaches){const me=this._mergedSourceCaches[ae];q[ae]=me.used,me.used=!1,me.tileCoverLift=0}const G={};for(const ae of this._mergedOrder){const me=this._mergedLayers[ae];if((me.visibility!=="none"||me.hasTransition())&&me.recalculate(g,this._availableImages),!me.isHidden(g.zoom)){const ye=this.getLayerSourceCache(me);ye&&(ye.used=!0,ye.tileCoverLift=Math.max(ye.tileCoverLift,me.tileCoverLift()))}if(me.type==="fill-extrusion"){const ye=o.F(me.source,me.scope);if(ye in this._mergedFillExtrusionSourceCaches){const Ae=me.layout&&me.layout.get("source-max-zoom");if(Ae!=null){const Te=G[ye];G[ye]=Te==null?Ae:Math.min(Te,Ae)}}}!this._precompileDone&&this._shouldPrecompile&&("requestIdleCallback"in window?requestIdleCallback(()=>{this.precompilePrograms(me,g)}):this.precompilePrograms(me,g))}this._shouldPrecompile&&(this._precompileDone=!0);for(const ae in this._mergedFillExtrusionSourceCaches)this._mergedFillExtrusionSourceCaches[ae].setMaxzoomOverride(G[ae]!=null?G[ae]:null);this.terrain&&F&&this.mergeLayers();const Q=this.imageManager.getPendingImageProviders();for(const ae of Q)ae.sourceCache.used=!0;for(const ae in q){const me=this._mergedSourceCaches[ae];q[ae]!==me.used&&me.getSource().fire(new o.C("data",{sourceDataType:"visibility",dataType:"source",sourceId:me.getSource().id}))}this.light&&this.light.recalculate(g),this.terrain&&this.terrain.recalculate(g),this.fog&&this.fog.recalculate(g),this.snow&&this.snow.recalculate(g),this.rain&&this.rain.recalculate(g),this.z=g.zoom,this._markersNeedUpdate&&(this._updateMarkersOpacity(),this._markersNeedUpdate=!1),this.imageManager.clearUpdatedImages(this.scope),P&&this.fire(new o.C("data",{dataType:"style"}))}updateImageProviders(){const g=this.imageManager.getPendingImageProviders();for(const N of g){const P=N.resolvePendingRequests(),F=this.getFragmentStyle(N.scope);F&&F.addImages(P)}}_updateTilesForChangedImages(){const g={};for(const N in this._mergedSourceCaches){const P=this._mergedSourceCaches[N].getSource().scope;g[P]=g[P]||this._changes.getUpdatedImages(P),g[P].length!==0&&this._mergedSourceCaches[N].reloadTilesForDependencies(["icons","patterns"],g[P])}for(const N in g)this._changes.resetUpdatedImages(N)}_updateWorkerLayers(g,N,P){const F=this.getFragmentStyle(g);F&&this.dispatcher.broadcast("updateLayers",{layers:N?F._serializeLayers(N):[],scope:g,removedIds:P||[],options:F.options})}setState(g,N){if(this._checkLoaded(),fv(this,Jt(g)))return!1;(g=o.d9(g)).layers=Xf(g.layers);const P=function(G,Q){if(!G)return[{command:Ua.setStyle,args:[Q]}];let ae=[];try{if(!o.b6(G.version,Q.version))return[{command:Ua.setStyle,args:[Q]}];if(o.b6(G.center,Q.center)||ae.push({command:Ua.setCenter,args:[Q.center]}),o.b6(G.zoom,Q.zoom)||ae.push({command:Ua.setZoom,args:[Q.zoom]}),o.b6(G.bearing,Q.bearing)||ae.push({command:Ua.setBearing,args:[Q.bearing]}),o.b6(G.pitch,Q.pitch)||ae.push({command:Ua.setPitch,args:[Q.pitch]}),o.b6(G.sprite,Q.sprite)||ae.push({command:Ua.setSprite,args:[Q.sprite]}),o.b6(G.glyphs,Q.glyphs)||ae.push({command:Ua.setGlyphs,args:[Q.glyphs]}),o.b6(G.imports,Q.imports)||function(Fe=[],Ye=[],Ge){Ye=Ye||[];const dt=(Fe=Fe||[]).map(Dp),lt=Ye.map(Dp),_t=Fe.reduce(Eg,{}),Ct=Ye.reduce(Eg,{}),ht=dt.slice();let Kt,Lt,Wt,Tt;for(Kt=0,Lt=0;Kt{Fe.source&&me[Fe.source]?ae.push({command:Ua.removeLayer,args:[Fe.id]}):Ae.push(Fe)});let Te=G.terrain;Te&&me[Te.source]&&(ae.push({command:Ua.setTerrain,args:[void 0]}),Te=void 0),ae=ae.concat(ye),o.b6(Te,Q.terrain)||ae.push({command:Ua.setTerrain,args:[Q.terrain]}),function(Fe,Ye,Ge){Ye=Ye||[];const dt=(Fe=Fe||[]).map(Dp),lt=Ye.map(Dp),_t=Fe.reduce(Eg,{}),Ct=Ye.reduce(Eg,{}),ht=dt.slice(),Kt=Object.create(null);let Lt,Wt,Tt,It,Ut,rs,Zt;for(Lt=0,Wt=0;Lt!(G.command in Aj));if(P.length===0)return!1;const F=P.filter(G=>!(G.command in wh));if(F.length>0)throw new Error(`Unimplemented: ${F.map(G=>G.command).join(", ")}.`);const q=[];return P.forEach(G=>{q.push(this[G.command](...G.args))}),N&&Promise.all(q).then(N).catch(N),this.stylesheet=g,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(g){if(g.size===0)return this;for(const[N,P]of g.entries()){if(this.getImage(N))return this.fire(new o.B(new Error(`An image with the name "${N.name}" already exists.`)));this.imageManager.addImage(N,this.scope,P),this._changes.updateImage(N,this.scope)}return this._updateWorkerImages(),this.fire(new o.C("data",{dataType:"style"})),this}addImage(g,N){return this.getImage(g)?this.fire(new o.B(new Error(`An image with the name "${g.name}" already exists.`))):(this.imageManager.addImage(g,this.scope,N),this._changes.updateImage(g,this.scope),this._updateWorkerImages(),this.fire(new o.C("data",{dataType:"style"})),this)}updateImage(g,N,P=!1){this.imageManager.updateImage(g,this.scope,N),P&&(this._changes.updateImage(g,this.scope),this._updateWorkerImages(),this.fire(new o.C("data",{dataType:"style"})))}getImage(g){return this.imageManager.getImage(g,this.scope)}removeImage(g){return this.getImage(g)?(this.imageManager.removeImage(g,this.scope),this._changes.updateImage(g,this.scope),this._updateWorkerImages(),this.fire(new o.C("data",{dataType:"style"})),this):this.fire(new o.B(new Error("No image with this name exists.")))}listImages(){return this._checkLoaded(),this._availableImages.slice()}getActualScope(){return this._importedAsBasemap?"basemap":this.scope}addModelURLs(g){return this.modelManager.addModelURLs(g,this.getActualScope()),this._updateWorkerModels(),this.fire(new o.C("data",{dataType:"style"})),this}addModel(g,N,P={}){return this._checkLoaded(),this._validate(Xs,`models.${g}`,N,null,P)||(this.modelManager.addModel(g,N,this.getActualScope()),this.fire(new o.C("data",{dataType:"style"}))),this}hasModel(g){return this.modelManager.hasModel(g,this.getActualScope())}removeModel(g){return this.hasModel(g)?(this.modelManager.removeModel(g,this.getActualScope(),!1,!0),this.fire(new o.C("data",{dataType:"style"})),this):this.fire(new o.B(new Error("No model with this ID exists.")))}listModels(){return this._checkLoaded(),this.modelManager.listModels(this.getActualScope())}addSource(g,N,P={}){if(this._checkLoaded(),this.getOwnSource(g)!==void 0)throw new Error(`There is already a source with ID "${g}".`);if(!N.type)throw new Error(`The type property must be defined, but only the following properties were given: ${Object.keys(N).join(", ")}.`);if(["vector","raster","geojson","video","image"].indexOf(N.type)>=0&&this._validate(Cr,`sources.${g}`,N,null,P))return;this.map&&this.map._collectResourceTiming&&(N.collectResourceTiming=!0);const F=z0(g,N,this.dispatcher,this);F.scope=this.scope,F.setEventedParent(this,()=>({isSourceLoaded:this._isSourceCacheLoaded(F.id),source:F.serialize(),sourceId:F.id}));const q=G=>{const Q=(G===o.b4.Symbol?"symbol:":G===o.b4.FillExtrusion?"fill-extrusion:":"other:")+F.id,ae=o.F(Q,this.scope),me=this._sourceCaches[Q]=new Uo(ae,F,G);G===o.b4.Symbol?this._symbolSourceCaches[F.id]=me:G===o.b4.FillExtrusion?this._fillExtrusionSourceCaches[F.id]=me:this._otherSourceCaches[F.id]=me,me.onAdd(this.map)};q(o.b4.Other),N.type!=="vector"&&N.type!=="geojson"||(q(o.b4.Symbol),N.type==="vector"&&q(o.b4.FillExtrusion)),F.onAdd&&F.onAdd(this.map),P.isInitialLoad||(this.mergeSources(),this._changes.setDirty())}removeSource(g){this._checkLoaded();const N=this.getOwnSource(g);if(!N)throw new Error("There is no source with this ID");for(const F in this._layers)if(this._layers[F].source===g)return this.fire(new o.B(new Error(`Source "${g}" cannot be removed while layer "${F}" is using it.`)));if(this.terrain&&this.terrain.scope===this.scope&&this.terrain.get().source===g)return this.fire(new o.B(new Error(`Source "${g}" cannot be removed while terrain is using it.`)));if(this.stylesheet.iconsets){const F=Object.entries(this.stylesheet.iconsets).find(([q,G])=>G.type==="source"&&G.source===g);if(F)return this.fire(new o.B(new Error(`Source "${g}" cannot be removed while iconset "${F[0]}" is using it.`)))}const P=this.getOwnSourceCaches(g);for(const F of P){const q=o.da(F.id);delete this._sourceCaches[q],this._changes.discardSourceCacheUpdate(F.id),F.fire(new o.C("data",{sourceDataType:"metadata",dataType:"source",sourceId:F.getSource().id})),F.setEventedParent(null),F.clearTiles()}return delete this._otherSourceCaches[g],delete this._symbolSourceCaches[g],delete this._fillExtrusionSourceCaches[g],this.mergeSources(),N.setEventedParent(null),N.onRemove&&N.onRemove(this.map),this._changes.setDirty(),this}setGeoJSONSourceData(g,N){this._checkLoaded(),this.getOwnSource(g).setData(N),this._changes.setDirty()}getOwnSource(g){const N=this.getOwnSourceCache(g);return N&&N.getSource()}getOwnSources(){const g=[];for(const N in this._otherSourceCaches){const P=this.getOwnSourceCache(N);P&&g.push(P.getSource())}return g}areTilesLoaded(){const g=this._mergedSourceCaches;for(const N in g){const P=g[N]._tiles;for(const F in P){const q=P[F];if(q.state!=="loaded"&&q.state!=="errored")return!1}}return!0}setLights(g){if(this._checkLoaded(),!g)return delete this.ambientLight,void delete this.directionalLight;const N=this._getTransitionParameters();for(const q of g){if(this._validate(Ee,"lights",q))return;switch(q.type){case"ambient":if(this.ambientLight){const G=this.ambientLight;G.set(q),G.updateTransitions(N)}else this.ambientLight=new hr(q,Sa(),this.scope,this.options);break;case"directional":if(this.directionalLight){const G=this.directionalLight;G.set(q),G.updateTransitions(N)}else this.directionalLight=new hr(q,$o(),this.scope,this.options)}}const P=Object.assign(N,{worldview:this.map.getWorldview()}),F=new o.ae(this.z||0,P);this.ambientLight&&this.ambientLight.recalculate(F),this.directionalLight&&this.directionalLight.recalculate(F),this._brightness=this.calculateLightsBrightness(),this.dispatcher.broadcast("setBrightness",this._brightness)}calculateLightsBrightness(){const g=this.directionalLight,N=this.ambientLight;if(!g||!N)return;const P=Te=>.2126*(Te[0]<=.03928?Te[0]/12.92:Math.pow((Te[0]+.055)/1.055,2.4))+.7152*(Te[1]<=.03928?Te[1]/12.92:Math.pow((Te[1]+.055)/1.055,2.4))+.0722*(Te[2]<=.03928?Te[2]/12.92:Math.pow((Te[2]+.055)/1.055,2.4)),F=g.properties.get("color").toNonPremultipliedRenderColor(null).toArray01(),q=g.properties.get("intensity"),G=g.properties.get("direction"),Q=1-o.cP(G.x,G.y,G.z)[2]/90,ae=P(F)*q*Q,me=N.properties.get("color").toNonPremultipliedRenderColor(null).toArray01(),ye=N.properties.get("intensity"),Ae=P(me)*ye;return Number(((ae+Ae)/2).toFixed(6))}getBrightness(){return this._brightness}getLights(){if(!this.enable3dLights())return null;const g=[];return this.directionalLight&&g.push(this.directionalLight.get()),this.ambientLight&&g.push(this.ambientLight.get()),g}enable3dLights(){return!!this.ambientLight&&!!this.directionalLight}getFragmentStyle(g){if(g==null||g===""&&this.isRootStyle())return this;if(o.db(g)){const N=o.dc(g),P=this.fragments.find(({id:q})=>q===N);if(!P)return;const F=o.da(g);return P.style.getFragmentStyle(F)}{const N=this.fragments.find(({id:P})=>P===g);return N?N.style:void 0}}setFeaturesetSelectors(g){if(!g)return;const N=(P,F="")=>`${P}::${F}`;this._featuresetSelectors={};for(const P in g){const F={},q=this._featuresetSelectors[P]=[];for(const G of g[P].selectors){if(G.featureNamespace){const ae=this.getOwnLayer(G.layer);if(!ae){o.w(`Layer is undefined for selector: ${G.layer}`);continue}const me=N(ae.source,ae.sourceLayer);if(me in F&&F[me]!==G.featureNamespace){o.w(`"featureNamespace ${G.featureNamespace} of featureset ${P}'s selector is not associated to the same source, skip this selector`);continue}F[me]=G.featureNamespace}let Q;if(G.properties)for(const ae in G.properties){const me=o.X(G.properties[ae]);me.result==="success"&&(Q=Q||{},Q[ae]=me.value)}q.push({layerId:G.layer,namespace:G.featureNamespace,properties:Q,uniqueFeatureID:G._uniqueFeatureID})}}}getFeaturesetDescriptors(g){const N=this.getFragmentStyle(g);if(!N||!N.stylesheet.featuresets)return[];const P=[];for(const F in N.stylesheet.featuresets)P.push({featuresetId:F,importId:N.scope?N.scope:void 0});return P}getFeaturesetLayers(g,N){const P=this.getFragmentStyle(N),F=P.stylesheet.featuresets;if(!F||!F[g])return this.fire(new o.B(new Error(`The featureset '${g}' does not exist in the map's style and cannot be queried.`))),[];const q=[];for(const G of F[g].selectors){const Q=P.getOwnLayer(G.layer);Q&&q.push(Q)}return q}getConfigProperty(g,N){const P=this.getFragmentStyle(g);if(!P)return null;const F=o.F(N,P.scope),q=P.options.get(F),G=q?q.value||q.default:null;return G?G.serialize():null}isIndoorEnabled(){return Object.keys(this._mergedIndoor).length>0}getIndoorSourceLayers(g,N){const P=o.F(g,N);return this._mergedIndoor[P]}setIndoorData(g,N){this.indoorManager.setIndoorData(N)}updateIndoorDependentLayers(){this._updateLayers(this._indoorDependentLayers),this.map._styleDirty=!0,this.map.triggerRepaint()}setConfigProperty(g,N,P){const F=this.getFragmentStyle(g);if(!F)return;const q=F.stylesheet.schema;if(!q||!q[N])return;const G=o.X(P);if(G.result!=="success")return void fv(this,G.value);const Q=G.value.expression,ae=o.F(N,F.scope),me=F.options.get(ae);if(!me)return;let ye;const{minValue:Ae,maxValue:Te,stepValue:Fe,type:Ye,values:Ge}=q[N],dt=o.X(q[N].default);dt.result==="success"&&(ye=dt.value.expression),ye?(this.options.set(ae,Object.assign({},me,{value:Q,default:ye,minValue:Ae,maxValue:Te,stepValue:Fe,type:Ye,values:Ge})),this.updateConfigDependencies(N)):this.fire(new o.B(new Error(`No schema defined for the config option "${N}" in the "${g}" fragment.`)))}getConfig(g){const N=this.getFragmentStyle(g);if(!N)return null;const P=N.stylesheet.schema;if(!P)return null;const F={};for(const q in P){const G=o.F(q,N.scope),Q=N.options.get(G),ae=Q?Q.value||Q.default:null;F[q]=ae?ae.serialize():null}return F}setConfig(g,N){const P=this.getFragmentStyle(g);P&&(P.updateConfig(N,P.stylesheet.schema),this.updateConfigDependencies())}getSchema(g){const N=this.getFragmentStyle(g);return N?N.stylesheet.schema:null}setSchema(g,N){const P=this.getFragmentStyle(g);P&&(P.stylesheet.schema=N,P.updateConfig(P._config,N),this.updateConfigDependencies())}updateConfig(g,N){if(this._config=g,g||N)if(N)for(const P in N){let F,q;const G=o.X(N[P].default);if(G.result==="success"&&(F=G.value.expression),g&&g[P]!==void 0){const Te=o.X(g[P]);Te.result==="success"&&(q=Te.value.expression)}const{minValue:Q,maxValue:ae,stepValue:me,type:ye,values:Ae}=N[P];if(F){const Te=o.F(P,this.scope);this.options.set(Te,{default:F,value:q,minValue:Q,maxValue:ae,stepValue:me,type:ye,values:Ae})}else this.fire(new o.B(new Error(`No schema defined for config option "${P}".`)))}else this.fire(new o.B(new Error("Attempting to set config for a style without schema.")))}_updateLayers(g,N=()=>!0){for(const P of g){const F=this.getLayer(P);F&&N(F)&&(F.possiblyEvaluateVisibility(),this._updateLayer(F),this._changes.setDirty())}}updateConfigDependencies(g){this._updateLayers(this._configDependentLayers,N=>!g||N.expressionDependencies.configDependencies.has(g)),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(N=>{const P=N._styleColorTheme.colorThemeOverride?N._styleColorTheme.colorThemeOverride:N._styleColorTheme.colorTheme;if(P){const F=N._evaluateColorThemeData(P);(!N._styleColorTheme.lut&&F!==""||N._styleColorTheme.lut&&F!==N._styleColorTheme.lut.data)&&N.setColorTheme(P)}}),this._changes.setDirty()}addLayer(g,N,P={}){this._checkLoaded();const F=g.id;if(this._layers[F])return void this.fire(new o.B(new Error(`Layer with id "${F}" already exists on this map`)));let q;if(g.type==="custom"){if(fv(this,o.dd(g)))return;q=o.de(g,this.scope,this._styleColorTheme.lut,this.options)}else{if(typeof g.source=="object"&&(this.addSource(F,g.source),g=o.d9(g),g=Object.assign(g,{source:F})),this._validate(qt,`layers.${F}`,g,{arrayIndex:-1},P))return;q=o.de(g,this.scope,this._styleColorTheme.lut,this.options),this._validateLayer(q),q.setEventedParent(this,{layer:{id:F}})}const G=o.F(q.source,q.scope);q.expressionDependencies.configDependencies.size!==0&&this._configDependentLayers.add(G),q.expressionDependencies.isIndoorDependent&&this._indoorDependentLayers.add(G);let Q=this._order.length;if(N){const Ae=this._order.indexOf(N);if(Ae===-1)return void this.fire(new o.B(new Error(`Layer with id "${N}" does not exist on this map.`)));q.slot&&q.slot!==this._layers[N].slot?o.w(`Layer with id "${N}" has a different slot. Layers can only be rearranged within the same slot.`):Q=Ae}this._order.splice(Q,0,F),this._handleLayerOrderChange(),this._layers[F]=q;const ae=this.getOwnLayerSourceCache(q),me=!!this.directionalLight&&this.directionalLight.shadowsEnabled();ae&&q.canCastShadows()&&me&&(ae.castsShadows=!0);const ye=this._changes.getRemovedLayer(q);if(ye&&q.source&&ae&&q.type!=="custom"){this._changes.discardLayerRemoval(q);const Ae=o.F(q.source,q.scope);ye.type!==q.type?this._changes.updateSourceCache(Ae,"clear"):(this._changes.updateSourceCache(Ae,"reload"),ae.pause())}this._updateLayer(q),q.onAdd&&q.onAdd(this.map),q.scope=this.scope,this.mergeLayers()}moveLayer(g,N){this._checkLoaded();const P=this._checkLayer(g);if(!P||g===N)return;const F=this._order.indexOf(g);this._order.splice(F,1);let q=this._order.length;if(N){const G=this._order.indexOf(N);if(G===-1)return void this.fire(new o.B(new Error(`Layer with id "${N}" does not exist on this map.`)));P.slot&&P.slot!==this._layers[N].slot?o.w(`Layer with id "${N}" has a different slot. Layers can only be rearranged within the same slot.`):q=G}this._order.splice(q,0,g),this._changes.setDirty(),this._handleLayerOrderChange(),this.mergeLayers()}removeLayer(g){this._checkLoaded();const N=this._checkLayer(g);if(!N)return;N.setEventedParent(null);const P=this._order.indexOf(g);this._order.splice(P,1),delete this._layers[g],this._changes.setDirty(),this._handleLayerOrderChange(),this._configDependentLayers.delete(N.fqid),this._indoorDependentLayers.delete(N.fqid),this._changes.removeLayer(N);const F=this.getOwnLayerSourceCache(N);if(F&&F.castsShadows){let q=!1;for(const G in this._layers)if(this._layers[G].source===N.source&&this._layers[G].canCastShadows()){q=!0;break}F.castsShadows=q}N.onRemove&&N.onRemove(this.map),this.mergeLayers()}getOwnLayer(g){return this._layers[g]}hasLayer(g){return g in this._mergedLayers}hasLayerType(g){for(const N in this._layers)if(this._layers[N].type===g)return!0;return!1}setLayerZoomRange(g,N,P){this._checkLoaded();const F=this._checkLayer(g);F&&(F.minzoom===N&&F.maxzoom===P||(N!=null&&(F.minzoom=N),P!=null&&(F.maxzoom=P),this._updateLayer(F)))}getSlots(){return this._checkLoaded(),this._mergedSlots}setSlot(g,N){this._checkLoaded();const P=this._checkLayer(g);P&&P.slot!==N&&(P.slot=N,this._updateLayer(P))}setFilter(g,N,P={}){this._checkLoaded();const F=this._checkLayer(g);if(F&&!o.b6(F.filter,N))return N==null?(F.filter=void 0,void this._updateLayer(F)):void(this._validate(ss,`layers.${F.id}.filter`,N,{layerType:F.type},P)||(F.filter=o.d9(N),this._updateLayer(F)))}getFilter(g){const N=this._checkLayer(g);if(N)return o.d9(N.filter)}setLayoutProperty(g,N,P,F={}){this._checkLoaded();const q=this._checkLayer(g);if(q&&!o.b6(q.getLayoutProperty(N),P)){if(P!=null&&(!F||F.validate!==!1)&&fv(q,ls.call(Jt,{key:`layers.${g}.layout.${N}`,layerType:q.type,objectKey:N,value:P,styleSpec:o.a8,style:{glyphs:!0,sprite:!0}})))return;q.setLayoutProperty(N,P),q.expressionDependencies.configDependencies.size!==0&&this._configDependentLayers.add(q.fqid),q.expressionDependencies.isIndoorDependent&&this._indoorDependentLayers.add(q.fqid),this._updateLayer(q)}}setLayerProperty(g,N,P,F={}){this._checkLoaded();const q=this._checkLayer(g);q&&(N==="appearances"?(q.setAppearances(P),this._updateLayer(q)):q.isPaintProperty(N)?this.setPaintProperty(g,N,P,F):this.setLayoutProperty(g,N,P,F))}getLayoutProperty(g,N){const P=this._checkLayer(g);if(P)return P.getLayoutProperty(N)}setPaintProperty(g,N,P,F={}){this._checkLoaded();const q=this._checkLayer(g);if(!q||o.b6(q.getPaintProperty(N),P)||P!=null&&(!F||F.validate!==!1)&&fv(q,Yt.call(Jt,{key:`layers.${g}.paint.${N}`,layerType:q.type,objectKey:N,value:P,styleSpec:o.a8})))return;const G=q.setPaintProperty(N,P);q.expressionDependencies.configDependencies.size!==0&&this._configDependentLayers.add(q.fqid),q.expressionDependencies.isIndoorDependent&&this._indoorDependentLayers.add(q.fqid),G&&this._updateLayer(q),this._changes.updatePaintProperties(q)}getPaintProperty(g,N){const P=this._checkLayer(g);if(P)return P.getPaintProperty(N)}setFeatureState(g,N){if(this._checkLoaded(),"target"in g){if("featuresetId"in g.target){const{featuresetId:ae,importId:me}=g.target,ye=this.getFragmentStyle(me),Ae=ye.getFeaturesetLayers(ae);for(const{source:Te,sourceLayer:Fe}of Ae)ye.setFeatureState({id:g.id,source:Te,sourceLayer:Fe},N)}else if("layerId"in g.target){const{layerId:ae}=g.target,me=this.getLayer(ae);this.setFeatureState({id:g.id,source:me.source,sourceLayer:me.sourceLayer},N)}return}const P=g.source,F=g.sourceLayer,q=this._checkSource(P);if(!q)return;const G=q.type;if(G==="geojson"&&F)return void this.fire(new o.B(new Error("GeoJSON sources cannot have a sourceLayer parameter.")));if(G==="vector"&&!F)return void this.fire(new o.B(new Error("The sourceLayer parameter must be provided for vector source types.")));g.id===void 0&&this.fire(new o.B(new Error("The feature id parameter must be provided.")));const Q=this.getOwnSourceCaches(P);for(const ae of Q)ae.setFeatureState(F,g.id,N)}removeFeatureState(g,N){if(this._checkLoaded(),"target"in g){if("featuresetId"in g.target){const{featuresetId:ae,importId:me}=g.target,ye=this.getFragmentStyle(me),Ae=ye.getFeaturesetLayers(ae);for(const{source:Te,sourceLayer:Fe}of Ae)ye.removeFeatureState({id:g.id,source:Te,sourceLayer:Fe},N)}else if("layerId"in g.target){const{layerId:ae}=g.target,me=this.getLayer(ae);this.removeFeatureState({id:g.id,source:me.source,sourceLayer:me.sourceLayer},N)}return}const P=g.source,F=this._checkSource(P);if(!F)return;const q=F.type,G=q==="vector"?g.sourceLayer:void 0;if(q==="vector"&&!G)return void this.fire(new o.B(new Error("The sourceLayer parameter must be provided for vector source types.")));if(N&&typeof g.id!="string"&&typeof g.id!="number")return void this.fire(new o.B(new Error("A feature id is required to remove its specific state property.")));const Q=this.getOwnSourceCaches(P);for(const ae of Q)ae.removeFeatureState(G,g.id,N)}getFeatureState(g){if(this._checkLoaded(),"target"in g){let q;if("featuresetId"in g.target){const{featuresetId:G,importId:Q}=g.target,ae=this.getFragmentStyle(Q),me=ae.getFeaturesetLayers(G);for(const{source:ye,sourceLayer:Ae}of me){const Te=ae.getFeatureState({id:g.id,source:ye,sourceLayer:Ae});if(Te&&!q)q=Te;else if(!o.b6(q,Te))return void this.fire(new o.B(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 g.target){const{layerId:G}=g.target,Q=this.getLayer(G);q=this.getFeatureState({id:g.id,source:Q.source,sourceLayer:Q.sourceLayer})}return q}const N=g.source,P=g.sourceLayer,F=this._checkSource(N);if(F){if(F.type!=="vector"||P)return g.id===void 0&&this.fire(new o.B(new Error("The feature id parameter must be provided."))),this.getOwnSourceCaches(N)[0].getFeatureState(P,g.id);this.fire(new o.B(new Error("The sourceLayer parameter must be provided for vector source types.")))}}setTransition(g){return this.stylesheet.transition=Object.assign({},this.stylesheet.transition,g),this.transition=this.stylesheet.transition,this}getTransition(){return Object.assign({},this.stylesheet.transition)}setWorldview(g){g!==this._worldview&&(this._worldview=g,this.dispatcher.broadcast("setWorldview",this._worldview),this.reloadSources())}serialize(){this._checkLoaded();const g=this.getTerrain(),N=g&&this.terrain&&this.terrain.scope===this.scope?g:this.stylesheet.terrain;return o.df({version:this.stylesheet.version,name:this.stylesheet.name,metadata:this.stylesheet.metadata,fragment:this.stylesheet.fragment,iconsets:this.stylesheet.iconsets,featuresets:this.stylesheet.featuresets,imports:this._serializeImports(),schema:this.stylesheet.schema,camera:this.stylesheet.camera,light:this.stylesheet.light,lights:this.stylesheet.lights,terrain:N,fog:this.stylesheet.fog,snow:this.stylesheet.snow,rain:this.stylesheet.rain,indoor:this.stylesheet.indoor,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)},P=>P!==void 0)}_updateFilteredLayers(g){for(const N of Object.values(this._mergedLayers))g(N)&&this._updateLayer(N)}_updateLayer(g){this._changes.updateLayer(g);const N=this.getLayerSourceCache(g),P=o.F(g.source,g.scope),F=this._changes.getUpdatedSourceCaches();g.source&&!F[P]&&N&&N.getSource().type!=="raster"&&(this._changes.updateSourceCache(P,"reload"),N.pause()),g.invalidateCompiledFilter()}_flattenAndSortRenderedFeatures(g){const N=Q=>this._mergedLayers[Q].is3D(!!this.terrain),P=this.order,F={},q=[];for(let Q=P.length-1;Q>=0;Q--){const ae=P[Q];if(N(ae)){F[ae]=Q;for(const me of g){const ye=me[ae];if(ye)for(const Ae of ye)q.push(Ae)}}}q.sort((Q,ae)=>ae.intersectionZ-Q.intersectionZ);const G=[];for(let Q=P.length-1;Q>=0;Q--){const ae=P[Q];if(N(ae))for(let me=q.length-1;me>=0;me--){const ye=q[me].feature;if(ye.layer&&F[ye.layer.id]{if(cw.has(ye.type))return;const Ae=this.getOwnLayerSourceCache(ye),Te=q[Ae.id]=q[Ae.id]||{sourceCache:Ae,layers:{},has3DLayers:!1};ye.is3D(!!this.terrain)&&(Te.has3DLayers=!0),Te.layers[ye.fqid]=Te.layers[ye.fqid]||{styleLayer:ye,targets:[]},Te.layers[ye.fqid].targets.push({filter:F})};if(N&&N.layers){if(!Array.isArray(N.layers))return this.fire(new o.B(new Error("parameters.layers must be an Array."))),[];for(const ye of N.layers){const Ae=this._layers[ye];if(!Ae)return this.fire(new o.B(new Error(`The layer '${ye}' does not exist in the map's style and cannot be queried for features.`))),[];G(Ae)}}else for(const ye in this._layers)G(this._layers[ye]);const Q=this._queryRenderedFeatures(g,q,P),ae=this._flattenAndSortRenderedFeatures(Q),me=[];for(const ye of ae)o.dh(ye.layer.id)===this.scope&&me.push(ye);return me}queryRenderedFeatureset(g,N,P){let F;N&&!Array.isArray(N)&&N.filter&&(this._validate(ss,"queryRenderedFeatures.filter",N.filter,null,N),F=o.dg(N.filter));const q="mock",G=[];if(N&&N.target)G.push(Object.assign({},N,{targetId:q,filter:F}));else{const ye=this.getFeaturesetDescriptors();for(const Ae of ye)G.push({targetId:q,filter:F,target:Ae});for(const{style:Ae}of this.fragments){const Te=Ae.getFeaturesetDescriptors();for(const Fe of Te)G.push({targetId:q,filter:F,target:Fe})}}const Q=this.queryRenderedTargets(g,G,P),ae=[],me=new Set;for(const ye of Q)for(const Ae of ye.variants[q])Ju(Ae,ye,me)||ae.push(new o.di(ye,Ae));return ae}queryRenderedTargets(g,N,P){const F={},q=(Q,ae,me,ye)=>{const Ae=F[ae.id]=F[ae.id]||{sourceCache:ae,layers:{},has3DLayers:!1};if(Ae.layers[Q.fqid]=Ae.layers[Q.fqid]||{styleLayer:Q,targets:[]},Q.is3D(!!this.terrain)&&(Ae.has3DLayers=!0),!ye)return me.uniqueFeatureID=!1,void Ae.layers[Q.fqid].targets.push(me);Ae.layers[Q.fqid].targets.push(Object.assign({},me,{namespace:ye.namespace,properties:ye.properties,uniqueFeatureID:ye.uniqueFeatureID}))};for(const Q of N)if("featuresetId"in Q.target){const{featuresetId:ae,importId:me}=Q.target,ye=this.getFragmentStyle(me);if(!ye||!ye._featuresetSelectors)continue;const Ae=ye._featuresetSelectors[ae];if(!Ae){this.fire(new o.B(new Error(`The featureset '${ae}' does not exist in the map's style and cannot be queried for features.`)));continue}for(const Te of Ae){const Fe=ye.getOwnLayer(Te.layerId);Fe&&!cw.has(Fe.type)&&q(Fe,ye.getOwnLayerSourceCache(Fe),Q,Te)}}else if("layerId"in Q.target){const{layerId:ae}=Q.target,me=this.getLayer(ae);if(!me||cw.has(me.type))continue;q(me,this.getLayerSourceCache(me),Q)}const G=this._queryRenderedFeatures(g,F,P);return this._flattenAndSortRenderedFeatures(G)}_queryRenderedFeatures(g,N,P){const F=[],q=!!this.map._showQueryGeometry,G=cl.createFromScreenPoints(g,P);for(const Q in N){const ae=Pp(G,N[Q],this._availableImages,P,q,this.getActualScope());Object.keys(ae).length&&F.push(ae)}if(this.placement)for(const Q in N){if(N[Q].sourceCache._renderSourceType!==o.b4.Symbol)continue;const ae=oo(G.screenGeometry,N[Q],this._availableImages,this.placement.collisionIndex,this.placement.retainedQueryData,this.map.getWorldview());Object.keys(ae).length&&F.push(ae)}return F}querySourceFeatures(g,N){const P=N&&N.filter;P&&this._validate(ss,"querySourceFeatures.filter",P,null,N);let F=[];const q=this.getOwnSourceCaches(g);for(const G of q)F=F.concat(q1(G,N));return F}addSourceType(g,N,P){return Mc.getSourceType(g)?P(new Error(`A source type called "${g}" already exists.`)):(Mc.setSourceType(g,N),N.workerSourceURL?void this.dispatcher.broadcast("loadWorkerSource",{name:g,url:N.workerSourceURL},P):P(null,null))}getFlatLight(){return this.light.getLight()}setFlatLight(g,N,P={}){this._checkLoaded();const F=this.light.getLight();let q=!1;for(const Q in g)if(!o.b6(g[Q],F[Q])){q=!0;break}if(!q)return;const G=this._getTransitionParameters();this.light.setLight(g,N,P),this.light.updateTransitions(G)}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=o.o.hasCanvasFingerprintNoise(),this.disableElevatedTerrain&&o.w("Terrain and hillshade are disabled because of Canvas2D limitations when fingerprinting protection is enabled (e.g. in private browsing mode)."))}setTerrain(g,N=1){if(this._checkLoaded(),!g)return this.terrainSetForDrapingOnly()||(delete this.terrain,this.map.transform.projection.requiresDraping&&this.setTerrainForDraping()),N===0&&delete this.terrain,g===null?this.stylesheet.terrain=null:delete this.stylesheet.terrain,this._force3DLayerUpdate(),void(this._markersNeedUpdate=!0);this.checkCanvasFingerprintNoise();let P=g;const F=!("source"in g)||g.source==null;if(N===1){if(this.disableElevatedTerrain)return;if("source"in P&&typeof P.source=="object"){const Q="terrain-dem-src";this.addSource(Q,P.source),P=o.d9(P),P=Object.assign(P,{source:Q})}const q=Object.assign({},P),G={};if(this.terrain&&F){q.source=this.terrain.get().source;const Q=this.terrain?this.getFragmentStyle(this.terrain.scope):null;Q&&(G.style=Q.serialize())}if(this._validate(He,"terrain",q,G))return}if(!this.terrain||this.terrain.scope!==this.scope&&!F||this.terrain&&N!==this.terrain.drapeRenderMode){if(!P)return;this._createTerrain(P,N),this.fire(new o.C("data",{dataType:"style"}))}else{const q=this.terrain,G=q.get();for(const Q of Object.keys(o.a8.terrain))!P.hasOwnProperty(Q)&&o.a8.terrain[Q].default&&(P[Q]=o.a8.terrain[Q].default);for(const Q in g)if(!o.b6(g[Q],G[Q])){q.set(g,this.options),this.stylesheet.terrain=g;const ae=this._getTransitionParameters({duration:0});q.updateTransitions(ae),this.fire(new o.C("data",{dataType:"style"}));break}}this.mergeTerrain(),this.updateDrapeFirstLayers(),this._markersNeedUpdate=!0}_createFog(g){const N=this.fog=new Wi(g,this.map.transform,this.scope,this.options);this.stylesheet.fog=N.get();const P=this._getTransitionParameters({duration:0});N.updateTransitions(P)}_createSnow(g){const N=this.snow=new co(g,this.map.transform,this.scope,this.options);this.stylesheet.snow=N.get();const P=this._getTransitionParameters({duration:0});N.updateTransitions(P)}_createRain(g){const N=this.rain=new ia(g,this.map.transform,this.scope,this.options);this.stylesheet.rain=N.get();const P=this._getTransitionParameters({duration:0});N.updateTransitions(P)}_updateMarkersOpacity(){this.map._markers.length!==0&&this.map._requestDomTask(()=>{for(const g of this.map._markers)g._evaluateOpacity()})}getFog(){return this.fog?this.fog.get():null}setFog(g){if(this._checkLoaded(),!g)return delete this.fog,delete this.stylesheet.fog,void(this._markersNeedUpdate=!0);if(this.fog){const N=this.fog;if(!o.b6(N.get(),g)){N.set(g,this.options),this.stylesheet.fog=N.get();const P=this._getTransitionParameters({duration:0});N.updateTransitions(P)}}else this._createFog(g);this._markersNeedUpdate=!0}getSnow(){return this.snow?this.snow.get():null}setSnow(g){if(this._checkLoaded(),!g)return delete this.snow,void delete this.stylesheet.snow;if(this.snow){const N=this.snow;if(!o.b6(N.get(),g)){N.set(g,this.options),this.stylesheet.snow=N.get();const P=this._getTransitionParameters({duration:0});N.updateTransitions(P)}}else this._createSnow(g);this._markersNeedUpdate=!0}getRain(){return this.rain?this.rain.get():null}setRain(g){if(this._checkLoaded(),!g)return delete this.rain,void delete this.stylesheet.rain;if(this.rain){const N=this.rain;if(!o.b6(N.get(),g)){N.set(g,this.options),this.stylesheet.rain=N.get();const P=this._getTransitionParameters({duration:0});N.updateTransitions(P)}}else this._createRain(g);this._markersNeedUpdate=!0}_reloadColorTheme(){const g=()=>{for(const F in this._layers)this._layers[F].lut=this._styleColorTheme.lut;for(const F in this._sourceCaches)this._sourceCaches[F].clearTiles()},N=this._styleColorTheme.colorThemeOverride?this._styleColorTheme.colorThemeOverride:this._styleColorTheme.colorTheme;if(!N)return this._styleColorTheme.lut=null,void g();const P=this._evaluateColorThemeData(N);this._loadColorTheme(P).then(()=>{this.fire(new o.C("colorthemeset")),g()}).catch(F=>{o.w(`Couldn't set color theme: ${F}`)})}setColorTheme(g){this._checkLoaded(),this._styleColorTheme.colorThemeOverride&&o.w("Note: setColorTheme is called on a style with a color-theme override, the passed color-theme won't be visible."),this._styleColorTheme.colorTheme=g,this._reloadColorTheme()}setImportColorTheme(g,N){const P=this.getFragmentStyle(g);P&&(P._styleColorTheme.colorThemeOverride=N,P._reloadColorTheme())}_getTransitionParameters(g){return{now:o.o.now(),transition:Object.assign(this.transition,g)}}updateDrapeFirstLayers(){if(!this.terrain)return;const g=[],N=[];for(const P of this._mergedOrder)this.isLayerDraped(this._mergedLayers[P])?g.push(P):N.push(P);this._drapedFirstOrder=[],this._drapedFirstOrder.push(...g),this._drapedFirstOrder.push(...N)}_createTerrain(g,N){const P=this.terrain=new pn(g,N,this.scope,this.options,this.map.getWorldview());N===1&&(this.stylesheet.terrain=g),this.mergeTerrain(),this.updateDrapeFirstLayers(),this._force3DLayerUpdate();const F=this._getTransitionParameters({duration:0});P.updateTransitions(F)}_force3DLayerUpdate(){for(const g in this._layers){const N=this._layers[g];N.type==="fill-extrusion"&&this._updateLayer(N)}}_forceSymbolLayerUpdate(){for(const g in this._layers){const N=this._layers[g];N.type==="symbol"&&this._updateLayer(N)}}_validate(g,N,P,F,q={}){if(q&&q.validate===!1)return!1;const G=Object.assign({},this.serialize());return fv(this,g.call(Jt,Object.assign({key:N,style:G,value:P,styleSpec:o.a8},F)))}_remove(){this._request&&(this._request.cancel(),this._request=null),this._spriteRequest&&(this._spriteRequest.cancel(),this._spriteRequest=null),o.dj.off("pluginStateChange",this._rtlTextPluginCallback);for(const g in this._mergedLayers)this._mergedLayers[g].setEventedParent(null);for(const g in this._mergedSourceCaches)this._mergedSourceCaches[g].clearTiles(),this._mergedSourceCaches[g].setEventedParent(null);this.imageManager.removeScope(this.scope),this.imageManager.imageAtlasCache.clear(),this.setEventedParent(null),delete this.fog,delete this.snow,delete this.rain,delete this.terrain,delete this.ambientLight,delete this.directionalLight,this.indoorManager.destroy(),this.isRootStyle()&&(this.imageManager.setEventedParent(null),this.imageManager.destroy(),this.modelManager.setEventedParent(null),this.modelManager.destroy(),this.dispatcher.remove())}clearSource(g){const N=this.getSourceCaches(g);for(const P of N)P.clearTiles()}clearSources(){for(const g in this._mergedSourceCaches)this._mergedSourceCaches[g].clearTiles()}clearLayers(){for(const g in this._mergedLayers){const N=this._mergedLayers[g];N._clear&&N._clear()}}reloadSource(g){const N=this.getSourceCaches(g);for(const P of N)P.resume(),P.reload()}reloadSources(){for(const g of this.getSources())g.reload&&g.reload()}reloadModels(){this.modelManager.reloadModels(""),this.forEachFragmentStyle(g=>{g.modelManager.reloadModels(g.scope)})}updateSources(g){let N;this.directionalLight&&(N=Ej(this.directionalLight));const P=new Set,F=new Set,q=new Set;for(const G in this._mergedLayers){const Q=this._mergedLayers[G];Q.type==="building"?P.add(Q.source):Q.type==="raster"&&Q.paint&&Q.paint.get("raster-elevation-reference")==="ground"&&q.add(Q.source),Q.hasElevation()&&!F.has(Q.source)&&F.add(Q.source)}for(const G in this._mergedSourceCaches){const Q=this._mergedSourceCaches[G],ae=F.has(Q._source.id);Q._isRasterElevatedOverTerrain=q.has(Q._source.id),P.has(Q._source.id)&&(Q._source.reparseOverscaled=!1),Q.update(g,void 0,void 0,N,ae)}}_generateCollisionBoxes(){for(const g in this._sourceCaches){const N=this._sourceCaches[g];N.resume(),N.reload()}}_handleLayerOrderChange(){this._requestFullLabelPlacement(),this.fire(new o.C("neworder"))}_requestFullLabelPlacement(){this.pauseablePlacement||(this.pauseablePlacement=new K1),this.pauseablePlacement.requestFullPlacement()}_setLabelPlacementStale(){this.placement&&this.placement.setStale()}_updatePlacement(g,N,P,F,q){this.pauseablePlacement||(this.pauseablePlacement=new K1);let G=!1,Q=!1;const ae={},me={};for(const Ge of this._mergedOrder){const dt=this._mergedLayers[Ge];if(dt.type!=="symbol")continue;const lt=o.F(dt.source,dt.scope);let _t=ae[lt];if(!_t){const ht=this.getLayerSourceCache(dt);if(!ht)continue;const Kt=ht.getRenderableIds(!0).map(Lt=>ht.getTileByID(Lt));me[lt]=Kt.slice(),_t=ae[lt]=Kt.sort((Lt,Wt)=>Wt.tileID.overscaledZ-Lt.tileID.overscaledZ||(Lt.tileID.isLessThan(Wt.tileID)?-1:1))}const Ct=this.crossTileSymbolIndex.addLayer(dt,_t,g.center.lng,g.projection);G=G||Ct}this.crossTileSymbolIndex.pruneUnusedLayers(this._mergedOrder);const ye=!!(this.placement&&!g.equals(this.placement.transform)),Ae=!!(this.placement&&(this.placement.lastReplacementSourceUpdateTime!==0&&!q||this.placement.lastReplacementSourceUpdateTime!==q.updateTime)),Te=ye||Ae||G,Fe=(Te||this.pauseablePlacement.isStale())&&P===0,Ye=this.pauseablePlacement.isDone()&&!this.placement.stillRecent(o.o.now(),g.zoom)&&P!==0;if((this.pauseablePlacement.isFullPlacementRequested()||!this.pauseablePlacement.placement||Fe||Ye)&&(this.pauseablePlacement=this.pauseablePlacement.startNewPlacement(g,this._mergedOrder,N,P,F,this.placement,this.fog&&g.projection.supportsFog?this.fog.state:null,this._buildingIndex),this.map.painter)){const Ge=this.map.painter.maxFrontCutoffRawStart;if(Ge>0){const dt=180*g.pitch/Math.PI;if(dt>=15){const lt=Math.min(1,Math.max(0,(dt-15)/5)),_t=lt*lt*(3-2*lt);this.pauseablePlacement.placement.frontCutoffStart=-.5*(1-_t)+Ge*_t}}}if(this.pauseablePlacement.isDone()?Te&&P!==0&&this.pauseablePlacement.setStale():(this.pauseablePlacement.continuePlacement(this._mergedOrder,this._mergedLayers,ae,me,this.map.painter.scaleFactor),this.pauseablePlacement.isDone()&&(this.placement=this.pauseablePlacement.commit(o.o.now()),Q=!0),G&&this.pauseablePlacement.setStale()),Q||G){this._buildingIndex.onNewFrame(g.zoom);for(let Ge=0;Geq===g.id)!==-1)return void this.fire(new o.B(new Error(`Import with id '${g.id}' already exists in the map's style.`)));if(!N)return P.push(g),this._loadImports([g],!0);const F=P.findIndex(({id:q})=>q===N);return F===-1&&this.fire(new o.B(new Error(`Import with id "${N}" does not exist on this map.`))),this.stylesheet.imports=P.slice(0,F).concat(g).concat(P.slice(F)),this._loadImports([g],!0,N)}updateImport(g,N){this._checkLoaded();const P=this.stylesheet.imports||[],F=this.getImportIndex(g);return F===-1?this:typeof N=="string"?(this.setImportUrl(g,N),this):(N.url&&N.url!==P[F].url&&this.setImportUrl(g,N.url),o.b6(N.config,P[F].config)||this.setImportConfig(g,N.config,N.data.schema),o.b6(N.data,P[F].data)||this.setImportData(g,N.data),this)}moveImport(g,N){this._checkLoaded();let P=this.stylesheet.imports||[];const F=this.getImportIndex(g);if(F===-1)return this;const q=this.getImportIndex(N);if(q===-1)return this;const G=P[F],Q=this.fragments[F];return P=P.filter(({id:ae})=>ae!==g),this.fragments=this.fragments.filter(({id:ae})=>ae!==g),this.stylesheet.imports=P.slice(0,q).concat(G).concat(P.slice(q)),this.fragments=this.fragments.slice(0,q).concat(Q).concat(this.fragments.slice(q)),this.mergeLayers(),this}setImportUrl(g,N){this._checkLoaded();const P=this.stylesheet.imports||[],F=this.getImportIndex(g);if(F===-1)return this;P[F].url=N;const q=this.fragments[F];return q.style=this._createFragmentStyle(P[F]),q.style.on("style.import.load",()=>this.mergeAll()),q.style.loadURL(N),this}setImportData(g,N){this._checkLoaded();const P=this.getImportIndex(g),F=this.stylesheet.imports||[];return P===-1?this:N?(this.fragments[P].style.setState(N),this._reloadImports(),this):(delete F[P].data,this.setImportUrl(g,F[P].url))}setImportConfig(g,N,P){this._checkLoaded();const F=this.getImportIndex(g),q=this.stylesheet.imports||[];if(F===-1)return this;N?q[F].config=N:delete q[F].config;const G=this.fragments[F];P&&G.style.stylesheet&&(G.style.stylesheet.schema=P);const Q=G.style.stylesheet&&G.style.stylesheet.schema;return G.config=N,G.style.updateConfig(N,Q),this.updateConfigDependencies(),this}removeImport(g){this._checkLoaded();const N=this.stylesheet.imports||[],P=this.getImportIndex(g);P!==-1&&(N.splice(P,1),this.fragments[P].style._remove(),this.fragments.splice(P,1),this._reloadImports())}getImportIndex(g){const N=(this.stylesheet.imports||[]).findIndex(P=>P.id===g);return N===-1&&this.fire(new o.B(new Error(`Import '${g}' does not exist in the map's style and cannot be updated.`))),N}getLayer(g){return this._mergedLayers[g]}getSources(){const g=[];for(const N in this._mergedOtherSourceCaches){const P=this._mergedOtherSourceCaches[N];P&&g.push(P.getSource())}return g}getSource(g,N){const P=this.getSourceCache(g,N);return P&&P.getSource()}getLayerSource(g){const N=this.getLayerSourceCache(g);return N&&N.getSource()}getSourceCache(g,N){const P=o.F(g,N);return this._mergedOtherSourceCaches[P]}getLayerSourceCache(g){const N=o.F(g.source,g.scope);return g.type==="symbol"?this._mergedSymbolSourceCaches[N]:g.type==="fill-extrusion"&&this._mergedFillExtrusionSourceCaches[N]||this._mergedOtherSourceCaches[N]}getSourceCaches(g){if(g==null)return Object.values(this._mergedSourceCaches);const N=[];return this._mergedOtherSourceCaches[g]&&N.push(this._mergedOtherSourceCaches[g]),this._mergedSymbolSourceCaches[g]&&N.push(this._mergedSymbolSourceCaches[g]),this._mergedFillExtrusionSourceCaches[g]&&N.push(this._mergedFillExtrusionSourceCaches[g]),N}updateSourceCaches(){const g=this._changes.getUpdatedSourceCaches();for(const N in g){const P=g[N];P==="reload"?this.reloadSource(N):P==="clear"&&this.clearSource(N)}}updateLayers(g){const N=this._changes.getUpdatedPaintProperties();for(const P of N){const F=this.getLayer(P);F&&F.updateTransitions(g)}}getGlyphsUrl(){return this.stylesheet.glyphs}setGlyphsUrl(g){this.stylesheet.glyphs=g,this.glyphManager.setURL(g)}getImages(g,N,P){this.imageManager.getImages(N.images,N.scope,P),this._updateTilesForChangedImages();const F=G=>{if(G){const Q=N.images.map(ae=>o.I.toString(ae));G.setDependencies(N.tileID.key,N.type,Q)}},q=o.F(N.source,N.scope);F(this._mergedOtherSourceCaches[q]),F(this._mergedSymbolSourceCaches[q]),N.images.some(G=>G.iconsetId)&&this.fire(new o.C("data",{dataType:"style"}))}rasterizeImages(g,N,P){this.imageManager.rasterizeImages(N,P)}checkAtlasCache(g,N,P){const F=this.imageManager.imageAtlasCache.findCachedAtlas(N.descriptor);P(null,F&&F.contentDescriptor?{iconPositions:F.iconPositions,patternPositions:F.patternPositions,sourceHash:F.contentDescriptor.hash}:null)}getGlyphs(g,N,P){this.glyphManager.getGlyphs(N.stacks,P)}getOwnSourceCache(g){return this._otherSourceCaches[g]}getOwnLayerSourceCache(g){return g.type==="symbol"?this._symbolSourceCaches[g.source]:g.type==="fill-extrusion"&&this._fillExtrusionSourceCaches[g.source]||this._otherSourceCaches[g.source]}getOwnSourceCaches(g){const N=[];return this._otherSourceCaches[g]&&N.push(this._otherSourceCaches[g]),this._symbolSourceCaches[g]&&N.push(this._symbolSourceCaches[g]),this._fillExtrusionSourceCaches[g]&&N.push(this._fillExtrusionSourceCaches[g]),N}_isSourceCacheLoaded(g){const N=this.getOwnSourceCaches(g);return N.length===0?(this.fire(new o.B(new Error(`There is no source with ID '${g}'`))),!1):N.every(P=>P.loaded())}has3DLayers(){return this._has3DLayers}hasSymbolLayers(){return this._hasSymbolLayers}hasCircleLayers(){return this._hasCircleLayers}isLayerClipped(g,N){if(!this._clipLayerPresent&&g.type!=="fill-extrusion"&&g.type!=="building")return!1;const P=g.type==="fill-extrusion"&&(g.sourceLayer==="building"||g.sourceLayer==="procedural_buildings"),F=g.type==="building";if(g.is3D(!!this.terrain)){if(P||F||N&&N.type==="batched-model"||g.type==="model")return!0}else if(g.type==="symbol")return!0;return!1}_clearWorkerCaches(){this.dispatcher.broadcast("clearCaches")}getBOMObject(){}destroy(){this._clearWorkerCaches(),this.imageManager.imageAtlasCache.clear(),this.fragments.forEach(g=>{g.style._remove()}),this.terrainSetForDrapingOnly()&&(delete this.terrain,delete this.stylesheet.terrain)}}Mc.getSourceType=function(M){return B0[M]},Mc.setSourceType=function(M,g){B0[M]=g},Mc.registerForPluginStateChange=o.dk;var pv=` #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`,dw=` #ifdef DUAL_SOURCE_BLENDING layout(location=0,index=0) out vec4 glFragColor;layout(location=0,index=1) out vec4 glFragColorSrc1; #elif defined(FLOAT_RENDER_TARGET) layout(location=0) out highp vec4 glFragColor; #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 const float DITHER_THRESHOLDS[16]=float[16]( 1.0/17.0, 9.0/17.0, 3.0/17.0,11.0/17.0,13.0/17.0, 5.0/17.0,15.0/17.0, 7.0/17.0,4.0/17.0,12.0/17.0, 2.0/17.0,10.0/17.0,16.0/17.0, 8.0/17.0,14.0/17.0, 6.0/17.0 );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 }float cutoutGroundRoofOpacity(vec4 groundRoof) { #ifdef INDICATOR_CUTOUT float fadeStartX=u_indicator_cutout_params.w;float holeRadius=u_indicator_cutout_params.y;float holeMinOpacity=mix(u_indicator_cutout_params.x,1.0,smoothstep(u_indicator_cutout_params.z,u_indicator_cutout_centers.z,groundRoof.y));float distX=abs(u_indicator_cutout_centers.x-groundRoof.x);float roofOpacity=mix(holeMinOpacity,1.0,smoothstep(fadeStartX,holeRadius,u_indicator_cutout_centers.y-groundRoof.w));float groundOpacity=min(smoothstep(fadeStartX,holeRadius,distX)+holeMinOpacity,1.0);return max(roofOpacity,groundOpacity); #else return 1.0; #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;}`,Mg=` #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);}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(ivec2 posWithComposedSkirt) {float skirt=float(float(posWithComposedSkirt.x) >=skirtOffset);vec2 pos=vec2(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`,Q1="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;}",Mj=` #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`,Ij=`#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`,gv=`#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`,xv=`#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`,Pj=`#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;}`,uw=`#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`,Dm=`#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 wx=/#include\s+"([^"]+)"/g,Sr=/#pragma mapbox: ([\w\-]+) ([\w]+) ([\w]+) ([\w]+)/g,hw=/\b[A-Za-z_][A-Za-z0-9_]*\b/g,mw=new Set(["ifdef","ifndef","elif","if","defined"]),K0=new Set;Ig(pv,K0),Ig(Mg,K0),Ig(dw,K0);const gf={"_prelude_fog.vertex.glsl":Ij,"_prelude_terrain.vertex.glsl":Mj,"_prelude_shadow.vertex.glsl":uw,"_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":gv,"_prelude_shadow.fragment.glsl":Dm,"_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":xv,"_prelude_raster_particle.glsl":Pj},yv={};mi("",Mj),mi(gv,Ij),mi(Dm,uw),mi(xv,""),mi(Pj,"");const jx=mi(dw,Mg),J1=pv,vv=[` #if defined(GL_EXT_blend_func_extended) && defined(DUAL_SOURCE_BLENDING) #extension GL_EXT_blend_func_extended : require #endif`,"precision mediump float;",J1,jx.fragmentSource].join(` `),o4=["precision highp float;",J1,jx.vertexSource].join(` `);var l4={background:mi(`#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 FEATURE_CUTOUT vec2 uv=gl_FragCoord.xy*u_inv_viewport_size.xy; #ifdef FLIP_Y uv.y=1.0-uv.y; #endif float factorTex=min(texture(u_cutout_factor_image,uv).r,1.0);float cutoutFactor=(1.0-u_feature_cutout_params.x)*factorTex;out_color=u_color*(1.0-cutoutFactor); #else #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 #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 ivec2 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); #ifndef FEATURE_CUTOUT #ifdef LIGHTING_3D_MODE v_color=apply_lighting_with_emission_ground(u_color,u_emissive_strength); #endif #ifdef FOG v_fog_pos=fog_position(vec2(a_pos)); #endif #endif }`),backgroundPattern:mi(`#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 ivec2 a_pos;out highp vec2 v_pos;void main() {vec2 pos=vec2(a_pos);gl_Position=u_matrix*vec4(pos,0,1);v_pos=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,u_pattern_size,u_pattern_units_to_pixels,pos); #ifdef FOG v_fog_pos=fog_position(pos); #endif }`),building:mi(`#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 RENDER_FRONT_CUTOFF in float v_front_cutoff_opacity; #endif #ifdef INDICATOR_CUTOUT #ifdef FEATURE_CUTOUT in vec4 v_ground_roof; #endif #endif #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 highp float hash12(in highp vec2 p) {highp 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);}highp vec2 get_uv_mask_id(in highp vec2 q,out highp float mask,out highp vec2 id) {highp 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;highp vec2 uv=modf(p/v_faux_facade_floor,id);highp vec4 d=(v_faux_facade_floor.xyxy+vec4(-v_faux_facade_window,v_faux_facade_window))*0.5;highp vec4 edge=d/v_faux_facade_floor.xyxy;highp 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;}highp float ray_unit_box(in highp vec3 ray_o,in highp vec3 ray_d,in highp vec3 bmin,in highp vec3 bmax) {highp vec3 planes=mix(bmin,bmax,step(0.0,ray_d));highp 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 highp vec3 v,in highp vec3 v_normalized,in vec3 color,in vec2 id,in mat3 tbn,inout vec3 out_normal,inout float out_emissive) {vec3 out_color=color;highp 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) {highp mat3 tbn=mat3(v_tbn_0,v_tbn_1,v_tbn_2);highp vec3 v=vec3(v_pos.xy,v_pos.z/u_tile_to_meter)-u_camera_pos;highp vec3 view_tangent=transpose(tbn)*v;highp vec2 q=vec2(v_faux_facade_ed,v_pos.z);float mask=0.0;vec2 id=vec2(0.0);highp vec2 uv=get_uv_mask_id(q,mask,id);uv*=v_faux_facade_window;highp vec3 bmin=vec3(0.0,0.0,-window_depth);highp vec3 bmax=bmin+vec3(v_faux_facade_window,window_depth);highp vec3 ray_o=vec3(uv,0.0);highp vec3 ray_d=normalize(view_tangent);highp float t_min=ray_unit_box(ray_o,ray_d,bmin,bmax);highp vec3 hit=ray_o+t_min*ray_d;highp vec3 r=vec3(v_faux_facade_window,-window_depth);hit-=r*0.5;highp 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=max(0.0,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 #ifdef FEATURE_CUTOUT {float ditherOpacity=cutoutGroundRoofOpacity(v_ground_roof);if (ditherOpacity < 1.0) {int index=(int(gl_FragCoord.x) % 4)*4+(int(gl_FragCoord.y) % 4);if (ditherOpacity < DITHER_THRESHOLDS[index]) {discard;}}} #else color=applyCutout(color,v_pos.z); #endif #endif #ifdef RENDER_FRONT_CUTOFF if (v_front_cutoff_opacity < 1.0) {int index=(int(gl_FragCoord.x) % 4)*4+(int(gl_FragCoord.y) % 4);if (v_front_cutoff_opacity < DITHER_THRESHOLDS[index]) {discard;}} #endif #ifdef FEATURE_CUTOUT color=apply_feature_cutout(color,gl_FragCoord,get_cutout_factors(gl_FragCoord).x); #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 ivec4 a_normal_3;in ivec4 a_centroid_3; #ifdef FLOOD_LIGHT in int a_flood_light_wall_radius_1i16; #endif #ifdef BUILDING_FAUX_FACADE in uvec4 a_faux_facade_data;in uvec2 a_faux_facade_vertical_range; #endif uniform mat4 u_matrix;uniform mat4 u_normal_matrix;uniform highp float u_tile_to_meter; #ifdef RENDER_FRONT_CUTOFF uniform vec3 u_front_cutoff_params;out float v_front_cutoff_opacity; #endif #ifdef INDICATOR_CUTOUT #ifdef FEATURE_CUTOUT out vec4 v_ground_roof; #endif #endif 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 uvec2 part_color_emissive #pragma mapbox: define-attribute-vertex-shader-only highp uvec2 faux_facade_color_emissive void main() { #pragma mapbox: initialize-attribute-custom highp uvec2 part_color_emissive #pragma mapbox: initialize-attribute-custom highp uvec2 faux_facade_color_emissive #ifdef FLOOD_LIGHT v_flood_radius=(float(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(vec2(part_color_emissive));v_color=vec4(sRGBToLinear(color_emissive.rgb),color_emissive.a);vec3 a_normal_3f=vec3(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;vec2 centroid_xy=vec2(a_centroid_3.xy >> 2);vec2 spanBits=vec2(a_centroid_3.xy & 3); #ifdef BUILDING_FAUX_FACADE vec4 faux_facade_data=vec4(a_faux_facade_data);v_faux_facade=faux_facade_data.x;if (v_faux_facade > 0.0) {v_faux_facade_ed=faux_facade_data.x *u_tile_to_meter;float window_x_perc=floor(faux_facade_data.y/TWO_POW_8);float window_y_perc=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=(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=(vec2(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(vec2(faux_facade_color_emissive));v_faux_color_emissive.rgb=sRGBToLinear(v_faux_color_emissive.rgb);depth_offset=min(1000.0,float(a_centroid_3.z))*0.0000002;} #endif v_pos=a_pos_3f; #if defined(RENDER_CUTOFF) || defined(RENDER_FRONT_CUTOFF) float halfSpanX=spanBits.x*10.0/u_tile_to_meter;float halfSpanY=spanBits.y*10.0/u_tile_to_meter;vec2 screenUpInTile=vec2(u_matrix[0][1],u_matrix[1][1]);vec2 spanOffset=vec2(halfSpanX,halfSpanY)*sign(screenUpInTile);vec2 cutoff_highestCorner=centroid_xy+spanOffset;vec2 cutoff_lowestCorner=centroid_xy-spanOffset; #endif #if defined(RENDER_CUTOFF) || defined(RENDER_FRONT_CUTOFF) vec4 ground=u_matrix*vec4(centroid_xy,0.0,1.0); #endif #ifdef RENDER_CUTOFF 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 #ifdef RENDER_FRONT_CUTOFF v_front_cutoff_opacity=1.0;{hidden=max(hidden,float(ground.w <=0.0));float ndc_y=ground.y/max(ground.w,0.001);float threshold=u_front_cutoff_params.x*2.0-1.0;float range_ndc=u_front_cutoff_params.y*2.0;hidden=max(hidden,float(ndc_y < threshold-range_ndc));float t=clamp((ndc_y-(threshold-range_ndc))/max(range_ndc,0.001),0.0,1.0);v_front_cutoff_opacity=mix(u_front_cutoff_params.z,1.0,t);} #endif gl_Position=mix(u_matrix*vec4(v_pos,1),AWAY,hidden);gl_Position.z-=depth_offset*gl_Position.w; #ifdef INDICATOR_CUTOUT #ifdef FEATURE_CUTOUT vec4 ic_ground=u_matrix*vec4(v_pos.xy,0.0,1.0);vec4 ic_roof=u_matrix*vec4(v_pos.xy,v_pos.z,1.0);v_ground_roof=vec4(ic_ground.xy/ic_ground.w,ic_roof.xy/ic_roof.w); #endif #endif }`),buildingBloom:mi(`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 uvec2 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 uvec2 part_color_emissive #pragma mapbox: initialize-attribute highp vec4 bloom_attenuation #ifdef HAS_ATTRIBUTE_a_part_color_emissive vec4 color_emissive=decode_color(vec2(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:mi("void main() {}","in vec3 a_pos_3f;uniform mat4 u_matrix;void main() {gl_Position=u_matrix*vec4(a_pos_3f,1.0);}"),circle:mi(`#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 ivec2 a_pos; #ifdef PROJECTION_GLOBE_VIEW in ivec4 a_pos_3;in ivec4 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.0,-1.0),radius,stroke_width,view_scale);vec2 c2=pos+calc_offset(vec2(1.0,-1.0),radius,stroke_width,view_scale);vec2 c3=pos+calc_offset(vec2(1.0,1.0),radius,stroke_width,view_scale);vec2 c4=pos+calc_offset(vec2(-1.0,1.0),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 pos2=vec2(a_pos);vec2 extrude=vec2(mod(pos2,2.0)*2.0-1.0);vec2 circle_center=floor(pos2*0.5);float height=circle_elevation(circle_center);vec4 world_center;mat3 surface_vectors; #ifdef PROJECTION_GLOBE_VIEW surface_vectors=globe_mercator_surface_vectors(vec3(a_pos_normal_3)/16384.0,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)*height;vec3 globe_pos=vec3(a_pos_3)+surface_extrusion+globe_elevation;vec3 mercator_elevation=u_up_dir*u_tile_up_scale*height;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);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:mi("void main() {glFragColor=vec4(1.0);}","in ivec2 a_pos;uniform mat4 u_matrix;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);}"),heatmap:mi(`#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 ivec2 a_pos; #ifdef PROJECTION_GLOBE_VIEW in ivec4 a_pos_3;in ivec4 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(vec2(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(vec2(a_pos)*0.5);vec3 pos; #ifdef PROJECTION_GLOBE_VIEW vec3 pos_normal_3=vec3(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=vec3(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:mi(`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 ivec2 a_pos;out vec2 v_pos;void main() {gl_Position=vec4(a_pos,0,1);v_pos=vec2(a_pos)*0.5+0.5;}"),collisionBox:mi("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 ivec4 a_pos;in ivec2 a_anchor_pos;in ivec2 a_extrude;in uvec2 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() {vec2 anchor_pos=vec2(a_anchor_pos);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(anchor_pos));vec3 proj_pos=vec3(a_pos)+elevationVector(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,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+=(vec2(a_extrude)*a_size_scale+a_shift+a_padding)*u_extrude_scale*gl_Position.w*collision_perspective_ratio;v_placed=float(a_placed.x);v_notUsed=float(a_placed.y);}`),collisionCircle:mi("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 ivec2 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;int vertexIdx=a_flags.y;vec2 quadVertexOffset=vec2( mix(-1.0,1.0,float(vertexIdx >=2)),mix(-1.0,1.0,float(vertexIdx >=1 && vertexIdx <=2)));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=float(a_flags.x);gl_Position=vec4(clipPos.xyz/clipPos.w,1.0)+vec4(quadVertexExtent*padding_factor/u_viewport_size*2.0,0.0,0.0);}`),debug:mi("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 ivec2 a_pos; #ifdef PROJECTION_GLOBE_VIEW in ivec4 a_pos_3; #endif out vec2 v_uv;uniform mat4 u_matrix;uniform float u_overlay_scale;void main() {vec2 pos=vec2(a_pos);float h=elevation(pos);v_uv=pos/8192.0; #ifdef PROJECTION_GLOBE_VIEW gl_Position=u_matrix*vec4(vec3(a_pos_3)+elevationVector(pos)*h,1); #else gl_Position=u_matrix*vec4(pos*u_overlay_scale,h,1); #endif }`),elevatedStructuresDepth:mi("void main() {}","in ivec2 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:mi(`#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,get_cutout_factors(gl_FragCoord).x); #endif #endif glFragColor=vec4(1.0,0.0,0.0,1.0);}`,`in ivec2 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:mi(`#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;vec2 cutout_factors=vec2(0.0); #ifdef FEATURE_CUTOUT cutout_factors=get_cutout_factors(gl_FragCoord); #endif #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 light=shadowed_light_factor_normal(transformed_normal,v_pos_light_view_0,v_pos_light_view_1,v_depth);light=mix(light,1.0,cutout_factors.y);color.rgb=apply_lighting(color.rgb,transformed_normal,light); #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,cutout_factors.x); #endif glFragColor=out_color;HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_shadow.vertex.glsl" in ivec2 a_pos;in float a_height;in ivec4 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=vec3(a_pos_normal_3)/16384.0;v_height=a_height;vec3 pos=vec3(vec2(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(vec2(a_pos)); #endif }`),fill:mi(`#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 vec2 cutout_factors=vec2(0.0); #ifdef FEATURE_CUTOUT cutout_factors=get_cutout_factors(gl_FragCoord); #endif 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);light=mix(light,1.0,cutout_factors.y);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,cutout_factors.x); #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 ivec2 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(vec2(a_pos)); #endif #ifdef INDICATOR_CUTOUT v_z_offset=z_offset; #endif }`),fillOutline:mi(`#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;vec2 cutout_factors=vec2(0.0); #ifdef FEATURE_CUTOUT cutout_factors=get_cutout_factors(gl_FragCoord); #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);light=mix(light,1.0,cutout_factors.y);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,cutout_factors.x); #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 ivec2 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(vec2(a_pos)); #endif }`),fillOutlinePattern:mi(`#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 uvec4 pattern #ifdef FILL_PATTERN_TRANSITION #pragma mapbox: define mediump uvec4 pattern_b #endif void main() { #pragma mapbox: initialize lowp float opacity #pragma mapbox: initialize mediump uvec4 pattern #ifdef FILL_PATTERN_TRANSITION #pragma mapbox: initialize mediump uvec4 pattern_b #endif vec2 pattern_tl=vec2(pattern.xy);vec2 pattern_br=vec2(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 vec2 cutout_factors=vec2(0.0); #ifdef FEATURE_CUTOUT cutout_factors=get_cutout_factors(gl_FragCoord); #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);light=mix(light,1.0,cutout_factors.y);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,cutout_factors.x); #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 ivec2 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 uvec4 pattern #ifdef FILL_PATTERN_TRANSITION #pragma mapbox: define mediump uvec4 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 uvec4 pattern #ifdef FILL_PATTERN_TRANSITION #pragma mapbox: initialize mediump uvec4 pattern_b #endif #pragma mapbox: initialize lowp float pixel_ratio #pragma mapbox: initialize highp float z_offset vec2 pattern_tl=vec2(pattern.xy);vec2 pattern_br=vec2(pattern.zw); #ifdef ELEVATED_ROADS z_offset+=a_road_z_offset; #endif float hidden=float(opacity==0.0);vec2 pos=vec2(a_pos);gl_Position=mix(u_matrix*vec4(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,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(pos,z_offset);vec3 shd_pos1=vec3(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(pos); #endif }`),fillPattern:mi(`#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 uvec4 pattern #ifdef FILL_PATTERN_TRANSITION #pragma mapbox: define mediump uvec4 pattern_b #endif void main() { #pragma mapbox: initialize lowp float opacity #pragma mapbox: initialize mediump uvec4 pattern #ifdef FILL_PATTERN_TRANSITION #pragma mapbox: initialize mediump uvec4 pattern_b #endif vec2 pattern_tl=vec2(pattern.xy);vec2 pattern_br=vec2(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=vec2(pattern_b.xy);vec2 pattern_b_br=vec2(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 vec2 cutout_factors=vec2(0.0); #ifdef FEATURE_CUTOUT cutout_factors=get_cutout_factors(gl_FragCoord); #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);light=mix(light,1.0,cutout_factors.y); #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,cutout_factors.x); #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 ivec2 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 uvec4 pattern #ifdef FILL_PATTERN_TRANSITION #pragma mapbox: define mediump uvec4 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 uvec4 pattern #pragma mapbox: initialize lowp float pixel_ratio #pragma mapbox: initialize highp float z_offset #ifdef FILL_PATTERN_TRANSITION #pragma mapbox: initialize mediump uvec4 pattern_b #endif vec2 pattern_tl=vec2(pattern.xy);vec2 pattern_br=vec2(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);vec2 pos=vec2(a_pos);gl_Position=mix(u_matrix*vec4(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,pos); #ifdef RENDER_SHADOWS vec3 shd_pos0=vec3(pos,z_offset);vec3 shd_pos1=vec3(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(pos); #endif }`),lineBlendComposite:mi(`uniform sampler2D u_image;uniform float u_opacity;uniform int u_blend_mode;in vec2 v_pos; #define ADDITIVE 1 void main() {vec4 color=texture(u_image,v_pos);if (u_blend_mode==ADDITIVE) {if (color.a <=0.0) {discard;}float density=color.a;vec3 avgColor=color.rgb/max(density,0.001);float t=density/(1.0+density);glFragColor=vec4(avgColor*t*u_opacity,t*u_opacity);} else {vec3 multiplyFactor=color.rgb*u_opacity+(1.0-u_opacity);glFragColor=vec4(multiplyFactor,1.0);} #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(0.0); #endif HANDLE_WIREFRAME_DEBUG;}`,"in ivec2 a_pos;out vec2 v_pos;void main() {gl_Position=vec4(a_pos,0,1);v_pos=vec2(a_pos)*0.5+0.5;}"),fillExtrusion:mi(`#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 RENDER_FRONT_CUTOFF in float v_front_cutoff_opacity; #endif #ifdef INDICATOR_CUTOUT #ifdef FEATURE_CUTOUT in vec4 v_ground_roof; #endif #endif #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 #ifdef FEATURE_CUTOUT {float ditherOpacity=cutoutGroundRoofOpacity(v_ground_roof);if (ditherOpacity < 1.0) {int index=(int(gl_FragCoord.x) % 4)*4+(int(gl_FragCoord.y) % 4);if (ditherOpacity < DITHER_THRESHOLDS[index]) {discard;}}} #else color=applyCutout(color,h); #endif #endif #ifdef RENDER_FRONT_CUTOFF if (v_front_cutoff_opacity < 1.0) {int index=(int(gl_FragCoord.x) % 4)*4+(int(gl_FragCoord.y) % 4);if (v_front_cutoff_opacity < DITHER_THRESHOLDS[index]) {discard;}} #endif #ifdef FEATURE_CUTOUT color=apply_feature_cutout(color,gl_FragCoord,get_cutout_factors(gl_FragCoord).x); #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 ivec4 a_pos_normal_ed; #if defined(HAS_CENTROID) || defined(TERRAIN) in uvec2 a_centroid_pos; #endif #ifdef RENDER_WALL_MODE in ivec4 a_join_normal_inside; #endif #ifdef PROJECTION_GLOBE_VIEW in ivec4 a_pos_3;in ivec4 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; #ifdef RENDER_FRONT_CUTOFF uniform vec3 u_front_cutoff_params;out float v_front_cutoff_opacity; #endif 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; #ifdef INDICATOR_CUTOUT #ifdef FEATURE_CUTOUT out vec4 v_ground_roof; #endif #endif 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 top_up_ny_start=vec4(a_pos_normal_ed & 1);vec4 pos_nx=vec4(a_pos_normal_ed >> 1);float x_normal=pos_nx.z/8192.0;vec3 normal=top_up_ny_start.y==1.0 ? vec3(0.0,0.0,1.0) : normalize(vec3(x_normal,(2.0*top_up_ny_start.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_start.y==0.0 && top_up_ny_start.x==1.0 ? height-u_edge_radius : height);float t=top_up_ny_start.x;vec2 centroid_pos=vec2(0.0); #if defined(HAS_CENTROID) || defined(TERRAIN) centroid_pos=vec2(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);bool is_elevation_encoded=centroid_pos.y==0.0 || (centroid_pos.y > 0.0 && (int(centroid_pos.y) & 7)==7);c_ele=is_flat_height || is_flat_base ? (is_elevation_encoded ? 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; #else h=t > 0.0 ? height : base; #endif pos=vec3(pos_nx.xy,h); #ifdef PROJECTION_GLOBE_VIEW float lift=float((t+base) > 0.0)*u_height_lift;h+=lift;vec3 globe_normal=normalize(mix(vec3(a_pos_normal_3)/16384.0,u_up_dir,u_zoom_transition));vec3 globe_pos=vec3(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; #if defined(RENDER_CUTOFF) || defined(RENDER_FRONT_CUTOFF) vec2 centroid_decoded=pos.xy;bool isBorderCentroid=false;if (centroid_pos.x > 0.0 && centroid_pos.y > 0.0) {int iy=int(centroid_pos.y);int spanYbits=iy & 7;if (spanYbits==7) {isBorderCentroid=true;int borderID=(iy >> 3) & 3;float coordAlongBorder=float(iy >> 5)*4.0;if (borderID==0) centroid_decoded=vec2(0.0,coordAlongBorder);else if (borderID==1) centroid_decoded=vec2(EXTENT,coordAlongBorder);else if (borderID==2) centroid_decoded=vec2(coordAlongBorder,0.0);else centroid_decoded=vec2(coordAlongBorder,EXTENT);} else {centroid_decoded=floor(centroid_pos/8.0);}} #endif #if defined(RENDER_CUTOFF) || defined(RENDER_FRONT_CUTOFF) vec4 ground=u_matrix*vec4(centroid_decoded,ele,1.0); #endif #ifdef RENDER_CUTOFF #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 centroid_random=vec3(centroid_pos.xy,centroid_pos.x+centroid_pos.y+1.0);vec3 ground_pos=centroid_random/8.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_FRONT_CUTOFF v_front_cutoff_opacity=1.0;if (centroid_pos.x > 0.0 && centroid_pos.y > 0.0) {hidden=max(hidden,float(ground.w <=0.0));float ndc_y=ground.y/max(ground.w,0.001);float threshold=u_front_cutoff_params.x*2.0-1.0;float range_ndc=u_front_cutoff_params.y*2.0;if (!isBorderCentroid) {hidden=max(hidden,float(ndc_y < threshold-range_ndc));}float t=clamp((ndc_y-(threshold-range_ndc))/max(range_ndc,0.001),0.0,1.0);v_front_cutoff_opacity=mix(u_front_cutoff_params.z,1.0,t);} #endif #ifdef RENDER_WALL_MODE vec3 join_normal_inside=vec3(a_join_normal_inside);vec2 wall_offset=u_width_scale*line_width*(join_normal_inside.xy/EXTENT);scaled_pos.xy+=(1.0-join_normal_inside.z)*wall_offset*0.5;scaled_pos.xy-=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_start.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_start.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 #ifdef INDICATOR_CUTOUT #ifdef FEATURE_CUTOUT vec4 pos_ground=u_matrix*vec4(pos.xy,ele,1.0);vec4 pos_roof=u_matrix*vec4(pos.xy,ele+height,1.0);v_ground_roof=vec4(pos_ground.xy/pos_ground.w,pos_roof.xy/pos_roof.w); #endif #endif }`),fillExtrusionDepth:mi("void main() {}",`#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 ivec4 a_pos_normal_ed; #if defined(HAS_CENTROID) || defined(TERRAIN) in uvec2 a_centroid_pos; #endif #ifdef RENDER_WALL_MODE in ivec4 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 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 top_up_ny=vec3(a_pos_normal_ed.xyz & 1);vec3 pos_nx=vec3(a_pos_normal_ed.xyz >> 1);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=vec2(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);bool is_elevation_encoded=centroid_pos.y==0.0 || (centroid_pos.y > 0.0 && int(centroid_pos.y)-(int(centroid_pos.y)/8)*8==7);float c_ele=is_flat_height || is_flat_base ? (is_elevation_encoded ? 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 vec3 join_normal_inside=vec3(a_join_normal_inside);vec2 wall_offset=u_width_scale*line_width*(join_normal_inside.xy/EXTENT);pos.xy+=(1.0-join_normal_inside.z)*wall_offset*0.5;pos.xy-=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);}`),fillExtrusionPattern:mi(`#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 uvec4 pattern #ifdef FILL_EXTRUSION_PATTERN_TRANSITION #pragma mapbox: define mediump uvec4 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 uvec4 pattern #ifdef FILL_EXTRUSION_PATTERN_TRANSITION #pragma mapbox: initialize mediump uvec4 pattern_b #endif #pragma mapbox: initialize highp float pixel_ratio vec2 pattern_tl=vec2(pattern.xy);vec2 pattern_br=vec2(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=vec2(pattern_b.xy);vec2 pattern_b_br=vec2(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 ivec4 a_pos_normal_ed; #if defined(HAS_CENTROID) || defined(TERRAIN) in uvec2 a_centroid_pos; #endif #ifdef RENDER_WALL_MODE in ivec4 a_join_normal_inside; #endif #ifdef PROJECTION_GLOBE_VIEW in ivec4 a_pos_3;in ivec4 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 uvec4 pattern #ifdef FILL_EXTRUSION_PATTERN_TRANSITION #pragma mapbox: define mediump uvec4 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 uvec4 pattern #ifdef FILL_EXTRUSION_PATTERN_TRANSITION #pragma mapbox: initialize mediump uvec4 pattern_b #endif #pragma mapbox: initialize highp float pixel_ratio #pragma mapbox: initialize highp float line_width vec2 pattern_tl=vec2(pattern.xy);vec2 pattern_br=vec2(pattern.zw);vec4 top_up_ny_start=vec4(a_pos_normal_ed & 1);vec4 pos_nx=vec4(a_pos_normal_ed >> 1);float x_normal=pos_nx.z/8192.0;vec3 normal=top_up_ny_start.y==1.0 ? vec3(0.0,0.0,1.0) : normalize(vec3(x_normal,(2.0*top_up_ny_start.z-1.0)*(1.0-abs(x_normal)),0.0));float edgedistance=float(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_start.x;float z=t > 0.0 ? height : base;vec2 centroid_pos=vec2(0.0); #if defined(HAS_CENTROID) || defined(TERRAIN) centroid_pos=vec2(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);bool is_elevation_encoded=centroid_pos.y==0.0 || (centroid_pos.y > 0.0 && int(centroid_pos.y)-(int(centroid_pos.y)/8)*8==7);c_ele=is_flat_height || is_flat_base ? (is_elevation_encoded ? 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(vec3(a_pos_normal_3)/16384.0,u_up_dir,u_zoom_transition));vec3 globe_pos=vec3(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 vec3 join_normal_inside=vec3(a_join_normal_inside);vec2 wall_offset=u_width_scale*line_width*(join_normal_inside.xy/EXTENT);p.xy+=(1.0-join_normal_inside.z)*wall_offset*0.5;p.xy-=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_start.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:mi(`#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 #ifdef FEATURE_CUTOUT shadow=mix(shadow,vec3(1.0),get_cutout_factors(gl_FragCoord).y); #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 ivec2 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(vec2(a_pos));v_fog_opacity=fog(v_fog_pos); #endif }`),fillExtrusionGroundEffect:mi(`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 ivec4 a_pos_end;in highp int a_angular_offset_factor;in highp uint 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 vec4 pos_end=vec4(a_pos_end);vec2 p=pos_end.xy;vec2 q=floor(pos_end.zw*0.5);vec2 start_bottom=pos_end.zw-q*2.0;float 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=float(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=float(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:mi(`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 ivec2 a_pos;in uvec2 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=(vec2(a_texture_pos)/8192.0)*scale+epsilon;}"),hillshade:mi(`#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 ivec2 a_pos;in uvec2 a_texture_pos;out vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);v_pos=vec2(a_texture_pos)/8192.0; #ifdef FOG v_fog_pos=fog_position(vec2(a_pos)); #endif }`),line:mi(`#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 highp vec2 u_trim_gradient_mix_range;uniform lowp vec4 u_trim_color;uniform bool u_emissive_in_shadows;in vec4 v_width2_dilute;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 VARIABLE_LINE_WIDTH in float stub_side; #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 mediump uvec4 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 mediump uvec4 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_dilute.x; #ifdef VARIABLE_LINE_WIDTH blur=mix(blur,0.0,stub_side); #endif float diluted_opacity=opacity*v_width2_dilute.z;float blur2=(u_width_scale*blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2_dilute.y-blur2),v_width2_dilute.x-dist)/blur2,0.0,1.0); #ifdef VARIABLE_LINE_WIDTH alpha=mix(alpha,1.0,stub_side); #endif 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)/(float(dash.z)+float(dash.w)/65535.0);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); #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);highp float gradient_trim_color_mix_factor=0.0; #ifdef RENDER_LINE_GRADIENT gradient_trim_color_mix_factor=smoothstep(u_trim_gradient_mix_range.x,u_trim_gradient_mix_range.y,line_progress); #endif highp vec4 trim_color=mix(u_trim_color,out_color,gradient_trim_color_mix_factor);out_color=mix(u_trim_gradient_mix_range.x < 1.0 ? color : out_color,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 #ifndef VARIABLE_LINE_WIDTH float edgeBlur=((border_width*u_width_scale)+1.0/u_device_pixel_ratio);float alpha2=clamp(min(dist-(v_width2_dilute.y-edgeBlur),v_width2_dilute.x-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);}out_color*=v_width2_dilute.w;} #endif #endif vec2 cutout_factors=vec2(0.0); #ifdef FEATURE_CUTOUT cutout_factors=get_cutout_factors(gl_FragCoord); #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);light=mix(light,1.0,cutout_factors.y);light=u_emissive_in_shadows ? mix(light,1.0,emissive_strength) : light; #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*diluted_opacity); #ifdef LINE_BLEND_MULTIPLY glFragColor=vec4(out_color.rgb+(1.0-out_color.a),1.0);HANDLE_WIREFRAME_DEBUG;return; #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,cutout_factors.x); #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 ivec2 a_pos_normal;in uvec4 a_data; #if defined(ELEVATED) || defined(ELEVATED_ROADS) || defined(VARIABLE_LINE_WIDTH) in vec3 a_z_offset_width; #endif #ifdef ELEVATION_GROUND_SCALE in float a_elevation_ground_scale; #endif #if defined(RENDER_LINE_GRADIENT) || defined(RENDER_LINE_TRIM_OFFSET) || defined(RENDER_LINE_CURVE) 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 RENDER_LINE_CURVE uniform mat3 u_curve_points_x;uniform mat3 u_curve_points_y;uniform mat3 u_curve_points_z;uniform float u_curve_point_count; #endif #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 vec4 v_width2_dilute;out float v_gamma_scale;out highp vec3 v_uv; #ifdef ELEVATED_ROADS out highp float v_road_z_offset; #endif #ifdef VARIABLE_LINE_WIDTH out float stub_side; #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 mediump uvec4 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 #ifdef RENDER_LINE_CURVE vec3 getCurvePoint(int index) {int row=index/3;int col=index-row*3;float x=u_curve_points_x[row][col];float y=u_curve_points_y[row][col];float z=u_curve_points_z[row][col];return vec3(x,y,z);}vec3 catmullRom(vec3 p0,vec3 p1,vec3 p2,vec3 p3,float t) {float t2=t*t;float t3=t2*t;return 0.5*( 2.0*p1+(-p0+p2)*t+(2.0*p0-5.0*p1+4.0*p2-p3)*t2+(-p0+3.0*p1-3.0*p2+p3)*t3 );}vec2 catmullRomTangent(vec2 p0,vec2 p1,vec2 p2,vec2 p3,float t) {float t2=t*t;return 0.5*( (-p0+p2)+(2.0*p0-5.0*p1+4.0*p2-p3)*2.0*t+(-p0+3.0*p1-3.0*p2+p3)*3.0*t2 );}struct CurveResult {vec3 point;vec2 tangent;};CurveResult calculateCurve(float line_progress) {float curve_progress=line_progress*(u_curve_point_count-1.0);float curve_progress_local=fract(curve_progress);float curve_segment=floor(curve_progress);int seg=int(curve_segment);vec3 p1=getCurvePoint(seg);vec3 p2=getCurvePoint(seg+1);float is_first_seg=step(curve_segment,0.5);vec3 p0_extrapolated=p1-(p2-p1);vec3 p0_fetched=getCurvePoint(max(seg-1,0));vec3 p0=mix(p0_fetched,p0_extrapolated,is_first_seg);int last_seg=int(u_curve_point_count)-2;float is_last_seg=step(float(last_seg)-0.5,curve_segment);vec3 p3_extrapolated=p2+(p2-p1);vec3 p3_fetched=getCurvePoint(min(seg+2,int(u_curve_point_count)-1));vec3 p3=mix(p3_fetched,p3_extrapolated,is_last_seg);vec3 point=catmullRom(p0,p1,p2,p3,curve_progress_local);vec2 tangent=catmullRomTangent(p0.xy,p1.xy,p2.xy,p3.xy,curve_progress_local)*(u_curve_point_count-1.0);CurveResult result;result.point=point;result.tangent=tangent;return result;} #endif void main() { #pragma mapbox: initialize highp vec4 color #pragma mapbox: initialize lowp float floorwidth #pragma mapbox: initialize mediump uvec4 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 highp float line_progress=0.0; #if defined(RENDER_LINE_GRADIENT) || defined(RENDER_LINE_TRIM_OFFSET) || defined(RENDER_LINE_CURVE) line_progress=a_packed[2]; #endif float ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=vec2(a_data.xy)-128.0;float a_direction=float(a_data.z & 3u)-1.0;vec2 pos_normal=vec2(a_pos_normal);vec2 pos=floor(pos_normal*0.5);mediump vec2 normal=pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;offset=-1.0*offset*u_width_scale;bool left=normal.y==1.0; #ifdef RENDER_LINE_CURVE CurveResult curve=calculateCurve(line_progress);pos=curve.point.xy*8192.0;a_extrude=length(a_extrude)*normalize(curve.tangent);a_extrude=left ? vec2(-a_extrude.y,a_extrude.x) : vec2(a_extrude.y,-a_extrude.x);a_z_offset+=curve.point.z; #endif gapwidth=gapwidth/2.0;float halfwidth;float dilute_scale=1.0;float dilute_border_scale=1.0; #ifdef VARIABLE_LINE_WIDTH float left_width=a_z_offset_width.y;float right_width=a_z_offset_width.z;halfwidth=(u_width_scale*(left ? left_width : right_width))/2.0;if (side_z_offset !=0.0) {float left_f=step(1.0,normal.y);float is_negative=step(side_z_offset,0.0);float apply=mix(1.0-left_f,left_f,is_negative);a_extrude*=apply;a_z_offset+=abs(side_z_offset)*apply;v_normal*=left_f;}offset=border_width > 0.0 ? (left_width+right_width)*u_width_scale*0.5 : offset;halfwidth=border_width > 0.0 ? border_width*u_width_scale*0.5 : halfwidth;bool zero_right_width=border_width==0.0 && right_width==0.0;stub_side=zero_right_width ?-normal.y : 0.0;v_normal=!left && zero_right_width ? vec2(0.0) : v_normal;ANTIALIASING=!left && zero_right_width ? 0.0 : ANTIALIASING; #else halfwidth=(u_width_scale*width)/2.0; #endif 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); #else #ifdef ELEVATED vec2 offsetTile=offset2*u_pixels_to_tile_units;vec2 offset_pos=pos+offsetTile;float ele=0.0;float scaled_z_offset=a_z_offset; #ifdef ELEVATION_GROUND_SCALE scaled_z_offset=a_z_offset*mix(1.0,u_exaggeration,a_elevation_ground_scale); #endif #ifdef CROSS_SLOPE_VERTICAL float top=pos_normal.y-2.0*floor(pos_normal.y*0.5);float line_height=2.0*u_tile_to_meter*outset*top*u_pixels_to_tile_units[1][1]+scaled_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+scaled_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+scaled_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=u_matrix*vec4(pos+offset2*u_pixels_to_tile_units,0.0,1.0); #endif #endif #ifndef ELEVATED #ifndef VARIABLE_LINE_WIDTH #ifndef RENDER_TO_TEXTURE float base_w=gl_Position.w;vec2 screen_width=abs(projected_extrude.xy/base_w*u_units_to_pixels);float max_extrude_component=max(screen_width.x,screen_width.y);if (width >=1.0 && base_w > 0.0 && max_extrude_component > 0.0001) {float min_pixel=1.05;if (max_extrude_component < min_pixel) {vec2 abs_pos=abs(gl_Position.xy);float is_out=max(abs_pos.x,abs_pos.y)/base_w;dilute_scale=mix(max_extrude_component/min_pixel,1.0,smoothstep(2.5,4.5,is_out));projected_extrude/=dilute_scale;}else { #ifdef RENDER_LINE_BORDER float border_ratio=(border_width*u_width_scale+ANTIALIASING)/outset;screen_width*=border_ratio;float max_border_component=max(screen_width.x,screen_width.y);dilute_border_scale=min(1.0,max_border_component/min_pixel); #endif }} #endif #endif #ifdef ELEVATED_ROADS gl_Position=gl_Position+projected_extrude; #else gl_Position=mix(gl_Position+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]; #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 vec4 dashf=vec4(dash);float totalLength=dashf.z+dashf.w/65535.0;float scale=totalLength==0.0 ? 0.0 : u_tile_units_to_pixels/totalLength;v_tex=vec2(a_linesofar*scale/(floorwidth*u_floor_width_scale),(-normal.y*dashf.y+dashf.x+0.5)/u_texsize.y); #endif v_width2_dilute=vec4(outset,inset,dilute_scale,dilute_border_scale); #ifdef FOG v_fog_pos=fog_position(pos); #endif #ifdef INDICATOR_CUTOUT v_z_offset=a_z_offset; #endif }`),linePattern:mi(`#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 uvec4 pattern #ifdef LINE_PATTERN_TRANSITION #pragma mapbox: define mediump uvec4 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 uvec4 pattern #ifdef LINE_PATTERN_TRANSITION #pragma mapbox: initialize mediump uvec4 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=vec2(pattern.xy);vec2 pattern_br=vec2(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=vec2(pattern_b.xy);vec2 pattern_b_br=vec2(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 ivec2 a_pos_normal;in uvec4 a_data; #if defined(ELEVATED) || defined(ELEVATED_ROADS) in vec3 a_z_offset_width; #endif #ifdef ELEVATION_GROUND_SCALE in float a_elevation_ground_scale; #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 uvec4 pattern #ifdef LINE_PATTERN_TRANSITION #pragma mapbox: define mediump uvec4 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 uvec4 pattern #ifdef LINE_PATTERN_TRANSITION #pragma mapbox: initialize mediump uvec4 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=vec2(a_data.xy)-128.0;float a_direction=float(a_data.z & 3u)-1.0;vec2 pos_normal=vec2(a_pos_normal);vec2 pos=floor(pos_normal*0.5);vec2 normal=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;float scaled_z_offset=a_z_offset; #ifdef ELEVATION_GROUND_SCALE scaled_z_offset=a_z_offset*mix(1.0,u_exaggeration,a_elevation_ground_scale); #endif #ifdef CROSS_SLOPE_VERTICAL float top=pos_normal.y-2.0*floor(pos_normal.y*0.5);float line_height=2.0*u_tile_to_meter*outset*top*u_pixels_to_tile_units[1][1]+scaled_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+scaled_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+scaled_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/(float(pattern.w-pattern.y)*pixel_ratio_inverse);highp float subt_multiple=float(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:mi(`#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" #include "_prelude_terrain.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; #ifdef ELEVATED uniform lowp float u_zbias_factor; #endif #define GLOBE_UPSCALE GLOBE_RADIUS/6371008.8 #ifdef GLOBE_POLES in vec3 a_globe_pos;in vec2 a_uv; #else in ivec2 a_pos;in uvec2 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;uv=a_uv;float ele=u_raster_elevation; #ifdef ELEVATION_REFERENCE_GROUND ele+=elevation(uv*EXTENT); #endif globe_pos+=normalize(globe_pos)*ele*GLOBE_UPSCALE;gl_Position=u_matrix*u_globe_matrix*vec4(globe_pos,1.0); #ifdef FOG v_fog_pos=fog_position((u_normalize_matrix*vec4(a_globe_pos,1.0)).xyz); #endif #else vec4 world_pos; #ifdef PROJECTION_GLOBE_VIEW vec2 texture_pos=vec2(a_texture_pos);uv=texture_pos/8192.0;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];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);}float ele=u_raster_elevation; #ifdef ELEVATION_REFERENCE_GROUND ele+=elevation(uv*EXTENT)-decomposed_pos_and_skirt.z; #endif vec4 merc_world_pos=vec4(0.0); v_split_fade=0.0;if (u_zoom_transition > 0.0) {vec2 merc_pos=vec2(mercatorX,mercatorY);merc_world_pos=vec4(merc_pos,ele,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)));}vec3 globe_pos=latLngToECEF(latLng.xy);globe_pos+=normalize(globe_pos)*ele*GLOBE_UPSCALE;vec4 globe_world_pos=u_globe_matrix*vec4(globe_pos,1.0);world_pos=vec4(mix(globe_world_pos.xyz,merc_world_pos.xyz,u_zoom_transition),1.0); #ifdef FOG v_fog_pos=fog_position((u_normalize_matrix*vec4(globe_pos,1.0)).xyz); #endif #else float ele=0.0;vec2 decodedPos=vec2(a_pos); #ifdef ELEVATION_REFERENCE_GROUND vec3 decomposedPosAndSkirt=decomposeToPosAndSkirt(a_pos);float skirt=decomposedPosAndSkirt.z;decodedPos=decomposedPosAndSkirt.xy;uv=decodedPos/8192.0;ele=elevation(decodedPos)-skirt; #else uv=vec2(a_texture_pos)/8192.0; #endif world_pos=vec4(decodedPos,(u_raster_elevation+ele),1.0); #ifdef FOG v_fog_pos=fog_position(decodedPos); #endif #endif float w=1.0+dot(uv*EXTENT,u_perspective_transform);gl_Position=u_matrix*world_pos*w; #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 ELEVATED 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);gl_Position.z-=(gl_Position.w*zbias); #endif #ifdef RENDER_CUTOFF v_depth=gl_Position.z; #endif }`),rasterParticle:mi(`#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 ivec2 a_pos;in uvec2 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=vec2(a_texture_pos)/8192.0;gl_Position=u_matrix*vec4(vec2(a_pos)*w,u_raster_elevation*w,w); #ifdef FOG v_fog_pos=fog_position(vec2(a_pos)); #endif #endif v_pos0=uv;v_pos1=(v_pos0*u_scale_parent)+u_tl_parent;}`),rasterParticleDraw:mi("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 int 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(float(a_index),u_particle_texture_side_len),float(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:mi("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 ivec2 a_pos;out vec2 v_tex_pos;void main() {vec2 uv=0.5*vec2(a_pos)+vec2(0.5);v_tex_pos=uv;gl_Position=vec4(a_pos,0.0,1.0);}"),rasterParticleUpdate:mi(`#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 ivec2 a_pos;out vec2 v_tex_coord;void main() {v_tex_coord=0.5*vec2(a_pos+ivec2(1));gl_Position=vec4(a_pos,0.0,1.0);}"),symbol:mi(`#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 #ifdef USE_PAINT_PROPERTIES_UBO in lowp float v_opacity; #ifdef RENDER_SDF in lowp vec4 v_fill_np_color;in lowp vec4 v_halo_np_color;in lowp float v_halo_width;in lowp float v_halo_blur; #endif #ifdef LIGHTING_3D_MODE in lowp float v_emissive_strength; #endif #else #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 #endif void main() { #ifdef USE_PAINT_PROPERTIES_UBO lowp float opacity=v_opacity;lowp vec4 fill_color=vec4(0.0);lowp vec4 halo_color=vec4(0.0);lowp float halo_width=0.0;lowp float halo_blur=0.0; #ifdef RENDER_SDF fill_color=vec4(v_fill_np_color.rgb*v_fill_np_color.a,v_fill_np_color.a);halo_color=vec4(v_halo_np_color.rgb*v_halo_np_color.a,v_halo_np_color.a);halo_width=v_halo_width;halo_blur=v_halo_blur; #endif lowp float emissive_strength=0.0; #ifdef LIGHTING_3D_MODE emissive_strength=v_emissive_strength; #endif #else #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 #endif 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 vec2 cutout_factors=vec2(0.0); #ifdef FEATURE_CUTOUT cutout_factors=get_cutout_factors(gl_FragCoord); #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);light=mix(light,1.0,cutout_factors.y); #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,cutout_factors.x); #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 USING_APPEARANCE 1.0 in ivec4 a_pos_offset;in uvec4 a_tex_size;in ivec4 a_pixeloffset;in vec4 a_projected_pos;in uint a_fade_opacity; #ifdef Z_OFFSET in float a_auto_z_offset; #endif #ifdef PROJECTION_GLOBE_VIEW in ivec4 a_globe_anchor;in vec3 a_globe_normal; #endif #ifdef ICON_TRANSITION in uvec2 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 #ifdef USE_PAINT_PROPERTIES_UBO #ifndef MAX_UBO_SIZE_VEC4 #define MAX_UBO_SIZE_VEC4 1024u #endif #define SPP_HEADER_SIZE_VEC4 3u #define DWORDS_PER_VEC4 4u struct SymbolPaintProperties {vec4 fill_np_color;vec4 halo_np_color;float opacity;float halo_width;float halo_blur;float emissive_strength;float occlusion_opacity;float z_offset;vec2 translate;};struct PropertyType {bool isDataDriven;bool isZoomDependent;uint offsetDwords;};struct SymbolPropertyHeader {uint dataDrivenBlockSizeVec4;PropertyType fill_np_color;PropertyType halo_np_color;PropertyType opacity;PropertyType halo_width;PropertyType halo_blur;PropertyType emissive_strength;PropertyType occlusion_opacity;PropertyType z_offset;PropertyType translate;};uniform float u_zoom;uniform lowp vec4 u_spp_fill_np_color;uniform lowp vec4 u_spp_halo_np_color;uniform lowp float u_spp_opacity;uniform lowp float u_spp_halo_width;uniform lowp float u_spp_halo_blur;uniform lowp float u_spp_emissive_strength;uniform lowp float u_spp_occlusion_opacity;uniform lowp float u_spp_z_offset;uniform lowp vec2 u_spp_translate_rotation;in float a_feature_index;layout(std140) uniform SymbolPaintPropertiesHeaderUniform {uvec4 header[SPP_HEADER_SIZE_VEC4];} u_spp_header;layout(std140) uniform SymbolPaintPropertiesUniform {vec4 properties[MAX_UBO_SIZE_VEC4];} u_spp_properties;layout(std140) uniform SymbolPaintPropertiesIndexUniform {uvec4 block_indices[MAX_UBO_SIZE_VEC4];} u_spp_index;out lowp float v_opacity; #ifdef RENDER_SDF out lowp vec4 v_fill_np_color;out lowp vec4 v_halo_np_color;out lowp float v_halo_width;out lowp float v_halo_blur; #endif #ifdef LIGHTING_3D_MODE out lowp float v_emissive_strength; #endif PropertyType getPropertyType(uint propertyIndex,uint dataDrivenMask,uint zoomDependentMask,uint offsetDwords) {PropertyType type;type.isDataDriven=(dataDrivenMask & (1u << propertyIndex)) !=0u;type.isZoomDependent=(zoomDependentMask & (1u << propertyIndex)) !=0u;type.offsetDwords=offsetDwords;return type;}SymbolPropertyHeader readSymbolPropertiesHeader() {SymbolPropertyHeader header;uint dataDrivenMask=u_spp_header.header[0][0];uint zoomDependentMask=u_spp_header.header[0][1];header.dataDrivenBlockSizeVec4=u_spp_header.header[0][2];header.fill_np_color =getPropertyType(0u,dataDrivenMask,zoomDependentMask,u_spp_header.header[0][3]);header.halo_np_color =getPropertyType(1u,dataDrivenMask,zoomDependentMask,u_spp_header.header[1][0]);header.opacity =getPropertyType(2u,dataDrivenMask,zoomDependentMask,u_spp_header.header[1][1]);header.halo_width =getPropertyType(3u,dataDrivenMask,zoomDependentMask,u_spp_header.header[1][2]);header.halo_blur =getPropertyType(4u,dataDrivenMask,zoomDependentMask,u_spp_header.header[1][3]);header.emissive_strength =getPropertyType(5u,dataDrivenMask,zoomDependentMask,u_spp_header.header[2][0]);header.occlusion_opacity =getPropertyType(6u,dataDrivenMask,zoomDependentMask,u_spp_header.header[2][1]);header.z_offset =getPropertyType(7u,dataDrivenMask,zoomDependentMask,u_spp_header.header[2][2]);header.translate =getPropertyType(8u,dataDrivenMask,zoomDependentMask,u_spp_header.header[2][3]);return header;}uint uvec4At(uvec4 v,uint index) {return (index==0u) ? v.x : (index==1u) ? v.y : (index==2u) ? v.z : v.w;}float vec4At(vec4 v,uint index) {return (index==0u) ? v.x : (index==1u) ? v.y : (index==2u) ? v.z : v.w;}vec4 readVec4(uint baseOffsetVec4,uint propertyOffsetDwords) {return u_spp_properties.properties[baseOffsetVec4+propertyOffsetDwords/DWORDS_PER_VEC4];}float readFloat(vec4 slot,uint propertyOffsetDwords) {return slot[propertyOffsetDwords % DWORDS_PER_VEC4];}uint readUint(uvec4 slot,uint offset) {return slot[offset % DWORDS_PER_VEC4];}vec2 readVec2(vec4 slot,uint propertyOffsetDwords) {float x=vec4At(slot,propertyOffsetDwords % DWORDS_PER_VEC4);float y=vec4At(slot,propertyOffsetDwords % DWORDS_PER_VEC4+1u);return vec2(x,y);}uint getDataDrivenBlockOffsetVec4(uint dataDrivenBlockSizeVec4) {uint featureIndex=uint(a_feature_index);uvec4 slot=u_spp_index.block_indices[featureIndex/DWORDS_PER_VEC4];uint blockIndex=uvec4At(slot,featureIndex % DWORDS_PER_VEC4);return blockIndex*dataDrivenBlockSizeVec4;}vec4 readColorProperty(PropertyType propertyType,uint dataDrivenBlockSizeVec4) {uint blockOffsetVec4=getDataDrivenBlockOffsetVec4(dataDrivenBlockSizeVec4);vec4 color=readVec4(blockOffsetVec4,propertyType.offsetDwords);if (propertyType.isZoomDependent) {color=unpack_mix_color(color,u_zoom);} else {vec2 packedColor=readVec2(color,propertyType.offsetDwords);color=decode_color(packedColor);}return color;}vec2 readVec2Property(PropertyType propertyType,uint dataDrivenBlockSizeVec4) {uint blockOffsetVec4=getDataDrivenBlockOffsetVec4(dataDrivenBlockSizeVec4);vec4 slot=readVec4(blockOffsetVec4,propertyType.offsetDwords);if (propertyType.isZoomDependent) {vec2 minVal=slot.xy;vec2 maxVal=slot.zw;return mix(minVal,maxVal,u_zoom);}return readVec2(slot,propertyType.offsetDwords);}float readFloatProperty(PropertyType propertyType,uint dataDrivenBlockSizeVec4) {uint blockOffsetVec4=getDataDrivenBlockOffsetVec4(dataDrivenBlockSizeVec4);vec4 slot=readVec4(blockOffsetVec4,propertyType.offsetDwords);float value;if (propertyType.isZoomDependent) {vec2 packedValues=readVec2(slot,propertyType.offsetDwords);value=unpack_mix_vec2(packedValues,u_zoom);} else {value=readFloat(slot,propertyType.offsetDwords);}return value;}SymbolPaintProperties readSymbolPaintProperties() {SymbolPropertyHeader header=readSymbolPropertiesHeader();uint sizeVec4=header.dataDrivenBlockSizeVec4;SymbolPaintProperties props;props.fill_np_color =header.fill_np_color.isDataDriven ? readColorProperty(header.fill_np_color,sizeVec4) : u_spp_fill_np_color;props.halo_np_color =header.halo_np_color.isDataDriven ? readColorProperty(header.halo_np_color,sizeVec4) : u_spp_halo_np_color;props.opacity =header.opacity.isDataDriven ? readFloatProperty(header.opacity,sizeVec4) : u_spp_opacity;props.halo_width =header.halo_width.isDataDriven ? readFloatProperty(header.halo_width,sizeVec4) : u_spp_halo_width;props.halo_blur =header.halo_blur.isDataDriven ? readFloatProperty(header.halo_blur,sizeVec4) : u_spp_halo_blur;props.emissive_strength =header.emissive_strength.isDataDriven ? readFloatProperty(header.emissive_strength,sizeVec4) : u_spp_emissive_strength;props.occlusion_opacity =header.occlusion_opacity.isDataDriven ? readFloatProperty(header.occlusion_opacity,sizeVec4) : u_spp_occlusion_opacity;props.z_offset =header.z_offset.isDataDriven ? readFloatProperty(header.z_offset,sizeVec4) : u_spp_z_offset;props.translate =header.translate.isDataDriven ? readVec2Property(header.translate,sizeVec4) : vec2(0.0);return props;} #else #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 #endif vec2 unpack_opacity(uint packedOpacity) {return vec2(float(packedOpacity/2u)/127.0,float(packedOpacity & 1u));}void main() { #ifdef USE_PAINT_PROPERTIES_UBO SymbolPaintProperties paint_properties=readSymbolPaintProperties();lowp float opacity=paint_properties.opacity;v_opacity=opacity; #ifdef RENDER_SDF v_fill_np_color=paint_properties.fill_np_color;v_halo_np_color=paint_properties.halo_np_color;v_halo_width=paint_properties.halo_width;v_halo_blur=paint_properties.halo_blur; #endif #ifdef LIGHTING_3D_MODE v_emissive_strength=paint_properties.emissive_strength; #endif lowp float occlusion_opacity=paint_properties.occlusion_opacity;lowp float z_offset=paint_properties.z_offset; #else #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 #endif vec2 a_pos=vec2(a_pos_offset.xy);vec2 a_offset=vec2(a_pos_offset.zw);vec2 a_tex=vec2(a_tex_size.xy);vec2 a_size=vec2(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=a_size[1]-2.0*a_size_max;vec2 a_pxoffset=vec2(a_pixeloffset.xy);vec2 a_min_font_scale=vec2(a_pixeloffset.zw)/256.0;highp float segment_angle=-a_projected_pos[3];float size;if (a_apperance==USING_APPEARANCE) {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=vec3(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(vec3(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); #ifdef USE_PAINT_PROPERTIES_UBO {vec2 tr=paint_properties.translate;vec2 rotated_tr=vec2( u_spp_translate_rotation.x*tr.x-u_spp_translate_rotation.y*tr.y,u_spp_translate_rotation.y*tr.x+u_spp_translate_rotation.x*tr.y );gl_Position.xy+=(u_coord_matrix*vec4(rotated_tr,0.0,0.0)).xy;} #endif 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=vec2(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:mi(`#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 ivec2 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:mi("precision highp float;in float v_depth;void main() {glFragColor=pack_depth(v_depth);}",`#include "_prelude_terrain.vertex.glsl" uniform mat4 u_matrix;in ivec2 a_pos;out float v_depth;void main() {float elevation=elevation(vec2(a_pos));gl_Position=u_matrix*vec4(a_pos,elevation,1.0);v_depth=gl_Position.z/gl_Position.w;}`),skybox:mi(`#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 }`,Q1),skyboxGradient:mi(`#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 }`,Q1),skyboxCapture:mi(` 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:mi(`#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 ivec2 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:mi(`#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:mi(`#include "_prelude_fog.fragment.glsl" #include "_prelude_shadow.fragment.glsl" #include "_prelude_lighting.glsl" uniform float u_opacity; #ifdef DITHERED_DISCARD uniform float u_dithered_discard_threshold; #endif 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 DITHERED_DISCARD if (abs(u_dithered_discard_threshold) < 1.0) {float ditherValue=fract(52.9829189*fract(0.06711056*gl_FragCoord.x+0.00583715*gl_FragCoord.y));float compareValue=mix(1.0-ditherValue,ditherValue,step(0.0,u_dithered_discard_threshold));if (abs(u_dithered_discard_threshold) < compareValue) {discard;}} #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,get_cutout_factors(gl_FragCoord).x); #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 uvec4 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 uvec4 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(vec2(pbr.xy));vec2 e_r_m=unpack_float(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(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:mi("void main() {}",`in vec3 a_pos_3f;uniform mat4 u_matrix; #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 }`),stars:mi(`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_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_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:mi("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:mi("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:mi("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:mi("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 Ig(M,g){const N=M.split(` `);for(let P of N){if(P=P.trimStart(),P[0]!=="#"||!P.includes("if")||P.startsWith("#endif"))continue;const F=P.match(hw);if(F)for(const q of F)mw.has(q)||g.add(q)}}function c4(M){return new Set(["uint","int","uvec2","ivec2","uvec3","ivec3","uvec4","ivec4"]).has(M)}function mi(M,g){const N=new Set,P=[],F=[];M=M.replace(wx,(G,Q)=>(F.push(Q),"")),g=g.replace(wx,(G,Q)=>(P.push(Q),""));let q=new Set(K0);Ig(M,q),Ig(g,q);for(const G of[...P,...F])yv[G]||(yv[G]=new Set,Ig(gf[G],yv[G])),q=new Set([...q,...yv[G]]);return{fragmentSource:M=M.replace(Sr,(G,Q,ae,me,ye)=>(N.add(ye),Q==="define"?` #ifndef HAS_UNIFORM_u_${ye} ${c4(me)?"flat ":""}in ${ae} ${me} ${ye}; #else uniform ${ae} ${me} u_${ye}; #endif `:Q==="initialize"?` #ifdef HAS_UNIFORM_u_${ye} ${ae} ${me} ${ye} = u_${ye}; #endif `:Q==="define-attribute"?` #ifdef HAS_ATTRIBUTE_a_${ye} in ${ae} ${me} ${ye}; #endif `:Q==="initialize-attribute"?"":void 0)),vertexSource:g=g.replace(Sr,(G,Q,ae,me,ye)=>{const Ae=`MATERIAL_ATTRIBUTE_OFFSET_${ye}`,Te=me==="float"?"vec2":me,Fe=`GET_ATTRIBUTE_${Te}(a_${ye}, materialInfo, ${Ae})`,Ye=ye.match(/color/)?"color":Te;return Q==="define-attribute-vertex-shader-only"?` #ifdef HAS_ATTRIBUTE_a_${ye} in ${ae} ${me} a_${ye}; #endif `:N.has(ye)?Q==="define"?` #ifndef HAS_UNIFORM_u_${ye} uniform lowp float u_${ye}_t; #if !defined(${Ae}) in ${ae} ${Te} a_${ye}; #endif ${c4(me)?"flat ":""}out ${ae} ${me} ${ye}; #else uniform ${ae} ${me} u_${ye}; #endif `:Q==="initialize"?Ye==="vec4"||Ye==="uvec4"?` #ifndef HAS_UNIFORM_u_${ye} ${ye} = a_${ye}; #else ${ae} ${me} ${ye} = u_${ye}; #endif `:` #if !defined(HAS_UNIFORM_u_${ye}) #ifdef ${Ae} ${ye} = unpack_mix_${Ye}(${Fe}, u_${ye}_t); #else ${ye} = unpack_mix_${Ye}(a_${ye}, u_${ye}_t); #endif #else ${ae} ${me} ${ye} = u_${ye}; #endif `:Q==="define-attribute"?` #ifdef HAS_ATTRIBUTE_a_${ye} in ${ae} ${me} a_${ye}; out ${ae} ${me} ${ye}; #endif `:Q==="initialize-attribute"?` #ifdef HAS_ATTRIBUTE_a_${ye} ${ye} = a_${ye}; #endif `:void 0:Q==="define"?` #ifndef HAS_UNIFORM_u_${ye} uniform lowp float u_${ye}_t; #if !defined(${Ae}) in ${ae} ${Te} a_${ye}; #endif #else uniform ${ae} ${me} u_${ye}; #endif `:Q==="define-instanced"?Ye==="mat4"?` #ifdef INSTANCED_ARRAYS in vec4 a_${ye}0; in vec4 a_${ye}1; in vec4 a_${ye}2; in vec4 a_${ye}3; #else uniform ${ae} ${me} u_${ye}; #endif `:` #ifdef INSTANCED_ARRAYS in ${ae} ${Te} a_${ye}; #else uniform ${ae} ${me} u_${ye}; #endif `:Q==="initialize-attribute-custom"?` #ifdef HAS_ATTRIBUTE_a_${ye} ${ae} ${me} ${ye} = a_${ye}; #endif `:Ye==="vec4"||Ye==="uvec4"?` #ifndef HAS_UNIFORM_u_${ye} #ifdef ${Ae} ${ae} ${me} ${ye} = ${Fe}; #else ${ae} ${me} ${ye} = a_${ye}; #endif #else ${ae} ${me} ${ye} = u_${ye}; #endif `:` #ifndef HAS_UNIFORM_u_${ye} #ifdef ${Ae} ${ae} ${me} ${ye} = unpack_mix_${Ye}(${Fe}, u_${ye}_t); #else ${ae} ${me} ${ye} = unpack_mix_${Ye}(a_${ye}, u_${ye}_t); #endif #else ${ae} ${me} ${ye} = u_${ye}; #endif `}),usedDefines:q,vertexIncludes:P,fragmentIncludes:F}}class d4{constructor(){this.boundProgram=null,this.boundLayoutVertexBuffer=null,this.boundPaintVertexBuffers=[],this.boundIndexBuffer=null,this.boundVertexOffset=null,this.boundDynamicVertexBuffers=[],this.vao=null}bind(g,N,P,F,q,G,Q,ae){this.context=g;let me=this.boundPaintVertexBuffers.length!==F.length;for(let Ae=0;!me&&Ae{const Kt=Ct.paint.get("hillshade-shadow-color"),Lt=Ct.paint.get("hillshade-shadow-color-use-theme").constantOr("default")==="none",Wt=Ct.paint.get("hillshade-highlight-color"),Tt=Ct.paint.get("hillshade-highlight-color-use-theme").constantOr("default")==="none",It=Ct.paint.get("hillshade-accent-color"),Ut=Ct.paint.get("hillshade-accent-color-use-theme").constantOr("default")==="none",rs=Ct.paint.get("hillshade-emissive-strength");let Zt=o.ap(Ct.paint.get("hillshade-illumination-direction"));if(Ct.paint.get("hillshade-illumination-anchor")==="viewport")Zt-=lt.transform.angle;else if(lt.style&<.style.enable3dLights()&<.style.directionalLight){const ms=lt.style.directionalLight.properties.get("direction"),Ws=o.cP(ms.x,ms.y,ms.z);Zt=o.ap(Ws[1])}const ks=!lt.options.moving;return{u_matrix:ht||lt.transform.calculateProjMatrix(_t.tileID.toUnwrapped(),ks),u_image:0,u_latrange:u4(0,_t.tileID),u_light:[Ct.paint.get("hillshade-exaggeration"),Zt],u_shadow:Kt.toPremultipliedRenderColor(Lt?null:Ct.lut),u_highlight:Wt.toPremultipliedRenderColor(Tt?null:Ct.lut),u_emissive_strength:rs,u_accent:It.toPremultipliedRenderColor(Ut?null:Ct.lut)}})(M,N,P,M.terrain?g.projMatrix:null);M.uploadCommonUniforms(Q,Te,g.toUnwrapped());const{tileBoundsBuffer:Ye,tileBoundsIndexBuffer:Ge,tileBoundsSegments:dt}=M.getTileBoundsBuffers(N);Te.draw(M,ae.TRIANGLES,F,q,G,_n.disabled,Fe,P.id,Ye,Ge,dt)}function h4(M,g,N){if(!g.needsDEMTextureUpload)return;const P=M.context,F=P.gl;P.pixelStoreUnpackPremultiplyAlpha.set(!1),g.demTexture=g.demTexture||M.getTileTexture(N.stride);const q=N.getPixels();g.demTexture?g.demTexture.update(q,{premultiply:!1}):g.demTexture=new o.T(P,q,F.R32F,{premultiply:!1}),g.needsDEMTextureUpload=!1}function oM(M,g,N){const P=M.context,F=P.gl;if(!g.dem)return;const q=g.dem;if(P.activeTexture.set(F.TEXTURE1),h4(M,g,q),!g.demTexture)return;g.demTexture.bind(F.NEAREST,F.CLAMP_TO_EDGE);const G=q.dim;P.activeTexture.set(F.TEXTURE0);let Q=g.hillshadeFBO;if(!Q){const Te=new o.T(P,{width:G,height:G,data:null},F.RGBA8);Te.bind(F.LINEAR,F.CLAMP_TO_EDGE),Q=g.hillshadeFBO=P.createFramebuffer(G,G,1,"renderbuffer"),Q.colorAttachment0.set(Te.texture)}P.bindFramebuffer.set(Q.framebuffer),P.viewport.set([0,0,G,G]);const{tileBoundsBuffer:ae,tileBoundsIndexBuffer:me,tileBoundsSegments:ye}=M.getMercatorTileBoundsBuffers(),Ae=[];M.linearFloatFilteringSupported()&&Ae.push("TERRAIN_DEM_FLOAT_FORMAT"),M.terrain&&M.terrain.renderingToTexture&&M.emissiveMode==="mrt-fallback"&&Ae.push("USE_MRT1"),M.getOrCreateProgram("hillshadePrepare",{defines:Ae}).draw(M,F.TRIANGLES,Wr.disabled,Gn.disabled,zn.unblended,_n.disabled,((Te,Fe)=>{const Ye=Fe.stride,Ge=o.bb();return o.bT(Ge,0,o.an,-o.an,0,0,1),o.bx(Ge,Ge,[0,-o.an,0]),{u_matrix:Ge,u_image:1,u_dimension:[Ye,Ye],u_zoom:Te.overscaledZ}})(g.tileID,q),N.id,ae,me,ye),g.needsHillshadePrepare=!1}class Ko{constructor(g){this.gl=g.gl,this.default=this.getDefault(),this.current=this.default,this.dirty=!1}get(){return this.current}set(g){}getDefault(){return this.default}setDefault(){this.set(this.default)}}class fw extends Ko{getDefault(){return o.aq.transparent.toNonPremultipliedRenderColor(null)}set(g){const N=this.current;(g.r!==N.r||g.g!==N.g||g.b!==N.b||g.a!==N.a||this.dirty)&&(this.gl.clearColor(g.r,g.g,g.b,g.a),this.current=g,this.dirty=!1)}}class lD extends Ko{getDefault(){return 1}set(g){(g!==this.current||this.dirty)&&(this.gl.clearDepth(g),this.current=g,this.dirty=!1)}}class Lj extends Ko{getDefault(){return 0}set(g){(g!==this.current||this.dirty)&&(this.gl.clearStencil(g),this.current=g,this.dirty=!1)}}class cD extends Ko{getDefault(){return[!0,!0,!0,!0]}set(g){const N=this.current;(g[0]!==N[0]||g[1]!==N[1]||g[2]!==N[2]||g[3]!==N[3]||this.dirty)&&(this.gl.colorMask(g[0],g[1],g[2],g[3]),this.current=g,this.dirty=!1)}}class ap extends Ko{getDefault(){return!0}set(g){(g!==this.current||this.dirty)&&(this.gl.depthMask(g),this.current=g,this.dirty=!1)}}class pw extends Ko{getDefault(){return 255}set(g){(g!==this.current||this.dirty)&&(this.gl.stencilMask(g),this.current=g,this.dirty=!1)}}class bv extends Ko{getDefault(){return{func:this.gl.ALWAYS,ref:0,mask:255}}set(g){const N=this.current;(g.func!==N.func||g.ref!==N.ref||g.mask!==N.mask||this.dirty)&&(this.gl.stencilFunc(g.func,g.ref,g.mask),this.current=g,this.dirty=!1)}}class Dj extends Ko{getDefault(){const g=this.gl;return[g.KEEP,g.KEEP,g.KEEP]}set(g){const N=this.current;(g[0]!==N[0]||g[1]!==N[1]||g[2]!==N[2]||this.dirty)&&(this.gl.stencilOp(g[0],g[1],g[2]),this.current=g,this.dirty=!1)}}class Y0 extends Ko{getDefault(){return!1}set(g){if(g===this.current&&!this.dirty)return;const N=this.gl;g?N.enable(N.STENCIL_TEST):N.disable(N.STENCIL_TEST),this.current=g,this.dirty=!1}}class Z0 extends Ko{getDefault(){return[0,1]}set(g){const N=this.current;(g[0]!==N[0]||g[1]!==N[1]||this.dirty)&&(this.gl.depthRange(g[0],g[1]),this.current=g,this.dirty=!1)}}class X0 extends Ko{getDefault(){return!1}set(g){if(g===this.current&&!this.dirty)return;const N=this.gl;g?N.enable(N.DEPTH_TEST):N.disable(N.DEPTH_TEST),this.current=g,this.dirty=!1}}class Wh extends Ko{getDefault(){return this.gl.LESS}set(g){(g!==this.current||this.dirty)&&(this.gl.depthFunc(g),this.current=g,this.dirty=!1)}}class Rj extends Ko{getDefault(){return!1}set(g){if(g===this.current&&!this.dirty)return;const N=this.gl;g?N.enable(N.BLEND):N.disable(N.BLEND),this.current=g,this.dirty=!1}}class gw extends Ko{getDefault(){const g=this.gl;return[g.ONE,g.ZERO,g.ONE,g.ZERO]}set(g){const N=this.current;(g[0]!==N[0]||g[1]!==N[1]||g[2]!==N[2]||g[3]!==N[3]||this.dirty)&&(this.gl.blendFuncSeparate(g[0],g[1],g[2],g[3]),this.current=g,this.dirty=!1)}}class lM extends Ko{getDefault(){return o.aq.transparent.toNonPremultipliedRenderColor(null)}set(g){const N=this.current;(g.r!==N.r||g.g!==N.g||g.b!==N.b||g.a!==N.a||this.dirty)&&(this.gl.blendColor(g.r,g.g,g.b,g.a),this.current=g,this.dirty=!1)}}class _v extends Ko{getDefault(){return this.gl.FUNC_ADD}set(g){(g!==this.current||this.dirty)&&(this.gl.blendEquationSeparate(g,g),this.current=g,this.dirty=!1)}}class xw extends Ko{getDefault(){return!1}set(g){if(g===this.current&&!this.dirty)return;const N=this.gl;g?N.enable(N.CULL_FACE):N.disable(N.CULL_FACE),this.current=g,this.dirty=!1}}class yw extends Ko{getDefault(){return this.gl.BACK}set(g){(g!==this.current||this.dirty)&&(this.gl.cullFace(g),this.current=g,this.dirty=!1)}}class Oj extends Ko{getDefault(){return this.gl.CCW}set(g){(g!==this.current||this.dirty)&&(this.gl.frontFace(g),this.current=g,this.dirty=!1)}}let vw=class extends Ko{getDefault(){return null}set(M){(M!==this.current||this.dirty)&&(this.gl.useProgram(M),this.current=M,this.dirty=!1)}};class bw extends Ko{getDefault(){return this.gl.TEXTURE0}set(g){(g!==this.current||this.dirty)&&(this.gl.activeTexture(g),this.current=g,this.dirty=!1)}}class Kh extends Ko{getDefault(){const g=this.gl;return[0,0,g.drawingBufferWidth,g.drawingBufferHeight]}set(g){const N=this.current;(g[0]!==N[0]||g[1]!==N[1]||g[2]!==N[2]||g[3]!==N[3]||this.dirty)&&(this.gl.viewport(g[0],g[1],g[2],g[3]),this.current=g,this.dirty=!1)}}class jh extends Ko{getDefault(){return null}set(g){if(g===this.current&&!this.dirty)return;const N=this.gl;N.bindFramebuffer(N.FRAMEBUFFER,g),this.current=g,this.dirty=!1}}class m4 extends Ko{getDefault(){return null}set(g){if(g===this.current&&!this.dirty)return;const N=this.gl;N.bindRenderbuffer(N.RENDERBUFFER,g),this.current=g,this.dirty=!1}}class wv extends Ko{getDefault(){return null}set(g){if(g===this.current&&!this.dirty)return;const N=this.gl;N.bindTexture(N.TEXTURE_2D,g),this.current=g,this.dirty=!1}}class f4 extends Ko{getDefault(){return null}set(g){if(g===this.current&&!this.dirty)return;const N=this.gl;N.bindBuffer(N.ARRAY_BUFFER,g),this.current=g,this.dirty=!1}}class cM extends Ko{getDefault(){return null}set(g){const N=this.gl;N.bindBuffer(N.ELEMENT_ARRAY_BUFFER,g),this.current=g,this.dirty=!1}}class dM extends Ko{getDefault(){return null}set(g){this.gl&&(g!==this.current||this.dirty)&&(this.gl.bindVertexArray(g),this.current=g,this.dirty=!1)}}class p4 extends Ko{getDefault(){return 4}set(g){if(g===this.current&&!this.dirty)return;const N=this.gl;N.pixelStorei(N.UNPACK_ALIGNMENT,g),this.current=g,this.dirty=!1}}class Fj extends Ko{getDefault(){return!1}set(g){if(g===this.current&&!this.dirty)return;const N=this.gl;N.pixelStorei(N.UNPACK_PREMULTIPLY_ALPHA_WEBGL,g),this.current=g,this.dirty=!1}}class _w extends Ko{getDefault(){return!1}set(g){if(g===this.current&&!this.dirty)return;const N=this.gl;N.pixelStorei(N.UNPACK_FLIP_Y_WEBGL,g),this.current=g,this.dirty=!1}}class eb extends Ko{constructor(g,N){super(g),this.context=g,this.parent=N}getDefault(){return null}}class jv extends eb{constructor(g,N,P=0){super(g,N),this.attachmentPoint=g.gl.COLOR_ATTACHMENT0+P}setDirty(){this.dirty=!0}set(g){if(g===this.current&&!this.dirty)return;this.context.bindFramebuffer.set(this.parent);const N=this.gl;N.framebufferTexture2D(N.FRAMEBUFFER,this.attachmentPoint,N.TEXTURE_2D,g,0),this.current=g,this.dirty=!1}}class ww extends eb{attachment(){return this.gl.DEPTH_ATTACHMENT}set(g){if(g===this.current&&!this.dirty)return;this.context.bindFramebuffer.set(this.parent);const N=this.gl;N.framebufferRenderbuffer(N.FRAMEBUFFER,this.attachment(),N.RENDERBUFFER,g),this.current=g,this.dirty=!1}}class Bj extends eb{attachment(){return this.gl.DEPTH_ATTACHMENT}set(g){if(g===this.current&&!this.dirty)return;this.context.bindFramebuffer.set(this.parent);const N=this.gl;N.framebufferTexture2D(N.FRAMEBUFFER,this.attachment(),N.TEXTURE_2D,g,0),this.current=g,this.dirty=!1}}class uM extends ww{attachment(){return this.gl.DEPTH_STENCIL_ATTACHMENT}}const Nv=(M,g,N,P)=>({u_matrix:M,u_image0:0,u_image1:1,u_skirt_height:g,u_ground_shadow_factor:N,u_emissive_texture_available:P}),Nx=(M,g,N,P,F,q,G,Q,ae,me,ye,Ae,Te,Fe,Ye,Ge,dt)=>({u_proj_matrix:Float32Array.from(M),u_globe_matrix:g,u_normalize_matrix:Float32Array.from(P),u_merc_matrix:N,u_zoom_transition:F,u_merc_center:q,u_image0:0,u_image1:1,u_frustum_tl:G,u_frustum_tr:Q,u_frustum_br:ae,u_frustum_bl:me,u_globe_pos:ye,u_globe_radius:Ae,u_viewport:Te,u_grid_matrix:dt?Float32Array.from(dt):new Float32Array(9),u_skirt_height:Fe,u_far_z_cutoff:Ye,u_emissive_texture_available:Ge});function g4(M,g){return M!=null&&g!=null&&!(!M.hasData()||!g.hasData())&&M.demTexture!=null&&g.demTexture!=null&&M.tileID.key!==g.tileID.key}const Jd=new class{constructor(){this.operations={}}newMorphing(M,g,N,P,F){if(M in this.operations){const q=this.operations[M];q.to.tileID.key!==N.tileID.key&&(q.queued=N)}else this.operations[M]={startTime:P,phase:0,duration:F,from:g,to:N,queued:null}}getMorphValuesForProxy(M){if(!(M in this.operations))return null;const g=this.operations[M];return{from:g.from,to:g.to,phase:g.phase}}update(M){for(const g in this.operations){const N=this.operations[g];for(N.phase=(M-N.startTime)/N.duration;N.phase>=1||!this._validOp(N);)if(!this._nextOp(N,M)){delete this.operations[g];break}}}_nextOp(M,g){return!!M.queued&&(M.from=M.to,M.to=M.queued,M.queued=null,M.phase=0,M.startTime=g,!0)}_validOp(M){return M.from.hasData()&&M.to.hasData()}},tb={0:null,1:"TERRAIN_VERTEX_MORPHING"};function sb(M,g,N){if(g===0)return 0;const P=g<1&&N===514?.25/g:1;return 6*Math.pow(1.5,22-M)*Math.max(g,1)*P}function kv(M,g){const N=1<({u_matrix:M});function Rm(M,g,N,P,F){if(F>0){const q=o.o.now(),G=(q-M.timeAdded)/F,Q=g?(q-g.timeAdded)/F:-1,ae=N.getSource(),me=P.coveringZoomLevel({tileSize:ae.tileSize,roundZoom:ae.roundZoom}),ye=!g||Math.abs(g.tileID.overscaledZ-me)>Math.abs(M.tileID.overscaledZ-me),Ae=ye&&M.refreshedUponExpiration?1:o.aC(ye?G:1-Q,0,1);return g?{opacity:1,mix:1-Ae,isFading:G<1}:{opacity:Ae,mix:0,isFading:G<1}}return{opacity:1,mix:0,isFading:!1}}class Nw extends Uo{constructor(g){const N={type:"raster-dem",maxzoom:Math.ceil(g.transform.maxZoom)},P=z0("mock-dem",N,g.style.dispatcher,g.style);super("mock-dem",P,null),P.setEventedParent(this),this._sourceLoaded=!0}_loadTile(g,N){g.state="loaded",N(null)}}class Sv extends Uo{constructor(g){const N=z0("proxy",{type:"geojson",maxzoom:Math.ceil(g.transform.maxZoom)},g.style.dispatcher,g.style);super("proxy",N,null),N.setEventedParent(this),this.map=this.getSource().map=g,this.used=this._sourceLoaded=!0,this.renderCache=[],this.renderCachePool=[],this.proxyCachedFBO={}}update(g,N,P){if(g.freezeTileCoverage)return;this.transform=g;const F=g.coveringTiles({tileSize:this._source.tileSize,minzoom:this._source.minzoom,maxzoom:this._source.maxzoom,roundZoom:this._source.roundZoom,reparseOverscaled:this._source.reparseOverscaled}).reduce((q,G)=>{if(q[G.key]="",!this._tiles[G.key]){const Q=new o.b0(G,this._source.tileSize*G.overscaleFactor(),g.tileZoom,void 0,void 0,this._source.worldview);Q.state="loaded",this._tiles[G.key]=Q}return q},{});for(const q in this._tiles)q in F||(this.freeFBO(q),this._tiles[q].unloadVectorData(),delete this._tiles[q])}freeFBO(g){const N=this.proxyCachedFBO[g];if(N!==void 0){const P=Object.values(N);this.renderCachePool.push(...P),delete this.proxyCachedFBO[g]}}deallocRenderCache(){this.renderCache.forEach(g=>g.fb.destroy()),this.renderCache=[],this.renderCachePool=[],this.proxyCachedFBO={}}}class Q0 extends o.aR{constructor(g,N,P){super(g.overscaledZ,g.wrap,g.canonical.z,g.canonical.x,g.canonical.y),this.proxyTileKey=N,this.projMatrix=P}}class J0 extends o.bu{constructor(g,N){super(),this._debugParams={sortTilesHiZFirst:!0,disableRenderCache:!1},this.painter=g,this.terrainTileForTile={},this.prevTerrainTileForTile={};const[P,F,q]=function(){const ae=new o.dB,me=new o.dC,ye=131;ae.reserve(17161),me.reserve(33800);const Ae=o.an/128,Te=o.an+Ae/2,Fe=Te+Ae;for(let Ge=-Ae;GeTe||Ge<0||Ge>Te?24575:0,_t=o.aC(Math.round(dt),0,o.an),Ct=o.aC(Math.round(Ge),0,o.an);ae.emplaceBack(_t+lt,Ct)}const Ye=(Ge,dt)=>{const lt=dt*ye+Ge;me.emplaceBack(lt+1,lt,lt+ye),me.emplaceBack(lt+ye,lt+ye+1,lt+1)};for(let Ge=1;Ge<129;Ge++)for(let dt=1;dt<129;dt++)Ye(dt,Ge);return[0,129].forEach(Ge=>{for(let dt=0;dt<130;dt++)Ye(dt,Ge),Ye(Ge,dt)}),[ae,me,32768]}(),G=g.context;this.gridBuffer=G.createVertexBuffer(P,o.dx.members),this.gridIndexBuffer=G.createIndexBuffer(F),this.gridSegments=o.dy.simpleSegment(0,0,P.length,F.length),this.gridNoSkirtSegments=o.dy.simpleSegment(0,0,P.length,q),this.proxyCoords=[],this.proxiedCoords={},this._visibleDemTiles=[],this._drapedRenderBatches=[],this._sourceTilesOverlap={},this.proxySourceCache=new Sv(N.map),this.orthoMatrix=o.bb(),o.bT(this.orthoMatrix,this.painter.transform.projection.name==="globe"?.015:0,o.an,0,o.an,0,1);const Q=G.gl;this._overlapStencilMode=new Gn({func:Q.GEQUAL,mask:255},0,255,Q.KEEP,Q.KEEP,Q.REPLACE),this._previousZoom=g.transform.zoom,this.pool=[],this._findCoveringTileCache={},this._tilesDirty={},this.style=N,this._useVertexMorphing=!0,this._exaggeration=1,this._mockSourceCache=new Nw(N.map),this._pendingGroundEffectLayers=[],this._emissiveTexture=!1}set style(g){g.on("data",this._onStyleDataEvent.bind(this)),this._style=g,this._style.map.on("moveend",()=>{this._clearLineLayersFromRenderCache()})}update(g,N,P){if(g&&g.terrain){this._style!==g&&(this.style=g,this._evaluationZoom=void 0);const F=g.terrain.properties,q=g.terrain.drapeRenderMode===0,G=g.terrain.isZoomDependent();this._previousUpdateTimestamp=this.enabled?this._updateTimestamp:void 0,this._updateTimestamp=o.o.now();const Q=g.terrain&&g.terrain.scope,ae=F.get("source"),me=q?this._mockSourceCache:g.getSourceCache(ae,Q);if(!me)return void o.w(`Couldn't find terrain source "${ae}".`);if(this.sourceCache=me,this._attenuationRange=g.terrain.getAttenuationRange(),this._exaggeration=G?this.calculateExaggeration(N):F.get("exaggeration"),!N.projection.requiresDraping&&G&&this._exaggeration===0)return void this._disable();this.enabled=!0;const ye=()=>{this.sourceCache.used&&o.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 Ae=this.getScaledDemTileSize();this.sourceCache.update(N,Ae,!0),this.resetTileLookupCache(this.sourceCache.id)};this.sourceCache.usedForTerrain||(this.resetTileLookupCache(this.sourceCache.id),this.sourceCache.usedForTerrain=!0,ye(),this._initializing=!0),ye(),N.updateElevation(!0,P),this.resetTileLookupCache(this.proxySourceCache.id),this.proxySourceCache.update(N),this._emptyDEMTextureDirty=!0,this._previousZoom=N.zoom}else this._disable()}calculateExaggeration(g){if(this._attenuationRange&&g.zoom>=Math.ceil(this._attenuationRange[1]))return this._style.terrain.getExaggeration(g.zoom);const N=this._previousCameraAltitude,P=g.getFreeCameraOptions().position.z/g.pixelsPerMeter*g.worldSize;this._previousCameraAltitude=P;const F=N!=null?P-N:Number.MAX_VALUE;if(Math.abs(F)<2)return this._exaggeration;const q=g.zoom,G=this._style.terrain;if(!this._previousUpdateTimestamp)return G.getExaggeration(q);let Q=q-this._previousZoom;const ae=this._previousUpdateTimestamp;let me=q;this._evaluationZoom!=null&&(me=this._evaluationZoom,Math.abs(q-me)>.5&&(Q=.5*(q-me+Q)),Q*F<0&&(me+=Q)),this._evaluationZoom=me;const ye=G.getExaggeration(me),Ae=ye===G.getExaggeration(Math.max(0,me-.1));if(Ae&&Math.abs(ye-this._exaggeration)<.01)return ye;let Te=Math.min(.1,.00375*(this._updateTimestamp-ae));return(Ae||ye<.1||Math.abs(Q)<1e-4)&&(Te=Math.min(.2,4*Te)),o.am(this._exaggeration,ye,Te)}resetTileLookupCache(g){this._findCoveringTileCache[g]={}}attenuationRange(){return this._attenuationRange}getDemUpscale(){return this.proxySourceCache.getSource().tileSize/128}getScaledDemTileSize(){return this.sourceCache.getSource().tileSize/128*this.proxySourceCache.getSource().tileSize}_onStyleDataEvent(g){g.dataType==="source"&&g.coord?this._clearRenderCacheForTile(g.sourceCacheId,g.coord):g.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 g in this._style._mergedSourceCaches)this._style._mergedSourceCaches[g].usedForTerrain=!1}destroy(){this._disable(),this._emptyDEMTexture&&this._emptyDEMTexture.destroy(),this.pool.forEach(g=>g.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 g=2*this.proxySourceCache.getSource().tileSize;return[g,g]}set useVertexMorphing(g){this._useVertexMorphing=g}updateTileBinding(g){if(!this.enabled)return;this.prevTerrainTileForTile=this.terrainTileForTile;const N=this.proxySourceCache,P=this.painter.transform;this._initializing&&(this._initializing=P._centerAltitude===0&&this.getAtPointOrZero(o.ag.fromLngLat(P.center),-1)===-1,this._emptyDEMTextureDirty=!this._initializing);const F=this.proxyCoords=N.getIds().map(ae=>{const me=N.getTileByID(ae).tileID;return me.projMatrix=P.calculateProjMatrix(me.toUnwrapped()),me});(function(ae,me){const ye=me.transform.pointCoordinate(me.transform.getCameraPoint()),Ae=new o.P(ye.x,ye.y);ae.sort((Te,Fe)=>{if(Fe.overscaledZ-Te.overscaledZ)return Fe.overscaledZ-Te.overscaledZ;const Ye=new o.P(Te.canonical.x+(1<{this.proxyToSource[ae.key]={}}),this.terrainTileForTile={};const G=this._style._mergedSourceCaches;for(const ae in G){const me=G[ae];if(!me.used||(me!==this.sourceCache&&this.resetTileLookupCache(me.id),this._setupProxiedCoordsForOrtho(me,g[ae],q),me.usedForTerrain))continue;const ye=g[ae];(me.getSource().reparseOverscaled||me._isRasterElevatedOverTerrain)&&this._assignTerrainTiles(ye)}this.proxiedCoords[N.id]=F.map(ae=>new Q0(ae,ae.key,this.orthoMatrix)),this._assignTerrainTiles(F),this._prepareDEMTextures(),this._setupDrapedRenderBatches(),this._initFBOPool(),this._setupRenderCache(q),this.renderingToTexture=!1;const Q={};this._visibleDemTiles=[];for(const ae of this.proxyCoords){const me=this.terrainTileForTile[ae.key];if(!me)continue;const ye=me.tileID.key;ye in Q||(this._visibleDemTiles.push(me),Q[ye]=ye)}}_assignTerrainTiles(g){this._initializing||g.forEach(N=>{if(this.terrainTileForTile[N.key])return;const P=this._findTileCoveringTileID(N,this.sourceCache);P&&(this.terrainTileForTile[N.key]=P)})}_prepareDEMTextures(){const g=this.painter.context,N=g.gl;for(const P in this.terrainTileForTile){const F=this.terrainTileForTile[P],q=F.dem;!q||F.demTexture&&!F.needsDEMTextureUpload||(g.activeTexture.set(N.TEXTURE1),h4(this.painter,F,q))}}_prepareDemTileUniforms(g,N,P,F){if(!N||N.demTexture==null)return!1;const q=g.tileID.canonical,G=Math.pow(2,N.tileID.canonical.z-q.z),Q=F||"";return P[`u_dem_tl${Q}`]=[q.x*G%1,q.y*G%1],P[`u_dem_scale${Q}`]=G,!0}get emptyDEMTexture(){return!this._emptyDEMTextureDirty&&this._emptyDEMTexture?this._emptyDEMTexture:this._updateEmptyDEMTexture()}_getLoadedAreaMinimum(){if(!this.enabled)return 0;let g=0;const N=this._visibleDemTiles.reduce((P,F)=>{if(!F.dem)return P;const q=F.dem.tree.minimums[0];return q>0&&g++,P+q},0);return g?N/g:0}_updateEmptyDEMTexture(){const g=this.painter.context,N=g.gl;g.activeTexture.set(N.TEXTURE2);const P=this._getLoadedAreaMinimum(),F=new o.dz({width:1,height:1},new Float32Array([P]));this._emptyDEMTextureDirty=!1;let q=this._emptyDEMTexture;return q?q.update(F,{premultiply:!1}):q=this._emptyDEMTexture=new o.T(g,F,N.R32F,{premultiply:!1}),q}setupElevationDraw(g,N,P){const F=this.painter.context,q=F.gl,G={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};G.u_exaggeration=this.exaggeration();let Q=null,ae=null,me=1;if(P&&P.morphing&&this._useVertexMorphing){const Fe=P.morphing.srcDemTile,Ye=P.morphing.dstDemTile;me=P.morphing.phase,Fe&&Ye&&(this._prepareDemTileUniforms(g,Fe,G,"_prev")&&(ae=Fe),this._prepareDemTileUniforms(g,Ye,G)&&(Q=Ye))}const ye=Fe=>Fe&&Fe.demTexture&&this.painter.linearFloatFilteringSupported()?q.LINEAR:q.NEAREST;let Ae=null;var Te;if(this.enabled?ae&&Q?(Ae=Q.demTexture,F.activeTexture.set(q.TEXTURE4),ae.demTexture.bind(ye(ae),q.CLAMP_TO_EDGE),G.u_dem_lerp=me):(Q=this.terrainTileForTile[g.tileID.key],Ae=this._prepareDemTileUniforms(g,Q,G)?Q.demTexture:this.emptyDEMTexture):Ae=this.emptyDEMTexture,F.activeTexture.set(q.TEXTURE2),Ae&&(G.u_dem_size=(Te=Ae).size[0]===1?1:Te.size[0]-2,Ae.bind(ye(Q),q.CLAMP_TO_EDGE)),this.painter.setupDepthForOcclusion(P&&P.useDepthForOcclusion,N,G),P&&P.useMeterToDem&&Q){const Fe=(1<{if(lt===ms)return;const Ws=[tb[ms],"PROJECTION_GLOBE_VIEW"];Ct&&Ws.push("CUSTOM_ANTIALIASING");const sr=me.isTileAffectedByFog(ks);dt=me.getOrCreateProgram("globeRaster",{defines:Ws,overrideFog:sr}),lt=ms},Kt=me.colorModeForRenderPass(),Lt=new Wr(Ge.LEQUAL,Wr.ReadWrite,me.depthRangeFor3D);Jd.update(Fe);const Wt=o.dq(_t),Tt=[o.aH(_t.center.lng),o.aL(_t.center.lat)],It=me.globeSharedBuffers,Ut=[_t.width*o.o.devicePixelRatio,_t.height*o.o.devicePixelRatio],rs=Float32Array.from(_t.globeMatrix),Zt={useDenormalizedUpVectorScale:!0};{const ks=me.transform,ms=sb(ks.zoom,ye.exaggeration(),ye.sourceCache._source.tileSize);lt=-1;const Ws=Ge.TRIANGLES;for(const sr of Te){const as=Ae.getTile(sr),Xt=Gn.disabled,ws=ye.prevTerrainTileForTile[sr.key],Ts=ye.terrainTileForTile[sr.key];g4(ws,Ts)&&Jd.newMorphing(sr.key,ws,Ts,Fe,250),xf(me,as.emissiveTexture),Ye.activeTexture.set(Ge.TEXTURE0),as.texture&&as.texture.bind(Ge.LINEAR,Ge.CLAMP_TO_EDGE);const Ls=Jd.getMorphValuesForProxy(sr.key),wr=Ls?1:0;Ls&&Object.assign(Zt,{morphing:{srcDemTile:Ls.from,dstDemTile:Ls.to,phase:o.dn(Ls.phase)}});const mr=o.dr(sr.canonical),fr=o.ds(mr.getCenter().lat),Js=o.dt(sr.canonical,mr,fr,ks.worldSize/ks._pixelsPerMercatorPixel),en=o.du(o.dv(sr.canonical)),dn=me.emissiveMode==="mrt-fallback"?1:0,Kr=Nx(ks.expandedFarZProjMatrix,rs,Wt,en,o.al(ks.zoom),Tt,ks.frustumCorners.TL,ks.frustumCorners.TR,ks.frustumCorners.BR,ks.frustumCorners.BL,ks.globeCenterInViewSpace,ks.globeRadius,Ut,ms,ks._farZ,dn,Js);if(ht(sr,wr),dt&&(ye.setupElevationDraw(as,dt,Zt),me.uploadCommonUniforms(Ye,dt,sr.toUnwrapped()),It)){const[Jr,$n,oa]=It.getGridBuffers(fr,ms!==0);dt.draw(me,Ws,Lt,Xt,Kt,_n.backCCW,Kr,"globe_raster",Jr,$n,oa)}}}if(It&&(me.renderDefaultNorthPole||me.renderDefaultSouthPole)){const ks=["GLOBE_POLES","PROJECTION_GLOBE_VIEW"];Ct&&ks.push("CUSTOM_ANTIALIASING"),dt=me.getOrCreateProgram("globeRaster",{defines:ks});for(const ms of Te){const{x:Ws,y:sr,z:as}=ms.canonical,Xt=sr===0,ws=sr===(1<Jr.draw(me,Ge.TRIANGLES,Lt,Gn.disabled,Kt,_n.disabled,Nx(_t.expandedFarZProjMatrix,Js,Js,en,0,Tt,_t.frustumCorners.TL,_t.frustumCorners.TR,_t.frustumCorners.BR,_t.frustumCorners.BL,_t.globeCenterInViewSpace,_t.globeRadius,Ut,0,_t._farZ,dn),"globe_pole_raster",$n,wr,mr);ye.setupElevationDraw(fr,dt,Zt),me.uploadCommonUniforms(Ye,dt,ms.toUnwrapped()),Xt&&me.renderDefaultNorthPole&&Kr(dt,Ts),ws&&me.renderDefaultSouthPole&&(Js=o.cC(o.bb(),Js,[1,-1,1]),Kr(dt,Ls))}}}})(F,q,G,Q,ae);else{const me=F.context,ye=me.gl;let Ae,Te;const Fe=F.shadowRenderer,Ye=wc(F,F.longestCutoffRange),Ge=Kt=>{if(Te===Kt)return;const Lt=[];Lt.push(tb[Kt]),Ye.shouldRenderCutoff&&Lt.push("RENDER_CUTOFF"),Fe&&(Lt.push("RENDER_SHADOWS"),Fe.useNormalOffset&&Lt.push("NORMAL_OFFSET")),Ae=F.getOrCreateProgram("terrainRaster",{defines:Lt}),Te=Kt},dt=F.colorModeForRenderPass(),lt=new Wr(ye.LEQUAL,Wr.ReadWrite,F.depthRangeFor3D);Jd.update(ae);const _t=F.transform,Ct=sb(_t.zoom,q.exaggeration(),q.sourceCache._source.tileSize);let ht=[0,0,0];if(Fe){const Kt=F.style.directionalLight,Lt=F.style.ambientLight;Kt&&Lt&&(ht=pf(F.style,Kt,Lt))}{Te=-1;const Kt=ye.TRIANGLES,[Lt,Wt]=[q.gridIndexBuffer,q.gridSegments];for(const Tt of Q){const It=G.getTile(Tt),Ut=Gn.disabled,rs=q.prevTerrainTileForTile[Tt.key],Zt=q.terrainTileForTile[Tt.key];g4(rs,Zt)&&Jd.newMorphing(Tt.key,rs,Zt,ae,250),xf(F,It.emissiveTexture),me.activeTexture.set(ye.TEXTURE0),It.texture&&It.texture.bind(ye.LINEAR,ye.CLAMP_TO_EDGE);const ks=Jd.getMorphValuesForProxy(Tt.key),ms=ks?1:0;let Ws;ks&&(Ws={morphing:{srcDemTile:ks.from,dstDemTile:ks.to,phase:o.dn(ks.phase)}});const sr=F.emissiveMode==="mrt-fallback"?1:0,as=Nv(Tt.projMatrix,kv(Tt.canonical,_t.renderWorldCopies)?Ct/10:Ct,ht,sr);if(Ge(ms),!Ae)continue;q.setupElevationDraw(It,Ae,Ws);const Xt=Tt.toUnwrapped();Fe&&Fe.setupShadows(Xt,Ae),F.uploadCommonUniforms(me,Ae,Xt,null,Ye),Ae.draw(F,Kt,lt,Ut,dt,_n.backCCW,as,"terrain_raster",q.gridBuffer,Lt,Wt)}}}}(N,this,this.proxySourceCache,g,this._updateTimestamp),this.renderingToTexture=!0,N.gpuTimingDeferredRenderEnd(),g.splice(0,g.length))}renderBatch(g){if(this._drapedRenderBatches.length===0)return g+1;this.renderingToTexture=!0;const N=this.painter,P=this.painter.context,F=this.proxySourceCache,q=this.proxiedCoords[F.id],G=this._drapedRenderBatches.shift(),Q=N.style.order,ae=[];this._updateFBOs(N.emissiveMode==="mrt-fallback");let me=0;for(const ye of q){const Ae=F.getTileByID(ye.proxyTileKey),Te=F.proxyCachedFBO[ye.key]?F.proxyCachedFBO[ye.key][g]:void 0,Fe=Te!==void 0?F.renderCache[Te]:this.pool[me++],Ye=Te!==void 0;if(Ae.texture=Fe.tex,Ae.emissiveTexture=Fe.emissiveTex,Ye&&!Fe.dirty){ae.push(Ae.tileID);continue}P.bindFramebuffer.set(Fe.fb.framebuffer);const Ge=P.gl;let dt;Ge.drawBuffers(N.emissiveMode==="mrt-fallback"?[Ge.COLOR_ATTACHMENT0,Ge.COLOR_ATTACHMENT1]:[Ge.COLOR_ATTACHMENT0]),this.renderedToTile=!1,Fe.dirty&&(P.clear({color:o.aq.transparent,stencil:0}),Fe.dirty=!1);for(let lt=G.start;lt<=G.end;++lt){const _t=N.style._mergedLayers[Q[lt]];if(_t.isHidden(N.transform.zoom))continue;const Ct=N.style.getLayerSourceCache(_t),ht=Ct?this.proxyToSource[ye.key][Ct.id]:[ye];if(!ht)continue;const Kt=ht;P.viewport.set([0,0,Fe.fb.width,Fe.fb.height]),dt!==(Ct?Ct.id:null)&&(this._setupStencil(Fe,ht,_t,Ct),dt=Ct?Ct.id:null),N.renderLayer(N,Ct,_t,Kt)}if(Ge.drawBuffers([Ge.COLOR_ATTACHMENT0]),this._drapedRenderBatches.length===0)for(const lt of this._pendingGroundEffectLayers){const _t=N.style._mergedLayers[Q[lt]];if(_t.isHidden(N.transform.zoom))continue;const Ct=N.style.getLayerSourceCache(_t),ht=Ct?this.proxyToSource[ye.key][Ct.id]:[ye];if(!ht)continue;const Kt=ht;P.viewport.set([0,0,Fe.fb.width,Fe.fb.height]),dt!==(Ct?Ct.id:null)&&(this._setupStencil(Fe,ht,_t,Ct),dt=Ct?Ct.id:null),N.renderLayer(N,Ct,_t,Kt)}this.renderedToTile?(Fe.dirty=!0,ae.push(Ae.tileID)):Ye||--me,me===5&&(me=0,this.renderToBackBuffer(ae))}return this.renderToBackBuffer(ae),this.renderingToTexture=!1,P.bindFramebuffer.set(null),P.viewport.set([0,0,N.width,N.height]),G.end+1}postRender(){}isLayerOrderingCorrect(g){const N=g.order.length;let P=-1,F=N;for(let q=0;qP}getMinElevationBelowMSL(){let g=0;return this._visibleDemTiles.filter(N=>N.dem).forEach(N=>{g=Math.min(g,N.dem.tree.minimums[0])}),g===0?g:(g-30)*this._exaggeration}raycast(g,N,P){if(!this._visibleDemTiles)return null;const F=this._visibleDemTiles.filter(q=>q.dem).map(q=>{const G=q.tileID,Q=1<(q.t!==null?q.t:Number.MAX_VALUE)-(G.t!==null?G.t:Number.MAX_VALUE));for(const q of F){if(q.t==null)return null;const G=q.tile.dem.tree.raycast(q.minx,q.miny,q.maxx,q.maxy,g,N,P);if(G!=null)return G}return null}_createFBO(){const g=this.painter.context,N=g.gl,P=this.drapeBufferSize;g.activeTexture.set(N.TEXTURE0);const F=new o.T(g,{width:P[0],height:P[1],data:null},N.RGBA8);F.bind(N.LINEAR,N.CLAMP_TO_EDGE);const q=g.createFramebuffer(P[0],P[1],1,null);let G;return q.colorAttachment0.set(F.texture),this._emissiveTexture&&(G=new o.T(g,{width:P[0],height:P[1],data:null},N.R8),G.bind(N.LINEAR,N.CLAMP_TO_EDGE),q.createColorAttachment(g,1),q.colorAttachment1.set(G.texture)),q.depthAttachment=new uM(g,q.framebuffer),this._sharedDepthStencil===void 0?(this._sharedDepthStencil=g.createRenderbuffer(g.gl.DEPTH_STENCIL,P[0],P[1]),this._stencilRef=0,q.depthAttachment.set(this._sharedDepthStencil),g.clear({stencil:0})):q.depthAttachment.set(this._sharedDepthStencil),g.extTextureFilterAnisotropic&&N.texParameterf(N.TEXTURE_2D,g.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,g.extTextureFilterAnisotropicMax),{fb:q,tex:F,emissiveTex:G,dirty:!1}}_updateFBOs(g){if(this._emissiveTexture!==g){for(const N of this.pool)this._updateFBO(N,g);for(const N of this.proxySourceCache.renderCache)this._updateFBO(N,g);this._emissiveTexture=g}}_updateFBO(g,N){const P=g.fb,F=this.painter.context,q=F.gl,G=this.drapeBufferSize;if(N){const Q=new o.T(F,{width:G[0],height:G[1],data:null},q.R8);Q.bind(q.LINEAR,q.CLAMP_TO_EDGE),g.emissiveTex=Q,P.createColorAttachment(F,1),P.colorAttachment1.set(Q.texture)}else g.emissiveTex=void 0,P.removeColorAttachment(F,1);g.dirty=!0}_initFBOPool(){for(;this.pool.length{const N=this._style._mergedLayers[g],P=N.isHidden(this.painter.transform.zoom);return N.type==="hillshade"||N.type==="custom"?!P&&N.shouldRedrape():!P&&N.hasTransition()})}_clearLineLayersFromRenderCache(){let g=!1;for(const P of this._style.getSources())if(P instanceof Ad){g=!0;break}if(!g)return;const N={};for(let P=0;Pae>Q.end)||o.w("fill-extrusion with flood lighting and/or ground ambient occlusion should be moved to be on top of all draped layers.")}this._drapedRenderBatches=P}_setupRenderCache(g){const N=this.proxySourceCache;if(this._shouldDisableRenderCache()||this.invalidateRenderCache){if(this.invalidateRenderCache=!1,N.renderCache.length>N.renderCachePool.length){const G=Object.values(N.proxyCachedFBO);N.proxyCachedFBO={};for(let Q=0;Q=0;G--){const Q=P[G];if(N.getTileByID(Q.key),N.proxyCachedFBO[Q.key]!==void 0){const ae=g[Q.key],me=this.proxyToSource[Q.key];let ye=0;for(const Ae in me){const Te=me[Ae],Fe=ae[Ae];if(!Fe||Fe.length!==Te.length||Te.some((Ye,Ge)=>Ye!==Fe[Ge]||F[Ae]&&F[Ae].hasOwnProperty(Ye.key))){ye=-1;break}++ye}for(const Ae in N.proxyCachedFBO[Q.key])N.renderCache[N.proxyCachedFBO[Q.key][Ae]].dirty=ye<0||ye!==Object.values(ae).length}}const q=[...this._drapedRenderBatches];q.sort((G,Q)=>Q.end-Q.start-(G.end-G.start));for(const G of q)for(const Q of P){if(N.proxyCachedFBO[Q.key])continue;let ae=N.renderCachePool.pop();ae===void 0&&N.renderCache.length<50&&(ae=N.renderCache.length,N.renderCache.push(this._createFBO())),ae!==void 0&&(N.proxyCachedFBO[Q.key]={},N.proxyCachedFBO[Q.key][G.start]=ae,N.renderCache[ae].dirty=!0)}this._tilesDirty={}}_setupStencil(g,N,P,F){if(!F||!this._sourceTilesOverlap[F.id])return void(this._overlapStencilType&&(this._overlapStencilType=!1));const q=this.painter.context,G=q.gl;if(N.length<=1)return void(this._overlapStencilType=!1);let Q;if(P.isTileClipped())Q=N.length,this._overlapStencilMode.test={func:G.EQUAL,mask:255},this._overlapStencilType="Clip";else{if(!(N[0].overscaledZ>N[N.length-1].overscaledZ))return void(this._overlapStencilType=!1);Q=1,this._overlapStencilMode.test={func:G.GREATER,mask:255},this._overlapStencilType="Mask"}this._stencilRef+Q>255&&(q.clear({stencil:0}),this._stencilRef=0),this._stencilRef+=Q,this._overlapStencilMode.ref=this._stencilRef,P.isTileClipped()&&this._renderTileClippingMasks(N,this._overlapStencilMode.ref)}clipOrMaskOverlapStencilType(){return this._overlapStencilType==="Clip"||this._overlapStencilType==="Mask"}stencilModeForRTTOverlap(g){return this.renderingToTexture&&this._overlapStencilType?(this._overlapStencilType==="Clip"&&(this._overlapStencilMode.ref=this.painter._tileClippingMaskIDs[g.key]),this._overlapStencilMode):Gn.disabled}_renderTileClippingMasks(g,N){const P=this.painter,F=this.painter.context,q=F.gl;P._tileClippingMaskIDs={},F.setColorMode(zn.disabled),F.setDepthMode(Wr.disabled);const G=P.getOrCreateProgram("clippingMask");for(const Q of g){const ae=P._tileClippingMaskIDs[Q.key]=--N;G.draw(P,q.TRIANGLES,Wr.disabled,new Gn({func:q.ALWAYS,mask:0},ae,255,q.KEEP,q.KEEP,q.REPLACE),zn.disabled,_n.disabled,jw(Q.projMatrix),"$clipping",P.tileExtentBuffer,P.quadTriangleIndexBuffer,P.tileExtentSegments)}}pointCoordinate(g){const N=this.painter.transform;if(g.x<0||g.x>N.width||g.y<0||g.y>N.height)return null;const P=[g.x,g.y,1,1];o.aE(P,P,N.pixelMatrixInverse),o.cu(P,P,1/P[3]),P[0]/=N.worldSize,P[1]/=N.worldSize;const F=N._camera.position,q=o.bU(1,N.center.lat),G=[F[0],F[1],F[2]/q,0],Q=o.cV([],P.slice(0,3),G);o.ay(Q,Q);const ae=this.raycast(G,Q,this._exaggeration);return ae!==null&&ae?(o.bg(G,G,Q,ae),G[3]=G[2],G[2]*=q,G):null}_setupProxiedCoordsForOrtho(g,N,P){if(g.getSource()instanceof o.aV)return this._setupProxiedCoordsForImageSource(g,N,P);this._findCoveringTileCache[g.id]=this._findCoveringTileCache[g.id]||{};const F=this.proxiedCoords[g.id]=[],q=this.proxyCoords;for(let ae=0;aeye.overscaledZ-me.overscaledZ)}_setupProxiedCoordsForImageSource(g,N,P){if(!g.getSource().loaded())return;const F=this.proxiedCoords[g.id]=[],q=this.proxyCoords,G=g.getSource(),Q=G.tileID;if(!Q)return;const ae=new o.P(Q.x,Q.y)._div(1<(Ae.min.x=Math.min(Ae.min.x,Te.x-ae.x),Ae.min.y=Math.min(Ae.min.y,Te.y-ae.y),Ae.max.x=Math.max(Ae.max.x,Te.x-ae.x),Ae.max.y=Math.max(Ae.max.y,Te.y-ae.y),Ae),{min:new o.P(Number.MAX_VALUE,Number.MAX_VALUE),max:new o.P(-Number.MAX_VALUE,-Number.MAX_VALUE)}),ye=(Ae,Te)=>{const Fe=Ae.wrap+Ae.canonical.x/(1<dt+me.max.x||Ye+Gelt+me.max.y};for(let Ae=0;AeG.key===N.tileID.key);if(q)return q}if(N.tileID.key!==g.key){const q=g.canonical.z-N.tileID.canonical.z;let G,Q,ae;F=o.bb();const me=N.tileID.wrap-g.wrap<0?(G=o.an>>q,Q=G*((N.tileID.canonical.x<=Ae){const Te=g.canonical.z-Ae;N.getSource().reparseOverscaled?(Q=Math.max(g.canonical.z+2,N.transform.tileZoom),G=new o.aR(Q,g.wrap,Ae,g.canonical.x>>Te,g.canonical.y>>Te)):Te!==0&&(Q=Ae,G=new o.aR(Q,g.wrap,Ae,g.canonical.x>>Te,g.canonical.y>>Te))}G.key!==g.key&&(me.push(G.key),P=N.getTile(G))}const ye=Ae=>{me.forEach(Te=>{F[Te]=Ae}),me.length=0};for(Q-=1;Q>=ae&&(!P||!P.hasData());Q--){P&&ye(P.tileID.key);const Ae=G.calculateScaledKey(Q);if(P=N.getTileByID(Ae),P&&P.hasData())break;const Te=F[Ae];if(Te===null)break;Te===void 0?me.push(Ae):P=N.getTileByID(Te)}return ye(P?P.tileID.key:null),P&&P.hasData()?P:null}findDEMTileFor(g){return this.enabled?this._findTileCoveringTileID(g,this.sourceCache):null}prepareDrawTile(){this.renderedToTile=!0}_clearRenderCacheForTile(g,N){let P=this._tilesDirty[g];P||(P=this._tilesDirty[g]={}),P[N.key]=!0}}function rb(M,g,N){const P=function(Q,ae,me){const ye=o.bi(ae,Q),Ae=o.bi(me,[.2126,.7152,.0722]),Te=(Ye,Ge,dt)=>(1-dt)*Ye+dt*Ge,Fe=Te(1-.3*Math.min(Ae,1),1,Math.min(ye+1,1));return Te(.92,1,Math.asin(o.aC(ae[2],-1,1))/Math.PI+.5)*Fe}(M,[0,0,1],g),F=[0,0,0];o.bJ(F,N.slice(0,3),P);const q=[0,0,0];o.bJ(q,g.slice(0,3),M[2]);const G=[0,0,0];return o.cT(G,F,q),o.cW(G)}const x4=["fill","fillOutline","fillPattern","line","linePattern","background","backgroundPattern","hillshade","raster"],nb=["stars","rainParticle","snowParticle","fillExtrusion","fillExtrusionGroundEffect","building","buildingBloom","elevatedStructures","model","symbol"];class Wc{static cacheKey(g,N,P,F){const q=[N];F&&q.push(F.cacheKey);for(const G of P)(typeof G=="string"&&G.includes(" ")||g.usedDefines.has(G))&&q.push(G);return q.join("/")}constructor(g,N,P,F,q,G){const Q=g.gl;this.program=Q.createProgram(),this.configuration=F,this.name=N,this.fixedDefines=[...G];const ae=`#version 300 es ${(F?F.defines():[]).concat(G.map(Ge=>`#define ${Ge}`)).join(` `)}`,me=[ae,vv];for(const Ge of P.fragmentIncludes)me.push(gf[Ge]);me.push(P.fragmentSource);const ye=me.join(` `),Ae=[ae,o4];for(const Ge of P.vertexIncludes)Ae.push(gf[Ge]);this.forceManualRenderingForInstanceIDShaders=g.forceManualRenderingForInstanceIDShaders&&P.vertexSource.includes("gl_InstanceID"),this.forceManualRenderingForInstanceIDShaders&&Ae.push("uniform int u_instanceID;"),Ae.push(P.vertexSource);let Te=Ae.join(` `);this.forceManualRenderingForInstanceIDShaders&&(Te=Te.replaceAll("gl_InstanceID","u_instanceID"));const Fe=Q.createShader(Q.FRAGMENT_SHADER);if(Q.isContextLost())return void(this.failedToCreate=!0);Q.shaderSource(Fe,ye),Q.compileShader(Fe),Q.attachShader(this.program,Fe);const Ye=Q.createShader(Q.VERTEX_SHADER);Q.isContextLost()?this.failedToCreate=!0:(Q.shaderSource(Ye,Te),Q.compileShader(Ye),Q.attachShader(this.program,Ye),this.attributes={},Q.linkProgram(this.program),Q.deleteShader(Ye),Q.deleteShader(Fe),this.fixedUniforms=q(g),this.fixedUniformsEntries=Object.entries(this.fixedUniforms),this.binderUniforms=F?F.getUniforms(g):[],this.forceManualRenderingForInstanceIDShaders&&(this.instancingUniforms=(Ge=>({u_instanceID:new o.bX(Ge)}))(g)),(G.includes("TERRAIN")||G.includes("ELEVATED")||N.includes("symbol")||N.includes("circle"))&&(this.terrainUniforms=(Ge=>({u_dem:new o.bX(Ge),u_dem_prev:new o.bX(Ge),u_dem_tl:new o.b_(Ge),u_dem_scale:new o.bZ(Ge),u_dem_tl_prev:new o.b_(Ge),u_dem_scale_prev:new o.bZ(Ge),u_dem_size:new o.bZ(Ge),u_dem_lerp:new o.bZ(Ge),u_exaggeration:new o.bZ(Ge),u_depth:new o.bX(Ge),u_depth_size_inv:new o.b_(Ge),u_depth_range_unpack:new o.b_(Ge),u_occluder_half_size:new o.bZ(Ge),u_occlusion_depth_offset:new o.bZ(Ge),u_meter_to_dem:new o.bZ(Ge),u_label_plane_matrix_inv:new o.b$(Ge)}))(g)),G.includes("GLOBE")&&(this.globeUniforms=(Ge=>({u_tile_tl_up:new o.bY(Ge),u_tile_tr_up:new o.bY(Ge),u_tile_br_up:new o.bY(Ge),u_tile_bl_up:new o.bY(Ge),u_tile_up_scale:new o.bZ(Ge)}))(g)),G.includes("FOG")&&(this.fogUniforms=(Ge=>({u_fog_matrix:new o.b$(Ge),u_fog_range:new o.b_(Ge),u_fog_color:new o.cO(Ge),u_fog_horizon_blend:new o.bZ(Ge),u_fog_vertical_limit:new o.b_(Ge),u_fog_temporal_offset:new o.bZ(Ge),u_frustum_tl:new o.bY(Ge),u_frustum_tr:new o.bY(Ge),u_frustum_br:new o.bY(Ge),u_frustum_bl:new o.bY(Ge),u_globe_pos:new o.bY(Ge),u_globe_radius:new o.bZ(Ge),u_globe_transition:new o.bZ(Ge),u_is_globe:new o.bX(Ge),u_viewport:new o.b_(Ge)}))(g)),G.includes("RENDER_CUTOFF")&&(this.cutoffUniforms=(Ge=>({u_cutoff_params:new o.cO(Ge)}))(g)),G.includes("LIGHTING_3D_MODE")&&(this.lightsUniforms=(Ge=>({u_lighting_ambient_color:new o.bY(Ge),u_lighting_directional_dir:new o.bY(Ge),u_lighting_directional_color:new o.bY(Ge),u_ground_radiance:new o.bY(Ge)}))(g)),G.includes("RENDER_SHADOWS")&&(this.shadowUniforms=(Ge=>({u_light_matrix_0:new o.b$(Ge),u_light_matrix_1:new o.b$(Ge),u_fade_range:new o.b_(Ge),u_shadow_normal_offset:new o.bY(Ge),u_shadow_intensity:new o.bZ(Ge),u_shadow_texel_size:new o.bZ(Ge),u_shadow_map_resolution:new o.bZ(Ge),u_shadow_direction:new o.bY(Ge),u_shadow_bias:new o.bY(Ge),u_shadowmap_0:new o.bX(Ge),u_shadowmap_1:new o.bX(Ge)}))(g)))}getAttributeLocation(g,N){let P=this.attributes[N];return P===void 0&&(P=this.attributes[N]=g.getAttribLocation(this.program,N)),P}setTerrainUniformValues(g,N){if(!this.terrainUniforms)return;const P=this.terrainUniforms;if(!this.failedToCreate){g.program.set(this.program);for(const F in N)P[F]&&P[F].set(this.program,F,N[F])}}setGlobeUniformValues(g,N){if(!this.globeUniforms)return;const P=this.globeUniforms;if(!this.failedToCreate){g.program.set(this.program);for(const F in N)P[F]&&P[F].set(this.program,F,N[F])}}setFogUniformValues(g,N){if(!this.fogUniforms)return;const P=this.fogUniforms;if(!this.failedToCreate){g.program.set(this.program);for(const F in N)P[F].set(this.program,F,N[F])}}setCutoffUniformValues(g,N){if(!this.cutoffUniforms)return;const P=this.cutoffUniforms;if(!this.failedToCreate){g.program.set(this.program);for(const F in N)P[F].set(this.program,F,N[F])}}setLightsUniformValues(g,N){if(!this.lightsUniforms)return;const P=this.lightsUniforms;if(!this.failedToCreate){g.program.set(this.program);for(const F in N)P[F].set(this.program,F,N[F])}}setShadowUniformValues(g,N){if(this.failedToCreate||!this.shadowUniforms)return;const P=this.shadowUniforms;g.program.set(this.program);for(const F in N)P[F].set(this.program,F,N[F])}_drawDebugWireframe(g,N,P,F,q,G,Q,ae,me,ye){const Ae=g.options.wireframe;if(Ae.terrain===!1&&Ae.layers2D===!1&&Ae.layers3D===!1)return;const Te=g.context;if(!(!(!Ae.terrain||this.name!=="terrainRaster"&&this.name!=="globeRaster")||!(!Ae.layers2D||g._terrain&&g._terrain.renderingToTexture||!x4.includes(this.name))||!(!Ae.layers3D||!nb.includes(this.name))))return;const Fe=Te.gl,Ye=g.wireframeDebugCache.getLinesFromTrianglesBuffer(g.frameCounter,q,Te);if(!Ye)return;const Ge=[...this.fixedDefines,"DEBUG_WIREFRAME"],dt=g.getOrCreateProgram(this.name,{config:this.configuration,defines:Ge});Te.program.set(dt.program);const lt=(ht,Kt,Lt)=>{if(Kt[ht]&&Lt[ht])for(const Wt in Kt[ht])Lt[ht][Wt]&&Lt[ht][Wt].set(Lt.program,Wt,Kt[ht][Wt].current)};me&&me.setUniforms(dt.program,Te,dt.binderUniforms,Q,{zoom:ae}),lt("fixedUniforms",this,dt),lt("terrainUniforms",this,dt),lt("globeUniforms",this,dt),lt("fogUniforms",this,dt),lt("lightsUniforms",this,dt),lt("shadowUniforms",this,dt),Ye.bind(),Te.setColorMode(new zn([Fe.ONE,Fe.ONE_MINUS_SRC_ALPHA,Fe.ZERO,Fe.ONE],o.aq.transparent,[!0,!0,!0,!1])),Te.setDepthMode(new Wr(N.func===Fe.LESS?Fe.LEQUAL:N.func,Wr.ReadOnly,N.range)),Te.setStencilMode(Gn.disabled);const _t=3*G.primitiveLength*2,Ct=3*G.primitiveOffset*2*2;if(this.forceManualRenderingForInstanceIDShaders){const ht=ye||1;for(let Kt=0;Kt1?Fe.drawElementsInstanced(Fe.LINES,_t,Fe.UNSIGNED_SHORT,Ct,ye):Fe.drawElements(Fe.LINES,_t,Fe.UNSIGNED_SHORT,Ct);q.bind(),Te.program.set(this.program),Te.setDepthMode(N),Te.setStencilMode(P),Te.setColorMode(F)}checkUniforms(g,N,P){if(this.fixedDefines.includes(N)){for(const F of Object.keys(P))if(!P[F].initialized)throw new Error(`Program '${this.name}', from draw '${g}': uniform ${F} not set but required by ${N} being defined`)}}draw(g,N,P,F,q,G,Q,ae,me,ye,Ae,Te,Fe,Ye,Ge,dt){const lt=g.context,_t=lt.gl;if(this.failedToCreate)return;lt.program.set(this.program),lt.setDepthMode(P),lt.setStencilMode(F),lt.setColorMode(q),lt.setCullFace(G);for(const[Tt,It]of this.fixedUniformsEntries)It.set(this.program,Tt,Q[Tt]);Ye&&Ye.setUniforms(this.program,lt,this.binderUniforms,Te,{zoom:Fe});const Ct={[_t.POINTS]:1,[_t.LINES]:2,[_t.TRIANGLES]:3,[_t.LINE_STRIP]:1}[N];this.checkUniforms(ae,"RENDER_SHADOWS",this.shadowUniforms);const ht=Ge||[],Kt=Ye?Ye.getPaintVertexBuffers():[],Lt=N===_t.TRIANGLES&&ye,Wt=dt&&dt>0?1:void 0;for(const Tt of Ae.get()){const It=Tt.vaos||(Tt.vaos={});if((It[ae]||(It[ae]=new d4)).bind(lt,this,me,Kt,ye,Tt.vertexOffset,ht,Wt),this.forceManualRenderingForInstanceIDShaders){const Ut=dt||1;for(let rs=0;rs1?_t.drawElementsInstanced(N,Tt.primitiveLength*Ct,_t.UNSIGNED_SHORT,Tt.primitiveOffset*Ct*2,dt):ye?_t.drawElements(N,Tt.primitiveLength*Ct,_t.UNSIGNED_SHORT,Tt.primitiveOffset*Ct*2):_t.drawArrays(N,Tt.vertexOffset,Tt.vertexLength);Lt&&this._drawDebugWireframe(g,P,F,q,ye,Tt,Te,Fe,Ye,dt)}}}function hM(M,g,N=0){const P=Math.pow(2,g.tileID.overscaledZ),F=g.tileSize*Math.pow(2,M.transform.tileZoom)/P,q=F*(g.tileID.canonical.x+g.tileID.wrap*P),G=F*g.tileID.canonical.y;return{u_image:0,u_texsize:g.imageAtlasTexture?g.imageAtlasTexture.size:[0,0],u_tile_units_to_pixels:1/o.aA(g,1,M.transform.tileZoom),u_pixel_coord_upper:[q>>16,G>>16],u_pixel_coord_lower:[65535&q,65535&G],u_pattern_transition:N}}const zj={terrain:0,flat:1},$j=o.bb(),eh=(M,g,N,P,F,q,G,Q,ae,me,ye,Ae,Te,Fe,Ye,Ge,dt,lt,_t=[0,0,1])=>{const Ct=g.style.light,ht=Ct.properties.get("position"),Kt=[ht.x,ht.y,ht.z],Lt=o.dE();Ct.properties.get("anchor")==="viewport"&&(o.dF(Lt,-g.transform.angle),o.dG(Kt,Kt,Lt));const Wt=Ct.properties.get("color").toPremultipliedRenderColor(null),Tt=g.transform,It={u_matrix:M,u_lightpos:Kt,u_lightintensity:Ct.properties.get("intensity"),u_lightcolor:[Wt.r,Wt.g,Wt.b],u_vertical_gradient:+N,u_opacity:P,u_tile_id:[0,0,0],u_zoom_transition:0,u_inv_rot_matrix:$j,u_merc_center:[0,0],u_up_dir:[0,0,0],u_height_lift:0,u_height_type:zj[me],u_base_type:zj[ye],u_ao:F,u_edge_radius:q,u_width_scale:G,u_flood_light_color:Ye,u_vertical_scale:Ge,u_flood_light_intensity:dt,u_ground_shadow_factor:lt,u_front_cutoff_params:_t};return Tt.projection.name==="globe"&&(It.u_tile_id=[Q.canonical.x,Q.canonical.y,1<({u_matrix:M,u_edge_radius:g,u_width_scale:N,u_vertical_scale:P,u_height_type:zj[F],u_base_type:zj[q]}),Ma=(M,g,N,P,F,q,G,Q,ae,me,ye,Ae,Te,Fe,Ye,Ge,dt,lt)=>{const _t=eh(M,g,N,P,F,q,G,Q,me,ye,Ae,Te,Fe,Ye,Ge,dt,1,[0,0,0]),Ct={u_height_factor:-Math.pow(2,Q.overscaledZ)/ae.tileSize/8};return Object.assign(_t,hM(g,ae,lt),Ct)},kx=(M,g,N)=>({u_matrix:M,u_emissive_strength:g,u_ground_shadow_factor:N}),ab=(M,g,N,P,F,q=0)=>Object.assign(kx(M,g,F),hM(N,P,q)),y4=(M,g,N,P)=>({u_matrix:M,u_world:N,u_emissive_strength:g,u_ground_shadow_factor:P}),ib=(M,g,N,P,F,q,G=0)=>Object.assign(ab(M,g,N,P,q,G),{u_world:F}),ob=(M,g)=>({u_matrix:M,u_depth_bias:g}),kw=(M,g)=>({u_matrix:M,u_ground_shadow_factor:g}),Cv=(M,g,N,P,F)=>({u_matrix:M,u_camera_pos:[g[0],g[1],g[2]],u_depth_bias:N,u_height_scale:P,u_reset_depth:F}),Sw=(M,g,N)=>({u_image:M,u_opacity:g,u_blend_mode:N}),Sx=(M,g,N,P,F,q,G,Q,ae,me=[0,0,1])=>({u_matrix:M,u_normal_matrix:g,u_opacity:N,u_faux_facade_ao_intensity:P,u_camera_pos:F,u_tile_to_meter:q,u_facade_emissive_chance:G,u_flood_light_color:Q,u_flood_light_intensity:ae,u_front_cutoff_params:me}),Cw=M=>({u_matrix:M}),lb=M=>({u_matrix:M}),Uj=(M,g,N,P,F,q,G,Q)=>{const ae=o.an/q.tileSize;return{u_matrix:M,u_inv_rot_matrix:g,u_camera_to_center_distance:N.getCameraToCenterDistance(Q),u_extrude_scale:[N.pixelsToGLUnits[0]/ae,N.pixelsToGLUnits[1]/ae],u_zoom_transition:P,u_tile_id:G,u_merc_center:F}},jc=(M,g,N,P)=>({u_matrix:M,u_inv_matrix:g,u_camera_to_center_distance:N.getCameraToCenterDistance(P),u_viewport_size:[N.width,N.height]}),Yh=(M,g,N=1)=>({u_matrix:M,u_color:g,u_overlay:0,u_overlay_scale:N}),yf=o.bb(),qj=(M,g,N,P,F,q,G)=>{const Q=M.transform,ae=Q.projection.name==="globe",me=ae?o.dH(Q.zoom,g.canonical)*Q._pixelsPerMercatorPixel:o.aA(N,1,q),ye={u_matrix:g.projMatrix,u_extrude_scale:me,u_intensity:G,u_inv_rot_matrix:yf,u_merc_center:[0,0],u_tile_id:[0,0,0],u_zoom_transition:0,u_up_dir:[0,0,0]};if(ae){ye.u_inv_rot_matrix=P,ye.u_merc_center=F,ye.u_tile_id=[g.canonical.x,g.canonical.y,1<({u_matrix:g,u_normalize_matrix:N,u_globe_matrix:P,u_merc_matrix:F,u_grid_matrix:q,u_tl_parent:G,u_scale_parent:ye,u_fade_t:Ae.mix,u_opacity:Ae.opacity*Te.paint.get("raster-opacity"),u_image0:0,u_image1:1,u_brightness_low:Te.paint.get("raster-brightness-min"),u_brightness_high:Te.paint.get("raster-brightness-max"),u_saturation_factor:o.dJ(Te.paint.get("raster-saturation")),u_contrast_factor:o.dI(Te.paint.get("raster-contrast")),u_spin_weights:mM(Te.paint.get("raster-hue-rotate")),u_perspective_transform:Fe,u_raster_elevation:Ye,u_zoom_transition:Q,u_merc_center:ae,u_cutoff_params:me,u_colorization_mix:Vj(o.dK,dt,_t),u_colorization_offset:Om(o.dK,lt,_t),u_color_ramp:Ge,u_texture_offset:[ht/(Ct+2*ht),Ct/(Ct+2*ht)],u_texture_res:[Ct+2*ht,Ct+2*ht],u_emissive_strength:Kt,u_zbias_factor:Hj(M)});function mM(M){M*=Math.PI/180;const g=Math.sin(M),N=Math.cos(M);return[(2*N+1)/3,(-Math.sqrt(3)*g-N+1)/3,(Math.sqrt(3)*g-N+1)/3]}const $p=.05,fM=(M,g,N,P,F,q,G,Q,ae,me,ye,Ae)=>({u_matrix:M,u_normalize_matrix:g,u_globe_matrix:N,u_merc_matrix:P,u_grid_matrix:F,u_tl_parent:q,u_scale_parent:me,u_fade_t:ye.mix,u_opacity:ye.opacity,u_image0:0,u_image1:1,u_raster_elevation:Ae,u_zoom_transition:G,u_merc_center:Q,u_cutoff_params:ae}),pM=(M,g,N,P,F,q,G,Q,ae,me)=>({u_particle_texture:M,u_particle_texture_side_len:g,u_tile_offset:N,u_velocity:P,u_color_ramp:q,u_velocity_res:F,u_max_speed:G,u_uv_offset:Q,u_data_scale:[255*ae[0],255*ae[1]],u_data_offset:me,u_particle_pos_scale:1.1,u_particle_pos_offset:[$p,$p]}),v4=(M,g,N,P,F,q,G,Q,ae,me)=>({u_particle_texture:M,u_particle_texture_side_len:g,u_velocity:N,u_velocity_res:P,u_max_speed:F,u_speed_factor:q,u_reset_rate:G,u_rand_seed:Math.random(),u_uv_offset:Q,u_data_scale:[255*ae[0],255*ae[1]],u_data_offset:me,u_particle_pos_scale:1.1,u_particle_pos_offset:[$p,$p]}),Tw=o.bb(),Tv=(M,g,N,P,F,q,G,Q,ae,me,ye,Ae,Te,Fe,Ye,Ge,dt,lt,_t,Ct,ht,Kt,Lt,Wt)=>{const Tt=F.transform,It={u_is_size_zoom_constant:+(M==="constant"||M==="source"),u_is_size_feature_constant:+(M==="constant"||M==="camera"),u_size_t:g?g.uSizeT:0,u_size:g?g.uSize:0,u_camera_to_center_distance:Tt.getCameraToCenterDistance(_t),u_rotate_symbol:+N,u_aspect_ratio:Tt.width/Tt.height,u_fade_change:F.options.fadeDuration?F.symbolFadeChange:1,u_matrix:q,u_label_plane_matrix:G,u_coord_matrix:Q,u_is_text:+me,u_elevation_from_sea:ae?1:0,u_pitch_with_map:+P,u_texsize:ye,u_texsize_icon:Ae,u_texture:0,u_texture_icon:1,u_tile_id:[0,0,0],u_zoom_transition:0,u_inv_rot_matrix:Tw,u_merc_center:[0,0],u_camera_forward:[0,0,0],u_ecef_origin:[0,0,0],u_tile_matrix:Tw,u_up_vector:[0,-1,0],u_color_adj_mat:Kt,u_icon_transition:Lt||0,u_gamma_scale:P?F.transform.getCameraToCenterDistance(_t)*Math.cos(F.terrain?0:F.transform._pitch):1,u_device_pixel_ratio:o.o.devicePixelRatio,u_is_halo:1,u_scale_factor:Wt||1,u_ground_shadow_factor:Ct,u_inv_matrix:o.b7(o.bb(),G),u_normal_scale:ht,u_lutTexture:10,u_zoom:Tt.zoom-Math.floor(Tt.zoom),u_spp_fill_np_color:[0,0,0,1],u_spp_halo_np_color:[0,0,0,0],u_spp_opacity:1,u_spp_halo_width:0,u_spp_halo_blur:0,u_spp_emissive_strength:0,u_spp_occlusion_opacity:1,u_spp_z_offset:0,u_spp_translate_rotation:[1,0]};return _t.name==="globe"&&(It.u_tile_id=[Fe.canonical.x,Fe.canonical.y,1<({u_matrix:M,u_emissive_strength:g,u_opacity:N,u_color:P}),Up=(M,g,N,P,F,q,G,Q,ae)=>Object.assign(function(me,ye,Ae,Te,Fe,Ye){const{width:Ge,height:dt}=Te.imageManager.getPixelSize(ye),lt=Math.pow(2,Ye.tileID.overscaledZ),_t=Ye.tileSize*Math.pow(2,Te.transform.tileZoom)/lt,Ct=_t*(Ye.tileID.canonical.x+Ye.tileID.wrap*lt),ht=_t*Ye.tileID.canonical.y;return{u_image:0,u_pattern_tl:Ae.tl,u_pattern_br:Ae.br,u_texsize:[Ge,dt],u_pattern_size:Ae.displaySize,u_pattern_units_to_pixels:Fe?[Te.transform.width,-1*Te.transform.height]:[1/o.aA(Ye,1,Te.transform.tileZoom),1/o.aA(Ye,1,Te.transform.tileZoom)],u_pixel_coord_upper:[Ct>>16,ht>>16],u_pixel_coord_lower:[65535&Ct,65535&ht]}}(0,q,G,P,Q,ae),{u_matrix:M,u_emissive_strength:g,u_opacity:N}),Cx=new Float32Array(o.b9([])),qp=(M,g,N,P,F,q,G,Q,ae,me,ye,Ae,Te,Fe=[0,0,0],Ye,Ge,dt)=>{const lt=F.style.light,_t=lt.properties.get("position"),Ct=[-_t.x,-_t.y,_t.z],ht=o.dE();lt.properties.get("anchor")==="viewport"&&(o.dF(ht,-F.transform.angle),o.dG(Ct,Ct,ht));const Kt=ye.alphaMode==="MASK",Lt=lt.properties.get("color").toNonPremultipliedRenderColor(null),Wt=Te.paint.get("model-ambient-occlusion-intensity"),Tt=Te.paint.get("model-color").constantOr(o.aq.white).toNonPremultipliedRenderColor(null);return Tt.a=Te.paint.get("model-color-mix-intensity").constantOr(0),dt&&(Tt.r=dt[0],Tt.g=dt[1],Tt.b=dt[2],Tt.a=dt[3]),Ge&&(Tt.r=Ge.color.r,Tt.g=Ge.color.g,Tt.b=Ge.color.b,Tt.a=Ge.colorMix,Ae=Ge.emissionStrength,q*=Ge.opacity),{u_matrix:M,u_lighting_matrix:g,u_normal_matrix:N,u_node_matrix:P||Cx,u_lightpos:Ct,u_lightintensity:lt.properties.get("intensity"),u_lightcolor:[Lt.r,Lt.g,Lt.b],u_camera_pos:Fe,u_opacity:q,u_baseTextureIsAlpha:0,u_alphaMask:+Kt,u_alphaCutoff:ye.alphaCutoff,u_baseColorFactor:G.toNonPremultipliedRenderColor(null).toArray01(),u_emissiveFactor:Q.toNonPremultipliedRenderColor(null).toArray01(),u_metallicFactor:ae,u_roughnessFactor:me,u_baseColorTexture:5,u_metallicRoughnessTexture:6,u_normalTexture:7,u_occlusionTexture:8,u_emissionTexture:9,u_lutTexture:10,u_color_mix:Tt.toArray01(),u_aoIntensity:Wt,u_emissive_strength:Ae,u_occlusionTextureTransform:Ye||[0,0,0,0]}},Ew=(M,g=Cx,N=Cx)=>({u_matrix:M,u_instance:g,u_node_matrix:N}),cb={fillExtrusion:M=>({u_matrix:new o.b$(M),u_lightpos:new o.bY(M),u_lightintensity:new o.bZ(M),u_lightcolor:new o.bY(M),u_vertical_gradient:new o.bZ(M),u_opacity:new o.bZ(M),u_edge_radius:new o.bZ(M),u_width_scale:new o.bZ(M),u_ao:new o.b_(M),u_height_type:new o.bX(M),u_base_type:new o.bX(M),u_tile_id:new o.bY(M),u_zoom_transition:new o.bZ(M),u_inv_rot_matrix:new o.b$(M),u_merc_center:new o.b_(M),u_up_dir:new o.bY(M),u_height_lift:new o.bZ(M),u_flood_light_color:new o.bY(M),u_vertical_scale:new o.bZ(M),u_flood_light_intensity:new o.bZ(M),u_ground_shadow_factor:new o.bY(M),u_front_cutoff_params:new o.bY(M)}),fillExtrusionDepth:M=>({u_matrix:new o.b$(M),u_edge_radius:new o.bZ(M),u_width_scale:new o.bZ(M),u_vertical_scale:new o.bZ(M),u_height_type:new o.bX(M),u_base_type:new o.bX(M)}),fillExtrusionPattern:M=>({u_matrix:new o.b$(M),u_lightpos:new o.bY(M),u_lightintensity:new o.bZ(M),u_lightcolor:new o.bY(M),u_vertical_gradient:new o.bZ(M),u_height_factor:new o.bZ(M),u_edge_radius:new o.bZ(M),u_width_scale:new o.bZ(M),u_ao:new o.b_(M),u_height_type:new o.bX(M),u_base_type:new o.bX(M),u_tile_id:new o.bY(M),u_zoom_transition:new o.bZ(M),u_inv_rot_matrix:new o.b$(M),u_merc_center:new o.b_(M),u_up_dir:new o.bY(M),u_height_lift:new o.bZ(M),u_image:new o.bX(M),u_texsize:new o.b_(M),u_pixel_coord_upper:new o.b_(M),u_pixel_coord_lower:new o.b_(M),u_tile_units_to_pixels:new o.bZ(M),u_opacity:new o.bZ(M),u_pattern_transition:new o.bZ(M)}),fillExtrusionGroundEffect:M=>({u_matrix:new o.b$(M),u_opacity:new o.bZ(M),u_ao_pass:new o.bZ(M),u_meter_to_tile:new o.bZ(M),u_ao:new o.b_(M),u_flood_light_intensity:new o.bZ(M),u_flood_light_color:new o.bY(M),u_attenuation:new o.bZ(M),u_edge_radius:new o.bZ(M),u_fb:new o.bX(M),u_fb_size:new o.bZ(M),u_dynamic_offset:new o.bZ(M)}),fill:M=>({u_matrix:new o.b$(M),u_emissive_strength:new o.bZ(M),u_ground_shadow_factor:new o.bY(M)}),fillPattern:M=>({u_matrix:new o.b$(M),u_emissive_strength:new o.bZ(M),u_image:new o.bX(M),u_texsize:new o.b_(M),u_pixel_coord_upper:new o.b_(M),u_pixel_coord_lower:new o.b_(M),u_tile_units_to_pixels:new o.bZ(M),u_ground_shadow_factor:new o.bY(M),u_pattern_transition:new o.bZ(M)}),fillOutline:M=>({u_matrix:new o.b$(M),u_emissive_strength:new o.bZ(M),u_world:new o.b_(M),u_ground_shadow_factor:new o.bY(M)}),fillOutlinePattern:M=>({u_matrix:new o.b$(M),u_emissive_strength:new o.bZ(M),u_world:new o.b_(M),u_image:new o.bX(M),u_texsize:new o.b_(M),u_pixel_coord_upper:new o.b_(M),u_pixel_coord_lower:new o.b_(M),u_tile_units_to_pixels:new o.bZ(M),u_ground_shadow_factor:new o.bY(M),u_pattern_transition:new o.bZ(M)}),lineBlendComposite:M=>({u_image:new o.bX(M),u_opacity:new o.bZ(M),u_blend_mode:new o.bX(M)}),building:M=>({u_matrix:new o.b$(M),u_normal_matrix:new o.b$(M),u_opacity:new o.bZ(M),u_faux_facade_ao_intensity:new o.bZ(M),u_camera_pos:new o.bY(M),u_tile_to_meter:new o.bZ(M),u_facade_emissive_chance:new o.bZ(M),u_flood_light_color:new o.bY(M),u_flood_light_intensity:new o.bZ(M),u_front_cutoff_params:new o.bY(M)}),buildingBloom:M=>({u_matrix:new o.b$(M)}),buildingDepth:M=>({u_matrix:new o.b$(M)}),elevatedStructuresDepth:M=>({u_matrix:new o.b$(M),u_depth_bias:new o.bZ(M)}),elevatedStructures:M=>({u_matrix:new o.b$(M),u_ground_shadow_factor:new o.bY(M)}),elevatedStructuresDepthReconstruct:M=>({u_matrix:new o.b$(M),u_camera_pos:new o.bY(M),u_depth_bias:new o.bZ(M),u_height_scale:new o.bZ(M),u_reset_depth:new o.bZ(M)}),circle:o.dO,collisionBox:M=>({u_matrix:new o.b$(M),u_inv_rot_matrix:new o.b$(M),u_camera_to_center_distance:new o.bZ(M),u_extrude_scale:new o.b_(M),u_zoom_transition:new o.bZ(M),u_merc_center:new o.b_(M),u_tile_id:new o.bY(M)}),collisionCircle:M=>({u_matrix:new o.b$(M),u_inv_matrix:new o.b$(M),u_camera_to_center_distance:new o.bZ(M),u_viewport_size:new o.b_(M)}),debug:M=>({u_color:new o.dl(M),u_matrix:new o.b$(M),u_overlay:new o.bX(M),u_overlay_scale:new o.bZ(M)}),clippingMask:M=>({u_matrix:new o.b$(M)}),heatmap:M=>({u_extrude_scale:new o.bZ(M),u_intensity:new o.bZ(M),u_matrix:new o.b$(M),u_inv_rot_matrix:new o.b$(M),u_merc_center:new o.b_(M),u_tile_id:new o.bY(M),u_zoom_transition:new o.bZ(M),u_up_dir:new o.bY(M)}),heatmapTexture:M=>({u_image:new o.bX(M),u_color_ramp:new o.bX(M),u_opacity:new o.bZ(M)}),hillshade:M=>({u_matrix:new o.b$(M),u_image:new o.bX(M),u_latrange:new o.b_(M),u_light:new o.b_(M),u_shadow:new o.dl(M),u_highlight:new o.dl(M),u_emissive_strength:new o.bZ(M),u_accent:new o.dl(M)}),hillshadePrepare:M=>({u_matrix:new o.b$(M),u_image:new o.bX(M),u_dimension:new o.b_(M),u_zoom:new o.bZ(M)}),line:o.dN,linePattern:o.dM,raster:M=>({u_matrix:new o.b$(M),u_normalize_matrix:new o.b$(M),u_globe_matrix:new o.b$(M),u_merc_matrix:new o.b$(M),u_grid_matrix:new o.dm(M),u_tl_parent:new o.b_(M),u_scale_parent:new o.bZ(M),u_fade_t:new o.bZ(M),u_opacity:new o.bZ(M),u_image0:new o.bX(M),u_image1:new o.bX(M),u_brightness_low:new o.bZ(M),u_brightness_high:new o.bZ(M),u_saturation_factor:new o.bZ(M),u_contrast_factor:new o.bZ(M),u_spin_weights:new o.bY(M),u_perspective_transform:new o.b_(M),u_raster_elevation:new o.bZ(M),u_zoom_transition:new o.bZ(M),u_merc_center:new o.b_(M),u_cutoff_params:new o.cO(M),u_colorization_mix:new o.cO(M),u_colorization_offset:new o.bZ(M),u_color_ramp:new o.bX(M),u_texture_offset:new o.b_(M),u_texture_res:new o.b_(M),u_emissive_strength:new o.bZ(M),u_zbias_factor:new o.bZ(M)}),rasterParticle:M=>({u_matrix:new o.b$(M),u_normalize_matrix:new o.b$(M),u_globe_matrix:new o.b$(M),u_merc_matrix:new o.b$(M),u_grid_matrix:new o.dm(M),u_tl_parent:new o.b_(M),u_scale_parent:new o.bZ(M),u_fade_t:new o.bZ(M),u_opacity:new o.bZ(M),u_image0:new o.bX(M),u_image1:new o.bX(M),u_raster_elevation:new o.bZ(M),u_zoom_transition:new o.bZ(M),u_merc_center:new o.b_(M),u_cutoff_params:new o.cO(M)}),rasterParticleTexture:M=>({u_texture:new o.bX(M),u_opacity:new o.bZ(M)}),rasterParticleDraw:M=>({u_particle_texture:new o.bX(M),u_particle_texture_side_len:new o.bZ(M),u_tile_offset:new o.b_(M),u_velocity:new o.bX(M),u_color_ramp:new o.bX(M),u_velocity_res:new o.b_(M),u_max_speed:new o.bZ(M),u_uv_offset:new o.b_(M),u_data_scale:new o.b_(M),u_data_offset:new o.bZ(M),u_particle_pos_scale:new o.bZ(M),u_particle_pos_offset:new o.b_(M)}),rasterParticleUpdate:M=>({u_particle_texture:new o.bX(M),u_particle_texture_side_len:new o.bZ(M),u_velocity:new o.bX(M),u_velocity_res:new o.b_(M),u_max_speed:new o.bZ(M),u_speed_factor:new o.bZ(M),u_reset_rate:new o.bZ(M),u_rand_seed:new o.bZ(M),u_uv_offset:new o.b_(M),u_data_scale:new o.b_(M),u_data_offset:new o.bZ(M),u_particle_pos_scale:new o.bZ(M),u_particle_pos_offset:new o.b_(M)}),symbol:M=>({u_is_size_zoom_constant:new o.bX(M),u_is_size_feature_constant:new o.bX(M),u_size_t:new o.bZ(M),u_size:new o.bZ(M),u_camera_to_center_distance:new o.bZ(M),u_rotate_symbol:new o.bX(M),u_aspect_ratio:new o.bZ(M),u_fade_change:new o.bZ(M),u_matrix:new o.b$(M),u_label_plane_matrix:new o.b$(M),u_coord_matrix:new o.b$(M),u_is_text:new o.bX(M),u_elevation_from_sea:new o.bX(M),u_pitch_with_map:new o.bX(M),u_texsize:new o.b_(M),u_texsize_icon:new o.b_(M),u_texture:new o.bX(M),u_texture_icon:new o.bX(M),u_gamma_scale:new o.bZ(M),u_device_pixel_ratio:new o.bZ(M),u_tile_id:new o.bY(M),u_zoom_transition:new o.bZ(M),u_inv_rot_matrix:new o.b$(M),u_merc_center:new o.b_(M),u_camera_forward:new o.bY(M),u_tile_matrix:new o.b$(M),u_up_vector:new o.bY(M),u_ecef_origin:new o.bY(M),u_is_halo:new o.bX(M),u_icon_transition:new o.bZ(M),u_color_adj_mat:new o.b$(M),u_scale_factor:new o.bZ(M),u_ground_shadow_factor:new o.bY(M),u_inv_matrix:new o.b$(M),u_normal_scale:new o.bZ(M),u_lutTexture:new o.bX(M),u_zoom:new o.bZ(M),u_spp_fill_np_color:new o.cO(M),u_spp_halo_np_color:new o.cO(M),u_spp_opacity:new o.bZ(M),u_spp_halo_width:new o.bZ(M),u_spp_halo_blur:new o.bZ(M),u_spp_emissive_strength:new o.bZ(M),u_spp_occlusion_opacity:new o.bZ(M),u_spp_z_offset:new o.bZ(M),u_spp_translate_rotation:new o.b_(M)}),background:M=>({u_matrix:new o.b$(M),u_emissive_strength:new o.bZ(M),u_opacity:new o.bZ(M),u_color:new o.dl(M)}),backgroundPattern:M=>({u_matrix:new o.b$(M),u_emissive_strength:new o.bZ(M),u_opacity:new o.bZ(M),u_image:new o.bX(M),u_pattern_tl:new o.b_(M),u_pattern_br:new o.b_(M),u_texsize:new o.b_(M),u_pattern_size:new o.b_(M),u_pixel_coord_upper:new o.b_(M),u_pixel_coord_lower:new o.b_(M),u_pattern_units_to_pixels:new o.b_(M)}),terrainRaster:M=>({u_matrix:new o.b$(M),u_image0:new o.bX(M),u_image1:new o.bX(M),u_skirt_height:new o.bZ(M),u_ground_shadow_factor:new o.bY(M),u_emissive_texture_available:new o.bZ(M)}),skybox:M=>({u_matrix:new o.b$(M),u_sun_direction:new o.bY(M),u_cubemap:new o.bX(M),u_opacity:new o.bZ(M),u_temporal_offset:new o.bZ(M)}),skyboxGradient:M=>({u_matrix:new o.b$(M),u_color_ramp:new o.bX(M),u_center_direction:new o.bY(M),u_radius:new o.bZ(M),u_opacity:new o.bZ(M),u_temporal_offset:new o.bZ(M)}),skyboxCapture:M=>({u_matrix_3f:new o.dm(M),u_sun_direction:new o.bY(M),u_sun_intensity:new o.bZ(M),u_color_tint_r:new o.cO(M),u_color_tint_m:new o.cO(M),u_luminance:new o.bZ(M)}),globeRaster:M=>({u_proj_matrix:new o.b$(M),u_globe_matrix:new o.b$(M),u_normalize_matrix:new o.b$(M),u_merc_matrix:new o.b$(M),u_zoom_transition:new o.bZ(M),u_merc_center:new o.b_(M),u_image0:new o.bX(M),u_image1:new o.bX(M),u_grid_matrix:new o.dm(M),u_skirt_height:new o.bZ(M),u_far_z_cutoff:new o.bZ(M),u_frustum_tl:new o.bY(M),u_frustum_tr:new o.bY(M),u_frustum_br:new o.bY(M),u_frustum_bl:new o.bY(M),u_globe_pos:new o.bY(M),u_globe_radius:new o.bZ(M),u_viewport:new o.b_(M),u_emissive_texture_available:new o.bZ(M)}),globeAtmosphere:M=>({u_frustum_tl:new o.bY(M),u_frustum_tr:new o.bY(M),u_frustum_br:new o.bY(M),u_frustum_bl:new o.bY(M),u_horizon:new o.bZ(M),u_transition:new o.bZ(M),u_fadeout_range:new o.bZ(M),u_atmosphere_fog_color:new o.cO(M),u_high_color:new o.cO(M),u_space_color:new o.cO(M),u_temporal_offset:new o.bZ(M),u_horizon_angle:new o.bZ(M)}),model:M=>({u_matrix:new o.b$(M),u_lighting_matrix:new o.b$(M),u_normal_matrix:new o.b$(M),u_node_matrix:new o.b$(M),u_lightpos:new o.bY(M),u_lightintensity:new o.bZ(M),u_lightcolor:new o.bY(M),u_camera_pos:new o.bY(M),u_opacity:new o.bZ(M),u_baseColorFactor:new o.cO(M),u_emissiveFactor:new o.cO(M),u_metallicFactor:new o.bZ(M),u_roughnessFactor:new o.bZ(M),u_baseTextureIsAlpha:new o.bX(M),u_alphaMask:new o.bX(M),u_alphaCutoff:new o.bZ(M),u_baseColorTexture:new o.bX(M),u_metallicRoughnessTexture:new o.bX(M),u_normalTexture:new o.bX(M),u_occlusionTexture:new o.bX(M),u_emissionTexture:new o.bX(M),u_lutTexture:new o.bX(M),u_color_mix:new o.cO(M),u_aoIntensity:new o.bZ(M),u_emissive_strength:new o.bZ(M),u_occlusionTextureTransform:new o.cO(M)}),modelDepth:M=>({u_matrix:new o.b$(M),u_instance:new o.b$(M),u_node_matrix:new o.b$(M)}),groundShadow:M=>({u_matrix:new o.b$(M),u_ground_shadow_factor:new o.bY(M)}),stars:M=>({u_matrix:new o.b$(M),u_up:new o.bY(M),u_right:new o.bY(M),u_intensity_multiplier:new o.bZ(M)}),snowParticle:M=>({u_modelview:new o.b$(M),u_projection:new o.b$(M),u_time:new o.bZ(M),u_cam_pos:new o.bY(M),u_velocityConeAperture:new o.bZ(M),u_velocity:new o.bZ(M),u_horizontalOscillationRadius:new o.bZ(M),u_horizontalOscillationRate:new o.bZ(M),u_boxSize:new o.bZ(M),u_billboardSize:new o.bZ(M),u_simpleShapeParameters:new o.b_(M),u_screenSize:new o.b_(M),u_thinningCenterPos:new o.b_(M),u_thinningShape:new o.bY(M),u_thinningAffectedRatio:new o.bZ(M),u_thinningParticleOffset:new o.bZ(M),u_particleColor:new o.cO(M),u_direction:new o.bY(M)}),rainParticle:M=>({u_modelview:new o.b$(M),u_projection:new o.b$(M),u_time:new o.bZ(M),u_cam_pos:new o.bY(M),u_texScreen:new o.bX(M),u_velocityConeAperture:new o.bZ(M),u_velocity:new o.bZ(M),u_boxSize:new o.bZ(M),u_rainDropletSize:new o.b_(M),u_distortionStrength:new o.bZ(M),u_rainDirection:new o.bY(M),u_color:new o.cO(M),u_screenSize:new o.b_(M),u_thinningCenterPos:new o.b_(M),u_thinningShape:new o.bY(M),u_thinningAffectedRatio:new o.bZ(M),u_thinningParticleOffset:new o.bZ(M),u_shapeDirectionalPower:new o.bZ(M),u_shapeNormalPower:new o.bZ(M),u_mode:new o.bZ(M)}),vignette:M=>({u_vignetteShape:new o.bY(M),u_vignetteColor:new o.cO(M)}),occlusion:M=>({u_matrix:new o.b$(M),u_anchorPos:new o.bY(M),u_screenSizePx:new o.b_(M),u_occluderSizePx:new o.b_(M),u_color:new o.cO(M)})};class vf{constructor(g,N,P,F){this.id=vf.uniqueIdxCounter,vf.uniqueIdxCounter++,this.context=g;const q=g.gl;this.buffer=q.createBuffer(),this.dynamicDraw=!!P,this.context.unbindVAO(),g.bindElementBuffer.set(this.buffer),q.bufferData(q.ELEMENT_ARRAY_BUFFER,N.arrayBuffer,this.dynamicDraw?q.DYNAMIC_DRAW:q.STATIC_DRAW),this.dynamicDraw||F||N.destroy()}bind(){this.context.bindElementBuffer.set(this.buffer)}updateData(g){this.id=vf.uniqueIdxCounter,vf.uniqueIdxCounter++;const N=this.context.gl;this.context.unbindVAO(),this.bind(),N.bufferSubData(N.ELEMENT_ARRAY_BUFFER,0,g.arrayBuffer)}destroy(){this.buffer&&(this.context.gl.deleteBuffer(this.buffer),delete this.buffer)}}vf.uniqueIdxCounter=0;const Gj={Int8:"BYTE",Uint8:"UNSIGNED_BYTE",Int16:"SHORT",Uint16:"UNSIGNED_SHORT",Int32:"INT",Uint32:"UNSIGNED_INT",Float32:"FLOAT"};class Wj{constructor(g,N,P,F,q,G){this.length=N.length,this.attributes=P,this.itemSize=N.bytesPerElement,this.dynamicDraw=F,this.instanceCount=G,this.context=g;const Q=g.gl;this.buffer=Q.createBuffer(),g.bindVertexBuffer.set(this.buffer),Q.bufferData(Q.ARRAY_BUFFER,N.arrayBuffer,this.dynamicDraw?Q.DYNAMIC_DRAW:Q.STATIC_DRAW),this.dynamicDraw||q||N.destroy()}bind(){this.context.bindVertexBuffer.set(this.buffer)}updateData(g){const N=this.context.gl;this.bind(),N.bufferSubData(N.ARRAY_BUFFER,0,g.arrayBuffer)}enableAttributes(g,N){for(const P of this.attributes){const F=N.getAttributeLocation(g,P.name);F!==-1&&g.enableVertexAttribArray(F)}}setVertexAttribPointers(g,N,P){for(const F of this.attributes){const q=N.getAttributeLocation(g,F.name);if(q!==-1){const G=F.offset+this.itemSize*(P||0);F.type==="Float32"?g.vertexAttribPointer(q,F.components,g.FLOAT,!1,this.itemSize,G):g.vertexAttribIPointer(q,F.components,g[Gj[F.type]],this.itemSize,G)}}}setVertexAttribDivisor(g,N,P){for(let F=0;F0&&g.vertexAttribDivisor(q,P)}}destroy(){this.buffer&&(this.context.gl.deleteBuffer(this.buffer),delete this.buffer)}}class Aw{constructor(g,N,P,F,q){this.context=g,this.width=N,this.height=P;const G=this.framebuffer=g.gl.createFramebuffer();F>0&&(this.colorAttachment0=new jv(g,G,0)),F>1&&(this.colorAttachment1=new jv(g,G,1)),q&&(this.depthAttachmentType=q,this.depthAttachment=q==="renderbuffer"?new ww(g,G):new Bj(g,G))}static createWithTexture(g,N,P,F,q){const G=g.gl;if(g.activeTexture.set(G.TEXTURE1),g.viewport.set([0,0,P,F]),N&&N.width===P&&N.height===F)return G.bindTexture(G.TEXTURE_2D,N.colorAttachment0.get()),g.bindFramebuffer.set(N.framebuffer),N;N&&N.destroy();const Q=new o.T(g,{width:P,height:F,data:null},g.extRenderToTextureHalfFloat?g.gl.RGBA16F:g.gl.RGBA8);Q.bind(G.LINEAR,G.CLAMP_TO_EDGE);const ae=g.createFramebuffer(P,F,1,null);if(ae.colorAttachment0.set(Q.texture),q){const me=g.createRenderbuffer(G.DEPTH24_STENCIL8,P,F);g.bindFramebuffer.set(ae.framebuffer),G.framebufferRenderbuffer(G.FRAMEBUFFER,G.DEPTH_STENCIL_ATTACHMENT,G.RENDERBUFFER,me),ae._stencilRbo=me}return ae}createColorAttachment(g,N){N===0?this.colorAttachment0=new jv(g,this.framebuffer,0):N===1&&(this.colorAttachment1=new jv(g,this.framebuffer,1))}removeColorAttachment(g,N){const P=this.context.gl;let F;N===0?(F=this.colorAttachment0.get(),this.colorAttachment0=void 0):N===1&&(F=this.colorAttachment1.get(),this.colorAttachment1=void 0),F&&P.deleteTexture(F)}destroy(){const g=this.context.gl;if(this.colorAttachment0){const N=this.colorAttachment0.get();N&&g.deleteTexture(N)}if(this.colorAttachment1){const N=this.colorAttachment1.get();N&&g.deleteTexture(N)}if(this.depthAttachment&&this.depthAttachmentType)if(this.depthAttachmentType==="renderbuffer"){const N=this.depthAttachment.get();N&&g.deleteRenderbuffer(N)}else{const N=this.depthAttachment.get();N&&g.deleteTexture(N)}this._stencilRbo&&(g.deleteRenderbuffer(this._stencilRbo),this._stencilRbo=null),g.deleteFramebuffer(this.framebuffer)}}class Tx{constructor(g,N){this.gl=g,this.clearColor=new fw(this),this.clearDepth=new lD(this),this.clearStencil=new Lj(this),this.colorMask=new cD(this),this.depthMask=new ap(this),this.stencilMask=new pw(this),this.stencilFunc=new bv(this),this.stencilOp=new Dj(this),this.stencilTest=new Y0(this),this.depthRange=new Z0(this),this.depthTest=new X0(this),this.depthFunc=new Wh(this),this.blend=new Rj(this),this.blendFunc=new gw(this),this.blendColor=new lM(this),this.blendEquation=new _v(this),this.cullFace=new xw(this),this.cullFaceSide=new yw(this),this.frontFace=new Oj(this),this.program=new vw(this),this.activeTexture=new bw(this),this.viewport=new Kh(this),this.bindFramebuffer=new jh(this),this.bindRenderbuffer=new m4(this),this.bindTexture=new wv(this),this.bindVertexBuffer=new f4(this),this.bindElementBuffer=new cM(this),this.bindVertexArrayOES=new dM(this),this.pixelStoreUnpack=new p4(this),this.pixelStoreUnpackPremultiplyAlpha=new Fj(this),this.pixelStoreUnpackFlipY=new _w(this),this.options=N?Object.assign({},N):{},this.options.extTextureFilterAnisotropicForceOff||(this.extTextureFilterAnisotropic=g.getExtension("EXT_texture_filter_anisotropic")||g.getExtension("MOZ_EXT_texture_filter_anisotropic")||g.getExtension("WEBKIT_EXT_texture_filter_anisotropic"),this.extTextureFilterAnisotropic&&(this.extTextureFilterAnisotropicMax=g.getParameter(this.extTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT))),this.extDebugRendererInfo=g.getExtension("WEBGL_debug_renderer_info"),this.extDebugRendererInfo&&(this.renderer=g.getParameter(this.extDebugRendererInfo.UNMASKED_RENDERER_WEBGL),this.vendor=g.getParameter(this.extDebugRendererInfo.UNMASKED_VENDOR_WEBGL)),this.forceManualRenderingForInstanceIDShaders=N&&!!N.forceManualRenderingForInstanceIDShaders||this.renderer&&this.renderer.indexOf("PowerVR")!==-1,this.disableSymbolUBO=N&&!!N.forceDisableSymbolUBO,this.options.extTextureFloatLinearForceOff||(this.extTextureFloatLinear=g.getExtension("OES_texture_float_linear")),this.extRenderToTextureHalfFloat=g.getExtension("EXT_color_buffer_half_float"),this.extTimerQuery=g.getExtension("EXT_disjoint_timer_query_webgl2"),this.maxTextureSize=g.getParameter(g.MAX_TEXTURE_SIZE),this.maxUniformBlockSize=Math.min(g.getParameter(g.MAX_UNIFORM_BLOCK_SIZE),32768),this.maxUniformBufferBindings=g.getParameter(g.MAX_UNIFORM_BUFFER_BINDINGS),this.extBlendFuncExtended=g.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(g,N,P){return new vf(this,g,N,P)}createVertexBuffer(g,N,P,F,q){return new Wj(this,g,N,P,F,q)}createRenderbuffer(g,N,P){const F=this.gl,q=F.createRenderbuffer();return this.bindRenderbuffer.set(q),F.renderbufferStorage(F.RENDERBUFFER,g,N,P),this.bindRenderbuffer.set(null),q}createFramebuffer(g,N,P,F){return new Aw(this,g,N,P,F)}clear({color:g,depth:N,stencil:P,colorMask:F}){const q=this.gl;let G=0;g&&(G|=q.COLOR_BUFFER_BIT,this.clearColor.set(g.toNonPremultipliedRenderColor(null)),this.colorMask.set(F||[!0,!0,!0,!0])),N!==void 0&&(G|=q.DEPTH_BUFFER_BIT,this.depthRange.set([0,1]),this.clearDepth.set(N),this.depthMask.set(!0)),P!==void 0&&(G|=q.STENCIL_BUFFER_BIT,this.clearStencil.set(P),this.stencilMask.set(255)),q.clear(G)}setCullFace(g){g.enable===!1?this.cullFace.set(!1):(this.cullFace.set(!0),this.cullFaceSide.set(g.mode),this.frontFace.set(g.frontFace))}setDepthMode(g){g.func!==this.gl.ALWAYS||g.mask?(this.depthTest.set(!0),this.depthFunc.set(g.func),this.depthMask.set(g.mask),this.depthRange.set(g.range)):this.depthTest.set(!1)}setStencilMode(g){g.test.func!==this.gl.ALWAYS||g.mask?(this.stencilTest.set(!0),this.stencilMask.set(g.mask),this.stencilOp.set([g.fail,g.depthFail,g.pass]),this.stencilFunc.set({func:g.test.func,ref:g.ref,mask:g.test.mask})):this.stencilTest.set(!1)}setColorMode(g){o.b6(g.blendFunction,zn.Replace)?this.blend.set(!1):(this.blend.set(!0),this.blendFunc.set(g.blendFunction),this.blendColor.set(g.blendColor),g.blendEquation?this.blendEquation.set(g.blendEquation):this.blendEquation.setDefault()),this.colorMask.set(g.mask)}unbindVAO(){this.bindVertexArrayOES.set(null)}}let Ex;function Pr(M,g,N,P,F,q,G){const Q=M.context,ae=Q.gl,me=M.transform,ye=[o.aH(me.center.lng),o.aL(me.center.lat)],Ae=N.layout.get("symbol-placement"),Te=N.layout.get("text-variable-anchor"),Fe=N.layout.get("icon-rotation-alignment")==="map",Ye=N.layout.get("text-rotation-alignment")==="map",Ge=Ae!=="point",dt=[];let lt=0,_t=0;for(let Tt=0;Tt0){const dn=o.bb(),Kr=mr;o.cz(dn,rs.placementInvProjMatrix,me.glCoordMatrix),o.cz(dn,dn,rs.placementViewportMatrix),dt.push({circleArray:Js,circleOffset:_t,transform:Kr,invTransform:dn,projection:rs.getProjection()}),lt+=Js.length/4,_t=lt}if(!fr)continue;M.terrain&&M.terrain.setupElevationDraw(Ut,wr);const en=Ts?[It.canonical.x,It.canonical.y,1<=0&&(Fe[Ct.associatedIconIndex]={x:Zt,y:ks,z:ms,angle:ws})}else Ja(Lt,Ae)}if(me){Te.clear();const _t=M.icon.placedSymbolArray;for(let Ct=0;Ct<_t.length;Ct++){const ht=_t.get(Ct),{numGlyphs:Kt}=ht,Lt=Fe[Ct];if(ht.hidden||!Lt)Ja(Kt,Te);else{const{x:Wt,y:Tt,z:It,angle:Ut}=Lt;for(let rs=0;rs{let ma=[0,0,0];if(Pi){const Yo=M.style.directionalLight,ho=M.style.ambientLight;Yo&&ho&&(ma=pf(M.style,Yo,ho))}return ma},Oa=Pi=>{if(M.context.disableSymbolUBO)return;Pi.push("USE_PAINT_PROPERTIES_UBO");const ma=Math.floor(M.context.maxUniformBlockSize/4),Yo=Math.floor(ma/4);Pi.push(`MAX_UBO_SIZE_VEC4 ${Yo}u`)},na=Pi=>{It.depthOcclusionForSymbolsAndCircles&&(N.hasOcclusionOpacityProperties||M.terrain)&&(Pi.push("DEPTH_D24"),Pi.push("DEPTH_OCCLUSION"))},ji=Pi=>{N.lut&&!Lt&&(N.lut.texture||(N.lut.texture=new o.dR(M.context,N.lut.image,[N.lut.image.height,N.lut.image.height,N.lut.image.height],Wt.gl.RGBA8)),Wt.activeTexture.set(Wt.gl.TEXTURE0+10),N.lut.texture&&N.lut.texture.bind(Wt.gl.LINEAR,Wt.gl.CLAMP_TO_EDGE),Pi.push("APPLY_LUT_ON_GPU"))},uo=()=>{const Pi=Ut&&N.layout.get("symbol-placement")!=="point",ma=[];na(ma),ji(ma);const Yo=Pi||oa,ho=Js.elevationType==="road",cc=M.shadowRenderer,ei=ho&&Zt&&!!cc&&cc.enabled,_o=Ln(ei),Ic=ho&&Zt&&!M.terrain?as:sr,rh=N.paint.get("icon-image-cross-fade");M.terrainRenderModeElevated()&&Zt&&ma.push("PITCH_WITH_MAP_TERRAIN"),en&&(ma.push("PROJECTION_GLOBE_VIEW"),Yo&&ma.push("PROJECTED_POS_ON_VIEWPORT")),rh>0&&Js.hasAnySecondaryIcon&&ma.push("ICON_TRANSITION"),!Js.icon.zOffsetVertexBuffer||ho&&M.terrain||ma.push("Z_OFFSET"),lt===0&&_t===0&&Ct===0&&ht===1||ma.push("COLOR_ADJUSTMENT"),Js.sdfIcons&&ma.push("RENDER_SDF"),ei&&ma.push("RENDER_SHADOWS","NORMAL_OFFSET"),ho&&Zt&&!M.terrain&&Js.icon.orientationVertexBuffer&&ma.push("ELEVATED_ROADS"),Oa(ma);const Zc=Wt.disableSymbolUBO?Js.icon.programConfigurations.get(N.id):null,eu=M.getOrCreateProgram("symbol",{config:Zc,defines:ma}),lp=fr.imageAtlasTexture?fr.imageAtlasTexture.size:[0,0],Vi=Js.iconSizeData,Wp=o.bj(Vi,It.zoom),Kp=Zt||!It.isOrthographic,Eo=fd(Kr,fr.tileID.canonical,Zt,Ut,It,Js.getProjection(),Jr),Do=Am(Kr,fr.tileID.canonical,Zt,Ut,It,Js.getProjection(),Jr),so=Js.icon.uboBinder&&Js.icon.uboBinder.cachedHeader&&256&Js.icon.uboBinder.cachedHeader.dataDrivenMask?[0,0]:Q,sc=M.translatePosMatrix(Do,fr,so,me,!0),Ch=M.translatePosMatrix(Kr,fr,so,me),Ml=Yo?lo:Eo,cp=Ut&&!Zt&&!Pi;let gb=wr;!Ts&&!It.mercatorFromTransition||Ut||(gb=tc(It));const Uw=en?gb:wr,qw=N.getColorAdjustmentMatrix(lt,_t,Ct,ht),rN=Tv(Vi.kind,Wp,cp,Zt,M,Ch,Ml,sc,Kt,!1,lp,[0,0],0,mr,dn,Xt,ra,Uw,Js.getProjection(),_o,Ra,qw,rh,null),Lv=fr.imageAtlasTexture?fr.imageAtlasTexture:null,iy=N.layout.get("icon-size").constantOr(0)!==1||Js.iconsNeedLinear,nN=Js.sdfIcons||M.options.rotating||M.options.zooming||iy||Kp?Tt.LINEAR:Tt.NEAREST,Nf=Js.sdfIcons&&N.paint.get("icon-halo-width").constantOr(1)!==0,xb=M.terrain&&Zt&&Pi?o.b7(o.bb(),Eo):lo;if(Pi&&Js.icon){const yb=o.bu.getAtTileOffsetFunc(mr,It.center.lat,It.worldSize,Js.getProjection()),vb=_c(Kr,fr.tileID.canonical,Zt,Ut,It,Js.getProjection(),Jr),AM=N.layout.get("icon-size-scale-range"),aN=o.aC(M.scaleFactor,AM[0],AM[1]);Mt(Js,Kr,M,!1,vb,Do,Zt,Ge,yb,mr,aN)}return{program:eu,buffers:Js.icon,uniformValues:rN,atlasTexture:Lv,atlasTextureIcon:null,atlasInterpolation:nN,atlasInterpolationIcon:null,isSDF:Js.sdfIcons,hasHalo:Nf,depthMode:Ic,tile:fr,renderWithShadows:ei,labelPlaneMatrixInv:xb}},rl=()=>{const Pi=rs&&N.layout.get("symbol-placement")!=="point",ma=[],Yo=Pi||ws||oa,ho=Js.elevationType==="road",cc=M.shadowRenderer,ei=ho&&ks&&!!cc&&cc.enabled,_o=Ln(ei),Ic=ho&&ks&&!M.terrain?as:sr;M.terrainRenderModeElevated()&&ks&&ma.push("PITCH_WITH_MAP_TERRAIN"),en&&(ma.push("PROJECTION_GLOBE_VIEW"),Yo&&ma.push("PROJECTED_POS_ON_VIEWPORT")),!Js.text.zOffsetVertexBuffer||ho&&M.terrain||ma.push("Z_OFFSET"),Js.iconsInText&&ma.push("RENDER_TEXT_AND_SYMBOL"),ma.push("RENDER_SDF"),ei&&ma.push("RENDER_SHADOWS","NORMAL_OFFSET"),ho&&ks&&!M.terrain&&Js.text.orientationVertexBuffer&&ma.push("ELEVATED_ROADS"),na(ma),Oa(ma);const rh=Wt.disableSymbolUBO?Js.text.programConfigurations.get(N.id):null,Zc=M.getOrCreateProgram("symbol",{config:rh,defines:ma});let eu,lp=[0,0],Vi=null;const Wp=Js.textSizeData;Js.iconsInText&&(lp=fr.imageAtlasTexture?fr.imageAtlasTexture.size:[0,0],Vi=fr.imageAtlasTexture?fr.imageAtlasTexture:null,eu=ks||!It.isOrthographic||M.options.rotating||M.options.zooming||Wp.kind==="composite"||Wp.kind==="camera"?Tt.LINEAR:Tt.NEAREST);const Kp=fr.glyphAtlasTexture?fr.glyphAtlasTexture.size:[0,0],Eo=N.layout.get("text-size-scale-range"),Do=o.aC(M.scaleFactor,Eo[0],Eo[1]),so=o.bj(Wp,It.zoom,Do),sc=fd(Kr,fr.tileID.canonical,ks,rs,It,Js.getProjection(),Jr),Ch=Am(Kr,fr.tileID.canonical,ks,rs,It,Js.getProjection(),Jr),Ml=Js.text.uboBinder&&Js.text.uboBinder.cachedHeader&&256&Js.text.uboBinder.cachedHeader.dataDrivenMask?[0,0]:ae,cp=M.translatePosMatrix(Ch,fr,Ml,ye,!0),gb=M.translatePosMatrix(Kr,fr,Ml,ye),Uw=Yo?lo:sc,qw=rs&&!ks&&!Pi;let rN=wr;!Ts&&!It.mercatorFromTransition||rs||(rN=tc(It));const Lv=Tv(Wp.kind,so,qw,ks,M,gb,Uw,cp,Kt,!0,Kp,lp,0,mr,dn,Xt,ra,en?rN:wr,Js.getProjection(),_o,Ra,null,null,Do),iy=fr.glyphAtlasTexture?fr.glyphAtlasTexture:null,nN=Tt.LINEAR,Nf=N.paint.get("text-halo-width").constantOr(1)!==0,xb=M.terrain&&ks&&Pi?o.b7(o.bb(),sc):lo;if(Pi&&Js.text){const yb=o.bu.getAtTileOffsetFunc(mr,It.center.lat,It.worldSize,Js.getProjection()),vb=_c(Kr,fr.tileID.canonical,ks,rs,It,Js.getProjection(),Jr);Mt(Js,Kr,M,!0,vb,Ch,ks,dt,yb,mr,Do)}return{program:Zc,buffers:Js.text,uniformValues:Lv,atlasTexture:iy,atlasTextureIcon:Vi,atlasInterpolation:nN,atlasInterpolationIcon:eu,isSDF:!0,hasHalo:Nf,depthMode:Ic,tile:fr,renderWithShadows:ei,labelPlaneMatrixInv:xb}},ko=Js.icon.segments.get().length,Ii=Js.text.segments.get().length,Ca=ko&&!G.onlyText?uo():null,Ta=Ii&&!G.onlyIcons?rl():null,So=N.paint.get("icon-opacity").constantOr(1),dl=N.paint.get("text-opacity").constantOr(1);if(ms&&Js.canOverlap){Ws=!0;const Pi=So&&!G.onlyText?Js.icon.segments.get():[],ma=dl&&!G.onlyIcons?Js.text.segments.get():[];for(const Yo of Pi)Ls.push({segments:new o.dy([Yo]),sortKey:Yo.sortKey,state:Ca});for(const Yo of ma)Ls.push({segments:new o.dy([Yo]),sortKey:Yo.sortKey,state:Ta})}else G.onlyText||Ls.push({segments:So?Js.icon.segments:new o.dy([]),sortKey:0,state:Ca}),G.onlyIcons||Ls.push({segments:dl?Js.text.segments:new o.dy([]),sortKey:0,state:Ta})}Ws&&Ls.sort((mr,fr)=>mr.sortKey-fr.sortKey);for(const mr of Ls){const fr=mr.state;if(fr)if(M.terrain?M.terrain.setupElevationDraw(fr.tile,fr.program,{useDepthForOcclusion:It.depthOcclusionForSymbolsAndCircles,labelPlaneMatrixInv:fr.labelPlaneMatrixInv}):M.setupDepthForOcclusion(It.depthOcclusionForSymbolsAndCircles,fr.program),Wt.activeTexture.set(Tt.TEXTURE0),fr.atlasTexture&&fr.atlasTexture.bind(fr.atlasInterpolation,Tt.CLAMP_TO_EDGE,!0),fr.atlasTextureIcon&&(Wt.activeTexture.set(Tt.TEXTURE1),fr.atlasTextureIcon&&fr.atlasTextureIcon.bind(fr.atlasInterpolationIcon,Tt.CLAMP_TO_EDGE,!0)),fr.renderWithShadows&&M.shadowRenderer.setupShadows(fr.tile.tileID.toUnwrapped(),fr.program,"vector-tile"),M.uploadCommonLightUniforms(M.context,fr.program),fr.hasHalo){const Js=fr.uniformValues;Js.u_is_halo=1,Ax(fr.buffers,mr.segments,N,M,fr.program,fr.depthMode,F,q,Js,2),Js.u_is_halo=0}else{if(fr.isSDF){const Js=fr.uniformValues;fr.hasHalo&&(Js.u_is_halo=1,Ax(fr.buffers,mr.segments,N,M,fr.program,fr.depthMode,F,q,Js,1)),Js.u_is_halo=0}Ax(fr.buffers,mr.segments,N,M,fr.program,fr.depthMode,F,q,fr.uniformValues,1)}}}function Ax(M,g,N,P,F,q,G,Q,ae,me){const ye=P.context,Ae=ye.gl,Te=[M.dynamicLayoutVertexBuffer,M.opacityVertexBuffer,M.iconTransitioningVertexBuffer,M.globeExtVertexBuffer,M.zOffsetVertexBuffer,M.orientationVertexBuffer];M.featureIdBuffer&&Te.push(M.featureIdBuffer);const Fe=M.uboBinder?null:M.programConfigurations.get(N.id);if(M.uboBinder){M.uboBinder.layer=N;const dt=P.transform.zoom,lt=P.style.getBrightness?P.style.getBrightness():null,_t=M.uboBinder.getConstantUniformValues(dt,lt);ae.u_spp_fill_np_color=_t.fill_np_color,ae.u_spp_halo_np_color=_t.halo_np_color,ae.u_spp_opacity=_t.opacity,ae.u_spp_halo_width=_t.halo_width,ae.u_spp_halo_blur=_t.halo_blur,ae.u_spp_emissive_strength=_t.emissive_strength,ae.u_spp_occlusion_opacity=_t.occlusion_opacity,ae.u_spp_z_offset=_t.z_offset;const Ct=N.paint.get(M.uboBinder.isText?"text-translate-anchor":"icon-translate-anchor"),ht=M.uboBinder.cachedHeader&&256&M.uboBinder.cachedHeader.dataDrivenMask&&Ct==="map"?P.transform.angle:0;ae.u_spp_translate_rotation=[Math.cos(ht),Math.sin(ht)]}const{batchIndices:Ye,batchSegments:Ge}=M.getBatchGrouping(g);for(const dt of Ye){const lt=Ge.get(dt);M.uboBinder&&M.uboBinder.bind(ye,F.program,dt),F.draw(P,Ae.TRIANGLES,q,G,Q,_n.disabled,ae,N.id,M.layoutVertexBuffer,M.indexBuffer,lt,N.paint,P.transform.zoom,Fe,Te,me)}}function Kc(M,g,N,P,F,q){const G=N.paint.get("line-width"),Q=N.paint.get("line-emissive-strength").isConstant(),ae=N.paint.get("line-emissive-strength").constantOr(0),me=N.paint.get("line-occlusion-opacity"),ye=N.layout.get("line-elevation-reference"),Ae=N.layout.get("line-width-unit")==="meters",Te=ye==="sea",Fe=!(!M.terrain||!M.terrain.enabled),Ye=M.context,Ge=Ye.gl;if(N.hasElevatedBuckets&&M.transform.projection.name==="globe")return;const dt=N.layout.get("line-cross-slope"),lt=dt!==void 0,_t=dt<1,Ct=F||M.colorModeForDrapableLayerRenderPass(Q?ae:null),ht=M.terrain&&M.terrain.renderingToTexture||q,Kt=ht?1:o.o.devicePixelRatio,Lt=N.paint.get("line-dasharray"),Wt=Lt.constantOr(1),Tt=N.layout.get("line-cap"),It=Lt.constantOr(null),Ut=Tt.constantOr(null),rs=N.paint.get("line-pattern"),Zt=rs.constantOr(1),ks=N.paint.get("line-pattern-cross-fade"),ms=rs.constantOr(null),Ws=N.paint.get("line-opacity").constantOr(1);let sr=!Zt&&Ws!==1||M.depthOcclusion&&me>0&&me<1;const as=N.paint.get("line-gradient"),Xt=Zt?"linePattern":"line",ws=o.dU(N);let Ts;if(ht&&M.terrain&&M.terrain.clipOrMaskOverlapStencilType()&&(sr=!1),me!==0&&M.depthOcclusion){const Js=N.paint._values["line-opacity"];Js&&Js.value&&Js.value.kind==="constant"?Ts=Js.value:o.w(`Occlusion opacity for layer ${N.id} is supported only when line-opacity isn't data-driven.`)}G.value.kind!=="constant"&&G.value.isLineProgressConstant===!1&&ws.push("VARIABLE_LINE_WIDTH"),ht&&(M.emissiveMode!=="dual-source-blending"||Q?M.emissiveMode==="mrt-fallback"&&ws.push("USE_MRT1"):ws.push("DUAL_SOURCE_BLENDING"));const Ls={},wr=(Js,en,dn,Kr,Jr,$n)=>{for(const oa of Js){const ra=g.getTile(oa);if(Zt&&!ra.patternsLoaded())continue;const Ra=ra.getBucket(N);if(!Ra||Ra.elevationType!=="none"&&!Jr||Ra.elevationType==="none"&&Jr)continue;M.prepareDrawTile();const Ln=[...en],Oa=M.shadowRenderer,na=Ra.elevationType==="road"&&!!Oa&&Oa.enabled;let ji=[0,0,0];if(na){const ei=M.style.directionalLight,_o=M.style.ambientLight;ei&&_o&&(ji=pf(M.style,ei,_o)),Ln.push("RENDER_SHADOWS","NORMAL_OFFSET")}const uo=Ra.programConfigurations.get(N.id);let rl=!1;if(ms&&ra.imageAtlas){const ei=o.dV.from(ms),_o=ei.getPrimary().scaleSelf(Kt).toString(),Ic=ra.imageAtlas.patternPositions.get(_o),rh=ei.getSecondary(),Zc=rh?ra.imageAtlas.patternPositions.get(rh.scaleSelf(Kt).toString()):null;rl=!!Ic&&!!Zc,Ic&&uo.setConstantPatternPositions(Ic,Zc)}ks>0&&(rl||uo.getPatternTransitionVertexBuffer("line-pattern"))&&Ln.push("LINE_PATTERN_TRANSITION"),Ra.elevationGroundScaleVertexBuffer&&Ln.push("ELEVATION_GROUND_SCALE");const ko=M.isTileAffectedByFog(oa),Ii=M.getOrCreateProgram(Xt,{config:uo,defines:Ln,overrideFog:ko});if(!Zt&&It&&Ut&&ra.lineAtlas){const ei=ra.lineAtlas.getDash(It,Ut);ei&&uo.setConstantPatternPositions(ei)}na&&Oa.setupShadows(ra.tileID.toUnwrapped(),Ii,"vector-tile");let[Ca,Ta]=N.paint.get("line-trim-offset");(Ut==="round"||Ut==="square")&&Ca!==Ta&&(Ca===0&&(Ca-=1),Ta===1&&(Ta+=1));const So=ht?oa.projMatrix:null,dl=Ae?1/Ra.tileToMeter/o.aA(ra,1,M.transform.zoom):1,Pi=Ae?1/Ra.tileToMeter/o.aA(ra,1,Math.floor(M.transform.zoom)):1,ma=Wt?N.paint._values["line-floorwidth"]:null;let Yo;if(ma&&ma.value.kind==="constant"){const ei=Ra.zoom;ei in Ls||(Ls[ei]=Math.max(.01,N.widthExpression().evaluate({zoom:ei}))),Yo=ma.value.value;const _o=Math.floor(M.transform.zoom);ma.value.value=Ls[ei]*Math.pow(2,_o-ra.tileID.overscaledZ)}const ho=Zt?o.dW(M,ra,N,So,Kt,dl,Pi,[Ca,Ta],ji,ks):o.dX(M,ra,N,So,Ra.lineClipsArray.length,Kt,dl,Pi,[Ca,Ta],ji);if(as){const ei=Ra.gradients[N.id];let _o=ei.texture;if(N.gradientVersion!==ei.version){let Ic=256;if(N.stepInterpolant){const rh=g.getSource().maxzoom,Zc=oa.canonical.z===rh?Math.ceil(1<{Ts!=null&&(Ts.value=Ws*me),Ii.draw(M,Ge.TRIANGLES,dn,ei,Ct,_n.disabled,ho,N.id,Ra.layoutVertexBuffer,Ra.indexBuffer,Ra.segments,N.paint,M.transform.zoom,uo,[Ra.layoutVertexBuffer2,Ra.patternVertexBuffer,Ra.zOffsetVertexBuffer,Ra.elevationGroundScaleVertexBuffer]),Ts!=null&&(Ts.value=Ws)};if(sr&&!Jr){const ei=M.stencilModeForClipping(oa).ref;ei===0&&ht&&Ye.clear({stencil:0});const _o={func:Ge.EQUAL,mask:255};ho.u_alpha_discard_threshold=.8,cc(new Gn(_o,ei,255,Ge.KEEP,Ge.KEEP,Ge.INVERT)),ho.u_alpha_discard_threshold=0,cc(new Gn(_o,ei,255,Ge.KEEP,Ge.KEEP,Ge.KEEP))}else ho.u_alpha_discard_threshold=sr&&Jr&&$n?.8:0,cc(Jr?Kr:M.stencilModeForClipping(oa));Yo!==void 0&&(ma.value.value=Yo)}};let mr=M.depthModeForSublayer(0,Wr.ReadOnly);const fr=new Wr(M.depthOcclusion?Ge.GREATER:Ge.LEQUAL,Wr.ReadOnly,M.depthRangeFor3D);if(N.hasNonElevatedBuckets){const Js=!ht&&M.terrain;me!==0&&Js?o.w(`Occlusion opacity for layer ${N.id} is supported on terrain only if the layer has line-z-offset enabled.`):Js?o.w(`Cannot render non-elevated lines in immediate mode when terrain is enabled. Layer: ${N.id}.`):wr(P,ws,mr,Gn.disabled,!1,!0)}if(N.hasElevatedBuckets){ye==="hd-road-markup"?Fe||(mr=fr,ws.push("ELEVATED_ROADS")):(ws.push("ELEVATED"),mr=fr,lt&&ws.push(_t?"CROSS_SLOPE_HORIZONTAL":"CROSS_SLOPE_VERTICAL"),Te&&ws.push("ELEVATION_REFERENCE_SEA"));const Js=sr?M.stencilModeFor3D():Gn.disabled;M.forceTerrainMode=!0,wr(P,ws,mr,Js,!0,!0),sr&&wr(P,ws,mr,Js,!0,!1),M.forceTerrainMode=!1}sr&&(M.resetStencilClippingMasks(),ht&&Ye.clear({stencil:0})),me===0||M.depthOcclusion||ht||M.layersWithOcclusionOpacity.push(M.currentLayer)}const bf={additive:{clearColor:new o.aq(0,0,0,0),colorMode:zn.additive,compositeUniformValue:1},multiply:{clearColor:new o.aq(1,1,1,1),colorMode:zn.multiply,compositeUniformValue:0}};function Mx(M,g){const N=1<=sp?1:Fe.pitch/sp))),2*Ye}(M.transform),me=M.transform.getFreeCameraOptions().position,ye="elevatedStructuresDepthReconstruct",Ae=M.getOrCreateProgram(ye,{defines:["DEPTH_RECONSTRUCTION"]}),Te=M.getOrCreateProgram(ye);for(const Fe of P){const Ye=g.getTile(Fe),Ge=Ye.getBucket(N);if(!Ge)continue;const dt=Ge.elevatedStructures;if(!dt)continue;const lt=Ge.elevationBufferData.heightRange,_t=Mx(Fe.toUnwrapped(),me),Ct=M.translatePosMatrix(Fe.projMatrix,Ye,N.paint.get("fill-translate"),N.paint.get("fill-translate-anchor"));let ht,Kt,Lt,Wt;if(F==="initialize"){if(!lt||lt.min>=1||dt.depthSegments.segments[0].primitiveLength===0)continue;ht=Cv(Ct,_t,ae,1,0),Kt=G,Lt=dt.depthSegments,Wt=Ae}else if(F==="reset"){if(!lt||lt.min>=0||dt.maskSegments.segments[0].primitiveLength===0)continue;ht=Cv(Ct,_t,0,0,1),Kt=Q,Lt=dt.maskSegments,Wt=Ae}else if(F==="geometry"){if(dt.depthSegments.segments[0].primitiveLength===0)continue;ht=Cv(Ct,_t,ae,1,0),Kt=G,Lt=dt.depthSegments,Wt=Te}Wt.draw(M,q.TRIANGLES,Kt,Gn.disabled,zn.disabled,_n.disabled,ht,N.id,dt.vertexBuffer,dt.indexBuffer,Lt,N.paint,M.transform.zoom)}}function Ev(M,g,N,P){const{painter:F,sourceCache:q,layer:G,coords:Q,colorMode:ae,elevationType:me,terrainEnabled:ye,pass:Ae}=M,Te=F.context.gl,Fe=G.paint.get("fill-pattern"),Ye=G.paint.get("fill-pattern-cross-fade"),Ge=Fe.constantOr(null);let dt=me;me!=="road"||g&&!ye||(dt="none");const lt=dt==="road",_t=M.painter.shadowRenderer,Ct=lt&&!!_t&&_t.enabled,ht=new Wr(F.context.gl.LEQUAL,Wr.ReadOnly,F.depthRangeFor3D);let Kt=[0,0,0];if(Ct){const It=F.style.directionalLight,Ut=F.style.ambientLight;It&&Ut&&(Kt=pf(F.style,It,Ut))}const Lt=Fe&&Fe.constantOr(1),Wt=F.terrain&&F.terrain.renderingToTexture,Tt=(It,Ut)=>{let rs,Zt,ks,ms,Ws;Ut?(rs=Lt&&!G.getPaintProperty("fill-outline-color")?"fillOutlinePattern":"fillOutline",ks=Te.LINES):(rs=Lt?"fillPattern":"fill",ks=Te.TRIANGLES);for(const sr of Q){const as=q.getTile(sr);if(Lt&&!as.patternsLoaded())continue;const Xt=as.getBucket(G);if(!Xt)continue;const ws=g?Xt.elevationBufferData:Xt.bufferData;if(ws.isEmpty())continue;F.prepareDrawTile();const Ts=ws.programConfigurations.get(G.id),Ls=F.isTileAffectedByFog(sr),wr=[],mr=[];lt&&(wr.push("ELEVATED_ROADS"),mr.push(ws.elevatedLayoutVertexBuffer)),Ct&&wr.push("RENDER_SHADOWS","NORMAL_OFFSET"),Wt&&N&&wr.push("USE_MRT1"),Lt&&(F.context.activeTexture.set(Te.TEXTURE0),as.imageAtlasTexture&&as.imageAtlasTexture.bind(Te.LINEAR,Te.CLAMP_TO_EDGE),Ts.updatePaintBuffers());let fr=!1;if(Ge&&as.imageAtlas){const Jr=as.imageAtlas,$n=o.dV.from(Ge),oa=$n.getPrimary().scaleSelf(o.o.devicePixelRatio).toString(),ra=$n.getSecondary(),Ra=Jr.patternPositions.get(oa),Ln=ra?Jr.patternPositions.get(ra.scaleSelf(o.o.devicePixelRatio).toString()):null;fr=!!Ra&&!!Ln,Ra&&Ts.setConstantPatternPositions(Ra,Ln)}Ye>0&&(fr||Ts.getPatternTransitionVertexBuffer("fill-pattern"))&&wr.push("FILL_PATTERN_TRANSITION");const Js=F.getOrCreateProgram(rs,{config:Ts,overrideFog:Ls,defines:wr}),en=F.translatePosMatrix(sr.projMatrix,as,G.paint.get("fill-translate"),G.paint.get("fill-translate-anchor"));Ct&&_t.setupShadows(as.tileID.toUnwrapped(),Js,"vector-tile");const dn=G.paint.get("fill-emissive-strength");if(Ut){ms=ws.lineIndexBuffer,Ws=ws.lineSegments;const Jr=F.terrain&&F.terrain.renderingToTexture?F.terrain.drapeBufferSize:[Te.drawingBufferWidth,Te.drawingBufferHeight];Zt=rs==="fillOutlinePattern"&&Lt?ib(en,dn,F,as,Jr,Kt,Ye):y4(en,dn,Jr,Kt)}else ms=ws.indexBuffer,Ws=ws.triangleSegments,Zt=Lt?ab(en,dn,F,as,Kt,Ye):kx(en,dn,Kt);F.uploadCommonUniforms(F.context,Js,sr.toUnwrapped());let Kr=It;(me==="road"&&!ye||me==="offset")&&(Kr=ht),Js.draw(F,ks,Kr,P||F.stencilModeForClipping(sr),ae,_n.disabled,Zt,G.id,ws.layoutVertexBuffer,ms,Ws,G.paint,F.transform.zoom,Ts,mr)}};F.renderPass===Ae&&Tt(F.depthModeForSublayer(1,F.renderPass==="opaque"?Wr.ReadWrite:Wr.ReadOnly),!1),dt==="none"&&F.renderPass==="translucent"&&G.paint.get("fill-antialias")&&Tt(F.depthModeForSublayer(G.getPaintProperty("fill-outline-color")?2:0,Wr.ReadOnly),!0)}function Vp(M,g,N,P,F,q,G,Q){N.resetLayerRenderingStats(M);const ae=M.context,me=ae.gl,ye=M.transform,Ae=N.paint.get("fill-extrusion-pattern"),Te=N.paint.get("fill-extrusion-pattern-cross-fade"),Fe=Ae.constantOr(null),Ye=Ae.constantOr(1),Ge=N.paint.get("fill-extrusion-opacity"),dt=M.style.enable3dLights(),lt=N.paint.get(dt&&!Ye?"fill-extrusion-ambient-occlusion-wall-radius":"fill-extrusion-ambient-occlusion-radius"),_t=[N.paint.get("fill-extrusion-ambient-occlusion-intensity"),lt],Ct=N.layout.get("fill-extrusion-edge-radius"),ht=Ct>0&&!N.paint.get("fill-extrusion-rounded-roof"),Kt=ht?0:Ct,Lt=ye.projection.name==="globe"?o.e1():0,Wt=ye.projection.name==="globe",Tt=Wt?o.al(ye.zoom):0,It=[o.aH(ye.center.lng),o.aL(ye.center.lat)],Ut=N.paint.get("fill-extrusion-flood-light-color-use-theme").constantOr("default")==="none",rs=N.paint.get("fill-extrusion-flood-light-color").toNonPremultipliedRenderColor(Ut?null:N.lut).toArray01().slice(0,3),Zt=N.paint.get("fill-extrusion-flood-light-intensity"),ks=N.paint.get("fill-extrusion-vertical-scale"),ms=N.paint.get("fill-extrusion-line-width").constantOr(1)!==0,Ws=N.paint.get("fill-extrusion-height-alignment"),sr=N.paint.get("fill-extrusion-base-alignment"),as=wc(M,N.paint.get("fill-extrusion-cutoff-fade-range")),Xt=N.paint.get("fill-extrusion-front-cutoff"),ws=db(ye.pitch,Xt,!!M.terrain),Ts=ws[2]<1;Ts&&(M.maxFrontCutoffRawStart=Math.max(M.maxFrontCutoffRawStart,Xt[0]));const Ls=[];let wr;Wt&&Ls.push("PROJECTION_GLOBE_VIEW"),_t[0]>0&&Ls.push("FAUX_AO"),ht&&Ls.push("ZERO_ROOF_RADIUS"),Q&&Ls.push("HAS_CENTROID"),Zt>0&&Ls.push("FLOOD_LIGHT"),as.shouldRenderCutoff&&Ls.push("RENDER_CUTOFF"),Ts&&Ls.push("RENDER_FRONT_CUTOFF"),ms&&Ls.push("RENDER_WALL_MODE");const mr=M.renderPass==="shadow",fr=M.shadowRenderer,Js=mr&&!!fr,en=mr?_n.disabled:_n.backCCW;M.shadowRenderer&&(M.shadowRenderer.useNormalOffset=!0);let dn=[0,0,0];if(fr){const $n=M.style.directionalLight,oa=M.style.ambientLight;$n&&oa&&(dn=pf(M.style,$n,oa)),mr||(Ls.push("RENDER_SHADOWS"),fr.useNormalOffset&&Ls.push("NORMAL_OFFSET")),wr=Ls.concat(["SHADOWS_SINGLE_CASCADE"])}const Kr=Js?"fillExtrusionDepth":Ye?"fillExtrusionPattern":"fillExtrusion",Jr=N.getLayerRenderingStats();for(const $n of P){const oa=g.getTile($n),ra=oa.getBucket(N);if(!ra||ra.projection.name!==ye.projection.name)continue;let Ra=!1;fr&&(Ra=fr.getMaxCascadeForTile($n.toUnwrapped())===0);const Ln=M.isTileAffectedByFog($n),Oa=ra.programConfigurations.get(N.id);let na=!1;if(Fe&&oa.imageAtlas){const Ta=oa.imageAtlas,So=o.dV.from(Fe),dl=So.getPrimary().scaleSelf(o.o.devicePixelRatio).toString(),Pi=So.getSecondary(),ma=Ta.patternPositions.get(dl),Yo=Pi?Ta.patternPositions.get(Pi.scaleSelf(o.o.devicePixelRatio).toString()):null;na=!!ma&&!!Yo,ma&&Oa.setConstantPatternPositions(ma,Yo)}Te>0&&(na||Oa.getPatternTransitionVertexBuffer("fill-extrusion-pattern"))&&Ls.push("FILL_EXTRUSION_PATTERN_TRANSITION");const ji=M.getOrCreateProgram(Kr,{config:Oa,defines:Ra?wr:Ls,overrideFog:Ln});if(M.terrain&&M.terrain.setupElevationDraw(oa,ji,{useMeterToDem:!0}),!ra.centroidVertexBuffer){const Ta=ji.getAttributeLocation(me,"a_centroid_pos");Ta!==-1&&me.vertexAttribI4ui(Ta,0,0,0,0)}!mr&&fr&&fr.setupShadows(oa.tileID.toUnwrapped(),ji,"vector-tile"),Ye&&(M.context.activeTexture.set(me.TEXTURE0),oa.imageAtlasTexture&&oa.imageAtlasTexture.bind(me.LINEAR,me.CLAMP_TO_EDGE),Oa.updatePaintBuffers());const uo=N.paint.get("fill-extrusion-vertical-gradient"),rl=1/ra.tileToMeter;let ko;if(mr&&fr){if(Hp(oa.tileID,ra.maxHeight,M))continue;const Ta=fr.calculateShadowPassMatrixFromTile(oa.tileID.toUnwrapped());ko=dD(Ta,Kt,rl,ks,Ws,sr)}else{const Ta=M.translatePosMatrix($n.expandedProjMatrix,oa,N.paint.get("fill-extrusion-translate"),N.paint.get("fill-extrusion-translate-anchor")),So=ye.projection.createInversionMatrix(ye,$n.canonical);ko=Ye?Ma(Ta,M,uo,Ge,_t,Kt,rl,$n,oa,Lt,Ws,sr,Tt,It,So,rs,ks,Te):eh(Ta,M,uo,Ge,_t,Kt,rl,$n,Lt,Ws,sr,Tt,It,So,rs,ks,Zt,dn,ws)}M.uploadCommonUniforms(ae,ji,$n.toUnwrapped(),null,as);let Ii=ra.segments;if(ye.projection.name==="mercator"&&!mr&&(Ii=ra.getVisibleSegments(oa.tileID,M.terrain,M.transform.getFrustum(0)),!Ii.get().length))continue;if(Jr)if(mr)for(const Ta of Ii.get())Jr.numRenderedVerticesInShadowPass+=Ta.primitiveLength;else for(const Ta of Ii.get())Jr.numRenderedVerticesInTransparentPass+=Ta.primitiveLength;const Ca=[];(M.terrain||Q)&&Ca.push(ra.centroidVertexBuffer),Wt&&Ca.push(ra.layoutVertexExtBuffer),ms&&Ca.push(ra.wallVertexBuffer),ji.draw(M,ae.gl.TRIANGLES,F,q,G,en,ko,N.id,ra.layoutVertexBuffer,ra.indexBuffer,Ii,N.paint,M.transform.zoom,Oa,Ca)}M.shadowRenderer&&(M.shadowRenderer.useNormalOffset=!1)}class kh{constructor(){this.translate=[0,0],this.translateAnchor="map",this.edgeRadius=0,this.cutoffFadeRange=0}}function db(M,g,N){if(!(g[2]<1)||N)return[0,0,1];const P=180*M/Math.PI;if(P<15)return[-.5,g[1],g[2]];const F=Math.min(1,Math.max(0,(P-15)/5)),q=F*F*(3-2*F);return[-.5*(1-q)+g[0]*q,g[1],g[2]]}function ip(M,g,N,P,F,q,G,Q,ae,me,ye,Ae,Te,Fe,Ye,Ge,dt,lt,_t,Ct,ht){const Kt=g.context,Lt=Kt.gl,Wt=g.transform,Tt=g.transform.zoom,It=[],Ut=M.translate,rs=M.translateAnchor,Zt=M.edgeRadius,ks=wc(g,M.cutoffFadeRange);ye==="clear"?(It.push("CLEAR_SUBPASS"),Ct&&(It.push("CLEAR_FROM_TEXTURE"),Kt.activeTexture.set(Lt.TEXTURE0),Ct.bind(Lt.LINEAR,Lt.CLAMP_TO_EDGE))):ye==="sdf"?It.push("SDF_SUBPASS"):ye==="emissive"&&(It.push("USE_MRT1"),Kt.activeTexture.set(Lt.TEXTURE0),Ct.bind(Lt.LINEAR,Lt.CLAMP_TO_EDGE)),lt&&It.push("HAS_CENTROID"),ks.shouldRenderCutoff&&It.push("RENDER_CUTOFF");const ms=(Ws,sr,as,Xt,ws)=>{let Ts=It;sr.groundRadiusBuffer!=null&&(Ts=It.concat("HAS_ATTRIBUTE_a_flood_light_ground_radius"));const Ls=sr.programConfigurations.get(P.id),wr=g.isTileAffectedByFog(Ws),mr=g.getOrCreateProgram("fillExtrusionGroundEffect",{config:Ls,defines:Ts,overrideFog:wr}),fr=((en,dn,Kr,Jr,$n,oa,ra,Ra,Ln,Oa,na)=>({u_matrix:dn,u_opacity:Kr,u_ao_pass:Jr?1:0,u_meter_to_tile:$n,u_ao:oa,u_flood_light_intensity:ra,u_flood_light_color:Ra,u_attenuation:Ln,u_edge_radius:Oa,u_fb:0,u_fb_size:na,u_dynamic_offset:1}))(0,Xt,Ae,me,ws,[Te,Fe*ws],Ye,Ge,dt,Tt>=17?0:Zt*ws,Ct?Ct.size[0]:0),Js=[];lt&&Js.push(sr.hiddenByLandmarkVertexBuffer),sr.groundRadiusBuffer!=null&&Js.push(sr.groundRadiusBuffer),g.uploadCommonUniforms(Kt,mr,Ws.toUnwrapped(),null,ks),mr.draw(g,Kt.gl.TRIANGLES,q,G,Q,ae,fr,P.id,sr.vertexBuffer,sr.indexBuffer,as,P.paint,Tt,Ls,Js)};for(const Ws of F){const sr=N.getTile(Ws),as=sr.getBucket(P);if(!as||as.projection.name!==Wt.projection.name||!as.groundEffect||as.groundEffect&&!as.groundEffect.hasData())continue;const Xt=as.groundEffect,ws=1/as.tileToMeter;{const Ts=g.translatePosMatrix(Ws.projMatrix,sr,Ut,rs),Ls=Xt.getDefaultSegment();ms(Ws,Xt,Ls,Ts,ws)}if(_t)for(let Ts=0;Ts<4;Ts++){const Ls=o.d$[Ts](Ws),wr=N.getTile(Ls);if(!wr)continue;const mr=wr.getBucket(P);if(!mr||mr.projection.name!==Wt.projection.name||!mr.groundEffect||mr.groundEffect&&!mr.groundEffect.hasData())continue;const fr=mr.groundEffect;let Js,en;Ts===0?(Js=[-o.an,0,0],en=1):Ts===1?(Js=[o.an,0,0],en=0):Ts===2?(Js=[0,-o.an,0],en=3):(Js=[0,o.an,0],en=2);const dn=fr.regionSegments[en];if(!dn)continue;const Kr=new Float32Array(16);o.bx(Kr,Ws.projMatrix,Js),ms(Ws,fr,dn,g.translatePosMatrix(Kr,sr,Ut,rs),ws)}}}function Pg(M,g,N,P,F,q,G){P.centroidVertexArray.length===0&&P.createCentroidsBuffer();const Q=q?q.findDEMTileFor(N):null;if(!(Q&&Q.dem||G))return;q&&Q&&Q.dem&&P.selfDEMTileTimestamp!==Q.dem._timestamp&&(P.borderDoneWithNeighborZ=[-1,-1,-1,-1],P.selfDEMTileTimestamp=Q.dem._timestamp);const ae=(lt,_t)=>{(lt.flags|_t.flags)&o.e3?(lt.flags|=o.e3,_t.flags|=o.e3):(lt.flags&=~o.e3,_t.flags&=~o.e3)},me=lt=>new o.P(Math.ceil((lt+o.e4)*o.e5),0),ye=(lt,_t,Ct)=>{const ht=Math.ceil((lt+o.e4)*o.e5),Kt=Math.floor(Math.max(0,Math.min(o.an-1,Ct))/4);return new o.P(ht,Kt<<5|(3&_t)<<3|7)},Ae=lt=>{const _t=g.getSource().minzoom,Ct=Kt=>{const Lt=g.getTileByID(Kt);if(Lt&&Lt.hasData())return Lt.getBucket(F)},ht=[0,-1,1];for(const Kt of ht){if(lt.overscaledZ+Kt<_t)continue;const Lt=Ct(lt.calculateScaledKey(lt.overscaledZ+Kt));if(Lt)return Lt}},Te=[0,0,0],Fe=(lt,_t)=>(Te[0]=Math.min(lt.min.y,_t.min.y),Te[1]=Math.max(lt.max.y,_t.max.y),Te[2]=o.an-_t.min.x>lt.max.x?_t.min.x-o.an:lt.max.x,Te),Ye=(lt,_t)=>(Te[0]=Math.min(lt.min.x,_t.min.x),Te[1]=Math.max(lt.max.x,_t.max.x),Te[2]=o.an-_t.min.y>lt.max.y?_t.min.y-o.an:lt.max.y,Te),Ge=[(lt,_t)=>Fe(lt,_t),(lt,_t)=>Fe(_t,lt),(lt,_t)=>Ye(lt,_t),(lt,_t)=>Ye(_t,lt)],dt=(lt,_t,Ct,ht,Kt,Lt,Wt)=>{if(!q)return 0;const Tt=[[Lt?Ct:lt,Lt?lt:Ct,0],[Lt?Ct:_t,Lt?_t:Ct,0]],It=Wt<0?o.an+Wt:Wt,Ut=[Lt?It:(lt+_t)/2,Lt?(lt+_t)/2:It,0];return Ct===0&&Wt<0||Ct!==0&&Wt>0?q.getForTilePoints(Kt,[Ut],!0,ht):Tt.push(Ut),q.getForTilePoints(N,Tt,!0,Q),Math.max(Tt[0][2],Tt[1][2],Ut[2])/q.exaggeration()};for(let lt=0;lt<4;lt++){const _t=P.borderFeatureIndices[lt];if(_t.length===0)continue;const Ct=o.d$[lt](N),ht=Ae(Ct);if(!(ht&&ht instanceof o.e0))continue;const Kt=q?q.findDEMTileFor(Ct):null;if(!(Kt&&Kt.dem||G)||(q&&Kt&&Kt.dem&&P.borderDEMTileTimestamp[lt]!==Kt.dem._timestamp&&(P.borderDoneWithNeighborZ[lt]=-1,P.borderDEMTileTimestamp[lt]=Kt.dem._timestamp),P.borderDoneWithNeighborZ[lt]===ht.canonical.z))continue;ht.centroidVertexArray.length===0&&ht.createCentroidsBuffer();const Lt=(lt<2?1:5)-lt,Wt=ht.borderDoneWithNeighborZ[Lt]!==P.canonical.z,Tt=ht.borderFeatureIndices[Lt];let It=0;if(P.canonical.z!==ht.canonical.z){for(const ks of _t)P.showCentroid(P.featuresOnBorder[ks]);if(Wt)for(const ks of Tt)ht.showCentroid(ht.featuresOnBorder[ks]);P.borderDoneWithNeighborZ[lt]=ht.canonical.z,ht.borderDoneWithNeighborZ[Lt]=P.canonical.z;continue}const Ut=new Map,rs=new Set,Zt=new Set;for(let ks=0;ks1||as.intersectsCount()>1;{let mr=0;if(Kt&&Kt.dem&&!wr){const fr=Ge[lt](Ws,Xt),Js=lt%2?o.an-1:0;mr=dt(fr[0],Math.min(o.an-1,fr[1]),Js,Kt,Ct,lt<2,fr[2])}Ws.centroidXY=ye(mr,lt,Ls),Xt.centroidXY=ye(mr,Lt,Ls)}if(P.writeCentroidToBuffer(Ws),ht.writeCentroidToBuffer(Xt),ms.buildingId!==void 0){for(const mr of P.centroidData)mr.buildingId===ms.buildingId&&mr!==Ws&&(mr.centroidXY=Ws.centroidXY,P.writeCentroidToBuffer(mr));for(const mr of ht.centroidData)mr.buildingId===ms.buildingId&&mr!==Xt&&(mr.centroidXY=Xt.centroidXY,ht.writeCentroidToBuffer(mr))}}for(const ks of _t){if(rs.has(ks))continue;const ms=P.featuresOnBorder[ks],Ws=P.centroidData[ms.centroidDataIndex],sr=ms.borders[lt];let as;for(;Itsr[0]+3||Xt[0]>sr[0]-3)break;ht.showCentroid(as),It++}if(as&&Itsr[1]-3||(ws++,++It===Tt.length))break;as=ht.featuresOnBorder[Tt[It]]}for(;Xt=Tt.length){P.showCentroid(ms);continue}as=ht.featuresOnBorder[Tt[Xt]];let Ts=!1;if(ws>=1){const mr=as.borders[Lt];Math.abs(sr[0]-mr[0])<3&&Math.abs(sr[1]-mr[1])<3&&(ws=1,Ts=!0,It=Xt+1)}else if(ws===0){P.showCentroid(ms);continue}const Ls=ht.centroidData[as.centroidDataIndex];G&&Ts&&ae(Ws,Ls);const wr=ms.intersectsCount()>1||as.intersectsCount()>1;if(ws>1)It=Xt,Ws.centroidXY=Ls.centroidXY=new o.P(0,0);else if(Kt&&Kt.dem&&!wr){const mr=Ge[lt](Ws,Ls),fr=lt%2?o.an-1:0,Js=dt(mr[0],Math.min(o.an-1,mr[1]),fr,Kt,Ct,lt<2,mr[2]);Ws.centroidXY=Ls.centroidXY=me(Js)}else wr?Ws.centroidXY=Ls.centroidXY=new o.P(0,0):(Ws.centroidXY=P.encodeBorderCentroid(ms),Ls.centroidXY=ht.encodeBorderCentroid(as));P.writeCentroidToBuffer(Ws),ht.writeCentroidToBuffer(Ls)}else P.showCentroid(ms)}P.borderDoneWithNeighborZ[lt]=ht.canonical.z,ht.borderDoneWithNeighborZ[Lt]=P.canonical.z}(P.needsCentroidUpdate||!P.centroidVertexBuffer&&P.centroidVertexArray.length!==0)&&P.uploadCentroid(M)}const Av=[1,0,0],Mw=[0,1,0],Iw=[0,0,1];function Hp(M,g,N){const P=N.transform,F=N.shadowRenderer;if(!F)return!0;const q=M.toUnwrapped(),G=P.tileSize*F._cascades[N.currentShadowCascade].scale;let Q=g;if(P.elevation){const Ye=P.elevation.getMinMaxForTile(M);Ye&&(Q+=Ye.max)}const ae=P.scaleZoom(G);Q/=o.e2(P.center.lat,ae);const me=[...F.shadowDirection];me[2]=-me[2];const ye=F.computeSimplifiedTileShadowVolume(q,Q,G,me);if(!ye)return!1;const Ae=[Av,Mw,Iw,me,[me[0],0,me[2]],[0,me[1],me[2]]],Te=o.cl.fromInvProjectionMatrix(P.invProjMatrix,P.worldSize,ae,P.projection.name!=="globe"),Fe=F.getCurrentCascadeFrustum();return Te.intersectsPrecise(ye.vertices,ye.planes,Ae)===0||Fe.intersectsPrecise(ye.vertices,ye.planes,Ae)===0}function sy(M){const{painter:g,source:N,layer:P,coords:F}=M;let q=M.defines;const G=g.context,Q=g.renderPass==="shadow",ae=g.renderPass==="light-beam",me=g.shadowRenderer,ye=o.e2(g.transform.center.lat,g.transform.zoom),Ae=wc(g,P.paint.get("building-cutoff-fade-range"));Ae.shouldRenderCutoff&&(q=q.concat("RENDER_CUTOFF"));const Te=P.paint.get("building-front-cutoff"),Fe=Te[2]<1&&!g.terrain,Ye=db(g.transform.pitch,Te,!!g.terrain);Fe&&(q=q.concat("RENDER_FRONT_CUTOFF"),g.maxFrontCutoffRawStart=Math.max(g.maxFrontCutoffRawStart,Te[0])),M.floodLightIntensity>0&&(q=q.concat("FLOOD_LIGHT"));for(const Ge of F){const dt=N.getTile(Ge),lt=dt.getBucket(P);if(!lt)continue;me&&me.getMaxCascadeForTile(Ge.toUnwrapped())===0&&(q=q.concat("SHADOWS_SINGLE_CASCADE"));const _t=lt.programConfigurations.get(P.id);let Ct,ht,Kt,Lt=g.translatePosMatrix(Ge.expandedProjMatrix,dt,[0,0],"map");if(Lt=o.cC(o.bb(),Lt,[1,1,M.verticalScale]),Q&&me){if(Hp(dt.tileID,lt.maxHeight*ye,g))continue;let Tt=me.calculateShadowPassMatrixFromTile(dt.tileID.toUnwrapped());Tt=o.cC(o.bb(),Tt,[1,1,M.verticalScale]),Kt=lb(Tt),Ct=ht=g.getOrCreateProgram("buildingDepth",{config:_t,defines:q,overrideFog:!1})}else if(ae)Ct=ht=g.getOrCreateProgram("buildingBloom",{config:_t,defines:q,overrideFog:!1}),Kt=Cw(Lt);else{const Tt=g.transform.calculatePosMatrix(Ge.toUnwrapped(),g.transform.worldSize);o.cC(Tt,Tt,[1,1,M.verticalScale]);const It=o.bb();o.cC(It,Tt,[1,-1,1/ye]),o.b7(It,It),o.e6(It,It);const Ut=g.transform.getFreeCameraOptions().position,rs=1<{if(ae){const Ut=Tt.entranceBloom;It.draw(g,G.gl.TRIANGLES,M.depthMode,Gn.disabled,M.blendMode,_n.disabled,Kt,P.id,Ut.layoutVertexBuffer,Ut.indexBuffer,Ut.segmentsBucket,P.paint,g.transform.zoom,_t,[Ut.layoutAttenuationBuffer,Ut.layoutColorBuffer])}else{const Ut=Tt.segmentsBucket;let rs=[Tt.layoutNormalBuffer,Tt.layoutCentroidBuffer,Tt.layoutColorBuffer,Tt.layoutFloodLightDataBuffer];Tt.layoutFacadePaintBuffer&&(rs=rs.concat([Tt.layoutFacadeDataBuffer,Tt.layoutFacadeVerticalRangeBuffer,Tt.layoutFacadePaintBuffer])),It.draw(g,G.gl.TRIANGLES,M.depthMode,Gn.disabled,M.blendMode,Q?_n.disabled:_n.backCW,Kt,P.id,Tt.layoutVertexBuffer,Tt.indexBuffer,Ut,P.paint,g.transform.zoom,_t,rs)}};g.uploadCommonUniforms(G,ht,Ge.toUnwrapped(),null,Ae),lt.buildingWithoutFacade&&Wt(lt.buildingWithoutFacade,ht),lt.buildingWithFacade&&(Ct!==ht&&g.uploadCommonUniforms(G,Ct,Ge.toUnwrapped(),null,Ae),Wt(lt.buildingWithFacade,Ct))}}function Lg(M,g,N,P,F,q,G,Q,ae,me,ye,Ae,Te,Fe){const Ye=M.context.gl,Ge=M.depthModeForSublayer(1,Wr.ReadOnly,Ye.LEQUAL,!0),dt=.1*(1-(lt=ye))+3*lt;var lt;const _t=M._showOverdrawInspector,Ct=Ae,ht=new kh;_t||ip(ht,M,g,N,P,Ge,new Gn({func:Ye.ALWAYS,mask:255},255,255,Ye.KEEP,Ye.KEEP,Ye.REPLACE),new zn([Ye.ONE,Ye.ONE,Ye.ONE,Ye.ONE],o.aq.transparent,[!1,!1,!1,!0],Ye.MIN),_n.disabled,F,"sdf",q,G,Q,ae,me,dt,Ct,!1,void 0);{const Kt=_t?Gn.disabled:new Gn({func:Ye.EQUAL,mask:255},255,255,Ye.KEEP,Ye.DECR,Ye.DECR),Lt=_t?M.colorModeForRenderPass():new zn([Ye.ONE_MINUS_DST_ALPHA,Ye.DST_ALPHA,Ye.ONE,Ye.ONE],o.aq.transparent,[!0,!0,!0,!0]);ip(ht,M,g,N,P,Ge,Kt,Lt,_n.disabled,F,"color",q,G,Q,ae,me,dt,Ct,!1,void 0)}}function ub(M){return[M[0]*o.e7,M[1]*o.e7,M[2]*o.e7,0]}function ry(M,g,N,P,F,q,G,Q,ae){const me=P.getSource(),ye=N.globeSharedBuffers;if(!ye)return;let Ae,Te,Fe;if(g&&(Ae=P.getTile(g)),me instanceof o.aV?(Te=me.texture,Fe=o.dw(0,0,N.transform)):Ae&&g&&(Te=Ae.texture,Fe=o.dw(g.canonical.z,g.canonical.x,N.transform)),!Te||!Fe)return;M||(Fe=o.cC(o.bb(),Fe,[1,-1,1]));const Ye=N.context,Ge=Ye.gl,dt=F.paint.get("raster-resampling")==="nearest"?Ge.NEAREST:Ge.LINEAR,lt=N.colorModeForDrapableLayerRenderPass(q),_t=G.defines;_t.push("GLOBE_POLES");const Ct=new Wr(Ge.LEQUAL,Wr.ReadWrite,N.depthRangeFor3D),ht=Float32Array.from(N.transform.expandedFarZProjMatrix),Kt=Float32Array.from(o.du(o.dv(new o.cn(0,0,0))));N.terrain&&N.terrain.prepareDrawTile(),Ye.activeTexture.set(Ge.TEXTURE0),Te.bind(dt,Ge.CLAMP_TO_EDGE),Ye.activeTexture.set(Ge.TEXTURE1),Te.bind(dt,Ge.CLAMP_TO_EDGE),"useMipmap"in Te&&Ye.extTextureFilterAnisotropic&&N.transform.pitch>20&&Ge.texParameterf(Ge.TEXTURE_2D,Ye.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,Ye.extTextureFilterAnisotropicMax);const[Lt,Wt,Tt,It]=g?ye.getPoleBuffers(g.canonical.z,!1):ye.getPoleBuffers(0,!0),Ut=F.paint.get("raster-elevation");let rs;M?(rs=Lt,N.renderDefaultNorthPole=Ut!==0):(rs=Wt,N.renderDefaultSouthPole=Ut!==0);const Zt=ub(G.mix),ks=((Ws,sr,as,Xt,ws,Ts,Ls,wr,mr,fr,Js,en,dn,Kr)=>zp(Ws,sr,as,Xt,new Float32Array(16),new Float32Array(9),[0,0],ws,[0,0],[0,0,0,0],1,{opacity:1,mix:0},Ls,[0,0],mr,2,Js,en,dn,1,0,Kr))(N,ht,Kt,Fe,o.al(N.transform.zoom),0,F,0,Ut,0,Zt,G.offset,G.range,q),ms=N.getOrCreateProgram("raster",{defines:_t});N.uploadCommonUniforms(Ye,ms,null),ms.draw(N,Ge.TRIANGLES,Ct,ae,lt,Q,ks,F.id,rs,Tt,It)}function Pw(M){if(M.isOrthographic)return[0,0,0,0];const g=M._nearZ,N=M.projection.farthestPixelDistance(M),P=N-g,F=.2*M.height,q=g+F;return[g,N,(q-F-g)/P,(q-g)/P]}function Lw(M,g,N,P){if(M)return g instanceof Uh&&M instanceof bh?g.getTextureDescriptor(M,N,!0):{texture:M.texture,mix:ub(P.mix),offset:P.offset,buffer:0,tileSize:1}}var hb=o.e8([{name:"a_index",type:"Int16",components:1}]);class th{constructor(g,N,P,F){const q={width:P[0],height:P[1],data:null},G=g.gl;this.targetColorTexture=new o.T(g,q,G.RGBA8,{useMipmap:!1}),this.backgroundColorTexture=new o.T(g,q,G.RGBA8,{useMipmap:!1}),this.context=g,this.updateParticleTexture(N,F),this.lastInvalidatedAt=0}updateParticleTexture(g,N){if(this.particleTextureDimension===N.width)return;(this.particleTexture0||this.particleTexture1||this.particleIndexBuffer||this.particleSegment)&&(this.particleTexture0.destroy(),this.particleTexture1.destroy(),this.particleIndexBuffer.destroy(),this.particleSegment.destroy());const P=this.context.gl,F=N.width*N.height;this.particleTexture0=new o.T(this.context,N,P.RGBA8,{premultiply:!1,useMipmap:!1}),this.particleTexture1=new o.T(this.context,N,P.RGBA8,{premultiply:!1,useMipmap:!1});const q=new o.e9;q.reserve(F);for(let G=0;G0){const Zt=o.ec(N.canonical,ae),ks=o.ed(Zt);Te=o.aD(new Float32Array(16),ae.globeMatrix,ks),o.aD(Te,ae.projMatrix,Te)}const Fe=o.bb();Fe[12]+=2*F/(o.o.devicePixelRatio*ae.width),Fe[13]+=2*q/(o.o.devicePixelRatio*ae.height),o.aD(Te,Fe,Te);const Ye=M.getOrCreateProgram("debug",{defines:Ae}),Ge=g.getTileByID(N.key);M.terrain&&M.terrain.setupElevationDraw(Ge,Ye);const dt=Wr.disabled,lt=Gn.disabled,_t=M.colorModeForRenderPass(),Ct="$debug";Q.activeTexture.set(me.TEXTURE0),M.emptyTexture.bind(me.LINEAR,me.CLAMP_TO_EDGE),ye?Ge._makeGlobeTileDebugBuffers(M.context,ae):Ge._makeDebugTileBoundsBuffers(M.context,ae.projection);const ht=Ge._tileDebugBuffer||M.debugBuffer,Kt=Ge._tileDebugIndexBuffer||M.debugIndexBuffer,Lt=Ge._tileDebugSegments||M.debugSegments;if(Ye.draw(M,me.LINE_STRIP,dt,lt,_t,_n.disabled,Yh(Te,P.toPremultipliedRenderColor(null)),Ct,ht,Kt,Lt,null,null,null,[Ge._globeTileDebugBorderBuffer]),G){const Zt=Ge.latestRawTileData,ks=Math.floor((Zt&&Zt.byteLength||0)/1024);let ms=N.canonical.toString();N.overscaledZ!==N.canonical.z&&(ms+=` => ${N.overscaledZ}`),ms+=` ${Ge.state}`,ms+=` ${ks}kb`,function(Ws,sr){Ws.initDebugOverlayCanvas();const as=Ws.debugOverlayCanvas,Xt=Ws.context.gl,ws=Ws.debugOverlayCanvas.getContext("2d");ws.clearRect(0,0,as.width,as.height),ws.shadowColor="white",ws.shadowBlur=2,ws.lineWidth=1.5,ws.strokeStyle="white",ws.textBaseline="top",ws.font="bold 36px Open Sans, sans-serif",ws.fillText(sr,5,5),ws.strokeText(sr,5,5),Ws.debugOverlayTexture.update(as),Ws.debugOverlayTexture.bind(Xt.LINEAR,Xt.CLAMP_TO_EDGE)}(M,ms)}const Wt=g.getTile(N).tileSize,Tt=512/Math.min(Wt,512)*(N.overscaledZ/ae.zoom)*.5,It=Ge._tileDebugTextBuffer||M.debugBuffer,Ut=Ge._tileDebugTextIndexBuffer||M.quadTriangleIndexBuffer,rs=Ge._tileDebugTextSegments||M.debugSegments;Ye.draw(M,me.TRIANGLES,dt,lt,zn.alphaBlended,_n.disabled,Yh(Te,o.aq.transparent.toPremultipliedRenderColor(null),Tt),Ct,It,Ut,rs,null,null,null,[Ge._globeTileDebugTextBuffer])}function j4(M,g,N,P){Rg(M,0,g+N/2,M.transform.width,N,P)}function Dw(M,g,N,P){Rg(M,g-N/2,0,N,M.transform.height,P)}function Rg(M,g,N,P,F,q){const G=M.context,Q=G.gl;Q.enable(Q.SCISSOR_TEST),Q.scissor(g*o.o.devicePixelRatio,N*o.o.devicePixelRatio,P*o.o.devicePixelRatio,F*o.o.devicePixelRatio),G.clear({color:q}),Q.disable(Q.SCISSOR_TEST)}const xM=o.e8([{name:"a_pos_3f",components:3,type:"Float32"}]),{members:Zh}=xM;function op(M,g,N,P){M.emplaceBack(g,N,P)}class Ld{constructor(g){this.vertexArray=new o.ee,this.indices=new o.dC,op(this.vertexArray,-1,-1,1),op(this.vertexArray,1,-1,1),op(this.vertexArray,-1,1,1),op(this.vertexArray,1,1,1),op(this.vertexArray,-1,-1,-1),op(this.vertexArray,1,-1,-1),op(this.vertexArray,-1,1,-1),op(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=g.createVertexBuffer(this.vertexArray,Zh),this.indexBuffer=g.createIndexBuffer(this.indices),this.segment=o.dy.simpleSegment(0,0,36,12)}}function _f(M,g,N,P,F,q){const G=M.context.gl,Q=g.paint.get("sky-atmosphere-color"),ae=g.paint.get("sky-atmosphere-halo-color"),me=g.paint.get("sky-atmosphere-sun-intensity"),ye=((Ae,Te,Fe,Ye,Ge)=>({u_matrix_3f:Ae,u_sun_direction:Te,u_sun_intensity:Fe,u_color_tint_r:[Ye.r,Ye.g,Ye.b,Ye.a],u_color_tint_m:[Ge.r,Ge.g,Ge.b,Ge.a],u_luminance:5e-5}))(o.eg(o.dE(),P),F,me,Q.toPremultipliedRenderColor(null),ae.toPremultipliedRenderColor(null));G.framebufferTexture2D(G.FRAMEBUFFER,G.COLOR_ATTACHMENT0,G.TEXTURE_CUBE_MAP_POSITIVE_X+q,g.skyboxTexture,0),N.draw(M,G.TRIANGLES,Wr.disabled,Gn.disabled,zn.unblended,_n.frontCW,ye,"skyboxCapture",g.skyboxGeometry.vertexBuffer,g.skyboxGeometry.indexBuffer,g.skyboxGeometry.segment)}const yM=o.e8([{type:"Float32",name:"a_pos",components:3},{type:"Float32",name:"a_uv",components:2}]);class Kj{constructor(g){const N=new o.eh;N.emplaceBack(-1,1,1,0,0),N.emplaceBack(1,1,1,1,0),N.emplaceBack(1,-1,1,1,1),N.emplaceBack(-1,-1,1,0,1);const P=new o.dC;P.emplaceBack(0,1,2),P.emplaceBack(2,3,0),this.vertexBuffer=g.createVertexBuffer(N,yM.members),this.indexBuffer=g.createIndexBuffer(P),this.segments=o.dy.simpleSegment(0,0,4,2)}destroy(){this.vertexBuffer.destroy(),this.indexBuffer.destroy(),this.segments.destroy()}}const Yj=o.e8([{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_opacity",components:1}]);class Px{constructor(){this.starsCount=16e3,this.sizeMultiplier=.15,this.sizeRange=100,this.intensityRange=200}}class vM{constructor(g){this.colorModeAlphaBlendedWriteRGB=new zn([1,yl,1,yl],o.aq.transparent,[!0,!0,!0,!1]),this.colorModeWriteAlpha=new zn([1,0,1,0],o.aq.transparent,[!1,!1,!1,!0]),this.params=new Px,this.updateNeeded=!0}update(g){const N=g.context;if(!this.atmosphereBuffer||this.updateNeeded){this.updateNeeded=!1,this.atmosphereBuffer=new Kj(N);const P=this.params.sizeRange,F=this.params.intensityRange,q=function(ye){const Ae=o.em(30),Te=[];for(let Fe=0;Fe{const Tt=q.projection.name==="globe"?["PROJECTION_GLOBE_VIEW","FOG"]:["FOG"];Wt&&Tt.push("ALPHA_PASS");const It=g.getOrCreateProgram("globeAtmosphere",{defines:Tt}),Ut=((Zt,ks,ms,Ws,sr,as,Xt,ws,Ts,Ls,wr,mr)=>({u_frustum_tl:Zt,u_frustum_tr:ks,u_frustum_br:ms,u_frustum_bl:Ws,u_horizon:sr,u_transition:as,u_fadeout_range:Xt,u_atmosphere_fog_color:ws.toArray01(),u_high_color:Ts.toArray01(),u_space_color:Ls.toArray01(),u_temporal_offset:wr,u_horizon_angle:mr}))(q.frustumCorners.TL,q.frustumCorners.TR,q.frustumCorners.BR,q.frustumCorners.BL,q.frustumCorners.horizon,Q,dt,ye,Te,Ye,_t,Kt);g.uploadCommonUniforms(P,It);const rs=this.atmosphereBuffer;rs&&It.draw(g,F.TRIANGLES,G,Gn.disabled,Wt?this.colorModeWriteAlpha:this.colorModeAlphaBlendedWriteRGB,_n.backCW,Ut,Wt?"atmosphere_glow_alpha":"atmosphere_glow",rs.vertexBuffer,rs.indexBuffer,rs.segments)};Lt(!1),Lt(!0)}drawStars(g,N){const P=o.aC(N.properties.get("star-intensity"),0,1);if(P===0)return;const F=g.context,q=F.gl,G=g.transform,Q=g.getOrCreateProgram("stars"),ae=o.bL([]);o.bN(ae,ae,-G._pitch),o.bM(ae,ae,-G.angle),o.bN(ae,ae,o.ap(G._center.lat)),o.ek(ae,ae,-o.ap(G._center.lng));const me=o.bR(new Float32Array(16),ae),ye=o.aD([],G.starsProjMatrix,me),Ae=o.eg([],me),Te=o.el([],Ae),Fe=[0,1,0];o.dG(Fe,Fe,Te),o.bJ(Fe,Fe,this.params.sizeMultiplier);const Ye=[1,0,0];o.dG(Ye,Ye,Te),o.bJ(Ye,Ye,this.params.sizeMultiplier);const Ge=(dt=Fe,lt=Ye,_t=P,{u_matrix:Float32Array.from(ye),u_up:dt,u_right:lt,u_intensity_multiplier:_t});var dt,lt,_t;g.uploadCommonUniforms(F,Q),this.starsVx&&this.starsIdx&&Q.draw(g,q.TRIANGLES,Wr.disabled,Gn.disabled,this.colorModeAlphaBlendedWriteRGB,_n.disabled,Ge,"atmosphere_stars",this.starsVx,this.starsIdx,this.starsSegments)}}class Xh{constructor(){this.visibleTiles=[]}updateBorders(g,N){const P=[],F=[],q=g._getRenderableCoordinates(!1,!0);for(const ae of q){const me=g.getTile(ae);if(!me.hasData())continue;const ye=me.getBucket(N);ye&&(ye.isEmpty()||(P.push(ae.key),F.push({bucket:ye,tileID:ae.canonical})))}let G=P.length!==this.visibleTiles.length;if(!G){P.sort();for(let ae=0;aeae.tileID.z-me.tileID.z||ae.tileID.x-me.tileID.x||ae.tileID.y-me.tileID.y);for(const ae of F){const me=new Array,ye=new Array,Ae=ae.bucket;for(const Te of Ae.featuresOnBorder)Q.has(Te.featureId)?ye.push(Te.footprintIndex):(Q.add(Te.featureId),me.push(Te.footprintIndex));Ae.updateFootprintHiddenFlags(me,o.en,!1),Ae.updateFootprintHiddenFlags(ye,o.en,!0)}}}function N4(M,g){const N=[...M],P=g.cameraWorldSizeForFog/g.worldSize,F=o.b9([]);return o.cC(F,F,[P,P,1]),o.aD(N,F,N),o.aD(N,g.worldToFogMatrix,N),N}function wa(M,g,N,P,F){const q=N.material,G=P.context,{baseColorTexture:Q,metallicRoughnessTexture:ae}=q.pbrMetallicRoughness,{normalTexture:me,occlusionTexture:ye,emissionTexture:Ae}=q;function Te(Ye,Ge,dt){if(Ye&&(M.push(Ge),G.activeTexture.set(G.gl.TEXTURE0+dt),Ye.gfxTexture)){const{minFilter:lt,magFilter:_t,wrapS:Ct,wrapT:ht}=Ye.sampler;Ye.gfxTexture.bindExtraParam(lt,_t,Ct,ht)}}Te(Q,"HAS_TEXTURE_u_baseColorTexture",5),Te(ae,"HAS_TEXTURE_u_metallicRoughnessTexture",6),Te(me,"HAS_TEXTURE_u_normalTexture",7),Te(ye,"HAS_TEXTURE_u_occlusionTexture",8),Te(Ae,"HAS_TEXTURE_u_emissionTexture",9),F&&(F.texture||(F.texture=new o.dR(P.context,F.image,[F.image.height,F.image.height,F.image.height],G.gl.RGBA8)),G.activeTexture.set(G.gl.TEXTURE0+10),F.texture&&F.texture.bind(G.gl.LINEAR,G.gl.CLAMP_TO_EDGE),M.push("APPLY_LUT_ON_GPU")),N.texcoordBuffer&&(M.push("HAS_ATTRIBUTE_a_uv_2f"),g.push(N.texcoordBuffer)),N.colorBuffer&&(M.push(N.colorBuffer.itemSize===12?"HAS_ATTRIBUTE_a_color_3f":"HAS_ATTRIBUTE_a_color_4f"),g.push(N.colorBuffer)),N.normalBuffer&&(M.push("HAS_ATTRIBUTE_a_normal_3f"),g.push(N.normalBuffer)),N.pbrBuffer&&(M.push("HAS_ATTRIBUTE_a_pbr"),M.push("HAS_ATTRIBUTE_a_heightBasedEmissiveStrength"),g.push(N.pbrBuffer)),q.alphaMode!=="OPAQUE"&&q.alphaMode!=="MASK"||M.push("UNPREMULT_TEXTURE_IN_SHADER"),q.defined||M.push("DIFFUSE_SHADED");const Fe=P.shadowRenderer;Fe&&(M.push("RENDER_SHADOWS"),Fe.useNormalOffset&&M.push("NORMAL_OFFSET"))}function mb(M,g,N,P,F,q){const G=M.modelOpacity,Q=g.context,ae=new Wr(g.context.gl.LEQUAL,M.isLightMesh?Wr.ReadOnly:Wr.ReadWrite,g.depthRangeFor3D),me=g.transform,ye=M.mesh,Ae=ye.material,Te=Ae.pbrMetallicRoughness,Fe=g.style.fog;let Ye;Ye=g.transform.projection.zAxisUnit==="pixels"?[...M.nodeModelMatrix]:o.aD([],P.zScaleMatrix,M.nodeModelMatrix),o.aD(Ye,P.negCameraPosMatrix,Ye);const Ge=o.b7([],Ye);o.e6(Ge,Ge);const dt=N.paint.get("model-color-use-theme").constantOr("default")==="none",lt=N.paint.get("model-emissive-strength").constantOr(0),_t=qp(new Float32Array(M.worldViewProjection),new Float32Array(Ye),new Float32Array(Ge),null,g,G,Te.baseColorFactor,Ae.emissiveFactor,Te.metallicFactor,Te.roughnessFactor,Ae,lt,N,void 0,void 0,M.materialOverride,M.modelColor),Ct={defines:[]},ht=[],Kt=g.shadowRenderer;Kt&&(Kt.useNormalOffset=!1),wa(Ct.defines,ht,ye,g,dt?null:N.lut);let Lt=null;if(Fe){const It=N4(M.nodeModelMatrix,g.transform);if(Lt=new Float32Array(It),me.projection.name!=="globe"){const Ut=ye.aabb.min,rs=ye.aabb.max,[Zt,ks]=Fe.getOpacityForBounds(It,Ut[0],Ut[1],rs[0],rs[1]);Ct.overrideFog=Zt>=Sn||ks>=Sn}}const Wt=wc(g,N.paint.get("model-cutoff-fade-range"));Wt.shouldRenderCutoff&&Ct.defines.push("RENDER_CUTOFF");const Tt=g.getOrCreateProgram("model",Ct);g.uploadCommonUniforms(Q,Tt,null,Lt,Wt),g.renderPass!=="shadow"&&Kt&&Kt.setupShadowsFromMatrix(M.nodeModelMatrix,Tt),Tt.draw(g,Q.gl.TRIANGLES,ae,F,q,ye.material.doubleSided?_n.disabled:_n.backCCW,_t,N.id,ye.vertexBuffer,ye.indexBuffer,ye.segments,N.paint,g.transform.zoom,void 0,ht)}function Rw(M,g){return M.style._importedAsBasemap?"basemap":g.scope}function Zj(M,g,N,P,F,q,G,Q,ae,me){const ye=M.transform,Ae=!!g.isGeometryBloom&&g.isGeometryBloom;if(Ae&&M.renderPass==="shadow")return;const Te=ye.projection.name==="globe"?o.ev(N,ye):[...N];o.aD(Te,Te,g.globalMatrix);const Fe=o.aD([],P,Te);if(g.meshes)for(const Ye of g.meshes){const Ge=Q.get(Ye.material.name);if(Ge&&Ge.opacity<=0)continue;if(Ye.material.alphaMode!=="BLEND"){G.push({mesh:Ye,depth:0,modelIndex:F,worldViewProjection:Fe,nodeModelMatrix:Te,isLightMesh:Ae,materialOverride:Ge,modelOpacity:ae,modelColor:me,node:g,modelMatrix:N});continue}const dt=o.ah([],Ye.centroid,Fe);!ye.isOrthographic&&dt[2]<=0||q.push({mesh:Ye,depth:dt[2],modelIndex:F,worldViewProjection:Fe,nodeModelMatrix:Te,isLightMesh:Ae,materialOverride:Ge,modelOpacity:ae,modelColor:me,node:g,modelMatrix:N})}if(g.children)for(const Ye of g.children)Zj(M,Ye,N,P,F,q,G,Q,ae,me)}function fb(M,g,N,P){const F=N.shadowRenderer;if(!F)return;const q=F.getShadowPassDepthMode(),G=F.calculateShadowPassMatrixFromMatrix(g),Q=Ew(G);N.getOrCreateProgram("modelDepth").draw(N,N.context.gl.TRIANGLES,q,Gn.disabled,zn.disabled,_n.disabled,Q,P.id,M.vertexBuffer,M.indexBuffer,M.segments,P.paint,N.transform.zoom,void 0,void 0)}function Xj(M,g,N,P){const F=function(ye,Ae){if(Ae.footprintDebugMesh)return Ae.footprintDebugMesh;if(!Ae.footprint)return null;const Te=ye.context,Fe=Ae.footprint.vertices,Ye=Ae.footprint.indices,Ge=new o.dB;Ge.reserve(Fe.length);for(const Ut of Fe)Ge.emplaceBack(Ut.x,Ut.y);const dt=new o.dC;dt.reserve(Ye.length);for(let Ut=0;Ut0){const Te=q.terrain,Fe=Te.findDEMTileFor(Q);Fe&&Fe.dem?ae=o.ex.create(Te,Q,Fe):Ae=0}if(Ae===0&&(G.terrainElevationMin=0,G.terrainElevationMax=0),Ae===G.validForExaggeration&&(Ae===0||ae&&ae._demTile&&ae._demTile.tileID===G.validForDEMTile.id&&ae._dem._timestamp===G.validForDEMTile.timestamp))return!1;for(const Te in G.instancesPerModel){const Fe=G.instancesPerModel[Te];for(let Ye=0;Yeme&&(me=Fe.max)}const ye=o.aC(P.x,q,G)-P.x,Ae=o.aC(P.y,Q,ae)-P.y,Te=o.bU(me,g.center.lat)-P.z;return g._zoomFromMercatorZ(Math.sqrt(ye*ye+Ae*Ae+Te*Te))}function Lo(M,g,N,P,F,q,G){const Q=M.context,ae=M.renderPass==="shadow",me=M.shadowRenderer,ye=ae&&me?me.getShadowPassDepthMode():new Wr(Q.gl.LEQUAL,Wr.ReadWrite,M.depthRangeFor3D),Ae=M.isTileAffectedByFog(q),Te=M.transform.projection.name==="globe";if(N.meshes)for(const Fe of N.meshes){const Ye=Te?[]:["MODEL_POSITION_ON_GPU"],Ge=[];let dt,lt,_t;const Ct=!Te&&P.instancedDataArray.length>20;Ct&&Ye.push("INSTANCED_ARRAYS");const ht=wc(M,g.paint.get("model-cutoff-fade-range"));if(ht.shouldRenderCutoff&&Ye.push("RENDER_CUTOFF"),ae&&me)dt=M.getOrCreateProgram("modelDepth",{defines:Ye}),lt=Ew(G.shadowTileMatrix,G.shadowTileMatrix,Float32Array.from(N.globalMatrix)),_t=zn.disabled;else{wa(Ye,Ge,Fe,M,g.paint.get("model-color-use-theme").constantOr("default")==="none"?null:g.lut),dt=M.getOrCreateProgram("model",{defines:Ye,overrideFog:Ae});const Lt=Fe.material,Wt=Lt.pbrMetallicRoughness,Tt=g.paint.get("model-opacity").constantOr(1),It=g.paint.get("model-emissive-strength").constantOr(0);lt=qp(q.expandedProjMatrix,Float32Array.from(N.globalMatrix),new Float32Array(16),null,M,Tt,Wt.baseColorFactor,Lt.emissiveFactor,Wt.metallicFactor,Wt.roughnessFactor,Lt,It,g,F),me&&(G.shadowUniformsInitialized?dt.setShadowUniformValues(Q,me.getShadowUniformValues()):(me.setupShadows(q.toUnwrapped(),dt,"model-tile"),G.shadowUniformsInitialized=!0)),_t=ht.shouldRenderCutoff||Tt<1||Lt.alphaMode!=="OPAQUE"?zn.alphaBlended:zn.unblended}M.uploadCommonUniforms(Q,dt,q.toUnwrapped(),null,ht);const Kt=Fe.material.doubleSided?_n.disabled:_n.backCCW;if(Ct)Ge.push(P.instancedDataBuffer),dt.draw(M,Q.gl.TRIANGLES,ye,Gn.disabled,_t,Kt,lt,g.id,Fe.vertexBuffer,Fe.indexBuffer,Fe.segments,g.paint,M.transform.zoom,void 0,Ge,P.instancedDataArray.length);else{const Lt=ae?"u_instance":"u_normal_matrix";for(let Wt=0;Wtae[1]?G:ae,q[0]=N.max[0],G=o.aE(o.bE(),q,F),Q=G[1]ae[1]?G:ae,q[1]=N.min[1],G=o.aE(o.bE(),q,F),Q=G[1]ae[1]?G:ae;const me=o.aC(P[0],0,1),ye=100*g.pixelsPerMeter*o.aC(P[1],0,1),Ae=o.aC(P[2],0,1),Te=o.ey(o.bE(),Q,ae,me),Fe=Math.tan(.5*g.fovX),Ye=-Te[2]*Fe;if(ye===0)return Te[1]<-Math.abs(Ye)?Ae:1;const Ge=(-Math.abs(Ye)-Te[1])/ye,dt=(_t,Ct,ht)=>(1-ht)*_t+ht*Ct,lt=o.aC(dt(1,Ae,Ge),Ae,1);return dt(1,lt,o.aC((g.pitch-20)/20,0,1))}class Jj{}class k4{constructor(){this._storage=new Map}getLinesFromTrianglesBuffer(g,N,P){{const Ae=this._storage.get(N.id);if(Ae)return Ae.lastUsedFrameIdx=g,Ae.buf}const F=P.gl,q=F.getBufferParameter(F.ELEMENT_ARRAY_BUFFER,F.BUFFER_SIZE),G=new ArrayBuffer(q),Q=new Int16Array(G);F.getBufferSubData(F.ELEMENT_ARRAY_BUFFER,0,new Int16Array(G));const ae=new o.eA;for(let Ae=0;Ae30&&(P.buf.destroy(),this._storage.delete(N))}destroy(){for(const[g,N]of this._storage)N.buf.destroy(),this._storage.delete(g)}}class S4{constructor(){this.occluderSize=30,this.depthOffset=-1e-4}}const Iv=o.e8([{type:"Float32",name:"a_pos_3f",components:3},{type:"Float32",name:"a_uv",components:2},{type:"Float32",name:"a_rainParticleData",components:4}]);class C4{constructor(g){this.revealStart=11,this.revealRange=2}}const eN=o.e8([{type:"Float32",name:"a_pos_2f",components:2}]);class bM{destroy(){this.vignetteVx&&this.vignetteVx.destroy(),this.vignetteIdx&&this.vignetteIdx.destroy()}draw(g,N){const P=g.getOrCreateProgram("vignette");if(!this.vignetteVx||!this.vignetteIdx){const G=new o.eB,Q=new o.dC;G.emplaceBack(-1,-1),G.emplaceBack(1,-1),G.emplaceBack(1,1),G.emplaceBack(-1,1),Q.emplaceBack(0,1,2),Q.emplaceBack(0,2,3),this.vignetteVx=g.context.createVertexBuffer(G,eN.members),this.vignetteIdx=g.context.createIndexBuffer(Q)}const F=o.dy.simpleSegment(0,0,4,6);if(this.vignetteVx&&this.vignetteIdx){g.uploadCommonUniforms(g.context,P);const G={u_vignetteShape:(q={vignetteShape:[N.start,N.range,Math.pow(10,N.fadePower)],vignetteColor:[N.color.r,N.color.g,N.color.b,N.color.a*N.strength]}).vignetteShape,u_vignetteColor:q.vignetteColor};P.draw(g,g.context.gl.TRIANGLES,Wr.disabled,Gn.disabled,zn.alphaBlended,_n.disabled,G,"vignette",this.vignetteVx,this.vignetteIdx,F)}var q}}class tN{constructor(){this._accumulatedOffsetX=0,this._accumulatedOffsetY=0,this._accumulatedElevation=0}update(g,N){const P=g.getFreeCameraOptions().position,F=P.toAltitude(),q=P.toLngLat(),G=o.ap(q.lng),Q=o.ap(q.lat),ae=g.pixelsPerMeter/N,me=G*o.eD,ye=o.eD*Math.log(Math.tan(Math.PI/4+Q/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 Ae=-this._offsetYPrev+ye,Te=-this._elevationPrev+F;this._accumulatedOffsetX+=(-this._offsetXPrev+me)*ae,this._accumulatedOffsetY+=Ae*ae,this._accumulatedElevation+=Te*ae,this._offsetXPrev=me,this._offsetYPrev=ye,this._elevationPrev=F}}getPosition(){return[this._accumulatedOffsetX,this._accumulatedOffsetY,this._accumulatedElevation]}}function W(M,g){return[-(M[0]-Math.floor(M[0]/g)*g),-(M[1]-Math.floor(M[1]/g)*g),-(M[2]-Math.floor(M[2]/g)*g)]}function X(M){const g=o.em(1323123451230),N=[];for(let P=0;P Rain"),this._vignetteParams={strength:1,start:.7,range:1,fadePower:.4,color:{r:.27,g:.27,b:.27,a:1}},this.particlesCount=16e3}update(g){const N=g.context;if(!this.particlesVx){const P=X(this.particlesCount),F=new o.eE,q=new o.dC;let G=0;const Q=o.em(1323123451230);for(let ae=0;aeP)return;const F=_e(0,1,N.revealStart,N.revealStart+N.revealRange,P);if(!this.particlesVx||!this.particlesIdx)return;const q=structuredClone(this._params);let G=[-q.direction.x,q.direction.y,-100];o.ay(G,G);const Q=structuredClone(this._vignetteParams);Q.strength*=F,q.overrideStyleParameters||(q.intensity=g.style.rain.state.density,q.timeFactor=g.style.rain.state.intensity,q.color=structuredClone(g.style.rain.state.color),G=structuredClone(g.style.rain.state.direction),q.screenThinning.intensity=g.style.rain.state.centerThinning,q.dropletSizeX=g.style.rain.state.dropletSize[0],q.dropletSizeYScale=g.style.rain.state.dropletSize[1]/g.style.rain.state.dropletSize[0],q.distortionStrength=100*g.style.rain.state.distortionStrength,Q.strength=1,Q.color=structuredClone(g.style.rain.state.vignetteColor));const ae=this.updateOnRender(g,q.timeFactor),me=g.context,ye=me.gl,Ae=g.transform;this.screenTexture&&this.screenTexture.size[0]===g.width&&this.screenTexture.size[1]===g.height||(this.screenTexture=new o.T(me,{width:g.width,height:g.height,data:null},ye.RGBA8)),q.distortionStrength>0&&(me.activeTexture.set(ye.TEXTURE0),this.screenTexture.bind(ye.LINEAR,ye.CLAMP_TO_EDGE),ye.copyTexSubImage2D(ye.TEXTURE_2D,0,0,0,0,0,g.width,g.height));const Te=g.getOrCreateProgram("rainParticle");g.uploadCommonUniforms(me,Te),me.activeTexture.set(ye.TEXTURE0),this.screenTexture.bind(ye.LINEAR,ye.CLAMP_TO_EDGE);const Fe=[q.color.r,q.color.g,q.color.b,q.color.a],Ye=(Ge,dt)=>{const lt=W(this._movement.getPosition(),Ge),_t=q.dropletSizeX,Ct=q.dropletSizeX*q.dropletSizeYScale,ht=g.width/2,Kt=g.height/2,Lt=_e(0,q.screenThinning.start,0,1,q.screenThinning.intensity),Wt=_e(.001,q.screenThinning.range,0,1,q.screenThinning.intensity),Tt=_e(0,q.screenThinning.particleOffset,0,1,q.screenThinning.intensity),It=(Ut={modelview:ae.modelviewMatrix,projection:ae.projectionMatrix,time:this._accumulatedTimeFromStart,camPos:lt,velocityConeAperture:q.velocityConeAperture,velocity:q.velocity,boxSize:Ge,rainDropletSize:[_t,Ct],distortionStrength:q.distortionStrength,rainDirection:G,color:Fe,screenSize:[Ae.width,Ae.height],thinningCenterPos:[ht,Kt],thinningShape:[Lt,Wt,Math.pow(10,q.screenThinning.fadePower)],thinningAffectedRatio:q.screenThinning.affectedRatio,thinningParticleOffset:Tt,shapeDirectionalPower:q.shapeDirPower,shapeNormalPower:q.shapeNormalPower,mode:dt?0:1},{u_modelview:Float32Array.from(Ut.modelview),u_projection:Float32Array.from(Ut.projection),u_time:Ut.time,u_cam_pos:Ut.camPos,u_texScreen:0,u_velocityConeAperture:Ut.velocityConeAperture,u_velocity:Ut.velocity,u_boxSize:Ut.boxSize,u_rainDropletSize:Ut.rainDropletSize,u_distortionStrength:Ut.distortionStrength,u_rainDirection:Ut.rainDirection,u_color:Ut.color,u_screenSize:Ut.screenSize,u_thinningCenterPos:Ut.thinningCenterPos,u_thinningShape:Ut.thinningShape,u_thinningAffectedRatio:Ut.thinningAffectedRatio,u_thinningParticleOffset:Ut.thinningParticleOffset,u_shapeDirectionalPower:Ut.shapeDirectionalPower,u_shapeNormalPower:Ut.shapeNormalPower,u_mode:Ut.mode});var Ut;const rs=Math.round(q.intensity*this.particlesCount),Zt=o.dy.simpleSegment(0,0,4*rs,2*rs);Te.draw(g,ye.TRIANGLES,Wr.disabled,Gn.disabled,zn.alphaBlended,_n.disabled,It,"rain_particles",this.particlesVx,this.particlesIdx,Zt)};q.distortionStrength>0&&Ye(q.boxSize,!0),Ye(q.boxSize,!1),this._vignette.draw(g,Q)}}const ft=o.e8([{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 Qt extends Be{constructor(g){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 C4("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(g){const N=g.context;if(!this.particlesVx){const P=X(this.particlesCount),F=new o.eF,q=new o.dC;let G=0;const Q=o.em(1323123451230);for(let ae=0;aeG)return;const Q=_e(0,1,q.revealStart,q.revealStart+q.revealRange,G);F.strength*=Q,N.overrideStyleParameters||(N.intensity=g.style.snow.state.density,N.timeFactor=g.style.snow.state.intensity,N.color=structuredClone(g.style.snow.state.color),P=structuredClone(g.style.snow.state.direction),N.screenThinning.intensity=g.style.snow.state.centerThinning,N.billboardSize=2.79*g.style.snow.state.flakeSize,F.strength=1,F.color=structuredClone(g.style.snow.state.vignetteColor));const ae=this.updateOnRender(g,N.timeFactor);if(!this.particlesVx||!this.particlesIdx)return;const me=g.context,ye=me.gl,Ae=g.transform,Te=g.getOrCreateProgram("snowParticle");g.uploadCommonUniforms(me,Te),((Fe,Ye,Ge)=>{const dt=W(this._movement.getPosition(),Fe),lt=Ae.width/2,_t=Ae.height/2,Ct=_e(0,Ge.screenThinning.start,0,1,Ge.screenThinning.intensity),ht=_e(.001,Ge.screenThinning.range,0,1,Ge.screenThinning.intensity),Kt=_e(0,Ge.screenThinning.particleOffset,0,1,Ge.screenThinning.intensity),Lt=(Wt={modelview:ae.modelviewMatrix,projection:ae.projectionMatrix,time:this._accumulatedTimeFromStart,camPos:dt,velocityConeAperture:Ge.velocityConeAperture,velocity:Ge.velocity,horizontalOscillationRadius:Ge.horizontalOscillationRadius,horizontalOscillationRate:Ge.horizontalOscillationRate,boxSize:Fe,billboardSize:1*Ge.billboardSize,simpleShapeParameters:[Ge.shapeFadeStart,Ge.shapeFadePower],screenSize:[Ae.width,Ae.height],thinningCenterPos:[lt,_t],thinningShape:[Ct,ht,Math.pow(10,Ge.screenThinning.fadePower)],thinningAffectedRatio:Ge.screenThinning.affectedRatio,thinningParticleOffset:Kt,color:[Ge.color.r,Ge.color.g,Ge.color.b,Ge.color.a],direction:P},{u_modelview:Float32Array.from(Wt.modelview),u_projection:Float32Array.from(Wt.projection),u_time:Wt.time,u_cam_pos:Wt.camPos,u_velocityConeAperture:Wt.velocityConeAperture,u_velocity:Wt.velocity,u_horizontalOscillationRadius:Wt.horizontalOscillationRadius,u_horizontalOscillationRate:Wt.horizontalOscillationRate,u_boxSize:Wt.boxSize,u_billboardSize:Wt.billboardSize,u_simpleShapeParameters:Wt.simpleShapeParameters,u_screenSize:Wt.screenSize,u_thinningCenterPos:Wt.thinningCenterPos,u_thinningShape:Wt.thinningShape,u_thinningAffectedRatio:Wt.thinningAffectedRatio,u_thinningParticleOffset:Wt.thinningParticleOffset,u_particleColor:Wt.color,u_direction:Wt.direction});var Wt;const Tt=Math.round(Ge.intensity*this.particlesCount),It=o.dy.simpleSegment(0,0,4*Tt,2*Tt);this.particlesVx&&this.particlesIdx&&Te.draw(g,ye.TRIANGLES,Wr.disabled,Gn.disabled,zn.alphaBlended,_n.disabled,Lt,"snow_particles",this.particlesVx,this.particlesIdx,It)})(N.boxSize,0,N),this._vignette.draw(g,F)}}const rr={symbol:function(M,g,N,P,F){if(M.renderPass!=="translucent")return;const q=Gn.disabled,G=M.colorModeForRenderPass(),Q=N.layout.get("text-variable-anchor"),ae=N.layout.get("text-size-scale-range"),me=o.aC(M.scaleFactor,ae[0],ae[1]);Q&&function(Te,Fe,Ye,Ge,dt,lt,_t,Ct){const ht=Fe.transform,Kt=dt==="map",Lt=lt==="map";for(const Wt of Te){const Tt=Ge.getTile(Wt),It=Tt.getBucket(Ye);if(!It||!It.text||!It.text.segments.get().length)continue;const Ut=o.bj(It.textSizeData,ht.zoom,Ct),rs=Em(Wt,It.getProjection(),ht),Zt=ht.calculatePixelsToTileUnitsMatrix(Tt),ks=fd(rs,Tt.tileID.canonical,Lt,Kt,ht,It.getProjection(),Zt),ms=It.hasIconTextFit()&&It.hasIconData();Ut&&Au(It,Kt,Lt,_t,ht,ks,Wt,Math.pow(2,ht.zoom-Tt.tileID.overscaledZ),Ut,ms)}}(P,M,N,g,N.layout.get("text-rotation-alignment"),N.layout.get("text-pitch-alignment"),F,me);const ye=N.paint.get("icon-opacity").constantOr(1)!==0,Ae=N.paint.get("text-opacity").constantOr(1)!==0;N.layout.get("symbol-sort-key").constantOr(1)!==void 0&&(ye||Ae)?Nh(M,g,N,P,q,G):(ye&&Nh(M,g,N,P,q,G,{onlyIcons:!0}),Ae&&Nh(M,g,N,P,q,G,{onlyText:!0})),g.map.showCollisionBoxes&&(Pr(M,g,N,P,N.paint.get("text-translate"),N.paint.get("text-translate-anchor"),!0),Pr(M,g,N,P,N.paint.get("icon-translate"),N.paint.get("icon-translate-anchor"),!1))},circle:function(M,g,N,P){if(M.renderPass!=="translucent")return;const F=N.paint.get("circle-opacity"),q=N.paint.get("circle-stroke-width"),G=N.paint.get("circle-stroke-opacity"),Q=N.layout.get("circle-sort-key").constantOr(1)!==void 0,ae=N.paint.get("circle-emissive-strength");if(F.constantOr(1)===0&&(q.constantOr(1)===0||G.constantOr(1)===0))return;const me=M.context,ye=me.gl,Ae=M.transform,Te=!(!M.terrain||!M.terrain.enabled),Fe=N.layout.get("circle-elevation-reference"),Ye=M.depthModeForSublayer(0,Wr.ReadOnly),Ge=new Wr(M.context.gl.LEQUAL,Wr.ReadOnly,M.depthRangeFor3D),dt=Fe==="none"||Te?Ye:Ge,lt=Gn.disabled,_t=M.colorModeForDrapableLayerRenderPass(ae),Ct=Ae.projection.name==="globe",ht=[o.aH(Ae.center.lng),o.aL(Ae.center.lat)],Kt=[];for(let Wt=0;WtWt.sortKey-Tt.sortKey);const Lt={useDepthForOcclusion:Ae.depthOcclusionForSymbolsAndCircles};for(const Wt of Kt){const{programConfiguration:Tt,program:It,layoutVertexBuffer:Ut,dynamicBuffers:rs,indexBuffer:Zt,uniformValues:ks,tile:ms}=Wt.state,Ws=Wt.segments;M.terrain&&M.terrain.setupElevationDraw(ms,It,Lt),M.uploadCommonUniforms(me,It,ms.tileID.toUnwrapped()),It.draw(M,ye.TRIANGLES,dt,lt,_t,_n.disabled,ks,N.id,Ut,Zt,Ws,N.paint,Ae.zoom,Tt,rs)}},heatmap:function(M,g,N,P){if(N.paint.get("heatmap-opacity")!==0)if(M.renderPass==="offscreen"){const F=M.context,q=F.gl,G=Gn.disabled,Q=new zn([q.ONE,q.ONE,q.ONE,q.ONE],o.aq.transparent,[!0,!0,!0,!0]),ae=M.transform.projection.name==="globe"?.5:.25;N.heatmapFbo=Aw.createWithTexture(F,N.heatmapFbo,M.width*ae,M.height*ae),F.clear({color:o.aq.transparent});const me=M.transform,ye=me.projection.name==="globe",Ae=ye?["PROJECTION_GLOBE_VIEW"]:[],Te=ye?_n.frontCCW:_n.disabled,Fe=[o.aH(me.center.lng),o.aL(me.center.lat)];for(let Ye=0;Ye({u_image:0,u_color_ramp:1,u_opacity:Ae.paint.get("heatmap-opacity")}))(0,q),q.id,F.viewportBuffer,F.quadTriangleIndexBuffer,F.viewportSegments,q.paint,F.transform.zoom)}(M,N))},line:function(M,g,N,P){const F=N.paint.get("line-opacity"),q=N.paint.get("line-width");if(F.constantOr(1)===0||q.constantOr(1)===0)return;const G=N.paint.get("line-blend-mode");if(G!=="default"&&M.transform.projection.name!=="globe")return M.terrain&&M.terrain.renderingToTexture?void function(Q,ae,me,ye,Ae){if(Q.renderPass!=="translucent")return;const Te=Q.context,Fe=Te.gl,Ye=Q.terrain;if(!Ye)return;const Ge=Te.bindFramebuffer.current,dt=Q.emissiveMode==="mrt-fallback";me.lineBlendDrapeFbo=Aw.createWithTexture(Te,me.lineBlendDrapeFbo,Ye.drapeBufferSize[0],Ye.drapeBufferSize[1],!0),me.lineBlendDrapeStencil=me.lineBlendDrapeFbo._stencilRbo,dt&&Fe.drawBuffers([Fe.COLOR_ATTACHMENT0]),Te.clear({color:bf[Ae].clearColor,depth:1,stencil:0});const lt=Q.currentStencilSource,_t=Q._tileClippingMaskIDs,Ct=Q.nextStencilID;Q.currentStencilSource=void 0,Q._tileClippingMaskIDs={},Q.nextStencilID=1;const ht=Q._terrain;Q._terrain=null,Q._renderTileClippingMasks(me,ae,ye),Kc(Q,ae,me,ye,bf[Ae].colorMode,!0),Q._terrain=ht,Q.currentStencilSource=lt,Q._tileClippingMaskIDs=_t,Q.nextStencilID=Ct,Te.bindFramebuffer.set(Ge),dt&&Fe.drawBuffers([Fe.COLOR_ATTACHMENT0,Fe.COLOR_ATTACHMENT1]);const Kt=Ye.drapeBufferSize;Te.viewport.set([0,0,Kt[0],Kt[1]]);const Lt=me.lineBlendDrapeFbo;if(!Lt)return;Te.activeTexture.set(Fe.TEXTURE0),Fe.bindTexture(Fe.TEXTURE_2D,Lt.colorAttachment0.get());const Wt=Ae==="additive"?1:me.paint.get("line-opacity").constantOr(1),Tt=me.paint.get("line-emissive-strength").constantOr(0),It=Ae==="additive"?Q.colorModeForDrapableLayerRenderPass(Tt):bf[Ae].colorMode;Q.getOrCreateProgram("lineBlendComposite").draw(Q,Fe.TRIANGLES,Wr.disabled,Gn.disabled,It,_n.disabled,Sw(0,Wt,bf[Ae].compositeUniformValue),me.id,Q.viewportBuffer,Q.quadTriangleIndexBuffer,Q.viewportSegments,me.paint,Q.transform.zoom)}(M,g,N,P,G):M.renderPass==="offscreen"?void function(Q,ae,me,ye,Ae){const Te=Q.context,Fe=Math.ceil(Q.width),Ye=Math.ceil(Q.height);me.lineBlendFbo=Aw.createWithTexture(Te,me.lineBlendFbo,Fe,Ye,!0),me.lineBlendStencil=me.lineBlendFbo._stencilRbo,Te.clear({color:bf[Ae].clearColor,depth:1,stencil:0});const Ge=Q.currentStencilSource,dt=Q._tileClippingMaskIDs,lt=Q.nextStencilID;Q.currentStencilSource=void 0,Q._tileClippingMaskIDs={},Q.nextStencilID=1,Q._renderTileClippingMasks(me,ae,ye);const _t=Q.renderPass;Q.renderPass="translucent",Kc(Q,ae,me,ye,bf[Ae].colorMode),Q.renderPass=_t,Q.currentStencilSource=Ge,Q._tileClippingMaskIDs=dt,Q.nextStencilID=lt,Te.viewport.set([0,0,Q.width,Q.height])}(M,g,N,P,G):M.renderPass==="translucent"?void function(Q,ae,me){const ye=Q.context,Ae=ye.gl,Te=ae.lineBlendFbo;if(!Te)return;ye.activeTexture.set(Ae.TEXTURE0),Ae.bindTexture(Ae.TEXTURE_2D,Te.colorAttachment0.get());const Fe=me==="additive"?1:ae.paint.get("line-opacity").constantOr(1),Ye=me==="additive"?Q.colorModeForDrapableLayerRenderPass(ae.paint.get("line-emissive-strength").constantOr(0)):bf[me].colorMode;Q.getOrCreateProgram("lineBlendComposite").draw(Q,Ae.TRIANGLES,Wr.disabled,Gn.disabled,Ye,_n.disabled,Sw(0,Fe,bf[me].compositeUniformValue),ae.id,Q.viewportBuffer,Q.quadTriangleIndexBuffer,Q.viewportSegments,ae.paint,Q.transform.zoom)}(M,N,G):void 0;M.renderPass==="translucent"&&Kc(M,g,N,P)},fill:function(M,g,N,P){const F=N.paint.get("fill-color"),q=N.paint.get("fill-opacity");if(q.constantOr(1)===0)return;const G=N.paint.get("fill-emissive-strength"),Q=M.colorModeForDrapableLayerRenderPass(G),ae=N.paint.get("fill-pattern"),me=M.opaquePassEnabledForLayer()&&!ae.constantOr(1)&&F.constantOr(o.aq.transparent).a===1&&q.constantOr(0)===1?"opaque":"translucent";let ye="none";N.layout.get("fill-elevation-reference")!=="none"?ye="road":N.paint.get("fill-z-offset").constantOr(1)!==0&&(ye="offset");const Ae=!(!M.terrain||!M.terrain.enabled),Te={painter:M,sourceCache:g,layer:N,coords:P,colorMode:Q,elevationType:ye,terrainEnabled:Ae,pass:me};if(M.renderPass==="shadow")return void(M.shadowRenderer&&ye==="road"&&!Ae&&function(Ye){const{painter:Ge,sourceCache:dt,layer:lt,coords:_t}=Ye,Ct=Ge.context.gl,ht=Ye.painter.shadowRenderer;for(const Kt of _t){const Lt=dt.getTile(Kt),Wt=Lt.getBucket(lt);if(!Wt)continue;const Tt=Wt.elevatedStructures;if(!Tt||!Tt.shadowCasterSegments||Tt.shadowCasterSegments.segments[0].primitiveLength===0)continue;Ge.prepareDrawTile();const It=Wt.bufferData.programConfigurations.get(lt.id),Ut=Ge.isTileAffectedByFog(Kt),rs=Ge.getOrCreateProgram("elevatedStructuresDepth",{config:It,overrideFog:Ut}),Zt=ht.calculateShadowPassMatrixFromTile(Lt.tileID.toUnwrapped());Ge.uploadCommonUniforms(Ge.context,rs,Kt.toUnwrapped());const ks=ob(Zt,0);rs.draw(Ge,Ct.TRIANGLES,ht.getShadowPassDepthMode(),Gn.disabled,zn.disabled,_n.disabled,ks,lt.id,Tt.vertexBuffer,Tt.indexBuffer,Tt.shadowCasterSegments,lt.paint,Ge.transform.zoom,It)}}(Te));const Fe=M.emissiveMode==="mrt-fallback";if(ye!=="offset"){if(Ev(Te,!1,Fe),ye==="road"){const Ye=!Ae&&M.renderPass==="translucent";Ye&&ty(M,g,N,P,"geometry"),Ev(Te,!0,Fe,Gn.disabled),Ye&&function(Ge){const{painter:dt,sourceCache:lt,layer:_t,coords:Ct,colorMode:ht}=Ge,Kt=dt.context.gl,Lt=Ge.painter.shadowRenderer,Wt=!!Lt&&Lt.enabled,Tt=new Wr(dt.context.gl.LEQUAL,Wr.ReadOnly,dt.depthRangeFor3D);let It=[0,0,0];if(Wt){const rs=dt.style.directionalLight,Zt=dt.style.ambientLight;rs&&Zt&&(It=pf(dt.style,rs,Zt))}const Ut=rs=>{for(const Zt of Ct){const ks=lt.getTile(Zt),ms=ks.getBucket(_t);if(!ms)continue;const Ws=ms.elevatedStructures;if(!Ws)continue;let sr,as;if(rs?(sr=Ws.renderableBridgeSegments,as=Ws.bridgeProgramConfigurations.get(_t.id)):(sr=Ws.renderableTunnelSegments,as=Ws.tunnelProgramConfigurations.get(_t.id)),!sr||sr.segments[0].primitiveLength===0)continue;as.updatePaintBuffers(),dt.prepareDrawTile();const Xt=dt.isTileAffectedByFog(Zt),ws=[];Wt&&ws.push("RENDER_SHADOWS","NORMAL_OFFSET");const Ts=dt.getOrCreateProgram("elevatedStructures",{config:as,overrideFog:Xt,defines:ws}),Ls=dt.translatePosMatrix(Zt.projMatrix,ks,_t.paint.get("fill-translate"),_t.paint.get("fill-translate-anchor"));Wt&&Lt.setupShadows(ks.tileID.toUnwrapped(),Ts,"vector-tile");const wr=kw(Ls,It);dt.uploadCommonUniforms(dt.context,Ts,Zt.toUnwrapped()),Ts.draw(dt,Kt.TRIANGLES,Tt,Gn.disabled,ht,_n.backCCW,wr,_t.id,Ws.vertexBuffer,Ws.indexBuffer,sr,_t.paint,dt.transform.zoom,as,[Ws.vertexBufferNormal])}};Ut(!0),Ut(!1)}(Te)}}else Ev(Te,!1,Fe,M.stencilModeFor3D())},"fill-extrusion":function(M,g,N,P){const F=N.paint.get("fill-extrusion-opacity"),q=M.context,G=q.gl,Q=M.terrain,ae=Q&&Q.renderingToTexture;if(F===0)return;const me=M.emissiveMode==="mrt-fallback",ye=M.conflationActive&&M.style.isLayerClipped(N,g.getSource()),Ae=M.style.order.indexOf(N.fqid);if(ye&&function(Te,Fe,Ye,Ge,dt){for(const lt of Ge){const _t=Fe.getTile(lt).getBucket(Ye);_t&&(_t.updateReplacement(lt,Te.replacementSource,dt),_t.uploadCentroid(Te.context))}}(M,g,N,P,Ae),Q||ye)for(const Te of P){const Fe=g.getTile(Te).getBucket(N);Fe&&Pg(M.context,g,Te,Fe,N,Q,ye)}if(M.renderPass==="shadow"&&M.shadowRenderer){if(Q&&F<.65&&N._transitionablePaint._values["fill-extrusion-opacity"].value.expression instanceof o.af)return;const Te=M.shadowRenderer.getShadowPassDepthMode();Vp(M,g,N,P,Te,Gn.disabled,zn.disabled,ye)}else if(M.renderPass==="translucent"){const Te=!N.paint.get("fill-extrusion-pattern").constantOr(1),Fe=N.paint.get("fill-extrusion-color").constantOr(o.aq.white);if(!ae&&Fe.a!==0){const Ye=new Wr(M.context.gl.LEQUAL,Wr.ReadWrite,M.depthRangeFor3D);F===1&&Te?Vp(M,g,N,P,Ye,Gn.disabled,zn.unblended,ye):(Vp(M,g,N,P,Ye,Gn.disabled,zn.disabled,ye),Vp(M,g,N,P,Ye,M.stencilModeFor3D(),M.colorModeForRenderPass(),ye),M.resetStencilClippingMasks())}if(M.style.enable3dLights()&&Te&&(!Q&&M.transform.projection.name!=="globe"||ae)){const Ye=N.paint.get("fill-extrusion-opacity"),Ge=N.paint.get("fill-extrusion-ambient-occlusion-intensity"),dt=N.paint.get("fill-extrusion-ambient-occlusion-ground-radius"),lt=N.paint.get("fill-extrusion-flood-light-intensity"),_t=N.paint.get("fill-extrusion-flood-light-color-use-theme").constantOr("default")==="none",Ct=N.paint.get("fill-extrusion-flood-light-color").toNonPremultipliedRenderColor(_t?null:N.lut).toArray01().slice(0,3),ht=Ge>0&&dt>0,Kt=lt>0,Lt=(It,Ut,rs)=>(1-rs)*It+rs*Ut,Wt=new kh;Wt.translate=N.paint.get("fill-extrusion-translate"),Wt.translateAnchor=N.paint.get("fill-extrusion-translate-anchor"),Wt.edgeRadius=N.layout.get("fill-extrusion-edge-radius"),Wt.cutoffFadeRange=N.paint.get("fill-extrusion-cutoff-fade-range");const Tt=It=>{const Ut=M.depthModeForSublayer(1,Wr.ReadOnly,G.LEQUAL,!0),rs=N.paint.get(It?"fill-extrusion-ambient-occlusion-ground-attenuation":"fill-extrusion-flood-light-ground-attenuation"),Zt=Lt(.1,3,rs),ks=M._showOverdrawInspector;if(!ks){const ms=new Gn({func:G.ALWAYS,mask:255},255,255,G.KEEP,G.KEEP,G.REPLACE),Ws=new zn([G.ONE,G.ONE,G.ONE,G.ONE],o.aq.transparent,[!1,!1,!1,!0],G.MIN);ip(Wt,M,g,N,P,Ut,ms,Ws,_n.disabled,It,"sdf",Ye,Ge,dt,lt,Ct,Zt,ye,!1)}{const ms=ks?Gn.disabled:new Gn({func:G.EQUAL,mask:255},255,255,G.KEEP,G.DECR,G.DECR),Ws=ks?M.colorModeForRenderPass():new zn([G.ONE_MINUS_DST_ALPHA,G.DST_ALPHA,G.ONE,G.ONE],o.aq.transparent,[!0,!0,!0,!0]);ip(Wt,M,g,N,P,Ut,ms,Ws,_n.disabled,It,"color",Ye,Ge,dt,lt,Ct,Zt,ye,!1)}};if(ae){const It=()=>{const rs=Q.drapeBufferSize[0],Zt=Q.drapeBufferSize[1];let ks=Q.framebufferCopyTexture;return ks&&(!ks||ks.size[0]===rs&&ks.size[1]===Zt)||(ks&&ks.destroy(),ks=Q.framebufferCopyTexture=new o.T(q,new o.q({width:rs,height:Zt}),G.RGBA8)),ks.bind(G.LINEAR,G.CLAMP_TO_EDGE),G.copyTexSubImage2D(G.TEXTURE_2D,0,0,0,0,0,rs,Zt),ks},Ut=(rs,Zt,ks)=>{const ms=M.depthModeForSublayer(1,Wr.ReadOnly,G.LEQUAL,!1),Ws=N.paint.get(rs?"fill-extrusion-ambient-occlusion-ground-attenuation":"fill-extrusion-flood-light-ground-attenuation"),sr=Lt(.1,3,Ws);{const as=new zn([G.ONE,G.ONE,G.ONE,G.ONE],o.aq.transparent,[!1,!1,!1,!0]);ip(Wt,M,g,N,P,ms,Gn.disabled,as,_n.disabled,rs,"clear",Ye,Ge,dt,lt,Ct,sr,ye,Zt)}{const as=new Gn({func:G.ALWAYS,mask:255},255,255,G.KEEP,G.KEEP,G.REPLACE),Xt=new zn([G.ONE,G.ONE,G.ONE,G.ONE],o.aq.transparent,[!1,!1,!1,!0],G.MIN);ip(Wt,M,g,N,P,ms,as,Xt,_n.disabled,rs,"sdf",Ye,Ge,dt,lt,Ct,sr,ye,Zt)}me&&!rs&&(ks=It());{const as=rs?G.ZERO:G.ONE_MINUS_DST_ALPHA,Xt=new Gn({func:G.EQUAL,mask:255},255,255,G.KEEP,G.DECR,G.DECR),ws=new zn([as,G.DST_ALPHA,G.ONE_MINUS_DST_ALPHA,G.ZERO],o.aq.transparent,[!0,!0,!0,!0]);ip(Wt,M,g,N,P,ms,Xt,ws,_n.disabled,rs,"color",Ye,Ge,dt,lt,Ct,sr,ye,Zt)}if(!me||rs){const as=new zn([G.ONE,G.ONE,G.ONE,rs?G.ZERO:G.ONE],o.aq.transparent,[!1,!1,!1,!0],rs?G.FUNC_ADD:G.MAX);ip(Wt,M,g,N,P,ms,Gn.disabled,as,_n.disabled,rs,"clear",Ye,Ge,dt,lt,Ct,sr,ye,Zt,ks)}else{G.drawBuffers([G.NONE,G.COLOR_ATTACHMENT1]);const as=new Gn({func:G.EQUAL,mask:255},254,255,G.KEEP,G.DECR,G.DECR),Xt=new zn([G.ONE,G.ONE,G.ONE,G.ONE],o.aq.transparent,[!0,!1,!1,!1],G.MAX);ip(Wt,M,g,N,P,ms,as,Xt,_n.disabled,rs,"emissive",Ye,Ge,dt,lt,Ct,sr,ye,Zt,ks),G.drawBuffers([G.COLOR_ATTACHMENT0])}};if(ht||Kt){let rs;M.prepareDrawTile(),me&&!ht||(rs=It()),ht&&Ut(!0,!1,rs),Kt&&Ut(!1,!0,rs)}}else ht&&Tt(!0),Kt&&Tt(!1),(ht||Kt)&&M.resetStencilClippingMasks()}}},building:function(M,g,N,P){M.currentLayer0&&q>0,me=!0;const ye=N.paint.get("building-vertical-scale");if(ye<=0)return;M.shadowRenderer||(me=!1);const Ae=M.conflationActive&&M.style.isLayerClipped(N,g.getSource()),Te=M.style.order.indexOf(N.fqid);if(function(Fe,Ye,Ge,dt,lt,_t){for(const Ct of _t){const ht=Ye.getTile(Ct).getBucket(Ge);ht&&(lt&&ht.updateReplacement(Ct,Fe.replacementSource,dt),ht.uploadUpdatedIndexBuffer(Fe.context))}}(M,g,N,Te,Ae,P),function(Fe,Ye,Ge,dt){for(const lt of dt){const _t=Ye.getTile(lt).getBucket(Ge);_t&&_t.needsEvaluation()&&_t.uploadUpdatedColorBuffer(Fe.context)}}(M,g,N,P),N.resetLayerRenderingStats(M),M.shadowRenderer&&(M.shadowRenderer.useNormalOffset=!0),M.renderPass==="shadow"&&M.shadowRenderer){const Fe=[],Ye=M.shadowRenderer.getShadowPassDepthMode();sy({painter:M,source:g,layer:N,coords:P,defines:Fe,blendMode:zn.disabled,depthMode:Ye,opacity:Q,verticalScale:ye,facadeEmissiveChance:0,facadeAOIntensity:0,floodLightIntensity:0,floodLightColor:[0,0,0]})}else if(M.renderPass==="translucent"){let Fe=["HAS_ATTRIBUTE_a_part_color_emissive","LIGHTING_3D_MODE"];me&&(Fe=Fe.concat("RENDER_SHADOWS")),M.shadowRenderer&&M.shadowRenderer.useNormalOffset&&(Fe=Fe.concat("NORMAL_OFFSET"));const Ye=N.paint.get("building-facade-emissive-chance"),Ge=N.paint.get("building-ambient-occlusion-intensity"),dt=N.paint.get("building-flood-light-intensity"),lt=N.paint.get("building-flood-light-color-use-theme").constantOr("default")==="none",_t=N.paint.get("building-flood-light-color").toNonPremultipliedRenderColor(lt?null:N.lut).toArray01().slice(0,3),Ct=N.paint.get("building-flood-light-ground-attenuation"),ht=dt>0,Kt=new Wr(M.context.gl.LEQUAL,Wr.ReadWrite,M.depthRangeFor3D);Q<1&&sy({painter:M,source:g,layer:N,coords:P,defines:Fe,blendMode:zn.disabled,depthMode:Kt,opacity:Q,verticalScale:ye,facadeEmissiveChance:Ye,facadeAOIntensity:Ge,floodLightIntensity:dt,floodLightColor:_t,depthOnly:!0});const Lt=M.colorModeForRenderPass();sy({painter:M,source:g,layer:N,coords:P,defines:Fe,blendMode:Lt,depthMode:Kt,opacity:Q,verticalScale:ye,facadeEmissiveChance:Ye,facadeAOIntensity:Ge,floodLightIntensity:dt,floodLightColor:_t});const Wt=N.paint.get("building-front-cutoff");db(M.transform.pitch,Wt,!!M.terrain),ae&&Lg(M,g,N,P,!0,Q,F,q,dt,_t,G,Ae),ht&&Lg(M,g,N,P,!1,Q,F,q,dt,_t,Ct,Ae)}else if(M.renderPass==="light-beam"){const Fe=["HAS_ATTRIBUTE_a_part_color_emissive","HAS_ATTRIBUTE_a_bloom_attenuation"],Ye=new Wr(M.context.gl.LEQUAL,Wr.ReadOnly,M.depthRangeFor3D);sy({painter:M,source:g,layer:N,coords:P,defines:Fe,blendMode:zn.alphaBlended,depthMode:Ye,opacity:Q,verticalScale:ye,facadeEmissiveChance:0,facadeAOIntensity:0,floodLightIntensity:0,floodLightColor:[0,0,0]})}M.shadowRenderer&&(M.shadowRenderer.useNormalOffset=!1),M.resetStencilClippingMasks()},hillshade:function(M,g,N,P){if(M.renderPass!=="offscreen"&&M.renderPass!=="translucent"||M.style.disableElevatedTerrain)return;const F=M.context,q=M.terrain&&M.terrain.renderingToTexture,[G,Q]=M.renderPass!=="translucent"||q?[{},P]:M.stencilConfigForOverlap(P);for(const ae of Q){const me=g.getTile(ae);if(me.needsHillshadePrepare&&M.renderPass==="offscreen")oM(M,me,N);else if(M.renderPass==="translucent"){const ye=M.depthModeForSublayer(0,Wr.ReadOnly),Ae=N.paint.get("hillshade-emissive-strength"),Te=M.colorModeForDrapableLayerRenderPass(Ae),Fe=q&&M.terrain?M.terrain.stencilModeForRTTOverlap(ae):G[ae.overscaledZ];oD(M,ae,me,N,ye,Fe,Te)}}F.viewport.set([0,0,M.width,M.height]),M.resetStencilClippingMasks()},raster:function(M,g,N,P,F,q){if(M.renderPass!=="translucent")return;const G=N.paint.get("raster-opacity");if(G===0)return;const Q=M.transform.projection.name==="globe",ae=N.paint.get("raster-elevation")!==0,me=ae&&Q,ye=M.terrain&&M.terrain.exaggeration()>0&&ae&&N.paint.get("raster-elevation-reference")==="ground",Ae=!Q&&ye;if(M.renderElevatedRasterBackface&&!me)return;const Te=M.context,Fe=Te.gl,Ye=g.getSource(),Ge=function(It,Ut,rs,Zt,ks){const ms=Ut.paint.get("raster-color"),Ws=It.type==="raster-array",sr=[],as=Ut.paint.get("raster-resampling"),Xt=Ut.paint.get("raster-color-mix");let ws=Ut.paint.get("raster-color-range");const Ts=[Xt[0],Xt[1],Xt[2],0],Ls=Xt[3];let wr=as==="nearest"?Zt.NEAREST:Zt.LINEAR;if(Ws&&(sr.push("RASTER_ARRAY"),ms||sr.push("RASTER_COLOR"),as==="linear"&&sr.push("RASTER_ARRAY_LINEAR"),wr=Zt.NEAREST,!ws&&It.rasterLayers)){const mr=It.rasterLayers.find(({id:fr})=>fr===Ut.sourceLayer);mr&&mr.fields&&mr.fields.range&&(ws=mr.fields.range)}if(ws=ws||[0,1],ms){sr.push("RASTER_COLOR"),rs.activeTexture.set(Zt.TEXTURE2),Ut.updateColorRamp(ws);let mr=Ut.colorRampTexture;mr||(mr=Ut.colorRampTexture=new o.T(rs,Ut.colorRamp,Zt.RGBA8)),mr.bind(wr,Zt.CLAMP_TO_EDGE)}return ks&&sr.push("USE_MRT1"),{mix:Ts,range:ws,offset:Ls,defines:sr,resampling:wr}}(Ye,N,Te,Fe,M.terrain&&M.terrain.renderingToTexture&&M.emissiveMode==="mrt-fallback");if(Ye instanceof o.aV&&!P.length&&!Q)return;const dt=N.paint.get("raster-emissive-strength"),lt=M.colorModeForDrapableLayerRenderPass(dt),_t=M.terrain&&M.terrain.renderingToTexture,Ct=!M.options.moving,ht=N.paint.get("raster-resampling")==="nearest"?Fe.NEAREST:Fe.LINEAR;if(Ye instanceof o.aV&&!P.length&&(Ye.onNorthPole||Ye.onSouthPole)){const It=ae?M.stencilModeFor3D():Gn.disabled;return void ry(!!Ye.onNorthPole,null,M,g,N,dt,Ge,_n.disabled,It)}if(!P.length)return;const[Kt,Lt]=Ye instanceof o.aV||_t?[{},P]:M.stencilConfigForOverlap(P),Wt=Lt[Lt.length-1].overscaledZ;me&&Ge.defines.push("PROJECTION_GLOBE_VIEW"),ae&&Ge.defines.push("RENDER_CUTOFF","ELEVATED"),ye&&Ge.defines.push("ELEVATION_REFERENCE_GROUND");const Tt=(It,Ut,rs)=>{for(const Zt of It){const ks=Zt.toUnwrapped(),ms=g.getTile(Zt);if(_t&&(!ms||!ms.hasData()))continue;Te.activeTexture.set(Fe.TEXTURE0);const Ws=Lw(ms,Ye,N,Ge);if(!Ws||!Ws.texture)continue;const{texture:sr,mix:as,offset:Xt,tileSize:ws,buffer:Ts}=Ws;let Ls,wr;_t?(Ls=Wr.disabled,wr=Zt.projMatrix):ae?(Ls=new Wr(Fe.LEQUAL,Wr.ReadWrite,M.depthRangeFor3D),wr=Q?Float32Array.from(M.transform.expandedFarZProjMatrix):M.transform.calculateProjMatrix(ks,Ct)):(Ls=M.depthModeForSublayer(Zt.overscaledZ-Wt,G===1?Wr.ReadWrite:Wr.ReadOnly,Fe.LESS),wr=M.transform.calculateProjMatrix(ks,Ct));const mr=M.terrain&&_t?M.terrain.stencilModeForRTTOverlap(Zt):Kt[Zt.overscaledZ],fr=q?0:N.paint.get("raster-fade-duration");ms.registerFadeDuration(fr);const Js=g.findLoadedParent(Zt,0),en=Rm(ms,Js,g,M.transform,fr);let dn,Kr;!en.isFading&&ms.refreshedUponExpiration&&(ms.refreshedUponExpiration=!1),M.terrain&&M.terrain.prepareDrawTile(),Te.activeTexture.set(Fe.TEXTURE0),sr.bind(ht,Fe.CLAMP_TO_EDGE),Te.activeTexture.set(Fe.TEXTURE1),Js?(Js.texture&&Js.texture.bind(ht,Fe.CLAMP_TO_EDGE),dn=Math.pow(2,Js.tileID.overscaledZ-ms.tileID.overscaledZ),Kr=[ms.tileID.canonical.x*dn%1,ms.tileID.canonical.y*dn%1]):sr.bind(ht,Fe.CLAMP_TO_EDGE),"useMipmap"in sr&&Te.extTextureFilterAnisotropic&&M.transform.pitch>20&&Fe.texParameterf(Fe.TEXTURE_2D,Te.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,Te.extTextureFilterAnisotropicMax);const Jr=M.transform;let $n;const oa=ae?Pw(Jr):[0,0,0,0];let ra,Ra,Ln,Oa,na,ji=0;if(me&&Ye instanceof o.aV&&Ye.coordinates.length>3)ra=Float32Array.from(o.du(o.dv(new o.cn(0,0,0)))),Ra=Float32Array.from(Jr.globeMatrix),Ln=Float32Array.from(o.dq(Jr)),Oa=[o.aH(Jr.center.lng),o.aL(Jr.center.lat)],$n=Ye.elevatedGlobePerspectiveTransform,na=Ye.elevatedGlobeGridMatrix||new Float32Array(9);else if(me){const Ii=o.dr(Zt.canonical);ji=o.ds(Ii.getCenter().lat),ra=Float32Array.from(o.du(o.dv(Zt.canonical))),Ra=Float32Array.from(Jr.globeMatrix),Ln=Float32Array.from(o.dq(Jr)),Oa=[o.aH(Jr.center.lng),o.aL(Jr.center.lat)],$n=[0,0],na=Float32Array.from(o.dt(Zt.canonical,Ii,ji,Jr.worldSize/Jr._pixelsPerMercatorPixel))}else $n=Ye instanceof o.aV?Ye.perspectiveTransform:[0,0],ra=new Float32Array(16),Ra=new Float32Array(9),Ln=new Float32Array(16),Oa=[0,0],na=new Float32Array(9);const uo=zp(M,wr,ra,Ra,Ln,na,Kr||[0,0],o.al(M.transform.zoom),Oa,oa,dn||1,en,N,$n,ae?N.paint.get("raster-elevation"):0,2,as,Xt,Ge.range,ws,Ts,dt),rl=M.isTileAffectedByFog(Zt),ko=M.getOrCreateProgram("raster",{defines:Ge.defines,overrideFog:rl});if(M.uploadCommonUniforms(Te,ko,ks),Ye instanceof o.aV){const Ii=Ye.elevatedGlobeVertexBuffer,Ca=Ye.elevatedGlobeIndexBuffer;if(_t||!Q)Ye.boundsBuffer&&Ye.boundsSegments&&ko.draw(M,Fe.TRIANGLES,Ls,Gn.disabled,lt,_n.disabled,uo,N.id,Ye.boundsBuffer,M.quadTriangleIndexBuffer,Ye.boundsSegments);else if(Ii&&Ca){const Ta=Jr.zoom<=o.cJ?Ye.elevatedGlobeSegments:Ye.getSegmentsForLongitude(Jr.center.lng);Ta&&ko.draw(M,Fe.TRIANGLES,Ls,Gn.disabled,lt,Ut,uo,N.id,Ii,Ca,Ta)}}else if(me){Ls=new Wr(Fe.LEQUAL,Wr.ReadOnly,M.depthRangeFor3D);const Ii=M.globeSharedBuffers;if(Ii){ye&&(M.terrain.setupElevationDraw(ms,ko),M.uploadCommonUniforms(Te,ko,ms.tileID.toUnwrapped()));const[Ca,Ta,So]=Ii.getGridBuffers(ji,!1),dl=ko.getAttributeLocation(Fe,"a_texture_pos");dl!==-1&&Fe.vertexAttribI4ui(dl,0,0,0,0),ko.draw(M,Fe.TRIANGLES,Ls,rs||mr,M.colorModeForRenderPass(),Ut,uo,N.id,Ca,Ta,So)}}else if(Ae)Ls=new Wr(Fe.LEQUAL,Wr.ReadWrite,M.depthRangeFor3D),M.terrain.setupElevationDraw(ms,ko),M.uploadCommonUniforms(Te,ko,ms.tileID.toUnwrapped()),Jr.pitch>20&&ko.draw(M,Fe.TRIANGLES,Ls,Gn.disabled,zn.disabled,_n.frontCCW,uo,N.id,M.terrain.gridBuffer,M.terrain.gridIndexBuffer,M.terrain.gridSegments),ko.draw(M,Fe.TRIANGLES,Ls,mr,lt,_n.backCCW,uo,N.id,M.terrain.gridBuffer,M.terrain.gridIndexBuffer,M.terrain.gridSegments);else{const{tileBoundsBuffer:Ii,tileBoundsIndexBuffer:Ca,tileBoundsSegments:Ta}=M.getTileBoundsBuffers(ms);ko.draw(M,Fe.TRIANGLES,Ls,mr,lt,_n.disabled,uo,N.id,Ii,Ca,Ta)}}if(!(Ye instanceof o.aV)&&me)for(const Zt of It){const ks=Zt.canonical.y===(1<o.d$[Ts](ks));as.push(ks);const Xt=ks.canonical.x,ws=ks.canonical.y;for(const Ts of as){const Ls=ht.getTile(Ut?Ts.wrapped():Ts);if(!Ls)continue;const wr=Ls.rasterParticleState;if(!wr)continue;const mr=Ts.canonical.x+(1<Wt.tileID)),Fe&&(me.activeTexture.set(ye.TEXTURE0),M.imageManager.bind(M.context,N.scope));const Lt=[];if(M.terrain&&M.terrain.renderingToTexture&&M.emissiveMode==="mrt-fallback"&&Lt.push("USE_MRT1"),ae){const Wt=M.getOrCreateProgram(Ct,{overrideFog:!1,overrideRtt:!0,defines:Lt}),Tt=new Float32Array(o.b9([])),It=new o.aR(0,0,0,0,0),Ut=Fe?Up(Tt,Q,G,M,0,N.scope,Ye,ae,{tileID:It,tileSize:Te}):ey(Tt,Q,G,F.toPremultipliedRenderColor(q?null:N.lut));return void Wt.draw(M,ye.TRIANGLES,lt,dt,_t,_n.disabled,Ut,N.id,M.viewportBuffer,M.quadTriangleIndexBuffer,M.viewportSegments)}for(const Wt of Kt){const Tt=M.isTileAffectedByFog(Wt),It=M.getOrCreateProgram(Ct,{overrideFog:Tt,defines:Lt}),Ut=Wt.toUnwrapped(),rs=P?Wt.projMatrix:M.transform.calculateProjMatrix(Ut);M.prepareDrawTile();const Zt=g?g.getTile(Wt):ht?ht[Wt.key]:new o.b0(Wt,Te,Ae.zoom,M),ks=Fe?Up(rs,Q,G,M,0,N.scope,Ye,ae,{tileID:Wt,tileSize:Te}):ey(rs,Q,G,F.toPremultipliedRenderColor(q?null:N.lut));M.uploadCommonUniforms(me,It,Ut);const{tileBoundsBuffer:ms,tileBoundsIndexBuffer:Ws,tileBoundsSegments:sr}=M.getTileBoundsBuffers(Zt);It.draw(M,ye.TRIANGLES,lt,dt,_t,_n.disabled,ks,N.id,ms,Ws,sr)}},sky:function(M,g,N){const P=M._atmosphere?o.al(M.transform.zoom):1,F=N.paint.get("sky-opacity")*P;if(F===0)return;const q=M.context,G=N.paint.get("sky-type"),Q=new Wr(q.gl.LEQUAL,Wr.ReadOnly,[0,1]),ae=M.frameCounter/1e3%1;G==="atmosphere"?M.renderPass==="offscreen"?N.needsSkyboxCapture(M)&&(function(me,ye){const Ae=me.context,Te=Ae.gl;let Fe=ye.skyboxFbo;if(!Fe){Fe=ye.skyboxFbo=Ae.createFramebuffer(32,32,1,null),ye.skyboxGeometry=new Ld(Ae),ye.skyboxTexture=Ae.gl.createTexture(),Te.bindTexture(Te.TEXTURE_CUBE_MAP,ye.skyboxTexture),Te.texParameteri(Te.TEXTURE_CUBE_MAP,Te.TEXTURE_WRAP_S,Te.CLAMP_TO_EDGE),Te.texParameteri(Te.TEXTURE_CUBE_MAP,Te.TEXTURE_WRAP_T,Te.CLAMP_TO_EDGE),Te.texParameteri(Te.TEXTURE_CUBE_MAP,Te.TEXTURE_MIN_FILTER,Te.LINEAR),Te.texParameteri(Te.TEXTURE_CUBE_MAP,Te.TEXTURE_MAG_FILTER,Te.LINEAR);for(let lt=0;lt<6;++lt)Te.texImage2D(Te.TEXTURE_CUBE_MAP_POSITIVE_X+lt,0,Te.RGBA,32,32,0,Te.RGBA,Te.UNSIGNED_BYTE,null)}Ae.bindFramebuffer.set(Fe.framebuffer),Ae.viewport.set([0,0,32,32]);const Ye=ye.getCenter(me,!0),Ge=me.getOrCreateProgram("skyboxCapture"),dt=new Float64Array(16);o.b9(dt),o.ef(dt,dt,.5*-Math.PI),_f(me,ye,Ge,dt,Ye,0),o.b9(dt),o.ef(dt,dt,.5*Math.PI),_f(me,ye,Ge,dt,Ye,1),o.b9(dt),o.cE(dt,dt,.5*-Math.PI),_f(me,ye,Ge,dt,Ye,2),o.b9(dt),o.cE(dt,dt,.5*Math.PI),_f(me,ye,Ge,dt,Ye,3),o.b9(dt),_f(me,ye,Ge,dt,Ye,4),o.b9(dt),o.ef(dt,dt,Math.PI),_f(me,ye,Ge,dt,Ye,5),Ae.viewport.set([0,0,me.width,me.height])}(M,N),N.markSkyboxValid(M)):M.renderPass==="sky"&&function(me,ye,Ae,Te,Fe){const Ye=me.context,Ge=Ye.gl,dt=me.transform,lt=me.getOrCreateProgram("skybox");Ye.activeTexture.set(Ge.TEXTURE0),Ge.bindTexture(Ge.TEXTURE_CUBE_MAP,ye.skyboxTexture);const _t=((Ct,ht,Kt,Lt,Wt)=>({u_matrix:Ct,u_sun_direction:ht,u_cubemap:0,u_opacity:Lt,u_temporal_offset:Wt}))(dt.skyboxMatrix,ye.getCenter(me,!1),0,Te,Fe);me.uploadCommonUniforms(Ye,lt),lt.draw(me,Ge.TRIANGLES,Ae,Gn.disabled,me.colorModeForRenderPass(),_n.backCW,_t,"skybox",ye.skyboxGeometry.vertexBuffer,ye.skyboxGeometry.indexBuffer,ye.skyboxGeometry.segment)}(M,N,Q,F,ae):G==="gradient"&&M.renderPass==="sky"&&function(me,ye,Ae,Te,Fe){const Ye=me.context,Ge=Ye.gl,dt=me.transform,lt=me.getOrCreateProgram("skyboxGradient");ye.skyboxGeometry||(ye.skyboxGeometry=new Ld(Ye)),Ye.activeTexture.set(Ge.TEXTURE0);let _t=ye.colorRampTexture;_t||(_t=ye.colorRampTexture=new o.T(Ye,ye.colorRamp,Ge.RGBA8)),_t.bind(Ge.LINEAR,Ge.CLAMP_TO_EDGE);const Ct=((ht,Kt,Lt,Wt,Tt)=>({u_matrix:ht,u_color_ramp:0,u_center_direction:Kt,u_radius:o.ap(Lt),u_opacity:Wt,u_temporal_offset:Tt}))(dt.skyboxMatrix,ye.getCenter(me,!1),ye.paint.get("sky-gradient-radius"),Te,Fe);me.uploadCommonUniforms(Ye,lt),lt.draw(me,Ge.TRIANGLES,Ae,Gn.disabled,me.colorModeForRenderPass(),_n.backCW,Ct,"skyboxGradient",ye.skyboxGeometry.vertexBuffer,ye.skyboxGeometry.indexBuffer,ye.skyboxGeometry.segment)}(M,N,Q,F,ae)},custom:function(M,g,N,P){const F=M.context,q=N.implementation;if(!M.transform.projection.unsupportedLayers||!M.transform.projection.unsupportedLayers.includes("custom")||M.terrain&&(M.terrain.renderingToTexture||M.renderPass==="offscreen")&&N.isDraped(g)){if(M.renderPass==="offscreen"){const G=q.prerender;if(G){if(M.setCustomLayerDefaults(),F.setColorMode(M.colorModeForRenderPass()),M.transform.projection.name==="globe"){const Q=M.transform.pointMerc;G.call(q,F.gl,M.transform.customLayerMatrix(),M.transform.getProjection(),M.transform.globeToMercatorMatrix(),o.al(M.transform.zoom),[Q.x,Q.y],M.transform.pixelsPerMeterRatio)}else G.call(q,F.gl,M.transform.customLayerMatrix());F.setDirty(),M.setBaseState()}}else if(M.renderPass==="translucent"){if(M.terrain&&M.terrain.renderingToTexture){const Q=q.renderToTile;if(Q){const ae=P[0].canonical,me={x:ae.x+P[0].wrap*(q.wrapTileId?0:1<{me&&(me.useNormalOffset=!0,ye||(me.enabled=!0))},Te=g.getSource();if(M.renderPass==="light-beam"&&Te.type!=="batched-model")return;if(Te.type==="vector"||Te.type==="geojson")return function(ht,Kt,Lt,Wt,Tt){const It=ht.transform,Ut=It.projection.name==="globe",rs=It.getFreeCameraOptions().position;if(!ht.modelManager)return;const Zt=ht.modelManager;Lt.modelManager=Zt;const ks=ht.shadowRenderer;if(!Lt._unevaluatedLayout._values.hasOwnProperty("model-id"))return;const ms=Lt._unevaluatedLayout._values["model-id"],Ws=Object.assign({},Lt.layout.get("model-id").parameters),sr=ht.style.order.indexOf(Lt.fqid),as=Lt.paint.get("model-opacity").constantOr(1);for(const Xt of Wt){const ws=Kt.getTile(Xt).getBucket(Lt);if(!ws||ws.projection.name!==It.projection.name)continue;const Ts=ws.getModelUris();if(Ts&&!ws.modelsRequested&&(Zt.addModelsFromBucket(Ts,Tt),ws.modelsRequested=!0),Ut)Ws.zoom=Xt.overscaledZ;else{const Kr=wf(Xt,It);Ws.zoom=Kr}const Ls=ms.possiblyEvaluate(Ws);if(ur(ht,ws,Xt),dr.shadowUniformsInitialized=!1,dr.useSingleShadowCascade=!!ks&&ks.getMaxCascadeForTile(Xt.toUnwrapped())===0,ht.renderPass==="shadow"&&ks){if(ht.currentShadowCascade===1&&ws.isInsideFirstShadowMapFrustum)continue;const Kr=It.calculatePosMatrix(Xt.toUnwrapped(),It.worldSize);if(dr.tileMatrix.set(Kr),dr.shadowTileMatrix=Float32Array.from(ks.calculateShadowPassMatrixFromMatrix(Kr)),dr.aabb.min=[0,0,0],dr.aabb.max[0]=dr.aabb.max[1]=o.an,dr.aabb.max[2]=0,Ow(ws,dr,ht,Lt.scope))continue}const wr=1<0&&ht.style.isLayerClipped(Lt,Kt.getSource())&&ws.updateReplacement(Xt,ht.replacementSource,sr,Lt.scope)&&(ws.uploaded=!1,ws.upload(ht.context));let fr=0;const Js=new Array,en=new Array,dn=new Array;for(let Kr in ws.instancesPerModel){const Jr=ws.instancesPerModel[Kr];Jr.features.length>0&&!Ut&&(Kr=Ls.evaluate(Jr.features[0].feature,{}));const $n=Zt.getModel(Kr,Tt);if($n||Zt.hasURLBeenRequested(Kr)||ws.modelUris.includes(Kr)||(ws.modelUris.push(Kr),ws.modelsRequested=!1),$n&&$n.uploaded)if(Ut){const oa=o.bJ([],[rs.x,rs.y,rs.z],ht.transform.worldSize);o.eo(oa,oa);for(let ra=0;ra0&&Oa.elevationUpdate(Kr.terrain,ra,Ln,$n.source),Oa.needsReEvaluation(Kr,Ra,$n)&&Oa.evaluate($n))}})(ht,Kt,Lt,Wt),function(){const Kr=new Map;let Jr,$n,oa;Js?(Jr=Wt.length-1,$n=-1,oa=-1):(Jr=0,$n=Wt.length,oa=1);const ra=new Float64Array(16),Ra=o.ce(),Ln=new o.P(0,0);for(let Oa=Jr;Oa!==$n;Oa+=oa){const na=Wt[Oa],ji=Kt.getTile(na).getBucket(Lt);if(!ji||!ji.uploaded)continue;let uo=!1;rs&&(uo=rs.getMaxCascadeForTile(na.toUnwrapped())===0);const rl=It.calculatePosMatrix(na.toUnwrapped(),It.worldSize),ko=ji.modelTraits;!wr&&Js&&(o.b7(ra,rl),o.ah(Ra,ks,ra),Ln.x=Ra[0],Ln.y=Ra[1]);const Ii=[];ji.setFilter(Lt.filter);for(const Ca of ji.getNodesInfo()){if(Ca.hiddenByReplacement||!Ca.node.meshes)continue;const Ta=Ca.node;let So=0;ht.terrain&&Ta.elevation&&(So=Ta.elevation*ht.terrain.exaggeration());const dl=(()=>{const eu=Ca.aabb;return Ls.min=[...eu.min],Ls.max=[...eu.max],Ls.min[2]+=So,Ls.max[2]+=So,o.ah(Ls.min,Ls.min,rl),o.ah(Ls.max,Ls.max,rl),Ls})(),Pi=Ca.evaluatedScale;if(Pi[0]<=1&&Pi[1]<=1&&Pi[2]<=1&&dl.intersects(mr)===0)continue;if(!wr&&Js){const eu=.16666666666666666;Ca.cameraCollisionOpacity=ks[0]>dl.min[0]&&ks[0]dl.min[1]&&ks[1]!Js||Ca.opacity===1&&Ta.opacity===1?Ca.depthTa.depth?-1:1);for(const Ca of Ii){const Ta=Ca.nodeInfo,So=Ta.node;if(ht._debugParams.show3DModelFootprints&&So.footprint){const ei=So.id||So.name||"footprint";Kr.has(ei)||Kr.set(ei,{node:So,mvp:Ca.wvpForTile})}let dl=o.aD([],as,Ca.tileModelMatrix);o.aD(dl,Ws,dl);const Pi=o.b7([],dl);o.e6(Pi,Pi),o.cC(Pi,Pi,es),dl=o.aD(dl,dl,So.globalMatrix);const ma=ht.renderPass==="light-beam",Yo=Lt.paint.get("model-color-use-theme").constantOr("default")==="none",ho=ko&o.ez.HasMapboxMeshFeatures,cc=ho?0:Ta.evaluatedRMEA[0][2];for(let ei=0;ei=Sn||cp>=Sn}}const Vi=_o.material;let Wp;Vi.occlusionTexture&&Vi.occlusionTexture.offsetScale&&(Wp=Vi.occlusionTexture.offsetScale,Zc.defines.push("OCCLUSION_TEXTURE_TRANSFORM"));const Kp=ht.getOrCreateProgram("model",Zc);!wr&&rs&&rs.setupShadowsFromMatrix(Ca.tileModelMatrix,Kp,rs.useNormalOffset),ht.uploadCommonUniforms(Tt,Kp,null,lp);const Eo=Vi.pbrMetallicRoughness;Eo.metallicFactor=.9,Eo.roughnessFactor=.5;const Do=qp(new Float32Array(rh),new Float32Array(dl),new Float32Array(Pi),new Float32Array(So.globalMatrix),ht,Ca.opacity,Eo.baseColorFactor,Vi.emissiveFactor,Eo.metallicFactor,Eo.roughnessFactor,Vi,cc,Lt,[0,0,0],Wp);!Ic&&(Ta.hasTranslucentParts||Ca.opacity<1)&&Kp.draw(ht,Tt.gl.TRIANGLES,ws,Gn.disabled,zn.disabled,_n.backCCW,Do,Lt.id,_o.vertexBuffer,_o.indexBuffer,_o.segments,Lt.paint,ht.transform.zoom,void 0,eu),Kp.draw(ht,Tt.gl.TRIANGLES,Ic?Ts:ws,Gn.disabled,Ic||Ca.opacity<1||Ta.hasTranslucentParts?zn.alphaBlended:zn.unblended,_n.backCCW,Do,Lt.id,_o.vertexBuffer,_o.indexBuffer,_o.segments,Lt.paint,ht.transform.zoom,void 0,eu)}}}if(ht._debugParams.show3DModelFootprints&&Kr.size>0){const Oa=Array.from(Kr.keys()).sort();for(const na of Oa){const{node:ji,mvp:uo}=Kr.get(na);Xj(ht,0,ji,uo)}}}()}(M,g,N,P),void Ae();if(Te.type!=="model")return;const Fe=Te.getModels(),Ye=[],Ge=M.transform.getFreeCameraOptions().position,dt=o.bJ([],[Ge.x,Ge.y,Ge.z],M.transform.worldSize);o.eo(dt,dt);const lt=[],_t=[];let Ct=0;for(const ht of Fe){const Kt=g.getFeatureState("",ht.id),Lt={type:"Unknown",id:ht.id,properties:ht.featureProperties},Wt=N.paint.get("model-rotation").evaluate(Lt,Kt),Tt=N.paint.get("model-scale").evaluate(Lt,Kt),It=N.paint.get("model-translation").evaluate(Lt,Kt),Ut=N.paint.get("model-opacity").evaluate(Lt,Kt);Qj(N,ht.id,Kt,ht.featureProperties,ht.nodeOverrideNames,ht.nodeOverrides),Mv(N,ht.id,Kt,ht.featureProperties,ht.materialOverrideNames,ht.materialOverrides),ht.nodeOverrides.size>0&&ht.computeBoundsAndApplyParent(),ht.computeModelMatrix(M,Wt,Tt,It,Q,G,!1);const rs=o.b9([]),Zt=o.e2(ht.position.lat,M.transform.zoom),ks=o.bP([],[1,1,1/Zt]);o.bx(rs,rs,dt),Ye.push({zScaleMatrix:ks,negCameraPosMatrix:rs});for(const ms of ht.nodes)Zj(M,ms,ht.matrix,M.transform.expandedFarZProjMatrix,Ct,lt,_t,ht.materialOverrides,Ut);Ct++}if(lt.sort((ht,Kt)=>Kt.depth-ht.depth),M.renderPass!=="shadow"){if(M._debugParams.show3DModelFootprints){const ht=M.transform.projMatrix,Kt=new Map,Lt=(Tt,It)=>{if(Tt.footprint){const Ut=Tt.id||Tt.name||"footprint";if(!Kt.has(Ut)){const rs=o.aD([],ht,It);Kt.set(Ut,{node:Tt,mvp:rs})}}};for(const Tt of _t)Lt(Tt.node,Tt.modelMatrix);for(const Tt of lt)Lt(Tt.node,Tt.modelMatrix);const Wt=Array.from(Kt.keys()).sort();for(const Tt of Wt){const{node:It,mvp:Ut}=Kt.get(Tt);Xj(M,0,It,Ut)}}Dd(M,N,lt,_t,Ye),Ae()}else{for(const ht of _t)fb(ht.mesh,ht.nodeModelMatrix,M,N);for(const ht of lt)fb(ht.mesh,ht.nodeModelMatrix,M,N);Ae()}}},Ir={line:function(M,g,N){if(M.hasElevatedBuckets=!1,M.hasNonElevatedBuckets=!1,M._unevaluatedLayout.getValue("line-elevation-reference")!==void 0||M._unevaluatedLayout.getValue("line-z-offset")!==void 0){if(g){const P=g.getVisibleCoordinates();for(const F of P){const q=g.getTile(F).getBucket(M);if(q&&(q.elevationType!=="none"?M.hasElevatedBuckets=!0:M.hasNonElevatedBuckets=!0,M.hasElevatedBuckets&&M.hasNonElevatedBuckets))break}}}else M.hasNonElevatedBuckets=!0},model:function(M,g,N){const P=g.getSource();if(!P.loaded())return;if(P.type==="vector"||P.type==="geojson")return void(N.modelManager&&N.modelManager.upload(N,Rw(N,M)));if(P.type==="batched-model"||P.type!=="model")return;const F=P.getModels();for(const q of F)q.upload(N.context)},raster:function(M,g,N){const P=g.getSource();if(!(P instanceof Uh&&P.loaded()))return;const F=M.sourceLayer||P.rasterLayerIds&&P.rasterLayerIds[0];if(!F)return;const q=M.paint.get("raster-array-band")||P.getInitialBand(F);if(q==null)return;const G=g.getIds().map(Q=>g.getTileByID(Q));for(const Q of G)Q.updateNeeded(M.id,q)&&P.prepareTile(Q,F,M.id,q)},"raster-particle":function(M,g,N){const P=g.getSource();if(!(P instanceof Uh&&P.loaded()))return;const F=M.sourceLayer||P.rasterLayerIds&&P.rasterLayerIds[0];if(!F)return;const q=M.paint.get("raster-particle-array-band")||P.getInitialBand(F);if(q==null)return;const G=g.getIds().map(Q=>g.getTileByID(Q));for(const Q of G)Q.updateNeeded(M.id,q)&&P.prepareTile(Q,F,M.id,q)}},Tn={fill:ty},Ia={fill:function(M,g,N,P){if(!N.layout||N.layout.get("fill-elevation-reference")==="none"||N.paint.get("fill-opacity").constantOr(1)===0)return;const F=M.context.gl,q=new Wr(F.LEQUAL,Wr.ReadOnly,M.depthRangeFor3D),G=new Gn({func:F.ALWAYS,mask:255},255,255,F.KEEP,F.KEEP,F.REPLACE),Q=M.transform.getFreeCameraOptions().position,ae=M.getOrCreateProgram("elevatedStructuresDepthReconstruct");for(const me of P){const ye=g.getTile(me),Ae=ye.getBucket(N);if(!Ae)continue;const Te=Ae.elevatedStructures;if(!Te||Te.depthSegments.segments[0].primitiveLength===0)continue;const Fe=Mx(me.toUnwrapped(),Q),Ye=M.translatePosMatrix(me.projMatrix,ye,N.paint.get("fill-translate"),N.paint.get("fill-translate-anchor")),Ge=Cv(Ye,Fe,0,1,0);ae.draw(M,F.TRIANGLES,q,G,zn.disabled,_n.disabled,Ge,N.id,Te.vertexBuffer,Te.indexBuffer,Te.depthSegments,N.paint,M.transform.zoom)}}};class eo{constructor(g,N,P,F,q){this.context=new Tx(g,N),this.transform=P,this._tileTextures={},this.frameCopies=[],this.loadTimeStamps=[],this._timeStamp=o.o.now(),this._averageFPS=0,this._fpsHistory=[],this._dt=0,this._debugParams={forceEnablePrecipitation:!1,showTerrainProxyTiles:!1,fpsWindow:30,continousRedraw:!1,show3DModelFootprints:!1,enabledLayers:{}};const G=["fill","line","symbol","circle","heatmap","fill-extrusion","building","raster","raster-particle","hillshade","model","background","sky"];for(const ae of G)this._debugParams.enabledLayers[ae]=!0;for(const ae of G);this.occlusionParams=new S4,this.setup(),this.numSublayers=Uo.maxUnderzooming+Uo.maxOverzooming+1,this.depthEpsilon=1/Math.pow(2,16),this.deferredRenderGpuTimeQueries=[],this.gpuTimers={},this.frameCounter=0,this._backgroundTiles={},this.conflationActive=!1,this.replacementSource=new o.eG,this.longestCutoffRange=0,this.minCutoffZoom=0,this._fogVisible=!1,this._cachedTileFogOpacities={},this._shadowRenderer=new Wl(this),this._wireframeDebugCache=new k4,this.renderDefaultNorthPole=!0,this.renderDefaultSouthPole=!0,this.layersWithOcclusionOpacity=[];const Q=new o.q({width:1,height:1},Uint8Array.of(0,0,0,0));this.emptyDepthTexture=new o.T(this.context,Q,g.RGBA8),this._clippingActiveLastFrame=!1,this.scaleFactor=F,this.maxFrontCutoffRawStart=0,this.worldview=q,this._forceEmissiveMode=!1,this.emissiveMode="constant"}updateTerrain(g,N){const P=!!g&&!!g.terrain&&this.transform.projection.supportsTerrain;if(!(P||this._terrain&&this._terrain.enabled))return;this._terrain||(this._terrain=new J0(this,g));const F=this._terrain;this.transform.elevation=P?F:null,F.update(g,this.transform,N),this.transform.elevation&&!F.enabled&&(this.transform.elevation=null)}_updateFog(g){const N=g.fog;if(!N||this.transform.projection.name==="globe"||N.getOpacity(this.transform.pitch)<1||N.properties.get("horizon-blend")<.03)return void(this.transform.fogCullDistSq=null);const[P,F]=N.getFovAdjustedRange(this.transform._fov);if(P>F)return void(this.transform.fogCullDistSq=null);const q=P+.78*(F-P);this.transform.fogCullDistSq=q*q}get terrain(){return this.transform._terrainEnabled()&&this._terrain&&this._terrain.enabled||this._forceTerrainMode?this._terrain:null}get forceTerrainMode(){return this._forceTerrainMode}set forceTerrainMode(g){g&&!this._terrain&&(this._terrain=new J0(this,this.style)),this._forceTerrainMode=g}get shadowRenderer(){return this._shadowRenderer&&this._shadowRenderer.enabled?this._shadowRenderer:null}get wireframeDebugCache(){return this._wireframeDebugCache}resize(g,N){if(this.width=g*o.o.devicePixelRatio,this.height=N*o.o.devicePixelRatio,this.context.viewport.set([0,0,this.width,this.height]),this.style)for(const P of this.style.order)this.style._mergedLayers[P].resize()}setup(){const g=this.context,N=new o.dB;N.emplaceBack(0,0),N.emplaceBack(o.an,0),N.emplaceBack(0,o.an),N.emplaceBack(o.an,o.an),this.tileExtentBuffer=g.createVertexBuffer(N,o.dx.members),this.tileExtentSegments=o.dy.simpleSegment(0,0,4,2);const P=new o.dB;P.emplaceBack(0,0),P.emplaceBack(o.an,0),P.emplaceBack(0,o.an),P.emplaceBack(o.an,o.an),this.debugBuffer=g.createVertexBuffer(P,o.dx.members),this.debugSegments=o.dy.simpleSegment(0,0,4,5);const F=new o.dB;F.emplaceBack(-1,-1),F.emplaceBack(1,-1),F.emplaceBack(-1,1),F.emplaceBack(1,1),this.viewportBuffer=g.createVertexBuffer(F,o.dx.members),this.viewportSegments=o.dy.simpleSegment(0,0,4,2);const q=new o.eH;q.emplaceBack(0,0,0,0),q.emplaceBack(o.an,0,o.an,0),q.emplaceBack(0,o.an,0,o.an),q.emplaceBack(o.an,o.an,o.an,o.an),this.mercatorBoundsBuffer=g.createVertexBuffer(q,o.eI.members),this.mercatorBoundsSegments=o.dy.simpleSegment(0,0,4,2);const G=new o.dC;G.emplaceBack(0,1,2),G.emplaceBack(2,1,3),this.quadTriangleIndexBuffer=g.createIndexBuffer(G);const Q=new o.eJ;for(const me of[0,1,3,2,0])Q.emplaceBack(me);this.debugIndexBuffer=g.createIndexBuffer(Q),this.emptyTexture=new o.T(g,new o.q({width:1,height:1},Uint8Array.of(0,0,0,0)),g.gl.RGBA8),this.identityMat=o.bb();const ae=this.context.gl;this.stencilClearMode=new Gn({func:ae.ALWAYS,mask:0},0,255,ae.ZERO,ae.ZERO,ae.ZERO),this.loadTimeStamps.push(performance.now())}getMercatorTileBoundsBuffers(){return{tileBoundsBuffer:this.mercatorBoundsBuffer,tileBoundsIndexBuffer:this.quadTriangleIndexBuffer,tileBoundsSegments:this.mercatorBoundsSegments}}getTileBoundsBuffers(g){return g._makeTileBoundsBuffers(this.context,this.transform.projection),g._tileBoundsBuffer?{tileBoundsBuffer:g._tileBoundsBuffer,tileBoundsIndexBuffer:g._tileBoundsIndexBuffer,tileBoundsSegments:g._tileBoundsSegments}:this.getMercatorTileBoundsBuffers()}clearStencil(){const g=this.context.gl;this.nextStencilID=1,this.currentStencilSource=void 0,this._tileClippingMaskIDs={},this.getOrCreateProgram("clippingMask").draw(this,g.TRIANGLES,Wr.disabled,this.stencilClearMode,zn.disabled,_n.disabled,jw(this.identityMat),"$clipping",this.viewportBuffer,this.quadTriangleIndexBuffer,this.viewportSegments)}resetStencilClippingMasks(){this.terrain||(this.currentStencilSource=void 0,this._tileClippingMaskIDs={})}_renderTileClippingMasks(g,N,P){if(!N||this.currentStencilSource===N.id||!g.isTileClipped()||!P||P.length===0)return;if(this._tileClippingMaskIDs&&!this.terrain){let Q=!1;for(const ae of P)if(this._tileClippingMaskIDs[ae.key]===void 0){Q=!0;break}if(!Q)return}this.currentStencilSource=N.id;const F=this.context,q=F.gl;this.nextStencilID+P.length>256&&this.clearStencil(),F.setColorMode(zn.disabled),F.setDepthMode(Wr.disabled);const G=this.getOrCreateProgram("clippingMask");this._tileClippingMaskIDs={};for(const Q of P){const ae=N.getTile(Q),me=this._tileClippingMaskIDs[Q.key]=this.nextStencilID++,{tileBoundsBuffer:ye,tileBoundsIndexBuffer:Ae,tileBoundsSegments:Te}=this.getTileBoundsBuffers(ae);G.draw(this,q.TRIANGLES,Wr.disabled,new Gn({func:q.ALWAYS,mask:0},me,255,q.KEEP,q.KEEP,q.REPLACE),zn.disabled,_n.disabled,jw(Q.projMatrix),"$clipping",ye,Ae,Te)}}stencilModeFor3D(){this.currentStencilSource=void 0,this.nextStencilID+1>256&&this.clearStencil();const g=this.nextStencilID++,N=this.context.gl;return new Gn({func:N.NOTEQUAL,mask:255},g,255,N.KEEP,N.KEEP,N.REPLACE)}stencilModeForClipping(g){if(this.terrain)return this.terrain.stencilModeForRTTOverlap(g);const N=this.context.gl;return new Gn({func:N.EQUAL,mask:255},this._tileClippingMaskIDs[g.key],0,N.KEEP,N.KEEP,N.REPLACE)}stencilConfigForOverlap(g){const N=this.context.gl,P=g.sort((G,Q)=>Q.overscaledZ-G.overscaledZ),F=P[P.length-1].overscaledZ,q=P[0].overscaledZ-F+1;if(q>1){this.currentStencilSource=void 0,this.nextStencilID+q>256&&this.clearStencil();const G={};for(let Q=0;Qthis._debugParams.fpsWindow&&this._fpsHistory.splice(0,this._fpsHistory.length-this._debugParams.fpsWindow),this._averageFPS=Math.round(this._fpsHistory.reduce((g,N)=>g+N/this._fpsHistory.length,0))}render(g,N){const P=o.o.now();this._dt=P-this._timeStamp,this._timeStamp=P,this._wireframeDebugCache.update(this.frameCounter),this._debugParams.continousRedraw=g.map.repaint,this.style=g,this.options=N;const F=this.style._mergedLayers,q=!(!this.terrain||!this.terrain.enabled),G=()=>this.style._getOrder(q).filter(as=>{const Xt=F[as];return!(Xt.type in this._debugParams.enabledLayers)||this._debugParams.enabledLayers[Xt.type]});let Q=G(),ae=!1,me=!1,ye=null,Ae=0,Te=!1;for(const as of Q){const Xt=F[as];Xt.visibility!=="none"&&(Xt.type==="circle"?ae=!0:Xt.type==="building"?(ye=Xt,++Ae):Xt.type==="symbol"&&(Xt.hasOcclusionOpacityProperties?me=!0:ae=!0))}this.updateEmissiveMode();let Fe=Q.map(as=>F[as]);const Ye=this.style._mergedSourceCaches;this.imageManager=g.imageManager,this.modelManager=g.modelManager,this.symbolFadeChange=g.placement.symbolFadeChange(o.o.now()),this.imageManager.beginFrame();for(const as in Ye){const Xt=Ye[as];Xt.used&&(Xt.prepare(this.context),Xt.getSource().usedInConflation&&++Ae)}let Ge=!1;for(const as of Fe)as.isHidden(this.transform.zoom)||(as.type==="clip"&&(Ge=!0),this.prepareLayer(as));const dt={},lt={},_t={},Ct={},ht={};for(const as in Ye){const Xt=Ye[as];dt[as]=Xt.getVisibleCoordinates(),lt[as]=dt[as].slice().reverse(),_t[as]=Xt.getVisibleCoordinates(!0).reverse(),Ct[as]=Xt.getShadowCasterCoordinates(),ht[as]=Xt.sortCoordinatesByDistance(dt[as])}const Kt=as=>{const Xt=this.style.getLayerSourceCache(as);return Xt&&Xt.used?Xt.getSource():null};if(Ae||Ge||this._clippingActiveLastFrame){const as=[],Xt=[];let ws=0;for(const Ts of Fe)this.isSourceForClippingOrConflation(Ts,Kt(Ts))&&(as.push(Ts),Xt.push(ws)),ws++;if(as&&(Ge||as.length>1)||this._clippingActiveLastFrame){Ge=!1;const Ts=[];for(let Ls=0;Ls0){const Ts=Kt(Xt);Ts&&(this.minCutoffZoom=Math.max(Ts.minzoom,this.minCutoffZoom)),Xt.minzoom&&(this.minCutoffZoom=Math.max(Xt.minzoom,this.minCutoffZoom))}Xt.is3D(q)&&(this.opaquePassCutoff===1/0&&(this.opaquePassCutoff=as),this._lastOcclusionLayer=as)}const Lt=this.style&&this.style.fog;Lt?(this._fogVisible=Lt.getOpacity(this.transform.pitch)!==0,this._fogVisible&&this.transform.projection.name!=="globe"&&(this._fogVisible=Lt.isVisibleOnFrustum(this.transform.cameraFrustum))):this._fogVisible=!1,this._cachedTileFogOpacities={},this.terrain&&(this.terrain.updateTileBinding(_t),this.opaquePassCutoff=0,Q=G(),Fe=Q.map(as=>F[as]));const Wt=this._shadowRenderer;if(Wt){Wt.updateShadowParameters(this.transform,this.style.directionalLight);for(const as in Ye)for(const Xt of dt[as]){let ws={min:0,max:0};this.terrain&&(ws=this.terrain.getMinMaxForTile(Xt)||ws),Wt.addShadowReceiver(Xt.toUnwrapped(),ws.min,ws.max)}}this.transform.projection.name!=="globe"||this.globeSharedBuffers||(this.globeSharedBuffers=new o.eL(this.context)),this.style.fog&&this.transform.projection.supportsFog?(this._atmosphere||(this._atmosphere=new vM(this)),this._atmosphere.update(this)):this._atmosphere&&(this._atmosphere.destroy(),this._atmosphere=void 0);const Tt=this._debugParams.forceEnablePrecipitation||!(!this.style||!this.style.snow),It=this._debugParams.forceEnablePrecipitation||!(!this.style||!this.style.rain);if(Tt&&!this._snow&&(this._snow=new Qt(this)),!Tt&&this._snow&&(this._snow.destroy(),delete this._snow),It&&!this._rain&&(this._rain=new Ke(this)),!It&&this._rain&&(this._rain.destroy(),delete this._rain),this._snow&&this._snow.update(this),this._rain&&this._rain.update(this),ye){this.buildingTileBorderManager||(this.buildingTileBorderManager=new Xh);const as=this.style.getLayerSourceCache(ye);this.buildingTileBorderManager.updateBorders(as,ye)}if(!et.has(this.context.gl))return;this.renderPass="offscreen";for(const as of Fe){const Xt=g.getLayerSourceCache(as);if(!as.hasOffscreenPass()||as.isHidden(this.transform.zoom))continue;const ws=Xt?lt[Xt.id]:void 0;(as.type==="custom"||as.type==="raster"||as.type==="raster-particle"||as.isSky()||ws&&ws.length)&&this.renderLayer(this,Xt,as,ws)}this.depthRangeFor3D=[0,1-(Fe.length+2)*this.numSublayers*this.depthEpsilon],this._shadowRenderer&&(this.renderPass="shadow",this._shadowRenderer.drawShadowPass(this.style,Ct)),this.context.bindFramebuffer.set(null),this.context.viewport.set([0,0,this.width,this.height]);const Ut=this.transform.projection.name==="globe"||this.transform.isHorizonVisible(),rs=(()=>{if(N.showOverdrawInspector)return o.aq.black;const as=this.style.fog;if(as&&this.transform.projection.supportsFog){const Xt=this.style.getLut(as.scope);if(!Ut){const ws=as.properties.get("color-use-theme")==="none",Ts=as.properties.get("color").toNonPremultipliedRenderColor(ws?null:Xt).toArray01();return new o.aq(...Ts)}if(Ut){const ws=as.properties.get("space-color-use-theme")==="none",Ts=as.properties.get("space-color").toNonPremultipliedRenderColor(ws?null:Xt).toArray01();return new o.aq(...Ts)}}return o.aq.transparent})();if(this.context.clear({color:rs,depth:1}),this.clearStencil(),this._showOverdrawInspector=N.showOverdrawInspector,this.renderPass="opaque",this.style.fog&&this.transform.projection.supportsFog&&this._atmosphere&&!this._showOverdrawInspector&&Ut&&this._atmosphere.drawStars(this,this.style.fog),!this.terrain)for(this.currentLayer=Q.length-1;this.currentLayer>=0;this.currentLayer--){const as=Fe[this.currentLayer],Xt=g.getLayerSourceCache(as);if(as.isSky())continue;const ws=Xt?(as.is3D(q)?ht:lt)[Xt.id]:void 0;this._renderTileClippingMasks(as,Xt,ws),this.renderLayer(this,Xt,as,ws)}if(this.style.fog&&this.transform.projection.supportsFog&&this._atmosphere&&!this._showOverdrawInspector&&Ut&&this._atmosphere.drawAtmosphereGlow(this,this.style.fog),this.renderPass="sky",(!this._atmosphere||o.al(this.transform.zoom)>0)&&(this.transform.projection.name==="globe"||this.transform.isHorizonVisible()))for(this.currentLayer=0;this.currentLayer{for(this.currentLayer=0;this.currentLayer=this._lastOcclusionLayer&&this.layersWithOcclusionOpacity.length>0){const ws=this.currentLayer;this.depthOcclusion=!0;for(const Ts of this.layersWithOcclusionOpacity){this.currentLayer=Ts;const Ls=Fe[this.currentLayer],wr=g.getLayerSourceCache(Ls),mr=wr?lt[wr.id]:void 0;this.terrain||this._renderTileClippingMasks(Ls,wr,wr?dt[wr.id]:void 0),this.renderLayer(this,wr,Ls,mr)}this.depthOcclusion=!1,this.currentLayer=ws,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 as=null;Fe.forEach(Xt=>{const ws=g.getLayerSourceCache(Xt);ws&&!Xt.isHidden(this.transform.zoom)&&ws.getVisibleCoordinates().length&&(!as||as.getSource().maxzoom0?N.pop():null}terrainRenderModeElevated(){return this.style&&!!this.style.getTerrain()&&!!this.terrain&&!this.terrain.renderingToTexture||this.forceTerrainMode}linearFloatFilteringSupported(){return this.context.extTextureFloatLinear!=null}currentGlobalDefines(g,N,P){const F=P===void 0?this.terrain&&this.terrain.renderingToTexture:P,q=[];return this.style&&this.style.enable3dLights()&&(g==="globeRaster"||g==="terrainRaster"?(q.push("LIGHTING_3D_MODE"),q.push("LIGHTING_3D_ALPHA_EMISSIVENESS")):F||q.push("LIGHTING_3D_MODE")),this.terrainRenderModeElevated()&&(q.push("TERRAIN"),this.linearFloatFilteringSupported()&&q.push("TERRAIN_DEM_FLOAT_FORMAT")),this.transform.projection.name==="globe"&&q.push("GLOBE"),!this._fogVisible||F||N!==void 0&&!N||q.push("FOG"),F&&q.push("RENDER_TO_TEXTURE"),this._showOverdrawInspector&&q.push("OVERDRAW_INSPECTOR"),q}getOrCreateProgram(g,N){this.cache=this.cache||{};const P=N&&N.defines||[],F=N&&N.config,q=this.currentGlobalDefines(g,N&&N.overrideFog,N&&N.overrideRtt).concat(P),G=Wc.cacheKey(l4[g],g,q,F);return this.cache[G]||(this.cache[G]=new Wc(this.context,g,l4[g],F,cb[g],q)),this.cache[G]}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 g=this.context.gl;this.context.cullFace.set(!1),this.context.viewport.set([0,0,this.width,this.height]),this.context.blendEquation.set(g.FUNC_ADD)}initDebugOverlayCanvas(){this.debugOverlayCanvas==null&&(this.debugOverlayCanvas=document.createElement("canvas"),this.debugOverlayCanvas.width=512,this.debugOverlayCanvas.height=512,this.debugOverlayTexture=new o.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(g,N){if(this.style.enable3dLights()){const P=this.style.directionalLight,F=this.style.ambientLight;if(P&&F){const q=((G,Q,ae)=>{const me=G.properties.get("direction"),ye=G.properties.get("color-use-theme")==="none",Ae=G.properties.get("color").toNonPremultipliedRenderColor(ye?null:ae.getLut(G.scope)).toArray01(),Te=G.properties.get("intensity"),Fe=Q.properties.get("color-use-theme")==="none",Ye=Q.properties.get("color").toNonPremultipliedRenderColor(Fe?null:ae.getLut(Q.scope)).toArray01(),Ge=Q.properties.get("intensity"),dt=[me.x,me.y,me.z],lt=o.dD(Ye,Ge),_t=o.dD(Ae,Te);return{u_lighting_ambient_color:lt,u_lighting_directional_dir:dt,u_lighting_directional_color:_t,u_ground_radiance:rb(dt,_t,lt)}})(P,F,this.style);N.setLightsUniformValues(g,q)}}}uploadCommonUniforms(g,N,P,F,q){if(this.uploadCommonLightUniforms(g,N),this.terrain&&this.terrain.renderingToTexture)return;const G=this.style.fog;if(G){const Q=G.getOpacity(this.transform.pitch),ae=((me,ye,Ae,Te,Fe,Ye,Ge,dt,lt,_t,Ct,ht)=>{const Kt=me.transform,Lt=ye.properties.get("color-use-theme")==="none",Wt=ye.properties.get("color").toNonPremultipliedRenderColor(Lt?null:me.style.getLut(ye.scope)).toArray01();Wt[3]=Te;const Tt=me.frameCounter/1e3%1,[It,Ut]=ye.properties.get("vertical-range");return{u_fog_matrix:Ae?Kt.calculateFogTileMatrix(Ae):ht||me.identityMat,u_fog_range:ye.getFovAdjustedRange(Kt._fov),u_fog_color:Wt,u_fog_horizon_blend:ye.properties.get("horizon-blend"),u_fog_vertical_limit:[Math.min(It,Ut),Ut],u_fog_temporal_offset:Tt,u_frustum_tl:Fe,u_frustum_tr:Ye,u_frustum_br:Ge,u_frustum_bl:dt,u_globe_pos:lt,u_globe_radius:_t,u_viewport:Ct,u_globe_transition:o.al(Kt.zoom),u_is_globe:+(Kt.projection.name==="globe")}})(this,G,P,Q,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*o.o.devicePixelRatio,this.transform.height*o.o.devicePixelRatio],F);N.setFogUniformValues(g,ae)}q&&N.setCutoffUniformValues(g,q.uniformValues)}setTileLoadedFlag(g){this.tileLoaded=g}saveCanvasCopy(){const g=this.canvasCopy();g&&(this.frameCopies.push(g),this.tileLoaded=!1)}canvasCopy(){const g=this.context.gl,N=g.createTexture();return g.bindTexture(g.TEXTURE_2D,N),g.copyTexImage2D(g.TEXTURE_2D,0,g.RGBA,0,0,g.drawingBufferWidth,g.drawingBufferHeight,0),N}getCanvasCopiesAndTimestamps(){return{canvasCopies:this.frameCopies,timeStamps:this.loadTimeStamps}}averageElevationNeedsEasing(){if(!this.transform._elevation)return!1;const g=this.style&&this.style.fog;return!!g&&g.getOpacity(this.transform.pitch)!==0}getBackgroundTiles(){const g=this._backgroundTiles,N=this._backgroundTiles={},P=this.transform.coveringTiles({tileSize:512});for(const F of P)N[F.key]=g[F.key]||new o.b0(F,512,this.transform.tileZoom,this,void 0,this.worldview);return N}clearBackgroundTiles(){this._backgroundTiles={}}isSourceForClippingOrConflation(g,N){return!(!g.is3D(!(!this.terrain||!this.terrain.enabled))||g.type!=="clip"&&g.type!=="building"&&(g.minzoom&&g.minzoom>this.transform.zoom||(this.style._clipLayerPresent||g.sourceLayer!=="building"&&g.sourceLayer!=="procedural_buildings")&&(!N||N.type!=="batched-model")))}isTileAffectedByFog(g){if(!this.style||!this.style.fog)return!1;if(this.transform.projection.name==="globe")return!0;let N=this._cachedTileFogOpacities[g.key];return N||(this._cachedTileFogOpacities[g.key]=N=this.style.fog.getOpacityForTile(g)),N[0]>=Sn||N[1]>=Sn}setupDepthForOcclusion(g,N,P){const F=this.context,q=F.gl,G=!!P;var Q;P||(P={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}),F.activeTexture.set(q.TEXTURE3),g&&this.depthFBO&&this.depthTexture?(this.depthTexture.bind(q.NEAREST,q.CLAMP_TO_EDGE),P.u_depth_size_inv=[1/this.depthFBO.width,1/this.depthFBO.height],P.u_depth_range_unpack=[2/((Q=this.depthRangeFor3D)[1]-Q[0]),-1-2*Q[0]/(Q[1]-Q[0])],P.u_occluder_half_size=.5*this.occlusionParams.occluderSize,P.u_occlusion_depth_offset=this.occlusionParams.depthOffset):this.emptyDepthTexture.bind(q.NEAREST,q.CLAMP_TO_EDGE),F.activeTexture.set(q.TEXTURE0),G||N.setTerrainUniformValues(F,P)}updateEmissiveMode(){if(this._forceEmissiveMode)return;const g=this.style.hasDataDrivenEmissiveStrength();this.emissiveMode=g?this.context.extBlendFuncExtended?"dual-source-blending":"mrt-fallback":"constant"}}function ha(M,g){let N=!1,P=null;const F=()=>{P=null,N&&(M(),P=setTimeout(F,g),N=!1)};return()=>(N=!0,P||F(),P)}class lc{constructor(g){this._hashName=g&&encodeURIComponent(g),o.aZ(["_getCurrentHash","_onHashChange","_updateHash"],this),this._updateHash=ha(this._updateHashUnthrottled.bind(this),300)}addTo(g){return this._map=g,window.addEventListener("hashchange",this._onHashChange,!1),g.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 g=this._map;if(!g)return"";const N=to(g);if(this._hashName){const P=this._hashName;let F=!1;const q=location.hash.slice(1).split("&").map(G=>{const Q=G.split("=")[0];return Q===P?(F=!0,`${Q}=${N}`):G}).filter(G=>G);return F||q.push(`${P}=${N}`),`#${q.join("&")}`}return`#${N}`}_getCurrentHash(){const g=location.hash.replace("#","");if(this._hashName){let N;return g.split("&").map(P=>P.split("=")).forEach(P=>{P[0]===this._hashName&&(N=P)}),(N&&N[1]||"").split("/")}return g.split("/")}_onHashChange(){const g=this._map;if(!g)return!1;const N=this._getCurrentHash();if(N.length>=3&&!N.some(P=>isNaN(Number(P)))){const P=g.dragRotate.isEnabled()&&g.touchZoomRotate.isEnabled()?+(N[3]||0):g.getBearing();return g.jumpTo({center:[+N[2],+N[1]],zoom:+N[0],bearing:P,pitch:+(N[4]||0)}),!0}return!1}_updateHashUnthrottled(){history.replaceState(history.state,"",location.href.replace(/(#.+)?$/,this.getHashString()))}}function to(M,g){const N=M.getCenter(),P=Math.round(100*M.getZoom())/100,F=Math.ceil((P*Math.LN2+Math.log(512/360/.5))/Math.LN10),q=Math.pow(10,F),G=Math.round(N.lng*q)/q,Q=Math.round(N.lat*q)/q,ae=M.getBearing(),me=M.getPitch();let ye=g?`/${G}/${Q}/${P}`:`${P}/${Q}/${G}`;return(ae||me)&&(ye+="/"+Math.round(10*ae)/10),me&&(ye+=`/${Math.round(me)}`),ye}const sh={linearity:.3,easing:o.eN(0,0,.3,1)},jf=Object.assign({deceleration:2500,maxSpeed:1400},sh),Tr=Object.assign({deceleration:20,maxSpeed:1400},sh),Ps=Object.assign({deceleration:1e3,maxSpeed:360},sh),Qs=Object.assign({deceleration:1e3,maxSpeed:90},sh);class ja{constructor(g){this._map=g,this.clear()}clear(){this._inertiaBuffer=[]}record(g){this._drainInertiaBuffer(),this._inertiaBuffer.push({time:o.o.now(),settings:g})}_drainInertiaBuffer(){const g=this._inertiaBuffer,N=o.o.now();for(;g.length>0&&N-g[0].time>160;)g.shift()}_onMoveEnd(g){if(this._map._prefersReducedMotion()||(this._drainInertiaBuffer(),this._inertiaBuffer.length<2))return;const N={zoom:0,bearing:0,pitch:0,pan:new o.P(0,0),pinchAround:void 0,around:void 0};for(const{settings:q}of this._inertiaBuffer)N.zoom+=q.zoomDelta||0,N.bearing+=q.bearingDelta||0,N.pitch+=q.pitchDelta||0,q.panDelta&&N.pan._add(q.panDelta),q.around&&(N.around=q.around),q.pinchAround&&(N.pinchAround=q.pinchAround);const P=this._inertiaBuffer[this._inertiaBuffer.length-1].time-this._inertiaBuffer[0].time,F={};if(N.pan.mag()){const q=Ei(N.pan.mag(),P,Object.assign({},jf,g||{}));F.offset=N.pan.mult(q.amount/N.pan.mag()),F.center=this._map.transform.center,Da(F,q)}if(N.zoom){const q=Ei(N.zoom,P,Tr);F.zoom=this._map.transform.zoom+q.amount,Da(F,q)}if(N.bearing){const q=Ei(N.bearing,P,Ps);F.bearing=this._map.transform.bearing+o.aC(q.amount,-179,179),Da(F,q)}if(N.pitch){const q=Ei(N.pitch,P,Qs);F.pitch=this._map.transform.pitch+q.amount,Da(F,q)}if(F.zoom||F.bearing){const q=N.pinchAround===void 0?N.around:N.pinchAround;F.around=q?this._map.unproject(q):this._map.getCenter()}return this.clear(),F.noMoveStart=!0,F}}function Da(M,g){(!M.duration||M.durationN.unproject(ae)),Q=q.reduce((ae,me,ye,Ae)=>ae.add(me.div(Ae.length)),new o.P(0,0));super(g,{points:q,point:Q,lngLats:G,lngLat:N.unproject(Q),originalEvent:P}),this._defaultPrevented=!1}}class Rd extends o.C{preventDefault(){this._defaultPrevented=!0}get defaultPrevented(){return this._defaultPrevented}constructor(g,N){super("wheel",{originalEvent:N}),this._defaultPrevented=!1}}class qo{constructor(g,N){this._map=g,this._clickTolerance=N.clickTolerance}reset(){this._mousedownPos=void 0}wheel(g){return this._firePreventable(new Rd(this._map,g))}mousedown(g,N){return this._mousedownPos=N,this._firePreventable(new Ya(g.type,this._map,g))}mouseup(g){this._map.fire(new Ya(g.type,this._map,g))}preclick(g){const N=new MouseEvent("preclick",g);this._map.fire(new Ya(N.type,this._map,N))}click(g,N){this._mousedownPos&&this._mousedownPos.dist(N)>=this._clickTolerance||(this.preclick(g),this._map.fire(new Ya(g.type,this._map,g)))}dblclick(g){return this._firePreventable(new Ya(g.type,this._map,g))}mouseover(g){this._map.fire(new Ya(g.type,this._map,g))}mouseout(g){this._map.fire(new Ya(g.type,this._map,g))}touchstart(g){return this._firePreventable(new Zi(g.type,this._map,g))}touchmove(g){this._map.fire(new Zi(g.type,this._map,g))}touchend(g){this._map.fire(new Zi(g.type,this._map,g))}touchcancel(g){this._map.fire(new Zi(g.type,this._map,g))}_firePreventable(g){if(this._map.fire(g),g.defaultPrevented)return{}}isEnabled(){return!0}isActive(){return!1}enable(){}disable(){}}class Og{constructor(g){this._map=g}reset(){this._delayContextMenu=!1,this._contextMenuEvent=void 0}mousemove(g){this._map.fire(new Ya(g.type,this._map,g))}mousedown(){this._delayContextMenu=!0}mouseup(){this._delayContextMenu=!1,this._contextMenuEvent&&(this._map.fire(new Ya("contextmenu",this._map,this._contextMenuEvent)),delete this._contextMenuEvent)}contextmenu(g){this._delayContextMenu?this._contextMenuEvent=g:this._map.fire(new Ya(g.type,this._map,g)),this._map.listens("contextmenu")&&g.preventDefault()}isEnabled(){return!0}isActive(){return!1}enable(){}disable(){}}class T4{constructor(g,N){this._map=g,this._el=g.getCanvasContainer(),this._container=g.getContainer(),this._clickTolerance=N.clickTolerance||1}isEnabled(){return!!this._enabled}isActive(){return!!this._active}enable(){this.isEnabled()||(this._enabled=!0)}disable(){this.isEnabled()&&(this._enabled=!1)}mousedown(g,N){this.isEnabled()&&g.shiftKey&&g.button===0&&(E(),this._startPos=this._lastPos=N,this._active=!0)}mousemoveWindow(g,N){if(!this._active)return;const P=N,F=this._startPos,q=this._lastPos;if(!F||!q||q.equals(P)||!this._box&&P.dist(F){this._box&&(this._box.style.transform=`translate(${G}px,${ae}px)`,this._box.style.width=Q-G+"px",this._box.style.height=me-ae+"px")})}mouseupWindow(g,N){if(!this._active)return;const P=this._startPos,F=N;if(P&&g.button===0){if(this.reset(),R(),P.x!==F.x||P.y!==F.y)return this._map.fire(new o.C("boxzoomend",{originalEvent:g})),{cameraAnimation:q=>q.fitScreenCoordinates(P,F,this._map.getBearing(),{linear:!1})};this._fireEvent("boxzoomcancel",g)}}keydown(g){this._active&&g.keyCode===27&&(this.reset(),this._fireEvent("boxzoomcancel",g))}blur(){this.reset()}reset(){this._active=!1,this._container.classList.remove("mapboxgl-crosshair"),this._box&&(this._box.remove(),this._box=null),A(),delete this._startPos,delete this._lastPos}_fireEvent(g,N){return this._map.fire(new o.C(g,{originalEvent:N}))}}function E4(M,g){const N={};for(let P=0;Pthis.numTouches)&&(this.aborted=!0),this.aborted||(this.startTime===0&&(this.startTime=g.timeStamp),P.length===this.numTouches&&(this.centroid=function(F){const q=new o.P(0,0);for(const G of F)q._add(G);return q.div(F.length)}(N),this.touches=E4(P,N)))}touchmove(g,N,P){if(this.aborted||!this.centroid)return;const F=E4(P,N);for(const q in this.touches){const G=F[q];(!G||G.dist(this.touches[q])>30)&&(this.aborted=!0)}}touchend(g,N,P){if((!this.centroid||g.timeStamp-this.startTime>500)&&(this.aborted=!0),P.length===0){const F=!this.aborted&&this.centroid;if(this.reset(),F)return F}}}class ay{constructor(g){this.singleTap=new Fg(g),this.numTaps=g.numTaps,this.reset()}reset(){this.lastTime=1/0,this.lastTap=void 0,this.count=0,this.singleTap.reset()}touchstart(g,N,P){this.singleTap.touchstart(g,N,P)}touchmove(g,N,P){this.singleTap.touchmove(g,N,P)}touchend(g,N,P){const F=this.singleTap.touchend(g,N,P);if(F){const q=g.timeStamp-this.lastTime<500,G=!this.lastTap||this.lastTap.dist(F)<30;if(q&&G||this.reset(),this.count++,this.lastTime=g.timeStamp,this.lastTap=F,this.count===this.numTaps)return this.reset(),F}}}class sN{constructor(){this._zoomIn=new ay({numTouches:1,numTaps:2}),this._zoomOut=new ay({numTouches:2,numTaps:1}),this.reset()}reset(){this._active=!1,this._zoomIn.reset(),this._zoomOut.reset()}touchstart(g,N,P){this._zoomIn.touchstart(g,N,P),this._zoomOut.touchstart(g,N,P)}touchmove(g,N,P){this._zoomIn.touchmove(g,N,P),this._zoomOut.touchmove(g,N,P)}touchend(g,N,P){const F=this._zoomIn.touchend(g,N,P),q=this._zoomOut.touchend(g,N,P);return F?(this._active=!0,g.preventDefault(),setTimeout(()=>this.reset(),0),{cameraAnimation:G=>G.easeTo({duration:300,zoom:G.getZoom()+1,around:G.unproject(F)},{originalEvent:g})}):q?(this._active=!0,g.preventDefault(),setTimeout(()=>this.reset(),0),{cameraAnimation:G=>G.easeTo({duration:300,zoom:G.getZoom()-1,around:G.unproject(q)},{originalEvent:g})}):void 0}touchcancel(){this.reset()}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}const _M=0,uD=2,hD={[_M]:1,[uD]:2},Pv={Control:"ctrlKey",Alt:"altKey",Shift:"shiftKey",Meta:"metaKey"};class A4{constructor(g){this.reset(),this._clickTolerance=g.clickTolerance||1}blur(){this.reset()}reset(){this._active=!1,this._moved=!1,this._lastPoint=void 0,this._eventButton=void 0}_correctButton(g,N){return!1}_move(g,N){return{}}mousedown(g,N){if(this._lastPoint)return;const P=$(g);this._correctButton(g,P)&&(this._lastPoint=N,this._eventButton=P)}mousemoveWindow(g,N){const P=this._lastPoint;if(P){if(g.preventDefault(),this._eventButton!=null&&function(F,q){const G=hD[q];return F.buttons===void 0||(F.buttons&G)!==G}(g,this._eventButton))this.reset();else if(this._moved||!(N.dist(P)0&&(this._active=!0);const F=E4(P,N),q=new o.P(0,0),G=new o.P(0,0);let Q=0;for(const me in F){const ye=F[me],Ae=this._touches[me];Ae&&(q._add(ye),G._add(ye.sub(Ae)),Q++,F[me]=ye)}if(this._touches=F,Q{this._alertContainer.classList.remove("mapboxgl-touch-pan-blocker-show"),this._alertContainer.removeAttribute("role")},500)}}class I4{constructor(){this.reset()}reset(){this._active=!1,this._firstTwoTouches=void 0}_start(g){}_move(g,N,P){return{}}touchstart(g,N,P){this._firstTwoTouches||P.length<2||(this._firstTwoTouches=[P[0].identifier,P[1].identifier],this._start([N[0],N[1]]))}touchmove(g,N,P){const F=this._firstTwoTouches;if(!F)return;g.preventDefault();const[q,G]=F,Q=Yl(P,N,q),ae=Yl(P,N,G);if(!Q||!ae)return;const me=this._aroundCenter?null:Q.add(ae).div(2);return this._move([Q,ae],me,g)}touchend(g,N,P){if(!this._firstTwoTouches)return;const[F,q]=this._firstTwoTouches,G=Yl(P,N,F),Q=Yl(P,N,q);G&&Q||(this._active&&R(),this.reset())}touchcancel(){this.reset()}enable(g){this._enabled=!0,this._aroundCenter=!!g&&g.around==="center"}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}function Yl(M,g,N){for(let P=0;PMath.abs(M.x)}class pD extends I4{constructor(g){super(),this._map=g}reset(){super.reset(),this._valid=void 0,this._firstMove=void 0,this._lastPoints=void 0}_start(g){this._lastPoints=g,P4(g[0].sub(g[1]))&&(this._valid=!1)}_move(g,N,P){const F=this._lastPoints;if(!F)return;const q=g[0].sub(F[0]),G=g[1].sub(F[1]);return this._map._cooperativeGestures&&!o.eO()&&P.touches.length<3||(this._valid=this.gestureBeginsVertically(q,G,P.timeStamp),!this._valid)?void 0:(this._lastPoints=g,this._active=!0,{pitchDelta:(q.y+G.y)/2*-.5})}gestureBeginsVertically(g,N,P){if(this._valid!==void 0)return this._valid;const F=g.mag()>=2,q=N.mag()>=2;if(!F&&!q)return;if(!F||!q)return this._firstMove==null&&(this._firstMove=P),P-this._firstMove<100&&void 0;const G=g.y>0==N.y>0;return P4(g)&&P4(N)&&G}}const gD={panStep:100,bearingStep:15,pitchStep:10};class zw{constructor(){const g=gD;this._panStep=g.panStep,this._bearingStep=g.bearingStep,this._pitchStep=g.pitchStep,this._rotationDisabled=!1}blur(){this.reset()}reset(){this._active=!1}keydown(g){if(g.altKey||g.ctrlKey||g.metaKey)return;let N=0,P=0,F=0,q=0,G=0;switch(g.keyCode){case 61:case 107:case 171:case 187:N=1;break;case 189:case 109:case 173:N=-1;break;case 37:g.shiftKey?P=-1:(g.preventDefault(),q=-1);break;case 39:g.shiftKey?P=1:(g.preventDefault(),q=1);break;case 38:g.shiftKey?F=1:(g.preventDefault(),G=-1);break;case 40:g.shiftKey?F=-1:(g.preventDefault(),G=1);break;default:return}return this._rotationDisabled&&(P=0,F=0),{cameraAnimation:Q=>{const ae=Q.getZoom();Q.easeTo({duration:300,easeId:"keyboardHandler",easing:xD,zoom:N?Math.round(ae)+N*(g.shiftKey?2:1):ae,bearing:Q.getBearing()+P*this._bearingStep,pitch:Q.getPitch()+F*this._pitchStep,offset:[-q*this._panStep,-G*this._panStep],center:Q.getCenter()},{originalEvent:g})}}}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 xD(M){return M*(2-M)}const $w=4.000244140625,yD=1/450;class kM{constructor(g,N){this._map=g,this._el=g.getCanvasContainer(),this._handler=N,this._delta=0,this._lastDelta=0,this._defaultZoomRate=.01,this._wheelZoomRate=yD,o.aZ(["_onTimeout","_addScrollZoomBlocker","_showBlockerAlert"],this)}setZoomRate(g){this._defaultZoomRate=g}setWheelZoomRate(g){this._wheelZoomRate=g}isEnabled(){return!!this._enabled}isActive(){return this._active||this._finishTimeout!==void 0}isZooming(){return!!this._zooming}enable(g){this.isEnabled()||(this._enabled=!0,this._aroundCenter=!!g&&g.around==="center",this._map._cooperativeGestures&&this._addScrollZoomBlocker())}disable(){this.isEnabled()&&(this._enabled=!1,this._map._cooperativeGestures&&(clearTimeout(this._alertTimer),this._alertContainer.remove()))}wheel(g){if(!this.isEnabled())return;if(this._map._cooperativeGestures){if(!(g.ctrlKey||g.metaKey||this.isZooming()||o.eO()))return void this._showBlockerAlert();this._alertContainer.style.visibility!=="hidden"&&(this._alertContainer.style.visibility="hidden",clearTimeout(this._alertTimer))}let N=g.deltaMode===WheelEvent.DOM_DELTA_LINE?40*g.deltaY:g.deltaY;const P=o.o.now(),F=P-(this._lastWheelEventTime||0);this._lastWheelEventTime=P,N!==0&&N%$w===0?this._type="wheel":N!==0&&Math.abs(N)<4?this._type="trackpad":F>400?(this._type=null,this._lastValue=N,this._timeout=window.setTimeout(this._onTimeout,40,g)):this._type||(this._type=Math.abs(F*N)<200?"trackpad":"wheel",this._timeout&&(clearTimeout(this._timeout),this._timeout=null,N+=this._lastValue)),g.shiftKey&&N&&(N/=4),this._type&&(this._lastWheelEvent=g,this._delta-=N,this._active||this._start(g)),g.preventDefault()}_onTimeout(g){this._type="wheel",this._delta-=this._lastValue,this._active||this._start(g)}_start(g){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 N=z(this._el,g);this._aroundPoint=this._aroundCenter?this._map.transform.centerPoint:N,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 g=this._map.transform;this._type==="wheel"&&g.projection.wrap&&(g._center.lng>=180||g._center.lng<=-180)&&(this._prevEase=null,this._easing=null,this._lastWheelEvent=null,this._lastWheelEventTime=0);const N=()=>g._terrainEnabled()&&this._aroundCoord?g.computeZoomRelativeTo(this._aroundCoord):g.zoom;if(this._delta!==0){const me=this._type==="wheel"&&Math.abs(this._delta)>$w?this._wheelZoomRate:this._defaultZoomRate;let ye=2/(1+Math.exp(-Math.abs(this._delta*me)));this._delta<0&&ye!==0&&(ye=1/ye);const Ae=N(),Te=Math.pow(2,Ae),Fe=typeof this._targetZoom=="number"?g.zoomScale(this._targetZoom):Te;this._targetZoom=Math.min(g.maxZoom,Math.max(g.minZoom,g.scaleZoom(Fe*ye))),this._type==="wheel"&&(this._startZoom=Ae,this._easing=this._smoothOutEasing(200)),this._lastDelta=this._delta,this._delta=0}const P=typeof this._targetZoom=="number"?this._targetZoom:N(),F=this._startZoom,q=this._easing;let G,Q=!1;if(this._type==="wheel"&&F&&q){const me=Math.min((o.o.now()-this._lastWheelEventTime)/200,1),ye=q(me);G=o.am(F,P,ye),me<1?this._frameId||(this._frameId=!0):Q=!0}else G=P,Q=!0;this._active=!0,Q&&(this._active=!1,this._finishTimeout=window.setTimeout(()=>{this._zooming=!1,this._handler._triggerRenderFrame(),delete this._targetZoom,delete this._finishTimeout},200));let ae=G-N();return ae*this._lastDelta<0&&(ae=0),{noInertia:!0,needsRenderFrame:!Q,zoomDelta:ae,around:this._aroundPoint,aroundCoord:this._aroundCoord,originalEvent:this._lastWheelEvent}}_smoothOutEasing(g){let N=o.eP;if(this._prevEase){const P=this._prevEase,F=(o.o.now()-P.start)/P.duration,q=P.easing(F+.01)-P.easing(F),G=.27/Math.sqrt(q*q+1e-4)*.01,Q=Math.sqrt(.0729-G*G);N=o.eN(G,Q,.25,1)}return this._prevEase={start:o.o.now(),duration:g,easing:N},N}blur(){this.reset()}reset(){this._active=!1}_addScrollZoomBlocker(){this._map&&!this._alertContainer&&(this._alertContainer=_("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 SM{constructor(g,N){this._clickZoom=g,this._tapZoom=N}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 CM{constructor(){this.reset()}reset(){this._active=!1}blur(){this.reset()}dblclick(g,N){return g.preventDefault(),{cameraAnimation:P=>{P.easeTo({duration:300,zoom:P.getZoom()+(g.shiftKey?-1:1),around:P.unproject(N)},{originalEvent:g})}}}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}class Gz{constructor(){this._tap=new ay({numTouches:1,numTaps:1}),this.reset()}reset(){this._active=!1,this._swipePoint=void 0,this._swipeTouch=0,this._tapTime=0,this._tap.reset()}touchstart(g,N,P){this._swipePoint||(this._tapTime&&g.timeStamp-this._tapTime>500&&this.reset(),this._tapTime?P.length>0&&(this._swipePoint=N[0],this._swipeTouch=P[0].identifier):this._tap.touchstart(g,N,P))}touchmove(g,N,P){if(this._tapTime){if(this._swipePoint){if(P[0].identifier!==this._swipeTouch)return;const F=N[0],q=F.y-this._swipePoint.y;return this._swipePoint=F,g.preventDefault(),this._active=!0,{zoomDelta:q/128}}}else this._tap.touchmove(g,N,P)}touchend(g,N,P){this._tapTime?this._swipePoint&&P.length===0&&this.reset():this._tap.touchend(g,N,P)&&(this._tapTime=g.timeStamp)}touchcancel(){this.reset()}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}class vD{constructor(g,N,P){this._el=g,this._mousePan=N,this._touchPan=P}enable(g){this._inertiaOptions=g||{},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 Wz{constructor(g,N,P){this._pitchWithRotate=g.pitchWithRotate,this._mouseRotate=N,this._mousePitch=P}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 Kz{constructor(g,N,P,F){this._el=g,this._touchZoom=N,this._touchRotate=P,this._tapDragZoom=F,this._rotationDisabled=!1,this._enabled=!0}enable(g){this._touchZoom.enable(g),this._rotationDisabled||this._touchRotate.enable(g),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 L4=M=>M.zoom||M.drag||M.pitch||M.rotate;class Yz extends o.C{}class Zz{constructor(){this.constants=[1,1,.01],this.radius=0}setup(g,N){const P=o.ax([],N,g);this.radius=o.ai(P[2]<0?o.eR([],P,this.constants):[P[0],P[1],0])}projectRay(g){o.eR(g,g,this.constants),o.ay(g,g),o.eS(g,g,this.constants);const N=o.bJ([],g,this.radius);if(N[2]>0){const P=o.bJ([],[0,0,1],o.bi(N,[0,0,1])),F=o.bJ([],o.ay([],[N[0],N[1],0]),this.radius),q=o.cT([],N,o.bJ([],o.ax([],o.cT([],F,P),N),2));N[0]=q[0],N[1]=q[1]}return N}}function D4(M){return M.panDelta&&M.panDelta.mag()||M.zoomDelta||M.bearingDelta||M.pitchDelta}class Xz{constructor(g,N){this._map=g,this._el=this._map.getCanvasContainer(),this._handlers=[],this._handlersById={},this._changes=[],this._inertia=new ja(g),this._bearingSnap=N.bearingSnap,this._previousActiveHandlers={},this._trackingEllipsoid=new Zz,this._dragOrigin=null,this._eventsInProgress={},this._addDefaultHandlers(N),o.aZ(["handleEvent","handleWindowEvent"],this);const P=this._el;this._listeners=[[P,"touchstart",{passive:!0}],[P,"touchmove",{passive:!1}],[P,"touchend",void 0],[P,"touchcancel",void 0],[P,"mousedown",void 0],[P,"mousemove",void 0],[P,"mouseup",void 0],[document,"mousemove",{capture:!0}],[document,"mouseup",void 0],[P,"mouseover",void 0],[P,"mouseout",void 0],[P,"dblclick",void 0],[P,"click",void 0],[P,"keydown",{capture:!1}],[P,"keyup",void 0],[P,"wheel",{passive:!1}],[P,"contextmenu",void 0],[window,"blur",void 0]];for(const[F,q,G]of this._listeners){const Q=F===document?this.handleWindowEvent:this.handleEvent;F.addEventListener(q,Q,G)}}destroy(){for(const[g,N,P]of this._listeners){const F=g===document?this.handleWindowEvent:this.handleEvent;g.removeEventListener(N,F,P)}}_addDefaultHandlers(g){const N=this._map,P=N.getCanvasContainer();this._add("mapEvent",new qo(N,g));const F=N.boxZoom=new T4(N,g);this._add("boxZoom",F);const q=new sN,G=new CM;N.doubleClickZoom=new SM(G,q),this._add("tapZoom",q),this._add("clickZoom",G);const Q=new Gz;this._add("tapDragZoom",Q);const ae=N.touchPitch=new pD(N);this._add("touchPitch",ae);const me=new wM(g),ye=new M4(g);N.dragRotate=new Wz(g,me,ye),this._add("mouseRotate",me,["mousePitch"]),this._add("mousePitch",ye,["mouseRotate"]);const Ae=new Bg(g),Te=new mD(N,g);N.dragPan=new vD(P,Ae,Te),this._add("mousePan",Ae),this._add("touchPan",Te,["touchZoom","touchRotate"]);const Fe=new Bw,Ye=new fD;N.touchZoomRotate=new Kz(P,Ye,Fe,Q),this._add("touchRotate",Fe,["touchPan","touchZoom"]),this._add("touchZoom",Ye,["touchPan","touchRotate"]),this._add("blockableMapEvent",new Og(N));const Ge=N.scrollZoom=new kM(N,this);this._add("scrollZoom",Ge,["mousePan"]);const dt=N.keyboard=new zw;this._add("keyboard",dt);for(const lt of["boxZoom","doubleClickZoom","tapDragZoom","touchPitch","dragRotate","dragPan","touchZoomRotate","scrollZoom","keyboard"])g.interactive&&g[lt]&&N[lt].enable(g[lt])}_add(g,N,P){this._handlers.push({handlerName:g,handler:N,allowed:P}),this._handlersById[g]=N}stop(g){if(!this._updatingCamera){for(const{handler:N}of this._handlers)N.reset();this._inertia.clear(),this._fireEvents({},{},g),this._changes=[],this._originalZoom=void 0}}isActive(){for(const{handler:g}of this._handlers)if(g.isActive())return!0;return!1}isZooming(){return!!this._eventsInProgress.zoom||this._map.scrollZoom.isZooming()}isRotating(){return!!this._eventsInProgress.rotate}isMoving(){return!!L4(this._eventsInProgress)||this.isZooming()}_isDragging(){return!!this._eventsInProgress.drag}_blockedByActive(g,N,P){for(const F in g)if(F!==P&&(!N||N.indexOf(F)<0))return!0;return!1}handleWindowEvent(g){this.handleEvent(g,`${g.type}Window`)}_getMapTouches(g){const N=[];for(const P of g)this._el.contains(P.target)&&N.push(P);return N}handleEvent(g,N){this._updatingCamera=!0;const P=g.type==="renderFrame",F=P?void 0:g,q={needsRenderFrame:!1},G={},Q={},ae=g.touches?this._getMapTouches(g.touches):void 0,me=ae?O(this._el,ae):P?void 0:z(this._el,g);for(const{handlerName:Te,handler:Fe,allowed:Ye}of this._handlers){if(!Fe.isEnabled())continue;let Ge;this._blockedByActive(Q,Ye,Te)?Fe.reset():Fe[N||g.type]&&(Ge=Fe[N||g.type](g,me,ae),this.mergeHandlerResult(q,G,Ge,Te,F),Ge&&Ge.needsRenderFrame&&this._triggerRenderFrame()),(Ge||Fe.isActive())&&(Q[Te]=Fe)}const ye={};for(const Te in this._previousActiveHandlers)Q[Te]||(ye[Te]=F);this._previousActiveHandlers=Q,(Object.keys(ye).length||D4(q))&&(this._changes.push([q,G,ye]),this._triggerRenderFrame()),(Object.keys(Q).length||D4(q))&&this._map._stop(!0),this._updatingCamera=!1;const{cameraAnimation:Ae}=q;Ae&&(this._inertia.clear(),this._fireEvents({},{},!0),this._changes=[],Ae(this._map))}mergeHandlerResult(g,N,P,F,q){if(!P)return;Object.assign(g,P);const G={handlerName:F,originalEvent:P.originalEvent||q};P.zoomDelta!==void 0&&(N.zoom=G),P.panDelta!==void 0&&(N.drag=G),P.pitchDelta!==void 0&&(N.pitch=G),P.bearingDelta!==void 0&&(N.rotate=G)}_applyChanges(){const g={},N={},P={};for(const[F,q,G]of this._changes)F.panDelta&&(g.panDelta=(g.panDelta||new o.P(0,0))._add(F.panDelta)),F.zoomDelta&&(g.zoomDelta=(g.zoomDelta||0)+F.zoomDelta),F.bearingDelta&&(g.bearingDelta=(g.bearingDelta||0)+F.bearingDelta),F.pitchDelta&&(g.pitchDelta=(g.pitchDelta||0)+F.pitchDelta),F.around!==void 0&&(g.around=F.around),F.aroundCoord!==void 0&&(g.aroundCoord=F.aroundCoord),F.pinchAround!==void 0&&(g.pinchAround=F.pinchAround),F.noInertia&&(g.noInertia=F.noInertia),Object.assign(N,q),Object.assign(P,G);this._updateMapTransform(g,N,P),this._changes=[]}_updateMapTransform(g,N,P){const F=this._map,q=F.transform,G=_t=>[_t.x,_t.y,_t.z];if((()=>{const _t=this._eventsInProgress.drag;return _t&&!this._handlersById[_t.handlerName].isActive()})()&&!D4(g)){const _t=q.zoom;q.cameraElevationReference="sea",this._originalZoom!=null&&q._orthographicProjectionAtLowPitch&&q.projection.name!=="globe"&&q.pitch===0?(q.cameraElevationReference="ground",q.zoom=this._originalZoom):(q.recenterOnTerrain(),q.cameraElevationReference="ground"),_t!==q.zoom&&this._map._update(!0)}if(q._isCameraConstrained&&F._stop(!0),!D4(g))return void this._fireEvents(N,P,!0);let{panDelta:Q,zoomDelta:ae,bearingDelta:me,pitchDelta:ye,around:Ae,aroundCoord:Te,pinchAround:Fe}=g;q._isCameraConstrained&&(ae>0&&(ae=0),q._isCameraConstrained=!1),Fe!==void 0&&(Ae=Fe),(ae||(_t=>N[_t]&&!this._eventsInProgress[_t])("drag"))&&Ae&&(this._dragOrigin=G(q.pointCoordinate3D(Ae)),this._originalZoom=q.zoom,this._trackingEllipsoid.setup(q._camera.position,this._dragOrigin)),q.cameraElevationReference="sea",F._stop(!0),Ae=Ae||F.transform.centerPoint,me&&(q.bearing+=me),ye&&(q.pitch+=ye),q._updateCameraState();const Ye=[0,0,0];if(Q)if(q.projection.name==="mercator"){const _t=this._trackingEllipsoid.projectRay(q.screenPointToMercatorRay(Ae).dir),Ct=this._trackingEllipsoid.projectRay(q.screenPointToMercatorRay(Ae.sub(Q)).dir);Ye[0]=Ct[0]-_t[0],Ye[1]=Ct[1]-_t[1]}else{const _t=q.pointCoordinate(Ae);if(q.projection.name==="globe"){Q=Q.rotate(-q.angle);const Ct=q._pixelsPerMercatorPixel/q.worldSize;Ye[0]=-Q.x*o.eQ(o.bV(_t.y))*Ct,Ye[1]=-Q.y*o.eQ(q.center.lat)*Ct}else{const Ct=q.pointCoordinate(Ae.sub(Q));_t&&Ct&&(Ye[0]=Ct.x-_t.x,Ye[1]=Ct.y-_t.y)}}const Ge=q.zoom,dt=[0,0,0];if(ae){const _t=G(Te||q.pointCoordinate3D(Ae)),Ct={dir:o.ay([],o.ax([],_t,q._camera.position))};if(Ct.dir[2]<0){const ht=q.zoomDeltaToMovement(_t,ae);o.bJ(dt,Ct.dir,ht)}}const lt=o.cT(Ye,Ye,dt);q._translateCameraConstrained(lt),ae&&Math.abs(q.zoom-Ge)>1e-4&&q.recenterOnTerrain(),q.cameraElevationReference="ground",this._map._update(),g.noInertia||this._inertia.record(g),this._fireEvents(N,P,!0)}_fireEvents(g,N,P){const F=L4(this._eventsInProgress),q=L4(g),G={};for(const ye in g){const{originalEvent:Ae}=g[ye];this._eventsInProgress[ye]||(G[`${ye}start`]=Ae),this._eventsInProgress[ye]=g[ye]}!F&&q&&this._fireEvent("movestart",q.originalEvent);for(const ye in G)this._fireEvent(ye,G[ye]);q&&this._fireEvent("move",q.originalEvent);for(const ye in g){const{originalEvent:Ae}=g[ye];this._fireEvent(ye,Ae)}const Q={};let ae;for(const ye in this._eventsInProgress){const{handlerName:Ae,originalEvent:Te}=this._eventsInProgress[ye];this._handlersById[Ae].isActive()||(delete this._eventsInProgress[ye],ae=N[Ae]||Te,Q[`${ye}end`]=ae)}for(const ye in Q)this._fireEvent(ye,Q[ye]);const me=L4(this._eventsInProgress);if(P&&(F||q)&&!me){this._updatingCamera=!0;const ye=this._inertia._onMoveEnd(this._map.dragPan._inertiaOptions),Ae=Te=>Te!==0&&-this._bearingSnap{this._frameId=void 0,this.handleEvent(new Yz("renderFrame",{timeStamp:g})),this._applyChanges()})}_triggerRenderFrame(){this._frameId===void 0&&(this._frameId=this._requestFrame())}}const bD="map.setFreeCameraOptions(...) and map.getFreeCameraOptions() are not yet supported for non-mercator projections.";class Qz extends o.E{constructor(g,N){super(),this._moving=!1,this._zooming=!1,this.transform=g,this._bearingSnap=N.bearingSnap,this._respectPrefersReducedMotion=N.respectPrefersReducedMotion!==!1,o.aZ(["_renderFrameCallback"],this)}getCenter(){return new o.aU(this.transform.center.lng,this.transform.center.lat)}setCenter(g,N){return this.jumpTo({center:g},N)}panBy(g,N,P){return g=o.P.convert(g).mult(-1),this.panTo(this.transform.center,Object.assign({offset:g},N),P)}panTo(g,N,P){return this.easeTo(Object.assign({center:g},N),P)}getZoom(){return this.transform.zoom}setZoom(g,N){return this.jumpTo({zoom:g},N),this}zoomTo(g,N,P){return this.easeTo(Object.assign({zoom:g},N),P)}zoomIn(g,N){return this.zoomTo(this.getZoom()+1,g,N),this}zoomOut(g,N){return this.zoomTo(this.getZoom()-1,g,N),this}getBearing(){return this.transform.bearing}setBearing(g,N){return this.jumpTo({bearing:g},N),this}getPadding(){return this.transform.padding}setPadding(g,N){return this.jumpTo({padding:g},N),this}rotateTo(g,N,P){return this.easeTo(Object.assign({bearing:g},N),P)}resetNorth(g,N){return this.rotateTo(0,Object.assign({duration:1e3},g),N),this}resetNorthPitch(g,N){return this.easeTo(Object.assign({bearing:0,pitch:0,duration:1e3},g),N),this}snapToNorth(g,N){return Math.abs(this.getBearing())g.aspect?P/(2*Math.tan(.5*g.fovX)*g.aspect):F/(2*Math.tan(.5*g.fovY)*g.aspect)}_cameraForBoundsOnGlobe(g,N,P,F,q,G){const Q=g.clone(),ae=this._extendCameraOptions(G);Q.bearing=F,Q.pitch=q;const me=o.aU.convert(N),ye=o.aU.convert(P),Ae=.5*(me.lat+ye.lat),Te=.5*(me.lng+ye.lng),Fe=o.eT(Ae,Te),Ye=o.ay([],Fe),Ge=o.ay([],o.bh([],Ye,[0,1,0])),dt=o.bh([],Ge,Ye),lt=[Ge[0],Ge[1],Ge[2],0,dt[0],dt[1],dt[2],0,Ye[0],Ye[1],Ye[2],0,0,0,0,1],_t=[Fe,o.eT(me.lat,me.lng),o.eT(ye.lat,me.lng),o.eT(ye.lat,ye.lng),o.eT(me.lat,ye.lng),o.eT(Ae,me.lng),o.eT(Ae,ye.lng),o.eT(me.lat,Te),o.eT(ye.lat,Te)];let Ct=o.cU.fromPoints(_t.map(Ts=>[o.bi(Ge,Ts),o.bi(dt,Ts),o.bi(Ye,Ts)]));const ht=o.ah([],Ct.center,lt);o.eU(ht)===0&&o.eV(ht,0,0,1),o.ay(ht,ht),o.bJ(ht,ht,o.aF),Q.center=o.eW(ht);const Kt=Q.getWorldToCameraMatrix(),Lt=o.b7(new Float64Array(16),Kt);Ct=o.cU.applyTransform(Ct,o.aD([],Kt,lt));const Wt=this._extendAABB(Ct,Q,ae,F);if(!Wt)return void o.w("Map cannot fit within canvas with the given bounds, padding, and/or offset.");Ct=Wt,o.ah(ht,ht,Kt);const Tt=.5*(Ct.max[2]-Ct.min[2]),It=this._minimumAABBFrustumDistance(Q,Ct),Ut=o.bJ([],[0,0,1],Tt),rs=o.cT(Ut,ht,Ut),Zt=It+(Q.pitch===0?0:o.bf(ht,rs)),ks=Q.globeCenterInViewSpace,ms=o.ax([],ht,[ks[0],ks[1],ks[2]]);o.ay(ms,ms),o.bJ(ms,ms,Zt);const Ws=o.cT([],ht,ms);o.ah(Ws,Ws,Lt);const sr=o.eD/o.aF,as=o.ai(Ws),Xt=o.bU(Math.max(as*sr-o.eD,Number.EPSILON),0),ws=Math.min(Q.zoomFromMercatorZAdjusted(Xt),ae.maxZoom);return ws>.5*(o.cJ+o.cv)?(Q.setProjection({name:"mercator"}),Q.zoom=ws,this._cameraForBounds(Q,N,P,F,q,G)):{center:Q.center,zoom:ws,bearing:F,pitch:q}}_extendAABB(g,N,P,F){const q=.5*((P.padding.left||0)+(P.padding.right||0)),G=.5*((P.padding.top||0)+(P.padding.bottom||0)),Q=G,ae=q,me=q,ye=G,Ae=N.width-(ae+me),Te=N.height-(Q+ye),Fe=o.ax([],g.max,g.min),Ye=Math.min(Ae/Fe[0],Te/Fe[1]),Ge=Math.min(N.scaleZoom(N.scale*Ye),P.maxZoom);if(isNaN(Ge))return null;const dt=N.scale/N.zoomScale(Ge),lt=new o.cU([g.min[0]-ae*dt,g.min[1]-ye*dt,g.min[2]],[g.max[0]+me*dt,g.max[1]+Q*dt,g.max[2]]),_t=(typeof P.offset.x=="number"&&typeof P.offset.y=="number"?new o.P(P.offset.x,P.offset.y):o.P.convert(P.offset)).rotate(-o.ap(F));return lt.center[0]-=_t.x*dt,lt.center[1]+=_t.y*dt,lt}queryTerrainElevation(g,N){const P=this.transform.elevation;return P?(N=Object.assign({},{exaggerated:!0},N),P.getAtPoint(o.ag.fromLngLat(g),null,N.exaggerated)):null}_cameraForBounds(g,N,P,F,q,G){if(g.projection.name==="globe")return this._cameraForBoundsOnGlobe(g,N,P,F,q,G);const Q=g.clone(),ae=this._extendCameraOptions(G);Q.bearing=F,Q.pitch=q;const me=o.aU.convert(N),ye=o.aU.convert(P),Ae=new o.aU(me.lng,ye.lat),Te=new o.aU(ye.lng,me.lat),Fe=Q.project(me),Ye=Q.project(ye),Ge=this.queryTerrainElevation(me),dt=this.queryTerrainElevation(ye),lt=this.queryTerrainElevation(Ae),_t=this.queryTerrainElevation(Te),Ct=[[Fe.x,Fe.y,Math.min(Ge||0,dt||0,lt||0,_t||0)],[Ye.x,Ye.y,Math.max(Ge||0,dt||0,lt||0,_t||0)]];let ht=o.cU.fromPoints(Ct);const Kt=Q.getWorldToCameraMatrix(),Lt=o.b7(new Float64Array(16),Kt);ht=o.cU.applyTransform(ht,Kt);const Wt=this._extendAABB(ht,Q,ae,F);if(!Wt)return void o.w("Map cannot fit within canvas with the given bounds, padding, and/or offset.");ht=Wt;const Tt=.5*o.ax([],ht.max,ht.min)[2],It=this._minimumAABBFrustumDistance(Q,ht),Ut=[0,0,1,0];o.aE(Ut,Ut,Kt),o.eX(Ut,Ut);const rs=o.bJ([],Ut,It+Tt),Zt=o.cT([],ht.center,rs);o.ah(ht.center,ht.center,Lt),o.ah(Zt,Zt,Lt);const ks=Q.unproject(new o.P(ht.center[0],ht.center[1])),ms=o.eY(Q.projection,ks),Ws=Math.pow(2,ms),sr=Math.min(Q._zoomFromMercatorZ(Zt[2]*Q.pixelsPerMeter*Ws/Q.worldSize),ae.maxZoom);return Q.mercatorFromTransition&&sr<.5*(o.cJ+o.cv)?(Q.setProjection({name:"globe"}),Q.zoom=sr,this._cameraForBounds(Q,N,P,F,q,G)):{center:ks,zoom:sr,bearing:F,pitch:q}}fitBounds(g,N,P){const F=this.cameraForBounds(g,N);return this._fitInternal(F,N,P)}fitScreenCoordinates(g,N,P,F,q){const G=o.P.convert(g),Q=o.P.convert(N),ae=new o.P(Math.min(G.x,Q.x),Math.min(G.y,Q.y)),me=new o.P(Math.max(G.x,Q.x),Math.max(G.y,Q.y));if(this.transform.projection.name==="mercator"&&this.transform.anyCornerOffEdge(G,Q))return this;const ye=this.transform.pointLocation3D(ae),Ae=this.transform.pointLocation3D(me),Te=this.transform.pointLocation3D(new o.P(ae.x,me.y)),Fe=this.transform.pointLocation3D(new o.P(me.x,ae.y)),Ye=[Math.min(ye.lng,Ae.lng,Te.lng,Fe.lng),Math.min(ye.lat,Ae.lat,Te.lat,Fe.lat)],Ge=[Math.max(ye.lng,Ae.lng,Te.lng,Fe.lng),Math.max(ye.lat,Ae.lat,Te.lat,Fe.lat)],dt=F&&F.pitch?F.pitch:this.getPitch(),lt=this._cameraForBounds(this.transform,Ye,Ge,P,dt,F);return this._fitInternal(lt,F,q)}_fitInternal(g,N,P){return g?(N=Object.assign(g,N)).linear?this.easeTo(N,P):this.flyTo(N,P):this}jumpTo(g,N){this.stop();const P=g.preloadOnly?this.transform.clone():this.transform;let F=!1,q=!1,G=!1;"zoom"in g&&P.zoom!==+g.zoom&&(F=!0,P.zoom=+g.zoom),g.center!==void 0&&(P.center=o.aU.convert(g.center)),"bearing"in g&&P.bearing!==+g.bearing&&(q=!0,P.bearing=+g.bearing),"pitch"in g&&P.pitch!==+g.pitch&&(G=!0,P.pitch=+g.pitch);const Q=typeof g.padding=="number"?this._extendPadding(g.padding):g.padding;if(g.padding!=null&&!P.isPaddingEqual(Q))if(g.retainPadding===!1){const ae=P.clone();ae.padding=Q,P.setLocationAtPoint(P.center,ae.centerPoint)}else P.padding=Q;return g.preloadOnly?(this._preloadTiles(P),this):(this.fire(new o.C("movestart",N)).fire(new o.C("move",N)),F&&this.fire(new o.C("zoomstart",N)).fire(new o.C("zoom",N)).fire(new o.C("zoomend",N)),q&&this.fire(new o.C("rotatestart",N)).fire(new o.C("rotate",N)).fire(new o.C("rotateend",N)),G&&this.fire(new o.C("pitchstart",N)).fire(new o.C("pitch",N)).fire(new o.C("pitchend",N)),this.fire(new o.C("moveend",N)))}getFreeCameraOptions(){return this.transform.projection.supportsFreeCamera||o.w(bD),this.transform.getFreeCameraOptions()}setFreeCameraOptions(g,N){const P=this.transform;if(!P.projection.supportsFreeCamera)return o.w(bD),this;this.stop();const F=P.zoom,q=P.pitch,G=P.bearing;P.setFreeCameraOptions(g);const Q=F!==P.zoom,ae=q!==P.pitch,me=G!==P.bearing;return this.fire(new o.C("movestart",N)).fire(new o.C("move",N)),Q&&this.fire(new o.C("zoomstart",N)).fire(new o.C("zoom",N)).fire(new o.C("zoomend",N)),me&&this.fire(new o.C("rotatestart",N)).fire(new o.C("rotate",N)).fire(new o.C("rotateend",N)),ae&&this.fire(new o.C("pitchstart",N)).fire(new o.C("pitch",N)).fire(new o.C("pitchend",N)),this.fire(new o.C("moveend",N)),this}easeTo(g,N){this._stop(!1,g.easeId),((g=Object.assign({offset:[0,0],duration:500,easing:o.eP},g)).animate===!1||this._prefersReducedMotion(g))&&(g.duration=0);const P=this.transform,F=this.getZoom(),q=this.getBearing(),G=this.getPitch(),Q=this.getPadding(),ae="zoom"in g?+g.zoom:F,me="bearing"in g?this._normalizeBearing(g.bearing,q):q,ye="pitch"in g?+g.pitch:G,Ae=this._extendPadding(g.padding),Te=o.P.convert(g.offset);let Fe,Ye,Ge;if(P.projection.name==="globe"){const Ut=o.ag.fromLngLat(P.center),rs=Te.rotate(-P.angle);Ut.x+=rs.x/P.worldSize,Ut.y+=rs.y/P.worldSize;const Zt=Ut.toLngLat(),ks=o.aU.convert(g.center||Zt);this._normalizeCenter(ks),Fe=P.centerPoint.add(rs),Ye=new o.P(Ut.x,Ut.y).mult(P.worldSize),Ge=new o.P(o.aH(ks.lng),o.aL(ks.lat)).mult(P.worldSize).sub(Ye)}else{Fe=P.centerPoint.add(Te);const Ut=P.pointLocation(Fe),rs=o.aU.convert(g.center||Ut);this._normalizeCenter(rs),Ye=P.project(Ut),Ge=P.project(rs).sub(Ye)}const dt=P.zoomScale(ae-F);let lt,_t;g.around&&(lt=o.aU.convert(g.around),_t=P.locationPoint(lt));const Ct=this._zooming||ae!==F,ht=this._rotating||q!==me,Kt=this._pitching||ye!==G,Lt=!P.isPaddingEqual(Ae),Wt=g.retainPadding===!1?P.clone():P,Tt=Ut=>rs=>{if(Ct&&(Ut.zoom=o.am(F,ae,rs)),ht&&(Ut.bearing=o.am(q,me,rs)),Kt&&(Ut.pitch=o.am(G,ye,rs)),Lt&&(Wt.interpolatePadding(Q,Ae,rs),Fe=Wt.centerPoint.add(Te)),lt)Ut.setLocationAtPoint(lt,_t);else{const Zt=Ut.zoomScale(Ut.zoom-F),ks=ae>F?Math.min(2,dt):Math.max(.5,dt),ms=Math.pow(ks,1-rs),Ws=Ut.unproject(Ye.add(Ge.mult(rs*ms)).mult(Zt));Ut.setLocationAtPoint(Ut.renderWorldCopies?Ws.wrap():Ws,Fe)}return g.preloadOnly||this._fireMoveEvents(N),Ut};if(g.preloadOnly){const Ut=this._emulate(Tt,g.duration,P);return this._preloadTiles(Ut),this}const It={moving:this._moving,zooming:this._zooming,rotating:this._rotating,pitching:this._pitching};return this._zooming=Ct,this._rotating=ht,this._pitching=Kt,this._padding=Lt,this._easeId=g.easeId,this._prepareEase(N,g.noMoveStart,It),this._ease(Tt(P),Ut=>{P.cameraElevationReference==="sea"&&P.recenterOnTerrain(),this._afterEase(N,Ut)},g),this}_prepareEase(g,N,P={}){this._moving=!0,this.transform.cameraElevationReference="sea",this.transform._orthographicProjectionAtLowPitch&&this.transform.pitch===0&&this.transform.projection.name!=="globe"&&(this.transform.cameraElevationReference="ground"),N||P.moving||this.fire(new o.C("movestart",g)),this._zooming&&!P.zooming&&this.fire(new o.C("zoomstart",g)),this._rotating&&!P.rotating&&this.fire(new o.C("rotatestart",g)),this._pitching&&!P.pitching&&this.fire(new o.C("pitchstart",g))}_fireMoveEvents(g){this.fire(new o.C("move",g)),this._zooming&&this.fire(new o.C("zoom",g)),this._rotating&&this.fire(new o.C("rotate",g)),this._pitching&&this.fire(new o.C("pitch",g))}_afterEase(g,N){if(this._easeId&&N&&this._easeId===N)return;this._easeId=void 0,this.transform.cameraElevationReference="ground";const P=this._zooming,F=this._rotating,q=this._pitching;this._moving=!1,this._zooming=!1,this._rotating=!1,this._pitching=!1,this._padding=!1,P&&this.fire(new o.C("zoomend",g)),F&&this.fire(new o.C("rotateend",g)),q&&this.fire(new o.C("pitchend",g)),this.fire(new o.C("moveend",g))}flyTo(g,N){if(this._prefersReducedMotion(g)){const Ts=o.aJ(g,["center","zoom","bearing","pitch","around","padding","retainPadding"]);return this.jumpTo(Ts,N)}this.stop(),g=Object.assign({offset:[0,0],speed:1.2,curve:1.42,easing:o.eP},g);const P=this.transform,F=this.getZoom(),q=this.getBearing(),G=this.getPitch(),Q=this.getPadding(),ae="zoom"in g?o.aC(+g.zoom,P.minZoom,P.maxZoom):F,me="bearing"in g?this._normalizeBearing(g.bearing,q):q,ye="pitch"in g?+g.pitch:G,Ae=this._extendPadding(g.padding),Te=P.zoomScale(ae-F),Fe=o.P.convert(g.offset);let Ye=P.centerPoint.add(Fe);const Ge=P.pointLocation(Ye),dt=o.aU.convert(g.center||Ge);this._normalizeCenter(dt);const lt=P.project(Ge),_t=P.project(dt).sub(lt);let Ct=g.curve;const ht=Math.max(P.width,P.height),Kt=ht/Te,Lt=_t.mag();if("minZoom"in g){const Ts=o.aC(Math.min(g.minZoom,F,ae),P.minZoom,P.maxZoom),Ls=ht/P.zoomScale(Ts-F);Ct=Math.sqrt(Ls/Lt*2)}const Wt=Ct*Ct;function Tt(Ts){const Ls=(Kt*Kt-ht*ht+(Ts?-1:1)*Wt*Wt*Lt*Lt)/(2*(Ts?Kt:ht)*Wt*Lt);return Math.log(Math.sqrt(Ls*Ls+1)-Ls)}function It(Ts){return(Math.exp(Ts)-Math.exp(-Ts))/2}function Ut(Ts){return(Math.exp(Ts)+Math.exp(-Ts))/2}const rs=Tt(0);let Zt=function(Ts){return Ut(rs)/Ut(rs+Ct*Ts)},ks=function(Ts){return ht*((Ut(rs)*(It(Ls=rs+Ct*Ts)/Ut(Ls))-It(rs))/Wt)/Lt;var Ls},ms=(Tt(1)-rs)/Ct;if(Math.abs(Lt)<1e-6||!isFinite(ms)){if(Math.abs(ht-Kt)<1e-6)return this.easeTo(g,N);const Ts=Ktg.maxDuration&&(g.duration=0);const Ws=q!==me,sr=ye!==G,as=!P.isPaddingEqual(Ae),Xt=g.retainPadding===!1?P.clone():P,ws=Ts=>Ls=>{const wr=Ls*ms,mr=1/Zt(wr);Ts.zoom=Ls===1?ae:F+Ts.scaleZoom(mr),Ws&&(Ts.bearing=o.am(q,me,Ls)),sr&&(Ts.pitch=o.am(G,ye,Ls)),as&&(Xt.interpolatePadding(Q,Ae,Ls),Ye=Xt.centerPoint.add(Fe));const fr=Ls===1?dt:Ts.unproject(lt.add(_t.mult(ks(wr))).mult(mr));return Ts.setLocationAtPoint(Ts.renderWorldCopies?fr.wrap():fr,Ye),Ts._updateCameraOnTerrain(),g.preloadOnly||this._fireMoveEvents(N),Ts};if(g.preloadOnly){const Ts=this._emulate(ws,g.duration,P);return this._preloadTiles(Ts),this}return this._zooming=!0,this._rotating=Ws,this._pitching=sr,this._padding=as,this._prepareEase(N,!1),this._ease(ws(P),()=>this._afterEase(N),g),this}isEasing(){return!!this._easeFrameId}stop(){return this._stop()}_requestRenderFrame(g){}_cancelRenderFrame(g){}_stop(g,N){if(this._easeFrameId&&(this._cancelRenderFrame(this._easeFrameId),this._easeFrameId=void 0,this._onEaseFrame=void 0),this._onEaseEnd){const P=this._onEaseEnd;this._onEaseEnd=void 0,P.call(this,N)}if(!g){const P=this.handlers;P&&P.stop(!1)}return this}_ease(g,N,P){P.animate===!1||P.duration===0?(g(1),N()):(this._easeStart=o.o.now(),this._easeOptions=P,this._onEaseFrame=g,this._onEaseEnd=N,this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback))}_renderFrameCallback(){const g=Math.min((o.o.now()-this._easeStart)/this._easeOptions.duration,1),N=this._onEaseFrame;N&&N(this._easeOptions.easing(g)),g<1?this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback):this.stop()}_normalizeBearing(g,N){g=o.bs(g,-180,180);const P=Math.abs(g-N);return Math.abs(g-360-N)180?-360:P<-180?360:0}_prefersReducedMotion(g){return this._respectPrefersReducedMotion&&o.o.prefersReducedMotion&&!(g&&g.essential)}_emulate(g,N,P){const F=Math.ceil(15*N/1e3),q=[],G=g(P.clone());for(let Q=0;Q<=F;Q++){const ae=G(Q/F);q.push(ae.clone())}return q}_preloadTiles(g,N){}}class _D{constructor(g={}){this.options=g,o.aZ(["_toggleAttribution","_updateEditLink","_updateData","_updateCompact"],this)}getDefaultPosition(){return"bottom-right"}onAdd(g){const N=this.options&&this.options.compact,P=g._getUIString("AttributionControl.ToggleAttribution");this._map=g,this._container=_("div","mapboxgl-ctrl mapboxgl-ctrl-attrib"),this._compactButton=_("button","mapboxgl-ctrl-attrib-button",this._container),this._compactButton.type="button",this._compactButton.addEventListener("click",this._toggleAttribution),this._compactButton.setAttribute("aria-label",P);const F=_("span","mapboxgl-ctrl-icon",this._compactButton);return F.setAttribute("aria-hidden","true"),F.setAttribute("title",P),this._innerContainer=_("div","mapboxgl-ctrl-attrib-inner",this._container),N&&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),N===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 g=this._editLink;g||(g=this._editLink=this._container.querySelector(".mapbox-improve-map"));const N=[{key:"owner",value:this.styleOwner},{key:"id",value:this.styleId},{key:"access_token",value:this._map._requestManager._customAccessToken||o.g.ACCESS_TOKEN}];if(g){const P=N.reduce((F,q,G)=>(q.value&&(F+=`${q.key}=${q.value}${GF.length-q.length),g=g.filter((F,q)=>{for(let G=q+1;G=0)return!1;return!0}),this.options.customAttribution&&(Array.isArray(this.options.customAttribution)?g=[...this.options.customAttribution,...g]:g.unshift(this.options.customAttribution));const P=g.map(F=>function(q){const G=new DOMParser().parseFromString(q,"text/html");return Array.from(G.body.querySelectorAll("*")).reverse().forEach(Q=>{const ae=Q.textContent||"";if(Q.tagName!=="A")return void Q.replaceWith(...Q.childNodes);const me=Q.getAttribute("href");if(!me||!/^(https?:|mailto:)/i.test(me))return void Q.replaceWith(G.createTextNode(ae));const ye=G.createElement("a");ye.href=me,ye.textContent=ae,ye.rel="noopener nofollow";const Ae=Q.getAttribute("class");Ae&&(ye.className=Ae),Q.replaceWith(ye)}),G.body.innerHTML}(F)).join(" | ");P!==this._attribHTML&&(this._attribHTML=P,g.length?(this._innerContainer.innerHTML=P,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 wD{constructor(){o.aZ(["_updateLogo","_updateCompact"],this)}onAdd(g){this._map=g,this._container=_("div","mapboxgl-ctrl");const N=_("a","mapboxgl-ctrl-logo");return N.target="_blank",N.rel="noopener nofollow",N.href="https://www.mapbox.com/",N.setAttribute("aria-label",this._map._getUIString("LogoControl.Title")),N.setAttribute("rel","noopener nofollow"),this._container.appendChild(N),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(g){g&&g.sourceDataType!=="metadata"||(this._container.style.display=this._logoRequired()?"block":"none")}_logoRequired(){if(!this._map.style)return!0;const g=this._map.style._sourceCaches;if(Object.entries(g).length===0)return!0;for(const N in g){const P=g[N].getSource();if(P.hasOwnProperty("mapbox_logo")&&!P.mapbox_logo)return!1}return!0}_updateCompact(){const g=this._container.children;if(g.length){const N=g[0];this._map.getCanvasContainer().offsetWidth<250?N.classList.add("mapboxgl-compact"):N.classList.remove("mapboxgl-compact")}}}class Jz{constructor(){this._queue=[],this._id=0,this._cleared=!1,this._currentlyRunning=!1}add(g){const N=++this._id;return this._queue.push({callback:g,id:N,cancelled:!1}),N}remove(g){const N=this._currentlyRunning,P=N?this._queue.concat(N):this._queue;for(const F of P)if(F.id===g)return void(F.cancelled=!0)}run(g=0){const N=this._currentlyRunning=this._queue;this._queue=[];for(const P of N)if(!P.cancelled&&(P.callback(g),this._cleared))break;this._cleared=!1,this._currentlyRunning=!1}clear(){this._currentlyRunning&&(this._cleared=!0),this._queue=[]}}class xye{constructor(g){this.jumpTo(g)}getValue(g){if(g<=this._startTime)return this._start;if(g>=this._endTime)return this._end;const N=o.dn((g-this._startTime)/(this._endTime-this._startTime));return this._start*(1-N)+this._end*N}isEasing(g){return g>=this._startTime&&g<=this._endTime}jumpTo(g){this._startTime=-1/0,this._endTime=-1/0,this._start=g,this._end=g}easeTo(g,N,P){this._start=this.getValue(N),this._end=g,this._startTime=N,this._endTime=N+P}}const yye={"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 No extends o.C{constructor(g,N,P,F){const{point:q,lngLat:G,originalEvent:Q,target:ae}=g;super(g.type,{point:q,lngLat:G,originalEvent:Q,target:ae}),this.preventDefault=()=>{g.preventDefault()},this.id=N,this.interaction=P,this.feature=F}}class TM{constructor(g){this.map=g,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(g,N){if(this.typeById.has(g))throw new Error(`Interaction id "${g}" already exists.`);const P=N.filter;let F=N.type;P&&this.filters.set(g,o.dg(P)),F==="mouseover"&&(F="mouseenter"),F==="mouseout"&&(F="mouseleave");const q=this.interactionsByType.get(F)||new Map;F==="mouseenter"||F==="mouseleave"?(this.delegatedInteractions.size===0&&(this.map.on("mousemove",this.handleMove),this.map.on("mouseout",this.handleOut)),this.delegatedInteractions.set(g,N)):q.size===0&&this.map.on(F,this.handleType),q.size===0&&this.interactionsByType.set(F,q),q.set(g,N),this.typeById.set(g,F)}get(g){const N=this.typeById.get(g);if(!N)return;const P=this.interactionsByType.get(N);return P?P.get(g):void 0}remove(g){const N=this.typeById.get(g);if(!N)return;this.typeById.delete(g),this.filters.delete(g);const P=this.interactionsByType.get(N);P&&(P.delete(g),N==="mouseenter"||N==="mouseleave"?(this.delegatedInteractions.delete(g),this.delegatedInteractions.size===0&&(this.map.off("mousemove",this.handleMove),this.map.off("mouseout",this.handleOut))):P.size===0&&this.map.off(N,this.handleType))}queryTargets(g,N){const P=[];for(const[F,q]of N)q.target&&P.push({targetId:F,target:q.target,filter:this.filters.get(F)});return this.map.style.queryRenderedTargets(g,P,this.map.transform)}handleMove(g){this.prevHoveredFeatures=this.hoveredFeatures,this.hoveredFeatures=new Map;const N=this.queryTargets(g.point,Array.from(this.delegatedInteractions).reverse());N.length&&(g.type="mouseenter",this.handleType(g,N));const P=new Map;for(const[F,{feature:q}]of this.prevHoveredFeatures)this.hoveredFeatures.has(F)||P.set(q.id,q);P.size&&(g.type="mouseleave",this.handleType(g,Array.from(P.values())))}handleOut(g){const N=Array.from(this.hoveredFeatures.values()).map(({feature:P})=>P);N.length&&(g.type="mouseleave",this.handleType(g,N)),this.hoveredFeatures.clear()}handleType(g,N){const P=g.type==="mouseenter";if(P&&!this.interactionsByType.has(g.type))return void o.w("mouseenter interaction required for mouseleave to work.");const F=Array.from(this.interactionsByType.get(g.type)).reverse(),q=!!N;N=N||this.queryTargets(g.point,F);let G=!1;const Q=new Set;for(const ae of N){for(const[me,ye]of F){if(!ye.target)continue;const Ae=ae.variants?ae.variants[me]:null;if(Ae){for(const Te of Ae){if(Ju(Te,ae,Q,me))continue;const Fe=new o.di(ae,Te),Ye=Zf(Te,ae,me);q&&Fe.id!==void 0&&(Fe.state=this.map.getFeatureState(Fe));const Ge=P?this.prevHoveredFeatures.get(Ye):null,dt=new No(g,me,ye,Fe),lt=Ge?Ge.stop:ye.handler(dt);if(P&&this.hoveredFeatures.set(Ye,{feature:ae,stop:lt}),lt!==!1){G=!0;break}}if(G)break}}if(G)break}if(!G)for(const[ae,me]of F){const{handler:ye,target:Ae}=me;if(!Ae&&ye(new No(g,ae,me,null))!==!1)break}}}function vye(M,g){if(Array.isArray(M)&&Array.isArray(g)){const N=new Set(M),P=new Set(g);return N.size===P.size&&M.every(F=>P.has(F))}return o.b6(M,g)}const bye={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,useServerFontComposition:!0,transformRequest:null,accessToken:null,fadeDuration:300,respectPrefersReducedMotion:!0,crossSourceCollisions:!0,collectResourceTiming:!1,testMode:!1,precompilePrograms:!0,scaleFactor:1},_ye={showCompass:!0,showZoom:!0,visualizePitch:!1};class R4{constructor(g,N,P=!1){this._clickTolerance=10,this.element=N,this.mouseRotate=new wM({clickTolerance:g.dragRotate._mouseRotate._clickTolerance}),this.map=g,P&&(this.mousePitch=new M4({clickTolerance:g.dragRotate._mousePitch._clickTolerance})),o.aZ(["mousedown","mousemove","mouseup","touchstart","touchmove","touchend","reset"],this),N.addEventListener("mousedown",this.mousedown),N.addEventListener("touchstart",this.touchstart,{passive:!1}),N.addEventListener("touchmove",this.touchmove),N.addEventListener("touchend",this.touchend),N.addEventListener("touchcancel",this.reset)}down(g,N){this.mouseRotate.mousedown(g,N),this.mousePitch&&this.mousePitch.mousedown(g,N),E()}move(g,N){const P=this.map,F=this.mouseRotate.mousemoveWindow(g,N),q=F&&F.bearingDelta;if(q&&P.setBearing(P.getBearing()+q),this.mousePitch){const G=this.mousePitch.mousemoveWindow(g,N),Q=G&&G.pitchDelta;Q&&P.setPitch(P.getPitch()+Q)}}off(){const g=this.element;g.removeEventListener("mousedown",this.mousedown),g.removeEventListener("touchstart",this.touchstart),g.removeEventListener("touchmove",this.touchmove),g.removeEventListener("touchend",this.touchend),g.removeEventListener("touchcancel",this.reset),this.offTemp()}offTemp(){A(),window.removeEventListener("mousemove",this.mousemove),window.removeEventListener("mouseup",this.mouseup)}mousedown(g){this.down(Object.assign({},g,{button:g.button,type:g.type,ctrlKey:!0,preventDefault:()=>g.preventDefault()}),z(this.element,g)),window.addEventListener("mousemove",this.mousemove),window.addEventListener("mouseup",this.mouseup)}mousemove(g){this.move(g,z(this.element,g))}mouseup(g){this.mouseRotate.mouseupWindow(g),this.mousePitch&&this.mousePitch.mouseupWindow(g),this.offTemp()}touchstart(g){g.targetTouches.length!==1?this.reset():(this._startPos=this._lastPos=O(this.element,g.targetTouches)[0],this.down({type:"mousedown",button:0,ctrlKey:!0,preventDefault:()=>g.preventDefault()},this._startPos))}touchmove(g){g.targetTouches.length!==1?this.reset():(this._lastPos=O(this.element,g.targetTouches)[0],this.move({buttons:1,preventDefault:()=>g.preventDefault()},this._lastPos))}touchend(g){g.targetTouches.length===0&&this._startPos&&this._lastPos&&this._startPos.dist(this._lastPos)N.width||g.y>N.height;N.locationPoint3D(P).distSqr(g)180;){const P=N.locationPoint3D(M);if(P.x>=0&&P.y>=0&&P.x<=N.width&&P.y<=N.height)break;M.lng>N.center.lng?M.lng-=360:M.lng+=360}return M}const O4={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%)"},Gp={rotation:0,rotationAlignment:"auto",pitchAlignment:"auto",occludedOpacity:.2,altitude:0};class zg extends o.E{constructor(g,N){super(),(g instanceof HTMLElement||N)&&(g=Object.assign({element:g},N)),o.aZ(["_update","_onMove","_onUp","_addDragHandler","_onMapClick","_onKeyPress","_clearFadeTimer"],this);const{anchor:P="center",color:F="#3FB1CE",scale:q=1,draggable:G=!1,clickTolerance:Q=0,rotation:ae=Gp.rotation,rotationAlignment:me=Gp.rotationAlignment,pitchAlignment:ye=Gp.pitchAlignment,occludedOpacity:Ae=Gp.occludedOpacity,altitude:Te=Gp.altitude}=g||{};this._anchor=P,this._color=F,this._scale=q,this._draggable=G,this._clickTolerance=Q,this._rotation=ae,this._rotationAlignment=me,this._pitchAlignment=ye,this._occludedOpacity=Ae,this._altitude=Te,this._state="inactive",this._isDragging=!1,this._updateMoving=()=>this._update(!0),g&&g.element?(this._element=g.element,this._offset=o.P.convert(g&&g.offset||[0,0])):(this._defaultMarker=!0,this._element=this._createDefaultMarker(),this._offset=o.P.convert(g&&g.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",Ge=>{Ge.preventDefault()}),this._element.addEventListener("mousedown",Ge=>{Ge.preventDefault()});const Fe=this._element.classList;for(const Ge in O4)Fe.remove(`mapboxgl-marker-anchor-${Ge}`);Fe.add(`mapboxgl-marker-anchor-${this._anchor}`);const Ye=g&&g.className?g.className.trim().split(/\s+/):[];Fe.add(...Ye),this._popup=null}_createDefaultMarker(){const g=_("div"),N=b("svg",{display:"block",height:41*this._scale+"px",width:27*this._scale+"px",viewBox:"0 0 27 41"},g);if(this._altitude===0){const P=b("radialGradient",{id:"shadowGradient"},b("defs",{},N));b("stop",{offset:"10%","stop-opacity":.4},P),b("stop",{offset:"100%","stop-opacity":.05},P),b("ellipse",{cx:13.5,cy:34.8,rx:10.5,ry:5.25,fill:"url(#shadowGradient)"},N)}return b("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"},N),b("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"},N),b("circle",{fill:"white",cx:13.5,cy:13.5,r:5.5},N),g}addTo(g){return g===this._map||(this.remove(),this._map=g,g.getCanvasContainer().appendChild(this._element),g.on("move",this._updateMoving),g.on("moveend",this._update),g.on("remove",this._clearFadeTimer),g._addMarker(this),this.setDraggable(this._draggable),this._update(),g.on("click",this._onMapClick)),this}remove(){const g=this._map;return g&&(g.off("click",this._onMapClick),g.off("move",this._updateMoving),g.off("moveend",this._update),g.off("mousedown",this._addDragHandler),g.off("touchstart",this._addDragHandler),g.off("mouseup",this._onUp),g.off("touchend",this._onUp),g.off("mousemove",this._onMove),g.off("touchmove",this._onMove),g.off("remove",this._clearFadeTimer),g._removeMarker(this),this._map=void 0),this._clearFadeTimer(),this._element.remove(),this._popup&&this._popup.remove(),this}getLngLat(){return this._lngLat}setLngLat(g){return this._lngLat=o.aU.convert(g),this._pos=null,this._popup&&this._popup.setLngLat(this._lngLat),this._update(!0),this}setAltitude(g){return g===this._altitude||(this._defaultMarker&&(this._altitude===0&&g!==0||this._altitude!==0&&g===0)&&(this._element=this._createDefaultMarker()),this._altitude=g||Gp.altitude,this._update()),this}getAltitude(){return this._altitude}getElement(){return this._element}setPopup(g){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")),g){if(!("offset"in g.options)){const F=Math.sqrt(Math.pow(13.5,2)/2);g.options.offset=this._defaultMarker?{top:[0,0],"top-left":[0,0],"top-right":[0,0],bottom:[0,-38.1],"bottom-left":[F,-1*(38.1-13.5+F)],"bottom-right":[-F,-1*(38.1-13.5+F)],left:[13.5,-1*(38.1-13.5)],right:[-13.5,-1*(38.1-13.5)]}:this._offset}this._popup=g,g._marker=this,g._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(g){const N=g.code,P=g.charCode||g.keyCode;N!=="Space"&&N!=="Enter"&&P!==32&&P!==13||this.togglePopup()}_onMapClick(g){const N=g.originalEvent.target,P=this._element;this._popup&&(N===P||P.contains(N))&&this.togglePopup()}getPopup(){return this._popup}togglePopup(){const g=this._popup;return g?(g.isOpen()?(g.remove(),this._element.setAttribute("aria-expanded","false")):this._map&&(g.addTo(this._map),this._element.setAttribute("aria-expanded","true")),this):this}_behindTerrain(){const g=this._map,N=this._pos;if(!g||!N)return!1;const P=g.unproject(N,this._altitude),F=g.getFreeCameraOptions();if(!F.position)return!1;const q=F.position.toLngLat();return q.distanceTo(P)<.9*q.distanceTo(this._lngLat)}_evaluateOpacity(){const g=this._map;if(!g)return;const N=this._pos;if(!N||N.x<0||N.x>g.transform.width||N.y<0||N.y>g.transform.height)return void this._clearFadeTimer();const P=g.unproject(N,this._altitude);let F;g._showingGlobe()&&o.e$(g.transform,this._lngLat)?F=0:(F=1-g._queryFogOpacity(P),g.transform._terrainEnabled()&&g.getTerrain()&&this._behindTerrain()&&(F*=this._occludedOpacity)),this._element.style.opacity=`${F}`,this._element.style.pointerEvents=F>0?"auto":"none",this._popup&&this._popup._setOpacity(F),this._fadeTimer=null}_clearFadeTimer(){this._fadeTimer&&(clearTimeout(this._fadeTimer),this._fadeTimer=null)}_updateDOM(){const g=this._pos;if(!g||!this._map)return;const N=this._offset.mult(this._scale);this._element.style.transform=` translate(${g.x}px,${g.y}px) ${O4[this._anchor]} ${this._calculateXYTransform()} ${this._calculateZTransform()} translate(${N.x}px,${N.y}px) `}_calculateXYTransform(){const g=this._pos,N=this._map,P=this.getPitchAlignment();if(!N||!g||P!=="map")return"";if(!N._showingGlobe()){const ae=N.getPitch();return ae?`rotateX(${ae}deg)`:""}const F=o.cH(o.f0(N.transform,this._lngLat)),q=g.sub(o.f1(N.transform)),G=Math.abs(q.x)+Math.abs(q.y);if(G===0)return"";const Q=F/G;return`rotateX(${-q.y*Q}deg) rotateY(${q.x*Q}deg)`}_calculateZTransform(){const g=this._pos,N=this._map;if(!N||!g)return"";let P=0;const F=this.getRotationAlignment();if(F==="map")if(N._showingGlobe()){const q=N.project(new o.aU(this._lngLat.lng,this._lngLat.lat+.001),this._altitude),G=N.project(new o.aU(this._lngLat.lng,this._lngLat.lat-.001),this._altitude).sub(q);P=o.cH(Math.atan2(G.y,G.x))-90}else P=-N.getBearing();else if(F==="horizon"){const q=o.aj(4,6,N.getZoom()),G=o.f1(N.transform);G.y+=q*N.transform.height;const Q=g.sub(G),ae=o.cH(Math.atan2(Q.y,Q.x));P=(ae>90?ae-270:ae+90)*(1-q)}return P+=this._rotation,P?`rotateZ(${P}deg)`:""}_update(g){cancelAnimationFrame(this._updateFrameId);const N=this._map;N&&(N.transform.renderWorldCopies&&(this._lngLat=jD(this._lngLat,this._pos,N.transform)),this._pos=N.project(this._lngLat,this._altitude),g===!0?this._updateFrameId=requestAnimationFrame(()=>{this._element&&this._pos&&this._anchor&&(this._pos=this._pos.round(),this._updateDOM())}):this._pos=this._pos.round(),N._requestDomTask(()=>{this._map&&(this._element&&this._pos&&this._anchor&&this._updateDOM(),(N._showingGlobe()||N.getTerrain()||N.getFog())&&!this._fadeTimer&&(this._fadeTimer=window.setTimeout(this._evaluateOpacity.bind(this),60)))}))}getOffset(){return this._offset}setOffset(g){return this._offset=o.P.convert(g),this._update(),this}addClassName(g){return this._element.classList.add(g),this}removeClassName(g){return this._element.classList.remove(g),this}toggleClassName(g){return this._element.classList.toggle(g)}_onMove(g){const N=this._map;if(!N)return;const P=this._pointerdownPos,F=this._positionDelta;if(P&&F){if(!this._isDragging){const q=this._clickTolerance||N._clickTolerance;if(g.point.dist(P)M.maxZoom)throw new Error("maxZoom must be greater than or equal to minZoom");if(M.minPitch!=null&&M.maxPitch!=null&&M.minPitch>M.maxPitch)throw new Error("maxPitch must be greater than or equal to minPitch");if(M.minPitch!=null&&M.minPitch<0)throw new Error("minPitch must be greater than or equal to 0");if(M.maxPitch!=null&&M.maxPitch>85)throw new Error("maxPitch must be less than or equal to 85");M.antialias&&o.eZ(window)&&(M.antialias=!1,o.w("Antialiasing is disabled for this WebGL context to avoid browser bug: https://github.com/mapbox/mapbox-gl-js/issues/11609")),super(new Lm(M.minZoom,M.maxZoom,M.minPitch,M.maxPitch,M.renderWorldCopies,null,null),M),this._repaint=!!M.repaint,this._interactive=M.interactive,this._minTileCacheSize=M.minTileCacheSize,this._maxTileCacheSize=M.maxTileCacheSize,this._failIfMajorPerformanceCaveat=M.failIfMajorPerformanceCaveat,this._preserveDrawingBuffer=M.preserveDrawingBuffer,this._antialias=M.antialias,this._trackResize=M.trackResize,this._bearingSnap=M.bearingSnap,this._refreshExpiredTiles=M.refreshExpiredTiles,this._fadeDuration=M.fadeDuration,this._isInitialLoad=!0,this._crossSourceCollisions=M.crossSourceCollisions,this._collectResourceTiming=M.collectResourceTiming,this._language=this._parseLanguage(M.language),this._worldview=M.worldview,this._renderTaskQueue=new Jz,this._domRenderTaskQueue=new Jz,this._controls=[],this._markers=[],this._popups=[],this._mapId=o.r(),this._locale=Object.assign({},yye,M.locale),this._clickTolerance=M.clickTolerance,this._cooperativeGestures=M.cooperativeGestures,this._performanceMetricsCollection=M.performanceMetricsCollection,this._tessellationStep=M.tessellationStep,this._containerWidth=0,this._containerHeight=0,this._showParseStatus=!0,this._precompilePrograms=M.precompilePrograms,this._averageElevationLastSampledAt=-1/0,this._averageElevationExaggeration=0,this._averageElevation=new xye(0),this._interactionRange=[1/0,-1/0],this._visibilityHidden=0,this._useExplicitProjection=!1,this._frameId=0,this._scaleFactor=M.scaleFactor,this._requestManager=new K(M.transformRequest,M.accessToken,M.testMode);const N=le(M.accessToken||o.g.ACCESS_TOKEN);if(N&&"atlas"in N&&typeof N.atlas=="number"&&(this._tokenExpiration=N.atlas),this._silenceAuthErrors=!!M.testMode,this._contextCreateOptions=M.contextCreateOptions?Object.assign({},M.contextCreateOptions):{},typeof M.container=="string"){const P=document.getElementById(M.container);if(!P)throw new Error(`Container '${M.container.toString()}' not found.`);this._container=P}else{if(!(M.container instanceof HTMLElement))throw new Error("Invalid type: 'container' must be a String or HTMLElement.");this._container=M.container}if(this._container.childNodes.length>0&&o.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."),M.maxBounds&&this.setMaxBounds(M.maxBounds),this._spriteFormat="auto",o.aZ(["_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 Xz(this,M),this._localFontFamily=M.localFontFamily,this._localIdeographFontFamily=M.localIdeographFontFamily,this._useServerFontComposition=M.useServerFontComposition,(M.style||!M.testMode)&&this.setStyle(M.style||o.g.DEFAULT_STYLE,{config:M.config,localFontFamily:this._localFontFamily,localIdeographFontFamily:this._localIdeographFontFamily,useServerFontComposition:this._useServerFontComposition}),M.projection&&this.setProjection(M.projection),M.hash&&(this._hash=new lc(typeof M.hash=="string"&&M.hash||void 0).addTo(this)),!this._hash||!this._hash._onHashChange()){g.center==null&&g.zoom==null||(this.transform._unmodified=!1),this.jumpTo({center:M.center,zoom:M.zoom,bearing:M.bearing,pitch:M.pitch});const P=M.bounds;P&&(this.resize(),this.fitBounds(P,Object.assign({},M.fitBoundsOptions,{duration:0})))}this.resize(),M.attributionControl&&this.addControl(new _D({customAttribution:M.customAttribution})),this._logoControl=new wD,this.addControl(this._logoControl,M.logoPosition),this.on("style.load",()=>{this.transform.unmodified&&this.jumpTo(this.style.stylesheet),this._postStyleLoadEvent(),this._postStyleWithAppearanceEvent()}),this.on("data",P=>{this._update(P.dataType==="style"),this.fire(new o.C(`${P.dataType}data`,P))}),this.on("dataloading",P=>{this.fire(new o.C(`${P.dataType}dataloading`,P))}),this._interactions=new TM(this)}_getMapId(){return this._mapId}addControl(M,g){if(g===void 0&&(g=M.getDefaultPosition?M.getDefaultPosition():"top-right"),!M||!M.onAdd)return this.fire(new o.B(new Error("Invalid argument to map.addControl(). Argument must be a control with onAdd and onRemove methods.")));const N=M.onAdd(this);this._controls.push(M);const P=this._controlPositions[g];return g.indexOf("bottom")!==-1?P.insertBefore(N,P.firstChild):P.appendChild(N),this}removeControl(M){if(!M||!M.onRemove)return this.fire(new o.B(new Error("Invalid argument to map.removeControl(). Argument must be a control with onAdd and onRemove methods.")));const g=this._controls.indexOf(M);return g>-1&&this._controls.splice(g,1),M.onRemove(this),this}hasControl(M){return this._controls.indexOf(M)>-1}getContainer(){return this._container}getCanvasContainer(){return this._canvasContainer}getCanvas(){return this._canvas}resize(M){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 g=!this._moving;return g&&this.fire(new o.C("movestart",M)).fire(new o.C("move",M)),this.fire(new o.C("resize",M)),g&&this.fire(new o.C("moveend",M)),this}getBounds(){return this.transform.getBounds()}getMaxBounds(){return this.transform.getMaxBounds()||null}setMaxBounds(M){return this.transform.setMaxBounds(o.aK.convert(M)),this._update()}setMinZoom(M){if((M=M??-2)>=-2&&M<=this.transform.maxZoom)return this.transform.minZoom=M,this._update(),this.getZoom()=this.transform.minZoom)return this.transform.maxZoom=M,this._update(),this.getZoom()>M?this.setZoom(M):this.fire(new o.C("zoomstart")).fire(new o.C("zoom")).fire(new o.C("zoomend")),this;throw new Error("maxZoom must be greater than the current minZoom")}getMaxZoom(){return this.transform.maxZoom}setMinPitch(M){if((M=M??0)<0)throw new Error("minPitch must be greater than or equal to 0");if(M>=0&&M<=this.transform.maxPitch)return this.transform.minPitch=M,this._update(),this.getPitch()85)throw new Error("maxPitch must be less than or equal to 85");if(M>=this.transform.minPitch)return this.transform.maxPitch=M,this._update(),this.getPitch()>M?this.setPitch(M):this.fire(new o.C("pitchstart")).fire(new o.C("pitch")).fire(new o.C("pitchend")),this;throw new Error("maxPitch must be greater than or equal to minPitch")}getMaxPitch(){return this.transform.maxPitch}getScaleFactor(){return this._scaleFactor}setScaleFactor(M){return this._scaleFactor=M,this.painter.scaleFactor=M,this.style&&this.style._setLabelPlacementStale(),this.style._updateFilteredLayers(g=>g.type==="symbol"),this._update(!0),this}getRenderWorldCopies(){return this.transform.renderWorldCopies}setRenderWorldCopies(M){return this.transform.renderWorldCopies=M,this.transform.renderWorldCopies||this._forceMarkerAndPopupUpdate(!0),this._update()}getLanguage(){return this._language}_parseLanguage(M){return M==="auto"?navigator.language:Array.isArray(M)?M.length===0?void 0:M.map(g=>g==="auto"?navigator.language:g):M}setLanguage(M){const g=this._parseLanguage(M);if(!this.style||g===this._language)return this;this._language=g,this.style.reloadSources();for(const N of this._controls)N._setLanguage&&N._setLanguage(this._language);return this}getWorldview(){return this._worldview}setWorldview(M){return this.style&&M!==this._worldview?(this._worldview=M,this._styleDirty=!0,this.style.setWorldview(M),this):this}getProjection(){return this.transform.mercatorFromTransition?{name:"globe",center:[0,0]}:this.transform.getProjection()}_showingGlobe(){return this.transform.projection.name==="globe"}setProjection(M){return this._lazyInitEmptyStyle(),M?typeof M=="string"&&(M={name:M}):M=null,this._useExplicitProjection=!!M,this._prioritizeAndUpdateProjection(M,this.style.projection)}_updateProjectionTransition(){if(this.getProjection().name!=="globe")return;const M=this.transform,g=M.projection.name;let N;g==="globe"&&M.zoom>=o.cv?(M.setMercatorFromTransition(),N=!0):g==="mercator"&&M.zoom=o.cv?this.transform.setMercatorFromTransition():this.transform.setProjection(M),this.style.applyProjectionUpdate();const P=this.transform.getProjection().name==="mercator"&&N!==this.transform.mercatorFromTransition;return(g||P)&&(this.painter.clearBackgroundTiles(),this.style.clearSources(),this._update(!0),this._forceMarkerAndPopupUpdate(!0)),this}project(M,g){return this.transform.locationPoint3D(o.aU.convert(M),g)}unproject(M,g){return this.transform.pointLocation3D(o.P.convert(M),g)}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(M,g,N){const P=F=>{let q=[];if(Array.isArray(g)){const G=g.filter(Q=>this.getLayer(Q));q=G.length?this.queryRenderedFeatures(F,{layers:G}):[]}else q=this.queryRenderedFeatures(F,{target:g});return q};if(M==="mouseenter"||M==="mouseover"){let F=!1;return{listener:N,targets:g,delegates:{mousemove:G=>{const Q=P(G.point);Q.length?F||(F=!0,N.call(this,new Ya(M,this,G.originalEvent,{features:Q}))):F=!1},mouseout:()=>{F=!1}}}}if(M==="mouseleave"||M==="mouseout"){let F=!1;return{listener:N,targets:g,delegates:{mousemove:Q=>{P(Q.point).length?F=!0:F&&(F=!1,N.call(this,new Ya(M,this,Q.originalEvent)))},mouseout:Q=>{F&&(F=!1,N.call(this,new Ya(M,this,Q.originalEvent)))}}}}{const F=q=>{const G=P(q.point);G.length&&(q.features=G,N.call(this,q),delete q.features)};return{listener:N,targets:g,delegates:{[M]:F}}}}on(M,g,N){if(typeof g=="function"||N===void 0)return super.on(M,g);if(typeof g=="string"&&(g=[g]),!this._areTargetsValid(g))return this;const P=this._createDelegatedListener(M,g,N);this._delegatedListeners=this._delegatedListeners||{},this._delegatedListeners[M]=this._delegatedListeners[M]||[],this._delegatedListeners[M].push(P);for(const F in P.delegates)this.on(F,P.delegates[F]);return this}once(M,g,N){if(typeof g=="function"||N===void 0)return super.once(M,g);if(typeof g=="string"&&(g=[g]),!this._areTargetsValid(g))return this;const P=this._createDelegatedListener(M,g,N);for(const F in P.delegates)this.once(F,P.delegates[F]);return this}off(M,g,N){if(typeof g=="function"||N===void 0)return super.off(M,g);if(typeof g=="string"&&(g=[g]),!this._areTargetsValid(g))return this;const P=this._delegatedListeners?this._delegatedListeners[M]:void 0;return P&&(F=>{for(let q=0;q{if(N){const F=typeof N=="string"?N:N instanceof Error?N.message:N.error;o.w(`Unable to perform style diff: ${F}. Rebuilding the style from scratch.`),this._updateStyle(M,g)}else P&&this._update(!0)},()=>this._postStyleLoadEvent()),this):(this._localIdeographFontFamily=g.localIdeographFontFamily,this._localFontFamily=g.localFontFamily,this._updateStyle(M,g))}_getUIString(M){const g=this._locale[M];if(g==null)throw new Error(`Missing UI string '${M}'`);return g}_updateStyle(M,g){if(this.style&&(this.style.setEventedParent(null),this.style._remove(),this.style=void 0),M){const N=Object.assign({},g);g&&g.config&&(N.initialConfig=g.config,delete N.config),this.style=new Mc(this,N).load(M),this.style.setEventedParent(this,{style:this.style})}return this._updateTerrain(),this}_lazyInitEmptyStyle(){this.style||(this.style=new Mc(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():(o.w("There is no style added to the map."),!1)}_isValidId(M){return M==null?(this.fire(new o.B(new Error("IDs can't be empty."))),!1):!o.db(M)||(this.fire(new o.B(new Error(`IDs can't contain special symbols: "${M}".`))),!1)}_isTargetValid(M){return"featuresetId"in M?this._isValidId("importId"in M?M.importId:M.featuresetId):"layerId"in M&&this._isValidId(M.layerId)}_areTargetsValid(M){if(Array.isArray(M)){for(const g of M)if(!this._isValidId(g))return!1;return!0}return this._isTargetValid(M)}addSource(M,g){return this._isValidId(M)?(this._lazyInitEmptyStyle(),this.style.addSource(M,g),this._update(!0)):this}isSourceLoaded(M){return!!this._isValidId(M)&&!!this.style&&this.style._isSourceCacheLoaded(M)}areTilesLoaded(){return this.style.areTilesLoaded()}addSourceType(M,g,N){this._lazyInitEmptyStyle(),this.style.addSourceType(M,g,N)}removeSource(M){return this._isValidId(M)?(this.style.removeSource(M),this._updateTerrain(),this._update(!0)):this}getSource(M){return this._isValidId(M)?this.style.getOwnSource(M):null}addImage(M,g,{pixelRatio:N=1,sdf:P=!1,stretchX:F,stretchY:q,content:G}={}){this._lazyInitEmptyStyle();const Q=o.I.from(M);if(g instanceof HTMLImageElement||ImageBitmap&&g instanceof ImageBitmap){const{width:ae,height:me,data:ye}=o.o.getImageData(g);this.style.addImage(Q,{data:new o.q({width:ae,height:me},ye),pixelRatio:N,stretchX:F,stretchY:q,content:G,sdf:P,version:0,usvg:!1})}else if(g.width===void 0||g.height===void 0)this.fire(new o.B(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:ae,height:me}=g,ye=g;this.style.addImage(Q,{data:new o.q({width:ae,height:me},new Uint8Array(ye.data)),pixelRatio:N,stretchX:F,stretchY:q,content:G,sdf:P,usvg:!1,version:0,userImage:ye}),ye.onAdd&&ye.onAdd(this,M)}}updateImage(M,g){this._lazyInitEmptyStyle();const N=o.I.from(M),P=this.style.getImage(N);if(!P)return void this.fire(new o.B(new Error("The map has no image with that id. If you are adding a new image use `map.addImage(...)` instead.")));const F=g instanceof HTMLImageElement||ImageBitmap&&g instanceof ImageBitmap?o.o.getImageData(g):g,{width:q,height:G,data:Q}=F;if(q===void 0||G===void 0)return void this.fire(new o.B(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(q!==(P.usvg?P.icon.usvg_tree.width:P.data.width)||G!==(P.usvg?P.icon.usvg_tree.height:P.data.height))return void this.fire(new o.B(new Error(`The width and height of the updated image (${q}, ${G}) must be that same as the previous version of the image (${P.data.width}, ${P.data.height})`)));const ae=!(g instanceof HTMLImageElement||ImageBitmap&&g instanceof ImageBitmap);let me=!1;P.usvg?(P.data=new o.q({width:q,height:G},new Uint8Array(Q)),P.usvg=!1,P.icon=void 0,me=!0):P.data.replace(Q,ae),this.style.updateImage(N,P,me)}hasImage(M){return M?!!this.style&&!!this.style.getImage(o.I.from(M)):(this.fire(new o.B(new Error("Missing required image id"))),!1)}removeImage(M){this.style.removeImage(o.I.from(M))}loadImage(M,g){o.n(this._requestManager.transformRequest(M,o.R.Image),(N,P)=>{g(N,P)})}listImages(){return this.style.listImages().map(M=>M.name)}addModel(M,g){this._lazyInitEmptyStyle(),this.style.addModel(M,g)}hasModel(M){return M?this.style.hasModel(M):(this.fire(new o.B(new Error("Missing required model id"))),!1)}removeModel(M){this.style.removeModel(M)}listModels(){return this.style.listModels()}addLayer(M,g){return this._isValidId(M.id)?(this._lazyInitEmptyStyle(),this.style.addLayer(M,g),this._update(!0)):this}getSlot(M){const g=this.getLayer(M);return g&&g.slot||null}setSlot(M,g){return this.style.setSlot(M,g),this.style.mergeLayers(),this._update(!0)}addImport(M,g){return this.style.addImport(M,g).catch(N=>this.fire(new o.B(new Error("Failed to add import",N)))),this}updateImport(M,g){return typeof g!="string"&&g.id!==M?(this.removeImport(M),this.addImport(g)):(this.style.updateImport(M,g),this._update(!0))}removeImport(M){return this.style.removeImport(M),this}moveImport(M,g){return this.style.moveImport(M,g),this._update(!0)}moveLayer(M,g){return this._isValidId(M)?(this.style.moveLayer(M,g),this._update(!0)):this}removeLayer(M){return this._isValidId(M)?(this.style.removeLayer(M),this._update(!0)):this}getLayer(M){if(!this._isValidId(M))return null;const g=this.style.getOwnLayer(M);return g?g.type==="custom"?g.implementation:g.serialize():void 0}getSlots(){return this.style.getSlots()}setLayerZoomRange(M,g,N){return this._isValidId(M)?(this.style.setLayerZoomRange(M,g,N),this._update(!0)):this}setFilter(M,g,N={}){return this._isValidId(M)?(this.style.setFilter(M,g,N),this._update(!0)):this}getFilter(M){return this._isValidId(M)?this.style.getFilter(M):null}setPaintProperty(M,g,N,P={}){return this._isValidId(M)?(this.style.setPaintProperty(M,g,N,P),this._update(!0)):this}getPaintProperty(M,g){return this._isValidId(M)?this.style.getPaintProperty(M,g):null}setLayoutProperty(M,g,N,P={}){return this._isValidId(M)?(this.style.setLayoutProperty(M,g,N,P),this._update(!0)):this}getLayoutProperty(M,g){return this._isValidId(M)?this.style.getLayoutProperty(M,g):null}setLayerProperty(M,g,N,P={}){return this._isValidId(M)?(g==="appearances"&&this._postAddingAppearancesToStyleEvent(),this.style.setLayerProperty(M,g,N,P),this._update(!0)):this}getGlyphsUrl(){return this.style.getGlyphsUrl()}setGlyphsUrl(M){return this.style.setGlyphsUrl(M),this._update(!0)}getSchema(M){return this.style.getSchema(M)}setSchema(M,g){return this.style.setSchema(M,g),this._update(!0)}getConfig(M){return this.style.getConfig(M)}setConfig(M,g){return this.style.setConfig(M,g),this._update(!0)}getConfigProperty(M,g){return this.style.getConfigProperty(M,g)}setConfigProperty(M,g,N){return this.style.setConfigProperty(M,g,N),this._update(!0)}getFeaturesetDescriptors(M){return this.style.getFeaturesetDescriptors(M)}setLights(M){if(this._lazyInitEmptyStyle(),M&&M.length===1&&M[0].type==="flat"){const g=M[0];g.properties?this.style.setFlatLight(g.properties,g.id,{}):this.style.setFlatLight({},"flat")}else this.style.setLights(M),this.painter.terrain&&(this.painter.terrain.invalidateRenderCache=!0);return this._update(!0)}getLights(){const M=this.style.getLights()||[];return M.length===0&&M.push({id:this.style.light.id,type:"flat",properties:this.style.getFlatLight()}),M}setLight(M,g={}){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:M}])}getLight(){return console.log("The `map.getLight` function is deprecated, prefer using `map.getLights` instead."),this.style.getFlatLight()}setTerrain(M){return this._lazyInitEmptyStyle(),!M&&this.transform.projection.requiresDraping?this.style.setTerrainForDraping():this.style.setTerrain(M),this._averageElevationLastSampledAt=-1/0,this._update(!0)}getTerrain(){return this.style?this.style.getTerrain():null}setFog(M){return this._lazyInitEmptyStyle(),this.style.setFog(M),this._update(!0)}getFog(){return this.style?this.style.getFog():null}setSnow(M){return this._lazyInitEmptyStyle(),this.style.setSnow(M),this._update(!0)}getSnow(){return this.style?this.style.getSnow():null}setRain(M){return this._lazyInitEmptyStyle(),this.style.setRain(M),this._update(!0)}getRain(){return this.style?this.style.getRain():null}setColorTheme(M){return this._lazyInitEmptyStyle(),this.style.setColorTheme(M),this._update(!0)}setImportColorTheme(M,g){return this._lazyInitEmptyStyle(),this.style.setImportColorTheme(M,g),this._update(!0)}setCamera(M){return this.style.setCamera(M),this._triggerCameraUpdate(M)}getNearClipOffset(){return this.transform.nearClipOffset}setNearClipOffset(M){const g=this.transform.nearClipOffset!==M;return this.transform.nearClipOffset=M,this._update(g)}_triggerCameraUpdate(M){return this._update(this.transform.setOrthographicProjectionAtLowPitch(M["camera-projection"]==="orthographic"))}getCamera(){return this.style.camera}_queryFogOpacity(M){return this.style&&this.style.fog?this.style.fog.getOpacityAtLatLng(o.aU.convert(M),this.transform):0}setFeatureState(M,g){return M.source&&!this._isValidId(M.source)?this:(this.style.setFeatureState(M,g),this._update())}removeFeatureState(M,g){return M.source&&!this._isValidId(M.source)?this:(this.style.removeFeatureState(M,g),this._update())}getFeatureState(M){return M.source&&!this._isValidId(M.source)?null:this.style.getFeatureState(M)}_selectIndoorFloor(M){this.style.indoorManager.selectFloor(M)}_setIndoorActiveFloorsVisibility(M){this.style.indoorManager.setActiveFloorsVisibility(M)}getIndoorTileOptions(M,g){return this.style.isIndoorEnabled()?this.style.indoorManager.getIndoorTileOptions(M,g):null}_updateContainerDimensions(){if(!this._container)return;const M=this._container.getBoundingClientRect().width||400,g=this._container.getBoundingClientRect().height||300;let N,P,F,q=this._container;for(;q&&(!P||!F);){const G=window.getComputedStyle(q).transform;G&&G!=="none"&&(N=G.match(/matrix.*\((.+)\)/)[1].split(", "),N[0]&&N[0]!=="0"&&N[0]!=="1"&&(P=N[0]),N[3]&&N[3]!=="0"&&N[3]!=="1"&&(F=N[3])),q=q.parentElement}this._containerWidth=P?Math.abs(M/P):M,this._containerHeight=F?Math.abs(g/F):g}_detectMissingCSS(){window.getComputedStyle(this._missingCSSCanary).getPropertyValue("background-color")!=="rgb(250, 128, 114)"&&o.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/.")}_setupContainer(){const M=this._container;M.classList.add("mapboxgl-map"),(this._missingCSSCanary=_("div","mapboxgl-canary",M)).style.visibility="hidden",this._detectMissingCSS();const g=this._canvasContainer=_("div","mapboxgl-canvas-container",M);this._canvas=_("canvas","mapboxgl-canvas",g),this._interactive&&(g.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 N=this._controlContainer=_("div","mapboxgl-control-container",M),P=this._controlPositions={};["top-left","top","top-right","right","bottom-right","bottom","bottom-left","left"].forEach(F=>{P[F]=_("div",`mapboxgl-ctrl-${F}`,N)}),this._container.addEventListener("scroll",this._onMapScroll,!1)}_resizeCanvas(M,g){const N=o.o.devicePixelRatio||1;this._canvas.width=N*Math.ceil(M),this._canvas.height=N*Math.ceil(g),this._canvas.style.width=`${M}px`,this._canvas.style.height=`${g}px`}_addMarker(M){this._markers.push(M)}_removeMarker(M){const g=this._markers.indexOf(M);g!==-1&&this._markers.splice(g,1)}_addPopup(M){this._popups.push(M)}_removePopup(M){const g=this._popups.indexOf(M);g!==-1&&this._popups.splice(g,1)}_setupPainter(){const M=Object.assign({},y.supported.webGLContextAttributes,{failIfMajorPerformanceCaveat:this._failIfMajorPerformanceCaveat,preserveDrawingBuffer:this._preserveDrawingBuffer,antialias:this._antialias||!1}),g=this._canvas.getContext("webgl2",M);g?(Qe(g,!0),this.painter=new eo(g,this._contextCreateOptions,this.transform,this._scaleFactor,this._worldview),this.on("data",N=>{if(N.dataType==="source"){const P=this.transform.elevation?this.transform.elevation._source():null;P&&N.sourceCacheId===P.id&&this.style&&this.style._setLabelPlacementStale(),this.painter.setTileLoadedFlag(!0)}}),o.k.testSupport(g)):this.fire(new o.B(new Error("Failed to initialize WebGL")))}_contextLost(M){M.preventDefault(),this._frame&&(this._frame.cancel(),this._frame=null),this.fire(new o.C("webglcontextlost",{originalEvent:M}))}_contextRestored(M){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.imageManager.imageAtlasCache.destroyTextures(),this.style.reloadModels(),this.style.clearSources()),this._update(),this.fire(new o.C("webglcontextrestored",{originalEvent:M}))}_onMapScroll(M){if(M.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(M){return this.style?(this._styleDirty=this._styleDirty||M,this._sourcesDirty=!0,this.triggerRepaint(),this):this}_requestRenderFrame(M){return this._update(),this._renderTaskQueue.add(M)}_cancelRenderFrame(M){this._renderTaskQueue.remove(M)}_requestDomTask(M){!this.loaded()||this.loaded()&&!this.isMoving()?M():this._domRenderTaskQueue.add(M)}_render(M){let g;this.fire(new o.C("renderstart")),++this._frameId;const N=this.painter.context.extTimerQuery,P=o.o.now(),F=this.painter.context.gl;if(this.listens("gpu-timing-frame")&&(g=F.createQuery(),F.beginQuery(N.TIME_ELAPSED_EXT,g)),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(M),this._domRenderTaskQueue.run(M),this._removed)return;this._updateProjectionTransition();const q=this._isInitialLoad?0:this._fadeDuration;if(this.style&&this._styleDirty){this._styleDirty=!1;const ae=this.transform.zoom,me=this.transform.pitch,ye=o.o.now(),Ae=new o.ae(ae,{now:ye,fadeDuration:q,pitch:me,transition:this.style.transition,worldview:this._worldview});this.style.update(Ae)}this.style&&this.style.hasFogTransition()&&(this.style._markersNeedUpdate=!0,this._sourcesDirty=!0);let G=!1;if(this.style&&this._sourcesDirty?(this._sourcesDirty=!1,this.painter._updateFog(this.style),this._updateTerrain(),G=this._updateAverageElevation(P),this.style.updateSources(this.transform),this.style.updateImageProviders(),this.isMoving()||this._forceMarkerAndPopupUpdate()):G=this._updateAverageElevation(P),this.style&&(this._placementDirty=this.style._updatePlacement(this.painter.transform,this.showCollisionBoxes,q,this._crossSourceCollisions,this.painter.replacementSource)),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:q,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 o.C("render")),this.loaded()&&!this._loaded&&(this._loaded=!0,h.mark(d.load),this.fire(new o.C("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(),g){const ae=o.o.now()-P;F.endQuery(N.TIME_ELAPSED_EXT),setTimeout(()=>{const me=F.getQueryParameter(g,F.QUERY_RESULT)/1e6;F.deleteQuery(g),this.fire(new o.C("gpu-timing-frame",{cpuTime:ae,gpuTime:me}))},50)}if(this.listens("gpu-timing-layer")){const ae=this.painter.collectGpuTimers();setTimeout(()=>{const me=this.painter.queryGpuTimers(ae);this.fire(new o.C("gpu-timing-layer",{layerTimes:me}))},50)}if(this.listens("gpu-timing-deferred-render")){const ae=this.painter.collectDeferredRenderGpuQueries();setTimeout(()=>{const me=this.painter.queryGpuTimeDeferredRender(ae);this.fire(new o.C("gpu-timing-deferred-render",{gpuTime:me}))},50)}const Q=this._sourcesDirty||this._styleDirty||this._placementDirty||G;if(Q||this._repaint)this.triggerRepaint();else{const ae=this.idle();if(ae&&(G=this._updateAverageElevation(P,!0)),G)this.triggerRepaint();else if(this._triggerFrame(!1),ae&&(this.fire(new o.C("idle")),this._isInitialLoad=!1,this.speedIndexTiming)){const me=this._calculateSpeedIndex();this.fire(new o.C("speedindexcompleted",{speedIndex:me})),this.speedIndexTiming=!1}}!this._loaded||this._fullyLoaded||Q||(this._fullyLoaded=!0,h.mark(d.fullLoad),this._performanceMetricsCollection&&ge(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(M){for(const g of this._markers)M&&!this.getRenderWorldCopies()&&(g._lngLat=g._lngLat.wrap()),g._update();for(const g of this._popups)!M||this.getRenderWorldCopies()||g._trackPointer||(g._lngLat=g._lngLat.wrap()),g._update()}_updateAverageElevation(M,g=!1){const N=F=>(this.transform.averageElevation=F,this._update(!1),!0);if(!this.painter.averageElevationNeedsEasing())return this.transform.averageElevation!==0&&N(0);const P=this.transform.elevation&&this.transform.elevation.exaggeration()!==this._averageElevationExaggeration;if(P||(g||M-this._averageElevationLastSampledAt>500)&&!this._averageElevation.isEasing(M)){const F=this.transform.averageElevation;let q=this.transform.sampleAverageElevation();this.transform.elevation!=null&&(this._averageElevationExaggeration=this.transform.elevation.exaggeration()),isNaN(q)?q=0:this._averageElevationLastSampledAt=M;const G=Math.abs(F-q);if(G>1){if(this._isInitialLoad||P)return this._averageElevation.jumpTo(q),N(q);this._averageElevation.easeTo(q,M,300)}else if(G>1e-4)return this._averageElevation.jumpTo(q),N(q)}return!!this._averageElevation.isEasing(M)&&N(this._averageElevation.getValue(M))}_isTokenExpired(){return this._tokenExpiration!=null&&Date.now()>this._tokenExpiration}_revokeAuth(){const M=this.painter.context.gl;Qe(M,!1),this._logoControl instanceof wD&&this._logoControl._updateLogo(),M&&M.clear(M.DEPTH_BUFFER_BIT|M.COLOR_BUFFER_BIT|M.STENCIL_BUFFER_BIT),this._silenceAuthErrors||this.fire(new o.B(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/")))}_authenticate(){Ue(this._getMapId(),this._requestManager._skuToken,this._requestManager._customAccessToken,M=>{M&&(M.message!==J&&M.status!==401||this._revokeAuth())}),this._isTokenExpired()&&this._revokeAuth(),Le(this._getMapId(),this._requestManager._skuToken,this._requestManager._customAccessToken,()=>{})}_postStyleLoadEvent(){this.style.globalId&&ze(this._requestManager._customAccessToken,{map:this,style:this.style.globalId,importedStyles:this.style.getImportGlobalIds()})}_postStyleWithAppearanceEvent(){this.style.globalId&&this.style.hasAppearances()&&Ie(this._requestManager._customAccessToken)}_postAddingAppearancesToStyleEvent(){pe(this._requestManager._customAccessToken)}_updateTerrain(){const M=this._isDragging();this.painter.updateTerrain(this.style,M)}_calculateSpeedIndex(){const M=this.painter.canvasCopy(),g=this.painter.getCanvasCopiesAndTimestamps();g.timeStamps.push(performance.now());const N=this.painter.context.gl,P=N.createFramebuffer();function F(q){N.framebufferTexture2D(N.FRAMEBUFFER,N.COLOR_ATTACHMENT0,N.TEXTURE_2D,q,0);const G=new Uint8Array(N.drawingBufferWidth*N.drawingBufferHeight*4);return N.readPixels(0,0,N.drawingBufferWidth,N.drawingBufferHeight,N.RGBA,N.UNSIGNED_BYTE,G),G}return N.bindFramebuffer(N.FRAMEBUFFER,P),this._canvasPixelComparison(F(M),g.canvasCopies.map(F),g.timeStamps)}_canvasPixelComparison(M,g,N){let P=N[1]-N[0];const F=M.length/4;for(let q=0;q{const N=!!this._renderNextFrame;this._frame=null,this._renderNextFrame=null,N&&this._render(g)}))}_preloadTiles(M){const g=this.style?this.style.getSourceCaches():[];return o.t(g,(N,P)=>N._preloadTiles(M,P),()=>{this.triggerRepaint()}),this}_onWindowOnline(){this._update()}_onWindowResize(M){this._trackResize&&this.resize({originalEvent:M})._update()}_onVisibilityChange(){document.visibilityState==="hidden"&&this._visibilityHidden++}get showTileBoundaries(){return!!this._showTileBoundaries}set showTileBoundaries(M){this._showTileBoundaries!==M&&(this._showTileBoundaries=M,this._update())}get showParseStatus(){return!!this._showParseStatus}set showParseStatus(M){this._showParseStatus!==M&&(this._showParseStatus=M,this._update())}get showTerrainWireframe(){return!!this._showTerrainWireframe}set showTerrainWireframe(M){this._showTerrainWireframe!==M&&(this._showTerrainWireframe=M,this._update())}get showLayers2DWireframe(){return!!this._showLayers2DWireframe}set showLayers2DWireframe(M){this._showLayers2DWireframe!==M&&(this._showLayers2DWireframe=M,this._update())}get showLayers3DWireframe(){return!!this._showLayers3DWireframe}set showLayers3DWireframe(M){this._showLayers3DWireframe!==M&&(this._showLayers3DWireframe=M,this._update())}get speedIndexTiming(){return!!this._speedIndexTiming}set speedIndexTiming(M){this._speedIndexTiming!==M&&(this._speedIndexTiming=M,this._update())}get showPadding(){return!!this._showPadding}set showPadding(M){this._showPadding!==M&&(this._showPadding=M,this._update())}get showCollisionBoxes(){return!!this._showCollisionBoxes}set showCollisionBoxes(M){this._showCollisionBoxes!==M&&(this._showCollisionBoxes=M,this.style&&M?this.style._generateCollisionBoxes():this._update())}get showOverdrawInspector(){return!!this._showOverdrawInspector}set showOverdrawInspector(M){this._showOverdrawInspector!==M&&(this._showOverdrawInspector=M,this._update())}get repaint(){return!!this._repaint}set repaint(M){this._repaint!==M&&(this._repaint=M,this.triggerRepaint())}get vertices(){return!!this._vertices}set vertices(M){this._vertices=M,this._update()}get showTileAABBs(){return!!this._showTileAABBs}set showTileAABBs(M){this._showTileAABBs!==M&&(this._showTileAABBs=M,M&&this._update())}_setCacheLimits(M,g){o.e_(M,g)}get version(){return c}},NavigationControl:class{constructor(M={}){this.options=Object.assign({},_ye,M),this._container=_("div","mapboxgl-ctrl mapboxgl-ctrl-group"),this._container.addEventListener("contextmenu",g=>g.preventDefault()),this.options.showZoom&&(o.aZ(["_setButtonTitle","_updateZoomButtons"],this),this._zoomInButton=this._createButton("mapboxgl-ctrl-zoom-in",g=>{this._map&&this._map.zoomIn({},{originalEvent:g})}),_("span","mapboxgl-ctrl-icon",this._zoomInButton).setAttribute("aria-hidden","true"),this._zoomOutButton=this._createButton("mapboxgl-ctrl-zoom-out",g=>{this._map&&this._map.zoomOut({},{originalEvent:g})}),_("span","mapboxgl-ctrl-icon",this._zoomOutButton).setAttribute("aria-hidden","true")),this.options.showCompass&&(o.aZ(["_rotateCompassArrow"],this),this._compass=this._createButton("mapboxgl-ctrl-compass",g=>{const N=this._map;N&&(this.options.visualizePitch?N.resetNorthPitch({},{originalEvent:g}):N.resetNorth({},{originalEvent:g}))}),this._compassIcon=_("span","mapboxgl-ctrl-icon",this._compass),this._compassIcon.setAttribute("aria-hidden","true"))}_updateZoomButtons(){const M=this._map;if(!M)return;const g=M.getZoom(),N=g===M.getMaxZoom(),P=g===M.getMinZoom();this._zoomInButton.disabled=N,this._zoomOutButton.disabled=P,this._zoomInButton.setAttribute("aria-disabled",N.toString()),this._zoomOutButton.setAttribute("aria-disabled",P.toString())}_rotateCompassArrow(){const M=this._map;if(!M)return;const g=this.options.visualizePitch?`scale(${1/Math.pow(Math.cos(M.transform.pitch*(Math.PI/180)),.5)}) rotateX(${M.transform.pitch}deg) rotateZ(${M.transform.angle*(180/Math.PI)}deg)`:`rotate(${M.transform.angle*(180/Math.PI)}deg)`;M._requestDomTask(()=>{this._compassIcon&&(this._compassIcon.style.transform=g)})}onAdd(M){return this._map=M,this.options.showZoom&&(this._setButtonTitle(this._zoomInButton,"ZoomIn"),this._setButtonTitle(this._zoomOutButton,"ZoomOut"),M.on("zoom",this._updateZoomButtons),this._updateZoomButtons()),this.options.showCompass&&(this._setButtonTitle(this._compass,"ResetBearing"),this.options.visualizePitch&&M.on("pitch",this._rotateCompassArrow),M.on("rotate",this._rotateCompassArrow),this._rotateCompassArrow(),this._handler=new R4(M,this._compass,this.options.visualizePitch)),this._container}onRemove(){const M=this._map;M&&(this._container.remove(),this.options.showZoom&&M.off("zoom",this._updateZoomButtons),this.options.showCompass&&(this.options.visualizePitch&&M.off("pitch",this._rotateCompassArrow),M.off("rotate",this._rotateCompassArrow),this._handler&&this._handler.off(),this._handler=void 0),this._map=void 0)}_createButton(M,g){const N=_("button",M,this._container);return N.type="button",N.addEventListener("click",g),N}_setButtonTitle(M,g){if(!this._map)return;const N=this._map._getUIString(`NavigationControl.${g}`);M.setAttribute("aria-label",N),M.firstElementChild&&M.firstElementChild.setAttribute("title",N)}},GeolocateControl:class extends o.E{constructor(M={}){super();const g=navigator.geolocation;this.options=Object.assign({geolocation:g},F4,M),o.aZ(["_onSuccess","_onError","_onZoom","_finish","_setupUI","_updateCamera","_updateMarker","_updateMarkerRotation","_onDeviceOrientation"],this),this._updateMarkerRotationThrottled=ha(this._updateMarkerRotation,20),this._numberOfWatches=0}onAdd(M){return this._map=M,this._container=_("div","mapboxgl-ctrl mapboxgl-ctrl-group"),this._checkGeolocationSupport(this._setupUI),this._container}onRemove(){this._clearRequestTimeout(),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(M){const g=(N=!!this.options.geolocation)=>{this._supportsGeolocation=N,M(N)};this._supportsGeolocation!==void 0?M(this._supportsGeolocation):navigator.permissions!==void 0?navigator.permissions.query({name:"geolocation"}).then(N=>g(N.state!=="denied")).catch(()=>g()):g()}_isOutOfMapMaxBounds(M){const g=this._map.getMaxBounds(),N=M.coords;return!!g&&(N.longitudeg.getEast()||N.latitudeg.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(M){if(this._map){if(this._clearRequestTimeout(),this._isOutOfMapMaxBounds(M))return this._setErrorState(),this.fire(new o.C("outofmaxbounds",M)),this._updateMarker(),void this._finish();if(this.options.trackUserLocation)switch(this._lastKnownPosition=M,this._watchState){case"WAITING_ACTIVE":case"ACTIVE_LOCK":case"ACTIVE_ERROR":this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active-error"),this.options.followUserLocation?(this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active")):(this._watchState="BACKGROUND",this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background"));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(M),this.options.followUserLocation&&(!this.options.trackUserLocation||this._watchState==="ACTIVE_LOCK")&&this._updateCamera(M),this.options.showUserLocation&&this._userLocationDotMarker.removeClassName("mapboxgl-user-location-dot-stale"),this.fire(new o.C("geolocate",Object.assign({coords:M.coords,timestamp:M.timestamp},M.toJSON?{toJSON:M.toJSON.bind(M)}:{}))),this._finish()}}_updateCamera(M){const g=new o.aU(M.coords.longitude,M.coords.latitude),N=M.coords.accuracy,P=this._map.getBearing(),F=Object.assign({bearing:P},this.options.fitBoundsOptions);this._map.fitBounds(g.toBounds(N),F,{geolocateSource:!0})}_updateMarker(M){if(M){const g=new o.aU(M.coords.longitude,M.coords.latitude);this._accuracyCircleMarker.setLngLat(g).addTo(this._map),this._userLocationDotMarker.setLngLat(g).addTo(this._map),this._accuracy=M.coords.accuracy,this.options.showUserLocation&&this.options.showAccuracyCircle&&this._updateCircleRadius()}else this._userLocationDotMarker.remove(),this._accuracyCircleMarker.remove()}_updateCircleRadius(){const M=this._map.transform,g=o.bU(1,M._center.lat)*M.worldSize,N=Math.ceil(2*this._accuracy*g);this._circleElement.style.width=`${N}px`,this._circleElement.style.height=`${N}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(M){if(this._map){if(this._clearRequestTimeout(),this.options.trackUserLocation)if(M.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 g=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.setAttribute("aria-label",g),this._geolocateButton.firstElementChild&&this._geolocateButton.firstElementChild.setAttribute("title",g),this._geolocationWatchID!==void 0&&this._clearWatch()}else{if(M.code===3&&this._noTimeout)return;this._setErrorState()}this._watchState!=="OFF"&&this.options.showUserLocation&&this._userLocationDotMarker.addClassName("mapboxgl-user-location-dot-stale"),this.fire(new o.C("error",{code:M.code,message:M.message,PERMISSION_DENIED:M.PERMISSION_DENIED,POSITION_UNAVAILABLE:M.POSITION_UNAVAILABLE,TIMEOUT:M.TIMEOUT})),this._finish()}}_finish(){this._timeoutId&&clearTimeout(this._timeoutId),this._timeoutId=void 0}_startRequestTimeout(){this._clearRequestTimeout();const M=this.options.positionOptions.timeout;M&&(this._requestTimeoutId=window.setTimeout(()=>{this._onError({code:3,message:"Geolocation request timed out"})},M))}_clearRequestTimeout(){this._requestTimeoutId!==void 0&&(clearTimeout(this._requestTimeoutId),this._requestTimeoutId=void 0)}_setupUI(M){if(this._map!==void 0){if(this._container.addEventListener("contextmenu",g=>g.preventDefault()),this._geolocateButton=_("button","mapboxgl-ctrl-geolocate",this._container),_("span","mapboxgl-ctrl-icon",this._geolocateButton).setAttribute("aria-hidden","true"),this._geolocateButton.type="button",M===!1){o.w("Geolocation support is not available so the GeolocateControl will be disabled.");const g=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.disabled=!0,this._geolocateButton.setAttribute("aria-label",g),this._geolocateButton.firstElementChild&&this._geolocateButton.firstElementChild.setAttribute("title",g)}else{const g=this._map._getUIString("GeolocateControl.FindMyLocation");this._geolocateButton.setAttribute("aria-label",g),this._geolocateButton.firstElementChild&&this._geolocateButton.firstElementChild.setAttribute("title",g)}this.options.trackUserLocation&&(this._geolocateButton.setAttribute("aria-pressed","false"),this._watchState="OFF"),this.options.showUserLocation&&(this._dotElement=_("div","mapboxgl-user-location"),this._dotElement.appendChild(_("div","mapboxgl-user-location-dot")),this._dotElement.appendChild(_("div","mapboxgl-user-location-heading")),this._userLocationDotMarker=new zg({element:this._dotElement,rotationAlignment:"map",pitchAlignment:"map"}),this._circleElement=_("div","mapboxgl-user-location-accuracy-circle"),this._accuracyCircleMarker=new zg({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.showButton||(this._container.style.display="none"),this.options.trackUserLocation&&this._map.on("movestart",g=>{g.geolocateSource||this._watchState!=="ACTIVE_LOCK"||g.originalEvent&&g.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 o.C("trackuserlocationend")))})}}_onDeviceOrientation(M){this._userLocationDotMarker&&(M.webkitCompassHeading?this._heading=M.webkitCompassHeading:M.absolute===!0&&(this._heading=-1*M.alpha),this._updateMarkerRotationThrottled())}trigger(){if(!this._setup)return o.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 o.C("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 o.C("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 o.C("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 M;this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","true"),this._numberOfWatches++,this._numberOfWatches>1?(M={maximumAge:6e5,timeout:0},this._noTimeout=!0):(M=this.options.positionOptions,this._noTimeout=!1),this._geolocationWatchID=this.options.geolocation.watchPosition(this._onSuccess,this._onError,M),this._startRequestTimeout(),this.options.showUserHeading&&this._addDeviceOrientationListener()}}else this.options.geolocation.getCurrentPosition(this._onSuccess,this._onError,this.options.positionOptions),this._startRequestTimeout(),this._timeoutId=window.setTimeout(this._finish,1e4);return!0}setFollowUserLocation(M){return this.options.followUserLocation=M??F4.followUserLocation,this.options.trackUserLocation&&this._watchState!=="OFF"&&(this.options.followUserLocation?this._watchState!=="BACKGROUND"&&this._watchState!=="BACKGROUND_ERROR"||(this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active"),this._lastKnownPosition&&this._updateCamera(this._lastKnownPosition),this.fire(new o.C("trackuserlocationstart"))):this._watchState!=="ACTIVE_LOCK"&&this._watchState!=="ACTIVE_ERROR"||(this._watchState="BACKGROUND",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background"),this.fire(new o.C("trackuserlocationend")))),this}_addDeviceOrientationListener(){const M=()=>{const g="ondeviceorientationabsolute"in window?"deviceorientationabsolute":"deviceorientation";window.addEventListener(g,this._onDeviceOrientation)};typeof DeviceOrientationEvent.requestPermission=="function"?DeviceOrientationEvent.requestPermission().then(g=>{g==="granted"&&M()}).catch(console.error):M()}_clearWatch(){this._clearRequestTimeout(),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:_D,ScaleControl:class{constructor(M={}){this.options=Object.assign({},Yc,M),o.aZ(["_update","_setScale","setUnit"],this)}getDefaultPosition(){return"bottom-left"}_update(){const M=this.options.maxWidth||100,g=this._map,N=g._containerHeight/2,P=g._containerWidth/2-M/2,F=g.unproject([P,N]),q=g.unproject([P+M,N]),G=F.distanceTo(q);if(this.options.unit==="imperial"){const Q=3.2808*G;Q>5280?this._setScale(M,Q/5280,"mile"):this._setScale(M,Q,"foot")}else this.options.unit==="nautical"?this._setScale(M,G/1852,"nautical-mile"):G>=1e3?this._setScale(M,G/1e3,"kilometer"):this._setScale(M,G,"meter")}_setScale(M,g,N){this._map._requestDomTask(()=>{const P=function(q){const G=Math.pow(10,`${Math.floor(q)}`.length-1);let Q=q/G;return Q=Q>=10?10:Q>=5?5:Q>=3?3:Q>=2?2:Q>=1?1:function(ae){const me=Math.pow(10,Math.ceil(-Math.log(ae)/Math.LN10));return Math.round(ae*me)/me}(Q),G*Q}(g),F=P/g;this._container.innerHTML=N!=="nautical-mile"?new Intl.NumberFormat(this._language,{style:"unit",unitDisplay:"short",unit:N}).format(P):`${P} ${$g[N]}`,this._container.style.width=M*F+"px"})}onAdd(M){return this._map=M,this._language=M.getLanguage(),this._container=_("div","mapboxgl-ctrl mapboxgl-ctrl-scale",M.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(M){this._language=M,this._update()}setUnit(M){this.options.unit=M,this._update()}},FullscreenControl:class{constructor(M={}){this._fullscreen=!1,M&&M.container&&(M.container instanceof HTMLElement?this._container=M.container:o.w("Full screen control 'container' must be a DOM element.")),o.aZ(["_onClickFullscreen","_changeIcon"],this),"onfullscreenchange"in document?this._fullscreenchange="fullscreenchange":"onwebkitfullscreenchange"in document&&(this._fullscreenchange="webkitfullscreenchange")}onAdd(M){return this._map=M,this._container||(this._container=this._map.getContainer()),this._controlContainer=_("div","mapboxgl-ctrl mapboxgl-ctrl-group"),this._checkFullscreenSupport()?this._setupUI():(this._controlContainer.style.display="none",o.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 M=this._fullscreenButton=_("button","mapboxgl-ctrl-fullscreen",this._controlContainer);_("span","mapboxgl-ctrl-icon",M).setAttribute("aria-hidden","true"),M.type="button",this._updateTitle(),this._fullscreenButton.addEventListener("click",this._onClickFullscreen),document.addEventListener(this._fullscreenchange,this._changeIcon)}_updateTitle(){const M=this._getTitle();this._fullscreenButton.setAttribute("aria-label",M),this._fullscreenButton.firstElementChild&&this._fullscreenButton.firstElementChild.setAttribute("title",M)}_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:class{constructor(){o.aZ(["_onIndoorUpdate","_onStyleData","_scrollUp","_scrollDown","_toggleIndoor"],this),this._visibleFloorStart=0,this._lastSelectedFloorId=null}onAdd(M){return this._map=M,this._container=_("div","mapboxgl-ctrl mapboxgl-ctrl-group"),this._container.style.display="none",this._map.on("styledata",this._onStyleData),this._updateConnection(),this._container}_onStyleData(){this._updateConnection()}_updateConnection(){if(this._map&&this._map.style&&this._map.style.indoorManager){const M=this._map.style.indoorManager;M.off("selector-update",this._onIndoorUpdate),M.on("selector-update",this._onIndoorUpdate),this._onIndoorUpdate(M.getControlState())}}_createButton(M,g){const N=_("button",M,this._container);return N.type="button",N.addEventListener("click",g),N}_setButtonTitle(M,g){M.setAttribute("aria-label",g),M.textContent=g}onRemove(){this._container&&this._container.remove(),this._map&&(this._map.off("styledata",this._onStyleData),this._map.style&&this._map.style.indoorManager.off("selector-update",this._onIndoorUpdate),this._map=null)}getDefaultPosition(){return"top-right"}_onIndoorUpdate(M){if(!M||!M.floors||M.floors.length===0)return this._model=M,void(this._container.style.display="none");const g=this._model;this._model=M,this._container.style.display="inline-block";const N=!g||g.floors.length!==M.floors.length||g.floors.some((P,F)=>P.id!==M.floors[F].id);if(N&&(this._visibleFloorStart=0,this._lastSelectedFloorId=null),M.selectedFloorId){if(M.selectedFloorId!==this._lastSelectedFloorId||N){const P=M.floors.findIndex(F=>F.id===M.selectedFloorId);if(P!==-1){const F=M.floors.length;let q,G;F<=5?(q=0,G=F-1):this._visibleFloorStart===0?(q=0,G=3):this._visibleFloorStart>=F-3?(q=F-3-1,G=F-1):(q=this._visibleFloorStart,G=this._visibleFloorStart+3-1),PG&&(this._visibleFloorStart=P-2)}}this._lastSelectedFloorId=M.selectedFloorId}this._render()}_render(){if(!this._container||!this._model||!this._model.floors)return;this._container.innerHTML="";const M=this._createButton("mapboxgl-ctrl-indoor-toggle",this._toggleIndoor);_("span","mapboxgl-ctrl-icon",M).setAttribute("aria-hidden","true"),this._model.activeFloorsVisible||M.classList.add("mapboxgl-ctrl-level-button-selected"),this._container.appendChild(M);const g=this._model.floors,N=g.length;if(N<=5)return void g.forEach(G=>this._createFloorButton(G));const P=this._visibleFloorStart===0,F=this._visibleFloorStart>=N-3;if(P)this._createFloorButton(g[0]);else{const G=this._createButton("mapboxgl-ctrl-arrow-up",this._scrollUp);_("span","mapboxgl-ctrl-icon",G).setAttribute("aria-hidden","true"),this._container.appendChild(G)}let q=[];if(q=P?g.slice(1,4):F?g.slice(this._visibleFloorStart-1,this._visibleFloorStart+3-1):g.slice(this._visibleFloorStart,this._visibleFloorStart+3),q.forEach(G=>this._createFloorButton(G)),F)this._createFloorButton(g[N-1]);else{const G=this._createButton("mapboxgl-ctrl-arrow-down",this._scrollDown);_("span","mapboxgl-ctrl-icon",G).setAttribute("aria-hidden","true"),this._container.appendChild(G)}}_createFloorButton(M){const g=this._createButton("mapboxgl-ctrl-level-button",()=>{const q=M.id;this._model&&this._model.selectedFloorId===q&&this._model.activeFloorsVisible||this._map&&(this._model&&!this._model.activeFloorsVisible&&this._map.style&&this._map.style.indoorManager&&this._map.style.indoorManager.setActiveFloorsVisibility(!0),this._map._selectIndoorFloor(q))}),N=(M.name||"").trim(),P=M.zIndex.toString(),F=N?Array.from(N).slice(0,3).join(""):P;this._setButtonTitle(g,F),this._model&&this._model.activeFloorsVisible&&M.id===this._model.selectedFloorId&&g.classList.add("mapboxgl-ctrl-level-button-selected"),this._container&&this._container.appendChild(g)}_toggleIndoor(){this._map&&this._map.style&&this._map.style.indoorManager&&this._model&&this._model.activeFloorsVisible&&this._map.style.indoorManager.setActiveFloorsVisibility(!1)}_scrollUp(){if(this._visibleFloorStart>0){this._visibleFloorStart--,this._visibleFloorStart===1&&(this._visibleFloorStart=0);const M=this._model&&this._model.floors||[];if(M.length>3){const g=M.length-3;this._visibleFloorStart===g-1&&(this._visibleFloorStart=g-2)}this._render()}}_scrollDown(){if(this._model&&this._model.floors){const M=this._model.floors.length-3;this._visibleFloorStartM&&(this._visibleFloorStart=M),this._render())}}},Popup:class extends o.E{constructor(M){super(),this.options=Object.assign(Object.create(B4),M),this._altitude=this.options.altitude,o.aZ(["_update","_onClose","remove","_onMouseEvent"],this),this._classList=new Set(M&&M.className?M.className.trim().split(/\s+/):[])}addTo(M){return this._map&&this.remove(),this._map=M,this.options.closeOnClick&&M.on("preclick",this._onClose),this.options.closeOnMove&&M.on("move",this._onClose),M.on("remove",this.remove),this._update(),M._addPopup(this),this._focusFirstElement(),this._trackPointer?(M.on("mousemove",this._onMouseEvent),M.on("mouseup",this._onMouseEvent),M._canvasContainer.classList.add("mapboxgl-track-pointer")):M.on("move",this._update),this.fire(new o.C("open")),this}isOpen(){return!!this._map}remove(){this._content&&this._content.remove(),this._container&&(this._container.remove(),this._container=void 0);const M=this._map;return M&&(M.off("move",this._update),M.off("move",this._onClose),M.off("preclick",this._onClose),M.off("click",this._onClose),M.off("remove",this.remove),M.off("mousemove",this._onMouseEvent),M.off("mouseup",this._onMouseEvent),M.off("drag",this._onMouseEvent),M._canvasContainer&&M._canvasContainer.classList.remove("mapboxgl-track-pointer"),M._removePopup(this),this._map=void 0),this.fire(new o.C("close")),this}getLngLat(){return this._lngLat}setLngLat(M){this._lngLat=o.aU.convert(M),this._pos=null,this._trackPointer=!1,this._update();const g=this._map;return g&&(g.on("move",this._update),g.off("mousemove",this._onMouseEvent),g._canvasContainer.classList.remove("mapboxgl-track-pointer")),this}getAltitude(){return this._altitude}setAltitude(M){return this._altitude=M,this._update(),this}trackPointer(){this._trackPointer=!0,this._pos=null,this._update();const M=this._map;return M&&(M.off("move",this._update),M.on("mousemove",this._onMouseEvent),M.on("drag",this._onMouseEvent),M._canvasContainer.classList.add("mapboxgl-track-pointer")),this}getElement(){return this._container}setText(M){return this.setDOMContent(document.createTextNode(M))}setHTML(M){const g=document.createDocumentFragment(),N=document.createElement("body");let P;for(N.innerHTML=M;P=N.firstChild,P;)g.appendChild(P);return this.setDOMContent(g)}getMaxWidth(){return this._container&&this._container.style.maxWidth}setMaxWidth(M){return this.options.maxWidth=M,this._update(),this}setDOMContent(M){let g=this._content;if(g)for(;g.hasChildNodes();)g.firstChild&&g.removeChild(g.firstChild);else g=this._content=_("div","mapboxgl-popup-content",this._container||void 0);if(g.appendChild(M),this.options.closeButton){const N=this._closeButton=_("button","mapboxgl-popup-close-button",g);N.type="button",N.setAttribute("aria-label","Close popup"),N.innerHTML='',N.addEventListener("click",this._onClose)}return this._update(),this._focusFirstElement(),this}addClassName(M){return this._classList.add(M),this._updateClassList(),this}removeClassName(M){return this._classList.delete(M),this._updateClassList(),this}setOffset(M){return this.options.offset=M,this._update(),this}toggleClassName(M){let g;return this._classList.delete(M)?g=!1:(this._classList.add(M),g=!0),this._updateClassList(),g}_onMouseEvent(M){this._update(M.point)}_getAnchor(M){if(this.options.anchor)return this.options.anchor;const g=this._map,N=this._container,P=this._pos;if(!g||!N||!P)return"bottom";const F=N.offsetWidth,q=N.offsetHeight,G=P.xg.transform.width-F/2;if(P.y+Mg.transform.height-q){if(G)return"bottom-left";if(Q)return"bottom-right"}return G?"left":Q?"right":"bottom"}_updateClassList(){const M=this._container;if(!M)return;const g=[...this._classList];g.push("mapboxgl-popup"),this._anchor&&g.push(`mapboxgl-popup-anchor-${this._anchor}`),this._trackPointer&&g.push("mapboxgl-popup-track-pointer"),M.className=g.join(" ")}_update(M){const g=this._map,N=this._content;if(!g||!this._lngLat&&!this._trackPointer||!N)return;let P=this._container;if(P||(P=this._container=_("div","mapboxgl-popup",g.getContainer()),this._tip=_("div","mapboxgl-popup-tip",P),P.appendChild(N)),this.options.maxWidth&&P.style.maxWidth!==this.options.maxWidth&&(P.style.maxWidth=this.options.maxWidth),g.transform.renderWorldCopies&&!this._trackPointer&&(this._lngLat=jD(this._lngLat,this._pos,g.transform)),!this._trackPointer||M){const F=this._pos=this._trackPointer&&M instanceof o.P?M:g.project(this._lngLat,this._altitude),q=EM(this.options.offset),G=this._anchor=this._getAnchor(q.y),Q=EM(this.options.offset,G),ae=F.add(Q).round();g._requestDomTask(()=>{this._container&&G&&(this._container.style.transform=`${O4[G]} translate(${ae.x}px,${ae.y}px)`)})}if(!this._marker&&g._showingGlobe()){const F=o.e$(g.transform,this._lngLat)?0:1;this._setOpacity(F)}this._updateClassList()}_focusFirstElement(){if(!this.options.focusAfterOpen||!this._container)return;const M=this._container.querySelector(wye);M&&M.focus()}_onClose(){this.remove()}_setOpacity(M){this._container&&(this._container.style.opacity=`${M}`),this._content&&(this._content.style.pointerEvents=M?"auto":"none")}},Marker:zg,Style:Mc,LngLat:o.aU,LngLatBounds:o.aK,Point:o.P,MercatorCoordinate:o.ag,FreeCameraOptions:Y1,Evented:o.E,config:o.g,prewarm:function(){Et().acquire(st)},clearPrewarmedResources:function(){const M=at;M&&(M.isPreloaded()&&M.numActive()===1?(M.release(st),at=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()"))},get accessToken(){return o.g.ACCESS_TOKEN},set accessToken(M){o.g.ACCESS_TOKEN=M},get baseApiUrl(){return o.g.API_URL},set baseApiUrl(M){o.g.API_URL=M},get workerCount(){return mt.workerCount},set workerCount(M){mt.workerCount=M},get maxParallelImageRequests(){return o.g.MAX_PARALLEL_IMAGE_REQUESTS},set maxParallelImageRequests(M){o.g.MAX_PARALLEL_IMAGE_REQUESTS=M},clearStorage(M){o.f7(M)},get workerUrl(){return it.workerUrl},set workerUrl(M){it.workerUrl=M},get workerClass(){return it.workerClass},set workerClass(M){it.workerClass=M},get workerParams(){return it.workerParams},set workerParams(M){it.workerParams=M},get dracoUrl(){return o.f6()},set dracoUrl(M){o.g.DRACO_URL=o.o.resolveURL(M)},get meshoptUrl(){return o.f5()},set meshoptUrl(M){const g=o.o.resolveURL(M);o.g.MESHOPT_URL=g,o.g.MESHOPT_SIMD_URL=g},get buildingGenUrl(){return o.f4()},set buildingGenUrl(M){o.g.BUILDING_GEN_URL=o.o.resolveURL(M)},setNow:o.o.setNow,restoreNow:o.o.restoreNow}});var l=a;return l})})(nst);var cPt=nst.exports;const fc=ol(cPt);function Ks({className:s,...t}){return e.jsx("div",{className:Ft("animate-pulse rounded-md bg-muted",s),...t})}const BOe={coming_soon:"#3B82F6",office_exclusive:"#6366F1",pre_market:"#06B6D4",active:"#10B981",price_improvement:"#F97316",under_contract:"#8B5CF6",sold:"#6B7280"},zOe={coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",active:"Active",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"};function dPt(s){return s>=1e6?`$${(s/1e6).toFixed(1)}M`:`$${(s/1e3).toFixed(0)}K`}function uPt({listings:s,isLoading:t}){const r=Fr(),n=S.useRef(null),a=S.useRef(null),i=S.useRef([]),[l,o]=S.useState(""),[c,d]=S.useState(!0);return S.useEffect(()=>{(async()=>{d(!0);try{const{data:p}=await V.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();p!=null&&p.value&&o(p.value)}catch(p){console.error("Error fetching mapbox token:",p)}d(!1)})()},[]),S.useEffect(()=>{if(!n.current||!l||a.current)return;fc.accessToken=l;const m=s.filter(y=>y.latitude!=null&&y.longitude!=null);let p=[-98.5795,39.8283],x=4;if(m.length>0){const y=m.reduce((b,j)=>b+j.longitude,0)/m.length,_=m.reduce((b,j)=>b+j.latitude,0)/m.length;p=[y,_],x=m.length===1?12:10}return a.current=new fc.Map({container:n.current,style:"mapbox://styles/mapbox/light-v11",zoom:x,center:p}),a.current.addControl(new fc.NavigationControl,"top-right"),()=>{var y;(y=a.current)==null||y.remove(),a.current=null}},[l]),S.useEffect(()=>{if(!a.current||!l)return;i.current.forEach(p=>p.remove()),i.current=[];const m=s.filter(p=>p.latitude!=null&&p.longitude!=null);if(m.forEach(p=>{var E,A,D;const x=BOe[p.status]||"#10B981",y=((E=p.photos)==null?void 0:E.find(R=>R.is_primary))||((A=p.photos)==null?void 0:A[0]),b=window.location.hostname==="listings.relevelup.com"||window.location.hostname.startsWith("listings.")?`/${p.slug||p.id}`:`/public/listing/${p.slug||p.id}`,j=document.createElement("div");j.className="cursor-pointer",j.innerHTML=`
`;const k=new fc.Popup({offset:25,closeButton:!0,maxWidth:"280px"}).setHTML(`
${y!=null&&y.photo_url?``:""}
${dPt(p.price)}
${p.property_address||""}
${p.city}, ${p.state}
${zOe[p.status]||p.status} ${p.bedrooms?`${p.bedrooms} bed`:""} ${p.bathrooms?`${p.bathrooms} bath`:""}
${(D=p.agent)!=null&&D.name?`
Listed by ${p.agent.name}
`:""}
Click to view details →
`),T=new fc.Marker(j).setLngLat([p.longitude,p.latitude]).setPopup(k).addTo(a.current);i.current.push(T)}),m.length>1){const p=new fc.LngLatBounds;m.forEach(x=>p.extend([x.longitude,x.latitude])),a.current.fitBounds(p,{padding:60,maxZoom:13})}else m.length===1&&a.current.flyTo({center:[m[0].longitude,m[0].latitude],zoom:12})},[s,l]),S.useEffect(()=>(window.__navigateToPublicListing__=m=>{r(m)},()=>{delete window.__navigateToPublicListing__}),[r]),c||t?e.jsx(Ks,{className:"w-full h-[500px] rounded-lg"}):!l||s.filter(m=>m.latitude!=null&&m.longitude!=null).length===0?null:e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"flex flex-wrap items-center gap-3 text-sm",children:Object.entries(BOe).map(([m,p])=>e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:"w-3 h-3 rounded-full border-2 border-white shadow",style:{background:p}}),e.jsx("span",{className:"text-xs text-gray-600",children:zOe[m]})]},m))}),e.jsx("div",{ref:n,className:"w-full h-[500px] rounded-lg shadow-lg border border-gray-200"})]})}function c9(s,[t,r]){return Math.min(r,Math.max(t,s))}function QB(s){const t=S.useRef({value:s,previous:s});return S.useMemo(()=>(t.current.value!==s&&(t.current.previous=t.current.value,t.current.value=s),t.current.previous),[s])}var hPt=[" ","Enter","ArrowUp","ArrowDown"],mPt=[" ","Enter"],uA="Select",[xge,yge,fPt]=DB(uA),[f8,TZs]=_u(uA,[fPt,q_]),vge=q_(),[pPt,FS]=f8(uA),[gPt,xPt]=f8(uA),ist=s=>{const{__scopeSelect:t,children:r,open:n,defaultOpen:a,onOpenChange:i,value:l,defaultValue:o,onValueChange:c,dir:d,name:h,autoComplete:m,disabled:p,required:x,form:y}=s,_=vge(t),[b,j]=S.useState(null),[k,T]=S.useState(null),[E,A]=S.useState(!1),D=RS(d),[R,z]=af({prop:n,defaultProp:a??!1,onChange:i,caller:uA}),[O,$]=af({prop:l,defaultProp:o,onChange:c,caller:uA}),ee=S.useRef(null),Z=b?y||!!b.closest("form"):!0,[J,K]=S.useState(new Set),re=Array.from(J).map(ie=>ie.props.value).join(";");return e.jsx(BB,{..._,children:e.jsxs(pPt,{required:x,scope:t,trigger:b,onTriggerChange:j,valueNode:k,onValueNodeChange:T,valueNodeHasChildren:E,onValueNodeHasChildrenChange:A,contentId:vm(),value:O,onValueChange:$,open:R,onOpenChange:z,dir:D,triggerPointerDownPosRef:ee,disabled:p,children:[e.jsx(xge.Provider,{scope:t,children:e.jsx(gPt,{scope:s.__scopeSelect,onNativeOptionAdd:S.useCallback(ie=>{K(ce=>new Set(ce).add(ie))},[]),onNativeOptionRemove:S.useCallback(ie=>{K(ce=>{const ne=new Set(ce);return ne.delete(ie),ne})},[]),children:r})}),Z?e.jsxs(Ast,{"aria-hidden":!0,required:x,tabIndex:-1,name:h,autoComplete:m,value:O,onChange:ie=>$(ie.target.value),disabled:p,form:y,children:[O===void 0?e.jsx("option",{value:""}):null,Array.from(J)]},re):null]})})};ist.displayName=uA;var ost="SelectTrigger",lst=S.forwardRef((s,t)=>{const{__scopeSelect:r,disabled:n=!1,...a}=s,i=vge(r),l=FS(ost,r),o=l.disabled||n,c=_i(t,l.onTriggerChange),d=yge(r),h=S.useRef("touch"),[m,p,x]=Ist(_=>{const b=d().filter(T=>!T.disabled),j=b.find(T=>T.value===l.value),k=Pst(b,_,j);k!==void 0&&l.onValueChange(k.value)}),y=_=>{o||(l.onOpenChange(!0),x()),_&&(l.triggerPointerDownPosRef.current={x:Math.round(_.pageX),y:Math.round(_.pageY)})};return e.jsx(i8,{asChild:!0,...i,children:e.jsx(Vn.button,{type:"button",role:"combobox","aria-controls":l.contentId,"aria-expanded":l.open,"aria-required":l.required,"aria-autocomplete":"none",dir:l.dir,"data-state":l.open?"open":"closed",disabled:o,"data-disabled":o?"":void 0,"data-placeholder":Mst(l.value)?"":void 0,...a,ref:c,onClick:an(a.onClick,_=>{_.currentTarget.focus(),h.current!=="mouse"&&y(_)}),onPointerDown:an(a.onPointerDown,_=>{h.current=_.pointerType;const b=_.target;b.hasPointerCapture(_.pointerId)&&b.releasePointerCapture(_.pointerId),_.button===0&&_.ctrlKey===!1&&_.pointerType==="mouse"&&(y(_),_.preventDefault())}),onKeyDown:an(a.onKeyDown,_=>{const b=m.current!=="";!(_.ctrlKey||_.altKey||_.metaKey)&&_.key.length===1&&p(_.key),!(b&&_.key===" ")&&hPt.includes(_.key)&&(y(),_.preventDefault())})})})});lst.displayName=ost;var cst="SelectValue",dst=S.forwardRef((s,t)=>{const{__scopeSelect:r,className:n,style:a,children:i,placeholder:l="",...o}=s,c=FS(cst,r),{onValueNodeHasChildrenChange:d}=c,h=i!==void 0,m=_i(t,c.onValueNodeChange);return Ku(()=>{d(h)},[d,h]),e.jsx(Vn.span,{...o,ref:m,style:{pointerEvents:"none"},children:Mst(c.value)?e.jsx(e.Fragment,{children:l}):i})});dst.displayName=cst;var yPt="SelectIcon",ust=S.forwardRef((s,t)=>{const{__scopeSelect:r,children:n,...a}=s;return e.jsx(Vn.span,{"aria-hidden":!0,...a,ref:t,children:n||"▼"})});ust.displayName=yPt;var vPt="SelectPortal",hst=s=>e.jsx(s8,{asChild:!0,...s});hst.displayName=vPt;var hA="SelectContent",mst=S.forwardRef((s,t)=>{const r=FS(hA,s.__scopeSelect),[n,a]=S.useState();if(Ku(()=>{a(new DocumentFragment)},[]),!r.open){const i=n;return i?tx.createPortal(e.jsx(fst,{scope:s.__scopeSelect,children:e.jsx(xge.Slot,{scope:s.__scopeSelect,children:e.jsx("div",{children:s.children})})}),i):null}return e.jsx(pst,{...s,ref:t})});mst.displayName=hA;var Kv=10,[fst,BS]=f8(hA),bPt="SelectContentImpl",_Pt=mS("SelectContent.RemoveScroll"),pst=S.forwardRef((s,t)=>{const{__scopeSelect:r,position:n="item-aligned",onCloseAutoFocus:a,onEscapeKeyDown:i,onPointerDownOutside:l,side:o,sideOffset:c,align:d,alignOffset:h,arrowPadding:m,collisionBoundary:p,collisionPadding:x,sticky:y,hideWhenDetached:_,avoidCollisions:b,...j}=s,k=FS(hA,r),[T,E]=S.useState(null),[A,D]=S.useState(null),R=_i(t,Me=>E(Me)),[z,O]=S.useState(null),[$,ee]=S.useState(null),Z=yge(r),[J,K]=S.useState(!1),re=S.useRef(!1);S.useEffect(()=>{if(T)return cge(T)},[T]),ige();const ie=S.useCallback(Me=>{const[ze,...Pe]=Z().map(pe=>pe.ref.current),[Ie]=Pe.slice(-1),De=document.activeElement;for(const pe of Me)if(pe===De||(pe==null||pe.scrollIntoView({block:"nearest"}),pe===ze&&A&&(A.scrollTop=0),pe===Ie&&A&&(A.scrollTop=A.scrollHeight),pe==null||pe.focus(),document.activeElement!==De))return},[Z,A]),ce=S.useCallback(()=>ie([z,T]),[ie,z,T]);S.useEffect(()=>{J&&ce()},[J,ce]);const{onOpenChange:ne,triggerPointerDownPosRef:le}=k;S.useEffect(()=>{if(T){let Me={x:0,y:0};const ze=Ie=>{var De,pe;Me={x:Math.abs(Math.round(Ie.pageX)-(((De=le.current)==null?void 0:De.x)??0)),y:Math.abs(Math.round(Ie.pageY)-(((pe=le.current)==null?void 0:pe.y)??0))}},Pe=Ie=>{Me.x<=10&&Me.y<=10?Ie.preventDefault():T.contains(Ie.target)||ne(!1),document.removeEventListener("pointermove",ze),le.current=null};return le.current!==null&&(document.addEventListener("pointermove",ze),document.addEventListener("pointerup",Pe,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",ze),document.removeEventListener("pointerup",Pe,{capture:!0})}}},[T,ne,le]),S.useEffect(()=>{const Me=()=>ne(!1);return window.addEventListener("blur",Me),window.addEventListener("resize",Me),()=>{window.removeEventListener("blur",Me),window.removeEventListener("resize",Me)}},[ne]);const[be,fe]=Ist(Me=>{const ze=Z().filter(De=>!De.disabled),Pe=ze.find(De=>De.ref.current===document.activeElement),Ie=Pst(ze,Me,Pe);Ie&&setTimeout(()=>Ie.ref.current.focus())}),je=S.useCallback((Me,ze,Pe)=>{const Ie=!re.current&&!Pe;(k.value!==void 0&&k.value===ze||Ie)&&(O(Me),Ie&&(re.current=!0))},[k.value]),ve=S.useCallback(()=>T==null?void 0:T.focus(),[T]),We=S.useCallback((Me,ze,Pe)=>{const Ie=!re.current&&!Pe;(k.value!==void 0&&k.value===ze||Ie)&&ee(Me)},[k.value]),Ve=n==="popper"?Kje:gst,Le=Ve===Kje?{side:o,sideOffset:c,align:d,alignOffset:h,arrowPadding:m,collisionBoundary:p,collisionPadding:x,sticky:y,hideWhenDetached:_,avoidCollisions:b}:{};return e.jsx(fst,{scope:r,content:T,viewport:A,onViewportChange:D,itemRefCallback:je,selectedItem:z,onItemLeave:ve,itemTextRefCallback:We,focusSelectedItem:ce,selectedItemText:$,position:n,isPositioned:J,searchRef:be,children:e.jsx(GB,{as:_Pt,allowPinchZoom:!0,children:e.jsx(VB,{asChild:!0,trapped:k.open,onMountAutoFocus:Me=>{Me.preventDefault()},onUnmountAutoFocus:an(a,Me=>{var ze;(ze=k.trigger)==null||ze.focus({preventScroll:!0}),Me.preventDefault()}),children:e.jsx(PS,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:i,onPointerDownOutside:l,onFocusOutside:Me=>Me.preventDefault(),onDismiss:()=>k.onOpenChange(!1),children:e.jsx(Ve,{role:"listbox",id:k.contentId,"data-state":k.open?"open":"closed",dir:k.dir,onContextMenu:Me=>Me.preventDefault(),...j,...Le,onPlaced:()=>K(!0),ref:R,style:{display:"flex",flexDirection:"column",outline:"none",...j.style},onKeyDown:an(j.onKeyDown,Me=>{const ze=Me.ctrlKey||Me.altKey||Me.metaKey;if(Me.key==="Tab"&&Me.preventDefault(),!ze&&Me.key.length===1&&fe(Me.key),["ArrowUp","ArrowDown","Home","End"].includes(Me.key)){let Ie=Z().filter(De=>!De.disabled).map(De=>De.ref.current);if(["ArrowUp","End"].includes(Me.key)&&(Ie=Ie.slice().reverse()),["ArrowUp","ArrowDown"].includes(Me.key)){const De=Me.target,pe=Ie.indexOf(De);Ie=Ie.slice(pe+1)}setTimeout(()=>ie(Ie)),Me.preventDefault()}})})})})})})});pst.displayName=bPt;var wPt="SelectItemAlignedPosition",gst=S.forwardRef((s,t)=>{const{__scopeSelect:r,onPlaced:n,...a}=s,i=FS(hA,r),l=BS(hA,r),[o,c]=S.useState(null),[d,h]=S.useState(null),m=_i(t,R=>h(R)),p=yge(r),x=S.useRef(!1),y=S.useRef(!0),{viewport:_,selectedItem:b,selectedItemText:j,focusSelectedItem:k}=l,T=S.useCallback(()=>{if(i.trigger&&i.valueNode&&o&&d&&_&&b&&j){const R=i.trigger.getBoundingClientRect(),z=d.getBoundingClientRect(),O=i.valueNode.getBoundingClientRect(),$=j.getBoundingClientRect();if(i.dir!=="rtl"){const De=$.left-z.left,pe=O.left-De,tt=R.left-pe,ge=R.width+tt,ct=Math.max(ge,z.width),Ue=window.innerWidth-Kv,et=c9(pe,[Kv,Math.max(Kv,Ue-ct)]);o.style.minWidth=ge+"px",o.style.left=et+"px"}else{const De=z.right-$.right,pe=window.innerWidth-O.right-De,tt=window.innerWidth-R.right-pe,ge=R.width+tt,ct=Math.max(ge,z.width),Ue=window.innerWidth-Kv,et=c9(pe,[Kv,Math.max(Kv,Ue-ct)]);o.style.minWidth=ge+"px",o.style.right=et+"px"}const ee=p(),Z=window.innerHeight-Kv*2,J=_.scrollHeight,K=window.getComputedStyle(d),re=parseInt(K.borderTopWidth,10),ie=parseInt(K.paddingTop,10),ce=parseInt(K.borderBottomWidth,10),ne=parseInt(K.paddingBottom,10),le=re+ie+J+ne+ce,be=Math.min(b.offsetHeight*5,le),fe=window.getComputedStyle(_),je=parseInt(fe.paddingTop,10),ve=parseInt(fe.paddingBottom,10),We=R.top+R.height/2-Kv,Ve=Z-We,Le=b.offsetHeight/2,Me=b.offsetTop+Le,ze=re+ie+Me,Pe=le-ze;if(ze<=We){const De=ee.length>0&&b===ee[ee.length-1].ref.current;o.style.bottom="0px";const pe=d.clientHeight-_.offsetTop-_.offsetHeight,tt=Math.max(Ve,Le+(De?ve:0)+pe+ce),ge=ze+tt;o.style.height=ge+"px"}else{const De=ee.length>0&&b===ee[0].ref.current;o.style.top="0px";const tt=Math.max(We,re+_.offsetTop+(De?je:0)+Le)+Pe;o.style.height=tt+"px",_.scrollTop=ze-We+_.offsetTop}o.style.margin=`${Kv}px 0`,o.style.minHeight=be+"px",o.style.maxHeight=Z+"px",n==null||n(),requestAnimationFrame(()=>x.current=!0)}},[p,i.trigger,i.valueNode,o,d,_,b,j,i.dir,n]);Ku(()=>T(),[T]);const[E,A]=S.useState();Ku(()=>{d&&A(window.getComputedStyle(d).zIndex)},[d]);const D=S.useCallback(R=>{R&&y.current===!0&&(T(),k==null||k(),y.current=!1)},[T,k]);return e.jsx(NPt,{scope:r,contentWrapper:o,shouldExpandOnScrollRef:x,onScrollButtonChange:D,children:e.jsx("div",{ref:c,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:E},children:e.jsx(Vn.div,{...a,ref:m,style:{boxSizing:"border-box",maxHeight:"100%",...a.style}})})})});gst.displayName=wPt;var jPt="SelectPopperPosition",Kje=S.forwardRef((s,t)=>{const{__scopeSelect:r,align:n="start",collisionPadding:a=Kv,...i}=s,l=vge(r);return e.jsx(zB,{...l,...i,ref:t,align:n,collisionPadding:a,style:{boxSizing:"border-box",...i.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)"}})});Kje.displayName=jPt;var[NPt,i5e]=f8(hA,{}),Yje="SelectViewport",xst=S.forwardRef((s,t)=>{const{__scopeSelect:r,nonce:n,...a}=s,i=BS(Yje,r),l=i5e(Yje,r),o=_i(t,i.onViewportChange),c=S.useRef(0);return e.jsxs(e.Fragment,{children:[e.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}),e.jsx(xge.Slot,{scope:r,children:e.jsx(Vn.div,{"data-radix-select-viewport":"",role:"presentation",...a,ref:o,style:{position:"relative",flex:1,overflow:"hidden auto",...a.style},onScroll:an(a.onScroll,d=>{const h=d.currentTarget,{contentWrapper:m,shouldExpandOnScrollRef:p}=l;if(p!=null&&p.current&&m){const x=Math.abs(c.current-h.scrollTop);if(x>0){const y=window.innerHeight-Kv*2,_=parseFloat(m.style.minHeight),b=parseFloat(m.style.height),j=Math.max(_,b);if(j0?E:0,m.style.justifyContent="flex-end")}}}c.current=h.scrollTop})})})]})});xst.displayName=Yje;var yst="SelectGroup",[kPt,SPt]=f8(yst),CPt=S.forwardRef((s,t)=>{const{__scopeSelect:r,...n}=s,a=vm();return e.jsx(kPt,{scope:r,id:a,children:e.jsx(Vn.div,{role:"group","aria-labelledby":a,...n,ref:t})})});CPt.displayName=yst;var vst="SelectLabel",bst=S.forwardRef((s,t)=>{const{__scopeSelect:r,...n}=s,a=SPt(vst,r);return e.jsx(Vn.div,{id:a.id,...n,ref:t})});bst.displayName=vst;var Mhe="SelectItem",[TPt,_st]=f8(Mhe),wst=S.forwardRef((s,t)=>{const{__scopeSelect:r,value:n,disabled:a=!1,textValue:i,...l}=s,o=FS(Mhe,r),c=BS(Mhe,r),d=o.value===n,[h,m]=S.useState(i??""),[p,x]=S.useState(!1),y=_i(t,k=>{var T;return(T=c.itemRefCallback)==null?void 0:T.call(c,k,n,a)}),_=vm(),b=S.useRef("touch"),j=()=>{a||(o.onValueChange(n),o.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 e.jsx(TPt,{scope:r,value:n,disabled:a,textId:_,isSelected:d,onItemTextChange:S.useCallback(k=>{m(T=>T||((k==null?void 0:k.textContent)??"").trim())},[]),children:e.jsx(xge.ItemSlot,{scope:r,value:n,disabled:a,textValue:h,children:e.jsx(Vn.div,{role:"option","aria-labelledby":_,"data-highlighted":p?"":void 0,"aria-selected":d&&p,"data-state":d?"checked":"unchecked","aria-disabled":a||void 0,"data-disabled":a?"":void 0,tabIndex:a?void 0:-1,...l,ref:y,onFocus:an(l.onFocus,()=>x(!0)),onBlur:an(l.onBlur,()=>x(!1)),onClick:an(l.onClick,()=>{b.current!=="mouse"&&j()}),onPointerUp:an(l.onPointerUp,()=>{b.current==="mouse"&&j()}),onPointerDown:an(l.onPointerDown,k=>{b.current=k.pointerType}),onPointerMove:an(l.onPointerMove,k=>{var T;b.current=k.pointerType,a?(T=c.onItemLeave)==null||T.call(c):b.current==="mouse"&&k.currentTarget.focus({preventScroll:!0})}),onPointerLeave:an(l.onPointerLeave,k=>{var T;k.currentTarget===document.activeElement&&((T=c.onItemLeave)==null||T.call(c))}),onKeyDown:an(l.onKeyDown,k=>{var E;((E=c.searchRef)==null?void 0:E.current)!==""&&k.key===" "||(mPt.includes(k.key)&&j(),k.key===" "&&k.preventDefault())})})})})});wst.displayName=Mhe;var pO="SelectItemText",jst=S.forwardRef((s,t)=>{const{__scopeSelect:r,className:n,style:a,...i}=s,l=FS(pO,r),o=BS(pO,r),c=_st(pO,r),d=xPt(pO,r),[h,m]=S.useState(null),p=_i(t,j=>m(j),c.onItemTextChange,j=>{var k;return(k=o.itemTextRefCallback)==null?void 0:k.call(o,j,c.value,c.disabled)}),x=h==null?void 0:h.textContent,y=S.useMemo(()=>e.jsx("option",{value:c.value,disabled:c.disabled,children:x},c.value),[c.disabled,c.value,x]),{onNativeOptionAdd:_,onNativeOptionRemove:b}=d;return Ku(()=>(_(y),()=>b(y)),[_,b,y]),e.jsxs(e.Fragment,{children:[e.jsx(Vn.span,{id:c.textId,...i,ref:p}),c.isSelected&&l.valueNode&&!l.valueNodeHasChildren?tx.createPortal(i.children,l.valueNode):null]})});jst.displayName=pO;var Nst="SelectItemIndicator",kst=S.forwardRef((s,t)=>{const{__scopeSelect:r,...n}=s;return _st(Nst,r).isSelected?e.jsx(Vn.span,{"aria-hidden":!0,...n,ref:t}):null});kst.displayName=Nst;var Zje="SelectScrollUpButton",Sst=S.forwardRef((s,t)=>{const r=BS(Zje,s.__scopeSelect),n=i5e(Zje,s.__scopeSelect),[a,i]=S.useState(!1),l=_i(t,n.onScrollButtonChange);return Ku(()=>{if(r.viewport&&r.isPositioned){let o=function(){const d=c.scrollTop>0;i(d)};const c=r.viewport;return o(),c.addEventListener("scroll",o),()=>c.removeEventListener("scroll",o)}},[r.viewport,r.isPositioned]),a?e.jsx(Tst,{...s,ref:l,onAutoScroll:()=>{const{viewport:o,selectedItem:c}=r;o&&c&&(o.scrollTop=o.scrollTop-c.offsetHeight)}}):null});Sst.displayName=Zje;var Xje="SelectScrollDownButton",Cst=S.forwardRef((s,t)=>{const r=BS(Xje,s.__scopeSelect),n=i5e(Xje,s.__scopeSelect),[a,i]=S.useState(!1),l=_i(t,n.onScrollButtonChange);return Ku(()=>{if(r.viewport&&r.isPositioned){let o=function(){const d=c.scrollHeight-c.clientHeight,h=Math.ceil(c.scrollTop)c.removeEventListener("scroll",o)}},[r.viewport,r.isPositioned]),a?e.jsx(Tst,{...s,ref:l,onAutoScroll:()=>{const{viewport:o,selectedItem:c}=r;o&&c&&(o.scrollTop=o.scrollTop+c.offsetHeight)}}):null});Cst.displayName=Xje;var Tst=S.forwardRef((s,t)=>{const{__scopeSelect:r,onAutoScroll:n,...a}=s,i=BS("SelectScrollButton",r),l=S.useRef(null),o=yge(r),c=S.useCallback(()=>{l.current!==null&&(window.clearInterval(l.current),l.current=null)},[]);return S.useEffect(()=>()=>c(),[c]),Ku(()=>{var h;const d=o().find(m=>m.ref.current===document.activeElement);(h=d==null?void 0:d.ref.current)==null||h.scrollIntoView({block:"nearest"})},[o]),e.jsx(Vn.div,{"aria-hidden":!0,...a,ref:t,style:{flexShrink:0,...a.style},onPointerDown:an(a.onPointerDown,()=>{l.current===null&&(l.current=window.setInterval(n,50))}),onPointerMove:an(a.onPointerMove,()=>{var d;(d=i.onItemLeave)==null||d.call(i),l.current===null&&(l.current=window.setInterval(n,50))}),onPointerLeave:an(a.onPointerLeave,()=>{c()})})}),EPt="SelectSeparator",Est=S.forwardRef((s,t)=>{const{__scopeSelect:r,...n}=s;return e.jsx(Vn.div,{"aria-hidden":!0,...n,ref:t})});Est.displayName=EPt;var Qje="SelectArrow",APt=S.forwardRef((s,t)=>{const{__scopeSelect:r,...n}=s,a=vge(r),i=FS(Qje,r),l=BS(Qje,r);return i.open&&l.position==="popper"?e.jsx($B,{...a,...n,ref:t}):null});APt.displayName=Qje;var MPt="SelectBubbleInput",Ast=S.forwardRef(({__scopeSelect:s,value:t,...r},n)=>{const a=S.useRef(null),i=_i(n,a),l=QB(t);return S.useEffect(()=>{const o=a.current;if(!o)return;const c=window.HTMLSelectElement.prototype,h=Object.getOwnPropertyDescriptor(c,"value").set;if(l!==t&&h){const m=new Event("change",{bubbles:!0});h.call(o,t),o.dispatchEvent(m)}},[l,t]),e.jsx(Vn.select,{...r,style:{...lQe,...r.style},ref:i,defaultValue:t})});Ast.displayName=MPt;function Mst(s){return s===""||s===void 0}function Ist(s){const t=Uu(s),r=S.useRef(""),n=S.useRef(0),a=S.useCallback(l=>{const o=r.current+l;t(o),function c(d){r.current=d,window.clearTimeout(n.current),d!==""&&(n.current=window.setTimeout(()=>c(""),1e3))}(o)},[t]),i=S.useCallback(()=>{r.current="",window.clearTimeout(n.current)},[]);return S.useEffect(()=>()=>window.clearTimeout(n.current),[]),[r,a,i]}function Pst(s,t,r){const a=t.length>1&&Array.from(t).every(d=>d===t[0])?t[0]:t,i=r?s.indexOf(r):-1;let l=IPt(s,Math.max(i,0));a.length===1&&(l=l.filter(d=>d!==r));const c=l.find(d=>d.textValue.toLowerCase().startsWith(a.toLowerCase()));return c!==r?c:void 0}function IPt(s,t){return s.map((r,n)=>s[(t+n)%s.length])}var PPt=ist,Lst=lst,LPt=dst,DPt=ust,RPt=hst,Dst=mst,OPt=xst,Rst=bst,Ost=wst,FPt=jst,BPt=kst,Fst=Sst,Bst=Cst,zst=Est;const Bs=PPt,Us=LPt,Os=S.forwardRef(({className:s,children:t,...r},n)=>e.jsxs(Lst,{ref:n,className:Ft("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",s),...r,children:[t,e.jsx(DPt,{asChild:!0,children:e.jsx(Io,{className:"h-4 w-4 opacity-50"})})]}));Os.displayName=Lst.displayName;const $st=S.forwardRef(({className:s,...t},r)=>e.jsx(Fst,{ref:r,className:Ft("flex cursor-default items-center justify-center py-1",s),...t,children:e.jsx(cx,{className:"h-4 w-4"})}));$st.displayName=Fst.displayName;const Ust=S.forwardRef(({className:s,...t},r)=>e.jsx(Bst,{ref:r,className:Ft("flex cursor-default items-center justify-center py-1",s),...t,children:e.jsx(Io,{className:"h-4 w-4"})}));Ust.displayName=Bst.displayName;const Fs=S.forwardRef(({className:s,children:t,position:r="popper",...n},a)=>e.jsx(RPt,{children:e.jsxs(Dst,{ref:a,className:Ft("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",s),position:r,...n,children:[e.jsx($st,{}),e.jsx(OPt,{className:Ft("p-1",r==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),e.jsx(Ust,{})]})}));Fs.displayName=Dst.displayName;const zPt=S.forwardRef(({className:s,...t},r)=>e.jsx(Rst,{ref:r,className:Ft("py-1.5 pl-8 pr-2 text-sm font-semibold",s),...t}));zPt.displayName=Rst.displayName;const pt=S.forwardRef(({className:s,children:t,...r},n)=>e.jsxs(Ost,{ref:n,className:Ft("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",s),...r,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(BPt,{children:e.jsx(va,{className:"h-4 w-4"})})}),e.jsx(FPt,{children:t})]}));pt.displayName=Ost.displayName;const $Pt=S.forwardRef(({className:s,...t},r)=>e.jsx(zst,{ref:r,className:Ft("-mx-1 my-1 h-px bg-muted",s),...t}));$Pt.displayName=zst.displayName;const UPt=s=>yt({queryKey:["public-listings",s],queryFn:async()=>{let t=V.from("listings").select(` id, slug, agent_id, property_address, city, state, neighborhood, price, property_type, status, bedrooms, bathrooms, square_footage, lot_size, year_built, has_hoa, description, latitude, longitude, created_at, updated_at, photos:listing_photos(id, photo_url, is_primary), agent:profiles!listings_agent_id_fkey(id, name, email, brokerage:brokerages(name)) `).eq("is_approved",!0).eq("is_public",!0).order("created_at",{ascending:!1});s!=null&&s.status&&(t=t.eq("status",s.status)),s!=null&&s.propertyType&&(t=t.eq("property_type",s.propertyType)),s!=null&&s.city&&(t=t.ilike("city",`%${s.city}%`)),s!=null&&s.minPrice&&(t=t.gte("price",s.minPrice)),s!=null&&s.maxPrice&&(t=t.lte("price",s.maxPrice));const{data:r,error:n}=await t;if(n)throw n;return r}}),qst=s=>yt({queryKey:["public-listing",s],queryFn:async()=>{const t=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(s);let r=V.from("listings").select(` id, slug, agent_id, property_address, city, state, neighborhood, price, property_type, status, bedrooms, bathrooms, square_footage, lot_size, year_built, has_hoa, description, agent_notes, agent_notes_public, mls_link, video_link, video_id, latitude, longitude, created_at, updated_at, photos:listing_photos(id, photo_url, is_primary, sort_order), agent:profiles!listings_agent_id_fkey(id, name, email, brokerage:brokerages(name)), video:agent_videos!listings_video_id_fkey(id, playback_url, thumbnail_url, title, duration_seconds, bunny_video_id) `).eq("is_approved",!0).eq("is_public",!0);t?r=r.eq("id",s):r=r.eq("slug",s);const{data:n,error:a}=await r.single();if(a)throw a;return n},enabled:!!s}),Vst=()=>Pt({mutationFn:async({listingId:s,agentId:t,firstName:r,lastName:n,email:a,phone:i,shareToken:l,leadType:o="info_request",preferredDate:c,preferredTime:d,showingMode:h,message:m})=>{let p=null,x=null;if(l){const{data:j}=await V.from("listing_shares").select("id, sharing_agent_id").eq("share_token",l).eq("listing_id",s).maybeSingle();j&&(p=j.id,x=j.sharing_agent_id)}const{data:y,error:_}=await V.from("listing_leads").insert({listing_id:s,agent_id:x||t,first_name:r,last_name:n,email:a,phone:i,share_id:p,referred_by_agent_id:x,lead_type:o,preferred_date:c||null,preferred_time:d||null,showing_mode:h||null,message:m||null}).select().single();if(_)throw _;const{error:b}=await V.functions.invoke("process-listing-lead",{body:{leadId:y.id}});return b&&console.error("Error processing lead:",b),y}}),qPt=()=>Pt({mutationFn:async s=>{const{error:t}=await V.rpc("increment_listing_share_click",{p_share_token:s});if(t)throw t}}),VPt={active:"bg-emerald-500",coming_soon:"bg-blue-600",office_exclusive:"bg-indigo-500",pre_market:"bg-cyan-500",price_improvement:"bg-orange-500",under_contract:"bg-purple-500",sold:"bg-gray-500"},$Oe={active:"Active",coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"},HPt={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"};function Hst(){const[s,t]=S.useState(""),[r,n]=S.useState(!1),[a,i]=S.useState({status:"",propertyType:"",minPrice:"",maxPrice:""}),{data:l,isLoading:o}=UPt({city:s||void 0,status:a.status||void 0,propertyType:a.propertyType||void 0,minPrice:a.minPrice?Number(a.minPrice):void 0,maxPrice:a.maxPrice?Number(a.maxPrice):void 0}),c=m=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(m),d=()=>{i({status:"",propertyType:"",minPrice:"",maxPrice:""}),t("")},h=s||a.status||a.propertyType||a.minPrice||a.maxPrice;return e.jsxs(e.Fragment,{children:[e.jsxs(el,{children:[e.jsx("title",{children:"LevelUp Listings - Find Your Dream Home | Real Estate for Sale"}),e.jsx("meta",{name:"description",content:"Browse exclusive property listings from LevelUp real estate agents. Find homes for sale, condos, townhouses, and luxury properties. View photos, prices, and connect with agents."}),e.jsx("link",{rel:"canonical",href:"https://listings.relevelup.com"}),e.jsx("meta",{property:"og:title",content:"LevelUp Listings - Find Your Dream Home"}),e.jsx("meta",{property:"og:description",content:"Browse exclusive property listings from LevelUp real estate agents. Find homes for sale, view photos, and connect with agents."}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("meta",{property:"og:url",content:"https://listings.relevelup.com"}),e.jsx("meta",{property:"og:site_name",content:"LevelUp Listings"}),e.jsx("meta",{property:"og:locale",content:"en_US"}),e.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),e.jsx("meta",{name:"twitter:title",content:"LevelUp Listings - Find Your Dream Home"}),e.jsx("meta",{name:"twitter:description",content:"Browse exclusive property listings from LevelUp real estate agents."}),e.jsx("meta",{name:"robots",content:"index, follow"}),e.jsx("meta",{name:"keywords",content:"homes for sale, real estate, property listings, houses, condos, townhouses, luxury homes, LevelUp"}),e.jsx("script",{type:"application/ld+json",children:JSON.stringify({"@context":"https://schema.org","@type":"WebSite",name:"LevelUp Listings",url:"https://listings.relevelup.com",description:"Browse exclusive property listings from LevelUp real estate agents",potentialAction:{"@type":"SearchAction",target:{"@type":"EntryPoint",urlTemplate:"https://listings.relevelup.com?q={search_term_string}"},"query-input":"required name=search_term_string"}})}),e.jsx("script",{type:"application/ld+json",children:JSON.stringify({"@context":"https://schema.org","@type":"RealEstateAgent",name:"LevelUp",url:"https://relevelup.com",logo:"https://listings.relevelup.com/assets/levelup-logo-color.png"})})]}),e.jsxs("div",{className:"min-h-screen bg-gray-50",children:[e.jsx("header",{className:"bg-white border-b border-gray-200 sticky top-0 z-50",children:e.jsx("div",{className:"max-w-7xl mx-auto px-4 py-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Xn,{to:"/public/listings",className:"flex items-center",children:e.jsx("img",{src:n5e,alt:"LevelUp",className:"h-8"})}),e.jsx("nav",{className:"hidden md:flex items-center gap-6",children:e.jsx("a",{href:"https://relevelup.com",target:"_blank",rel:"noopener noreferrer",className:"text-sm font-medium text-gray-600 hover:text-gray-900 transition-colors",children:"About LevelUp"})})]})})}),e.jsxs("section",{className:"relative bg-cover bg-center py-20 md:py-32",style:{backgroundImage:`url(${lPt})`},children:[e.jsx("div",{className:"absolute inset-0 bg-black/40"}),e.jsxs("div",{className:"relative max-w-7xl mx-auto px-4",children:[e.jsx("h1",{className:"text-4xl md:text-5xl lg:text-6xl font-bold text-white mb-3 text-center drop-shadow-lg",children:"Find Your Perfect Home"}),e.jsx("p",{className:"text-white/90 text-center mb-10 text-lg md:text-xl drop-shadow",children:"Exclusive listings from LevelUp agents"}),e.jsxs("div",{className:"max-w-3xl mx-auto",children:[e.jsxs("div",{className:"flex gap-0 shadow-2xl rounded-lg overflow-hidden",children:[e.jsxs("div",{className:"relative flex-1 bg-white",children:[e.jsx(Mn,{className:"absolute left-4 top-1/2 -translate-y-1/2 h-5 w-5 text-gray-400"}),e.jsx(Se,{placeholder:"Enter an address, neighborhood, city, or ZIP code",value:s,onChange:m=>t(m.target.value),className:"pl-12 h-14 md:h-16 text-base md:text-lg border-0 focus-visible:ring-0 rounded-none bg-white"})]}),e.jsx(H,{className:"h-14 md:h-16 px-6 md:px-8 rounded-none bg-blue-600 hover:bg-blue-700",children:e.jsx(Mn,{className:"h-5 w-5 md:h-6 md:w-6"})})]}),e.jsx("div",{className:"flex justify-center mt-6",children:e.jsxs(H,{variant:"secondary",size:"sm",onClick:()=>n(!r),className:"gap-2 bg-white/90 hover:bg-white text-gray-700 shadow-lg",children:[e.jsx(OE,{className:"h-4 w-4"}),r?"Hide Filters":"More Filters"]})}),r&&e.jsxs("div",{className:"mt-4 p-6 bg-white rounded-lg shadow-xl",children:[e.jsxs("div",{className:"grid sm:grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium text-gray-700 mb-1.5 block",children:"Status"}),e.jsxs(Bs,{value:a.status||"all",onValueChange:m=>i({...a,status:m==="all"?"":m}),children:[e.jsx(Os,{className:"bg-white",children:e.jsx(Us,{placeholder:"Any status"})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"all",children:"Any status"}),Object.entries($Oe).map(([m,p])=>e.jsx(pt,{value:m,children:p},m))]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium text-gray-700 mb-1.5 block",children:"Property Type"}),e.jsxs(Bs,{value:a.propertyType||"all",onValueChange:m=>i({...a,propertyType:m==="all"?"":m}),children:[e.jsx(Os,{className:"bg-white",children:e.jsx(Us,{placeholder:"Any type"})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"all",children:"Any type"}),Object.entries(HPt).map(([m,p])=>e.jsx(pt,{value:m,children:p},m))]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium text-gray-700 mb-1.5 block",children:"Min Price"}),e.jsx(Se,{type:"number",placeholder:"No min",value:a.minPrice,onChange:m=>i({...a,minPrice:m.target.value}),className:"bg-white"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium text-gray-700 mb-1.5 block",children:"Max Price"}),e.jsx(Se,{type:"number",placeholder:"No max",value:a.maxPrice,onChange:m=>i({...a,maxPrice:m.target.value}),className:"bg-white"})]})]}),h&&e.jsx("div",{className:"flex justify-end mt-4",children:e.jsxs(H,{variant:"ghost",size:"sm",onClick:d,className:"gap-1 text-gray-500",children:[e.jsx(Rr,{className:"h-4 w-4"}),"Clear all"]})})]})]})]})]}),l&&l.length>0&&e.jsx("section",{className:"py-8 bg-white border-b border-gray-200",children:e.jsxs("div",{className:"max-w-7xl mx-auto px-4",children:[e.jsx("h2",{className:"text-xl font-semibold text-gray-900 mb-4",children:"Explore on Map"}),e.jsx(uPt,{listings:l,isLoading:o})]})}),e.jsx("section",{className:"py-8",children:e.jsx("div",{className:"max-w-7xl mx-auto px-4",children:o?e.jsx("div",{className:"grid sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-5",children:[...Array(8)].map((m,p)=>e.jsxs("div",{className:"bg-white rounded-lg overflow-hidden shadow-sm",children:[e.jsx(Ks,{className:"aspect-[4/3]"}),e.jsxs("div",{className:"p-4 space-y-3",children:[e.jsx(Ks,{className:"h-7 w-28"}),e.jsx(Ks,{className:"h-4 w-full"}),e.jsx(Ks,{className:"h-4 w-3/4"})]})]},p))}):l&&l.length>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex items-center justify-between mb-6",children:e.jsxs("h2",{className:"text-xl font-semibold text-gray-900",children:[l.length," ",l.length===1?"Home":"Homes"," Available"]})}),e.jsx("div",{className:"grid sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-5",children:l.map(m=>{var _,b,j;const p=((_=m.photos)==null?void 0:_.find(k=>k.is_primary))||((b=m.photos)==null?void 0:b[0]),y=window.location.hostname==="listings.relevelup.com"||window.location.hostname.startsWith("listings.")?`/${m.slug||m.id}`:`/public/listing/${m.slug||m.id}`;return e.jsx(Xn,{to:y,children:e.jsxs("div",{className:"bg-white rounded-lg overflow-hidden shadow-sm hover:shadow-lg transition-shadow cursor-pointer group border border-gray-100",children:[e.jsxs("div",{className:"aspect-[4/3] relative overflow-hidden bg-gray-100",children:[p?e.jsx("img",{src:p.photo_url,alt:m.property_address||m.city,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(Fn,{className:"h-12 w-12 text-gray-300"})}),e.jsx(Xe,{className:`absolute top-2 left-2 ${VPt[m.status]} text-white border-0 text-xs font-medium px-2 py-0.5`,children:$Oe[m.status]}),e.jsx("button",{className:"absolute top-2 right-2 p-2 rounded-full bg-white/80 hover:bg-white transition-colors",onClick:k=>k.preventDefault(),children:e.jsx(Bi,{className:"h-5 w-5 text-gray-600"})})]}),e.jsxs("div",{className:"p-4",children:[e.jsx("p",{className:"text-xl font-bold text-gray-900 mb-1",children:c(m.price)}),e.jsxs("div",{className:"flex items-center gap-1 text-sm text-gray-700 mb-2",children:[m.bedrooms&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"font-semibold",children:m.bedrooms}),e.jsx("span",{className:"text-gray-500",children:"bds"}),e.jsx("span",{className:"text-gray-300 mx-1",children:"|"})]}),m.bathrooms&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"font-semibold",children:m.bathrooms}),e.jsx("span",{className:"text-gray-500",children:"ba"}),e.jsx("span",{className:"text-gray-300 mx-1",children:"|"})]}),m.square_footage&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"font-semibold",children:m.square_footage.toLocaleString()}),e.jsx("span",{className:"text-gray-500",children:"sqft"})]})]}),m.property_address&&e.jsx("p",{className:"text-sm text-gray-700 truncate",children:m.property_address}),e.jsxs("p",{className:"text-sm text-gray-500 truncate",children:[m.city,", ",m.state]}),m.agent&&e.jsxs("div",{className:"mt-3 pt-3 border-t border-gray-100",children:[e.jsx("p",{className:"text-xs text-gray-500 truncate",children:m.agent.name}),((j=m.agent.brokerage)==null?void 0:j.name)&&e.jsx("p",{className:"text-xs text-gray-400 truncate",children:m.agent.brokerage.name})]})]})]})},m.id)})})]}):e.jsxs("div",{className:"text-center py-16",children:[e.jsx("div",{className:"w-20 h-20 mx-auto mb-4 rounded-full bg-gray-100 flex items-center justify-center",children:e.jsx(Fn,{className:"h-10 w-10 text-gray-400"})}),e.jsx("h3",{className:"text-xl font-semibold text-gray-900 mb-2",children:"No listings found"}),e.jsx("p",{className:"text-gray-500 mb-6",children:h?"Try adjusting your search or filters":"Check back soon for new listings"}),h&&e.jsx(H,{variant:"outline",onClick:d,children:"Clear filters"})]})})}),e.jsx("footer",{className:"bg-gray-900 text-white py-10 mt-auto",children:e.jsx("div",{className:"max-w-7xl mx-auto px-4",children:e.jsxs("div",{className:"flex flex-col md:flex-row items-center justify-between gap-4",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("img",{src:a5e,alt:"LevelUp",className:"h-6"})}),e.jsxs("p",{className:"text-gray-400 text-sm",children:["© ",new Date().getFullYear()," LevelUp. All rights reserved."]}),e.jsx("a",{href:"https://relevelup.com",target:"_blank",rel:"noopener noreferrer",className:"text-gray-400 hover:text-white text-sm transition-colors",children:"relevelup.com"})]})})})]})]})}const ke=S.forwardRef(({className:s,...t},r)=>e.jsx("div",{ref:r,className:Ft("rounded-lg border bg-card text-card-foreground shadow-sm",s),...t}));ke.displayName="Card";const Ot=S.forwardRef(({className:s,...t},r)=>e.jsx("div",{ref:r,className:Ft("flex flex-col space-y-1.5 p-6",s),...t}));Ot.displayName="CardHeader";const zt=S.forwardRef(({className:s,...t},r)=>e.jsx("h3",{ref:r,className:Ft("text-2xl font-semibold leading-none tracking-tight",s),...t}));zt.displayName="CardTitle";const Br=S.forwardRef(({className:s,...t},r)=>e.jsx("p",{ref:r,className:Ft("text-sm text-muted-foreground",s),...t}));Br.displayName="CardDescription";const Oe=S.forwardRef(({className:s,...t},r)=>e.jsx("div",{ref:r,className:Ft("p-6 pt-0",s),...t}));Oe.displayName="CardContent";const WF=S.forwardRef(({className:s,...t},r)=>e.jsx("div",{ref:r,className:Ft("flex items-center p-6 pt-0",s),...t}));WF.displayName="CardFooter";var GPt="Label",Gst=S.forwardRef((s,t)=>e.jsx(Vn.label,{...s,ref:t,onMouseDown:r=>{var a;r.target.closest("button, input, select, textarea")||((a=s.onMouseDown)==null||a.call(s,r),!r.defaultPrevented&&r.detail>1&&r.preventDefault())}}));Gst.displayName=GPt;var Wst=Gst;const WPt=zA("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),ue=S.forwardRef(({className:s,...t},r)=>e.jsx(Wst,{ref:r,className:Ft(WPt(),s),...t}));ue.displayName=Wst.displayName;const Ihe="/assets/levelup-logo-color-D3mY9gCJ.png";function KPt(){const s=Vc(),t=window.location.hostname;if(!(t==="listings.relevelup.com"||t.startsWith("listings.")))return null;const n=s.pathname.slice(1);return!n||n===""?e.jsx(Hst,{}):n.startsWith("public/")?null:e.jsx(YPt,{slug:n})}function YPt({slug:s}){return e.jsx(QPt,{slug:s})}const ZPt={active:"bg-emerald-500",coming_soon:"bg-sky-500",office_exclusive:"bg-indigo-500",pre_market:"bg-cyan-500",price_improvement:"bg-orange-500",under_contract:"bg-purple-500",sold:"bg-gray-500"},XPt={active:"Active",coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"},UOe={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"};function QPt({slug:s}){var O,$;const{data:t,isLoading:r}=qst(s),n=Vst(),[a,i]=S.useState(""),[l,o]=S.useState(""),[c,d]=S.useState(""),[h,m]=S.useState(""),[p,x]=S.useState(!1),[y,_]=S.useState(!1),[b,j]=S.useState(null),k=ee=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(ee),T=async ee=>{if(ee.preventDefault(),!(!a.trim()||!c.trim()||!t)){x(!0);try{await n.mutateAsync({listingId:t.id,agentId:t.agent_id,firstName:a.trim(),lastName:l.trim(),email:c.trim(),phone:h.trim()}),_(!0),he.success("Thanks! The agent will be in touch soon.")}catch(Z){console.error("Lead submission error:",Z),he.error(`Failed to submit: ${Z.message||"Please try again"}`)}finally{x(!1)}}},E=(t==null?void 0:t.photos)||[],A=E.find(ee=>ee.is_primary)||E[0],D=()=>{b!==null&&j(b===0?E.length-1:b-1)},R=()=>{b!==null&&j(b===E.length-1?0:b+1)};if(r)return e.jsxs("div",{className:"min-h-screen bg-background",children:[e.jsx("header",{className:"border-b bg-card",children:e.jsx("div",{className:"container mx-auto px-4 py-4",children:e.jsx(Ks,{className:"h-8 w-32"})})}),e.jsxs("div",{className:"container mx-auto px-4 py-8",children:[e.jsx(Ks,{className:"h-10 w-48 mb-6"}),e.jsx(Ks,{className:"aspect-video mb-6"}),e.jsxs("div",{className:"grid md:grid-cols-3 gap-6",children:[e.jsxs("div",{className:"md:col-span-2 space-y-4",children:[e.jsx(Ks,{className:"h-12 w-48"}),e.jsx(Ks,{className:"h-6 w-full"}),e.jsx(Ks,{className:"h-6 w-3/4"})]}),e.jsx(Ks,{className:"h-64"})]})]})]});if(!t)return e.jsxs("div",{className:"min-h-screen bg-background",children:[e.jsx("header",{className:"border-b bg-card",children:e.jsx("div",{className:"container mx-auto px-4 py-4",children:e.jsx("a",{href:"/",className:"flex items-center gap-2",children:e.jsx("img",{src:Ihe,alt:"LevelUp",className:"h-8"})})})}),e.jsxs("div",{className:"container mx-auto px-4 py-16 text-center",children:[e.jsx(Fn,{className:"h-16 w-16 mx-auto text-muted-foreground mb-4"}),e.jsx("h1",{className:"text-2xl font-bold mb-2",children:"Listing Not Found"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"This listing may no longer be available."}),e.jsx(H,{asChild:!0,children:e.jsx("a",{href:"/",children:"Browse All Listings"})})]})]});const z=t.property_address?`${t.property_address} - ${t.city}, ${t.state}`:`${t.city}, ${t.state} Home for Sale`;return e.jsxs(e.Fragment,{children:[e.jsxs(el,{children:[e.jsxs("title",{children:[z," | LevelUp Listings"]}),e.jsx("meta",{name:"description",content:`${k(t.price)} - ${t.bedrooms||""}BD ${t.bathrooms||""}BA ${t.square_footage?t.square_footage.toLocaleString()+" sqft":""} ${UOe[t.property_type]} in ${t.city}, ${t.state}. ${((O=t.description)==null?void 0:O.slice(0,150))||""}`}),e.jsx("meta",{property:"og:title",content:z}),e.jsx("meta",{property:"og:description",content:`${k(t.price)} - ${t.bedrooms||""}BD ${t.bathrooms||""}BA in ${t.city}, ${t.state}`}),e.jsx("meta",{property:"og:type",content:"website"}),A&&e.jsx("meta",{property:"og:image",content:A.photo_url})]}),e.jsxs("div",{className:"min-h-screen bg-background",children:[e.jsx("header",{className:"border-b bg-card sticky top-0 z-50",children:e.jsx("div",{className:"container mx-auto px-4 py-4",children:e.jsx("div",{className:"flex items-center justify-between",children:e.jsx("a",{href:"/",className:"flex items-center gap-2",children:e.jsx("img",{src:Ihe,alt:"LevelUp",className:"h-8"})})})})}),e.jsxs("div",{className:"container mx-auto px-4 py-6",children:[e.jsxs("a",{href:"/",className:"inline-flex items-center text-muted-foreground hover:text-foreground mb-6",children:[e.jsx(za,{className:"h-4 w-4 mr-2"}),"Back to Listings"]}),E.length>0&&e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4 mb-8",children:[e.jsx("div",{className:"md:col-span-2",children:e.jsx("div",{className:"aspect-[16/10] rounded-lg overflow-hidden bg-muted cursor-pointer",onClick:()=>j(0),children:e.jsx("img",{src:A==null?void 0:A.photo_url,alt:"Primary",className:"w-full h-full object-cover hover:scale-105 transition-transform duration-300"})})}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:E.slice(1,5).map((ee,Z)=>e.jsxs("div",{className:"aspect-square rounded-lg overflow-hidden bg-muted cursor-pointer relative",onClick:()=>j(Z+1),children:[e.jsx("img",{src:ee.photo_url,alt:`Photo ${Z+2}`,className:"w-full h-full object-cover hover:scale-105 transition-transform duration-300"}),Z===3&&E.length>5&&e.jsxs("div",{className:"absolute inset-0 bg-black/60 flex items-center justify-center text-white font-semibold",children:["+",E.length-5," more"]})]},ee.id))})]}),e.jsxs("div",{className:"grid md:grid-cols-3 gap-8",children:[e.jsxs("div",{className:"md:col-span-2 space-y-6",children:[e.jsxs("div",{children:[e.jsx("div",{className:"flex items-center gap-2 mb-3",children:e.jsx(Xe,{className:`${ZPt[t.status]} text-white border-0`,children:XPt[t.status]})}),e.jsx("h1",{className:"text-4xl font-bold text-primary mb-2",children:k(t.price)}),t.property_address&&e.jsx("p",{className:"text-xl font-medium",children:t.property_address}),e.jsxs("p",{className:"text-muted-foreground flex items-center gap-1",children:[e.jsx(Qa,{className:"h-4 w-4"}),t.city,", ",t.state,t.neighborhood&&` • ${t.neighborhood}`]})]}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-4 py-4 border-y",children:[t.bedrooms&&e.jsxs("div",{className:"text-center",children:[e.jsx(x1,{className:"h-6 w-6 mx-auto mb-1 text-muted-foreground"}),e.jsx("p",{className:"text-xl font-semibold",children:t.bedrooms}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Beds"})]}),t.bathrooms&&e.jsxs("div",{className:"text-center",children:[e.jsx(_p,{className:"h-6 w-6 mx-auto mb-1 text-muted-foreground"}),e.jsx("p",{className:"text-xl font-semibold",children:t.bathrooms}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Baths"})]}),t.square_footage&&e.jsxs("div",{className:"text-center",children:[e.jsx(Hy,{className:"h-6 w-6 mx-auto mb-1 text-muted-foreground"}),e.jsx("p",{className:"text-xl font-semibold",children:t.square_footage.toLocaleString()}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Sq Ft"})]}),t.year_built&&e.jsxs("div",{className:"text-center",children:[e.jsx(Nn,{className:"h-6 w-6 mx-auto mb-1 text-muted-foreground"}),e.jsx("p",{className:"text-xl font-semibold",children:t.year_built}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Built"})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(Xe,{variant:"secondary",children:[e.jsx(Xa,{className:"h-3 w-3 mr-1"}),UOe[t.property_type]]}),t.lot_size&&e.jsxs(Xe,{variant:"secondary",children:["Lot: ",t.lot_size]}),t.has_hoa&&e.jsx(Xe,{variant:"secondary",children:"HOA"})]}),t.description&&e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold mb-2",children:"About This Property"}),e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:t.description})]}),t.agent_notes&&t.agent_notes_public&&e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold mb-2",children:"Agent Notes"}),e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:t.agent_notes})]}),t.mls_link&&e.jsx(H,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:t.mls_link,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(gn,{className:"h-4 w-4 mr-2"}),"View on MLS"]})})]})]}),e.jsxs("div",{className:"space-y-6",children:[t.agent&&e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsxs(zt,{className:"text-lg flex items-center gap-2",children:[e.jsx(io,{className:"h-5 w-5"}),"Listing Agent"]})}),e.jsxs(Oe,{children:[e.jsx("p",{className:"font-semibold text-lg",children:t.agent.name}),(($=t.agent.brokerage)==null?void 0:$.name)&&e.jsx("p",{className:"text-sm text-muted-foreground",children:t.agent.brokerage.name})]})]}),e.jsxs(ke,{className:"border-primary",children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-lg",children:"Interested in this property?"})}),e.jsx(Oe,{children:y?e.jsxs("div",{className:"text-center py-4",children:[e.jsx("div",{className:"h-12 w-12 rounded-full bg-primary/10 flex items-center justify-center mx-auto mb-3",children:e.jsx(er,{className:"h-6 w-6 text-primary"})}),e.jsx("p",{className:"font-medium",children:"Thanks for your interest!"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"The listing agent will contact you soon."})]}):e.jsxs("form",{onSubmit:T,className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"firstName",children:"First Name *"}),e.jsx(Se,{id:"firstName",type:"text",placeholder:"John",value:a,onChange:ee=>i(ee.target.value),required:!0})]}),e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"lastName",children:"Last Name"}),e.jsx(Se,{id:"lastName",type:"text",placeholder:"Doe",value:l,onChange:ee=>o(ee.target.value)})]})]}),e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"email",children:"Email *"}),e.jsx(Se,{id:"email",type:"email",placeholder:"you@example.com",value:c,onChange:ee=>d(ee.target.value),required:!0})]}),e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"phone",children:"Phone"}),e.jsx(Se,{id:"phone",type:"tel",placeholder:"(555) 123-4567",value:h,onChange:ee=>m(ee.target.value)})]}),e.jsx(H,{type:"submit",className:"w-full",disabled:p,children:p?"Submitting...":"Get More Info"}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:"The listing agent will reach out to you directly."})]})})]})]})]})]}),e.jsx(bs,{open:b!==null,onOpenChange:()=>j(null),children:e.jsxs(vs,{className:"max-w-5xl p-0 bg-black/95",children:[e.jsx(Cs,{className:"sr-only",children:e.jsx(Ns,{children:"Photo Gallery"})}),e.jsx("button",{onClick:()=>j(null),className:"absolute right-4 top-4 z-50 rounded-full bg-black/50 p-2 text-white hover:bg-black/70",children:e.jsx(Rr,{className:"h-5 w-5"})}),b!==null&&E[b]&&e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:E[b].photo_url,alt:`Photo ${b+1}`,className:"w-full max-h-[80vh] object-contain"}),E.length>1&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:D,className:"absolute left-4 top-1/2 -translate-y-1/2 rounded-full bg-black/50 p-2 text-white hover:bg-black/70",children:e.jsx(fl,{className:"h-6 w-6"})}),e.jsx("button",{onClick:R,className:"absolute right-4 top-1/2 -translate-y-1/2 rounded-full bg-black/50 p-2 text-white hover:bg-black/70",children:e.jsx($a,{className:"h-6 w-6"})}),e.jsxs("div",{className:"absolute bottom-4 left-1/2 -translate-x-1/2 text-white bg-black/50 px-3 py-1 rounded-full text-sm",children:[b+1," / ",E.length]})]})]})]})}),e.jsx("footer",{className:"border-t py-8 mt-16",children:e.jsxs("div",{className:"container mx-auto px-4 text-center text-sm text-muted-foreground",children:[e.jsxs("p",{children:["© ",new Date().getFullYear()," LevelUp. All rights reserved."]}),e.jsx("p",{className:"mt-2",children:e.jsx("a",{href:"https://relevelup.com",target:"_blank",rel:"noopener noreferrer",className:"hover:text-foreground",children:"relevelup.com"})})]})})]})]})}function bge({card:s,variant:t}){const r=s.brokerage_display_name||s.brokerage_logo_url,n=s.team_name||s.team_logo_url;if(!r&&!n)return null;const a={standard:{container:"bg-slate-50 border border-slate-100",text:"text-slate-600",subtext:"text-slate-400"},luxury:{container:"bg-[#1e2636] border border-[#c9a84c]/10",text:"text-[#e2e8f0]",subtext:"text-[#4a5568]"},bold:{container:"bg-gray-50 border border-gray-100",text:"text-[#1a1a2e]",subtext:"text-gray-400"},classic:{container:"bg-white border border-[#d4cfc5] shadow-sm",text:"text-[#1b3a4b]",subtext:"text-[#a0aec0]"}}[t];return e.jsx("div",{className:`rounded-2xl p-4 mb-6 ${a.container}`,children:e.jsxs("div",{className:`flex flex-col items-center gap-3 ${r&&n?"divide-y divide-current/10":""}`,children:[r&&e.jsxs("div",{className:"flex flex-col items-center gap-1.5 w-full",children:[s.brokerage_logo_url&&e.jsx("img",{src:s.brokerage_logo_url,alt:s.brokerage_display_name||"Brokerage",style:{height:`${s.brokerage_logo_size||56}px`},className:"max-w-[280px] object-contain"}),s.brokerage_display_name&&!s.brokerage_logo_url&&e.jsx("p",{className:`text-sm font-medium ${a.text}`,children:s.brokerage_display_name})]}),n&&e.jsxs("div",{className:`flex flex-col items-center gap-1.5 w-full ${r?"pt-3":""}`,children:[s.team_logo_url&&e.jsx("img",{src:s.team_logo_url,alt:s.team_name||"Team",style:{height:`${s.team_logo_size||56}px`},className:"max-w-[280px] object-contain"}),s.team_name&&!s.team_logo_url&&e.jsx("p",{className:`text-sm font-medium ${a.text}`,children:s.team_name})]})]})})}const Kst=s=>yt({queryKey:["agent-card-public",s],queryFn:async()=>{if(!s)throw new Error("No slug provided");const{data:t,error:r}=await V.from("agent_cards").select("*").eq("slug",s).eq("is_published",!0).single();if(r)throw r;const{data:n}=await V.from("profiles").select("name, email, phone, brokerage_id").eq("id",t.user_id).single();let a=null;if(n!=null&&n.brokerage_id){const{data:o}=await V.from("brokerages").select("name").eq("id",n.brokerage_id).single();a=(o==null?void 0:o.name)||null}let i=null;try{const{data:o}=await V.from("profiles").select("avatar_url").eq("id",t.user_id).single();if(o!=null&&o.avatar_url)i=o.avatar_url;else{const{data:c}=await V.storage.from("avatars").list(`${t.user_id}`);if(c&&c.length>0){const{data:d}=V.storage.from("avatars").getPublicUrl(`${t.user_id}/${c[0].name}`);i=`${d.publicUrl}?t=${Date.now()}`}}}catch{}const l={...n||{name:null,email:null,phone:null,brokerage_id:null},email:t.display_email||(n==null?void 0:n.email)||null};return{...t,social_links:t.social_links||[],profile:l,brokerage_name:t.brokerage_display_name||a,avatar_url:i}},enabled:!!s}),JPt=()=>yt({queryKey:["agent-cards-admin"],queryFn:async()=>{const{data:s,error:t}=await V.from("agent_cards").select("*").order("created_at",{ascending:!1});if(t)throw t;return s}}),eLt=s=>yt({queryKey:["agent-card",s],queryFn:async()=>{if(!s)return null;const{data:t,error:r}=await V.from("agent_cards").select("*").eq("user_id",s).maybeSingle();if(r)throw r;return t},enabled:!!s}),Yst=()=>{const s=ns();return Pt({mutationFn:async t=>{const{data:r,error:n}=await V.from("agent_cards").insert(t).select().single();if(n)throw n;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-cards-admin"]}),s.invalidateQueries({queryKey:["agent-card"]}),he.success("Agent card created")},onError:t=>he.error(t.message)})},Zst=()=>{const s=ns();return Pt({mutationFn:async({id:t,...r})=>{const{data:n,error:a}=await V.from("agent_cards").update(r).eq("id",t).select().single();if(a)throw a;return n},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["agent-cards-admin"]}),s.invalidateQueries({queryKey:["agent-card"]}),he.success("Agent card updated")},onError:t=>he.error(t.message)})},Xo=async(s,t,r,n)=>{const a=new URLSearchParams(window.location.search);await V.from("agent_card_interactions").insert({card_id:s,interaction_type:t,interaction_detail:r||null,referrer:document.referrer||null,user_agent:navigator.userAgent||null,utm_source:a.get("utm_source")||null,utm_medium:a.get("utm_medium")||null,utm_campaign:a.get("utm_campaign")||null,metadata:{}})},tLt=async(s,t)=>{const{error:r}=await V.from("agent_card_leads").insert({card_id:s,...t});if(r)throw r},Xst=s=>yt({queryKey:["agent-card-analytics",s],queryFn:async()=>{if(!s)return null;const{data:t,error:r}=await V.from("agent_card_interactions").select("interaction_type, interaction_detail, created_at").eq("card_id",s).order("created_at",{ascending:!1}).limit(500);if(r)throw r;const{data:n,error:a}=await V.from("agent_card_leads").select("*").eq("card_id",s).order("created_at",{ascending:!1});if(a)throw a;const i=(t==null?void 0:t.filter(c=>c.interaction_type==="card_view").length)||0,l=(t==null?void 0:t.filter(c=>c.interaction_type==="button_click").length)||0,o=(t==null?void 0:t.filter(c=>c.interaction_type==="contact_saved").length)||0;return{views:i,clicks:l,saves:o,leads:n||[],interactions:t||[]}},enabled:!!s});function _ge({open:s,onOpenChange:t,cardId:r,type:n,agentName:a}){const[i,l]=S.useState(""),[o,c]=S.useState(""),[d,h]=S.useState(""),[m,p]=S.useState(""),[x,y]=S.useState(""),[_,b]=S.useState(!1),j=async k=>{if(k.preventDefault(),!i.trim()){he.error("Please enter your name");return}b(!0);try{await tLt(r,{lead_type:n,name:i.trim(),email:o.trim()||void 0,phone:d.trim()||void 0,message:x.trim()||void 0,intent:m||void 0}),Xo(r,"lead_submitted",n),V.functions.invoke("card-lead-notify",{body:{cardId:r,leadType:n,name:i.trim(),email:o.trim()||void 0,phone:d.trim()||void 0,message:x.trim()||void 0,intent:m||void 0}}).catch(T=>console.error("Card lead notify failed:",T)),he.success(n==="booking"?"Request sent! They'll be in touch soon.":n==="connect"?"Info shared! They'll be in touch soon.":"Referral submitted! Thank you."),t(!1),l(""),c(""),h(""),p(""),y("")}catch{he.error("Something went wrong. Please try again.")}finally{b(!1)}};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"sm:max-w-md rounded-2xl",children:[e.jsxs(Cs,{children:[e.jsx(Ns,{children:n==="booking"?"Book a Call":n==="connect"?"Connect with Me":"Refer a Friend"}),e.jsx(nn,{children:n==="booking"?`Let ${a} know you'd like to connect.`:n==="connect"?`Share your info and ${a} will reach out.`:`Know someone who could use ${a}'s help?`})]}),e.jsxs("form",{onSubmit:j,className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"lead-name",children:"Name *"}),e.jsx(Se,{id:"lead-name",value:i,onChange:k=>l(k.target.value),placeholder:"Your name",required:!0})]}),e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"lead-phone",children:"Phone"}),e.jsx(Se,{id:"lead-phone",type:"tel",value:d,onChange:k=>h(k.target.value),placeholder:"(555) 123-4567"})]}),e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"lead-email",children:"Email"}),e.jsx(Se,{id:"lead-email",type:"email",value:o,onChange:k=>c(k.target.value),placeholder:"you@example.com"})]}),n==="booking"&&e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"lead-intent",children:"I'm looking to..."}),e.jsxs(Bs,{value:m,onValueChange:p,children:[e.jsx(Os,{children:e.jsx(Us,{placeholder:"Select one"})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"buy",children:"Buy a home"}),e.jsx(pt,{value:"sell",children:"Sell my home"}),e.jsx(pt,{value:"both",children:"Buy & Sell"}),e.jsx(pt,{value:"other",children:"Something else"})]})]})]}),n!=="connect"&&e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"lead-message",children:n==="referral"?"Tell us about them":"Message (optional)"}),e.jsx(Se,{id:"lead-message",value:x,onChange:k=>y(k.target.value),placeholder:n==="referral"?"Their name, phone, situation...":"Anything you'd like us to know"})]}),e.jsx(H,{type:"submit",className:"w-full rounded-2xl",disabled:_,children:_?"Sending...":"Submit"})]})]})})}const sLt=s=>yt({queryKey:["card-blocks",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await V.from("card_blocks").select("*").eq("card_id",s).eq("is_visible",!0).order("sort_order",{ascending:!0});if(r)throw r;return t||[]},enabled:!!s}),rLt=s=>yt({queryKey:["card-blocks-all",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await V.from("card_blocks").select("*").eq("card_id",s).order("sort_order",{ascending:!0});if(r)throw r;return t||[]},enabled:!!s}),nLt=()=>{const s=ns();return Pt({mutationFn:async t=>{const{data:r,error:n}=await V.from("card_blocks").insert(t).select().single();if(n)throw n;return r},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["card-blocks",r.card_id]}),s.invalidateQueries({queryKey:["card-blocks-all",r.card_id]}),he.success("Block added")},onError:t=>he.error(t.message)})},aLt=()=>{const s=ns();return Pt({mutationFn:async({id:t,...r})=>{const{data:n,error:a}=await V.from("card_blocks").update(r).eq("id",t).select().single();if(a)throw a;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["card-blocks"]}),s.invalidateQueries({queryKey:["card-blocks-all"]}),he.success("Block updated")},onError:t=>he.error(t.message)})},iLt=()=>{const s=ns();return Pt({mutationFn:async t=>{const{error:r}=await V.from("card_blocks").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["card-blocks"]}),s.invalidateQueries({queryKey:["card-blocks-all"]}),he.success("Block removed")},onError:t=>he.error(t.message)})};function oLt(s){const t=s.match(/(?:iframe\.mediadelivery\.net\/embed\/|video\.bunnycdn\.com\/play\/)(\d+)\/([a-f0-9-]+)/i);return t?`https://iframe.mediadelivery.net/embed/${t[1]}/${t[2]}?autoplay=false&responsive=true`:(s.includes("iframe.mediadelivery.net"),s)}function lLt(s){const t=s.match(/(?:youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/embed\/)([a-zA-Z0-9_-]{11})/);return t?`https://www.youtube.com/embed/${t[1]}`:null}const cLt={standard:"rounded-2xl overflow-hidden mb-6 bg-slate-100",luxury:"rounded-xl overflow-hidden mb-6 bg-[#1e2636] border border-[#c9a84c]/10",bold:"rounded-2xl overflow-hidden mb-6",classic:"rounded-lg overflow-hidden mb-6 border border-[#d4cfc5] shadow-sm"};function dLt({block:s,variant:t}){const r=s.config;if(!r.video_url)return null;const n=r.video_url.includes("mediadelivery.net")||r.video_url.includes("bunnycdn.com"),a=lLt(r.video_url),i=n||!!a,l=n?oLt(r.video_url):a||r.video_url;return e.jsx("div",{className:cLt[t],children:i?e.jsx("div",{style:{position:"relative",paddingTop:"56.25%"},children:e.jsx("iframe",{src:l,loading:"lazy",style:{border:0,position:"absolute",top:0,left:0,width:"100%",height:"100%"},allow:"accelerometer; gyroscope; autoplay; encrypted-media; picture-in-picture",allowFullScreen:!0})}):e.jsx("video",{src:r.video_url,controls:!0,className:"w-full",preload:"metadata"})})}const uLt={standard:{container:"mb-6",card:"bg-slate-50 rounded-2xl p-5 border border-slate-100",quote:"text-sm text-slate-600 italic",name:"text-sm font-semibold text-slate-800",role:"text-xs text-slate-500",dot:"bg-primary",dotInactive:"bg-slate-300",nav:"text-slate-400 hover:text-slate-600"},luxury:{container:"mb-6",card:"bg-[#1e2636] rounded-xl p-5 border border-[#c9a84c]/10",quote:"text-sm text-[#a0aec0] italic font-serif",name:"text-sm font-semibold text-white",role:"text-xs text-[#c9a84c]",dot:"bg-[#c9a84c]",dotInactive:"bg-[#2a3040]",nav:"text-[#4a5568] hover:text-[#c9a84c]"},bold:{container:"mb-6",card:"bg-[#fff3e0] rounded-2xl p-5",quote:"text-sm text-[#1a1a2e] font-medium",name:"text-sm font-black text-[#1a1a2e]",role:"text-xs text-[#ff5722] font-bold",dot:"bg-[#ff5722]",dotInactive:"bg-gray-300",nav:"text-gray-400 hover:text-[#ff5722]"},classic:{container:"mb-6",card:"bg-white rounded-lg p-5 border border-[#d4cfc5] shadow-sm",quote:"text-sm text-[#4a5568] italic font-serif",name:"text-sm font-semibold text-[#1b3a4b]",role:"text-xs text-[#5a7a6f]",dot:"bg-[#1b3a4b]",dotInactive:"bg-[#d4cfc5]",nav:"text-[#a0aec0] hover:text-[#1b3a4b]"}};function hLt({block:s,variant:t}){const n=s.config.testimonials||[],[a,i]=S.useState(0);if(n.length===0)return null;const l=uLt[t],o=n[a];return e.jsxs("div",{className:l.container,children:[e.jsxs("div",{className:l.card,children:[e.jsx(Kk,{className:"h-4 w-4 mb-2 opacity-30"}),e.jsxs("p",{className:`${l.quote} mb-3`,children:['"',o.quote,'"']}),e.jsxs("div",{children:[e.jsx("p",{className:l.name,children:o.name}),o.role&&e.jsx("p",{className:l.role,children:o.role})]})]}),n.length>1&&e.jsxs("div",{className:"flex items-center justify-center gap-3 mt-3",children:[e.jsx("button",{onClick:()=>i(c=>(c-1+n.length)%n.length),className:l.nav,children:e.jsx(fl,{className:"h-4 w-4"})}),e.jsx("div",{className:"flex gap-1.5",children:n.map((c,d)=>e.jsx("div",{className:`h-1.5 w-1.5 rounded-full transition-colors cursor-pointer ${d===a?l.dot:l.dotInactive}`,onClick:()=>i(d)},d))}),e.jsx("button",{onClick:()=>i(c=>(c+1)%n.length),className:l.nav,children:e.jsx($a,{className:"h-4 w-4"})})]})]})}const mLt={standard:{container:"flex flex-wrap gap-2 mb-6 justify-center",tag:"px-3 py-1.5 text-xs font-medium rounded-full bg-primary/10 text-primary"},luxury:{container:"flex flex-wrap gap-2 mb-6 justify-center",tag:"px-3 py-1.5 text-xs font-medium rounded-full bg-[#c9a84c]/10 text-[#e8d48b] border border-[#c9a84c]/20"},bold:{container:"flex flex-wrap gap-2 mb-6 justify-center",tag:"px-3 py-1.5 text-xs font-black rounded-full bg-[#1a1a2e] text-white uppercase tracking-wide"},classic:{container:"flex flex-wrap gap-2 mb-6 justify-center",tag:"px-3 py-1.5 text-xs font-medium rounded-md bg-[#1b3a4b]/10 text-[#1b3a4b] border border-[#d4cfc5]"}};function fLt({block:s,variant:t}){const n=s.config.tags||[];if(n.length===0)return null;const a=mLt[t];return e.jsx("div",{className:a.container,children:n.map((i,l)=>e.jsx("span",{className:a.tag,children:i},l))})}const pLt={standard:{container:"space-y-2 mb-6",link:"w-full flex items-center justify-between h-12 px-4 rounded-2xl bg-slate-50 hover:bg-slate-100 border border-slate-100 transition-colors text-sm font-medium text-slate-700",icon:"text-primary"},luxury:{container:"space-y-2 mb-6",link:"w-full flex items-center justify-between h-12 px-4 rounded-xl bg-[#1e2636] hover:bg-[#252d3f] border border-[#c9a84c]/10 transition-colors text-sm font-medium text-[#e2e8f0]",icon:"text-[#c9a84c]"},bold:{container:"space-y-2 mb-6",link:"w-full flex items-center justify-between h-12 px-4 rounded-2xl bg-gray-50 hover:bg-gray-100 transition-colors text-sm font-bold text-[#1a1a2e]",icon:"text-[#ff5722]"},classic:{container:"space-y-2 mb-6",link:"w-full flex items-center justify-between h-12 px-4 rounded-lg bg-white hover:bg-[#f5f1eb] border border-[#d4cfc5] shadow-sm transition-colors text-sm font-medium text-[#1b3a4b]",icon:"text-[#5a7a6f]"}};function gLt({block:s,cardId:t,variant:r}){const a=s.config.links||[];if(a.length===0)return null;const i=pLt[r];return e.jsx("div",{className:i.container,children:a.map((l,o)=>e.jsxs("a",{href:l.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>Xo(t,"button_click",`custom_link_${l.label}`),className:i.link,children:[e.jsx("span",{children:l.label}),e.jsx(gn,{className:`h-4 w-4 ${i.icon}`})]},o))})}const Jje={instagram:{label:"Instagram",icon:"M12 2.163c3.204 0 3.584.012 4.85.07 3.252.148 4.771 1.691 4.919 4.919.058 1.265.069 1.645.069 4.849 0 3.205-.012 3.584-.069 4.849-.149 3.225-1.664 4.771-4.919 4.919-1.266.058-1.644.07-4.85.07-3.204 0-3.584-.012-4.849-.07-3.26-.149-4.771-1.699-4.919-4.92-.058-1.265-.07-1.644-.07-4.849 0-3.204.013-3.583.07-4.849.149-3.227 1.664-4.771 4.919-4.919 1.266-.057 1.645-.069 4.849-.069zM12 0C8.741 0 8.333.014 7.053.072 2.695.272.273 2.69.073 7.052.014 8.333 0 8.741 0 12c0 3.259.014 3.668.072 4.948.2 4.358 2.618 6.78 6.98 6.98C8.333 23.986 8.741 24 12 24c3.259 0 3.668-.014 4.948-.072 4.354-.2 6.782-2.618 6.979-6.98.059-1.28.073-1.689.073-4.948 0-3.259-.014-3.667-.072-4.947-.196-4.354-2.617-6.78-6.979-6.98C15.668.014 15.259 0 12 0zm0 5.838a6.162 6.162 0 100 12.324 6.162 6.162 0 000-12.324zM12 16a4 4 0 110-8 4 4 0 010 8zm6.406-11.845a1.44 1.44 0 100 2.881 1.44 1.44 0 000-2.881z",color:"#E4405F",hoverBg:"hover:bg-[#E4405F]/10"},facebook:{label:"Facebook",icon:"M24 12.073c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.99 4.388 10.954 10.125 11.854v-8.385H7.078v-3.47h3.047V9.43c0-3.007 1.792-4.669 4.533-4.669 1.312 0 2.686.235 2.686.235v2.953H15.83c-1.491 0-1.956.925-1.956 1.874v2.25h3.328l-.532 3.47h-2.796v8.385C19.612 23.027 24 18.062 24 12.073z",color:"#1877F2",hoverBg:"hover:bg-[#1877F2]/10"},linkedin:{label:"LinkedIn",icon:"M20.447 20.452h-3.554v-5.569c0-1.328-.027-3.037-1.852-3.037-1.853 0-2.136 1.445-2.136 2.939v5.667H9.351V9h3.414v1.561h.046c.477-.9 1.637-1.85 3.37-1.85 3.601 0 4.267 2.37 4.267 5.455v6.286zM5.337 7.433c-1.144 0-2.063-.926-2.063-2.065 0-1.138.92-2.063 2.063-2.063 1.14 0 2.064.925 2.064 2.063 0 1.139-.925 2.065-2.064 2.065zm1.782 13.019H3.555V9h3.564v11.452zM22.225 0H1.771C.792 0 0 .774 0 1.729v20.542C0 23.227.792 24 1.771 24h20.451C23.2 24 24 23.227 24 22.271V1.729C24 .774 23.2 0 22.222 0h.003z",color:"#0A66C2",hoverBg:"hover:bg-[#0A66C2]/10"},twitter:{label:"X",icon:"M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z",color:"#000000",hoverBg:"hover:bg-black/10"},youtube:{label:"YouTube",icon:"M23.498 6.186a3.016 3.016 0 00-2.122-2.136C19.505 3.545 12 3.545 12 3.545s-7.505 0-9.377.505A3.017 3.017 0 00.502 6.186C0 8.07 0 12 0 12s0 3.93.502 5.814a3.016 3.016 0 002.122 2.136c1.871.505 9.376.505 9.376.505s7.505 0 9.377-.505a3.015 3.015 0 002.122-2.136C24 15.93 24 12 24 12s0-3.93-.502-5.814z M9.545 15.568V8.432L15.818 12z",color:"#FF0000",hoverBg:"hover:bg-[#FF0000]/10"},tiktok:{label:"TikTok",icon:"M12.525.02c1.31-.02 2.61-.01 3.91-.02.08 1.53.63 3.09 1.75 4.17 1.12 1.11 2.7 1.62 4.24 1.79v4.03c-1.44-.05-2.89-.35-4.2-.97-.57-.26-1.1-.59-1.62-.93-.01 2.92.01 5.84-.02 8.75-.08 1.4-.54 2.79-1.35 3.94-1.31 1.92-3.58 3.17-5.91 3.21-1.43.08-2.86-.31-4.08-1.03-2.02-1.19-3.44-3.37-3.65-5.71-.02-.5-.03-1-.01-1.49.18-1.9 1.12-3.72 2.58-4.96 1.66-1.44 3.98-2.13 6.15-1.72.02 1.48-.04 2.96-.04 4.44-.99-.32-2.15-.23-3.02.37-.63.41-1.11 1.04-1.36 1.75-.21.51-.15 1.07-.14 1.61.24 1.64 1.82 3.02 3.5 2.87 1.12-.01 2.19-.66 2.77-1.61.19-.33.4-.67.41-1.06.1-1.79.06-3.57.07-5.36.01-4.03-.01-8.05.02-12.07z",color:"#000000",hoverBg:"hover:bg-black/10"},zillow:{label:"Zillow",icon:"M12 0L1 6v12l11 6 11-6V6L12 0zm0 2.18L21 7.5v9L12 21.82 3 16.5v-9L12 2.18z",color:"#006AFF",hoverBg:"hover:bg-[#006AFF]/10"},realtor:{label:"Realtor",icon:"M12 2L2 7v10l10 5 10-5V7L12 2zm0 2.18l8 4v8l-8 4-8-4v-8l8-4z",color:"#D92228",hoverBg:"hover:bg-[#D92228]/10"},spotify:{label:"Spotify",icon:"M12 0C5.4 0 0 5.4 0 12s5.4 12 12 12 12-5.4 12-12S18.66 0 12 0zm5.521 17.34c-.24.359-.66.48-1.021.24-2.82-1.74-6.36-2.101-10.561-1.141-.418.122-.779-.179-.899-.539-.12-.421.18-.78.54-.9 4.56-1.021 8.52-.6 11.64 1.32.42.18.479.659.301 1.02zm1.44-3.3c-.301.42-.841.6-1.262.3-3.239-1.98-8.159-2.58-11.939-1.38-.479.12-1.02-.12-1.14-.6-.12-.48.12-1.021.6-1.141C9.6 9.9 15 10.561 18.72 12.84c.361.181.54.78.241 1.2zm.12-3.36C15.24 8.4 8.82 8.16 5.16 9.301c-.6.179-1.2-.181-1.38-.721-.18-.601.18-1.2.72-1.381 4.26-1.26 11.28-1.02 15.721 1.621.539.3.719 1.02.419 1.56-.299.421-1.02.599-1.559.3z",color:"#1DB954",hoverBg:"hover:bg-[#1DB954]/10"},apple_music:{label:"Apple Music",icon:"M23.994 6.124a9.23 9.23 0 00-.24-2.19c-.317-1.31-1.062-2.31-2.18-3.043A5.022 5.022 0 0019.7.198a10.7 10.7 0 00-1.564-.15C17.637.017 17.14 0 12.002 0h-.004C6.858 0 6.362.017 5.862.047 5.34.08 4.82.13 4.309.325a5.017 5.017 0 00-1.874.826C1.317 2.07.573 3.07.255 4.38A9.234 9.234 0 00.02 6.57C-.013 7.068-.03 7.564 0 12.002v.004c-.03 4.438.013 4.934.047 5.432.033.522.083 1.042.278 1.554a5.017 5.017 0 00.826 1.874c.92 1.118 1.92 1.862 3.23 2.18a9.23 9.23 0 002.19.24c.498.03.994.013 5.432.047h.004c4.438.034 4.934-.013 5.432-.047a9.23 9.23 0 002.19-.24c1.31-.317 2.31-1.062 3.043-2.18a5.022 5.022 0 00.627-1.874c.195-.492.245-1.012.278-1.534.03-.498.047-.994.047-5.432v-.004c.034-4.438-.013-4.934-.047-5.432zM17.42 16.41c0 .612-.15 1.21-.44 1.758a3.58 3.58 0 01-1.207 1.31c-.518.339-1.09.521-1.705.545-.13.005-.26 0-.39-.017a2.617 2.617 0 01-1.653-.772 2.305 2.305 0 01-.668-1.653c-.005-.13 0-.26.017-.39.07-.52.275-.986.602-1.39a2.998 2.998 0 011.218-.94 3.14 3.14 0 011.12-.282c.17-.009.336.002.502.034V9.472L10.2 10.637v7.093c0 .612-.15 1.21-.44 1.758a3.58 3.58 0 01-1.207 1.31c-.518.339-1.09.521-1.705.545-.13.005-.26 0-.39-.017a2.617 2.617 0 01-1.653-.772A2.305 2.305 0 014.137 18.9c-.005-.13 0-.26.017-.39.07-.52.275-.986.602-1.39a2.998 2.998 0 011.218-.94 3.14 3.14 0 011.12-.282c.17-.009.336.002.502.034V8.377c0-.453.066-.903.195-1.34a3.2 3.2 0 01.694-1.204 2.62 2.62 0 011.063-.738c.39-.14.793-.208 1.196-.196l4.84-1.01v10.52z",color:"#FA243C",hoverBg:"hover:bg-[#FA243C]/10"}};function xLt({path:s,color:t,size:r=20}){return e.jsx("svg",{viewBox:"0 0 24 24",width:r,height:r,fill:t,children:e.jsx("path",{d:s})})}const yLt={standard:{container:"bg-white rounded-2xl border border-slate-100 p-5 mb-6 shadow-sm",title:"text-sm font-semibold text-slate-800 mb-3",linkClass:"h-11 w-11 rounded-xl bg-slate-50 border border-slate-100 flex items-center justify-center transition-all duration-200 hover:scale-110 hover:shadow-md"},luxury:{container:"bg-zinc-900/50 backdrop-blur rounded-2xl border border-amber-900/20 p-5 mb-6",title:"text-sm font-semibold text-amber-200/80 mb-3",linkClass:"h-11 w-11 rounded-xl bg-zinc-800/80 border border-amber-900/20 flex items-center justify-center transition-all duration-200 hover:scale-110 hover:border-amber-500/40 hover:shadow-md hover:shadow-amber-500/10"},bold:{container:"bg-white/10 backdrop-blur rounded-2xl border border-white/20 p-5 mb-6",title:"text-sm font-semibold text-white/90 mb-3",linkClass:"h-11 w-11 rounded-xl bg-white/10 border border-white/20 flex items-center justify-center transition-all duration-200 hover:scale-110 hover:bg-white/20 hover:shadow-md"},classic:{container:"bg-stone-50 rounded-2xl border border-stone-200 p-5 mb-6",title:"text-sm font-semibold text-stone-800 mb-3",linkClass:"h-11 w-11 rounded-xl bg-white border border-stone-200 flex items-center justify-center transition-all duration-200 hover:scale-110 hover:shadow-md"}};function vLt({block:s,cardId:t,variant:r}){const a=s.config.platforms||[],i=yLt[r];return a.length===0?null:e.jsxs("div",{className:i.container,children:[e.jsx("h3",{className:i.title,children:"Follow Me"}),e.jsx("div",{className:"flex flex-wrap gap-3 justify-center",children:a.map((l,o)=>{const c=Jje[l.platform.toLowerCase()];return!c||!l.url?null:e.jsx("a",{href:l.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>Xo(t,"button_click",`social_${l.platform}`),className:i.linkClass,title:c.label,children:e.jsx(xLt,{path:c.icon,color:c.color})},o)})})]})}function wge({cardId:s,variant:t}){const{data:r}=sLt(s);if(!r||r.length===0)return null;const n=r.filter(l=>l.block_type==="social_media"&&l.is_visible),a=r.filter(l=>l.block_type!=="social_media"),i=n.length>0?{...n[0],config:{platforms:n.flatMap(l=>l.config.platforms||[])}}:null;return r.findIndex(l=>l.block_type==="social_media"),e.jsxs(e.Fragment,{children:[a.map(l=>{switch(l.block_type){case"video_intro":return e.jsx(dLt,{block:l,variant:t},l.id);case"testimonials":return e.jsx(hLt,{block:l,variant:t},l.id);case"specialties":return e.jsx(fLt,{block:l,variant:t},l.id);case"custom_links":return e.jsx(gLt,{block:l,cardId:s,variant:t},l.id);default:return null}}),i&&e.jsx(vLt,{block:i,cardId:s,variant:t})]})}async function bLt(s){try{const t=await fetch(s);if(!t.ok)return null;const r=await t.blob(),n=r.type||"image/jpeg";return new Promise(a=>{const i=new FileReader;i.onloadend=()=>{const o=i.result.split(",")[1];a({base64:o,mimeType:n})},i.onerror=()=>a(null),i.readAsDataURL(r)})}catch{return null}}function _Lt(s){const t=s.trim().split(/\s+/);if(t.length<=1)return{first:t[0]||"",last:""};const r=t.pop();return{first:t.join(" "),last:r}}async function jge(s){const{first:t,last:r}=_Lt(s.name),n=["BEGIN:VCARD","VERSION:3.0",`FN:${s.name}`,`N:${r};${t};;;`];if(s.phone&&n.push(`TEL;TYPE=CELL:${s.phone}`),s.email&&n.push(`EMAIL;TYPE=INTERNET:${s.email}`),s.brokerage&&n.push(`ORG:${s.brokerage}`),n.push(`URL:${s.cardUrl}`),s.avatarUrl){const o=await bLt(s.avatarUrl);if(o){const d={"image/jpeg":"JPEG","image/jpg":"JPEG","image/png":"PNG","image/gif":"GIF","image/webp":"JPEG"}[o.mimeType]||"JPEG";n.push(`PHOTO;ENCODING=b;TYPE=${d}:${o.base64}`)}}n.push("END:VCARD");const a=new Blob([n.join(`\r `)],{type:"text/vcard"}),i=URL.createObjectURL(a),l=document.createElement("a");l.href=i,l.download=`${s.name.replace(/\s+/g,"_")}.vcf`,l.click(),URL.revokeObjectURL(i),he.success("Contact saved!")}function wLt({card:s}){var j;const[t,r]=S.useState(!1),[n,a]=S.useState("booking"),i=((j=s.profile)==null?void 0:j.name)||"Agent",l=i.split(" ").map(k=>k[0]).join("").toUpperCase().slice(0,2),o=(k,T)=>{Xo(s.id,"button_click",k),T()},c=()=>o("call",()=>{var k;(k=s.profile)!=null&&k.phone?window.location.href=`tel:${s.profile.phone}`:he.error("Phone number not available")}),d=()=>o("text",()=>{var k;(k=s.profile)!=null&&k.phone?window.location.href=`sms:${s.profile.phone}`:he.error("Phone number not available")}),h=()=>o("email",()=>{var k;(k=s.profile)!=null&&k.email?window.location.href=`mailto:${s.profile.email}`:he.error("Email not available")}),m=()=>{s.booking_url?o("book",()=>window.open(s.booking_url,"_blank")):(a("booking"),r(!0),Xo(s.id,"button_click","book"))},p=()=>{var k,T;Xo(s.id,"contact_saved"),jge({name:i,phone:(k=s.profile)==null?void 0:k.phone,email:(T=s.profile)==null?void 0:T.email,brokerage:s.brokerage_name,avatarUrl:s.avatar_url,cardUrl:window.location.href})},x=async()=>{Xo(s.id,"share_event");const k=`https://cards.relevelup.com/${s.slug}`,T="Here's my contact card — save it so we can stay in touch.";if(navigator.share)try{await navigator.share({title:`${i}`,text:T,url:k})}catch{}else await navigator.clipboard.writeText(k),he.success("Link copied!")},y=()=>{a("referral"),r(!0),Xo(s.id,"button_click","refer")},_=()=>{a("connect"),r(!0),Xo(s.id,"button_click","connect")},b={instagram:"📸",facebook:"📘",linkedin:"💼",twitter:"🐦",youtube:"🎬",tiktok:"🎵"};return e.jsxs("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 via-white to-slate-50",children:[e.jsxs("div",{className:"max-w-md mx-auto px-5 py-10",children:[e.jsxs("div",{className:"text-center mb-8",children:[s.show_photo&&e.jsxs(Un,{className:"h-28 w-28 mx-auto mb-4 ring-4 ring-white shadow-lg",children:[e.jsx(Ka,{src:s.avatar_url||void 0,alt:i}),e.jsx(qn,{className:"text-2xl font-semibold bg-primary text-primary-foreground",children:l})]}),e.jsx("h1",{className:"text-2xl font-bold text-slate-900 mb-0.5",children:i}),s.title&&e.jsx("p",{className:"text-sm font-medium text-primary mb-1",children:s.title}),s.brokerage_name&&!s.brokerage_logo_url&&e.jsx("p",{className:"text-sm font-medium text-slate-500 mb-1",children:s.brokerage_name}),s.team_name&&!s.team_logo_url&&e.jsx("p",{className:"text-xs font-medium text-slate-400 mb-3",children:s.team_name}),s.positioning_statement&&e.jsxs("p",{className:"text-base text-slate-600 italic leading-relaxed max-w-xs mx-auto",children:['"',s.positioning_statement,'"']})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3 mb-4",children:[e.jsxs(H,{onClick:c,className:"flex flex-col items-center gap-1.5 h-auto py-4 bg-primary hover:bg-primary/90 text-primary-foreground rounded-2xl shadow-sm",children:[e.jsx(Yn,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs font-medium",children:"Call"})]}),e.jsxs(H,{onClick:d,className:"flex flex-col items-center gap-1.5 h-auto py-4 bg-primary hover:bg-primary/90 text-primary-foreground rounded-2xl shadow-sm",children:[e.jsx(Gi,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs font-medium",children:"Text"})]}),e.jsxs(H,{onClick:h,className:"flex flex-col items-center gap-1.5 h-auto py-4 bg-primary hover:bg-primary/90 text-primary-foreground rounded-2xl shadow-sm",children:[e.jsx(er,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs font-medium",children:"Email"})]})]}),e.jsxs(H,{onClick:m,className:"w-full h-12 text-base font-semibold rounded-2xl shadow-sm mb-6",variant:"outline",children:[e.jsx(Nn,{className:"h-5 w-5 mr-2"}),s.custom_cta_label||"Book a Call"]}),s.show_credentials&&s.review_snippet&&e.jsx("div",{className:"flex items-center justify-center gap-4 mb-6 text-sm text-slate-600",children:e.jsxs("div",{className:"text-center flex items-center gap-1",children:[e.jsx(ya,{className:"h-4 w-4 text-amber-500 fill-amber-500"}),e.jsx("span",{className:"font-bold text-slate-900",children:"5.0"})]})}),s.review_snippet&&e.jsx("div",{className:"bg-slate-50 rounded-2xl p-4 mb-6 border border-slate-100",children:e.jsxs("p",{className:"text-sm text-slate-600 italic text-center",children:['"',s.review_snippet,'"']})}),s.show_bio&&s.bio&&e.jsxs("div",{className:"mb-6",children:[e.jsx("h2",{className:"text-sm font-semibold text-slate-800 mb-2",children:"About Me"}),e.jsx("p",{className:"text-sm text-slate-600 leading-relaxed",children:s.bio})]}),e.jsx(bge,{card:s,variant:"standard"}),e.jsx(wge,{cardId:s.id,variant:"standard"}),e.jsxs("div",{className:"space-y-2 mb-6",children:[s.show_save_contact&&e.jsxs(H,{variant:"ghost",onClick:p,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[e.jsx(hi,{className:"h-4 w-4 mr-3 text-primary"}),"Save Contact"]}),s.show_leave_review&&s.review_source_url&&e.jsxs(H,{variant:"ghost",onClick:()=>{Xo(s.id,"button_click","review"),window.open(s.review_source_url,"_blank")},className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[e.jsx(ya,{className:"h-4 w-4 mr-3 text-amber-500"}),"Leave a Review"]}),s.show_refer_friend&&e.jsxs(H,{variant:"ghost",onClick:y,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[e.jsx(Ar,{className:"h-4 w-4 mr-3 text-primary"}),"Refer a Friend"]}),e.jsxs(H,{variant:"ghost",onClick:_,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[e.jsx(Vl,{className:"h-4 w-4 mr-3 text-primary"}),"Connect with Me"]}),e.jsxs(H,{variant:"ghost",onClick:x,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[e.jsx(cd,{className:"h-4 w-4 mr-3 text-primary"}),"Share My Card"]})]}),s.show_social_links&&s.social_links&&s.social_links.length>0&&e.jsx("div",{className:"flex justify-center gap-4 mb-8",children:s.social_links.slice(0,3).map((k,T)=>e.jsx("a",{href:k.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>Xo(s.id,"button_click",`social_${k.platform}`),className:"h-10 w-10 rounded-full bg-slate-100 hover:bg-slate-200 flex items-center justify-center text-lg transition-colors",children:b[k.platform.toLowerCase()]||"🔗"},T))}),e.jsx("div",{className:"text-center",children:e.jsx("p",{className:"text-xs text-slate-400",children:"Powered by LevelUp"})})]}),e.jsx(_ge,{open:t,onOpenChange:r,cardId:s.id,type:n,agentName:i})]})}function jLt({card:s}){var j;const[t,r]=S.useState(!1),[n,a]=S.useState("booking"),i=((j=s.profile)==null?void 0:j.name)||"Agent",l=i.split(" ").map(k=>k[0]).join("").toUpperCase().slice(0,2),o=(k,T)=>{Xo(s.id,"button_click",k),T()},c=()=>o("call",()=>{var k;(k=s.profile)!=null&&k.phone?window.location.href=`tel:${s.profile.phone}`:he.error("Phone number not available")}),d=()=>o("text",()=>{var k;(k=s.profile)!=null&&k.phone?window.location.href=`sms:${s.profile.phone}`:he.error("Phone number not available")}),h=()=>o("email",()=>{var k;(k=s.profile)!=null&&k.email?window.location.href=`mailto:${s.profile.email}`:he.error("Email not available")}),m=()=>{s.booking_url?o("book",()=>window.open(s.booking_url,"_blank")):(a("booking"),r(!0),Xo(s.id,"button_click","book"))},p=()=>{var k,T;Xo(s.id,"contact_saved"),jge({name:i,phone:(k=s.profile)==null?void 0:k.phone,email:(T=s.profile)==null?void 0:T.email,brokerage:s.brokerage_name,avatarUrl:s.avatar_url,cardUrl:window.location.href})},x=async()=>{Xo(s.id,"share_event");const k=`https://cards.relevelup.com/${s.slug}`,T="Here's my contact card — save it so we can stay in touch.";if(navigator.share)try{await navigator.share({title:`${i}`,text:T,url:k})}catch{}else await navigator.clipboard.writeText(k),he.success("Link copied!")},y=()=>{a("referral"),r(!0),Xo(s.id,"button_click","refer")},_=()=>{a("connect"),r(!0),Xo(s.id,"button_click","connect")},b={instagram:"📸",facebook:"📘",linkedin:"💼",twitter:"🐦",youtube:"🎬",tiktok:"🎵"};return e.jsxs("div",{className:"min-h-screen bg-gradient-to-b from-[#0f1419] via-[#1a1f2e] to-[#0f1419]",children:[e.jsxs("div",{className:"max-w-md mx-auto px-5 py-10",children:[e.jsx("div",{className:"w-16 h-0.5 bg-gradient-to-r from-[#c9a84c] to-[#e8d48b] mx-auto mb-8"}),e.jsxs("div",{className:"text-center mb-8",children:[s.show_photo&&e.jsxs(Un,{className:"h-32 w-32 mx-auto mb-5 ring-2 ring-[#c9a84c]/40 shadow-2xl",children:[e.jsx(Ka,{src:s.avatar_url||void 0,alt:i}),e.jsx(qn,{className:"text-2xl font-serif bg-[#c9a84c]/20 text-[#e8d48b]",children:l})]}),e.jsx("h1",{className:"text-2xl font-serif font-bold text-white tracking-wide mb-0.5",children:i}),s.title&&e.jsx("p",{className:"text-sm font-medium text-[#e8d48b] mb-1",children:s.title}),s.brokerage_name&&!s.brokerage_logo_url&&e.jsx("p",{className:"text-sm font-medium text-[#c9a84c] tracking-widest uppercase mb-1",children:s.brokerage_name}),s.team_name&&!s.team_logo_url&&e.jsx("p",{className:"text-xs font-medium text-[#a0aec0] mb-3",children:s.team_name}),s.positioning_statement&&e.jsxs("p",{className:"text-base text-[#a0aec0] italic leading-relaxed max-w-xs mx-auto font-serif",children:['"',s.positioning_statement,'"']})]}),e.jsx("div",{className:"grid grid-cols-3 gap-3 mb-4",children:[{icon:Yn,label:"Call",handler:c},{icon:Gi,label:"Text",handler:d},{icon:er,label:"Email",handler:h}].map(({icon:k,label:T,handler:E})=>e.jsxs("button",{onClick:E,className:"flex flex-col items-center gap-1.5 py-4 bg-[#1e2636] hover:bg-[#252d3f] border border-[#c9a84c]/20 rounded-xl transition-colors",children:[e.jsx(k,{className:"h-5 w-5 text-[#c9a84c]"}),e.jsx("span",{className:"text-xs font-medium text-[#e2e8f0]",children:T})]},T))}),e.jsxs("button",{onClick:m,className:"w-full h-12 text-base font-semibold rounded-xl mb-6 bg-gradient-to-r from-[#c9a84c] to-[#e8d48b] text-[#0f1419] hover:opacity-90 transition-opacity flex items-center justify-center gap-2",children:[e.jsx(Nn,{className:"h-5 w-5"}),s.custom_cta_label||"Book a Call"]}),s.show_credentials&&s.review_snippet&&e.jsx("div",{className:"flex items-center justify-center gap-4 mb-6 text-sm",children:e.jsxs("div",{className:"text-center flex items-center gap-1",children:[e.jsx(ya,{className:"h-4 w-4 text-[#c9a84c] fill-[#c9a84c]"}),e.jsx("span",{className:"font-bold text-white",children:"5.0"})]})}),s.review_snippet&&e.jsx("div",{className:"bg-[#1e2636] rounded-xl p-4 mb-6 border border-[#c9a84c]/10",children:e.jsxs("p",{className:"text-sm text-[#a0aec0] italic text-center font-serif",children:['"',s.review_snippet,'"']})}),s.show_bio&&s.bio&&e.jsxs("div",{className:"mb-6",children:[e.jsx("h2",{className:"text-sm font-semibold text-[#c9a84c] mb-2 tracking-wide uppercase",children:"About"}),e.jsx("p",{className:"text-sm text-[#a0aec0] leading-relaxed",children:s.bio})]}),e.jsx(bge,{card:s,variant:"luxury"}),e.jsx(wge,{cardId:s.id,variant:"luxury"}),e.jsxs("div",{className:"space-y-1 mb-6",children:[s.show_save_contact&&e.jsxs("button",{onClick:p,className:"w-full flex items-center gap-3 h-12 px-4 rounded-xl text-[#e2e8f0] hover:bg-[#1e2636] transition-colors text-sm",children:[e.jsx(hi,{className:"h-4 w-4 text-[#c9a84c]"})," Save Contact"]}),s.show_leave_review&&s.review_source_url&&e.jsxs("button",{onClick:()=>{Xo(s.id,"button_click","review"),window.open(s.review_source_url,"_blank")},className:"w-full flex items-center gap-3 h-12 px-4 rounded-xl text-[#e2e8f0] hover:bg-[#1e2636] transition-colors text-sm",children:[e.jsx(ya,{className:"h-4 w-4 text-[#c9a84c]"})," Leave a Review"]}),s.show_refer_friend&&e.jsxs("button",{onClick:y,className:"w-full flex items-center gap-3 h-12 px-4 rounded-xl text-[#e2e8f0] hover:bg-[#1e2636] transition-colors text-sm",children:[e.jsx(Ar,{className:"h-4 w-4 text-[#c9a84c]"})," Refer a Friend"]}),e.jsxs("button",{onClick:_,className:"w-full flex items-center gap-3 h-12 px-4 rounded-xl text-[#e2e8f0] hover:bg-[#1e2636] transition-colors text-sm",children:[e.jsx(Vl,{className:"h-4 w-4 text-[#c9a84c]"})," Connect with Me"]}),e.jsxs("button",{onClick:x,className:"w-full flex items-center gap-3 h-12 px-4 rounded-xl text-[#e2e8f0] hover:bg-[#1e2636] transition-colors text-sm",children:[e.jsx(cd,{className:"h-4 w-4 text-[#c9a84c]"})," Share My Card"]})]}),s.show_social_links&&s.social_links&&s.social_links.length>0&&e.jsx("div",{className:"flex justify-center gap-4 mb-8",children:s.social_links.slice(0,3).map((k,T)=>e.jsx("a",{href:k.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>Xo(s.id,"button_click",`social_${k.platform}`),className:"h-10 w-10 rounded-full bg-[#1e2636] border border-[#c9a84c]/20 hover:border-[#c9a84c]/50 flex items-center justify-center text-lg transition-colors",children:b[k.platform.toLowerCase()]||"🔗"},T))}),e.jsx("div",{className:"text-center",children:e.jsx("p",{className:"text-xs text-[#4a5568]",children:"Powered by LevelUp"})})]}),e.jsx(_ge,{open:t,onOpenChange:r,cardId:s.id,type:n,agentName:i})]})}function NLt({card:s}){var T,E,A,D;const[t,r]=S.useState(!1),[n,a]=S.useState("booking"),i=((T=s.profile)==null?void 0:T.name)||"Agent",l=i.split(" ").map(R=>R[0]).join("").toUpperCase().slice(0,2),o={accent:((E=s.bold_theme_colors)==null?void 0:E.accent)||"#ff5722",dark:((A=s.bold_theme_colors)==null?void 0:A.dark)||"#1a1a2e",button:((D=s.bold_theme_colors)==null?void 0:D.button)||"#ff5722"},c=(R,z)=>{const O=parseInt(R.replace("#",""),16),$=Math.max(0,(O>>16)-z),ee=Math.max(0,(O>>8&255)-z),Z=Math.max(0,(O&255)-z);return`#${($<<16|ee<<8|Z).toString(16).padStart(6,"0")}`};c(o.accent,25),c(o.dark,-20),c(o.button,25);const d=(R,z)=>{Xo(s.id,"button_click",R),z()},h=()=>d("call",()=>{var R;(R=s.profile)!=null&&R.phone?window.location.href=`tel:${s.profile.phone}`:he.error("Phone number not available")}),m=()=>d("text",()=>{var R;(R=s.profile)!=null&&R.phone?window.location.href=`sms:${s.profile.phone}`:he.error("Phone number not available")}),p=()=>d("email",()=>{var R;(R=s.profile)!=null&&R.email?window.location.href=`mailto:${s.profile.email}`:he.error("Email not available")}),x=()=>{s.booking_url?d("book",()=>window.open(s.booking_url,"_blank")):(a("booking"),r(!0),Xo(s.id,"button_click","book"))},y=()=>{var R,z;Xo(s.id,"contact_saved"),jge({name:i,phone:(R=s.profile)==null?void 0:R.phone,email:(z=s.profile)==null?void 0:z.email,brokerage:s.brokerage_name,avatarUrl:s.avatar_url,cardUrl:window.location.href})},_=async()=>{Xo(s.id,"share_event");const R=`https://cards.relevelup.com/${s.slug}`,z="Here's my contact card — save it so we can stay in touch.";if(navigator.share)try{await navigator.share({title:`${i}`,text:z,url:R})}catch{}else await navigator.clipboard.writeText(R),he.success("Link copied!")},b=()=>{a("referral"),r(!0),Xo(s.id,"button_click","refer")},j=()=>{a("connect"),r(!0),Xo(s.id,"button_click","connect")},k={instagram:"📸",facebook:"📘",linkedin:"💼",twitter:"🐦",youtube:"🎬",tiktok:"🎵"};return e.jsxs("div",{className:"min-h-screen",style:{backgroundColor:o.accent},children:[e.jsxs("div",{className:"px-5 pt-10 pb-14 text-center relative",style:{backgroundColor:o.dark},children:[s.show_photo&&e.jsxs(Un,{className:"h-28 w-28 mx-auto mb-4 shadow-2xl",style:{boxShadow:`0 0 0 4px ${o.accent}`},children:[e.jsx(Ka,{src:s.avatar_url||void 0,alt:i}),e.jsx(qn,{className:"text-2xl font-black text-white",style:{backgroundColor:o.accent},children:l})]}),e.jsx("h1",{className:"text-3xl font-black text-white tracking-tight mb-0.5",children:i}),s.title&&e.jsx("p",{className:"text-sm font-bold mb-1",style:{color:`${o.accent}cc`},children:s.title}),s.brokerage_name&&!s.brokerage_logo_url&&e.jsx("p",{className:"text-sm font-bold uppercase tracking-wider mb-1",style:{color:o.accent},children:s.brokerage_name}),s.team_name&&!s.team_logo_url&&e.jsx("p",{className:"text-xs font-bold text-white/60 uppercase tracking-wider",children:s.team_name})]}),e.jsxs("div",{className:"max-w-md mx-auto px-5 -mt-6",children:[e.jsxs("div",{className:"bg-white rounded-3xl shadow-2xl px-5 py-8",children:[s.positioning_statement&&e.jsx("p",{className:"text-center font-bold text-lg leading-snug mb-6 max-w-xs mx-auto",style:{color:o.dark},children:s.positioning_statement}),e.jsx("div",{className:"grid grid-cols-3 gap-3 mb-4",children:[{icon:Yn,label:"Call",handler:h},{icon:Gi,label:"Text",handler:m},{icon:er,label:"Email",handler:p}].map(({icon:R,label:z,handler:O})=>e.jsxs("button",{onClick:O,className:"flex flex-col items-center gap-1.5 py-4 text-white rounded-2xl transition-opacity font-bold hover:opacity-85",style:{backgroundColor:o.dark},children:[e.jsx(R,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs",children:z})]},z))}),e.jsxs("button",{onClick:x,className:"w-full h-14 text-base font-black rounded-2xl mb-6 text-white transition-opacity hover:opacity-90 flex items-center justify-center gap-2 uppercase tracking-wide",style:{backgroundColor:o.button},children:[e.jsx(Nn,{className:"h-5 w-5"}),s.custom_cta_label||"Book a Call"]}),s.show_credentials&&s.review_snippet&&e.jsx("div",{className:"flex items-center justify-center gap-5 mb-6",children:s.review_snippet&&e.jsxs("div",{className:"text-center flex items-center gap-1",children:[e.jsx(ya,{className:"h-5 w-5",style:{color:o.accent,fill:o.accent}}),e.jsx("span",{className:"font-black text-2xl",style:{color:o.dark},children:"5.0"})]})}),s.review_snippet&&e.jsx("div",{className:"rounded-2xl p-4 mb-6",style:{backgroundColor:`${o.accent}15`},children:e.jsxs("p",{className:"text-sm font-medium text-center",style:{color:o.dark},children:['"',s.review_snippet,'"']})}),s.show_bio&&s.bio&&e.jsxs("div",{className:"mb-6",children:[e.jsx("h2",{className:"text-xs font-black mb-2 uppercase tracking-wider",style:{color:o.accent},children:"About Me"}),e.jsx("p",{className:"text-sm text-gray-600 leading-relaxed",children:s.bio})]}),e.jsx(bge,{card:s,variant:"bold"}),e.jsx(wge,{cardId:s.id,variant:"bold"}),e.jsxs("div",{className:"space-y-1 mb-6",children:[s.show_save_contact&&e.jsxs("button",{onClick:y,className:"w-full flex items-center gap-3 h-12 px-4 rounded-2xl hover:bg-gray-100 transition-colors text-sm font-bold",style:{color:o.dark},children:[e.jsx(hi,{className:"h-4 w-4",style:{color:o.accent}})," Save Contact"]}),s.show_leave_review&&s.review_source_url&&e.jsxs("button",{onClick:()=>{Xo(s.id,"button_click","review"),window.open(s.review_source_url,"_blank")},className:"w-full flex items-center gap-3 h-12 px-4 rounded-2xl hover:bg-gray-100 transition-colors text-sm font-bold",style:{color:o.dark},children:[e.jsx(ya,{className:"h-4 w-4",style:{color:o.accent}})," Leave a Review"]}),s.show_refer_friend&&e.jsxs("button",{onClick:b,className:"w-full flex items-center gap-3 h-12 px-4 rounded-2xl hover:bg-gray-100 transition-colors text-sm font-bold",style:{color:o.dark},children:[e.jsx(Ar,{className:"h-4 w-4",style:{color:o.accent}})," Refer a Friend"]}),e.jsxs("button",{onClick:j,className:"w-full flex items-center gap-3 h-12 px-4 rounded-2xl hover:bg-gray-100 transition-colors text-sm font-bold",style:{color:o.dark},children:[e.jsx(Vl,{className:"h-4 w-4",style:{color:o.accent}})," Connect with Me"]}),e.jsxs("button",{onClick:_,className:"w-full flex items-center gap-3 h-12 px-4 rounded-2xl hover:bg-gray-100 transition-colors text-sm font-bold",style:{color:o.dark},children:[e.jsx(cd,{className:"h-4 w-4",style:{color:o.accent}})," Share My Card"]})]}),s.show_social_links&&s.social_links&&s.social_links.length>0&&e.jsx("div",{className:"flex justify-center gap-4 mb-6",children:s.social_links.slice(0,3).map((R,z)=>e.jsx("a",{href:R.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>Xo(s.id,"button_click",`social_${R.platform}`),className:"h-10 w-10 rounded-full flex items-center justify-center text-lg transition-opacity hover:opacity-85",style:{backgroundColor:o.dark},children:k[R.platform.toLowerCase()]||"🔗"},z))})]}),e.jsx("div",{className:"text-center py-6",children:e.jsx("p",{className:"text-xs text-white/50",children:"Powered by LevelUp"})})]}),e.jsx(_ge,{open:t,onOpenChange:r,cardId:s.id,type:n,agentName:i})]})}function kLt({card:s}){var j;const[t,r]=S.useState(!1),[n,a]=S.useState("booking"),i=((j=s.profile)==null?void 0:j.name)||"Agent",l=i.split(" ").map(k=>k[0]).join("").toUpperCase().slice(0,2),o=(k,T)=>{Xo(s.id,"button_click",k),T()},c=()=>o("call",()=>{var k;(k=s.profile)!=null&&k.phone?window.location.href=`tel:${s.profile.phone}`:he.error("Phone number not available")}),d=()=>o("text",()=>{var k;(k=s.profile)!=null&&k.phone?window.location.href=`sms:${s.profile.phone}`:he.error("Phone number not available")}),h=()=>o("email",()=>{var k;(k=s.profile)!=null&&k.email?window.location.href=`mailto:${s.profile.email}`:he.error("Email not available")}),m=()=>{s.booking_url?o("book",()=>window.open(s.booking_url,"_blank")):(a("booking"),r(!0),Xo(s.id,"button_click","book"))},p=()=>{var k,T;Xo(s.id,"contact_saved"),jge({name:i,phone:(k=s.profile)==null?void 0:k.phone,email:(T=s.profile)==null?void 0:T.email,brokerage:s.brokerage_name,avatarUrl:s.avatar_url,cardUrl:window.location.href})},x=async()=>{Xo(s.id,"share_event");const k=`https://cards.relevelup.com/${s.slug}`,T="Here's my contact card — save it so we can stay in touch.";if(navigator.share)try{await navigator.share({title:`${i}`,text:T,url:k})}catch{}else await navigator.clipboard.writeText(k),he.success("Link copied!")},y=()=>{a("referral"),r(!0),Xo(s.id,"button_click","refer")},_=()=>{a("connect"),r(!0),Xo(s.id,"button_click","connect")},b={instagram:"📸",facebook:"📘",linkedin:"💼",twitter:"🐦",youtube:"🎬",tiktok:"🎵"};return e.jsxs("div",{className:"min-h-screen bg-[#f5f1eb]",children:[e.jsx("div",{className:"bg-[#1b3a4b] h-2"}),e.jsxs("div",{className:"max-w-md mx-auto px-5 py-10",children:[e.jsxs("div",{className:"text-center mb-8",children:[s.show_photo&&e.jsxs(Un,{className:"h-28 w-28 mx-auto mb-4 ring-4 ring-white shadow-lg",children:[e.jsx(Ka,{src:s.avatar_url||void 0,alt:i}),e.jsx(qn,{className:"text-2xl font-serif bg-[#1b3a4b] text-white",children:l})]}),e.jsx("h1",{className:"text-2xl font-serif font-bold text-[#1b3a4b] mb-0.5",children:i}),s.title&&e.jsx("p",{className:"text-sm font-medium text-[#5a7a6f] mb-1",children:s.title}),s.brokerage_name&&!s.brokerage_logo_url&&e.jsx("p",{className:"text-sm font-medium text-[#5a7a6f] mb-1",children:s.brokerage_name}),s.team_name&&!s.team_logo_url&&e.jsx("p",{className:"text-xs font-medium text-[#a0aec0] mb-3",children:s.team_name}),s.positioning_statement&&e.jsxs("p",{className:"text-base text-[#4a5568] italic leading-relaxed max-w-xs mx-auto font-serif",children:['"',s.positioning_statement,'"']})]}),e.jsx("div",{className:"grid grid-cols-3 gap-3 mb-4",children:[{icon:Yn,label:"Call",handler:c},{icon:Gi,label:"Text",handler:d},{icon:er,label:"Email",handler:h}].map(({icon:k,label:T,handler:E})=>e.jsxs("button",{onClick:E,className:"flex flex-col items-center gap-1.5 py-4 bg-white hover:bg-[#e8e3db] border border-[#d4cfc5] rounded-lg transition-colors shadow-sm",children:[e.jsx(k,{className:"h-5 w-5 text-[#1b3a4b]"}),e.jsx("span",{className:"text-xs font-semibold text-[#1b3a4b]",children:T})]},T))}),e.jsxs("button",{onClick:m,className:"w-full h-12 text-base font-semibold rounded-lg mb-6 bg-[#1b3a4b] hover:bg-[#264d61] text-white transition-colors flex items-center justify-center gap-2 shadow-sm",children:[e.jsx(Nn,{className:"h-5 w-5"}),s.custom_cta_label||"Book a Call"]}),s.show_credentials&&s.review_snippet&&e.jsx("div",{className:"bg-white rounded-lg border border-[#d4cfc5] p-4 mb-6 shadow-sm",children:e.jsx("div",{className:"flex items-center justify-center gap-6",children:e.jsxs("div",{className:"text-center flex items-center gap-1",children:[e.jsx(ya,{className:"h-4 w-4 text-[#d4a843] fill-[#d4a843]"}),e.jsx("span",{className:"font-bold text-[#1b3a4b] font-serif",children:"5.0"})]})})}),s.review_snippet&&e.jsx("div",{className:"bg-white rounded-lg border border-[#d4cfc5] p-4 mb-6 shadow-sm",children:e.jsxs("p",{className:"text-sm text-[#4a5568] italic text-center font-serif",children:['"',s.review_snippet,'"']})}),s.show_bio&&s.bio&&e.jsxs("div",{className:"mb-6",children:[e.jsx("h2",{className:"text-sm font-semibold text-[#1b3a4b] mb-2 font-serif",children:"About"}),e.jsx("p",{className:"text-sm text-[#4a5568] leading-relaxed",children:s.bio})]}),e.jsx(bge,{card:s,variant:"classic"}),e.jsx(wge,{cardId:s.id,variant:"classic"}),e.jsxs("div",{className:"bg-white rounded-lg border border-[#d4cfc5] shadow-sm divide-y divide-[#e8e3db] mb-6",children:[s.show_save_contact&&e.jsxs("button",{onClick:p,className:"w-full flex items-center gap-3 h-12 px-4 text-[#1b3a4b] hover:bg-[#f5f1eb] transition-colors text-sm font-medium",children:[e.jsx(hi,{className:"h-4 w-4 text-[#5a7a6f]"})," Save Contact"]}),s.show_leave_review&&s.review_source_url&&e.jsxs("button",{onClick:()=>{Xo(s.id,"button_click","review"),window.open(s.review_source_url,"_blank")},className:"w-full flex items-center gap-3 h-12 px-4 text-[#1b3a4b] hover:bg-[#f5f1eb] transition-colors text-sm font-medium",children:[e.jsx(ya,{className:"h-4 w-4 text-[#d4a843]"})," Leave a Review"]}),s.show_refer_friend&&e.jsxs("button",{onClick:y,className:"w-full flex items-center gap-3 h-12 px-4 text-[#1b3a4b] hover:bg-[#f5f1eb] transition-colors text-sm font-medium",children:[e.jsx(Ar,{className:"h-4 w-4 text-[#5a7a6f]"})," Refer a Friend"]}),e.jsxs("button",{onClick:_,className:"w-full flex items-center gap-3 h-12 px-4 text-[#1b3a4b] hover:bg-[#f5f1eb] transition-colors text-sm font-medium",children:[e.jsx(Vl,{className:"h-4 w-4 text-[#5a7a6f]"})," Connect with Me"]}),e.jsxs("button",{onClick:x,className:"w-full flex items-center gap-3 h-12 px-4 text-[#1b3a4b] hover:bg-[#f5f1eb] transition-colors text-sm font-medium",children:[e.jsx(cd,{className:"h-4 w-4 text-[#5a7a6f]"})," Share My Card"]})]}),s.show_social_links&&s.social_links&&s.social_links.length>0&&e.jsx("div",{className:"flex justify-center gap-4 mb-8",children:s.social_links.slice(0,3).map((k,T)=>e.jsx("a",{href:k.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>Xo(s.id,"button_click",`social_${k.platform}`),className:"h-10 w-10 rounded-full bg-white border border-[#d4cfc5] hover:bg-[#e8e3db] flex items-center justify-center text-lg transition-colors shadow-sm",children:b[k.platform.toLowerCase()]||"🔗"},T))}),e.jsx("div",{className:"text-center",children:e.jsx("p",{className:"text-xs text-[#a0aec0]",children:"Powered by LevelUp"})})]}),e.jsx(_ge,{open:t,onOpenChange:r,cardId:s.id,type:n,agentName:i})]})}function o5e({card:s}){switch(s.theme){case"luxury":return e.jsx(jLt,{card:s});case"bold":return e.jsx(NLt,{card:s});case"classic":return e.jsx(kLt,{card:s});case"standard":default:return e.jsx(wLt,{card:s})}}function SLt(){const s=Vc();S.useEffect(()=>(document.body.classList.add("agent-card-page"),()=>{document.body.classList.remove("agent-card-page")}),[]);const t=s.pathname.slice(1);return!t||t===""?e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center p-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Agent Cards"}),e.jsx("p",{className:"text-slate-500",children:"Visit a specific agent's card URL to view their digital business card."})]})}):e.jsx(CLt,{slug:t})}function CLt({slug:s}){return e.jsx(TLt,{slug:s})}function TLt({slug:s}){var i;const{data:t,isLoading:r,error:n}=Kst(s);if(S.useEffect(()=>{t!=null&&t.id&&Xo(t.id,"card_view")},[t==null?void 0:t.id]),r)return e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center",children:e.jsxs("div",{className:"w-full max-w-md mx-auto p-6 space-y-6",children:[e.jsxs("div",{className:"flex flex-col items-center gap-4",children:[e.jsx(Ks,{className:"h-28 w-28 rounded-full"}),e.jsx(Ks,{className:"h-6 w-48"}),e.jsx(Ks,{className:"h-4 w-36"})]}),e.jsx(Ks,{className:"h-12 w-full"}),e.jsx(Ks,{className:"h-12 w-full"})]})});if(n||!t)return e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center p-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Card Not Found"}),e.jsx("p",{className:"text-slate-500",children:"This agent card doesn't exist or isn't published yet."})]})});const a=((i=t.profile)==null?void 0:i.name)||"Agent";return e.jsxs(e.Fragment,{children:[e.jsxs(el,{children:[e.jsxs("title",{children:[a," | Real Estate Agent"]}),e.jsx("meta",{name:"description",content:t.positioning_statement||`Connect with ${a}, your trusted real estate professional.`}),e.jsx("meta",{property:"og:title",content:`${a} | Real Estate Agent`}),e.jsx("meta",{property:"og:description",content:t.positioning_statement||`Connect with ${a}`}),t.avatar_url&&e.jsx("meta",{property:"og:image",content:t.avatar_url})]}),e.jsx(o5e,{card:t})]})}function Qst({presentationId:s,ctaLabel:t,agentName:r,prefillName:n,prefillEmail:a,prefillPhone:i}){const[l,o]=S.useState(n||""),[c,d]=S.useState(a||""),[h,m]=S.useState(i||""),[p,x]=S.useState(""),[y,_]=S.useState(""),[b,j]=S.useState(!1),[k,T]=S.useState(!1),E=async A=>{if(A.preventDefault(),!l.trim()){he.error("Please enter your name");return}j(!0);try{const{error:D}=await V.from("smart_presentation_leads").insert({presentation_id:s,name:l.trim(),email:c.trim()||null,phone:h.trim()||null,intent:p||null,message:y.trim()||null});if(D)throw D;try{await V.rpc("log_presentation_view",{p_presentation_id:s,p_section_index:null,p_cta_clicked:!0,p_ip_hash:null,p_user_agent:navigator.userAgent,p_referrer:null})}catch{}V.functions.invoke("presentation-lead-notify",{body:{presentationId:s,name:l.trim(),email:c.trim()||void 0,phone:h.trim()||void 0,intent:p||void 0,message:y.trim()||void 0}}).catch(R=>console.error("Presentation lead notify failed:",R)),T(!0)}catch{he.error("Something went wrong. Please try again.")}finally{j(!1)}};return k?e.jsxs("div",{className:"text-center py-8",children:[e.jsx("div",{className:"w-16 h-16 rounded-full bg-emerald-100 flex items-center justify-center mx-auto mb-4",children:e.jsx(va,{className:"h-8 w-8 text-emerald-600"})}),e.jsx("h3",{className:"text-xl font-semibold text-gray-900 mb-2",children:"Thank you!"}),e.jsx("p",{className:"text-gray-500",children:r?`${r} will be in touch soon.`:"We'll be in touch soon."})]}):e.jsxs("form",{onSubmit:E,className:"space-y-4 max-w-md mx-auto",children:[e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"pres-lead-name",children:"Name *"}),e.jsx(Se,{id:"pres-lead-name",value:l,onChange:A=>o(A.target.value),placeholder:"Your name",required:!0})]}),e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"pres-lead-phone",children:"Phone"}),e.jsx(Se,{id:"pres-lead-phone",type:"tel",value:h,onChange:A=>m(A.target.value),placeholder:"(555) 123-4567"})]}),e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"pres-lead-email",children:"Email"}),e.jsx(Se,{id:"pres-lead-email",type:"email",value:c,onChange:A=>d(A.target.value),placeholder:"you@example.com"})]}),e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"pres-lead-intent",children:"I'm looking to..."}),e.jsxs(Bs,{value:p,onValueChange:x,children:[e.jsx(Os,{children:e.jsx(Us,{placeholder:"Select one"})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"buy",children:"Buy a home"}),e.jsx(pt,{value:"sell",children:"Sell my home"}),e.jsx(pt,{value:"both",children:"Buy & Sell"}),e.jsx(pt,{value:"other",children:"Something else"})]})]})]}),e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"pres-lead-message",children:"Message (optional)"}),e.jsx(Se,{id:"pres-lead-message",value:y,onChange:A=>_(A.target.value),placeholder:"Anything you'd like us to know"})]}),e.jsx(H,{type:"submit",className:"w-full text-lg py-6 rounded-xl bg-blue-600 hover:bg-blue-700 text-white shadow-lg",disabled:b,children:b?"Sending...":t})]})}function ELt(){const s=Vc();S.useEffect(()=>(document.body.classList.add("presentation-page"),()=>{document.body.classList.remove("presentation-page")}),[]);const t=s.pathname.slice(1);return!t||t===""?e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center p-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Smart Presentations"}),e.jsx("p",{className:"text-slate-500",children:"Visit a specific presentation URL to view it."})]})}):e.jsx(ALt,{shareToken:t})}function ALt({shareToken:s}){var y;const[t,r]=S.useState(null),[n,a]=S.useState(!0),[i,l]=S.useState(0),[o,c]=S.useState(!1);S.useEffect(()=>{d()},[s]);const d=async()=>{const{data:_,error:b}=await V.from("smart_presentations").select("*").eq("share_token",s).eq("status","published").single();if(b||!_){c(!0),a(!1);return}const{data:j}=await V.from("profiles").select("name, email, phone, avatar_url, title, brokerage_id").eq("id",_.owner_user_id).single();let k;if(j!=null&&j.brokerage_id){const{data:E}=await V.from("brokerages").select("name").eq("id",j.brokerage_id).single();k=(E==null?void 0:E.name)||void 0}let T=null;if(_.contact_id){const{data:E}=await V.from("innercircle_contacts").select("first_name, last_name, email, phone").eq("id",_.contact_id).single();T=E}r({..._,owner_name:j==null?void 0:j.name,owner_email:j==null?void 0:j.email,owner_phone:j==null?void 0:j.phone,owner_avatar:j==null?void 0:j.avatar_url,owner_title:(j==null?void 0:j.title)||void 0,brokerage_name:k,contact_name:T?[T.first_name,T.last_name].filter(Boolean).join(" "):void 0,contact_email:(T==null?void 0:T.email)||void 0,contact_phone:(T==null?void 0:T.phone)||void 0}),a(!1);try{await V.rpc("log_presentation_view",{p_presentation_id:_.id,p_section_index:0,p_cta_clicked:!1,p_ip_hash:null,p_user_agent:navigator.userAgent,p_referrer:document.referrer||null})}catch{}},h=async()=>{if(t){try{await V.rpc("log_presentation_view",{p_presentation_id:t.id,p_section_index:null,p_cta_clicked:!0,p_ip_hash:null,p_user_agent:navigator.userAgent,p_referrer:null})}catch{}t.cta_url&&window.open(t.cta_url,"_blank")}},m=_=>{const b=_.match(/(?:youtube\.com\/watch\?v=|youtu\.be\/)([a-zA-Z0-9_-]+)/);if(b)return`https://www.youtube.com/embed/${b[1]}?rel=0`;if(_.includes("iframe.mediadelivery.net/play/")){const T=_.replace("/play/","/embed/"),E=T.includes("?")?"&":"?";return`${T}${E}responsive=true`}if(_.includes("iframe.mediadelivery.net")){const T=_.includes("?")?"&":"?";return`${_}${T}responsive=true`}const j=_.match(/loom\.com\/share\/([a-zA-Z0-9]+)/);if(j)return`https://www.loom.com/embed/${j[1]}`;const k=_.match(/video\.bunnycdn\.com\/play\/(\d+)\/([a-f0-9-]+)/);return k?`https://iframe.mediadelivery.net/embed/${k[1]}/${k[2]}?responsive=true`:_};if(n)return e.jsx("div",{className:"min-h-screen bg-white flex items-center justify-center",children:e.jsxs("div",{className:"space-y-4 w-full max-w-2xl px-4",children:[e.jsx(Ks,{className:"h-12 w-3/4 mx-auto"}),e.jsx(Ks,{className:"h-64 w-full"}),e.jsx(Ks,{className:"h-8 w-1/2 mx-auto"})]})});if(o||!t)return e.jsx("div",{className:"min-h-screen bg-white flex items-center justify-center",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold mb-2",children:"Presentation Not Found"}),e.jsx("p",{className:"text-gray-500",children:"This presentation may have been removed or is no longer available."})]})});const p=t.sections.filter(_=>_.is_visible!==!1),x=p[i];return e.jsxs("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white",children:[e.jsx("header",{className:"bg-white border-b border-gray-100 sticky top-0 z-10",children:e.jsx("div",{className:"max-w-5xl mx-auto px-4 py-3 flex items-center justify-end",children:e.jsxs("div",{className:"flex items-center gap-3",children:[t.owner_avatar&&e.jsx("img",{src:t.owner_avatar,alt:t.owner_name||"Agent",className:"h-10 w-10 rounded-full object-cover border border-gray-200"}),e.jsxs("div",{className:"text-right text-sm",children:[e.jsx("p",{className:"font-semibold text-gray-900",children:t.owner_name}),t.owner_title&&e.jsx("p",{className:"text-gray-500 text-xs",children:t.owner_title}),t.brokerage_name&&!t.owner_title&&e.jsx("p",{className:"text-gray-500 text-xs",children:t.brokerage_name})]})]})})}),e.jsxs("main",{className:"max-w-5xl mx-auto px-4 py-8",children:[e.jsxs("div",{className:"text-center mb-8",children:[e.jsx("h1",{className:"text-3xl md:text-4xl font-bold text-gray-900 mb-2",children:t.heading||(t.client_name?`Welcome, ${t.client_name}!`:t.title)}),t.property_address&&e.jsxs("p",{className:"text-lg text-gray-600",children:["Here's the plan for your home at ",e.jsx("strong",{children:t.property_address}),"."]})]}),e.jsxs("div",{className:"grid md:grid-cols-5 gap-8",children:[e.jsxs("div",{className:"md:col-span-3",children:[x!=null&&x.video_url?e.jsx("div",{className:"relative w-full rounded-xl overflow-hidden shadow-lg bg-gray-900",style:{paddingTop:"56.25%"},children:e.jsx("iframe",{src:m(x.video_url),className:"absolute inset-0 w-full h-full border-0",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,loading:"lazy"})}):x!=null&&x.image_url?e.jsx("div",{className:"rounded-xl overflow-hidden shadow-lg",children:e.jsx("img",{src:x.image_url,alt:x.title,className:"w-full h-auto object-cover",loading:"lazy"})}):e.jsxs("div",{className:"aspect-video bg-gradient-to-br from-blue-50 to-slate-100 rounded-xl flex flex-col items-center justify-center shadow-lg",children:[e.jsx("span",{className:"text-5xl mb-3",children:x==null?void 0:x.icon}),e.jsx("h3",{className:"text-xl font-semibold text-gray-800",children:x==null?void 0:x.title}),e.jsx("p",{className:"text-gray-500 mt-1 text-sm",children:x==null?void 0:x.description})]}),(x==null?void 0:x.text)&&e.jsx("div",{className:"mt-4 p-4 bg-white rounded-lg border text-gray-700 text-sm leading-relaxed prose prose-sm max-w-none",dangerouslySetInnerHTML:{__html:x.text}})]}),e.jsx("div",{className:"md:col-span-2 space-y-3",children:p.map((_,b)=>e.jsx("button",{onClick:()=>l(b),className:Ft("w-full text-left p-4 rounded-xl border transition-all",i===b?"border-blue-500 bg-blue-50 shadow-sm":"border-gray-200 bg-white hover:border-blue-200 hover:bg-blue-50/50"),children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsxs("span",{className:"text-blue-600 font-bold text-sm mt-0.5",children:[String(b+1).padStart(2,"0"),"."]}),e.jsxs("div",{children:[e.jsx("span",{className:"mr-2",children:_.icon}),e.jsx("span",{className:"font-semibold text-gray-900",children:_.title}),e.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:_.description})]})]})},b))})]}),e.jsxs("div",{className:"mt-12 max-w-md mx-auto bg-white rounded-2xl border border-gray-200 shadow-sm p-6 text-center",children:[t.owner_avatar&&e.jsx("img",{src:t.owner_avatar,alt:t.owner_name||"Agent",className:"h-20 w-20 rounded-full object-cover mx-auto mb-3 border-2 border-gray-100"}),e.jsx("h3",{className:"text-lg font-bold text-gray-900",children:t.owner_name}),t.owner_title&&e.jsx("p",{className:"text-sm text-gray-500",children:t.owner_title}),t.brokerage_name&&e.jsx("p",{className:"text-sm text-gray-500",children:t.brokerage_name}),e.jsxs("div",{className:"mt-3 flex flex-col items-center gap-1 text-sm text-gray-600",children:[t.owner_phone&&e.jsx("a",{href:`tel:${t.owner_phone}`,className:"hover:text-blue-600 transition-colors",children:t.owner_phone}),t.owner_email&&e.jsx("a",{href:`mailto:${t.owner_email}`,className:"hover:text-blue-600 transition-colors",children:t.owner_email})]})]}),t.cta_label&&e.jsxs("div",{className:"text-center mt-8 py-8",children:[e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-4",children:"Ready to Get Started?"}),(y=t.cta_url)!=null&&y.trim()?e.jsxs(H,{size:"lg",onClick:h,className:"text-lg px-8 py-6 rounded-xl bg-blue-600 hover:bg-blue-700 text-white shadow-lg",children:[t.cta_label,e.jsx(gn,{className:"h-5 w-5 ml-2"})]}):e.jsx("div",{className:"max-w-md mx-auto bg-white rounded-2xl border border-gray-200 shadow-sm p-6",children:e.jsx(Qst,{presentationId:t.id,ctaLabel:t.cta_label,agentName:t.owner_name||void 0,prefillName:t.contact_name,prefillEmail:t.contact_email,prefillPhone:t.contact_phone})})]})]}),e.jsx("footer",{className:"border-t border-gray-100 bg-white mt-12 py-6 text-center text-xs text-gray-400",children:"Powered by LevelUp"})]})}const sv=()=>{const s=ba();return yt({queryKey:["user-team",s],queryFn:async()=>{const{data:t,error:r}=await V.from("team_members").select("id, team_id, role").eq("user_id",s).maybeSingle();if(console.log("[useUserTeam] membership query:",{userId:s,membership:t,error:r}),r)throw r;if(!t)return null;const{data:n,error:a}=await V.from("teams").select("*").eq("id",t.team_id).single();if(a)throw a;return{membershipId:t.id,teamId:t.team_id,role:t.role,team:n}},enabled:!!s,staleTime:5*60*1e3})};function MLt(){const{user:s}=Ms(),t=ba(),{data:r}=sv();return yt({queryKey:["open-houses",t,r==null?void 0:r.teamId,r==null?void 0:r.role],queryFn:async()=>{const{data:n,error:a}=await V.from("open_houses").select("*").eq("agent_id",t).order("event_date",{ascending:!1});if(a)throw a;let i=n||[];if((r==null?void 0:r.role)==="team_leader"&&r.teamId){const{data:l,error:o}=await V.rpc("get_team_open_houses",{_user_id:t});if(!o&&l){const c=[...new Set(l.map(m=>m.agent_id))],d={};if(c.length>0){const{data:m}=await V.from("profiles").select("id, name").in("id",c);m==null||m.forEach(p=>{p.name&&(d[p.id]=p.name)})}const h=l.map(m=>({...m,agent_name:d[m.agent_id]||void 0}));i=[...i,...h]}}return i.sort((l,o)=>o.event_date.localeCompare(l.event_date)),i},enabled:!!s&&!!t})}function EZs(s){const{user:t}=Ms();return yt({queryKey:["open-house",s],queryFn:async()=>{const{data:r,error:n}=await V.from("open_houses").select("*").eq("id",s).single();if(n)throw n;return r},enabled:!!t&&!!s})}function Jst(s){const{user:t}=Ms(),r=ns();return S.useEffect(()=>{if(!s)return;const n=`visitors-${s}-${Math.random().toString(36).slice(2,10)}`,a=V.channel(n).on("postgres_changes",{event:"*",schema:"public",table:"open_house_visitors",filter:`open_house_id=eq.${s}`},()=>{r.invalidateQueries({queryKey:["open-house-visitors",s]}),r.invalidateQueries({queryKey:["open-houses"]})}).subscribe();return()=>{V.removeChannel(a)}},[s,r]),yt({queryKey:["open-house-visitors",s],queryFn:async()=>{const{data:n,error:a}=await V.from("open_house_visitors").select("*").eq("open_house_id",s).order("created_at",{ascending:!1});if(a)throw a;return n},enabled:!!t&&!!s})}function ILt(){const s=ns(),t=ba();return Pt({mutationFn:async r=>{const{data:n,error:a}=await V.from("open_houses").insert({...r,agent_id:t}).select().single();if(a)throw a;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["open-houses"]}),En({title:"Open house created!"})},onError:r=>{En({title:"Error",description:r.message,variant:"destructive"})}})}function ert(){const s=ns();return Pt({mutationFn:async({id:t,...r})=>{const{error:n}=await V.from("open_houses").update(r).eq("id",t);if(n)throw n},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["open-houses"]}),s.invalidateQueries({queryKey:["open-house",r.id]})}})}function PLt(){const s=ns();return Pt({mutationFn:async t=>{const{error:r}=await V.from("open_houses").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["open-houses"]}),En({title:"Open house deleted"})}})}function LLt(s){return yt({queryKey:["public-open-house",s],queryFn:async()=>{const{data:t,error:r}=await V.from("open_houses").select("*, profiles:agent_id(name, avatar_url, title, email, phone)").eq("slug",s).eq("is_active",!0).single();if(r)throw r;let n=null;if(t.agent_id){const{data:a}=await V.from("agent_cards").select("slug").eq("user_id",t.agent_id).eq("is_published",!0).maybeSingle();a&&(n=a.slug)}return{...t,agent_card_slug:n}},enabled:!!s})}function DLt(s){const{user:t}=Ms();return yt({queryKey:["survey-questions",s],queryFn:async()=>{const{data:r,error:n}=await V.from("open_house_survey_questions").select("*").eq("open_house_id",s).order("sort_order");if(n)throw n;return r},enabled:!!t&&!!s})}function RLt(s){return yt({queryKey:["public-survey-questions",s],queryFn:async()=>{const{data:t,error:r}=await V.from("open_house_survey_questions").select("*").eq("open_house_id",s).eq("is_active",!0).order("sort_order");if(r)throw r;return t},enabled:!!s})}function OLt(){return Pt({mutationFn:async s=>{const{error:t}=await V.from("open_house_survey_responses").insert(s);if(t)throw t}})}function FLt(s){const{user:t}=Ms();return yt({queryKey:["survey-responses",s],queryFn:async()=>{const{data:r,error:n}=await V.from("open_house_survey_questions").select("*").eq("open_house_id",s).order("sort_order");if(n)throw n;const a=(r||[]).map(o=>o.id);if(a.length===0)return{questions:[],responses:[]};const{data:i,error:l}=await V.from("open_house_survey_responses").select("*").in("question_id",a).order("created_at",{ascending:!1});if(l)throw l;return{questions:r,responses:i||[]}},enabled:!!t&&!!s})}function BLt(){const s=ns();return Pt({mutationFn:async t=>{const{data:r,error:n}=await V.from("open_house_survey_questions").insert(t).select().single();if(n)throw n;return r},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["survey-questions",r.open_house_id]})}})}function zLt(){const s=ns();return Pt({mutationFn:async({id:t,open_house_id:r,...n})=>{const{error:a}=await V.from("open_house_survey_questions").update(n).eq("id",t);if(a)throw a},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["survey-questions",r.open_house_id]})}})}function $Lt(){const s=ns();return Pt({mutationFn:async({id:t,open_house_id:r})=>{const{error:n}=await V.from("open_house_survey_questions").delete().eq("id",t);if(n)throw n},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["survey-questions",r.open_house_id]})}})}function ULt(){const s=ns();return Pt({mutationFn:async t=>{const{error:r}=await V.rpc("seed_default_survey_questions",{_open_house_id:t});if(r)throw r},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["survey-questions",r]})}})}function qLt(){return Pt({mutationFn:async s=>{const{data:t,error:r}=await V.from("open_house_visitors").insert(s).select("id").single();if(r)throw r;return t}})}function VLt(){return Pt({mutationFn:async({visitor_id:s,...t})=>{const{error:r}=await V.from("open_house_visitors").update(t).eq("id",s);if(r)throw r}})}function HLt(){return Pt({mutationFn:async s=>{await V.rpc("increment_open_house_scan",{_slug:s})}})}async function trt(s){const{data:t,error:r}=await V.from("open_house_rooms").select("*").eq("open_house_id",s).order("sort_order");if(r)throw r;const n=t||[];if(n.length===0)return[];const a=n.map(c=>c.id),{data:i,error:l}=await V.from("open_house_room_media").select("*").in("room_id",a).order("sort_order");if(l)throw l;const o={};return(i||[]).forEach(c=>{var h;const d=c;(o[h=d.room_id]||(o[h]=[])).push(d)}),n.map(c=>({...c,media:o[c.id]||[]}))}function GLt(s){const{user:t}=Ms();return yt({queryKey:["open-house-rooms",s],queryFn:()=>trt(s),enabled:!!t&&!!s})}function WLt(s){return yt({queryKey:["public-open-house-rooms",s],queryFn:()=>trt(s),enabled:!!s})}function KLt(){const s=ns();return Pt({mutationFn:async t=>{const{data:r,error:n}=await V.from("open_house_rooms").insert(t).select().single();if(n)throw n;return r},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["open-house-rooms",r.open_house_id]})}})}function YLt(){const s=ns();return Pt({mutationFn:async({id:t,open_house_id:r,...n})=>{const{error:a}=await V.from("open_house_rooms").update(n).eq("id",t);if(a)throw a},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["open-house-rooms",r.open_house_id]})}})}function ZLt(){const s=ns();return Pt({mutationFn:async({id:t,open_house_id:r})=>{const{error:n}=await V.from("open_house_rooms").delete().eq("id",t);if(n)throw n},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["open-house-rooms",r.open_house_id]})}})}function XLt(){const s=ns();return Pt({mutationFn:async({open_house_id:t,...r})=>{const{data:n,error:a}=await V.from("open_house_room_media").insert(r).select().single();if(a)throw a;return n},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["open-house-rooms",r.open_house_id]})}})}function QLt(){const s=ns();return Pt({mutationFn:async({id:t,open_house_id:r})=>{const{error:n}=await V.from("open_house_room_media").delete().eq("id",t);if(n)throw n},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["open-house-rooms",r.open_house_id]})}})}function JLt(s){const{user:t}=Ms();return yt({queryKey:["open-house-leads",s],queryFn:async()=>{const{data:r,error:n}=await V.from("open_house_leads").select("*").eq("open_house_id",s).order("created_at",{ascending:!1});if(n)throw n;return r||[]},enabled:!!t&&!!s})}function e8t(){const s=ns();return Pt({mutationFn:async({id:t,status:r,open_house_id:n})=>{const{error:a}=await V.from("open_house_leads").update({status:r}).eq("id",t);if(a)throw a;return{open_house_id:n}},onSuccess:t=>{s.invalidateQueries({queryKey:["open-house-leads",t.open_house_id]})}})}var Nge="Switch",[t8t,AZs]=_u(Nge),[s8t,r8t]=t8t(Nge),srt=S.forwardRef((s,t)=>{const{__scopeSwitch:r,name:n,checked:a,defaultChecked:i,required:l,disabled:o,value:c="on",onCheckedChange:d,form:h,...m}=s,[p,x]=S.useState(null),y=_i(t,T=>x(T)),_=S.useRef(!1),b=p?h||!!p.closest("form"):!0,[j,k]=af({prop:a,defaultProp:i??!1,onChange:d,caller:Nge});return e.jsxs(s8t,{scope:r,checked:j,disabled:o,children:[e.jsx(Vn.button,{type:"button",role:"switch","aria-checked":j,"aria-required":l,"data-state":irt(j),"data-disabled":o?"":void 0,disabled:o,value:c,...m,ref:y,onClick:an(s.onClick,T=>{k(E=>!E),b&&(_.current=T.isPropagationStopped(),_.current||T.stopPropagation())})}),b&&e.jsx(art,{control:p,bubbles:!_.current,name:n,value:c,checked:j,required:l,disabled:o,form:h,style:{transform:"translateX(-100%)"}})]})});srt.displayName=Nge;var rrt="SwitchThumb",nrt=S.forwardRef((s,t)=>{const{__scopeSwitch:r,...n}=s,a=r8t(rrt,r);return e.jsx(Vn.span,{"data-state":irt(a.checked),"data-disabled":a.disabled?"":void 0,...n,ref:t})});nrt.displayName=rrt;var n8t="SwitchBubbleInput",art=S.forwardRef(({__scopeSwitch:s,control:t,checked:r,bubbles:n=!0,...a},i)=>{const l=S.useRef(null),o=_i(l,i),c=QB(r),d=FB(t);return S.useEffect(()=>{const h=l.current;if(!h)return;const m=window.HTMLInputElement.prototype,x=Object.getOwnPropertyDescriptor(m,"checked").set;if(c!==r&&x){const y=new Event("click",{bubbles:n});x.call(h,r),h.dispatchEvent(y)}},[c,r,n]),e.jsx("input",{type:"checkbox","aria-hidden":!0,defaultChecked:r,...a,tabIndex:-1,ref:o,style:{...a.style,...d,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})});art.displayName=n8t;function irt(s){return s?"checked":"unchecked"}var ort=srt,a8t=nrt;const Or=S.forwardRef(({className:s,...t},r)=>e.jsx(ort,{className:Ft("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",s),...t,ref:r,children:e.jsx(a8t,{className:Ft("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")})}));Or.displayName=ort.displayName;function Ha(s){const t=Object.prototype.toString.call(s);return s instanceof Date||typeof s=="object"&&t==="[object Date]"?new s.constructor(+s):typeof s=="number"||t==="[object Number]"||typeof s=="string"||t==="[object String]"?new Date(s):new Date(NaN)}function mc(s,t){return s instanceof Date?new s.constructor(t):new Date(t)}function Lc(s,t){const r=Ha(s);return isNaN(t)?mc(s,NaN):(t&&r.setDate(r.getDate()+t),r)}function wg(s,t){const r=Ha(s);if(isNaN(t))return mc(s,NaN);if(!t)return r;const n=r.getDate(),a=mc(s,r.getTime());a.setMonth(r.getMonth()+t+1,0);const i=a.getDate();return n>=i?a:(r.setFullYear(a.getFullYear(),a.getMonth(),n),r)}function lrt(s,t){const r=+Ha(s);return mc(s,r+t)}const l5e=6048e5,i8t=864e5,kge=6e4,JB=36e5,o8t=1e3,qU=43200,qOe=1440;function VOe(s,t){return lrt(s,t*JB)}let l8t={};function zS(){return l8t}function Np(s,t){var o,c,d,h;const r=zS(),n=(t==null?void 0:t.weekStartsOn)??((c=(o=t==null?void 0:t.locale)==null?void 0:o.options)==null?void 0:c.weekStartsOn)??r.weekStartsOn??((h=(d=r.locale)==null?void 0:d.options)==null?void 0:h.weekStartsOn)??0,a=Ha(s),i=a.getDay(),l=(i=a.getTime()?r+1:t.getTime()>=l.getTime()?r:r-1}function jg(s){const t=Ha(s);return t.setHours(0,0,0,0),t}function yS(s){const t=Ha(s),r=new Date(Date.UTC(t.getFullYear(),t.getMonth(),t.getDate(),t.getHours(),t.getMinutes(),t.getSeconds(),t.getMilliseconds()));return r.setUTCFullYear(t.getFullYear()),+s-+r}function l0(s,t){const r=jg(s),n=jg(t),a=+r-yS(r),i=+n-yS(n);return Math.round((a-i)/i8t)}function c8t(s){const t=crt(s),r=mc(s,0);return r.setFullYear(t,0,4),r.setHours(0,0,0,0),oj(r)}function oI(s,t){return lrt(s,t*kge)}function DT(s,t){const r=t*7;return Lc(s,r)}function d8t(s,t){return wg(s,t*12)}function u8t(s){let t;return s.forEach(function(r){const n=Ha(r);(t===void 0||t{const n=Ha(r);(!t||t>n||isNaN(+n))&&(t=n)}),t||new Date(NaN)}function hue(s,t){const r=Ha(s),n=Ha(t),a=r.getTime()-n.getTime();return a<0?-1:a>0?1:a}function c5e(s){return mc(s,Date.now())}function Cc(s,t){const r=jg(s),n=jg(t);return+r==+n}function d5e(s){return s instanceof Date||typeof s=="object"&&Object.prototype.toString.call(s)==="[object Date]"}function eNe(s){if(!d5e(s)&&typeof s!="number")return!1;const t=Ha(s);return!isNaN(Number(t))}function ZP(s,t){const r=Ha(s),n=Ha(t),a=r.getFullYear()-n.getFullYear(),i=r.getMonth()-n.getMonth();return a*12+i}function m8t(s,t,r){const n=Np(s,r),a=Np(t,r),i=+n-yS(n),l=+a-yS(a);return Math.round((i-l)/l5e)}function Jy(s,t){const r=Ha(s),n=Ha(t),a=HOe(r,n),i=Math.abs(l0(r,n));r.setDate(r.getDate()-a*i);const l=+(HOe(r,n)===-a),o=a*(i-l);return o===0?0:o}function HOe(s,t){const r=s.getFullYear()-t.getFullYear()||s.getMonth()-t.getMonth()||s.getDate()-t.getDate()||s.getHours()-t.getHours()||s.getMinutes()-t.getMinutes()||s.getSeconds()-t.getSeconds()||s.getMilliseconds()-t.getMilliseconds();return r<0?-1:r>0?1:r}function drt(s){return t=>{const r=Math.trunc,n=r(t);return n===0?0:n}}function urt(s,t){return+Ha(s)-+Ha(t)}function f8t(s,t,r){const n=urt(s,t)/JB;return drt()(n)}function p8t(s){const t=Ha(s);return t.setHours(23,59,59,999),t}function Ny(s){const t=Ha(s),r=t.getMonth();return t.setFullYear(t.getFullYear(),r+1,0),t.setHours(23,59,59,999),t}function g8t(s){const t=Ha(s);return+p8t(t)==+Ny(t)}function x8t(s,t){const r=Ha(s),n=Ha(t),a=hue(r,n),i=Math.abs(ZP(r,n));let l;if(i<1)l=0;else{r.getMonth()===1&&r.getDate()>27&&r.setDate(30),r.setMonth(r.getMonth()-a*i);let o=hue(r,n)===-a;g8t(Ha(s))&&i===1&&hue(s,n)===1&&(o=!1),l=a*(i-Number(o))}return l===0?0:l}function y8t(s,t,r){const n=urt(s,t)/1e3;return drt()(n)}function v8t(s,t){const r=Ha(s.start),n=Ha(s.end);let a=+r>+n;const i=a?+r:+n,l=a?n:r;l.setHours(0,0,0,0);let o=1;const c=[];for(;+l<=i;)c.push(Ha(l)),l.setDate(l.getDate()+o),l.setHours(0,0,0,0);return a?c.reverse():c}function Gd(s){const t=Ha(s);return t.setDate(1),t.setHours(0,0,0,0),t}function hrt(s){const t=Ha(s),r=mc(s,0);return r.setFullYear(t.getFullYear(),0,1),r.setHours(0,0,0,0),r}function Sge(s,t){var o,c,d,h;const r=zS(),n=(t==null?void 0:t.weekStartsOn)??((c=(o=t==null?void 0:t.locale)==null?void 0:o.options)==null?void 0:c.weekStartsOn)??r.weekStartsOn??((h=(d=r.locale)==null?void 0:d.options)==null?void 0:h.weekStartsOn)??0,a=Ha(s),i=a.getDay(),l=(i{let n;const a=b8t[s];return typeof a=="string"?n=a:t===1?n=a.one:n=a.other.replace("{{count}}",t.toString()),r!=null&&r.addSuffix?r.comparison&&r.comparison>0?"in "+n:n+" ago":n};function rbe(s){return(t={})=>{const r=t.width?String(t.width):s.defaultWidth;return s.formats[r]||s.formats[s.defaultWidth]}}const w8t={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},j8t={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},N8t={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},k8t={date:rbe({formats:w8t,defaultWidth:"full"}),time:rbe({formats:j8t,defaultWidth:"full"}),dateTime:rbe({formats:N8t,defaultWidth:"full"})},S8t={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},C8t=(s,t,r,n)=>S8t[s];function kR(s){return(t,r)=>{const n=r!=null&&r.context?String(r.context):"standalone";let a;if(n==="formatting"&&s.formattingValues){const l=s.defaultFormattingWidth||s.defaultWidth,o=r!=null&&r.width?String(r.width):l;a=s.formattingValues[o]||s.formattingValues[l]}else{const l=s.defaultWidth,o=r!=null&&r.width?String(r.width):s.defaultWidth;a=s.values[o]||s.values[l]}const i=s.argumentCallback?s.argumentCallback(t):t;return a[i]}}const T8t={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},E8t={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},A8t={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"]},M8t={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"]},I8t={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"}},P8t={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"}},L8t=(s,t)=>{const r=Number(s),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"},D8t={ordinalNumber:L8t,era:kR({values:T8t,defaultWidth:"wide"}),quarter:kR({values:E8t,defaultWidth:"wide",argumentCallback:s=>s-1}),month:kR({values:A8t,defaultWidth:"wide"}),day:kR({values:M8t,defaultWidth:"wide"}),dayPeriod:kR({values:I8t,defaultWidth:"wide",formattingValues:P8t,defaultFormattingWidth:"wide"})};function SR(s){return(t,r={})=>{const n=r.width,a=n&&s.matchPatterns[n]||s.matchPatterns[s.defaultMatchWidth],i=t.match(a);if(!i)return null;const l=i[0],o=n&&s.parsePatterns[n]||s.parsePatterns[s.defaultParseWidth],c=Array.isArray(o)?O8t(o,m=>m.test(l)):R8t(o,m=>m.test(l));let d;d=s.valueCallback?s.valueCallback(c):c,d=r.valueCallback?r.valueCallback(d):d;const h=t.slice(l.length);return{value:d,rest:h}}}function R8t(s,t){for(const r in s)if(Object.prototype.hasOwnProperty.call(s,r)&&t(s[r]))return r}function O8t(s,t){for(let r=0;r{const n=t.match(s.matchPattern);if(!n)return null;const a=n[0],i=t.match(s.parsePattern);if(!i)return null;let l=s.valueCallback?s.valueCallback(i[0]):i[0];l=r.valueCallback?r.valueCallback(l):l;const o=t.slice(a.length);return{value:l,rest:o}}}const B8t=/^(\d+)(th|st|nd|rd)?/i,z8t=/\d+/i,$8t={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},U8t={any:[/^b/i,/^(a|c)/i]},q8t={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},V8t={any:[/1/i,/2/i,/3/i,/4/i]},H8t={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},G8t={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]},W8t={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},K8t={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]},Y8t={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},Z8t={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}},X8t={ordinalNumber:F8t({matchPattern:B8t,parsePattern:z8t,valueCallback:s=>parseInt(s,10)}),era:SR({matchPatterns:$8t,defaultMatchWidth:"wide",parsePatterns:U8t,defaultParseWidth:"any"}),quarter:SR({matchPatterns:q8t,defaultMatchWidth:"wide",parsePatterns:V8t,defaultParseWidth:"any",valueCallback:s=>s+1}),month:SR({matchPatterns:H8t,defaultMatchWidth:"wide",parsePatterns:G8t,defaultParseWidth:"any"}),day:SR({matchPatterns:W8t,defaultMatchWidth:"wide",parsePatterns:K8t,defaultParseWidth:"any"}),dayPeriod:SR({matchPatterns:Y8t,defaultMatchWidth:"any",parsePatterns:Z8t,defaultParseWidth:"any"})},Cge={code:"en-US",formatDistance:_8t,formatLong:k8t,formatRelative:C8t,localize:D8t,match:X8t,options:{weekStartsOn:0,firstWeekContainsDate:1}};function Q8t(s){const t=Ha(s);return l0(t,hrt(t))+1}function u5e(s){const t=Ha(s),r=+oj(t)-+c8t(t);return Math.round(r/l5e)+1}function h5e(s,t){var h,m,p,x;const r=Ha(s),n=r.getFullYear(),a=zS(),i=(t==null?void 0:t.firstWeekContainsDate)??((m=(h=t==null?void 0:t.locale)==null?void 0:h.options)==null?void 0:m.firstWeekContainsDate)??a.firstWeekContainsDate??((x=(p=a.locale)==null?void 0:p.options)==null?void 0:x.firstWeekContainsDate)??1,l=mc(s,0);l.setFullYear(n+1,0,i),l.setHours(0,0,0,0);const o=Np(l,t),c=mc(s,0);c.setFullYear(n,0,i),c.setHours(0,0,0,0);const d=Np(c,t);return r.getTime()>=o.getTime()?n+1:r.getTime()>=d.getTime()?n:n-1}function J8t(s,t){var o,c,d,h;const r=zS(),n=(t==null?void 0:t.firstWeekContainsDate)??((c=(o=t==null?void 0:t.locale)==null?void 0:o.options)==null?void 0:c.firstWeekContainsDate)??r.firstWeekContainsDate??((h=(d=r.locale)==null?void 0:d.options)==null?void 0:h.firstWeekContainsDate)??1,a=h5e(s,t),i=mc(s,0);return i.setFullYear(a,0,n),i.setHours(0,0,0,0),Np(i,t)}function m5e(s,t){const r=Ha(s),n=+Np(r,t)-+J8t(r,t);return Math.round(n/l5e)+1}function uc(s,t){const r=s<0?"-":"",n=Math.abs(s).toString().padStart(t,"0");return r+n}const vN={y(s,t){const r=s.getFullYear(),n=r>0?r:1-r;return uc(t==="yy"?n%100:n,t.length)},M(s,t){const r=s.getMonth();return t==="M"?String(r+1):uc(r+1,2)},d(s,t){return uc(s.getDate(),t.length)},a(s,t){const r=s.getHours()/12>=1?"pm":"am";switch(t){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(s,t){return uc(s.getHours()%12||12,t.length)},H(s,t){return uc(s.getHours(),t.length)},m(s,t){return uc(s.getMinutes(),t.length)},s(s,t){return uc(s.getSeconds(),t.length)},S(s,t){const r=t.length,n=s.getMilliseconds(),a=Math.trunc(n*Math.pow(10,r-3));return uc(a,t.length)}},u6={am:"am",pm:"pm",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},GOe={G:function(s,t,r){const n=s.getFullYear()>0?1:0;switch(t){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(s,t,r){if(t==="yo"){const n=s.getFullYear(),a=n>0?n:1-n;return r.ordinalNumber(a,{unit:"year"})}return vN.y(s,t)},Y:function(s,t,r,n){const a=h5e(s,n),i=a>0?a:1-a;if(t==="YY"){const l=i%100;return uc(l,2)}return t==="Yo"?r.ordinalNumber(i,{unit:"year"}):uc(i,t.length)},R:function(s,t){const r=crt(s);return uc(r,t.length)},u:function(s,t){const r=s.getFullYear();return uc(r,t.length)},Q:function(s,t,r){const n=Math.ceil((s.getMonth()+1)/3);switch(t){case"Q":return String(n);case"QQ":return uc(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(s,t,r){const n=Math.ceil((s.getMonth()+1)/3);switch(t){case"q":return String(n);case"qq":return uc(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(s,t,r){const n=s.getMonth();switch(t){case"M":case"MM":return vN.M(s,t);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(s,t,r){const n=s.getMonth();switch(t){case"L":return String(n+1);case"LL":return uc(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(s,t,r,n){const a=m5e(s,n);return t==="wo"?r.ordinalNumber(a,{unit:"week"}):uc(a,t.length)},I:function(s,t,r){const n=u5e(s);return t==="Io"?r.ordinalNumber(n,{unit:"week"}):uc(n,t.length)},d:function(s,t,r){return t==="do"?r.ordinalNumber(s.getDate(),{unit:"date"}):vN.d(s,t)},D:function(s,t,r){const n=Q8t(s);return t==="Do"?r.ordinalNumber(n,{unit:"dayOfYear"}):uc(n,t.length)},E:function(s,t,r){const n=s.getDay();switch(t){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(s,t,r,n){const a=s.getDay(),i=(a-n.weekStartsOn+8)%7||7;switch(t){case"e":return String(i);case"ee":return uc(i,2);case"eo":return r.ordinalNumber(i,{unit:"day"});case"eee":return r.day(a,{width:"abbreviated",context:"formatting"});case"eeeee":return r.day(a,{width:"narrow",context:"formatting"});case"eeeeee":return r.day(a,{width:"short",context:"formatting"});case"eeee":default:return r.day(a,{width:"wide",context:"formatting"})}},c:function(s,t,r,n){const a=s.getDay(),i=(a-n.weekStartsOn+8)%7||7;switch(t){case"c":return String(i);case"cc":return uc(i,t.length);case"co":return r.ordinalNumber(i,{unit:"day"});case"ccc":return r.day(a,{width:"abbreviated",context:"standalone"});case"ccccc":return r.day(a,{width:"narrow",context:"standalone"});case"cccccc":return r.day(a,{width:"short",context:"standalone"});case"cccc":default:return r.day(a,{width:"wide",context:"standalone"})}},i:function(s,t,r){const n=s.getDay(),a=n===0?7:n;switch(t){case"i":return String(a);case"ii":return uc(a,t.length);case"io":return r.ordinalNumber(a,{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(s,t,r){const a=s.getHours()/12>=1?"pm":"am";switch(t){case"a":case"aa":return r.dayPeriod(a,{width:"abbreviated",context:"formatting"});case"aaa":return r.dayPeriod(a,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return r.dayPeriod(a,{width:"narrow",context:"formatting"});case"aaaa":default:return r.dayPeriod(a,{width:"wide",context:"formatting"})}},b:function(s,t,r){const n=s.getHours();let a;switch(n===12?a=u6.noon:n===0?a=u6.midnight:a=n/12>=1?"pm":"am",t){case"b":case"bb":return r.dayPeriod(a,{width:"abbreviated",context:"formatting"});case"bbb":return r.dayPeriod(a,{width:"abbreviated",context:"formatting"}).toLowerCase();case"bbbbb":return r.dayPeriod(a,{width:"narrow",context:"formatting"});case"bbbb":default:return r.dayPeriod(a,{width:"wide",context:"formatting"})}},B:function(s,t,r){const n=s.getHours();let a;switch(n>=17?a=u6.evening:n>=12?a=u6.afternoon:n>=4?a=u6.morning:a=u6.night,t){case"B":case"BB":case"BBB":return r.dayPeriod(a,{width:"abbreviated",context:"formatting"});case"BBBBB":return r.dayPeriod(a,{width:"narrow",context:"formatting"});case"BBBB":default:return r.dayPeriod(a,{width:"wide",context:"formatting"})}},h:function(s,t,r){if(t==="ho"){let n=s.getHours()%12;return n===0&&(n=12),r.ordinalNumber(n,{unit:"hour"})}return vN.h(s,t)},H:function(s,t,r){return t==="Ho"?r.ordinalNumber(s.getHours(),{unit:"hour"}):vN.H(s,t)},K:function(s,t,r){const n=s.getHours()%12;return t==="Ko"?r.ordinalNumber(n,{unit:"hour"}):uc(n,t.length)},k:function(s,t,r){let n=s.getHours();return n===0&&(n=24),t==="ko"?r.ordinalNumber(n,{unit:"hour"}):uc(n,t.length)},m:function(s,t,r){return t==="mo"?r.ordinalNumber(s.getMinutes(),{unit:"minute"}):vN.m(s,t)},s:function(s,t,r){return t==="so"?r.ordinalNumber(s.getSeconds(),{unit:"second"}):vN.s(s,t)},S:function(s,t){return vN.S(s,t)},X:function(s,t,r){const n=s.getTimezoneOffset();if(n===0)return"Z";switch(t){case"X":return KOe(n);case"XXXX":case"XX":return _T(n);case"XXXXX":case"XXX":default:return _T(n,":")}},x:function(s,t,r){const n=s.getTimezoneOffset();switch(t){case"x":return KOe(n);case"xxxx":case"xx":return _T(n);case"xxxxx":case"xxx":default:return _T(n,":")}},O:function(s,t,r){const n=s.getTimezoneOffset();switch(t){case"O":case"OO":case"OOO":return"GMT"+WOe(n,":");case"OOOO":default:return"GMT"+_T(n,":")}},z:function(s,t,r){const n=s.getTimezoneOffset();switch(t){case"z":case"zz":case"zzz":return"GMT"+WOe(n,":");case"zzzz":default:return"GMT"+_T(n,":")}},t:function(s,t,r){const n=Math.trunc(s.getTime()/1e3);return uc(n,t.length)},T:function(s,t,r){const n=s.getTime();return uc(n,t.length)}};function WOe(s,t=""){const r=s>0?"-":"+",n=Math.abs(s),a=Math.trunc(n/60),i=n%60;return i===0?r+String(a):r+String(a)+t+uc(i,2)}function KOe(s,t){return s%60===0?(s>0?"-":"+")+uc(Math.abs(s)/60,2):_T(s,t)}function _T(s,t=""){const r=s>0?"-":"+",n=Math.abs(s),a=uc(Math.trunc(n/60),2),i=uc(n%60,2);return r+a+t+i}const YOe=(s,t)=>{switch(s){case"P":return t.date({width:"short"});case"PP":return t.date({width:"medium"});case"PPP":return t.date({width:"long"});case"PPPP":default:return t.date({width:"full"})}},frt=(s,t)=>{switch(s){case"p":return t.time({width:"short"});case"pp":return t.time({width:"medium"});case"ppp":return t.time({width:"long"});case"pppp":default:return t.time({width:"full"})}},eDt=(s,t)=>{const r=s.match(/(P+)(p+)?/)||[],n=r[1],a=r[2];if(!a)return YOe(s,t);let i;switch(n){case"P":i=t.dateTime({width:"short"});break;case"PP":i=t.dateTime({width:"medium"});break;case"PPP":i=t.dateTime({width:"long"});break;case"PPPP":default:i=t.dateTime({width:"full"});break}return i.replace("{{date}}",YOe(n,t)).replace("{{time}}",frt(a,t))},tNe={p:frt,P:eDt},tDt=/^D+$/,sDt=/^Y+$/,rDt=["D","DD","YY","YYYY"];function prt(s){return tDt.test(s)}function grt(s){return sDt.test(s)}function sNe(s,t,r){const n=nDt(s,t,r);if(console.warn(n),rDt.includes(s))throw new RangeError(n)}function nDt(s,t,r){const n=s[0]==="Y"?"years":"days of the month";return`Use \`${s.toLowerCase()}\` instead of \`${s}\` (in \`${t}\`) for formatting ${n} to the input \`${r}\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`}const aDt=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,iDt=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,oDt=/^'([^]*?)'?$/,lDt=/''/g,cDt=/[a-zA-Z]/;function As(s,t,r){var h,m,p,x,y,_,b,j;const n=zS(),a=(r==null?void 0:r.locale)??n.locale??Cge,i=(r==null?void 0:r.firstWeekContainsDate)??((m=(h=r==null?void 0:r.locale)==null?void 0:h.options)==null?void 0:m.firstWeekContainsDate)??n.firstWeekContainsDate??((x=(p=n.locale)==null?void 0:p.options)==null?void 0:x.firstWeekContainsDate)??1,l=(r==null?void 0:r.weekStartsOn)??((_=(y=r==null?void 0:r.locale)==null?void 0:y.options)==null?void 0:_.weekStartsOn)??n.weekStartsOn??((j=(b=n.locale)==null?void 0:b.options)==null?void 0:j.weekStartsOn)??0,o=Ha(s);if(!eNe(o))throw new RangeError("Invalid time value");let c=t.match(iDt).map(k=>{const T=k[0];if(T==="p"||T==="P"){const E=tNe[T];return E(k,a.formatLong)}return k}).join("").match(aDt).map(k=>{if(k==="''")return{isToken:!1,value:"'"};const T=k[0];if(T==="'")return{isToken:!1,value:dDt(k)};if(GOe[T])return{isToken:!0,value:k};if(T.match(cDt))throw new RangeError("Format string contains an unescaped latin alphabet character `"+T+"`");return{isToken:!1,value:k}});a.localize.preprocessor&&(c=a.localize.preprocessor(o,c));const d={firstWeekContainsDate:i,weekStartsOn:l,locale:a};return c.map(k=>{if(!k.isToken)return k.value;const T=k.value;(!(r!=null&&r.useAdditionalWeekYearTokens)&&grt(T)||!(r!=null&&r.useAdditionalDayOfYearTokens)&&prt(T))&&sNe(T,t,String(s));const E=GOe[T[0]];return E(o,T,a.localize,d)}).join("")}function dDt(s){const t=s.match(oDt);return t?t[1].replace(lDt,"'"):s}function uDt(s,t,r){const n=zS(),a=(r==null?void 0:r.locale)??n.locale??Cge,i=2520,l=hue(s,t);if(isNaN(l))throw new RangeError("Invalid time value");const o=Object.assign({},r,{addSuffix:r==null?void 0:r.addSuffix,comparison:l});let c,d;l>0?(c=Ha(t),d=Ha(s)):(c=Ha(s),d=Ha(t));const h=y8t(d,c),m=(yS(d)-yS(c))/1e3,p=Math.round((h-m)/60);let x;if(p<2)return r!=null&&r.includeSeconds?h<5?a.formatDistance("lessThanXSeconds",5,o):h<10?a.formatDistance("lessThanXSeconds",10,o):h<20?a.formatDistance("lessThanXSeconds",20,o):h<40?a.formatDistance("halfAMinute",0,o):h<60?a.formatDistance("lessThanXMinutes",1,o):a.formatDistance("xMinutes",1,o):p===0?a.formatDistance("lessThanXMinutes",1,o):a.formatDistance("xMinutes",p,o);if(p<45)return a.formatDistance("xMinutes",p,o);if(p<90)return a.formatDistance("aboutXHours",1,o);if(pn.getTime()}function fA(s,t){const r=Ha(s),n=Ha(t);return+r<+n}function yDt(s){return+Ha(s)>Date.now()}function vDt(s,t){const r=t instanceof Date?mc(t,0):new t(0);return r.setFullYear(s.getFullYear(),s.getMonth(),s.getDate()),r.setHours(s.getHours(),s.getMinutes(),s.getSeconds(),s.getMilliseconds()),r}const bDt=10;class xrt{constructor(){ga(this,"subPriority",0)}validate(t,r){return!0}}class _Dt extends xrt{constructor(t,r,n,a,i){super(),this.value=t,this.validateValue=r,this.setValue=n,this.priority=a,i&&(this.subPriority=i)}validate(t,r){return this.validateValue(t,this.value,r)}set(t,r,n){return this.setValue(t,r,this.value,n)}}class wDt extends xrt{constructor(){super(...arguments);ga(this,"priority",bDt);ga(this,"subPriority",-1)}set(r,n){return n.timestampIsSet?r:mc(r,vDt(r,Date))}}class ec{run(t,r,n,a){const i=this.parse(t,r,n,a);return i?{setter:new _Dt(i.value,this.validate,this.set,this.priority,this.subPriority),rest:i.rest}:null}validate(t,r,n){return!0}}class jDt extends ec{constructor(){super(...arguments);ga(this,"priority",140);ga(this,"incompatibleTokens",["R","u","t","T"])}parse(r,n,a){switch(n){case"G":case"GG":case"GGG":return a.era(r,{width:"abbreviated"})||a.era(r,{width:"narrow"});case"GGGGG":return a.era(r,{width:"narrow"});case"GGGG":default:return a.era(r,{width:"wide"})||a.era(r,{width:"abbreviated"})||a.era(r,{width:"narrow"})}}set(r,n,a){return n.era=a,r.setFullYear(a,0,1),r.setHours(0,0,0,0),r}}const hh={month:/^(1[0-2]|0?\d)/,date:/^(3[0-1]|[0-2]?\d)/,dayOfYear:/^(36[0-6]|3[0-5]\d|[0-2]?\d?\d)/,week:/^(5[0-3]|[0-4]?\d)/,hour23h:/^(2[0-3]|[0-1]?\d)/,hour24h:/^(2[0-4]|[0-1]?\d)/,hour11h:/^(1[0-1]|0?\d)/,hour12h:/^(1[0-2]|0?\d)/,minute:/^[0-5]?\d/,second:/^[0-5]?\d/,singleDigit:/^\d/,twoDigits:/^\d{1,2}/,threeDigits:/^\d{1,3}/,fourDigits:/^\d{1,4}/,anyDigitsSigned:/^-?\d+/,singleDigitSigned:/^-?\d/,twoDigitsSigned:/^-?\d{1,2}/,threeDigitsSigned:/^-?\d{1,3}/,fourDigitsSigned:/^-?\d{1,4}/},Qb={basicOptionalMinutes:/^([+-])(\d{2})(\d{2})?|Z/,basic:/^([+-])(\d{2})(\d{2})|Z/,basicOptionalSeconds:/^([+-])(\d{2})(\d{2})((\d{2}))?|Z/,extended:/^([+-])(\d{2}):(\d{2})|Z/,extendedOptionalSeconds:/^([+-])(\d{2}):(\d{2})(:(\d{2}))?|Z/};function mh(s,t){return s&&{value:t(s.value),rest:s.rest}}function mu(s,t){const r=t.match(s);return r?{value:parseInt(r[0],10),rest:t.slice(r[0].length)}:null}function Jb(s,t){const r=t.match(s);if(!r)return null;if(r[0]==="Z")return{value:0,rest:t.slice(1)};const n=r[1]==="+"?1:-1,a=r[2]?parseInt(r[2],10):0,i=r[3]?parseInt(r[3],10):0,l=r[5]?parseInt(r[5],10):0;return{value:n*(a*JB+i*kge+l*o8t),rest:t.slice(r[0].length)}}function yrt(s){return mu(hh.anyDigitsSigned,s)}function Yu(s,t){switch(s){case 1:return mu(hh.singleDigit,t);case 2:return mu(hh.twoDigits,t);case 3:return mu(hh.threeDigits,t);case 4:return mu(hh.fourDigits,t);default:return mu(new RegExp("^\\d{1,"+s+"}"),t)}}function Phe(s,t){switch(s){case 1:return mu(hh.singleDigitSigned,t);case 2:return mu(hh.twoDigitsSigned,t);case 3:return mu(hh.threeDigitsSigned,t);case 4:return mu(hh.fourDigitsSigned,t);default:return mu(new RegExp("^-?\\d{1,"+s+"}"),t)}}function f5e(s){switch(s){case"morning":return 4;case"evening":return 17;case"pm":case"noon":case"afternoon":return 12;case"am":case"midnight":case"night":default:return 0}}function vrt(s,t){const r=t>0,n=r?t:1-t;let a;if(n<=50)a=s||100;else{const i=n+50,l=Math.trunc(i/100)*100,o=s>=i%100;a=s+l-(o?100:0)}return r?a:1-a}function brt(s){return s%400===0||s%4===0&&s%100!==0}class NDt extends ec{constructor(){super(...arguments);ga(this,"priority",130);ga(this,"incompatibleTokens",["Y","R","u","w","I","i","e","c","t","T"])}parse(r,n,a){const i=l=>({year:l,isTwoDigitYear:n==="yy"});switch(n){case"y":return mh(Yu(4,r),i);case"yo":return mh(a.ordinalNumber(r,{unit:"year"}),i);default:return mh(Yu(n.length,r),i)}}validate(r,n){return n.isTwoDigitYear||n.year>0}set(r,n,a){const i=r.getFullYear();if(a.isTwoDigitYear){const o=vrt(a.year,i);return r.setFullYear(o,0,1),r.setHours(0,0,0,0),r}const l=!("era"in n)||n.era===1?a.year:1-a.year;return r.setFullYear(l,0,1),r.setHours(0,0,0,0),r}}class kDt extends ec{constructor(){super(...arguments);ga(this,"priority",130);ga(this,"incompatibleTokens",["y","R","u","Q","q","M","L","I","d","D","i","t","T"])}parse(r,n,a){const i=l=>({year:l,isTwoDigitYear:n==="YY"});switch(n){case"Y":return mh(Yu(4,r),i);case"Yo":return mh(a.ordinalNumber(r,{unit:"year"}),i);default:return mh(Yu(n.length,r),i)}}validate(r,n){return n.isTwoDigitYear||n.year>0}set(r,n,a,i){const l=h5e(r,i);if(a.isTwoDigitYear){const c=vrt(a.year,l);return r.setFullYear(c,0,i.firstWeekContainsDate),r.setHours(0,0,0,0),Np(r,i)}const o=!("era"in n)||n.era===1?a.year:1-a.year;return r.setFullYear(o,0,i.firstWeekContainsDate),r.setHours(0,0,0,0),Np(r,i)}}class SDt extends ec{constructor(){super(...arguments);ga(this,"priority",130);ga(this,"incompatibleTokens",["G","y","Y","u","Q","q","M","L","w","d","D","e","c","t","T"])}parse(r,n){return Phe(n==="R"?4:n.length,r)}set(r,n,a){const i=mc(r,0);return i.setFullYear(a,0,4),i.setHours(0,0,0,0),oj(i)}}class CDt extends ec{constructor(){super(...arguments);ga(this,"priority",130);ga(this,"incompatibleTokens",["G","y","Y","R","w","I","i","e","c","t","T"])}parse(r,n){return Phe(n==="u"?4:n.length,r)}set(r,n,a){return r.setFullYear(a,0,1),r.setHours(0,0,0,0),r}}class TDt extends ec{constructor(){super(...arguments);ga(this,"priority",120);ga(this,"incompatibleTokens",["Y","R","q","M","L","w","I","d","D","i","e","c","t","T"])}parse(r,n,a){switch(n){case"Q":case"QQ":return Yu(n.length,r);case"Qo":return a.ordinalNumber(r,{unit:"quarter"});case"QQQ":return a.quarter(r,{width:"abbreviated",context:"formatting"})||a.quarter(r,{width:"narrow",context:"formatting"});case"QQQQQ":return a.quarter(r,{width:"narrow",context:"formatting"});case"QQQQ":default:return a.quarter(r,{width:"wide",context:"formatting"})||a.quarter(r,{width:"abbreviated",context:"formatting"})||a.quarter(r,{width:"narrow",context:"formatting"})}}validate(r,n){return n>=1&&n<=4}set(r,n,a){return r.setMonth((a-1)*3,1),r.setHours(0,0,0,0),r}}class EDt extends ec{constructor(){super(...arguments);ga(this,"priority",120);ga(this,"incompatibleTokens",["Y","R","Q","M","L","w","I","d","D","i","e","c","t","T"])}parse(r,n,a){switch(n){case"q":case"qq":return Yu(n.length,r);case"qo":return a.ordinalNumber(r,{unit:"quarter"});case"qqq":return a.quarter(r,{width:"abbreviated",context:"standalone"})||a.quarter(r,{width:"narrow",context:"standalone"});case"qqqqq":return a.quarter(r,{width:"narrow",context:"standalone"});case"qqqq":default:return a.quarter(r,{width:"wide",context:"standalone"})||a.quarter(r,{width:"abbreviated",context:"standalone"})||a.quarter(r,{width:"narrow",context:"standalone"})}}validate(r,n){return n>=1&&n<=4}set(r,n,a){return r.setMonth((a-1)*3,1),r.setHours(0,0,0,0),r}}class ADt extends ec{constructor(){super(...arguments);ga(this,"incompatibleTokens",["Y","R","q","Q","L","w","I","D","i","e","c","t","T"]);ga(this,"priority",110)}parse(r,n,a){const i=l=>l-1;switch(n){case"M":return mh(mu(hh.month,r),i);case"MM":return mh(Yu(2,r),i);case"Mo":return mh(a.ordinalNumber(r,{unit:"month"}),i);case"MMM":return a.month(r,{width:"abbreviated",context:"formatting"})||a.month(r,{width:"narrow",context:"formatting"});case"MMMMM":return a.month(r,{width:"narrow",context:"formatting"});case"MMMM":default:return a.month(r,{width:"wide",context:"formatting"})||a.month(r,{width:"abbreviated",context:"formatting"})||a.month(r,{width:"narrow",context:"formatting"})}}validate(r,n){return n>=0&&n<=11}set(r,n,a){return r.setMonth(a,1),r.setHours(0,0,0,0),r}}class MDt extends ec{constructor(){super(...arguments);ga(this,"priority",110);ga(this,"incompatibleTokens",["Y","R","q","Q","M","w","I","D","i","e","c","t","T"])}parse(r,n,a){const i=l=>l-1;switch(n){case"L":return mh(mu(hh.month,r),i);case"LL":return mh(Yu(2,r),i);case"Lo":return mh(a.ordinalNumber(r,{unit:"month"}),i);case"LLL":return a.month(r,{width:"abbreviated",context:"standalone"})||a.month(r,{width:"narrow",context:"standalone"});case"LLLLL":return a.month(r,{width:"narrow",context:"standalone"});case"LLLL":default:return a.month(r,{width:"wide",context:"standalone"})||a.month(r,{width:"abbreviated",context:"standalone"})||a.month(r,{width:"narrow",context:"standalone"})}}validate(r,n){return n>=0&&n<=11}set(r,n,a){return r.setMonth(a,1),r.setHours(0,0,0,0),r}}function IDt(s,t,r){const n=Ha(s),a=m5e(n,r)-t;return n.setDate(n.getDate()-a*7),n}class PDt extends ec{constructor(){super(...arguments);ga(this,"priority",100);ga(this,"incompatibleTokens",["y","R","u","q","Q","M","L","I","d","D","i","t","T"])}parse(r,n,a){switch(n){case"w":return mu(hh.week,r);case"wo":return a.ordinalNumber(r,{unit:"week"});default:return Yu(n.length,r)}}validate(r,n){return n>=1&&n<=53}set(r,n,a,i){return Np(IDt(r,a,i),i)}}function LDt(s,t){const r=Ha(s),n=u5e(r)-t;return r.setDate(r.getDate()-n*7),r}class DDt extends ec{constructor(){super(...arguments);ga(this,"priority",100);ga(this,"incompatibleTokens",["y","Y","u","q","Q","M","L","w","d","D","e","c","t","T"])}parse(r,n,a){switch(n){case"I":return mu(hh.week,r);case"Io":return a.ordinalNumber(r,{unit:"week"});default:return Yu(n.length,r)}}validate(r,n){return n>=1&&n<=53}set(r,n,a){return oj(LDt(r,a))}}const RDt=[31,28,31,30,31,30,31,31,30,31,30,31],ODt=[31,29,31,30,31,30,31,31,30,31,30,31];class FDt extends ec{constructor(){super(...arguments);ga(this,"priority",90);ga(this,"subPriority",1);ga(this,"incompatibleTokens",["Y","R","q","Q","w","I","D","i","e","c","t","T"])}parse(r,n,a){switch(n){case"d":return mu(hh.date,r);case"do":return a.ordinalNumber(r,{unit:"date"});default:return Yu(n.length,r)}}validate(r,n){const a=r.getFullYear(),i=brt(a),l=r.getMonth();return i?n>=1&&n<=ODt[l]:n>=1&&n<=RDt[l]}set(r,n,a){return r.setDate(a),r.setHours(0,0,0,0),r}}class BDt extends ec{constructor(){super(...arguments);ga(this,"priority",90);ga(this,"subpriority",1);ga(this,"incompatibleTokens",["Y","R","q","Q","M","L","w","I","d","E","i","e","c","t","T"])}parse(r,n,a){switch(n){case"D":case"DD":return mu(hh.dayOfYear,r);case"Do":return a.ordinalNumber(r,{unit:"date"});default:return Yu(n.length,r)}}validate(r,n){const a=r.getFullYear();return brt(a)?n>=1&&n<=366:n>=1&&n<=365}set(r,n,a){return r.setMonth(0,a),r.setHours(0,0,0,0),r}}function p5e(s,t,r){var m,p,x,y;const n=zS(),a=(r==null?void 0:r.weekStartsOn)??((p=(m=r==null?void 0:r.locale)==null?void 0:m.options)==null?void 0:p.weekStartsOn)??n.weekStartsOn??((y=(x=n.locale)==null?void 0:x.options)==null?void 0:y.weekStartsOn)??0,i=Ha(s),l=i.getDay(),c=(t%7+7)%7,d=7-a,h=t<0||t>6?t-(l+d)%7:(c+d)%7-(l+d)%7;return Lc(i,h)}class zDt extends ec{constructor(){super(...arguments);ga(this,"priority",90);ga(this,"incompatibleTokens",["D","i","e","c","t","T"])}parse(r,n,a){switch(n){case"E":case"EE":case"EEE":return a.day(r,{width:"abbreviated",context:"formatting"})||a.day(r,{width:"short",context:"formatting"})||a.day(r,{width:"narrow",context:"formatting"});case"EEEEE":return a.day(r,{width:"narrow",context:"formatting"});case"EEEEEE":return a.day(r,{width:"short",context:"formatting"})||a.day(r,{width:"narrow",context:"formatting"});case"EEEE":default:return a.day(r,{width:"wide",context:"formatting"})||a.day(r,{width:"abbreviated",context:"formatting"})||a.day(r,{width:"short",context:"formatting"})||a.day(r,{width:"narrow",context:"formatting"})}}validate(r,n){return n>=0&&n<=6}set(r,n,a,i){return r=p5e(r,a,i),r.setHours(0,0,0,0),r}}class $Dt extends ec{constructor(){super(...arguments);ga(this,"priority",90);ga(this,"incompatibleTokens",["y","R","u","q","Q","M","L","I","d","D","E","i","c","t","T"])}parse(r,n,a,i){const l=o=>{const c=Math.floor((o-1)/7)*7;return(o+i.weekStartsOn+6)%7+c};switch(n){case"e":case"ee":return mh(Yu(n.length,r),l);case"eo":return mh(a.ordinalNumber(r,{unit:"day"}),l);case"eee":return a.day(r,{width:"abbreviated",context:"formatting"})||a.day(r,{width:"short",context:"formatting"})||a.day(r,{width:"narrow",context:"formatting"});case"eeeee":return a.day(r,{width:"narrow",context:"formatting"});case"eeeeee":return a.day(r,{width:"short",context:"formatting"})||a.day(r,{width:"narrow",context:"formatting"});case"eeee":default:return a.day(r,{width:"wide",context:"formatting"})||a.day(r,{width:"abbreviated",context:"formatting"})||a.day(r,{width:"short",context:"formatting"})||a.day(r,{width:"narrow",context:"formatting"})}}validate(r,n){return n>=0&&n<=6}set(r,n,a,i){return r=p5e(r,a,i),r.setHours(0,0,0,0),r}}class UDt extends ec{constructor(){super(...arguments);ga(this,"priority",90);ga(this,"incompatibleTokens",["y","R","u","q","Q","M","L","I","d","D","E","i","e","t","T"])}parse(r,n,a,i){const l=o=>{const c=Math.floor((o-1)/7)*7;return(o+i.weekStartsOn+6)%7+c};switch(n){case"c":case"cc":return mh(Yu(n.length,r),l);case"co":return mh(a.ordinalNumber(r,{unit:"day"}),l);case"ccc":return a.day(r,{width:"abbreviated",context:"standalone"})||a.day(r,{width:"short",context:"standalone"})||a.day(r,{width:"narrow",context:"standalone"});case"ccccc":return a.day(r,{width:"narrow",context:"standalone"});case"cccccc":return a.day(r,{width:"short",context:"standalone"})||a.day(r,{width:"narrow",context:"standalone"});case"cccc":default:return a.day(r,{width:"wide",context:"standalone"})||a.day(r,{width:"abbreviated",context:"standalone"})||a.day(r,{width:"short",context:"standalone"})||a.day(r,{width:"narrow",context:"standalone"})}}validate(r,n){return n>=0&&n<=6}set(r,n,a,i){return r=p5e(r,a,i),r.setHours(0,0,0,0),r}}function qDt(s,t){const r=Ha(s),n=fDt(r),a=t-n;return Lc(r,a)}class VDt extends ec{constructor(){super(...arguments);ga(this,"priority",90);ga(this,"incompatibleTokens",["y","Y","u","q","Q","M","L","w","d","D","E","e","c","t","T"])}parse(r,n,a){const i=l=>l===0?7:l;switch(n){case"i":case"ii":return Yu(n.length,r);case"io":return a.ordinalNumber(r,{unit:"day"});case"iii":return mh(a.day(r,{width:"abbreviated",context:"formatting"})||a.day(r,{width:"short",context:"formatting"})||a.day(r,{width:"narrow",context:"formatting"}),i);case"iiiii":return mh(a.day(r,{width:"narrow",context:"formatting"}),i);case"iiiiii":return mh(a.day(r,{width:"short",context:"formatting"})||a.day(r,{width:"narrow",context:"formatting"}),i);case"iiii":default:return mh(a.day(r,{width:"wide",context:"formatting"})||a.day(r,{width:"abbreviated",context:"formatting"})||a.day(r,{width:"short",context:"formatting"})||a.day(r,{width:"narrow",context:"formatting"}),i)}}validate(r,n){return n>=1&&n<=7}set(r,n,a){return r=qDt(r,a),r.setHours(0,0,0,0),r}}class HDt extends ec{constructor(){super(...arguments);ga(this,"priority",80);ga(this,"incompatibleTokens",["b","B","H","k","t","T"])}parse(r,n,a){switch(n){case"a":case"aa":case"aaa":return a.dayPeriod(r,{width:"abbreviated",context:"formatting"})||a.dayPeriod(r,{width:"narrow",context:"formatting"});case"aaaaa":return a.dayPeriod(r,{width:"narrow",context:"formatting"});case"aaaa":default:return a.dayPeriod(r,{width:"wide",context:"formatting"})||a.dayPeriod(r,{width:"abbreviated",context:"formatting"})||a.dayPeriod(r,{width:"narrow",context:"formatting"})}}set(r,n,a){return r.setHours(f5e(a),0,0,0),r}}class GDt extends ec{constructor(){super(...arguments);ga(this,"priority",80);ga(this,"incompatibleTokens",["a","B","H","k","t","T"])}parse(r,n,a){switch(n){case"b":case"bb":case"bbb":return a.dayPeriod(r,{width:"abbreviated",context:"formatting"})||a.dayPeriod(r,{width:"narrow",context:"formatting"});case"bbbbb":return a.dayPeriod(r,{width:"narrow",context:"formatting"});case"bbbb":default:return a.dayPeriod(r,{width:"wide",context:"formatting"})||a.dayPeriod(r,{width:"abbreviated",context:"formatting"})||a.dayPeriod(r,{width:"narrow",context:"formatting"})}}set(r,n,a){return r.setHours(f5e(a),0,0,0),r}}class WDt extends ec{constructor(){super(...arguments);ga(this,"priority",80);ga(this,"incompatibleTokens",["a","b","t","T"])}parse(r,n,a){switch(n){case"B":case"BB":case"BBB":return a.dayPeriod(r,{width:"abbreviated",context:"formatting"})||a.dayPeriod(r,{width:"narrow",context:"formatting"});case"BBBBB":return a.dayPeriod(r,{width:"narrow",context:"formatting"});case"BBBB":default:return a.dayPeriod(r,{width:"wide",context:"formatting"})||a.dayPeriod(r,{width:"abbreviated",context:"formatting"})||a.dayPeriod(r,{width:"narrow",context:"formatting"})}}set(r,n,a){return r.setHours(f5e(a),0,0,0),r}}class KDt extends ec{constructor(){super(...arguments);ga(this,"priority",70);ga(this,"incompatibleTokens",["H","K","k","t","T"])}parse(r,n,a){switch(n){case"h":return mu(hh.hour12h,r);case"ho":return a.ordinalNumber(r,{unit:"hour"});default:return Yu(n.length,r)}}validate(r,n){return n>=1&&n<=12}set(r,n,a){const i=r.getHours()>=12;return i&&a<12?r.setHours(a+12,0,0,0):!i&&a===12?r.setHours(0,0,0,0):r.setHours(a,0,0,0),r}}class YDt extends ec{constructor(){super(...arguments);ga(this,"priority",70);ga(this,"incompatibleTokens",["a","b","h","K","k","t","T"])}parse(r,n,a){switch(n){case"H":return mu(hh.hour23h,r);case"Ho":return a.ordinalNumber(r,{unit:"hour"});default:return Yu(n.length,r)}}validate(r,n){return n>=0&&n<=23}set(r,n,a){return r.setHours(a,0,0,0),r}}class ZDt extends ec{constructor(){super(...arguments);ga(this,"priority",70);ga(this,"incompatibleTokens",["h","H","k","t","T"])}parse(r,n,a){switch(n){case"K":return mu(hh.hour11h,r);case"Ko":return a.ordinalNumber(r,{unit:"hour"});default:return Yu(n.length,r)}}validate(r,n){return n>=0&&n<=11}set(r,n,a){return r.getHours()>=12&&a<12?r.setHours(a+12,0,0,0):r.setHours(a,0,0,0),r}}class XDt extends ec{constructor(){super(...arguments);ga(this,"priority",70);ga(this,"incompatibleTokens",["a","b","h","H","K","t","T"])}parse(r,n,a){switch(n){case"k":return mu(hh.hour24h,r);case"ko":return a.ordinalNumber(r,{unit:"hour"});default:return Yu(n.length,r)}}validate(r,n){return n>=1&&n<=24}set(r,n,a){const i=a<=24?a%24:a;return r.setHours(i,0,0,0),r}}class QDt extends ec{constructor(){super(...arguments);ga(this,"priority",60);ga(this,"incompatibleTokens",["t","T"])}parse(r,n,a){switch(n){case"m":return mu(hh.minute,r);case"mo":return a.ordinalNumber(r,{unit:"minute"});default:return Yu(n.length,r)}}validate(r,n){return n>=0&&n<=59}set(r,n,a){return r.setMinutes(a,0,0),r}}class JDt extends ec{constructor(){super(...arguments);ga(this,"priority",50);ga(this,"incompatibleTokens",["t","T"])}parse(r,n,a){switch(n){case"s":return mu(hh.second,r);case"so":return a.ordinalNumber(r,{unit:"second"});default:return Yu(n.length,r)}}validate(r,n){return n>=0&&n<=59}set(r,n,a){return r.setSeconds(a,0),r}}class eRt extends ec{constructor(){super(...arguments);ga(this,"priority",30);ga(this,"incompatibleTokens",["t","T"])}parse(r,n){const a=i=>Math.trunc(i*Math.pow(10,-n.length+3));return mh(Yu(n.length,r),a)}set(r,n,a){return r.setMilliseconds(a),r}}class tRt extends ec{constructor(){super(...arguments);ga(this,"priority",10);ga(this,"incompatibleTokens",["t","T","x"])}parse(r,n){switch(n){case"X":return Jb(Qb.basicOptionalMinutes,r);case"XX":return Jb(Qb.basic,r);case"XXXX":return Jb(Qb.basicOptionalSeconds,r);case"XXXXX":return Jb(Qb.extendedOptionalSeconds,r);case"XXX":default:return Jb(Qb.extended,r)}}set(r,n,a){return n.timestampIsSet?r:mc(r,r.getTime()-yS(r)-a)}}class sRt extends ec{constructor(){super(...arguments);ga(this,"priority",10);ga(this,"incompatibleTokens",["t","T","X"])}parse(r,n){switch(n){case"x":return Jb(Qb.basicOptionalMinutes,r);case"xx":return Jb(Qb.basic,r);case"xxxx":return Jb(Qb.basicOptionalSeconds,r);case"xxxxx":return Jb(Qb.extendedOptionalSeconds,r);case"xxx":default:return Jb(Qb.extended,r)}}set(r,n,a){return n.timestampIsSet?r:mc(r,r.getTime()-yS(r)-a)}}class rRt extends ec{constructor(){super(...arguments);ga(this,"priority",40);ga(this,"incompatibleTokens","*")}parse(r){return yrt(r)}set(r,n,a){return[mc(r,a*1e3),{timestampIsSet:!0}]}}class nRt extends ec{constructor(){super(...arguments);ga(this,"priority",20);ga(this,"incompatibleTokens","*")}parse(r){return yrt(r)}set(r,n,a){return[mc(r,a),{timestampIsSet:!0}]}}const aRt={G:new jDt,y:new NDt,Y:new kDt,R:new SDt,u:new CDt,Q:new TDt,q:new EDt,M:new ADt,L:new MDt,w:new PDt,I:new DDt,d:new FDt,D:new BDt,E:new zDt,e:new $Dt,c:new UDt,i:new VDt,a:new HDt,b:new GDt,B:new WDt,h:new KDt,H:new YDt,K:new ZDt,k:new XDt,m:new QDt,s:new JDt,S:new eRt,X:new tRt,x:new sRt,t:new rRt,T:new nRt},iRt=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,oRt=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,lRt=/^'([^]*?)'?$/,cRt=/''/g,dRt=/\S/,uRt=/[a-zA-Z]/;function g5e(s,t,r,n){var _,b,j,k;const a=mDt(),i=a.locale??Cge,l=a.firstWeekContainsDate??((b=(_=a.locale)==null?void 0:_.options)==null?void 0:b.firstWeekContainsDate)??1,o=a.weekStartsOn??((k=(j=a.locale)==null?void 0:j.options)==null?void 0:k.weekStartsOn)??0;if(t==="")return s===""?Ha(r):mc(r,NaN);const c={firstWeekContainsDate:l,weekStartsOn:o,locale:i},d=[new wDt],h=t.match(oRt).map(T=>{const E=T[0];if(E in tNe){const A=tNe[E];return A(T,i.formatLong)}return T}).join("").match(iRt),m=[];for(let T of h){grt(T)&&sNe(T,t,s),prt(T)&&sNe(T,t,s);const E=T[0],A=aRt[E];if(A){const{incompatibleTokens:D}=A;if(Array.isArray(D)){const z=m.find(O=>D.includes(O.token)||O.token===E);if(z)throw new RangeError(`The format string mustn't contain \`${z.fullToken}\` and \`${T}\` at the same time`)}else if(A.incompatibleTokens==="*"&&m.length>0)throw new RangeError(`The format string mustn't contain \`${T}\` and any other token at the same time`);m.push({token:E,fullToken:T});const R=A.run(s,T,i.match,c);if(!R)return mc(r,NaN);d.push(R.setter),s=R.rest}else{if(E.match(uRt))throw new RangeError("Format string contains an unescaped latin alphabet character `"+E+"`");if(T==="''"?T="'":E==="'"&&(T=hRt(T)),s.indexOf(T)===0)s=s.slice(T.length);else return mc(r,NaN)}}if(s.length>0&&dRt.test(s))return mc(r,NaN);const p=d.map(T=>T.priority).sort((T,E)=>E-T).filter((T,E,A)=>A.indexOf(T)===E).map(T=>d.filter(E=>E.priority===T).sort((E,A)=>A.subPriority-E.subPriority)).map(T=>T[0]);let x=Ha(r);if(isNaN(x.getTime()))return mc(r,NaN);const y={};for(const T of p){if(!T.validate(x,c))return mc(r,NaN);const E=T.set(x,y,c);Array.isArray(E)?(x=E[0],Object.assign(y,E[1])):x=E}return mc(r,x)}function hRt(s){return s.match(lRt)[1].replace(cRt,"'")}function __(s){return+Ha(s)i-l);return r>=n&&r<=a}function mue(s,t){return Lc(s,-t)}function dg(s,t){const n=vRt(s);let a;if(n.date){const c=bRt(n.date,2);a=_Rt(c.restDateString,c.year)}if(!a||isNaN(a.getTime()))return new Date(NaN);const i=a.getTime();let l=0,o;if(n.time&&(l=wRt(n.time),isNaN(l)))return new Date(NaN);if(n.timezone){if(o=jRt(n.timezone),isNaN(o))return new Date(NaN)}else{const c=new Date(i+l),d=new Date(0);return d.setFullYear(c.getUTCFullYear(),c.getUTCMonth(),c.getUTCDate()),d.setHours(c.getUTCHours(),c.getUTCMinutes(),c.getUTCSeconds(),c.getUTCMilliseconds()),d}return new Date(i+l+o)}const VU={dateTimeDelimiter:/[T ]/,timeZoneDelimiter:/[Z ]/i,timezone:/([Z+-].*)$/},gRt=/^-?(?:(\d{3})|(\d{2})(?:-?(\d{2}))?|W(\d{2})(?:-?(\d{1}))?|)$/,xRt=/^(\d{2}(?:[.,]\d*)?)(?::?(\d{2}(?:[.,]\d*)?))?(?::?(\d{2}(?:[.,]\d*)?))?$/,yRt=/^([+-])(\d{2})(?::?(\d{2}))?$/;function vRt(s){const t={},r=s.split(VU.dateTimeDelimiter);let n;if(r.length>2)return t;if(/:/.test(r[0])?n=r[0]:(t.date=r[0],n=r[1],VU.timeZoneDelimiter.test(t.date)&&(t.date=s.split(VU.timeZoneDelimiter)[0],n=s.substr(t.date.length,s.length))),n){const a=VU.timezone.exec(n);a?(t.time=n.replace(a[1],""),t.timezone=a[1]):t.time=n}return t}function bRt(s,t){const r=new RegExp("^(?:(\\d{4}|[+-]\\d{"+(4+t)+"})|(\\d{2}|[+-]\\d{"+(2+t)+"})$)"),n=s.match(r);if(!n)return{year:NaN,restDateString:""};const a=n[1]?parseInt(n[1]):null,i=n[2]?parseInt(n[2]):null;return{year:i===null?a:i*100,restDateString:s.slice((n[1]||n[2]).length)}}function _Rt(s,t){if(t===null)return new Date(NaN);const r=s.match(gRt);if(!r)return new Date(NaN);const n=!!r[4],a=CR(r[1]),i=CR(r[2])-1,l=CR(r[3]),o=CR(r[4]),c=CR(r[5])-1;if(n)return TRt(t,o,c)?NRt(t,o,c):new Date(NaN);{const d=new Date(0);return!SRt(t,i,l)||!CRt(t,a)?new Date(NaN):(d.setUTCFullYear(t,i,Math.max(a,l)),d)}}function CR(s){return s?parseInt(s):1}function wRt(s){const t=s.match(xRt);if(!t)return NaN;const r=nbe(t[1]),n=nbe(t[2]),a=nbe(t[3]);return ERt(r,n,a)?r*JB+n*kge+a*1e3:NaN}function nbe(s){return s&&parseFloat(s.replace(",","."))||0}function jRt(s){if(s==="Z")return 0;const t=s.match(yRt);if(!t)return 0;const r=t[1]==="+"?-1:1,n=parseInt(t[2]),a=t[3]&&parseInt(t[3])||0;return ARt(n,a)?r*(n*JB+a*kge):NaN}function NRt(s,t,r){const n=new Date(0);n.setUTCFullYear(s,0,4);const a=n.getUTCDay()||7,i=(t-1)*7+r+1-a;return n.setUTCDate(n.getUTCDate()+i),n}const kRt=[31,null,31,30,31,30,31,31,30,31,30,31];function _rt(s){return s%400===0||s%4===0&&s%100!==0}function SRt(s,t,r){return t>=0&&t<=11&&r>=1&&r<=(kRt[t]||(_rt(s)?29:28))}function CRt(s,t){return t>=1&&t<=(_rt(s)?366:365)}function TRt(s,t,r){return t>=1&&t<=53&&r>=0&&r<=6}function ERt(s,t,r){return s===24?t===0&&r===0:r>=0&&r<60&&t>=0&&t<60&&s>=0&&s<25}function ARt(s,t){return t>=0&&t<=59}function abe(s,t){const r=Ha(s),n=r.getFullYear(),a=r.getDate(),i=mc(s,0);i.setFullYear(n,t,15),i.setHours(0,0,0,0);const l=hDt(i);return r.setMonth(t,Math.min(a,l)),r}function KF(s,t){const r=Ha(s);return r.setHours(t),r}function YF(s,t){const r=Ha(s);return r.setMinutes(t),r}function XOe(s,t){const r=Ha(s);return isNaN(+r)?mc(s,NaN):(r.setFullYear(t),r)}function RT(s,t){return wg(s,-t)}var zl;(function(s){s.assertEqual=a=>{};function t(a){}s.assertIs=t;function r(a){throw new Error}s.assertNever=r,s.arrayToEnum=a=>{const i={};for(const l of a)i[l]=l;return i},s.getValidEnumValues=a=>{const i=s.objectKeys(a).filter(o=>typeof a[a[o]]!="number"),l={};for(const o of i)l[o]=a[o];return s.objectValues(l)},s.objectValues=a=>s.objectKeys(a).map(function(i){return a[i]}),s.objectKeys=typeof Object.keys=="function"?a=>Object.keys(a):a=>{const i=[];for(const l in a)Object.prototype.hasOwnProperty.call(a,l)&&i.push(l);return i},s.find=(a,i)=>{for(const l of a)if(i(l))return l},s.isInteger=typeof Number.isInteger=="function"?a=>Number.isInteger(a):a=>typeof a=="number"&&Number.isFinite(a)&&Math.floor(a)===a;function n(a,i=" | "){return a.map(l=>typeof l=="string"?`'${l}'`:l).join(i)}s.joinValues=n,s.jsonStringifyReplacer=(a,i)=>typeof i=="bigint"?i.toString():i})(zl||(zl={}));var QOe;(function(s){s.mergeShapes=(t,r)=>({...t,...r})})(QOe||(QOe={}));const oi=zl.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),$N=s=>{switch(typeof s){case"undefined":return oi.undefined;case"string":return oi.string;case"number":return Number.isNaN(s)?oi.nan:oi.number;case"boolean":return oi.boolean;case"function":return oi.function;case"bigint":return oi.bigint;case"symbol":return oi.symbol;case"object":return Array.isArray(s)?oi.array:s===null?oi.null:s.then&&typeof s.then=="function"&&s.catch&&typeof s.catch=="function"?oi.promise:typeof Map<"u"&&s instanceof Map?oi.map:typeof Set<"u"&&s instanceof Set?oi.set:typeof Date<"u"&&s instanceof Date?oi.date:oi.object;default:return oi.unknown}},Wn=zl.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 M_ extends Error{get errors(){return this.issues}constructor(t){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=t}format(t){const r=t||function(i){return i.message},n={_errors:[]},a=i=>{for(const l of i.issues)if(l.code==="invalid_union")l.unionErrors.map(a);else if(l.code==="invalid_return_type")a(l.returnTypeError);else if(l.code==="invalid_arguments")a(l.argumentsError);else if(l.path.length===0)n._errors.push(r(l));else{let o=n,c=0;for(;cr.message){const r={},n=[];for(const a of this.issues)if(a.path.length>0){const i=a.path[0];r[i]=r[i]||[],r[i].push(t(a))}else n.push(t(a));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}}M_.create=s=>new M_(s);const rNe=(s,t)=>{let r;switch(s.code){case Wn.invalid_type:s.received===oi.undefined?r="Required":r=`Expected ${s.expected}, received ${s.received}`;break;case Wn.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(s.expected,zl.jsonStringifyReplacer)}`;break;case Wn.unrecognized_keys:r=`Unrecognized key(s) in object: ${zl.joinValues(s.keys,", ")}`;break;case Wn.invalid_union:r="Invalid input";break;case Wn.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${zl.joinValues(s.options)}`;break;case Wn.invalid_enum_value:r=`Invalid enum value. Expected ${zl.joinValues(s.options)}, received '${s.received}'`;break;case Wn.invalid_arguments:r="Invalid function arguments";break;case Wn.invalid_return_type:r="Invalid function return type";break;case Wn.invalid_date:r="Invalid date";break;case Wn.invalid_string:typeof s.validation=="object"?"includes"in s.validation?(r=`Invalid input: must include "${s.validation.includes}"`,typeof s.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${s.validation.position}`)):"startsWith"in s.validation?r=`Invalid input: must start with "${s.validation.startsWith}"`:"endsWith"in s.validation?r=`Invalid input: must end with "${s.validation.endsWith}"`:zl.assertNever(s.validation):s.validation!=="regex"?r=`Invalid ${s.validation}`:r="Invalid";break;case Wn.too_small:s.type==="array"?r=`Array must contain ${s.exact?"exactly":s.inclusive?"at least":"more than"} ${s.minimum} element(s)`:s.type==="string"?r=`String must contain ${s.exact?"exactly":s.inclusive?"at least":"over"} ${s.minimum} character(s)`:s.type==="number"?r=`Number must be ${s.exact?"exactly equal to ":s.inclusive?"greater than or equal to ":"greater than "}${s.minimum}`:s.type==="bigint"?r=`Number must be ${s.exact?"exactly equal to ":s.inclusive?"greater than or equal to ":"greater than "}${s.minimum}`:s.type==="date"?r=`Date must be ${s.exact?"exactly equal to ":s.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(s.minimum))}`:r="Invalid input";break;case Wn.too_big:s.type==="array"?r=`Array must contain ${s.exact?"exactly":s.inclusive?"at most":"less than"} ${s.maximum} element(s)`:s.type==="string"?r=`String must contain ${s.exact?"exactly":s.inclusive?"at most":"under"} ${s.maximum} character(s)`:s.type==="number"?r=`Number must be ${s.exact?"exactly":s.inclusive?"less than or equal to":"less than"} ${s.maximum}`:s.type==="bigint"?r=`BigInt must be ${s.exact?"exactly":s.inclusive?"less than or equal to":"less than"} ${s.maximum}`:s.type==="date"?r=`Date must be ${s.exact?"exactly":s.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(s.maximum))}`:r="Invalid input";break;case Wn.custom:r="Invalid input";break;case Wn.invalid_intersection_types:r="Intersection results could not be merged";break;case Wn.not_multiple_of:r=`Number must be a multiple of ${s.multipleOf}`;break;case Wn.not_finite:r="Number must be finite";break;default:r=t.defaultError,zl.assertNever(s)}return{message:r}};let MRt=rNe;function IRt(){return MRt}const PRt=s=>{const{data:t,path:r,errorMaps:n,issueData:a}=s,i=[...r,...a.path||[]],l={...a,path:i};if(a.message!==void 0)return{...a,path:i,message:a.message};let o="";const c=n.filter(d=>!!d).slice().reverse();for(const d of c)o=d(l,{data:t,defaultError:o}).message;return{...a,path:i,message:o}};function La(s,t){const r=IRt(),n=PRt({issueData:t,data:s.data,path:s.path,errorMaps:[s.common.contextualErrorMap,s.schemaErrorMap,r,r===rNe?void 0:rNe].filter(a=>!!a)});s.common.issues.push(n)}class N0{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,r){const n=[];for(const a of r){if(a.status==="aborted")return go;a.status==="dirty"&&t.dirty(),n.push(a.value)}return{status:t.value,value:n}}static async mergeObjectAsync(t,r){const n=[];for(const a of r){const i=await a.key,l=await a.value;n.push({key:i,value:l})}return N0.mergeObjectSync(t,n)}static mergeObjectSync(t,r){const n={};for(const a of r){const{key:i,value:l}=a;if(i.status==="aborted"||l.status==="aborted")return go;i.status==="dirty"&&t.dirty(),l.status==="dirty"&&t.dirty(),i.value!=="__proto__"&&(typeof l.value<"u"||a.alwaysSet)&&(n[i.value]=l.value)}return{status:t.value,value:n}}}const go=Object.freeze({status:"aborted"}),gO=s=>({status:"dirty",value:s}),rv=s=>({status:"valid",value:s}),JOe=s=>s.status==="aborted",eFe=s=>s.status==="dirty",XP=s=>s.status==="valid",Lhe=s=>typeof Promise<"u"&&s instanceof Promise;var fi;(function(s){s.errToObj=t=>typeof t=="string"?{message:t}:t||{},s.toString=t=>typeof t=="string"?t:t==null?void 0:t.message})(fi||(fi={}));class vS{constructor(t,r,n,a){this._cachedPath=[],this.parent=t,this.data=r,this._path=n,this._key=a}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 tFe=(s,t)=>{if(XP(t))return{success:!0,data:t.value};if(!s.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 M_(s.common.issues);return this._error=r,this._error}}};function Wo(s){if(!s)return{};const{errorMap:t,invalid_type_error:r,required_error:n,description:a}=s;if(t&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:a}:{errorMap:(l,o)=>{const{message:c}=s;return l.code==="invalid_enum_value"?{message:c??o.defaultError}:typeof o.data>"u"?{message:c??n??o.defaultError}:l.code!=="invalid_type"?{message:o.defaultError}:{message:c??r??o.defaultError}},description:a}}class Fl{get description(){return this._def.description}_getType(t){return $N(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:$N(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new N0,ctx:{common:t.parent.common,data:t.data,parsedType:$N(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const r=this._parse(t);if(Lhe(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(t){const r=this._parse(t);return Promise.resolve(r)}parse(t,r){const n=this.safeParse(t,r);if(n.success)return n.data;throw n.error}safeParse(t,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:t,parsedType:$N(t)},a=this._parseSync({data:t,path:n.path,parent:n});return tFe(n,a)}"~validate"(t){var n,a;const r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:$N(t)};if(!this["~standard"].async)try{const i=this._parseSync({data:t,path:[],parent:r});return XP(i)?{value:i.value}:{issues:r.common.issues}}catch(i){(a=(n=i==null?void 0:i.message)==null?void 0:n.toLowerCase())!=null&&a.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:r}).then(i=>XP(i)?{value:i.value}:{issues:r.common.issues})}async parseAsync(t,r){const n=await this.safeParseAsync(t,r);if(n.success)return n.data;throw n.error}async safeParseAsync(t,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:t,parsedType:$N(t)},a=this._parse({data:t,path:n.path,parent:n}),i=await(Lhe(a)?a:Promise.resolve(a));return tFe(n,i)}refine(t,r){const n=a=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(a):r;return this._refinement((a,i)=>{const l=t(a),o=()=>i.addIssue({code:Wn.custom,...n(a)});return typeof Promise<"u"&&l instanceof Promise?l.then(c=>c?!0:(o(),!1)):l?!0:(o(),!1)})}refinement(t,r){return this._refinement((n,a)=>t(n)?!0:(a.addIssue(typeof r=="function"?r(n,a):r),!1))}_refinement(t){return new eL({schema:this,typeName:xo.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,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 tS.create(this,this._def)}nullable(){return tL.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return w_.create(this)}promise(){return Fhe.create(this,this._def)}or(t){return Rhe.create([this,t],this._def)}and(t){return Ohe.create(this,t,this._def)}transform(t){return new eL({...Wo(this._def),schema:this,typeName:xo.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const r=typeof t=="function"?t:()=>t;return new oNe({...Wo(this._def),innerType:this,defaultValue:r,typeName:xo.ZodDefault})}brand(){return new sOt({typeName:xo.ZodBranded,type:this,...Wo(this._def)})}catch(t){const r=typeof t=="function"?t:()=>t;return new lNe({...Wo(this._def),innerType:this,catchValue:r,typeName:xo.ZodCatch})}describe(t){const r=this.constructor;return new r({...this._def,description:t})}pipe(t){return x5e.create(this,t)}readonly(){return cNe.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const LRt=/^c[^\s-]{8,}$/i,DRt=/^[0-9a-z]+$/,RRt=/^[0-9A-HJKMNP-TV-Z]{26}$/i,ORt=/^[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,FRt=/^[a-z0-9_-]{21}$/i,BRt=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,zRt=/^[-+]?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)?)??$/,$Rt=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,URt="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let ibe;const qRt=/^(?:(?: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])$/,VRt=/^(?:(?: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])$/,HRt=/^(([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]))$/,GRt=/^(([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])$/,WRt=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,KRt=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,wrt="((\\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])))",YRt=new RegExp(`^${wrt}$`);function jrt(s){let t="[0-5]\\d";s.precision?t=`${t}\\.\\d{${s.precision}}`:s.precision==null&&(t=`${t}(\\.\\d+)?`);const r=s.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${r}`}function ZRt(s){return new RegExp(`^${jrt(s)}$`)}function XRt(s){let t=`${wrt}T${jrt(s)}`;const r=[];return r.push(s.local?"Z?":"Z"),s.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function QRt(s,t){return!!((t==="v4"||!t)&&qRt.test(s)||(t==="v6"||!t)&&HRt.test(s))}function JRt(s,t){if(!BRt.test(s))return!1;try{const[r]=s.split(".");if(!r)return!1;const n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),a=JSON.parse(atob(n));return!(typeof a!="object"||a===null||"typ"in a&&(a==null?void 0:a.typ)!=="JWT"||!a.alg||t&&a.alg!==t)}catch{return!1}}function eOt(s,t){return!!((t==="v4"||!t)&&VRt.test(s)||(t==="v6"||!t)&&GRt.test(s))}class bk extends Fl{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==oi.string){const i=this._getOrReturnCtx(t);return La(i,{code:Wn.invalid_type,expected:oi.string,received:i.parsedType}),go}const n=new N0;let a;for(const i of this._def.checks)if(i.kind==="min")t.data.lengthi.value&&(a=this._getOrReturnCtx(t,a),La(a,{code:Wn.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="length"){const l=t.data.length>i.value,o=t.data.lengtht.test(a),{validation:r,code:Wn.invalid_string,...fi.errToObj(n)})}_addCheck(t){return new bk({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...fi.errToObj(t)})}url(t){return this._addCheck({kind:"url",...fi.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...fi.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...fi.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...fi.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...fi.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...fi.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...fi.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...fi.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...fi.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...fi.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...fi.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...fi.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof(t==null?void 0:t.precision)>"u"?null:t==null?void 0:t.precision,offset:(t==null?void 0:t.offset)??!1,local:(t==null?void 0:t.local)??!1,...fi.errToObj(t==null?void 0:t.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof(t==null?void 0:t.precision)>"u"?null:t==null?void 0:t.precision,...fi.errToObj(t==null?void 0:t.message)})}duration(t){return this._addCheck({kind:"duration",...fi.errToObj(t)})}regex(t,r){return this._addCheck({kind:"regex",regex:t,...fi.errToObj(r)})}includes(t,r){return this._addCheck({kind:"includes",value:t,position:r==null?void 0:r.position,...fi.errToObj(r==null?void 0:r.message)})}startsWith(t,r){return this._addCheck({kind:"startsWith",value:t,...fi.errToObj(r)})}endsWith(t,r){return this._addCheck({kind:"endsWith",value:t,...fi.errToObj(r)})}min(t,r){return this._addCheck({kind:"min",value:t,...fi.errToObj(r)})}max(t,r){return this._addCheck({kind:"max",value:t,...fi.errToObj(r)})}length(t,r){return this._addCheck({kind:"length",value:t,...fi.errToObj(r)})}nonempty(t){return this.min(1,fi.errToObj(t))}trim(){return new bk({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new bk({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new bk({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(const r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxLength(){let t=null;for(const r of this._def.checks)r.kind==="max"&&(t===null||r.valuenew bk({checks:[],typeName:xo.ZodString,coerce:(s==null?void 0:s.coerce)??!1,...Wo(s)});function tOt(s,t){const r=(s.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,a=r>n?r:n,i=Number.parseInt(s.toFixed(a).replace(".","")),l=Number.parseInt(t.toFixed(a).replace(".",""));return i%l/10**a}class QP extends Fl{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==oi.number){const i=this._getOrReturnCtx(t);return La(i,{code:Wn.invalid_type,expected:oi.number,received:i.parsedType}),go}let n;const a=new N0;for(const i of this._def.checks)i.kind==="int"?zl.isInteger(t.data)||(n=this._getOrReturnCtx(t,n),La(n,{code:Wn.invalid_type,expected:"integer",received:"float",message:i.message}),a.dirty()):i.kind==="min"?(i.inclusive?t.datai.value:t.data>=i.value)&&(n=this._getOrReturnCtx(t,n),La(n,{code:Wn.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),a.dirty()):i.kind==="multipleOf"?tOt(t.data,i.value)!==0&&(n=this._getOrReturnCtx(t,n),La(n,{code:Wn.not_multiple_of,multipleOf:i.value,message:i.message}),a.dirty()):i.kind==="finite"?Number.isFinite(t.data)||(n=this._getOrReturnCtx(t,n),La(n,{code:Wn.not_finite,message:i.message}),a.dirty()):zl.assertNever(i);return{status:a.value,value:t.data}}gte(t,r){return this.setLimit("min",t,!0,fi.toString(r))}gt(t,r){return this.setLimit("min",t,!1,fi.toString(r))}lte(t,r){return this.setLimit("max",t,!0,fi.toString(r))}lt(t,r){return this.setLimit("max",t,!1,fi.toString(r))}setLimit(t,r,n,a){return new QP({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:fi.toString(a)}]})}_addCheck(t){return new QP({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:fi.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:fi.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:fi.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:fi.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:fi.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:fi.toString(r)})}finite(t){return this._addCheck({kind:"finite",message:fi.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:fi.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:fi.toString(t)})}get minValue(){let t=null;for(const r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(const r of this._def.checks)r.kind==="max"&&(t===null||r.valuet.kind==="int"||t.kind==="multipleOf"&&zl.isInteger(t.value))}get isFinite(){let t=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"&&(t===null||n.valuenew QP({checks:[],typeName:xo.ZodNumber,coerce:(s==null?void 0:s.coerce)||!1,...Wo(s)});class d9 extends Fl{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==oi.bigint)return this._getInvalidInput(t);let n;const a=new N0;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?t.datai.value:t.data>=i.value)&&(n=this._getOrReturnCtx(t,n),La(n,{code:Wn.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),a.dirty()):i.kind==="multipleOf"?t.data%i.value!==BigInt(0)&&(n=this._getOrReturnCtx(t,n),La(n,{code:Wn.not_multiple_of,multipleOf:i.value,message:i.message}),a.dirty()):zl.assertNever(i);return{status:a.value,value:t.data}}_getInvalidInput(t){const r=this._getOrReturnCtx(t);return La(r,{code:Wn.invalid_type,expected:oi.bigint,received:r.parsedType}),go}gte(t,r){return this.setLimit("min",t,!0,fi.toString(r))}gt(t,r){return this.setLimit("min",t,!1,fi.toString(r))}lte(t,r){return this.setLimit("max",t,!0,fi.toString(r))}lt(t,r){return this.setLimit("max",t,!1,fi.toString(r))}setLimit(t,r,n,a){return new d9({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:fi.toString(a)}]})}_addCheck(t){return new d9({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:fi.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:fi.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:fi.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:fi.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:fi.toString(r)})}get minValue(){let t=null;for(const r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(const r of this._def.checks)r.kind==="max"&&(t===null||r.valuenew d9({checks:[],typeName:xo.ZodBigInt,coerce:(s==null?void 0:s.coerce)??!1,...Wo(s)});class nNe extends Fl{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==oi.boolean){const n=this._getOrReturnCtx(t);return La(n,{code:Wn.invalid_type,expected:oi.boolean,received:n.parsedType}),go}return rv(t.data)}}nNe.create=s=>new nNe({typeName:xo.ZodBoolean,coerce:(s==null?void 0:s.coerce)||!1,...Wo(s)});class Dhe extends Fl{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==oi.date){const i=this._getOrReturnCtx(t);return La(i,{code:Wn.invalid_type,expected:oi.date,received:i.parsedType}),go}if(Number.isNaN(t.data.getTime())){const i=this._getOrReturnCtx(t);return La(i,{code:Wn.invalid_date}),go}const n=new N0;let a;for(const i of this._def.checks)i.kind==="min"?t.data.getTime()i.value&&(a=this._getOrReturnCtx(t,a),La(a,{code:Wn.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),n.dirty()):zl.assertNever(i);return{status:n.value,value:new Date(t.data.getTime())}}_addCheck(t){return new Dhe({...this._def,checks:[...this._def.checks,t]})}min(t,r){return this._addCheck({kind:"min",value:t.getTime(),message:fi.toString(r)})}max(t,r){return this._addCheck({kind:"max",value:t.getTime(),message:fi.toString(r)})}get minDate(){let t=null;for(const r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(const r of this._def.checks)r.kind==="max"&&(t===null||r.valuenew Dhe({checks:[],coerce:(s==null?void 0:s.coerce)||!1,typeName:xo.ZodDate,...Wo(s)});class sFe extends Fl{_parse(t){if(this._getType(t)!==oi.symbol){const n=this._getOrReturnCtx(t);return La(n,{code:Wn.invalid_type,expected:oi.symbol,received:n.parsedType}),go}return rv(t.data)}}sFe.create=s=>new sFe({typeName:xo.ZodSymbol,...Wo(s)});class rFe extends Fl{_parse(t){if(this._getType(t)!==oi.undefined){const n=this._getOrReturnCtx(t);return La(n,{code:Wn.invalid_type,expected:oi.undefined,received:n.parsedType}),go}return rv(t.data)}}rFe.create=s=>new rFe({typeName:xo.ZodUndefined,...Wo(s)});class nFe extends Fl{_parse(t){if(this._getType(t)!==oi.null){const n=this._getOrReturnCtx(t);return La(n,{code:Wn.invalid_type,expected:oi.null,received:n.parsedType}),go}return rv(t.data)}}nFe.create=s=>new nFe({typeName:xo.ZodNull,...Wo(s)});class aFe extends Fl{constructor(){super(...arguments),this._any=!0}_parse(t){return rv(t.data)}}aFe.create=s=>new aFe({typeName:xo.ZodAny,...Wo(s)});class iFe extends Fl{constructor(){super(...arguments),this._unknown=!0}_parse(t){return rv(t.data)}}iFe.create=s=>new iFe({typeName:xo.ZodUnknown,...Wo(s)});class bS extends Fl{_parse(t){const r=this._getOrReturnCtx(t);return La(r,{code:Wn.invalid_type,expected:oi.never,received:r.parsedType}),go}}bS.create=s=>new bS({typeName:xo.ZodNever,...Wo(s)});class oFe extends Fl{_parse(t){if(this._getType(t)!==oi.undefined){const n=this._getOrReturnCtx(t);return La(n,{code:Wn.invalid_type,expected:oi.void,received:n.parsedType}),go}return rv(t.data)}}oFe.create=s=>new oFe({typeName:xo.ZodVoid,...Wo(s)});class w_ extends Fl{_parse(t){const{ctx:r,status:n}=this._processInputParams(t),a=this._def;if(r.parsedType!==oi.array)return La(r,{code:Wn.invalid_type,expected:oi.array,received:r.parsedType}),go;if(a.exactLength!==null){const l=r.data.length>a.exactLength.value,o=r.data.lengtha.maxLength.value&&(La(r,{code:Wn.too_big,maximum:a.maxLength.value,type:"array",inclusive:!0,exact:!1,message:a.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((l,o)=>a.type._parseAsync(new vS(r,l,r.path,o)))).then(l=>N0.mergeArray(n,l));const i=[...r.data].map((l,o)=>a.type._parseSync(new vS(r,l,r.path,o)));return N0.mergeArray(n,i)}get element(){return this._def.type}min(t,r){return new w_({...this._def,minLength:{value:t,message:fi.toString(r)}})}max(t,r){return new w_({...this._def,maxLength:{value:t,message:fi.toString(r)}})}length(t,r){return new w_({...this._def,exactLength:{value:t,message:fi.toString(r)}})}nonempty(t){return this.min(1,t)}}w_.create=(s,t)=>new w_({type:s,minLength:null,maxLength:null,exactLength:null,typeName:xo.ZodArray,...Wo(t)});function B6(s){if(s instanceof Ru){const t={};for(const r in s.shape){const n=s.shape[r];t[r]=tS.create(B6(n))}return new Ru({...s._def,shape:()=>t})}else return s instanceof w_?new w_({...s._def,type:B6(s.element)}):s instanceof tS?tS.create(B6(s.unwrap())):s instanceof tL?tL.create(B6(s.unwrap())):s instanceof pA?pA.create(s.items.map(t=>B6(t))):s}class Ru extends Fl{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const t=this._def.shape(),r=zl.objectKeys(t);return this._cached={shape:t,keys:r},this._cached}_parse(t){if(this._getType(t)!==oi.object){const d=this._getOrReturnCtx(t);return La(d,{code:Wn.invalid_type,expected:oi.object,received:d.parsedType}),go}const{status:n,ctx:a}=this._processInputParams(t),{shape:i,keys:l}=this._getCached(),o=[];if(!(this._def.catchall instanceof bS&&this._def.unknownKeys==="strip"))for(const d in a.data)l.includes(d)||o.push(d);const c=[];for(const d of l){const h=i[d],m=a.data[d];c.push({key:{status:"valid",value:d},value:h._parse(new vS(a,m,a.path,d)),alwaysSet:d in a.data})}if(this._def.catchall instanceof bS){const d=this._def.unknownKeys;if(d==="passthrough")for(const h of o)c.push({key:{status:"valid",value:h},value:{status:"valid",value:a.data[h]}});else if(d==="strict")o.length>0&&(La(a,{code:Wn.unrecognized_keys,keys:o}),n.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const d=this._def.catchall;for(const h of o){const m=a.data[h];c.push({key:{status:"valid",value:h},value:d._parse(new vS(a,m,a.path,h)),alwaysSet:h in a.data})}}return a.common.async?Promise.resolve().then(async()=>{const d=[];for(const h of c){const m=await h.key,p=await h.value;d.push({key:m,value:p,alwaysSet:h.alwaysSet})}return d}).then(d=>N0.mergeObjectSync(n,d)):N0.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(t){return fi.errToObj,new Ru({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(r,n)=>{var i,l;const a=((l=(i=this._def).errorMap)==null?void 0:l.call(i,r,n).message)??n.defaultError;return r.code==="unrecognized_keys"?{message:fi.errToObj(t).message??a}:{message:a}}}:{}})}strip(){return new Ru({...this._def,unknownKeys:"strip"})}passthrough(){return new Ru({...this._def,unknownKeys:"passthrough"})}extend(t){return new Ru({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new Ru({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:xo.ZodObject})}setKey(t,r){return this.augment({[t]:r})}catchall(t){return new Ru({...this._def,catchall:t})}pick(t){const r={};for(const n of zl.objectKeys(t))t[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new Ru({...this._def,shape:()=>r})}omit(t){const r={};for(const n of zl.objectKeys(this.shape))t[n]||(r[n]=this.shape[n]);return new Ru({...this._def,shape:()=>r})}deepPartial(){return B6(this)}partial(t){const r={};for(const n of zl.objectKeys(this.shape)){const a=this.shape[n];t&&!t[n]?r[n]=a:r[n]=a.optional()}return new Ru({...this._def,shape:()=>r})}required(t){const r={};for(const n of zl.objectKeys(this.shape))if(t&&!t[n])r[n]=this.shape[n];else{let i=this.shape[n];for(;i instanceof tS;)i=i._def.innerType;r[n]=i}return new Ru({...this._def,shape:()=>r})}keyof(){return Nrt(zl.objectKeys(this.shape))}}Ru.create=(s,t)=>new Ru({shape:()=>s,unknownKeys:"strip",catchall:bS.create(),typeName:xo.ZodObject,...Wo(t)});Ru.strictCreate=(s,t)=>new Ru({shape:()=>s,unknownKeys:"strict",catchall:bS.create(),typeName:xo.ZodObject,...Wo(t)});Ru.lazycreate=(s,t)=>new Ru({shape:s,unknownKeys:"strip",catchall:bS.create(),typeName:xo.ZodObject,...Wo(t)});class Rhe extends Fl{_parse(t){const{ctx:r}=this._processInputParams(t),n=this._def.options;function a(i){for(const o of i)if(o.result.status==="valid")return o.result;for(const o of i)if(o.result.status==="dirty")return r.common.issues.push(...o.ctx.common.issues),o.result;const l=i.map(o=>new M_(o.ctx.common.issues));return La(r,{code:Wn.invalid_union,unionErrors:l}),go}if(r.common.async)return Promise.all(n.map(async i=>{const l={...r,common:{...r.common,issues:[]},parent:null};return{result:await i._parseAsync({data:r.data,path:r.path,parent:l}),ctx:l}})).then(a);{let i;const l=[];for(const c of n){const d={...r,common:{...r.common,issues:[]},parent:null},h=c._parseSync({data:r.data,path:r.path,parent:d});if(h.status==="valid")return h;h.status==="dirty"&&!i&&(i={result:h,ctx:d}),d.common.issues.length&&l.push(d.common.issues)}if(i)return r.common.issues.push(...i.ctx.common.issues),i.result;const o=l.map(c=>new M_(c));return La(r,{code:Wn.invalid_union,unionErrors:o}),go}}get options(){return this._def.options}}Rhe.create=(s,t)=>new Rhe({options:s,typeName:xo.ZodUnion,...Wo(t)});function aNe(s,t){const r=$N(s),n=$N(t);if(s===t)return{valid:!0,data:s};if(r===oi.object&&n===oi.object){const a=zl.objectKeys(t),i=zl.objectKeys(s).filter(o=>a.indexOf(o)!==-1),l={...s,...t};for(const o of i){const c=aNe(s[o],t[o]);if(!c.valid)return{valid:!1};l[o]=c.data}return{valid:!0,data:l}}else if(r===oi.array&&n===oi.array){if(s.length!==t.length)return{valid:!1};const a=[];for(let i=0;i{if(JOe(i)||JOe(l))return go;const o=aNe(i.value,l.value);return o.valid?((eFe(i)||eFe(l))&&r.dirty(),{status:r.value,value:o.data}):(La(n,{code:Wn.invalid_intersection_types}),go)};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(([i,l])=>a(i,l)):a(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}}Ohe.create=(s,t,r)=>new Ohe({left:s,right:t,typeName:xo.ZodIntersection,...Wo(r)});class pA extends Fl{_parse(t){const{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==oi.array)return La(n,{code:Wn.invalid_type,expected:oi.array,received:n.parsedType}),go;if(n.data.lengththis._def.items.length&&(La(n,{code:Wn.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());const i=[...n.data].map((l,o)=>{const c=this._def.items[o]||this._def.rest;return c?c._parse(new vS(n,l,n.path,o)):null}).filter(l=>!!l);return n.common.async?Promise.all(i).then(l=>N0.mergeArray(r,l)):N0.mergeArray(r,i)}get items(){return this._def.items}rest(t){return new pA({...this._def,rest:t})}}pA.create=(s,t)=>{if(!Array.isArray(s))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new pA({items:s,typeName:xo.ZodTuple,rest:null,...Wo(t)})};class lFe extends Fl{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==oi.map)return La(n,{code:Wn.invalid_type,expected:oi.map,received:n.parsedType}),go;const a=this._def.keyType,i=this._def.valueType,l=[...n.data.entries()].map(([o,c],d)=>({key:a._parse(new vS(n,o,n.path,[d,"key"])),value:i._parse(new vS(n,c,n.path,[d,"value"]))}));if(n.common.async){const o=new Map;return Promise.resolve().then(async()=>{for(const c of l){const d=await c.key,h=await c.value;if(d.status==="aborted"||h.status==="aborted")return go;(d.status==="dirty"||h.status==="dirty")&&r.dirty(),o.set(d.value,h.value)}return{status:r.value,value:o}})}else{const o=new Map;for(const c of l){const d=c.key,h=c.value;if(d.status==="aborted"||h.status==="aborted")return go;(d.status==="dirty"||h.status==="dirty")&&r.dirty(),o.set(d.value,h.value)}return{status:r.value,value:o}}}}lFe.create=(s,t,r)=>new lFe({valueType:t,keyType:s,typeName:xo.ZodMap,...Wo(r)});class u9 extends Fl{_parse(t){const{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==oi.set)return La(n,{code:Wn.invalid_type,expected:oi.set,received:n.parsedType}),go;const a=this._def;a.minSize!==null&&n.data.sizea.maxSize.value&&(La(n,{code:Wn.too_big,maximum:a.maxSize.value,type:"set",inclusive:!0,exact:!1,message:a.maxSize.message}),r.dirty());const i=this._def.valueType;function l(c){const d=new Set;for(const h of c){if(h.status==="aborted")return go;h.status==="dirty"&&r.dirty(),d.add(h.value)}return{status:r.value,value:d}}const o=[...n.data.values()].map((c,d)=>i._parse(new vS(n,c,n.path,d)));return n.common.async?Promise.all(o).then(c=>l(c)):l(o)}min(t,r){return new u9({...this._def,minSize:{value:t,message:fi.toString(r)}})}max(t,r){return new u9({...this._def,maxSize:{value:t,message:fi.toString(r)}})}size(t,r){return this.min(t,r).max(t,r)}nonempty(t){return this.min(1,t)}}u9.create=(s,t)=>new u9({valueType:s,minSize:null,maxSize:null,typeName:xo.ZodSet,...Wo(t)});class cFe extends Fl{get schema(){return this._def.getter()}_parse(t){const{ctx:r}=this._processInputParams(t);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}}cFe.create=(s,t)=>new cFe({getter:s,typeName:xo.ZodLazy,...Wo(t)});class iNe extends Fl{_parse(t){if(t.data!==this._def.value){const r=this._getOrReturnCtx(t);return La(r,{received:r.data,code:Wn.invalid_literal,expected:this._def.value}),go}return{status:"valid",value:t.data}}get value(){return this._def.value}}iNe.create=(s,t)=>new iNe({value:s,typeName:xo.ZodLiteral,...Wo(t)});function Nrt(s,t){return new JP({values:s,typeName:xo.ZodEnum,...Wo(t)})}class JP extends Fl{_parse(t){if(typeof t.data!="string"){const r=this._getOrReturnCtx(t),n=this._def.values;return La(r,{expected:zl.joinValues(n),received:r.parsedType,code:Wn.invalid_type}),go}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){const r=this._getOrReturnCtx(t),n=this._def.values;return La(r,{received:r.data,code:Wn.invalid_enum_value,options:n}),go}return rv(t.data)}get options(){return this._def.values}get enum(){const t={};for(const r of this._def.values)t[r]=r;return t}get Values(){const t={};for(const r of this._def.values)t[r]=r;return t}get Enum(){const t={};for(const r of this._def.values)t[r]=r;return t}extract(t,r=this._def){return JP.create(t,{...this._def,...r})}exclude(t,r=this._def){return JP.create(this.options.filter(n=>!t.includes(n)),{...this._def,...r})}}JP.create=Nrt;class dFe extends Fl{_parse(t){const r=zl.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(t);if(n.parsedType!==oi.string&&n.parsedType!==oi.number){const a=zl.objectValues(r);return La(n,{expected:zl.joinValues(a),received:n.parsedType,code:Wn.invalid_type}),go}if(this._cache||(this._cache=new Set(zl.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){const a=zl.objectValues(r);return La(n,{received:n.data,code:Wn.invalid_enum_value,options:a}),go}return rv(t.data)}get enum(){return this._def.values}}dFe.create=(s,t)=>new dFe({values:s,typeName:xo.ZodNativeEnum,...Wo(t)});class Fhe extends Fl{unwrap(){return this._def.type}_parse(t){const{ctx:r}=this._processInputParams(t);if(r.parsedType!==oi.promise&&r.common.async===!1)return La(r,{code:Wn.invalid_type,expected:oi.promise,received:r.parsedType}),go;const n=r.parsedType===oi.promise?r.data:Promise.resolve(r.data);return rv(n.then(a=>this._def.type.parseAsync(a,{path:r.path,errorMap:r.common.contextualErrorMap})))}}Fhe.create=(s,t)=>new Fhe({type:s,typeName:xo.ZodPromise,...Wo(t)});class eL extends Fl{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===xo.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:r,ctx:n}=this._processInputParams(t),a=this._def.effect||null,i={addIssue:l=>{La(n,l),l.fatal?r.abort():r.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),a.type==="preprocess"){const l=a.transform(n.data,i);if(n.common.async)return Promise.resolve(l).then(async o=>{if(r.value==="aborted")return go;const c=await this._def.schema._parseAsync({data:o,path:n.path,parent:n});return c.status==="aborted"?go:c.status==="dirty"||r.value==="dirty"?gO(c.value):c});{if(r.value==="aborted")return go;const o=this._def.schema._parseSync({data:l,path:n.path,parent:n});return o.status==="aborted"?go:o.status==="dirty"||r.value==="dirty"?gO(o.value):o}}if(a.type==="refinement"){const l=o=>{const c=a.refinement(o,i);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(n.common.async===!1){const o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?go:(o.status==="dirty"&&r.dirty(),l(o.value),{status:r.value,value:o.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>o.status==="aborted"?go:(o.status==="dirty"&&r.dirty(),l(o.value).then(()=>({status:r.value,value:o.value}))))}if(a.type==="transform")if(n.common.async===!1){const l=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!XP(l))return go;const o=a.transform(l.value,i);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:o}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(l=>XP(l)?Promise.resolve(a.transform(l.value,i)).then(o=>({status:r.value,value:o})):go);zl.assertNever(a)}}eL.create=(s,t,r)=>new eL({schema:s,typeName:xo.ZodEffects,effect:t,...Wo(r)});eL.createWithPreprocess=(s,t,r)=>new eL({schema:t,effect:{type:"preprocess",transform:s},typeName:xo.ZodEffects,...Wo(r)});class tS extends Fl{_parse(t){return this._getType(t)===oi.undefined?rv(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}tS.create=(s,t)=>new tS({innerType:s,typeName:xo.ZodOptional,...Wo(t)});class tL extends Fl{_parse(t){return this._getType(t)===oi.null?rv(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}tL.create=(s,t)=>new tL({innerType:s,typeName:xo.ZodNullable,...Wo(t)});class oNe extends Fl{_parse(t){const{ctx:r}=this._processInputParams(t);let n=r.data;return r.parsedType===oi.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}}oNe.create=(s,t)=>new oNe({innerType:s,typeName:xo.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Wo(t)});class lNe extends Fl{_parse(t){const{ctx:r}=this._processInputParams(t),n={...r,common:{...r.common,issues:[]}},a=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Lhe(a)?a.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new M_(n.common.issues)},input:n.data})})):{status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new M_(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}lNe.create=(s,t)=>new lNe({innerType:s,typeName:xo.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Wo(t)});class uFe extends Fl{_parse(t){if(this._getType(t)!==oi.nan){const n=this._getOrReturnCtx(t);return La(n,{code:Wn.invalid_type,expected:oi.nan,received:n.parsedType}),go}return{status:"valid",value:t.data}}}uFe.create=s=>new uFe({typeName:xo.ZodNaN,...Wo(s)});class sOt extends Fl{_parse(t){const{ctx:r}=this._processInputParams(t),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}}class x5e extends Fl{_parse(t){const{status:r,ctx:n}=this._processInputParams(t);if(n.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?go:i.status==="dirty"?(r.dirty(),gO(i.value)):this._def.out._parseAsync({data:i.value,path:n.path,parent:n})})();{const a=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?go:a.status==="dirty"?(r.dirty(),{status:"dirty",value:a.value}):this._def.out._parseSync({data:a.value,path:n.path,parent:n})}}static create(t,r){return new x5e({in:t,out:r,typeName:xo.ZodPipeline})}}class cNe extends Fl{_parse(t){const r=this._def.innerType._parse(t),n=a=>(XP(a)&&(a.value=Object.freeze(a.value)),a);return Lhe(r)?r.then(a=>n(a)):n(r)}unwrap(){return this._def.innerType}}cNe.create=(s,t)=>new cNe({innerType:s,typeName:xo.ZodReadonly,...Wo(t)});Ru.lazycreate;var xo;(function(s){s.ZodString="ZodString",s.ZodNumber="ZodNumber",s.ZodNaN="ZodNaN",s.ZodBigInt="ZodBigInt",s.ZodBoolean="ZodBoolean",s.ZodDate="ZodDate",s.ZodSymbol="ZodSymbol",s.ZodUndefined="ZodUndefined",s.ZodNull="ZodNull",s.ZodAny="ZodAny",s.ZodUnknown="ZodUnknown",s.ZodNever="ZodNever",s.ZodVoid="ZodVoid",s.ZodArray="ZodArray",s.ZodObject="ZodObject",s.ZodUnion="ZodUnion",s.ZodDiscriminatedUnion="ZodDiscriminatedUnion",s.ZodIntersection="ZodIntersection",s.ZodTuple="ZodTuple",s.ZodRecord="ZodRecord",s.ZodMap="ZodMap",s.ZodSet="ZodSet",s.ZodFunction="ZodFunction",s.ZodLazy="ZodLazy",s.ZodLiteral="ZodLiteral",s.ZodEnum="ZodEnum",s.ZodEffects="ZodEffects",s.ZodNativeEnum="ZodNativeEnum",s.ZodOptional="ZodOptional",s.ZodNullable="ZodNullable",s.ZodDefault="ZodDefault",s.ZodCatch="ZodCatch",s.ZodPromise="ZodPromise",s.ZodBranded="ZodBranded",s.ZodPipeline="ZodPipeline",s.ZodReadonly="ZodReadonly"})(xo||(xo={}));const Ho=bk.create,ZF=QP.create,rOt=nNe.create;bS.create;w_.create;const yj=Ru.create;Ru.strictCreate;Rhe.create;Ohe.create;pA.create;const ky=iNe.create,krt=JP.create;Fhe.create;tS.create;tL.create;const vr=S.forwardRef(({className:s,...t},r)=>e.jsx("textarea",{className:Ft("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",s),ref:r,...t}));vr.displayName="Textarea";const nOt=["Excellent","Good","Neutral","Bad","Very Bad"],aOt=[5,4,3,2,1];function iOt({questions:s,visitorId:t,onComplete:r,onSkip:n}){const a=OLt(),[i,l]=S.useState({}),o=s.filter(p=>p.question_type==="rating"),c=s.filter(p=>p.question_type!=="rating"),d=(p,x)=>{l(y=>({...y,[p]:{rating_value:x}}))},h=(p,x)=>{l(y=>({...y,[p]:{text_value:x}}))},m=async()=>{const p=Object.entries(i).filter(([,x])=>x.rating_value!=null||x.text_value&&x.text_value.trim()).map(([x,y])=>{var _;return{visitor_id:t,question_id:x,rating_value:y.rating_value??null,text_value:((_=y.text_value)==null?void 0:_.trim())||null}});if(p.length>0)try{await a.mutateAsync(p)}catch{}r()};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("h2",{className:"text-lg font-bold text-slate-900",children:"Quick Feedback"}),e.jsx("button",{onClick:n,className:"text-sm text-slate-400 hover:text-slate-600 underline",children:"Skip"})]}),e.jsx("p",{className:"text-sm text-slate-500 -mt-2",children:"Your feedback helps the agent — totally optional!"}),o.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("div",{className:"flex-1"}),nOt.map(p=>e.jsx("div",{className:"w-12 text-center",children:e.jsx("span",{className:"text-[10px] text-slate-400 leading-tight block",children:p})},p))]}),o.map(p=>e.jsxs("div",{className:"flex items-center gap-1 py-1.5 border-b border-slate-100 last:border-0",children:[e.jsx("span",{className:"flex-1 text-sm text-slate-700 pr-2",children:p.question_text}),aOt.map(x=>{var y;return e.jsx("div",{className:"w-12 flex justify-center",children:e.jsx("button",{type:"button",onClick:()=>d(p.id,x),className:`w-6 h-6 rounded-full border-2 transition-all ${((y=i[p.id])==null?void 0:y.rating_value)===x?"bg-slate-900 border-slate-900":"border-slate-300 hover:border-slate-500"}`})},x)})]},p.id))]}),c.map(p=>{var x;return e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium text-slate-700 block mb-1",children:p.question_text}),e.jsx(vr,{value:((x=i[p.id])==null?void 0:x.text_value)||"",onChange:y=>h(p.id,y.target.value),placeholder:"Your thoughts...",className:"h-16 text-sm resize-none rounded-xl border-slate-200"})]},p.id)}),e.jsx(H,{onClick:m,disabled:a.isPending,className:"w-full h-12 text-base bg-slate-900 hover:bg-slate-800 text-white rounded-xl",children:a.isPending?e.jsx(is,{className:"h-5 w-5 animate-spin"}):"Submit Feedback"})]})}var Ege="Checkbox",[oOt,MZs]=_u(Ege),[lOt,y5e]=oOt(Ege);function cOt(s){const{__scopeCheckbox:t,checked:r,children:n,defaultChecked:a,disabled:i,form:l,name:o,onCheckedChange:c,required:d,value:h="on",internal_do_not_use_render:m}=s,[p,x]=af({prop:r,defaultProp:a??!1,onChange:c,caller:Ege}),[y,_]=S.useState(null),[b,j]=S.useState(null),k=S.useRef(!1),T=y?!!l||!!y.closest("form"):!0,E={checked:p,disabled:i,setChecked:x,control:y,setControl:_,name:o,form:l,value:h,hasConsumerStoppedPropagationRef:k,required:d,defaultChecked:sS(a)?!1:a,isFormControl:T,bubbleInput:b,setBubbleInput:j};return e.jsx(lOt,{scope:t,...E,children:dOt(m)?m(E):n})}var Srt="CheckboxTrigger",Crt=S.forwardRef(({__scopeCheckbox:s,onKeyDown:t,onClick:r,...n},a)=>{const{control:i,value:l,disabled:o,checked:c,required:d,setControl:h,setChecked:m,hasConsumerStoppedPropagationRef:p,isFormControl:x,bubbleInput:y}=y5e(Srt,s),_=_i(a,h),b=S.useRef(c);return S.useEffect(()=>{const j=i==null?void 0:i.form;if(j){const k=()=>m(b.current);return j.addEventListener("reset",k),()=>j.removeEventListener("reset",k)}},[i,m]),e.jsx(Vn.button,{type:"button",role:"checkbox","aria-checked":sS(c)?"mixed":c,"aria-required":d,"data-state":Irt(c),"data-disabled":o?"":void 0,disabled:o,value:l,...n,ref:_,onKeyDown:an(t,j=>{j.key==="Enter"&&j.preventDefault()}),onClick:an(r,j=>{m(k=>sS(k)?!0:!k),y&&x&&(p.current=j.isPropagationStopped(),p.current||j.stopPropagation())})})});Crt.displayName=Srt;var v5e=S.forwardRef((s,t)=>{const{__scopeCheckbox:r,name:n,checked:a,defaultChecked:i,required:l,disabled:o,value:c,onCheckedChange:d,form:h,...m}=s;return e.jsx(cOt,{__scopeCheckbox:r,checked:a,defaultChecked:i,disabled:o,required:l,onCheckedChange:d,name:n,form:h,value:c,internal_do_not_use_render:({isFormControl:p})=>e.jsxs(e.Fragment,{children:[e.jsx(Crt,{...m,ref:t,__scopeCheckbox:r}),p&&e.jsx(Mrt,{__scopeCheckbox:r})]})})});v5e.displayName=Ege;var Trt="CheckboxIndicator",Ert=S.forwardRef((s,t)=>{const{__scopeCheckbox:r,forceMount:n,...a}=s,i=y5e(Trt,r);return e.jsx(vh,{present:n||sS(i.checked)||i.checked===!0,children:e.jsx(Vn.span,{"data-state":Irt(i.checked),"data-disabled":i.disabled?"":void 0,...a,ref:t,style:{pointerEvents:"none",...s.style}})})});Ert.displayName=Trt;var Art="CheckboxBubbleInput",Mrt=S.forwardRef(({__scopeCheckbox:s,...t},r)=>{const{control:n,hasConsumerStoppedPropagationRef:a,checked:i,defaultChecked:l,required:o,disabled:c,name:d,value:h,form:m,bubbleInput:p,setBubbleInput:x}=y5e(Art,s),y=_i(r,x),_=QB(i),b=FB(n);S.useEffect(()=>{const k=p;if(!k)return;const T=window.HTMLInputElement.prototype,A=Object.getOwnPropertyDescriptor(T,"checked").set,D=!a.current;if(_!==i&&A){const R=new Event("click",{bubbles:D});k.indeterminate=sS(i),A.call(k,sS(i)?!1:i),k.dispatchEvent(R)}},[p,_,i,a]);const j=S.useRef(sS(i)?!1:i);return e.jsx(Vn.input,{type:"checkbox","aria-hidden":!0,defaultChecked:l??j.current,required:o,disabled:c,name:d,value:h,form:m,...t,tabIndex:-1,ref:y,style:{...t.style,...b,position:"absolute",pointerEvents:"none",opacity:0,margin:0,transform:"translateX(-100%)"}})});Mrt.displayName=Art;function dOt(s){return typeof s=="function"}function sS(s){return s==="indeterminate"}function Irt(s){return sS(s)?"indeterminate":s?"checked":"unchecked"}const ao=S.forwardRef(({className:s,...t},r)=>e.jsx(v5e,{ref:r,className:Ft("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",s),...t,children:e.jsx(Ert,{className:Ft("flex items-center justify-center text-current"),children:e.jsx(va,{className:"h-4 w-4"})})}));ao.displayName=v5e.displayName;const $S=pge,b5e=r5e,uOt=gge,Prt=S.forwardRef(({className:s,...t},r)=>e.jsx(h8,{className:Ft("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",s),...t,ref:r}));Prt.displayName=h8.displayName;const hOt=zA("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"}}),vj=S.forwardRef(({side:s="right",className:t,children:r,...n},a)=>e.jsxs(uOt,{children:[e.jsx(Prt,{}),e.jsxs(m8,{ref:a,className:Ft(hOt({side:s}),t),...n,children:[r,e.jsxs(XB,{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:[e.jsx(Rr,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));vj.displayName=m8.displayName;const US=({className:s,...t})=>e.jsx("div",{className:Ft("flex flex-col space-y-2 text-center sm:text-left",s),...t});US.displayName="SheetHeader";const qS=S.forwardRef(({className:s,...t},r)=>e.jsx(YB,{ref:r,className:Ft("text-lg font-semibold text-foreground",s),...t}));qS.displayName=YB.displayName;const _5e=S.forwardRef(({className:s,...t},r)=>e.jsx(ZB,{ref:r,className:Ft("text-sm text-muted-foreground",s),...t}));_5e.displayName=ZB.displayName;function dNe(s){return/iframe\.mediadelivery\.net\/embed\//.test(s)}function mOt({rooms:s}){var m;const[t,r]=S.useState(((m=s[0])==null?void 0:m.id)||""),[n,a]=S.useState(null),i=s.find(p=>p.id===t)||s[0],l=n!==null?i==null?void 0:i.media[n]:null,o=(i==null?void 0:i.media.length)??0,c=()=>a(null),d=()=>a(p=>p===null||o===0?p:(p-1+o)%o),h=()=>a(p=>p===null||o===0?p:(p+1)%o);return S.useEffect(()=>{if(n===null)return;const p=x=>{x.key==="Escape"?c():x.key==="ArrowLeft"?d():x.key==="ArrowRight"&&h()};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[n,o]),s.length?e.jsxs("div",{className:"hidden md:block",children:[e.jsx("div",{className:"sticky top-0 z-20 -mx-5 px-5 py-3 bg-slate-950/80 backdrop-blur-md border-b border-white/10 overflow-x-auto",children:e.jsx("div",{className:"flex gap-2 min-w-max",children:s.map(p=>e.jsxs("button",{onClick:()=>r(p.id),className:Ft("px-4 py-2 rounded-full text-sm font-medium whitespace-nowrap transition",t===p.id?"bg-white text-slate-900":"bg-white/5 text-white/70 hover:bg-white/10"),children:[p.name,e.jsx("span",{className:"ml-1.5 text-xs opacity-60",children:p.media.length})]},p.id))})}),i&&e.jsxs("div",{className:"mt-6",children:[e.jsx("h3",{className:"text-2xl font-bold",children:i.name}),i.description&&e.jsx("p",{className:"text-white/60 mt-1.5 text-sm max-w-2xl",children:i.description}),i.media.length===0?e.jsx("p",{className:"text-white/40 text-sm mt-6 italic",children:"No media yet for this room."}):e.jsx("div",{className:"mt-5 grid grid-cols-2 lg:grid-cols-3 gap-3",children:i.media.map((p,x)=>e.jsx("button",{onClick:()=>a(x),className:"relative aspect-[4/3] rounded-xl overflow-hidden bg-white/5 group",children:p.kind==="video"?e.jsxs(e.Fragment,{children:[dNe(p.url)?e.jsx("div",{className:"absolute inset-0 bg-slate-900"}):e.jsx("video",{src:p.url,className:"w-full h-full object-cover"}),e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/30 group-hover:bg-black/50 transition",children:e.jsx("div",{className:"w-12 h-12 rounded-full bg-white/90 flex items-center justify-center",children:e.jsx(xn,{className:"h-5 w-5 text-slate-900"})})})]}):e.jsx("img",{src:p.url,alt:i.name,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"})},p.id))})]}),l&&i&&e.jsxs("div",{className:"fixed inset-0 z-50 bg-black/95 flex items-center justify-center p-6 cursor-zoom-out",onClick:c,children:[e.jsxs("div",{className:"absolute top-5 left-1/2 -translate-x-1/2 px-3 py-1.5 rounded-full bg-white/10 backdrop-blur-sm text-white/80 text-xs font-medium",children:[i.name," — ",(n??0)+1," / ",o]}),e.jsx("button",{onClick:p=>{p.stopPropagation(),c()},className:"absolute top-5 right-5 h-10 w-10 rounded-full bg-white/10 hover:bg-white/20 text-white text-xl flex items-center justify-center transition","aria-label":"Close",children:"×"}),o>1&&e.jsx("button",{onClick:p=>{p.stopPropagation(),d()},className:"absolute left-5 top-1/2 -translate-y-1/2 h-12 w-12 rounded-full bg-white/10 hover:bg-white/20 text-white flex items-center justify-center transition","aria-label":"Previous",children:e.jsx(fl,{className:"h-6 w-6"})}),l.kind==="video"?dNe(l.url)?e.jsx("iframe",{src:`${l.url}?autoplay=true`,allow:"accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,className:"w-full max-w-5xl aspect-video rounded-lg",onClick:p=>p.stopPropagation()},l.url):e.jsx("video",{src:l.url,controls:!0,autoPlay:!0,className:"max-w-full max-h-full rounded-lg",onClick:p=>p.stopPropagation()},l.url):e.jsx("img",{src:l.url,alt:"",className:"max-w-full max-h-full rounded-lg cursor-default",onClick:p=>p.stopPropagation()}),o>1&&e.jsx("button",{onClick:p=>{p.stopPropagation(),h()},className:"absolute right-5 top-1/2 -translate-y-1/2 h-12 w-12 rounded-full bg-white/10 hover:bg-white/20 text-white flex items-center justify-center transition","aria-label":"Next",children:e.jsx($a,{className:"h-6 w-6"})})]})]}):null}function fOt({rooms:s}){var o;const t=[];s.forEach(c=>{t.push({type:"cover",roomId:c.id,roomName:c.name,description:c.description,mediaCount:c.media.length}),c.media.forEach((d,h)=>{t.push({type:"media",roomId:c.id,roomName:c.name,url:d.url,kind:d.kind,index:h,total:c.media.length})})});const r=S.useRef(null),[n,a]=S.useState(0);S.useEffect(()=>{const c=r.current;if(!c)return;let d=0;const h=()=>{cancelAnimationFrame(d),d=requestAnimationFrame(()=>{const m=Math.round(c.scrollLeft/c.clientWidth);a(m)})};return c.addEventListener("scroll",h,{passive:!0}),()=>{c.removeEventListener("scroll",h),cancelAnimationFrame(d)}},[]);const i=c=>{const d=r.current;d&&d.scrollTo({left:c*d.clientWidth,behavior:"smooth"})};if(!t.length)return null;const l=(o=t[n])==null?void 0:o.roomId;return e.jsxs("div",{className:"md:hidden -mx-5",children:[e.jsx("div",{className:"px-5 py-3 overflow-x-auto sticky top-0 z-20 bg-slate-950/80 backdrop-blur-md border-b border-white/10",children:e.jsx("div",{className:"flex gap-2 min-w-max",children:s.map(c=>{const d=t.findIndex(m=>m.roomId===c.id),h=l===c.id;return e.jsx("button",{onClick:()=>i(d),className:Ft("px-3.5 py-1.5 rounded-full text-xs font-medium whitespace-nowrap transition",h?"bg-white text-slate-900":"bg-white/10 text-white/80"),children:c.name},c.id)})})}),e.jsx("div",{ref:r,className:"flex overflow-x-auto snap-x snap-mandatory scroll-smooth no-scrollbar",style:{scrollSnapType:"x mandatory"},children:t.map((c,d)=>e.jsx("div",{className:"shrink-0 w-screen snap-center",children:e.jsxs("div",{className:"w-full aspect-[9/16] max-h-[75vh] bg-slate-900 relative",children:[c.type==="cover"?e.jsxs("div",{className:"w-full h-full flex flex-col items-center justify-center p-8 text-center bg-gradient-to-br from-slate-800 to-slate-950",children:[e.jsx("p",{className:"text-xs uppercase tracking-widest text-white/40 mb-2",children:"Next room"}),e.jsx("h3",{className:"text-3xl font-bold",children:c.roomName}),c.description&&e.jsx("p",{className:"text-white/70 text-sm mt-3 max-w-xs",children:c.description}),e.jsxs("p",{className:"text-white/40 text-xs mt-5",children:[c.mediaCount," ",c.mediaCount===1?"item":"items"," — swipe to view →"]})]}):c.kind==="video"?dNe(c.url)?e.jsx("iframe",{src:c.url,allow:"accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,className:"w-full h-full"}):e.jsx("video",{src:c.url,controls:!0,playsInline:!0,className:"w-full h-full object-cover"}):e.jsx("img",{src:c.url,alt:c.roomName,className:"w-full h-full object-cover"}),c.type==="media"&&e.jsxs("div",{className:"absolute top-3 left-3 right-3 flex items-center justify-between pointer-events-none",children:[e.jsx("div",{className:"px-3 py-1 rounded-full bg-black/50 backdrop-blur-sm text-xs text-white font-medium",children:c.roomName}),e.jsxs("div",{className:"px-2.5 py-1 rounded-full bg-black/50 backdrop-blur-sm text-[10px] text-white/80",children:[c.index+1," / ",c.total]})]})]})},d))}),e.jsxs("div",{className:"flex items-center justify-between px-5 mt-3",children:[e.jsxs("button",{onClick:()=>i(Math.max(0,n-1)),disabled:n===0,className:"flex items-center gap-1 text-sm text-white/70 disabled:opacity-30",children:[e.jsx(fl,{className:"h-4 w-4"})," Prev"]}),e.jsxs("span",{className:"text-xs text-white/50",children:[n+1," / ",t.length]}),e.jsxs("button",{onClick:()=>i(Math.min(t.length-1,n+1)),disabled:n===t.length-1,className:"flex items-center gap-1 text-sm text-white/70 disabled:opacity-30",children:["Next ",e.jsx($a,{className:"h-4 w-4"})]})]})]})}const obe={question:{label:"Ask a Question",title:"Ask the agent",placeholder:"What would you like to know about the home?",icon:Gi},showing:{label:"Schedule a Showing",title:"Request a private showing",placeholder:"Anything specific to focus on during the showing? (optional)",icon:Nn},disclosure:{label:"Request Disclosures",title:"Request seller disclosures",placeholder:"Any specific documents? (optional)",icon:kn},offer:{label:"I'm Interested — Let's Talk",title:"Express interest / make an offer",placeholder:"Tell the agent about your interest or any offer thoughts.",icon:oc}},pOt=["Seller's Property Disclosure","HOA Documents & Bylaws","Inspection Reports","Title / CC&Rs","Utility & Tax History"];function gOt(s){return s==null?null:s>=1e6?`$${(s/1e6).toFixed(s%1e6===0?0:2)}M`:s>=1e3?`$${(s/1e3).toFixed(0)}K`:`$${s}`}function xOt({openHouse:s,visitorId:t,visitorName:r,visitorEmail:n,visitorPhone:a,previewMode:i=!1}){var De;const l=s.profiles,o=((De=l==null?void 0:l.name)==null?void 0:De.split(" ").map(pe=>pe[0]).join("").slice(0,2))||"?",c=s.brand_color_override||null,[d,h]=S.useState(null),[m,p]=S.useState(""),[x,y]=S.useState(n||""),[_,b]=S.useState(a||""),[j,k]=S.useState(!1),[T,E]=S.useState(null),[A,D]=S.useState(""),[R,z]=S.useState(""),[O,$]=S.useState(""),[ee,Z]=S.useState([]),[J,K]=S.useState(""),[re,ie]=S.useState(""),[ce,ne]=S.useState(""),[le,be]=S.useState(""),fe=gOt(s.price),je=s.tour_mode==="rooms",{data:ve=[]}=WLt(je?s.id:void 0),We=[s.enable_question&&"question",s.enable_showing&&"showing",s.enable_disclosures&&"disclosure",s.enable_offer&&"offer"].filter(Boolean),Ve=pe=>{h(pe),p(""),D(""),z(""),$(""),Z([]),K(""),ie(""),ne(""),be("")},Le=()=>{h(null)},Me=pe=>{Z(tt=>tt.includes(pe)?tt.filter(ge=>ge!==pe):[...tt,pe])},ze=pe=>pe==="showing"?{preferred_date:A||null,preferred_time:R||null,alternate_date:O||null}:pe==="disclosure"?{requested_documents:ee}:pe==="offer"?{offer_amount:J||null,financing:re||null,timeline:ce||null,pre_approved:le||null}:{},Pe=d?d==="showing"?!!A:d==="question"?m.trim().length>0:!0:!1,Ie=async()=>{if(d){if(i){En({title:"Preview mode",description:"Lead not sent — this is just a preview."}),E(d),setTimeout(()=>{h(null),E(null)},1500);return}k(!0);try{const pe=ze(d),{error:tt}=await V.from("open_house_leads").insert({open_house_id:s.id,visitor_id:t,action_type:d,payload:{message:m.trim()||null,email:x.trim()||null,phone:_.trim()||null,visitor_name:r,...pe}});if(tt)throw tt;V.functions.invoke("send-virtual-open-house-lead",{body:{open_house_id:s.id,visitor_id:t,action_type:d,message:m.trim()||null,visitor_name:r,visitor_email:x.trim()||null,visitor_phone:_.trim()||null,extras:pe}}).catch(()=>{}),E(d),En({title:"Sent!",description:"The agent has been notified."}),setTimeout(()=>{Le(),E(null)},1400)}catch(pe){En({title:"Something went wrong",description:pe.message,variant:"destructive"})}finally{k(!1)}}};return e.jsxs("div",{className:"min-h-screen bg-slate-950 text-white",children:[e.jsxs("div",{className:"relative w-full aspect-video bg-slate-900 md:max-h-[70vh]",children:[s.hero_video_url?e.jsx("video",{src:s.hero_video_url,poster:s.hero_video_thumbnail_url||s.photo_url||void 0,controls:!0,playsInline:!0,className:"w-full h-full object-cover"}):s.photo_url?e.jsx("img",{src:s.photo_url,alt:s.property_address,className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-white/40",children:"No tour video yet"}),e.jsx("div",{className:"absolute inset-x-0 bottom-0 h-32 bg-gradient-to-t from-slate-950 to-transparent pointer-events-none"})]}),e.jsxs("div",{className:"max-w-3xl mx-auto px-5 pb-32 -mt-10 relative z-10",children:[e.jsxs("div",{className:"bg-slate-900/80 backdrop-blur-md border border-white/10 rounded-2xl p-6 shadow-2xl",children:[e.jsx("h1",{className:"text-2xl font-bold leading-tight",children:s.property_address}),s.city&&e.jsxs("p",{className:"text-sm text-white/60 mt-1 flex items-center gap-1",children:[e.jsx(Qa,{className:"h-3.5 w-3.5"}),s.city,s.state?`, ${s.state}`:""," ",s.zip]}),fe&&e.jsx("p",{className:"text-3xl font-bold text-white mt-3",children:fe}),e.jsxs("div",{className:"flex flex-wrap gap-4 mt-4 text-sm text-white/80",children:[s.beds!=null&&e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(x1,{className:"h-4 w-4"}),s.beds," bd"]}),s.baths!=null&&e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(_p,{className:"h-4 w-4"}),s.baths," ba"]}),s.sqft!=null&&e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Hy,{className:"h-4 w-4"}),s.sqft.toLocaleString()," sqft"]})]}),s.property_description?e.jsx("p",{className:"text-white/80 text-sm mt-5 whitespace-pre-wrap leading-relaxed",children:s.property_description}):s.agent_greeting&&e.jsxs("p",{className:"text-white/70 text-sm mt-5 border-l-2 border-white/20 pl-3 italic",children:['"',s.agent_greeting,'"']})]}),l&&e.jsxs("div",{className:"mt-5 flex items-center gap-3 bg-white/5 border border-white/10 rounded-xl p-4",children:[e.jsxs(Un,{className:"h-12 w-12 ring-2 ring-white/20",style:c?{boxShadow:`0 0 0 2px ${c}`}:void 0,children:[e.jsx(Ka,{src:l.avatar_url||"",alt:l.name||""}),e.jsx(qn,{className:"bg-white/10 text-white",children:o})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-semibold text-white truncate",children:l.name}),l.title&&e.jsx("p",{className:"text-xs text-white/60 truncate",children:l.title})]}),(l.phone||l.email)&&e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[l.phone&&e.jsx("a",{href:`tel:${l.phone}`,"aria-label":`Call ${l.name}`,className:"h-10 w-10 rounded-full bg-white/10 hover:bg-white/20 transition-colors flex items-center justify-center text-white",style:c?{backgroundColor:`${c}33`,color:"white"}:void 0,children:e.jsx(Yn,{className:"h-4 w-4"})}),l.email&&e.jsx("a",{href:`mailto:${l.email}`,"aria-label":`Email ${l.name}`,className:"h-10 w-10 rounded-full bg-white/10 hover:bg-white/20 transition-colors flex items-center justify-center text-white",style:c?{backgroundColor:`${c}33`,color:"white"}:void 0,children:e.jsx(er,{className:"h-4 w-4"})})]})]}),je&&ve.length>0&&e.jsxs("div",{className:"mt-8",children:[e.jsx(mOt,{rooms:ve}),e.jsx(fOt,{rooms:ve})]}),We.length>0&&e.jsx("div",{className:"mt-5 grid grid-cols-1 sm:grid-cols-2 gap-3",children:We.map(pe=>{const tt=obe[pe],ge=tt.icon;return e.jsxs("button",{onClick:()=>Ve(pe),className:"flex items-center gap-3 p-4 rounded-xl bg-white text-slate-900 hover:bg-white/90 transition-colors text-left",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg flex items-center justify-center shrink-0",style:c?{backgroundColor:`${c}1a`,color:c}:{backgroundColor:"#f1f5f9",color:"#334155"},children:e.jsx(ge,{className:"h-5 w-5"})}),e.jsx("span",{className:"font-medium text-sm",children:tt.label})]},pe)})}),e.jsx("p",{className:"text-center text-white/30 text-xs mt-8",children:"Powered by LevelUp Virtual Open House"})]}),e.jsx($S,{open:!!d,onOpenChange:pe=>!pe&&Le(),children:e.jsx(vj,{side:"bottom",className:"rounded-t-2xl max-h-[92vh] overflow-y-auto",children:d&&e.jsxs(e.Fragment,{children:[e.jsxs(US,{className:"text-left",children:[e.jsx(qS,{children:obe[d].title}),e.jsxs(_5e,{children:[(l==null?void 0:l.name)||"The agent"," will be notified by email."]})]}),T===d?e.jsxs("div",{className:"py-10 flex flex-col items-center gap-3",children:[e.jsx("div",{className:"w-14 h-14 rounded-full bg-green-100 flex items-center justify-center",children:e.jsx(ea,{className:"h-7 w-7 text-green-600"})}),e.jsx("p",{className:"font-medium",children:"Message sent!"})]}):e.jsxs("div",{className:"space-y-4 pt-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs",children:"Email"}),e.jsx(Se,{type:"email",value:x,onChange:pe=>y(pe.target.value),placeholder:"you@example.com",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs",children:"Phone"}),e.jsx(Se,{type:"tel",value:_,onChange:pe=>b(pe.target.value),placeholder:"(555) 123-4567",className:"mt-1"})]})]}),d==="showing"&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs",children:"Preferred date *"}),e.jsx(Se,{type:"date",value:A,onChange:pe=>D(pe.target.value),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs",children:"Preferred time"}),e.jsx(Se,{type:"time",value:R,onChange:pe=>z(pe.target.value),className:"mt-1"})]})]}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs",children:"Alternate date (optional)"}),e.jsx(Se,{type:"date",value:O,onChange:pe=>$(pe.target.value),className:"mt-1"})]})]}),d==="disclosure"&&e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs",children:"Which documents? (select all that apply)"}),e.jsx("div",{className:"mt-2 space-y-2",children:pOt.map(pe=>e.jsxs("label",{className:"flex items-center gap-2 text-sm cursor-pointer",children:[e.jsx(ao,{checked:ee.includes(pe),onCheckedChange:()=>Me(pe)}),e.jsx("span",{children:pe})]},pe))})]}),d==="offer"&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs",children:"Estimated offer"}),e.jsx(Se,{value:J,onChange:pe=>K(pe.target.value),placeholder:"$",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs",children:"Financing"}),e.jsxs(Bs,{value:re,onValueChange:ie,children:[e.jsx(Os,{className:"mt-1",children:e.jsx(Us,{placeholder:"Select..."})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"Cash",children:"Cash"}),e.jsx(pt,{value:"Conventional",children:"Conventional"}),e.jsx(pt,{value:"FHA",children:"FHA"}),e.jsx(pt,{value:"VA",children:"VA"}),e.jsx(pt,{value:"Other",children:"Other"})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs",children:"Timeline"}),e.jsxs(Bs,{value:ce,onValueChange:ne,children:[e.jsx(Os,{className:"mt-1",children:e.jsx(Us,{placeholder:"Select..."})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"ASAP",children:"ASAP"}),e.jsx(pt,{value:"30 days",children:"30 days"}),e.jsx(pt,{value:"60 days",children:"60 days"}),e.jsx(pt,{value:"90+ days",children:"90+ days"})]})]})]}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs",children:"Pre-approved?"}),e.jsxs(Bs,{value:le,onValueChange:be,children:[e.jsx(Os,{className:"mt-1",children:e.jsx(Us,{placeholder:"Select..."})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"Yes",children:"Yes"}),e.jsx(pt,{value:"No",children:"No"}),e.jsx(pt,{value:"In progress",children:"In progress"})]})]})]})]})]}),e.jsxs("div",{children:[e.jsxs(ue,{className:"text-xs",children:["Message",d==="question"?" *":" (optional)"]}),e.jsx(vr,{value:m,onChange:pe=>p(pe.target.value),placeholder:obe[d].placeholder,rows:4,className:"mt-1"})]}),e.jsx(H,{onClick:Ie,disabled:j||!Pe,className:"w-full h-12 text-white hover:opacity-90",style:c?{backgroundColor:c}:void 0,children:j?e.jsx(is,{className:"h-4 w-4 animate-spin"}):"Send to agent"})]})]})})})]})}const yOt=yj({first_name:Ho().trim().min(1,"First name is required").max(50),last_name:Ho().trim().max(50).optional(),email:Ho().trim().email("Please enter a valid email").max(255).optional().or(ky("")),phone:Ho().trim().max(20).optional().or(ky(""))}),vOt=[{value:"buying",label:"Looking to Buy",emoji:"🏠"},{value:"selling",label:"Thinking of Selling",emoji:"📋"},{value:"browsing",label:"Just Browsing",emoji:"👀"},{value:"neighbor",label:"I'm a Neighbor",emoji:"👋"}];function Lrt({slug:s}={}){var Pe;const t=Po(),r=s||t.slug,{data:n,isLoading:a,error:i}=LLt(r),l=qLt(),o=VLt(),c=HLt(),d=S.useRef(!1),[h,m]=S.useState("welcome"),[p,x]=S.useState(null),[y,_]=S.useState({first_name:"",last_name:"",email:"",phone:""}),[b,j]=S.useState(""),[k,T]=S.useState(!1),[E,A]=S.useState(!1),[D,R]=S.useState(""),[z,O]=S.useState(""),{data:$,isLoading:ee}=RLt(n==null?void 0:n.id),Z=!!(n!=null&&n.enable_survey),J=(n==null?void 0:n.ask_visitor_intent)!==!1;S.useEffect(()=>{if(!r||!(n!=null&&n.id)||d.current)return;const Ie=`oh_scan_${n.id}`;if(sessionStorage.getItem(Ie)){d.current=!0;return}d.current=!0,sessionStorage.setItem(Ie,"1"),c.mutate(r)},[r,n==null?void 0:n.id]),S.useEffect(()=>{h==="pending_survey"&&(ee||m(Z&&(($==null?void 0:$.length)??0)>0?"survey":"done"))},[h,ee,Z,$]);const K=Ie=>{if(!Ie)return"";const[De,pe]=Ie.split(":"),tt=parseInt(De),ge=tt>=12?"PM":"AM";return`${tt>12?tt-12:tt||12}:${pe} ${ge}`},re=async()=>{O("");const Ie=yOt.safeParse(y);if(!Ie.success){O(Ie.error.issues[0].message);return}if(!y.email&&!y.phone){O("Please provide either an email or phone number");return}const De=(n==null?void 0:n.kind)==="virtual";if(!p&&(n!=null&&n.id))try{const pe=await l.mutateAsync({open_house_id:n.id,first_name:y.first_name.trim(),last_name:y.last_name.trim()||void 0,email:y.email.trim()||void 0,phone:y.phone.trim()||void 0,wants_market_updates:k,has_agent:E,working_with_agent_name:E&&D.trim()?D.trim():void 0,partial_signin:De?!1:J});x(pe.id)}catch{if(De){O("We could not start the virtual tour. Please try again.");return}}if(De){m(J?"intent":"done");return}if(!J){Z?!ee&&$&&$.length>0?m("survey"):m("pending_survey"):m("done");return}m("intent")},ie=async Ie=>{j(Ie);try{let De=p;if(De?await o.mutateAsync({visitor_id:De,visitor_intent:Ie,wants_market_updates:k,has_agent:E,working_with_agent_name:E&&D.trim()?D.trim():null,partial_signin:!1}):(De=(await l.mutateAsync({open_house_id:n.id,first_name:y.first_name.trim(),last_name:y.last_name.trim()||void 0,email:y.email.trim()||void 0,phone:y.phone.trim()||void 0,visitor_intent:Ie,wants_market_updates:k,has_agent:E,working_with_agent_name:E&&D.trim()?D.trim():void 0,partial_signin:!1})).id,x(De)),(n==null?void 0:n.kind)==="virtual"){m("done");return}Z?!ee&&$&&$.length>0?m("survey"):m("pending_survey"):m("done")}catch{O("Something went wrong. Please try again.")}};if(a)return e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900 flex items-center justify-center",children:e.jsx("div",{className:"w-10 h-10 border-4 border-white/20 border-t-white rounded-full animate-spin"})});if(i||!n)return e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900 flex items-center justify-center p-6",children:e.jsxs("div",{className:"text-center text-white",children:[e.jsx(Fn,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("h1",{className:"text-2xl font-bold mb-2",children:"Open House Not Found"}),e.jsx("p",{className:"text-white/60",children:"This sign-in page doesn't exist or is no longer active."})]})});const ce=n.profiles,ne=((Pe=ce==null?void 0:ce.name)==null?void 0:Pe.split(" ").map(Ie=>Ie[0]).join("").slice(0,2))||"?",le=n.event_type==="community",be=n.kind==="virtual",fe=typeof window<"u"&&new URLSearchParams(window.location.search).get("preview")==="1";if(be&&(fe||h==="done"))return!fe&&!p?e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900 flex items-center justify-center",children:e.jsx("div",{className:"w-10 h-10 border-4 border-white/20 border-t-white rounded-full animate-spin"})}):e.jsxs(e.Fragment,{children:[e.jsxs(el,{children:[e.jsxs("title",{children:["Virtual Tour | ",n.property_address]}),e.jsx("meta",{name:"description",content:`Take a virtual tour of ${n.property_address}`}),e.jsx("meta",{name:"robots",content:"noindex, nofollow"})]}),fe&&e.jsx("div",{className:"fixed top-3 left-1/2 -translate-x-1/2 z-[100] bg-amber-500 text-white text-xs font-semibold px-3 py-1.5 rounded-full shadow-lg pointer-events-none",children:"Agent Preview Mode — visitors won't see this"}),e.jsx(xOt,{openHouse:n,visitorId:fe?"preview":p,visitorName:fe?"Preview Visitor":`${y.first_name} ${y.last_name}`.trim(),visitorEmail:fe?"":y.email,visitorPhone:fe?"":y.phone,previewMode:fe})]});const ve=`${be?"Virtual Open House":le?"Community Event":"Open House"} — ${n.property_address}`,Ve=[[n.city,n.state].filter(Boolean).join(", "),n.event_date?As(new Date(n.event_date+"T00:00:00"),"EEE, MMM d"):null,ce!=null&&ce.name?`Hosted by ${ce.name}`:null].filter(Boolean).join(" · "),Le=n.photo_url||"",Me=Le&&Le.includes("/storage/v1/object/public/")?Le.replace("/object/public/","/render/image/public/")+"?width=1200&height=630&resize=cover":Le||"https://dashboard.relevelup.com/og-image.png",ze=typeof window<"u"?window.location.href:`https://guestbook.relevelup.com/${r}`;return e.jsxs(e.Fragment,{children:[e.jsxs(el,{children:[e.jsx("title",{children:ve}),e.jsx("meta",{name:"description",content:Ve||`Sign in to ${n.property_address}`}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("meta",{property:"og:title",content:ve}),e.jsx("meta",{property:"og:description",content:Ve||`Sign in to ${n.property_address}`}),e.jsx("meta",{property:"og:image",content:Me}),e.jsx("meta",{property:"og:image:width",content:"1200"}),e.jsx("meta",{property:"og:image:height",content:"630"}),e.jsx("meta",{property:"og:url",content:ze}),e.jsx("meta",{property:"og:site_name",content:"ReLevel Up"}),e.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),e.jsx("meta",{name:"twitter:title",content:ve}),e.jsx("meta",{name:"twitter:description",content:Ve||`Sign in to ${n.property_address}`}),e.jsx("meta",{name:"twitter:image",content:Me}),e.jsx("meta",{name:"robots",content:"noindex, nofollow"})]}),e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900 flex items-center justify-center p-4",children:e.jsxs("div",{className:"w-full max-w-md",children:[e.jsxs("div",{className:"text-center mb-6",children:[e.jsxs(Un,{className:"h-16 w-16 mx-auto mb-3 ring-2 ring-white/20",children:[e.jsx(Ka,{src:(ce==null?void 0:ce.avatar_url)||"",alt:(ce==null?void 0:ce.name)||""}),e.jsx(qn,{className:"bg-white/10 text-white text-lg",children:ne})]}),e.jsx("p",{className:"text-white/60 text-sm",children:ce==null?void 0:ce.name}),(ce==null?void 0:ce.title)&&e.jsx("p",{className:"text-white/40 text-xs",children:ce.title})]}),e.jsxs("div",{className:"bg-white rounded-2xl shadow-2xl overflow-hidden",children:[n.photo_url&&e.jsxs("div",{className:"relative h-44 sm:h-52 overflow-hidden",children:[e.jsx("img",{src:n.photo_url,alt:n.property_address,className:"w-full h-full object-cover"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-slate-900/80 via-slate-900/20 to-transparent"}),e.jsxs("div",{className:"absolute bottom-0 left-0 right-0 px-6 pb-4",children:[e.jsx("h1",{className:"text-white font-bold text-lg leading-tight drop-shadow-md",children:n.property_address}),e.jsxs("div",{className:"flex flex-wrap gap-3 mt-1.5 text-white/70 text-xs",children:[n.city&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Qa,{className:"h-3 w-3"}),n.city,n.state?`, ${n.state}`:""," ",n.zip]}),!be&&e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Nn,{className:"h-3 w-3"}),As(new Date(n.event_date+"T00:00:00"),"MMM d, yyyy")]}),n.start_time&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Pn,{className:"h-3 w-3"}),K(n.start_time),n.end_time?` – ${K(n.end_time)}`:""]})]})]})]})]}),!n.photo_url&&e.jsx("div",{className:"bg-gradient-to-r from-slate-800 to-slate-700 px-6 py-5",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-white/10 flex items-center justify-center shrink-0 mt-0.5",children:le?e.jsx(Xa,{className:"h-5 w-5 text-white"}):e.jsx(Fn,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-white font-bold text-lg leading-tight",children:n.property_address}),e.jsxs("div",{className:"flex flex-wrap gap-3 mt-2 text-white/60 text-xs",children:[n.city&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Qa,{className:"h-3 w-3"}),n.city,n.state?`, ${n.state}`:""," ",n.zip]}),!be&&e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Nn,{className:"h-3 w-3"}),As(new Date(n.event_date+"T00:00:00"),"MMM d, yyyy")]}),n.start_time&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Pn,{className:"h-3 w-3"}),K(n.start_time),n.end_time?` – ${K(n.end_time)}`:""]})]})]})]})]})}),e.jsxs("div",{className:"p-6",children:[h==="welcome"&&e.jsxs("div",{className:"text-center space-y-6",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-bold text-slate-900 mb-2",children:"Welcome!"}),e.jsx("p",{className:"text-slate-500 text-sm",children:n.agent_greeting||"Please sign in below."})]}),e.jsxs(H,{onClick:()=>m("info"),className:"w-full h-14 text-base bg-slate-900 hover:bg-slate-800 text-white rounded-xl",children:["Sign In ",e.jsx(bi,{className:"h-5 w-5 ml-2"})]}),e.jsx("p",{className:"text-xs text-slate-400",children:"Quick & easy — takes 30 seconds"})]}),h==="info"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("button",{onClick:()=>m("welcome"),className:"text-slate-400 hover:text-slate-600",children:e.jsx(za,{className:"h-4 w-4"})}),e.jsx("h2",{className:"text-lg font-bold text-slate-900",children:"Your Info"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ue,{className:"text-slate-600 text-xs",children:"First Name *"}),e.jsx(Se,{value:y.first_name,onChange:Ie=>_(De=>({...De,first_name:Ie.target.value})),placeholder:"First",className:"mt-1 h-12 rounded-xl border-slate-200 text-base",autoFocus:!0})]}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-slate-600 text-xs",children:"Last Name"}),e.jsx(Se,{value:y.last_name,onChange:Ie=>_(De=>({...De,last_name:Ie.target.value})),placeholder:"Last",className:"mt-1 h-12 rounded-xl border-slate-200 text-base"})]})]}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-slate-600 text-xs",children:"Email"}),e.jsx(Se,{type:"email",value:y.email,onChange:Ie=>_(De=>({...De,email:Ie.target.value})),placeholder:"your@email.com",className:"mt-1 h-12 rounded-xl border-slate-200 text-base"})]}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-slate-600 text-xs",children:"Phone"}),e.jsx(Se,{type:"tel",value:y.phone,onChange:Ie=>_(De=>({...De,phone:Ie.target.value})),placeholder:"(555) 123-4567",className:"mt-1 h-12 rounded-xl border-slate-200 text-base"})]}),e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer pt-1",children:[e.jsx("input",{type:"checkbox",checked:k,onChange:Ie=>T(Ie.target.checked),className:"rounded border-slate-300 text-slate-900 focus:ring-slate-500"}),e.jsx("span",{className:"text-sm text-slate-600",children:"Send me market updates for this area"})]}),e.jsxs("div",{className:"space-y-2 pt-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm text-slate-600",children:"Already working with an agent?"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs font-medium text-slate-400",children:E?"Yes":"No"}),e.jsx(Or,{checked:E,onCheckedChange:A})]})]}),E&&e.jsx(Se,{value:D,onChange:Ie=>R(Ie.target.value),placeholder:"Agent's name",className:"mt-1 h-10 rounded-xl border-slate-200 text-sm"})]}),z&&e.jsx("p",{className:"text-destructive text-sm",children:z}),e.jsxs(H,{onClick:re,className:"w-full h-14 text-base bg-slate-900 hover:bg-slate-800 text-white rounded-xl",children:["Continue ",e.jsx(bi,{className:"h-5 w-5 ml-2"})]})]}),h==="intent"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("button",{onClick:()=>m("info"),className:"text-slate-400 hover:text-slate-600",children:e.jsx(za,{className:"h-4 w-4"})}),e.jsx("h2",{className:"text-lg font-bold text-slate-900",children:"What brings you here?"})]}),e.jsx("div",{className:"grid grid-cols-2 gap-3",children:vOt.map(Ie=>e.jsxs("button",{onClick:()=>ie(Ie.value),disabled:l.isPending,className:"flex flex-col items-center gap-2 p-5 rounded-xl border-2 border-slate-200 hover:border-slate-900 hover:bg-slate-50 transition-all text-center group",children:[e.jsx("span",{className:"text-2xl",children:Ie.emoji}),e.jsx("span",{className:"text-sm font-medium text-slate-700 group-hover:text-slate-900",children:Ie.label})]},Ie.value))}),z&&e.jsx("p",{className:"text-destructive text-sm text-center",children:z})]}),h==="pending_survey"&&e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 gap-3",children:[e.jsx("div",{className:"w-8 h-8 border-[3px] border-slate-200 border-t-slate-900 rounded-full animate-spin"}),e.jsx("p",{className:"text-sm text-slate-500",children:"Loading survey..."})]}),h==="survey"&&p&&$&&e.jsx(iOt,{questions:$,visitorId:p,onComplete:()=>m("done"),onSkip:()=>m("done")}),h==="done"&&e.jsxs("div",{className:"text-center space-y-4 py-4",children:[e.jsx("div",{className:"w-16 h-16 rounded-full bg-green-100 flex items-center justify-center mx-auto",children:e.jsx(ea,{className:"h-8 w-8 text-green-600"})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-bold text-slate-900",children:"You're all set!"}),e.jsxs("p",{className:"text-slate-500 text-sm mt-1",children:["Thanks for signing in, ",y.first_name,". ",le?"Enjoy the event!":"Enjoy the open house!"]})]}),(n==null?void 0:n.disclosure_pdf_url)&&e.jsxs("a",{href:`https://docs.google.com/gview?url=${encodeURIComponent(n.disclosure_pdf_url)}&embedded=true`,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-2 px-5 py-3 rounded-xl bg-slate-100 hover:bg-slate-200 text-slate-800 font-medium text-sm transition-colors",children:[e.jsx(kn,{className:"h-4 w-4"}),"View Seller's Disclosures"]}),(ce==null?void 0:ce.name)&&e.jsxs("p",{className:"text-sm text-slate-400",children:["Your host today: ",e.jsx("strong",{className:"text-slate-600",children:ce.name})]})]})]})]}),e.jsx("p",{className:"text-center text-white/30 text-xs mt-6",children:"Powered by LevelUp Guest Book"})]})})]})}function IZs(s){const{user:t}=Ms();return yt({queryKey:["cohost-tokens",s],queryFn:async()=>{const{data:r,error:n}=await V.from("open_house_cohost_tokens").select("*").eq("open_house_id",s).order("created_at",{ascending:!1});if(n)throw n;return r},enabled:!!t&&!!s})}function PZs(){const s=ns(),{user:t}=Ms();return Pt({mutationFn:async({openHouseId:r,label:n})=>{const{data:a,error:i}=await V.from("open_house_cohost_tokens").insert({open_house_id:r,label:n||null,created_by:t.id,expires_at:new Date(Date.now()+864e5).toISOString()}).select().single();if(i)throw i;return a},onSuccess:(r,n)=>{s.invalidateQueries({queryKey:["cohost-tokens",n.openHouseId]})}})}function LZs(){const s=ns();return Pt({mutationFn:async({id:t,openHouseId:r})=>{const{error:n}=await V.from("open_house_cohost_tokens").update({is_active:!1}).eq("id",t);if(n)throw n},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["cohost-tokens",r.openHouseId]})}})}function bOt(s){return yt({queryKey:["cohost-validate",s],queryFn:async()=>{const{data:t,error:r}=await V.from("open_house_cohost_tokens").select("*, open_houses(*)").eq("token",s).eq("is_active",!0).single();if(r)throw r;if(t.expires_at&&new Date(t.expires_at)t[r][n]??r,s)}var w5e="ScrollArea",[Drt,DZs]=_u(w5e),[wOt,nv]=Drt(w5e),Rrt=S.forwardRef((s,t)=>{const{__scopeScrollArea:r,type:n="hover",dir:a,scrollHideDelay:i=600,...l}=s,[o,c]=S.useState(null),[d,h]=S.useState(null),[m,p]=S.useState(null),[x,y]=S.useState(null),[_,b]=S.useState(null),[j,k]=S.useState(0),[T,E]=S.useState(0),[A,D]=S.useState(!1),[R,z]=S.useState(!1),O=_i(t,ee=>c(ee)),$=RS(a);return e.jsx(wOt,{scope:r,type:n,dir:$,scrollHideDelay:i,scrollArea:o,viewport:d,onViewportChange:h,content:m,onContentChange:p,scrollbarX:x,onScrollbarXChange:y,scrollbarXEnabled:A,onScrollbarXEnabledChange:D,scrollbarY:_,onScrollbarYChange:b,scrollbarYEnabled:R,onScrollbarYEnabledChange:z,onCornerWidthChange:k,onCornerHeightChange:E,children:e.jsx(Vn.div,{dir:$,...l,ref:O,style:{position:"relative","--radix-scroll-area-corner-width":j+"px","--radix-scroll-area-corner-height":T+"px",...s.style}})})});Rrt.displayName=w5e;var Ort="ScrollAreaViewport",Frt=S.forwardRef((s,t)=>{const{__scopeScrollArea:r,children:n,nonce:a,...i}=s,l=nv(Ort,r),o=S.useRef(null),c=_i(t,o,l.onViewportChange);return e.jsxs(e.Fragment,{children:[e.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:a}),e.jsx(Vn.div,{"data-radix-scroll-area-viewport":"",...i,ref:c,style:{overflowX:l.scrollbarXEnabled?"scroll":"hidden",overflowY:l.scrollbarYEnabled?"scroll":"hidden",...s.style},children:e.jsx("div",{ref:l.onContentChange,style:{minWidth:"100%",display:"table"},children:n})})]})});Frt.displayName=Ort;var H_="ScrollAreaScrollbar",j5e=S.forwardRef((s,t)=>{const{forceMount:r,...n}=s,a=nv(H_,s.__scopeScrollArea),{onScrollbarXEnabledChange:i,onScrollbarYEnabledChange:l}=a,o=s.orientation==="horizontal";return S.useEffect(()=>(o?i(!0):l(!0),()=>{o?i(!1):l(!1)}),[o,i,l]),a.type==="hover"?e.jsx(jOt,{...n,ref:t,forceMount:r}):a.type==="scroll"?e.jsx(NOt,{...n,ref:t,forceMount:r}):a.type==="auto"?e.jsx(Brt,{...n,ref:t,forceMount:r}):a.type==="always"?e.jsx(N5e,{...n,ref:t}):null});j5e.displayName=H_;var jOt=S.forwardRef((s,t)=>{const{forceMount:r,...n}=s,a=nv(H_,s.__scopeScrollArea),[i,l]=S.useState(!1);return S.useEffect(()=>{const o=a.scrollArea;let c=0;if(o){const d=()=>{window.clearTimeout(c),l(!0)},h=()=>{c=window.setTimeout(()=>l(!1),a.scrollHideDelay)};return o.addEventListener("pointerenter",d),o.addEventListener("pointerleave",h),()=>{window.clearTimeout(c),o.removeEventListener("pointerenter",d),o.removeEventListener("pointerleave",h)}}},[a.scrollArea,a.scrollHideDelay]),e.jsx(vh,{present:r||i,children:e.jsx(Brt,{"data-state":i?"visible":"hidden",...n,ref:t})})}),NOt=S.forwardRef((s,t)=>{const{forceMount:r,...n}=s,a=nv(H_,s.__scopeScrollArea),i=s.orientation==="horizontal",l=Mge(()=>c("SCROLL_END"),100),[o,c]=_Ot("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 S.useEffect(()=>{if(o==="idle"){const d=window.setTimeout(()=>c("HIDE"),a.scrollHideDelay);return()=>window.clearTimeout(d)}},[o,a.scrollHideDelay,c]),S.useEffect(()=>{const d=a.viewport,h=i?"scrollLeft":"scrollTop";if(d){let m=d[h];const p=()=>{const x=d[h];m!==x&&(c("SCROLL"),l()),m=x};return d.addEventListener("scroll",p),()=>d.removeEventListener("scroll",p)}},[a.viewport,i,c,l]),e.jsx(vh,{present:r||o!=="hidden",children:e.jsx(N5e,{"data-state":o==="hidden"?"hidden":"visible",...n,ref:t,onPointerEnter:an(s.onPointerEnter,()=>c("POINTER_ENTER")),onPointerLeave:an(s.onPointerLeave,()=>c("POINTER_LEAVE"))})})}),Brt=S.forwardRef((s,t)=>{const r=nv(H_,s.__scopeScrollArea),{forceMount:n,...a}=s,[i,l]=S.useState(!1),o=s.orientation==="horizontal",c=Mge(()=>{if(r.viewport){const d=r.viewport.offsetWidth{const{orientation:r="vertical",...n}=s,a=nv(H_,s.__scopeScrollArea),i=S.useRef(null),l=S.useRef(0),[o,c]=S.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),d=Vrt(o.viewport,o.content),h={...n,sizes:o,onSizesChange:c,hasThumb:d>0&&d<1,onThumbChange:p=>i.current=p,onThumbPointerUp:()=>l.current=0,onThumbPointerDown:p=>l.current=p};function m(p,x){return AOt(p,l.current,o,x)}return r==="horizontal"?e.jsx(kOt,{...h,ref:t,onThumbPositionChange:()=>{if(a.viewport&&i.current){const p=a.viewport.scrollLeft,x=hFe(p,o,a.dir);i.current.style.transform=`translate3d(${x}px, 0, 0)`}},onWheelScroll:p=>{a.viewport&&(a.viewport.scrollLeft=p)},onDragScroll:p=>{a.viewport&&(a.viewport.scrollLeft=m(p,a.dir))}}):r==="vertical"?e.jsx(SOt,{...h,ref:t,onThumbPositionChange:()=>{if(a.viewport&&i.current){const p=a.viewport.scrollTop,x=hFe(p,o);i.current.style.transform=`translate3d(0, ${x}px, 0)`}},onWheelScroll:p=>{a.viewport&&(a.viewport.scrollTop=p)},onDragScroll:p=>{a.viewport&&(a.viewport.scrollTop=m(p))}}):null}),kOt=S.forwardRef((s,t)=>{const{sizes:r,onSizesChange:n,...a}=s,i=nv(H_,s.__scopeScrollArea),[l,o]=S.useState(),c=S.useRef(null),d=_i(t,c,i.onScrollbarXChange);return S.useEffect(()=>{c.current&&o(getComputedStyle(c.current))},[c]),e.jsx($rt,{"data-orientation":"horizontal",...a,ref:d,sizes:r,style:{bottom:0,left:i.dir==="rtl"?"var(--radix-scroll-area-corner-width)":0,right:i.dir==="ltr"?"var(--radix-scroll-area-corner-width)":0,"--radix-scroll-area-thumb-width":Age(r)+"px",...s.style},onThumbPointerDown:h=>s.onThumbPointerDown(h.x),onDragScroll:h=>s.onDragScroll(h.x),onWheelScroll:(h,m)=>{if(i.viewport){const p=i.viewport.scrollLeft+h.deltaX;s.onWheelScroll(p),Grt(p,m)&&h.preventDefault()}},onResize:()=>{c.current&&i.viewport&&l&&n({content:i.viewport.scrollWidth,viewport:i.viewport.offsetWidth,scrollbar:{size:c.current.clientWidth,paddingStart:zhe(l.paddingLeft),paddingEnd:zhe(l.paddingRight)}})}})}),SOt=S.forwardRef((s,t)=>{const{sizes:r,onSizesChange:n,...a}=s,i=nv(H_,s.__scopeScrollArea),[l,o]=S.useState(),c=S.useRef(null),d=_i(t,c,i.onScrollbarYChange);return S.useEffect(()=>{c.current&&o(getComputedStyle(c.current))},[c]),e.jsx($rt,{"data-orientation":"vertical",...a,ref:d,sizes:r,style:{top:0,right:i.dir==="ltr"?0:void 0,left:i.dir==="rtl"?0:void 0,bottom:"var(--radix-scroll-area-corner-height)","--radix-scroll-area-thumb-height":Age(r)+"px",...s.style},onThumbPointerDown:h=>s.onThumbPointerDown(h.y),onDragScroll:h=>s.onDragScroll(h.y),onWheelScroll:(h,m)=>{if(i.viewport){const p=i.viewport.scrollTop+h.deltaY;s.onWheelScroll(p),Grt(p,m)&&h.preventDefault()}},onResize:()=>{c.current&&i.viewport&&l&&n({content:i.viewport.scrollHeight,viewport:i.viewport.offsetHeight,scrollbar:{size:c.current.clientHeight,paddingStart:zhe(l.paddingTop),paddingEnd:zhe(l.paddingBottom)}})}})}),[COt,zrt]=Drt(H_),$rt=S.forwardRef((s,t)=>{const{__scopeScrollArea:r,sizes:n,hasThumb:a,onThumbChange:i,onThumbPointerUp:l,onThumbPointerDown:o,onThumbPositionChange:c,onDragScroll:d,onWheelScroll:h,onResize:m,...p}=s,x=nv(H_,r),[y,_]=S.useState(null),b=_i(t,O=>_(O)),j=S.useRef(null),k=S.useRef(""),T=x.viewport,E=n.content-n.viewport,A=Uu(h),D=Uu(c),R=Mge(m,10);function z(O){if(j.current){const $=O.clientX-j.current.left,ee=O.clientY-j.current.top;d({x:$,y:ee})}}return S.useEffect(()=>{const O=$=>{const ee=$.target;(y==null?void 0:y.contains(ee))&&A($,E)};return document.addEventListener("wheel",O,{passive:!1}),()=>document.removeEventListener("wheel",O,{passive:!1})},[T,y,E,A]),S.useEffect(D,[n,D]),sL(y,R),sL(x.content,R),e.jsx(COt,{scope:r,scrollbar:y,hasThumb:a,onThumbChange:Uu(i),onThumbPointerUp:Uu(l),onThumbPositionChange:D,onThumbPointerDown:Uu(o),children:e.jsx(Vn.div,{...p,ref:b,style:{position:"absolute",...p.style},onPointerDown:an(s.onPointerDown,O=>{O.button===0&&(O.target.setPointerCapture(O.pointerId),j.current=y.getBoundingClientRect(),k.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",x.viewport&&(x.viewport.style.scrollBehavior="auto"),z(O))}),onPointerMove:an(s.onPointerMove,z),onPointerUp:an(s.onPointerUp,O=>{const $=O.target;$.hasPointerCapture(O.pointerId)&&$.releasePointerCapture(O.pointerId),document.body.style.webkitUserSelect=k.current,x.viewport&&(x.viewport.style.scrollBehavior=""),j.current=null})})})}),Bhe="ScrollAreaThumb",Urt=S.forwardRef((s,t)=>{const{forceMount:r,...n}=s,a=zrt(Bhe,s.__scopeScrollArea);return e.jsx(vh,{present:r||a.hasThumb,children:e.jsx(TOt,{ref:t,...n})})}),TOt=S.forwardRef((s,t)=>{const{__scopeScrollArea:r,style:n,...a}=s,i=nv(Bhe,r),l=zrt(Bhe,r),{onThumbPositionChange:o}=l,c=_i(t,m=>l.onThumbChange(m)),d=S.useRef(void 0),h=Mge(()=>{d.current&&(d.current(),d.current=void 0)},100);return S.useEffect(()=>{const m=i.viewport;if(m){const p=()=>{if(h(),!d.current){const x=MOt(m,o);d.current=x,o()}};return o(),m.addEventListener("scroll",p),()=>m.removeEventListener("scroll",p)}},[i.viewport,h,o]),e.jsx(Vn.div,{"data-state":l.hasThumb?"visible":"hidden",...a,ref:c,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...n},onPointerDownCapture:an(s.onPointerDownCapture,m=>{const x=m.target.getBoundingClientRect(),y=m.clientX-x.left,_=m.clientY-x.top;l.onThumbPointerDown({x:y,y:_})}),onPointerUp:an(s.onPointerUp,l.onThumbPointerUp)})});Urt.displayName=Bhe;var k5e="ScrollAreaCorner",qrt=S.forwardRef((s,t)=>{const r=nv(k5e,s.__scopeScrollArea),n=!!(r.scrollbarX&&r.scrollbarY);return r.type!=="scroll"&&n?e.jsx(EOt,{...s,ref:t}):null});qrt.displayName=k5e;var EOt=S.forwardRef((s,t)=>{const{__scopeScrollArea:r,...n}=s,a=nv(k5e,r),[i,l]=S.useState(0),[o,c]=S.useState(0),d=!!(i&&o);return sL(a.scrollbarX,()=>{var m;const h=((m=a.scrollbarX)==null?void 0:m.offsetHeight)||0;a.onCornerHeightChange(h),c(h)}),sL(a.scrollbarY,()=>{var m;const h=((m=a.scrollbarY)==null?void 0:m.offsetWidth)||0;a.onCornerWidthChange(h),l(h)}),d?e.jsx(Vn.div,{...n,ref:t,style:{width:i,height:o,position:"absolute",right:a.dir==="ltr"?0:void 0,left:a.dir==="rtl"?0:void 0,bottom:0,...s.style}}):null});function zhe(s){return s?parseInt(s,10):0}function Vrt(s,t){const r=s/t;return isNaN(r)?0:r}function Age(s){const t=Vrt(s.viewport,s.content),r=s.scrollbar.paddingStart+s.scrollbar.paddingEnd,n=(s.scrollbar.size-r)*t;return Math.max(n,18)}function AOt(s,t,r,n="ltr"){const a=Age(r),i=a/2,l=t||i,o=a-l,c=r.scrollbar.paddingStart+l,d=r.scrollbar.size-r.scrollbar.paddingEnd-o,h=r.content-r.viewport,m=n==="ltr"?[0,h]:[h*-1,0];return Hrt([c,d],m)(s)}function hFe(s,t,r="ltr"){const n=Age(t),a=t.scrollbar.paddingStart+t.scrollbar.paddingEnd,i=t.scrollbar.size-a,l=t.content-t.viewport,o=i-n,c=r==="ltr"?[0,l]:[l*-1,0],d=c9(s,c);return Hrt([0,l],[0,o])(d)}function Hrt(s,t){return r=>{if(s[0]===s[1]||t[0]===t[1])return t[0];const n=(t[1]-t[0])/(s[1]-s[0]);return t[0]+n*(r-s[0])}}function Grt(s,t){return s>0&&s{})=>{let r={left:s.scrollLeft,top:s.scrollTop},n=0;return function a(){const i={left:s.scrollLeft,top:s.scrollTop},l=r.left!==i.left,o=r.top!==i.top;(l||o)&&t(),r=i,n=window.requestAnimationFrame(a)}(),()=>window.cancelAnimationFrame(n)};function Mge(s,t){const r=Uu(s),n=S.useRef(0);return S.useEffect(()=>()=>window.clearTimeout(n.current),[]),S.useCallback(()=>{window.clearTimeout(n.current),n.current=window.setTimeout(r,t)},[r,t])}function sL(s,t){const r=Uu(t);Ku(()=>{let n=0;if(s){const a=new ResizeObserver(()=>{cancelAnimationFrame(n),n=window.requestAnimationFrame(r)});return a.observe(s),()=>{window.cancelAnimationFrame(n),a.unobserve(s)}}},[s,r])}var Wrt=Rrt,IOt=Frt,POt=qrt;const Ci=S.forwardRef(({className:s,children:t,...r},n)=>e.jsxs(Wrt,{ref:n,className:Ft("relative overflow-hidden",s),...r,children:[e.jsx(IOt,{className:"h-full w-full rounded-[inherit]",children:t}),e.jsx(Ige,{}),e.jsx(POt,{})]}));Ci.displayName=Wrt.displayName;const Ige=S.forwardRef(({className:s,orientation:t="vertical",...r},n)=>e.jsx(j5e,{ref:n,orientation:t,className:Ft("flex touch-none select-none transition-colors",t==="vertical"&&"h-full w-2.5 border-l border-l-transparent p-[1px]",t==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",s),...r,children:e.jsx(Urt,{className:"relative flex-1 rounded-full bg-border"})}));Ige.displayName=j5e.displayName;const S5e=S.createContext({});function C5e(s){const t=S.useRef(null);return t.current===null&&(t.current=s()),t.current}const LOt=typeof window<"u",Krt=LOt?S.useLayoutEffect:S.useEffect,Pge=S.createContext(null);function T5e(s,t){s.indexOf(t)===-1&&s.push(t)}function $he(s,t){const r=s.indexOf(t);r>-1&&s.splice(r,1)}const I_=(s,t,r)=>r>t?t:r{},rL=()=>{};const _S={},Yrt=s=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(s);function Zrt(s){return typeof s=="object"&&s!==null}const Xrt=s=>/^0[^.\s]+$/u.test(s);function Qrt(s){let t;return()=>(t===void 0&&(t=s()),t)}const Wy=s=>s,DOt=(s,t)=>r=>t(s(r)),ez=(...s)=>s.reduce(DOt),h9=(s,t,r)=>{const n=t-s;return n===0?1:(r-s)/n};class E5e{constructor(){this.subscriptions=[]}add(t){return T5e(this.subscriptions,t),()=>$he(this.subscriptions,t)}notify(t,r,n){const a=this.subscriptions.length;if(a)if(a===1)this.subscriptions[0](t,r,n);else for(let i=0;is*1e3,Fy=s=>s/1e3;function Jrt(s,t){return t?s*(1e3/t):0}const ent=(s,t,r)=>(((1-3*r+3*t)*s+(3*r-6*t))*s+3*t)*s,ROt=1e-7,OOt=12;function FOt(s,t,r,n,a){let i,l,o=0;do l=t+(r-t)/2,i=ent(l,n,a)-s,i>0?r=l:t=l;while(Math.abs(i)>ROt&&++oFOt(i,0,1,s,r);return i=>i===0||i===1?i:ent(a(i),t,n)}const tnt=s=>t=>t<=.5?s(2*t)/2:(2-s(2*(1-t)))/2,snt=s=>t=>1-s(1-t),rnt=tz(.33,1.53,.69,.99),A5e=snt(rnt),nnt=tnt(A5e),ant=s=>s>=1?1:(s*=2)<1?.5*A5e(s):.5*(2-Math.pow(2,-10*(s-1))),M5e=s=>1-Math.sin(Math.acos(s)),int=snt(M5e),ont=tnt(M5e),BOt=tz(.42,0,1,1),zOt=tz(0,0,.58,1),lnt=tz(.42,0,.58,1),$Ot=s=>Array.isArray(s)&&typeof s[0]!="number",cnt=s=>Array.isArray(s)&&typeof s[0]=="number",mFe={linear:Wy,easeIn:BOt,easeInOut:lnt,easeOut:zOt,circIn:M5e,circInOut:ont,circOut:int,backIn:A5e,backInOut:nnt,backOut:rnt,anticipate:ant},UOt=s=>typeof s=="string",fFe=s=>{if(cnt(s)){rL(s.length===4,"Cubic bezier arrays must contain four numerical values.","cubic-bezier-length");const[t,r,n,a]=s;return tz(t,r,n,a)}else if(UOt(s))return rL(mFe[s]!==void 0,`Invalid easing type '${s}'`,"invalid-easing-type"),mFe[s];return s},HU=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"],pFe={value:null,addProjectionMetrics:null};function qOt(s,t){let r=new Set,n=new Set,a=!1,i=!1;const l=new WeakSet;let o={delta:0,timestamp:0,isProcessing:!1},c=0;function d(m){l.has(m)&&(h.schedule(m),s()),c++,m(o)}const h={schedule:(m,p=!1,x=!1)=>{const _=x&&a?r:n;return p&&l.add(m),_.add(m),m},cancel:m=>{n.delete(m),l.delete(m)},process:m=>{if(o=m,a){i=!0;return}a=!0;const p=r;r=n,n=p,r.forEach(d),t&&pFe.value&&pFe.value.frameloop[t].push(c),c=0,r.clear(),a=!1,i&&(i=!1,h.process(m))}};return h}const VOt=40;function dnt(s,t){let r=!1,n=!0;const a={delta:0,timestamp:0,isProcessing:!1},i=()=>r=!0,l=HU.reduce((T,E)=>(T[E]=qOt(i,t?E:void 0),T),{}),{setup:o,read:c,resolveKeyframes:d,preUpdate:h,update:m,preRender:p,render:x,postRender:y}=l,_=()=>{const T=_S.useManualTiming,E=T?a.timestamp:performance.now();r=!1,T||(a.delta=n?1e3/60:Math.max(Math.min(E-a.timestamp,VOt),1)),a.timestamp=E,a.isProcessing=!0,o.process(a),c.process(a),d.process(a),h.process(a),m.process(a),p.process(a),x.process(a),y.process(a),a.isProcessing=!1,r&&t&&(n=!1,s(_))},b=()=>{r=!0,n=!0,a.isProcessing||s(_)};return{schedule:HU.reduce((T,E)=>{const A=l[E];return T[E]=(D,R=!1,z=!1)=>(r||b(),A.schedule(D,R,z)),T},{}),cancel:T=>{for(let E=0;E(fue===void 0&&ug.set(Mf.isProcessing||_S.useManualTiming?Mf.timestamp:performance.now()),fue),set:s=>{fue=s,queueMicrotask(HOt)}},unt=s=>t=>typeof t=="string"&&t.startsWith(s),hnt=unt("--"),GOt=unt("var(--"),I5e=s=>GOt(s)?WOt.test(s.split("/*")[0].trim()):!1,WOt=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu;function gFe(s){return typeof s!="string"?!1:s.split("/*")[0].includes("var(--")}const p8={test:s=>typeof s=="number",parse:parseFloat,transform:s=>s},m9={...p8,transform:s=>I_(0,1,s)},GU={...p8,default:1},XF=s=>Math.round(s*1e5)/1e5,P5e=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function KOt(s){return s==null}const YOt=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,L5e=(s,t)=>r=>!!(typeof r=="string"&&YOt.test(r)&&r.startsWith(s)||t&&!KOt(r)&&Object.prototype.hasOwnProperty.call(r,t)),mnt=(s,t,r)=>n=>{if(typeof n!="string")return n;const[a,i,l,o]=n.match(P5e);return{[s]:parseFloat(a),[t]:parseFloat(i),[r]:parseFloat(l),alpha:o!==void 0?parseFloat(o):1}},ZOt=s=>I_(0,255,s),cbe={...p8,transform:s=>Math.round(ZOt(s))},OT={test:L5e("rgb","red"),parse:mnt("red","green","blue"),transform:({red:s,green:t,blue:r,alpha:n=1})=>"rgba("+cbe.transform(s)+", "+cbe.transform(t)+", "+cbe.transform(r)+", "+XF(m9.transform(n))+")"};function XOt(s){let t="",r="",n="",a="";return s.length>5?(t=s.substring(1,3),r=s.substring(3,5),n=s.substring(5,7),a=s.substring(7,9)):(t=s.substring(1,2),r=s.substring(2,3),n=s.substring(3,4),a=s.substring(4,5),t+=t,r+=r,n+=n,a+=a),{red:parseInt(t,16),green:parseInt(r,16),blue:parseInt(n,16),alpha:a?parseInt(a,16)/255:1}}const uNe={test:L5e("#"),parse:XOt,transform:OT.transform},sz=s=>({test:t=>typeof t=="string"&&t.endsWith(s)&&t.split(" ").length===1,parse:parseFloat,transform:t=>`${t}${s}`}),IN=sz("deg"),j_=sz("%"),ti=sz("px"),QOt=sz("vh"),JOt=sz("vw"),xFe={...j_,parse:s=>j_.parse(s)/100,transform:s=>j_.transform(s*100)},lI={test:L5e("hsl","hue"),parse:mnt("hue","saturation","lightness"),transform:({hue:s,saturation:t,lightness:r,alpha:n=1})=>"hsla("+Math.round(s)+", "+j_.transform(XF(t))+", "+j_.transform(XF(r))+", "+XF(m9.transform(n))+")"},Mh={test:s=>OT.test(s)||uNe.test(s)||lI.test(s),parse:s=>OT.test(s)?OT.parse(s):lI.test(s)?lI.parse(s):uNe.parse(s),transform:s=>typeof s=="string"?s:s.hasOwnProperty("red")?OT.transform(s):lI.transform(s),getAnimatableNone:s=>{const t=Mh.parse(s);return t.alpha=0,Mh.transform(t)}},eFt=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function tFt(s){var t,r;return isNaN(s)&&typeof s=="string"&&(((t=s.match(P5e))==null?void 0:t.length)||0)+(((r=s.match(eFt))==null?void 0:r.length)||0)>0}const fnt="number",pnt="color",sFt="var",rFt="var(",yFe="${}",nFt=/var\s*\(\s*--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)|#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\)|-?(?:\d+(?:\.\d+)?|\.\d+)/giu;function nL(s){const t=s.toString(),r=[],n={color:[],number:[],var:[]},a=[];let i=0;const o=t.replace(nFt,c=>(Mh.test(c)?(n.color.push(i),a.push(pnt),r.push(Mh.parse(c))):c.startsWith(rFt)?(n.var.push(i),a.push(sFt),r.push(c)):(n.number.push(i),a.push(fnt),r.push(parseFloat(c))),++i,yFe)).split(yFe);return{values:r,split:o,indexes:n,types:a}}function aFt(s){return nL(s).values}function gnt({split:s,types:t}){const r=s.length;return n=>{let a="";for(let i=0;itypeof s=="number"?0:Mh.test(s)?Mh.getAnimatableNone(s):s,lFt=(s,t)=>typeof s=="number"?t!=null&&t.trim().endsWith("/")?s:0:oFt(s);function cFt(s){const t=nL(s);return gnt(t)(t.values.map((n,a)=>lFt(n,t.split[a])))}const k1={test:tFt,parse:aFt,createTransformer:iFt,getAnimatableNone:cFt};function dbe(s,t,r){return r<0&&(r+=1),r>1&&(r-=1),r<1/6?s+(t-s)*6*r:r<1/2?t:r<2/3?s+(t-s)*(2/3-r)*6:s}function dFt({hue:s,saturation:t,lightness:r,alpha:n}){s/=360,t/=100,r/=100;let a=0,i=0,l=0;if(!t)a=i=l=r;else{const o=r<.5?r*(1+t):r+t-r*t,c=2*r-o;a=dbe(c,o,s+1/3),i=dbe(c,o,s),l=dbe(c,o,s-1/3)}return{red:Math.round(a*255),green:Math.round(i*255),blue:Math.round(l*255),alpha:n}}function Uhe(s,t){return r=>r>0?t:s}const Sd=(s,t,r)=>s+(t-s)*r,ube=(s,t,r)=>{const n=s*s,a=r*(t*t-n)+n;return a<0?0:Math.sqrt(a)},uFt=[uNe,OT,lI],hFt=s=>uFt.find(t=>t.test(s));function vFe(s){const t=hFt(s);if(Lge(!!t,`'${s}' is not an animatable color. Use the equivalent color code instead.`,"color-not-animatable"),!t)return!1;let r=t.parse(s);return t===lI&&(r=dFt(r)),r}const bFe=(s,t)=>{const r=vFe(s),n=vFe(t);if(!r||!n)return Uhe(s,t);const a={...r};return i=>(a.red=ube(r.red,n.red,i),a.green=ube(r.green,n.green,i),a.blue=ube(r.blue,n.blue,i),a.alpha=Sd(r.alpha,n.alpha,i),OT.transform(a))},hNe=new Set(["none","hidden"]);function mFt(s,t){return hNe.has(s)?r=>r<=0?s:t:r=>r>=1?t:s}function fFt(s,t){return r=>Sd(s,t,r)}function D5e(s){return typeof s=="number"?fFt:typeof s=="string"?I5e(s)?Uhe:Mh.test(s)?bFe:xFt:Array.isArray(s)?xnt:typeof s=="object"?Mh.test(s)?bFe:pFt:Uhe}function xnt(s,t){const r=[...s],n=r.length,a=s.map((i,l)=>D5e(i)(i,t[l]));return i=>{for(let l=0;l{for(const i in n)r[i]=n[i](a);return r}}function gFt(s,t){const r=[],n={color:0,var:0,number:0};for(let a=0;a{const r=k1.createTransformer(t),n=nL(s),a=nL(t);return n.indexes.var.length===a.indexes.var.length&&n.indexes.color.length===a.indexes.color.length&&n.indexes.number.length>=a.indexes.number.length?hNe.has(s)&&!a.values.length||hNe.has(t)&&!n.values.length?mFt(s,t):ez(xnt(gFt(n,a),a.values),r):(Lge(!0,`Complex values '${s}' and '${t}' too different to mix. Ensure all colors are of the same type, and that each contains the same quantity of number and color values. Falling back to instant transition.`,"complex-values-different"),Uhe(s,t))};function ynt(s,t,r){return typeof s=="number"&&typeof t=="number"&&typeof r=="number"?Sd(s,t,r):D5e(s)(s,t)}const yFt=s=>{const t=({timestamp:r})=>s(r);return{start:(r=!0)=>zc.update(t,r),stop:()=>wS(t),now:()=>Mf.isProcessing?Mf.timestamp:ug.now()}},vnt=(s,t,r=10)=>{let n="";const a=Math.max(Math.round(t/r),2);for(let i=0;i=qhe?1/0:t}function vFt(s,t=100,r){const n=r({...s,keyframes:[0,t]}),a=Math.min(R5e(n),qhe);return{type:"keyframes",ease:i=>n.next(a*i).value/t,duration:Fy(a)}}const lu={stiffness:100,damping:10,mass:1,velocity:0,duration:800,bounce:.3,visualDuration:.3,restSpeed:{granular:.01,default:2},restDelta:{granular:.005,default:.5},minDuration:.01,maxDuration:10,minDamping:.05,maxDamping:1};function mNe(s,t){return s*Math.sqrt(1-t*t)}const bFt=12;function _Ft(s,t,r){let n=r;for(let a=1;a{const h=d*l,m=h*s,p=h-r,x=mNe(d,l),y=Math.exp(-m);return hbe-p/x*y},i=d=>{const m=d*l*s,p=m*r+r,x=Math.pow(l,2)*Math.pow(d,2)*s,y=Math.exp(-m),_=mNe(Math.pow(d,2),l);return(-a(d)+hbe>0?-1:1)*((p-x)*y)/_}):(a=d=>{const h=Math.exp(-d*s),m=(d-r)*s+1;return-hbe+h*m},i=d=>{const h=Math.exp(-d*s),m=(r-d)*(s*s);return h*m});const o=5/s,c=_Ft(a,i,o);if(s=ux(s),isNaN(c))return{stiffness:lu.stiffness,damping:lu.damping,duration:s};{const d=Math.pow(c,2)*n;return{stiffness:d,damping:l*2*Math.sqrt(n*d),duration:s}}}const jFt=["duration","bounce"],NFt=["stiffness","damping","mass"];function _Fe(s,t){return t.some(r=>s[r]!==void 0)}function kFt(s){let t={velocity:lu.velocity,stiffness:lu.stiffness,damping:lu.damping,mass:lu.mass,isResolvedFromDuration:!1,...s};if(!_Fe(s,NFt)&&_Fe(s,jFt))if(t.velocity=0,s.visualDuration){const r=s.visualDuration,n=2*Math.PI/(r*1.2),a=n*n,i=2*I_(.05,1,1-(s.bounce||0))*Math.sqrt(a);t={...t,mass:lu.mass,stiffness:a,damping:i}}else{const r=wFt({...s,velocity:0});t={...t,...r,mass:lu.mass},t.isResolvedFromDuration=!0}return t}function Vhe(s=lu.visualDuration,t=lu.bounce){const r=typeof s!="object"?{visualDuration:s,keyframes:[0,1],bounce:t}:s;let{restSpeed:n,restDelta:a}=r;const i=r.keyframes[0],l=r.keyframes[r.keyframes.length-1],o={done:!1,value:i},{stiffness:c,damping:d,mass:h,duration:m,velocity:p,isResolvedFromDuration:x}=kFt({...r,velocity:-Fy(r.velocity||0)}),y=p||0,_=d/(2*Math.sqrt(c*h)),b=l-i,j=Fy(Math.sqrt(c/h)),k=Math.abs(b)<5;n||(n=k?lu.restSpeed.granular:lu.restSpeed.default),a||(a=k?lu.restDelta.granular:lu.restDelta.default);let T,E,A,D,R,z;if(_<1)A=mNe(j,_),D=(y+_*j*b)/A,T=$=>{const ee=Math.exp(-_*j*$);return l-ee*(D*Math.sin(A*$)+b*Math.cos(A*$))},R=_*j*D+b*A,z=_*j*b-D*A,E=$=>Math.exp(-_*j*$)*(R*Math.sin(A*$)+z*Math.cos(A*$));else if(_===1){T=ee=>l-Math.exp(-j*ee)*(b+(y+j*b)*ee);const $=y+j*b;E=ee=>Math.exp(-j*ee)*(j*$*ee-y)}else{const $=j*Math.sqrt(_*_-1);T=K=>{const re=Math.exp(-_*j*K),ie=Math.min($*K,300);return l-re*((y+_*j*b)*Math.sinh(ie)+$*b*Math.cosh(ie))/$};const ee=(y+_*j*b)/$,Z=_*j*ee-b*$,J=_*j*b-ee*$;E=K=>{const re=Math.exp(-_*j*K),ie=Math.min($*K,300);return re*(Z*Math.sinh(ie)+J*Math.cosh(ie))}}const O={calculatedDuration:x&&m||null,velocity:$=>ux(E($)),next:$=>{if(!x&&_<1){const Z=Math.exp(-_*j*$),J=Math.sin(A*$),K=Math.cos(A*$),re=l-Z*(D*J+b*K),ie=ux(Z*(R*J+z*K));return o.done=Math.abs(ie)<=n&&Math.abs(l-re)<=a,o.value=o.done?l:re,o}const ee=T($);if(x)o.done=$>=m;else{const Z=ux(E($));o.done=Math.abs(Z)<=n&&Math.abs(l-ee)<=a}return o.value=o.done?l:ee,o},toString:()=>{const $=Math.min(R5e(O),qhe),ee=vnt(Z=>O.next($*Z).value,$,30);return $+"ms "+ee},toTransition:()=>{}};return O}Vhe.applyToOptions=s=>{const t=vFt(s,100,Vhe);return s.ease=t.ease,s.duration=ux(t.duration),s.type="keyframes",s};const SFt=5;function bnt(s,t,r){const n=Math.max(t-SFt,0);return Jrt(r-s(n),t-n)}function fNe({keyframes:s,velocity:t=0,power:r=.8,timeConstant:n=325,bounceDamping:a=10,bounceStiffness:i=500,modifyTarget:l,min:o,max:c,restDelta:d=.5,restSpeed:h}){const m=s[0],p={done:!1,value:m},x=z=>o!==void 0&&zc,y=z=>o===void 0?c:c===void 0||Math.abs(o-z)-_*Math.exp(-z/n),T=z=>j+k(z),E=z=>{const O=k(z),$=T(z);p.done=Math.abs(O)<=d,p.value=p.done?j:$};let A,D;const R=z=>{x(p.value)&&(A=z,D=Vhe({keyframes:[p.value,y(p.value)],velocity:bnt(T,z,p.value),damping:a,stiffness:i,restDelta:d,restSpeed:h}))};return R(0),{calculatedDuration:null,next:z=>{let O=!1;return!D&&A===void 0&&(O=!0,E(z),R(z)),A!==void 0&&z>=A?D.next(z-A):(!O&&E(z),p)}}}function CFt(s,t,r){const n=[],a=r||_S.mix||ynt,i=s.length-1;for(let l=0;lt[0];if(i===2&&t[0]===t[1])return()=>t[1];const l=s[0]===s[1];s[0]>s[i-1]&&(s=[...s].reverse(),t=[...t].reverse());const o=CFt(t,n,a),c=o.length,d=h=>{if(l&&h1)for(;md(I_(s[0],s[i-1],h)):d}function EFt(s,t){const r=s[s.length-1];for(let n=1;n<=t;n++){const a=h9(0,t,n);s.push(Sd(r,1,a))}}function AFt(s){const t=[0];return EFt(t,s.length-1),t}function MFt(s,t){return s.map(r=>r*t)}function IFt(s,t){return s.map(()=>t||lnt).splice(0,s.length-1)}function QF({duration:s=300,keyframes:t,times:r,ease:n="easeInOut"}){const a=$Ot(n)?n.map(fFe):fFe(n),i={done:!1,value:t[0]},l=MFt(r&&r.length===t.length?r:AFt(t),s),o=TFt(l,t,{ease:Array.isArray(a)?a:IFt(t,a)});return{calculatedDuration:s,next:c=>(i.value=o(c),i.done=c>=s,i)}}const PFt=s=>s!==null;function Dge(s,{repeat:t,repeatType:r="loop"},n,a=1){const i=s.filter(PFt),o=a<0||t&&r!=="loop"&&t%2===1?0:i.length-1;return!o||n===void 0?i[o]:n}const LFt={decay:fNe,inertia:fNe,tween:QF,keyframes:QF,spring:Vhe};function _nt(s){typeof s.type=="string"&&(s.type=LFt[s.type])}class O5e{constructor(){this.updateFinished()}get finished(){return this._finished}updateFinished(){this._finished=new Promise(t=>{this.resolve=t})}notifyFinished(){this.resolve()}then(t,r){return this.finished.then(t,r)}}const DFt=s=>s/100;class Hhe extends O5e{constructor(t){super(),this.state="idle",this.startTime=null,this.isStopped=!1,this.currentTime=0,this.holdTime=null,this.playbackSpeed=1,this.delayState={done:!1,value:void 0},this.stop=()=>{var n,a;const{motionValue:r}=this.options;r&&r.updatedAt!==ug.now()&&this.tick(ug.now()),this.isStopped=!0,this.state!=="idle"&&(this.teardown(),(a=(n=this.options).onStop)==null||a.call(n))},this.options=t,this.initAnimation(),this.play(),t.autoplay===!1&&this.pause()}initAnimation(){const{options:t}=this;_nt(t);const{type:r=QF,repeat:n=0,repeatDelay:a=0,repeatType:i,velocity:l=0}=t;let{keyframes:o}=t;const c=r||QF;c!==QF&&typeof o[0]!="number"&&(this.mixKeyframes=ez(DFt,ynt(o[0],o[1])),o=[0,100]);const d=c({...t,keyframes:o});i==="mirror"&&(this.mirroredGenerator=c({...t,keyframes:[...o].reverse(),velocity:-l})),d.calculatedDuration===null&&(d.calculatedDuration=R5e(d));const{calculatedDuration:h}=d;this.calculatedDuration=h,this.resolvedDuration=h+a,this.totalDuration=this.resolvedDuration*(n+1)-a,this.generator=d}updateTime(t){const r=Math.round(t-this.startTime)*this.playbackSpeed;this.holdTime!==null?this.currentTime=this.holdTime:this.currentTime=r}tick(t,r=!1){const{generator:n,totalDuration:a,mixKeyframes:i,mirroredGenerator:l,resolvedDuration:o,calculatedDuration:c}=this;if(this.startTime===null)return n.next(0);const{delay:d=0,keyframes:h,repeat:m,repeatType:p,repeatDelay:x,type:y,onUpdate:_,finalKeyframe:b}=this.options;this.speed>0?this.startTime=Math.min(this.startTime,t):this.speed<0&&(this.startTime=Math.min(t-a/this.speed,this.startTime)),r?this.currentTime=t:this.updateTime(t);const j=this.currentTime-d*(this.playbackSpeed>=0?1:-1),k=this.playbackSpeed>=0?j<0:j>a;this.currentTime=Math.max(j,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=a);let T=this.currentTime,E=n;if(m){const z=Math.min(this.currentTime,a)/o;let O=Math.floor(z),$=z%1;!$&&z>=1&&($=1),$===1&&O--,O=Math.min(O,m+1),!!(O%2)&&(p==="reverse"?($=1-$,x&&($-=x/o)):p==="mirror"&&(E=l)),T=I_(0,1,$)*o}let A;k?(this.delayState.value=h[0],A=this.delayState):A=E.next(T),i&&!k&&(A.value=i(A.value));let{done:D}=A;!k&&c!==null&&(D=this.playbackSpeed>=0?this.currentTime>=a:this.currentTime<=0);const R=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&D);return R&&y!==fNe&&(A.value=Dge(h,this.options,b,this.speed)),_&&_(A.value),R&&this.finish(),A}then(t,r){return this.finished.then(t,r)}get duration(){return Fy(this.calculatedDuration)}get iterationDuration(){const{delay:t=0}=this.options||{};return this.duration+Fy(t)}get time(){return Fy(this.currentTime)}set time(t){t=ux(t),this.currentTime=t,this.startTime===null||this.holdTime!==null||this.playbackSpeed===0?this.holdTime=t:this.driver&&(this.startTime=this.driver.now()-t/this.playbackSpeed),this.driver?this.driver.start(!1):(this.startTime=0,this.state="paused",this.holdTime=t,this.tick(t))}getGeneratorVelocity(){const t=this.currentTime;if(t<=0)return this.options.velocity||0;if(this.generator.velocity)return this.generator.velocity(t);const r=this.generator.next(t).value;return bnt(n=>this.generator.next(n).value,t,r)}get speed(){return this.playbackSpeed}set speed(t){const r=this.playbackSpeed!==t;r&&this.driver&&this.updateTime(ug.now()),this.playbackSpeed=t,r&&this.driver&&(this.time=Fy(this.currentTime))}play(){var a,i;if(this.isStopped)return;const{driver:t=yFt,startTime:r}=this.options;this.driver||(this.driver=t(l=>this.tick(l))),(i=(a=this.options).onPlay)==null||i.call(a);const n=this.driver.now();this.state==="finished"?(this.updateFinished(),this.startTime=n):this.holdTime!==null?this.startTime=n-this.holdTime:this.startTime||(this.startTime=r??n),this.state==="finished"&&this.speed<0&&(this.startTime+=this.calculatedDuration),this.holdTime=null,this.state="running",this.driver.start()}pause(){this.state="paused",this.updateTime(ug.now()),this.holdTime=this.currentTime}complete(){this.state!=="running"&&this.play(),this.state="finished",this.holdTime=null}finish(){var t,r;this.notifyFinished(),this.teardown(),this.state="finished",(r=(t=this.options).onComplete)==null||r.call(t)}cancel(){var t,r;this.holdTime=null,this.startTime=0,this.tick(0),this.teardown(),(r=(t=this.options).onCancel)==null||r.call(t)}teardown(){this.state="idle",this.stopDriver(),this.startTime=this.holdTime=null}stopDriver(){this.driver&&(this.driver.stop(),this.driver=void 0)}sample(t){return this.startTime=0,this.tick(t,!0)}attachTimeline(t){var r;return this.options.allowFlatten&&(this.options.type="keyframes",this.options.ease="linear",this.initAnimation()),(r=this.driver)==null||r.stop(),t.observe(this)}}function RFt(s){for(let t=1;ts*180/Math.PI,pNe=s=>{const t=FT(Math.atan2(s[1],s[0]));return gNe(t)},OFt={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:s=>(Math.abs(s[0])+Math.abs(s[3]))/2,rotate:pNe,rotateZ:pNe,skewX:s=>FT(Math.atan(s[1])),skewY:s=>FT(Math.atan(s[2])),skew:s=>(Math.abs(s[1])+Math.abs(s[2]))/2},gNe=s=>(s=s%360,s<0&&(s+=360),s),wFe=pNe,jFe=s=>Math.sqrt(s[0]*s[0]+s[1]*s[1]),NFe=s=>Math.sqrt(s[4]*s[4]+s[5]*s[5]),FFt={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:jFe,scaleY:NFe,scale:s=>(jFe(s)+NFe(s))/2,rotateX:s=>gNe(FT(Math.atan2(s[6],s[5]))),rotateY:s=>gNe(FT(Math.atan2(-s[2],s[0]))),rotateZ:wFe,rotate:wFe,skewX:s=>FT(Math.atan(s[4])),skewY:s=>FT(Math.atan(s[1])),skew:s=>(Math.abs(s[1])+Math.abs(s[4]))/2};function xNe(s){return s.includes("scale")?1:0}function yNe(s,t){if(!s||s==="none")return xNe(t);const r=s.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let n,a;if(r)n=FFt,a=r;else{const o=s.match(/^matrix\(([-\d.e\s,]+)\)$/u);n=OFt,a=o}if(!a)return xNe(t);const i=n[t],l=a[1].split(",").map(zFt);return typeof i=="function"?i(l):l[i]}const BFt=(s,t)=>{const{transform:r="none"}=getComputedStyle(s);return yNe(r,t)};function zFt(s){return parseFloat(s.trim())}const g8=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],x8=new Set(g8),kFe=s=>s===p8||s===ti,$Ft=new Set(["x","y","z"]),UFt=g8.filter(s=>!$Ft.has(s));function qFt(s){const t=[];return UFt.forEach(r=>{const n=s.getValue(r);n!==void 0&&(t.push([r,n.get()]),n.set(r.startsWith("scale")?1:0))}),t}const _k={width:({x:s},{paddingLeft:t="0",paddingRight:r="0",boxSizing:n})=>{const a=s.max-s.min;return n==="border-box"?a:a-parseFloat(t)-parseFloat(r)},height:({y:s},{paddingTop:t="0",paddingBottom:r="0",boxSizing:n})=>{const a=s.max-s.min;return n==="border-box"?a:a-parseFloat(t)-parseFloat(r)},top:(s,{top:t})=>parseFloat(t),left:(s,{left:t})=>parseFloat(t),bottom:({y:s},{top:t})=>parseFloat(t)+(s.max-s.min),right:({x:s},{left:t})=>parseFloat(t)+(s.max-s.min),x:(s,{transform:t})=>yNe(t,"x"),y:(s,{transform:t})=>yNe(t,"y")};_k.translateX=_k.x;_k.translateY=_k.y;const zE=new Set;let vNe=!1,bNe=!1,_Ne=!1;function wnt(){if(bNe){const s=Array.from(zE).filter(n=>n.needsMeasurement),t=new Set(s.map(n=>n.element)),r=new Map;t.forEach(n=>{const a=qFt(n);a.length&&(r.set(n,a),n.render())}),s.forEach(n=>n.measureInitialState()),t.forEach(n=>{n.render();const a=r.get(n);a&&a.forEach(([i,l])=>{var o;(o=n.getValue(i))==null||o.set(l)})}),s.forEach(n=>n.measureEndState()),s.forEach(n=>{n.suspendedScrollY!==void 0&&window.scrollTo(0,n.suspendedScrollY)})}bNe=!1,vNe=!1,zE.forEach(s=>s.complete(_Ne)),zE.clear()}function jnt(){zE.forEach(s=>{s.readKeyframes(),s.needsMeasurement&&(bNe=!0)})}function VFt(){_Ne=!0,jnt(),wnt(),_Ne=!1}class F5e{constructor(t,r,n,a,i,l=!1){this.state="pending",this.isAsync=!1,this.needsMeasurement=!1,this.unresolvedKeyframes=[...t],this.onComplete=r,this.name=n,this.motionValue=a,this.element=i,this.isAsync=l}scheduleResolve(){this.state="scheduled",this.isAsync?(zE.add(this),vNe||(vNe=!0,zc.read(jnt),zc.resolveKeyframes(wnt))):(this.readKeyframes(),this.complete())}readKeyframes(){const{unresolvedKeyframes:t,name:r,element:n,motionValue:a}=this;if(t[0]===null){const i=a==null?void 0:a.get(),l=t[t.length-1];if(i!==void 0)t[0]=i;else if(n&&r){const o=n.readValue(r,l);o!=null&&(t[0]=o)}t[0]===void 0&&(t[0]=l),a&&i===void 0&&a.set(t[0])}RFt(t)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(t=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,t),zE.delete(this)}cancel(){this.state==="scheduled"&&(zE.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const HFt=s=>s.startsWith("--");function Nnt(s,t,r){HFt(t)?s.style.setProperty(t,r):s.style[t]=r}const GFt={};function knt(s,t){const r=Qrt(s);return()=>GFt[t]??r()}const WFt=knt(()=>window.ScrollTimeline!==void 0,"scrollTimeline"),Snt=knt(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),xO=([s,t,r,n])=>`cubic-bezier(${s}, ${t}, ${r}, ${n})`,SFe={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:xO([0,.65,.55,1]),circOut:xO([.55,0,1,.45]),backIn:xO([.31,.01,.66,-.59]),backOut:xO([.33,1.53,.69,.99])};function Cnt(s,t){if(s)return typeof s=="function"?Snt()?vnt(s,t):"ease-out":cnt(s)?xO(s):Array.isArray(s)?s.map(r=>Cnt(r,t)||SFe.easeOut):SFe[s]}function KFt(s,t,r,{delay:n=0,duration:a=300,repeat:i=0,repeatType:l="loop",ease:o="easeOut",times:c}={},d=void 0){const h={[t]:r};c&&(h.offset=c);const m=Cnt(o,a);Array.isArray(m)&&(h.easing=m);const p={delay:n,duration:a,easing:Array.isArray(m)?"linear":m,fill:"both",iterations:i+1,direction:l==="reverse"?"alternate":"normal"};return d&&(p.pseudoElement=d),s.animate(h,p)}function Tnt(s){return typeof s=="function"&&"applyToOptions"in s}function YFt({type:s,...t}){return Tnt(s)&&Snt()?s.applyToOptions(t):(t.duration??(t.duration=300),t.ease??(t.ease="easeOut"),t)}class Ent extends O5e{constructor(t){if(super(),this.finishedTime=null,this.isStopped=!1,this.manualStartTime=null,!t)return;const{element:r,name:n,keyframes:a,pseudoElement:i,allowFlatten:l=!1,finalKeyframe:o,onComplete:c}=t;this.isPseudoElement=!!i,this.allowFlatten=l,this.options=t,rL(typeof t.type!="string",`Mini animate() doesn't support "type" as a string.`,"mini-spring");const d=YFt(t);this.animation=KFt(r,n,a,d,i),d.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!i){const h=Dge(a,this.options,o,this.speed);this.updateMotionValue&&this.updateMotionValue(h),Nnt(r,n,h),this.animation.cancel()}c==null||c(),this.notifyFinished()}}play(){this.isStopped||(this.manualStartTime=null,this.animation.play(),this.state==="finished"&&this.updateFinished())}pause(){this.animation.pause()}complete(){var t,r;(r=(t=this.animation).finish)==null||r.call(t)}cancel(){try{this.animation.cancel()}catch{}}stop(){if(this.isStopped)return;this.isStopped=!0;const{state:t}=this;t==="idle"||t==="finished"||(this.updateMotionValue?this.updateMotionValue():this.commitStyles(),this.isPseudoElement||this.cancel())}commitStyles(){var r,n,a;const t=(r=this.options)==null?void 0:r.element;!this.isPseudoElement&&(t!=null&&t.isConnected)&&((a=(n=this.animation).commitStyles)==null||a.call(n))}get duration(){var r,n;const t=((n=(r=this.animation.effect)==null?void 0:r.getComputedTiming)==null?void 0:n.call(r).duration)||0;return Fy(Number(t))}get iterationDuration(){const{delay:t=0}=this.options||{};return this.duration+Fy(t)}get time(){return Fy(Number(this.animation.currentTime)||0)}set time(t){const r=this.finishedTime!==null;this.manualStartTime=null,this.finishedTime=null,this.animation.currentTime=ux(t),r&&this.animation.pause()}get speed(){return this.animation.playbackRate}set speed(t){t<0&&(this.finishedTime=null),this.animation.playbackRate=t}get state(){return this.finishedTime!==null?"finished":this.animation.playState}get startTime(){return this.manualStartTime??Number(this.animation.startTime)}set startTime(t){this.manualStartTime=this.animation.startTime=t}attachTimeline({timeline:t,rangeStart:r,rangeEnd:n,observe:a}){var i;return this.allowFlatten&&((i=this.animation.effect)==null||i.updateTiming({easing:"linear"})),this.animation.onfinish=null,t&&WFt()?(this.animation.timeline=t,r&&(this.animation.rangeStart=r),n&&(this.animation.rangeEnd=n),Wy):a(this)}}const Ant={anticipate:ant,backInOut:nnt,circInOut:ont};function ZFt(s){return s in Ant}function XFt(s){typeof s.ease=="string"&&ZFt(s.ease)&&(s.ease=Ant[s.ease])}const mbe=10;class QFt extends Ent{constructor(t){XFt(t),_nt(t),super(t),t.startTime!==void 0&&t.autoplay!==!1&&(this.startTime=t.startTime),this.options=t}updateMotionValue(t){const{motionValue:r,onUpdate:n,onComplete:a,element:i,...l}=this.options;if(!r)return;if(t!==void 0){r.set(t);return}const o=new Hhe({...l,autoplay:!1}),c=Math.max(mbe,ug.now()-this.startTime),d=I_(0,mbe,c-mbe),h=o.sample(c).value,{name:m}=this.options;i&&m&&Nnt(i,m,h),r.setWithVelocity(o.sample(Math.max(0,c-d)).value,h,d),o.stop()}}const CFe=(s,t)=>t==="zIndex"?!1:!!(typeof s=="number"||Array.isArray(s)||typeof s=="string"&&(k1.test(s)||s==="0")&&!s.startsWith("url("));function JFt(s){const t=s[0];if(s.length===1)return!0;for(let r=0;rObject.hasOwnProperty.call(Element.prototype,"animate"));function a7t(s){var m;const{motionValue:t,name:r,repeatDelay:n,repeatType:a,damping:i,type:l,keyframes:o}=s;if(!(((m=t==null?void 0:t.owner)==null?void 0:m.current)instanceof HTMLElement))return!1;const{onUpdate:d,transformTemplate:h}=t.owner.getProps();return n7t()&&r&&(Mnt.has(r)||r7t.has(r)&&s7t(o))&&(r!=="transform"||!h)&&!d&&!n&&a!=="mirror"&&i!==0&&l!=="inertia"}const i7t=40;class o7t extends O5e{constructor({autoplay:t=!0,delay:r=0,type:n="keyframes",repeat:a=0,repeatDelay:i=0,repeatType:l="loop",keyframes:o,name:c,motionValue:d,element:h,...m}){var y;super(),this.stop=()=>{var _,b;this._animation&&(this._animation.stop(),(_=this.stopTimeline)==null||_.call(this)),(b=this.keyframeResolver)==null||b.cancel()},this.createdAt=ug.now();const p={autoplay:t,delay:r,type:n,repeat:a,repeatDelay:i,repeatType:l,name:c,motionValue:d,element:h,...m},x=(h==null?void 0:h.KeyframeResolver)||F5e;this.keyframeResolver=new x(o,(_,b,j)=>this.onKeyframesResolved(_,b,p,!j),c,d,h),(y=this.keyframeResolver)==null||y.scheduleResolve()}onKeyframesResolved(t,r,n,a){var j,k;this.keyframeResolver=void 0;const{name:i,type:l,velocity:o,delay:c,isHandoff:d,onUpdate:h}=n;this.resolvedAt=ug.now();let m=!0;e7t(t,i,l,o)||(m=!1,(_S.instantAnimations||!c)&&(h==null||h(Dge(t,n,r))),t[0]=t[t.length-1],wNe(n),n.repeat=0);const x={startTime:a?this.resolvedAt?this.resolvedAt-this.createdAt>i7t?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:r,...n,keyframes:t},y=m&&!d&&a7t(x),_=(k=(j=x.motionValue)==null?void 0:j.owner)==null?void 0:k.current;let b;if(y)try{b=new QFt({...x,element:_})}catch{b=new Hhe(x)}else b=new Hhe(x);b.finished.then(()=>{this.notifyFinished()}).catch(Wy),this.pendingTimeline&&(this.stopTimeline=b.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=b}get finished(){return this._animation?this.animation.finished:this._finished}then(t,r){return this.finished.finally(t).then(()=>{})}get animation(){var t;return this._animation||((t=this.keyframeResolver)==null||t.resume(),VFt()),this._animation}get duration(){return this.animation.duration}get iterationDuration(){return this.animation.iterationDuration}get time(){return this.animation.time}set time(t){this.animation.time=t}get speed(){return this.animation.speed}get state(){return this.animation.state}set speed(t){this.animation.speed=t}get startTime(){return this.animation.startTime}attachTimeline(t){return this._animation?this.stopTimeline=this.animation.attachTimeline(t):this.pendingTimeline=t,()=>this.stop()}play(){this.animation.play()}pause(){this.animation.pause()}complete(){this.animation.complete()}cancel(){var t;this._animation&&this.animation.cancel(),(t=this.keyframeResolver)==null||t.cancel()}}function Int(s,t,r,n=0,a=1){const i=Array.from(s).sort((d,h)=>d.sortNodePosition(h)).indexOf(t),l=s.size,o=(l-1)*n;return typeof r=="function"?r(i,l):a===1?i*n:o-i*n}const l7t=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function c7t(s){const t=l7t.exec(s);if(!t)return[,];const[,r,n,a]=t;return[`--${r??n}`,a]}const d7t=4;function Pnt(s,t,r=1){rL(r<=d7t,`Max CSS variable fallback depth detected in property "${s}". This may indicate a circular fallback dependency.`,"max-css-var-depth");const[n,a]=c7t(s);if(!n)return;const i=window.getComputedStyle(t).getPropertyValue(n);if(i){const l=i.trim();return Yrt(l)?parseFloat(l):l}return I5e(a)?Pnt(a,t,r+1):a}const u7t={type:"spring",stiffness:500,damping:25,restSpeed:10},h7t=s=>({type:"spring",stiffness:550,damping:s===0?2*Math.sqrt(550):30,restSpeed:10}),m7t={type:"keyframes",duration:.8},f7t={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},p7t=(s,{keyframes:t})=>t.length>2?m7t:x8.has(s)?s.startsWith("scale")?h7t(t[1]):u7t:f7t;function Lnt(s,t){if(s!=null&&s.inherit&&t){const{inherit:r,...n}=s;return{...t,...n}}return s}function B5e(s,t){const r=(s==null?void 0:s[t])??(s==null?void 0:s.default)??s;return r!==s?Lnt(r,s):r}const g7t=new Set(["when","delay","delayChildren","staggerChildren","staggerDirection","repeat","repeatType","repeatDelay","from","elapsed"]);function x7t(s){for(const t in s)if(!g7t.has(t))return!0;return!1}const z5e=(s,t,r,n={},a,i)=>l=>{const o=B5e(n,s)||{},c=o.delay||n.delay||0;let{elapsed:d=0}=n;d=d-ux(c);const h={keyframes:Array.isArray(r)?r:[null,r],ease:"easeOut",velocity:t.getVelocity(),...o,delay:-d,onUpdate:p=>{t.set(p),o.onUpdate&&o.onUpdate(p)},onComplete:()=>{l(),o.onComplete&&o.onComplete()},name:s,motionValue:t,element:i?void 0:a};x7t(o)||Object.assign(h,p7t(s,h)),h.duration&&(h.duration=ux(h.duration)),h.repeatDelay&&(h.repeatDelay=ux(h.repeatDelay)),h.from!==void 0&&(h.keyframes[0]=h.from);let m=!1;if((h.type===!1||h.duration===0&&!h.repeatDelay)&&(wNe(h),h.delay===0&&(m=!0)),(_S.instantAnimations||_S.skipAnimations||a!=null&&a.shouldSkipAnimations)&&(m=!0,wNe(h),h.delay=0),h.allowFlatten=!o.type&&!o.ease,m&&!i&&t.get()!==void 0){const p=Dge(h.keyframes,o);if(p!==void 0){zc.update(()=>{h.onUpdate(p),h.onComplete()});return}}return o.isSync?new Hhe(h):new o7t(h)};function TFe(s){const t=[{},{}];return s==null||s.values.forEach((r,n)=>{t[0][n]=r.get(),t[1][n]=r.getVelocity()}),t}function $5e(s,t,r,n){if(typeof t=="function"){const[a,i]=TFe(n);t=t(r!==void 0?r:s.custom,a,i)}if(typeof t=="string"&&(t=s.variants&&s.variants[t]),typeof t=="function"){const[a,i]=TFe(n);t=t(r!==void 0?r:s.custom,a,i)}return t}function $E(s,t,r){const n=s.getProps();return $5e(n,t,r!==void 0?r:n.custom,s)}const Dnt=new Set(["width","height","top","left","right","bottom",...g8]),EFe=30,y7t=s=>!isNaN(parseFloat(s));class v7t{constructor(t,r={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=n=>{var i;const a=ug.now();if(this.updatedAt!==a&&this.setPrevFrameValue(),this.prev=this.current,this.setCurrent(n),this.current!==this.prev&&((i=this.events.change)==null||i.notify(this.current),this.dependents))for(const l of this.dependents)l.dirty()},this.hasAnimated=!1,this.setCurrent(t),this.owner=r.owner}setCurrent(t){this.current=t,this.updatedAt=ug.now(),this.canTrackVelocity===null&&t!==void 0&&(this.canTrackVelocity=y7t(this.current))}setPrevFrameValue(t=this.current){this.prevFrameValue=t,this.prevUpdatedAt=this.updatedAt}onChange(t){return this.on("change",t)}on(t,r){this.events[t]||(this.events[t]=new E5e);const n=this.events[t].add(r);return t==="change"?()=>{n(),zc.read(()=>{this.events.change.getSize()||this.stop()})}:n}clearListeners(){for(const t in this.events)this.events[t].clear()}attach(t,r){this.passiveEffect=t,this.stopPassiveEffect=r}set(t){this.passiveEffect?this.passiveEffect(t,this.updateAndNotify):this.updateAndNotify(t)}setWithVelocity(t,r,n){this.set(r),this.prev=void 0,this.prevFrameValue=t,this.prevUpdatedAt=this.updatedAt-n}jump(t,r=!0){this.updateAndNotify(t),this.prev=t,this.prevUpdatedAt=this.prevFrameValue=void 0,r&&this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}dirty(){var t;(t=this.events.change)==null||t.notify(this.current)}addDependent(t){this.dependents||(this.dependents=new Set),this.dependents.add(t)}removeDependent(t){this.dependents&&this.dependents.delete(t)}get(){return this.current}getPrevious(){return this.prev}getVelocity(){const t=ug.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||t-this.updatedAt>EFe)return 0;const r=Math.min(this.updatedAt-this.prevUpdatedAt,EFe);return Jrt(parseFloat(this.current)-parseFloat(this.prevFrameValue),r)}start(t){return this.stop(),new Promise(r=>{this.hasAnimated=!0,this.animation=t(r),this.events.animationStart&&this.events.animationStart.notify()}).then(()=>{this.events.animationComplete&&this.events.animationComplete.notify(),this.clearAnimation()})}stop(){this.animation&&(this.animation.stop(),this.events.animationCancel&&this.events.animationCancel.notify()),this.clearAnimation()}isAnimating(){return!!this.animation}clearAnimation(){delete this.animation}destroy(){var t,r;(t=this.dependents)==null||t.clear(),(r=this.events.destroy)==null||r.notify(),this.clearListeners(),this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}}function aL(s,t){return new v7t(s,t)}const jNe=s=>Array.isArray(s);function b7t(s,t,r){s.hasValue(t)?s.getValue(t).set(r):s.addValue(t,aL(r))}function _7t(s){return jNe(s)?s[s.length-1]||0:s}function w7t(s,t){const r=$E(s,t);let{transitionEnd:n={},transition:a={},...i}=r||{};i={...i,...n};for(const l in i){const o=_7t(i[l]);b7t(s,l,o)}}const Of=s=>!!(s&&s.getVelocity);function j7t(s){return!!(Of(s)&&s.add)}function NNe(s,t){const r=s.getValue("willChange");if(j7t(r))return r.add(t);if(!r&&_S.WillChange){const n=new _S.WillChange("auto");s.addValue("willChange",n),n.add(t)}}function U5e(s){return s.replace(/([A-Z])/g,t=>`-${t.toLowerCase()}`)}const N7t="framerAppearId",Rnt="data-"+U5e(N7t);function Ont(s){return s.props[Rnt]}function k7t({protectedKeys:s,needsAnimating:t},r){const n=s.hasOwnProperty(r)&&t[r]!==!0;return t[r]=!1,n}function Fnt(s,t,{delay:r=0,transitionOverride:n,type:a}={}){let{transition:i,transitionEnd:l,...o}=t;const c=s.getDefaultTransition();i=i?Lnt(i,c):c;const d=i==null?void 0:i.reduceMotion;n&&(i=n);const h=[],m=a&&s.animationState&&s.animationState.getState()[a];for(const p in o){const x=s.getValue(p,s.latestValues[p]??null),y=o[p];if(y===void 0||m&&k7t(m,p))continue;const _={delay:r,...B5e(i||{},p)},b=x.get();if(b!==void 0&&!x.isAnimating()&&!Array.isArray(y)&&y===b&&!_.velocity){zc.update(()=>x.set(y));continue}let j=!1;if(window.MotionHandoffAnimation){const E=Ont(s);if(E){const A=window.MotionHandoffAnimation(E,p,zc);A!==null&&(_.startTime=A,j=!0)}}NNe(s,p);const k=d??s.shouldReduceMotion;x.start(z5e(p,x,y,k&&Dnt.has(p)?{type:!1}:_,s,j));const T=x.animation;T&&h.push(T)}if(l){const p=()=>zc.update(()=>{l&&w7t(s,l)});h.length?Promise.all(h).then(p):p()}return h}function kNe(s,t,r={}){var c;const n=$E(s,t,r.type==="exit"?(c=s.presenceContext)==null?void 0:c.custom:void 0);let{transition:a=s.getDefaultTransition()||{}}=n||{};r.transitionOverride&&(a=r.transitionOverride);const i=n?()=>Promise.all(Fnt(s,n,r)):()=>Promise.resolve(),l=s.variantChildren&&s.variantChildren.size?(d=0)=>{const{delayChildren:h=0,staggerChildren:m,staggerDirection:p}=a;return S7t(s,t,d,h,m,p,r)}:()=>Promise.resolve(),{when:o}=a;if(o){const[d,h]=o==="beforeChildren"?[i,l]:[l,i];return d().then(()=>h())}else return Promise.all([i(),l(r.delay)])}function S7t(s,t,r=0,n=0,a=0,i=1,l){const o=[];for(const c of s.variantChildren)c.notify("AnimationStart",t),o.push(kNe(c,t,{...l,delay:r+(typeof n=="function"?0:n)+Int(s.variantChildren,c,n,a,i)}).then(()=>c.notify("AnimationComplete",t)));return Promise.all(o)}function C7t(s,t,r={}){s.notify("AnimationStart",t);let n;if(Array.isArray(t)){const a=t.map(i=>kNe(s,i,r));n=Promise.all(a)}else if(typeof t=="string")n=kNe(s,t,r);else{const a=typeof t=="function"?$E(s,t,r.custom):t;n=Promise.all(Fnt(s,a,r))}return n.then(()=>{s.notify("AnimationComplete",t)})}const T7t={test:s=>s==="auto",parse:s=>s},Bnt=s=>t=>t.test(s),znt=[p8,ti,j_,IN,JOt,QOt,T7t],AFe=s=>znt.find(Bnt(s));function E7t(s){return typeof s=="number"?s===0:s!==null?s==="none"||s==="0"||Xrt(s):!0}const A7t=new Set(["brightness","contrast","saturate","opacity"]);function M7t(s){const[t,r]=s.slice(0,-1).split("(");if(t==="drop-shadow")return s;const[n]=r.match(P5e)||[];if(!n)return s;const a=r.replace(n,"");let i=A7t.has(t)?1:0;return n!==r&&(i*=100),t+"("+i+a+")"}const I7t=/\b([a-z-]*)\(.*?\)/gu,SNe={...k1,getAnimatableNone:s=>{const t=s.match(I7t);return t?t.map(M7t).join(" "):s}},CNe={...k1,getAnimatableNone:s=>{const t=k1.parse(s);return k1.createTransformer(s)(t.map(n=>typeof n=="number"?0:typeof n=="object"?{...n,alpha:1}:n))}},MFe={...p8,transform:Math.round},P7t={rotate:IN,rotateX:IN,rotateY:IN,rotateZ:IN,scale:GU,scaleX:GU,scaleY:GU,scaleZ:GU,skew:IN,skewX:IN,skewY:IN,distance:ti,translateX:ti,translateY:ti,translateZ:ti,x:ti,y:ti,z:ti,perspective:ti,transformPerspective:ti,opacity:m9,originX:xFe,originY:xFe,originZ:ti},q5e={borderWidth:ti,borderTopWidth:ti,borderRightWidth:ti,borderBottomWidth:ti,borderLeftWidth:ti,borderRadius:ti,borderTopLeftRadius:ti,borderTopRightRadius:ti,borderBottomRightRadius:ti,borderBottomLeftRadius:ti,width:ti,maxWidth:ti,height:ti,maxHeight:ti,top:ti,right:ti,bottom:ti,left:ti,inset:ti,insetBlock:ti,insetBlockStart:ti,insetBlockEnd:ti,insetInline:ti,insetInlineStart:ti,insetInlineEnd:ti,padding:ti,paddingTop:ti,paddingRight:ti,paddingBottom:ti,paddingLeft:ti,paddingBlock:ti,paddingBlockStart:ti,paddingBlockEnd:ti,paddingInline:ti,paddingInlineStart:ti,paddingInlineEnd:ti,margin:ti,marginTop:ti,marginRight:ti,marginBottom:ti,marginLeft:ti,marginBlock:ti,marginBlockStart:ti,marginBlockEnd:ti,marginInline:ti,marginInlineStart:ti,marginInlineEnd:ti,fontSize:ti,backgroundPositionX:ti,backgroundPositionY:ti,...P7t,zIndex:MFe,fillOpacity:m9,strokeOpacity:m9,numOctaves:MFe},L7t={...q5e,color:Mh,backgroundColor:Mh,outlineColor:Mh,fill:Mh,stroke:Mh,borderColor:Mh,borderTopColor:Mh,borderRightColor:Mh,borderBottomColor:Mh,borderLeftColor:Mh,filter:SNe,WebkitFilter:SNe,mask:CNe,WebkitMask:CNe},$nt=s=>L7t[s],D7t=new Set([SNe,CNe]);function Unt(s,t){let r=$nt(s);return D7t.has(r)||(r=k1),r.getAnimatableNone?r.getAnimatableNone(t):void 0}const R7t=new Set(["auto","none","0"]);function O7t(s,t,r){let n=0,a;for(;n{t.getValue(c).set(d)}),this.resolveNoneKeyframes()}}function V5e(s,t,r){if(s==null)return[];if(s instanceof EventTarget)return[s];if(typeof s=="string"){const a=document.querySelectorAll(s);return a?Array.from(a):[]}return Array.from(s).filter(n=>n!=null)}const qnt=(s,t)=>t&&typeof s=="number"?t.transform(s):s;function pue(s){return Zrt(s)&&"offsetHeight"in s&&!("ownerSVGElement"in s)}const{schedule:H5e,cancel:RZs}=dnt(queueMicrotask,!1),Yv={x:!1,y:!1};function Vnt(){return Yv.x||Yv.y}function B7t(s){return s==="x"||s==="y"?Yv[s]?null:(Yv[s]=!0,()=>{Yv[s]=!1}):Yv.x||Yv.y?null:(Yv.x=Yv.y=!0,()=>{Yv.x=Yv.y=!1})}function Hnt(s,t){const r=V5e(s),n=new AbortController,a={passive:!0,...t,signal:n.signal};return[r,a,()=>n.abort()]}function z7t(s){return!(s.pointerType==="touch"||Vnt())}function $7t(s,t,r={}){const[n,a,i]=Hnt(s,r);return n.forEach(l=>{let o=!1,c=!1,d;const h=()=>{l.removeEventListener("pointerleave",y)},m=b=>{d&&(d(b),d=void 0),h()},p=b=>{o=!1,window.removeEventListener("pointerup",p),window.removeEventListener("pointercancel",p),c&&(c=!1,m(b))},x=()=>{o=!0,window.addEventListener("pointerup",p,a),window.addEventListener("pointercancel",p,a)},y=b=>{if(b.pointerType!=="touch"){if(o){c=!0;return}m(b)}},_=b=>{if(!z7t(b))return;c=!1;const j=t(l,b);typeof j=="function"&&(d=j,l.addEventListener("pointerleave",y,a))};l.addEventListener("pointerenter",_,a),l.addEventListener("pointerdown",x,a)}),i}const Gnt=(s,t)=>t?s===t?!0:Gnt(s,t.parentElement):!1,G5e=s=>s.pointerType==="mouse"?typeof s.button!="number"||s.button<=0:s.isPrimary!==!1,U7t=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function q7t(s){return U7t.has(s.tagName)||s.isContentEditable===!0}const V7t=new Set(["INPUT","SELECT","TEXTAREA"]);function H7t(s){return V7t.has(s.tagName)||s.isContentEditable===!0}const gue=new WeakSet;function IFe(s){return t=>{t.key==="Enter"&&s(t)}}function fbe(s,t){s.dispatchEvent(new PointerEvent("pointer"+t,{isPrimary:!0,bubbles:!0}))}const G7t=(s,t)=>{const r=s.currentTarget;if(!r)return;const n=IFe(()=>{if(gue.has(r))return;fbe(r,"down");const a=IFe(()=>{fbe(r,"up")}),i=()=>fbe(r,"cancel");r.addEventListener("keyup",a,t),r.addEventListener("blur",i,t)});r.addEventListener("keydown",n,t),r.addEventListener("blur",()=>r.removeEventListener("keydown",n),t)};function PFe(s){return G5e(s)&&!Vnt()}const LFe=new WeakSet;function W7t(s,t,r={}){const[n,a,i]=Hnt(s,r),l=o=>{const c=o.currentTarget;if(!PFe(o)||LFe.has(o))return;gue.add(c),r.stopPropagation&&LFe.add(o);const d=t(c,o),h=(x,y)=>{window.removeEventListener("pointerup",m),window.removeEventListener("pointercancel",p),gue.has(c)&&gue.delete(c),PFe(x)&&typeof d=="function"&&d(x,{success:y})},m=x=>{h(x,c===window||c===document||r.useGlobalTarget||Gnt(c,x.target))},p=x=>{h(x,!1)};window.addEventListener("pointerup",m,a),window.addEventListener("pointercancel",p,a)};return n.forEach(o=>{(r.useGlobalTarget?window:o).addEventListener("pointerdown",l,a),pue(o)&&(o.addEventListener("focus",d=>G7t(d,a)),!q7t(o)&&!o.hasAttribute("tabindex")&&(o.tabIndex=0))}),i}function W5e(s){return Zrt(s)&&"ownerSVGElement"in s}const xue=new WeakMap;let PN;const Wnt=(s,t,r)=>(n,a)=>a&&a[0]?a[0][s+"Size"]:W5e(n)&&"getBBox"in n?n.getBBox()[t]:n[r],K7t=Wnt("inline","width","offsetWidth"),Y7t=Wnt("block","height","offsetHeight");function Z7t({target:s,borderBoxSize:t}){var r;(r=xue.get(s))==null||r.forEach(n=>{n(s,{get width(){return K7t(s,t)},get height(){return Y7t(s,t)}})})}function X7t(s){s.forEach(Z7t)}function Q7t(){typeof ResizeObserver>"u"||(PN=new ResizeObserver(X7t))}function J7t(s,t){PN||Q7t();const r=V5e(s);return r.forEach(n=>{let a=xue.get(n);a||(a=new Set,xue.set(n,a)),a.add(t),PN==null||PN.observe(n)}),()=>{r.forEach(n=>{const a=xue.get(n);a==null||a.delete(t),a!=null&&a.size||PN==null||PN.unobserve(n)})}}const yue=new Set;let cI;function e9t(){cI=()=>{const s={get width(){return window.innerWidth},get height(){return window.innerHeight}};yue.forEach(t=>t(s))},window.addEventListener("resize",cI)}function t9t(s){return yue.add(s),cI||e9t(),()=>{yue.delete(s),!yue.size&&typeof cI=="function"&&(window.removeEventListener("resize",cI),cI=void 0)}}function DFe(s,t){return typeof s=="function"?t9t(s):J7t(s,t)}function s9t(s){return W5e(s)&&s.tagName==="svg"}const r9t=[...znt,Mh,k1],n9t=s=>r9t.find(Bnt(s)),RFe=()=>({translate:0,scale:1,origin:0,originPoint:0}),dI=()=>({x:RFe(),y:RFe()}),OFe=()=>({min:0,max:0}),sm=()=>({x:OFe(),y:OFe()}),a9t=new WeakMap;function Rge(s){return s!==null&&typeof s=="object"&&typeof s.start=="function"}function f9(s){return typeof s=="string"||Array.isArray(s)}const K5e=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],Y5e=["initial",...K5e];function Oge(s){return Rge(s.animate)||Y5e.some(t=>f9(s[t]))}function Knt(s){return!!(Oge(s)||s.variants)}function i9t(s,t,r){for(const n in t){const a=t[n],i=r[n];if(Of(a))s.addValue(n,a);else if(Of(i))s.addValue(n,aL(a,{owner:s}));else if(i!==a)if(s.hasValue(n)){const l=s.getValue(n);l.liveStyle===!0?l.jump(a):l.hasAnimated||l.set(a)}else{const l=s.getStaticValue(n);s.addValue(n,aL(l!==void 0?l:a,{owner:s}))}}for(const n in r)t[n]===void 0&&s.removeValue(n);return t}const TNe={current:null},Ynt={current:!1},o9t=typeof window<"u";function l9t(){if(Ynt.current=!0,!!o9t)if(window.matchMedia){const s=window.matchMedia("(prefers-reduced-motion)"),t=()=>TNe.current=s.matches;s.addEventListener("change",t),t()}else TNe.current=!1}const FFe=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];let Ghe={};function Znt(s){Ghe=s}function c9t(){return Ghe}class d9t{scrapeMotionValuesFromProps(t,r,n){return{}}constructor({parent:t,props:r,presenceContext:n,reducedMotionConfig:a,skipAnimations:i,blockInitialAnimation:l,visualState:o},c={}){this.current=null,this.children=new Set,this.isVariantNode=!1,this.isControllingVariants=!1,this.shouldReduceMotion=null,this.shouldSkipAnimations=!1,this.values=new Map,this.KeyframeResolver=F5e,this.features={},this.valueSubscriptions=new Map,this.prevMotionValues={},this.hasBeenMounted=!1,this.events={},this.propEventSubscriptions={},this.notifyUpdate=()=>this.notify("Update",this.latestValues),this.render=()=>{this.current&&(this.triggerBuild(),this.renderInstance(this.current,this.renderState,this.props.style,this.projection))},this.renderScheduledAt=0,this.scheduleRender=()=>{const x=ug.now();this.renderScheduledAtthis.bindToMotionValue(i,a)),this.reducedMotionConfig==="never"?this.shouldReduceMotion=!1:this.reducedMotionConfig==="always"?this.shouldReduceMotion=!0:(Ynt.current||l9t(),this.shouldReduceMotion=TNe.current),this.shouldSkipAnimations=this.skipAnimationsConfig??!1,(n=this.parent)==null||n.addChild(this),this.update(this.props,this.presenceContext),this.hasBeenMounted=!0}unmount(){var t;this.projection&&this.projection.unmount(),wS(this.notifyUpdate),wS(this.render),this.valueSubscriptions.forEach(r=>r()),this.valueSubscriptions.clear(),this.removeFromVariantTree&&this.removeFromVariantTree(),(t=this.parent)==null||t.removeChild(this);for(const r in this.events)this.events[r].clear();for(const r in this.features){const n=this.features[r];n&&(n.unmount(),n.isMounted=!1)}this.current=null}addChild(t){this.children.add(t),this.enteringChildren??(this.enteringChildren=new Set),this.enteringChildren.add(t)}removeChild(t){this.children.delete(t),this.enteringChildren&&this.enteringChildren.delete(t)}bindToMotionValue(t,r){if(this.valueSubscriptions.has(t)&&this.valueSubscriptions.get(t)(),r.accelerate&&Mnt.has(t)&&this.current instanceof HTMLElement){const{factory:l,keyframes:o,times:c,ease:d,duration:h}=r.accelerate,m=new Ent({element:this.current,name:t,keyframes:o,times:c,ease:d,duration:ux(h)}),p=l(m);this.valueSubscriptions.set(t,()=>{p(),m.cancel()});return}const n=x8.has(t);n&&this.onBindTransform&&this.onBindTransform();const a=r.on("change",l=>{this.latestValues[t]=l,this.props.onUpdate&&zc.preRender(this.notifyUpdate),n&&this.projection&&(this.projection.isTransformDirty=!0),this.scheduleRender()});let i;typeof window<"u"&&window.MotionCheckAppearSync&&(i=window.MotionCheckAppearSync(this,t,r)),this.valueSubscriptions.set(t,()=>{a(),i&&i(),r.owner&&r.stop()})}sortNodePosition(t){return!this.current||!this.sortInstanceNodePosition||this.type!==t.type?0:this.sortInstanceNodePosition(this.current,t.current)}updateFeatures(){let t="animation";for(t in Ghe){const r=Ghe[t];if(!r)continue;const{isEnabled:n,Feature:a}=r;if(!this.features[t]&&a&&n(this.props)&&(this.features[t]=new a(this)),this.features[t]){const i=this.features[t];i.isMounted?i.update():(i.mount(),i.isMounted=!0)}}}triggerBuild(){this.build(this.renderState,this.latestValues,this.props)}measureViewportBox(){return this.current?this.measureInstanceViewportBox(this.current,this.props):sm()}getStaticValue(t){return this.latestValues[t]}setStaticValue(t,r){this.latestValues[t]=r}update(t,r){(t.transformTemplate||this.props.transformTemplate)&&this.scheduleRender(),this.prevProps=this.props,this.props=t,this.prevPresenceContext=this.presenceContext,this.presenceContext=r;for(let n=0;nr.variantChildren.delete(t)}addValue(t,r){const n=this.values.get(t);r!==n&&(n&&this.removeValue(t),this.bindToMotionValue(t,r),this.values.set(t,r),this.latestValues[t]=r.get())}removeValue(t){this.values.delete(t);const r=this.valueSubscriptions.get(t);r&&(r(),this.valueSubscriptions.delete(t)),delete this.latestValues[t],this.removeValueFromRenderState(t,this.renderState)}hasValue(t){return this.values.has(t)}getValue(t,r){if(this.props.values&&this.props.values[t])return this.props.values[t];let n=this.values.get(t);return n===void 0&&r!==void 0&&(n=aL(r===null?void 0:r,{owner:this}),this.addValue(t,n)),n}readValue(t,r){let n=this.latestValues[t]!==void 0||!this.current?this.latestValues[t]:this.getBaseTargetFromProps(this.props,t)??this.readValueFromInstance(this.current,t,this.options);return n!=null&&(typeof n=="string"&&(Yrt(n)||Xrt(n))?n=parseFloat(n):!n9t(n)&&k1.test(r)&&(n=Unt(t,r)),this.setBaseTarget(t,Of(n)?n.get():n)),Of(n)?n.get():n}setBaseTarget(t,r){this.baseTarget[t]=r}getBaseTarget(t){var i;const{initial:r}=this.props;let n;if(typeof r=="string"||typeof r=="object"){const l=$5e(this.props,r,(i=this.presenceContext)==null?void 0:i.custom);l&&(n=l[t])}if(r&&n!==void 0)return n;const a=this.getBaseTargetFromProps(this.props,t);return a!==void 0&&!Of(a)?a:this.initialValues[t]!==void 0&&n===void 0?void 0:this.baseTarget[t]}on(t,r){return this.events[t]||(this.events[t]=new E5e),this.events[t].add(r)}notify(t,...r){this.events[t]&&this.events[t].notify(...r)}scheduleRenderMicrotask(){H5e.render(this.render)}}class Xnt extends d9t{constructor(){super(...arguments),this.KeyframeResolver=F7t}sortInstanceNodePosition(t,r){return t.compareDocumentPosition(r)&2?1:-1}getBaseTargetFromProps(t,r){const n=t.style;return n?n[r]:void 0}removeValueFromRenderState(t,{vars:r,style:n}){delete r[t],delete n[t]}handleChildMotionValue(){this.childSubscription&&(this.childSubscription(),delete this.childSubscription);const{children:t}=this.props;Of(t)&&(this.childSubscription=t.on("change",r=>{this.current&&(this.current.textContent=`${r}`)}))}}class VS{constructor(t){this.isMounted=!1,this.node=t}update(){}}function Qnt({top:s,left:t,right:r,bottom:n}){return{x:{min:t,max:r},y:{min:s,max:n}}}function u9t({x:s,y:t}){return{top:t.min,right:s.max,bottom:t.max,left:s.min}}function h9t(s,t){if(!t)return s;const r=t({x:s.left,y:s.top}),n=t({x:s.right,y:s.bottom});return{top:r.y,left:r.x,bottom:n.y,right:n.x}}function pbe(s){return s===void 0||s===1}function ENe({scale:s,scaleX:t,scaleY:r}){return!pbe(s)||!pbe(t)||!pbe(r)}function wT(s){return ENe(s)||Jnt(s)||s.z||s.rotate||s.rotateX||s.rotateY||s.skewX||s.skewY}function Jnt(s){return BFe(s.x)||BFe(s.y)}function BFe(s){return s&&s!=="0%"}function Whe(s,t,r){const n=s-r,a=t*n;return r+a}function zFe(s,t,r,n,a){return a!==void 0&&(s=Whe(s,a,n)),Whe(s,r,n)+t}function ANe(s,t=0,r=1,n,a){s.min=zFe(s.min,t,r,n,a),s.max=zFe(s.max,t,r,n,a)}function eat(s,{x:t,y:r}){ANe(s.x,t.translate,t.scale,t.originPoint),ANe(s.y,r.translate,r.scale,r.originPoint)}const $Fe=.999999999999,UFe=1.0000000000001;function m9t(s,t,r,n=!1){var o;const a=r.length;if(!a)return;t.x=t.y=1;let i,l;for(let c=0;c$Fe&&(t.x=1),t.y$Fe&&(t.y=1)}function Kb(s,t){s.min+=t,s.max+=t}function qFe(s,t,r,n,a=.5){const i=Sd(s.min,s.max,a);ANe(s,t,r,i,n)}function VFe(s,t){return typeof s=="string"?parseFloat(s)/100*(t.max-t.min):s}function vue(s,t,r){const n=r??s;qFe(s.x,VFe(t.x,n.x),t.scaleX,t.scale,t.originX),qFe(s.y,VFe(t.y,n.y),t.scaleY,t.scale,t.originY)}function tat(s,t){return Qnt(h9t(s.getBoundingClientRect(),t))}function f9t(s,t,r){const n=tat(s,r),{scroll:a}=t;return a&&(Kb(n.x,a.offset.x),Kb(n.y,a.offset.y)),n}const p9t={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},g9t=g8.length;function x9t(s,t,r){let n="",a=!0;for(let i=0;i{if(!t.target)return s;if(typeof s=="string")if(ti.test(s))s=parseFloat(s);else return s;const r=HFe(s,t.target.x),n=HFe(s,t.target.y);return`${r}% ${n}%`}},y9t={correct:(s,{treeScale:t,projectionDelta:r})=>{const n=s,a=k1.parse(s);if(a.length>5)return n;const i=k1.createTransformer(s),l=typeof a[0]!="number"?1:0,o=r.x.scale*t.x,c=r.y.scale*t.y;a[0+l]/=o,a[1+l]/=c;const d=Sd(o,c,.5);return typeof a[2+l]=="number"&&(a[2+l]/=d),typeof a[3+l]=="number"&&(a[3+l]/=d),i(a)}},MNe={borderRadius:{...TR,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:TR,borderTopRightRadius:TR,borderBottomLeftRadius:TR,borderBottomRightRadius:TR,boxShadow:y9t};function rat(s,{layout:t,layoutId:r}){return x8.has(s)||s.startsWith("origin")||(t||r!==void 0)&&(!!MNe[s]||s==="opacity")}function X5e(s,t,r){var l;const n=s.style,a=t==null?void 0:t.style,i={};if(!n)return i;for(const o in n)(Of(n[o])||a&&Of(a[o])||rat(o,s)||((l=r==null?void 0:r.getValue(o))==null?void 0:l.liveStyle)!==void 0)&&(i[o]=n[o]);return i}function v9t(s){return window.getComputedStyle(s)}class b9t extends Xnt{constructor(){super(...arguments),this.type="html",this.renderInstance=sat}readValueFromInstance(t,r){var n;if(x8.has(r))return(n=this.projection)!=null&&n.isProjecting?xNe(r):BFt(t,r);{const a=v9t(t),i=(hnt(r)?a.getPropertyValue(r):a[r])||0;return typeof i=="string"?i.trim():i}}measureInstanceViewportBox(t,{transformPagePoint:r}){return tat(t,r)}build(t,r,n){Z5e(t,r,n.transformTemplate)}scrapeMotionValuesFromProps(t,r,n){return X5e(t,r,n)}}const _9t={offset:"stroke-dashoffset",array:"stroke-dasharray"},w9t={offset:"strokeDashoffset",array:"strokeDasharray"};function j9t(s,t,r=1,n=0,a=!0){s.pathLength=1;const i=a?_9t:w9t;s[i.offset]=`${-n}`,s[i.array]=`${t} ${r}`}const N9t=["offsetDistance","offsetPath","offsetRotate","offsetAnchor"];function nat(s,{attrX:t,attrY:r,attrScale:n,pathLength:a,pathSpacing:i=1,pathOffset:l=0,...o},c,d,h){if(Z5e(s,o,d),c){s.style.viewBox&&(s.attrs.viewBox=s.style.viewBox);return}s.attrs=s.style,s.style={};const{attrs:m,style:p}=s;m.transform&&(p.transform=m.transform,delete m.transform),(p.transform||m.transformOrigin)&&(p.transformOrigin=m.transformOrigin??"50% 50%",delete m.transformOrigin),p.transform&&(p.transformBox=(h==null?void 0:h.transformBox)??"fill-box",delete m.transformBox);for(const x of N9t)m[x]!==void 0&&(p[x]=m[x],delete m[x]);t!==void 0&&(m.x=t),r!==void 0&&(m.y=r),n!==void 0&&(m.scale=n),a!==void 0&&j9t(m,a,i,l,!1)}const aat=new Set(["baseFrequency","diffuseConstant","kernelMatrix","kernelUnitLength","keySplines","keyTimes","limitingConeAngle","markerHeight","markerWidth","numOctaves","targetX","targetY","surfaceScale","specularConstant","specularExponent","stdDeviation","tableValues","viewBox","gradientTransform","pathLength","startOffset","textLength","lengthAdjust"]),iat=s=>typeof s=="string"&&s.toLowerCase()==="svg";function k9t(s,t,r,n){sat(s,t,void 0,n);for(const a in t.attrs)s.setAttribute(aat.has(a)?a:U5e(a),t.attrs[a])}function oat(s,t,r){const n=X5e(s,t,r);for(const a in s)if(Of(s[a])||Of(t[a])){const i=g8.indexOf(a)!==-1?"attr"+a.charAt(0).toUpperCase()+a.substring(1):a;n[i]=s[a]}return n}class S9t extends Xnt{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=sm}getBaseTargetFromProps(t,r){return t[r]}readValueFromInstance(t,r){if(x8.has(r)){const n=$nt(r);return n&&n.default||0}return r=aat.has(r)?r:U5e(r),t.getAttribute(r)}scrapeMotionValuesFromProps(t,r,n){return oat(t,r,n)}build(t,r,n){nat(t,r,this.isSVGTag,n.transformTemplate,n.style)}renderInstance(t,r,n,a){k9t(t,r,n,a)}mount(t){this.isSVGTag=iat(t.tagName),super.mount(t)}}const C9t=Y5e.length;function lat(s){if(!s)return;if(!s.isControllingVariants){const r=s.parent?lat(s.parent)||{}:{};return s.props.initial!==void 0&&(r.initial=s.props.initial),r}const t={};for(let r=0;rPromise.all(t.map(({animation:r,options:n})=>C7t(s,r,n)))}function M9t(s){let t=A9t(s),r=GFe(),n=!0,a=!1;const i=d=>(h,m)=>{var x;const p=$E(s,m,d==="exit"?(x=s.presenceContext)==null?void 0:x.custom:void 0);if(p){const{transition:y,transitionEnd:_,...b}=p;h={...h,...b,..._}}return h};function l(d){t=d(s)}function o(d){const{props:h}=s,m=lat(s.parent)||{},p=[],x=new Set;let y={},_=1/0;for(let j=0;j_&&A,$=!1;const ee=Array.isArray(E)?E:[E];let Z=ee.reduce(i(k),{});D===!1&&(Z={});const{prevResolvedValues:J={}}=T,K={...J,...Z},re=ne=>{O=!0,x.has(ne)&&($=!0,x.delete(ne)),T.needsAnimating[ne]=!0;const le=s.getValue(ne);le&&(le.liveStyle=!1)};for(const ne in K){const le=Z[ne],be=J[ne];if(y.hasOwnProperty(ne))continue;let fe=!1;jNe(le)&&jNe(be)?fe=!cat(le,be):fe=le!==be,fe?le!=null?re(ne):x.add(ne):le!==void 0&&x.has(ne)?re(ne):T.protectedKeys[ne]=!0}T.prevProp=E,T.prevResolvedValues=Z,T.isActive&&(y={...y,...Z}),(n||a)&&s.blockInitialAnimation&&(O=!1);const ie=R&&z;O&&(!ie||$)&&p.push(...ee.map(ne=>{const le={type:k};if(typeof ne=="string"&&(n||a)&&!ie&&s.manuallyAnimateOnMount&&s.parent){const{parent:be}=s,fe=$E(be,ne);if(be.enteringChildren&&fe){const{delayChildren:je}=fe.transition||{};le.delay=Int(be.enteringChildren,s,je)}}return{animation:ne,options:le}}))}if(x.size){const j={};if(typeof h.initial!="boolean"){const k=$E(s,Array.isArray(h.initial)?h.initial[0]:h.initial);k&&k.transition&&(j.transition=k.transition)}x.forEach(k=>{const T=s.getBaseTarget(k),E=s.getValue(k);E&&(E.liveStyle=!0),j[k]=T??null}),p.push({animation:j})}let b=!!p.length;return n&&(h.initial===!1||h.initial===h.animate)&&!s.manuallyAnimateOnMount&&(b=!1),n=!1,a=!1,b?t(p):Promise.resolve()}function c(d,h){var p;if(r[d].isActive===h)return Promise.resolve();(p=s.variantChildren)==null||p.forEach(x=>{var y;return(y=x.animationState)==null?void 0:y.setActive(d,h)}),r[d].isActive=h;const m=o(d);for(const x in r)r[x].protectedKeys={};return m}return{animateChanges:o,setActive:c,setAnimateFunction:l,getState:()=>r,reset:()=>{r=GFe(),a=!0}}}function I9t(s,t){return typeof t=="string"?t!==s:Array.isArray(t)?!cat(t,s):!1}function eC(s=!1){return{isActive:s,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function GFe(){return{animate:eC(!0),whileInView:eC(),whileHover:eC(),whileTap:eC(),whileDrag:eC(),whileFocus:eC(),exit:eC()}}function INe(s,t){s.min=t.min,s.max=t.max}function Vv(s,t){INe(s.x,t.x),INe(s.y,t.y)}function WFe(s,t){s.translate=t.translate,s.scale=t.scale,s.originPoint=t.originPoint,s.origin=t.origin}const dat=1e-4,P9t=1-dat,L9t=1+dat,uat=.01,D9t=0-uat,R9t=0+uat;function hg(s){return s.max-s.min}function O9t(s,t,r){return Math.abs(s-t)<=r}function KFe(s,t,r,n=.5){s.origin=n,s.originPoint=Sd(t.min,t.max,s.origin),s.scale=hg(r)/hg(t),s.translate=Sd(r.min,r.max,s.origin)-s.originPoint,(s.scale>=P9t&&s.scale<=L9t||isNaN(s.scale))&&(s.scale=1),(s.translate>=D9t&&s.translate<=R9t||isNaN(s.translate))&&(s.translate=0)}function JF(s,t,r,n){KFe(s.x,t.x,r.x,n?n.originX:void 0),KFe(s.y,t.y,r.y,n?n.originY:void 0)}function YFe(s,t,r,n=0){const a=n?Sd(r.min,r.max,n):r.min;s.min=a+t.min,s.max=s.min+hg(t)}function F9t(s,t,r,n){YFe(s.x,t.x,r.x,n==null?void 0:n.x),YFe(s.y,t.y,r.y,n==null?void 0:n.y)}function ZFe(s,t,r,n=0){const a=n?Sd(r.min,r.max,n):r.min;s.min=t.min-a,s.max=s.min+hg(t)}function Khe(s,t,r,n){ZFe(s.x,t.x,r.x,n==null?void 0:n.x),ZFe(s.y,t.y,r.y,n==null?void 0:n.y)}function XFe(s,t,r,n,a){return s-=t,s=Whe(s,1/r,n),a!==void 0&&(s=Whe(s,1/a,n)),s}function B9t(s,t=0,r=1,n=.5,a,i=s,l=s){if(j_.test(t)&&(t=parseFloat(t),t=Sd(l.min,l.max,t/100)-l.min),typeof t!="number")return;let o=Sd(i.min,i.max,n);s===i&&(o-=t),s.min=XFe(s.min,t,r,o,a),s.max=XFe(s.max,t,r,o,a)}function QFe(s,t,[r,n,a],i,l){B9t(s,t[r],t[n],t[a],t.scale,i,l)}const z9t=["x","scaleX","originX"],$9t=["y","scaleY","originY"];function JFe(s,t,r,n){QFe(s.x,t,z9t,r?r.x:void 0,n?n.x:void 0),QFe(s.y,t,$9t,r?r.y:void 0,n?n.y:void 0)}function e7e(s){return s.translate===0&&s.scale===1}function hat(s){return e7e(s.x)&&e7e(s.y)}function t7e(s,t){return s.min===t.min&&s.max===t.max}function U9t(s,t){return t7e(s.x,t.x)&&t7e(s.y,t.y)}function s7e(s,t){return Math.round(s.min)===Math.round(t.min)&&Math.round(s.max)===Math.round(t.max)}function mat(s,t){return s7e(s.x,t.x)&&s7e(s.y,t.y)}function r7e(s){return hg(s.x)/hg(s.y)}function n7e(s,t){return s.translate===t.translate&&s.scale===t.scale&&s.originPoint===t.originPoint}function Ob(s){return[s("x"),s("y")]}function q9t(s,t,r){let n="";const a=s.x.translate/t.x,i=s.y.translate/t.y,l=(r==null?void 0:r.z)||0;if((a||i||l)&&(n=`translate3d(${a}px, ${i}px, ${l}px) `),(t.x!==1||t.y!==1)&&(n+=`scale(${1/t.x}, ${1/t.y}) `),r){const{transformPerspective:d,rotate:h,rotateX:m,rotateY:p,skewX:x,skewY:y}=r;d&&(n=`perspective(${d}px) ${n}`),h&&(n+=`rotate(${h}deg) `),m&&(n+=`rotateX(${m}deg) `),p&&(n+=`rotateY(${p}deg) `),x&&(n+=`skewX(${x}deg) `),y&&(n+=`skewY(${y}deg) `)}const o=s.x.scale*t.x,c=s.y.scale*t.y;return(o!==1||c!==1)&&(n+=`scale(${o}, ${c})`),n||"none"}const fat=["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"],V9t=fat.length,a7e=s=>typeof s=="string"?parseFloat(s):s,i7e=s=>typeof s=="number"||ti.test(s);function H9t(s,t,r,n,a,i){a?(s.opacity=Sd(0,r.opacity??1,G9t(n)),s.opacityExit=Sd(t.opacity??1,0,W9t(n))):i&&(s.opacity=Sd(t.opacity??1,r.opacity??1,n));for(let l=0;lnt?1:r(h9(s,t,n))}function K9t(s,t,r){const n=Of(s)?s:aL(s);return n.start(z5e("",n,t,r)),n.animation}function p9(s,t,r,n={passive:!0}){return s.addEventListener(t,r,n),()=>s.removeEventListener(t,r)}const Y9t=(s,t)=>s.depth-t.depth;class Z9t{constructor(){this.children=[],this.isDirty=!1}add(t){T5e(this.children,t),this.isDirty=!0}remove(t){$he(this.children,t),this.isDirty=!0}forEach(t){this.isDirty&&this.children.sort(Y9t),this.isDirty=!1,this.children.forEach(t)}}function X9t(s,t){const r=ug.now(),n=({timestamp:a})=>{const i=a-r;i>=t&&(wS(n),s(i-t))};return zc.setup(n,!0),()=>wS(n)}function bue(s){return Of(s)?s.get():s}class Q9t{constructor(){this.members=[]}add(t){T5e(this.members,t);for(let r=this.members.length-1;r>=0;r--){const n=this.members[r];if(n===t||n===this.lead||n===this.prevLead)continue;const a=n.instance;(!a||a.isConnected===!1)&&!n.snapshot&&($he(this.members,n),n.unmount())}t.scheduleRender()}remove(t){if($he(this.members,t),t===this.prevLead&&(this.prevLead=void 0),t===this.lead){const r=this.members[this.members.length-1];r&&this.promote(r)}}relegate(t){var r;for(let n=this.members.indexOf(t)-1;n>=0;n--){const a=this.members[n];if(a.isPresent!==!1&&((r=a.instance)==null?void 0:r.isConnected)!==!1)return this.promote(a),!0}return!1}promote(t,r){var a;const n=this.lead;if(t!==n&&(this.prevLead=n,this.lead=t,t.show(),n)){n.updateSnapshot(),t.scheduleRender();const{layoutDependency:i}=n.options,{layoutDependency:l}=t.options;(i===void 0||i!==l)&&(t.resumeFrom=n,r&&(n.preserveOpacity=!0),n.snapshot&&(t.snapshot=n.snapshot,t.snapshot.latestValues=n.animationValues||n.latestValues),(a=t.root)!=null&&a.isUpdating&&(t.isLayoutDirty=!0)),t.options.crossfade===!1&&n.hide()}}exitAnimationComplete(){this.members.forEach(t=>{var r,n,a,i,l;(n=(r=t.options).onExitComplete)==null||n.call(r),(l=(a=t.resumingFrom)==null?void 0:(i=a.options).onExitComplete)==null||l.call(i)})}scheduleRender(){this.members.forEach(t=>t.instance&&t.scheduleRender(!1))}removeLeadSnapshot(){var t;(t=this.lead)!=null&&t.snapshot&&(this.lead.snapshot=void 0)}}const _ue={hasAnimatedSinceResize:!0,hasEverUpdated:!1},gbe=["","X","Y","Z"],J9t=1e3;let eBt=0;function xbe(s,t,r,n){const{latestValues:a}=t;a[s]&&(r[s]=a[s],t.setStaticValue(s,0),n&&(n[s]=0))}function gat(s){if(s.hasCheckedOptimisedAppear=!0,s.root===s)return;const{visualElement:t}=s.options;if(!t)return;const r=Ont(t);if(window.MotionHasOptimisedAnimation(r,"transform")){const{layout:a,layoutId:i}=s.options;window.MotionCancelOptimisedAnimation(r,"transform",zc,!(a||i))}const{parent:n}=s;n&&!n.hasCheckedOptimisedAppear&&gat(n)}function xat({attachResizeListener:s,defaultParent:t,measureScroll:r,checkIsScrollRoot:n,resetTransform:a}){return class{constructor(l={},o=t==null?void 0:t()){this.id=eBt++,this.animationId=0,this.animationCommitId=0,this.children=new Set,this.options={},this.isTreeAnimating=!1,this.isAnimationBlocked=!1,this.isLayoutDirty=!1,this.isProjectionDirty=!1,this.isSharedProjectionDirty=!1,this.isTransformDirty=!1,this.updateManuallyBlocked=!1,this.updateBlockedByResize=!1,this.isUpdating=!1,this.isSVG=!1,this.needsReset=!1,this.shouldResetTransform=!1,this.hasCheckedOptimisedAppear=!1,this.treeScale={x:1,y:1},this.eventHandlers=new Map,this.hasTreeAnimated=!1,this.layoutVersion=0,this.updateScheduled=!1,this.scheduleUpdate=()=>this.update(),this.projectionUpdateScheduled=!1,this.checkUpdateFailed=()=>{this.isUpdating&&(this.isUpdating=!1,this.clearAllSnapshots())},this.updateProjection=()=>{this.projectionUpdateScheduled=!1,this.nodes.forEach(rBt),this.nodes.forEach(cBt),this.nodes.forEach(dBt),this.nodes.forEach(nBt)},this.resolvedRelativeTargetAt=0,this.linkedParentVersion=0,this.hasProjected=!1,this.isVisible=!0,this.animationProgress=0,this.sharedNodes=new Map,this.latestValues=l,this.root=o?o.root||o:this,this.path=o?[...o.path,o]:[],this.parent=o,this.depth=o?o.depth+1:0;for(let c=0;cthis.root.updateBlockedByResize=!1;zc.read(()=>{m=window.innerWidth}),s(l,()=>{const x=window.innerWidth;x!==m&&(m=x,this.root.updateBlockedByResize=!0,h&&h(),h=X9t(p,250),_ue.hasAnimatedSinceResize&&(_ue.hasAnimatedSinceResize=!1,this.nodes.forEach(d7e)))})}o&&this.root.registerSharedNode(o,this),this.options.animate!==!1&&d&&(o||c)&&this.addEventListener("didUpdate",({delta:h,hasLayoutChanged:m,hasRelativeLayoutChanged:p,layout:x})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const y=this.options.transition||d.getDefaultTransition()||pBt,{onLayoutAnimationStart:_,onLayoutAnimationComplete:b}=d.getProps(),j=!this.targetLayout||!mat(this.targetLayout,x),k=!m&&p;if(this.options.layoutRoot||this.resumeFrom||k||m&&(j||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const T={...B5e(y,"layout"),onPlay:_,onComplete:b};(d.shouldReduceMotion||this.options.layoutRoot)&&(T.delay=0,T.type=!1),this.startAnimation(T),this.setAnimationOrigin(h,k)}else m||d7e(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=x})}unmount(){this.options.layoutId&&this.willUpdate(),this.root.nodes.remove(this);const l=this.getStack();l&&l.remove(this),this.parent&&this.parent.children.delete(this),this.instance=void 0,this.eventHandlers.clear(),wS(this.updateProjection)}blockUpdate(){this.updateManuallyBlocked=!0}unblockUpdate(){this.updateManuallyBlocked=!1}isUpdateBlocked(){return this.updateManuallyBlocked||this.updateBlockedByResize}isTreeAnimationBlocked(){return this.isAnimationBlocked||this.parent&&this.parent.isTreeAnimationBlocked()||!1}startUpdate(){this.isUpdateBlocked()||(this.isUpdating=!0,this.nodes&&this.nodes.forEach(uBt),this.animationId++)}getTransformTemplate(){const{visualElement:l}=this.options;return l&&l.getProps().transformTemplate}willUpdate(l=!0){if(this.root.hasTreeAnimated=!0,this.root.isUpdateBlocked()){this.options.onExitComplete&&this.options.onExitComplete();return}if(window.MotionCancelOptimisedAnimation&&!this.hasCheckedOptimisedAppear&&gat(this),!this.root.isUpdating&&this.root.startUpdate(),this.isLayoutDirty)return;this.isLayoutDirty=!0;for(let h=0;h{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!hg(this.snapshot.measuredBox.x)&&!hg(this.snapshot.measuredBox.y)&&(this.snapshot=void 0))}updateLayout(){if(!this.instance||(this.updateScroll(),!(this.options.alwaysMeasureLayout&&this.isLead())&&!this.isLayoutDirty))return;if(this.resumeFrom&&!this.resumeFrom.instance)for(let c=0;c{const A=E/1e3;u7e(m.x,l.x,A),u7e(m.y,l.y,A),this.setTargetDelta(m),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(Khe(p,this.layout.layoutBox,this.relativeParent.layout.layoutBox,this.options.layoutAnchor||void 0),mBt(this.relativeTarget,this.relativeTargetOrigin,p,A),T&&U9t(this.relativeTarget,T)&&(this.isProjectionDirty=!1),T||(T=sm()),Vv(T,this.relativeTarget)),_&&(this.animationValues=h,H9t(h,d,this.latestValues,A,k,j)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=A},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(l){var o,c,d;this.notifyListeners("animationStart"),(o=this.currentAnimation)==null||o.stop(),(d=(c=this.resumingFrom)==null?void 0:c.currentAnimation)==null||d.stop(),this.pendingAnimation&&(wS(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=zc.update(()=>{_ue.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=aL(0)),this.motionValue.jump(0,!1),this.currentAnimation=K9t(this.motionValue,[0,1e3],{...l,velocity:0,isSync:!0,onUpdate:h=>{this.mixTargetDelta(h),l.onUpdate&&l.onUpdate(h)},onStop:()=>{},onComplete:()=>{l.onComplete&&l.onComplete(),this.completeAnimation()}}),this.resumingFrom&&(this.resumingFrom.currentAnimation=this.currentAnimation),this.pendingAnimation=void 0})}completeAnimation(){this.resumingFrom&&(this.resumingFrom.currentAnimation=void 0,this.resumingFrom.preserveOpacity=void 0);const l=this.getStack();l&&l.exitAnimationComplete(),this.resumingFrom=this.currentAnimation=this.animationValues=void 0,this.notifyListeners("animationComplete")}finishAnimation(){this.currentAnimation&&(this.mixTargetDelta&&this.mixTargetDelta(J9t),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const l=this.getLead();let{targetWithTransforms:o,target:c,layout:d,latestValues:h}=l;if(!(!o||!c||!d)){if(this!==l&&this.layout&&d&&yat(this.options.animationType,this.layout.layoutBox,d.layoutBox)){c=this.target||sm();const m=hg(this.layout.layoutBox.x);c.x.min=l.target.x.min,c.x.max=c.x.min+m;const p=hg(this.layout.layoutBox.y);c.y.min=l.target.y.min,c.y.max=c.y.min+p}Vv(o,c),vue(o,h),JF(this.projectionDeltaWithTransform,this.layoutCorrected,o,h)}}registerSharedNode(l,o){this.sharedNodes.has(l)||this.sharedNodes.set(l,new Q9t),this.sharedNodes.get(l).add(o);const d=o.options.initialPromotionConfig;o.promote({transition:d?d.transition:void 0,preserveFollowOpacity:d&&d.shouldPreserveFollowOpacity?d.shouldPreserveFollowOpacity(o):void 0})}isLead(){const l=this.getStack();return l?l.lead===this:!0}getLead(){var o;const{layoutId:l}=this.options;return l?((o=this.getStack())==null?void 0:o.lead)||this:this}getPrevLead(){var o;const{layoutId:l}=this.options;return l?(o=this.getStack())==null?void 0:o.prevLead:void 0}getStack(){const{layoutId:l}=this.options;if(l)return this.root.sharedNodes.get(l)}promote({needsReset:l,transition:o,preserveFollowOpacity:c}={}){const d=this.getStack();d&&d.promote(this,c),l&&(this.projectionDelta=void 0,this.needsReset=!0),o&&this.setOptions({transition:o})}relegate(){const l=this.getStack();return l?l.relegate(this):!1}resetSkewAndRotation(){const{visualElement:l}=this.options;if(!l)return;let o=!1;const{latestValues:c}=l;if((c.z||c.rotate||c.rotateX||c.rotateY||c.rotateZ||c.skewX||c.skewY)&&(o=!0),!o)return;const d={};c.z&&xbe("z",l,d,this.animationValues);for(let h=0;h{var o;return(o=l.currentAnimation)==null?void 0:o.stop()}),this.root.nodes.forEach(l7e),this.root.sharedNodes.clear()}}}function tBt(s){s.updateLayout()}function sBt(s){var r;const t=((r=s.resumeFrom)==null?void 0:r.snapshot)||s.snapshot;if(s.isLead()&&s.layout&&t&&s.hasListeners("didUpdate")){const{layoutBox:n,measuredBox:a}=s.layout,{animationType:i}=s.options,l=t.source!==s.layout.source;if(i==="size")Ob(m=>{const p=l?t.measuredBox[m]:t.layoutBox[m],x=hg(p);p.min=n[m].min,p.max=p.min+x});else if(i==="x"||i==="y"){const m=i==="x"?"y":"x";INe(l?t.measuredBox[m]:t.layoutBox[m],n[m])}else yat(i,t.layoutBox,n)&&Ob(m=>{const p=l?t.measuredBox[m]:t.layoutBox[m],x=hg(n[m]);p.max=p.min+x,s.relativeTarget&&!s.currentAnimation&&(s.isProjectionDirty=!0,s.relativeTarget[m].max=s.relativeTarget[m].min+x)});const o=dI();JF(o,n,t.layoutBox);const c=dI();l?JF(c,s.applyTransform(a,!0),t.measuredBox):JF(c,n,t.layoutBox);const d=!hat(o);let h=!1;if(!s.resumeFrom){const m=s.getClosestProjectingParent();if(m&&!m.resumeFrom){const{snapshot:p,layout:x}=m;if(p&&x){const y=s.options.layoutAnchor||void 0,_=sm();Khe(_,t.layoutBox,p.layoutBox,y);const b=sm();Khe(b,n,x.layoutBox,y),mat(_,b)||(h=!0),m.options.layoutRoot&&(s.relativeTarget=b,s.relativeTargetOrigin=_,s.relativeParent=m)}}}s.notifyListeners("didUpdate",{layout:n,snapshot:t,delta:c,layoutDelta:o,hasLayoutChanged:d,hasRelativeLayoutChanged:h})}else if(s.isLead()){const{onExitComplete:n}=s.options;n&&n()}s.options.transition=void 0}function rBt(s){s.parent&&(s.isProjecting()||(s.isProjectionDirty=s.parent.isProjectionDirty),s.isSharedProjectionDirty||(s.isSharedProjectionDirty=!!(s.isProjectionDirty||s.parent.isProjectionDirty||s.parent.isSharedProjectionDirty)),s.isTransformDirty||(s.isTransformDirty=s.parent.isTransformDirty))}function nBt(s){s.isProjectionDirty=s.isSharedProjectionDirty=s.isTransformDirty=!1}function aBt(s){s.clearSnapshot()}function l7e(s){s.clearMeasurements()}function iBt(s){s.isLayoutDirty=!0,s.updateLayout()}function c7e(s){s.isLayoutDirty=!1}function oBt(s){s.isAnimationBlocked&&s.layout&&!s.isLayoutDirty&&(s.snapshot=s.layout,s.isLayoutDirty=!0)}function lBt(s){const{visualElement:t}=s.options;t&&t.getProps().onBeforeLayoutMeasure&&t.notify("BeforeLayoutMeasure"),s.resetTransform()}function d7e(s){s.finishAnimation(),s.targetDelta=s.relativeTarget=s.target=void 0,s.isProjectionDirty=!0}function cBt(s){s.resolveTargetDelta()}function dBt(s){s.calcProjection()}function uBt(s){s.resetSkewAndRotation()}function hBt(s){s.removeLeadSnapshot()}function u7e(s,t,r){s.translate=Sd(t.translate,0,r),s.scale=Sd(t.scale,1,r),s.origin=t.origin,s.originPoint=t.originPoint}function h7e(s,t,r,n){s.min=Sd(t.min,r.min,n),s.max=Sd(t.max,r.max,n)}function mBt(s,t,r,n){h7e(s.x,t.x,r.x,n),h7e(s.y,t.y,r.y,n)}function fBt(s){return s.animationValues&&s.animationValues.opacityExit!==void 0}const pBt={duration:.45,ease:[.4,0,.1,1]},m7e=s=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(s),f7e=m7e("applewebkit/")&&!m7e("chrome/")?Math.round:Wy;function p7e(s){s.min=f7e(s.min),s.max=f7e(s.max)}function gBt(s){p7e(s.x),p7e(s.y)}function yat(s,t,r){return s==="position"||s==="preserve-aspect"&&!O9t(r7e(t),r7e(r),.2)}function xBt(s){var t;return s!==s.root&&((t=s.scroll)==null?void 0:t.wasRoot)}const yBt=xat({attachResizeListener:(s,t)=>p9(s,"resize",t),measureScroll:()=>{var s,t;return{x:document.documentElement.scrollLeft||((s=document.body)==null?void 0:s.scrollLeft)||0,y:document.documentElement.scrollTop||((t=document.body)==null?void 0:t.scrollTop)||0}},checkIsScrollRoot:()=>!0}),ybe={current:void 0},vat=xat({measureScroll:s=>({x:s.scrollLeft,y:s.scrollTop}),defaultParent:()=>{if(!ybe.current){const s=new yBt({});s.mount(window),s.setOptions({layoutScroll:!0}),ybe.current=s}return ybe.current},resetTransform:(s,t)=>{s.style.transform=t!==void 0?t:"none"},checkIsScrollRoot:s=>window.getComputedStyle(s).position==="fixed"}),Q5e=S.createContext({transformPagePoint:s=>s,isStatic:!1,reducedMotion:"never"});function g7e(s,t){if(typeof s=="function")return s(t);s!=null&&(s.current=t)}function vBt(...s){return t=>{let r=!1;const n=s.map(a=>{const i=g7e(a,t);return!r&&typeof i=="function"&&(r=!0),i});if(r)return()=>{for(let a=0;a{const{width:x,height:y,top:_,left:b,right:j,bottom:k}=c.current;if(t||i===!1||!o.current||!x||!y)return;const T=r==="left"?`left: ${b}`:`right: ${j}`,E=n==="bottom"?`bottom: ${k}`:`top: ${_}`;o.current.dataset.motionPopId=l;const A=document.createElement("style");d&&(A.nonce=d);const D=a??document.head;return D.appendChild(A),A.sheet&&A.sheet.insertRule(` [data-motion-pop-id="${l}"] { position: absolute !important; width: ${x}px !important; height: ${y}px !important; ${T}px !important; ${E}px !important; } `),()=>{var R;(R=o.current)==null||R.removeAttribute("data-motion-pop-id"),D.contains(A)&&D.removeChild(A)}},[t]),e.jsx(_Bt,{isPresent:t,childRef:o,sizeRef:c,pop:i,children:i===!1?s:S.cloneElement(s,{ref:m})})}const jBt=({children:s,initial:t,isPresent:r,onExitComplete:n,custom:a,presenceAffectsLayout:i,mode:l,anchorX:o,anchorY:c,root:d})=>{const h=C5e(NBt),m=S.useId();let p=!0,x=S.useMemo(()=>(p=!1,{id:m,initial:t,isPresent:r,custom:a,onExitComplete:y=>{h.set(y,!0);for(const _ of h.values())if(!_)return;n&&n()},register:y=>(h.set(y,!1),()=>h.delete(y))}),[r,h,n]);return i&&p&&(x={...x}),S.useMemo(()=>{h.forEach((y,_)=>h.set(_,!1))},[r]),S.useEffect(()=>{!r&&!h.size&&n&&n()},[r]),s=e.jsx(wBt,{pop:l==="popLayout",isPresent:r,anchorX:o,anchorY:c,root:d,children:s}),e.jsx(Pge.Provider,{value:x,children:s})};function NBt(){return new Map}function bat(s=!0){const t=S.useContext(Pge);if(t===null)return[!0,null];const{isPresent:r,onExitComplete:n,register:a}=t,i=S.useId();S.useEffect(()=>{if(s)return a(i)},[s]);const l=S.useCallback(()=>s&&n&&n(i),[i,n,s]);return!r&&n?[!1,l]:[!0]}const WU=s=>s.key||"";function x7e(s){const t=[];return S.Children.forEach(s,r=>{S.isValidElement(r)&&t.push(r)}),t}const J5e=({children:s,custom:t,initial:r=!0,onExitComplete:n,presenceAffectsLayout:a=!0,mode:i="sync",propagate:l=!1,anchorX:o="left",anchorY:c="top",root:d})=>{const[h,m]=bat(l),p=S.useMemo(()=>x7e(s),[s]),x=l&&!h?[]:p.map(WU),y=S.useRef(!0),_=S.useRef(p),b=C5e(()=>new Map),j=S.useRef(new Set),[k,T]=S.useState(p),[E,A]=S.useState(p);Krt(()=>{y.current=!1,_.current=p;for(let z=0;z{const O=WU(z),$=l&&!h?!1:p===E||x.includes(O),ee=()=>{if(j.current.has(O))return;if(b.has(O))j.current.add(O),b.set(O,!0);else return;let Z=!0;b.forEach(J=>{J||(Z=!1)}),Z&&(R==null||R(),A(_.current),l&&(m==null||m()),n&&n())};return e.jsx(jBt,{isPresent:$,initial:!y.current||r?void 0:!1,custom:t,presenceAffectsLayout:a,mode:i,root:d,onExitComplete:$?void 0:ee,anchorX:o,anchorY:c,children:z},O)})})},_at=S.createContext({strict:!1}),y7e={animation:["animate","variants","whileHover","whileTap","exit","whileInView","whileFocus","whileDrag"],exit:["exit"],drag:["drag","dragControls"],focus:["whileFocus"],hover:["whileHover","onHoverStart","onHoverEnd"],tap:["whileTap","onTap","onTapStart","onTapCancel"],pan:["onPan","onPanStart","onPanSessionStart","onPanEnd"],inView:["whileInView","onViewportEnter","onViewportLeave"],layout:["layout","layoutId"]};let v7e=!1;function kBt(){if(v7e)return;const s={};for(const t in y7e)s[t]={isEnabled:r=>y7e[t].some(n=>!!r[n])};Znt(s),v7e=!0}function wat(){return kBt(),c9t()}function SBt(s){const t=wat();for(const r in s)t[r]={...t[r],...s[r]};Znt(t)}const CBt=new Set(["animate","exit","variants","initial","style","values","variants","transition","transformTemplate","custom","inherit","onBeforeLayoutMeasure","onAnimationStart","onAnimationComplete","onUpdate","onDragStart","onDrag","onDragEnd","onMeasureDragConstraints","onDirectionLock","onDragTransitionEnd","_dragX","_dragY","onHoverStart","onHoverEnd","onViewportEnter","onViewportLeave","globalTapTarget","propagate","ignoreStrict","viewport"]);function Yhe(s){return s.startsWith("while")||s.startsWith("drag")&&s!=="draggable"||s.startsWith("layout")||s.startsWith("onTap")||s.startsWith("onPan")||s.startsWith("onLayout")||CBt.has(s)}let jat=s=>!Yhe(s);function TBt(s){typeof s=="function"&&(jat=t=>t.startsWith("on")?!Yhe(t):s(t))}try{TBt(require("@emotion/is-prop-valid").default)}catch{}function EBt(s,t,r){const n={};for(const a in s)a==="values"&&typeof s.values=="object"||Of(s[a])||(jat(a)||r===!0&&Yhe(a)||!t&&!Yhe(a)||s.draggable&&a.startsWith("onDrag"))&&(n[a]=s[a]);return n}const Fge=S.createContext({});function ABt(s,t){if(Oge(s)){const{initial:r,animate:n}=s;return{initial:r===!1||f9(r)?r:void 0,animate:f9(n)?n:void 0}}return s.inherit!==!1?t:{}}function MBt(s){const{initial:t,animate:r}=ABt(s,S.useContext(Fge));return S.useMemo(()=>({initial:t,animate:r}),[b7e(t),b7e(r)])}function b7e(s){return Array.isArray(s)?s.join(" "):s}const eTe=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function Nat(s,t,r){for(const n in t)!Of(t[n])&&!rat(n,r)&&(s[n]=t[n])}function IBt({transformTemplate:s},t){return S.useMemo(()=>{const r=eTe();return Z5e(r,t,s),Object.assign({},r.vars,r.style)},[t])}function PBt(s,t){const r=s.style||{},n={};return Nat(n,r,s),Object.assign(n,IBt(s,t)),n}function LBt(s,t){const r={},n=PBt(s,t);return s.drag&&s.dragListener!==!1&&(r.draggable=!1,n.userSelect=n.WebkitUserSelect=n.WebkitTouchCallout="none",n.touchAction=s.drag===!0?"none":`pan-${s.drag==="x"?"y":"x"}`),s.tabIndex===void 0&&(s.onTap||s.onTapStart||s.whileTap)&&(r.tabIndex=0),r.style=n,r}const kat=()=>({...eTe(),attrs:{}});function DBt(s,t,r,n){const a=S.useMemo(()=>{const i=kat();return nat(i,t,iat(n),s.transformTemplate,s.style),{...i.attrs,style:{...i.style}}},[t]);if(s.style){const i={};Nat(i,s.style,s),a.style={...i,...a.style}}return a}const RBt=["animate","circle","defs","desc","ellipse","g","image","line","filter","marker","mask","metadata","path","pattern","polygon","polyline","rect","stop","switch","symbol","svg","text","tspan","use","view"];function tTe(s){return typeof s!="string"||s.includes("-")?!1:!!(RBt.indexOf(s)>-1||/[A-Z]/u.test(s))}function OBt(s,t,r,{latestValues:n},a,i=!1,l){const c=(l??tTe(s)?DBt:LBt)(t,n,a,s),d=EBt(t,typeof s=="string",i),h=s!==S.Fragment?{...d,...c,ref:r}:{},{children:m}=t,p=S.useMemo(()=>Of(m)?m.get():m,[m]);return S.createElement(s,{...h,children:p})}function FBt({scrapeMotionValuesFromProps:s,createRenderState:t},r,n,a){return{latestValues:BBt(r,n,a,s),renderState:t()}}function BBt(s,t,r,n){const a={},i=n(s,{});for(const p in i)a[p]=bue(i[p]);let{initial:l,animate:o}=s;const c=Oge(s),d=Knt(s);t&&d&&!c&&s.inherit!==!1&&(l===void 0&&(l=t.initial),o===void 0&&(o=t.animate));let h=r?r.initial===!1:!1;h=h||l===!1;const m=h?o:l;if(m&&typeof m!="boolean"&&!Rge(m)){const p=Array.isArray(m)?m:[m];for(let x=0;x(t,r)=>{const n=S.useContext(Fge),a=S.useContext(Pge),i=()=>FBt(s,t,n,a);return r?i():C5e(i)},zBt=Sat({scrapeMotionValuesFromProps:X5e,createRenderState:eTe}),$Bt=Sat({scrapeMotionValuesFromProps:oat,createRenderState:kat}),UBt=Symbol.for("motionComponentSymbol");function qBt(s,t,r){const n=S.useRef(r);S.useInsertionEffect(()=>{n.current=r});const a=S.useRef(null);return S.useCallback(i=>{var o;i&&((o=s.onMount)==null||o.call(s,i));const l=n.current;if(typeof l=="function")if(i){const c=l(i);typeof c=="function"&&(a.current=c)}else a.current?(a.current(),a.current=null):l(i);else l&&(l.current=i);t&&(i?t.mount(i):t.unmount())},[t])}const Cat=S.createContext({});function z6(s){return s&&typeof s=="object"&&Object.prototype.hasOwnProperty.call(s,"current")}function VBt(s,t,r,n,a,i){var T,E;const{visualElement:l}=S.useContext(Fge),o=S.useContext(_at),c=S.useContext(Pge),d=S.useContext(Q5e),h=d.reducedMotion,m=d.skipAnimations,p=S.useRef(null),x=S.useRef(!1);n=n||o.renderer,!p.current&&n&&(p.current=n(s,{visualState:t,parent:l,props:r,presenceContext:c,blockInitialAnimation:c?c.initial===!1:!1,reducedMotionConfig:h,skipAnimations:m,isSVG:i}),x.current&&p.current&&(p.current.manuallyAnimateOnMount=!0));const y=p.current,_=S.useContext(Cat);y&&!y.projection&&a&&(y.type==="html"||y.type==="svg")&&HBt(p.current,r,a,_);const b=S.useRef(!1);S.useInsertionEffect(()=>{y&&b.current&&y.update(r,c)});const j=r[Rnt],k=S.useRef(!!j&&typeof window<"u"&&!((T=window.MotionHandoffIsComplete)!=null&&T.call(window,j))&&((E=window.MotionHasOptimisedAnimation)==null?void 0:E.call(window,j)));return Krt(()=>{x.current=!0,y&&(b.current=!0,window.MotionIsMounted=!0,y.updateFeatures(),y.scheduleRenderMicrotask(),k.current&&y.animationState&&y.animationState.animateChanges())}),S.useEffect(()=>{y&&(!k.current&&y.animationState&&y.animationState.animateChanges(),k.current&&(queueMicrotask(()=>{var A;(A=window.MotionHandoffMarkAsComplete)==null||A.call(window,j)}),k.current=!1),y.enteringChildren=void 0)}),y}function HBt(s,t,r,n){const{layoutId:a,layout:i,drag:l,dragConstraints:o,layoutScroll:c,layoutRoot:d,layoutAnchor:h,layoutCrossfade:m}=t;s.projection=new r(s.latestValues,t["data-framer-portal-id"]?void 0:Tat(s.parent)),s.projection.setOptions({layoutId:a,layout:i,alwaysMeasureLayout:!!l||o&&z6(o),visualElement:s,animationType:typeof i=="string"?i:"both",initialPromotionConfig:n,crossfade:m,layoutScroll:c,layoutRoot:d,layoutAnchor:h})}function Tat(s){if(s)return s.options.allowProjection!==!1?s.projection:Tat(s.parent)}function vbe(s,{forwardMotionProps:t=!1,type:r}={},n,a){n&&SBt(n);const i=r?r==="svg":tTe(s),l=i?$Bt:zBt;function o(d,h){let m;const p={...S.useContext(Q5e),...d,layoutId:GBt(d)},{isStatic:x}=p,y=MBt(d),_=l(d,x);if(!x&&typeof window<"u"){WBt();const b=KBt(p);m=b.MeasureLayout,y.visualElement=VBt(s,_,p,a,b.ProjectionNode,i)}return e.jsxs(Fge.Provider,{value:y,children:[m&&y.visualElement?e.jsx(m,{visualElement:y.visualElement,...p}):null,OBt(s,d,qBt(_,y.visualElement,h),_,x,t,i)]})}o.displayName=`motion.${typeof s=="string"?s:`create(${s.displayName??s.name??""})`}`;const c=S.forwardRef(o);return c[UBt]=s,c}function GBt({layoutId:s}){const t=S.useContext(S5e).id;return t&&s!==void 0?t+"-"+s:s}function WBt(s,t){S.useContext(_at).strict}function KBt(s){const t=wat(),{drag:r,layout:n}=t;if(!r&&!n)return{};const a={...r,...n};return{MeasureLayout:r!=null&&r.isEnabled(s)||n!=null&&n.isEnabled(s)?a.MeasureLayout:void 0,ProjectionNode:a.ProjectionNode}}function YBt(s,t){if(typeof Proxy>"u")return vbe;const r=new Map,n=(i,l)=>vbe(i,l,s,t),a=(i,l)=>n(i,l);return new Proxy(a,{get:(i,l)=>l==="create"?n:(r.has(l)||r.set(l,vbe(l,void 0,s,t)),r.get(l))})}const ZBt=(s,t)=>t.isSVG??tTe(s)?new S9t(t):new b9t(t,{allowProjection:s!==S.Fragment});class XBt extends VS{constructor(t){super(t),t.animationState||(t.animationState=M9t(t))}updateAnimationControlsSubscription(){const{animate:t}=this.node.getProps();Rge(t)&&(this.unmountControls=t.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){const{animate:t}=this.node.getProps(),{animate:r}=this.node.prevProps||{};t!==r&&this.updateAnimationControlsSubscription()}unmount(){var t;this.node.animationState.reset(),(t=this.unmountControls)==null||t.call(this)}}let QBt=0;class JBt extends VS{constructor(){super(...arguments),this.id=QBt++,this.isExitComplete=!1}update(){var i;if(!this.node.presenceContext)return;const{isPresent:t,onExitComplete:r}=this.node.presenceContext,{isPresent:n}=this.node.prevPresenceContext||{};if(!this.node.animationState||t===n)return;if(t&&n===!1){if(this.isExitComplete){const{initial:l,custom:o}=this.node.getProps();if(typeof l=="string"){const c=$E(this.node,l,o);if(c){const{transition:d,transitionEnd:h,...m}=c;for(const p in m)(i=this.node.getValue(p))==null||i.jump(m[p])}}this.node.animationState.reset(),this.node.animationState.animateChanges()}else this.node.animationState.setActive("exit",!1);this.isExitComplete=!1;return}const a=this.node.animationState.setActive("exit",!t);r&&!t&&a.then(()=>{this.isExitComplete=!0,r(this.id)})}mount(){const{register:t,onExitComplete:r}=this.node.presenceContext||{};r&&r(this.id),t&&(this.unmount=t(this.id))}unmount(){}}const ezt={animation:{Feature:XBt},exit:{Feature:JBt}};function rz(s){return{point:{x:s.pageX,y:s.pageY}}}const tzt=s=>t=>G5e(t)&&s(t,rz(t));function e7(s,t,r,n){return p9(s,t,tzt(r),n)}const Eat=({current:s})=>s?s.ownerDocument.defaultView:null,_7e=(s,t)=>Math.abs(s-t);function szt(s,t){const r=_7e(s.x,t.x),n=_7e(s.y,t.y);return Math.sqrt(r**2+n**2)}const w7e=new Set(["auto","scroll"]);class Aat{constructor(t,r,{transformPagePoint:n,contextWindow:a=window,dragSnapToOrigin:i=!1,distanceThreshold:l=3,element:o}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.lastRawMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.scrollPositions=new Map,this.removeScrollListeners=null,this.onElementScroll=x=>{this.handleScroll(x.target)},this.onWindowScroll=()=>{this.handleScroll(window)},this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;this.lastRawMoveEventInfo&&(this.lastMoveEventInfo=KU(this.lastRawMoveEventInfo,this.transformPagePoint));const x=bbe(this.lastMoveEventInfo,this.history),y=this.startEvent!==null,_=szt(x.offset,{x:0,y:0})>=this.distanceThreshold;if(!y&&!_)return;const{point:b}=x,{timestamp:j}=Mf;this.history.push({...b,timestamp:j});const{onStart:k,onMove:T}=this.handlers;y||(k&&k(this.lastMoveEvent,x),this.startEvent=this.lastMoveEvent),T&&T(this.lastMoveEvent,x)},this.handlePointerMove=(x,y)=>{this.lastMoveEvent=x,this.lastRawMoveEventInfo=y,this.lastMoveEventInfo=KU(y,this.transformPagePoint),zc.update(this.updatePoint,!0)},this.handlePointerUp=(x,y)=>{this.end();const{onEnd:_,onSessionEnd:b,resumeAnimation:j}=this.handlers;if((this.dragSnapToOrigin||!this.startEvent)&&j&&j(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const k=bbe(x.type==="pointercancel"?this.lastMoveEventInfo:KU(y,this.transformPagePoint),this.history);this.startEvent&&_&&_(x,k),b&&b(x,k)},!G5e(t))return;this.dragSnapToOrigin=i,this.handlers=r,this.transformPagePoint=n,this.distanceThreshold=l,this.contextWindow=a||window;const c=rz(t),d=KU(c,this.transformPagePoint),{point:h}=d,{timestamp:m}=Mf;this.history=[{...h,timestamp:m}];const{onSessionStart:p}=r;p&&p(t,bbe(d,this.history)),this.removeListeners=ez(e7(this.contextWindow,"pointermove",this.handlePointerMove),e7(this.contextWindow,"pointerup",this.handlePointerUp),e7(this.contextWindow,"pointercancel",this.handlePointerUp)),o&&this.startScrollTracking(o)}startScrollTracking(t){let r=t.parentElement;for(;r;){const n=getComputedStyle(r);(w7e.has(n.overflowX)||w7e.has(n.overflowY))&&this.scrollPositions.set(r,{x:r.scrollLeft,y:r.scrollTop}),r=r.parentElement}this.scrollPositions.set(window,{x:window.scrollX,y:window.scrollY}),window.addEventListener("scroll",this.onElementScroll,{capture:!0}),window.addEventListener("scroll",this.onWindowScroll),this.removeScrollListeners=()=>{window.removeEventListener("scroll",this.onElementScroll,{capture:!0}),window.removeEventListener("scroll",this.onWindowScroll)}}handleScroll(t){const r=this.scrollPositions.get(t);if(!r)return;const n=t===window,a=n?{x:window.scrollX,y:window.scrollY}:{x:t.scrollLeft,y:t.scrollTop},i={x:a.x-r.x,y:a.y-r.y};i.x===0&&i.y===0||(n?this.lastMoveEventInfo&&(this.lastMoveEventInfo.point.x+=i.x,this.lastMoveEventInfo.point.y+=i.y):this.history.length>0&&(this.history[0].x-=i.x,this.history[0].y-=i.y),this.scrollPositions.set(t,a),zc.update(this.updatePoint,!0))}updateHandlers(t){this.handlers=t}end(){this.removeListeners&&this.removeListeners(),this.removeScrollListeners&&this.removeScrollListeners(),this.scrollPositions.clear(),wS(this.updatePoint)}}function KU(s,t){return t?{point:t(s.point)}:s}function j7e(s,t){return{x:s.x-t.x,y:s.y-t.y}}function bbe({point:s},t){return{point:s,delta:j7e(s,Mat(t)),offset:j7e(s,rzt(t)),velocity:nzt(t,.1)}}function rzt(s){return s[0]}function Mat(s){return s[s.length-1]}function nzt(s,t){if(s.length<2)return{x:0,y:0};let r=s.length-1,n=null;const a=Mat(s);for(;r>=0&&(n=s[r],!(a.timestamp-n.timestamp>ux(t)));)r--;if(!n)return{x:0,y:0};n===s[0]&&s.length>2&&a.timestamp-n.timestamp>ux(t)*2&&(n=s[1]);const i=Fy(a.timestamp-n.timestamp);if(i===0)return{x:0,y:0};const l={x:(a.x-n.x)/i,y:(a.y-n.y)/i};return l.x===1/0&&(l.x=0),l.y===1/0&&(l.y=0),l}function azt(s,{min:t,max:r},n){return t!==void 0&&sr&&(s=n?Sd(r,s,n.max):Math.min(s,r)),s}function N7e(s,t,r){return{min:t!==void 0?s.min+t:void 0,max:r!==void 0?s.max+r-(s.max-s.min):void 0}}function izt(s,{top:t,left:r,bottom:n,right:a}){return{x:N7e(s.x,r,a),y:N7e(s.y,t,n)}}function k7e(s,t){let r=t.min-s.min,n=t.max-s.max;return t.max-t.minn?r=h9(t.min,t.max-n,s.min):n>a&&(r=h9(s.min,s.max-a,t.min)),I_(0,1,r)}function czt(s,t){const r={};return t.min!==void 0&&(r.min=t.min-s.min),t.max!==void 0&&(r.max=t.max-s.min),r}const PNe=.35;function dzt(s=PNe){return s===!1?s=0:s===!0&&(s=PNe),{x:S7e(s,"left","right"),y:S7e(s,"top","bottom")}}function S7e(s,t,r){return{min:C7e(s,t),max:C7e(s,r)}}function C7e(s,t){return typeof s=="number"?s:s[t]||0}const uzt=new WeakMap;class hzt{constructor(t){this.openDragLock=null,this.isDragging=!1,this.currentDirection=null,this.originPoint={x:0,y:0},this.constraints=!1,this.hasMutatedConstraints=!1,this.elastic=sm(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=t}start(t,{snapToCursor:r=!1,distanceThreshold:n}={}){const{presenceContext:a}=this.visualElement;if(a&&a.isPresent===!1)return;const i=m=>{r&&this.snapToCursor(rz(m).point),this.stopAnimation()},l=(m,p)=>{const{drag:x,dragPropagation:y,onDragStart:_}=this.getProps();if(x&&!y&&(this.openDragLock&&this.openDragLock(),this.openDragLock=B7t(x),!this.openDragLock))return;this.latestPointerEvent=m,this.latestPanInfo=p,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),Ob(j=>{let k=this.getAxisMotionValue(j).get()||0;if(j_.test(k)){const{projection:T}=this.visualElement;if(T&&T.layout){const E=T.layout.layoutBox[j];E&&(k=hg(E)*(parseFloat(k)/100))}}this.originPoint[j]=k}),_&&zc.update(()=>_(m,p),!1,!0),NNe(this.visualElement,"transform");const{animationState:b}=this.visualElement;b&&b.setActive("whileDrag",!0)},o=(m,p)=>{this.latestPointerEvent=m,this.latestPanInfo=p;const{dragPropagation:x,dragDirectionLock:y,onDirectionLock:_,onDrag:b}=this.getProps();if(!x&&!this.openDragLock)return;const{offset:j}=p;if(y&&this.currentDirection===null){this.currentDirection=fzt(j),this.currentDirection!==null&&_&&_(this.currentDirection);return}this.updateAxis("x",p.point,j),this.updateAxis("y",p.point,j),this.visualElement.render(),b&&zc.update(()=>b(m,p),!1,!0)},c=(m,p)=>{this.latestPointerEvent=m,this.latestPanInfo=p,this.stop(m,p),this.latestPointerEvent=null,this.latestPanInfo=null},d=()=>{const{dragSnapToOrigin:m}=this.getProps();(m||this.constraints)&&this.startAnimation({x:0,y:0})},{dragSnapToOrigin:h}=this.getProps();this.panSession=new Aat(t,{onSessionStart:i,onStart:l,onMove:o,onSessionEnd:c,resumeAnimation:d},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:h,distanceThreshold:n,contextWindow:Eat(this.visualElement),element:this.visualElement.current})}stop(t,r){const n=t||this.latestPointerEvent,a=r||this.latestPanInfo,i=this.isDragging;if(this.cancel(),!i||!a||!n)return;const{velocity:l}=a;this.startAnimation(l);const{onDragEnd:o}=this.getProps();o&&zc.postRender(()=>o(n,a))}cancel(){this.isDragging=!1;const{projection:t,animationState:r}=this.visualElement;t&&(t.isAnimationBlocked=!1),this.endPanSession();const{dragPropagation:n}=this.getProps();!n&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),r&&r.setActive("whileDrag",!1)}endPanSession(){this.panSession&&this.panSession.end(),this.panSession=void 0}updateAxis(t,r,n){const{drag:a}=this.getProps();if(!n||!YU(t,a,this.currentDirection))return;const i=this.getAxisMotionValue(t);let l=this.originPoint[t]+n[t];this.constraints&&this.constraints[t]&&(l=azt(l,this.constraints[t],this.elastic[t])),i.set(l)}resolveConstraints(){var i;const{dragConstraints:t,dragElastic:r}=this.getProps(),n=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):(i=this.visualElement.projection)==null?void 0:i.layout,a=this.constraints;t&&z6(t)?this.constraints||(this.constraints=this.resolveRefConstraints()):t&&n?this.constraints=izt(n.layoutBox,t):this.constraints=!1,this.elastic=dzt(r),a!==this.constraints&&!z6(t)&&n&&this.constraints&&!this.hasMutatedConstraints&&Ob(l=>{this.constraints!==!1&&this.getAxisMotionValue(l)&&(this.constraints[l]=czt(n.layoutBox[l],this.constraints[l]))})}resolveRefConstraints(){const{dragConstraints:t,onMeasureDragConstraints:r}=this.getProps();if(!t||!z6(t))return!1;const n=t.current;rL(n!==null,"If `dragConstraints` is set as a React ref, that ref must be passed to another component's `ref` prop.","drag-constraints-ref");const{projection:a}=this.visualElement;if(!a||!a.layout)return!1;const i=f9t(n,a.root,this.visualElement.getTransformPagePoint());let l=ozt(a.layout.layoutBox,i);if(r){const o=r(u9t(l));this.hasMutatedConstraints=!!o,o&&(l=Qnt(o))}return l}startAnimation(t){const{drag:r,dragMomentum:n,dragElastic:a,dragTransition:i,dragSnapToOrigin:l,onDragTransitionEnd:o}=this.getProps(),c=this.constraints||{},d=Ob(h=>{if(!YU(h,r,this.currentDirection))return;let m=c&&c[h]||{};(l===!0||l===h)&&(m={min:0,max:0});const p=a?200:1e6,x=a?40:1e7,y={type:"inertia",velocity:n?t[h]:0,bounceStiffness:p,bounceDamping:x,timeConstant:750,restDelta:1,restSpeed:10,...i,...m};return this.startAxisValueAnimation(h,y)});return Promise.all(d).then(o)}startAxisValueAnimation(t,r){const n=this.getAxisMotionValue(t);return NNe(this.visualElement,t),n.start(z5e(t,n,0,r,this.visualElement,!1))}stopAnimation(){Ob(t=>this.getAxisMotionValue(t).stop())}getAxisMotionValue(t){const r=`_drag${t.toUpperCase()}`,n=this.visualElement.getProps(),a=n[r];return a||this.visualElement.getValue(t,(n.initial?n.initial[t]:void 0)||0)}snapToCursor(t){Ob(r=>{const{drag:n}=this.getProps();if(!YU(r,n,this.currentDirection))return;const{projection:a}=this.visualElement,i=this.getAxisMotionValue(r);if(a&&a.layout){const{min:l,max:o}=a.layout.layoutBox[r],c=i.get()||0;i.set(t[r]-Sd(l,o,.5)+c)}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:t,dragConstraints:r}=this.getProps(),{projection:n}=this.visualElement;if(!z6(r)||!n||!this.constraints)return;this.stopAnimation();const a={x:0,y:0};Ob(l=>{const o=this.getAxisMotionValue(l);if(o&&this.constraints!==!1){const c=o.get();a[l]=lzt({min:c,max:c},this.constraints[l])}});const{transformTemplate:i}=this.visualElement.getProps();this.visualElement.current.style.transform=i?i({},""):"none",n.root&&n.root.updateScroll(),n.updateLayout(),this.constraints=!1,this.resolveConstraints(),Ob(l=>{if(!YU(l,t,null))return;const o=this.getAxisMotionValue(l),{min:c,max:d}=this.constraints[l];o.set(Sd(c,d,a[l]))}),this.visualElement.render()}addListeners(){if(!this.visualElement.current)return;uzt.set(this.visualElement,this);const t=this.visualElement.current,r=e7(t,"pointerdown",d=>{const{drag:h,dragListener:m=!0}=this.getProps(),p=d.target,x=p!==t&&H7t(p);h&&m&&!x&&this.start(d)});let n;const a=()=>{const{dragConstraints:d}=this.getProps();z6(d)&&d.current&&(this.constraints=this.resolveRefConstraints(),n||(n=mzt(t,d.current,()=>this.scalePositionWithinConstraints())))},{projection:i}=this.visualElement,l=i.addEventListener("measure",a);i&&!i.layout&&(i.root&&i.root.updateScroll(),i.updateLayout()),zc.read(a);const o=p9(window,"resize",()=>this.scalePositionWithinConstraints()),c=i.addEventListener("didUpdate",({delta:d,hasLayoutChanged:h})=>{this.isDragging&&h&&(Ob(m=>{const p=this.getAxisMotionValue(m);p&&(this.originPoint[m]+=d[m].translate,p.set(p.get()+d[m].translate))}),this.visualElement.render())});return()=>{o(),r(),l(),c&&c(),n&&n()}}getProps(){const t=this.visualElement.getProps(),{drag:r=!1,dragDirectionLock:n=!1,dragPropagation:a=!1,dragConstraints:i=!1,dragElastic:l=PNe,dragMomentum:o=!0}=t;return{...t,drag:r,dragDirectionLock:n,dragPropagation:a,dragConstraints:i,dragElastic:l,dragMomentum:o}}}function T7e(s){let t=!0;return()=>{if(t){t=!1;return}s()}}function mzt(s,t,r){const n=DFe(s,T7e(r)),a=DFe(t,T7e(r));return()=>{n(),a()}}function YU(s,t,r){return(t===!0||t===s)&&(r===null||r===s)}function fzt(s,t=10){let r=null;return Math.abs(s.y)>t?r="y":Math.abs(s.x)>t&&(r="x"),r}class pzt extends VS{constructor(t){super(t),this.removeGroupControls=Wy,this.removeListeners=Wy,this.controls=new hzt(t)}mount(){const{dragControls:t}=this.node.getProps();t&&(this.removeGroupControls=t.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||Wy}update(){const{dragControls:t}=this.node.getProps(),{dragControls:r}=this.node.prevProps||{};t!==r&&(this.removeGroupControls(),t&&(this.removeGroupControls=t.subscribe(this.controls)))}unmount(){this.removeGroupControls(),this.removeListeners(),this.controls.isDragging||this.controls.endPanSession()}}const _be=s=>(t,r)=>{s&&zc.update(()=>s(t,r),!1,!0)};class gzt extends VS{constructor(){super(...arguments),this.removePointerDownListener=Wy}onPointerDown(t){this.session=new Aat(t,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:Eat(this.node)})}createPanHandlers(){const{onPanSessionStart:t,onPanStart:r,onPan:n,onPanEnd:a}=this.node.getProps();return{onSessionStart:_be(t),onStart:_be(r),onMove:_be(n),onEnd:(i,l)=>{delete this.session,a&&zc.postRender(()=>a(i,l))}}}mount(){this.removePointerDownListener=e7(this.node.current,"pointerdown",t=>this.onPointerDown(t))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}}let wbe=!1;class xzt extends S.Component{componentDidMount(){const{visualElement:t,layoutGroup:r,switchLayoutGroup:n,layoutId:a}=this.props,{projection:i}=t;i&&(r.group&&r.group.add(i),n&&n.register&&a&&n.register(i),wbe&&i.root.didUpdate(),i.addEventListener("animationComplete",()=>{this.safeToRemove()}),i.setOptions({...i.options,layoutDependency:this.props.layoutDependency,onExitComplete:()=>this.safeToRemove()})),_ue.hasEverUpdated=!0}getSnapshotBeforeUpdate(t){const{layoutDependency:r,visualElement:n,drag:a,isPresent:i}=this.props,{projection:l}=n;return l&&(l.isPresent=i,t.layoutDependency!==r&&l.setOptions({...l.options,layoutDependency:r}),wbe=!0,a||t.layoutDependency!==r||r===void 0||t.isPresent!==i?l.willUpdate():this.safeToRemove(),t.isPresent!==i&&(i?l.promote():l.relegate()||zc.postRender(()=>{const o=l.getStack();(!o||!o.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{visualElement:t,layoutAnchor:r}=this.props,{projection:n}=t;n&&(n.options.layoutAnchor=r,n.root.didUpdate(),H5e.postRender(()=>{!n.currentAnimation&&n.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:t,layoutGroup:r,switchLayoutGroup:n}=this.props,{projection:a}=t;wbe=!0,a&&(a.scheduleCheckAfterUnmount(),r&&r.group&&r.group.remove(a),n&&n.deregister&&n.deregister(a))}safeToRemove(){const{safeToRemove:t}=this.props;t&&t()}render(){return null}}function Iat(s){const[t,r]=bat(),n=S.useContext(S5e);return e.jsx(xzt,{...s,layoutGroup:n,switchLayoutGroup:S.useContext(Cat),isPresent:t,safeToRemove:r})}const yzt={pan:{Feature:gzt},drag:{Feature:pzt,ProjectionNode:vat,MeasureLayout:Iat}};function E7e(s,t,r){const{props:n}=s;s.animationState&&n.whileHover&&s.animationState.setActive("whileHover",r==="Start");const a="onHover"+r,i=n[a];i&&zc.postRender(()=>i(t,rz(t)))}class vzt extends VS{mount(){const{current:t}=this.node;t&&(this.unmount=$7t(t,(r,n)=>(E7e(this.node,n,"Start"),a=>E7e(this.node,a,"End"))))}unmount(){}}class bzt extends VS{constructor(){super(...arguments),this.isActive=!1}onFocus(){let t=!1;try{t=this.node.current.matches(":focus-visible")}catch{t=!0}!t||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!0),this.isActive=!0)}onBlur(){!this.isActive||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!1),this.isActive=!1)}mount(){this.unmount=ez(p9(this.node.current,"focus",()=>this.onFocus()),p9(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function A7e(s,t,r){const{props:n}=s;if(s.current instanceof HTMLButtonElement&&s.current.disabled)return;s.animationState&&n.whileTap&&s.animationState.setActive("whileTap",r==="Start");const a="onTap"+(r==="End"?"":r),i=n[a];i&&zc.postRender(()=>i(t,rz(t)))}class _zt extends VS{mount(){const{current:t}=this.node;if(!t)return;const{globalTapTarget:r,propagate:n}=this.node.props;this.unmount=W7t(t,(a,i)=>(A7e(this.node,i,"Start"),(l,{success:o})=>A7e(this.node,l,o?"End":"Cancel")),{useGlobalTarget:r,stopPropagation:(n==null?void 0:n.tap)===!1})}unmount(){}}const LNe=new WeakMap,jbe=new WeakMap,wzt=s=>{const t=LNe.get(s.target);t&&t(s)},jzt=s=>{s.forEach(wzt)};function Nzt({root:s,...t}){const r=s||document;jbe.has(r)||jbe.set(r,{});const n=jbe.get(r),a=JSON.stringify(t);return n[a]||(n[a]=new IntersectionObserver(jzt,{root:s,...t})),n[a]}function kzt(s,t,r){const n=Nzt(t);return LNe.set(s,r),n.observe(s),()=>{LNe.delete(s),n.unobserve(s)}}const Szt={some:0,all:1};class Czt extends VS{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){var c;(c=this.stopObserver)==null||c.call(this);const{viewport:t={}}=this.node.getProps(),{root:r,margin:n,amount:a="some",once:i}=t,l={root:r?r.current:void 0,rootMargin:n,threshold:typeof a=="number"?a:Szt[a]},o=d=>{const{isIntersecting:h}=d;if(this.isInView===h||(this.isInView=h,i&&!h&&this.hasEnteredView))return;h&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",h);const{onViewportEnter:m,onViewportLeave:p}=this.node.getProps(),x=h?m:p;x&&x(d)};this.stopObserver=kzt(this.node.current,l,o)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>"u")return;const{props:t,prevProps:r}=this.node;["amount","margin","root"].some(Tzt(t,r))&&this.startObserver()}unmount(){var t;(t=this.stopObserver)==null||t.call(this),this.hasEnteredView=!1,this.isInView=!1}}function Tzt({viewport:s={}},{viewport:t={}}={}){return r=>s[r]!==t[r]}const Ezt={inView:{Feature:Czt},tap:{Feature:_zt},focus:{Feature:bzt},hover:{Feature:vzt}},Azt={layout:{ProjectionNode:vat,MeasureLayout:Iat}},Mzt={...ezt,...Ezt,...yzt,...Azt},Ur=YBt(Mzt,ZBt),Izt={some:0,all:1};function Pzt(s,t,{root:r,margin:n,amount:a="some"}={}){const i=V5e(s),l=new WeakMap,o=d=>{d.forEach(h=>{const m=l.get(h.target);if(h.isIntersecting!==!!m)if(h.isIntersecting){const p=t(h.target,h);typeof p=="function"?l.set(h.target,p):c.unobserve(h.target)}else typeof m=="function"&&(m(h),l.delete(h.target))})},c=new IntersectionObserver(o,{root:r,rootMargin:n,threshold:typeof a=="number"?a:Izt[a]});return i.forEach(d=>c.observe(d)),()=>c.disconnect()}function Lzt(s,{root:t,margin:r,amount:n,once:a=!1,initial:i=!1}={}){const[l,o]=S.useState(i);return S.useEffect(()=>{if(!s.current||a&&l)return;const c=()=>(o(!0),a?void 0:()=>o(!1)),d={root:t&&t.current||void 0,margin:r,amount:n};return Pzt(s.current,c,d)},[t,s,r,a,n]),l}function Dzt(s){switch(s){case"buying":return{label:"Buying",emoji:"🏠",color:"bg-emerald-500/15 text-emerald-400 border-emerald-500/30"};case"selling":return{label:"Selling",emoji:"📋",color:"bg-blue-500/15 text-blue-400 border-blue-500/30"};case"neighbor":return{label:"Neighbor",emoji:"👋",color:"bg-amber-500/15 text-amber-400 border-amber-500/30"};case"browsing":return{label:"Browsing",emoji:"👀",color:"bg-slate-500/15 text-slate-300 border-slate-500/30"};default:return{label:"Visitor",emoji:"🙂",color:"bg-slate-500/15 text-slate-300 border-slate-500/30"}}}function M7e(s){return s.visitor_intent==="buying"&&!s.has_agent}function Rzt({token:s}={}){var y;const t=Po(),r=s||t.token,{data:n,isLoading:a,isError:i}=bOt(r),l=ns(),o=(y=n==null?void 0:n.open_houses)==null?void 0:y.id,{data:c}=yt({queryKey:["cohost-visitors",o],queryFn:async()=>{const{data:_,error:b}=await V.from("open_house_visitors").select("*").eq("open_house_id",o).order("created_at",{ascending:!1});if(b)throw b;return _},enabled:!!o});if(S.useEffect(()=>{if(!o)return;const _=V.channel(`cohost-visitors-${o}`).on("postgres_changes",{event:"INSERT",schema:"public",table:"open_house_visitors",filter:`open_house_id=eq.${o}`},()=>{l.invalidateQueries({queryKey:["cohost-visitors",o]})}).subscribe();return()=>{V.removeChannel(_)}},[o,l]),a)return e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-950 via-slate-900 to-slate-950 flex items-center justify-center",children:e.jsx("div",{className:"animate-pulse text-white/40",children:"Validating access..."})});if(i||!n)return e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-950 via-slate-900 to-slate-950 flex items-center justify-center p-6",children:e.jsxs("div",{className:"text-center text-white",children:[e.jsx("h1",{className:"text-xl font-bold mb-2",children:"Link Expired or Invalid"}),e.jsx("p",{className:"text-white/40 text-sm",children:"This co-host link is no longer active. Ask the host for a new one."})]})});const d=n.open_houses,h=(c==null?void 0:c.length)||0,m=(c==null?void 0:c.filter(_=>_.visitor_intent==="buying").length)||0,p=(c==null?void 0:c.filter(M7e).length)||0,x=_=>{if(!_)return"";const[b,j]=_.split(":"),k=parseInt(b);return`${k>12?k-12:k||12}:${j} ${k>=12?"PM":"AM"}`};return e.jsxs("div",{className:"fixed inset-0 bg-gradient-to-br from-slate-950 via-slate-900 to-slate-950 flex flex-col",children:[e.jsxs("div",{className:"border-b border-white/10 px-4 sm:px-6 py-3 flex items-center justify-between bg-black/30 backdrop-blur-xl",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-emerald-400 animate-pulse"}),e.jsx("span",{className:"text-xs font-medium text-emerald-400 uppercase tracking-wider",children:"Live · Co-Host View"})]}),e.jsx("h1",{className:"text-white font-bold text-sm sm:text-base truncate",children:d.property_address})]}),e.jsxs("div",{className:"flex items-center gap-4 sm:gap-6 text-white/70",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Ar,{className:"h-4 w-4"}),e.jsx("span",{className:"font-bold text-white",children:h})]}),e.jsxs("div",{className:"flex items-center gap-1.5 text-orange-400",children:[e.jsx(od,{className:"h-4 w-4"}),e.jsx("span",{className:"font-bold text-white",children:p})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Fn,{className:"h-4 w-4"}),e.jsx("span",{className:"font-bold text-white",children:m})]})]})]}),e.jsxs("div",{className:"px-4 sm:px-6 py-2 flex items-center gap-4 text-xs text-white/40 border-b border-white/5",children:[e.jsx("span",{children:As(new Date(d.event_date+"T00:00:00"),"EEEE, MMMM d, yyyy")}),d.start_time&&e.jsxs("span",{children:[x(d.start_time),d.end_time?` – ${x(d.end_time)}`:""]})]}),e.jsx(Ci,{className:"flex-1 p-4 sm:p-6",children:c!=null&&c.length?e.jsx("div",{className:"space-y-2 max-w-3xl mx-auto",children:e.jsx(J5e,{children:c.map((_,b)=>{var T;const j=Dzt(_.visitor_intent),k=M7e(_);return e.jsxs(Ur.div,{initial:{opacity:0,x:-40,scale:.95},animate:{opacity:1,x:0,scale:1},transition:{duration:.4,delay:b*.05},className:`flex items-center gap-4 p-4 rounded-xl border ${k?"bg-orange-500/10 border-orange-500/30":"bg-white/5 border-white/10"}`,children:[e.jsx("div",{className:`w-11 h-11 rounded-full flex items-center justify-center text-lg font-bold shrink-0 ${k?"bg-gradient-to-br from-orange-500 to-amber-500 text-white":"bg-white/10 text-white/80"}`,children:(T=_.first_name[0])==null?void 0:T.toUpperCase()}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs("span",{className:"font-semibold text-white truncate",children:[_.first_name," ",_.last_name||""]}),k&&e.jsx(Xe,{className:"bg-orange-500/20 text-orange-300 border-orange-500/40 text-[10px] px-1.5 py-0",children:"🔥 HOT"}),_.has_agent&&e.jsx(Xe,{variant:"outline",className:"text-[10px] px-1.5 py-0 border-yellow-500/40 text-yellow-400",children:"⚠️ Has Agent"})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[e.jsxs(Xe,{variant:"outline",className:`text-[10px] px-1.5 py-0 ${j.color}`,children:[j.emoji," ",j.label]}),e.jsx("span",{className:"text-white/30 text-xs",children:As(new Date(_.created_at),"h:mm a")})]})]})]},_.id)})})}):e.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-center py-20",children:[e.jsx("div",{className:"w-20 h-20 rounded-full bg-white/5 flex items-center justify-center mb-4",children:e.jsx(G2,{className:"h-10 w-10 text-white/20"})}),e.jsx("h2",{className:"text-xl font-bold text-white/60 mb-1",children:"Waiting for visitors..."}),e.jsx("p",{className:"text-white/30 text-sm",children:"New sign-ins will appear here in real-time"})]})})]})}function Ozt(){const t=Vc().pathname.slice(1);if(S.useEffect(()=>(document.body.classList.add("guestbook-page"),()=>{document.body.classList.remove("guestbook-page")}),[]),t.startsWith("live/")){const r=t.slice(5);if(r)return e.jsx(Rzt,{token:r})}return!t||t===""?e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900 flex items-center justify-center p-6",children:e.jsxs("div",{className:"text-center text-white",children:[e.jsx("h1",{className:"text-2xl font-bold mb-2",children:"Guest Book"}),e.jsx("p",{className:"text-white/60",children:"The modern open house sign-in experience."}),e.jsx("p",{className:"text-white/40 text-sm mt-2",children:"Visit a specific open house link to sign in."})]})}):e.jsx(Lrt,{slug:t})}const Fzt="#2a4c64",Bzt="#406E71";function zzt({dealData:s,agentProfile:t,welcomeMessage:r,isWon:n,branding:a}){var y;const i=s!=null&&s.property_address?`${s.property_address}, ${s.city||""}, ${s.state||""}`.replace(/,\s*,/g,",").replace(/,\s*$/,""):null,l=(a==null?void 0:a.brand_color)||Fzt,o=(a==null?void 0:a.accent_color)||Bzt,c=(a==null?void 0:a.logo_url)||null,d=(a==null?void 0:a.cover_photo_url)||null,h=(a==null?void 0:a.tagline)||"Your Real Estate Agent",m=d?{backgroundImage:`linear-gradient(135deg, ${l}d9 0%, ${l}b3 50%, ${o}d9 100%), url(${d})`,backgroundSize:"cover",backgroundPosition:"center"}:{background:`linear-gradient(135deg, ${l} 0%, ${l} 30%, ${o} 100%)`},p="flex items-center gap-2 px-4 py-2.5 rounded-xl transition-colors",x={backgroundColor:`${l}1a`,color:l};return e.jsxs("div",{className:"relative overflow-hidden",children:[e.jsxs("div",{className:"relative text-white px-4 pt-10 pb-16",style:m,children:[!d&&e.jsx("div",{className:"absolute inset-0 opacity-[0.04]",style:{backgroundImage:"radial-gradient(circle at 25% 25%, white 1px, transparent 1px)",backgroundSize:"24px 24px"}}),e.jsxs("div",{className:"relative text-center max-w-lg mx-auto",children:[c&&e.jsx("div",{className:"mb-4 flex justify-center",children:e.jsx("div",{className:"bg-white/95 backdrop-blur-sm rounded-2xl px-4 py-2.5 shadow-lg",children:e.jsx("img",{src:c,alt:"Brand logo",className:"h-9 max-w-[160px] object-contain"})})}),t&&e.jsxs("div",{className:"mb-6",children:[t.avatar_url?e.jsx("img",{src:t.avatar_url,alt:t.name,className:"w-20 h-20 rounded-full border-[3px] border-white/30 shadow-xl mx-auto mb-3 object-cover"}):e.jsx("div",{className:"w-20 h-20 rounded-full border-[3px] border-white/30 shadow-xl mx-auto mb-3 bg-white/10 flex items-center justify-center",children:e.jsx("span",{className:"text-2xl font-bold text-white/70",children:((y=t.name)==null?void 0:y.charAt(0))||"?"})}),e.jsx("p",{className:"text-sm font-medium text-white/95",children:t.name}),e.jsx("p",{className:"text-xs text-white/60 mt-0.5",children:h})]}),e.jsxs("div",{className:"inline-flex items-center gap-1.5 bg-white/10 backdrop-blur-sm rounded-full px-3 py-1 text-xs font-medium text-white/80 mb-3",children:[e.jsx(Fn,{className:"w-3 h-3"}),(s==null?void 0:s.deal_type)==="listing"?"Listing":(s==null?void 0:s.deal_type)==="buy-side"?"Purchase":"Transaction"]}),e.jsx("h1",{className:"text-2xl font-bold tracking-tight mb-1.5 font-serif",children:(s==null?void 0:s.deal_name)||"Your Transaction Portal"}),i&&e.jsxs("div",{className:"flex items-center justify-center gap-1 text-white/70 text-sm",children:[e.jsx(Qa,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:i})]}),r&&e.jsx("p",{className:"mt-4 text-sm text-white/80 leading-relaxed max-w-sm mx-auto",children:r})]})]}),t&&e.jsx("div",{className:"max-w-lg mx-auto px-4 -mt-8 relative z-10",children:e.jsx("div",{className:"bg-white rounded-2xl shadow-lg border border-slate-100 p-4",children:e.jsxs("div",{className:"flex items-center justify-center gap-3",children:[t.phone&&e.jsxs("a",{href:`tel:${t.phone}`,className:p,style:x,children:[e.jsx(Yn,{className:"w-4 h-4"}),e.jsx("span",{className:"text-sm font-medium",children:"Call"})]}),t.email&&e.jsxs("a",{href:`mailto:${t.email}`,className:p,style:x,children:[e.jsx(er,{className:"w-4 h-4"}),e.jsx("span",{className:"text-sm font-medium",children:"Email"})]}),t.phone&&e.jsxs("a",{href:`sms:${t.phone}`,className:p,style:x,children:[e.jsx(qc,{className:"w-4 h-4"}),e.jsx("span",{className:"text-sm font-medium",children:"Text"})]})]})})})]})}function Pat({targetCloseDate:s,actualCloseDate:t,clientName:r}){if(t||!s)return null;const n=s.split(/[-/T]/),a=new Date(Number(n[0]),Number(n[1])-1,Number(n[2])),i=new Date,l=Jy(a,i);if(f8t(a,i),__(a)&&!cm(a))return null;let o="from-blue-500 to-cyan-400",c="from-blue-50 to-cyan-50",d="text-blue-900",h="text-blue-600",m="🏡";l<=3?(o="from-emerald-500 to-teal-400",c="from-emerald-50 to-teal-50",d="text-emerald-900",h="text-emerald-600",m="🎉"):l<=7?(o="from-amber-500 to-orange-400",c="from-amber-50 to-orange-50",d="text-amber-900",h="text-amber-600",m="⏳"):l<=14&&(o="from-violet-500 to-purple-400",c="from-violet-50 to-purple-50",d="text-violet-900",h="text-violet-600",m="📅");const p=cm(a)?"Today!":l===1?"1":String(l),x=cm(a)?"Closing Day":l===1?"day until closing":"days until closing";return e.jsxs("div",{className:`bg-gradient-to-br ${c} rounded-2xl p-6 border border-white/60 shadow-sm text-center`,children:[e.jsx("span",{className:"text-3xl mb-2 block",children:m}),cm(a)?e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:`text-2xl font-bold ${d}`,children:"It's Closing Day!"}),e.jsxs("p",{className:`text-sm ${h} mt-1`,children:["Congratulations",r?`, ${r.split(" ")[0]}`:"","! 🎊"]})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex items-baseline justify-center gap-1.5",children:e.jsx("span",{className:`text-5xl font-bold ${d} tabular-nums leading-none`,children:p})}),e.jsx("p",{className:`text-sm font-medium ${h} mt-1.5`,children:x}),l<=7&&e.jsxs("p",{className:`text-xs ${h} opacity-70 mt-1`,children:["You're almost there",r?`, ${r.split(" ")[0]}`:"","!"]})]}),!cm(a)&&l<=30&&e.jsx("div",{className:"mt-4 mx-auto w-full max-w-[200px]",children:e.jsx("div",{className:"h-2 rounded-full bg-white/60 overflow-hidden",children:e.jsx("div",{className:`h-full rounded-full bg-gradient-to-r ${o} transition-all duration-1000`,style:{width:`${Math.max(5,Math.min(100,(30-l)/30*100))}%`}})})})]})}function Lat({journeyStages:s,currentIndex:t}){return s.length===0?null:e.jsxs("div",{className:"bg-white rounded-2xl p-5 shadow-sm border border-slate-100",children:[e.jsx("h2",{className:"text-base font-semibold text-slate-800 mb-1",children:"Your Home Journey"}),e.jsx("p",{className:"text-xs text-slate-400 mb-5",children:"Follow along as your transaction progresses"}),e.jsx("div",{className:"relative",children:s.map((r,n)=>{const a=nt;return e.jsxs("div",{className:"flex items-start gap-3.5 relative",children:[n{var l,o;if(i.includes("youtube.com/watch")){const c=new URL(i).searchParams.get("v");return c?`https://www.youtube.com/embed/${c}`:null}if(i.includes("youtu.be/")){const c=(l=i.split("youtu.be/")[1])==null?void 0:l.split("?")[0];return c?`https://www.youtube.com/embed/${c}`:null}if(i.includes("loom.com/share/")){const c=(o=i.split("loom.com/share/")[1])==null?void 0:o.split("?")[0];return c?`https://www.loom.com/embed/${c}`:null}return i};return e.jsxs("div",{className:"bg-gradient-to-br from-[#406E71]/5 via-white to-[#406E71]/5 rounded-2xl border border-[#406E71]/15 overflow-hidden",children:[e.jsx("div",{className:"bg-[#406E71] px-5 py-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(bi,{className:"w-4 h-4 text-white/80"}),e.jsx("h3",{className:"text-sm font-semibold text-white",children:"Current Stage"})]})}),e.jsxs("div",{className:"p-5 space-y-4",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"text-lg font-bold text-slate-800",children:s.label}),e.jsx("p",{className:"text-sm text-slate-500 mt-1 leading-relaxed",children:s.description})]}),t&&e.jsxs("div",{className:"bg-slate-50 rounded-xl p-4 border border-slate-100",children:[e.jsx("p",{className:"text-xs font-semibold text-slate-500 uppercase tracking-wider mb-1.5",children:"Update from your agent"}),e.jsx("p",{className:"text-sm text-slate-700 leading-relaxed",children:t})]}),r&&e.jsxs("div",{className:"bg-blue-50/60 rounded-xl p-4 border border-blue-100",children:[e.jsx("p",{className:"text-xs font-semibold text-blue-600 uppercase tracking-wider mb-1.5",children:"What's Next"}),e.jsx("p",{className:"text-sm text-blue-800 leading-relaxed",children:r})]}),n&&e.jsx("div",{className:"rounded-xl overflow-hidden bg-slate-900 aspect-video shadow-md",children:e.jsx("iframe",{src:a(n)||n,className:"w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,title:"Next step video"})})]})]})}function Tc(s){const t=s.split(/[-/T]/);if(t.length>=3){const r=Number(t[0]);return r>99?new Date(r,Number(t[1])-1,Number(t[2])):new Date(Number(t[2]),Number(t[0])-1,Number(t[1]))}return new Date(`${s}T12:00:00`)}function $zt(s,t){const r=As(t,"yyyyMMdd");return`https://calendar.google.com/calendar/render?${new URLSearchParams({action:"TEMPLATE",text:s,dates:`${r}/${r}`,details:"Added from your Client Portal"}).toString()}`}function Uzt(s,t){const r=As(t,"yyyyMMdd");return`data:text/calendar;charset=utf-8,${encodeURIComponent(`BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT DTSTART;VALUE=DATE:${r} DTEND;VALUE=DATE:${r} SUMMARY:${s} DESCRIPTION:Added from your Client Portal END:VEVENT END:VCALENDAR`)}`}function Rat({targetCloseDate:s,contractDate:t,inspectionDate:r,appraisalDate:n,actualCloseDate:a}){const i=[{label:"Contract Date",date:t,icon:PI,color:"text-blue-600 bg-blue-50"},{label:"Inspection",date:r,icon:Mn,color:"text-amber-600 bg-amber-50"},{label:"Appraisal",date:n,icon:Fn,color:"text-purple-600 bg-purple-50"},{label:a?"Closed":"Target Close",date:a||s,icon:Nn,color:"text-emerald-600 bg-emerald-50"}].filter(o=>o.date);if(i.length===0)return null;const l=(o,c,d)=>{const h=Tc(c);if(d==="google")window.open($zt(o,h),"_blank");else{const m=Uzt(o,h),p=document.createElement("a");p.href=m,p.download=`${o.replace(/\s+/g,"-").toLowerCase()}.ics`,p.click()}};return e.jsxs("div",{className:"bg-white rounded-2xl p-5 shadow-sm border border-slate-100",children:[e.jsx("h2",{className:"text-sm font-semibold text-slate-800 mb-3",children:"Key Dates"}),e.jsx("div",{className:"space-y-3",children:i.map(({label:o,date:c,icon:d,color:h})=>{const m=Tc(c),p=__(m)&&!cm(m),x=cm(m),y=!p&&!x;return e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:`w-8 h-8 rounded-lg flex items-center justify-center ${h}`,children:e.jsx(d,{className:"w-4 h-4"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-xs text-slate-500",children:o}),e.jsxs("p",{className:`text-sm font-medium ${x?"text-emerald-600":p?"text-slate-400":"text-slate-800"}`,children:[As(m,"MMM d, yyyy"),x&&e.jsx("span",{className:"ml-1.5 text-xs bg-emerald-100 text-emerald-700 px-1.5 py-0.5 rounded-full",children:"Today"})]})]}),p&&e.jsx("span",{className:"text-xs text-slate-400",children:"✓"}),y&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("button",{onClick:()=>l(o,c,"google"),className:"text-xs text-slate-400 hover:text-blue-500 transition-colors px-1.5 py-1 rounded hover:bg-blue-50",title:"Add to Google Calendar",children:e.jsx(A2,{className:"w-3.5 h-3.5"})}),e.jsx("button",{onClick:()=>l(o,c,"apple"),className:"text-[10px] text-slate-400 hover:text-slate-600 transition-colors px-1.5 py-1 rounded hover:bg-slate-100",title:"Download .ics file",children:".ics"})]})]},o)})})]})}function Oat({documents:s}){const t=n=>n<1024?`${n} B`:n<1048576?`${(n/1024).toFixed(0)} KB`:`${(n/1048576).toFixed(1)} MB`,r=async n=>{const{data:a}=await V.storage.from("deal-files").createSignedUrl(n.storage_path,300);a!=null&&a.signedUrl&&window.open(a.signedUrl,"_blank")};return e.jsxs("div",{className:"bg-white rounded-2xl p-5 shadow-sm border border-slate-100",children:[e.jsx("h2",{className:"text-sm font-semibold text-slate-800 mb-3",children:"Documents"}),e.jsx("div",{className:"space-y-2",children:s.map(n=>e.jsxs("button",{onClick:()=>r(n),className:"w-full flex items-center gap-3 p-3 rounded-xl hover:bg-slate-50 transition-colors text-left group",children:[e.jsx("div",{className:"w-9 h-9 rounded-lg bg-slate-100 flex items-center justify-center flex-shrink-0 group-hover:bg-blue-50 transition-colors",children:e.jsx(kn,{className:"w-4 h-4 text-slate-500 group-hover:text-blue-600"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-slate-700 truncate",children:n.file_name}),e.jsx("p",{className:"text-xs text-slate-400",children:t(n.file_size)})]}),e.jsx(hi,{className:"w-4 h-4 text-slate-300 group-hover:text-blue-500 transition-colors"})]},n.id))})]})}function Fat({updates:s}){const t=r=>{var n,a;if(r.includes("youtube.com/watch")){const i=new URL(r).searchParams.get("v");return i?`https://www.youtube.com/embed/${i}`:null}if(r.includes("youtu.be/")){const i=(n=r.split("youtu.be/")[1])==null?void 0:n.split("?")[0];return i?`https://www.youtube.com/embed/${i}`:null}if(r.includes("loom.com/share/")){const i=(a=r.split("loom.com/share/")[1])==null?void 0:a.split("?")[0];return i?`https://www.loom.com/embed/${i}`:null}return r};return e.jsxs("div",{className:"bg-white rounded-2xl p-5 shadow-sm border border-slate-100",children:[e.jsx("h2",{className:"text-sm font-semibold text-slate-800 mb-4",children:"Updates from Your Agent"}),e.jsx("div",{className:"space-y-4",children:s.map((r,n)=>e.jsx("div",{className:`${n>0?"pt-4 border-t border-slate-100":""}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:`w-7 h-7 rounded-full flex items-center justify-center flex-shrink-0 ${r.is_stage_change?"bg-emerald-100":"bg-blue-100"}`,children:r.is_stage_change?e.jsx(qu,{className:"w-3.5 h-3.5 text-emerald-600"}):e.jsx(wp,{className:"w-3.5 h-3.5 text-blue-600"})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-baseline justify-between gap-2",children:[e.jsx("h3",{className:"text-sm font-medium text-slate-800",children:r.title}),e.jsx("span",{className:"text-xs text-slate-400 flex-shrink-0",children:As(new Date(r.created_at),"MMM d")})]}),r.content&&e.jsx("p",{className:"text-sm text-slate-500 mt-1 leading-relaxed",children:r.content}),r.video_url&&e.jsx("div",{className:"mt-3 rounded-xl overflow-hidden bg-slate-900 aspect-video",children:e.jsx("iframe",{src:t(r.video_url)||r.video_url,className:"w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,title:r.title})})]})]})},r.id))})]})}const nz=[{value:"lender",label:"Lender"},{value:"inspector",label:"Inspector"},{value:"title_escrow",label:"Title / Escrow"},{value:"insurance",label:"Insurance"},{value:"home_warranty",label:"Home Warranty"},{value:"movers",label:"Movers"},{value:"cleaners",label:"Cleaners"},{value:"handyman",label:"Handyman"},{value:"painter",label:"Painter"},{value:"landscaper",label:"Landscaper"},{value:"photographer",label:"Photographer"},{value:"stager",label:"Stager"},{value:"contractor",label:"Contractor"},{value:"electrician",label:"Electrician"},{value:"plumber",label:"Plumber"},{value:"hvac",label:"HVAC"},{value:"roofer",label:"Roofer"},{value:"pest_control",label:"Pest Control"},{value:"attorney",label:"Attorney"},{value:"accountant",label:"Accountant"},{value:"other",label:"Other"}],qzt=[{value:"book",label:"Book Now (link)"},{value:"quote",label:"Request Quote (email)"},{value:"call",label:"Call"},{value:"email",label:"Email"},{value:"website",label:"Visit Website"}];function Vzt(s){return yt({queryKey:["vendors","brokerage",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await V.from("vendors").select("*").eq("owner_type","brokerage").eq("owner_brokerage_id",s).order("sort_order",{ascending:!0}).order("name",{ascending:!0});if(r)throw r;return t||[]},enabled:!!s})}function Hzt(){const s=ba(),{brokerageId:t}=Ms();return yt({queryKey:["vendors","library",s,t],queryFn:async()=>{if(!s)return{vendors:[],selections:[]};let r=V.from("vendors").select("*");t?r=r.or(`and(owner_type.eq.agent,owner_user_id.eq.${s}),and(owner_type.eq.brokerage,owner_brokerage_id.eq.${t})`):r=r.eq("owner_type","agent").eq("owner_user_id",s);const[{data:n,error:a},{data:i,error:l}]=await Promise.all([r.order("sort_order",{ascending:!0}).order("name",{ascending:!0}),V.from("agent_vendor_selections").select("*").eq("agent_user_id",s)]);if(a)throw a;if(l)throw l;return{vendors:n||[],selections:i||[]}},enabled:!!s})}function Gzt(){const s=ns();return Pt({mutationFn:async t=>{if(t.id){const{id:r,created_at:n,...a}=t,{data:i,error:l}=await V.from("vendors").update(a).eq("id",r).select().single();if(l)throw l;return i}else{const{data:r,error:n}=await V.from("vendors").insert(t).select().single();if(n)throw n;return r}},onSuccess:()=>s.invalidateQueries({queryKey:["vendors"]})})}function Bat(){const s=ns();return Pt({mutationFn:async t=>{const{error:r}=await V.from("vendors").delete().eq("id",t);if(r)throw r},onSuccess:()=>s.invalidateQueries({queryKey:["vendors"]})})}function Wzt(){const s=ba(),t=ns();return Pt({mutationFn:async({vendorId:r,isVisible:n})=>{if(!s)throw new Error("No user");const{data:a}=await V.from("agent_vendor_selections").select("id").eq("agent_user_id",s).eq("vendor_id",r).maybeSingle();if(a){const{error:i}=await V.from("agent_vendor_selections").update({is_visible:n}).eq("id",a.id);if(i)throw i}else{const{error:i}=await V.from("agent_vendor_selections").insert({agent_user_id:s,vendor_id:r,is_visible:n});if(i)throw i}},onSuccess:()=>t.invalidateQueries({queryKey:["vendors"]})})}function Kzt(s){return yt({queryKey:["portal-vendors",s==null?void 0:s.id,s==null?void 0:s.owner_user_id],queryFn:async()=>{if(!(s!=null&&s.id)||!(s!=null&&s.owner_user_id))return[];const[{data:t},{data:r}]=await Promise.all([V.from("agent_vendor_selections").select("vendor_id, display_order, stage_filter, is_visible, vendors:vendors!inner(*)").eq("agent_user_id",s.owner_user_id).eq("is_visible",!0),V.from("portal_vendor_overrides").select("vendor_id, is_visible").eq("portal_id",s.id)]),n=new Map;return(r||[]).forEach(i=>n.set(i.vendor_id,i.is_visible)),(t||[]).map(i=>({...i.vendors,display_order:i.display_order})).filter(i=>i.is_active&&n.get(i.id)!==!1).sort((i,l)=>(i.display_order||0)-(l.display_order||0))},enabled:!!(s!=null&&s.id)&&!!(s!=null&&s.owner_user_id)})}async function Yzt(s){try{await V.from("vendor_clicks").insert({vendor_id:s.vendorId,portal_id:s.portalId||null,agent_user_id:s.agentUserId||null,action_taken:s.actionTaken||null,user_agent:typeof navigator<"u"?navigator.userAgent.slice(0,500):null})}catch(t){console.warn("vendor click track failed",t)}}function zat(s,t){return yt({queryKey:["vendor-clicks",s,t],queryFn:async()=>{if(!t)return{};const{data:r}=await V.from("vendors").select("id").eq(s==="agent"?"owner_user_id":"owner_brokerage_id",t).eq("owner_type",s),n=(r||[]).map(l=>l.id);if(n.length===0)return{};const{data:a}=await V.from("vendor_clicks").select("vendor_id").in("vendor_id",n),i={};return(a||[]).forEach(l=>{i[l.vendor_id]=(i[l.vendor_id]||0)+1}),i},enabled:!!t})}function $at({portalId:s,ownerUserId:t,currentStage:r,brandingColor:n}){const{data:a=[],isLoading:i}=Kzt({id:s,owner_user_id:t});if(i||a.length===0)return null;const l=a.filter(p=>!p.stage_filter||p.stage_filter.length===0||!r?!0:p.stage_filter.includes(r));if(l.length===0)return null;const o=l.reduce((p,x)=>((p[x.category]=p[x.category]||[]).push(x),p),{}),c=n||"#406E71",d=p=>{let x=p.action_type,y=null;switch(p.action_type){case"book":y=p.booking_url;break;case"website":y=p.website;break;case"call":y=p.phone?`tel:${p.phone.replace(/[^\d+]/g,"")}`:null;break;case"email":case"quote":y=p.email?`mailto:${p.email}`:null;break}Yzt({vendorId:p.id,portalId:s,agentUserId:t,actionTaken:x}),y&&window.open(y,p.action_type==="call"||p.action_type==="email"||p.action_type==="quote"?"_self":"_blank")},h=p=>{switch(p.action_type){case"book":return"Book Now";case"quote":return"Request Quote";case"call":return"Call";case"email":return"Email";case"website":return"Visit Site"}},m=p=>{switch(p.action_type){case"book":return e.jsx(Nn,{className:"w-3.5 h-3.5"});case"call":return e.jsx(Yn,{className:"w-3.5 h-3.5"});case"email":case"quote":return e.jsx(er,{className:"w-3.5 h-3.5"});case"website":return e.jsx(ld,{className:"w-3.5 h-3.5"})}};return e.jsxs(ke,{className:"p-5 rounded-2xl border-slate-200/80 shadow-sm",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx("div",{className:"w-8 h-8 rounded-lg flex items-center justify-center",style:{backgroundColor:`${c}15`,color:c},children:e.jsx(Lr,{className:"w-4 h-4"})}),e.jsxs("div",{children:[e.jsx("h2",{className:"font-semibold text-slate-800",children:"Trusted Partners"}),e.jsx("p",{className:"text-xs text-slate-500",children:"My personally-vetted recommendations for you"})]})]}),e.jsx("div",{className:"space-y-4",children:Object.entries(o).map(([p,x])=>{var _;const y=((_=nz.find(b=>b.value===p))==null?void 0:_.label)||p;return e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-slate-400 font-medium mb-2",children:y}),e.jsx("div",{className:"space-y-2",children:x.map(b=>e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-xl bg-slate-50 hover:bg-slate-100 transition-colors",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-white border border-slate-200 flex items-center justify-center overflow-hidden shrink-0",children:b.logo_url?e.jsx("img",{src:b.logo_url,alt:b.name,className:"w-full h-full object-cover"}):e.jsx("span",{className:"text-sm font-semibold text-slate-500",children:b.name.charAt(0)})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm text-slate-800 truncate",children:b.company||b.name}),b.company&&b.name&&e.jsx("p",{className:"text-xs text-slate-500 truncate",children:b.name}),b.description&&e.jsx("p",{className:"text-xs text-slate-500 truncate mt-0.5",children:b.description})]}),e.jsxs(H,{size:"sm",onClick:()=>d(b),style:{backgroundColor:c},className:"text-white hover:opacity-90 shrink-0",children:[m(b),e.jsx("span",{className:"ml-1.5 text-xs",children:h(b)})]})]},b.id))})]},p)})}),l.some(p=>p.disclosure_text)&&e.jsx("div",{className:"mt-4 pt-3 border-t border-slate-100 space-y-1",children:l.filter(p=>p.disclosure_text).map(p=>e.jsxs("p",{className:"text-[10px] text-slate-400",children:[e.jsxs("span",{className:"font-medium",children:[p.company||p.name,":"]})," ",p.disclosure_text]},p.id))})]})}function Zzt(s){const t=window.location.hostname;return t==="localhost"||t.includes("lovable.app")?`${window.location.origin}/portal/${s}/refer`:`https://clients.relevelup.com/${s}/refer`}function Xzt(s){if(!s)return null;const t=s.match(/(?:youtube\.com\/(?:watch\?v=|embed\/)|youtu\.be\/)([\w-]+)/);if(t)return`https://www.youtube.com/embed/${t[1]}`;const r=s.match(/loom\.com\/share\/([\w-]+)/);return r?`https://www.loom.com/embed/${r[1]}`:(s.match(/\.(mp4|webm|mov)(\?|$)/i),s)}function Uat({portalId:s,portalSlug:t,ownerUserId:r,rewardText:n,ctaHeadline:a,agentName:i,clientName:l,reviewUrl:o,hubVideoUrl:c}){const[d,h]=S.useState(!1),m=S.useRef(!1),p=Zzt(t);S.useEffect(()=>{m.current||(m.current=!0,V.from("portal_referral_clicks").insert({portal_id:s,owner_user_id:r,click_type:"card_view",user_agent:navigator.userAgent.slice(0,500)}).then(()=>{}))},[s,r]);const x=async D=>{await V.from("portal_referral_clicks").insert({portal_id:s,owner_user_id:r,click_type:D,user_agent:navigator.userAgent.slice(0,500)})},y=()=>`${l?`Hey, it's ${l}!`:"Hey!"} I just had an amazing experience working with ${i||"my real estate agent"} on my home. If you or someone you know is thinking about buying or selling, here's their referral link: ${p}`,_=async()=>{await navigator.clipboard.writeText(p),h(!0),x("copy_link"),setTimeout(()=>h(!1),2e3)},b=()=>{x("share_sms");const D=encodeURIComponent(y());window.location.href=`sms:?&body=${D}`},j=()=>{x("share_email");const D=encodeURIComponent("A referral you'll thank me for"),R=encodeURIComponent(y());window.location.href=`mailto:?subject=${D}&body=${R}`},k=()=>{x("open_form"),window.open(p,"_blank")},T=a||"Know someone buying or selling?",E=c?Xzt(c):null,A=E==null?void 0:E.match(/\.(mp4|webm|mov)(\?|$)/i);return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"bg-gradient-to-br from-emerald-50 via-teal-50 to-cyan-50 rounded-2xl p-6 border border-emerald-100 text-center",children:[e.jsx("div",{className:"text-5xl mb-2",children:"🎉"}),e.jsxs("h3",{className:"text-xl font-bold text-emerald-900 mb-1 font-serif",children:["Welcome Home",l?`, ${l.split(" ")[0]}`:"","!"]}),e.jsx("p",{className:"text-sm text-emerald-700/80",children:"Your transaction is complete. We're so proud to have been part of your journey."})]}),E&&e.jsxs("div",{className:"bg-white rounded-2xl border border-slate-100 shadow-sm overflow-hidden",children:[e.jsx("div",{className:"px-4 pt-4 pb-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Lr,{className:"w-4 h-4 text-[#406E71]"}),e.jsxs("p",{className:"text-sm font-medium text-slate-700",children:["A message from ",i||"your agent"]})]})}),e.jsx("div",{className:"aspect-video bg-slate-900",children:A?e.jsx("video",{src:E,controls:!0,className:"w-full h-full",playsInline:!0}):e.jsx("iframe",{src:E,className:"w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})})]}),e.jsxs("div",{className:"relative overflow-hidden rounded-2xl bg-gradient-to-br from-[#2a4c64] via-[#345e7a] to-[#406E71] text-white shadow-xl",children:[e.jsx("div",{className:"absolute inset-0 opacity-[0.07]",style:{backgroundImage:"radial-gradient(circle at 25% 25%, white 1px, transparent 1px)",backgroundSize:"20px 20px"}}),e.jsxs("div",{className:"relative p-6",children:[e.jsxs("div",{className:"inline-flex items-center gap-1.5 bg-white/15 backdrop-blur-sm rounded-full px-3 py-1 text-xs font-medium mb-3",children:[e.jsx(Di,{className:"w-3 h-3"}),"Referral Program"]}),e.jsx("h3",{className:"text-xl font-bold leading-tight mb-2 font-serif",children:T}),n&&e.jsxs("p",{className:"text-sm text-white/85 mb-1",children:[e.jsx("span",{className:"font-semibold text-white",children:"Your reward:"})," ",n]}),e.jsxs("p",{className:"text-sm text-white/70 mb-5 leading-relaxed",children:["The biggest compliment you can give ",i||"us"," is sending a friend or family member."]}),e.jsxs("button",{onClick:k,className:"w-full bg-white text-[#2a4c64] font-semibold rounded-xl py-3.5 px-4 flex items-center justify-center gap-2 shadow-md hover:bg-white/95 active:scale-[0.99] transition-all",children:["Refer a Friend",e.jsx(bi,{className:"w-4 h-4"})]}),e.jsxs("div",{className:"mt-4 grid grid-cols-3 gap-2",children:[e.jsxs("button",{onClick:b,className:"flex items-center justify-center gap-1.5 bg-white/10 hover:bg-white/20 backdrop-blur-sm rounded-lg py-2.5 text-xs font-medium transition-colors",children:[e.jsx(qc,{className:"w-3.5 h-3.5"}),"Text"]}),e.jsxs("button",{onClick:j,className:"flex items-center justify-center gap-1.5 bg-white/10 hover:bg-white/20 backdrop-blur-sm rounded-lg py-2.5 text-xs font-medium transition-colors",children:[e.jsx(er,{className:"w-3.5 h-3.5"}),"Email"]}),e.jsxs("button",{onClick:_,className:"flex items-center justify-center gap-1.5 bg-white/10 hover:bg-white/20 backdrop-blur-sm rounded-lg py-2.5 text-xs font-medium transition-colors",children:[d?e.jsx(va,{className:"w-3.5 h-3.5"}):e.jsx(ui,{className:"w-3.5 h-3.5"}),d?"Copied":"Copy"]})]})]})]}),o&&e.jsx("a",{href:o,target:"_blank",rel:"noopener noreferrer",onClick:()=>x("review_click"),className:"block bg-white border border-slate-200 hover:border-amber-300 hover:bg-amber-50/30 rounded-2xl p-4 transition-colors",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"text-2xl",children:"⭐"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm font-semibold text-slate-800",children:"Loved working together?"}),e.jsx("p",{className:"text-xs text-slate-500",children:"Leave a quick review — it means the world."})]}),e.jsx(bi,{className:"w-4 h-4 text-slate-400"})]})})]})}function Qzt(s){return s==="buy-side"?"Home Search in Progress":s==="listing"?"Your Home Is On The Market":"Active Phase"}function Jzt(s){return s==="buy-side"?"We're actively searching for homes that match your criteria.":s==="listing"?"Your property is now being marketed to potential buyers.":"Your transaction is actively moving forward."}const e$t={Lead:{label:"Getting Started",description:"We're beginning your home journey and preparing the next steps."},Consultation:{label:"Planning Your Move",description:"We're discussing your goals and building a plan for buying or selling."},"Agreement Signed":{label:"Officially Working Together",description:"We've signed the agreement and are moving forward together."},"Under Contract":{label:"Under Contract",description:"Your offer has been accepted and we are now moving through inspections and due diligence."},Closing:{label:"Final Steps to Closing",description:"We're finalizing documents and preparing for closing day."},"Closed Won":{label:"Closing Day",description:"Congratulations! Your transaction is complete. 🎉"}},qat=["Lead","Consultation","Agreement Signed","Active","Under Contract","Closing","Closed Won"];function Bge(s){return qat.map(t=>{if(t==="Active")return{key:"Active",label:Qzt(s),description:Jzt(s)};const r=e$t[t];return{key:t,label:r.label,description:r.description}})}function Zhe(s){if(!s)return 0;const t=qat.indexOf(s);return t>=0?t:0}const t$t="#2a4c64",s$t="#406E71";function r$t({portal:s,linkedPortal:t,activePortal:r,activeTab:n,onTabChange:a,agentProfile:i,branding:l,updates:o,documents:c}){var K,re,ie;const d=(l==null?void 0:l.brand_color)||t$t,h=(l==null?void 0:l.accent_color)||s$t,m=(l==null?void 0:l.cover_photo_url)||null,p=(l==null?void 0:l.logo_url)||null,x=(l==null?void 0:l.tagline)||"Your Real Estate Agent",y=r==null?void 0:r.deal_pipeline,_=y==null?void 0:y.deal_pipeline_stages,b=_==null?void 0:_.is_won_stage,j=y==null?void 0:y.deal_type,k=r==null?void 0:r.stage_mapping;let T=Bge(j);k&&k.length>0&&(T=k.map((ce,ne)=>{var le,be;return{key:`custom-${ne}`,label:ce.label||((le=T[ne])==null?void 0:le.label)||`Stage ${ne+1}`,description:ce.description||((be=T[ne])==null?void 0:be.description)||"",video_url:ce.video_url||void 0}}));const E=k&&k.length>0?Math.min(Zhe(_==null?void 0:_.name),T.length-1):Zhe(_==null?void 0:_.name),A=T[E],D=A==null?void 0:A.video_url,R=b&&r.show_post_close_tips!==!1&&r.referral_enabled!==!1,z=y!=null&&y.property_address?`${y.property_address}, ${y.city||""}, ${y.state||""}`.replace(/,\s*,/g,",").replace(/,\s*$/,""):null,O=!!t,$=(K=s==null?void 0:s.deal_pipeline)==null?void 0:K.deal_type,ee=(re=t==null?void 0:t.deal_pipeline)==null?void 0:re.deal_type,Z=ce=>ce==="listing"?"Your Sale":ce==="buy-side"?"Your Purchase":"Transaction",J=T.length>1?Math.round((E+1)/T.length*100):0;return e.jsxs("div",{className:"min-h-screen relative",style:{background:`radial-gradient(ellipse 80% 60% at 50% -10%, ${d}22, transparent 60%), linear-gradient(180deg, #f8fafc 0%, #ffffff 100%)`},children:[e.jsx("div",{className:"pointer-events-none absolute inset-x-0 top-0 h-[480px] opacity-50",style:{background:`radial-gradient(circle at 80% 0%, ${h}33, transparent 50%), radial-gradient(circle at 10% 10%, ${d}33, transparent 55%)`}}),e.jsxs("div",{className:"relative max-w-[1400px] mx-auto px-8 py-10",children:[e.jsxs("div",{className:"flex items-center justify-between mb-8",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[p?e.jsx("div",{className:"bg-white/80 backdrop-blur-sm rounded-xl px-3 py-1.5 shadow-sm border border-white",children:e.jsx("img",{src:p,alt:"Brand",className:"h-7 max-w-[140px] object-contain"})}):e.jsx("div",{className:"w-10 h-10 rounded-xl flex items-center justify-center text-white font-bold shadow-md",style:{background:`linear-gradient(135deg, ${d}, ${h})`},children:e.jsx(Lr,{className:"w-5 h-5"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs uppercase tracking-[0.18em] text-slate-400 font-semibold",children:"Client Portal"}),e.jsx("p",{className:"text-sm font-medium text-slate-700",children:r!=null&&r.client_name?`Welcome, ${r.client_name.split(" ")[0]}`:"Your transaction"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-slate-400",children:[e.jsx(Fh,{className:"w-3.5 h-3.5"}),"Secure portal"]})]}),e.jsxs(Ur.div,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},transition:{duration:.5,ease:"easeOut"},className:"relative overflow-hidden rounded-3xl shadow-2xl border border-white/60 mb-8",style:{minHeight:320},children:[e.jsx("div",{className:"absolute inset-0",style:m?{backgroundImage:`linear-gradient(135deg, ${d}e6 0%, ${d}b3 45%, ${h}cc 100%), url(${m})`,backgroundSize:"cover",backgroundPosition:"center"}:{background:`linear-gradient(135deg, ${d} 0%, ${h} 100%)`}}),e.jsx("div",{className:"absolute inset-0 opacity-[0.06]",style:{backgroundImage:"radial-gradient(circle at 25% 25%, white 1px, transparent 1px)",backgroundSize:"28px 28px"}}),e.jsxs("div",{className:"relative grid grid-cols-3 gap-8 p-10 text-white",children:[e.jsxs("div",{className:"col-span-2 flex flex-col justify-end",children:[e.jsxs("div",{className:"inline-flex items-center gap-1.5 bg-white/15 backdrop-blur-sm rounded-full px-3 py-1 text-xs font-medium text-white/90 mb-4 self-start",children:[e.jsx(Fn,{className:"w-3 h-3"}),j==="listing"?"Listing":j==="buy-side"?"Purchase":"Transaction",b&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"opacity-50 mx-1",children:"•"}),"Complete"]})]}),e.jsx("h1",{className:"text-5xl font-bold tracking-tight leading-[1.05] mb-3 font-serif",children:(y==null?void 0:y.deal_name)||"Your Transaction"}),z&&e.jsxs("div",{className:"flex items-center gap-1.5 text-white/80 text-base",children:[e.jsx(Qa,{className:"w-4 h-4"}),e.jsx("span",{children:z})]}),(r==null?void 0:r.welcome_message)&&e.jsx("p",{className:"mt-5 text-white/85 text-sm leading-relaxed max-w-2xl",children:r.welcome_message})]}),e.jsxs("div",{className:"flex flex-col items-center justify-center",children:[e.jsx(n$t,{pct:J,brand:d,accent:h}),e.jsx("p",{className:"text-xs uppercase tracking-widest text-white/70 mt-3",children:"Journey progress"}),e.jsxs("p",{className:"text-sm font-medium text-white/95 mt-1",children:["Stage ",E+1," of ",T.length]})]})]})]}),O&&e.jsx("div",{className:"inline-flex gap-1 bg-white/70 backdrop-blur border border-slate-200 rounded-xl p-1 mb-6 shadow-sm",children:["primary","linked"].map(ce=>{const ne=ce==="primary"?$:ee;return e.jsx("button",{onClick:()=>a(ce),className:`px-4 py-2 rounded-lg text-sm font-medium transition-all ${n===ce?"bg-white text-slate-800 shadow-sm":"text-slate-500 hover:text-slate-700"}`,children:Z(ne)},ce)})}),e.jsxs("div",{className:"grid grid-cols-12 gap-6",children:[e.jsx("aside",{className:"col-span-3",children:e.jsxs("div",{className:"sticky top-6 space-y-4",children:[e.jsxs(bN,{children:[e.jsxs("div",{className:"text-center pt-2",children:[i!=null&&i.avatar_url?e.jsx("img",{src:i.avatar_url,alt:i.name,className:"w-24 h-24 rounded-full mx-auto object-cover ring-4 ring-white shadow-lg"}):e.jsx("div",{className:"w-24 h-24 rounded-full mx-auto flex items-center justify-center text-3xl font-bold text-white ring-4 ring-white shadow-lg",style:{background:`linear-gradient(135deg, ${d}, ${h})`},children:((ie=i==null?void 0:i.name)==null?void 0:ie.charAt(0))||"?"}),e.jsx("h3",{className:"mt-4 text-lg font-bold text-slate-800",children:i==null?void 0:i.name}),e.jsx("p",{className:"text-xs text-slate-500 mt-0.5",children:x})]}),e.jsxs("div",{className:"mt-5 space-y-2",children:[(i==null?void 0:i.phone)&&e.jsx(Nbe,{href:`tel:${i.phone}`,icon:Yn,label:"Call",sub:i.phone,brand:d}),(i==null?void 0:i.phone)&&e.jsx(Nbe,{href:`sms:${i.phone}`,icon:qc,label:"Text message",brand:d}),(i==null?void 0:i.email)&&e.jsx(Nbe,{href:`mailto:${i.email}`,icon:er,label:"Email",sub:i.email,brand:d})]})]}),e.jsxs(bN,{children:[e.jsx("p",{className:"text-xs uppercase tracking-wider text-slate-400 font-semibold mb-3",children:"At a glance"}),e.jsxs("div",{className:"space-y-3",children:[(y==null?void 0:y.target_close_date)&&e.jsx(kbe,{icon:Nn,label:"Target close",value:I7e(y.target_close_date),brand:d}),(y==null?void 0:y.contract_date)&&e.jsx(kbe,{icon:Pn,label:"Under contract",value:I7e(y.contract_date),brand:d}),e.jsx(kbe,{icon:Lr,label:"Progress",value:`${J}%`,brand:d})]})]}),e.jsx("div",{className:"text-center pt-2 space-y-1",children:e.jsx("p",{className:"text-[11px] text-slate-400",children:"Powered by ReLevelUp"})})]})}),e.jsxs("main",{className:"col-span-6 space-y-6",children:[R&&e.jsx(Uat,{portalId:r.id,portalSlug:r.slug,ownerUserId:r.owner_user_id,rewardText:r.referral_reward_text,ctaHeadline:r.referral_cta_headline,agentName:i==null?void 0:i.name,clientName:r.client_name,reviewUrl:r.review_url,hubVideoUrl:r.homeowner_hub_video_url}),e.jsx(Pat,{targetCloseDate:y==null?void 0:y.target_close_date,actualCloseDate:y==null?void 0:y.actual_close_date,clientName:r.client_name}),A&&e.jsxs(bN,{children:[e.jsx("p",{className:"text-xs uppercase tracking-wider text-slate-400 font-semibold mb-3",children:"Where you are now"}),e.jsx(Dat,{currentStage:A,nextStepText:r.next_step_text,nextStepVideoUrl:D||r.next_step_video_url})]}),e.jsxs(bN,{children:[e.jsx("p",{className:"text-xs uppercase tracking-wider text-slate-400 font-semibold mb-4",children:"Your journey"}),e.jsx(Lat,{journeyStages:T,currentIndex:E})]}),o&&o.length>0&&e.jsx(bN,{children:e.jsx(Fat,{updates:o})})]}),e.jsxs("aside",{className:"col-span-3 space-y-6",children:[e.jsx(bN,{children:e.jsx(Rat,{targetCloseDate:y==null?void 0:y.target_close_date,contractDate:y==null?void 0:y.contract_date,inspectionDate:r.inspection_date,appraisalDate:r.appraisal_date,actualCloseDate:y==null?void 0:y.actual_close_date})}),c&&c.length>0&&e.jsx(bN,{children:e.jsx(Oat,{documents:c})}),(r==null?void 0:r.id)&&(r==null?void 0:r.owner_user_id)&&e.jsx(bN,{children:e.jsx($at,{portalId:r.id,ownerUserId:r.owner_user_id,currentStage:_==null?void 0:_.name})})]})]})]})]})}function bN({children:s}){return e.jsx("div",{className:"bg-white/80 backdrop-blur-xl rounded-2xl border border-white shadow-[0_8px_32px_-8px_rgba(15,23,42,0.08)] p-5",children:s})}function Nbe({href:s,icon:t,label:r,sub:n,brand:a}){return e.jsxs("a",{href:s,className:"flex items-center gap-3 rounded-xl px-3 py-2.5 transition-all hover:scale-[1.02] hover:shadow-sm border border-transparent hover:border-slate-100",style:{backgroundColor:`${a}0d`},children:[e.jsx("div",{className:"w-9 h-9 rounded-lg flex items-center justify-center shrink-0",style:{backgroundColor:`${a}1f`,color:a},children:e.jsx(t,{className:"w-4 h-4"})}),e.jsxs("div",{className:"min-w-0 text-left",children:[e.jsx("p",{className:"text-sm font-medium text-slate-800 leading-tight",children:r}),n&&e.jsx("p",{className:"text-xs text-slate-500 truncate",children:n})]})]})}function kbe({icon:s,label:t,value:r,brand:n}){return e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-8 h-8 rounded-lg flex items-center justify-center shrink-0",style:{backgroundColor:`${n}14`,color:n},children:e.jsx(s,{className:"w-4 h-4"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-[11px] text-slate-400 uppercase tracking-wide",children:t}),e.jsx("p",{className:"text-sm font-semibold text-slate-800 truncate",children:r})]})]})}function n$t({pct:s,brand:t,accent:r}){const l=2*Math.PI*74,o=l-s/100*l,c="pg-"+t.replace("#","");return e.jsxs("div",{className:"relative",style:{width:160,height:160},children:[e.jsxs("svg",{width:160,height:160,className:"-rotate-90",children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:c,x1:"0%",y1:"0%",x2:"100%",y2:"100%",children:[e.jsx("stop",{offset:"0%",stopColor:"#ffffff",stopOpacity:"0.95"}),e.jsx("stop",{offset:"100%",stopColor:r,stopOpacity:"0.9"})]})}),e.jsx("circle",{cx:160/2,cy:160/2,r:74,stroke:"rgba(255,255,255,0.18)",strokeWidth:12,fill:"none"}),e.jsx(Ur.circle,{cx:160/2,cy:160/2,r:74,stroke:`url(#${c})`,strokeWidth:12,strokeLinecap:"round",fill:"none",initial:{strokeDashoffset:l},animate:{strokeDashoffset:o},transition:{duration:1.2,ease:"easeOut"},strokeDasharray:l})]}),e.jsx("div",{className:"absolute inset-0 flex flex-col items-center justify-center",children:e.jsxs("span",{className:"text-4xl font-bold tabular-nums",children:[s,"%"]})})]})}function I7e(s){const t=s.split(/[-/T]/),r=new Date(Number(t[0]),Number(t[1])-1,Number(t[2]));return new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric",timeZone:"America/New_York"}).format(r)}function a$t({portal:s,dealData:t,agentProfile:r,customQuestions:n,deviceFingerprint:a,onComplete:i}){var y,_;const[l,o]=S.useState({first_name:((y=s.client_name)==null?void 0:y.split(" ")[0])||"",last_name:((_=s.client_name)==null?void 0:_.split(" ").slice(1).join(" "))||"",email:s.client_email||"",phone:s.client_phone||"",preferred_contact_method:"email",client_role:"buyer",notes:"",spouse_first_name:"",spouse_last_name:"",spouse_email:"",spouse_phone:""}),[c,d]=S.useState({}),[h,m]=S.useState(!1),p=Pt({mutationFn:async()=>{const{error:b}=await V.from("portal_onboarding_submissions").insert({portal_id:s.id,first_name:l.first_name,last_name:l.last_name||null,email:l.email||null,phone:l.phone||null,preferred_contact_method:l.preferred_contact_method,client_role:l.client_role,notes:l.notes||null,device_fingerprint:a,custom_answers:Object.keys(c).length>0?c:null,spouse_first_name:h&&l.spouse_first_name||null,spouse_last_name:h&&l.spouse_last_name||null,spouse_email:h&&l.spouse_email||null,spouse_phone:h&&l.spouse_phone||null});if(b)throw b},onSuccess:i,onError:b=>{console.error("[PortalOnboarding] Submit failed:",b),he.error("Something went wrong. Please try again.")}}),x=t!=null&&t.property_address?`${t.property_address}, ${t.city||""}, ${t.state||""}`:null;return e.jsxs("div",{className:"max-w-md mx-auto px-4 py-10",children:[e.jsxs("div",{className:"text-center mb-8",children:[(r==null?void 0:r.avatar_url)&&e.jsx("img",{src:r.avatar_url,alt:r.name,className:"w-14 h-14 rounded-full border-2 border-slate-200 mx-auto mb-3 object-cover"}),e.jsx("h1",{className:"text-xl font-bold text-slate-800",children:"Welcome to Your Portal"}),x&&e.jsxs("div",{className:"flex items-center justify-center gap-1 text-slate-500 text-sm mt-1",children:[e.jsx(Qa,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:x.replace(/,\s*,/g,",").replace(/,\s*$/,"")})]}),e.jsx("p",{className:"text-sm text-slate-500 mt-2",children:"Please fill in your details to access your transaction portal."})]}),e.jsxs("form",{onSubmit:b=>{b.preventDefault(),p.mutate()},className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs text-slate-600",children:"First Name *"}),e.jsx(Se,{required:!0,value:l.first_name,onChange:b=>o(j=>({...j,first_name:b.target.value})),className:"mt-1 rounded-xl",placeholder:"John"})]}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs text-slate-600",children:"Last Name"}),e.jsx(Se,{value:l.last_name,onChange:b=>o(j=>({...j,last_name:b.target.value})),className:"mt-1 rounded-xl",placeholder:"Doe"})]})]}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs text-slate-600",children:"Email"}),e.jsx(Se,{type:"email",value:l.email,onChange:b=>o(j=>({...j,email:b.target.value})),className:"mt-1 rounded-xl",placeholder:"john@example.com"})]}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs text-slate-600",children:"Phone"}),e.jsx(Se,{type:"tel",value:l.phone,onChange:b=>o(j=>({...j,phone:b.target.value})),className:"mt-1 rounded-xl",placeholder:"(555) 123-4567"})]}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs text-slate-600",children:"Preferred Contact Method"}),e.jsx("div",{className:"flex gap-2 mt-1.5",children:[{value:"email",label:"Email"},{value:"call",label:"Phone"},{value:"text",label:"Text"}].map(b=>e.jsx("button",{type:"button",onClick:()=>o(j=>({...j,preferred_contact_method:b.value})),className:`px-3.5 py-1.5 rounded-full text-xs font-medium border transition-colors ${l.preferred_contact_method===b.value?"bg-slate-800 text-white border-slate-800":"bg-white text-slate-600 border-slate-200 hover:border-slate-300"}`,children:b.label},b.value))})]}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs text-slate-600",children:"Your Role"}),e.jsx("div",{className:"flex gap-2 mt-1.5",children:["buyer","seller","both"].map(b=>e.jsx("button",{type:"button",onClick:()=>o(j=>({...j,client_role:b})),className:`px-3.5 py-1.5 rounded-full text-xs font-medium border transition-colors ${l.client_role===b?"bg-slate-800 text-white border-slate-800":"bg-white text-slate-600 border-slate-200 hover:border-slate-300"}`,children:b.charAt(0).toUpperCase()+b.slice(1)},b))})]}),n.map(b=>e.jsxs("div",{children:[e.jsxs(ue,{className:"text-xs text-slate-600",children:[b.question_text," ",b.is_required&&"*"]}),b.field_type==="text"&&e.jsx(Se,{required:b.is_required,value:c[b.id]||"",onChange:j=>d(k=>({...k,[b.id]:j.target.value})),className:"mt-1 rounded-xl"}),b.field_type==="textarea"&&e.jsx("textarea",{required:b.is_required,value:c[b.id]||"",onChange:j=>d(k=>({...k,[b.id]:j.target.value})),className:"mt-1 w-full rounded-xl border border-input bg-background px-3 py-2 text-sm min-h-[80px] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"}),b.field_type==="dropdown"&&e.jsxs("select",{required:b.is_required,value:c[b.id]||"",onChange:j=>d(k=>({...k,[b.id]:j.target.value})),className:"mt-1 w-full rounded-xl border border-input bg-background px-3 py-2 text-sm h-10",children:[e.jsx("option",{value:"",children:"Select..."}),(b.options||[]).map(j=>e.jsx("option",{value:j,children:j},j))]}),b.field_type==="toggle"&&e.jsx("div",{className:"mt-1.5 flex gap-2",children:["Yes","No"].map(j=>e.jsx("button",{type:"button",onClick:()=>d(k=>({...k,[b.id]:j})),className:`px-3.5 py-1.5 rounded-full text-xs font-medium border transition-colors ${c[b.id]===j?"bg-slate-800 text-white border-slate-800":"bg-white text-slate-600 border-slate-200"}`,children:j},j))})]},b.id)),e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs text-slate-600",children:"Notes for your agent"}),e.jsx("textarea",{value:l.notes,onChange:b=>o(j=>({...j,notes:b.target.value})),className:"mt-1 w-full rounded-xl border border-input bg-background px-3 py-2 text-sm min-h-[60px] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",placeholder:"Anything you'd like your agent to know..."})]}),s.allow_spouse&&e.jsxs("div",{children:[e.jsx("button",{type:"button",onClick:()=>m(!h),className:"text-sm text-blue-600 hover:text-blue-700 font-medium",children:h?"− Remove spouse/partner":"+ Add spouse/partner"}),h&&e.jsxs("div",{className:"mt-3 p-4 bg-slate-50 rounded-xl space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs text-slate-600",children:"First Name"}),e.jsx(Se,{value:l.spouse_first_name,onChange:b=>o(j=>({...j,spouse_first_name:b.target.value})),className:"mt-1 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs text-slate-600",children:"Last Name"}),e.jsx(Se,{value:l.spouse_last_name,onChange:b=>o(j=>({...j,spouse_last_name:b.target.value})),className:"mt-1 rounded-xl"})]})]}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs text-slate-600",children:"Email"}),e.jsx(Se,{type:"email",value:l.spouse_email,onChange:b=>o(j=>({...j,spouse_email:b.target.value})),className:"mt-1 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs text-slate-600",children:"Phone"}),e.jsx(Se,{type:"tel",value:l.spouse_phone,onChange:b=>o(j=>({...j,spouse_phone:b.target.value})),className:"mt-1 rounded-xl"})]})]})]}),e.jsx(H,{type:"submit",disabled:p.isPending||!l.first_name,className:"w-full h-12 rounded-full text-sm font-semibold bg-slate-900 hover:bg-slate-800",children:p.isPending?"Submitting...":"Access My Portal"})]})]})}function i$t(s,t){const r=(n,a)=>a!=null&&a!==""?a:n!=null&&n!==""?n:null;return{logo_url:r(s==null?void 0:s.logo_url,t==null?void 0:t.logo_url),cover_photo_url:r(s==null?void 0:s.cover_photo_url,t==null?void 0:t.cover_photo_url),brand_color:r(s==null?void 0:s.brand_color,t==null?void 0:t.brand_color),accent_color:r(s==null?void 0:s.accent_color,t==null?void 0:t.accent_color),tagline:r(s==null?void 0:s.tagline,t==null?void 0:t.tagline),welcome_message:r(s==null?void 0:s.welcome_message,t==null?void 0:t.welcome_message)}}function Vat(){const s=ba();return yt({queryKey:["agent-portal-branding",s],queryFn:async()=>{if(!s)return null;const{data:t,error:r}=await V.from("agent_portal_branding").select("*").eq("user_id",s).maybeSingle();if(r)throw r;return t},enabled:!!s})}function o$t(s){return yt({queryKey:["agent-portal-branding-public",s],queryFn:async()=>{if(!s)return null;const{data:t,error:r}=await V.from("agent_portal_branding").select("logo_url, cover_photo_url, brand_color, accent_color, tagline, welcome_message").eq("user_id",s).maybeSingle();if(r)throw r;return t},enabled:!!s})}function l$t(){const s=ba(),t=ns();return Pt({mutationFn:async r=>{if(!s)throw new Error("Not authenticated");const{data:n,error:a}=await V.from("agent_portal_branding").upsert({user_id:s,...r},{onConflict:"user_id"}).select().single();if(a)throw a;return n},onSuccess:()=>{t.invalidateQueries({queryKey:["agent-portal-branding",s]}),t.invalidateQueries({queryKey:["agent-portal-branding-public",s]})}})}async function Hat(s,t,r){var o;const n=((o=t.name.split(".").pop())==null?void 0:o.toLowerCase())||"png",a=`${s}/${r}-${Date.now()}.${n}`,{error:i}=await V.storage.from("portal-branding").upload(a,t,{upsert:!0,cacheControl:"3600"});if(i)throw i;const{data:l}=V.storage.from("portal-branding").getPublicUrl(a);return l.publicUrl}function c$t(s,t){return yt({queryKey:["client-portal-public",s],queryFn:async()=>{if(!s)return null;const{data:r,error:n}=await V.from("client_portals").select(` *, deal_pipeline ( id, deal_name, property_address, city, state, deal_type, target_close_date, contract_date, expected_price, actual_close_date, stage_id, owner_user_id, deal_pipeline_stages (id, name, color, icon, sort_order, is_won_stage, is_lost_stage) ) `).eq("slug",s).eq("is_enabled",!0).maybeSingle();if(n)throw n;return r},enabled:t})}function d$t(s){return yt({queryKey:["client-portal-by-id",s],queryFn:async()=>{if(!s)return null;const{data:t,error:r}=await V.from("client_portals").select(` *, deal_pipeline ( id, deal_name, property_address, city, state, deal_type, target_close_date, contract_date, expected_price, actual_close_date, stage_id, owner_user_id, deal_pipeline_stages (id, name, color, icon, sort_order, is_won_stage, is_lost_stage) ) `).eq("id",s).eq("is_enabled",!0).maybeSingle();if(r)throw r;return t},enabled:!!s})}function Gat({slug:s}){var ce,ne,le,be,fe,je;const[t,r]=S.useState(!1),[n,a]=S.useState("primary"),[i]=S.useState(()=>{const ve=`portal_fp_${s}`;let We=localStorage.getItem(ve);return We||(We=localStorage.getItem("portal_fp"),We?localStorage.setItem(ve,We):(We=crypto.randomUUID(),localStorage.setItem(ve,We),localStorage.setItem("portal_fp",We))),We});S.useEffect(()=>(document.body.classList.add("client-portal-page"),()=>document.body.classList.remove("client-portal-page")),[]);const{data:l,isLoading:o,error:c}=c$t(s,!0),d=l==null?void 0:l.linked_portal_id,{data:h}=d$t(d),m=(ce=l==null?void 0:l.deal_pipeline)==null?void 0:ce.owner_user_id;yt({queryKey:["portal-stages",m],queryFn:async()=>{const{data:ve,error:We}=await V.from("deal_pipeline_stages").select("*").eq("owner_user_id",m).order("sort_order",{ascending:!0});if(We)throw We;return ve},enabled:!!m});const{data:p}=yt({queryKey:["portal-agent",m],queryFn:async()=>{const{data:ve,error:We}=await V.from("profiles").select("id, name, avatar_url, phone, email").eq("id",m).single();if(We)throw We;return ve},enabled:!!m}),{data:x}=o$t(m),y=n==="linked"&&h?h:l,_=y==null?void 0:y.id,b=i$t(x,y==null?void 0:y.branding_override),{data:j}=yt({queryKey:["portal-updates-public",_],queryFn:async()=>{const{data:ve,error:We}=await V.from("portal_updates").select("*").eq("portal_id",_).order("created_at",{ascending:!1});if(We)throw We;return ve},enabled:!!_}),k=(ne=y==null?void 0:y.deal_pipeline)==null?void 0:ne.id,{data:T}=yt({queryKey:["portal-documents",k],queryFn:async()=>{const{data:ve,error:We}=await V.from("deal_files").select("*").eq("deal_id",k).eq("visible_on_portal",!0).order("created_at",{ascending:!1});if(We)throw We;return ve},enabled:!!k}),E=l==null?void 0:l.id,A=E?`portal_onboarded_${E}_${i}`:null,D=A?localStorage.getItem(A)==="1":!1,{data:R,isLoading:z}=yt({queryKey:["portal-onboarding-check",E,i],queryFn:async()=>{const{data:ve,error:We}=await V.from("portal_onboarding_submissions").select("id").eq("portal_id",E).eq("device_fingerprint",i).maybeSingle();if(We)throw We;return ve&&A&&localStorage.setItem(A,"1"),ve},enabled:!!E&&!!(l!=null&&l.require_onboarding)&&!D,staleTime:5*60*1e3}),O=!!(l!=null&&l.require_onboarding)&&!D&&!R&&!t,{data:$}=yt({queryKey:["portal-custom-questions-public",m],queryFn:async()=>{const{data:ve,error:We}=await V.from("portal_custom_questions").select("*").eq("owner_user_id",m).eq("is_active",!0).order("sort_order",{ascending:!0});if(We)throw We;return ve},enabled:!!m&&O}),ee=D||!!R||t||!(l!=null&&l.require_onboarding);if(o||l!=null&&l.require_onboarding&&!D&&z)return e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center",children:e.jsx(is,{className:"w-6 h-6 text-slate-400 animate-spin"})});if(c||!l)return e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center p-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-16 h-16 bg-slate-100 rounded-full flex items-center justify-center mx-auto mb-4",children:e.jsx("span",{className:"text-2xl",children:"🔒"})}),e.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Portal Not Available"}),e.jsx("p",{className:"text-slate-500",children:"This portal is no longer active or doesn't exist."})]})});if(!ee){const ve=l==null?void 0:l.deal_pipeline;return e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white",children:e.jsx(a$t,{portal:l,dealData:ve,agentProfile:p,customQuestions:$||[],deviceFingerprint:i,onComplete:()=>{A&&localStorage.setItem(A,"1"),r(!0)}})})}const Z=(le=l==null?void 0:l.deal_pipeline)==null?void 0:le.deal_type,J=(be=h==null?void 0:h.deal_pipeline)==null?void 0:be.deal_type,K=!!h,re=ve=>ve==="listing"?"Your Sale":ve==="buy-side"?"Your Purchase":"Transaction",ie=ve=>ve==="listing"?e.jsx(Fn,{className:"w-3.5 h-3.5"}):e.jsx(dx,{className:"w-3.5 h-3.5"});return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"hidden lg:block",children:e.jsx(r$t,{portal:l,linkedPortal:h,activePortal:y,activeTab:n,onTabChange:a,agentProfile:p,branding:b,updates:j,documents:T})}),e.jsxs("div",{className:"lg:hidden min-h-screen bg-gradient-to-b from-slate-50 to-white pb-12",children:[e.jsx(zzt,{dealData:y==null?void 0:y.deal_pipeline,agentProfile:p,welcomeMessage:(y==null?void 0:y.welcome_message)||b.welcome_message,isWon:(je=(fe=y==null?void 0:y.deal_pipeline)==null?void 0:fe.deal_pipeline_stages)==null?void 0:je.is_won_stage,branding:b}),e.jsxs("div",{className:"max-w-lg mx-auto px-4 space-y-5 mt-6",children:[K&&e.jsxs("div",{className:"flex gap-1 bg-slate-100 rounded-xl p-1",children:[e.jsxs("button",{onClick:()=>a("primary"),className:`flex-1 flex items-center justify-center gap-1.5 rounded-lg py-2.5 text-sm font-medium transition-all ${n==="primary"?"bg-white text-slate-800 shadow-sm":"text-slate-500 hover:text-slate-700"}`,children:[ie(Z),re(Z)]}),e.jsxs("button",{onClick:()=>a("linked"),className:`flex-1 flex items-center justify-center gap-1.5 rounded-lg py-2.5 text-sm font-medium transition-all ${n==="linked"?"bg-white text-slate-800 shadow-sm":"text-slate-500 hover:text-slate-700"}`,children:[ie(J),re(J)]})]}),e.jsx(u$t,{portal:y,updates:j,documents:T,agentProfile:p}),e.jsxs("div",{className:"text-center pt-6 pb-2 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-center gap-1.5 text-slate-400",children:[e.jsx(Fh,{className:"w-3.5 h-3.5"}),e.jsx("span",{className:"text-xs",children:"Secure Client Portal"})]}),p&&e.jsxs("p",{className:"text-xs text-slate-400",children:["Managed by ",e.jsx("span",{className:"font-medium text-slate-500",children:p.name})]}),e.jsx("p",{className:"text-[10px] text-slate-300",children:"Powered by ReLevelUp"})]})]})]})]})}function u$t({portal:s,updates:t,documents:r,agentProfile:n}){const a=s,i=a==null?void 0:a.deal_pipeline,l=i==null?void 0:i.deal_pipeline_stages,o=l==null?void 0:l.is_won_stage,c=i==null?void 0:i.deal_type,d=s.stage_mapping;let h=Bge(c);d&&d.length>0&&(h=d.map((_,b)=>{var j,k;return{key:`custom-${b}`,label:_.label||((j=h[b])==null?void 0:j.label)||`Stage ${b+1}`,description:_.description||((k=h[b])==null?void 0:k.description)||"",video_url:_.video_url||void 0}}));const m=d&&d.length>0?Math.min(Zhe(l==null?void 0:l.name),h.length-1):Zhe(l==null?void 0:l.name),p=h[m],x=p==null?void 0:p.video_url,y=o&&s.show_post_close_tips!==!1&&s.referral_enabled!==!1;return e.jsxs(e.Fragment,{children:[y&&e.jsx(Uat,{portalId:s.id,portalSlug:s.slug,ownerUserId:s.owner_user_id,rewardText:s.referral_reward_text,ctaHeadline:s.referral_cta_headline,agentName:n==null?void 0:n.name,clientName:s.client_name,reviewUrl:s.review_url,hubVideoUrl:s.homeowner_hub_video_url}),e.jsx(Pat,{targetCloseDate:i==null?void 0:i.target_close_date,actualCloseDate:i==null?void 0:i.actual_close_date,clientName:s.client_name}),e.jsx(Lat,{journeyStages:h,currentIndex:m}),p&&e.jsx(Dat,{currentStage:p,nextStepText:s.next_step_text,nextStepVideoUrl:x||s.next_step_video_url}),e.jsx(Rat,{targetCloseDate:i==null?void 0:i.target_close_date,contractDate:i==null?void 0:i.contract_date,inspectionDate:s.inspection_date,appraisalDate:s.appraisal_date,actualCloseDate:i==null?void 0:i.actual_close_date}),r&&r.length>0&&e.jsx(Oat,{documents:r}),(s==null?void 0:s.id)&&(s==null?void 0:s.owner_user_id)&&e.jsx($at,{portalId:s.id,ownerUserId:s.owner_user_id,currentStage:l==null?void 0:l.name}),t&&t.length>0&&e.jsx(Fat,{updates:t})]})}function Wat({slug:s}){const t=Po(),r=s||t.slug,[n,a]=S.useState(!1),[i,l]=S.useState(!1),[o,c]=S.useState(""),[d,h]=S.useState(""),[m,p]=S.useState(""),[x,y]=S.useState(""),[_,b]=S.useState(""),[j,k]=S.useState("buying"),[T,E]=S.useState("");S.useEffect(()=>(document.body.classList.add("client-portal-page"),()=>document.body.classList.remove("client-portal-page")),[]);const{data:A,isLoading:D,error:R}=yt({queryKey:["portal-referral-target",r],queryFn:async()=>{if(!r)return null;const{data:$,error:ee}=await V.from("client_portals").select(` id, slug, owner_user_id, client_name, referral_enabled, referral_reward_text, referral_cta_headline, is_enabled `).eq("slug",r).eq("is_enabled",!0).maybeSingle();if(ee)throw ee;return $},enabled:!!r}),{data:z}=yt({queryKey:["portal-referral-agent",A==null?void 0:A.owner_user_id],queryFn:async()=>{const{data:$}=await V.from("profiles").select("id, name, avatar_url").eq("id",A.owner_user_id).single();return $},enabled:!!(A!=null&&A.owner_user_id)}),O=async $=>{if($.preventDefault(),!A||!m.trim()){he.error("Please enter your friend's name");return}if(!x.trim()&&!_.trim()){he.error("Please add at least an email or phone for your friend");return}a(!0);try{const{error:ee}=await V.from("portal_referrals").insert({portal_id:A.id,owner_user_id:A.owner_user_id,referrer_name:o.trim()||A.client_name||null,referrer_email:d.trim()||null,friend_name:m.trim(),friend_email:x.trim()||null,friend_phone:_.trim()||null,friend_interest:j,friend_message:T.trim()||null});if(ee)throw ee;l(!0)}catch(ee){he.error(ee.message||"Could not submit referral")}finally{a(!1)}};return D?e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center",children:e.jsx(Ks,{className:"h-96 w-full max-w-lg rounded-2xl mx-4"})}):R||!A||!A.referral_enabled?e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center p-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-16 h-16 bg-slate-100 rounded-full flex items-center justify-center mx-auto mb-4",children:e.jsx("span",{className:"text-2xl",children:"🔒"})}),e.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Referral Page Unavailable"}),e.jsx("p",{className:"text-slate-500",children:"This referral link is no longer active."})]})}):i?e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-emerald-50 via-teal-50 to-white flex items-center justify-center p-6",children:e.jsxs("div",{className:"max-w-md w-full bg-white rounded-2xl shadow-xl p-8 text-center",children:[e.jsx("div",{className:"w-16 h-16 bg-emerald-100 rounded-full flex items-center justify-center mx-auto mb-4",children:e.jsx(va,{className:"w-8 h-8 text-emerald-600"})}),e.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2 font-serif",children:"Thank you! 🙏"}),e.jsxs("p",{className:"text-sm text-slate-600 leading-relaxed mb-6",children:["Your referral has been sent to ",(z==null?void 0:z.name)||"your agent",". They'll reach out to"," ",e.jsx("span",{className:"font-semibold text-slate-800",children:m})," personally and treat them like family."]}),e.jsxs("button",{onClick:()=>window.history.back(),className:"inline-flex items-center gap-2 text-sm text-[#406E71] hover:text-[#2a4c64] font-medium",children:[e.jsx(za,{className:"w-4 h-4"}),"Back to your portal"]})]})}):e.jsxs("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white pb-12",children:[e.jsxs("div",{className:"relative bg-gradient-to-br from-[#2a4c64] via-[#345e7a] to-[#406E71] text-white px-4 pt-10 pb-12 overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 opacity-[0.05]",style:{backgroundImage:"radial-gradient(circle at 25% 25%, white 1px, transparent 1px)",backgroundSize:"24px 24px"}}),e.jsxs("div",{className:"relative max-w-lg mx-auto text-center",children:[z!=null&&z.avatar_url?e.jsx("img",{src:z.avatar_url,alt:z.name||"Agent",className:"w-16 h-16 rounded-full border-[3px] border-white/30 shadow-xl mx-auto mb-3 object-cover"}):e.jsx("div",{className:"w-16 h-16 rounded-full border-[3px] border-white/30 shadow-xl mx-auto mb-3 bg-white/10 flex items-center justify-center",children:e.jsx(Di,{className:"w-7 h-7 text-white/70"})}),e.jsxs("div",{className:"inline-flex items-center gap-1.5 bg-white/10 backdrop-blur-sm rounded-full px-3 py-1 text-xs font-medium text-white/90 mb-2",children:[e.jsx(Di,{className:"w-3 h-3"})," Referral"]}),e.jsx("h1",{className:"text-2xl font-bold tracking-tight mb-1 font-serif",children:A.referral_cta_headline||"Refer a Friend"}),e.jsxs("p",{className:"text-sm text-white/70",children:["Send ",(z==null?void 0:z.name)||"your agent"," someone you trust."]}),A.referral_reward_text&&e.jsxs("p",{className:"text-xs text-white/60 mt-2",children:["You'll get: ",e.jsx("span",{className:"text-white font-medium",children:A.referral_reward_text})," when they close."]})]})]}),e.jsx("div",{className:"max-w-lg mx-auto px-4 -mt-6 relative z-10",children:e.jsxs("form",{onSubmit:O,className:"bg-white rounded-2xl shadow-lg border border-slate-100 p-5 space-y-5",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-slate-500 mb-3",children:"Tell us about your friend"}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsxs(ue,{htmlFor:"friend_name",className:"text-sm",children:["Their name ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(Se,{id:"friend_name",value:m,onChange:$=>p($.target.value),placeholder:"Jane Smith",required:!0,className:"mt-1"})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"friend_email",className:"text-sm",children:"Email"}),e.jsx(Se,{id:"friend_email",type:"email",value:x,onChange:$=>y($.target.value),placeholder:"jane@email.com",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"friend_phone",className:"text-sm",children:"Phone"}),e.jsx(Se,{id:"friend_phone",type:"tel",value:_,onChange:$=>b($.target.value),placeholder:"(555) 123-4567",className:"mt-1"})]})]}),e.jsx("p",{className:"text-[11px] text-slate-400",children:"Add at least an email or phone so we can reach them."}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-sm",children:"They're interested in..."}),e.jsx("div",{className:"mt-2 grid grid-cols-2 gap-2",children:[{v:"buying",l:"Buying"},{v:"selling",l:"Selling"},{v:"both",l:"Both"},{v:"unsure",l:"Not sure"}].map($=>e.jsx("button",{type:"button",onClick:()=>k($.v),className:`rounded-lg border px-3 py-2 text-sm font-medium transition-colors ${j===$.v?"bg-[#406E71] text-white border-[#406E71]":"bg-white text-slate-600 border-slate-200 hover:border-slate-300"}`,children:$.l},$.v))})]}),e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"friend_message",className:"text-sm",children:"A note (optional)"}),e.jsx("textarea",{id:"friend_message",value:T,onChange:$=>E($.target.value),placeholder:"They're moving from Boston in the spring...",rows:3,className:"mt-1 w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"})]})]})]}),e.jsxs("div",{className:"border-t pt-4",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-slate-500 mb-3",children:"Your info"}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"referrer_name",className:"text-sm",children:"Your name"}),e.jsx(Se,{id:"referrer_name",value:o,onChange:$=>c($.target.value),placeholder:A.client_name||"Your name",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"referrer_email",className:"text-sm",children:"Your email"}),e.jsx(Se,{id:"referrer_email",type:"email",value:d,onChange:$=>h($.target.value),placeholder:"So we can thank you!",className:"mt-1"})]})]})]}),e.jsxs("button",{type:"submit",disabled:n,className:"w-full bg-[#406E71] hover:bg-[#345e7a] disabled:opacity-60 text-white font-semibold rounded-xl py-3.5 px-4 flex items-center justify-center gap-2 transition-colors",children:[n?e.jsx(is,{className:"w-4 h-4 animate-spin"}):e.jsx(Di,{className:"w-4 h-4"}),n?"Sending...":"Send Referral"]}),e.jsx("p",{className:"text-[11px] text-center text-slate-400",children:"By submitting, you confirm your friend has agreed to be contacted."})]})})]})}function h$t(){const t=Vc().pathname.slice(1).replace(/\/$/,"");if(S.useEffect(()=>(document.body.classList.add("client-portal-page"),()=>{document.body.classList.remove("client-portal-page")}),[]),!t)return e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center p-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Client Portal"}),e.jsx("p",{className:"text-slate-500",children:"Visit your personalized portal link to view your transaction details."})]})});const r=t.match(/^([^/]+)\/refer$/);return r?e.jsx(Wat,{slug:r[1]}):t.includes("/")?e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center p-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Page Not Found"}),e.jsx("p",{className:"text-slate-500",children:"This portal link doesn't look right."})]})}):e.jsx(Gat,{slug:t})}const DNe="levelup_affiliate_ref",m$t=30,f$t=()=>{const[s]=Ed();S.useEffect(()=>{const t=s.get("ref");if(t){const r={code:t.toUpperCase(),timestamp:Date.now()};localStorage.setItem(DNe,JSON.stringify(r)),console.log("[Affiliate] Stored referral code:",t)}},[s])},p$t=()=>{try{const s=localStorage.getItem(DNe);if(!s)return null;const t=JSON.parse(s),r=m$t*24*60*60*1e3;return Date.now()-t.timestamp>r?(localStorage.removeItem(DNe),console.log("[Affiliate] Referral code expired"),null):t.code}catch{return null}},Xhe="/assets/levelup-logo-header-_ZX7DvlA.png",g$t="/assets/scale-your-team-ku4MPatU.png";function x$t({open:s,onOpenChange:t}){return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-3xl max-h-[90vh] overflow-hidden",children:[e.jsx(Cs,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-[#4a6b6d]/10 rounded-lg",children:e.jsx(Xa,{className:"h-5 w-5 text-[#4a6b6d]"})}),e.jsxs("div",{children:[e.jsx(Ns,{children:"Schedule a Brokerage Interest Meeting"}),e.jsx(nn,{children:"Learn how LevelUp can empower your entire team"})]})]})}),s&&e.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 qm={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",popular:!1},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"],popular:!0},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"],popular:!1}},y$t=[{icon:cg,title:"Academy Training",description:"Access a library of on-demand video training covering lead generation, marketing, technology, and more."},{icon:pl,title:"300+ Templates",description:"Professional Canva templates for social media, flyers, postcards, and marketing materials."},{icon:Nn,title:"Live Events",description:"Weekly live training sessions, workshops, and Q&A events with industry experts."},{icon:qc,title:"Agent Community",description:"Connect with fellow agents, share wins, ask questions, and network in our private community."},{icon:kn,title:"Resource Kits",description:"Downloadable toolkits with scripts, checklists, guides, and everything you need to close more deals."},{icon:Di,title:"Social Swag",description:"Fresh social media content and designs updated regularly to help you stand out online."}],v$t=[{icon:Ar,title:"Contact Management",description:"Organize your sphere into relationship tiers—Top 25, Past Clients, Referral Partners, and more."},{icon:Lr,title:"Smart Touchpoint Plans",description:"Automated action plans that tell you exactly who to contact and how, based on relationship type."},{icon:Yn,title:"One-Tap Actions",description:"Call, text, or email contacts directly with pre-written scripts tailored to each relationship."},{icon:gm,title:"Birthday & Anniversary Alerts",description:"Never miss an important date—get reminders for birthdays and home anniversaries."},{icon:Qa,title:"Pop-by Map",description:"See all your contacts on a map and plan efficient pop-by routes in your area."},{icon:Bo,title:"Momentum Tracking",description:"Track your touch streaks, weekly goals, and relationship health scores."},{icon:Bi,title:"Relationship Health",description:"Visual dashboard showing which contacts need attention based on last touch date."},{icon:ym,title:"Daily Action Cards",description:"Wake up to a prioritized list of exactly who to reach out to today."}],b$t=[{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."}],_$t=()=>{const{user:s,loading:t}=Ms(),r=Fr(),[n]=Ed();S.useEffect(()=>{const R=window.location.host==="listings.relevelup.com",z=window.location.pathname==="/";if(R&&z){r("/public/listings",{replace:!0});return}},[r]);const[a,i]=S.useState(null),[l,o]=S.useState(null),[c,d]=S.useState(!1),[h,m]=S.useState(""),[p,x]=S.useState(""),[y,_]=S.useState(""),[b,j]=S.useState(!1),[k,T]=S.useState(!1),E=(R,z=!1)=>{o({tier:R,skipTrial:z}),d(!0)};f$t(),S.useEffect(()=>{const R=window.location.host==="listings.relevelup.com",z=location.pathname.startsWith("/public/");!t&&s&&!R&&!z&&r("/dashboard")},[s,t,r,location.pathname]),S.useEffect(()=>{n.get("canceled")==="true"&&he.error("Checkout was canceled. Feel free to try again when you're ready!")},[n]);const A=async(R,z=!1)=>{if(!h){he.error("Please enter your email address");return}if(!p.trim()){he.error("Please enter your full name");return}j(!0),i(R+(z?"_direct":""));const O=p$t();try{const{data:$,error:ee}=await V.functions.invoke("create-checkout",{body:{tier:R,email:h,name:p.trim(),couponCode:y.trim()||void 0,skipTrial:z,referralCode:O}});if(ee)throw ee;if($!=null&&$.url)window.open($.url,"_blank","noopener,noreferrer"),he.success("Checkout opened in a new tab");else throw new Error("No checkout URL returned")}catch($){console.error("Checkout error:",$),he.error($.message||"Failed to start checkout. Please try again.")}finally{j(!1),i(null),d(!1),o(null)}},D=()=>{l&&A(l.tier,l.skipTrial)};return t?e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-[#4a6b6d]",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-white border-t-transparent"})}):e.jsxs("div",{className:"min-h-screen bg-background overflow-hidden",children:[e.jsx("nav",{className:"fixed top-0 left-0 right-0 z-50 bg-[#4a6b6d] shadow-md",children:e.jsxs("div",{className:"container mx-auto px-4 py-3 flex items-center justify-between",children:[e.jsx("div",{className:"flex items-center",children:e.jsx("img",{src:Xhe,alt:"LevelUp",className:"h-8 md:h-10"})}),e.jsxs("div",{className:"flex items-center gap-2 md:gap-4",children:[e.jsx(H,{variant:"ghost",className:"text-white/90 hover:text-white hover:bg-white/10 hidden sm:inline-flex",onClick:()=>{var R;return(R=document.getElementById("features"))==null?void 0:R.scrollIntoView({behavior:"smooth"})},children:"Features"}),e.jsx(H,{variant:"ghost",className:"text-white/90 hover:text-white hover:bg-white/10 hidden sm:inline-flex",onClick:()=>{var R;return(R=document.getElementById("pricing"))==null?void 0:R.scrollIntoView({behavior:"smooth"})},children:"Pricing"}),e.jsx(H,{onClick:()=>r("/auth"),className:"bg-white text-[#4a6b6d] hover:bg-gray-100 font-medium shadow-md",children:"Sign In"})]})]})}),e.jsxs("section",{className:"relative pt-24 pb-20 bg-gradient-to-br from-[#1e3a4c] via-[#2a4f5f] to-[#3d6b6b] overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 opacity-10",children:e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),e.jsx("div",{className:"container mx-auto px-4 relative",children:e.jsxs("div",{className:"max-w-5xl mx-auto text-center space-y-8",children:[e.jsx("div",{className:"flex justify-center mb-8",children:e.jsx("img",{alt:"LevelUp Consulting Group",className:"h-[136px] md:h-[164px] drop-shadow-lg",src:"/lovable-uploads/3a0c7ef9-9e79-411f-a9af-6f2a99e8bd7b.webp"})}),e.jsxs("p",{className:"text-lg text-white/80 max-w-3xl mx-auto leading-relaxed font-sans font-bold md:text-4xl",children:["The tools you need to get it done.",e.jsx("br",{}),e.jsx("em",{children:"The platform you need to keep it going."})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 justify-center items-center pt-4",children:[e.jsxs(H,{size:"lg",onClick:()=>{var R;return(R=document.getElementById("free-trial"))==null?void 0:R.scrollIntoView({behavior:"smooth"})},className:"px-8 py-7 text-lg font-semibold bg-white text-[#1e3a4c] hover:bg-white/90 shadow-2xl transition-all hover:scale-105 group rounded-full",children:["Start Your Free Trial",e.jsx(bi,{className:"ml-2 w-5 h-5 group-hover:translate-x-1 transition-transform"})]}),e.jsx(H,{size:"lg",variant:"outline",onClick:()=>{var R;return(R=document.getElementById("features"))==null?void 0:R.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-[#1e3a4c] rounded-full",children:"See What's Included"})]})]})})]}),e.jsx("section",{className:"py-20 bg-background",children:e.jsx("div",{className:"container mx-auto px-4",children:e.jsxs("div",{className:"max-w-4xl mx-auto text-center space-y-8",children:[e.jsx("h2",{className:"text-3xl md:text-5xl leading-tight font-sans font-semibold text-secondary",children:"We help brokerages and agents grow with training, tools, and built-in execution."}),e.jsxs("div",{className:"space-y-2 text-lg text-muted-foreground",children:[e.jsx("p",{children:"Agents get weekly coaching + plug-and-play marketing."}),e.jsx("p",{children:"Brokerages get higher adoption, consistency, and real engagement."})]}),e.jsx("p",{className:"text-2xl md:text-4xl text-[#4a6b6d] pt-4 font-sans font-bold",children:"LEVELUP EQUIPS BOTH TO THRIVE."}),e.jsx("p",{className:"text-lg text-muted-foreground",children:"Learn how we support agents and empower brokerages to grow—together."}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 justify-center pt-4",children:[e.jsxs(H,{size:"lg",variant:"outline",onClick:()=>{var R;return(R=document.getElementById("brokerage"))==null?void 0:R.scrollIntoView({behavior:"smooth"})},className:"border-[#4a6b6d] text-[#4a6b6d] hover:bg-[#4a6b6d]/5",children:[e.jsx(Xa,{className:"mr-2 h-5 w-5"}),"Brokerage Partnership"]}),e.jsxs(H,{size:"lg",onClick:()=>{var R;return(R=document.getElementById("pricing"))==null?void 0:R.scrollIntoView({behavior:"smooth"})},className:"bg-[#4a6b6d] hover:bg-[#3d5a5c]",children:[e.jsx(io,{className:"mr-2 h-5 w-5"}),"Individual Membership"]})]})]})})}),e.jsx("section",{id:"features",className:"py-20 bg-muted/30",children:e.jsxs("div",{className:"container mx-auto px-4",children:[e.jsxs("div",{className:"text-center max-w-3xl mx-auto mb-16",children:[e.jsx("h2",{className:"text-3xl md:text-4xl mb-6 font-sans font-bold",children:"What's inside our members only portal?"}),e.jsx("p",{className:"text-lg text-muted-foreground",children:"Everything you need to grow your business, all in one place."})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8 max-w-6xl mx-auto",children:y$t.map((R,z)=>e.jsxs(ke,{className:"group relative overflow-hidden border hover:border-[#4a6b6d]/50 transition-all duration-300 hover:shadow-lg bg-background",children:[e.jsxs(Ot,{children:[e.jsx("div",{className:"w-14 h-14 rounded-2xl bg-[#4a6b6d]/10 flex items-center justify-center mb-4",children:e.jsx(R.icon,{className:"w-7 h-7 text-[#4a6b6d]"})}),e.jsx(zt,{className:"text-xl font-sans",children:R.title})]}),e.jsx(Oe,{children:e.jsx("p",{className:"text-muted-foreground leading-relaxed",children:R.description})})]},z))})]})}),e.jsxs("section",{id:"agent-os",className:"py-20 bg-gradient-to-br from-[#4a6b6d] to-[#3d5a5c] relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 opacity-10",children:e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),e.jsxs("div",{className:"container mx-auto px-4 relative",children:[e.jsxs("div",{className:"text-center max-w-3xl mx-auto mb-16",children:[e.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:[e.jsx(Lr,{className:"w-4 h-4"}),"Included with Membership"]}),e.jsxs("h2",{className:"text-3xl mb-6 text-white font-sans font-bold md:text-6xl",children:["Meet ",e.jsx("span",{className:"italic",children:"Agent OS"})]}),e.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."})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 max-w-6xl mx-auto",children:v$t.map((R,z)=>e.jsxs(ke,{className:"group relative overflow-hidden border-0 bg-white/10 backdrop-blur-sm hover:bg-white/20 transition-all duration-300",children:[e.jsxs(Ot,{className:"pb-3",children:[e.jsx("div",{className:"w-12 h-12 rounded-xl bg-white/20 flex items-center justify-center mb-3",children:e.jsx(R.icon,{className:"w-6 h-6 text-white"})}),e.jsx(zt,{className:"text-lg font-semibold text-white",children:R.title})]}),e.jsx(Oe,{children:e.jsx("p",{className:"text-white/70 text-sm leading-relaxed",children:R.description})})]},z))}),e.jsx("div",{className:"text-center mt-12",children:e.jsxs(H,{size:"lg",onClick:()=>{var R;return(R=document.getElementById("pricing"))==null?void 0:R.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",e.jsx(bi,{className:"ml-2 w-5 h-5"})]})})]})]}),e.jsx("section",{id:"brokerage",className:"py-20 bg-[#4a6b6d]/5",children:e.jsx("div",{className:"container mx-auto px-4",children:e.jsx("div",{className:"max-w-6xl mx-auto",children:e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-12 items-center",children:[e.jsxs("div",{className:"space-y-6",children:[e.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:[e.jsx(Xa,{className:"w-4 h-4"}),"For Brokerages"]}),e.jsxs("h2",{className:"text-3xl font-sans font-bold md:text-6xl",children:["Empower Your"," ",e.jsx("span",{className:"italic text-[#4a6b6d]",children:"Entire Team"})]}),e.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."}),e.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((R,z)=>e.jsxs("li",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-6 h-6 rounded-full bg-[#4a6b6d]/10 flex items-center justify-center flex-shrink-0",children:e.jsx(va,{className:"w-4 h-4 text-[#4a6b6d]"})}),e.jsx("span",{className:"text-foreground",children:R})]},z))}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3 mt-4",children:[e.jsxs(H,{size:"lg",onClick:()=>{var R;return(R=document.getElementById("pricing"))==null?void 0:R.scrollIntoView({behavior:"smooth"})},className:"bg-[#4a6b6d] hover:bg-[#3d5a5c]",children:["See Brokerage Plans",e.jsx($a,{className:"ml-2 w-5 h-5"})]}),e.jsxs(H,{size:"lg",variant:"outline",onClick:()=>T(!0),className:"border-[#4a6b6d] text-[#4a6b6d] hover:bg-[#4a6b6d]/10",children:[e.jsx(Nn,{className:"mr-2 w-5 h-5"}),"Schedule Info Session"]})]})]}),e.jsx("div",{className:"relative hidden md:block",children:e.jsx("img",{src:g$t,alt:"Scale Your Team from 5 to 500 Agents",className:"w-full rounded-3xl shadow-lg"})})]})})})}),e.jsx("section",{className:"py-20 bg-background",children:e.jsxs("div",{className:"container mx-auto px-4",children:[e.jsxs("div",{className:"text-center max-w-3xl mx-auto mb-16",children:[e.jsxs("h2",{className:"text-3xl mb-6 font-sans md:text-5xl font-bold",children:["Agents Love ",e.jsx("span",{className:"italic text-[#4a6b6d]",children:"LevelUp"})]}),e.jsx("p",{className:"text-lg text-muted-foreground",children:"See what top producers are saying about the platform."})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-8 max-w-6xl mx-auto",children:b$t.map((R,z)=>e.jsx(ke,{className:"bg-muted/30 border-0",children:e.jsxs(Oe,{className:"pt-8",children:[e.jsx("div",{className:"flex gap-1 mb-4",children:[1,2,3,4,5].map(O=>e.jsx(ya,{className:"w-5 h-5 fill-yellow-400 text-yellow-400"},O))}),e.jsxs("p",{className:"text-lg mb-6 italic text-muted-foreground",children:['"',R.quote,'"']}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold",children:R.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:R.role})]})]})},z))})]})}),e.jsxs("section",{id:"free-trial",className:"py-20 bg-gradient-to-br from-[#1e3a4c] via-[#2a4f5f] to-[#3d6b6b] relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 opacity-10",children:e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),e.jsx("div",{className:"container mx-auto px-4 relative",children:e.jsxs("div",{className:"max-w-3xl mx-auto text-center space-y-8",children:[e.jsxs("h2",{className:"text-3xl md:text-5xl font-bold text-white",children:["Start Your Free Trial ",e.jsx("span",{className:"italic",children:"Today"})]}),e.jsx("p",{className:"text-lg md:text-xl text-white/80 leading-relaxed",children:"Get instant access to 7 days of trainings, templates, and tools — designed to give you quick wins now and resources you'll keep forever."}),e.jsx("div",{className:"pt-4",children:e.jsxs(H,{size:"lg",className:"px-12 py-7 text-lg font-semibold bg-white text-[#4a6b6d] hover:bg-white/90 shadow-2xl transition-all hover:scale-105 group rounded-full",onClick:()=>E("individual_agent"),children:["Start Free Trial",e.jsx(bi,{className:"ml-2 w-5 h-5 group-hover:translate-x-1 transition-transform"})]})})]})})]}),e.jsx("section",{id:"pricing",className:"py-20 bg-muted/30",children:e.jsxs("div",{className:"container mx-auto px-4",children:[e.jsxs("div",{className:"text-center mb-16",children:[e.jsxs("h2",{className:"text-3xl mb-6 font-sans md:text-5xl font-bold",children:["Simple, Transparent ",e.jsx("span",{className:"italic text-[#4a6b6d]",children:"Pricing"})]}),e.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."})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-8 max-w-6xl mx-auto",children:[e.jsxs(ke,{className:"relative flex flex-col border hover:border-[#4a6b6d]/50 transition-all hover:shadow-xl bg-background",children:[e.jsxs(Ot,{className:"pb-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-[#4a6b6d]/10 flex items-center justify-center",children:e.jsx(io,{className:"w-5 h-5 text-[#4a6b6d]"})}),e.jsx(zt,{className:"text-xl font-sans",children:qm.individual_agent.name})]}),e.jsxs("div",{className:"flex items-baseline gap-1 mt-4",children:[e.jsx("span",{className:"text-5xl font-bold",children:qm.individual_agent.price}),e.jsx("span",{className:"text-muted-foreground text-lg",children:qm.individual_agent.period})]}),e.jsx(Br,{className:"text-base mt-2",children:qm.individual_agent.description}),e.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:[e.jsx(Pn,{className:"w-4 h-4"}),qm.individual_agent.trial]})]}),e.jsx(Oe,{className:"flex-1 pt-0",children:e.jsx("ul",{className:"space-y-3",children:qm.individual_agent.features.map((R,z)=>e.jsxs("li",{className:"flex items-center gap-3",children:[e.jsx(va,{className:"w-5 h-5 text-[#4a6b6d] flex-shrink-0"}),e.jsx("span",{children:R})]},z))})}),e.jsxs(WF,{className:"flex flex-col gap-3 pt-4",children:[e.jsx(H,{className:"w-full py-6 text-lg bg-[#4a6b6d] hover:bg-[#3d5a5c]",onClick:()=>E("individual_agent"),children:"Start Free Trial"}),e.jsx(H,{variant:"outline",className:"w-full rounded-full border-2 border-[#4a6b6d] text-[#4a6b6d] bg-white hover:bg-[#4a6b6d]/5 uppercase text-sm font-medium tracking-wide",onClick:()=>E("individual_agent",!0),children:"Skip Trial, Subscribe Now"})]})]}),e.jsxs(ke,{className:"relative flex flex-col border-2 border-[#4a6b6d] shadow-2xl scale-105 bg-background",children:[e.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"}),e.jsxs(Ot,{className:"pb-4 pt-8",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-[#4a6b6d]/20 flex items-center justify-center",children:e.jsx(Xa,{className:"w-5 h-5 text-[#4a6b6d]"})}),e.jsxs("div",{children:[e.jsx(zt,{className:"text-xl font-sans",children:qm.brokerage_under_25.name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:qm.brokerage_under_25.subtitle})]})]}),e.jsxs("div",{className:"flex items-baseline gap-1 mt-4",children:[e.jsx("span",{className:"text-5xl font-bold",children:qm.brokerage_under_25.price}),e.jsx("span",{className:"text-muted-foreground text-lg",children:qm.brokerage_under_25.period})]}),e.jsx(Br,{className:"text-base mt-2",children:qm.brokerage_under_25.description})]}),e.jsx(Oe,{className:"flex-1 pt-0",children:e.jsx("ul",{className:"space-y-3",children:qm.brokerage_under_25.features.map((R,z)=>e.jsxs("li",{className:"flex items-center gap-3",children:[e.jsx(va,{className:"w-5 h-5 text-[#4a6b6d] flex-shrink-0"}),e.jsx("span",{children:R})]},z))})}),e.jsx(WF,{className:"pt-4",children:e.jsx(H,{className:"w-full py-6 text-lg shadow-lg bg-[#4a6b6d] hover:bg-[#3d5a5c]",onClick:()=>E("brokerage_under_25"),children:"Get Started"})})]}),e.jsxs(ke,{className:"relative flex flex-col border hover:border-[#4a6b6d]/50 transition-all hover:shadow-xl bg-background",children:[e.jsxs(Ot,{className:"pb-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-[#4a6b6d]/10 flex items-center justify-center",children:e.jsx(Xa,{className:"w-5 h-5 text-[#4a6b6d]"})}),e.jsxs("div",{children:[e.jsx(zt,{className:"text-xl font-sans",children:qm.brokerage_over_25.name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:qm.brokerage_over_25.subtitle})]})]}),e.jsxs("div",{className:"flex items-baseline gap-1 mt-4",children:[e.jsx("span",{className:"text-5xl font-bold",children:qm.brokerage_over_25.price}),e.jsx("span",{className:"text-muted-foreground text-lg",children:qm.brokerage_over_25.period})]}),e.jsx(Br,{className:"text-base mt-2",children:qm.brokerage_over_25.description})]}),e.jsx(Oe,{className:"flex-1 pt-0",children:e.jsx("ul",{className:"space-y-3",children:qm.brokerage_over_25.features.map((R,z)=>e.jsxs("li",{className:"flex items-center gap-3",children:[e.jsx(va,{className:"w-5 h-5 text-[#4a6b6d] flex-shrink-0"}),e.jsx("span",{children:R})]},z))})}),e.jsx(WF,{className:"pt-4",children:e.jsx(H,{className:"w-full py-6 text-lg bg-[#4a6b6d] hover:bg-[#3d5a5c]",onClick:()=>E("brokerage_over_25"),children:"Get Started"})})]})]})]})}),e.jsx("section",{id:"neutrality",className:"py-20 bg-background",children:e.jsx("div",{className:"container mx-auto px-4",children:e.jsxs("div",{className:"max-w-4xl mx-auto",children:[e.jsxs("div",{className:"text-center mb-12",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 px-4 py-2 rounded-full bg-[#4a6b6d]/10 text-[#4a6b6d] text-sm font-medium mb-4",children:[e.jsx(Fh,{className:"w-4 h-4"}),"Our Commitment"]}),e.jsxs("h2",{className:"text-3xl md:text-4xl font-sans font-bold",children:["LevelUp Brokerage ",e.jsx("span",{className:"italic text-[#4a6b6d]",children:"Neutrality Policy"})]}),e.jsx("p",{className:"text-lg text-muted-foreground mt-4 max-w-2xl mx-auto",children:"We are committed to being a trusted, independent partner for every agent and brokerage."})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsx(ke,{className:"border-[#4a6b6d]/20 bg-[#4a6b6d]/[0.03]",children:e.jsxs(Oe,{className:"p-6 flex items-start gap-4",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-[#4a6b6d]/10 flex items-center justify-center shrink-0",children:e.jsx(Xa,{className:"w-5 h-5 text-[#4a6b6d]"})}),e.jsx("p",{className:"text-foreground font-medium leading-relaxed",children:"LevelUp serves all brokerages."})]})}),e.jsx(ke,{className:"border-[#4a6b6d]/20 bg-[#4a6b6d]/[0.03]",children:e.jsxs(Oe,{className:"p-6 flex items-start gap-4",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-[#4a6b6d]/10 flex items-center justify-center shrink-0",children:e.jsx(Td,{className:"w-5 h-5 text-[#4a6b6d]"})}),e.jsx("p",{className:"text-foreground font-medium leading-relaxed",children:"LevelUp does not share member information with any brokerage."})]})}),e.jsx(ke,{className:"border-[#4a6b6d]/20 bg-[#4a6b6d]/[0.03]",children:e.jsxs(Oe,{className:"p-6 flex items-start gap-4",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-[#4a6b6d]/10 flex items-center justify-center shrink-0",children:e.jsx(j1,{className:"w-5 h-5 text-[#4a6b6d]"})}),e.jsx("p",{className:"text-foreground font-medium leading-relaxed",children:"LevelUp does not recruit brokerage partners' agents."})]})}),e.jsx(ke,{className:"border-[#4a6b6d]/20 bg-[#4a6b6d]/[0.03]",children:e.jsxs(Oe,{className:"p-6 flex items-start gap-4",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-[#4a6b6d]/10 flex items-center justify-center shrink-0",children:e.jsx(kn,{className:"w-5 h-5 text-[#4a6b6d]"})}),e.jsx("p",{className:"text-foreground font-medium leading-relaxed",children:"LevelUp does not use LevelUp events, trainings, webinars, CRM data, or member lists for recruiting purposes."})]})})]})]})})}),e.jsxs("section",{className:"py-20 bg-gradient-to-br from-[#1e3a4c] via-[#2a4f5f] to-[#3d6b6b] relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 opacity-10",children:e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),e.jsx("div",{className:"container mx-auto px-4 relative",children:e.jsxs("div",{className:"max-w-4xl mx-auto text-center space-y-8",children:[e.jsx("h2",{className:"text-3xl text-white font-sans md:text-5xl",children:"Ready to Level Up?"}),e.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."}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 justify-center",children:[e.jsxs(H,{size:"lg",onClick:()=>{var R;return(R=document.getElementById("pricing"))==null?void 0:R.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",e.jsx(bi,{className:"ml-2 w-5 h-5"})]}),e.jsx(H,{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"})]})]})})]}),e.jsx("footer",{className:"py-12 bg-[#3d5a5c] text-white/80",children:e.jsx("div",{className:"container mx-auto px-4",children:e.jsxs("div",{className:"flex flex-col md:flex-row items-center justify-between gap-4",children:[e.jsx("img",{src:Xhe,alt:"LevelUp",className:"h-8"}),e.jsxs("p",{className:"text-sm",children:["© ",new Date().getFullYear()," LevelUp. All rights reserved."]}),e.jsxs("div",{className:"flex items-center gap-6",children:[e.jsx("a",{href:"/privacy-policy",className:"text-white/60 hover:text-white transition-colors text-sm",children:"Privacy Policy"}),e.jsx("a",{href:"mailto:support@relevelup.com",className:"text-white/60 hover:text-white transition-colors text-sm",children:"Contact Support"})]})]})})}),e.jsx(x$t,{open:k,onOpenChange:T}),e.jsx(bs,{open:c,onOpenChange:d,children:e.jsxs(vs,{className:"sm:max-w-md",children:[e.jsxs(Cs,{children:[e.jsx(Ns,{className:"text-xl font-sans font-semibold",children:"Enter your details to get started"}),e.jsx(nn,{children:(l==null?void 0:l.tier)==="individual_agent"&&!(l!=null&&l.skipTrial)?"Start your 7-day free trial":(l==null?void 0:l.tier)==="individual_agent"?"Subscribe to Individual Agent":(l==null?void 0:l.tier)==="brokerage_under_25"?"Subscribe to Brokerage (Under 25 Agents)":"Subscribe to Brokerage (Over 25 Agents)"})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{children:[e.jsxs(ue,{htmlFor:"dialog-name",children:["Full Name ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(Se,{id:"dialog-name",type:"text",placeholder:"John Smith",value:p,onChange:R=>x(R.target.value),className:"mt-1",required:!0})]}),e.jsxs("div",{children:[e.jsxs(ue,{htmlFor:"dialog-email",children:["Email Address ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(Se,{id:"dialog-email",type:"email",placeholder:"you@example.com",value:h,onChange:R=>m(R.target.value),className:"mt-1",required:!0})]}),e.jsxs("div",{children:[e.jsxs(ue,{htmlFor:"dialog-coupon",children:["Discount Code ",e.jsx("span",{className:"text-muted-foreground",children:"(Optional)"})]}),e.jsx(Se,{id:"dialog-coupon",type:"text",placeholder:"Enter discount code",value:y,onChange:R=>_(R.target.value),className:"mt-1"})]})]}),e.jsx(H,{className:"w-full py-6 text-lg bg-[#4a6b6d] hover:bg-[#3d5a5c]",onClick:D,disabled:b,children:b?"Loading...":"Continue to Checkout"})]})})]})},P7e=()=>e.jsxs(e.Fragment,{children:[e.jsxs(el,{children:[e.jsx("title",{children:"Privacy Policy | LevelUp"}),e.jsx("meta",{name:"description",content:"Privacy Policy for LevelUp platform"})]}),e.jsx("div",{className:"min-h-screen bg-background py-12 px-4 sm:px-6 lg:px-8",children:e.jsxs("div",{className:"max-w-3xl mx-auto",children:[e.jsx("h1",{className:"text-3xl font-bold text-foreground mb-8",children:"Privacy Policy"}),e.jsxs("div",{className:"prose prose-sm max-w-none text-muted-foreground space-y-6",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Last updated: January 17, 2026"}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"1. Introduction"}),e.jsx("p",{children:'Welcome to LevelUp ("we," "our," or "us"). We are committed to protecting your personal information and your right to privacy. This Privacy Policy explains how we collect, use, disclose, and safeguard your information when you use our platform.'})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"2. Information We Collect"}),e.jsx("p",{children:"We collect information that you provide directly to us, including:"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Name and contact information (email address, phone number)"}),e.jsx("li",{children:"Account credentials"}),e.jsx("li",{children:"Profile information"}),e.jsx("li",{children:"Transaction and billing information"}),e.jsx("li",{children:"Communications you send to us"})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"3. How We Use Your Information"}),e.jsx("p",{children:"We use the information we collect to:"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Provide, maintain, and improve our services"}),e.jsx("li",{children:"Process transactions and send related information"}),e.jsx("li",{children:"Send you technical notices and support messages"}),e.jsx("li",{children:"Respond to your comments and questions"}),e.jsx("li",{children:"Communicate with you about products, services, and events"})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"4. Information Sharing"}),e.jsx("p",{children:"We do not sell, trade, or otherwise transfer your personal information to third parties without your consent, except as described in this policy or as required by law."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"5. Data Security"}),e.jsx("p",{children:"We implement appropriate technical and organizational measures to protect the security of your personal information. However, no method of transmission over the Internet is 100% secure."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"6. Your Rights"}),e.jsx("p",{children:"You have the right to:"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Access your personal information"}),e.jsx("li",{children:"Correct inaccurate data"}),e.jsx("li",{children:"Request deletion of your data"}),e.jsx("li",{children:"Opt-out of marketing communications"})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"7. SMS / Text Messaging Program & Mobile Information"}),e.jsx("p",{children:"Your privacy is important to us. This section outlines how we collect, use, and protect your information when you use our services, including our SMS/text messaging program."}),e.jsxs("p",{className:"mt-3",children:[e.jsx("strong",{className:"text-foreground",children:"Information We Collect:"})," We collect personal information you provide, including your name, email address, phone number, and mobile number when you opt in to receive text messages from us."]}),e.jsxs("p",{className:"mt-3",children:[e.jsx("strong",{className:"text-foreground",children:"How We Use Your Information:"})," We use your information to deliver the services you requested, send transactional and informational messages, and improve your experience."]}),e.jsxs("p",{className:"mt-3",children:[e.jsx("strong",{className:"text-foreground",children:"No Sharing of Mobile Information:"})," No mobile information will be shared with third parties/affiliates for marketing/promotional purposes. All the above categories exclude text messaging originator opt-in data and consent; this information will not be shared with any third parties."]}),e.jsxs("p",{className:"mt-3",children:[e.jsx("strong",{className:"text-foreground",children:"Your Rights:"})," You have the right to access, modify, or delete your personal information at any time. You may opt out of text messages at any time by replying STOP to any message. Reply HELP for help. Message and data rates may apply. Message frequency varies."]}),e.jsxs("p",{className:"mt-3",children:["For questions about this policy, contact us at"," ",e.jsx("a",{href:"mailto:support@relevelup.com",className:"text-primary hover:underline",children:"support@relevelup.com"}),"."]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"8. Third-Party Services"}),e.jsx("p",{children:"Our platform may integrate with third-party services such as Facebook and Instagram for social media posting features. When you connect these accounts, you are subject to their respective privacy policies."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"9. Contact Us"}),e.jsxs("p",{children:["If you have questions about this Privacy Policy, please contact us at"," ",e.jsx("a",{href:"mailto:support@relevelup.com",className:"text-primary hover:underline",children:"support@relevelup.com"})]})]})]})]})})]}),L7e=()=>e.jsxs(e.Fragment,{children:[e.jsxs(el,{children:[e.jsx("title",{children:"Terms of Service | LevelUp"}),e.jsx("meta",{name:"description",content:"Terms of Service for LevelUp platform"})]}),e.jsx("div",{className:"min-h-screen bg-background py-12 px-4 sm:px-6 lg:px-8",children:e.jsxs("div",{className:"max-w-3xl mx-auto",children:[e.jsx("h1",{className:"text-3xl font-bold text-foreground mb-8",children:"Terms of Service"}),e.jsxs("div",{className:"prose prose-sm max-w-none text-muted-foreground space-y-6",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Last updated: January 17, 2026"}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"1. Acceptance of Terms"}),e.jsx("p",{children:'By accessing or using the LevelUp platform ("Service"), you agree to be bound by these Terms of Service. If you do not agree to these terms, please do not use our Service.'})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"2. Description of Service"}),e.jsx("p",{children:"LevelUp provides a platform for real estate professionals to access training, resources, marketing tools, and community features. We reserve the right to modify or discontinue the Service at any time."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"3. User Accounts"}),e.jsx("p",{children:"To use certain features, you must create an account. You agree to:"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Provide accurate and complete information"}),e.jsx("li",{children:"Maintain the security of your account credentials"}),e.jsx("li",{children:"Notify us immediately of any unauthorized access"}),e.jsx("li",{children:"Accept responsibility for all activities under your account"})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"4. Acceptable Use"}),e.jsx("p",{children:"You agree not to:"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Violate any applicable laws or regulations"}),e.jsx("li",{children:"Infringe on the rights of others"}),e.jsx("li",{children:"Upload malicious code or interfere with the Service"}),e.jsx("li",{children:"Attempt to gain unauthorized access to any part of the Service"}),e.jsx("li",{children:"Use the Service for any unlawful purpose"})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"5. Intellectual Property"}),e.jsx("p",{children:"The Service and its original content, features, and functionality are owned by LevelUp and are protected by international copyright, trademark, and other intellectual property laws."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"6. Third-Party Integrations"}),e.jsx("p",{children:"Our Service may integrate with third-party platforms such as Facebook and Instagram. Your use of these integrations is subject to the terms and policies of those third parties. We are not responsible for the content or practices of any third-party services."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"7. Payment Terms"}),e.jsx("p",{children:"Certain features may require payment. By subscribing to paid features, you agree to pay all applicable fees. All payments are non-refundable unless otherwise specified."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"8. Limitation of Liability"}),e.jsx("p",{children:"To the maximum extent permitted by law, LevelUp shall not be liable for any indirect, incidental, special, consequential, or punitive damages resulting from your use of the Service."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"9. Termination"}),e.jsx("p",{children:"We may terminate or suspend your account at any time, without prior notice, for conduct that we believe violates these Terms or is harmful to other users, us, or third parties."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"10. Changes to Terms"}),e.jsx("p",{children:"We reserve the right to modify these Terms at any time. We will notify you of significant changes by posting a notice on our platform. Continued use of the Service constitutes acceptance of the modified terms."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"11. SMS / Text Messaging Terms"}),e.jsxs("div",{className:"rounded-lg border border-primary/30 bg-primary/5 p-4 mb-4 text-sm",children:[e.jsx("strong",{children:"To opt in:"})," Submit our public SMS opt-in form at"," ",e.jsx("a",{href:"/sms-opt-in",className:"text-primary hover:underline font-medium",children:"/sms-opt-in"})," ","— consent is captured with timestamp and the exact disclosure text shown below."]}),e.jsx("p",{children:"By opting in to receive text messages from LevelUp Consulting Group, you agree to the following terms:"}),e.jsx("p",{className:"mt-2",children:"You consent to receive recurring SMS/MMS messages from LevelUp, including but not limited to account notifications, service updates, AI concierge replies, and customer support communications. Message frequency varies. Message and data rates may apply."}),e.jsxs("p",{className:"mt-2",children:["You may opt out at any time by replying STOP to any message. After opting out, you will receive a confirmation message and no further messages will be sent. For assistance, reply HELP or contact us at"," ",e.jsx("a",{href:"mailto:support@relevelup.com",className:"text-primary hover:underline",children:"support@relevelup.com"}),"."]}),e.jsxs("p",{className:"mt-2",children:["Your mobile phone number and opt-in data will not be shared with or sold to third parties. See our"," ",e.jsx("a",{href:"/privacy-policy",className:"text-primary hover:underline",children:"Privacy Policy"})," ","for full details."]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"12. Contact Us"}),e.jsxs("p",{children:["If you have questions about these Terms, please contact us at"," ",e.jsx("a",{href:"mailto:support@relevelup.com",className:"text-primary hover:underline",children:"support@relevelup.com"})]})]})]})]})})]}),w$t=()=>e.jsxs(e.Fragment,{children:[e.jsxs(el,{children:[e.jsx("title",{children:"Data Deletion | LevelUp"}),e.jsx("meta",{name:"description",content:"Data deletion instructions for LevelUp platform"})]}),e.jsx("div",{className:"min-h-screen bg-background py-12 px-4 sm:px-6 lg:px-8",children:e.jsxs("div",{className:"max-w-3xl mx-auto",children:[e.jsx("h1",{className:"text-3xl font-bold text-foreground mb-8",children:"Data Deletion Instructions"}),e.jsxs("div",{className:"prose prose-sm max-w-none text-muted-foreground space-y-6",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Last updated: January 17, 2026"}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"How to Request Data Deletion"}),e.jsx("p",{children:"If you wish to have your data deleted from LevelUp, you can request deletion through one of the following methods:"})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"Option 1: Email Request"}),e.jsxs("p",{children:["Send an email to"," ",e.jsx("a",{href:"mailto:support@relevelup.com",className:"text-primary hover:underline",children:"support@relevelup.com"})," ",'with the subject line "Data Deletion Request" and include:']}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Your full name"}),e.jsx("li",{children:"The email address associated with your account"}),e.jsx("li",{children:"A clear statement requesting deletion of your data"})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"Option 2: Account Settings"}),e.jsx("p",{children:"If you have an active account, you can request data deletion through your account settings:"}),e.jsxs("ol",{className:"list-decimal pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Log in to your LevelUp account"}),e.jsx("li",{children:"Navigate to your Profile settings"}),e.jsx("li",{children:"Contact support through the Support page to request account deletion"})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"What Data Will Be Deleted"}),e.jsx("p",{children:"Upon a valid deletion request, we will delete:"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Your account information (name, email, profile data)"}),e.jsx("li",{children:"Any content you have created or uploaded"}),e.jsx("li",{children:"Your activity history and preferences"}),e.jsx("li",{children:"Connected social media account tokens and data"})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"Data Retention"}),e.jsx("p",{children:"Some data may be retained for legal or legitimate business purposes, such as:"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Transaction records required for financial reporting"}),e.jsx("li",{children:"Data necessary to comply with legal obligations"}),e.jsx("li",{children:"Anonymized or aggregated data that cannot identify you"})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"Facebook/Instagram Data"}),e.jsx("p",{children:"If you have connected your Facebook or Instagram account to LevelUp, you can also manage your data through Facebook's settings:"}),e.jsxs("ol",{className:"list-decimal pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Go to your Facebook Settings & Privacy → Settings"}),e.jsx("li",{children:'Click on "Apps and Websites"'}),e.jsx("li",{children:'Find LevelUp and click "Remove"'}),e.jsx("li",{children:"This will revoke our access to your Facebook/Instagram data"})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"Processing Time"}),e.jsx("p",{children:"We will process your data deletion request within 30 days of receiving it. You will receive a confirmation email once your data has been deleted."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"Contact Us"}),e.jsxs("p",{children:["If you have questions about data deletion, please contact us at"," ",e.jsx("a",{href:"mailto:support@relevelup.com",className:"text-primary hover:underline",children:"support@relevelup.com"})]})]})]})]})})]}),D7e="I agree to receive recurring SMS/MMS messages from LevelUp Consulting Group, including AI concierge replies, account notifications, service updates, and customer support communications. Message frequency varies. Message & data rates may apply. Reply STOP to opt out at any time, or HELP for assistance.",j$t=yj({name:Ho().trim().min(1,"Name is required").max(200),phone:Ho().trim().min(10,"Enter a valid mobile number").max(30).regex(/^[+\d\s()\-.]+$/,"Enter a valid mobile number"),email:Ho().trim().email("Enter a valid email").max(320).optional().or(ky(""))});function N$t(){const[s,t]=S.useState(""),[r,n]=S.useState(""),[a,i]=S.useState(""),[l,o]=S.useState(!1),[c,d]=S.useState(!1),[h,m]=S.useState(!1),p=async x=>{var b;if(x.preventDefault(),!l){he.error("Please check the consent box to opt in.");return}const y=j$t.safeParse({name:s,phone:r,email:a});if(!y.success){he.error(((b=y.error.issues[0])==null?void 0:b.message)??"Please check your inputs.");return}d(!0);const{error:_}=await V.from("sms_opt_in_consents").insert({name:y.data.name,phone:y.data.phone,email:y.data.email||null,consent_text:D7e,source:"web_form",user_agent:navigator.userAgent.slice(0,500)});if(d(!1),_){he.error("Something went wrong. Please try again.");return}m(!0)};return e.jsxs("div",{className:"min-h-screen bg-gradient-to-br from-background via-background to-muted/30 py-10 px-4",children:[e.jsxs(el,{children:[e.jsx("title",{children:"SMS Opt-In | LevelUp Consulting Group"}),e.jsx("meta",{name:"description",content:"Opt in to receive SMS messages from LevelUp Consulting Group's AI concierge. Review consent terms, message frequency, and STOP/HELP instructions."}),e.jsx("link",{rel:"canonical",href:"https://tile-portal.lovable.app/sms-opt-in"})]}),e.jsxs("div",{className:"max-w-2xl mx-auto",children:[e.jsxs("header",{className:"text-center mb-8",children:[e.jsx("div",{className:"inline-flex items-center justify-center w-14 h-14 rounded-2xl bg-primary/10 text-primary mb-4",children:e.jsx(Gi,{className:"w-7 h-7"})}),e.jsx("h1",{className:"text-3xl md:text-4xl font-bold tracking-tight",children:"LevelUp Consulting Group — SMS Opt-In"}),e.jsx("p",{className:"text-muted-foreground mt-3 max-w-xl mx-auto",children:"Join the LevelUp SMS Concierge. Text our AI assistant from your phone to get help with social posts, listing info, reminders, and more."})]}),h?e.jsxs(ke,{className:"p-8 text-center",children:[e.jsx(ea,{className:"w-14 h-14 text-primary mx-auto mb-4"}),e.jsx("h2",{className:"text-2xl font-semibold mb-2",children:"You're opted in!"}),e.jsxs("p",{className:"text-muted-foreground",children:["Text our concierge at"," ",e.jsx("span",{className:"font-semibold text-foreground",children:"+1 (888) 593-6381"})," ","from your mobile to get started. Reply ",e.jsx("strong",{children:"STOP"})," at any time to opt out, or ",e.jsx("strong",{children:"HELP"})," for assistance."]})]}):e.jsx(ke,{className:"p-6 md:p-8",children:e.jsxs("form",{onSubmit:p,className:"space-y-5",children:[e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"name",children:"Full Name *"}),e.jsx(Se,{id:"name",value:s,onChange:x=>t(x.target.value),required:!0,maxLength:200,autoComplete:"name",className:"mt-1.5"})]}),e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"phone",children:"Mobile Number *"}),e.jsx(Se,{id:"phone",type:"tel",value:r,onChange:x=>n(x.target.value),required:!0,maxLength:30,placeholder:"(555) 123-4567",autoComplete:"tel",className:"mt-1.5"})]}),e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"email",children:"Email (optional)"}),e.jsx(Se,{id:"email",type:"email",value:a,onChange:x=>i(x.target.value),maxLength:320,autoComplete:"email",className:"mt-1.5"})]}),e.jsx("div",{className:"rounded-lg border bg-muted/30 p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(ao,{id:"consent",checked:l,onCheckedChange:x=>o(x===!0),className:"mt-0.5"}),e.jsx(ue,{htmlFor:"consent",className:"text-sm leading-relaxed font-normal cursor-pointer",children:D7e})]})}),e.jsxs("div",{className:"text-xs text-muted-foreground space-y-1",children:[e.jsxs("p",{children:["By submitting, you agree to our"," ",e.jsx(Xn,{to:"/terms-of-service",className:"text-primary underline underline-offset-2",children:"SMS Terms & Conditions"})," ","and"," ",e.jsx(Xn,{to:"/privacy-policy",className:"text-primary underline underline-offset-2",children:"Privacy Policy"}),"."]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Message types:"})," AI concierge replies, account notifications, service updates, customer support."," ",e.jsx("strong",{children:"Frequency:"})," varies."," ",e.jsx("strong",{children:"Msg & data rates may apply."})," ","Reply ",e.jsx("strong",{children:"STOP"})," to opt out, ",e.jsx("strong",{children:"HELP"})," for help."]}),e.jsx("p",{children:"Your mobile phone number and opt-in data will not be shared with or sold to third parties for marketing or promotional purposes."})]}),e.jsx(H,{type:"submit",disabled:!l||c,className:"w-full",size:"lg",children:c?"Submitting…":"Opt in to SMS"}),e.jsxs("div",{className:"flex items-center justify-center gap-2 text-xs text-muted-foreground pt-2",children:[e.jsx(w1,{className:"w-3.5 h-3.5"}),"Secure consent record stored for compliance."]})]})}),e.jsx("footer",{className:"text-center mt-8 text-xs text-muted-foreground",children:e.jsxs("p",{children:["LevelUp Consulting Group · Questions? Email"," ",e.jsx("a",{href:"mailto:support@relevelup.com",className:"text-primary hover:underline",children:"support@relevelup.com"})]})})]})]})}const k$t=yj({email:Ho().email("Invalid email address"),password:Ho().min(6,"Password must be at least 6 characters")}),S$t=()=>{const{signIn:s,user:t}=Ms(),r=Fr(),[n,a]=S.useState(!1),[i,l]=S.useState({}),[o,c]=S.useState(""),[d,h]=S.useState(!1),[m,p]=S.useState(!1);S.useEffect(()=>{if(t){const _=sessionStorage.getItem("redirectAfterLogin")||"/dashboard";sessionStorage.removeItem("redirectAfterLogin"),r(_)}},[t,r]);const x=async _=>{_.preventDefault(),l({}),a(!0);const b=new FormData(_.currentTarget),j=b.get("email"),k=b.get("password");try{k$t.parse({email:j,password:k}),await s(j,k)}catch(T){if(T instanceof M_){const E={};T.errors.forEach(A=>{A.path[0]&&(E[A.path[0]]=A.message)}),l(E)}}finally{a(!1)}},y=async()=>{if(!o){he.error("Please enter your email address");return}h(!0);try{const{error:_}=await V.functions.invoke("send-password-reset",{body:{email:o,redirectTo:"https://dashboard.relevelup.com/profile?reset=true"}});if(_)throw _;he.success("Password reset email sent! Check your inbox."),p(!1),c("")}catch(_){he.error(_.message||"Failed to send reset email")}finally{h(!1)}};return e.jsxs("div",{className:"min-h-screen relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-[#4a6b6d] via-[#3d5a5c] to-[#2a4347]",children:e.jsxs("div",{className:"absolute inset-0 opacity-30",children:[e.jsx("div",{className:"absolute top-0 left-0 w-96 h-96 bg-white/10 rounded-full blur-3xl animate-pulse"}),e.jsx("div",{className:"absolute bottom-0 right-0 w-96 h-96 bg-white/5 rounded-full blur-3xl animate-pulse",style:{animationDelay:"1s"}}),e.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"}})]})}),e.jsxs("div",{className:"relative z-10 flex flex-col min-h-screen",children:[e.jsx("header",{className:"p-6",children:e.jsxs(Xn,{to:"/",className:"inline-flex items-center gap-2 text-sm text-white/80 hover:text-white transition-colors",children:[e.jsx(za,{className:"h-4 w-4"}),"Back to Home"]})}),e.jsx("div",{className:"flex-1 flex items-center justify-center p-4",children:e.jsxs("div",{className:"w-full max-w-md",children:[e.jsx("div",{className:"flex justify-center mb-8",children:e.jsx("div",{className:"bg-white rounded-xl p-4 shadow-2xl",children:e.jsx("img",{src:n5e,alt:"LevelUp",className:"h-12 w-auto"})})}),e.jsxs(ke,{className:"border-0 shadow-2xl bg-white/95 backdrop-blur-sm",children:[e.jsxs(Ot,{className:"space-y-1 text-center pb-4",children:[e.jsx(zt,{className:"text-3xl font-bold text-[#2a4347]",style:{fontFamily:"'Libre Baskerville', serif"},children:"Welcome Back"}),e.jsx(Br,{className:"text-gray-600",children:"Sign in to access your dashboard"})]}),e.jsx(Oe,{children:e.jsxs("form",{onSubmit:x,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"signin-email",className:"text-gray-700",children:"Email"}),e.jsx(Se,{id:"signin-email",name:"email",type:"email",placeholder:"your@email.com",required:!0,className:"border-gray-300 focus:border-[#4a6b6d] focus:ring-[#4a6b6d]"}),i.email&&e.jsx("p",{className:"text-sm text-red-600",children:i.email})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"signin-password",className:"text-gray-700",children:"Password"}),e.jsx(Se,{id:"signin-password",name:"password",type:"password",required:!0,className:"border-gray-300 focus:border-[#4a6b6d] focus:ring-[#4a6b6d]"}),i.password&&e.jsx("p",{className:"text-sm text-red-600",children:i.password})]}),e.jsx(H,{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"}),e.jsxs(bs,{open:m,onOpenChange:p,children:[e.jsx(Qi,{asChild:!0,children:e.jsx(H,{variant:"link",className:"w-full text-sm text-[#4a6b6d] hover:text-[#3d5a5c]",children:"Forgot password?"})}),e.jsxs(vs,{className:"bg-white",children:[e.jsxs(Cs,{children:[e.jsx(Ns,{className:"text-[#2a4347]",style:{fontFamily:"'Libre Baskerville', serif"},children:"Reset Password"}),e.jsx(nn,{className:"text-gray-600",children:"Enter your email address and we'll send you a link to reset your password."})]}),e.jsxs("div",{className:"space-y-4 pt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"reset-email",className:"text-gray-700",children:"Email"}),e.jsx(Se,{id:"reset-email",type:"email",placeholder:"your@email.com",value:o,onChange:_=>c(_.target.value),className:"border-gray-300 focus:border-[#4a6b6d] focus:ring-[#4a6b6d]"})]}),e.jsx(H,{onClick:y,className:"w-full bg-[#4a6b6d] hover:bg-[#3d5a5c] text-white",disabled:d,children:d?"Sending...":"Send Reset Link"})]})]})]})]})})]}),e.jsxs("p",{className:"text-center text-white/70 text-sm mt-6",children:["Don't have an account?"," ",e.jsx(Xn,{to:"/",className:"text-white hover:underline font-medium",children:"View Plans"})]})]})})]})]})},C$t=()=>{const[s]=Ed(),t=s.get("tier"),r=t==null?void 0:t.includes("brokerage");return e.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:e.jsxs(ke,{className:"max-w-lg w-full",children:[e.jsxs(Ot,{className:"text-center",children:[e.jsx("div",{className:"mx-auto w-16 h-16 rounded-full bg-green-500/10 flex items-center justify-center mb-4",children:e.jsx(zi,{className:"w-10 h-10 text-green-500"})}),e.jsx(zt,{className:"text-2xl",children:"Welcome to LevelUp!"}),e.jsx(Br,{className:"text-lg",children:"Your subscription has been activated successfully."})]}),e.jsxs(Oe,{className:"space-y-6",children:[e.jsxs("div",{className:"p-4 rounded-lg bg-primary/10 border border-primary/20 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-primary",children:[e.jsx(er,{className:"w-5 h-5"}),e.jsx("span",{className:"font-semibold",children:"Check your email to sign in"})]}),e.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?e.jsxs("div",{className:"space-y-3",children:[e.jsx("h3",{className:"font-semibold",children:"What's next?"}),e.jsxs("ul",{className:"space-y-2 text-sm text-muted-foreground",children:[e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"font-bold text-primary",children:"1."}),"Click the link in your email to sign in"]}),e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"font-bold text-primary",children:"2."}),"Create and name your brokerage"]}),e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"font-bold text-primary",children:"3."}),"Set your password and complete your profile"]}),e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"font-bold text-primary",children:"4."}),"Start inviting agents to join your team"]})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsx("h3",{className:"font-semibold",children:"What's next?"}),e.jsxs("ul",{className:"space-y-2 text-sm text-muted-foreground",children:[e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"font-bold text-primary",children:"1."}),"Click the link in your email to sign in"]}),e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"font-bold text-primary",children:"2."}),"Set your password and complete your profile"]}),e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"font-bold text-primary",children:"3."}),"Start exploring templates, training videos, and more!"]})]}),e.jsx("p",{className:"text-sm text-green-600 font-medium mt-4",children:"🎉 Your 7-day free trial has started!"})]}),e.jsx("div",{className:"p-3 rounded-lg bg-muted/50 text-center",children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"Didn't receive the email? Check your spam folder or contact support."})})]})]})})},Kat=s=>{const[t,r]=S.useState(null),[n,a]=S.useState(!0);return S.useEffect(()=>{if(!s){a(!1);return}(async()=>{try{const{data:o}=await V.storage.from("avatars").list(`${s}`);if(o&&o.length>0){const{data:c}=V.storage.from("avatars").getPublicUrl(`${s}/${o[0].name}`);r(`${c.publicUrl}?t=${Date.now()}`)}else r(null)}catch(o){console.error("Error fetching avatar:",o),r(null)}finally{a(!1)}})()},[s]),{avatarUrl:t,loading:n,refreshAvatar:async()=>{if(s)try{const{data:l}=await V.storage.from("avatars").list(`${s}`);if(l&&l.length>0){const{data:o}=V.storage.from("avatars").getPublicUrl(`${s}/${l[0].name}`);r(`${o.publicUrl}?t=${Date.now()}`)}}catch(l){console.error("Error refreshing avatar:",l)}}}},Yat=async s=>{const t=new Map;return await Promise.all(s.map(async r=>{try{const{data:n}=await V.storage.from("avatars").list(`${r}`);if(n&&n.length>0){const{data:a}=V.storage.from("avatars").getPublicUrl(`${r}/${n[0].name}`);t.set(r,a.publicUrl)}}catch{}})),t},T$t=s=>{const[t,r]=S.useState({isTrial:!1,isExpired:!1,expiresAt:null,daysLeft:null,loading:!0});return S.useEffect(()=>{if(!s){r(a=>({...a,loading:!1}));return}(async()=>{try{const{data:a,error:i}=await V.from("profiles").select("is_trial, trial_expires_at, subscription_status, subscription_end_date").eq("id",s).single();if(i){console.error("Error fetching trial status:",i),r(m=>({...m,loading:!1}));return}const l=(a==null?void 0:a.subscription_status)==="trialing",o=!!(a!=null&&a.is_trial),c=!!(a!=null&&a.trial_expires_at)&&new Date(a.trial_expires_at).getTime()>Date.now()&&(a==null?void 0:a.subscription_status)!=="active",d=l&&(a==null?void 0:a.subscription_end_date)||(a==null?void 0:a.trial_expires_at)||(a==null?void 0:a.subscription_end_date)||null;if((l||o||c)&&!!d&&d){const m=new Date().getTime(),p=new Date(d).getTime(),x=Math.ceil((p-m)/(1e3*60*60*24)),y=x<=0;r({isTrial:!0,isExpired:y,expiresAt:d,daysLeft:y?0:x,loading:!1})}else r({isTrial:!1,isExpired:!1,expiresAt:null,daysLeft:null,loading:!1})}catch(a){console.error("Error in useTrialStatus:",a),r(i=>({...i,loading:!1}))}})()},[s]),t},Zat=()=>{const{data:s,isLoading:t}=yt({queryKey:["feature-flags"],queryFn:async()=>{const{data:n,error:a}=await V.from("feature_flags").select("*");if(a)throw a;return n}}),r=n=>{if(!s)return!1;const a=s.find(i=>i.key===n);return(a==null?void 0:a.enabled)??!1};return{flags:s,isLoading:t,isFeatureEnabled:r,isAgentOSEnabled:r("agent_os_enabled"),isInnerCircleEnabled:r("innercircle_enabled"),isMarketplaceEnabled:r("marketplace")}},R7e="community_last_seen_post_at";function E$t(){const{user:s}=Ms(),t=Vc(),[r,n]=S.useState(0),[a,i]=S.useState(null);S.useEffect(()=>{if(!s)return;const o=localStorage.getItem(`${R7e}_${s.id}`);i(o)},[s]),S.useEffect(()=>{if(!s)return;const o=`community_unread_count_${s.id}`,c=2*60*1e3;(async()=>{try{const x=sessionStorage.getItem(o);if(x){const y=JSON.parse(x);if(y.ts&&Date.now()-y.ts{if(!s)return;const o=V.channel("community-new-posts").on("postgres_changes",{event:"INSERT",schema:"public",table:"community_posts"},async c=>{const d=c.new;if(d.user_id===s.id)return;const h=t.pathname==="/community";h||n(_=>_+1);const{data:m}=await V.from("profiles").select("name").eq("id",d.user_id).single(),p=(m==null?void 0:m.name)||"Someone",x=d.content.replace(/@\[([^\]]+)\]\([^)]+\)/g,"@$1"),y=x.length>50?x.substring(0,50)+"...":x;h||he("New Community Post",{description:`${p}: ${y}`,action:{label:"View",onClick:()=>{window.location.href="/community"}}})}).subscribe();return()=>{V.removeChannel(o)}},[s,t.pathname]);const l=S.useCallback(()=>{if(!s)return;const o=new Date().toISOString();localStorage.setItem(`${R7e}_${s.id}`,o),i(o),n(0)},[s]);return S.useEffect(()=>{t.pathname==="/community"&&r>0&&l()},[t.pathname,r,l]),{unreadCount:r,markAsRead:l}}function A$t(){const{isAdmin:s}=Ms(),{data:t=0}=yt({queryKey:["wishlist-open-count"],queryFn:async()=>{const{count:r,error:n}=await V.from("wishlist_items").select("*",{count:"exact",head:!0}).eq("status","open");if(n)throw n;return r||0},enabled:s,staleTime:6e4});return{openCount:s?t:0}}var zge="Collapsible",[M$t,FZs]=_u(zge),[I$t,sTe]=M$t(zge),Xat=S.forwardRef((s,t)=>{const{__scopeCollapsible:r,open:n,defaultOpen:a,disabled:i,onOpenChange:l,...o}=s,[c,d]=af({prop:n,defaultProp:a??!1,onChange:l,caller:zge});return e.jsx(I$t,{scope:r,disabled:i,contentId:vm(),open:c,onOpenToggle:S.useCallback(()=>d(h=>!h),[d]),children:e.jsx(Vn.div,{"data-state":nTe(c),"data-disabled":i?"":void 0,...o,ref:t})})});Xat.displayName=zge;var Qat="CollapsibleTrigger",Jat=S.forwardRef((s,t)=>{const{__scopeCollapsible:r,...n}=s,a=sTe(Qat,r);return e.jsx(Vn.button,{type:"button","aria-controls":a.contentId,"aria-expanded":a.open||!1,"data-state":nTe(a.open),"data-disabled":a.disabled?"":void 0,disabled:a.disabled,...n,ref:t,onClick:an(s.onClick,a.onOpenToggle)})});Jat.displayName=Qat;var rTe="CollapsibleContent",eit=S.forwardRef((s,t)=>{const{forceMount:r,...n}=s,a=sTe(rTe,s.__scopeCollapsible);return e.jsx(vh,{present:r||a.open,children:({present:i})=>e.jsx(P$t,{...n,ref:t,present:i})})});eit.displayName=rTe;var P$t=S.forwardRef((s,t)=>{const{__scopeCollapsible:r,present:n,children:a,...i}=s,l=sTe(rTe,r),[o,c]=S.useState(n),d=S.useRef(null),h=_i(t,d),m=S.useRef(0),p=m.current,x=S.useRef(0),y=x.current,_=l.open||o,b=S.useRef(_),j=S.useRef(void 0);return S.useEffect(()=>{const k=requestAnimationFrame(()=>b.current=!1);return()=>cancelAnimationFrame(k)},[]),Ku(()=>{const k=d.current;if(k){j.current=j.current||{transitionDuration:k.style.transitionDuration,animationName:k.style.animationName},k.style.transitionDuration="0s",k.style.animationName="none";const T=k.getBoundingClientRect();m.current=T.height,x.current=T.width,b.current||(k.style.transitionDuration=j.current.transitionDuration,k.style.animationName=j.current.animationName),c(n)}},[l.open,n]),e.jsx(Vn.div,{"data-state":nTe(l.open),"data-disabled":l.disabled?"":void 0,id:l.contentId,hidden:!_,...i,ref:h,style:{"--radix-collapsible-content-height":p?`${p}px`:void 0,"--radix-collapsible-content-width":y?`${y}px`:void 0,...s.style},children:_&&a})});function nTe(s){return s?"open":"closed"}var L$t=Xat;const m0=L$t,f0=Jat,p0=eit,D$t="/assets/levelup-logo-Eif24dqY.png",R$t="/assets/levelup-logo-icon-C-7iromj.png",O$t="/assets/levelup-logo-mobile-B9skSjUG.png";var az=s=>s.type==="checkbox",BT=s=>s instanceof Date,lg=s=>s==null;const tit=s=>typeof s=="object";var yh=s=>!lg(s)&&!Array.isArray(s)&&tit(s)&&!BT(s),sit=s=>yh(s)&&s.target?az(s.target)?s.target.checked:s.target.value:s,F$t=s=>s.substring(0,s.search(/\.\d+(\.|$)/))||s,rit=(s,t)=>s.has(F$t(t)),B$t=s=>{const t=s.constructor&&s.constructor.prototype;return yh(t)&&t.hasOwnProperty("isPrototypeOf")},aTe=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function tm(s){let t;const r=Array.isArray(s),n=typeof FileList<"u"?s instanceof FileList:!1;if(s instanceof Date)t=new Date(s);else if(!(aTe&&(s instanceof Blob||n))&&(r||yh(s)))if(t=r?[]:{},!r&&!B$t(s))t=s;else for(const a in s)s.hasOwnProperty(a)&&(t[a]=tm(s[a]));else return s;return t}var $ge=s=>/^\w*$/.test(s),oh=s=>s===void 0,iTe=s=>Array.isArray(s)?s.filter(Boolean):[],oTe=s=>iTe(s.replace(/["|']|\]/g,"").split(/\.|\[/)),xa=(s,t,r)=>{if(!t||!yh(s))return r;const n=($ge(t)?[t]:oTe(t)).reduce((a,i)=>lg(a)?a:a[i],s);return oh(n)||n===s?oh(s[t])?r:s[t]:n},Qx=s=>typeof s=="boolean",dc=(s,t,r)=>{let n=-1;const a=$ge(t)?[t]:oTe(t),i=a.length,l=i-1;for(;++nNt.useContext(lTe),z$t=s=>{const{children:t,...r}=s;return Nt.createElement(lTe.Provider,{value:r},t)};var nit=(s,t,r,n=!0)=>{const a={defaultValues:t._defaultValues};for(const i in s)Object.defineProperty(a,i,{get:()=>{const l=i;return t._proxyFormState[l]!==o1.all&&(t._proxyFormState[l]=!n||o1.all),r&&(r[l]=!0),s[l]}});return a};const cTe=typeof window<"u"?Nt.useLayoutEffect:Nt.useEffect;function $$t(s){const t=Uge(),{control:r=t.control,disabled:n,name:a,exact:i}=s||{},[l,o]=Nt.useState(r._formState),c=Nt.useRef({isDirty:!1,isLoading:!1,dirtyFields:!1,touchedFields:!1,validatingFields:!1,isValidating:!1,isValid:!1,errors:!1});return cTe(()=>r._subscribe({name:a,formState:c.current,exact:i,callback:d=>{!n&&o({...r._formState,...d})}}),[a,n,i]),Nt.useEffect(()=>{c.current.isValid&&r._setValid(!0)},[r]),Nt.useMemo(()=>nit(l,r,c.current,!1),[l,r])}var s_=s=>typeof s=="string",ait=(s,t,r,n,a)=>s_(s)?(n&&t.watch.add(s),xa(r,s,a)):Array.isArray(s)?s.map(i=>(n&&t.watch.add(i),xa(r,i))):(n&&(t.watchAll=!0),r),RNe=s=>lg(s)||!tit(s);function S2(s,t,r=new WeakSet){if(RNe(s)||RNe(t))return s===t;if(BT(s)&&BT(t))return s.getTime()===t.getTime();const n=Object.keys(s),a=Object.keys(t);if(n.length!==a.length)return!1;if(r.has(s)||r.has(t))return!0;r.add(s),r.add(t);for(const i of n){const l=s[i];if(!a.includes(i))return!1;if(i!=="ref"){const o=t[i];if(BT(l)&&BT(o)||yh(l)&&yh(o)||Array.isArray(l)&&Array.isArray(o)?!S2(l,o,r):l!==o)return!1}}return!0}function U$t(s){const t=Uge(),{control:r=t.control,name:n,defaultValue:a,disabled:i,exact:l,compute:o}=s||{},c=Nt.useRef(a),d=Nt.useRef(o),h=Nt.useRef(void 0);d.current=o;const m=Nt.useMemo(()=>r._getWatch(n,c.current),[r,n]),[p,x]=Nt.useState(d.current?d.current(m):m);return cTe(()=>r._subscribe({name:n,formState:{values:!0},exact:l,callback:y=>{if(!i){const _=ait(n,r._names,y.values||r._formValues,!1,c.current);if(d.current){const b=d.current(_);S2(b,h.current)||(x(b),h.current=b)}else x(_)}}}),[r,i,n,l]),Nt.useEffect(()=>r._removeUnmounted()),p}function q$t(s){const t=Uge(),{name:r,disabled:n,control:a=t.control,shouldUnregister:i,defaultValue:l}=s,o=rit(a._names.array,r),c=Nt.useMemo(()=>xa(a._formValues,r,xa(a._defaultValues,r,l)),[a,r,l]),d=U$t({control:a,name:r,defaultValue:c,exact:!0}),h=$$t({control:a,name:r,exact:!0}),m=Nt.useRef(s),p=Nt.useRef(a.register(r,{...s.rules,value:d,...Qx(s.disabled)?{disabled:s.disabled}:{}}));m.current=s;const x=Nt.useMemo(()=>Object.defineProperties({},{invalid:{enumerable:!0,get:()=>!!xa(h.errors,r)},isDirty:{enumerable:!0,get:()=>!!xa(h.dirtyFields,r)},isTouched:{enumerable:!0,get:()=>!!xa(h.touchedFields,r)},isValidating:{enumerable:!0,get:()=>!!xa(h.validatingFields,r)},error:{enumerable:!0,get:()=>xa(h.errors,r)}}),[h,r]),y=Nt.useCallback(k=>p.current.onChange({target:{value:sit(k),name:r},type:Qhe.CHANGE}),[r]),_=Nt.useCallback(()=>p.current.onBlur({target:{value:xa(a._formValues,r),name:r},type:Qhe.BLUR}),[r,a._formValues]),b=Nt.useCallback(k=>{const T=xa(a._fields,r);T&&k&&(T._f.ref={focus:()=>k.focus&&k.focus(),select:()=>k.select&&k.select(),setCustomValidity:E=>k.setCustomValidity(E),reportValidity:()=>k.reportValidity()})},[a._fields,r]),j=Nt.useMemo(()=>({name:r,value:d,...Qx(n)||h.disabled?{disabled:h.disabled||n}:{},onChange:y,onBlur:_,ref:b}),[r,n,h.disabled,y,_,b,d]);return Nt.useEffect(()=>{const k=a._options.shouldUnregister||i;a.register(r,{...m.current.rules,...Qx(m.current.disabled)?{disabled:m.current.disabled}:{}});const T=(E,A)=>{const D=xa(a._fields,E);D&&D._f&&(D._f.mount=A)};if(T(r,!0),k){const E=tm(xa(a._options.defaultValues,r));dc(a._defaultValues,r,E),oh(xa(a._formValues,r))&&dc(a._formValues,r,E)}return!o&&a.register(r),()=>{(o?k&&!a._state.action:k)?a.unregister(r):T(r,!1)}},[r,a,o,i]),Nt.useEffect(()=>{a._setDisabledField({disabled:n,name:r})},[n,r,a]),Nt.useMemo(()=>({field:j,formState:h,fieldState:x}),[j,h,x])}const V$t=s=>s.render(q$t(s));var iit=(s,t,r,n,a)=>t?{...r[s],types:{...r[s]&&r[s].types?r[s].types:{},[n]:a||!0}}:{},t7=s=>Array.isArray(s)?s:[s],O7e=()=>{let s=[];return{get observers(){return s},next:a=>{for(const i of s)i.next&&i.next(a)},subscribe:a=>(s.push(a),{unsubscribe:()=>{s=s.filter(i=>i!==a)}}),unsubscribe:()=>{s=[]}}},Kg=s=>yh(s)&&!Object.keys(s).length,dTe=s=>s.type==="file",l1=s=>typeof s=="function",Jhe=s=>{if(!aTe)return!1;const t=s?s.ownerDocument:0;return s instanceof(t&&t.defaultView?t.defaultView.HTMLElement:HTMLElement)},oit=s=>s.type==="select-multiple",uTe=s=>s.type==="radio",H$t=s=>uTe(s)||az(s),Sbe=s=>Jhe(s)&&s.isConnected;function G$t(s,t){const r=t.slice(0,-1).length;let n=0;for(;n{for(const t in s)if(l1(s[t]))return!0;return!1};function eme(s,t={}){const r=Array.isArray(s);if(yh(s)||r)for(const n in s)Array.isArray(s[n])||yh(s[n])&&!lit(s[n])?(t[n]=Array.isArray(s[n])?[]:{},eme(s[n],t[n])):lg(s[n])||(t[n]=!0);return t}function cit(s,t,r){const n=Array.isArray(s);if(yh(s)||n)for(const a in s)Array.isArray(s[a])||yh(s[a])&&!lit(s[a])?oh(t)||RNe(r[a])?r[a]=Array.isArray(s[a])?eme(s[a],[]):{...eme(s[a])}:cit(s[a],lg(t)?{}:t[a],r[a]):r[a]=!S2(s[a],t[a]);return r}var ER=(s,t)=>cit(s,t,eme(t));const F7e={value:!1,isValid:!1},B7e={value:!0,isValid:!0};var dit=s=>{if(Array.isArray(s)){if(s.length>1){const t=s.filter(r=>r&&r.checked&&!r.disabled).map(r=>r.value);return{value:t,isValid:!!t.length}}return s[0].checked&&!s[0].disabled?s[0].attributes&&!oh(s[0].attributes.value)?oh(s[0].value)||s[0].value===""?B7e:{value:s[0].value,isValid:!0}:B7e:F7e}return F7e},uit=(s,{valueAsNumber:t,valueAsDate:r,setValueAs:n})=>oh(s)?s:t?s===""?NaN:s&&+s:r&&s_(s)?new Date(s):n?n(s):s;const z7e={isValid:!1,value:null};var hit=s=>Array.isArray(s)?s.reduce((t,r)=>r&&r.checked&&!r.disabled?{isValid:!0,value:r.value}:t,z7e):z7e;function $7e(s){const t=s.ref;return dTe(t)?t.files:uTe(t)?hit(s.refs).value:oit(t)?[...t.selectedOptions].map(({value:r})=>r):az(t)?dit(s.refs).value:uit(oh(t.value)?s.ref.value:t.value,s)}var K$t=(s,t,r,n)=>{const a={};for(const i of s){const l=xa(t,i);l&&dc(a,i,l._f)}return{criteriaMode:r,names:[...s],fields:a,shouldUseNativeValidation:n}},tme=s=>s instanceof RegExp,AR=s=>oh(s)?s:tme(s)?s.source:yh(s)?tme(s.value)?s.value.source:s.value:s,U7e=s=>({isOnSubmit:!s||s===o1.onSubmit,isOnBlur:s===o1.onBlur,isOnChange:s===o1.onChange,isOnAll:s===o1.all,isOnTouch:s===o1.onTouched});const q7e="AsyncFunction";var Y$t=s=>!!s&&!!s.validate&&!!(l1(s.validate)&&s.validate.constructor.name===q7e||yh(s.validate)&&Object.values(s.validate).find(t=>t.constructor.name===q7e)),Z$t=s=>s.mount&&(s.required||s.min||s.max||s.maxLength||s.minLength||s.pattern||s.validate),V7e=(s,t,r)=>!r&&(t.watchAll||t.watch.has(s)||[...t.watch].some(n=>s.startsWith(n)&&/^\.\w+/.test(s.slice(n.length))));const s7=(s,t,r,n)=>{for(const a of r||Object.keys(s)){const i=xa(s,a);if(i){const{_f:l,...o}=i;if(l){if(l.refs&&l.refs[0]&&t(l.refs[0],a)&&!n)return!0;if(l.ref&&t(l.ref,l.name)&&!n)return!0;if(s7(o,t))break}else if(yh(o)&&s7(o,t))break}}};function H7e(s,t,r){const n=xa(s,r);if(n||$ge(r))return{error:n,name:r};const a=r.split(".");for(;a.length;){const i=a.join("."),l=xa(t,i),o=xa(s,i);if(l&&!Array.isArray(l)&&r!==i)return{name:r};if(o&&o.type)return{name:i,error:o};if(o&&o.root&&o.root.type)return{name:`${i}.root`,error:o.root};a.pop()}return{name:r}}var X$t=(s,t,r,n)=>{r(s);const{name:a,...i}=s;return Kg(i)||Object.keys(i).length>=Object.keys(t).length||Object.keys(i).find(l=>t[l]===(!n||o1.all))},Q$t=(s,t,r)=>!s||!t||s===t||t7(s).some(n=>n&&(r?n===t:n.startsWith(t)||t.startsWith(n))),J$t=(s,t,r,n,a)=>a.isOnAll?!1:!r&&a.isOnTouch?!(t||s):(r?n.isOnBlur:a.isOnBlur)?!s:(r?n.isOnChange:a.isOnChange)?s:!0,eUt=(s,t)=>!iTe(xa(s,t)).length&&Eh(s,t),tUt=(s,t,r)=>{const n=t7(xa(s,r));return dc(n,"root",t[r]),dc(s,r,n),s},wue=s=>s_(s);function G7e(s,t,r="validate"){if(wue(s)||Array.isArray(s)&&s.every(wue)||Qx(s)&&!s)return{type:r,message:wue(s)?s:"",ref:t}}var h6=s=>yh(s)&&!tme(s)?s:{value:s,message:""},W7e=async(s,t,r,n,a,i)=>{const{ref:l,refs:o,required:c,maxLength:d,minLength:h,min:m,max:p,pattern:x,validate:y,name:_,valueAsNumber:b,mount:j}=s._f,k=xa(r,_);if(!j||t.has(_))return{};const T=o?o[0]:l,E=Z=>{a&&T.reportValidity&&(T.setCustomValidity(Qx(Z)?"":Z||""),T.reportValidity())},A={},D=uTe(l),R=az(l),z=D||R,O=(b||dTe(l))&&oh(l.value)&&oh(k)||Jhe(l)&&l.value===""||k===""||Array.isArray(k)&&!k.length,$=iit.bind(null,_,n,A),ee=(Z,J,K,re=Jw.maxLength,ie=Jw.minLength)=>{const ce=Z?J:K;A[_]={type:Z?re:ie,message:ce,ref:l,...$(Z?re:ie,ce)}};if(i?!Array.isArray(k)||!k.length:c&&(!z&&(O||lg(k))||Qx(k)&&!k||R&&!dit(o).isValid||D&&!hit(o).isValid)){const{value:Z,message:J}=wue(c)?{value:!!c,message:c}:h6(c);if(Z&&(A[_]={type:Jw.required,message:J,ref:T,...$(Jw.required,J)},!n))return E(J),A}if(!O&&(!lg(m)||!lg(p))){let Z,J;const K=h6(p),re=h6(m);if(!lg(k)&&!isNaN(k)){const ie=l.valueAsNumber||k&&+k;lg(K.value)||(Z=ie>K.value),lg(re.value)||(J=ienew Date(new Date().toDateString()+" "+be),ne=l.type=="time",le=l.type=="week";s_(K.value)&&k&&(Z=ne?ce(k)>ce(K.value):le?k>K.value:ie>new Date(K.value)),s_(re.value)&&k&&(J=ne?ce(k)+Z.value,re=!lg(J.value)&&k.length<+J.value;if((K||re)&&(ee(K,Z.message,J.message),!n))return E(A[_].message),A}if(x&&!O&&s_(k)){const{value:Z,message:J}=h6(x);if(tme(Z)&&!k.match(Z)&&(A[_]={type:Jw.pattern,message:J,ref:l,...$(Jw.pattern,J)},!n))return E(J),A}if(y){if(l1(y)){const Z=await y(k,r),J=G7e(Z,T);if(J&&(A[_]={...J,...$(Jw.validate,J.message)},!n))return E(J.message),A}else if(yh(y)){let Z={};for(const J in y){if(!Kg(Z)&&!n)break;const K=G7e(await y[J](k,r),T,J);K&&(Z={...K,...$(J,K.message)},E(K.message),n&&(A[_]=Z))}if(!Kg(Z)&&(A[_]={ref:T,...Z},!n))return A}}return E(!0),A};const sUt={mode:o1.onSubmit,reValidateMode:o1.onChange,shouldFocusError:!0};function rUt(s={}){let t={...sUt,...s},r={submitCount:0,isDirty:!1,isReady:!1,isLoading:l1(t.defaultValues),isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},validatingFields:{},errors:t.errors||{},disabled:t.disabled||!1},n={},a=yh(t.defaultValues)||yh(t.values)?tm(t.defaultValues||t.values)||{}:{},i=t.shouldUnregister?{}:tm(a),l={action:!1,mount:!1,watch:!1},o={mount:new Set,disabled:new Set,unMount:new Set,array:new Set,watch:new Set},c,d=0;const h={isDirty:!1,dirtyFields:!1,validatingFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1};let m={...h};const p={array:O7e(),state:O7e()},x=t.criteriaMode===o1.all,y=$e=>it=>{clearTimeout(d),d=setTimeout($e,it)},_=async $e=>{if(!t.disabled&&(h.isValid||m.isValid||$e)){const it=t.resolver?Kg((await R()).errors):await O(n,!0);it!==r.isValid&&p.state.next({isValid:it})}},b=($e,it)=>{!t.disabled&&(h.isValidating||h.validatingFields||m.isValidating||m.validatingFields)&&(($e||Array.from(o.mount)).forEach(Je=>{Je&&(it?dc(r.validatingFields,Je,it):Eh(r.validatingFields,Je))}),p.state.next({validatingFields:r.validatingFields,isValidating:!Kg(r.validatingFields)}))},j=($e,it=[],Je,st,mt=!0,wt=!0)=>{if(st&&Je&&!t.disabled){if(l.action=!0,wt&&Array.isArray(xa(n,$e))){const at=Je(xa(n,$e),st.argA,st.argB);mt&&dc(n,$e,at)}if(wt&&Array.isArray(xa(r.errors,$e))){const at=Je(xa(r.errors,$e),st.argA,st.argB);mt&&dc(r.errors,$e,at),eUt(r.errors,$e)}if((h.touchedFields||m.touchedFields)&&wt&&Array.isArray(xa(r.touchedFields,$e))){const at=Je(xa(r.touchedFields,$e),st.argA,st.argB);mt&&dc(r.touchedFields,$e,at)}(h.dirtyFields||m.dirtyFields)&&(r.dirtyFields=ER(a,i)),p.state.next({name:$e,isDirty:ee($e,it),dirtyFields:r.dirtyFields,errors:r.errors,isValid:r.isValid})}else dc(i,$e,it)},k=($e,it)=>{dc(r.errors,$e,it),p.state.next({errors:r.errors})},T=$e=>{r.errors=$e,p.state.next({errors:r.errors,isValid:!1})},E=($e,it,Je,st)=>{const mt=xa(n,$e);if(mt){const wt=xa(i,$e,oh(Je)?xa(a,$e):Je);oh(wt)||st&&st.defaultChecked||it?dc(i,$e,it?wt:$7e(mt._f)):K($e,wt),l.mount&&_()}},A=($e,it,Je,st,mt)=>{let wt=!1,at=!1;const rt={name:$e};if(!t.disabled){if(!Je||st){(h.isDirty||m.isDirty)&&(at=r.isDirty,r.isDirty=rt.isDirty=ee(),wt=at!==rt.isDirty);const Et=S2(xa(a,$e),it);at=!!xa(r.dirtyFields,$e),Et?Eh(r.dirtyFields,$e):dc(r.dirtyFields,$e,!0),rt.dirtyFields=r.dirtyFields,wt=wt||(h.dirtyFields||m.dirtyFields)&&at!==!Et}if(Je){const Et=xa(r.touchedFields,$e);Et||(dc(r.touchedFields,$e,Je),rt.touchedFields=r.touchedFields,wt=wt||(h.touchedFields||m.touchedFields)&&Et!==Je)}wt&&mt&&p.state.next(rt)}return wt?rt:{}},D=($e,it,Je,st)=>{const mt=xa(r.errors,$e),wt=(h.isValid||m.isValid)&&Qx(it)&&r.isValid!==it;if(t.delayError&&Je?(c=y(()=>k($e,Je)),c(t.delayError)):(clearTimeout(d),c=null,Je?dc(r.errors,$e,Je):Eh(r.errors,$e)),(Je?!S2(mt,Je):mt)||!Kg(st)||wt){const at={...st,...wt&&Qx(it)?{isValid:it}:{},errors:r.errors,name:$e};r={...r,...at},p.state.next(at)}},R=async $e=>{b($e,!0);const it=await t.resolver(i,t.context,K$t($e||o.mount,n,t.criteriaMode,t.shouldUseNativeValidation));return b($e),it},z=async $e=>{const{errors:it}=await R($e);if($e)for(const Je of $e){const st=xa(it,Je);st?dc(r.errors,Je,st):Eh(r.errors,Je)}else r.errors=it;return it},O=async($e,it,Je={valid:!0})=>{for(const st in $e){const mt=$e[st];if(mt){const{_f:wt,...at}=mt;if(wt){const rt=o.array.has(wt.name),Et=mt._f&&Y$t(mt._f);Et&&h.validatingFields&&b([st],!0);const hs=await W7e(mt,o.disabled,i,x,t.shouldUseNativeValidation&&!it,rt);if(Et&&h.validatingFields&&b([st]),hs[wt.name]&&(Je.valid=!1,it))break;!it&&(xa(hs,wt.name)?rt?tUt(r.errors,hs,wt.name):dc(r.errors,wt.name,hs[wt.name]):Eh(r.errors,wt.name))}!Kg(at)&&await O(at,it,Je)}}return Je.valid},$=()=>{for(const $e of o.unMount){const it=xa(n,$e);it&&(it._f.refs?it._f.refs.every(Je=>!Sbe(Je)):!Sbe(it._f.ref))&&Me($e)}o.unMount=new Set},ee=($e,it)=>!t.disabled&&($e&&it&&dc(i,$e,it),!S2(be(),a)),Z=($e,it,Je)=>ait($e,o,{...l.mount?i:oh(it)?a:s_($e)?{[$e]:it}:it},Je,it),J=$e=>iTe(xa(l.mount?i:a,$e,t.shouldUnregister?xa(a,$e,[]):[])),K=($e,it,Je={})=>{const st=xa(n,$e);let mt=it;if(st){const wt=st._f;wt&&(!wt.disabled&&dc(i,$e,uit(it,wt)),mt=Jhe(wt.ref)&&lg(it)?"":it,oit(wt.ref)?[...wt.ref.options].forEach(at=>at.selected=mt.includes(at.value)):wt.refs?az(wt.ref)?wt.refs.forEach(at=>{(!at.defaultChecked||!at.disabled)&&(Array.isArray(mt)?at.checked=!!mt.find(rt=>rt===at.value):at.checked=mt===at.value||!!mt)}):wt.refs.forEach(at=>at.checked=at.value===mt):dTe(wt.ref)?wt.ref.value="":(wt.ref.value=mt,wt.ref.type||p.state.next({name:$e,values:tm(i)})))}(Je.shouldDirty||Je.shouldTouch)&&A($e,mt,Je.shouldTouch,Je.shouldDirty,!0),Je.shouldValidate&&le($e)},re=($e,it,Je)=>{for(const st in it){if(!it.hasOwnProperty(st))return;const mt=it[st],wt=$e+"."+st,at=xa(n,wt);(o.array.has($e)||yh(mt)||at&&!at._f)&&!BT(mt)?re(wt,mt,Je):K(wt,mt,Je)}},ie=($e,it,Je={})=>{const st=xa(n,$e),mt=o.array.has($e),wt=tm(it);dc(i,$e,wt),mt?(p.array.next({name:$e,values:tm(i)}),(h.isDirty||h.dirtyFields||m.isDirty||m.dirtyFields)&&Je.shouldDirty&&p.state.next({name:$e,dirtyFields:ER(a,i),isDirty:ee($e,wt)})):st&&!st._f&&!lg(wt)?re($e,wt,Je):K($e,wt,Je),V7e($e,o)&&p.state.next({...r,name:$e}),p.state.next({name:l.mount?$e:void 0,values:tm(i)})},ce=async $e=>{l.mount=!0;const it=$e.target;let Je=it.name,st=!0;const mt=xa(n,Je),wt=Et=>{st=Number.isNaN(Et)||BT(Et)&&isNaN(Et.getTime())||S2(Et,xa(i,Je,Et))},at=U7e(t.mode),rt=U7e(t.reValidateMode);if(mt){let Et,hs;const Is=it.type?$7e(mt._f):sit($e),lr=$e.type===Qhe.BLUR||$e.type===Qhe.FOCUS_OUT,us=!Z$t(mt._f)&&!t.resolver&&!xa(r.errors,Je)&&!mt._f.deps||J$t(lr,xa(r.touchedFields,Je),r.isSubmitted,rt,at),St=V7e(Je,o,lr);dc(i,Je,Is),lr?(mt._f.onBlur&&mt._f.onBlur($e),c&&c(0)):mt._f.onChange&&mt._f.onChange($e);const xs=A(Je,Is,lr),kt=!Kg(xs)||St;if(!lr&&p.state.next({name:Je,type:$e.type,values:tm(i)}),us)return(h.isValid||m.isValid)&&(t.mode==="onBlur"?lr&&_():lr||_()),kt&&p.state.next({name:Je,...St?{}:xs});if(!lr&&St&&p.state.next({...r}),t.resolver){const{errors:fs}=await R([Je]);if(wt(Is),st){const Gs=H7e(r.errors,n,Je),_s=H7e(fs,n,Gs.name||Je);Et=_s.error,Je=_s.name,hs=Kg(fs)}}else b([Je],!0),Et=(await W7e(mt,o.disabled,i,x,t.shouldUseNativeValidation))[Je],b([Je]),wt(Is),st&&(Et?hs=!1:(h.isValid||m.isValid)&&(hs=await O(n,!0)));st&&(mt._f.deps&&le(mt._f.deps),D(Je,hs,Et,xs))}},ne=($e,it)=>{if(xa(r.errors,it)&&$e.focus)return $e.focus(),1},le=async($e,it={})=>{let Je,st;const mt=t7($e);if(t.resolver){const wt=await z(oh($e)?$e:mt);Je=Kg(wt),st=$e?!mt.some(at=>xa(wt,at)):Je}else $e?(st=(await Promise.all(mt.map(async wt=>{const at=xa(n,wt);return await O(at&&at._f?{[wt]:at}:at)}))).every(Boolean),!(!st&&!r.isValid)&&_()):st=Je=await O(n);return p.state.next({...!s_($e)||(h.isValid||m.isValid)&&Je!==r.isValid?{}:{name:$e},...t.resolver||!$e?{isValid:Je}:{},errors:r.errors}),it.shouldFocus&&!st&&s7(n,ne,$e?mt:o.mount),st},be=$e=>{const it={...l.mount?i:a};return oh($e)?it:s_($e)?xa(it,$e):$e.map(Je=>xa(it,Je))},fe=($e,it)=>({invalid:!!xa((it||r).errors,$e),isDirty:!!xa((it||r).dirtyFields,$e),error:xa((it||r).errors,$e),isValidating:!!xa(r.validatingFields,$e),isTouched:!!xa((it||r).touchedFields,$e)}),je=$e=>{$e&&t7($e).forEach(it=>Eh(r.errors,it)),p.state.next({errors:$e?r.errors:{}})},ve=($e,it,Je)=>{const st=(xa(n,$e,{_f:{}})._f||{}).ref,mt=xa(r.errors,$e)||{},{ref:wt,message:at,type:rt,...Et}=mt;dc(r.errors,$e,{...Et,...it,ref:st}),p.state.next({name:$e,errors:r.errors,isValid:!1}),Je&&Je.shouldFocus&&st&&st.focus&&st.focus()},We=($e,it)=>l1($e)?p.state.subscribe({next:Je=>"values"in Je&&$e(Z(void 0,it),Je)}):Z($e,it,!0),Ve=$e=>p.state.subscribe({next:it=>{Q$t($e.name,it.name,$e.exact)&&X$t(it,$e.formState||h,et,$e.reRenderRoot)&&$e.callback({values:{...i},...r,...it,defaultValues:a})}}).unsubscribe,Le=$e=>(l.mount=!0,m={...m,...$e.formState},Ve({...$e,formState:m})),Me=($e,it={})=>{for(const Je of $e?t7($e):o.mount)o.mount.delete(Je),o.array.delete(Je),it.keepValue||(Eh(n,Je),Eh(i,Je)),!it.keepError&&Eh(r.errors,Je),!it.keepDirty&&Eh(r.dirtyFields,Je),!it.keepTouched&&Eh(r.touchedFields,Je),!it.keepIsValidating&&Eh(r.validatingFields,Je),!t.shouldUnregister&&!it.keepDefaultValue&&Eh(a,Je);p.state.next({values:tm(i)}),p.state.next({...r,...it.keepDirty?{isDirty:ee()}:{}}),!it.keepIsValid&&_()},ze=({disabled:$e,name:it})=>{(Qx($e)&&l.mount||$e||o.disabled.has(it))&&($e?o.disabled.add(it):o.disabled.delete(it))},Pe=($e,it={})=>{let Je=xa(n,$e);const st=Qx(it.disabled)||Qx(t.disabled);return dc(n,$e,{...Je||{},_f:{...Je&&Je._f?Je._f:{ref:{name:$e}},name:$e,mount:!0,...it}}),o.mount.add($e),Je?ze({disabled:Qx(it.disabled)?it.disabled:t.disabled,name:$e}):E($e,!0,it.value),{...st?{disabled:it.disabled||t.disabled}:{},...t.progressive?{required:!!it.required,min:AR(it.min),max:AR(it.max),minLength:AR(it.minLength),maxLength:AR(it.maxLength),pattern:AR(it.pattern)}:{},name:$e,onChange:ce,onBlur:ce,ref:mt=>{if(mt){Pe($e,it),Je=xa(n,$e);const wt=oh(mt.value)&&mt.querySelectorAll&&mt.querySelectorAll("input,select,textarea")[0]||mt,at=H$t(wt),rt=Je._f.refs||[];if(at?rt.find(Et=>Et===wt):wt===Je._f.ref)return;dc(n,$e,{_f:{...Je._f,...at?{refs:[...rt.filter(Sbe),wt,...Array.isArray(xa(a,$e))?[{}]:[]],ref:{type:wt.type,name:$e}}:{ref:wt}}}),E($e,!1,void 0,wt)}else Je=xa(n,$e,{}),Je._f&&(Je._f.mount=!1),(t.shouldUnregister||it.shouldUnregister)&&!(rit(o.array,$e)&&l.action)&&o.unMount.add($e)}}},Ie=()=>t.shouldFocusError&&s7(n,ne,o.mount),De=$e=>{Qx($e)&&(p.state.next({disabled:$e}),s7(n,(it,Je)=>{const st=xa(n,Je);st&&(it.disabled=st._f.disabled||$e,Array.isArray(st._f.refs)&&st._f.refs.forEach(mt=>{mt.disabled=st._f.disabled||$e}))},0,!1))},pe=($e,it)=>async Je=>{let st;Je&&(Je.preventDefault&&Je.preventDefault(),Je.persist&&Je.persist());let mt=tm(i);if(p.state.next({isSubmitting:!0}),t.resolver){const{errors:wt,values:at}=await R();r.errors=wt,mt=tm(at)}else await O(n);if(o.disabled.size)for(const wt of o.disabled)Eh(mt,wt);if(Eh(r.errors,"root"),Kg(r.errors)){p.state.next({errors:{}});try{await $e(mt,Je)}catch(wt){st=wt}}else it&&await it({...r.errors},Je),Ie(),setTimeout(Ie);if(p.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:Kg(r.errors)&&!st,submitCount:r.submitCount+1,errors:r.errors}),st)throw st},tt=($e,it={})=>{xa(n,$e)&&(oh(it.defaultValue)?ie($e,tm(xa(a,$e))):(ie($e,it.defaultValue),dc(a,$e,tm(it.defaultValue))),it.keepTouched||Eh(r.touchedFields,$e),it.keepDirty||(Eh(r.dirtyFields,$e),r.isDirty=it.defaultValue?ee($e,tm(xa(a,$e))):ee()),it.keepError||(Eh(r.errors,$e),h.isValid&&_()),p.state.next({...r}))},ge=($e,it={})=>{const Je=$e?tm($e):a,st=tm(Je),mt=Kg($e),wt=mt?a:st;if(it.keepDefaultValues||(a=Je),!it.keepValues){if(it.keepDirtyValues){const at=new Set([...o.mount,...Object.keys(ER(a,i))]);for(const rt of Array.from(at))xa(r.dirtyFields,rt)?dc(wt,rt,xa(i,rt)):ie(rt,xa(wt,rt))}else{if(aTe&&oh($e))for(const at of o.mount){const rt=xa(n,at);if(rt&&rt._f){const Et=Array.isArray(rt._f.refs)?rt._f.refs[0]:rt._f.ref;if(Jhe(Et)){const hs=Et.closest("form");if(hs){hs.reset();break}}}}if(it.keepFieldsRef)for(const at of o.mount)ie(at,xa(wt,at));else n={}}i=t.shouldUnregister?it.keepDefaultValues?tm(a):{}:tm(wt),p.array.next({values:{...wt}}),p.state.next({values:{...wt}})}o={mount:it.keepDirtyValues?o.mount:new Set,unMount:new Set,array:new Set,disabled:new Set,watch:new Set,watchAll:!1,focus:""},l.mount=!h.isValid||!!it.keepIsValid||!!it.keepDirtyValues,l.watch=!!t.shouldUnregister,p.state.next({submitCount:it.keepSubmitCount?r.submitCount:0,isDirty:mt?!1:it.keepDirty?r.isDirty:!!(it.keepDefaultValues&&!S2($e,a)),isSubmitted:it.keepIsSubmitted?r.isSubmitted:!1,dirtyFields:mt?{}:it.keepDirtyValues?it.keepDefaultValues&&i?ER(a,i):r.dirtyFields:it.keepDefaultValues&&$e?ER(a,$e):it.keepDirty?r.dirtyFields:{},touchedFields:it.keepTouched?r.touchedFields:{},errors:it.keepErrors?r.errors:{},isSubmitSuccessful:it.keepIsSubmitSuccessful?r.isSubmitSuccessful:!1,isSubmitting:!1})},ct=($e,it)=>ge(l1($e)?$e(i):$e,it),Ue=($e,it={})=>{const Je=xa(n,$e),st=Je&&Je._f;if(st){const mt=st.refs?st.refs[0]:st.ref;mt.focus&&(mt.focus(),it.shouldSelect&&l1(mt.select)&&mt.select())}},et=$e=>{r={...r,...$e}},Ne={control:{register:Pe,unregister:Me,getFieldState:fe,handleSubmit:pe,setError:ve,_subscribe:Ve,_runSchema:R,_focusError:Ie,_getWatch:Z,_getDirty:ee,_setValid:_,_setFieldArray:j,_setDisabledField:ze,_setErrors:T,_getFieldArray:J,_reset:ge,_resetDefaultValues:()=>l1(t.defaultValues)&&t.defaultValues().then($e=>{ct($e,t.resetOptions),p.state.next({isLoading:!1})}),_removeUnmounted:$,_disableForm:De,_subjects:p,_proxyFormState:h,get _fields(){return n},get _formValues(){return i},get _state(){return l},set _state($e){l=$e},get _defaultValues(){return a},get _names(){return o},set _names($e){o=$e},get _formState(){return r},get _options(){return t},set _options($e){t={...t,...$e}}},subscribe:Le,trigger:le,register:Pe,handleSubmit:pe,watch:We,setValue:ie,getValues:be,reset:ct,resetField:tt,clearErrors:je,unregister:Me,setError:ve,setFocus:Ue,getFieldState:fe};return{...Ne,formControl:Ne}}function qge(s={}){const t=Nt.useRef(void 0),r=Nt.useRef(void 0),[n,a]=Nt.useState({isDirty:!1,isValidating:!1,isLoading:l1(s.defaultValues),isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,submitCount:0,dirtyFields:{},touchedFields:{},validatingFields:{},errors:s.errors||{},disabled:s.disabled||!1,isReady:!1,defaultValues:l1(s.defaultValues)?void 0:s.defaultValues});if(!t.current)if(s.formControl)t.current={...s.formControl,formState:n},s.defaultValues&&!l1(s.defaultValues)&&s.formControl.reset(s.defaultValues,s.resetOptions);else{const{formControl:l,...o}=rUt(s);t.current={...o,formState:n}}const i=t.current.control;return i._options=s,cTe(()=>{const l=i._subscribe({formState:i._proxyFormState,callback:()=>a({...i._formState}),reRenderRoot:!0});return a(o=>({...o,isReady:!0})),i._formState.isReady=!0,l},[i]),Nt.useEffect(()=>i._disableForm(s.disabled),[i,s.disabled]),Nt.useEffect(()=>{s.mode&&(i._options.mode=s.mode),s.reValidateMode&&(i._options.reValidateMode=s.reValidateMode)},[i,s.mode,s.reValidateMode]),Nt.useEffect(()=>{s.errors&&(i._setErrors(s.errors),i._focusError())},[i,s.errors]),Nt.useEffect(()=>{s.shouldUnregister&&i._subjects.state.next({values:i._getWatch()})},[i,s.shouldUnregister]),Nt.useEffect(()=>{if(i._proxyFormState.isDirty){const l=i._getDirty();l!==n.isDirty&&i._subjects.state.next({isDirty:l})}},[i,n.isDirty]),Nt.useEffect(()=>{s.values&&!S2(s.values,r.current)?(i._reset(s.values,{keepFieldsRef:!0,...i._options.resetOptions}),r.current=s.values,a(l=>({...l}))):i._resetDefaultValues()},[i,s.values]),Nt.useEffect(()=>{i._state.mount||(i._setValid(),i._state.mount=!0),i._state.watch&&(i._state.watch=!1,i._subjects.state.next({...i._formState})),i._removeUnmounted()}),t.current.formState=nit(n,i),t.current}const K7e=(s,t,r)=>{if(s&&"reportValidity"in s){const n=xa(r,t);s.setCustomValidity(n&&n.message||""),s.reportValidity()}},mit=(s,t)=>{for(const r in t.fields){const n=t.fields[r];n&&n.ref&&"reportValidity"in n.ref?K7e(n.ref,r,s):n.refs&&n.refs.forEach(a=>K7e(a,r,s))}},nUt=(s,t)=>{t.shouldUseNativeValidation&&mit(s,t);const r={};for(const n in s){const a=xa(t.fields,n),i=Object.assign(s[n]||{},{ref:a&&a.ref});if(aUt(t.names||Object.keys(s),n)){const l=Object.assign({},xa(r,n));dc(l,"root",i),dc(r,n,l)}else dc(r,n,i)}return r},aUt=(s,t)=>s.some(r=>r.startsWith(t+"."));var iUt=function(s,t){for(var r={};s.length;){var n=s[0],a=n.code,i=n.message,l=n.path.join(".");if(!r[l])if("unionErrors"in n){var o=n.unionErrors[0].errors[0];r[l]={message:o.message,type:o.code}}else r[l]={message:i,type:a};if("unionErrors"in n&&n.unionErrors.forEach(function(h){return h.errors.forEach(function(m){return s.push(m)})}),t){var c=r[l].types,d=c&&c[n.code];r[l]=iit(l,t,r,a,d?[].concat(d,n.message):n.message)}s.shift()}return r},Vge=function(s,t,r){return r===void 0&&(r={}),function(n,a,i){try{return Promise.resolve(function(l,o){try{var c=Promise.resolve(s[r.mode==="sync"?"parse":"parseAsync"](n,t)).then(function(d){return i.shouldUseNativeValidation&&mit({},i),{errors:{},values:r.raw?n:d}})}catch(d){return o(d)}return c&&c.then?c.then(void 0,o):c}(0,function(l){if(function(o){return Array.isArray(o==null?void 0:o.errors)}(l))return{values:{},errors:nUt(iUt(l.errors,!i.shouldUseNativeValidation&&i.criteriaMode==="all"),i)};throw l}))}catch(l){return Promise.reject(l)}}};const Hge=z$t,fit=S.createContext({}),iu=({...s})=>e.jsx(fit.Provider,{value:{name:s.name},children:e.jsx(V$t,{...s})}),Gge=()=>{const s=S.useContext(fit),t=S.useContext(pit),{getFieldState:r,formState:n}=Uge(),a=r(s.name,n);if(!s)throw new Error("useFormField should be used within ");const{id:i}=t;return{id:i,name:s.name,formItemId:`${i}-form-item`,formDescriptionId:`${i}-form-item-description`,formMessageId:`${i}-form-item-message`,...a}},pit=S.createContext({}),Ud=S.forwardRef(({className:s,...t},r)=>{const n=S.useId();return e.jsx(pit.Provider,{value:{id:n},children:e.jsx("div",{ref:r,className:Ft("space-y-2",s),...t})})});Ud.displayName="FormItem";const qd=S.forwardRef(({className:s,...t},r)=>{const{error:n,formItemId:a}=Gge();return e.jsx(ue,{ref:r,className:Ft(n&&"text-destructive",s),htmlFor:a,...t})});qd.displayName="FormLabel";const Vd=S.forwardRef(({...s},t)=>{const{error:r,formItemId:n,formDescriptionId:a,formMessageId:i}=Gge();return e.jsx(p3e,{ref:t,id:n,"aria-describedby":r?`${a} ${i}`:`${a}`,"aria-invalid":!!r,...s})});Vd.displayName="FormControl";const jue=S.forwardRef(({className:s,...t},r)=>{const{formDescriptionId:n}=Gge();return e.jsx("p",{ref:r,id:n,className:Ft("text-sm text-muted-foreground",s),...t})});jue.displayName="FormDescription";const mg=S.forwardRef(({className:s,children:t,...r},n)=>{const{error:a,formMessageId:i}=Gge(),l=a?String(a==null?void 0:a.message):t;return l?e.jsx("p",{ref:n,id:i,className:Ft("text-sm font-medium text-destructive",s),...r,children:l}):null});mg.displayName="FormMessage";const oUt=yj({category:krt(["general","technology","crm","marketing"]),subject:Ho().min(5,"Subject must be at least 5 characters").max(200),description:Ho().min(20,"Please provide more details (at least 20 characters)").max(2e3)}),lUt={general:"General Support",technology:"Technology Support",crm:"CRM Support",marketing:"Marketing Support"};function ONe({trigger:s}){const[t,r]=S.useState(!1),[n,a]=S.useState(!1),{user:i}=Ms(),l=qge({resolver:Vge(oUt),defaultValues:{category:"general",subject:"",description:""}}),o=async c=>{if(!i){he.error("You must be logged in to submit a ticket");return}a(!0);try{const{error:d}=await V.from("support_tickets").insert({user_id:i.id,category:c.category,subject:c.subject,description:c.description});if(d)throw d;try{await V.functions.invoke("support-ticket-notify",{body:{category:lUt[c.category],subject:c.subject}})}catch(h){console.log("Notification send attempted:",h)}he.success("Support ticket submitted successfully!"),l.reset(),r(!1)}catch(d){console.error("Error submitting ticket:",d),he.error("Failed to submit ticket. Please try again.")}finally{a(!1)}};return e.jsxs(bs,{open:t,onOpenChange:r,children:[e.jsx(Qi,{asChild:!0,children:s||e.jsxs(H,{variant:"ghost",size:"icon",className:"relative",children:[e.jsx(vF,{className:"h-5 w-5"}),e.jsx("span",{className:"sr-only",children:"Support"})]})}),e.jsxs(vs,{className:"sm:max-w-[500px]",children:[e.jsxs(Cs,{children:[e.jsx(Ns,{children:"Need Help?"}),e.jsx(nn,{children:"Submit a support ticket and we'll get back to you as soon as possible."})]}),e.jsxs("div",{className:"flex items-center gap-2 p-3 bg-muted rounded-lg mb-4",children:[e.jsx(Yn,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:["You can also text us at: ",e.jsx("span",{className:"font-medium text-foreground",children:"1-866-527-8668"})]})]}),e.jsx(Hge,{...l,children:e.jsxs("form",{onSubmit:l.handleSubmit(o),className:"space-y-4",children:[e.jsx(iu,{control:l.control,name:"category",render:({field:c})=>e.jsxs(Ud,{children:[e.jsx(qd,{children:"Category"}),e.jsxs(Bs,{onValueChange:c.onChange,defaultValue:c.value,children:[e.jsx(Vd,{children:e.jsx(Os,{children:e.jsx(Us,{placeholder:"Select a category"})})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"general",children:"General Support"}),e.jsx(pt,{value:"technology",children:"Technology Support"}),e.jsx(pt,{value:"crm",children:"CRM Support"}),e.jsx(pt,{value:"marketing",children:"Marketing Support"})]})]}),e.jsx(mg,{})]})}),e.jsx(iu,{control:l.control,name:"subject",render:({field:c})=>e.jsxs(Ud,{children:[e.jsx(qd,{children:"Subject"}),e.jsx(Vd,{children:e.jsx(Se,{placeholder:"Brief description of your issue",...c})}),e.jsx(mg,{})]})}),e.jsx(iu,{control:l.control,name:"description",render:({field:c})=>e.jsxs(Ud,{children:[e.jsx(qd,{children:"Description"}),e.jsx(Vd,{children:e.jsx(vr,{placeholder:"Please describe your issue in detail...",className:"min-h-[120px]",...c})}),e.jsx(mg,{})]})}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(H,{type:"button",variant:"outline",onClick:()=>r(!1),children:"Cancel"}),e.jsx(H,{type:"submit",disabled:n,children:n?"Submitting...":"Submit Ticket"})]})]})})]})]})}const cUt=()=>{const{user:s}=Ms(),t=Fr(),[r,n]=S.useState([]),[a,i]=S.useState(0),[l,o]=S.useState(!1),[c,d]=S.useState(null),h=S.useRef(null);S.useEffect(()=>{h.current=c},[c]),S.useEffect(()=>{if(!s)return;const _=`notification_last_read_${s.id}`,b=localStorage.getItem(_);b&&!h.current&&(h.current=b,d(b));const j=`nb_cache_${s.id}`,k=60*1e3,T=async()=>{try{const z=sessionStorage.getItem(j);if(z){const O=JSON.parse(z);if(O.ts&&Date.now()-O.ts{n(D);const R=h.current?new Date(h.current):null,z=D.filter(O=>R?new Date(O.created_at)>R:!0);i(z.length)};T();const A=V.channel("push-notifications").on("postgres_changes",{event:"INSERT",schema:"public",table:"push_notifications"},D=>{const R=D.new;n(O=>{const $=[R,...O].slice(0,20);try{sessionStorage.setItem(j,JSON.stringify({ts:Date.now(),data:$}))}catch{}return $});const z=h.current?new Date(h.current):null;(!z||new Date(R.created_at)>z)&&i(O=>O+1),Notification.permission==="granted"&&new Notification(R.title,{body:R.body,icon:"/favicon.ico"})}).subscribe();return()=>{V.removeChannel(A)}},[s]);const m=_=>{const b=_.toLowerCase();return b.includes("community")||b.includes("post")?Gi:b.includes("academy")||b.includes("video")?xn:b.includes("template")?pl:b.includes("event")?Nn:b.includes("newsletter")?x_:b.includes("brokerage")?pm:b.includes("swag")||b.includes("social")?Di:b.includes("toolbox")||b.includes("tool")?N1:b.includes("brief")?Lr:Gi},p=_=>{o(!1),_.url&&_.url!=="/"&&t(_.url)},x=()=>{if(!s)return;const _=new Date().toISOString(),b=`notification_last_read_${s.id}`;localStorage.setItem(b,_),d(_),i(0)},y=_=>{o(_),_&&a>0&&x()};return e.jsxs(Xu,{open:l,onOpenChange:y,children:[e.jsx(Qu,{asChild:!0,children:e.jsxs(H,{variant:"ghost",size:"icon",className:"relative",children:[e.jsx(wp,{className:"h-5 w-5"}),a>0&&e.jsx(Xe,{variant:"destructive",className:"absolute -top-1 -right-1 h-5 w-5 flex items-center justify-center p-0 text-xs",children:a>9?"9+":a})]})}),e.jsxs(wu,{align:"end",className:"w-80",children:[e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b",children:[e.jsx("span",{className:"font-semibold",children:"Notifications"}),r.length>0&&e.jsx(H,{variant:"ghost",size:"sm",className:"text-xs h-6",onClick:x,children:"Mark all read"})]}),e.jsx(Ci,{className:"h-[300px]",children:r.length===0?e.jsx("div",{className:"p-4 text-center text-muted-foreground text-sm",children:"No notifications yet"}):r.map(_=>{const b=m(_.title);return e.jsxs(di,{className:"group flex items-start gap-3 p-3 cursor-pointer data-[highlighted]:bg-accent data-[highlighted]:text-accent-foreground",onClick:()=>p(_),children:[e.jsx("div",{className:"flex-shrink-0 mt-0.5",children:e.jsx(b,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{className:"flex flex-col gap-1 min-w-0",children:[e.jsx("span",{className:"font-medium text-sm",children:_.title}),e.jsx("span",{className:"text-xs text-muted-foreground line-clamp-2 group-data-[highlighted]:text-accent-foreground/80",children:_.body}),e.jsx("span",{className:"text-xs text-muted-foreground group-data-[highlighted]:text-accent-foreground/80",children:Hl(new Date(_.created_at),{addSuffix:!0})})]})]},_.id)})})]})]})};var Y7e=1,dUt=.9,uUt=.8,hUt=.17,Cbe=.1,Tbe=.999,mUt=.9999,fUt=.99,pUt=/[\\\/_+.#"@\[\(\{&]/,gUt=/[\\\/_+.#"@\[\(\{&]/g,xUt=/[\s-]/,git=/[\s-]/g;function FNe(s,t,r,n,a,i,l){if(i===t.length)return a===s.length?Y7e:fUt;var o=`${a},${i}`;if(l[o]!==void 0)return l[o];for(var c=n.charAt(i),d=r.indexOf(c,a),h=0,m,p,x,y;d>=0;)m=FNe(s,t,r,n,d+1,i+1,l),m>h&&(d===a?m*=Y7e:pUt.test(s.charAt(d-1))?(m*=uUt,x=s.slice(a,d-1).match(gUt),x&&a>0&&(m*=Math.pow(Tbe,x.length))):xUt.test(s.charAt(d-1))?(m*=dUt,y=s.slice(a,d-1).match(git),y&&a>0&&(m*=Math.pow(Tbe,y.length))):(m*=hUt,a>0&&(m*=Math.pow(Tbe,d-a))),s.charAt(d)!==t.charAt(i)&&(m*=mUt)),(mm&&(m=p*Cbe)),m>h&&(h=m),d=r.indexOf(c,d+1);return l[o]=h,h}function Z7e(s){return s.toLowerCase().replace(git," ")}function yUt(s,t,r){return s=r&&r.length>0?`${s+" "+r.join(" ")}`:s,FNe(s,t,Z7e(s),Z7e(t),0,0,{})}var MR='[cmdk-group=""]',Ebe='[cmdk-group-items=""]',vUt='[cmdk-group-heading=""]',xit='[cmdk-item=""]',X7e=`${xit}:not([aria-disabled="true"])`,BNe="cmdk-item-select",$6="data-value",bUt=(s,t,r)=>yUt(s,t,r),yit=S.createContext(void 0),iz=()=>S.useContext(yit),vit=S.createContext(void 0),hTe=()=>S.useContext(vit),bit=S.createContext(void 0),_it=S.forwardRef((s,t)=>{let r=U6(()=>{var je,ve;return{search:"",value:(ve=(je=s.value)!=null?je:s.defaultValue)!=null?ve:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),n=U6(()=>new Set),a=U6(()=>new Map),i=U6(()=>new Map),l=U6(()=>new Set),o=wit(s),{label:c,children:d,value:h,onValueChange:m,filter:p,shouldFilter:x,loop:y,disablePointerSelection:_=!1,vimBindings:b=!0,...j}=s,k=vm(),T=vm(),E=vm(),A=S.useRef(null),D=MUt();gA(()=>{if(h!==void 0){let je=h.trim();r.current.value=je,R.emit()}},[h]),gA(()=>{D(6,J)},[]);let R=S.useMemo(()=>({subscribe:je=>(l.current.add(je),()=>l.current.delete(je)),snapshot:()=>r.current,setState:(je,ve,We)=>{var Ve,Le,Me,ze;if(!Object.is(r.current[je],ve)){if(r.current[je]=ve,je==="search")Z(),$(),D(1,ee);else if(je==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let Pe=document.getElementById(E);Pe?Pe.focus():(Ve=document.getElementById(k))==null||Ve.focus()}if(D(7,()=>{var Pe;r.current.selectedItemId=(Pe=K())==null?void 0:Pe.id,R.emit()}),We||D(5,J),((Le=o.current)==null?void 0:Le.value)!==void 0){let Pe=ve??"";(ze=(Me=o.current).onValueChange)==null||ze.call(Me,Pe);return}}R.emit()}},emit:()=>{l.current.forEach(je=>je())}}),[]),z=S.useMemo(()=>({value:(je,ve,We)=>{var Ve;ve!==((Ve=i.current.get(je))==null?void 0:Ve.value)&&(i.current.set(je,{value:ve,keywords:We}),r.current.filtered.items.set(je,O(ve,We)),D(2,()=>{$(),R.emit()}))},item:(je,ve)=>(n.current.add(je),ve&&(a.current.has(ve)?a.current.get(ve).add(je):a.current.set(ve,new Set([je]))),D(3,()=>{Z(),$(),r.current.value||ee(),R.emit()}),()=>{i.current.delete(je),n.current.delete(je),r.current.filtered.items.delete(je);let We=K();D(4,()=>{Z(),(We==null?void 0:We.getAttribute("id"))===je&&ee(),R.emit()})}),group:je=>(a.current.has(je)||a.current.set(je,new Set),()=>{i.current.delete(je),a.current.delete(je)}),filter:()=>o.current.shouldFilter,label:c||s["aria-label"],getDisablePointerSelection:()=>o.current.disablePointerSelection,listId:k,inputId:E,labelId:T,listInnerRef:A}),[]);function O(je,ve){var We,Ve;let Le=(Ve=(We=o.current)==null?void 0:We.filter)!=null?Ve:bUt;return je?Le(je,r.current.search,ve):0}function $(){if(!r.current.search||o.current.shouldFilter===!1)return;let je=r.current.filtered.items,ve=[];r.current.filtered.groups.forEach(Ve=>{let Le=a.current.get(Ve),Me=0;Le.forEach(ze=>{let Pe=je.get(ze);Me=Math.max(Pe,Me)}),ve.push([Ve,Me])});let We=A.current;re().sort((Ve,Le)=>{var Me,ze;let Pe=Ve.getAttribute("id"),Ie=Le.getAttribute("id");return((Me=je.get(Ie))!=null?Me:0)-((ze=je.get(Pe))!=null?ze:0)}).forEach(Ve=>{let Le=Ve.closest(Ebe);Le?Le.appendChild(Ve.parentElement===Le?Ve:Ve.closest(`${Ebe} > *`)):We.appendChild(Ve.parentElement===We?Ve:Ve.closest(`${Ebe} > *`))}),ve.sort((Ve,Le)=>Le[1]-Ve[1]).forEach(Ve=>{var Le;let Me=(Le=A.current)==null?void 0:Le.querySelector(`${MR}[${$6}="${encodeURIComponent(Ve[0])}"]`);Me==null||Me.parentElement.appendChild(Me)})}function ee(){let je=re().find(We=>We.getAttribute("aria-disabled")!=="true"),ve=je==null?void 0:je.getAttribute($6);R.setState("value",ve||void 0)}function Z(){var je,ve,We,Ve;if(!r.current.search||o.current.shouldFilter===!1){r.current.filtered.count=n.current.size;return}r.current.filtered.groups=new Set;let Le=0;for(let Me of n.current){let ze=(ve=(je=i.current.get(Me))==null?void 0:je.value)!=null?ve:"",Pe=(Ve=(We=i.current.get(Me))==null?void 0:We.keywords)!=null?Ve:[],Ie=O(ze,Pe);r.current.filtered.items.set(Me,Ie),Ie>0&&Le++}for(let[Me,ze]of a.current)for(let Pe of ze)if(r.current.filtered.items.get(Pe)>0){r.current.filtered.groups.add(Me);break}r.current.filtered.count=Le}function J(){var je,ve,We;let Ve=K();Ve&&(((je=Ve.parentElement)==null?void 0:je.firstChild)===Ve&&((We=(ve=Ve.closest(MR))==null?void 0:ve.querySelector(vUt))==null||We.scrollIntoView({block:"nearest"})),Ve.scrollIntoView({block:"nearest"}))}function K(){var je;return(je=A.current)==null?void 0:je.querySelector(`${xit}[aria-selected="true"]`)}function re(){var je;return Array.from(((je=A.current)==null?void 0:je.querySelectorAll(X7e))||[])}function ie(je){let ve=re()[je];ve&&R.setState("value",ve.getAttribute($6))}function ce(je){var ve;let We=K(),Ve=re(),Le=Ve.findIndex(ze=>ze===We),Me=Ve[Le+je];(ve=o.current)!=null&&ve.loop&&(Me=Le+je<0?Ve[Ve.length-1]:Le+je===Ve.length?Ve[0]:Ve[Le+je]),Me&&R.setState("value",Me.getAttribute($6))}function ne(je){let ve=K(),We=ve==null?void 0:ve.closest(MR),Ve;for(;We&&!Ve;)We=je>0?EUt(We,MR):AUt(We,MR),Ve=We==null?void 0:We.querySelector(X7e);Ve?R.setState("value",Ve.getAttribute($6)):ce(je)}let le=()=>ie(re().length-1),be=je=>{je.preventDefault(),je.metaKey?le():je.altKey?ne(1):ce(1)},fe=je=>{je.preventDefault(),je.metaKey?ie(0):je.altKey?ne(-1):ce(-1)};return S.createElement(Vn.div,{ref:t,tabIndex:-1,...j,"cmdk-root":"",onKeyDown:je=>{var ve;(ve=j.onKeyDown)==null||ve.call(j,je);let We=je.nativeEvent.isComposing||je.keyCode===229;if(!(je.defaultPrevented||We))switch(je.key){case"n":case"j":{b&&je.ctrlKey&&be(je);break}case"ArrowDown":{be(je);break}case"p":case"k":{b&&je.ctrlKey&&fe(je);break}case"ArrowUp":{fe(je);break}case"Home":{je.preventDefault(),ie(0);break}case"End":{je.preventDefault(),le();break}case"Enter":{je.preventDefault();let Ve=K();if(Ve){let Le=new Event(BNe);Ve.dispatchEvent(Le)}}}}},S.createElement("label",{"cmdk-label":"",htmlFor:z.inputId,id:z.labelId,style:PUt},c),Wge(s,je=>S.createElement(vit.Provider,{value:R},S.createElement(yit.Provider,{value:z},je))))}),_Ut=S.forwardRef((s,t)=>{var r,n;let a=vm(),i=S.useRef(null),l=S.useContext(bit),o=iz(),c=wit(s),d=(n=(r=c.current)==null?void 0:r.forceMount)!=null?n:l==null?void 0:l.forceMount;gA(()=>{if(!d)return o.item(a,l==null?void 0:l.id)},[d]);let h=jit(a,i,[s.value,s.children,i],s.keywords),m=hTe(),p=jS(D=>D.value&&D.value===h.current),x=jS(D=>d||o.filter()===!1?!0:D.search?D.filtered.items.get(a)>0:!0);S.useEffect(()=>{let D=i.current;if(!(!D||s.disabled))return D.addEventListener(BNe,y),()=>D.removeEventListener(BNe,y)},[x,s.onSelect,s.disabled]);function y(){var D,R;_(),(R=(D=c.current).onSelect)==null||R.call(D,h.current)}function _(){m.setState("value",h.current,!0)}if(!x)return null;let{disabled:b,value:j,onSelect:k,forceMount:T,keywords:E,...A}=s;return S.createElement(Vn.div,{ref:nj(i,t),...A,id:a,"cmdk-item":"",role:"option","aria-disabled":!!b,"aria-selected":!!p,"data-disabled":!!b,"data-selected":!!p,onPointerMove:b||o.getDisablePointerSelection()?void 0:_,onClick:b?void 0:y},s.children)}),wUt=S.forwardRef((s,t)=>{let{heading:r,children:n,forceMount:a,...i}=s,l=vm(),o=S.useRef(null),c=S.useRef(null),d=vm(),h=iz(),m=jS(x=>a||h.filter()===!1?!0:x.search?x.filtered.groups.has(l):!0);gA(()=>h.group(l),[]),jit(l,o,[s.value,s.heading,c]);let p=S.useMemo(()=>({id:l,forceMount:a}),[a]);return S.createElement(Vn.div,{ref:nj(o,t),...i,"cmdk-group":"",role:"presentation",hidden:m?void 0:!0},r&&S.createElement("div",{ref:c,"cmdk-group-heading":"","aria-hidden":!0,id:d},r),Wge(s,x=>S.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":r?d:void 0},S.createElement(bit.Provider,{value:p},x))))}),jUt=S.forwardRef((s,t)=>{let{alwaysRender:r,...n}=s,a=S.useRef(null),i=jS(l=>!l.search);return!r&&!i?null:S.createElement(Vn.div,{ref:nj(a,t),...n,"cmdk-separator":"",role:"separator"})}),NUt=S.forwardRef((s,t)=>{let{onValueChange:r,...n}=s,a=s.value!=null,i=hTe(),l=jS(d=>d.search),o=jS(d=>d.selectedItemId),c=iz();return S.useEffect(()=>{s.value!=null&&i.setState("search",s.value)},[s.value]),S.createElement(Vn.input,{ref:t,...n,"cmdk-input":"",autoComplete:"off",autoCorrect:"off",spellCheck:!1,"aria-autocomplete":"list",role:"combobox","aria-expanded":!0,"aria-controls":c.listId,"aria-labelledby":c.labelId,"aria-activedescendant":o,id:c.inputId,type:"text",value:a?s.value:l,onChange:d=>{a||i.setState("search",d.target.value),r==null||r(d.target.value)}})}),kUt=S.forwardRef((s,t)=>{let{children:r,label:n="Suggestions",...a}=s,i=S.useRef(null),l=S.useRef(null),o=jS(d=>d.selectedItemId),c=iz();return S.useEffect(()=>{if(l.current&&i.current){let d=l.current,h=i.current,m,p=new ResizeObserver(()=>{m=requestAnimationFrame(()=>{let x=d.offsetHeight;h.style.setProperty("--cmdk-list-height",x.toFixed(1)+"px")})});return p.observe(d),()=>{cancelAnimationFrame(m),p.unobserve(d)}}},[]),S.createElement(Vn.div,{ref:nj(i,t),...a,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":o,"aria-label":n,id:c.listId},Wge(s,d=>S.createElement("div",{ref:nj(l,c.listInnerRef),"cmdk-list-sizer":""},d)))}),SUt=S.forwardRef((s,t)=>{let{open:r,onOpenChange:n,overlayClassName:a,contentClassName:i,container:l,...o}=s;return S.createElement(pge,{open:r,onOpenChange:n},S.createElement(gge,{container:l},S.createElement(h8,{"cmdk-overlay":"",className:a}),S.createElement(m8,{"aria-label":s.label,"cmdk-dialog":"",className:i},S.createElement(_it,{ref:t,...o}))))}),CUt=S.forwardRef((s,t)=>jS(r=>r.filtered.count===0)?S.createElement(Vn.div,{ref:t,...s,"cmdk-empty":"",role:"presentation"}):null),TUt=S.forwardRef((s,t)=>{let{progress:r,children:n,label:a="Loading...",...i}=s;return S.createElement(Vn.div,{ref:t,...i,"cmdk-loading":"",role:"progressbar","aria-valuenow":r,"aria-valuemin":0,"aria-valuemax":100,"aria-label":a},Wge(s,l=>S.createElement("div",{"aria-hidden":!0},l)))}),fx=Object.assign(_it,{List:kUt,Item:_Ut,Input:NUt,Group:wUt,Separator:jUt,Dialog:SUt,Empty:CUt,Loading:TUt});function EUt(s,t){let r=s.nextElementSibling;for(;r;){if(r.matches(t))return r;r=r.nextElementSibling}}function AUt(s,t){let r=s.previousElementSibling;for(;r;){if(r.matches(t))return r;r=r.previousElementSibling}}function wit(s){let t=S.useRef(s);return gA(()=>{t.current=s}),t}var gA=typeof window>"u"?S.useEffect:S.useLayoutEffect;function U6(s){let t=S.useRef();return t.current===void 0&&(t.current=s()),t}function jS(s){let t=hTe(),r=()=>s(t.snapshot());return S.useSyncExternalStore(t.subscribe,r,r)}function jit(s,t,r,n=[]){let a=S.useRef(),i=iz();return gA(()=>{var l;let o=(()=>{var d;for(let h of r){if(typeof h=="string")return h.trim();if(typeof h=="object"&&"current"in h)return h.current?(d=h.current.textContent)==null?void 0:d.trim():a.current}})(),c=n.map(d=>d.trim());i.value(s,o,c),(l=t.current)==null||l.setAttribute($6,o),a.current=o}),a}var MUt=()=>{let[s,t]=S.useState(),r=U6(()=>new Map);return gA(()=>{r.current.forEach(n=>n()),r.current=new Map},[s]),(n,a)=>{r.current.set(n,a),t({})}};function IUt(s){let t=s.type;return typeof t=="function"?t(s.props):"render"in t?t.render(s.props):s}function Wge({asChild:s,children:t},r){return s&&S.isValidElement(t)?S.cloneElement(IUt(t),{ref:t.ref},r(t.props.children)):r(t)}var PUt={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};const k0=S.forwardRef(({className:s,...t},r)=>e.jsx(fx,{ref:r,className:Ft("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",s),...t}));k0.displayName=fx.displayName;const LUt=({children:s,...t})=>e.jsx(bs,{...t,children:e.jsx(vs,{className:"overflow-hidden p-0 shadow-lg",children:e.jsx(k0,{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:s})})}),S0=S.forwardRef(({className:s,...t},r)=>e.jsxs("div",{className:"flex items-center border-b px-3","cmdk-input-wrapper":"",children:[e.jsx(Mn,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),e.jsx(fx.Input,{ref:r,className:Ft("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",s),...t})]}));S0.displayName=fx.Input.displayName;const C0=S.forwardRef(({className:s,...t},r)=>e.jsx(fx.List,{ref:r,className:Ft("max-h-[300px] overflow-y-auto overflow-x-hidden",s),...t}));C0.displayName=fx.List.displayName;const T0=S.forwardRef((s,t)=>e.jsx(fx.Empty,{ref:t,className:"py-6 text-center text-sm",...s}));T0.displayName=fx.Empty.displayName;const E0=S.forwardRef(({className:s,...t},r)=>e.jsx(fx.Group,{ref:r,className:Ft("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",s),...t}));E0.displayName=fx.Group.displayName;const DUt=S.forwardRef(({className:s,...t},r)=>e.jsx(fx.Separator,{ref:r,className:Ft("-mx-1 h-px bg-border",s),...t}));DUt.displayName=fx.Separator.displayName;const fg=S.forwardRef(({className:s,...t},r)=>e.jsx(fx.Item,{ref:r,className:Ft("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",s),...t}));fg.displayName=fx.Item.displayName;const RUt={event:{label:"Events",icon:xu,color:"bg-blue-500/10 text-blue-600"},template:{label:"Templates",icon:pl,color:"bg-purple-500/10 text-purple-600"},academy:{label:"Academy",icon:Vu,color:"bg-amber-500/10 text-amber-600"},toolbox:{label:"Toolbox",icon:N1,color:"bg-green-500/10 text-green-600"},"social-swag":{label:"Social Swag",icon:Lr,color:"bg-fuchsia-500/10 text-fuchsia-600"}},Q7e=()=>{const[s,t]=S.useState(!1),[r,n]=S.useState(""),[a,i]=S.useState([]),[l,o]=S.useState(!1),c=Fr();S.useEffect(()=>{const p=x=>{x.key==="k"&&(x.metaKey||x.ctrlKey)&&(x.preventDefault(),t(y=>!y))};return document.addEventListener("keydown",p),()=>document.removeEventListener("keydown",p)},[]);const d=S.useCallback(async p=>{if(!p.trim()){i([]);return}o(!0);const x=`%${p}%`;try{const[y,_,b,j,k]=await Promise.all([V.from("events").select("id, title, description, event_date").eq("is_published",!0).or(`title.ilike.${x},description.ilike.${x}`).limit(5),V.from("canva_templates").select("id, name, description, publish_date").or(`name.ilike.${x},description.ilike.${x}`).limit(5),V.from("academy_videos").select("id, title, description, publish_date").eq("is_published",!0).or(`title.ilike.${x},description.ilike.${x}`).limit(5),V.from("resource_kits").select("id, name, description, publish_date").eq("is_published",!0).or(`name.ilike.${x},description.ilike.${x}`).limit(5),V.from("social_swag").select("id, title, description, publish_date").eq("is_published",!0).or(`title.ilike.${x},description.ilike.${x}`).limit(5)]),T=[];y.data&&y.data.forEach(E=>{T.push({id:E.id,title:E.title,description:E.description,type:"event",date:E.event_date,path:`/event/${E.id}`})}),_.data&&_.data.forEach(E=>{T.push({id:E.id,title:E.name,description:E.description,type:"template",date:E.publish_date,path:`/templates/${E.id}`})}),b.data&&b.data.forEach(E=>{T.push({id:E.id,title:E.title,description:E.description,type:"academy",date:E.publish_date,path:`/academy/${E.id}`})}),j.data&&j.data.forEach(E=>{T.push({id:E.id,title:E.name,description:E.description,type:"toolbox",date:E.publish_date,path:`/toolbox/${E.id}`})}),k.data&&k.data.forEach(E=>{T.push({id:E.id,title:E.title,description:E.description,type:"social-swag",date:E.publish_date,path:`/social-swag/${E.id}`})}),i(T)}catch(y){console.error("Search error:",y)}finally{o(!1)}},[]);S.useEffect(()=>{const p=setTimeout(()=>{d(r)},300);return()=>clearTimeout(p)},[r,d]);const h=p=>{t(!1),n(""),c(p)},m=a.reduce((p,x)=>(p[x.type]||(p[x.type]=[]),p[x.type].push(x),p),{});return e.jsxs(e.Fragment,{children:[e.jsxs(H,{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:()=>t(!0),children:[e.jsx(Mn,{className:"h-4 w-4 xl:mr-2"}),e.jsx("span",{className:"hidden xl:inline-flex text-muted-foreground text-sm",children:"Search..."}),e.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:[e.jsx("span",{className:"text-xs",children:"⌘"}),"K"]})]}),e.jsxs(LUt,{open:s,onOpenChange:t,children:[e.jsx(S0,{placeholder:"Search events, templates, academy, toolbox, social swag...",value:r,onValueChange:n}),e.jsxs(C0,{children:[l&&e.jsx("div",{className:"py-6 text-center text-sm text-muted-foreground",children:"Searching..."}),!l&&r&&a.length===0&&e.jsxs(T0,{children:['No results found for "',r,'"']}),!l&&!r&&e.jsx("div",{className:"py-6 text-center text-sm text-muted-foreground",children:"Start typing to search across all content..."}),Object.entries(m).map(([p,x])=>{const y=RUt[p],_=y.icon;return e.jsx(E0,{heading:y.label,children:x.map(b=>e.jsxs(fg,{value:`${b.type}-${b.id}-${b.title}`,onSelect:()=>h(b.path),className:"flex items-start gap-3 py-3 cursor-pointer",children:[e.jsx("div",{className:`p-2 rounded-md ${y.color}`,children:e.jsx(_,{className:"h-4 w-4"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-medium truncate",children:b.title}),b.description&&e.jsx("div",{className:"text-sm text-muted-foreground truncate group-data-[selected=true]:text-primary-foreground/80",children:b.description})]}),e.jsxs("div",{className:"flex flex-col items-end gap-1 shrink-0",children:[e.jsx(Xe,{variant:"secondary",className:"text-xs",children:y.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Hl(new Date(b.date),{addSuffix:!0})})]})]},`${b.type}-${b.id}`))},p)})]})]})]})},OUt=({expiresAt:s,className:t,showUpgradeButton:r=!0})=>{const[n,a]=S.useState(null),i=Fr();if(S.useEffect(()=>{const d=()=>{const m=new Date().getTime(),x=new Date(s).getTime()-m;if(x<=0){a({days:0,hours:0,minutes:0});return}const y=Math.floor(x/(1e3*60*60*24)),_=Math.floor(x%(1e3*60*60*24)/(1e3*60*60)),b=Math.floor(x%(1e3*60*60)/(1e3*60));a({days:y,hours:_,minutes:b})};d();const h=setInterval(d,6e4);return()=>clearInterval(h)},[s]),!n)return null;const l=n.days===0&&n.hours===0&&n.minutes===0,o=n.days<=1,c=n.days<=3&&!o;return l?e.jsxs("div",{className:Ft("flex items-center justify-between gap-3 px-4 py-2 rounded-lg bg-destructive/10 border border-destructive/20",t),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(uu,{className:"h-4 w-4 text-destructive"}),e.jsx("span",{className:"text-sm font-medium text-destructive",children:"Your free trial has expired"})]}),r&&e.jsxs(H,{size:"sm",onClick:()=>i("/subscription"),className:"bg-primary hover:bg-primary/90 text-xs h-7 px-3",children:[e.jsx(Lr,{className:"h-3 w-3 mr-1"}),"Upgrade Now"]})]}):e.jsxs("div",{className:Ft("flex items-center justify-between 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",t),children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Pn,{className:Ft("h-4 w-4",o?"text-destructive":c?"text-amber-500":"text-primary")}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:Ft("text-sm font-medium",o?"text-destructive":c?"text-amber-600":"text-primary"),children:"Free Trial:"}),e.jsxs("div",{className:"flex items-center gap-1",children:[n.days>0&&e.jsxs("span",{className:Ft("text-sm font-bold",o?"text-destructive":c?"text-amber-600":"text-primary"),children:[n.days,"d"]}),e.jsxs("span",{className:Ft("text-sm font-bold",o?"text-destructive":c?"text-amber-600":"text-primary"),children:[n.hours,"h"]}),e.jsxs("span",{className:Ft("text-sm font-bold",o?"text-destructive":c?"text-amber-600":"text-primary"),children:[n.minutes,"m"]}),e.jsx("span",{className:Ft("text-xs",o?"text-destructive/70":c?"text-amber-600/70":"text-primary/70"),children:"remaining"})]})]})]}),r&&e.jsxs(H,{size:"sm",onClick:()=>i("/subscription"),variant:o?"destructive":c?"default":"outline",className:Ft("text-xs h-7 px-3",c&&"bg-amber-500 hover:bg-amber-600 text-white"),children:[e.jsx(Lr,{className:"h-3 w-3 mr-1"}),"Upgrade"]})]})},FUt=()=>{const s=Fr();return e.jsx("div",{className:"fixed inset-0 bg-background/95 backdrop-blur-sm z-50 flex items-center justify-center p-4 overflow-y-auto",children:e.jsxs(ke,{className:"w-full max-w-2xl shadow-2xl border-destructive/20 my-8",children:[e.jsxs(Ot,{className:"text-center pb-2",children:[e.jsx("div",{className:"mx-auto mb-4 h-16 w-16 rounded-full bg-destructive/10 flex items-center justify-center",children:e.jsx(uu,{className:"h-8 w-8 text-destructive"})}),e.jsx(zt,{className:"text-2xl",children:"Your Free Trial Has Ended"}),e.jsx(Br,{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!"})]}),e.jsxs(Oe,{className:"space-y-6",children:[e.jsxs("div",{className:"grid sm:grid-cols-2 gap-4",children:[e.jsx(ke,{className:"border-2 border-primary/20 hover:border-primary/50 transition-colors cursor-pointer",onClick:()=>s("/subscription"),children:e.jsxs(Oe,{className:"p-5 text-center",children:[e.jsx("div",{className:"mx-auto mb-3 h-12 w-12 rounded-full bg-primary/10 flex items-center justify-center",children:e.jsx(Ar,{className:"h-6 w-6 text-primary"})}),e.jsx("h3",{className:"font-semibold text-lg mb-1",children:"Individual Agent"}),e.jsxs("p",{className:"text-2xl font-bold text-primary mb-2",children:["$39",e.jsx("span",{className:"text-sm font-normal text-muted-foreground",children:"/mo"})]}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Perfect for solo agents ready to level up"}),e.jsxs(H,{className:"w-full",onClick:t=>{t.stopPropagation(),s("/subscription")},children:[e.jsx(Lr,{className:"h-4 w-4 mr-2"}),"Choose Individual"]})]})}),e.jsx(ke,{className:"border-2 border-amber-500/20 hover:border-amber-500/50 transition-colors cursor-pointer",onClick:()=>s("/subscription"),children:e.jsxs(Oe,{className:"p-5 text-center",children:[e.jsx("div",{className:"mx-auto mb-3 h-12 w-12 rounded-full bg-amber-500/10 flex items-center justify-center",children:e.jsx(Xa,{className:"h-6 w-6 text-amber-600"})}),e.jsx("h3",{className:"font-semibold text-lg mb-1",children:"Brokerage"}),e.jsxs("p",{className:"text-2xl font-bold text-amber-600 mb-2",children:["$299",e.jsx("span",{className:"text-sm font-normal text-muted-foreground",children:"/mo"})]}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"For teams and brokerages"}),e.jsxs(H,{variant:"outline",className:"w-full border-amber-500 text-amber-600 hover:bg-amber-50",onClick:t=>{t.stopPropagation(),s("/subscription")},children:[e.jsx(Xa,{className:"h-4 w-4 mr-2"}),"Choose Brokerage"]})]})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm text-muted-foreground text-center",children:"With a full membership, you'll get:"}),e.jsxs("ul",{className:"text-sm space-y-1 text-muted-foreground grid sm:grid-cols-2 gap-x-4",children:[e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-primary",children:"✓"})," Unlimited access to all marketing templates"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-primary",children:"✓"})," Complete Academy training library"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-primary",children:"✓"})," AI-powered tools and resources"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-primary",children:"✓"})," Community forums and support"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-primary",children:"✓"})," Exclusive member events and workshops"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-primary",children:"✓"})," Deal pipeline & scorecard tracking"]})]})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-4 space-y-3",children:[e.jsx("p",{className:"text-sm font-medium text-center",children:"Questions? Contact us:"}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3 justify-center",children:[e.jsxs("a",{href:"tel:1-866-527-8668",className:"flex items-center justify-center gap-2 text-primary hover:underline",children:[e.jsx(Yn,{className:"h-4 w-4"}),e.jsx("span",{children:"1-866-527-8668"})]}),e.jsxs("a",{href:"mailto:support@relevelup.com",className:"flex items-center justify-center gap-2 text-primary hover:underline",children:[e.jsx(er,{className:"h-4 w-4"}),e.jsx("span",{children:"support@relevelup.com"})]})]})]})]})]})})},BUt=({hasUnseenBrief:s,onClick:t,className:r})=>e.jsxs(rd,{children:[e.jsx(nd,{asChild:!0,children:e.jsxs(H,{variant:"ghost",size:"icon",onClick:t,className:Ft("relative transition-colors",s&&"text-primary hover:text-primary",r),children:[e.jsx(ph,{className:"h-5 w-5"}),s&&e.jsx("span",{className:"absolute top-1 right-1 h-2 w-2 rounded-full bg-primary animate-pulse"})]})}),e.jsx(Rc,{children:e.jsx("p",{children:"The LevelUp Brief"})})]});var mTe="Radio",[zUt,Nit]=_u(mTe),[$Ut,UUt]=zUt(mTe),kit=S.forwardRef((s,t)=>{const{__scopeRadio:r,name:n,checked:a=!1,required:i,disabled:l,value:o="on",onCheck:c,form:d,...h}=s,[m,p]=S.useState(null),x=_i(t,b=>p(b)),y=S.useRef(!1),_=m?d||!!m.closest("form"):!0;return e.jsxs($Ut,{scope:r,checked:a,disabled:l,children:[e.jsx(Vn.button,{type:"button",role:"radio","aria-checked":a,"data-state":Eit(a),"data-disabled":l?"":void 0,disabled:l,value:o,...h,ref:x,onClick:an(s.onClick,b=>{a||c==null||c(),_&&(y.current=b.isPropagationStopped(),y.current||b.stopPropagation())})}),_&&e.jsx(Tit,{control:m,bubbles:!y.current,name:n,value:o,checked:a,required:i,disabled:l,form:d,style:{transform:"translateX(-100%)"}})]})});kit.displayName=mTe;var Sit="RadioIndicator",Cit=S.forwardRef((s,t)=>{const{__scopeRadio:r,forceMount:n,...a}=s,i=UUt(Sit,r);return e.jsx(vh,{present:n||i.checked,children:e.jsx(Vn.span,{"data-state":Eit(i.checked),"data-disabled":i.disabled?"":void 0,...a,ref:t})})});Cit.displayName=Sit;var qUt="RadioBubbleInput",Tit=S.forwardRef(({__scopeRadio:s,control:t,checked:r,bubbles:n=!0,...a},i)=>{const l=S.useRef(null),o=_i(l,i),c=QB(r),d=FB(t);return S.useEffect(()=>{const h=l.current;if(!h)return;const m=window.HTMLInputElement.prototype,x=Object.getOwnPropertyDescriptor(m,"checked").set;if(c!==r&&x){const y=new Event("click",{bubbles:n});x.call(h,r),h.dispatchEvent(y)}},[c,r,n]),e.jsx(Vn.input,{type:"radio","aria-hidden":!0,defaultChecked:r,...a,tabIndex:-1,ref:o,style:{...a.style,...d,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})});Tit.displayName=qUt;function Eit(s){return s?"checked":"unchecked"}var VUt=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],Kge="RadioGroup",[HUt,BZs]=_u(Kge,[OS,Nit]),Ait=OS(),Mit=Nit(),[GUt,WUt]=HUt(Kge),Iit=S.forwardRef((s,t)=>{const{__scopeRadioGroup:r,name:n,defaultValue:a,value:i,required:l=!1,disabled:o=!1,orientation:c,dir:d,loop:h=!0,onValueChange:m,...p}=s,x=Ait(r),y=RS(d),[_,b]=af({prop:i,defaultProp:a??null,onChange:m,caller:Kge});return e.jsx(GUt,{scope:r,name:n,required:l,disabled:o,value:_,onValueChange:b,children:e.jsx(oge,{asChild:!0,...x,orientation:c,dir:y,loop:h,children:e.jsx(Vn.div,{role:"radiogroup","aria-required":l,"aria-orientation":c,"data-disabled":o?"":void 0,dir:y,...p,ref:t})})})});Iit.displayName=Kge;var Pit="RadioGroupItem",Lit=S.forwardRef((s,t)=>{const{__scopeRadioGroup:r,disabled:n,...a}=s,i=WUt(Pit,r),l=i.disabled||n,o=Ait(r),c=Mit(r),d=S.useRef(null),h=_i(t,d),m=i.value===a.value,p=S.useRef(!1);return S.useEffect(()=>{const x=_=>{VUt.includes(_.key)&&(p.current=!0)},y=()=>p.current=!1;return document.addEventListener("keydown",x),document.addEventListener("keyup",y),()=>{document.removeEventListener("keydown",x),document.removeEventListener("keyup",y)}},[]),e.jsx(lge,{asChild:!0,...o,focusable:!l,active:m,children:e.jsx(kit,{disabled:l,required:i.required,checked:m,...c,...a,name:i.name,ref:h,onCheck:()=>i.onValueChange(a.value),onKeyDown:an(x=>{x.key==="Enter"&&x.preventDefault()}),onFocus:an(a.onFocus,()=>{var x;p.current&&((x=d.current)==null||x.click())})})})});Lit.displayName=Pit;var KUt="RadioGroupIndicator",Dit=S.forwardRef((s,t)=>{const{__scopeRadioGroup:r,...n}=s,a=Mit(r);return e.jsx(Cit,{...a,...n,ref:t})});Dit.displayName=KUt;var Rit=Iit,Oit=Lit,YUt=Dit;const I2=S.forwardRef(({className:s,...t},r)=>e.jsx(Rit,{className:Ft("grid gap-2",s),...t,ref:r}));I2.displayName=Rit.displayName;const ih=S.forwardRef(({className:s,...t},r)=>e.jsx(Oit,{ref:r,className:Ft("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",s),...t,children:e.jsx(YUt,{className:"flex items-center justify-center",children:e.jsx(Gu,{className:"h-2.5 w-2.5 fill-current text-current"})})}));ih.displayName=Oit.displayName;const ZUt=({brief:s,open:t,onClose:r,onDismiss:n})=>{const{user:a}=Ms(),[i,l]=S.useState({}),[o,c]=S.useState({}),[d,h]=S.useState([]);S.useEffect(()=>{t&&a&&s.polls.length>0&&m()},[t,a,s.polls]);const m=async()=>{if(!a)return;const b=s.polls.map(k=>k.id),{data:j}=await V.from("levelup_brief_poll_responses").select("poll_id, option_id").eq("user_id",a.id).in("poll_id",b);if(j){const k={};j.forEach(T=>{k[T.poll_id]||(k[T.poll_id]=[]),k[T.poll_id].push(T.option_id)}),c(k)}},p=(b,j)=>{l(k=>({...k,[b]:j}))},x=(b,j,k)=>{l(T=>{const E=T[b]||[];return k?{...T,[b]:[...E,j]}:{...T,[b]:E.filter(A=>A!==j)}})},y=async b=>{if(!a)return;const j=i[b];if(!j||Array.isArray(j)&&j.length===0){he.error("Please select an option");return}h(k=>[...k,b]);try{await V.from("levelup_brief_poll_responses").delete().eq("poll_id",b).eq("user_id",a.id);const k=Array.isArray(j)?j:[j],T=k.map(A=>({poll_id:b,option_id:A,user_id:a.id})),{error:E}=await V.from("levelup_brief_poll_responses").insert(T);if(E)throw E;c(A=>({...A,[b]:k})),he.success("Response submitted!")}catch(k){console.error("Error submitting poll response:",k),he.error("Failed to submit response")}finally{h(k=>k.filter(T=>T!==b))}},_=b=>(b.includes("mediadelivery.net")||b.includes("bunny"),b);return e.jsx(bs,{open:t,onOpenChange:b=>!b&&r(),children:e.jsxs(vs,{className:"max-w-2xl max-h-[90vh] p-0 overflow-hidden [&>button]:hidden",children:[e.jsxs("div",{className:"bg-gradient-to-r from-primary to-primary/80 p-4 pr-12 text-primary-foreground relative",children:[e.jsx("button",{onClick:r,className:"absolute top-3 right-3 p-1.5 rounded-full bg-white/30 hover:bg-white/50 transition-colors","aria-label":"Close",children:e.jsx(Rr,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-white/20 rounded-lg",children:e.jsx(ph,{className:"h-6 w-6"})}),e.jsxs("div",{children:[e.jsx(Xe,{variant:"secondary",className:"mb-1 bg-white/20 text-white border-0",children:"The LevelUp Brief"}),e.jsx(Ns,{className:"text-xl font-bold text-white",children:s.brief.title})]})]})]}),e.jsx(Ci,{className:"max-h-[calc(90vh-240px)]",children:e.jsxs("div",{className:"p-6 space-y-6",children:[s.brief.description&&e.jsx("div",{className:"text-muted-foreground prose prose-sm max-w-none",dangerouslySetInnerHTML:{__html:s.brief.description}}),s.brief.video_url&&e.jsx("div",{className:"relative w-full aspect-video rounded-lg overflow-hidden bg-muted",children:e.jsx("iframe",{src:_(s.brief.video_url),className:"absolute inset-0 w-full h-full",allow:"autoplay; fullscreen; picture-in-picture",allowFullScreen:!0})}),s.brief.graphic_url&&!s.brief.video_url&&e.jsx("div",{className:"rounded-lg overflow-hidden bg-muted",children:s.brief.graphic_link_url?e.jsx("a",{href:s.brief.graphic_link_url,target:"_blank",rel:"noopener noreferrer",className:"block",children:e.jsx("img",{src:s.brief.graphic_url,alt:"Brief graphic",className:"w-full object-contain cursor-pointer hover:opacity-90 transition-opacity"})}):e.jsx("img",{src:s.brief.graphic_url,alt:"Brief graphic",className:"w-full object-contain"})}),s.links.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("h4",{className:"font-semibold text-foreground",children:"Quick Links"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:s.links.map(b=>e.jsxs(H,{variant:"outline",size:"sm",onClick:()=>window.open(b.url,"_blank"),className:"gap-2",children:[e.jsx(gn,{className:"h-4 w-4"}),b.title]},b.id))})]}),s.polls.map(b=>{var T,E;const j=((T=o[b.id])==null?void 0:T.length)>0,k=d.includes(b.id);return e.jsxs("div",{className:"space-y-3 p-4 bg-muted/50 rounded-lg border",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h4",{className:"font-semibold text-foreground",children:b.question}),j&&e.jsxs(Xe,{variant:"secondary",className:"gap-1",children:[e.jsx(ea,{className:"h-3 w-3"}),"Responded"]})]}),b.poll_type==="single"?e.jsx(I2,{value:i[b.id]||((E=o[b.id])==null?void 0:E[0])||"",onValueChange:A=>p(b.id,A),className:"space-y-2",children:b.options.map(A=>e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(ih,{value:A.id,id:A.id}),e.jsx(ue,{htmlFor:A.id,className:"cursor-pointer",children:A.option_text})]},A.id))}):e.jsx("div",{className:"space-y-2",children:b.options.map(A=>{const R=(i[b.id]||o[b.id]||[]).includes(A.id);return e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(ao,{id:A.id,checked:R,onCheckedChange:z=>x(b.id,A.id,z)}),e.jsx(ue,{htmlFor:A.id,className:"cursor-pointer",children:A.option_text})]},A.id)})}),e.jsx(H,{size:"sm",onClick:()=>y(b.id),disabled:k,children:k?"Submitting...":j?"Update Response":"Submit"})]},b.id)})]})}),e.jsxs("div",{className:"p-4 pb-[calc(1rem+env(safe-area-inset-bottom))] border-t bg-muted/30 flex flex-col items-center gap-2 sticky bottom-0 z-10",children:[e.jsx(H,{onClick:r,className:"w-full max-w-xs",children:"Got it!"}),e.jsx(H,{variant:"ghost",size:"sm",onClick:n,children:"Don't show again"})]})]})})},XUt=()=>{const{user:s}=Ms(),[t,r]=S.useState(null),[n,a]=S.useState(!1),[i,l]=S.useState(!0),[o,c]=S.useState(!1),d=S.useCallback(async()=>{if(!s){l(!1);return}try{const{data:y,error:_}=await V.from("levelup_briefs").select("*").eq("is_published",!0).lte("publish_date",new Date().toISOString()).order("publish_date",{ascending:!1}).limit(1).single();if(_||!y){l(!1);return}const{data:b}=await V.from("levelup_brief_views").select("*").eq("brief_id",y.id).eq("user_id",s.id).maybeSingle(),[j,k]=await Promise.all([V.from("levelup_brief_links").select("*").eq("brief_id",y.id).order("sort_order"),V.from("levelup_brief_polls").select("*").eq("brief_id",y.id).order("sort_order")]),T=[];if(k.data)for(const z of k.data){const{data:O}=await V.from("levelup_brief_poll_options").select("*").eq("poll_id",z.id).order("sort_order");T.push({...z,options:O||[]})}const E={brief:y,links:j.data||[],polls:T};r(E);const A=!!b,D=(b==null?void 0:b.dismissed_at)!=null,R=localStorage.getItem(`brief-dismissed-${y.id}`)==="true";if(D||R)c(!1),a(!1);else if(!A)a(!0),c(!0);else if(y.show_frequency==="every_login")a(!0),c(!0);else if(y.show_frequency==="daily"){const z=new Date(b.viewed_at);(new Date().getTime()-z.getTime())/(1e3*60*60)>=24&&(a(!0),c(!0))}else c(!1)}catch(y){console.error("Error fetching brief:",y)}finally{l(!1)}},[s]);S.useEffect(()=>{d()},[d]);const h=async()=>{if(!(!s||!t))try{const{data:y}=await V.from("levelup_brief_views").select("id").eq("brief_id",t.brief.id).eq("user_id",s.id).maybeSingle();y?await V.from("levelup_brief_views").update({viewed_at:new Date().toISOString()}).eq("id",y.id):await V.from("levelup_brief_views").insert({brief_id:t.brief.id,user_id:s.id})}catch(y){console.error("Error marking brief as viewed:",y)}};return{currentBrief:t,shouldShowPopup:n,hasUnseenBrief:o,loading:i,openBrief:()=>{a(!0)},closeBrief:()=>{a(!1),h()},dismissBrief:async()=>{if(!(!s||!t)){a(!1),c(!1);try{const{data:y,error:_}=await V.from("levelup_brief_views").select("id").eq("brief_id",t.brief.id).eq("user_id",s.id).maybeSingle();if(_&&console.error("Error checking existing brief view:",_),y){const{error:b}=await V.from("levelup_brief_views").update({dismissed_at:new Date().toISOString()}).eq("id",y.id).eq("user_id",s.id);b&&console.error("Error updating brief dismiss:",b)}else{const{error:b}=await V.from("levelup_brief_views").insert({brief_id:t.brief.id,user_id:s.id,dismissed_at:new Date().toISOString()});b&&console.error("Error inserting brief dismiss:",b)}localStorage.setItem(`brief-dismissed-${t.brief.id}`,"true")}catch(y){console.error("Error dismissing brief:",y),t&&localStorage.setItem(`brief-dismissed-${t.brief.id}`,"true")}}},refetch:d}};function QUt(){const[s,t]=S.useState(!1),[r,n]=S.useState(!1),[a,i]=S.useState(null);S.useEffect(()=>{if(localStorage.getItem("install-banner-dismissed")||window.matchMedia("(display-mode: standalone)").matches||!/iPhone|iPad|iPod|Android/i.test(navigator.userAgent))return;const m=/iPhone|iPad|iPod/i.test(navigator.userAgent);n(m),t(!0);const p=x=>{x.preventDefault(),i(x)};return window.addEventListener("beforeinstallprompt",p),()=>{window.removeEventListener("beforeinstallprompt",p)}},[]);const l=()=>{localStorage.setItem("install-banner-dismissed","true"),t(!1)},o=async()=>{if(a){await a.prompt();const{outcome:c}=await a.userChoice;c==="accepted"&&l(),i(null)}};return s?e.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:e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[e.jsx("div",{className:"flex-shrink-0 p-2 bg-primary-foreground/10 rounded-full",children:e.jsx(hi,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium text-sm",children:"Add LevelUp to your home screen"}),r?e.jsxs("p",{className:"text-xs opacity-80 flex items-center gap-1",children:["Tap ",e.jsx(IF,{className:"h-3 w-3 inline"}),' then "Add to Home Screen"']}):e.jsx("p",{className:"text-xs opacity-80",children:"Quick access anytime"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[!r&&a&&e.jsx(H,{size:"sm",variant:"secondary",onClick:o,className:"text-xs",children:"Install"}),e.jsx("button",{onClick:l,className:"p-1.5 hover:bg-primary-foreground/10 rounded-full transition-colors","aria-label":"Dismiss",children:e.jsx(Rr,{className:"h-4 w-4"})})]})]})}):null}const JUt=({children:s,onRefresh:t})=>{const[r,n]=S.useState(!1),[a,i]=S.useState(0),[l,o]=S.useState(!1),c=S.useRef(null),d=S.useRef(0),h=ns(),m=80,p=120,x=S.useCallback(k=>{const T=c.current;T&&T.scrollTop<=0&&(d.current=k.touches[0].clientY,n(!0))},[]),y=S.useCallback(k=>{if(!r||l)return;const T=c.current;if(!T||T.scrollTop>0){n(!1),i(0);return}const A=k.touches[0].clientY-d.current;if(A>0){const R=Math.min(A*.5,p);i(R),R>10&&k.preventDefault()}},[r,l]),_=S.useCallback(async()=>{if(r)if(n(!1),a>=m&&!l){o(!0),i(m);try{t?await t():await h.invalidateQueries()}catch(k){console.error("Refresh failed:",k)}finally{o(!1),i(0)}}else i(0)},[r,a,l,t,h]),b=Math.min(a/m,1),j=b*180;return e.jsxs("div",{ref:c,className:"h-full overflow-auto",onTouchStart:x,onTouchMove:y,onTouchEnd:_,children:[e.jsx("div",{className:"flex justify-center items-center overflow-hidden transition-all duration-200 ease-out",style:{height:a>0?a:0,opacity:b},children:e.jsx("div",{className:`p-2 rounded-full bg-primary/10 ${l?"animate-spin":""}`,style:{transform:l?void 0:`rotate(${j}deg)`,transition:l?void 0:"transform 0.1s ease-out"},children:e.jsx(po,{className:"h-5 w-5 text-primary"})})}),e.jsx("div",{style:{transform:a>0?`translateY(${Math.max(0,a-60)}px)`:void 0,transition:r?void 0:"transform 0.2s ease-out"},children:s})]})},Fit=()=>{const{user:s}=Ms(),[t,r]=S.useState(!1),[n,a]=S.useState(!1),[i,l]=S.useState(0),[o,c]=S.useState(!0);S.useEffect(()=>{(async()=>{if(!s){c(!1);return}try{const{data:x}=await V.from("membership_reviews").select("id").eq("user_id",s.id).maybeSingle();if(x){a(!0),r(!1),c(!1);return}const{data:y}=await V.from("profiles").select("login_count").eq("id",s.id).single(),_=(y==null?void 0:y.login_count)||0;l(_);const b=sessionStorage.getItem("review-prompt-dismissed");r(_>=4&&!b)}catch(x){console.error("Error checking review eligibility:",x)}finally{c(!1)}})()},[s]);const d=S.useCallback(()=>{sessionStorage.setItem("review-prompt-dismissed","true"),r(!1)},[]),h=S.useCallback(async(p,x)=>{if(!s)return{success:!1,error:"Not authenticated"};try{const{error:y}=await V.from("membership_reviews").insert({user_id:s.id,rating:p,review_text:x});if(y)throw y;return a(!0),r(!1),{success:!0,pointsAwarded:25}}catch(y){return console.error("Error submitting review:",y),{success:!1,error:y.message}}},[s]),m=S.useCallback(async()=>{if(s)try{await V.from("membership_reviews").update({posted_to_google:!0}).eq("user_id",s.id)}catch(p){console.error("Error updating Google review status:",p)}},[s]);return{shouldShowPrompt:t,hasSubmittedReview:n,loginCount:i,isLoading:o,dismissPrompt:d,submitReview:h,markPostedToGoogle:m}},eqt="https://search.google.com/local/writereview?placeid=ChIJM73ERQD1QogRPxupMFObuck&source=g.page.m.ia._&laa=nmx-review-solicitation-ia2",tqt=()=>{const{shouldShowPrompt:s,isLoading:t,dismissPrompt:r,submitReview:n,markPostedToGoogle:a}=Fit(),[i,l]=S.useState(!1),[o,c]=S.useState("review"),[d,h]=S.useState(0),[m,p]=S.useState(0),[x,y]=S.useState(""),[_,b]=S.useState(!1),[j,k]=S.useState(!1);if(t||!s&&!j)return null;const T=async()=>{if(d===0){En({title:"Please select a rating",variant:"destructive"});return}b(!0);const D=await n(d,x);b(!1),D.success?(k(!0),En({title:"Thank you for your feedback!",description:"Your review helps us improve."}),c("google")):En({title:"Error submitting review",description:D.error,variant:"destructive"})},E=async D=>{D&&(await navigator.clipboard.writeText(x||`${d} star rating for LevelUp!`),En({title:"Review copied!",description:"Paste it on Google Reviews."}),await a(),window.open(eqt,"_blank")),l(!1),r()},A=()=>{l(!1),r()};return e.jsxs(e.Fragment,{children:[e.jsxs("button",{onClick:()=>l(!0),className:"fixed bottom-20 left-1/2 -translate-x-1/2 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:[e.jsx(ya,{className:"h-3.5 w-3.5 fill-current"}),e.jsx("span",{className:"hidden sm:inline",children:"Leave a Review"})]}),e.jsx(bs,{open:i,onOpenChange:A,children:e.jsx(vs,{className:"sm:max-w-md",children:o==="review"?e.jsxs(e.Fragment,{children:[e.jsxs(Cs,{children:[e.jsx(Ns,{className:"text-center",children:"How are you enjoying LevelUp?"}),e.jsx(nn,{className:"text-center",children:"Your feedback helps us improve the experience for all members."})]}),e.jsxs("div",{className:"space-y-6 py-4",children:[e.jsx("div",{className:"flex justify-center gap-1",children:[1,2,3,4,5].map(D=>e.jsx("button",{type:"button",onClick:()=>h(D),onMouseEnter:()=>p(D),onMouseLeave:()=>p(0),className:"p-1 transition-transform hover:scale-110",children:e.jsx(ya,{className:Ft("h-8 w-8 transition-colors",(m||d)>=D?"fill-yellow-400 text-yellow-400":"text-muted-foreground")})},D))}),e.jsx(vr,{placeholder:"Tell us about your experience (optional)",value:x,onChange:D=>y(D.target.value),rows:4,className:"resize-none"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(H,{variant:"outline",onClick:A,className:"flex-1",children:"Maybe Later"}),e.jsx(H,{onClick:T,disabled:_||d===0,className:"flex-1",children:_?"Submitting...":"Submit Review"})]})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(Cs,{children:[e.jsx(Ns,{className:"text-center",children:"🎉 Thank you!"}),e.jsx(nn,{className:"text-center",children:"Would you mind sharing your review on Google? It really helps other agents discover LevelUp!"})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsx("p",{className:"text-center text-sm text-muted-foreground",children:"We'll copy your review so you can easily paste it."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(H,{variant:"outline",onClick:()=>E(!1),className:"flex-1",children:"No Thanks"}),e.jsx(H,{onClick:()=>E(!0),className:"flex-1",children:"Yes, Open Google"})]})]})]})})})]})};function sqt(s){const t="=".repeat((4-s.length%4)%4),r=(s+t).replace(/-/g,"+").replace(/_/g,"/"),n=window.atob(r),a=new Uint8Array(n.length);for(let i=0;i{if(!m){l(!1);return}(async()=>{try{const _="vapid_public_key";let b=localStorage.getItem(_);if(!b){const{data:T,error:E}=await V.functions.invoke("get-vapid-public-key",{body:{}});if(E)throw E;if(b=(T==null?void 0:T.vapidPublicKey)??null,!b)throw new Error("Missing VAPID public key");localStorage.setItem(_,b)}h(b);const j=await navigator.serviceWorker.register("/push-sw.js",{scope:"/push-notifications/"});c(j),r(Notification.permission);const k=await j.pushManager.getSubscription();a(!!k)}catch(_){console.error("Error initializing push notifications:",_)}finally{l(!1)}})()},[m]);const p=S.useCallback(async()=>{if(!m||!o||!s)return console.error("Push notifications not supported or user not logged in"),!1;if(!d)return he.error("Push notifications are not ready yet. Please try again in a moment."),!1;try{l(!0);const y=await o.pushManager.getSubscription();if(y){try{await y.unsubscribe()}catch(E){console.warn("Failed to unsubscribe existing push subscription:",E)}const{error:T}=await V.from("push_subscriptions").delete().eq("user_id",s.id);T&&console.warn("Failed to cleanup push_subscriptions rows:",T)}if(Notification.permission!=="granted"){const T=await Notification.requestPermission();if(r(T),T!=="granted")return T==="denied"?he.error("Notifications blocked. Please enable them in your browser settings (click the lock icon in the address bar)."):he.error("Notification permission was dismissed. Please try again."),!1}const _=sqt(d);let b;try{b=await o.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:_})}catch(T){console.error("PushManager.subscribe() failed:",T);const E=(T==null?void 0:T.message)||String(T);return E.includes("permission")?he.error("Push permission denied. Check your browser notification settings."):E.includes("key")||E.includes("VAPID")?he.error("Push configuration error. Please contact support."):E.includes("AbortError")?he.error("Push subscription was cancelled. Please try again."):he.error(`Failed to subscribe: ${E}`),!1}const j=b.toJSON(),{error:k}=await V.from("push_subscriptions").upsert({user_id:s.id,endpoint:j.endpoint,p256dh_key:j.keys.p256dh,auth_key:j.keys.auth},{onConflict:"user_id,endpoint"});if(k)throw console.error("Error saving subscription:",k),he.error("Failed to save notification preferences. Please try again."),k;return a(!0),he.success("Push notifications enabled!"),!0}catch(y){if(console.error("Error subscribing to push notifications:",y),!(y instanceof Error&&y.message.includes("toast"))){const _=y instanceof Error?y.message:"Unknown error";he.error("Failed to enable push notifications: "+_)}return!1}finally{l(!1)}},[m,o,s,d]),x=S.useCallback(async()=>{if(!o||!s)return!1;try{l(!0);const y=await o.pushManager.getSubscription();return y&&await y.unsubscribe(),await V.from("push_subscriptions").delete().eq("user_id",s.id),a(!1),he.success("Push notifications disabled"),!0}catch(y){console.error("Error unsubscribing:",y);const _=y instanceof Error?y.message:"Unknown error";return he.error("Failed to disable push notifications: "+_),!1}finally{l(!1)}},[o,s]);return{isSupported:m,permission:t,isSubscribed:n,isLoading:i,vapidPublicKey:d,subscribe:p,unsubscribe:x}}const Abe="push_notification_prompt_dismissed",rqt=["/dashboard","/admin"],nqt=()=>{const{user:s}=Ms(),{isSupported:t,isSubscribed:r,isLoading:n,subscribe:a}=Bit(),i=Vc(),[l,o]=S.useState(!1),[c,d]=S.useState(!1),h=rqt.some(x=>i.pathname===x||i.pathname.startsWith(`${x}/`));S.useEffect(()=>{if(h){o(!1);return}if(!s||!t||r||n||localStorage.getItem(`${Abe}_${s.id}`))return;const y=setTimeout(()=>{o(!0)},2e3);return()=>clearTimeout(y)},[s,t,r,n,h]);const m=async()=>{d(!0);const x=await a();d(!1),x&&(s&&localStorage.setItem(`${Abe}_${s.id}`,"true"),o(!1))},p=()=>{s&&localStorage.setItem(`${Abe}_${s.id}`,"true"),o(!1)};return!t||r||h?null:e.jsx(bs,{open:l,onOpenChange:x=>!x&&p(),children:e.jsxs(vs,{className:"sm:max-w-md",children:[e.jsxs(Cs,{children:[e.jsx("div",{className:"mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-primary/10",children:e.jsx(wp,{className:"h-6 w-6 text-primary"})}),e.jsx(Ns,{className:"text-center",children:"Stay in the Loop!"}),e.jsx(nn,{className:"text-center",children:"Enable push notifications to get alerted when:"})]}),e.jsxs("ul",{className:"my-4 space-y-2 text-sm text-muted-foreground",children:[e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-primary",children:"•"})," New events go live"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-primary",children:"•"})," Fresh templates are added"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-primary",children:"•"})," New toolbox resources drop"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-primary",children:"•"})," Social swag updates"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-primary",children:"•"})," New newsletters arrive"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-primary",children:"•"})," Posts in your community groups"]})]}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx(H,{onClick:m,disabled:c,className:"w-full",children:c?"Enabling...":"Enable Notifications"}),e.jsx(H,{variant:"ghost",onClick:p,className:"w-full",children:"Not Now"})]}),e.jsx("p",{className:"text-center text-xs text-muted-foreground",children:"You can always change this in your Profile settings."})]})})},J7e=s=>{let t;const r=new Set,n=(d,h)=>{const m=typeof d=="function"?d(t):d;if(!Object.is(m,t)){const p=t;t=h??(typeof m!="object"||m===null)?m:Object.assign({},t,m),r.forEach(x=>x(t,p))}},a=()=>t,o={setState:n,getState:a,getInitialState:()=>c,subscribe:d=>(r.add(d),()=>r.delete(d))},c=t=s(n,a,o);return o},aqt=s=>s?J7e(s):J7e,iqt=s=>s;function oqt(s,t=iqt){const r=Nt.useSyncExternalStore(s.subscribe,Nt.useCallback(()=>t(s.getState()),[s,t]),Nt.useCallback(()=>t(s.getInitialState()),[s,t]));return Nt.useDebugValue(r),r}const e9e=s=>{const t=aqt(s),r=n=>oqt(t,n);return Object.assign(r,t),r},lqt=s=>s?e9e(s):e9e;function cqt(s,t){let r;try{r=s()}catch{return}return{getItem:a=>{var i;const l=c=>c===null?null:JSON.parse(c,void 0),o=(i=r.getItem(a))!=null?i:null;return o instanceof Promise?o.then(l):l(o)},setItem:(a,i)=>r.setItem(a,JSON.stringify(i,void 0)),removeItem:a=>r.removeItem(a)}}const zNe=s=>t=>{try{const r=s(t);return r instanceof Promise?r:{then(n){return zNe(n)(r)},catch(n){return this}}}catch(r){return{then(n){return this},catch(n){return zNe(n)(r)}}}},dqt=(s,t)=>(r,n,a)=>{let i={storage:cqt(()=>window.localStorage),partialize:b=>b,version:0,merge:(b,j)=>({...j,...b}),...t},l=!1,o=0;const c=new Set,d=new Set;let h=i.storage;if(!h)return s((...b)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),r(...b)},n,a);const m=()=>{const b=i.partialize({...n()});return h.setItem(i.name,{state:b,version:i.version})},p=a.setState;a.setState=(b,j)=>(p(b,j),m());const x=s((...b)=>(r(...b),m()),n,a);a.getInitialState=()=>x;let y;const _=()=>{var b,j;if(!h)return;const k=++o;l=!1,c.forEach(E=>{var A;return E((A=n())!=null?A:x)});const T=((j=i.onRehydrateStorage)==null?void 0:j.call(i,(b=n())!=null?b:x))||void 0;return zNe(h.getItem.bind(h))(i.name).then(E=>{if(E)if(typeof E.version=="number"&&E.version!==i.version){if(i.migrate){const A=i.migrate(E.state,E.version);return A instanceof Promise?A.then(D=>[!0,D]):[!0,A]}console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,E.state];return[!1,void 0]}).then(E=>{var A;if(k!==o)return;const[D,R]=E;if(y=i.merge(R,(A=n())!=null?A:x),r(y,!0),D)return m()}).then(()=>{k===o&&(T==null||T(n(),void 0),y=n(),l=!0,d.forEach(E=>E(y)))}).catch(E=>{k===o&&(T==null||T(void 0,E))})};return a.persist={setOptions:b=>{i={...i,...b},b.storage&&(h=b.storage)},clearStorage:()=>{h==null||h.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>_(),hasHydrated:()=>l,onHydrate:b=>(c.add(b),()=>{c.delete(b)}),onFinishHydration:b=>(d.add(b),()=>{d.delete(b)})},i.skipHydration||_(),y||x},uqt=dqt,Yge=lqt()(uqt((s,t)=>({cartItems:[],addToCart:(r,n,a=1,i)=>{s(l=>{const o=l.cartItems.findIndex(c=>{var d;return c.product.id===r.id&&((d=c.variant)==null?void 0:d.id)===(n==null?void 0:n.id)});if(o>=0){const c=[...l.cartItems];return c[o].quantity+=a,i&&(c[o].artworkUrl=i),{cartItems:c}}return{cartItems:[...l.cartItems,{product:r,variant:n,quantity:a,artworkUrl:i}]}})},removeFromCart:(r,n)=>{s(a=>({cartItems:a.cartItems.filter(i=>{var l;return!(i.product.id===r&&((l=i.variant)==null?void 0:l.id)===n)})}))},updateQuantity:(r,n,a)=>{s(i=>({cartItems:i.cartItems.map(l=>{var o;return l.product.id===r&&((o=l.variant)==null?void 0:o.id)===n?{...l,quantity:Math.max(1,a)}:l})}))},updateArtwork:(r,n,a)=>{s(i=>({cartItems:i.cartItems.map(l=>{var o;return l.product.id===r&&((o=l.variant)==null?void 0:o.id)===n?{...l,artworkUrl:a}:l})}))},clearCart:()=>s({cartItems:[]}),getItemPrice:r=>{const n=Number(r.product.base_price),a=r.variant?Number(r.variant.price_adjustment):0;return n+a},getSubtotal:()=>{const{cartItems:r,getItemPrice:n}=t();return r.reduce((a,i)=>a+n(i)*i.quantity,0)},getShippingTotal:()=>{const{cartItems:r}=t();return r.reduce((n,a)=>n+Number(a.product.shipping_fee)*a.quantity,0)},getTotal:()=>{const{getSubtotal:r,getShippingTotal:n}=t();return r()+n()}}),{name:"marketplace-cart",partialize:s=>({cartItems:s.cartItems})}));function av(){const{user:s}=Ms(),{data:t,isLoading:r}=yt({queryKey:["agent-lead-site",s==null?void 0:s.id],queryFn:async()=>{const{data:n,error:a}=await V.from("lead_sites").select("id, subdomain_slug, site_title, is_active, mls_agent_id, mls_agent_key, mls_office_id").eq("agent_id",s.id).eq("is_active",!0).order("created_at",{ascending:!0}).limit(1).maybeSingle();if(a)throw a;return n},enabled:!!s,staleTime:5*60*1e3});return{leadSite:t??null,hasLeadSite:!!t,isLoading:r,siteUrl:t?`https://${t.subdomain_slug}.thelocalmove.com`:null}}const t9e="dashboard-sidebar-collapsed",Ss=({children:s,title:t})=>{var ct;const{user:r,signOut:n,isAdmin:a,isBrokerageManager:i,isCoach:l,brokerageId:o}=Ms(),{isAssistant:c,actingAsAgent:d,hasPermission:h}=V3e(),{isImpersonating:m}=age(),x=(c&&!!d?40:0)+(m?40:0),{avatarUrl:y}=Kat(r==null?void 0:r.id),{isTrial:_,isExpired:b,expiresAt:j}=T$t(r==null?void 0:r.id),{isInnerCircleEnabled:k,isMarketplaceEnabled:T}=Zat(),{currentBrief:E,shouldShowPopup:A,hasUnseenBrief:D,openBrief:R,closeBrief:z,dismissBrief:O}=XUt(),{unreadCount:$}=E$t(),{openCount:ee}=A$t(),{data:Z}=sv(),J=!!Z,re=Yge(Ue=>Ue.cartItems).reduce((Ue,et)=>Ue+et.quantity,0),{leadSite:ie,hasLeadSite:ce,siteUrl:ne}=av(),le=Fr(),be=Vc(),[fe,je]=S.useState(null);S.useEffect(()=>{r!=null&&r.id&&V.from("profiles").select("name").eq("id",r.id).single().then(({data:Ue})=>{Ue!=null&&Ue.name&&je(Ue.name)})},[r==null?void 0:r.id]);const ve=fe||((ct=r==null?void 0:r.user_metadata)==null?void 0:ct.name)||(r==null?void 0:r.email)||"User",[We,Ve]=S.useState(()=>typeof window<"u"?localStorage.getItem(t9e)==="true":!1);S.useEffect(()=>{localStorage.setItem(t9e,String(We))},[We]);const[Le,Me]=S.useState({agentos:!0,tools:!0,marketing:!0,learning:!0,community:!0,contacts:!0,website:!0,help:!1}),ze=Ue=>{Me(et=>({...et,[Ue]:!et[Ue]}))},Pe=Ue=>Ue.split(" ").map(et=>et[0]).join("").toUpperCase().slice(0,2),Ie=Ue=>be.pathname===Ue,De=Ue=>Ue.some(et=>be.pathname===et),pe=({path:Ue,icon:et,label:Qe,badgeCount:Ne})=>{const $e=e.jsxs(H,{variant:"ghost",size:"sm",className:Ft("text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground relative",Ie(Ue)&&"bg-sidebar-accent text-sidebar-accent-foreground",We?"w-10 h-10 p-0 justify-center":"w-full justify-start gap-2"),onClick:()=>le(Ue),children:[e.jsxs("div",{className:"relative",children:[e.jsx(et,{className:"h-4 w-4 shrink-0"}),We&&Ne!=null&&Ne>0&&e.jsx("span",{className:"absolute -top-1 -right-1 h-2 w-2 rounded-full bg-muted-foreground/40 border border-background"})]}),!We&&Qe,!We&&Ne!=null&&Ne>0&&e.jsx("span",{className:"ml-auto flex h-5 w-5 items-center justify-center rounded-full bg-muted text-muted-foreground text-xs font-medium border border-muted-foreground/20",children:Ne>9?"9+":Ne})]});return We?e.jsxs(rd,{delayDuration:0,children:[e.jsx(nd,{asChild:!0,children:$e}),e.jsxs(Rc,{side:"right",className:"flex items-center gap-2",children:[Qe,Ne!=null&&Ne>0&&e.jsx("span",{className:"flex h-5 w-5 items-center justify-center rounded-full bg-muted text-muted-foreground text-xs font-medium border border-muted-foreground/20",children:Ne>9?"9+":Ne})]})]}):$e},tt=({id:Ue,label:et,icon:Qe,children:Ne,activePaths:$e,showBetaBadge:it,defaultPath:Je,badgeCount:st})=>{if(We){const mt=Je||$e[0];return e.jsxs(rd,{delayDuration:0,children:[e.jsx(nd,{asChild:!0,children:e.jsx(H,{variant:"ghost",size:"sm",className:Ft("w-10 h-10 p-0 justify-center text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground relative",De($e)&&"text-primary"),onClick:()=>le(mt),children:e.jsxs("div",{className:"relative",children:[e.jsx(Qe,{className:"h-4 w-4"}),st!=null&&st>0&&e.jsx("span",{className:"absolute -top-1 -right-1 h-2 w-2 rounded-full bg-muted-foreground/40 border border-background"})]})})}),e.jsxs(Rc,{side:"right",className:"flex items-center gap-2",children:[et,it&&e.jsx("span",{className:"text-[9px] font-bold uppercase tracking-wide px-1 py-0.5 rounded border border-amber-500 text-amber-600",children:"Beta"}),st!=null&&st>0&&e.jsx("span",{className:"flex h-5 w-5 items-center justify-center rounded-full bg-muted text-muted-foreground text-xs font-medium border border-muted-foreground/20",children:st>9?"9+":st})]})]})}return e.jsxs(m0,{open:Le[Ue],onOpenChange:()=>ze(Ue),children:[e.jsx(f0,{asChild:!0,children:e.jsxs(H,{variant:"ghost",size:"sm",className:Ft("w-full justify-between gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",De($e)&&"text-primary"),children:[e.jsxs("span",{className:"flex items-center gap-2 font-semibold text-[15px]",children:[e.jsx(Qe,{className:"h-4 w-4"}),et,it&&e.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"})]}),e.jsxs("span",{className:"flex items-center gap-1",children:[st!=null&&st>0&&e.jsx("span",{className:"flex h-5 w-5 items-center justify-center rounded-full bg-muted text-muted-foreground text-xs font-medium border border-muted-foreground/20",children:st>9?"9+":st}),e.jsx(Io,{className:Ft("h-4 w-4 transition-transform duration-200",Le[Ue]&&"rotate-180")})]})]})}),e.jsx(p0,{className:"pl-4 space-y-1 mt-1",children:Ne})]})},ge=({isMobile:Ue=!1})=>{const et=Ue?!1:We;return e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsxs("div",{className:Ft("p-3 border-b border-sidebar-border",et?"flex flex-col items-center gap-2":"flex items-center justify-between"),children:[et?e.jsx("img",{src:R$t,alt:"LevelUp",className:"h-8 w-auto"}):e.jsx("img",{src:D$t,alt:"LevelUp",className:"h-8 w-auto"}),!Ue&&e.jsxs(rd,{delayDuration:0,children:[e.jsx(nd,{asChild:!0,children:e.jsx(H,{variant:"ghost",size:"icon",className:"h-8 w-8 shrink-0",onClick:()=>Ve(!et),children:e.jsx(fl,{className:Ft("h-4 w-4 transition-transform duration-300",et&&"rotate-180")})})}),e.jsx(Rc,{side:"right",children:et?"Expand sidebar":"Collapse sidebar"})]})]}),e.jsx(Ci,{className:"flex-1 [&_[data-radix-scroll-area-scrollbar]]:w-1.5",children:e.jsxs("nav",{className:Ft("p-3 space-y-1",et&&"flex flex-col items-center"),children:[Ue&&_&&!b&&e.jsx("button",{type:"button",onClick:()=>le("/subscription"),className:Ft("relative w-full overflow-hidden rounded-md p-[1.5px] mb-2","bg-[linear-gradient(120deg,#f59e0b,#ef4444,#a855f7,#f59e0b)] bg-[length:200%_200%]","animate-gradient-x shadow-lg shadow-amber-500/20"),children:e.jsxs("span",{className:"flex items-center gap-2 rounded-[5px] bg-sidebar px-3 py-2 text-sm font-semibold text-sidebar-foreground",children:[e.jsx(Lr,{className:"h-4 w-4 text-amber-500 animate-pulse"}),e.jsx("span",{className:"flex-1 text-left bg-[linear-gradient(90deg,#f59e0b,#ef4444,#a855f7)] bg-clip-text text-transparent",children:"Ready to Upgrade?"}),j&&e.jsxs("span",{className:"text-[10px] font-bold uppercase tracking-wide px-1.5 py-0.5 rounded bg-amber-500/15 text-amber-600 dark:text-amber-400 border border-amber-500/30",children:[Math.max(0,Math.ceil((new Date(j).getTime()-Date.now())/864e5)),"d left"]})]})}),e.jsx(pe,{path:"/dashboard",icon:wE,label:"Dashboard"}),e.jsx(pe,{path:"/apps",icon:by,label:"Apps & Tools"}),We?e.jsxs(rd,{delayDuration:0,children:[e.jsx(nd,{asChild:!0,children:e.jsxs(H,{variant:"ghost",size:"sm",className:Ft("w-10 h-10 p-0 justify-center relative text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Ie("/levelup-u")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>le("/levelup-u"),children:[e.jsx(Vu,{className:"h-4 w-4 shrink-0"}),e.jsx("span",{className:"absolute -top-0.5 -right-0.5 h-2 w-2 rounded-full bg-primary animate-pulse"})]})}),e.jsxs(Rc,{side:"right",className:"flex items-center gap-2",children:["LevelUp U",e.jsx("span",{className:"text-[10px] font-bold uppercase tracking-wider text-primary-foreground bg-primary rounded px-1 py-0.5",children:"New"})]})]}):e.jsxs(H,{variant:"ghost",size:"sm",className:Ft("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Ie("/levelup-u")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>le("/levelup-u"),children:[e.jsx(Vu,{className:"h-4 w-4 shrink-0"}),"LevelUp U",e.jsx("span",{className:"ml-auto text-[10px] font-bold uppercase tracking-wider text-primary-foreground bg-primary rounded px-1.5 py-0.5",children:"New"})]}),e.jsx(pe,{path:"/events",icon:xu,label:"Events"}),e.jsxs(tt,{id:"agentos",label:"Agent OS",icon:MI,activePaths:["/mission-control","/mission-control/contacts","/mission-control/plans","/mission-control/popbys","/mission-control/video-library","/mission-control/scorecard","/mission-control/listings","/mission-control/pipeline","/mission-control/tasks","/mission-control/smart-drips","/mission-control/relationship-scorecard","/mission-control/sphere-gaps","/mission-control/signals","/mission-control/connect-page","/mission-control/client-portals","/mission-control/vendors","/mission-control/portal-referrals"],showBetaBadge:!0,defaultPath:"/mission-control",children:[h("contacts")&&e.jsx(pe,{path:"/mission-control",icon:Bi,label:"Mission Control"}),h("contacts")&&!et&&e.jsxs(m0,{open:Le.contacts,onOpenChange:()=>ze("contacts"),children:[e.jsx(f0,{asChild:!0,children:e.jsxs(H,{variant:"ghost",size:"sm",className:Ft("w-full justify-between gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",De(["/mission-control/contacts","/mission-control/relationship-scorecard","/mission-control/sphere-gaps","/mission-control/connect-page"])&&"text-primary"),children:[e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Ar,{className:"h-4 w-4"}),"Contacts"]}),e.jsx(Io,{className:Ft("h-3.5 w-3.5 transition-transform duration-200",Le.contacts&&"rotate-180")})]})}),e.jsxs(p0,{className:"pl-4 pr-1 space-y-0.5 mt-0.5",children:[e.jsx(pe,{path:"/mission-control/contacts",icon:Ar,label:"All Contacts"}),e.jsx(pe,{path:"/mission-control/relationship-scorecard",icon:ef,label:"Relationship Report"}),e.jsx(pe,{path:"/mission-control/sphere-gaps",icon:AF,label:"Sphere Gaps"}),e.jsx(pe,{path:"/mission-control/sent-emails",icon:yn,label:"Sent Emails"}),e.jsx(pe,{path:"/mission-control/connect-page",icon:ql,label:"Connect Page"})]})]}),h("contacts")&&et&&e.jsx(pe,{path:"/mission-control/contacts",icon:Ar,label:"Contacts"}),h("contacts")&&e.jsx(pe,{path:"/mission-control/plans",icon:xu,label:"TouchPlans"}),h("pipeline")&&e.jsx(pe,{path:"/mission-control/pipeline",icon:p_,label:"Deal Pipeline"}),h("pipeline")&&e.jsx(pe,{path:"/mission-control/tasks",icon:j2,label:"Tasks"}),h("popbys")&&e.jsx(pe,{path:"/mission-control/popbys",icon:Di,label:"Popbys"}),h("videos")&&e.jsx(pe,{path:"/mission-control/video-library",icon:xn,label:"Video Library"}),h("scorecard")&&e.jsx(pe,{path:"/mission-control/scorecard",icon:Bo,label:"Scorecard"}),h("listings")&&e.jsx(pe,{path:"/mission-control/listings",icon:Xa,label:"Listing Exchange"}),e.jsx(pe,{path:"/mission-control/client-portals",icon:Lr,label:"Client Portals"}),e.jsx(pe,{path:"/mission-control/signals",icon:WI,label:"Signals"}),!et&&e.jsxs(H,{variant:"ghost",size:"sm",className:Ft("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Ie("/mission-control/smart-drips")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>le("/mission-control/smart-drips"),children:[e.jsx(ym,{className:"h-4 w-4"}),"Smart Drips",e.jsx("span",{className:"ml-auto 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"})]}),et&&e.jsx(pe,{path:"/mission-control/smart-drips",icon:ym,label:"Smart Drips"})]}),ce&&ie&&e.jsxs(tt,{id:"website",label:"My Website",icon:ld,activePaths:[`/admin/lead-sites/${ie.id}/edit`],defaultPath:`/admin/lead-sites/${ie.id}/edit`,children:[et?e.jsxs(rd,{delayDuration:0,children:[e.jsx(nd,{asChild:!0,children:e.jsx(H,{variant:"ghost",size:"sm",className:"w-10 h-10 p-0 justify-center text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",onClick:()=>window.open(ne||"#","_blank"),children:e.jsx(Bn,{className:"h-4 w-4"})})}),e.jsx(Rc,{side:"right",children:"View Site"})]}):e.jsxs(H,{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(ne||"#","_blank"),children:[e.jsx(Bn,{className:"h-4 w-4"}),"View Site",e.jsx(gn,{className:"h-3 w-3 ml-auto opacity-50"})]}),e.jsx(pe,{path:`/my-website/${ie.id}/edit`,icon:ni,label:"Edit Website"}),e.jsx(pe,{path:"/my-website/mls-listings",icon:Fn,label:"MLS Listings"}),e.jsx(pe,{path:"/my-website/market-report",icon:Bo,label:"Market Reports"}),e.jsx(pe,{path:"/mission-control/website-activity",icon:ef,label:"Website Activity"}),e.jsx(pe,{path:"/m",icon:Vy,label:"Mobile Command"})]}),e.jsxs(tt,{id:"marketing",label:"Marketing",icon:ph,activePaths:["/templates","/social-swag-2","/newsletters","/website-apps","/marketing-studio"],defaultPath:"/templates",children:[e.jsx(pe,{path:"/templates",icon:pl,label:"Templates"}),e.jsx(pe,{path:"/marketing-studio",icon:wl,label:"Marketing Studio"}),e.jsx(pe,{path:"/social-swag-2",icon:Vy,label:"Social Swag"}),We?e.jsxs(rd,{delayDuration:0,children:[e.jsx(nd,{asChild:!0,children:e.jsxs(H,{variant:"ghost",size:"sm",className:Ft("w-10 h-10 p-0 justify-center relative text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Ie("/newsletters")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>le("/newsletters"),children:[e.jsx(x_,{className:"h-4 w-4 shrink-0"}),e.jsx("span",{className:"absolute -top-0.5 -right-0.5 h-2 w-2 rounded-full bg-primary animate-pulse"})]})}),e.jsxs(Rc,{side:"right",className:"flex items-center gap-2",children:["Newsletter Pro",e.jsx("span",{className:"text-[10px] font-bold uppercase tracking-wider text-primary-foreground bg-primary rounded px-1 py-0.5",children:"New"})]})]}):e.jsxs(H,{variant:"ghost",size:"sm",className:Ft("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Ie("/newsletters")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>le("/newsletters"),children:[e.jsx(x_,{className:"h-4 w-4 shrink-0"}),"Newsletter Pro",e.jsx("span",{className:"ml-auto text-[10px] font-bold uppercase tracking-wider text-primary-foreground bg-primary rounded px-1.5 py-0.5",children:"New"})]}),e.jsx(pe,{path:"/website-apps",icon:Lr,label:"Website Apps"})]}),e.jsxs(tt,{id:"learning",label:"Learning",icon:tf,activePaths:["/academy","/toolbox"],defaultPath:"/academy",children:[e.jsx(pe,{path:"/academy",icon:Vu,label:"Academy"}),e.jsx(pe,{path:"/toolbox",icon:N1,label:"Toolbox"})]}),e.jsxs(tt,{id:"community",label:"Community",icon:Gi,activePaths:["/community","/wishlist"],defaultPath:"/community",badgeCount:$,children:[e.jsx(pe,{path:"/community",icon:Ar,label:"Community",badgeCount:$}),e.jsx(pe,{path:"/wishlist",icon:q2,label:"Wishlist",badgeCount:ee}),!et&&e.jsxs(H,{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/share/g/1CC6thti2V/","_blank"),children:[e.jsx(gn,{className:"h-4 w-4"}),"Facebook Group"]})]}),e.jsxs(tt,{id:"goods",label:"The Goods",icon:sx,activePaths:["/marketplace","/reward-store"],defaultPath:"/reward-store",children:[T&&!et&&e.jsxs(H,{variant:"ghost",size:"sm",className:Ft("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",be.pathname.startsWith("/marketplace")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>le("/marketplace"),children:[e.jsx(sx,{className:"h-4 w-4"}),"Marketplace",e.jsx("span",{className:"ml-auto text-[9px] font-bold uppercase tracking-wide px-1.5 py-0.5 rounded-full bg-primary text-primary-foreground",children:"New"})]}),T&&et&&e.jsx(pe,{path:"/marketplace",icon:sx,label:"Marketplace"}),e.jsx(pe,{path:"/reward-store",icon:To,label:"Reward Store"}),e.jsx(pe,{path:"/refer-friends",icon:Di,label:"Refer & Earn"})]}),e.jsxs(tt,{id:"help",label:"Help & Services",icon:v2,activePaths:["/support","/additional-services"],defaultPath:"/support",children:[e.jsx(pe,{path:"/support",icon:zI,label:"Support"}),e.jsx(pe,{path:"/additional-services",icon:Lr,label:"Additional Services"})]}),l&&e.jsx("div",{className:"pt-3 border-t border-sidebar-border mt-3 space-y-1",children:e.jsx(pe,{path:"/coaching",icon:Vu,label:"Coaching"})}),e.jsx(hqt,{}),a&&e.jsxs(e.Fragment,{children:[!et&&e.jsx("div",{className:"pt-3 pb-1",children:e.jsx("p",{className:"px-2 text-xs font-semibold text-muted-foreground uppercase tracking-wider",children:"Admin"})}),et?e.jsx("div",{className:"pt-3 border-t border-sidebar-border mt-3 space-y-1",children:e.jsx(pe,{path:"/admin",icon:Td,label:"Admin Dashboard"})}):e.jsxs(H,{variant:"ghost",size:"sm",className:Ft("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",be.pathname==="/admin"&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>le("/admin"),children:[e.jsx(Td,{className:"h-4 w-4"}),"Admin Dashboard"]})]}),(o||i)&&!a&&e.jsxs(e.Fragment,{children:[!et&&e.jsx("div",{className:"pt-3 pb-1",children:e.jsx("p",{className:"px-2 text-xs font-semibold text-muted-foreground uppercase tracking-wider",children:"My Brokerage"})}),et?e.jsxs("div",{className:"border-t border-sidebar-border mt-3 pt-3 space-y-1",children:[o&&e.jsxs(e.Fragment,{children:[e.jsx(pe,{path:"/my-brokerage",icon:Xa,label:"My Brokerage"}),e.jsx(pe,{path:"/brokerage/help-board",icon:i1,label:"Help Board"}),e.jsx(pe,{path:"/brokerage-content",icon:tf,label:"Brokerage Content"})]}),J&&!i&&e.jsx(pe,{path:"/my-team",icon:Ar,label:"My Team"}),i&&e.jsxs(e.Fragment,{children:[e.jsx(pe,{path:"/brokerage/dashboard",icon:Go,label:"Manage Brokerages"}),e.jsx(pe,{path:"/brokerage/teams",icon:Ar,label:"Teams"}),e.jsx(pe,{path:"/brokerage/recruiting",icon:ph,label:"Recruiting"}),e.jsx(pe,{path:"/brokerage/vendors",icon:zk,label:"Vendors"}),e.jsx(pe,{path:"/brokerage-resources",icon:pm,label:"Brokerage Resources"})]})]}):e.jsxs(e.Fragment,{children:[o&&e.jsxs(e.Fragment,{children:[e.jsxs(H,{variant:"ghost",size:"sm",className:Ft("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Ie("/my-brokerage")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>le("/my-brokerage"),children:[e.jsx(Xa,{className:"h-4 w-4"}),"My Brokerage"]}),e.jsxs(H,{variant:"ghost",size:"sm",className:Ft("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Ie("/brokerage/help-board")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>le("/brokerage/help-board"),children:[e.jsx(i1,{className:"h-4 w-4"}),"Help Board"]}),e.jsxs(H,{variant:"ghost",size:"sm",className:Ft("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Ie("/brokerage-content")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>le("/brokerage-content"),children:[e.jsx(tf,{className:"h-4 w-4"}),"Brokerage Content"]})]}),J&&!i&&e.jsxs(H,{variant:"ghost",size:"sm",className:Ft("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Ie("/my-team")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>le("/my-team"),children:[e.jsx(Ar,{className:"h-4 w-4"}),"My Team"]}),i&&e.jsxs(e.Fragment,{children:[e.jsxs(H,{variant:"ghost",size:"sm",className:Ft("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Ie("/brokerage/dashboard")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>le("/brokerage/dashboard"),children:[e.jsx(Go,{className:"h-4 w-4"}),"Manage Brokerages"]}),e.jsxs(H,{variant:"ghost",size:"sm",className:Ft("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Ie("/brokerage/teams")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>le("/brokerage/teams"),children:[e.jsx(Ar,{className:"h-4 w-4"}),"Teams",e.jsx("span",{className:"ml-auto 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:"New"})]}),e.jsxs(H,{variant:"ghost",size:"sm",className:Ft("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Ie("/brokerage/recruiting")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>le("/brokerage/recruiting"),children:[e.jsx(ph,{className:"h-4 w-4"}),"Recruiting"]}),e.jsxs(H,{variant:"ghost",size:"sm",className:Ft("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Ie("/brokerage/vendors")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>le("/brokerage/vendors"),children:[e.jsx(zk,{className:"h-4 w-4"}),"Vendors"]}),e.jsxs(H,{variant:"ghost",size:"sm",className:Ft("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Ie("/brokerage-resources")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>le("/brokerage-resources"),children:[e.jsx(pm,{className:"h-4 w-4"}),"Brokerage Resources"]})]})]})]})]})}),e.jsxs("div",{className:"p-3 border-t border-sidebar-border md:hidden",children:[e.jsxs(H,{variant:"ghost",size:"sm",className:Ft("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Ie("/profile")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>le("/profile"),children:[e.jsx(io,{className:"h-4 w-4"}),"Profile"]}),e.jsxs(H,{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:[e.jsx(UI,{className:"h-4 w-4"}),"Sign Out"]})]})]})};return e.jsx(xj,{children:e.jsxs("div",{className:"min-h-screen bg-background flex",children:[_&&b&&be.pathname!=="/subscription"&&e.jsx(FUt,{}),typeof document<"u"&&tx.createPortal(e.jsx("aside",{className:Ft("hidden md:flex flex-col bg-card border-r border-border fixed left-0 z-30 !pointer-events-auto transition-[width] duration-300",We?"w-16":"w-56"),style:{top:`${x}px`,height:`calc(100vh - ${x}px)`},children:e.jsx(ge,{})}),document.body),e.jsxs("div",{className:Ft("flex-1 flex flex-col overflow-hidden transition-all duration-300",We?"md:ml-16":"md:ml-56"),style:{height:`calc(100vh - ${x}px)`,marginTop:`${x}px`},children:[e.jsx("header",{className:"sticky top-0 z-40 bg-card border-b border-border flex-shrink-0",children:e.jsxs("div",{className:"flex items-center justify-between px-6 py-3",children:[e.jsxs($S,{children:[e.jsx(b5e,{asChild:!0,children:e.jsx(H,{variant:"ghost",size:"icon",className:"md:hidden",children:e.jsx(TE,{className:"h-5 w-5"})})}),e.jsx(vj,{side:"left",className:"w-56 p-0 bg-card",children:e.jsx(ge,{isMobile:!0})})]}),e.jsx("div",{className:"flex-1 md:hidden",children:e.jsx("img",{src:O$t,alt:"LevelUp",className:"h-8 w-auto"})}),e.jsx("div",{className:"hidden md:flex flex-1 justify-center",children:e.jsx(Q7e,{})}),e.jsxs("div",{className:"flex items-center gap-3 ml-auto",children:[_&&!b&&j&&e.jsx(OUt,{expiresAt:j,className:"hidden lg:flex"}),e.jsx("div",{className:"md:hidden",children:e.jsx(Q7e,{})}),E&&e.jsx(BUt,{hasUnseenBrief:D,onClick:R}),T&&e.jsxs(H,{variant:"ghost",size:"icon",className:"relative",onClick:()=>le("/marketplace/cart"),children:[e.jsx(sx,{className:"h-5 w-5"}),re>0&&e.jsx("span",{className:"absolute -top-1 -right-1 h-5 w-5 rounded-full bg-primary text-primary-foreground text-xs font-medium flex items-center justify-center",children:re>99?"99+":re})]}),e.jsx(cUt,{}),e.jsx(ONe,{}),e.jsxs("span",{className:"hidden sm:block text-sm font-medium text-foreground",children:["Hello, ",ve.split(" ")[0],"!"]}),e.jsxs(Xu,{children:[e.jsx(Qu,{asChild:!0,children:e.jsx("button",{className:"focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 rounded-full",children:e.jsxs(Un,{className:"h-9 w-9 cursor-pointer hover:opacity-80 transition-opacity",children:[e.jsx(Ka,{src:y||void 0}),e.jsx(qn,{className:"bg-primary text-primary-foreground font-medium text-sm",children:Pe(ve)})]})})}),e.jsxs(wu,{align:"end",className:"w-48",children:[e.jsxs(di,{onClick:()=>le("/profile"),className:"cursor-pointer",children:[e.jsx(io,{className:"h-4 w-4 mr-2"}),"Profile"]}),e.jsxs(di,{onClick:()=>le("/mission-control/integrations"),className:"cursor-pointer",children:[e.jsx(IE,{className:"h-4 w-4 mr-2"}),"Integrations"]}),e.jsxs(di,{onClick:()=>le("/mission-control/browser-extension"),className:"cursor-pointer",children:[e.jsx(IE,{className:"h-4 w-4 mr-2"}),"Browser Extension"]}),e.jsx(A_,{}),e.jsxs(di,{onClick:n,className:"cursor-pointer text-destructive focus:text-destructive",children:[e.jsx(UI,{className:"h-4 w-4 mr-2"}),"Sign Out"]})]})]})]})]})}),e.jsx(JUt,{children:e.jsx("main",{className:"p-4 sm:p-6 lg:p-8 overflow-x-hidden",children:s})}),E&&e.jsx(ZUt,{brief:E,open:A,onClose:z,onDismiss:O}),e.jsx(QUt,{}),e.jsx(tqt,{}),e.jsx(nqt,{})]})]})})};function hqt(){const{user:s}=Ms(),t=Vc(),r=Fr(),{data:n}=yt({queryKey:["my-coach-nav",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:i}=await V.from("coaching_assignments").select("id").eq("agent_id",s.id).eq("status","active").limit(1);return(i||[]).length>0}});if(!n)return null;const a=t.pathname==="/my-coach";return e.jsx("div",{className:"pt-3 border-t border-sidebar-border mt-3 space-y-1",children:e.jsxs(H,{variant:"ghost",size:"sm",className:`w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground ${a?"bg-sidebar-accent text-sidebar-accent-foreground":""}`,onClick:()=>r("/my-coach"),children:[e.jsx(Vu,{className:"h-4 w-4"}),"My Coach"]})})}const mqt=()=>{const{user:s}=Ms(),[t,r]=S.useState(!1),[n,a]=S.useState(null),[i,l]=S.useState(""),o=async m=>{var p;if(!(s!=null&&s.email)){he.error("Please sign in to upgrade");return}r(!0),a(m);try{const{data:x,error:y}=await V.functions.invoke("create-checkout",{body:{tier:m,email:s.email,name:((p=s.user_metadata)==null?void 0:p.full_name)||s.email,couponCode:i.trim()||void 0,skipTrial:!0}});if(y)throw y;if(x!=null&&x.url)window.open(x.url,"_blank","noopener,noreferrer"),he.success("Checkout opened in a new tab");else throw new Error("No checkout URL returned")}catch(x){console.error("Checkout error:",x),he.error(x.message||"Failed to start checkout. Please try again.")}finally{r(!1),a(null)}},c=["Unlimited access to all marketing templates","Complete Academy training library","AI-powered tools and resources","Community forums and support","Exclusive member events and workshops","Deal pipeline & scorecard tracking","Listing exchange access","Social media content library"],d=["Everything in Individual plan","Up to 25 agent seats","Brokerage admin dashboard","Team performance analytics","Custom branding options","Priority support","Agent onboarding tools","Brokerage-wide announcements"],h=["Everything in Brokerage plan","Unlimited agent seats","Dedicated account manager","Advanced analytics & reporting","White-label options","API access","Custom integrations","Enterprise-level support"];return e.jsx(Ss,{children:e.jsxs("div",{className:"container max-w-6xl py-8 px-4",children:[e.jsxs("div",{className:"text-center mb-8",children:[e.jsx("h1",{className:"text-3xl font-bold mb-2",children:"Upgrade Your Membership"}),e.jsx("p",{className:"text-muted-foreground text-lg",children:"Choose the plan that's right for you and unlock the full power of LevelUp"})]}),e.jsxs("div",{className:"max-w-md mx-auto mb-8",children:[e.jsx(ue,{htmlFor:"coupon",className:"text-sm font-medium",children:"Have a discount code?"}),e.jsx(Se,{id:"coupon",placeholder:"Enter discount code",value:i,onChange:m=>l(m.target.value),className:"mt-1"})]}),e.jsxs("div",{className:"grid md:grid-cols-3 gap-6 mb-8",children:[e.jsxs(ke,{className:"border-2 border-primary/20 hover:border-primary/50 transition-colors relative overflow-hidden",children:[e.jsx("div",{className:"absolute top-0 right-0 bg-primary text-primary-foreground text-xs px-3 py-1 rounded-bl-lg font-medium",children:"Popular"}),e.jsxs(Ot,{className:"text-center pb-2",children:[e.jsx("div",{className:"mx-auto mb-3 h-14 w-14 rounded-full bg-primary/10 flex items-center justify-center",children:e.jsx(Ar,{className:"h-7 w-7 text-primary"})}),e.jsx(zt,{className:"text-xl",children:"Individual Agent"}),e.jsx(Br,{children:"Perfect for solo agents ready to level up"})]}),e.jsxs(Oe,{className:"space-y-6",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("span",{className:"text-4xl font-bold text-primary",children:"$39"}),e.jsx("span",{className:"text-muted-foreground",children:"/month"})]}),e.jsx("ul",{className:"space-y-2",children:c.map((m,p)=>e.jsxs("li",{className:"flex items-start gap-2 text-sm",children:[e.jsx(va,{className:"h-4 w-4 text-primary mt-0.5 shrink-0"}),e.jsx("span",{children:m})]},p))}),e.jsxs(H,{className:"w-full",size:"lg",onClick:()=>o("individual_agent"),disabled:t,children:[t&&n==="individual_agent"?e.jsx(is,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Lr,{className:"h-4 w-4 mr-2"}),"Get Started"]})]})]}),e.jsxs(ke,{className:"border-2 border-amber-500/20 hover:border-amber-500/50 transition-colors",children:[e.jsxs(Ot,{className:"text-center pb-2",children:[e.jsx("div",{className:"mx-auto mb-3 h-14 w-14 rounded-full bg-amber-500/10 flex items-center justify-center",children:e.jsx(Xa,{className:"h-7 w-7 text-amber-600"})}),e.jsx(zt,{className:"text-xl",children:"Brokerage"}),e.jsx(Br,{children:"For teams and brokerages up to 25 agents"})]}),e.jsxs(Oe,{className:"space-y-6",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("span",{className:"text-4xl font-bold text-amber-600",children:"$299"}),e.jsx("span",{className:"text-muted-foreground",children:"/month"})]}),e.jsx("ul",{className:"space-y-2",children:d.map((m,p)=>e.jsxs("li",{className:"flex items-start gap-2 text-sm",children:[e.jsx(va,{className:"h-4 w-4 text-amber-600 mt-0.5 shrink-0"}),e.jsx("span",{children:m})]},p))}),e.jsxs(H,{variant:"outline",className:"w-full border-amber-500 text-amber-600 hover:bg-amber-50",size:"lg",onClick:()=>o("brokerage_under_25"),disabled:t,children:[t&&n==="brokerage_under_25"?e.jsx(is,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Xa,{className:"h-4 w-4 mr-2"}),"Get Started"]})]})]}),e.jsxs(ke,{className:"border-2 border-purple-500/20 hover:border-purple-500/50 transition-colors",children:[e.jsxs(Ot,{className:"text-center pb-2",children:[e.jsx("div",{className:"mx-auto mb-3 h-14 w-14 rounded-full bg-purple-500/10 flex items-center justify-center",children:e.jsx(Xa,{className:"h-7 w-7 text-purple-600"})}),e.jsx(zt,{className:"text-xl",children:"Brokerage 25+"}),e.jsx(Br,{children:"For larger brokerages with 25+ agents"})]}),e.jsxs(Oe,{className:"space-y-6",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("span",{className:"text-4xl font-bold text-purple-600",children:"$499"}),e.jsx("span",{className:"text-muted-foreground",children:"/month"})]}),e.jsx("ul",{className:"space-y-2",children:h.map((m,p)=>e.jsxs("li",{className:"flex items-start gap-2 text-sm",children:[e.jsx(va,{className:"h-4 w-4 text-purple-600 mt-0.5 shrink-0"}),e.jsx("span",{children:m})]},p))}),e.jsxs(H,{variant:"outline",className:"w-full border-purple-500 text-purple-600 hover:bg-purple-50",size:"lg",onClick:()=>o("brokerage_over_25"),disabled:t,children:[t&&n==="brokerage_over_25"?e.jsx(is,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Xa,{className:"h-4 w-4 mr-2"}),"Get Started"]})]})]})]}),e.jsx(ke,{className:"bg-muted/50",children:e.jsxs(Oe,{className:"py-6",children:[e.jsx("p",{className:"text-center font-medium mb-4",children:"Questions? We're here to help!"}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 justify-center",children:[e.jsxs("a",{href:"tel:1-866-527-8668",className:"flex items-center justify-center gap-2 text-primary hover:underline",children:[e.jsx(Yn,{className:"h-4 w-4"}),e.jsx("span",{children:"1-866-527-8668"})]}),e.jsxs("a",{href:"mailto:support@relevelup.com",className:"flex items-center justify-center gap-2 text-primary hover:underline",children:[e.jsx(er,{className:"h-4 w-4"}),e.jsx("span",{children:"support@relevelup.com"})]})]})]})})]})})},fqt=()=>{const{user:s,loading:t,isBrokerageManager:r,brokerageId:n}=Ms(),a=Fr(),[i,l]=S.useState(""),[o,c]=S.useState(!1),[d,h]=S.useState(!1);S.useEffect(()=>{!t&&!s&&a("/auth")},[s,t,a]),S.useEffect(()=>{!t&&s&&n&&a("/profile?setup=true")},[s,t,n,a]);const m=async()=>{if(!i.trim()){he.error("Please enter a brokerage name");return}const{data:p}=await V.auth.getSession(),x=p.session;if(!s||!x){he.error("Please sign in again to create your brokerage."),a("/auth");return}c(!0);try{console.log("[SetupBrokerage] Creating brokerage…",{hasUser:!!s,hasSession:!!x,userId:s==null?void 0:s.id});const{data:y,error:_}=await V.functions.invoke("create-brokerage",{body:{name:i.trim()}});if(console.log("[SetupBrokerage] create-brokerage response",{data:y,error:_}),_)throw _;if(!(y!=null&&y.ok))throw new Error((y==null?void 0:y.error)||"Failed to create brokerage");c(!1),h(!0),he.success("Brokerage created! Setting up your account..."),setTimeout(()=>{a("/profile?setup=true")},2e3)}catch(y){console.error("Error creating brokerage:",y),he.error(y.message||"Failed to create brokerage"),c(!1)}};return t?e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):d?e.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:e.jsxs(ke,{className:"max-w-lg w-full",children:[e.jsxs(Ot,{className:"text-center",children:[e.jsx("div",{className:"mx-auto w-16 h-16 rounded-full bg-primary/10 flex items-center justify-center mb-4",children:e.jsx(is,{className:"w-10 h-10 text-primary animate-spin"})}),e.jsx(zt,{className:"text-2xl",children:"Setting Up Your Brokerage"}),e.jsx(Br,{className:"text-lg",children:"We're assigning you as the brokerage manager and preparing your dashboard..."})]}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-center gap-2 text-muted-foreground",children:[e.jsx(zi,{className:"w-5 h-5 text-green-500"}),e.jsx("span",{children:"Brokerage created"})]}),e.jsxs("div",{className:"flex items-center justify-center gap-2 text-muted-foreground",children:[e.jsx(is,{className:"w-5 h-5 animate-spin text-primary"}),e.jsx("span",{children:"Assigning you as manager..."})]}),e.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."})]})]})}):e.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:e.jsxs(ke,{className:"max-w-lg w-full",children:[e.jsxs(Ot,{className:"text-center",children:[e.jsx("div",{className:"mx-auto w-16 h-16 rounded-full bg-primary/10 flex items-center justify-center mb-4",children:e.jsx(Xa,{className:"w-10 h-10 text-primary"})}),e.jsx(zt,{className:"text-2xl",children:"Set Up Your Brokerage"}),e.jsx(Br,{className:"text-lg",children:"Create your brokerage to start managing your team"})]}),e.jsxs(Oe,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"brokerage-name",children:"Brokerage Name"}),e.jsx(Se,{id:"brokerage-name",placeholder:"Enter your brokerage name",value:i,onChange:p=>l(p.target.value),onKeyDown:p=>p.key==="Enter"&&m()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This is how your brokerage will appear to your agents"})]}),e.jsxs("div",{className:"p-4 rounded-lg bg-muted/50 space-y-3",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2",children:[e.jsx(Ar,{className:"w-4 h-4 text-primary"}),"What you can do as a Brokerage Manager:"]}),e.jsxs("ul",{className:"space-y-2 text-sm text-muted-foreground",children:[e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx(zi,{className:"w-4 h-4 text-green-500"}),"Invite agents to join your brokerage"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx(zi,{className:"w-4 h-4 text-green-500"}),"Access exclusive brokerage resources"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx(zi,{className:"w-4 h-4 text-green-500"}),"Track your team's activity and engagement"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx(zi,{className:"w-4 h-4 text-green-500"}),"Share resources with your agents"]})]})]}),e.jsxs(H,{onClick:m,className:"w-full",disabled:o||!i.trim(),children:[o?"Creating...":"Create Brokerage",e.jsx(bi,{className:"w-4 h-4 ml-2"})]})]})]})})},s9e=()=>{const s=Fr(),[t,r]=S.useState("verifying"),[n,a]=S.useState("");S.useEffect(()=>{(async()=>{try{const{data:{session:o},error:c}=await V.auth.getSession();if(c)throw c;if(o!=null&&o.user){const{data:d}=await V.from("profiles").select("login_count").eq("id",o.user.id).single();if(((d==null?void 0:d.login_count)||0)>1){console.log("Account already claimed, redirecting to dashboard"),r("already_claimed");return}console.log("User logged in successfully:",o.user.email),r("success");try{await V.functions.invoke("trial-claim-hook",{body:{userId:o.user.id}})}catch(h){console.log("Trial claim hook (non-critical):",h)}setTimeout(()=>{s("/profile?setup=true")},1500)}else setTimeout(()=>{r("already_claimed")},2e3)}catch(o){console.error("Claim error:",o),r("already_claimed")}})()},[s]);const i=()=>{window.location.href="https://dashboard.relevelup.com/auth"};return e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background p-4",children:e.jsxs(ke,{className:"w-full max-w-md",children:[e.jsxs(Ot,{className:"space-y-1 text-center",children:[e.jsxs("div",{className:"mx-auto mb-4 flex h-16 w-16 items-center justify-center rounded-full bg-primary/10",children:[t==="verifying"&&e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"}),t==="success"&&e.jsx("svg",{className:"h-8 w-8 text-primary",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})}),t==="already_claimed"&&e.jsx("svg",{className:"h-8 w-8 text-primary",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"})}),t==="error"&&e.jsx("svg",{className:"h-8 w-8 text-destructive",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})]}),e.jsxs(zt,{className:"text-2xl",children:[t==="verifying"&&"Claiming Your Account...",t==="success"&&"Account Claimed!",t==="already_claimed"&&"Account Already Claimed",t==="error"&&"Claim Failed"]}),e.jsxs(Br,{children:[t==="verifying"&&"Please wait while we verify your account...",t==="success"&&"Redirecting you to complete your profile...",t==="already_claimed"&&"This account has already been set up. Please log in to access your dashboard.",t==="error"&&n]})]}),(t==="already_claimed"||t==="error")&&e.jsx(Oe,{children:e.jsx(H,{onClick:i,className:"w-full",children:"Go to Login"})})]})})},pqt=()=>{const[s,t]=S.useState(!1),r=S.useMemo(()=>new URLSearchParams(window.location.search).get("link"),[]),n=S.useMemo(()=>{if(!r)return!1;try{const i=new URL(r);return i.hostname.endsWith(".supabase.co")&&i.pathname.startsWith("/auth/v1/verify")}catch{return!1}},[r]);S.useEffect(()=>{document.title="Reset Your Password"},[]);const a=()=>{!n||!r||(t(!0),window.location.href=r)};return e.jsxs("div",{className:"min-h-screen relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-[#4a6b6d] via-[#3d5a5c] to-[#2a4347]"}),e.jsx("div",{className:"relative z-10 flex flex-col min-h-screen items-center justify-center p-4",children:e.jsxs("div",{className:"w-full max-w-md",children:[e.jsx("div",{className:"flex justify-center mb-8",children:e.jsx("div",{className:"bg-white rounded-xl p-4 shadow-2xl",children:e.jsx("img",{src:n5e,alt:"LevelUp",className:"h-12 w-auto"})})}),e.jsxs(ke,{className:"border-0 shadow-2xl bg-white/95 backdrop-blur-sm",children:[e.jsxs(Ot,{className:"text-center",children:[e.jsx(zt,{className:"text-2xl font-bold text-[#2a4347]",style:{fontFamily:"'Libre Baskerville', serif"},children:"Reset Your Password"}),e.jsx(Br,{className:"text-gray-600 pt-2",children:n?"Click the button below to continue resetting your password.":"This link is invalid or has expired. Please request a new password reset email."})]}),e.jsxs(Oe,{className:"space-y-4",children:[n?e.jsx(H,{onClick:a,disabled:s,className:"w-full bg-[#4a6b6d] hover:bg-[#3d5a5c] text-white font-semibold py-6 text-lg shadow-lg hover:shadow-xl",children:s?"Continuing…":"Continue to Reset Password"}):e.jsx(H,{onClick:()=>window.location.href="/auth",className:"w-full bg-[#4a6b6d] hover:bg-[#3d5a5c] text-white font-semibold py-6 text-lg",children:"Go to Sign In"}),e.jsx("p",{className:"text-xs text-center text-gray-500 pt-2",children:"For your security, password reset links expire and can only be used once."})]})]})]})})]})},gqt=()=>{const s=Fr(),[t]=Ed(),[r,n]=S.useState(t.get("code")||""),[a,i]=S.useState(""),[l,o]=S.useState(""),[c,d]=S.useState(""),[h,m]=S.useState(!1),[p,x]=S.useState(!1),[y,_]=S.useState(!1),[b,j]=S.useState(!1),[k,T]=S.useState(null),[E,A]=S.useState(null),[D,R]=S.useState(null),[z,O]=S.useState(null);S.useEffect(()=>{const J=t.get("code");J&&(n(J),$(J))},[t]);const $=async J=>{_(!0);const{data:K,error:re}=await V.from("invite_codes").select("id, code, max_uses, uses_count, expires_at, is_active, brokerage_id, trial_days").eq("code",J.toUpperCase().trim()).single();if(re||!K){he.error("Invalid invite code"),_(!1);return}if(!K.is_active){he.error("This invite code is no longer active"),_(!1);return}if(K.max_uses&&K.uses_count>=K.max_uses){he.error("This invite code has reached its maximum uses"),_(!1);return}if(K.expires_at&&new Date(K.expires_at){J.preventDefault(),$(r)},Z=async J=>{var K;if(J.preventDefault(),!c.trim()){he.error("Please enter your name");return}if(l.length<6){he.error("Password must be at least 6 characters");return}x(!0);try{const re=`${window.location.origin}/`,{data:ie,error:ce}=await V.auth.signUp({email:a.trim(),password:l,options:{emailRedirectTo:re,data:{name:c.trim()}}});if(ce){ce.message.includes("already registered")?he.error("This email is already registered. Please sign in instead."):he.error(ce.message);return}ie.user&&(await V.rpc("add_default_signup_tag",{user_id:ie.user.id}),E?await V.functions.invoke("assign-brokerage",{body:{userId:ie.user.id,brokerageId:E}}):z?await V.functions.invoke("assign-brokerage",{body:{userId:ie.user.id,trialDays:z}}):await V.functions.invoke("assign-brokerage",{body:{userId:ie.user.id,grandfathered:!0}}),k&&await V.from("invite_codes").update({uses_count:((K=(await V.from("invite_codes").select("uses_count").eq("id",k).single()).data)==null?void 0:K.uses_count)+1}).eq("id",k),he.success("Account created! You can now access the dashboard."),s("/dashboard"))}catch(re){console.error("Signup error:",re),he.error("An unexpected error occurred")}finally{x(!1)}};return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsxs(ke,{className:"w-full max-w-md",children:[e.jsxs(Ot,{className:"text-center",children:[e.jsx(zt,{className:"text-2xl font-bold text-primary",children:D?`Join ${D}`:"Join LevelUp"}),e.jsx(Br,{children:b?D?`Create your account to join ${D}`:"Create your account to get started":"Enter your invite code to continue"})]}),e.jsx(Oe,{children:b?e.jsxs("form",{onSubmit:Z,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"name",children:"Full Name"}),e.jsx(Se,{id:"name",type:"text",placeholder:"John Doe",value:c,onChange:J=>d(J.target.value),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"email",children:"Email"}),e.jsx(Se,{id:"email",type:"email",placeholder:"you@example.com",value:a,onChange:J=>i(J.target.value),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"password",children:"Password"}),e.jsxs("div",{className:"relative",children:[e.jsx(Se,{id:"password",type:h?"text":"password",placeholder:"••••••••",value:l,onChange:J=>o(J.target.value),required:!0,minLength:6}),e.jsx("button",{type:"button",className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground",onClick:()=>m(!h),children:h?e.jsx($f,{className:"h-4 w-4"}):e.jsx(Bn,{className:"h-4 w-4"})})]})]}),e.jsx(H,{type:"submit",className:"w-full",disabled:p,children:p?e.jsxs(e.Fragment,{children:[e.jsx(is,{className:"mr-2 h-4 w-4 animate-spin"}),"Creating Account..."]}):"Create Account"})]}):e.jsxs("form",{onSubmit:ee,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"inviteCode",children:"Invite Code"}),e.jsx(Se,{id:"inviteCode",type:"text",placeholder:"Enter your invite code",value:r,onChange:J=>n(J.target.value),required:!0,autoFocus:!0})]}),e.jsx(H,{type:"submit",className:"w-full",disabled:y,children:y?e.jsxs(e.Fragment,{children:[e.jsx(is,{className:"mr-2 h-4 w-4 animate-spin"}),"Verifying..."]}):"Verify Code"})]})})]})})},Zge=()=>{const{user:s,isCoach:t}=Ms();return yt({queryKey:["my-coach-profile",s==null?void 0:s.id],enabled:!!s&&t,queryFn:async()=>{const{data:r,error:n}=await V.from("coaches").select("*").eq("user_id",s.id).maybeSingle();if(n)throw n;return r}})},xqt=()=>{const{data:s}=Zge();return yt({queryKey:["coach-roster",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:r}=await V.from("coaching_assignments").select("*").eq("coach_id",s.id).order("started_at",{ascending:!1});if(r)throw r;const n=t||[];if(n.length===0)return[];const a=n.map(o=>o.agent_id),{data:i}=await V.from("profiles").select("id, name, email, avatar_url").in("id",a),l=new Map((i||[]).map(o=>[o.id,o]));return n.map(o=>({...o,agent:l.get(o.agent_id)||null}))}})},yqt=()=>{const{user:s}=Ms();return yt({queryKey:["my-coaching-assignment",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:r}=await V.from("coaching_assignments").select("*").eq("agent_id",s.id).eq("status","active").order("started_at",{ascending:!1}).limit(1);if(r)throw r;const n=(t||[])[0];if(!n)return null;const{data:a}=await V.from("coaches").select("*").eq("id",n.coach_id).maybeSingle();let i=null;if(a!=null&&a.user_id){const{data:l}=await V.from("profiles").select("id, name, email, avatar_url").eq("id",a.user_id).maybeSingle();i=l}return{...n,coach:a,coachProfile:i}}})},vqt=s=>yt({queryKey:["coaching-assignment",s],enabled:!!s,queryFn:async()=>{const{data:t,error:r}=await V.from("coaching_assignments").select("*").eq("id",s).maybeSingle();if(r)throw r;if(!t)return null;const{data:n}=await V.from("profiles").select("id, name, email, avatar_url").eq("id",t.agent_id).maybeSingle();return{...t,agent:n}}}),zit=s=>yt({queryKey:["coaching-sessions",s],enabled:!!s,queryFn:async()=>{const{data:t,error:r}=await V.from("coaching_sessions").select("*").eq("assignment_id",s).order("scheduled_at",{ascending:!1});if(r)throw r;return t||[]}}),$it=s=>yt({queryKey:["coaching-action-items",s],enabled:!!s,queryFn:async()=>{const{data:t,error:r}=await V.from("coaching_action_items").select("*").eq("assignment_id",s).order("due_date",{ascending:!0,nullsFirst:!1});if(r)throw r;return t||[]}}),bqt=[{key:"onboarding",label:"Onboarding"},{key:"active",label:"Active"},{key:"thriving",label:"Thriving"},{key:"at_risk",label:"At Risk"},{key:"graduated",label:"Graduated"}];function _qt(){const s=Fr(),{data:t,isLoading:r}=Zge(),{data:n=[],isLoading:a}=xqt();if(r)return e.jsx(Ss,{title:"Coaching",children:e.jsx("div",{className:"p-8",children:"Loading…"})});if(!t)return e.jsx(Ss,{title:"Coaching",children:e.jsxs("div",{className:"max-w-2xl mx-auto p-8 text-center",children:[e.jsx(Vu,{className:"h-12 w-12 mx-auto mb-4 text-muted-foreground"}),e.jsx("h2",{className:"text-2xl font-semibold mb-2",children:"Coach profile not set up yet"}),e.jsx("p",{className:"text-muted-foreground",children:"An admin needs to create your coach profile. Reach out to support to get started."})]})});bqt.map(l=>({...l,items:n.filter(o=>(o.pipeline_stage||"active")===l.key)}));const i=n.filter(l=>l.status==="active").length;return e.jsx(Ss,{title:"Coaching",children:e.jsxs("div",{className:"p-4 md:p-8 max-w-7xl mx-auto space-y-8",children:[e.jsxs("div",{className:"relative overflow-hidden rounded-2xl bg-gradient-to-br from-[#2a4c64] to-[#406E71] text-white p-8",children:[e.jsx("div",{className:"absolute -right-20 -top-20 h-64 w-64 rounded-full bg-white/10 blur-3xl"}),e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2 text-white/80",children:[e.jsx(Lr,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm uppercase tracking-wider font-medium",children:"Coaching Command Center"})]}),e.jsx("h1",{className:"text-3xl md:text-4xl font-bold mb-2",children:"Welcome back, Coach"}),e.jsx("p",{className:"text-white/80 mb-6",children:"Lead your agents. Track momentum. Build champions."}),e.jsxs("div",{className:"flex flex-wrap gap-6",children:[e.jsx(Mbe,{icon:Vu,label:"Active agents",value:i}),e.jsx(Mbe,{icon:xu,label:"This month",value:"—"}),e.jsx(Mbe,{icon:od,label:"Momentum",value:"🔥"})]})]})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h2",{className:"text-xl font-semibold",children:"Your Roster"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(H,{size:"sm",variant:"outline",onClick:()=>s("/coaching/settings"),children:"Profile Settings"}),e.jsx(H,{size:"sm",variant:"outline",onClick:()=>s("/coaching/billing"),children:"Billing & Packages"})]})]}),a?e.jsx("div",{className:"text-muted-foreground",children:"Loading roster…"}):n.length===0?e.jsx(ke,{children:e.jsx(Oe,{className:"p-8 text-center",children:e.jsx("p",{className:"text-muted-foreground",children:"No agents assigned yet. An admin or you can invite agents to get started."})})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4",children:n.map(l=>{var o,c,d,h;return e.jsx(ke,{className:"cursor-pointer hover:shadow-lg transition-all hover:-translate-y-0.5",onClick:()=>s(`/coaching/agent/${l.id}`),children:e.jsx(Oe,{className:"p-5",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsxs(Un,{className:"h-14 w-14",children:[e.jsx(Ka,{src:((o=l.agent)==null?void 0:o.avatar_url)||void 0}),e.jsx(qn,{children:(((c=l.agent)==null?void 0:c.name)||"?").charAt(0)})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("h3",{className:"font-semibold truncate",children:((d=l.agent)==null?void 0:d.name)||"Unknown"}),e.jsx(bi,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:(h=l.agent)==null?void 0:h.email}),e.jsxs("div",{className:"flex items-center gap-2 mt-3",children:[e.jsx(Xe,{variant:"secondary",className:"capitalize",children:(l.pipeline_stage||"active").replace("_"," ")}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["Started ",Hl(new Date(l.started_at),{addSuffix:!0})]})]})]})]})})},l.id)})})]})]})})}function Mbe({icon:s,label:t,value:r}){return e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-white/15 flex items-center justify-center",children:e.jsx(s,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold leading-none",children:r}),e.jsx("div",{className:"text-xs text-white/70 mt-1",children:t})]})]})}var Xge="Tabs",[wqt,zZs]=_u(Xge,[OS]),Uit=OS(),[jqt,fTe]=wqt(Xge),qit=S.forwardRef((s,t)=>{const{__scopeTabs:r,value:n,onValueChange:a,defaultValue:i,orientation:l="horizontal",dir:o,activationMode:c="automatic",...d}=s,h=RS(o),[m,p]=af({prop:n,onChange:a,defaultProp:i??"",caller:Xge});return e.jsx(jqt,{scope:r,baseId:vm(),value:m,onValueChange:p,orientation:l,dir:h,activationMode:c,children:e.jsx(Vn.div,{dir:h,"data-orientation":l,...d,ref:t})})});qit.displayName=Xge;var Vit="TabsList",Hit=S.forwardRef((s,t)=>{const{__scopeTabs:r,loop:n=!0,...a}=s,i=fTe(Vit,r),l=Uit(r);return e.jsx(oge,{asChild:!0,...l,orientation:i.orientation,dir:i.dir,loop:n,children:e.jsx(Vn.div,{role:"tablist","aria-orientation":i.orientation,...a,ref:t})})});Hit.displayName=Vit;var Git="TabsTrigger",Wit=S.forwardRef((s,t)=>{const{__scopeTabs:r,value:n,disabled:a=!1,...i}=s,l=fTe(Git,r),o=Uit(r),c=Zit(l.baseId,n),d=Xit(l.baseId,n),h=n===l.value;return e.jsx(lge,{asChild:!0,...o,focusable:!a,active:h,children:e.jsx(Vn.button,{type:"button",role:"tab","aria-selected":h,"aria-controls":d,"data-state":h?"active":"inactive","data-disabled":a?"":void 0,disabled:a,id:c,...i,ref:t,onMouseDown:an(s.onMouseDown,m=>{!a&&m.button===0&&m.ctrlKey===!1?l.onValueChange(n):m.preventDefault()}),onKeyDown:an(s.onKeyDown,m=>{[" ","Enter"].includes(m.key)&&l.onValueChange(n)}),onFocus:an(s.onFocus,()=>{const m=l.activationMode!=="manual";!h&&!a&&m&&l.onValueChange(n)})})})});Wit.displayName=Git;var Kit="TabsContent",Yit=S.forwardRef((s,t)=>{const{__scopeTabs:r,value:n,forceMount:a,children:i,...l}=s,o=fTe(Kit,r),c=Zit(o.baseId,n),d=Xit(o.baseId,n),h=n===o.value,m=S.useRef(h);return S.useEffect(()=>{const p=requestAnimationFrame(()=>m.current=!1);return()=>cancelAnimationFrame(p)},[]),e.jsx(vh,{present:a||h,children:({present:p})=>e.jsx(Vn.div,{"data-state":h?"active":"inactive","data-orientation":o.orientation,role:"tabpanel","aria-labelledby":c,hidden:!p,id:d,tabIndex:0,...l,ref:t,style:{...s.style,animationDuration:m.current?"0s":void 0},children:p&&i})})});Yit.displayName=Kit;function Zit(s,t){return`${s}-trigger-${t}`}function Xit(s,t){return`${s}-content-${t}`}var Nqt=qit,Qit=Hit,Jit=Wit,eot=Yit;const ta=Nqt,Qn=S.forwardRef(({className:s,...t},r)=>e.jsx(Qit,{ref:r,className:Ft("inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground",s),...t}));Qn.displayName=Qit.displayName;const ts=S.forwardRef(({className:s,...t},r)=>e.jsx(Jit,{ref:r,className:Ft("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",s),...t}));ts.displayName=Jit.displayName;const cs=S.forwardRef(({className:s,...t},r)=>e.jsx(eot,{ref:r,className:Ft("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",s),...t}));cs.displayName=eot.displayName;function tot({assignmentId:s}){const{user:t}=Ms(),r=ns(),[n,a]=S.useState(""),[i,l]=S.useState(!1),o=S.useRef(null),{data:c=[]}=yt({queryKey:["coaching-messages",s],enabled:!!s,queryFn:async()=>{const{data:h,error:m}=await V.from("coaching_messages").select("*").eq("assignment_id",s).order("created_at",{ascending:!0});if(m)throw m;return h||[]}});S.useEffect(()=>{if(!s)return;const h=V.channel(`coaching-messages-${s}`).on("postgres_changes",{event:"INSERT",schema:"public",table:"coaching_messages",filter:`assignment_id=eq.${s}`},()=>r.invalidateQueries({queryKey:["coaching-messages",s]})).subscribe();return()=>{V.removeChannel(h)}},[s,r]),S.useEffect(()=>{var h;(h=o.current)==null||h.scrollTo({top:o.current.scrollHeight,behavior:"smooth"})},[c]);const d=async()=>{const h=n.trim();if(!h||!t)return;l(!0);const{error:m}=await V.from("coaching_messages").insert({assignment_id:s,sender_id:t.id,body:h});l(!1),m||a("")};return e.jsxs(ke,{className:"flex flex-col h-[60vh] min-h-[400px]",children:[e.jsx("div",{ref:o,className:"flex-1 overflow-y-auto p-4 space-y-3",children:c.length===0?e.jsx("div",{className:"h-full flex items-center justify-center text-sm text-muted-foreground",children:"No messages yet. Say hi 👋"}):c.map(h=>{const m=h.sender_id===(t==null?void 0:t.id);return e.jsxs("div",{className:Ft("flex gap-2",m?"justify-end":"justify-start"),children:[!m&&e.jsx(Un,{className:"h-8 w-8 mt-1",children:e.jsx(qn,{className:"text-xs",children:(h.sender_id||"?").charAt(0).toUpperCase()})}),e.jsxs("div",{className:Ft("max-w-[75%] rounded-2xl px-3 py-2 text-sm",m?"bg-[#406E71] text-white rounded-br-sm":"bg-muted rounded-bl-sm"),children:[e.jsx("p",{className:"whitespace-pre-wrap break-words",children:h.body}),e.jsx("p",{className:Ft("text-[10px] mt-1",m?"text-white/70":"text-muted-foreground"),children:Hl(new Date(h.created_at),{addSuffix:!0})})]})]},h.id)})}),e.jsx(Oe,{className:"border-t p-3",children:e.jsxs("div",{className:"flex gap-2 items-end",children:[e.jsx(vr,{value:n,onChange:h=>a(h.target.value),onKeyDown:h=>{h.key==="Enter"&&!h.shiftKey&&(h.preventDefault(),d())},placeholder:"Type a message…",rows:1,className:"resize-none min-h-[40px]"}),e.jsx(H,{onClick:d,disabled:i||!n.trim(),size:"icon",className:"bg-[#406E71] hover:bg-[#2a4c64]",children:e.jsx(yn,{className:"h-4 w-4"})})]})})]})}var pTe="Progress",gTe=100,[kqt,$Zs]=_u(pTe),[Sqt,Cqt]=kqt(pTe),sot=S.forwardRef((s,t)=>{const{__scopeProgress:r,value:n=null,max:a,getValueLabel:i=Tqt,...l}=s;(a||a===0)&&!r9e(a)&&console.error(Eqt(`${a}`,"Progress"));const o=r9e(a)?a:gTe;n!==null&&!n9e(n,o)&&console.error(Aqt(`${n}`,"Progress"));const c=n9e(n,o)?n:null,d=sme(c)?i(c,o):void 0;return e.jsx(Sqt,{scope:r,value:c,max:o,children:e.jsx(Vn.div,{"aria-valuemax":o,"aria-valuemin":0,"aria-valuenow":sme(c)?c:void 0,"aria-valuetext":d,role:"progressbar","data-state":aot(c,o),"data-value":c??void 0,"data-max":o,...l,ref:t})})});sot.displayName=pTe;var rot="ProgressIndicator",not=S.forwardRef((s,t)=>{const{__scopeProgress:r,...n}=s,a=Cqt(rot,r);return e.jsx(Vn.div,{"data-state":aot(a.value,a.max),"data-value":a.value??void 0,"data-max":a.max,...n,ref:t})});not.displayName=rot;function Tqt(s,t){return`${Math.round(s/t*100)}%`}function aot(s,t){return s==null?"indeterminate":s===t?"complete":"loading"}function sme(s){return typeof s=="number"}function r9e(s){return sme(s)&&!isNaN(s)&&s>0}function n9e(s,t){return sme(s)&&!isNaN(s)&&s<=t&&s>=0}function Eqt(s,t){return`Invalid prop \`max\` of value \`${s}\` supplied to \`${t}\`. Only numbers greater than 0 are valid max values. Defaulting to \`${gTe}\`.`}function Aqt(s,t){return`Invalid prop \`value\` of value \`${s}\` supplied to \`${t}\`. The \`value\` prop must be: - a positive number - less than the value passed to \`max\` (or ${gTe} if no \`max\` prop is set) - \`null\` or \`undefined\` if the progress is indeterminate. Defaulting to \`null\`.`}var iot=sot,Mqt=not;const Mi=S.forwardRef(({className:s,value:t,...r},n)=>e.jsx(iot,{ref:n,className:Ft("relative h-4 w-full overflow-hidden rounded-full bg-secondary",s),...r,children:e.jsx(Mqt,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(t||0)}%)`}})}));Mi.displayName=iot.displayName;function oot({agentUserId:s}){const t=new Date().getFullYear(),r=`${t}-01-01`,n=`${t}-12-31`,{data:a=[]}=yt({queryKey:["coaching-kpi-txns",s,t],enabled:!!s,queryFn:async()=>{const{data:_,error:b}=await V.from("scorecard_transactions").select("id, sale_price, commission_amount, close_date, is_win").eq("owner_user_id",s).gte("close_date",r).lte("close_date",n);if(b)throw b;return _||[]}}),{data:i}=yt({queryKey:["coaching-kpi-goal",s,t],enabled:!!s,queryFn:async()=>{const{data:_}=await V.from("scorecard_goals").select("*").eq("owner_user_id",s).eq("year",t).maybeSingle();return _}}),l=a.filter(_=>_.is_win),o=l.length,c=l.reduce((_,b)=>_+(Number(b.sale_price)||0),0),d=l.reduce((_,b)=>_+(Number(b.commission_amount)||0),0),h=i,m=(h==null?void 0:h.transactions_goal)||0,p=(h==null?void 0:h.volume_goal)||0,x=(h==null?void 0:h.gci_goal)||0,y=_=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(_);return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("h2",{className:"text-lg font-semibold flex items-center gap-2",children:[e.jsx(al,{className:"h-5 w-5"})," ",t," KPIs"]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3",children:[e.jsx(Ibe,{icon:Bc,label:"Transactions",value:o.toString(),goal:m,current:o,suffix:m?`/ ${m}`:""}),e.jsx(Ibe,{icon:al,label:"Volume",value:y(c),goal:p,current:c,suffix:p?`of ${y(p)}`:""}),e.jsx(Ibe,{icon:oc,label:"GCI",value:y(d),goal:x,current:d,suffix:x?`of ${y(x)}`:""})]}),o===0&&e.jsx(ke,{children:e.jsxs(Oe,{className:"p-4 text-sm text-muted-foreground text-center",children:["No transactions logged for ",t," yet."]})})]})}function Ibe({icon:s,label:t,value:r,goal:n,current:a,suffix:i}){const l=n>0?Math.min(100,a/n*100):0;return e.jsx(ke,{children:e.jsxs(Oe,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-2",children:[e.jsx(s,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs uppercase tracking-wider",children:t})]}),e.jsx("div",{className:"text-2xl font-bold",children:r}),n>0&&e.jsxs("div",{className:"mt-2 space-y-1",children:[e.jsx(Mi,{value:l}),e.jsxs("div",{className:"flex justify-between text-xs text-muted-foreground",children:[e.jsx("span",{children:i}),e.jsxs("span",{children:[l.toFixed(0),"%"]})]})]})]})})}function lot({assignmentId:s,canEdit:t}){const r=ns(),[n,a]=S.useState(!1),[i,l]=S.useState(null),{data:o=[]}=yt({queryKey:["coaching-goals",s],enabled:!!s,queryFn:async()=>{const{data:d,error:h}=await V.from("coaching_goals").select("*").eq("assignment_id",s).order("created_at",{ascending:!1});if(h)throw h;return d||[]}}),c=()=>r.invalidateQueries({queryKey:["coaching-goals",s]});return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("h2",{className:"text-lg font-semibold flex items-center gap-2",children:[e.jsx(Wu,{className:"h-5 w-5"})," Goals"]}),t&&e.jsxs(H,{size:"sm",onClick:()=>{l(null),a(!0)},children:[e.jsx(Ys,{className:"h-4 w-4 mr-1"})," New Goal"]})]}),o.length===0?e.jsx(ke,{children:e.jsx(Oe,{className:"p-6 text-center text-muted-foreground",children:"No goals yet."})}):o.map(d=>{const h=Number(d.target_value||0),m=Number(d.current_value||0),p=h>0?Math.min(100,m/h*100):0;return e.jsx(ke,{children:e.jsxs(Oe,{className:"p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"font-semibold",children:d.title}),e.jsx(Xe,{variant:"outline",className:"capitalize",children:d.status||"active"})]}),d.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:d.description})]}),t&&e.jsx(H,{variant:"ghost",size:"icon",onClick:()=>{l(d),a(!0)},children:e.jsx(ni,{className:"h-4 w-4"})})]}),h>0&&e.jsxs("div",{className:"mt-3 space-y-1",children:[e.jsxs("div",{className:"flex justify-between text-xs text-muted-foreground",children:[e.jsxs("span",{children:[m.toLocaleString()," / ",h.toLocaleString()," ",d.target_metric||""]}),e.jsxs("span",{children:[p.toFixed(0),"%"]})]}),e.jsx(Mi,{value:p})]}),d.due_date&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:["Due ",As(new Date(d.due_date),"PP")]})]})},d.id)}),t&&e.jsx(Iqt,{open:n,onOpenChange:a,assignmentId:s,goal:i,onSaved:c})]})}function Iqt({open:s,onOpenChange:t,assignmentId:r,goal:n,onSaved:a}){var E,A;const[i,l]=S.useState((n==null?void 0:n.title)||""),[o,c]=S.useState((n==null?void 0:n.description)||""),[d,h]=S.useState((n==null?void 0:n.target_metric)||""),[m,p]=S.useState(((E=n==null?void 0:n.target_value)==null?void 0:E.toString())||""),[x,y]=S.useState(((A=n==null?void 0:n.current_value)==null?void 0:A.toString())||"0"),[_,b]=S.useState((n==null?void 0:n.due_date)||""),[j,k]=S.useState(!1);S.useState(()=>{var D,R;l((n==null?void 0:n.title)||""),c((n==null?void 0:n.description)||""),h((n==null?void 0:n.target_metric)||""),p(((D=n==null?void 0:n.target_value)==null?void 0:D.toString())||""),y(((R=n==null?void 0:n.current_value)==null?void 0:R.toString())||"0"),b((n==null?void 0:n.due_date)||"")});const T=async()=>{if(!i.trim())return;k(!0);const D={assignment_id:r,title:i,description:o||null,target_metric:d||null,target_value:m?Number(m):null,current_value:x?Number(x):0,due_date:_||null},{error:R}=n!=null&&n.id?await V.from("coaching_goals").update(D).eq("id",n.id):await V.from("coaching_goals").insert(D);if(k(!1),R)return he.error(R.message);he.success(n!=null&&n.id?"Goal updated":"Goal created"),a==null||a(),t(!1)};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{children:[e.jsx(Cs,{children:e.jsx(Ns,{children:n!=null&&n.id?"Edit Goal":"New Goal"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(Se,{placeholder:"Title",value:i,onChange:D=>l(D.target.value)}),e.jsx(vr,{placeholder:"Description (optional)",rows:2,value:o,onChange:D=>c(D.target.value)}),e.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Metric"}),e.jsx(Se,{placeholder:"transactions",value:d,onChange:D=>h(D.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Target"}),e.jsx(Se,{type:"number",value:m,onChange:D=>p(D.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Current"}),e.jsx(Se,{type:"number",value:x,onChange:D=>y(D.target.value)})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Due date"}),e.jsx(Se,{type:"date",value:_,onChange:D=>b(D.target.value)})]})]}),e.jsxs(wn,{children:[e.jsx(H,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(H,{onClick:T,disabled:j,children:n!=null&&n.id?"Save":"Create"})]})]})})}function cot({assignmentId:s}){const t=ns(),{user:r}=Ms(),n=S.useRef(null),[a,i]=S.useState(!1),{data:l=[]}=yt({queryKey:["coaching-files",s],enabled:!!s,queryFn:async()=>{const{data:m,error:p}=await V.from("coaching_shared_files").select("*").eq("assignment_id",s).order("created_at",{ascending:!1});if(p)throw p;return m||[]}}),o=()=>t.invalidateQueries({queryKey:["coaching-files",s]}),c=async m=>{var x;const p=(x=m.target.files)==null?void 0:x[0];if(!(!p||!r)){i(!0);try{const y=`${s}/${Date.now()}-${p.name}`,{error:_}=await V.storage.from("coaching-files").upload(y,p);if(_)throw _;const{error:b}=await V.from("coaching_shared_files").insert({assignment_id:s,uploaded_by:r.id,file_url:y,file_name:p.name,file_size_bytes:p.size,mime_type:p.type});if(b)throw b;he.success("File uploaded"),o()}catch(y){he.error(y.message||"Upload failed")}finally{i(!1),n.current&&(n.current.value="")}}},d=async m=>{const{data:p,error:x}=await V.storage.from("coaching-files").createSignedUrl(m.file_url,60);if(x||!p)return he.error("Could not get download link");window.open(p.signedUrl,"_blank")},h=async m=>{confirm("Delete this file?")&&(await V.storage.from("coaching-files").remove([m.file_url]),await V.from("coaching_shared_files").delete().eq("id",m.id),o())};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Shared Files"}),e.jsxs(H,{size:"sm",onClick:()=>{var m;return(m=n.current)==null?void 0:m.click()},disabled:a,children:[e.jsx(Ea,{className:"h-4 w-4 mr-1"})," ",a?"Uploading…":"Upload"]}),e.jsx("input",{ref:n,type:"file",hidden:!0,onChange:c})]}),l.length===0?e.jsx(ke,{children:e.jsx(Oe,{className:"p-6 text-center text-muted-foreground",children:"No files yet."})}):e.jsx("div",{className:"space-y-2",children:l.map(m=>e.jsx(ke,{children:e.jsxs(Oe,{className:"p-3 flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-muted flex items-center justify-center",children:e.jsx(kn,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-medium truncate",children:m.file_name}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[m.file_size_bytes?`${(m.file_size_bytes/1024).toFixed(0)} KB · `:"",As(new Date(m.created_at),"PP")]})]}),e.jsx(H,{variant:"ghost",size:"icon",onClick:()=>d(m),children:e.jsx(hi,{className:"h-4 w-4"})}),m.uploaded_by===(r==null?void 0:r.id)&&e.jsx(H,{variant:"ghost",size:"icon",onClick:()=>h(m),children:e.jsx(Dr,{className:"h-4 w-4"})})]})},m.id))})]})}function Pqt(){var p,x,y,_;const{id:s}=Po(),t=Fr(),r=ns(),{data:n,isLoading:a}=vqt(s),{data:i=[]}=zit(s),{data:l=[]}=$it(s),[o,c]=S.useState(!1),[d,h]=S.useState(!1);if(a)return e.jsx(Ss,{title:"Coaching",children:e.jsx("div",{className:"p-8",children:"Loading…"})});if(!n)return e.jsx(Ss,{title:"Coaching",children:e.jsx("div",{className:"p-8",children:"Assignment not found."})});const m=n;return e.jsxs(Ss,{title:"Coaching",children:[e.jsxs("div",{className:"p-4 md:p-8 max-w-6xl mx-auto space-y-6",children:[e.jsxs(H,{variant:"ghost",size:"sm",onClick:()=>t("/coaching"),children:[e.jsx(za,{className:"h-4 w-4 mr-2"})," Back to roster"]}),e.jsxs(ke,{className:"overflow-hidden",children:[e.jsx("div",{className:"h-24 bg-gradient-to-br from-[#2a4c64] to-[#406E71]"}),e.jsx(Oe,{className:"pt-0 -mt-12 pb-6",children:e.jsxs("div",{className:"flex flex-col md:flex-row gap-4 md:items-end",children:[e.jsxs(Un,{className:"h-24 w-24 ring-4 ring-background",children:[e.jsx(Ka,{src:((p=m.agent)==null?void 0:p.avatar_url)||void 0}),e.jsx(qn,{className:"text-2xl",children:(((x=m.agent)==null?void 0:x.name)||"?").charAt(0)})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h1",{className:"text-2xl font-bold",children:((y=m.agent)==null?void 0:y.name)||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(_=m.agent)==null?void 0:_.email}),e.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[e.jsx(Xe,{variant:"secondary",className:"capitalize",children:(m.pipeline_stage||"active").replace("_"," ")}),e.jsx(Xe,{variant:"outline",className:"capitalize",children:m.status})]})]}),e.jsx("div",{className:"flex gap-2",children:e.jsx(Lqt,{value:m.pipeline_stage||"active",onChange:async b=>{await V.from("coaching_assignments").update({pipeline_stage:b}).eq("id",m.id),r.invalidateQueries({queryKey:["coaching-assignment",m.id]}),r.invalidateQueries({queryKey:["coach-roster"]})}})})]})})]}),e.jsxs(ta,{defaultValue:"sessions",children:[e.jsxs(Qn,{className:"w-full flex flex-wrap justify-start h-auto",children:[e.jsxs(ts,{value:"sessions",children:[e.jsx(Nn,{className:"h-4 w-4 mr-2"}),"Sessions"]}),e.jsxs(ts,{value:"actions",children:[e.jsx(V2,{className:"h-4 w-4 mr-2"}),"Actions"]}),e.jsxs(ts,{value:"goals",children:[e.jsx(Wu,{className:"h-4 w-4 mr-2"}),"Goals"]}),e.jsxs(ts,{value:"kpis",children:[e.jsx(al,{className:"h-4 w-4 mr-2"}),"KPIs"]}),e.jsxs(ts,{value:"messages",children:[e.jsx(Gi,{className:"h-4 w-4 mr-2"}),"Messages"]}),e.jsxs(ts,{value:"files",children:[e.jsx(Uf,{className:"h-4 w-4 mr-2"}),"Files"]}),e.jsxs(ts,{value:"notes",children:[e.jsx(kn,{className:"h-4 w-4 mr-2"}),"Private Notes"]})]}),e.jsxs(cs,{value:"sessions",className:"space-y-4",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Sessions"}),e.jsxs(H,{size:"sm",onClick:()=>c(!0),children:[e.jsx(Ys,{className:"h-4 w-4 mr-1"})," New Session"]})]}),i.length===0?e.jsx(ke,{children:e.jsx(Oe,{className:"p-6 text-muted-foreground text-center",children:"No sessions yet."})}):e.jsx("div",{className:"space-y-3",children:i.map(b=>e.jsx(ke,{children:e.jsx(Oe,{className:"p-4",children:e.jsx("div",{className:"flex items-start justify-between gap-3",children:e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"font-medium",children:As(new Date(b.scheduled_at),"PPp")}),e.jsx(Xe,{variant:"outline",className:"capitalize",children:b.status}),b.template&&e.jsx(Xe,{variant:"secondary",children:b.template})]}),b.summary&&e.jsx("p",{className:"text-sm text-muted-foreground whitespace-pre-wrap",children:b.summary}),b.private_notes&&e.jsxs("div",{className:"mt-2 p-2 rounded bg-muted/50 text-xs",children:[e.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground mb-1",children:[e.jsx(Td,{className:"h-3 w-3"})," Private"]}),e.jsx("p",{className:"whitespace-pre-wrap",children:b.private_notes})]})]})})})},b.id))})]}),e.jsxs(cs,{value:"actions",className:"space-y-4",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Action Items"}),e.jsxs(H,{size:"sm",onClick:()=>h(!0),children:[e.jsx(Ys,{className:"h-4 w-4 mr-1"})," Add"]})]}),l.length===0?e.jsx(ke,{children:e.jsx(Oe,{className:"p-6 text-muted-foreground text-center",children:"No action items yet."})}):e.jsx("div",{className:"space-y-2",children:l.map(b=>e.jsx(ke,{children:e.jsxs(Oe,{className:"p-3 flex items-center gap-3",children:[e.jsx(ao,{checked:b.status==="done",onCheckedChange:async j=>{await V.from("coaching_action_items").update({status:j?"done":"open",completed_at:j?new Date().toISOString():null}).eq("id",b.id),r.invalidateQueries({queryKey:["coaching-action-items",m.id]})}}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:b.status==="done"?"line-through text-muted-foreground":"font-medium",children:b.title}),b.description&&e.jsx("div",{className:"text-xs text-muted-foreground",children:b.description})]}),b.due_date&&e.jsx(Xe,{variant:"outline",children:As(new Date(b.due_date),"MMM d")}),e.jsx(Xe,{variant:"secondary",className:"capitalize",children:b.priority})]})},b.id))})]}),e.jsx(cs,{value:"goals",children:e.jsx(lot,{assignmentId:m.id,canEdit:!0})}),e.jsx(cs,{value:"kpis",children:m.agent_id&&e.jsx(oot,{agentUserId:m.agent_id})}),e.jsx(cs,{value:"messages",children:e.jsx(tot,{assignmentId:m.id})}),e.jsx(cs,{value:"files",children:e.jsx(cot,{assignmentId:m.id})}),e.jsx(cs,{value:"notes",className:"space-y-4",children:e.jsx(ke,{children:e.jsx(Oe,{className:"p-6 text-muted-foreground",children:"Private notes per session live under the Sessions tab. General-relationship notes coming soon."})})})]})]}),e.jsx(Dqt,{open:o,onOpenChange:c,assignmentId:m.id,onSaved:()=>r.invalidateQueries({queryKey:["coaching-sessions",m.id]})}),e.jsx(Rqt,{open:d,onOpenChange:h,assignmentId:m.id,onSaved:()=>r.invalidateQueries({queryKey:["coaching-action-items",m.id]})})]})}function Lqt({value:s,onChange:t}){return e.jsxs(Bs,{value:s,onValueChange:t,children:[e.jsx(Os,{className:"w-40",children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"onboarding",children:"Onboarding"}),e.jsx(pt,{value:"active",children:"Active"}),e.jsx(pt,{value:"thriving",children:"Thriving"}),e.jsx(pt,{value:"at_risk",children:"At Risk"}),e.jsx(pt,{value:"graduated",children:"Graduated"})]})]})}function Dqt({open:s,onOpenChange:t,assignmentId:r,onSaved:n}){const[a,i]=S.useState(()=>new Date().toISOString().slice(0,16)),[l,o]=S.useState(60),[c,d]=S.useState("weekly_1on1"),[h,m]=S.useState(""),[p,x]=S.useState(""),[y,_]=S.useState(!1),[b,j]=S.useState(!0),[k,T]=S.useState(null),[E,A]=S.useState(!1),D=async()=>{A(!0);const{data:z,error:O}=await V.functions.invoke("coaching-prep-brief",{body:{assignmentId:r}});if(A(!1),O||z!=null&&z.error)return he.error((z==null?void 0:z.error)||(O==null?void 0:O.message)||"Failed to generate brief");T(z.brief||"No brief returned.")},R=async()=>{_(!0);const{data:z,error:O}=await V.from("coaching_sessions").insert({assignment_id:r,scheduled_at:new Date(a).toISOString(),duration_minutes:l,template:c,summary:h,private_notes:p,status:"completed"}).select("id").maybeSingle();if(O)return _(!1),he.error(O.message);if(he.success("Session saved"),b&&h.trim()&&(z!=null&&z.id)){const{error:$}=await V.functions.invoke("coaching-send-recap",{body:{sessionId:z.id}});$?he.error("Saved, but recap email failed: "+$.message):he.success("Recap emailed to agent")}_(!1),n==null||n(),t(!1),m(""),x(""),T(null)};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Cs,{children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx(Ns,{children:"New Session"}),e.jsxs(H,{size:"sm",variant:"outline",onClick:D,disabled:E,children:[E?e.jsx(is,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Lr,{className:"h-4 w-4 mr-1"}),"Pre-session brief"]})]})}),e.jsxs("div",{className:"space-y-3",children:[k&&e.jsxs("div",{className:"rounded-lg border bg-gradient-to-br from-[#406E71]/5 to-[#2a4c64]/5 p-3 text-sm whitespace-pre-wrap max-h-60 overflow-y-auto",children:[e.jsxs("div",{className:"flex items-center gap-1 text-xs font-medium text-[#406E71] mb-2",children:[e.jsx(Lr,{className:"h-3 w-3"})," AI Brief"]}),k]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"When"}),e.jsx(Se,{type:"datetime-local",value:a,onChange:z=>i(z.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Duration (min)"}),e.jsx(Se,{type:"number",value:l,onChange:z=>o(Number(z.target.value))})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Template"}),e.jsxs(Bs,{value:c,onValueChange:d,children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"weekly_1on1",children:"Weekly 1:1"}),e.jsx(pt,{value:"grow",children:"GROW Model"}),e.jsx(pt,{value:"goal_review",children:"Goal Review"}),e.jsx(pt,{value:"breakthrough",children:"Breakthrough Session"})]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Summary (agent sees this)"}),e.jsx(vr,{rows:4,value:h,onChange:z=>m(z.target.value),placeholder:"Key takeaways, wins, focus areas…"})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"text-sm font-medium flex items-center gap-1",children:[e.jsx(Td,{className:"h-3 w-3"})," Private notes (only you)"]}),e.jsx(vr,{rows:3,value:p,onChange:z=>x(z.target.value),placeholder:"Your private observations…"})]}),e.jsxs("label",{className:"flex items-center gap-2 text-sm pt-1",children:[e.jsx(ao,{checked:b,onCheckedChange:z=>j(!!z)}),e.jsx(yn,{className:"h-3.5 w-3.5 text-muted-foreground"}),"Email recap to agent on save"]})]}),e.jsxs(wn,{children:[e.jsx(H,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(H,{onClick:R,disabled:y,children:[e.jsx(vc,{className:"h-4 w-4 mr-1"})," Save Session"]})]})]})})}function Rqt({open:s,onOpenChange:t,assignmentId:r,onSaved:n}){const[a,i]=S.useState(""),[l,o]=S.useState(""),[c,d]=S.useState(""),[h,m]=S.useState("medium"),[p,x]=S.useState(!1),y=async()=>{if(!a.trim())return;x(!0);const{error:_}=await V.from("coaching_action_items").insert({assignment_id:r,title:a,description:l||null,due_date:c||null,priority:h});if(x(!1),_)return he.error(_.message);he.success("Action item added"),n==null||n(),t(!1),i(""),o(""),d("")};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{children:[e.jsx(Cs,{children:e.jsx(Ns,{children:"New Action Item"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(Se,{placeholder:"Title",value:a,onChange:_=>i(_.target.value)}),e.jsx(vr,{rows:3,placeholder:"Description (optional)",value:l,onChange:_=>o(_.target.value)}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Due date"}),e.jsx(Se,{type:"date",value:c,onChange:_=>d(_.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Priority"}),e.jsxs(Bs,{value:h,onValueChange:m,children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"low",children:"Low"}),e.jsx(pt,{value:"medium",children:"Medium"}),e.jsx(pt,{value:"high",children:"High"})]})]})]})]})]}),e.jsxs(wn,{children:[e.jsx(H,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(H,{onClick:y,disabled:p,children:"Add"})]})]})})}function $Ne({value:s,size:t=16,onChange:r}){return e.jsx("div",{className:"flex items-center gap-0.5",children:[1,2,3,4,5].map(n=>e.jsx("button",{type:"button",onClick:()=>r==null?void 0:r(n),disabled:!r,className:r?"cursor-pointer":"cursor-default",children:e.jsx(ya,{style:{width:t,height:t},className:n<=s?"fill-yellow-400 text-yellow-400":"text-muted-foreground/40"})},n))})}function Oqt({coachId:s}){const[t,r]=S.useState([]),[n,a]=S.useState(!0);S.useEffect(()=>{(async()=>{const{data:l}=await V.from("coaching_reviews").select("*").eq("coach_id",s).eq("is_published",!0).order("created_at",{ascending:!1}),o=l||[];if(o.length){const c=o.map(m=>m.agent_id),{data:d}=await V.from("profiles").select("id, name, avatar_url").in("id",c),h=new Map((d||[]).map(m=>[m.id,m]));o.forEach(m=>m.profile=h.get(m.agent_id))}r(o),a(!1)})()},[s]);const i=t.length?t.reduce((l,o)=>l+o.rating,0)/t.length:0;return n||!t.length?null:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h2",{className:"text-xl font-semibold",children:"Reviews"}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx($Ne,{value:Math.round(i)}),e.jsxs("span",{children:[i.toFixed(1)," · ",t.length," review",t.length===1?"":"s"]})]})]}),e.jsx("div",{className:"space-y-3",children:t.map(l=>{var o,c,d;return e.jsx(ke,{children:e.jsx(Oe,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsxs(Un,{className:"h-9 w-9",children:[e.jsx(Ka,{src:((o=l.profile)==null?void 0:o.avatar_url)||void 0}),e.jsx(qn,{children:(((c=l.profile)==null?void 0:c.name)||"?").charAt(0)})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium",children:((d=l.profile)==null?void 0:d.name)||"Agent"}),e.jsx($Ne,{value:l.rating,size:14})]}),l.title&&e.jsx("div",{className:"font-semibold mt-1",children:l.title}),l.body&&e.jsx("p",{className:"text-sm text-muted-foreground whitespace-pre-wrap mt-1",children:l.body})]})]})})},l.id)})})]})}function Fqt({coachId:s,assignmentId:t}){const{user:r}=Ms(),[n,a]=S.useState(null),[i,l]=S.useState(0),[o,c]=S.useState(""),[d,h]=S.useState(""),[m,p]=S.useState(!1);S.useEffect(()=>{r&&(async()=>{const{data:y}=await V.from("coaching_reviews").select("*").eq("coach_id",s).eq("agent_id",r.id).maybeSingle();y&&(a(y),l(y.rating),c(y.title||""),h(y.body||""))})()},[r,s]);const x=async()=>{if(!r)return;if(!i)return he.error("Pick a rating");p(!0);const y={coach_id:s,agent_id:r.id,assignment_id:t||null,rating:i,title:o||null,body:d||null},{error:_}=n?await V.from("coaching_reviews").update(y).eq("id",n.id):await V.from("coaching_reviews").insert(y);if(p(!1),_)return he.error(_.message);he.success("Thanks for your review!"),a({...y,id:n==null?void 0:n.id})};return e.jsx(ke,{children:e.jsxs(Oe,{className:"p-5 space-y-3",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold",children:n?"Your review":"Leave a review"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Help other agents find a great coach."})]}),e.jsx($Ne,{value:i,size:28,onChange:l}),e.jsx(Se,{placeholder:"Title (optional)",value:o,onChange:y=>c(y.target.value)}),e.jsx(vr,{rows:4,placeholder:"What was your experience like?",value:d,onChange:y=>h(y.target.value)}),e.jsx(H,{onClick:x,disabled:m,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:m?"Saving…":n?"Update review":"Submit review"})]})})}function Bqt(){var m,p,x,y,_,b;const{user:s}=Ms(),{data:t,isLoading:r,refetch:n}=yqt(),a=ns(),i=t==null?void 0:t.id,{data:l=[]}=zit(i),{data:o=[]}=$it(i);if(S.useEffect(()=>{new URLSearchParams(window.location.search).get("subscribed")==="1"&&V.functions.invoke("coaching-verify-checkout").then(()=>{n(),a.invalidateQueries({queryKey:["my-coaching-assignment"]})})},[n,a]),r)return e.jsx(Ss,{title:"My Coach",children:e.jsx("div",{className:"p-8",children:"Loading…"})});if(!t)return e.jsx(Ss,{title:"My Coach",children:e.jsxs("div",{className:"max-w-2xl mx-auto p-8 text-center",children:[e.jsx(Vu,{className:"h-12 w-12 mx-auto mb-4 text-muted-foreground"}),e.jsx("h2",{className:"text-2xl font-semibold mb-2",children:"You're not in a coaching program yet"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"Browse LevelUp Certified Coaches to find a fit (coming soon)."})]})});const c=t,d=o.filter(j=>j.status!=="done"),h=o.length-d.length;return e.jsx(Ss,{title:"My Coach",children:e.jsxs("div",{className:"p-4 md:p-8 max-w-5xl mx-auto space-y-6",children:[e.jsx(ke,{className:"overflow-hidden",children:e.jsxs("div",{className:"relative bg-gradient-to-br from-[#2a4c64] to-[#406E71] text-white p-8",children:[e.jsx("div",{className:"absolute -right-20 -top-20 h-64 w-64 rounded-full bg-white/10 blur-3xl"}),e.jsxs("div",{className:"relative flex flex-col md:flex-row items-start md:items-center gap-6",children:[e.jsxs(Un,{className:"h-24 w-24 ring-4 ring-white/20",children:[e.jsx(Ka,{src:((m=c.coachProfile)==null?void 0:m.avatar_url)||void 0}),e.jsx(qn,{className:"text-2xl bg-white/20 text-white",children:(((p=c.coachProfile)==null?void 0:p.name)||"C").charAt(0)})]}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 text-white/80 mb-1",children:[e.jsx(Lr,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm uppercase tracking-wider",children:"Your Coach"})]}),e.jsx("h1",{className:"text-3xl font-bold",children:((x=c.coachProfile)==null?void 0:x.name)||"Your Coach"}),((y=c.coach)==null?void 0:y.headline)&&e.jsx("p",{className:"text-white/80 mt-1",children:c.coach.headline}),e.jsxs("div",{className:"flex gap-2 mt-3",children:[((_=c.coach)==null?void 0:_.is_certified)&&e.jsx(Xe,{className:"bg-yellow-400/20 text-yellow-100 border-yellow-300/30",children:"LevelUp Certified"}),e.jsx(Xe,{variant:"secondary",className:"bg-white/15 text-white border-white/20",children:"Active Program"})]})]})]})]})}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsx(Pbe,{icon:V2,label:"Open action items",value:d.length}),e.jsx(Pbe,{icon:Wu,label:"Completed",value:h}),e.jsx(Pbe,{icon:Nn,label:"Sessions",value:l.length})]}),((b=c.coach)==null?void 0:b.id)&&e.jsx(Fqt,{coachId:c.coach.id,assignmentId:i}),e.jsxs(ta,{defaultValue:"actions",children:[e.jsxs(Qn,{className:"flex flex-wrap h-auto w-full justify-start",children:[e.jsxs(ts,{value:"actions",children:[e.jsx(V2,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Actions"})]}),e.jsxs(ts,{value:"sessions",children:[e.jsx(Nn,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Recaps"})]}),e.jsxs(ts,{value:"goals",children:[e.jsx(Wu,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Goals"})]}),e.jsxs(ts,{value:"kpis",children:[e.jsx(al,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"KPIs"})]}),e.jsxs(ts,{value:"messages",children:[e.jsx(Gi,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Messages"})]}),e.jsxs(ts,{value:"files",children:[e.jsx(Uf,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Files"})]})]}),e.jsx(cs,{value:"actions",className:"space-y-2",children:o.length===0?e.jsx(ke,{children:e.jsx(Oe,{className:"p-6 text-center text-muted-foreground",children:"Your coach hasn't assigned any action items yet."})}):o.map(j=>e.jsx(ke,{children:e.jsxs(Oe,{className:"p-3 flex items-center gap-3",children:[e.jsx(ao,{checked:j.status==="done",onCheckedChange:async k=>{await V.from("coaching_action_items").update({status:k?"done":"open",completed_at:k?new Date().toISOString():null}).eq("id",j.id),a.invalidateQueries({queryKey:["coaching-action-items",i]})}}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:j.status==="done"?"line-through text-muted-foreground":"font-medium",children:j.title}),j.description&&e.jsx("div",{className:"text-xs text-muted-foreground",children:j.description})]}),j.due_date&&e.jsx(Xe,{variant:"outline",children:As(new Date(j.due_date),"MMM d")}),e.jsx(Xe,{variant:"secondary",className:"capitalize",children:j.priority})]})},j.id))}),e.jsx(cs,{value:"sessions",className:"space-y-3",children:l.length===0?e.jsx(ke,{children:e.jsx(Oe,{className:"p-6 text-center text-muted-foreground",children:"No sessions logged yet."})}):l.map(j=>e.jsx(ke,{children:e.jsxs(Oe,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("span",{className:"font-medium",children:As(new Date(j.scheduled_at),"PPp")}),e.jsx(Xe,{variant:"outline",className:"capitalize",children:j.status})]}),j.summary?e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:j.summary}):e.jsx("p",{className:"text-sm text-muted-foreground italic",children:"Recap coming soon."})]})},j.id))}),e.jsx(cs,{value:"goals",children:e.jsx(lot,{assignmentId:i,canEdit:!1})}),e.jsx(cs,{value:"kpis",children:s&&e.jsx(oot,{agentUserId:s.id})}),e.jsx(cs,{value:"messages",children:e.jsx(tot,{assignmentId:i})}),e.jsx(cs,{value:"files",children:e.jsx(cot,{assignmentId:i})})]})]})})}function Pbe({icon:s,label:t,value:r}){return e.jsx(ke,{children:e.jsxs(Oe,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-primary/10 flex items-center justify-center",children:e.jsx(s,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold leading-none",children:r}),e.jsx("div",{className:"text-xs text-muted-foreground mt-1",children:t})]})]})})}function zqt(){const s=ns(),[t,r]=S.useState(""),[n,a]=S.useState([]),[i,l]=S.useState(null),{data:o=[],isLoading:c}=yt({queryKey:["admin-coaches"],queryFn:async()=>{const{data:m,error:p}=await V.from("coaches").select("*").order("created_at",{ascending:!1});if(p)throw p;if(!(m!=null&&m.length))return[];const x=m.map(b=>b.user_id),{data:y}=await V.from("profiles").select("id, name, email, avatar_url").in("id",x),_=new Map((y||[]).map(b=>[b.id,b]));return m.map(b=>({...b,profile:_.get(b.user_id)}))}});S.useEffect(()=>{const m=t.trim();if(m.length<2){a([]);return}const p=setTimeout(async()=>{const{data:x}=await V.from("profiles").select("id, email, name, avatar_url").or(`email.ilike.%${m}%,name.ilike.%${m}%`).limit(10);a(x||[])},250);return()=>clearTimeout(p)},[t]);const d=async m=>{const{error:p}=await V.functions.invoke("manage-user-roles",{body:{userId:m.id,role:"coach",action:"add"}});if(p)return he.error(p.message);const{error:x}=await V.from("coaches").insert({user_id:m.id});if(x&&!String(x.message).includes("duplicate"))return he.error(x.message);he.success(`${m.name||m.email} is now a coach`),r(""),a([]),s.invalidateQueries({queryKey:["admin-coaches"]})},h=async(m,p)=>{const{error:x}=await V.from("coaches").update({is_certified:p}).eq("id",m);if(x)return he.error(x.message);he.success(p?"Marked Certified":"Removed certification"),s.invalidateQueries({queryKey:["admin-coaches"]})};return e.jsxs(Ss,{title:"Coaching Admin",children:[e.jsxs("div",{className:"p-4 md:p-8 max-w-6xl mx-auto space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Vu,{className:"h-7 w-7 text-primary"}),e.jsx("h1",{className:"text-2xl font-bold",children:"LevelUp Coaching"})]}),e.jsx($qt,{}),e.jsx(qqt,{}),e.jsx(ke,{children:e.jsxs(Oe,{className:"p-4 space-y-3",children:[e.jsx(Se,{placeholder:"Search by user email or name…",value:t,onChange:m=>r(m.target.value)}),t.trim().length>=2&&e.jsx("div",{className:"border rounded-md divide-y max-h-72 overflow-auto",children:n.length===0?e.jsx("div",{className:"p-3 text-sm text-muted-foreground",children:"No users found"}):n.map(m=>e.jsxs("div",{className:"flex items-center justify-between p-2 hover:bg-muted/40",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-medium truncate",children:m.name||m.email}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:m.email})]}),e.jsxs(H,{size:"sm",onClick:()=>d(m),children:[e.jsx(Ys,{className:"h-4 w-4 mr-1"})," Make Coach"]})]},m.id))})]})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold mb-3",children:"Coaches"}),c?e.jsx("div",{children:"Loading…"}):o.length===0?e.jsx(ke,{children:e.jsx(Oe,{className:"p-6 text-center text-muted-foreground",children:"No coaches yet. Search for a user above to promote them."})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:o.map(m=>{var p,x,y;return e.jsx(ke,{children:e.jsxs(Oe,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-medium",children:((p=m.profile)==null?void 0:p.name)||((x=m.profile)==null?void 0:x.email)||m.user_id}),e.jsx("div",{className:"text-xs text-muted-foreground",children:(y=m.profile)==null?void 0:y.email}),e.jsxs("div",{className:"flex gap-2 mt-2 flex-wrap",children:[m.is_certified&&e.jsxs(Xe,{className:"bg-yellow-500/15 text-yellow-700 border-yellow-300/40",children:[e.jsx(Lr,{className:"h-3 w-3 mr-1"}),"Certified"]}),m.accepting_clients&&e.jsx(Xe,{variant:"outline",children:"Accepting clients"})]})]}),e.jsxs(H,{size:"sm",variant:"outline",onClick:()=>l(m.id),children:[e.jsx(Vl,{className:"h-4 w-4 mr-1"})," Assign"]})]}),e.jsxs("div",{className:"flex items-center justify-between text-sm pt-2 border-t",children:[e.jsx("span",{className:"text-muted-foreground",children:"LevelUp Certified"}),e.jsx(Or,{checked:m.is_certified,onCheckedChange:_=>h(m.id,_)})]})]})},m.id)})})]})]}),e.jsx(Uqt,{coachId:i,onClose:()=>l(null)})]})}function $qt(){const[s,t]=S.useState("1500"),[r,n]=S.useState(!1),[a,i]=S.useState(!1);S.useEffect(()=>{(async()=>{const{data:c}=await V.from("settings").select("value").eq("key","coaching_platform_fee_bps").maybeSingle();c!=null&&c.value&&t(String(c.value)),i(!0)})()},[]);const l=async()=>{const c=parseInt(s,10);if(isNaN(c)||c<0||c>5e3)return he.error("Enter a value between 0 and 5000 bps (0–50%)");n(!0);const{error:d}=await V.from("settings").upsert({key:"coaching_platform_fee_bps",value:String(c)});if(n(!1),d)return he.error(d.message);he.success("Platform fee updated")};if(!a)return null;const o=(parseInt(s,10)/100).toFixed(2);return e.jsx(ke,{children:e.jsxs(Oe,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ME,{className:"h-5 w-5 text-primary"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Platform Fee"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"The percentage LevelUp takes from every coaching subscription. Stored as basis points (100 bps = 1%)."}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx(ue,{children:"Fee (bps)"}),e.jsx(Se,{type:"number",value:s,onChange:c=>t(c.target.value),min:0,max:5e3}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["= ",o,"%"]})]}),e.jsx(H,{onClick:l,disabled:r,className:"bg-[#406E71] hover:bg-[#2a4c64] self-end",children:r?"Saving…":"Save"})]})]})})}function Uqt({coachId:s,onClose:t}){const[r,n]=S.useState(""),[a,i]=S.useState([]),[l,o]=S.useState(!1),c=ns();S.useEffect(()=>{if(!s){n(""),i([]);return}},[s]),S.useEffect(()=>{const h=r.trim();if(h.length<2){i([]);return}o(!0);const m=setTimeout(async()=>{const{data:p}=await V.from("profiles").select("id, name, email").or(`email.ilike.%${h}%,name.ilike.%${h}%`).limit(15);i(p||[]),o(!1)},250);return()=>clearTimeout(m)},[r]);const d=async h=>{const{error:m}=await V.from("coaching_assignments").insert({coach_id:s,agent_id:h,status:"active",source:"admin",pipeline_stage:"onboarding"});if(m)return he.error(m.message);he.success("Agent assigned"),c.invalidateQueries({queryKey:["coach-roster"]}),t()};return e.jsx(bs,{open:!!s,onOpenChange:h=>!h&&t(),children:e.jsxs(vs,{children:[e.jsx(Cs,{children:e.jsx(Ns,{children:"Assign Agent"})}),e.jsx(Se,{placeholder:"Search agents by name or email…",value:r,onChange:h=>n(h.target.value),autoFocus:!0}),e.jsx("div",{className:"space-y-1 max-h-72 overflow-auto border rounded-md",children:r.trim().length<2?e.jsx("div",{className:"p-3 text-sm text-muted-foreground",children:"Type at least 2 characters to search…"}):l?e.jsx("div",{className:"p-3 text-sm text-muted-foreground",children:"Searching…"}):a.length===0?e.jsx("div",{className:"p-3 text-sm text-muted-foreground",children:"No agents found"}):a.map(h=>e.jsxs("button",{onClick:()=>d(h.id),className:"w-full text-left p-2 hover:bg-muted",children:[e.jsx("div",{className:"font-medium",children:h.name||h.email}),e.jsx("div",{className:"text-xs text-muted-foreground",children:h.email})]},h.id))}),e.jsx(wn,{children:e.jsx(H,{variant:"outline",onClick:t,children:"Close"})})]})})}function qqt(){const s=ns(),[t,r]=S.useState("pending"),[n,a]=S.useState(null),{data:i=[],isLoading:l}=yt({queryKey:["coach-applications",t],queryFn:async()=>{let h=V.from("coach_applications").select("*").order("created_at",{ascending:!1});t!=="all"&&(h=h.eq("status",t));const{data:m,error:p}=await h;if(p)throw p;return m||[]}}),{data:o=0}=yt({queryKey:["coach-applications-pending-count"],queryFn:async()=>{const{count:h}=await V.from("coach_applications").select("id",{count:"exact",head:!0}).eq("status","pending");return h||0}}),c=async(h,m)=>{const{error:p}=await V.from("coach_applications").update({status:m,reviewed_at:new Date().toISOString()}).eq("id",h);if(p)return he.error(p.message);he.success(`Marked ${m}`),s.invalidateQueries({queryKey:["coach-applications"]}),s.invalidateQueries({queryKey:["coach-applications-pending-count"]}),a(null)},d=h=>h==="approved"?e.jsxs(Xe,{className:"bg-emerald-500/15 text-emerald-700 border-emerald-300/40",children:[e.jsx(va,{className:"h-3 w-3 mr-1"}),"Approved"]}):h==="rejected"?e.jsxs(Xe,{className:"bg-rose-500/15 text-rose-700 border-rose-300/40",children:[e.jsx(Rr,{className:"h-3 w-3 mr-1"}),"Rejected"]}):e.jsxs(Xe,{className:"bg-yellow-500/15 text-yellow-700 border-yellow-300/40",children:[e.jsx(Pn,{className:"h-3 w-3 mr-1"}),"Pending"]});return e.jsxs(ke,{children:[e.jsxs(Oe,{className:"p-4 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(Uk,{className:"h-5 w-5 text-primary"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Coach Applications"}),o>0&&e.jsxs(Xe,{className:"bg-yellow-500/15 text-yellow-700 border-yellow-300/40",children:[o," pending"]}),e.jsx("div",{className:"ml-auto flex gap-1 flex-wrap",children:["pending","approved","rejected","all"].map(h=>e.jsx(H,{size:"sm",variant:t===h?"default":"outline",onClick:()=>r(h),className:t===h?"bg-[#406E71] hover:bg-[#2a4c64]":"",children:h.charAt(0).toUpperCase()+h.slice(1)},h))})]}),l?e.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading…"}):i.length===0?e.jsxs("div",{className:"text-sm text-muted-foreground p-6 text-center border rounded-md",children:["No applications ",t!=="all"?`with status "${t}"`:"yet","."]}):e.jsx("div",{className:"divide-y border rounded-md",children:i.map(h=>e.jsx("button",{onClick:()=>a(h),className:"w-full text-left p-3 hover:bg-muted/40 transition-colors",children:e.jsxs("div",{className:"flex items-center justify-between gap-3 flex-wrap",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-medium",children:h.full_name}),e.jsxs("div",{className:"text-xs text-muted-foreground flex items-center gap-3 mt-0.5",children:[e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(er,{className:"h-3 w-3"}),h.email]}),h.brokerage&&e.jsxs("span",{children:["· ",h.brokerage]}),h.years_experience&&e.jsxs("span",{children:["· ",h.years_experience," yrs"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[d(h.status),e.jsx("span",{className:"text-xs text-muted-foreground",children:new Date(h.created_at).toLocaleDateString()})]})]})},h.id))})]}),e.jsx(bs,{open:!!n,onOpenChange:h=>!h&&a(null),children:e.jsx(vs,{className:"max-w-2xl max-h-[85vh] overflow-y-auto",children:n&&e.jsxs(e.Fragment,{children:[e.jsx(Cs,{children:e.jsxs(Ns,{className:"flex items-center gap-3",children:[n.full_name,d(n.status)]})}),e.jsxs("div",{className:"space-y-4 text-sm",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(m6,{icon:er,label:"Email",value:n.email,link:`mailto:${n.email}`}),n.phone&&e.jsx(m6,{icon:Yn,label:"Phone",value:n.phone,link:`tel:${n.phone}`}),n.brokerage&&e.jsx(m6,{label:"Brokerage",value:n.brokerage}),n.years_experience&&e.jsx(m6,{label:"Years",value:n.years_experience}),n.website_url&&e.jsx(m6,{icon:gn,label:"Website",value:n.website_url,link:n.website_url}),n.linkedin_url&&e.jsx(m6,{icon:gn,label:"LinkedIn",value:n.linkedin_url,link:n.linkedin_url})]}),n.specialties&&e.jsx(Lbe,{label:"Specialties",children:n.specialties}),e.jsx(Lbe,{label:"Why they want to coach",children:n.why_coach}),n.results_story&&e.jsx(Lbe,{label:"Results story",children:n.results_story}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs font-semibold uppercase text-muted-foreground",children:"Admin notes"}),e.jsx(vr,{defaultValue:n.admin_notes||"",rows:3,onBlur:async h=>{const m=h.target.value;m!==(n.admin_notes||"")&&(await V.from("coach_applications").update({admin_notes:m}).eq("id",n.id),s.invalidateQueries({queryKey:["coach-applications"]}))},placeholder:"Internal notes (saved on blur)…"})]})]}),e.jsxs(wn,{className:"gap-2 flex-wrap",children:[n.status!=="rejected"&&e.jsxs(H,{variant:"outline",onClick:()=>c(n.id,"rejected"),className:"text-rose-600 border-rose-200 hover:bg-rose-50",children:[e.jsx(Rr,{className:"h-4 w-4 mr-1"})," Reject"]}),n.status!=="pending"&&e.jsxs(H,{variant:"outline",onClick:()=>c(n.id,"pending"),children:[e.jsx(Pn,{className:"h-4 w-4 mr-1"})," Move to pending"]}),n.status!=="approved"&&e.jsxs(H,{onClick:()=>c(n.id,"approved"),className:"bg-emerald-600 hover:bg-emerald-700",children:[e.jsx(va,{className:"h-4 w-4 mr-1"})," Approve"]})]})]})})})]})}function m6({icon:s,label:t,value:r,link:n}){const a=e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[s&&e.jsx(s,{className:"h-3.5 w-3.5"}),r]});return e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] font-semibold uppercase text-muted-foreground tracking-wide",children:t}),e.jsx("div",{className:"text-sm",children:n?e.jsx("a",{href:n,target:"_blank",rel:"noreferrer",className:"text-[#406E71] hover:underline break-all",children:a}):a})]})}function Lbe({label:s,children:t}){return e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] font-semibold uppercase text-muted-foreground tracking-wide mb-1",children:s}),e.jsx("div",{className:"text-sm whitespace-pre-wrap text-slate-700",children:t})]})}function Vqt(){const s=Fr(),{data:t}=Zge(),r=ns(),[n,a]=S.useState(!1),[i,l]=S.useState(!1),[o,c]=S.useState(null),{data:d,refetch:h}=yt({queryKey:["coach-stripe-status",t==null?void 0:t.id],enabled:!!t,queryFn:async()=>{const{data:b}=await V.functions.invoke("coach-stripe-status");return b}}),{data:m=[]}=yt({queryKey:["coach-packages",t==null?void 0:t.id],enabled:!!t,queryFn:async()=>{const{data:b}=await V.from("coaching_packages").select("*").eq("coach_id",t.id).order("sort_order");return b||[]}});S.useEffect(()=>{const b=new URLSearchParams(window.location.search);(b.get("onboarded")||b.get("refresh"))&&h()},[h]);const p=async()=>{var T,E;a(!0);const{data:b,error:j}=await V.functions.invoke("coach-stripe-connect");a(!1);let k=b==null?void 0:b.error;if(!k&&j)try{const A=await((E=(T=j==null?void 0:j.context)==null?void 0:T.json)==null?void 0:E.call(T));k=(A==null?void 0:A.error)||j.message}catch{k=j.message}if(k)return he.error(k,{duration:1e4});b!=null&&b.url&&(window.location.href=b.url)},x=d||{},y=!!(t!=null&&t.use_platform_stripe),_=y||x.connected&&x.charges_enabled;return e.jsx(Ss,{title:"Coaching · Billing",children:e.jsxs("div",{className:"max-w-3xl mx-auto p-4 md:p-8 space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(H,{variant:"ghost",size:"icon",onClick:()=>s("/coaching"),children:e.jsx(za,{className:"h-5 w-5"})}),e.jsx("h1",{className:"text-2xl font-bold",children:"Billing & Packages"})]}),e.jsx(ke,{children:e.jsxs(Oe,{className:"p-6 space-y-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-lg font-semibold flex items-center gap-2",children:[e.jsx(u0,{className:"h-5 w-5"})," Stripe Connect"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:y?"Your coaching sales are billed through the main LevelUp Stripe account.":"Payouts go directly to your bank. LevelUp takes a small platform fee from each charge."})]}),_?e.jsxs(Xe,{className:"bg-emerald-500/15 text-emerald-700 border-emerald-300/40 flex items-center gap-1",children:[e.jsx(ea,{className:"h-3 w-3"})," ",y?"Using LevelUp billing":"Connected"]}):x.connected?e.jsxs(Xe,{variant:"secondary",className:"flex items-center gap-1",children:[e.jsx(wo,{className:"h-3 w-3"})," Setup incomplete"]}):e.jsx(Xe,{variant:"outline",children:"Not connected"})]}),!y&&e.jsxs(H,{onClick:p,disabled:n,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:[_?"Update Stripe details":x.connected?"Finish Stripe setup":"Connect Stripe",e.jsx(gn,{className:"h-4 w-4 ml-1"})]})]})}),e.jsx(ke,{children:e.jsxs(Oe,{className:"p-6 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Packages"}),e.jsxs(H,{size:"sm",onClick:()=>{c(null),l(!0)},disabled:!_,children:[e.jsx(Ys,{className:"h-4 w-4 mr-1"})," New Package"]})]}),!_&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Connect Stripe before creating packages."}),m.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"No packages yet."}):e.jsx("div",{className:"space-y-2",children:m.map(b=>e.jsxs("div",{className:"flex items-center gap-3 p-3 border rounded-lg",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-medium flex items-center gap-2",children:[b.name,b.is_active&&b.accepting_clients===!1&&e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full bg-amber-100 text-amber-800 font-semibold",children:"Booked full"})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:["$",(b.price_cents/100).toFixed(0)," / ",b.billing_interval,!b.is_active&&" · Inactive"]})]}),e.jsx(H,{variant:"ghost",size:"icon",onClick:()=>{c(b),l(!0)},children:e.jsx(ni,{className:"h-4 w-4"})}),e.jsx(H,{variant:"ghost",size:"icon",onClick:async()=>{confirm("Delete this package?")&&(await V.from("coaching_packages").delete().eq("id",b.id),r.invalidateQueries({queryKey:["coach-packages",t==null?void 0:t.id]}))},children:e.jsx(Dr,{className:"h-4 w-4"})})]},b.id))})]})}),e.jsx(Hqt,{open:i,onOpenChange:l,coachId:t==null?void 0:t.id,pkg:o,onSaved:()=>r.invalidateQueries({queryKey:["coach-packages",t==null?void 0:t.id]})})]})})}function Hqt({open:s,onOpenChange:t,coachId:r,pkg:n,onSaved:a}){const[i,l]=S.useState(""),[o,c]=S.useState(""),[d,h]=S.useState(""),[m,p]=S.useState("month"),[x,y]=S.useState(!0),[_,b]=S.useState(!0),[j,k]=S.useState(!1);S.useEffect(()=>{s&&(l((n==null?void 0:n.name)||""),c((n==null?void 0:n.description)||""),h(n?(n.price_cents/100).toString():""),p((n==null?void 0:n.billing_interval)||"month"),y((n==null?void 0:n.is_active)??!0),b((n==null?void 0:n.accepting_clients)??!0))},[s,n]);const T=async()=>{if(!i.trim()||!d)return he.error("Name and price required");k(!0);const E={coach_id:r,name:i,description:o||null,price_cents:Math.round(Number(d)*100),billing_interval:m,is_active:x,accepting_clients:_},{error:A}=n!=null&&n.id?await V.from("coaching_packages").update(E).eq("id",n.id):await V.from("coaching_packages").insert(E);if(k(!1),A)return he.error(A.message);he.success("Saved"),a==null||a(),t(!1)};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{children:[e.jsx(Cs,{children:e.jsx(Ns,{children:n!=null&&n.id?"Edit Package":"New Package"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(Se,{placeholder:"Name (e.g. Accelerator)",value:i,onChange:E=>l(E.target.value)}),e.jsx(vr,{rows:3,placeholder:"What's included",value:o,onChange:E=>c(E.target.value)}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Price (USD)"}),e.jsx(Se,{type:"number",value:d,onChange:E=>h(E.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Interval"}),e.jsxs(Bs,{value:m,onValueChange:p,children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"month",children:"Monthly"}),e.jsx(pt,{value:"year",children:"Yearly"}),e.jsx(pt,{value:"one_time",children:"One-time"})]})]})]})]}),e.jsxs("div",{className:"space-y-2 pt-1",children:[e.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[e.jsx("input",{type:"checkbox",checked:x,onChange:E=>y(E.target.checked)}),"Active (visible to agents)"]}),e.jsxs("label",{className:"flex items-start gap-2 text-sm",children:[e.jsx("input",{type:"checkbox",className:"mt-0.5",checked:_,onChange:E=>b(E.target.checked)}),e.jsxs("span",{children:[e.jsx("span",{className:"font-medium",children:"Accepting new clients"}),e.jsx("span",{className:"block text-xs text-muted-foreground",children:"Uncheck if you're booked full — visitors will still see the package but can't sign up."})]})]})]})]}),e.jsxs(wn,{children:[e.jsx(H,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(H,{onClick:T,disabled:j,children:n!=null&&n.id?"Save":"Create"})]})]})})}function a9e({kind:s,value:t,onChange:r}){const n=S.useRef(null),[a,i]=S.useState(!1),[l,o]=S.useState(!1),[c,d]=S.useState(null),h=S.useRef(null),m=S.useRef(null),p=S.useRef(null),x=S.useRef([]),[y,_]=S.useState(!1),b=s==="photo"?"image/*":"video/*",j=s==="photo"?10*1024*1024:200*1024*1024,k=async(z,O)=>{var re;const{data:$}=await V.auth.getUser(),ee=(re=$.user)==null?void 0:re.id;if(!ee)return he.error("Not signed in");if(z.size>j)return he.error(`File too large. Max ${s==="photo"?"10MB":"200MB"}.`);i(!0);const Z=`${ee}/${s}-${Date.now()}.${O}`,{error:J}=await V.storage.from("coach-media").upload(Z,z,{upsert:!0,contentType:z.type||(s==="photo"?"image/jpeg":"video/webm")});if(J)return i(!1),he.error(J.message);const{data:K}=await V.storage.from("coach-media").createSignedUrl(Z,60*60*24*365*10);i(!1),K!=null&&K.signedUrl&&(r(K.signedUrl),he.success("Uploaded"),d(null))},T=async z=>{const O=z.name.split(".").pop()||(s==="photo"?"jpg":"webm");await k(z,O)},E=async()=>{try{const z=await navigator.mediaDevices.getUserMedia({video:!0,audio:!0});m.current=z,_(!0),setTimeout(()=>{h.current&&(h.current.srcObject=z,h.current.play())},50);const O=new MediaRecorder(z,{mimeType:"video/webm"});x.current=[],O.ondataavailable=$=>$.data.size>0&&x.current.push($.data),O.onstop=()=>{const $=new Blob(x.current,{type:"video/webm"});d($),z.getTracks().forEach(ee=>ee.stop())},p.current=O,O.start(),o(!0)}catch(z){he.error(z.message||"Could not access camera")}},A=()=>{var z;(z=p.current)==null||z.stop(),o(!1)},D=()=>{var z;(z=m.current)==null||z.getTracks().forEach(O=>O.stop()),_(!1),o(!1),d(null)},R=async()=>{c&&(await k(c,"webm"),D())};return S.useEffect(()=>()=>{var z;return(z=m.current)==null?void 0:z.getTracks().forEach(O=>O.stop())},[]),e.jsxs("div",{className:"space-y-2",children:[t&&e.jsx("div",{className:"rounded-lg overflow-hidden border bg-muted/30",children:s==="photo"?e.jsx("img",{src:t,alt:"Profile",className:"w-32 h-32 object-cover"}):e.jsx("video",{src:t,controls:!0,className:"w-full max-h-64"})}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("input",{ref:n,type:"file",accept:b,className:"hidden",onChange:z=>{var $;const O=($=z.target.files)==null?void 0:$[0];O&&T(O),z.target.value=""}}),e.jsxs(H,{type:"button",variant:"outline",size:"sm",disabled:a,onClick:()=>{var z;return(z=n.current)==null?void 0:z.click()},children:[a?e.jsx(is,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Ea,{className:"h-4 w-4 mr-1"}),s==="photo"?"Upload photo":"Upload video"]}),s==="video"&&e.jsxs(H,{type:"button",variant:"outline",size:"sm",onClick:E,disabled:a||y,children:[e.jsx(lx,{className:"h-4 w-4 mr-1"})," Record intro"]}),t&&e.jsxs(H,{type:"button",variant:"ghost",size:"sm",onClick:()=>r(""),children:[e.jsx(Dr,{className:"h-4 w-4 mr-1"})," Remove"]})]}),y&&e.jsxs("div",{className:"rounded-lg border p-3 space-y-3 bg-background",children:[c?e.jsx("video",{src:URL.createObjectURL(c),controls:!0,className:"w-full max-h-64 rounded bg-black"}):e.jsx("video",{ref:h,muted:!0,playsInline:!0,className:"w-full max-h-64 rounded bg-black"}),e.jsxs("div",{className:"flex gap-2",children:[!c&&l&&e.jsxs(H,{type:"button",size:"sm",onClick:A,className:"bg-red-600 hover:bg-red-700",children:[e.jsx(Hy,{className:"h-4 w-4 mr-1"})," Stop"]}),!c&&!l&&e.jsxs(H,{type:"button",size:"sm",onClick:()=>{var z;return(z=p.current)==null?void 0:z.start()},children:[e.jsx(xn,{className:"h-4 w-4 mr-1"})," Start"]}),c&&e.jsxs(e.Fragment,{children:[e.jsxs(H,{type:"button",size:"sm",onClick:R,disabled:a,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:[a?e.jsx(is,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Ea,{className:"h-4 w-4 mr-1"}),"Use this recording"]}),e.jsx(H,{type:"button",size:"sm",variant:"outline",onClick:()=>{d(null),E()},children:"Re-record"})]}),e.jsx(H,{type:"button",size:"sm",variant:"ghost",onClick:D,children:"Cancel"})]})]})]})}function Gqt(){const s=Fr(),{data:t,isLoading:r}=Zge(),n=ns(),[a,i]=S.useState(""),[l,o]=S.useState(""),[c,d]=S.useState(""),[h,m]=S.useState(""),[p,x]=S.useState(""),[y,_]=S.useState(!1),[b,j]=S.useState([]),[k,T]=S.useState(""),[E,A]=S.useState(!1);S.useEffect(()=>{if(!t)return;const $=t;i($.slug||""),o($.headline||""),d($.bio||""),m($.photo_url||""),x($.intro_video_url||""),_(!!$.accepting_clients),j($.specialties||[])},[t]);const D=async()=>{if(!t)return;A(!0);const{error:$}=await V.from("coaches").update({slug:a.trim()||null,headline:l||null,bio:c||null,photo_url:h||null,intro_video_url:p||null,accepting_clients:y,specialties:b}).eq("id",t.id);if(A(!1),$)return he.error($.message);he.success("Profile saved"),n.invalidateQueries({queryKey:["my-coach-profile"]})},R=()=>{const $=k.trim();if($){if(b.includes($))return T("");j([...b,$]),T("")}};if(r)return e.jsx(Ss,{title:"Coach Settings",children:e.jsx("div",{className:"p-8",children:"Loading…"})});if(!t)return e.jsx(Ss,{title:"Coach Settings",children:e.jsx("div",{className:"max-w-2xl mx-auto p-8 text-center text-muted-foreground",children:"You don't have a coach profile yet."})});const z=t,O=z.slug?`${window.location.origin}/coaches/${z.slug}`:null;return e.jsx(Ss,{title:"Coach Settings",children:e.jsxs("div",{className:"max-w-3xl mx-auto p-4 md:p-8 space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(H,{variant:"ghost",size:"icon",onClick:()=>s("/coaching"),children:e.jsx(za,{className:"h-5 w-5"})}),e.jsx("h1",{className:"text-2xl font-bold",children:"Coach Profile"})]}),e.jsxs("div",{className:"flex gap-2",children:[O&&e.jsxs(H,{variant:"outline",size:"sm",onClick:()=>window.open(O,"_blank"),children:[e.jsx(gn,{className:"h-4 w-4 mr-1"})," View public"]}),e.jsxs(H,{onClick:D,disabled:E,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:[e.jsx(vc,{className:"h-4 w-4 mr-1"})," ",E?"Saving…":"Save"]})]})]}),z.is_certified&&e.jsxs("div",{className:"rounded-lg border border-yellow-300/50 bg-yellow-50 dark:bg-yellow-950/20 px-4 py-3 text-sm",children:["✨ ",e.jsx("strong",{children:"LevelUp Certified"})," — Your profile displays a verified badge."]}),e.jsx(ke,{children:e.jsxs(Oe,{className:"p-6 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border bg-muted/30",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:"Accepting new clients"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"When off, you're hidden from the public directory."})]}),e.jsx(Or,{checked:y,onCheckedChange:_})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Public URL slug"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm text-muted-foreground whitespace-nowrap",children:"/coaches/"}),e.jsx(Se,{value:a,onChange:$=>i($.target.value.toLowerCase().replace(/[^a-z0-9-]/g,"")),placeholder:"your-name"})]})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Headline"}),e.jsx(Se,{value:l,onChange:$=>o($.target.value),placeholder:"e.g. Helping new agents close their first 10 deals",maxLength:140})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Bio"}),e.jsx(vr,{rows:6,value:c,onChange:$=>d($.target.value),placeholder:"Tell agents who you are, what you've done, how you coach…"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Profile photo"}),e.jsx(a9e,{kind:"photo",value:h,onChange:m})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Intro video"}),e.jsx(a9e,{kind:"video",value:p,onChange:x})]})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Specialties"}),e.jsx("div",{className:"flex flex-wrap gap-2 mb-2",children:b.map($=>e.jsxs(Xe,{variant:"secondary",className:"gap-1",children:[$,e.jsx("button",{onClick:()=>j(b.filter(ee=>ee!==$)),children:e.jsx(Rr,{className:"h-3 w-3"})})]},$))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Se,{value:k,onChange:$=>T($.target.value),placeholder:"Add a specialty…",onKeyDown:$=>{$.key==="Enter"&&($.preventDefault(),R())}}),e.jsx(H,{type:"button",variant:"outline",onClick:R,children:e.jsx(Ys,{className:"h-4 w-4"})})]})]})]})}),e.jsx(ke,{children:e.jsx(Oe,{className:"p-6",children:e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Packages & Stripe"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Manage your monetized packages on the Billing page."})]}),e.jsx(H,{variant:"outline",onClick:()=>s("/coaching/billing"),children:"Go to Billing"})]})})}),e.jsx(Wqt,{coachId:z.id})]})})}function Wqt({coachId:s}){const[t,r]=S.useState("");ns();const{data:n=[],refetch:a}=yt({queryKey:["coach-invites",s],queryFn:async()=>{const{data:c}=await V.from("coaching_invites").select("*").eq("coach_id",s).order("created_at",{ascending:!1});return c||[]}}),i=async()=>{const c=t.trim().toLowerCase();if(!c)return he.error("Email required");const{error:d}=await V.from("coaching_invites").insert({coach_id:s,email:c});if(d)return he.error(d.message);r(""),he.success("Invite created"),a()},l=c=>{const d=`${window.location.origin}/auth?coach_invite=${c}`;navigator.clipboard.writeText(d),he.success("Link copied")},o=async c=>{confirm("Revoke this invite?")&&(await V.from("coaching_invites").delete().eq("id",c),a())};return e.jsx(ke,{children:e.jsxs(Oe,{className:"p-6 space-y-3",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-lg font-semibold flex items-center gap-2",children:[e.jsx(Jo,{className:"h-5 w-5"})," Invite agents"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Generate a magic link to onboard agents directly."})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Se,{placeholder:"agent@email.com",value:t,onChange:c=>r(c.target.value),onKeyDown:c=>c.key==="Enter"&&i()}),e.jsxs(H,{onClick:i,children:[e.jsx(Ys,{className:"h-4 w-4 mr-1"})," Create"]})]}),e.jsxs("div",{className:"space-y-2",children:[n.map(c=>e.jsxs("div",{className:"flex items-center gap-2 p-3 border rounded-lg",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-medium truncate",children:c.email}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[c.status," · expires ",new Date(c.expires_at).toLocaleDateString()]})]}),e.jsx(H,{variant:"ghost",size:"icon",onClick:()=>l(c.token),children:e.jsx(ui,{className:"h-4 w-4"})}),e.jsx(H,{variant:"ghost",size:"icon",onClick:()=>o(c.id),children:e.jsx(Dr,{className:"h-4 w-4"})})]},c.id)),n.length===0&&e.jsx("div",{className:"text-sm text-muted-foreground text-center py-4",children:"No invites yet."})]})]})})}function Kqt(){const{data:s=[],isLoading:t}=yt({queryKey:["coaches-directory"],queryFn:async()=>{const{data:r,error:n}=await V.from("coaches").select("id, slug, headline, bio, specialties, photo_url, is_certified, accepting_clients, user_id").not("slug","is",null);if(n)throw n;const a=(r||[]).map(o=>o.user_id);if(a.length===0)return[];const{data:i}=await V.from("profiles").select("id, name, avatar_url").in("id",a),l=new Map((i||[]).map(o=>[o.id,o]));return(r||[]).map(o=>({...o,profile:l.get(o.user_id)}))}});return e.jsxs("div",{className:"min-h-screen bg-white",children:[e.jsxs("section",{className:"relative overflow-hidden bg-gradient-to-br from-[#1c3447] via-[#2a4c64] to-[#406E71] text-white",children:[e.jsx("div",{className:"absolute -top-32 -left-24 h-96 w-96 rounded-full bg-[#5a9ea2]/20 blur-3xl"}),e.jsx("div",{className:"absolute -bottom-32 -right-24 h-96 w-96 rounded-full bg-yellow-400/10 blur-3xl"}),e.jsx("div",{className:"absolute inset-0 opacity-[0.04]",style:{backgroundImage:"radial-gradient(white 1px, transparent 1px)",backgroundSize:"22px 22px"}}),e.jsxs("div",{className:"relative max-w-6xl mx-auto px-4 py-20 md:py-28 text-center",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 px-3 py-1.5 rounded-full bg-white/10 backdrop-blur-sm border border-white/15 text-xs uppercase tracking-[0.18em] font-semibold mb-6",children:[e.jsx(Lr,{className:"h-3.5 w-3.5 text-yellow-300"}),"LevelUp Certified Coaches"]}),e.jsxs("h1",{className:"text-5xl md:text-7xl font-bold tracking-tight leading-[1.05]",children:["Coaching that ",e.jsx("span",{className:"bg-gradient-to-r from-yellow-300 to-yellow-100 bg-clip-text text-transparent",children:"moves the needle."})]}),e.jsx("p",{className:"text-white/75 mt-6 max-w-2xl mx-auto text-lg leading-relaxed",children:"Hand-picked real-estate coaches ready to help you hit your next breakthrough — from lead gen to listings to luxury."}),e.jsxs("div",{className:"flex flex-wrap justify-center gap-6 mt-10 text-sm text-white/70",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ea,{className:"h-4 w-4 text-yellow-300"})," Vetted by LevelUp"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(To,{className:"h-4 w-4 text-yellow-300"})," Top-producer experience"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ya,{className:"h-4 w-4 text-yellow-300"})," Real, measurable results"]})]})]}),e.jsx("svg",{className:"block w-full text-white",viewBox:"0 0 1440 60",preserveAspectRatio:"none","aria-hidden":!0,children:e.jsx("path",{fill:"currentColor",d:"M0,40 C360,80 1080,0 1440,40 L1440,60 L0,60 Z"})})]}),e.jsxs("section",{className:"max-w-6xl mx-auto px-4 py-16 md:py-20",children:[t?e.jsx("div",{className:"text-center text-muted-foreground",children:"Loading coaches…"}):s.length===0?e.jsx("div",{className:"text-center text-muted-foreground",children:"No coaches available yet. Check back soon."}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6",children:s.map(r=>{var i,l;const n=((i=r.profile)==null?void 0:i.name)||"Coach",a=r.photo_url||((l=r.profile)==null?void 0:l.avatar_url);return e.jsx(Xn,{to:`/coaches/${r.slug||r.id}`,className:"group",children:e.jsx("article",{className:"relative h-full rounded-2xl bg-[#1c3447] overflow-hidden transition-all duration-300 hover:-translate-y-1 hover:shadow-[0_24px_60px_-20px_rgba(42,76,100,0.5)]",children:e.jsxs("div",{className:"relative aspect-[3/4] w-full overflow-hidden",children:[a?e.jsx("img",{src:a,alt:n,className:"absolute inset-0 h-full w-full object-cover object-top group-hover:scale-105 transition-transform duration-700"}):e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-gradient-to-br from-[#2a4c64] to-[#406E71] text-white text-6xl font-bold",children:n.charAt(0)}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-[#0d1f2d] via-[#0d1f2d]/70 to-transparent"}),e.jsxs("div",{className:"absolute top-3 left-3 right-3 flex items-start justify-between gap-2",children:[r.is_certified?e.jsxs("div",{className:"inline-flex items-center gap-1 px-2.5 py-1 rounded-full bg-gradient-to-r from-yellow-400 to-yellow-300 text-[#2a4c64] text-[11px] font-semibold shadow-md",children:[e.jsx(Lr,{className:"h-3 w-3"})," Certified"]}):e.jsx("span",{}),e.jsxs("div",{className:`inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-[11px] font-medium backdrop-blur-md ${r.accepting_clients?"bg-emerald-500/90 text-white":"bg-white/85 text-[#2a4c64]"}`,children:[e.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${r.accepting_clients?"bg-white":"bg-amber-500"}`}),r.accepting_clients?"Accepting":"Waitlist"]})]}),e.jsxs("div",{className:"absolute inset-x-0 bottom-0 p-5 text-white",children:[e.jsx("h3",{className:"text-xl font-bold leading-tight drop-shadow-sm",children:n}),r.headline&&e.jsx("p",{className:"text-sm text-yellow-200/90 font-medium mt-1 line-clamp-1",children:r.headline}),r.bio&&e.jsx("p",{className:"text-[13px] text-white/80 mt-2 line-clamp-2 leading-relaxed",children:r.bio}),r.specialties&&r.specialties.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5 mt-3",children:r.specialties.slice(0,2).map(o=>e.jsx("span",{className:"text-[10px] px-2 py-0.5 rounded-full bg-white/15 backdrop-blur-sm text-white border border-white/20",children:o},o))}),e.jsxs("div",{className:"flex items-center justify-between mt-4 pt-3 border-t border-white/15",children:[e.jsx("span",{className:"text-sm font-semibold text-white",children:"View profile"}),e.jsx("span",{className:"inline-flex items-center justify-center h-8 w-8 rounded-full bg-white/15 backdrop-blur-sm text-white group-hover:bg-yellow-300 group-hover:text-[#1c3447] transition-colors",children:e.jsx(bi,{className:"h-4 w-4"})})]})]})]})})},r.id)})}),e.jsxs("div",{className:"mt-20 rounded-3xl bg-gradient-to-br from-[#1c3447] via-[#2a4c64] to-[#406E71] text-white p-10 md:p-14 relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 opacity-[0.06]",style:{backgroundImage:"radial-gradient(white 1px, transparent 1px)",backgroundSize:"18px 18px"}}),e.jsx("div",{className:"absolute -top-24 -right-24 h-72 w-72 rounded-full bg-yellow-300/15 blur-3xl"}),e.jsxs("div",{className:"relative md:flex items-center gap-10",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 px-3 py-1.5 rounded-full bg-white/10 border border-white/15 text-[11px] uppercase tracking-[0.18em] font-semibold mb-5",children:[e.jsx(Lr,{className:"h-3.5 w-3.5 text-yellow-300"})," Coach Applications Open"]}),e.jsxs("h2",{className:"text-3xl md:text-4xl font-bold leading-tight",children:["Are you the kind of agent ",e.jsx("span",{className:"text-yellow-300",children:"other agents need?"})]}),e.jsx("p",{className:"text-white/80 mt-4 max-w-xl leading-relaxed",children:"LevelUp Coaches are the top 1% — top producers, proven mentors, and category leaders making a measurable difference in agents' businesses. If that's you, we want to meet you."}),e.jsxs("div",{className:"mt-6 flex flex-wrap gap-3 text-sm text-white/70",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(ea,{className:"h-4 w-4 text-yellow-300"})," Premium client base"]}),e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(ea,{className:"h-4 w-4 text-yellow-300"})," Recurring revenue"]}),e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(ea,{className:"h-4 w-4 text-yellow-300"})," Certified status"]})]})]}),e.jsxs("div",{className:"mt-8 md:mt-0",children:[e.jsxs(Xn,{to:"/coaches/apply",className:"inline-flex items-center gap-2 bg-yellow-300 text-[#1c3447] hover:bg-yellow-200 font-bold px-7 py-4 rounded-xl shadow-lg shadow-yellow-300/20 transition-all hover:-translate-y-0.5",children:["Apply to coach ",e.jsx(bi,{className:"h-5 w-5"})]}),e.jsx("p",{className:"text-xs text-white/60 mt-3 text-center md:text-left",children:"By application only."})]})]})]})]})]})}function Yqt(){var x;const{slug:s}=Po(),t=Fr(),{user:r}=Ms(),[n,a]=S.useState(null),{data:i,isLoading:l}=yt({queryKey:["coach-public",s],enabled:!!s,queryFn:async()=>{const y=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(s||""),_=V.from("coaches").select("*"),{data:b}=y?await _.eq("id",s).maybeSingle():await _.eq("slug",s).maybeSingle();if(!b)return null;const[{data:j},{data:k}]=await Promise.all([V.from("profiles").select("id, name, avatar_url").eq("id",b.user_id).maybeSingle(),V.from("coaching_packages").select("*").eq("coach_id",b.id).eq("is_active",!0).order("sort_order")]);return{coach:b,profile:j,packages:k||[]}}}),o=async y=>{if(!r){he.error("Please sign in to subscribe"),t(`/auth?redirect=/coaches/${s}`);return}a(y);const{data:_,error:b}=await V.functions.invoke("create-coaching-checkout",{body:{packageId:y}});if(a(null),b||_!=null&&_.error){he.error((_==null?void 0:_.error)||(b==null?void 0:b.message)||"Checkout failed");return}_!=null&&_.url&&(window.location.href=_.url)};if(l)return e.jsx("div",{className:"p-12 text-center",children:"Loading…"});if(!(i!=null&&i.coach))return e.jsx("div",{className:"p-12 text-center",children:"Coach not found."});const{coach:c,profile:d,packages:h}=i,m=c,p=(y,_)=>{const b=(y/100).toLocaleString("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0});return _==="one_time"?b:`${b} / ${_}`};return e.jsxs("div",{className:"min-h-screen bg-background",children:[e.jsx("div",{className:"bg-gradient-to-br from-[#2a4c64] to-[#406E71] text-white",children:e.jsxs("div",{className:"max-w-5xl mx-auto px-4 py-12 md:py-20",children:[e.jsxs(H,{variant:"ghost",size:"sm",className:"text-white/80 hover:text-white hover:bg-white/10 mb-6",onClick:()=>t("/coaches"),children:[e.jsx(za,{className:"h-4 w-4 mr-1"})," All Coaches"]}),e.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:items-center",children:[e.jsxs(Un,{className:"h-28 w-28 ring-4 ring-white/20",children:[e.jsx(Ka,{src:m.photo_url||(d==null?void 0:d.avatar_url)}),e.jsx(qn,{className:"text-3xl bg-white/20",children:((d==null?void 0:d.name)||"C").charAt(0)})]}),e.jsxs("div",{className:"flex-1",children:[m.is_certified&&e.jsxs("div",{className:"inline-flex items-center gap-1 bg-yellow-400/20 border border-yellow-300/30 text-yellow-100 px-2 py-1 rounded-full text-xs mb-2",children:[e.jsx(Lr,{className:"h-3 w-3"})," LevelUp Certified"]}),e.jsx("h1",{className:"text-3xl md:text-4xl font-bold",children:(d==null?void 0:d.name)||"Coach"}),m.headline&&e.jsx("p",{className:"text-white/80 text-lg mt-2",children:m.headline}),((x=m.specialties)==null?void 0:x.length)>0&&e.jsx("div",{className:"flex flex-wrap gap-2 mt-4",children:m.specialties.map(y=>e.jsx(Xe,{className:"bg-white/15 text-white border-white/20",children:y},y))})]})]})]})}),e.jsxs("div",{className:"max-w-5xl mx-auto px-4 py-12 grid grid-cols-1 md:grid-cols-3 gap-8",children:[e.jsxs("div",{className:"md:col-span-2 space-y-6",children:[m.intro_video_url&&e.jsx("div",{className:"aspect-video rounded-xl overflow-hidden bg-black",children:e.jsx("video",{src:m.intro_video_url,controls:!0,className:"w-full h-full"})}),m.bio&&e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-semibold mb-3",children:"About"}),e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap leading-relaxed",children:m.bio})]}),e.jsx(Oqt,{coachId:m.id})]}),e.jsxs("div",{className:"space-y-4 md:sticky md:top-6 md:self-start",children:[e.jsx("h2",{className:"text-xl font-semibold",children:"Choose a plan"}),h.length===0?e.jsx(ke,{children:e.jsx(Oe,{className:"p-6 text-sm text-muted-foreground text-center",children:"No packages available yet."})}):h.map(y=>{const _=y.accepting_clients===!1;return e.jsx(ke,{className:`border-2 transition-colors ${_?"border-amber-200 bg-amber-50/30":"hover:border-[#406E71]"}`,children:e.jsxs(Oe,{className:"p-5",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx("h3",{className:"font-semibold text-lg",children:y.name}),_&&e.jsx("span",{className:"text-[10px] uppercase tracking-wider font-bold px-2 py-1 rounded-full bg-amber-500 text-white shrink-0",children:"Booked Full"})]}),y.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:y.description}),e.jsx("div",{className:"text-2xl font-bold mt-3",children:p(y.price_cents,y.billing_interval)}),_?e.jsx("div",{className:"mt-4 rounded-md bg-amber-100 border border-amber-200 text-amber-900 px-3 py-2.5 text-sm text-center",children:"Currently not accepting new clients. Check back soon."}):e.jsxs(H,{className:"w-full mt-4 bg-[#406E71] hover:bg-[#2a4c64]",onClick:()=>o(y.id),disabled:n===y.id,children:[n===y.id?"Loading…":"Get Started",e.jsx(va,{className:"h-4 w-4 ml-1"})]})]})},y.id)}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:"Secure checkout powered by Stripe."})]})]})]})}const Zqt=yj({full_name:Ho().trim().min(2,"Please enter your full name").max(100),email:Ho().trim().email("Enter a valid email").max(255),phone:Ho().trim().max(40).optional().or(ky("")),brokerage:Ho().trim().max(150).optional().or(ky("")),years_experience:Ho().trim().max(40).optional().or(ky("")),specialties:Ho().trim().max(500).optional().or(ky("")),why_coach:Ho().trim().min(20,"Tell us a bit more — at least 20 characters").max(2e3),results_story:Ho().trim().max(2e3).optional().or(ky("")),website_url:Ho().trim().max(300).optional().or(ky("")),linkedin_url:Ho().trim().max(300).optional().or(ky(""))});function Xqt(){const s=Fr(),[t,r]=S.useState(!1),[n,a]=S.useState(!1),[i,l]=S.useState({full_name:"",email:"",phone:"",brokerage:"",years_experience:"",specialties:"",why_coach:"",results_story:"",website_url:"",linkedin_url:""}),o=(d,h)=>l(m=>({...m,[d]:h})),c=async d=>{var p;d.preventDefault();const h=Zqt.safeParse(i);if(!h.success){const x=(p=Object.values(h.error.flatten().fieldErrors)[0])==null?void 0:p[0];return he.error(x||"Please check the form and try again")}r(!0);const{error:m}=await V.from("coach_applications").insert(h.data);if(r(!1),m)return he.error(m.message||"Could not submit application");a(!0),window.scrollTo({top:0,behavior:"smooth"})};return n?e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-[#1c3447] via-[#2a4c64] to-[#406E71] text-white flex items-center justify-center p-6",children:e.jsxs("div",{className:"max-w-xl text-center",children:[e.jsx("div",{className:"inline-flex items-center justify-center h-20 w-20 rounded-full bg-gradient-to-br from-yellow-400 to-yellow-300 text-[#1c3447] mb-6 shadow-2xl",children:e.jsx(ea,{className:"h-10 w-10"})}),e.jsx("h1",{className:"text-4xl md:text-5xl font-bold mb-4",children:"Application received."}),e.jsx("p",{className:"text-white/80 text-lg leading-relaxed mb-8",children:"Thank you for applying to the LevelUp Coaching program. Our team personally reviews every application — we'll be in touch within 5 business days."}),e.jsx(H,{onClick:()=>s("/coaches"),className:"bg-yellow-300 text-[#1c3447] hover:bg-yellow-200 font-semibold",children:"Browse our coaches"})]})}):e.jsxs("div",{className:"min-h-screen bg-white",children:[e.jsxs("section",{className:"relative overflow-hidden bg-gradient-to-br from-[#1c3447] via-[#2a4c64] to-[#406E71] text-white",children:[e.jsx("div",{className:"absolute -top-32 -left-24 h-96 w-96 rounded-full bg-[#5a9ea2]/20 blur-3xl"}),e.jsx("div",{className:"absolute -bottom-32 -right-24 h-96 w-96 rounded-full bg-yellow-400/10 blur-3xl"}),e.jsx("div",{className:"absolute inset-0 opacity-[0.04]",style:{backgroundImage:"radial-gradient(white 1px, transparent 1px)",backgroundSize:"22px 22px"}}),e.jsxs("div",{className:"relative max-w-5xl mx-auto px-4 py-16 md:py-20",children:[e.jsxs(Xn,{to:"/coaches",className:"inline-flex items-center gap-2 text-white/70 hover:text-white text-sm mb-8",children:[e.jsx(za,{className:"h-4 w-4"})," Back to coaches"]}),e.jsxs("div",{className:"inline-flex items-center gap-2 px-3 py-1.5 rounded-full bg-white/10 backdrop-blur-sm border border-white/15 text-xs uppercase tracking-[0.18em] font-semibold mb-6",children:[e.jsx(Lr,{className:"h-3.5 w-3.5 text-yellow-300"}),"Coach Application — By Invitation & Application Only"]}),e.jsx("h1",{className:"text-4xl md:text-6xl font-bold tracking-tight leading-[1.05] max-w-3xl",children:"Join the most respected coaching program in real estate."}),e.jsx("p",{className:"text-white/80 mt-6 max-w-2xl text-lg leading-relaxed",children:"LevelUp Coaches don't just teach — they transform careers. We hand-pick top-producing agents and proven mentors who are ready to multiply their impact, build a recurring revenue stream, and help thousands of agents finally break through."}),e.jsxs("div",{className:"grid md:grid-cols-3 gap-4 mt-12",children:[e.jsxs("div",{className:"rounded-2xl bg-white/5 backdrop-blur-sm border border-white/10 p-5",children:[e.jsx(Ar,{className:"h-6 w-6 text-yellow-300 mb-3"}),e.jsx("h3",{className:"font-semibold text-lg",children:"Premium client base"}),e.jsx("p",{className:"text-sm text-white/70 mt-1",children:"Get matched with motivated, vetted agents who are serious about leveling up."})]}),e.jsxs("div",{className:"rounded-2xl bg-white/5 backdrop-blur-sm border border-white/10 p-5",children:[e.jsx(al,{className:"h-6 w-6 text-yellow-300 mb-3"}),e.jsx("h3",{className:"font-semibold text-lg",children:"Built-for-you platform"}),e.jsx("p",{className:"text-sm text-white/70 mt-1",children:"Subscriptions, scheduling, session notes, and payouts — handled. You just coach."})]}),e.jsxs("div",{className:"rounded-2xl bg-white/5 backdrop-blur-sm border border-white/10 p-5",children:[e.jsx(Bc,{className:"h-6 w-6 text-yellow-300 mb-3"}),e.jsx("h3",{className:"font-semibold text-lg",children:"LevelUp Certified status"}),e.jsx("p",{className:"text-sm text-white/70 mt-1",children:"A trust mark that opens doors with brokerages and high-performance agents nationwide."})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-6 mt-10 text-sm text-white/70",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ea,{className:"h-4 w-4 text-yellow-300"})," Less than 8% of applicants accepted"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(To,{className:"h-4 w-4 text-yellow-300"})," Backed by real producer results"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ya,{className:"h-4 w-4 text-yellow-300"})," Featured in our coach directory"]})]})]}),e.jsx("svg",{className:"block w-full text-white",viewBox:"0 0 1440 60",preserveAspectRatio:"none","aria-hidden":!0,children:e.jsx("path",{fill:"currentColor",d:"M0,40 C360,80 1080,0 1440,40 L1440,60 L0,60 Z"})})]}),e.jsxs("section",{className:"max-w-3xl mx-auto px-4 py-16",children:[e.jsxs("div",{className:"mb-10",children:[e.jsx("h2",{className:"text-3xl font-bold text-[#1c3447]",children:"Tell us about you."}),e.jsx("p",{className:"text-slate-600 mt-2",children:"All applications are reviewed personally by the LevelUp team. Be specific — the more we know, the better the match."})]}),e.jsxs("form",{onSubmit:c,className:"space-y-6 rounded-2xl border border-slate-200 bg-white p-6 md:p-8 shadow-[0_24px_60px_-30px_rgba(42,76,100,0.25)]",children:[e.jsxs("div",{className:"grid md:grid-cols-2 gap-5",children:[e.jsx(Cb,{label:"Full name *",children:e.jsx(Se,{value:i.full_name,onChange:d=>o("full_name",d.target.value),required:!0,maxLength:100})}),e.jsx(Cb,{label:"Email *",children:e.jsx(Se,{type:"email",value:i.email,onChange:d=>o("email",d.target.value),required:!0,maxLength:255})}),e.jsx(Cb,{label:"Phone",children:e.jsx(Se,{value:i.phone,onChange:d=>o("phone",d.target.value),maxLength:40})}),e.jsx(Cb,{label:"Current brokerage",children:e.jsx(Se,{value:i.brokerage,onChange:d=>o("brokerage",d.target.value),maxLength:150})}),e.jsx(Cb,{label:"Years in real estate",children:e.jsx(Se,{value:i.years_experience,onChange:d=>o("years_experience",d.target.value),placeholder:"e.g. 8",maxLength:40})}),e.jsx(Cb,{label:"Coaching specialties",children:e.jsx(Se,{value:i.specialties,onChange:d=>o("specialties",d.target.value),placeholder:"Lead gen, listings, luxury, teams…",maxLength:500})}),e.jsx(Cb,{label:"Website",children:e.jsx(Se,{value:i.website_url,onChange:d=>o("website_url",d.target.value),placeholder:"https://",maxLength:300})}),e.jsx(Cb,{label:"LinkedIn",children:e.jsx(Se,{value:i.linkedin_url,onChange:d=>o("linkedin_url",d.target.value),placeholder:"https://linkedin.com/in/",maxLength:300})})]}),e.jsx(Cb,{label:"Why do you want to coach with LevelUp? *",children:e.jsx(vr,{value:i.why_coach,onChange:d=>o("why_coach",d.target.value),required:!0,rows:5,maxLength:2e3,placeholder:"What drives you? Who do you want to help? What makes your approach different?"})}),e.jsx(Cb,{label:"Tell us about results you've created — for yourself or other agents.",children:e.jsx(vr,{value:i.results_story,onChange:d=>o("results_story",d.target.value),rows:5,maxLength:2e3,placeholder:"Production numbers, agent breakthroughs, testimonials — anything that shows the impact you've had."})}),e.jsxs("div",{className:"flex flex-col sm:flex-row items-stretch sm:items-center gap-3 pt-2",children:[e.jsx(H,{type:"submit",disabled:t,className:"bg-gradient-to-r from-[#406E71] to-[#2a4c64] hover:opacity-95 text-white font-semibold px-8 py-6 text-base flex-1 sm:flex-none",children:t?"Submitting…":"Submit application"}),e.jsx("p",{className:"text-xs text-slate-500",children:"We review every application within 5 business days."})]})]})]})]})}function Cb({label:s,children:t}){return e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{className:"text-sm font-semibold text-[#1c3447]",children:s}),t]})}const Qqt="/assets/testimonial-avatar-1-BsCQFauB.jpg",Jqt="/assets/testimonial-avatar-2-B6VPVc2t.jpg",eVt="/assets/testimonial-avatar-3-GuEFwYUE.jpg",tVt="/assets/testimonial-avatar-4-98iKMtkB.jpg",sVt="/assets/testimonial-avatar-5-ZsZfyxMX.jpg",rVt=[Qqt,Jqt,eVt,tVt,sVt],nVt=yj({name:Ho().trim().min(2,"Name must be at least 2 characters").max(100),email:Ho().trim().email("Please enter a valid email address").max(255),phone:Ho().trim().min(10,"Please enter a valid phone number").max(20).optional().or(ky("")),brokerage:Ho().trim().max(200).optional().or(ky(""))}),aVt=[{icon:cg,title:"Academy Training",description:"Access a library of on-demand video training covering lead generation, marketing, technology, and more."},{icon:pl,title:"300+ Templates",description:"Professional Canva templates for social media, flyers, postcards, and marketing materials."},{icon:Nn,title:"Live Events",description:"Weekly live training sessions, workshops, and Q&A events with industry experts."},{icon:qc,title:"Agent Community",description:"Connect with fellow agents, share wins, ask questions, and network in our private community."},{icon:kn,title:"Resource Kits",description:"Downloadable toolkits with scripts, checklists, guides, and everything you need to close more deals."},{icon:Di,title:"Social Swag",description:"Fresh social media content and designs updated regularly to help you stand out online."}],iVt=[{icon:Ar,title:"Contact Management",description:"Organize your sphere into relationship tiers—Top 25, Past Clients, Referral Partners, and more."},{icon:Lr,title:"Smart TouchPlans",description:"Automated action plans that tell you exactly who to contact and how, based on relationship type."},{icon:Yn,title:"One-Tap Actions",description:"Call, text, or email contacts directly with pre-written scripts tailored to each relationship."},{icon:gm,title:"Birthday Alerts",description:"Never miss an important date—get reminders for birthdays and home anniversaries."},{icon:Qa,title:"Pop-by Map",description:"See all your contacts on a map and plan efficient pop-by routes in your area."},{icon:Bo,title:"Momentum Tracking",description:"Track your touch streaks, weekly goals, and relationship health scores."},{icon:Bi,title:"Relationship Health",description:"Visual dashboard showing which contacts need attention based on last touch date."},{icon:ym,title:"Daily Action Cards",description:"Wake up to a prioritized list of exactly who to reach out to today."}],oVt=[{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."}],lVt=()=>{const s=Fr(),[t,r]=S.useState(!1),[n,a]=S.useState({name:"",email:"",phone:"",brokerage:""}),[i,l]=S.useState({}),o=async c=>{var h,m;c.preventDefault(),l({});const d=nVt.safeParse(n);if(!d.success){const p={};d.error.errors.forEach(x=>{x.path[0]&&(p[x.path[0]]=x.message)}),l(p);return}r(!0);try{const p=typeof window<"u"&&localStorage.getItem("levelup_referral_code")||void 0,{data:x,error:y}=await V.functions.invoke("create-trial-signup",{body:{name:n.name.trim(),email:n.email.trim().toLowerCase(),phone:((h=n.phone)==null?void 0:h.trim())||void 0,brokerage:((m=n.brokerage)==null?void 0:m.trim())||void 0,referral_code:p}});if(y){console.error("Trial signup error:",y),he.error(y.message||"Something went wrong. Please try again.");return}if(x!=null&&x.error){he.error(x.error);return}he.success("🎉 Welcome aboard! Check your email to claim your account."),typeof window<"u"&&window.oaiq&&window.oaiq("measure","trial_started",{type:"plan_enrollment"}),s("/trial/success")}catch(p){console.error("Trial signup error:",p),he.error("Something went wrong. Please try again.")}finally{r(!1)}};return e.jsxs(e.Fragment,{children:[e.jsxs(el,{children:[e.jsx("title",{children:"Start Your Free 7-Day Trial | LevelUp Dashboard"}),e.jsx("meta",{name:"description",content:"Take LevelUp for a free 7-day test drive. No credit card required. The all-in-one platform for real estate agents and brokerages."}),e.jsx("meta",{property:"og:title",content:"Start Your Free 7-Day Trial | LevelUp"}),e.jsx("meta",{property:"og:description",content:"Take LevelUp for a free 7-day test drive. No credit card required."}),e.jsx("meta",{property:"og:type",content:"website"})]}),e.jsxs("div",{className:"min-h-screen bg-background overflow-hidden",children:[e.jsx("nav",{className:"fixed top-0 left-0 right-0 z-50 bg-[#4a6b6d] shadow-md",children:e.jsxs("div",{className:"container mx-auto px-4 py-3 flex items-center justify-between",children:[e.jsx("div",{className:"flex items-center",children:e.jsx("img",{src:Xhe,alt:"LevelUp",className:"h-8 md:h-10"})}),e.jsxs("div",{className:"flex items-center gap-2 md:gap-4",children:[e.jsx(H,{variant:"ghost",className:"text-white/90 hover:text-white hover:bg-white/10 hidden sm:inline-flex",onClick:()=>{var c;return(c=document.getElementById("features"))==null?void 0:c.scrollIntoView({behavior:"smooth"})},children:"Features"}),e.jsx(H,{onClick:()=>s("/auth"),className:"bg-white text-[#4a6b6d] hover:bg-gray-100 font-medium shadow-md",children:"Sign In"})]})]})}),e.jsxs("section",{className:"relative pt-24 pb-20 bg-gradient-to-br from-[#1e3a4c] via-[#2a4f5f] to-[#3d6b6b] overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 opacity-10",children:e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),e.jsx("div",{className:"container mx-auto px-4 relative",children:e.jsxs("div",{className:"grid lg:grid-cols-2 gap-12 items-center",children:[e.jsxs("div",{className:"space-y-8 text-center lg:text-left",children:[e.jsx("div",{className:"flex justify-center lg:justify-start",children:e.jsx("img",{alt:"LevelUp Consulting Group",className:"h-24 md:h-32 drop-shadow-lg",src:"/lovable-uploads/3a0c7ef9-9e79-411f-a9af-6f2a99e8bd7b.webp"})}),e.jsxs("div",{className:"inline-flex items-center gap-2 px-4 py-2 rounded-full bg-white/10 text-white text-sm font-medium",children:[e.jsx(Lr,{className:"h-4 w-4 text-yellow-400"}),e.jsx("span",{children:"7-Day Free Trial • No Credit Card Required"})]}),e.jsxs("h1",{className:"text-3xl md:text-4xl lg:text-5xl font-bold text-white leading-tight font-sans",children:["Take LevelUp for a"," ",e.jsx("span",{className:"italic",children:"Free Test Drive"})]}),e.jsxs("p",{className:"text-lg md:text-xl text-white/80 max-w-xl mx-auto lg:mx-0 font-sans",children:["The tools you need to get it done.",e.jsx("br",{}),e.jsx("em",{children:"The platform you need to keep it going."})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 justify-center lg:justify-start",children:[e.jsxs("div",{className:"flex items-center gap-2 text-white/80",children:[e.jsx(ea,{className:"h-5 w-5 text-green-400"}),e.jsx("span",{children:"No credit card required"})]}),e.jsxs("div",{className:"flex items-center gap-2 text-white/80",children:[e.jsx(ea,{className:"h-5 w-5 text-green-400"}),e.jsx("span",{children:"Full access to all features"})]})]}),e.jsxs("div",{className:"flex items-center gap-4 justify-center lg:justify-start pt-4",children:[e.jsx("div",{className:"flex -space-x-3",children:rVt.map((c,d)=>e.jsx("img",{src:c,alt:`Agent ${d+1}`,className:"w-10 h-10 rounded-full border-2 border-white/20 object-cover"},d))}),e.jsxs("div",{children:[e.jsx("div",{className:"flex gap-0.5",children:[1,2,3,4,5].map(c=>e.jsx(ya,{className:"h-4 w-4 fill-yellow-400 text-yellow-400"},c))}),e.jsx("p",{className:"text-sm text-white/60",children:"Trusted by 3,000+ agents"})]})]})]}),e.jsx("div",{className:"lg:pl-8",children:e.jsx(ke,{className:"bg-white shadow-2xl border-0",children:e.jsxs(Oe,{className:"p-8",children:[e.jsxs("div",{className:"text-center mb-8",children:[e.jsx("div",{className:"inline-flex items-center justify-center w-16 h-16 rounded-full bg-[#4a6b6d] mb-4",children:e.jsx(v_,{className:"h-8 w-8 text-white"})}),e.jsx("h2",{className:"text-2xl font-bold text-foreground font-sans",children:"Start Your Free Trial"}),e.jsx("p",{className:"text-muted-foreground mt-2",children:"Get instant access • No credit card needed"})]}),e.jsxs("form",{onSubmit:o,className:"space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"name",children:"Full Name *"}),e.jsx(Se,{id:"name",type:"text",placeholder:"John Smith",value:n.name,onChange:c=>a({...n,name:c.target.value}),required:!0}),i.name&&e.jsx("p",{className:"text-sm text-destructive",children:i.name})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"email",children:"Email Address *"}),e.jsx(Se,{id:"email",type:"email",placeholder:"john@example.com",value:n.email,onChange:c=>a({...n,email:c.target.value}),required:!0}),i.email&&e.jsx("p",{className:"text-sm text-destructive",children:i.email})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"phone",children:"Phone Number"}),e.jsx(Se,{id:"phone",type:"tel",placeholder:"(555) 123-4567",value:n.phone,onChange:c=>a({...n,phone:c.target.value})}),i.phone&&e.jsx("p",{className:"text-sm text-destructive",children:i.phone})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"brokerage",children:"Brokerage Name"}),e.jsx(Se,{id:"brokerage",type:"text",placeholder:"Your brokerage or team name",value:n.brokerage,onChange:c=>a({...n,brokerage:c.target.value})}),i.brokerage&&e.jsx("p",{className:"text-sm text-destructive",children:i.brokerage})]}),e.jsx(H,{type:"submit",className:"w-full h-12 text-lg font-semibold bg-[#4a6b6d] hover:bg-[#3d5a5c]",disabled:t,children:t?e.jsxs(e.Fragment,{children:[e.jsx(is,{className:"mr-2 h-5 w-5 animate-spin"}),"Creating Your Account..."]}):e.jsxs(e.Fragment,{children:["Start My Free Trial",e.jsx(bi,{className:"ml-2 h-5 w-5"})]})}),e.jsxs("p",{className:"text-center text-sm text-muted-foreground",children:["By signing up, you agree to our"," ",e.jsx("a",{href:"/terms-of-service",className:"text-[#4a6b6d] hover:underline",children:"Terms"})," ","and"," ",e.jsx("a",{href:"/privacy-policy",className:"text-[#4a6b6d] hover:underline",children:"Privacy Policy"})]})]})]})})})]})})]}),e.jsx("section",{className:"py-20 bg-background",children:e.jsx("div",{className:"container mx-auto px-4",children:e.jsxs("div",{className:"max-w-4xl mx-auto text-center space-y-8",children:[e.jsx("h2",{className:"text-3xl md:text-5xl leading-tight font-sans font-semibold text-secondary",children:"We help brokerages and agents grow with training, tools, and built-in execution."}),e.jsxs("div",{className:"space-y-2 text-lg text-muted-foreground",children:[e.jsx("p",{children:"Agents get weekly coaching + plug-and-play marketing."}),e.jsx("p",{children:"Brokerages get higher adoption, consistency, and real engagement."})]}),e.jsx("p",{className:"text-2xl md:text-4xl text-[#4a6b6d] pt-4 font-sans font-bold",children:"LEVELUP EQUIPS BOTH TO THRIVE."})]})})}),e.jsx("section",{id:"features",className:"py-20 bg-muted/30",children:e.jsxs("div",{className:"container mx-auto px-4",children:[e.jsxs("div",{className:"text-center max-w-3xl mx-auto mb-16",children:[e.jsx("h2",{className:"text-3xl md:text-4xl mb-6 font-sans font-bold",children:"What's inside our members only portal?"}),e.jsx("p",{className:"text-lg text-muted-foreground",children:"Everything you need to grow your business, all in one place."})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8 max-w-6xl mx-auto",children:aVt.map((c,d)=>e.jsxs(ke,{className:"group relative overflow-hidden border hover:border-[#4a6b6d]/50 transition-all duration-300 hover:shadow-lg bg-background",children:[e.jsxs(Ot,{children:[e.jsx("div",{className:"w-14 h-14 rounded-2xl bg-[#4a6b6d]/10 flex items-center justify-center mb-4",children:e.jsx(c.icon,{className:"w-7 h-7 text-[#4a6b6d]"})}),e.jsx(zt,{className:"text-xl font-sans",children:c.title})]}),e.jsx(Oe,{children:e.jsx("p",{className:"text-muted-foreground leading-relaxed",children:c.description})})]},d))})]})}),e.jsxs("section",{className:"py-20 bg-gradient-to-br from-[#4a6b6d] to-[#3d5a5c] relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 opacity-10",children:e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),e.jsxs("div",{className:"container mx-auto px-4 relative",children:[e.jsxs("div",{className:"text-center max-w-3xl mx-auto mb-16",children:[e.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:[e.jsx(Lr,{className:"w-4 h-4"}),"Included with Your Trial"]}),e.jsxs("h2",{className:"text-3xl mb-6 text-white font-sans font-bold md:text-6xl",children:["Meet ",e.jsx("span",{className:"italic",children:"Agent OS"})]}),e.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."})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 max-w-6xl mx-auto",children:iVt.map((c,d)=>e.jsxs(ke,{className:"group relative overflow-hidden border-0 bg-white/10 backdrop-blur-sm hover:bg-white/20 transition-all duration-300",children:[e.jsxs(Ot,{className:"pb-3",children:[e.jsx("div",{className:"w-12 h-12 rounded-xl bg-white/20 flex items-center justify-center mb-3",children:e.jsx(c.icon,{className:"w-6 h-6 text-white"})}),e.jsx(zt,{className:"text-lg font-semibold text-white",children:c.title})]}),e.jsx(Oe,{children:e.jsx("p",{className:"text-white/70 text-sm leading-relaxed",children:c.description})})]},d))})]})]}),e.jsx("section",{className:"py-20 bg-background",children:e.jsxs("div",{className:"container mx-auto px-4",children:[e.jsxs("div",{className:"text-center mb-16",children:[e.jsx("h2",{className:"text-3xl md:text-4xl font-bold mb-4 font-sans",children:"Loved by Top Producers"}),e.jsx("p",{className:"text-lg text-muted-foreground",children:"See what agents are saying about LevelUp"})]}),e.jsx("div",{className:"grid md:grid-cols-3 gap-8 max-w-5xl mx-auto",children:oVt.map((c,d)=>e.jsx(ke,{className:"border hover:shadow-lg transition-shadow",children:e.jsxs(Oe,{className:"p-6",children:[e.jsx("div",{className:"flex gap-1 mb-4",children:[1,2,3,4,5].map(h=>e.jsx(ya,{className:"h-4 w-4 fill-yellow-400 text-yellow-400"},h))}),e.jsxs("p",{className:"text-muted-foreground mb-4 italic",children:['"',c.quote,'"']}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold",children:c.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:c.role})]})]})},d))})]})}),e.jsx("section",{className:"py-16 bg-muted/30",children:e.jsx("div",{className:"container mx-auto px-4",children:e.jsxs("div",{className:"flex flex-wrap justify-center gap-8 md:gap-16",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-12 h-12 rounded-full bg-[#4a6b6d]/10 flex items-center justify-center",children:e.jsx(Fh,{className:"h-6 w-6 text-[#4a6b6d]"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold",children:"Secure & Private"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Bank-level encryption"})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-12 h-12 rounded-full bg-[#4a6b6d]/10 flex items-center justify-center",children:e.jsx(ym,{className:"h-6 w-6 text-[#4a6b6d]"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold",children:"Fast Setup"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Start in 2 minutes"})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-12 h-12 rounded-full bg-[#4a6b6d]/10 flex items-center justify-center",children:e.jsx(Ar,{className:"h-6 w-6 text-[#4a6b6d]"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold",children:"Expert Support"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Real estate pros"})]})]})]})})}),e.jsx("section",{id:"free-trial",className:"py-20 bg-background",children:e.jsx("div",{className:"container mx-auto px-4",children:e.jsxs(ke,{className:"bg-gradient-to-br from-[#1e3a4c] via-[#2a4f5f] to-[#3d6b6b] border-0 shadow-2xl overflow-hidden relative",children:[e.jsx("div",{className:"absolute inset-0 opacity-10",children:e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),e.jsxs(Oe,{className:"p-12 text-center relative",children:[e.jsx("h2",{className:"text-3xl md:text-4xl font-bold text-white mb-4 font-sans",children:"Ready to Level Up Your Business?"}),e.jsx("p",{className:"text-xl text-white/80 mb-8 max-w-2xl mx-auto",children:"Join thousands of successful agents. Start your free 7-day trial today."}),e.jsxs(H,{onClick:()=>window.scrollTo({top:0,behavior:"smooth"}),size:"lg",className:"h-14 px-8 text-lg font-semibold bg-white text-[#1e3a4c] hover:bg-white/90 shadow-2xl transition-all hover:scale-105 rounded-full",children:["Start Your Free Trial Now",e.jsx(bi,{className:"ml-2 h-5 w-5"})]})]})]})})}),e.jsx("footer",{className:"bg-[#1e3a4c] py-12",children:e.jsx("div",{className:"container mx-auto px-4",children:e.jsxs("div",{className:"flex flex-col md:flex-row justify-between items-center gap-6",children:[e.jsx("img",{src:a5e,alt:"LevelUp",className:"h-8"}),e.jsxs("div",{className:"flex gap-6 text-sm text-white/60",children:[e.jsx("a",{href:"/privacy-policy",className:"hover:text-white transition-colors",children:"Privacy Policy"}),e.jsx("a",{href:"/terms-of-service",className:"hover:text-white transition-colors",children:"Terms of Service"})]}),e.jsx("p",{className:"text-sm text-white/40",children:"© 2025 LevelUp Consulting Group. All rights reserved."})]})})})]})]})},cVt=()=>{const s=Fr();return e.jsxs(e.Fragment,{children:[e.jsx(el,{children:e.jsx("title",{children:"Welcome to LevelUp! | Check Your Email"})}),e.jsxs("div",{className:"min-h-screen bg-background flex flex-col",children:[e.jsx("nav",{className:"fixed top-0 left-0 right-0 z-50 bg-[#4a6b6d] shadow-md",children:e.jsxs("div",{className:"container mx-auto px-4 py-3 flex items-center justify-between",children:[e.jsx("div",{className:"flex items-center",children:e.jsx("img",{src:Xhe,alt:"LevelUp",className:"h-8 md:h-10"})}),e.jsx(H,{onClick:()=>s("/auth"),className:"bg-white text-[#4a6b6d] hover:bg-gray-100 font-medium shadow-md",children:"Sign In"})]})}),e.jsxs("section",{className:"relative pt-24 pb-12 bg-gradient-to-br from-[#1e3a4c] via-[#2a4f5f] to-[#3d6b6b] overflow-hidden flex-1 flex items-center",children:[e.jsx("div",{className:"absolute inset-0 opacity-10",children:e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),e.jsx("div",{className:"container mx-auto px-4 relative",children:e.jsx("div",{className:"flex justify-center",children:e.jsx(ke,{className:"max-w-lg w-full bg-white shadow-2xl border-0",children:e.jsxs(Oe,{className:"p-8 md:p-12 text-center",children:[e.jsxs("div",{className:"relative inline-block mb-8",children:[e.jsx("div",{className:"w-24 h-24 rounded-full bg-gradient-to-br from-[#4a6b6d] to-[#3d5a5c] flex items-center justify-center",children:e.jsx(ea,{className:"h-12 w-12 text-white"})}),e.jsx("div",{className:"absolute -top-2 -right-2 w-10 h-10 rounded-full bg-yellow-500 flex items-center justify-center animate-bounce",children:e.jsx(gh,{className:"h-5 w-5 text-white"})})]}),e.jsx("h1",{className:"text-3xl md:text-4xl font-bold text-foreground mb-4 font-sans",children:"You're In! 🎉"}),e.jsx("p",{className:"text-xl text-muted-foreground mb-8",children:"Your 7-day LevelUp adventure starts now!"}),e.jsxs("div",{className:"bg-[#4a6b6d]/10 rounded-xl p-6 mb-8",children:[e.jsxs("div",{className:"flex items-center justify-center gap-3 mb-4",children:[e.jsx("div",{className:"w-12 h-12 rounded-full bg-[#4a6b6d]/20 flex items-center justify-center",children:e.jsx(er,{className:"h-6 w-6 text-[#4a6b6d]"})}),e.jsx("h2",{className:"text-lg font-semibold text-foreground",children:"Check Your Inbox"})]}),e.jsx("p",{className:"text-muted-foreground",children:"We just sent you a magic link to claim your account and set up your password. Click the link in your email to get started!"})]}),e.jsxs("div",{className:"text-left space-y-3 mb-8",children:[e.jsx("p",{className:"text-sm text-muted-foreground font-medium uppercase tracking-wide",children:"What happens next:"}),e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-6 h-6 rounded-full bg-[#4a6b6d] flex items-center justify-center flex-shrink-0 mt-0.5",children:e.jsx("span",{className:"text-xs font-bold text-white",children:"1"})}),e.jsx("p",{className:"text-foreground",children:"Check your email for the welcome message"})]}),e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-6 h-6 rounded-full bg-[#4a6b6d] flex items-center justify-center flex-shrink-0 mt-0.5",children:e.jsx("span",{className:"text-xs font-bold text-white",children:"2"})}),e.jsx("p",{className:"text-foreground",children:'Click "Claim Your Account" to set your password'})]}),e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-6 h-6 rounded-full bg-[#4a6b6d] flex items-center justify-center flex-shrink-0 mt-0.5",children:e.jsx("span",{className:"text-xs font-bold text-white",children:"3"})}),e.jsx("p",{className:"text-foreground",children:"Start exploring all the features!"})]})]}),e.jsxs("p",{className:"text-sm text-muted-foreground mb-6",children:["Didn't receive the email? Check your spam folder or"," ",e.jsx("button",{onClick:()=>s("/trial"),className:"text-[#4a6b6d] hover:underline font-medium",children:"try again"})]}),e.jsxs(H,{onClick:()=>s("/auth"),className:"bg-[#4a6b6d] hover:bg-[#3d5a5c]",children:["Go to Sign In",e.jsx(bi,{className:"ml-2 h-4 w-4"})]})]})})})})]}),e.jsx("footer",{className:"bg-[#1e3a4c] py-8",children:e.jsx("div",{className:"container mx-auto px-4",children:e.jsxs("div",{className:"flex flex-col md:flex-row justify-between items-center gap-4",children:[e.jsx("img",{src:a5e,alt:"LevelUp",className:"h-8"}),e.jsxs("p",{className:"text-sm text-white/40",children:["© ",new Date().getFullYear()," LevelUp Consulting Group. All rights reserved."]})]})})})]})]})},dVt=yj({viewerName:Ho().min(1,"Name is required").max(100,"Name must be less than 100 characters"),viewerEmail:Ho().email("Please enter a valid email").max(255,"Email must be less than 255 characters"),viewerPhone:Ho().max(20,"Phone must be less than 20 characters").optional(),message:Ho().min(1,"Message is required").max(1e3,"Message must be less than 1000 characters")});function uVt({shareToken:s,agentName:t,hasContact:r}){const[n,a]=S.useState(!1),[i,l]=S.useState(!1),[o,c]=S.useState(null),d=qge({resolver:Vge(dVt),defaultValues:{viewerName:"",viewerEmail:"",viewerPhone:"",message:""}}),h=async m=>{a(!0),c(null);try{const{data:p,error:x}=await V.functions.invoke("video-reply-notify",{body:{shareToken:s,viewerName:m.viewerName,viewerEmail:m.viewerEmail,viewerPhone:m.viewerPhone||void 0,message:m.message}});if(x)throw new Error(x.message);if(!(p!=null&&p.success))throw new Error((p==null?void 0:p.error)||"Failed to send reply");l(!0)}catch(p){console.error("Failed to submit reply:",p),c(p.message||"Something went wrong. Please try again.")}finally{a(!1)}};return i?e.jsx(ke,{className:"border-2 border-primary/20 bg-gradient-to-br from-primary/5 to-primary/10",children:e.jsxs(Oe,{className:"py-8 text-center",children:[e.jsx("div",{className:"inline-flex items-center justify-center w-16 h-16 rounded-full bg-primary/20 mb-4",children:e.jsx(ea,{className:"h-8 w-8 text-primary"})}),e.jsx("h3",{className:"text-xl font-semibold mb-2",children:"Message Sent!"}),e.jsxs("p",{className:"text-muted-foreground",children:[t?`${t} will`:"They'll"," get back to you soon."]})]})}):e.jsxs(ke,{children:[e.jsxs(Ot,{className:"pb-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(qc,{className:"h-5 w-5 text-primary"}),e.jsx(zt,{className:"text-lg",children:"Reply to this video"})]}),e.jsx(Br,{children:r?`Have a question or want to connect? Send ${t||"them"} a message.`:`Interested? Share your info and ${t||"your agent"} will be in touch.`})]}),e.jsx(Oe,{children:e.jsx(Hge,{...d,children:e.jsxs("form",{onSubmit:d.handleSubmit(h),className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsx(iu,{control:d.control,name:"viewerName",render:({field:m})=>e.jsxs(Ud,{children:[e.jsx(qd,{children:"Your Name *"}),e.jsx(Vd,{children:e.jsx(Se,{placeholder:"John Smith",...m})}),e.jsx(mg,{})]})}),e.jsx(iu,{control:d.control,name:"viewerEmail",render:({field:m})=>e.jsxs(Ud,{children:[e.jsx(qd,{children:"Email *"}),e.jsx(Vd,{children:e.jsx(Se,{type:"email",placeholder:"john@example.com",...m})}),e.jsx(mg,{})]})})]}),!r&&e.jsx(iu,{control:d.control,name:"viewerPhone",render:({field:m})=>e.jsxs(Ud,{children:[e.jsx(qd,{children:"Phone (optional)"}),e.jsx(Vd,{children:e.jsx(Se,{type:"tel",placeholder:"(555) 123-4567",...m})}),e.jsx(mg,{})]})}),e.jsx(iu,{control:d.control,name:"message",render:({field:m})=>e.jsxs(Ud,{children:[e.jsx(qd,{children:"Message *"}),e.jsx(Vd,{children:e.jsx(vr,{placeholder:r?"Thanks for the video! I had a question about...":"I'm interested in learning more about...",className:"min-h-[100px] resize-none",...m})}),e.jsx(mg,{})]})}),o&&e.jsx("p",{className:"text-sm text-destructive",children:o}),e.jsx(H,{type:"submit",className:"w-full gap-2",disabled:n,children:n?e.jsxs(e.Fragment,{children:[e.jsx(is,{className:"h-4 w-4 animate-spin"}),"Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(yn,{className:"h-4 w-4"}),"Send Message"]})})]})})})]})}const hVt=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsxs("div",{className:"absolute inset-0 opacity-[0.08]",children:[e.jsx("div",{className:"absolute top-0 left-0 right-0 h-[8%] bg-red-600"}),e.jsx("div",{className:"absolute top-[16%] left-0 right-0 h-[8%] bg-red-600"}),e.jsx("div",{className:"absolute top-[32%] left-0 right-0 h-[8%] bg-red-600"}),e.jsx("div",{className:"absolute top-[48%] left-0 right-0 h-[8%] bg-red-600"}),e.jsx("div",{className:"absolute top-[64%] left-0 right-0 h-[8%] bg-red-600"}),e.jsx("div",{className:"absolute top-[80%] left-0 right-0 h-[8%] bg-red-600"})]}),e.jsx("div",{className:"absolute top-0 left-0 w-[35%] h-[45%] bg-blue-900/10 rounded-br-3xl"}),e.jsx(ya,{className:"absolute top-[5%] left-[8%] w-6 h-6 text-blue-600/30 fill-blue-600/20"}),e.jsx(ya,{className:"absolute top-[15%] left-[20%] w-4 h-4 text-blue-600/25 fill-blue-600/15"}),e.jsx(ya,{className:"absolute top-[8%] left-[28%] w-5 h-5 text-blue-600/30 fill-blue-600/20"}),e.jsx(ya,{className:"absolute top-[25%] left-[12%] w-4 h-4 text-blue-600/20 fill-blue-600/10"}),e.jsx(ya,{className:"absolute top-[20%] right-[15%] w-5 h-5 text-red-500/25 fill-red-500/15 animate-pulse"}),e.jsx(U2,{className:"absolute bottom-[20%] right-[10%] w-12 h-12 text-blue-600/15 rotate-12"})]}),mVt=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-red-500/5 via-transparent to-blue-500/5"}),e.jsxs("div",{className:"absolute top-[10%] left-[15%] w-32 h-32",children:[e.jsx("div",{className:"absolute inset-0 rounded-full border-2 border-red-400/20 animate-ping",style:{animationDuration:"3s"}}),e.jsx(Lr,{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-8 h-8 text-red-400/40"})]}),e.jsxs("div",{className:"absolute top-[5%] right-[20%] w-24 h-24",children:[e.jsx("div",{className:"absolute inset-0 rounded-full border-2 border-blue-400/20 animate-ping",style:{animationDuration:"4s",animationDelay:"1s"}}),e.jsx(ya,{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-6 h-6 text-blue-400/40 fill-blue-400/20"})]}),e.jsxs("div",{className:"absolute top-[20%] left-[50%] w-20 h-20",children:[e.jsx("div",{className:"absolute inset-0 rounded-full border border-white/10 animate-ping",style:{animationDuration:"3.5s",animationDelay:"0.5s"}}),e.jsx(Lr,{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-5 h-5 text-amber-400/40"})]}),e.jsx(ya,{className:"absolute bottom-[25%] left-[10%] w-6 h-6 text-blue-500/25 fill-blue-500/15 animate-pulse"}),e.jsx(ya,{className:"absolute bottom-[15%] right-[15%] w-5 h-5 text-red-500/25 fill-red-500/15 animate-pulse",style:{animationDelay:"0.5s"}}),e.jsx(U2,{className:"absolute top-[8%] left-[5%] w-10 h-10 text-red-500/20 rotate-12"})]}),fVt=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-pink-200/20 via-rose-100/10 to-purple-200/15"}),e.jsx("div",{className:"absolute top-[5%] left-[5%] opacity-20",children:e.jsx(u1,{className:"w-20 h-20 text-pink-400 rotate-12"})}),e.jsx("div",{className:"absolute top-[2%] right-[8%] opacity-15",children:e.jsx(u1,{className:"w-16 h-16 text-rose-400 -rotate-12"})}),e.jsx("div",{className:"absolute bottom-[15%] left-[8%] opacity-15",children:e.jsx(u1,{className:"w-14 h-14 text-purple-400 rotate-45"})}),e.jsx("div",{className:"absolute bottom-[20%] right-[5%] opacity-20",children:e.jsx(u1,{className:"w-16 h-16 text-pink-300 -rotate-6"})}),e.jsx(Bi,{className:"absolute top-[15%] left-[30%] w-5 h-5 text-rose-300/40 fill-rose-300/20 animate-pulse"}),e.jsx(Bi,{className:"absolute top-[25%] right-[25%] w-4 h-4 text-pink-300/40 fill-pink-300/20 animate-pulse",style:{animationDelay:"0.3s"}}),e.jsx(Bi,{className:"absolute top-[10%] left-[60%] w-4 h-4 text-rose-400/30 fill-rose-400/15 animate-pulse",style:{animationDelay:"0.6s"}}),e.jsx("div",{className:"absolute top-[8%] left-[45%] w-8 h-8 rounded-full bg-pink-300/10 blur-sm"}),e.jsx("div",{className:"absolute bottom-[25%] right-[30%] w-6 h-6 rounded-full bg-rose-300/10 blur-sm"})]}),pVt=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-blue-900/5 via-slate-800/3 to-indigo-900/5"}),e.jsx("div",{className:"absolute top-[5%] right-[10%] opacity-15",children:e.jsxs("div",{className:"w-12 h-24 relative",children:[e.jsx("div",{className:"absolute top-0 left-1/2 -translate-x-1/2 w-10 h-3 bg-blue-600 rounded-full"}),e.jsx("div",{className:"absolute top-2 left-1/2 -translate-x-1/2 w-0 h-0 border-l-[20px] border-r-[20px] border-t-[60px] border-l-transparent border-r-transparent border-t-blue-500"})]})}),e.jsx(Bc,{className:"absolute top-[8%] left-[12%] w-12 h-12 text-blue-600/15"}),e.jsx(ya,{className:"absolute top-[15%] left-[22%] w-5 h-5 text-amber-500/25 fill-amber-500/15"}),e.jsx(Bc,{className:"absolute bottom-[20%] right-[8%] w-14 h-14 text-indigo-500/12"}),e.jsx("div",{className:"absolute top-[3%] left-[40%] opacity-12",children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx("div",{className:"w-10 h-5 bg-slate-700 rounded-full rounded-tr-none rotate-6"}),e.jsx("div",{className:"w-10 h-5 bg-slate-700 rounded-full rounded-tl-none -rotate-6"})]})}),e.jsx(ya,{className:"absolute bottom-[25%] left-[15%] w-6 h-6 text-blue-500/20 fill-blue-500/10 animate-pulse"}),e.jsx(ya,{className:"absolute top-[20%] right-[22%] w-5 h-5 text-indigo-400/20 fill-indigo-400/10 animate-pulse",style:{animationDelay:"0.5s"}})]}),gVt=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-pink-100/20 via-purple-100/15 to-sky-100/20"}),e.jsx("div",{className:"absolute top-[5%] left-[8%] w-12 h-16 rounded-full bg-gradient-to-b from-pink-300/25 to-pink-400/18 rotate-12"}),e.jsx("div",{className:"absolute top-[8%] right-[12%] w-10 h-14 rounded-full bg-gradient-to-b from-purple-300/25 to-purple-400/18 -rotate-6"}),e.jsx("div",{className:"absolute bottom-[18%] left-[15%] w-11 h-15 rounded-full bg-gradient-to-b from-sky-300/20 to-sky-400/12 rotate-6"}),e.jsx("div",{className:"absolute bottom-[22%] right-[10%] w-12 h-16 rounded-full bg-gradient-to-b from-yellow-300/20 to-yellow-400/12 -rotate-12"}),e.jsx("div",{className:"absolute top-[10%] left-[10%] w-6 h-1 bg-white/30 rounded-full rotate-12"}),e.jsx("div",{className:"absolute top-[12%] right-[15%] w-5 h-1 bg-white/25 rounded-full -rotate-6"}),e.jsx(u1,{className:"absolute top-[20%] left-[32%] w-7 h-7 text-purple-400/30"}),e.jsx(u1,{className:"absolute top-[12%] right-[28%] w-6 h-6 text-pink-400/30"}),e.jsx(DI,{className:"absolute top-[18%] left-[52%] w-5 h-5 text-sky-400/35"})]}),xVt=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-orange-900/12 via-purple-900/8 to-slate-900/12"}),e.jsx(vE,{className:"absolute top-[5%] left-[10%] w-16 h-16 text-orange-400/25"}),e.jsx(vE,{className:"absolute top-[10%] right-[12%] w-12 h-12 text-purple-400/20 animate-pulse"}),e.jsxs("div",{className:"absolute bottom-[18%] left-[8%]",children:[e.jsx("div",{className:"w-14 h-12 rounded-full bg-orange-500/20"}),e.jsx("div",{className:"absolute -top-2 left-1/2 -translate-x-1/2 w-2 h-4 bg-green-600/25 rounded-t-full"})]}),e.jsxs("div",{className:"absolute bottom-[22%] right-[12%]",children:[e.jsx("div",{className:"w-12 h-10 rounded-full bg-orange-400/15"}),e.jsx("div",{className:"absolute -top-1.5 left-1/2 -translate-x-1/2 w-1.5 h-3 bg-green-600/20 rounded-t-full"})]}),e.jsx("div",{className:"absolute top-[15%] left-[40%] opacity-20",children:e.jsx("svg",{viewBox:"0 0 24 12",className:"w-10 h-5 text-slate-800 fill-current",children:e.jsx("path",{d:"M12 6c-2-4-6-6-12-6 4 2 6 4 6 6s-2 4-6 6c6 0 10-2 12-6zm0 0c2-4 6-6 12-6-4 2-6 4-6 6s2 4 6 6c-6 0-10-2-12-6z"})})}),e.jsx(Lr,{className:"absolute top-[8%] left-[55%] w-6 h-6 text-purple-400/35 animate-pulse"}),e.jsx(Lr,{className:"absolute bottom-[28%] right-[25%] w-5 h-5 text-orange-400/30 animate-pulse",style:{animationDelay:"0.5s"}})]}),yVt=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-red-900/8 via-green-900/5 to-emerald-900/8"}),e.jsx(Zk,{className:"absolute bottom-[8%] left-[5%] w-20 h-20 text-green-600/18"}),e.jsx(Zk,{className:"absolute bottom-[12%] right-[8%] w-16 h-16 text-emerald-600/15"}),e.jsx(Zk,{className:"absolute bottom-[10%] left-[28%] w-12 h-12 text-green-500/12"}),e.jsx(h1,{className:"absolute top-[5%] left-[15%] w-10 h-10 text-sky-300/30 animate-pulse"}),e.jsx(h1,{className:"absolute top-[10%] right-[20%] w-8 h-8 text-blue-300/25 animate-pulse",style:{animationDelay:"0.3s"}}),e.jsx(h1,{className:"absolute top-[18%] left-[45%] w-6 h-6 text-sky-200/25 animate-pulse",style:{animationDelay:"0.6s"}}),e.jsx(h1,{className:"absolute top-[8%] left-[70%] w-8 h-8 text-blue-200/20 animate-pulse",style:{animationDelay:"0.9s"}}),e.jsx("div",{className:"absolute top-[12%] left-[10%] w-5 h-5 rounded-full bg-red-500/25"}),e.jsx("div",{className:"absolute top-[15%] right-[15%] w-4 h-4 rounded-full bg-amber-400/25"}),e.jsx("div",{className:"absolute top-[20%] left-[55%] w-4 h-4 rounded-full bg-green-500/20"}),e.jsx(ya,{className:"absolute top-[3%] left-[50%] -translate-x-1/2 w-10 h-10 text-amber-400/35 fill-amber-400/25"})]}),vVt=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-orange-900/10 via-amber-800/6 to-red-900/10"}),e.jsx("div",{className:"absolute top-[5%] left-[10%] w-10 h-8 rounded-full bg-orange-500/25 rotate-45"}),e.jsx("div",{className:"absolute top-[10%] right-[15%] w-8 h-6 rounded-full bg-red-500/20 -rotate-12"}),e.jsx("div",{className:"absolute top-[15%] left-[35%] w-7 h-5 rounded-full bg-amber-500/22 rotate-30"}),e.jsx("div",{className:"absolute bottom-[18%] left-[12%] w-10 h-7 rounded-full bg-yellow-600/18 -rotate-45"}),e.jsx("div",{className:"absolute bottom-[22%] right-[10%] w-9 h-6 rounded-full bg-orange-600/15 rotate-12"}),e.jsxs("div",{className:"absolute bottom-[12%] left-[50%] -translate-x-1/2",children:[e.jsx("div",{className:"w-16 h-14 rounded-full bg-orange-400/15"}),e.jsx("div",{className:"absolute -top-2 left-1/2 -translate-x-1/2 w-2 h-5 bg-green-600/18 rounded-t-full"})]}),e.jsx(Bi,{className:"absolute top-[8%] left-[55%] w-6 h-6 text-red-400/22 fill-red-400/12"}),e.jsx(Bi,{className:"absolute top-[20%] right-[25%] w-5 h-5 text-orange-400/22 fill-orange-400/12"})]}),bVt=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-yellow-900/8 via-amber-900/4 to-purple-900/8"}),e.jsx(ya,{className:"absolute top-[5%] left-[15%] w-12 h-12 text-yellow-400/35 fill-yellow-400/25 animate-pulse"}),e.jsx(ya,{className:"absolute top-[8%] right-[12%] w-10 h-10 text-amber-400/30 fill-amber-400/20 animate-pulse",style:{animationDelay:"0.3s"}}),e.jsx(ya,{className:"absolute top-[15%] left-[40%] w-7 h-7 text-yellow-300/25 fill-yellow-300/15 animate-pulse",style:{animationDelay:"0.6s"}}),e.jsx(ya,{className:"absolute top-[12%] right-[35%] w-8 h-8 text-amber-300/28 fill-amber-300/18 animate-pulse",style:{animationDelay:"0.9s"}}),e.jsx("div",{className:"absolute top-[20%] left-[25%] w-4 h-4 rounded-full bg-pink-400/30"}),e.jsx("div",{className:"absolute top-[18%] right-[30%] w-3 h-3 rounded-full bg-sky-400/30"}),e.jsx("div",{className:"absolute top-[25%] left-[60%] w-2.5 h-2.5 rounded-full bg-emerald-400/30"}),e.jsx("div",{className:"absolute top-[22%] right-[42%] w-3 h-3 rounded-full bg-purple-400/30"}),e.jsx(Lr,{className:"absolute top-[3%] left-[50%] w-10 h-10 text-yellow-400/40"}),e.jsx(gh,{className:"absolute bottom-[18%] left-[10%] w-12 h-12 text-purple-400/18 rotate-12"}),e.jsx(gh,{className:"absolute bottom-[20%] right-[12%] w-10 h-10 text-amber-400/15 -rotate-12"})]}),_Vt=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-blue-900/10 via-indigo-900/6 to-sky-900/10"}),e.jsxs("div",{className:"absolute bottom-[12%] left-1/2 -translate-x-1/2 flex items-end gap-3",children:[e.jsx("div",{className:"w-2 h-14 bg-blue-400/18 rounded-full"}),e.jsx("div",{className:"w-2 h-12 bg-blue-300/15 rounded-full"}),e.jsx("div",{className:"w-2 h-16 bg-blue-400/20 rounded-full"}),e.jsx("div",{className:"w-2.5 h-20 bg-blue-500/22 rounded-full"})," ",e.jsx("div",{className:"w-2 h-16 bg-blue-400/20 rounded-full"}),e.jsx("div",{className:"w-2 h-12 bg-blue-300/15 rounded-full"}),e.jsx("div",{className:"w-2 h-14 bg-blue-400/18 rounded-full"})]}),e.jsx("div",{className:"absolute bottom-[38%] left-[calc(50%-42px)] w-3 h-4 bg-yellow-400/30 rounded-full blur-sm"}),e.jsx("div",{className:"absolute bottom-[35%] left-[calc(50%-28px)] w-2.5 h-3 bg-yellow-300/25 rounded-full blur-sm"}),e.jsx("div",{className:"absolute bottom-[40%] left-[calc(50%-14px)] w-3 h-4 bg-amber-400/30 rounded-full blur-sm"}),e.jsx("div",{className:"absolute bottom-[45%] left-1/2 -translate-x-1/2 w-4 h-5 bg-yellow-400/35 rounded-full blur-sm"}),e.jsx(ya,{className:"absolute top-[8%] left-[50%] -translate-x-1/2 w-14 h-14 text-yellow-400/28 fill-yellow-400/18"}),e.jsx(Lr,{className:"absolute top-[5%] left-[20%] w-7 h-7 text-blue-400/35"}),e.jsx(Lr,{className:"absolute top-[10%] right-[18%] w-6 h-6 text-sky-400/30"})]}),wVt=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-green-900/12 via-emerald-900/6 to-teal-900/10"}),e.jsx(M2,{className:"absolute top-[5%] left-[10%] w-16 h-16 text-green-500/25"}),e.jsx(M2,{className:"absolute top-[8%] right-[12%] w-12 h-12 text-emerald-500/20"}),e.jsx(M2,{className:"absolute bottom-[18%] left-[12%] w-14 h-14 text-green-400/22"}),e.jsx(M2,{className:"absolute bottom-[22%] right-[10%] w-11 h-11 text-emerald-400/18"}),e.jsx("div",{className:"absolute top-[15%] left-[35%] w-6 h-6 rounded-full bg-yellow-500/30 border-2 border-yellow-600/25"}),e.jsx("div",{className:"absolute top-[20%] right-[28%] w-5 h-5 rounded-full bg-amber-500/25 border-2 border-amber-600/20"}),e.jsx("div",{className:"absolute bottom-[28%] left-[45%] w-5 h-5 rounded-full bg-yellow-400/25 border-2 border-yellow-500/20"}),e.jsx("div",{className:"absolute top-0 right-0 w-48 h-48 opacity-12 rounded-bl-full overflow-hidden",children:e.jsx("div",{className:"absolute inset-0 bg-gradient-to-bl from-red-400/60 via-yellow-400/60 to-green-400/60"})}),e.jsxs("div",{className:"absolute bottom-[10%] right-[5%] opacity-15",children:[e.jsx("div",{className:"w-12 h-8 bg-slate-700 rounded-b-full"}),e.jsx("div",{className:"absolute -top-1 left-1/2 -translate-x-1/2 w-10 h-3 bg-slate-600 rounded-full"}),e.jsxs("div",{className:"absolute top-0 left-1/2 -translate-x-1/2 flex gap-0.5",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-yellow-400"}),e.jsx("div",{className:"w-2 h-2 rounded-full bg-amber-400"}),e.jsx("div",{className:"w-2 h-2 rounded-full bg-yellow-400"})]})]})]}),jVt=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-blue-900/10 via-indigo-900/6 to-sky-900/10"}),e.jsx("div",{className:"absolute top-[8%] left-[12%] w-16 h-16 rounded-full border-4 border-blue-500/18"}),e.jsx("div",{className:"absolute top-[10%] right-[10%] w-14 h-14 rounded-full border-4 border-indigo-500/15"}),e.jsx("div",{className:"absolute bottom-[18%] left-[18%] w-12 h-12 rounded-full border-3 border-sky-500/12"}),e.jsx(ya,{className:"absolute top-[5%] left-[42%] w-10 h-10 text-amber-400/30 fill-amber-400/20"}),e.jsx(ya,{className:"absolute top-[15%] right-[25%] w-7 h-7 text-yellow-400/25 fill-yellow-400/15"}),e.jsx(Bc,{className:"absolute bottom-[20%] right-[12%] w-12 h-12 text-blue-500/18"}),e.jsx(Bc,{className:"absolute top-[18%] left-[28%] w-8 h-8 text-indigo-400/15"}),e.jsx(U2,{className:"absolute top-[8%] left-[60%] w-10 h-10 text-indigo-400/18"})]}),NVt=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-amber-900/6 via-rose-900/6 to-purple-900/6"}),e.jsx(gm,{className:"absolute bottom-[10%] left-[50%] -translate-x-1/2 w-20 h-20 text-amber-400/18"}),e.jsxs("div",{className:"absolute top-[5%] left-[15%]",children:[e.jsx("div",{className:"w-12 h-14 rounded-full bg-rose-400/25"}),e.jsx("div",{className:"w-0.5 h-10 bg-rose-400/18 mx-auto"})]}),e.jsxs("div",{className:"absolute top-[3%] left-[25%]",children:[e.jsx("div",{className:"w-10 h-12 rounded-full bg-sky-400/25"}),e.jsx("div",{className:"w-0.5 h-12 bg-sky-400/18 mx-auto"})]}),e.jsxs("div",{className:"absolute top-[8%] right-[18%]",children:[e.jsx("div",{className:"w-11 h-13 rounded-full bg-purple-400/25"}),e.jsx("div",{className:"w-0.5 h-9 bg-purple-400/18 mx-auto"})]}),e.jsxs("div",{className:"absolute top-[5%] right-[10%]",children:[e.jsx("div",{className:"w-10 h-12 rounded-full bg-amber-400/25"}),e.jsx("div",{className:"w-0.5 h-11 bg-amber-400/18 mx-auto"})]}),e.jsx("div",{className:"absolute top-[20%] left-[35%] w-3 h-3 bg-pink-400/35 rounded-full"}),e.jsx("div",{className:"absolute top-[18%] right-[40%] w-2.5 h-2.5 bg-emerald-400/35 rounded-full"}),e.jsx("div",{className:"absolute top-[25%] left-[55%] w-2 h-2 bg-amber-400/35 rounded-full"}),e.jsx("div",{className:"absolute top-[22%] right-[30%] w-2.5 h-2.5 bg-sky-400/35 rounded-full"}),e.jsx(gh,{className:"absolute top-[8%] left-[45%] w-10 h-10 text-purple-400/22 rotate-12"}),e.jsx(Di,{className:"absolute bottom-[18%] right-[15%] w-12 h-12 text-rose-400/18"})]}),kVt=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-rose-900/12 via-pink-900/8 to-red-900/12"}),e.jsx(Bi,{className:"absolute top-[5%] left-[10%] w-16 h-16 text-rose-400/28 fill-rose-400/18"}),e.jsx(Bi,{className:"absolute top-[8%] right-[12%] w-14 h-14 text-pink-400/25 fill-pink-400/15"}),e.jsx(Bi,{className:"absolute bottom-[15%] left-[12%] w-12 h-12 text-red-400/22 fill-red-400/12"}),e.jsx(Bi,{className:"absolute bottom-[18%] right-[10%] w-13 h-13 text-rose-300/25 fill-rose-300/15"}),e.jsx(Bi,{className:"absolute top-[15%] left-[30%] w-6 h-6 text-pink-300/35 fill-pink-300/20 animate-pulse"}),e.jsx(Bi,{className:"absolute top-[20%] right-[35%] w-5 h-5 text-rose-300/35 fill-rose-300/20 animate-pulse",style:{animationDelay:"0.3s"}}),e.jsx(Bi,{className:"absolute top-[12%] left-[55%] w-5 h-5 text-red-300/30 fill-red-300/15 animate-pulse",style:{animationDelay:"0.6s"}}),e.jsx(Bi,{className:"absolute top-[25%] right-[25%] w-4 h-4 text-pink-400/30 fill-pink-400/15 animate-pulse",style:{animationDelay:"0.9s"}}),e.jsx("div",{className:"absolute top-[18%] left-[45%] w-8 h-8 rounded-full bg-rose-300/18 blur-sm"}),e.jsx("div",{className:"absolute bottom-[25%] right-[40%] w-6 h-6 rounded-full bg-pink-300/15 blur-sm"})]}),SVt=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-amber-900/10 via-yellow-900/6 to-orange-900/10"}),e.jsxs("div",{className:"absolute top-[5%] right-[12%]",children:[e.jsx("div",{className:"w-24 h-24 rounded-full bg-yellow-400/25 blur-sm"}),e.jsx(W2,{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-14 h-14 text-amber-400/45"})]}),e.jsx("div",{className:"absolute bottom-[12%] left-[20%] w-20 h-10 bg-slate-800/12 rounded-full blur-md"}),e.jsx(W2,{className:"absolute top-[15%] left-[18%] w-10 h-10 text-yellow-400/30"}),e.jsx(Lr,{className:"absolute top-[10%] left-[42%] w-7 h-7 text-amber-400/35"}),e.jsx(W2,{className:"absolute bottom-[22%] right-[25%] w-8 h-8 text-orange-400/25"}),e.jsx("div",{className:"absolute bottom-0 left-0 right-0 h-[15%] bg-gradient-to-t from-amber-900/10 to-transparent"})]}),CVt=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-teal-900/10 via-cyan-900/6 to-emerald-900/10"}),e.jsx(Fn,{className:"absolute top-[8%] left-[10%] w-14 h-14 text-teal-500/22"}),e.jsx(Fn,{className:"absolute bottom-[15%] right-[8%] w-16 h-16 text-emerald-500/18"}),e.jsx(dx,{className:"absolute top-[12%] right-[18%] w-10 h-10 text-amber-400/25"}),e.jsx(dx,{className:"absolute bottom-[22%] left-[22%] w-8 h-8 text-yellow-400/22"}),e.jsx(Bi,{className:"absolute top-[18%] left-[40%] w-6 h-6 text-rose-400/22 fill-rose-400/12"}),e.jsx(Bi,{className:"absolute top-[22%] right-[35%] w-5 h-5 text-teal-400/20 fill-teal-400/10"}),e.jsx(Lr,{className:"absolute top-[5%] left-[55%] w-8 h-8 text-teal-400/30"}),e.jsx(gh,{className:"absolute bottom-[20%] left-[48%] w-10 h-10 text-cyan-400/18 rotate-12"})]}),TVt=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-emerald-900/10 via-teal-900/6 to-cyan-900/10"}),e.jsx(gh,{className:"absolute top-[5%] left-[12%] w-14 h-14 text-emerald-400/25 rotate-12"}),e.jsx(gh,{className:"absolute top-[8%] right-[10%] w-12 h-12 text-teal-400/22 -rotate-12"}),e.jsx(dx,{className:"absolute bottom-[18%] left-[18%] w-12 h-12 text-amber-400/25"}),e.jsx(Fn,{className:"absolute bottom-[15%] right-[12%] w-14 h-14 text-teal-500/18"}),e.jsx(Lr,{className:"absolute top-[15%] left-[42%] w-10 h-10 text-emerald-400/35"}),e.jsx(Lr,{className:"absolute top-[20%] right-[32%] w-7 h-7 text-cyan-400/30"}),e.jsx("div",{className:"absolute top-[25%] left-[55%] w-3 h-3 bg-amber-400/30 rounded-full"}),e.jsx("div",{className:"absolute top-[22%] right-[42%] w-2.5 h-2.5 bg-teal-400/30 rounded-full"}),e.jsx("div",{className:"absolute top-[28%] left-[35%] w-2 h-2 bg-emerald-400/30 rounded-full"})]}),EVt=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-amber-900/10 via-yellow-900/6 to-orange-900/10"}),e.jsx(dx,{className:"absolute bottom-[12%] left-[50%] -translate-x-1/2 w-24 h-24 text-amber-400/25 rotate-45"}),e.jsx(dx,{className:"absolute top-[10%] left-[12%] w-10 h-10 text-yellow-400/30"}),e.jsx(dx,{className:"absolute top-[12%] right-[15%] w-9 h-9 text-amber-300/25"}),e.jsx(Fn,{className:"absolute top-[8%] left-[42%] w-12 h-12 text-teal-500/18"}),e.jsx(gh,{className:"absolute bottom-[22%] right-[18%] w-12 h-12 text-orange-400/18 rotate-12"}),e.jsx(Lr,{className:"absolute top-[5%] right-[35%] w-8 h-8 text-yellow-400/35"}),e.jsx(ya,{className:"absolute top-[18%] left-[28%] w-6 h-6 text-amber-400/25 fill-amber-400/15"})]}),AVt=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-teal-900/10 via-emerald-900/6 to-green-900/10"}),e.jsx(Fn,{className:"absolute bottom-[10%] left-[50%] -translate-x-1/2 w-20 h-20 text-teal-500/22"}),e.jsx("div",{className:"absolute bottom-[18%] left-[12%] w-12 h-10 bg-amber-400/18 rounded-sm"}),e.jsx("div",{className:"absolute bottom-[20%] left-[20%] w-10 h-8 bg-orange-400/15 rounded-sm"}),e.jsx("div",{className:"absolute bottom-[16%] right-[15%] w-11 h-9 bg-amber-300/18 rounded-sm"}),e.jsx(dx,{className:"absolute top-[10%] right-[12%] w-10 h-10 text-amber-400/28"}),e.jsx(Bi,{className:"absolute top-[8%] left-[18%] w-8 h-8 text-rose-400/25 fill-rose-400/15"}),e.jsx(Lr,{className:"absolute top-[12%] left-[45%] w-8 h-8 text-teal-400/30"}),e.jsx(m_,{className:"absolute top-[15%] right-[28%] w-10 h-10 text-emerald-400/20"})]}),i9e=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx("div",{className:"absolute top-4 left-[10%] w-3 h-3 bg-amber-400/60 rounded-full animate-pulse"}),e.jsx("div",{className:"absolute top-12 right-[15%] w-2 h-2 bg-rose-400/60 rounded-full animate-pulse delay-100"}),e.jsx("div",{className:"absolute top-8 left-[30%] w-2.5 h-2.5 bg-sky-400/60 rounded-full animate-pulse delay-200"}),e.jsx("div",{className:"absolute top-16 right-[25%] w-2 h-2 bg-emerald-400/60 rounded-full animate-pulse delay-300"})]}),MVt=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(Bi,{className:"absolute top-6 left-[12%] w-4 h-4 text-rose-300/50 fill-rose-300/30 animate-pulse"}),e.jsx(Bi,{className:"absolute top-10 right-[18%] w-3 h-3 text-pink-300/50 fill-pink-300/30 animate-pulse delay-150"}),e.jsx(Bi,{className:"absolute top-4 left-[40%] w-2.5 h-2.5 text-rose-400/40 fill-rose-400/20 animate-pulse delay-300"}),e.jsx(Bi,{className:"absolute top-14 right-[35%] w-3.5 h-3.5 text-pink-300/40 fill-pink-300/20 animate-pulse delay-200"})]}),IVt=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(m_,{className:"absolute top-5 left-[10%] w-4 h-4 text-blue-400/50 animate-pulse"}),e.jsx(Lr,{className:"absolute top-10 right-[15%] w-3 h-3 text-amber-400/50 animate-pulse delay-100"}),e.jsx(Fn,{className:"absolute top-8 left-[38%] w-3 h-3 text-teal-300/40 animate-pulse delay-200"})]}),PVt=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(gE,{className:"absolute top-5 left-[12%] w-4 h-4 text-amber-500/50 animate-pulse"}),e.jsx(VI,{className:"absolute top-10 right-[15%] w-3 h-3 text-rose-400/50 animate-pulse delay-100"}),e.jsx(gE,{className:"absolute top-8 left-[40%] w-3 h-3 text-amber-400/40 animate-pulse delay-200"})]}),IR=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(Lr,{className:"absolute top-5 left-[10%] w-4 h-4 text-emerald-400/50 animate-pulse"}),e.jsx(gh,{className:"absolute top-10 right-[12%] w-5 h-5 text-amber-400/50 animate-pulse delay-150"}),e.jsx(Lr,{className:"absolute top-8 left-[45%] w-3 h-3 text-sky-400/40 animate-pulse delay-300"})]}),o9e=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(Fn,{className:"absolute top-6 left-[12%] w-4 h-4 text-teal-400/40 animate-pulse"}),e.jsx(Lr,{className:"absolute top-10 right-[15%] w-3 h-3 text-emerald-400/50 animate-pulse delay-100"}),e.jsx(Fn,{className:"absolute top-4 right-[40%] w-3 h-3 text-cyan-400/30 animate-pulse delay-200"})]}),UNe=[{id:"default",name:"Classic",description:"Clean, professional look for any occasion",icon:e.jsx(Lr,{className:"h-5 w-5"}),category:"general",headerText:()=>"Video Message",subText:"A personal video just for you",gradientClasses:"from-background to-muted/30",accentColor:"primary"},{id:"thank_you",name:"Thank You",description:"Express your gratitude",icon:e.jsx(Bi,{className:"h-5 w-5"}),category:"general",headerText:s=>s?`Thank You, ${s}!`:"Thank You!",subText:"Your support means the world to me",gradientClasses:"from-rose-50/70 via-pink-50/50 to-red-50/40 dark:from-rose-950/30 dark:via-pink-950/20 dark:to-red-950/20",accentColor:"rose",decorativeElement:e.jsx(MVt,{})},{id:"thinking_of_you",name:"Thinking of You",description:"Let them know they're on your mind",icon:e.jsx(eF,{className:"h-5 w-5"}),category:"general",headerText:s=>s?`Thinking of You, ${s}`:"Thinking of You",subText:"Just wanted to reach out and say hello",gradientClasses:"from-violet-50/70 via-purple-50/50 to-indigo-50/40 dark:from-violet-950/30 dark:via-purple-950/20 dark:to-indigo-950/20",accentColor:"violet",decorativeElement:e.jsx(IR,{})},{id:"check_in",name:"Check-in",description:"Touch base with your contacts",icon:e.jsx(gE,{className:"h-5 w-5"}),category:"general",headerText:s=>s?`Hey ${s}!`:"Hey There!",subText:"Just checking in to see how you're doing",gradientClasses:"from-amber-50/70 via-orange-50/50 to-yellow-50/40 dark:from-amber-950/30 dark:via-orange-950/20 dark:to-yellow-950/20",accentColor:"amber",decorativeElement:e.jsx(PVt,{})},{id:"market_update",name:"Market Update",description:"Share real estate market insights",icon:e.jsx(Bo,{className:"h-5 w-5"}),category:"general",headerText:s=>s?`Market Update for ${s}`:"Market Update",subText:"The latest insights from your local market",gradientClasses:"from-blue-50/70 via-indigo-50/50 to-sky-50/40 dark:from-blue-950/30 dark:via-indigo-950/20 dark:to-sky-950/20",accentColor:"blue"},{id:"referral_thank_you",name:"Referral Thank You",description:"Thank someone for a referral",icon:e.jsx(Ar,{className:"h-5 w-5"}),category:"general",headerText:s=>s?`Thank You for the Referral, ${s}!`:"Thank You for the Referral!",subText:"Your trust in me means everything",gradientClasses:"from-emerald-50/70 via-green-50/50 to-teal-50/40 dark:from-emerald-950/30 dark:via-green-950/20 dark:to-teal-950/20",accentColor:"emerald",decorativeElement:e.jsx(IR,{})},{id:"congratulations",name:"Congratulations",description:"Celebrate their achievements",icon:e.jsx(Bc,{className:"h-5 w-5"}),category:"general",headerText:s=>s?`Congratulations, ${s}!`:"Congratulations!",subText:"So proud of your accomplishment",gradientClasses:"from-amber-50/70 via-yellow-50/50 to-orange-50/40 dark:from-amber-950/30 dark:via-yellow-950/20 dark:to-orange-950/20",accentColor:"amber",decorativeElement:e.jsx(i9e,{})},{id:"welcome_neighborhood",name:"Welcome to the Neighborhood",description:"Greet new neighbors",icon:e.jsx(Qa,{className:"h-5 w-5"}),category:"general",headerText:s=>s?`Welcome to the Neighborhood, ${s}!`:"Welcome to the Neighborhood!",subText:"So excited to have you as our new neighbor",gradientClasses:"from-teal-50/70 via-cyan-50/50 to-sky-50/40 dark:from-teal-950/30 dark:via-cyan-950/20 dark:to-sky-950/20",accentColor:"teal",decorativeElement:e.jsx(o9e,{})},{id:"just_because",name:"Just Because",description:"No reason needed to connect",icon:e.jsx(VI,{className:"h-5 w-5"}),category:"general",headerText:s=>s?`Hey ${s}!`:"Hey There!",subText:"No reason needed – just wanted to connect",gradientClasses:"from-sky-50/70 via-blue-50/50 to-indigo-50/40 dark:from-sky-950/30 dark:via-blue-950/20 dark:to-indigo-950/20",accentColor:"sky",decorativeElement:e.jsx(IR,{})},{id:"birthday",name:"Birthday",description:"Celebrate their special day",icon:e.jsx(gm,{className:"h-5 w-5"}),category:"holidays",headerText:s=>s?`Happy Birthday, ${s}!`:"Happy Birthday!",subText:"Wishing you an amazing year ahead",gradientClasses:"from-amber-50/80 via-rose-50/60 to-purple-50/40 dark:from-amber-950/30 dark:via-rose-950/20 dark:to-purple-950/20",accentColor:"amber",decorativeElement:e.jsx(NVt,{})},{id:"valentines_day",name:"Valentine's Day",description:"Show appreciation on this special day",icon:e.jsx(Bi,{className:"h-5 w-5"}),category:"holidays",headerText:s=>s?`Happy Valentine's Day, ${s}!`:"Happy Valentine's Day!",subText:"A heartfelt message from your real estate professional",gradientClasses:"from-rose-50/80 via-pink-50/60 to-red-50/40 dark:from-rose-950/30 dark:via-pink-950/20 dark:to-red-950/20",accentColor:"rose",decorativeElement:e.jsx(kVt,{})},{id:"groundhog_day",name:"Groundhog Day",description:"A fun seasonal greeting",icon:e.jsx(W2,{className:"h-5 w-5"}),category:"holidays",headerText:s=>s?`Happy Groundhog Day, ${s}!`:"Happy Groundhog Day!",subText:"Wishing you an early spring!",gradientClasses:"from-amber-50/70 via-yellow-50/50 to-orange-50/40 dark:from-amber-950/30 dark:via-yellow-950/20 dark:to-orange-950/20",accentColor:"amber",decorativeElement:e.jsx(SVt,{})},{id:"new_years",name:"New Year's Day",description:"Ring in the new year",icon:e.jsx(ya,{className:"h-5 w-5"}),category:"holidays",headerText:s=>s?`Happy New Year, ${s}!`:"Happy New Year!",subText:"Wishing you a year full of success and happiness",gradientClasses:"from-yellow-50/70 via-amber-50/50 to-orange-50/40 dark:from-yellow-950/30 dark:via-amber-950/20 dark:to-orange-950/20",accentColor:"yellow",decorativeElement:e.jsx(bVt,{})},{id:"easter",name:"Easter",description:"Celebrate the spring season",icon:e.jsx(DI,{className:"h-5 w-5"}),category:"holidays",headerText:s=>s?`Happy Easter, ${s}!`:"Happy Easter!",subText:"Wishing you a joyful celebration",gradientClasses:"from-pink-50/70 via-purple-50/50 to-sky-50/40 dark:from-pink-950/30 dark:via-purple-950/20 dark:to-sky-950/20",accentColor:"pink",decorativeElement:e.jsx(gVt,{})},{id:"mothers_day",name:"Mother's Day",description:"Celebrate the amazing moms",icon:e.jsx(u1,{className:"h-5 w-5"}),category:"holidays",headerText:s=>s?`Happy Mother's Day, ${s}!`:"Happy Mother's Day!",subText:"Celebrating the wonderful mothers in our lives",gradientClasses:"from-pink-50/70 via-rose-50/50 to-purple-50/40 dark:from-pink-950/30 dark:via-rose-950/20 dark:to-purple-950/20",accentColor:"pink",decorativeElement:e.jsx(fVt,{})},{id:"fathers_day",name:"Father's Day",description:"Celebrate the amazing dads",icon:e.jsx(Bc,{className:"h-5 w-5"}),category:"holidays",headerText:s=>s?`Happy Father's Day, ${s}!`:"Happy Father's Day!",subText:"Celebrating the wonderful fathers in our lives",gradientClasses:"from-blue-50/70 via-sky-50/50 to-indigo-50/40 dark:from-blue-950/30 dark:via-sky-950/20 dark:to-indigo-950/20",accentColor:"blue",decorativeElement:e.jsx(pVt,{})},{id:"memorial_day",name:"Memorial Day",description:"Honor those who served",icon:e.jsx(U2,{className:"h-5 w-5"}),category:"holidays",headerText:s=>s?`Happy Memorial Day, ${s}`:"Happy Memorial Day",subText:"Honoring those who served our country",gradientClasses:"from-red-50/60 via-white to-blue-50/60 dark:from-red-950/30 dark:via-slate-950/20 dark:to-blue-950/30",accentColor:"blue",decorativeElement:e.jsx(hVt,{})},{id:"independence_day",name:"4th of July",description:"Celebrate Independence Day",icon:e.jsx(od,{className:"h-5 w-5"}),category:"holidays",headerText:s=>s?`Happy 4th of July, ${s}!`:"Happy 4th of July!",subText:"Celebrating freedom and independence",gradientClasses:"from-red-50/70 via-white to-blue-50/70 dark:from-red-950/30 dark:via-slate-950/10 dark:to-blue-950/30",accentColor:"red",decorativeElement:e.jsx(mVt,{})},{id:"labor_day",name:"Labor Day",description:"Celebrate the workers",icon:e.jsx(Bc,{className:"h-5 w-5"}),category:"holidays",headerText:s=>s?`Happy Labor Day, ${s}!`:"Happy Labor Day!",subText:"Celebrating the hard work that builds our communities",gradientClasses:"from-blue-50/70 via-indigo-50/50 to-sky-50/40 dark:from-blue-950/30 dark:via-indigo-950/20 dark:to-sky-950/20",accentColor:"blue",decorativeElement:e.jsx(jVt,{})},{id:"halloween",name:"Halloween",description:"Spooky seasonal greetings",icon:e.jsx(vE,{className:"h-5 w-5"}),category:"holidays",headerText:s=>s?`Happy Halloween, ${s}!`:"Happy Halloween!",subText:"Have a spooktacular day!",gradientClasses:"from-orange-50/70 via-amber-50/50 to-purple-50/40 dark:from-orange-950/30 dark:via-amber-950/20 dark:to-purple-950/30",accentColor:"orange",decorativeElement:e.jsx(xVt,{})},{id:"thanksgiving",name:"Thanksgiving",description:"Express gratitude this season",icon:e.jsx(Bi,{className:"h-5 w-5"}),category:"holidays",headerText:s=>s?`Happy Thanksgiving, ${s}!`:"Happy Thanksgiving!",subText:"Grateful for you and your friendship",gradientClasses:"from-orange-50/70 via-amber-50/50 to-red-50/40 dark:from-orange-950/30 dark:via-amber-950/20 dark:to-red-950/20",accentColor:"orange",decorativeElement:e.jsx(vVt,{})},{id:"christmas",name:"Christmas",description:"Spread holiday cheer",icon:e.jsx(Zk,{className:"h-5 w-5"}),category:"holidays",headerText:s=>s?`Merry Christmas, ${s}!`:"Merry Christmas!",subText:"Wishing you joy and peace this holiday season",gradientClasses:"from-red-50/70 via-green-50/40 to-emerald-50/40 dark:from-red-950/30 dark:via-green-950/20 dark:to-emerald-950/20",accentColor:"red",decorativeElement:e.jsx(yVt,{})},{id:"hanukkah",name:"Hanukkah",description:"Celebrate the Festival of Lights",icon:e.jsx(Lr,{className:"h-5 w-5"}),category:"holidays",headerText:s=>s?`Happy Hanukkah, ${s}!`:"Happy Hanukkah!",subText:"Wishing you eight nights of light and joy",gradientClasses:"from-blue-50/70 via-indigo-50/50 to-sky-50/40 dark:from-blue-950/30 dark:via-indigo-950/20 dark:to-sky-950/20",accentColor:"blue",decorativeElement:e.jsx(_Vt,{})},{id:"st_patricks_day",name:"St. Patrick's Day",description:"Celebrate the luck of the Irish",icon:e.jsx(M2,{className:"h-5 w-5"}),category:"holidays",headerText:s=>s?`Happy St. Patrick's Day, ${s}!`:"Happy St. Patrick's Day!",subText:"Wishing you the luck of the Irish!",gradientClasses:"from-green-50/70 via-emerald-50/50 to-teal-50/40 dark:from-green-950/30 dark:via-emerald-950/20 dark:to-teal-950/20",accentColor:"green",decorativeElement:e.jsx(wVt,{})},{id:"home_anniversary",name:"Home Anniversary",description:"Celebrate their home ownership milestone",icon:e.jsx(Fn,{className:"h-5 w-5"}),category:"transactional",headerText:s=>s?`Happy Home Anniversary, ${s}!`:"Happy Home Anniversary!",subText:"Celebrating another year in your beautiful home",gradientClasses:"from-teal-50/70 via-cyan-50/50 to-emerald-50/40 dark:from-teal-950/30 dark:via-cyan-950/20 dark:to-emerald-950/20",accentColor:"teal",decorativeElement:e.jsx(CVt,{})},{id:"under_contract",name:"Under Contract",description:"Celebrate this exciting milestone",icon:e.jsx(gh,{className:"h-5 w-5"}),category:"transactional",headerText:s=>s?`Congratulations, ${s}!`:"Congratulations!",subText:"You're under contract – exciting times ahead!",gradientClasses:"from-emerald-50/70 via-teal-50/50 to-cyan-50/40 dark:from-emerald-950/30 dark:via-teal-950/20 dark:to-cyan-950/20",accentColor:"emerald",decorativeElement:e.jsx(TVt,{})},{id:"just_listed",name:"Just Listed",description:"Announce a new listing",icon:e.jsx(Nn,{className:"h-5 w-5"}),category:"transactional",headerText:s=>s?`Exciting News, ${s}!`:"Just Listed!",subText:"A new property is now on the market",gradientClasses:"from-blue-50/70 via-indigo-50/50 to-violet-50/40 dark:from-blue-950/30 dark:via-indigo-950/20 dark:to-violet-950/20",accentColor:"blue",decorativeElement:e.jsx(o9e,{})},{id:"just_sold",name:"Just Sold",description:"Celebrate a successful sale",icon:e.jsx(oc,{className:"h-5 w-5"}),category:"transactional",headerText:s=>s?`Congratulations, ${s}!`:"Just Sold!",subText:"Another successful transaction completed",gradientClasses:"from-emerald-50/70 via-green-50/50 to-teal-50/40 dark:from-emerald-950/30 dark:via-green-950/20 dark:to-teal-950/20",accentColor:"emerald",decorativeElement:e.jsx(IR,{})},{id:"price_reduction",name:"Price Reduction",description:"Notify about a price change",icon:e.jsx(K2,{className:"h-5 w-5"}),category:"transactional",headerText:s=>s?`Great News, ${s}!`:"Price Reduced!",subText:"This property just became more affordable",gradientClasses:"from-orange-50/70 via-amber-50/50 to-yellow-50/40 dark:from-orange-950/30 dark:via-amber-950/20 dark:to-yellow-950/20",accentColor:"orange"},{id:"open_house",name:"Open House",description:"Invite to an open house event",icon:e.jsx(m_,{className:"h-5 w-5"}),category:"transactional",headerText:s=>s?`You're Invited, ${s}!`:"You're Invited!",subText:"Join us for an exclusive open house",gradientClasses:"from-sky-50/70 via-blue-50/50 to-indigo-50/40 dark:from-sky-950/30 dark:via-blue-950/20 dark:to-indigo-950/20",accentColor:"sky",decorativeElement:e.jsx(IVt,{})},{id:"closing_day",name:"Closing Day",description:"Celebrate their closing day",icon:e.jsx(dx,{className:"h-5 w-5"}),category:"transactional",headerText:s=>s?`Congratulations, ${s}!`:"Congratulations!",subText:"It's official – the keys are yours!",gradientClasses:"from-amber-50/70 via-yellow-50/50 to-orange-50/40 dark:from-amber-950/30 dark:via-yellow-950/20 dark:to-orange-950/20",accentColor:"amber",decorativeElement:e.jsx(EVt,{})},{id:"move_in_day",name:"Move-in Day",description:"Welcome them to their new home",icon:e.jsx(Fn,{className:"h-5 w-5"}),category:"transactional",headerText:s=>s?`Welcome Home, ${s}!`:"Welcome Home!",subText:"Wishing you all the best in your new home",gradientClasses:"from-teal-50/70 via-emerald-50/50 to-green-50/40 dark:from-teal-950/30 dark:via-emerald-950/20 dark:to-green-950/20",accentColor:"teal",decorativeElement:e.jsx(AVt,{})},{id:"offer_accepted",name:"Offer Accepted",description:"Celebrate their accepted offer",icon:e.jsx(sf,{className:"h-5 w-5"}),category:"transactional",headerText:s=>s?`Amazing News, ${s}!`:"Offer Accepted!",subText:"Your offer has been accepted – congratulations!",gradientClasses:"from-green-50/70 via-emerald-50/50 to-teal-50/40 dark:from-green-950/30 dark:via-emerald-950/20 dark:to-teal-950/20",accentColor:"green",decorativeElement:e.jsx(IR,{})},{id:"pre_approval",name:"Pre-Approval Congrats",description:"Congratulate on pre-approval",icon:e.jsx(Bc,{className:"h-5 w-5"}),category:"transactional",headerText:s=>s?`Congratulations, ${s}!`:"Congratulations!",subText:"You're pre-approved and ready to find your dream home",gradientClasses:"from-violet-50/70 via-purple-50/50 to-indigo-50/40 dark:from-violet-950/30 dark:via-purple-950/20 dark:to-indigo-950/20",accentColor:"violet",decorativeElement:e.jsx(i9e,{})}],LVt=[{id:"general",name:"General Touch",description:"Everyday connection templates"},{id:"holidays",name:"Holidays",description:"Seasonal and holiday greetings"},{id:"transactional",name:"Transactional",description:"Real estate milestone templates"}];function DVt(s){return UNe.filter(t=>t.category===s)}function iP(s){return UNe.find(t=>t.id===s)||UNe[0]}function l9e(){const{shareToken:s,recipientToken:t}=Po(),[r,n]=S.useState(null),[a,i]=S.useState(null),[l,o]=S.useState(null),[c,d]=S.useState(!0),[h,m]=S.useState(null),[p,x]=S.useState(!0),y=S.useRef(null),_=S.useRef(0),b=S.useRef(0),j=(()=>{const Z=new URLSearchParams(window.location.search);return t||Z.get("rt")||null})(),k=S.useCallback((Z,J=!1)=>{if(!j||Z<=0)return;const K=Math.max(1,Math.round(Z));if(K<=b.current)return;const ie=`https://relzejiswnotikjgvjhz.supabase.co/functions/v1/track-video-share?t=${encodeURIComponent(j)}&e=watch&ws=${K}`;J&&navigator.sendBeacon?navigator.sendBeacon(ie):fetch(ie,{method:"GET",keepalive:J}).catch(()=>{}),b.current=Math.max(b.current,K)},[j]);S.useEffect(()=>{var ne;if(!p||!(r!=null&&r.playback_url)||!j)return;let Z=!1;const J=()=>{_.current>0&&k(_.current,!0)},K=()=>{document.visibilityState==="hidden"&&J()},re=()=>{J()},ie=()=>{var be;if(Z||!y.current||!((be=window.playerjs)!=null&&be.Player))return;const le=new window.playerjs.Player(y.current);le.on("timeupdate",fe=>{const je=Math.floor(Number((fe==null?void 0:fe.seconds)??0));!Number.isFinite(je)||je<=0||(_.current=Math.max(_.current,je))}),le.on("pause",()=>{_.current>0&&k(_.current)}),le.on("ended",()=>{_.current>0&&k(_.current,!0)})},ce=document.querySelector('script[data-bunny-playerjs="true"]');if((ne=window.playerjs)!=null&&ne.Player)ie();else if(ce)ce.addEventListener("load",ie,{once:!0});else{const le=document.createElement("script");le.src="https://assets.mediadelivery.net/playerjs/playerjs-latest.min.js",le.async=!0,le.defer=!0,le.dataset.bunnyPlayerjs="true",le.onload=ie,document.body.appendChild(le)}return document.addEventListener("visibilitychange",K),window.addEventListener("beforeunload",re),()=>{Z=!0,document.removeEventListener("visibilitychange",K),window.removeEventListener("beforeunload",re),J()}},[p,r==null?void 0:r.playback_url,j,k]),S.useEffect(()=>{_.current=0,b.current=0},[j,s]),S.useEffect(()=>{const Z=()=>{['[id*="lc_text_widget"]','[class*="lc-text-widget"]','[id*="chat-widget"]','[class*="chat-widget"]','iframe[src*="widgets.leadconnectorhq"]','iframe[src*="msgsndr"]',"[data-chat-widget]"].forEach(ie=>{document.querySelectorAll(ie).forEach(ce=>{ce.style.display="none"})})};Z();const J=[setTimeout(Z,500),setTimeout(Z,1500),setTimeout(Z,3e3)],K=new MutationObserver(Z);return K.observe(document.body,{childList:!0,subtree:!0}),()=>{J.forEach(clearTimeout),K.disconnect()}},[]),S.useEffect(()=>{(async()=>{if(!s){m("Invalid share link"),d(!1);return}const{data:J,error:K}=await V.from("agent_videos").select("id, title, playback_url, thumbnail_url, preview_url, duration_seconds, share_token, owner_user_id, contact_id, page_template, recipient_name").eq("share_token",s).eq("is_deleted",!1).single();if(K||!J){m("Video not found or has been removed"),d(!1);return}n(J);try{await V.rpc("log_video_view",{p_video_id:J.id,p_user_agent:navigator.userAgent,p_referrer:document.referrer||null})}catch(re){console.warn("Failed to log video view:",re)}if(J.owner_user_id){const{data:re}=await V.from("profiles").select("id, name, email, phone").eq("id",J.owner_user_id).single();if(re){i(re);try{const{data:ie}=await V.storage.from("avatars").list(`${J.owner_user_id}`);if(ie&&ie.length>0){const{data:ce}=V.storage.from("avatars").getPublicUrl(`${J.owner_user_id}/${ie[0].name}`);o(ce.publicUrl)}}catch{}}}d(!1)})()},[s]);const T=Z=>{if(!Z)return"0:00";const J=Math.floor(Z/60),K=Z%60;return`${J}:${K.toString().padStart(2,"0")}`},E=Z=>Z.includes("iframe.mediadelivery.net/play/")?Z.replace("/play/","/embed/")+"?autoplay=true&responsive=true":Z,A=Z=>{if(!Z)return"?";const J=Z.split(" ");return J.length>=2?`${J[0][0]}${J[1][0]}`.toUpperCase():Z.substring(0,2).toUpperCase()},D=iP((r==null?void 0:r.page_template)||"default"),R=(r==null?void 0:r.recipient_name)||null,z=D.headerText(R),$=`https://dashboard.relevelup.com/share/video/${s}`;if(c)return e.jsx("div",{className:"min-h-screen bg-background flex items-center justify-center",children:e.jsx(is,{className:"h-8 w-8 animate-spin text-primary"})});if(h||!r)return e.jsx("div",{className:"min-h-screen bg-background flex items-center justify-center p-4",children:e.jsx(ke,{className:"max-w-md w-full",children:e.jsxs(Oe,{className:"py-12 text-center",children:[e.jsx(xn,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h2",{className:"text-xl font-semibold mb-2",children:"Video Not Found"}),e.jsx("p",{className:"text-muted-foreground",children:h||"This video is no longer available."})]})})});const ee=D.id!=="default";return e.jsxs(e.Fragment,{children:[e.jsxs(el,{children:[e.jsx("title",{children:z}),e.jsx("meta",{name:"description",content:D.subText}),e.jsx("meta",{property:"og:title",content:z}),e.jsx("meta",{property:"og:description",content:D.subText}),e.jsx("meta",{property:"og:type",content:"video.other"}),e.jsx("meta",{property:"og:url",content:$}),r.preview_url&&e.jsx("meta",{property:"og:image",content:r.preview_url}),!r.preview_url&&r.thumbnail_url&&e.jsx("meta",{property:"og:image",content:r.thumbnail_url}),r.playback_url&&e.jsxs(e.Fragment,{children:[e.jsx("meta",{property:"og:video",content:r.playback_url}),e.jsx("meta",{property:"og:video:type",content:"text/html"}),e.jsx("meta",{property:"og:video:width",content:"1280"}),e.jsx("meta",{property:"og:video:height",content:"720"})]}),e.jsx("meta",{name:"twitter:card",content:"player"}),e.jsx("meta",{name:"twitter:title",content:z}),e.jsx("meta",{name:"twitter:description",content:D.subText}),r.preview_url&&e.jsx("meta",{name:"twitter:image",content:r.preview_url}),r.playback_url&&e.jsxs(e.Fragment,{children:[e.jsx("meta",{name:"twitter:player",content:r.playback_url}),e.jsx("meta",{name:"twitter:player:width",content:"1280"}),e.jsx("meta",{name:"twitter:player:height",content:"720"})]})]}),e.jsxs("div",{className:Ft("min-h-screen flex items-center justify-center p-4 bg-gradient-to-b relative",D.gradientClasses),children:[ee&&D.decorativeElement,e.jsxs("div",{className:"max-w-2xl w-full space-y-6 relative z-10",children:[ee&&e.jsxs("div",{className:"text-center py-4 animate-fade-in",children:[e.jsx("div",{className:"flex justify-center mb-3",children:e.jsx("div",{className:Ft("w-14 h-14 rounded-full flex items-center justify-center shadow-sm",D.accentColor==="primary"&&"bg-primary/10 text-primary",D.accentColor==="amber"&&"bg-amber-100 text-amber-600 dark:bg-amber-900/50 dark:text-amber-400",D.accentColor==="teal"&&"bg-teal-100 text-teal-600 dark:bg-teal-900/50 dark:text-teal-400",D.accentColor==="rose"&&"bg-rose-100 text-rose-600 dark:bg-rose-900/50 dark:text-rose-400",D.accentColor==="emerald"&&"bg-emerald-100 text-emerald-600 dark:bg-emerald-900/50 dark:text-emerald-400",D.accentColor==="yellow"&&"bg-yellow-100 text-yellow-600 dark:bg-yellow-900/50 dark:text-yellow-400",D.accentColor==="pink"&&"bg-pink-100 text-pink-600 dark:bg-pink-900/50 dark:text-pink-400",D.accentColor==="blue"&&"bg-blue-100 text-blue-600 dark:bg-blue-900/50 dark:text-blue-400",D.accentColor==="red"&&"bg-red-100 text-red-600 dark:bg-red-900/50 dark:text-red-400",D.accentColor==="orange"&&"bg-orange-100 text-orange-600 dark:bg-orange-900/50 dark:text-orange-400",D.accentColor==="green"&&"bg-green-100 text-green-600 dark:bg-green-900/50 dark:text-green-400",D.accentColor==="violet"&&"bg-violet-100 text-violet-600 dark:bg-violet-900/50 dark:text-violet-400",D.accentColor==="sky"&&"bg-sky-100 text-sky-600 dark:bg-sky-900/50 dark:text-sky-400"),children:e.jsx("div",{className:"scale-150",children:D.icon})})}),e.jsx("h1",{className:"text-2xl sm:text-3xl font-bold mb-2",children:z}),e.jsx("p",{className:"text-muted-foreground",children:D.subText})]}),a&&e.jsxs("div",{className:"flex items-center gap-4 p-4 bg-card/90 backdrop-blur-sm rounded-lg border shadow-sm",children:[e.jsxs(Un,{className:"h-14 w-14 border-2 border-primary/20",children:[e.jsx(Ka,{src:l||void 0,alt:a.name||"Agent"}),e.jsx(qn,{className:"bg-primary/10 text-primary font-semibold",children:A(a.name)})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:ee?"A special video from":"A personal video from"}),e.jsx("h2",{className:"text-lg font-semibold truncate",children:a.name||"Your Agent"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Your Real Estate Professional"})]}),e.jsxs("div",{className:"flex gap-2 shrink-0",children:[a.phone&&e.jsx(H,{variant:"outline",size:"icon",asChild:!0,className:"h-10 w-10",children:e.jsx("a",{href:`tel:${a.phone}`,"aria-label":"Call agent",children:e.jsx(Yn,{className:"h-4 w-4"})})}),a.email&&e.jsx(H,{variant:"outline",size:"icon",asChild:!0,className:"h-10 w-10",children:e.jsx("a",{href:`mailto:${a.email}`,"aria-label":"Email agent",children:e.jsx(er,{className:"h-4 w-4"})})})]})]}),e.jsx(ke,{className:"overflow-hidden shadow-lg",children:p&&r.playback_url?e.jsx("div",{className:"relative w-full",style:{paddingBottom:"56.25%"},children:e.jsx("iframe",{ref:y,src:E(r.playback_url),title:r.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})}):e.jsxs("div",{className:"relative aspect-video bg-muted cursor-pointer group",onClick:()=>x(!0),children:[r.preview_url||r.thumbnail_url?e.jsx("img",{src:r.preview_url||r.thumbnail_url||"",alt:r.title?`${r.title} video preview`:"Video message preview",className:"w-full h-full object-cover",onError:Z=>{var K;Z.currentTarget.style.display="none";const J=(K=Z.currentTarget.parentElement)==null?void 0:K.querySelector(".video-fallback");J&&(J.style.display="flex")}}):null,e.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:r.preview_url||r.thumbnail_url?"none":"flex"},children:e.jsx(xn,{className:"h-16 w-16 text-primary/50"})}),e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/30 group-hover:bg-black/40 transition-colors",children:e.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:e.jsx(El,{className:"h-10 w-10 text-primary ml-1"})})}),r.duration_seconds&&e.jsx("div",{className:"absolute bottom-3 right-3 bg-black/70 text-white text-sm px-2 py-1 rounded",children:T(r.duration_seconds)})]})}),!ee&&e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold",children:r.title||"Video Message"}),e.jsx("p",{className:"text-muted-foreground mt-2",children:p?"Enjoy the video!":"Click to play the video"})]}),!p&&e.jsx("div",{className:"flex justify-center",children:e.jsxs(H,{size:"lg",onClick:()=>x(!0),className:"gap-2",children:[e.jsx(El,{className:"h-5 w-5"}),"Watch Video"]})}),e.jsx(uVt,{shareToken:s,agentName:(a==null?void 0:a.name)||null,hasContact:!!r.contact_id})]})]})]})}function RVt(){return S.useEffect(()=>(document.body.classList.add("video-landing-page"),()=>{document.body.classList.remove("video-landing-page")}),[]),e.jsx(aTt,{})}function OVt(){const{token:s}=Po();return S.useEffect(()=>{if(!s)return;const t=`https://relzejiswnotikjgvjhz.supabase.co/functions/v1/video-og-image?token=${s}`;window.location.replace(t)},[s]),e.jsx("main",{className:"min-h-screen bg-background flex items-center justify-center",children:e.jsxs("div",{className:"flex items-center gap-3 text-muted-foreground",children:[e.jsx(is,{className:"h-5 w-5 animate-spin"}),e.jsx("span",{children:"Loading video preview…"})]})})}const FVt={active:"bg-emerald-500",coming_soon:"bg-sky-500",office_exclusive:"bg-indigo-500",pre_market:"bg-cyan-500",price_improvement:"bg-orange-500",under_contract:"bg-purple-500",sold:"bg-gray-500"},BVt={active:"Active",coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"},f6={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"};function zVt(){var We,Ve,Le,Me;const{slugOrId:s}=Po(),[t]=Ed(),{data:r,isLoading:n}=qst(s||""),a=Vst(),i=qPt(),l=t.get("ref"),[o,c]=S.useState(""),[d,h]=S.useState(""),[m,p]=S.useState(""),[x,y]=S.useState(""),[_,b]=S.useState(""),[j,k]=S.useState(""),[T,E]=S.useState(""),[A,D]=S.useState("in_person"),[R,z]=S.useState("info"),[O,$]=S.useState(!1),[ee,Z]=S.useState(!1),[J,K]=S.useState(null),[re,ie]=S.useState(!1);S.useEffect(()=>{l&&i.mutate(l)},[l]);const ce=ze=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(ze),ne=async ze=>{if(ze.preventDefault(),!o.trim()||!m.trim()||!r)return;const Pe=R==="showing";if(Pe&&!j){he.error("Please pick a preferred date for your showing");return}$(!0);try{await a.mutateAsync({listingId:r.id,agentId:r.agent_id,firstName:o.trim(),lastName:d.trim(),email:m.trim(),phone:x.trim(),shareToken:l,leadType:Pe?"showing_request":"info_request",preferredDate:Pe?j:null,preferredTime:Pe&&T||null,showingMode:Pe?A:null,message:_.trim()||null}),Z(!0),he.success(Pe?"Showing request sent! The agent will confirm details shortly.":"Thanks! The agent will be in touch soon.")}catch(Ie){console.error("Lead submission error:",Ie),he.error(`Failed to submit: ${Ie.message||"Please try again"}`)}finally{$(!1)}},le=(r==null?void 0:r.photos)||[],be=le.find(ze=>ze.is_primary)||le[0],fe=()=>{J!==null&&K(J===0?le.length-1:J-1)},je=()=>{J!==null&&K(J===le.length-1?0:J+1)};if(n)return e.jsxs("div",{className:"min-h-screen bg-background",children:[e.jsx("header",{className:"border-b bg-card",children:e.jsx("div",{className:"container mx-auto px-4 py-4",children:e.jsx(Ks,{className:"h-8 w-32"})})}),e.jsxs("div",{className:"container mx-auto px-4 py-8",children:[e.jsx(Ks,{className:"h-10 w-48 mb-6"}),e.jsx(Ks,{className:"aspect-video mb-6"}),e.jsxs("div",{className:"grid md:grid-cols-3 gap-6",children:[e.jsxs("div",{className:"md:col-span-2 space-y-4",children:[e.jsx(Ks,{className:"h-12 w-48"}),e.jsx(Ks,{className:"h-6 w-full"}),e.jsx(Ks,{className:"h-6 w-3/4"})]}),e.jsx(Ks,{className:"h-64"})]})]})]});if(!r)return e.jsxs("div",{className:"min-h-screen bg-background",children:[e.jsx("header",{className:"border-b bg-card",children:e.jsx("div",{className:"container mx-auto px-4 py-4",children:e.jsx(Xn,{to:"/public/listings",className:"flex items-center gap-2",children:e.jsx("img",{src:Ihe,alt:"LevelUp",className:"h-8"})})})}),e.jsxs("div",{className:"container mx-auto px-4 py-16 text-center",children:[e.jsx(Fn,{className:"h-16 w-16 mx-auto text-muted-foreground mb-4"}),e.jsx("h1",{className:"text-2xl font-bold mb-2",children:"Listing Not Found"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"This listing may no longer be available."}),e.jsx(H,{asChild:!0,children:e.jsx(Xn,{to:"/public/listings",children:"Browse All Listings"})})]})]});const ve=r.property_address?`${r.property_address} - ${r.city}, ${r.state}`:`${r.city}, ${r.state} Home for Sale`;return e.jsxs(e.Fragment,{children:[e.jsxs(el,{children:[e.jsxs("title",{children:[ve," | LevelUp Listings"]}),e.jsx("meta",{name:"description",content:`${ce(r.price)} - ${r.bedrooms||""}BD ${r.bathrooms||""}BA ${r.square_footage?r.square_footage.toLocaleString()+" sqft":""} ${f6[r.property_type]} in ${r.city}, ${r.state}. ${((We=r.description)==null?void 0:We.slice(0,150))||""}`}),e.jsx("link",{rel:"canonical",href:`https://listings.relevelup.com/${r.slug||r.id}`}),e.jsx("meta",{property:"og:title",content:ve}),e.jsx("meta",{property:"og:description",content:`${ce(r.price)} - ${r.bedrooms||""}BD ${r.bathrooms||""}BA ${f6[r.property_type]} in ${r.city}, ${r.state}. View photos, details, and contact the listing agent.`}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("meta",{property:"og:url",content:`https://listings.relevelup.com/${r.slug||r.id}`}),be&&e.jsx("meta",{property:"og:image",content:be.photo_url}),be&&e.jsx("meta",{property:"og:image:alt",content:`${r.property_address||r.city} - ${f6[r.property_type]} for sale`}),e.jsx("meta",{property:"og:site_name",content:"LevelUp Listings"}),e.jsx("meta",{property:"og:locale",content:"en_US"}),e.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),e.jsx("meta",{name:"twitter:title",content:ve}),e.jsx("meta",{name:"twitter:description",content:`${ce(r.price)} - ${r.bedrooms||""}BD ${r.bathrooms||""}BA in ${r.city}, ${r.state}`}),be&&e.jsx("meta",{name:"twitter:image",content:be.photo_url}),e.jsx("meta",{name:"robots",content:"index, follow"}),e.jsx("meta",{name:"geo.region",content:`US-${r.state}`}),e.jsx("meta",{name:"geo.placename",content:r.city}),e.jsx("script",{type:"application/ld+json",children:JSON.stringify({"@context":"https://schema.org","@type":"RealEstateListing",name:r.property_address||`${r.city}, ${r.state} Home`,description:r.description||`${f6[r.property_type]} for sale in ${r.city}, ${r.state}`,url:`https://listings.relevelup.com/${r.slug||r.id}`,datePosted:r.created_at,image:le.map(ze=>ze.photo_url),address:{"@type":"PostalAddress",streetAddress:r.property_address||void 0,addressLocality:r.city,addressRegion:r.state,addressCountry:"US"},geo:r.neighborhood?{"@type":"GeoCoordinates",name:r.neighborhood}:void 0,offers:{"@type":"Offer",price:r.price,priceCurrency:"USD",availability:r.status==="sold"?"https://schema.org/SoldOut":r.status==="under_contract"?"https://schema.org/LimitedAvailability":"https://schema.org/InStock"},numberOfRooms:r.bedrooms||void 0,numberOfBathroomsTotal:r.bathrooms||void 0,floorSize:r.square_footage?{"@type":"QuantitativeValue",value:r.square_footage,unitCode:"FTK"}:void 0,yearBuilt:r.year_built||void 0,broker:r.agent?{"@type":"RealEstateAgent",name:r.agent.name,email:r.agent.email,worksFor:(Ve=r.agent.brokerage)!=null&&Ve.name?{"@type":"RealEstateAgent",name:r.agent.brokerage.name}:void 0}:void 0})})]}),e.jsxs("div",{className:"min-h-screen bg-background",children:[e.jsx("header",{className:"border-b bg-card sticky top-0 z-50",children:e.jsx("div",{className:"container mx-auto px-4 py-4",children:e.jsx("div",{className:"flex items-center justify-between",children:e.jsx(Xn,{to:"/public/listings",className:"flex items-center gap-2",children:e.jsx("img",{src:Ihe,alt:"LevelUp",className:"h-8"})})})})}),e.jsxs("div",{className:"container mx-auto px-4 py-6",children:[e.jsxs(Xn,{to:"/public/listings",className:"inline-flex items-center text-muted-foreground hover:text-foreground mb-6",children:[e.jsx(za,{className:"h-4 w-4 mr-2"}),"Back to Listings"]}),le.length>0&&e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4 mb-8",children:[e.jsx("div",{className:"md:col-span-2",children:e.jsx("div",{className:"aspect-[16/10] rounded-lg overflow-hidden bg-muted cursor-pointer",onClick:()=>K(0),children:e.jsx("img",{src:be==null?void 0:be.photo_url,alt:`${r.property_address||r.city+", "+r.state} - ${f6[r.property_type]} main photo`,className:"w-full h-full object-cover hover:scale-105 transition-transform duration-300"})})}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:le.slice(1,5).map((ze,Pe)=>e.jsxs("div",{className:"aspect-square rounded-lg overflow-hidden bg-muted cursor-pointer relative",onClick:()=>K(Pe+1),children:[e.jsx("img",{src:ze.photo_url,alt:`${r.property_address||r.city} - Photo ${Pe+2} of ${le.length}`,className:"w-full h-full object-cover hover:scale-105 transition-transform duration-300"}),Pe===3&&le.length>5&&e.jsxs("div",{className:"absolute inset-0 bg-black/60 flex items-center justify-center text-white font-semibold",children:["+",le.length-5," more"]})]},ze.id))})]}),e.jsxs("div",{className:"grid md:grid-cols-3 gap-8",children:[e.jsxs("div",{className:"md:col-span-2 space-y-6",children:[e.jsxs("div",{children:[e.jsx("div",{className:"flex items-center gap-2 mb-3",children:e.jsx(Xe,{className:`${FVt[r.status]} text-white border-0`,children:BVt[r.status]})}),e.jsx("h1",{className:"text-4xl font-bold text-primary mb-2",children:ce(r.price)}),r.property_address&&e.jsx("p",{className:"text-xl font-medium",children:r.property_address}),e.jsxs("p",{className:"text-muted-foreground flex items-center gap-1",children:[e.jsx(Qa,{className:"h-4 w-4"}),r.city,", ",r.state,r.neighborhood&&` • ${r.neighborhood}`]})]}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-4 py-4 border-y",children:[r.bedrooms&&e.jsxs("div",{className:"text-center",children:[e.jsx(x1,{className:"h-6 w-6 mx-auto mb-1 text-muted-foreground"}),e.jsx("p",{className:"text-xl font-semibold",children:r.bedrooms}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Beds"})]}),r.bathrooms&&e.jsxs("div",{className:"text-center",children:[e.jsx(_p,{className:"h-6 w-6 mx-auto mb-1 text-muted-foreground"}),e.jsx("p",{className:"text-xl font-semibold",children:r.bathrooms}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Baths"})]}),r.square_footage&&e.jsxs("div",{className:"text-center",children:[e.jsx(Hy,{className:"h-6 w-6 mx-auto mb-1 text-muted-foreground"}),e.jsx("p",{className:"text-xl font-semibold",children:r.square_footage.toLocaleString()}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Sq Ft"})]}),r.year_built&&e.jsxs("div",{className:"text-center",children:[e.jsx(Nn,{className:"h-6 w-6 mx-auto mb-1 text-muted-foreground"}),e.jsx("p",{className:"text-xl font-semibold",children:r.year_built}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Built"})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(Xe,{variant:"secondary",children:[e.jsx(Xa,{className:"h-3 w-3 mr-1"}),f6[r.property_type]]}),r.lot_size&&e.jsxs(Xe,{variant:"secondary",children:["Lot: ",r.lot_size]}),r.has_hoa&&e.jsx(Xe,{variant:"secondary",children:"HOA"})]}),r.description&&e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold mb-2",children:"About This Property"}),e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:r.description})]}),r.agent_notes&&r.agent_notes_public&&e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold mb-2",children:"Agent Notes"}),e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:r.agent_notes})]}),r.mls_link&&e.jsx(H,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:r.mls_link,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(gn,{className:"h-4 w-4 mr-2"}),"View on MLS"]})})]})]}),e.jsxs("div",{className:"space-y-6",children:[r.video&&r.video.playback_url&&e.jsx(ke,{className:"overflow-hidden bg-gradient-to-br from-primary/5 to-primary/10 border-primary/20",children:e.jsxs(Oe,{className:"p-0",children:[e.jsxs("div",{className:"relative aspect-video bg-muted cursor-pointer group",onClick:()=>ie(!0),children:[r.video.thumbnail_url?e.jsx("img",{src:r.video.thumbnail_url,alt:"Video thumbnail",className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center bg-gradient-to-br from-primary/20 to-primary/30",children:e.jsx(xn,{className:"h-12 w-12 text-primary"})}),e.jsx("div",{className:"absolute inset-0 bg-black/30 group-hover:bg-black/40 transition-colors flex items-center justify-center",children:e.jsx("div",{className:"h-16 w-16 rounded-full bg-white/90 group-hover:bg-white flex items-center justify-center transition-colors shadow-lg",children:e.jsx(El,{className:"h-8 w-8 text-primary fill-primary ml-1"})})})]}),e.jsxs("div",{className:"p-4",children:[e.jsxs(H,{onClick:()=>ie(!0),className:"w-full gap-2",size:"lg",children:[e.jsx(El,{className:"h-4 w-4"}),"Watch Video Tour"]}),r.video.title&&e.jsx("p",{className:"text-xs text-muted-foreground mt-2 text-center truncate",children:r.video.title})]})]})}),r.agent&&e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsxs(zt,{className:"text-lg flex items-center gap-2",children:[e.jsx(io,{className:"h-5 w-5"}),"Listing Agent"]})}),e.jsxs(Oe,{children:[e.jsx("p",{className:"font-semibold text-lg",children:r.agent.name}),((Le=r.agent.brokerage)==null?void 0:Le.name)&&e.jsx("p",{className:"text-sm text-muted-foreground",children:r.agent.brokerage.name})]})]}),e.jsxs(ke,{className:"border-primary",children:[e.jsx(Ot,{className:"pb-3",children:e.jsx(zt,{className:"text-lg",children:"Interested in this property?"})}),e.jsx(Oe,{children:ee?e.jsxs("div",{className:"text-center py-4",children:[e.jsx("div",{className:"h-12 w-12 rounded-full bg-primary/10 flex items-center justify-center mx-auto mb-3",children:e.jsx(er,{className:"h-6 w-6 text-primary"})}),e.jsx("p",{className:"font-medium",children:R==="showing"?"Showing request sent!":"Thanks for your interest!"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:R==="showing"?"The listing agent will reach out to confirm your showing time.":"The listing agent will contact you soon."})]}):e.jsxs(ta,{value:R,onValueChange:ze=>z(ze),children:[e.jsxs(Qn,{className:"grid w-full grid-cols-2 mb-4",children:[e.jsxs(ts,{value:"info",className:"gap-1.5",children:[e.jsx(er,{className:"h-3.5 w-3.5"}),"Get Info"]}),e.jsxs(ts,{value:"showing",className:"gap-1.5",children:[e.jsx(h_,{className:"h-3.5 w-3.5"}),"Request Tour"]})]}),e.jsxs("form",{onSubmit:ne,className:"space-y-3",children:[e.jsxs(cs,{value:"showing",className:"mt-0 space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"preferredDate",children:"Preferred Date *"}),e.jsx(Se,{id:"preferredDate",type:"date",value:j,onChange:ze=>k(ze.target.value),min:new Date().toISOString().split("T")[0],required:R==="showing"})]}),e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"preferredTime",children:"Preferred Time"}),e.jsxs(Bs,{value:T,onValueChange:E,children:[e.jsx(Os,{id:"preferredTime",children:e.jsx(Us,{placeholder:"Any time"})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"morning",children:"Morning (9am–12pm)"}),e.jsx(pt,{value:"afternoon",children:"Afternoon (12pm–5pm)"}),e.jsx(pt,{value:"evening",children:"Evening (5pm–8pm)"})]})]})]})]}),e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"showingMode",children:"Tour Type"}),e.jsxs(Bs,{value:A,onValueChange:ze=>D(ze),children:[e.jsx(Os,{id:"showingMode",children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"in_person",children:"🏡 In-person showing"}),e.jsx(pt,{value:"video",children:"📱 Video tour (FaceTime/Zoom)"}),e.jsx(pt,{value:"either",children:"Either works for me"})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"firstName",children:"First Name *"}),e.jsx(Se,{id:"firstName",type:"text",placeholder:"John",value:o,onChange:ze=>c(ze.target.value),required:!0})]}),e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"lastName",children:"Last Name"}),e.jsx(Se,{id:"lastName",type:"text",placeholder:"Doe",value:d,onChange:ze=>h(ze.target.value)})]})]}),e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"email",children:"Email *"}),e.jsx(Se,{id:"email",type:"email",placeholder:"you@example.com",value:m,onChange:ze=>p(ze.target.value),required:!0})]}),e.jsxs("div",{children:[e.jsxs(ue,{htmlFor:"phone",children:["Phone ",R==="showing"&&"*"]}),e.jsx(Se,{id:"phone",type:"tel",placeholder:"(555) 123-4567",value:x,onChange:ze=>y(ze.target.value),required:R==="showing"})]}),e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"message",children:R==="showing"?"Anything else?":"Message (optional)"}),e.jsx(vr,{id:"message",placeholder:R==="showing"?"e.g. I have flexibility on weekends":"Any specific questions about the property?",value:_,onChange:ze=>b(ze.target.value),rows:2})]}),e.jsx(H,{type:"submit",className:"w-full",disabled:O,children:O?"Submitting...":R==="showing"?"Request Showing":"Get More Info"}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:"The listing agent will reach out to you directly."})]})]})})]})]})]})]}),e.jsx(bs,{open:J!==null,onOpenChange:()=>K(null),children:e.jsxs(vs,{className:"max-w-5xl p-0 bg-black/95",children:[e.jsx(Cs,{className:"sr-only",children:e.jsx(Ns,{children:"Photo Gallery"})}),e.jsx("button",{onClick:()=>K(null),className:"absolute right-4 top-4 z-50 rounded-full bg-black/50 p-2 text-white hover:bg-black/70",children:e.jsx(Rr,{className:"h-5 w-5"})}),J!==null&&le[J]&&e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:le[J].photo_url,alt:`Photo ${J+1}`,className:"w-full max-h-[80vh] object-contain"}),le.length>1&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:fe,className:"absolute left-4 top-1/2 -translate-y-1/2 rounded-full bg-black/50 p-2 text-white hover:bg-black/70",children:e.jsx(fl,{className:"h-6 w-6"})}),e.jsx("button",{onClick:je,className:"absolute right-4 top-1/2 -translate-y-1/2 rounded-full bg-black/50 p-2 text-white hover:bg-black/70",children:e.jsx($a,{className:"h-6 w-6"})}),e.jsxs("div",{className:"absolute bottom-4 left-1/2 -translate-x-1/2 text-white bg-black/50 px-3 py-1 rounded-full text-sm",children:[J+1," / ",le.length]})]})]})]})}),e.jsx(bs,{open:re,onOpenChange:ie,children:e.jsxs(vs,{className:"max-w-4xl p-0 bg-black overflow-hidden",children:[e.jsx(Cs,{className:"sr-only",children:e.jsx(Ns,{children:"Video Tour"})}),e.jsx("button",{onClick:()=>ie(!1),className:"absolute right-4 top-4 z-50 rounded-full bg-black/50 p-2 text-white hover:bg-black/70",children:e.jsx(Rr,{className:"h-5 w-5"})}),((Me=r==null?void 0:r.video)==null?void 0:Me.playback_url)&&e.jsx("div",{className:"aspect-video w-full",children:e.jsx("iframe",{src:r.video.playback_url,className:"w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})})]})}),e.jsx("footer",{className:"border-t py-8 mt-16",children:e.jsxs("div",{className:"container mx-auto px-4 text-center text-sm text-muted-foreground",children:[e.jsxs("p",{children:["© ",new Date().getFullYear()," LevelUp. All rights reserved."]}),e.jsx("p",{className:"mt-2",children:e.jsx("a",{href:"https://relevelup.com",target:"_blank",rel:"noopener noreferrer",className:"hover:text-foreground",children:"relevelup.com"})})]})})]})]})}function $Vt(){var i;const{slug:s}=Po(),{data:t,isLoading:r,error:n}=Kst(s);if(S.useEffect(()=>(document.body.classList.add("agent-card-page"),()=>{document.body.classList.remove("agent-card-page")}),[]),S.useEffect(()=>{t!=null&&t.id&&Xo(t.id,"card_view")},[t==null?void 0:t.id]),r)return e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center",children:e.jsxs("div",{className:"w-full max-w-md mx-auto p-6 space-y-6",children:[e.jsxs("div",{className:"flex flex-col items-center gap-4",children:[e.jsx(Ks,{className:"h-28 w-28 rounded-full"}),e.jsx(Ks,{className:"h-6 w-48"}),e.jsx(Ks,{className:"h-4 w-36"})]}),e.jsx(Ks,{className:"h-12 w-full"}),e.jsx(Ks,{className:"h-12 w-full"})]})});if(n||!t)return e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center p-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Card Not Found"}),e.jsx("p",{className:"text-slate-500",children:"This agent card doesn't exist or isn't published yet."})]})});const a=((i=t.profile)==null?void 0:i.name)||"Agent";return e.jsxs(e.Fragment,{children:[e.jsxs(el,{children:[e.jsxs("title",{children:[a," | Real Estate Agent"]}),e.jsx("meta",{name:"description",content:t.positioning_statement||`Connect with ${a}, your trusted real estate professional.`}),e.jsx("meta",{property:"og:title",content:`${a} | Real Estate Agent`}),e.jsx("meta",{property:"og:description",content:t.positioning_statement||`Connect with ${a}`}),t.avatar_url&&e.jsx("meta",{property:"og:image",content:t.avatar_url})]}),e.jsx(o5e,{card:t})]})}function dot({slugOverride:s}={}){var Qe;const{slug:t}=Po(),r=s||t,[n]=Ed(),a=n.get("t"),[i,l]=S.useState(!0),[o,c]=S.useState(null),[d,h]=S.useState(null),m=S.useRef(null),p=S.useRef(null),[x,y]=S.useState(null),[_,b]=S.useState(null),[j,k]=S.useState(!1),[T,E]=S.useState(!1),[A,D]=S.useState(0),[R,z]=S.useState(!1),[O,$]=S.useState(""),[ee,Z]=S.useState(""),[J,K]=S.useState(""),[re,ie]=S.useState(""),[ce,ne]=S.useState(""),[le,be]=S.useState(""),[fe,je]=S.useState(""),[ve,We]=S.useState(""),[Ve,Le]=S.useState(""),[Me,ze]=S.useState(""),[Pe,Ie]=S.useState(""),[De,pe]=S.useState("");S.useEffect(()=>{tt()},[r,a]);const tt=async()=>{if(!r)return;l(!0);const{data:Ne,error:$e}=await V.from("contact_intake_pages").select("*").eq("slug",r).eq("is_active",!0).maybeSingle();if($e||!Ne){z(!0),l(!1);return}h(Ne),p.current=Ne;const{data:it}=await V.from("profiles").select("name, avatar_url, title, phone, email, brokerage_id").eq("id",Ne.user_id).single();if(it){let Je;if(it.brokerage_id){const{data:wt}=await V.from("brokerages").select("name").eq("id",it.brokerage_id).single();Je=(wt==null?void 0:wt.name)||void 0}let st=it.avatar_url||null;if(!st){const{data:wt}=V.storage.from("avatars").getPublicUrl(`${Ne.user_id}/avatar.jpg`);wt!=null&&wt.publicUrl&&(st=`${wt.publicUrl}?t=${Date.now()}`)}const mt={...it,avatar_url:st,brokerage_name:Je};c(mt),m.current=mt}if(a)try{console.log("[ConnectPage] Resolving token:",a,"for page:",Ne.id);const{data:Je,error:st}=await V.functions.invoke("process-intake-submissions",{body:{action:"resolve_token",token:a,page_id:Ne.id}});if(console.log("[ConnectPage] Resolve result:",{resolved:Je,resolveErr:st}),!st&&(Je!=null&&Je.contact_id)){b(Je.contact_id);const mt=Je.contact;mt&&(y(mt),$(mt.first_name||""),Z(mt.last_name||""),K(mt.email||""),ie(mt.phone||""),ne(mt.address||""),be(mt.city||""),je(mt.state||""),We(mt.zip||""),Le(mt.birthday||""),ze(mt.home_anniversary||""))}}catch(Je){console.error("Failed to resolve token:",Je)}l(!1)},ge=async()=>{var Ne,$e;if(!O.trim()){he.error("Please enter your first name");return}if(!r){he.error("Invalid page. Please refresh.");return}E(!0);try{let it=(Ne=p.current)==null?void 0:Ne.id,Je=($e=p.current)==null?void 0:$e.user_id;if(!it||!Je){const{data:mt}=await V.from("contact_intake_pages").select("id, user_id").eq("slug",r).eq("is_active",!0).maybeSingle();if(!mt){he.error("This page is no longer active. Please contact the agent directly."),E(!1);return}it=mt.id,Je=mt.user_id}const{error:st}=await V.from("contact_intake_submissions").insert({intake_page_id:it,agent_user_id:Je,existing_contact_id:_,first_name:O.trim(),last_name:ee.trim()||null,email:J.trim()||null,phone:re.trim()||null,address:ce.trim()||null,city:le.trim()||null,state:fe.trim()||null,zip:ve.trim()||null,birthday:Ve||null,home_anniversary:Me||null,real_estate_interest:Pe||null,message:De.trim()||null});if(console.log("[ConnectPage] Insert result:",{error:st}),st)throw st;a&&await V.from("contact_intake_tokens").update({used_at:new Date().toISOString()}).eq("token",a);try{const mt=[O.trim(),ee.trim()].filter(Boolean).join(" ");await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/connect-page-notify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({agentUserId:Je,contactName:mt,contactEmail:J.trim()||null,contactPhone:re.trim()||null,slug:r})})}catch(mt){console.warn("Connect page notification failed (non-blocking):",mt)}k(!0)}catch(it){console.error(it),he.error("Something went wrong. Please try again.")}finally{E(!1)}};if(i)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-50 via-white to-blue-50",children:e.jsx(is,{className:"h-8 w-8 animate-spin text-slate-400"})});if(R)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-50 via-white to-blue-50",children:e.jsxs("div",{className:"text-center space-y-3",children:[e.jsx("h1",{className:"text-2xl font-semibold text-slate-700",children:"Page Not Found"}),e.jsx("p",{className:"text-slate-500",children:"This connect page doesn't exist or is no longer active."})]})});if(j)return e.jsxs("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-50 via-white to-blue-50 p-4",children:[e.jsx(el,{children:e.jsxs("title",{children:["Thank You | ",o==null?void 0:o.name]})}),e.jsxs(Ur.div,{initial:{opacity:0,scale:.9},animate:{opacity:1,scale:1},className:"max-w-md w-full text-center space-y-6 p-8",children:[e.jsx(Ur.div,{initial:{scale:0},animate:{scale:1},transition:{type:"spring",delay:.2},className:"mx-auto w-20 h-20 rounded-full bg-emerald-100 flex items-center justify-center",children:e.jsx(ea,{className:"h-10 w-10 text-emerald-600"})}),e.jsx("h1",{className:"text-3xl font-bold text-slate-800",children:"Thank You!"}),e.jsxs("p",{className:"text-lg text-slate-600",children:[o==null?void 0:o.name," has received your info and will be in touch soon."]}),e.jsxs("div",{className:"flex items-center justify-center gap-1 text-sm text-slate-400 pt-4",children:[e.jsx(Bi,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Powered by ReLevelUp"})]})]})]});const ct=!!a&&!!x,Ue=3,et=[{title:ct?"Confirm Your Info":"Let's Get Connected",fields:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-slate-600 mb-1.5",children:"First Name *"}),e.jsx("input",{type:"text",value:O,onChange:Ne=>$(Ne.target.value),placeholder:"Jane",className:"w-full px-4 py-3 rounded-xl border border-slate-200 bg-white text-slate-800 placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500/40 focus:border-blue-400 transition-all",required:!0})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-slate-600 mb-1.5",children:"Last Name"}),e.jsx("input",{type:"text",value:ee,onChange:Ne=>Z(Ne.target.value),placeholder:"Smith",className:"w-full px-4 py-3 rounded-xl border border-slate-200 bg-white text-slate-800 placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500/40 focus:border-blue-400 transition-all"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-slate-600 mb-1.5",children:"Email"}),e.jsx("input",{type:"email",value:J,onChange:Ne=>K(Ne.target.value),placeholder:"jane@email.com",className:"w-full px-4 py-3 rounded-xl border border-slate-200 bg-white text-slate-800 placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500/40 focus:border-blue-400 transition-all"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-slate-600 mb-1.5",children:"Phone"}),e.jsx("input",{type:"tel",value:re,onChange:Ne=>ie(Ne.target.value),placeholder:"(555) 123-4567",className:"w-full px-4 py-3 rounded-xl border border-slate-200 bg-white text-slate-800 placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500/40 focus:border-blue-400 transition-all"})]})]})},{title:"A Little More About You",fields:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-slate-600 mb-1.5",children:"Street Address"}),e.jsx("input",{type:"text",value:ce,onChange:Ne=>ne(Ne.target.value),placeholder:"123 Main St",className:"w-full px-4 py-3 rounded-xl border border-slate-200 bg-white text-slate-800 placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500/40 focus:border-blue-400 transition-all"})]}),e.jsxs("div",{className:"grid grid-cols-5 gap-3",children:[e.jsxs("div",{className:"col-span-2",children:[e.jsx("label",{className:"block text-sm font-medium text-slate-600 mb-1.5",children:"City"}),e.jsx("input",{type:"text",value:le,onChange:Ne=>be(Ne.target.value),placeholder:"Austin",className:"w-full px-4 py-3 rounded-xl border border-slate-200 bg-white text-slate-800 placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500/40 focus:border-blue-400 transition-all"})]}),e.jsxs("div",{className:"col-span-1",children:[e.jsx("label",{className:"block text-sm font-medium text-slate-600 mb-1.5",children:"State"}),e.jsx("input",{type:"text",value:fe,onChange:Ne=>je(Ne.target.value),placeholder:"TX",maxLength:2,className:"w-full px-4 py-3 rounded-xl border border-slate-200 bg-white text-slate-800 placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500/40 focus:border-blue-400 transition-all"})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx("label",{className:"block text-sm font-medium text-slate-600 mb-1.5",children:"Zip"}),e.jsx("input",{type:"text",value:ve,onChange:Ne=>We(Ne.target.value),placeholder:"78701",className:"w-full px-4 py-3 rounded-xl border border-slate-200 bg-white text-slate-800 placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500/40 focus:border-blue-400 transition-all"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-slate-600 mb-1.5",children:"Birthday"}),e.jsx("input",{type:"date",value:Ve,onChange:Ne=>Le(Ne.target.value),className:"w-full px-4 py-3 rounded-xl border border-slate-200 bg-white text-slate-800 placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500/40 focus:border-blue-400 transition-all"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-slate-600 mb-1.5",children:"Home Anniversary"}),e.jsx("input",{type:"date",value:Me,onChange:Ne=>ze(Ne.target.value),className:"w-full px-4 py-3 rounded-xl border border-slate-200 bg-white text-slate-800 placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500/40 focus:border-blue-400 transition-all"})]})]})]})},{title:"One Last Thing",fields:e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium text-slate-600 mb-3",children:["Are you thinking about making a move anytime soon? ",e.jsx("span",{className:"text-slate-400 font-normal",children:"(totally optional)"})]}),e.jsx("div",{className:"grid grid-cols-2 gap-3",children:[{value:"buying",label:"🏠 Buying",desc:"Looking for a home"},{value:"selling",label:"📋 Selling",desc:"Thinking of selling"},{value:"both",label:"🔄 Both",desc:"Buy & sell"},{value:"not_now",label:"😊 Not right now",desc:"Just staying connected"}].map(Ne=>e.jsxs("button",{type:"button",onClick:()=>Ie(Pe===Ne.value?"":Ne.value),className:`p-3.5 rounded-xl border-2 text-left transition-all ${Pe===Ne.value?"border-blue-500 bg-blue-50 shadow-sm":"border-slate-200 bg-white hover:border-slate-300"}`,children:[e.jsx("span",{className:"block text-sm font-medium text-slate-800",children:Ne.label}),e.jsx("span",{className:"block text-xs text-slate-500 mt-0.5",children:Ne.desc})]},Ne.value))})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium text-slate-600 mb-1.5",children:["Anything else you'd like to share? ",e.jsx("span",{className:"text-slate-400 font-normal",children:"(optional)"})]}),e.jsx("textarea",{value:De,onChange:Ne=>pe(Ne.target.value),placeholder:"Feel free to drop a note...",rows:3,className:"w-full px-4 py-3 rounded-xl border border-slate-200 bg-white text-slate-800 placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500/40 focus:border-blue-400 transition-all resize-none"})]})]})}];return e.jsxs("div",{className:"min-h-screen bg-gradient-to-br from-slate-50 via-white to-blue-50",children:[e.jsxs(el,{children:[e.jsxs("title",{children:["Connect with ",(o==null?void 0:o.name)||"Agent"]}),e.jsx("meta",{name:"robots",content:"noindex, nofollow"})]}),e.jsxs("div",{className:"max-w-lg mx-auto px-4 py-8 sm:py-12",children:[e.jsxs(Ur.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},className:"text-center mb-8",children:[o!=null&&o.avatar_url?e.jsx("img",{src:o.avatar_url,alt:o.name,className:"w-24 h-24 rounded-full object-cover mx-auto mb-4 ring-4 ring-white shadow-lg"}):e.jsx("div",{className:"w-24 h-24 rounded-full bg-gradient-to-br from-blue-500 to-indigo-600 mx-auto mb-4 flex items-center justify-center ring-4 ring-white shadow-lg",children:e.jsx("span",{className:"text-3xl font-bold text-white",children:((Qe=o==null?void 0:o.name)==null?void 0:Qe.charAt(0))||"?"})}),e.jsx("h1",{className:"text-2xl font-bold text-slate-800",children:o==null?void 0:o.name}),(o==null?void 0:o.title)&&e.jsx("p",{className:"text-slate-500 mt-0.5",children:o.title}),(o==null?void 0:o.brokerage_name)&&e.jsx("p",{className:"text-sm text-slate-400",children:o.brokerage_name}),((o==null?void 0:o.phone)||(o==null?void 0:o.email))&&e.jsxs("div",{className:"flex items-center justify-center gap-3 mt-3",children:[(o==null?void 0:o.phone)&&e.jsx("a",{href:`tel:${o.phone}`,className:"flex items-center justify-center w-10 h-10 rounded-full bg-blue-50 hover:bg-blue-100 text-blue-600 transition-colors","aria-label":"Call agent",children:e.jsx(Yn,{className:"h-4.5 w-4.5"})}),(o==null?void 0:o.email)&&e.jsx("a",{href:`mailto:${o.email}`,className:"flex items-center justify-center w-10 h-10 rounded-full bg-blue-50 hover:bg-blue-100 text-blue-600 transition-colors","aria-label":"Email agent",children:e.jsx(er,{className:"h-4.5 w-4.5"})})]})]}),e.jsx(Ur.p,{initial:{opacity:0},animate:{opacity:1},transition:{delay:.2},className:"text-center text-slate-600 mb-8 px-4 leading-relaxed",children:(d==null?void 0:d.welcome_message)||"I'd love to stay connected! Fill in your info below."}),e.jsx("div",{className:"flex gap-2 mb-8 px-2",children:Array.from({length:Ue}).map((Ne,$e)=>e.jsx("div",{className:`h-1.5 flex-1 rounded-full transition-all duration-500 ${$e<=A?"bg-blue-500":"bg-slate-200"}`},$e))}),e.jsxs(Ur.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:.3},className:"bg-white rounded-2xl shadow-lg shadow-slate-200/50 border border-slate-100 p-6 sm:p-8",children:[e.jsx(J5e,{mode:"wait",children:e.jsxs(Ur.div,{initial:{opacity:0,x:20},animate:{opacity:1,x:0},exit:{opacity:0,x:-20},transition:{duration:.25},children:[e.jsxs("div",{className:"flex items-center gap-2 mb-6",children:[e.jsx(Lr,{className:"h-5 w-5 text-blue-500"}),e.jsx("h2",{className:"text-lg font-semibold text-slate-800",children:et[A].title})]}),et[A].fields]},A)}),e.jsxs("div",{className:"flex justify-between mt-8",children:[A>0?e.jsx("button",{type:"button",onClick:()=>D(Ne=>Ne-1),className:"px-5 py-2.5 text-sm font-medium text-slate-600 hover:text-slate-800 transition-colors",children:"Back"}):e.jsx("div",{}),A{if(A===0&&!O.trim()){he.error("Please enter your first name");return}D(Ne=>Ne+1)},className:"px-6 py-2.5 bg-blue-600 text-white text-sm font-medium rounded-xl hover:bg-blue-700 transition-colors shadow-sm",children:"Continue"}):e.jsx("button",{type:"button",onClick:()=>ge(),disabled:T,className:"px-6 py-2.5 bg-blue-600 text-white text-sm font-medium rounded-xl hover:bg-blue-700 transition-colors shadow-sm disabled:opacity-50 flex items-center gap-2",children:T?e.jsxs(e.Fragment,{children:[e.jsx(is,{className:"h-4 w-4 animate-spin"}),"Sending..."]}):"Submit"})]}),A>0&&AD(Ne=>Ne+1),className:"text-xs text-slate-400 hover:text-slate-500 transition-colors",children:"Skip this step"})})]}),e.jsx("div",{className:"text-center mt-8",children:e.jsxs("div",{className:"flex items-center justify-center gap-1 text-xs text-slate-400",children:[e.jsx(Bi,{className:"h-3 w-3"}),e.jsx("span",{children:"Powered by ReLevelUp"})]})})]})]})}const y8=()=>({trackEngagement:S.useCallback(async(t,r,n,a="view")=>{try{const{data:{user:i}}=await V.auth.getUser();if(!i)return;await V.from("content_engagement_logs").insert({user_id:i.id,resource_type:t,resource_id:r,resource_title:n,action_type:a})}catch(i){console.error("Error tracking engagement:",i)}},[])});function PR({banners:s,autoPlayInterval:t=5e3,className:r}){const[n,a]=S.useState(0),[i,l]=S.useState(!1),{trackEngagement:o}=y8(),c=S.useCallback(x=>{o("newsletter",x.id,x.title,"click_link")},[o]),d=S.useCallback(()=>{a(x=>(x+1)%s.length)},[s.length]),h=S.useCallback(()=>{a(x=>(x-1+s.length)%s.length)},[s.length]),m=S.useCallback(x=>{a(x)},[]);if(S.useEffect(()=>{if(s.length<=1||i)return;const x=setInterval(d,t);return()=>clearInterval(x)},[s.length,i,t,d]),!s||s.length===0)return null;const p=s[n];return e.jsxs("div",{className:Ft("relative w-full overflow-hidden rounded-xl",r),onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),children:[e.jsxs("div",{className:"relative aspect-[21/9] md:aspect-[3/1] w-full",children:[e.jsx("img",{src:p.image_url,alt:p.title,className:"w-full h-full object-cover rounded-t-xl"}),s.length>1&&e.jsxs(e.Fragment,{children:[e.jsx(H,{variant:"ghost",size:"icon",className:Ft("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",i&&"opacity-100"),onClick:h,children:e.jsx(fl,{className:"h-6 w-6"})}),e.jsx(H,{variant:"ghost",size:"icon",className:Ft("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",i&&"opacity-100"),onClick:d,children:e.jsx($a,{className:"h-6 w-6"})})]}),s.length>1&&e.jsx("div",{className:"absolute bottom-3 left-1/2 -translate-x-1/2 flex gap-2",children:s.map((x,y)=>e.jsx("button",{onClick:()=>m(y),className:Ft("w-2 h-2 rounded-full transition-all duration-300",y===n?"bg-white w-6":"bg-white/50 hover:bg-white/70"),"aria-label":`Go to slide ${y+1}`},y))})]}),e.jsxs("div",{className:"bg-foreground rounded-b-xl px-5 py-3 flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("h2",{className:"text-sm md:text-base font-semibold text-background truncate",children:p.title}),p.description&&e.jsx("p",{className:"text-xs text-background/70 truncate",children:p.description})]}),p.link_url&&e.jsx("a",{href:p.link_url,target:"_blank",rel:"noopener noreferrer",className:"shrink-0",onClick:()=>c(p),children:e.jsx(H,{size:"sm",className:"bg-primary text-primary-foreground font-semibold transition-colors hover:bg-background hover:text-foreground",children:p.link_text||"Learn More"})})]})]})}function UVt(s){return"EST"}function g9(s){const r=new Intl.DateTimeFormat("en-US",{hour:"numeric",minute:"2-digit",hour12:!0,timeZone:"America/New_York"}).format(s),n=UVt();return`${r} ${n}`}function oP(s){const t=new Date,r=new Date(s),n=oI(r,-15),a=oI(r,30);return t>a?"ended":s1(t,{start:r,end:a})?"live":s1(t,{start:n,end:r})?"starting_soon":"upcoming"}function xTe(s){const t=oP(s);return t==="starting_soon"||t==="live"}const c9e=xTe,qVt=({events:s,registrations:t,onNavigateToEvents:r})=>{const[n,a]=S.useState(new Date);S.useEffect(()=>{const x=setInterval(()=>{a(new Date)},3e4);return()=>clearInterval(x)},[]);const i=s.filter(x=>xTe(x.event_date));if(i.length===0)return null;const l=i[0],o=oP(l.event_date),c=t.find(x=>x.event_id===l.id),d=(c==null?void 0:c.zoom_join_url)||l.zoom_link,h=!!c,m=o==="live",p=m?{container:"from-red-500/10 via-red-500/5 to-primary/10 border-red-500/30",pulse:"from-red-500/5",indicator:"bg-red-500",text:"text-red-500",button:"bg-red-500 hover:bg-red-600",outlineButton:"border-red-500/50 text-red-500 hover:bg-red-500/10"}:{container:"from-amber-500/10 via-amber-500/5 to-primary/10 border-amber-500/30",pulse:"from-amber-500/5",indicator:"bg-amber-500",text:"text-amber-500",button:"bg-amber-500 hover:bg-amber-600",outlineButton:"border-amber-500/50 text-amber-500 hover:bg-amber-500/10"};return e.jsxs("div",{className:`relative mb-8 overflow-hidden rounded-xl bg-gradient-to-r ${p.container} border`,children:[e.jsx("div",{className:`absolute inset-0 bg-gradient-to-r ${p.pulse} to-transparent animate-pulse`}),e.jsx("div",{className:"relative p-4 sm:p-6",children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"relative flex items-center justify-center",children:[e.jsx("span",{className:`absolute inline-flex h-full w-full animate-ping rounded-full ${p.indicator} opacity-75`}),e.jsx("span",{className:`relative flex h-3 w-3 rounded-full ${p.indicator}`})]}),e.jsx("div",{className:`flex items-center gap-2 ${p.text} font-bold text-sm uppercase tracking-wider`,children:m?e.jsxs(e.Fragment,{children:[e.jsx(G2,{className:"h-4 w-4"}),"Live Now"]}):e.jsxs(e.Fragment,{children:[e.jsx(Pn,{className:"h-4 w-4"}),"Starting Soon"]})})]}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"font-semibold text-lg text-foreground line-clamp-1",children:l.title}),e.jsx("p",{className:"text-sm text-muted-foreground",children:m?`Started at ${g9(new Date(l.event_date))}`:`Starts at ${g9(new Date(l.event_date))}`})]}),e.jsx("div",{className:"flex items-center gap-2",children:h?e.jsxs(H,{onClick:()=>window.open(d,"_blank"),className:`${p.button} text-white gap-2`,children:[e.jsx(gn,{className:"h-4 w-4"}),m?"Join Now":"Join When Live"]}):e.jsxs(H,{variant:"outline",onClick:r,className:`${p.outlineButton} gap-2`,children:[e.jsx(Ar,{className:"h-4 w-4"}),"Register & Join"]})})]})})]})};function VVt(){const{user:s,isBrokerageManager:t}=Ms(),[r,n]=S.useState([]),[a,i]=S.useState([]),[l,o]=S.useState(!1),[c,d]=S.useState(!0),h=t?"brokerage_manager":"agent";S.useEffect(()=>{if(!(s!=null&&s.id)){d(!1);return}m()},[s==null?void 0:s.id,h]);const m=async()=>{if(s!=null&&s.id)try{const{data:E,error:A}=await V.from("onboarding_checklist_items").select("*").eq("target_role",h).eq("is_active",!0).order("sort_order");if(A)throw A;const{data:D,error:R}=await V.from("onboarding_checklist_progress").select("item_id, completed_at").eq("user_id",s.id);if(R)throw R;const{data:z,error:O}=await V.from("onboarding_checklist_dismissed").select("id").eq("user_id",s.id).maybeSingle();if(O)throw O;n(E||[]),i(D||[]),o(!!z),E&&E.length>0&&await p(E,D||[])}catch(E){console.error("Error fetching checklist data:",E)}finally{d(!1)}},p=async(E,A)=>{var ze,Pe;if(!(s!=null&&s.id))return;const D=A.map(Ie=>Ie.item_id),R=E.filter(Ie=>!D.includes(Ie.id));if(R.length===0)return;const[z,O,$,ee,Z,J,K,re,ie,ce,ne,le,be,fe,je]=await Promise.all([V.from("profiles").select("brokerage_id").eq("id",s.id).maybeSingle(),V.from("resource_shares").select("id",{count:"exact",head:!0}).eq("sender_id",s.id),V.from("community_posts").select("id",{count:"exact",head:!0}).eq("user_id",s.id),V.from("event_registrations").select("id",{count:"exact",head:!0}).eq("user_id",s.id),V.from("content_engagement_logs").select("id",{count:"exact",head:!0}).eq("user_id",s.id).eq("resource_type","template"),V.from("content_engagement_logs").select("id",{count:"exact",head:!0}).eq("user_id",s.id).eq("resource_type","academy_video"),V.from("content_engagement_logs").select("id",{count:"exact",head:!0}).eq("user_id",s.id).eq("resource_type","toolbox"),V.from("activity_logs").select("id",{count:"exact",head:!0}).eq("user_id",s.id),V.from("innercircle_contacts").select("id",{count:"exact",head:!0}).eq("owner_user_id",s.id),V.from("agent_videos").select("id",{count:"exact",head:!0}).eq("owner_user_id",s.id),V.from("contact_touch_logs").select("id",{count:"exact",head:!0}).eq("owner_user_id",s.id),V.from("scorecard_transactions").select("id",{count:"exact",head:!0}).eq("owner_user_id",s.id),V.from("listings").select("id",{count:"exact",head:!0}).eq("agent_id",s.id),V.from("innercircle_contacts").select("id").eq("owner_user_id",s.id),V.from("deal_pipeline").select("id",{count:"exact",head:!0}).eq("owner_user_id",s.id)]),ve={},We=(ze=z.data)==null?void 0:ze.brokerage_id;ve.share_resource=(O.count||0)>0,ve.post_community=($.count||0)>0,ve.register_event=(ee.count||0)>0,ve.view_template=(Z.count||0)>0,ve.watch_academy=(J.count||0)>0,ve.use_toolbox=(K.count||0)>0,ve.launch_app=(re.count||0)>0,ve.add_contact=(ie.count||0)>0,ve.create_video=(ce.count||0)>0,ve.complete_touch=(ne.count||0)>0,ve.add_transaction=(le.count||0)>0,ve.add_listing=(be.count||0)>0,ve.add_deal=(je.count||0)>0;const Ve=((Pe=fe.data)==null?void 0:Pe.map(Ie=>Ie.id))||[],Le=[];We?Le.push(V.from("profiles").select("id").eq("brokerage_id",We).neq("id",s.id).then(Ie=>{var De;ve.add_agent=(((De=Ie.data)==null?void 0:De.length)||0)>0})):ve.add_agent=!1,Ve.length>0?(Le.push(V.from("contact_plan_cycles").select("id",{count:"exact",head:!0}).in("contact_id",Ve).then(Ie=>{ve.add_plan=(Ie.count||0)>0})),Le.push(V.from("contact_popby_settings").select("id",{count:"exact",head:!0}).in("contact_id",Ve).then(Ie=>{ve.schedule_popby=(Ie.count||0)>0}))):(ve.add_plan=!1,ve.schedule_popby=!1),await Promise.all(Le);const Me=R.filter(Ie=>ve[Ie.action_type]);if(Me.length>0){const Ie=Me.map(pe=>({user_id:s.id,item_id:pe.id})),{error:De}=await V.from("onboarding_checklist_progress").upsert(Ie,{onConflict:"user_id,item_id",ignoreDuplicates:!0});if(!De){const pe=Me.map(tt=>({item_id:tt.id,completed_at:new Date().toISOString()}));i(tt=>[...tt,...pe])}}},x=async E=>{if(s!=null&&s.id)try{const{error:A}=await V.from("onboarding_checklist_progress").insert({user_id:s.id,item_id:E});if(A)throw A;i(D=>[...D,{item_id:E,completed_at:new Date().toISOString()}])}catch(A){console.error("Error marking item complete:",A)}},y=async()=>{if(s!=null&&s.id)try{const{error:E}=await V.from("onboarding_checklist_dismissed").insert({user_id:s.id});if(E)throw E;o(!0)}catch(E){console.error("Error dismissing checklist:",E)}},_=a.length,b=r.length,j=b>0&&_>=b,k=b>0?_/b*100:0;return{items:r,progress:a,isDismissed:l,loading:c,completedCount:_,totalCount:b,isComplete:j,progressPercentage:k,isItemComplete:E=>a.some(A=>A.item_id===E),markComplete:x,dismiss:y,refetch:m}}const HVt={add_agent:e.jsx(Ar,{className:"h-4 w-4"}),share_resource:e.jsx(cd,{className:"h-4 w-4"}),post_community:e.jsx(Gi,{className:"h-4 w-4"}),register_event:e.jsx(Nn,{className:"h-4 w-4"}),view_template:e.jsx(w2,{className:"h-4 w-4"}),watch_academy:e.jsx(Vu,{className:"h-4 w-4"}),use_toolbox:e.jsx(N1,{className:"h-4 w-4"}),launch_app:e.jsx(KO,{className:"h-4 w-4"}),add_deal:e.jsx(p_,{className:"h-4 w-4"}),add_listing:e.jsx(Fn,{className:"h-4 w-4"})},GVt={add_deal:"/mission-control/pipeline",add_listing:"/mission-control/listings/new",post_community:"/community",add_contact:"/mission-control/contacts"};function WVt(){const{items:s,isDismissed:t,loading:r,completedCount:n,totalCount:a,isComplete:i,progressPercentage:l,isItemComplete:o,markComplete:c,dismiss:d}=VVt(),h=Fr(),[m,p]=S.useState(!0);return r||t||a===0||i?null:e.jsxs(ke,{className:"mb-6 border-primary/20 bg-gradient-to-r from-primary/5 to-transparent",children:[e.jsxs(Ot,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(v_,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(zt,{className:"text-lg",children:"Get Started with LevelUp"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-0.5",children:"Complete these steps to make the most of your membership"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(H,{variant:"ghost",size:"sm",onClick:()=>p(!m),className:"h-8 w-8 p-0",children:m?e.jsx(cx,{className:"h-4 w-4"}):e.jsx(Io,{className:"h-4 w-4"})}),e.jsx(H,{variant:"ghost",size:"sm",onClick:d,className:"h-8 w-8 p-0 text-muted-foreground hover:text-foreground",children:e.jsx(Rr,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"mt-4",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm mb-2",children:[e.jsx("span",{className:"text-muted-foreground",children:"Progress"}),e.jsxs("span",{className:"font-medium",children:[n," of ",a," complete"]})]}),e.jsx(Mi,{value:l,className:"h-2"})]})]}),m&&e.jsx(Oe,{className:"pt-0",children:e.jsx("div",{className:"space-y-3",children:s.map(x=>{const y=o(x.id);return e.jsxs("div",{className:Ft("flex items-start gap-3 p-3 rounded-lg transition-colors",y?"bg-muted/50":"bg-background hover:bg-muted/30 cursor-pointer"),onClick:()=>{if(y)return;const _=GVt[x.action_type];_?h(_):c(x.id)},children:[e.jsx("div",{className:"mt-0.5",children:y?e.jsx(ea,{className:"h-5 w-5 text-primary"}):e.jsx(Gu,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-muted-foreground",children:HVt[x.action_type]||e.jsx(Gu,{className:"h-4 w-4"})}),e.jsx("span",{className:Ft("font-medium",y&&"line-through text-muted-foreground"),children:x.title})]}),x.description&&e.jsx("p",{className:Ft("text-sm text-muted-foreground mt-1",y&&"line-through"),children:x.description})]})]},x.id)})})})]})}const R0=()=>yt({queryKey:["relationship-types"],queryFn:async()=>{const{data:s,error:t}=await V.from("relationship_types").select("*").order("sort_order");if(t)throw t;return s}}),Cp=s=>{const t=ba(),r=1e3,n=async a=>{const i=[];let l=0;for(;;){const{data:o,error:c}=await a.range(l,l+r-1);if(c)throw c;const d=o??[];if(i.push(...d),d.length{let a=V.from("innercircle_contacts").select(` *, lead_source_ref:lead_sources(id, name), tags:innercircle_contact_tags( id, contact_id, relationship_type_id, relationship_type:relationship_types(*) ) `).eq("owner_user_id",t).order("created_at",{ascending:!1}).order("first_name");return await n(a)},enabled:!!t})},KVt=s=>yt({queryKey:["innercircle-contact",s],queryFn:async()=>{const{data:t,error:r}=await V.from("innercircle_contacts").select(` *, lead_source_ref:lead_sources(id, name), tags:innercircle_contact_tags( id, contact_id, relationship_type_id, relationship_type:relationship_types(*) ) `).eq("id",s).maybeSingle();if(r)throw r;return t},enabled:!!s}),uot=()=>{const s=ba();return yt({queryKey:["innercircle-contact-counts",s],queryFn:async()=>{const{data:t,error:r}=await V.from("innercircle_contacts").select(` id, tags:innercircle_contact_tags(relationship_type_id) `);if(r)throw r;const n={};return t==null||t.forEach(a=>{var i;(i=a.tags)==null||i.forEach(l=>{n[l.relationship_type_id]=(n[l.relationship_type_id]||0)+1})}),n},enabled:!!s})},Qge=()=>{const s=ns(),t=ba();return Pt({mutationFn:async r=>{const{tagIds:n,...a}=r,i={...a,birthday:a.birthday||null,home_anniversary:a.home_anniversary||null,owner_user_id:t},{data:l,error:o}=await V.from("innercircle_contacts").insert(i).select().single();if(o)throw o;if(n&&n.length>0){const{error:c}=await V.from("innercircle_contact_tags").insert(n.map(d=>({contact_id:l.id,relationship_type_id:d})));if(c)throw c}return l},onSuccess:()=>{s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact-counts"]}),En({title:"Contact created successfully"})},onError:r=>{En({title:"Error creating contact",description:r.message,variant:"destructive"})}})},yTe=()=>{const s=ns();return Pt({mutationFn:async({id:t,...r})=>{const{tagIds:n,tags:a,...i}=r,l={...i,birthday:i.birthday||null,home_anniversary:i.home_anniversary||null},{data:o,error:c}=await V.from("innercircle_contacts").update(l).eq("id",t).select().single();if(c)throw c;if(n!==void 0&&(await V.from("innercircle_contact_tags").delete().eq("contact_id",t),n.length>0)){const{error:d}=await V.from("innercircle_contact_tags").insert(n.map(h=>({contact_id:t,relationship_type_id:h})));if(d)throw d}return o},onSuccess:()=>{s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact"]}),s.invalidateQueries({queryKey:["innercircle-contact-counts"]}),En({title:"Contact updated successfully"})},onError:t=>{En({title:"Error updating contact",description:t.message,variant:"destructive"})}})},hot=()=>{const s=ns();return Pt({mutationFn:async({contactId:t,spouseContactId:r})=>{if(r){const{error:n}=await V.from("innercircle_contacts").update({spouse_contact_id:r}).eq("id",t);if(n)throw n;const{error:a}=await V.from("innercircle_contacts").update({spouse_contact_id:t}).eq("id",r);if(a)throw a}else{const{data:n}=await V.from("innercircle_contacts").select("spouse_contact_id").eq("id",t).single(),a=n==null?void 0:n.spouse_contact_id,{error:i}=await V.from("innercircle_contacts").update({spouse_contact_id:null}).eq("id",t);if(i)throw i;if(a){const{error:l}=await V.from("innercircle_contacts").update({spouse_contact_id:null}).eq("id",a);if(l)throw l}}},onSuccess:()=>{s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact"]}),s.invalidateQueries({queryKey:["innercircle-contact-spouse"]}),En({title:"Spouse link updated"})},onError:t=>{En({title:"Error linking spouse",description:t.message,variant:"destructive"})}})},vTe=()=>{const s=ns();return Pt({mutationFn:async t=>{const{error:r}=await V.from("innercircle_contacts").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact-counts"]}),En({title:"Contact deleted successfully"})},onError:t=>{En({title:"Error deleting contact",description:t.message,variant:"destructive"})}})},oz=()=>yt({queryKey:["action-types"],queryFn:async()=>{const{data:s,error:t}=await V.from("action_types").select("*").order("sort_order");if(t)throw t;return s}}),YVt=s=>yt({queryKey:["action-scripts",s],queryFn:async()=>{let t=V.from("action_scripts").select("*, action_type:action_types(*)");const{data:r,error:n}=await t;if(n)throw n;return r}}),ZVt=()=>yt({queryKey:["touchpoint-plans"],queryFn:async()=>{const{data:s,error:t}=await V.from("touchpoint_plans").select(` *, items:touchpoint_plan_items( *, action_type:action_types(*), default_script:action_scripts(*) ) `).order("name");if(t)throw t;return s}}),XVt=()=>{const s=ns(),t=ba();return Pt({mutationFn:async({name:r,description:n})=>{const{data:a,error:i}=await V.from("touchpoint_plans").insert({name:r,description:n,owner_user_id:t,active:!0,is_template:!1}).select().single();if(i)throw i;return a},onSuccess:()=>{s.invalidateQueries({queryKey:["touchpoint-plans"]}),En({title:"Plan created successfully"})},onError:r=>{En({title:"Error creating plan",description:r.message,variant:"destructive"})}})},QVt=()=>{const s=ns(),t=ba();return Pt({mutationFn:async({sourcePlanId:r,newName:n})=>{const{data:a,error:i}=await V.from("touchpoint_plans").select(` *, items:touchpoint_plan_items(*) `).eq("id",r).single();if(i)throw i;if(!a)throw new Error("Source plan not found");const{data:l,error:o}=await V.from("touchpoint_plans").insert({name:n,description:a.description,owner_user_id:t,active:!0,is_template:!1}).select().single();if(o)throw o;if(a.items&&a.items.length>0){const c=a.items.map(h=>({plan_id:l.id,month_number:h.month_number,action_type_id:h.action_type_id,default_script_id:h.default_script_id,notes:h.notes})),{error:d}=await V.from("touchpoint_plan_items").insert(c);if(d)throw d}return l},onSuccess:()=>{s.invalidateQueries({queryKey:["touchpoint-plans"]}),En({title:"Plan duplicated successfully",description:"You can now edit your copy of this plan."})},onError:r=>{En({title:"Error duplicating plan",description:r.message,variant:"destructive"})}})},JVt=()=>{const s=ns();return Pt({mutationFn:async({id:t,name:r,description:n})=>{const{data:a,error:i}=await V.from("touchpoint_plans").update({name:r,description:n}).eq("id",t).select().single();if(i)throw i;return a},onSuccess:()=>{s.invalidateQueries({queryKey:["touchpoint-plans"]}),En({title:"Plan updated successfully"})}})},eHt=()=>{const s=ns();return Pt({mutationFn:async t=>{const{error:r}=await V.from("touchpoint_plans").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["touchpoint-plans"]}),En({title:"Plan deleted successfully"})}})},tHt=()=>{const s=ns();return Pt({mutationFn:async({planId:t,items:r})=>{if(await V.from("touchpoint_plan_items").delete().eq("plan_id",t),r.length>0){const{error:n}=await V.from("touchpoint_plan_items").insert(r.map(a=>({plan_id:t,month_number:a.month_number,action_type_id:a.action_type_id,default_script_id:a.default_script_id||null,notes:a.notes})));if(n)throw n}},onSuccess:()=>{s.invalidateQueries({queryKey:["touchpoint-plans"]}),En({title:"Plan schedule updated"})}})},sHt=()=>{const s=ns();return Pt({mutationFn:async({actionTypeId:t,title:r,scriptBody:n,emailSubject:a,tone:i})=>{const{data:{user:l}}=await V.auth.getUser(),{data:o,error:c}=await V.from("action_scripts").insert({action_type_id:t,title:r,script_body:n,email_subject:a||null,tone:i||null,active:!0,user_id:l==null?void 0:l.id}).select().single();if(c)throw c;return o},onSuccess:()=>{s.invalidateQueries({queryKey:["action-scripts"]}),En({title:"Script created successfully"})},onError:t=>{En({title:"Error creating script",description:t.message,variant:"destructive"})}})},rHt=()=>{const s=ba();return yt({queryKey:["user-plan-enrollments",s],queryFn:async()=>{const{data:t,error:r}=await V.from("user_plan_enrollments").select(` *, plan:touchpoint_plans(*), relationship_type:relationship_types(*) `);if(r)throw r;return t},enabled:!!s})},nHt=()=>{const s=ns(),t=ba();return Pt({mutationFn:async({planId:r,relationshipTypeId:n,active:a})=>{const{data:i}=await V.from("user_plan_enrollments").select("id").eq("plan_id",r).eq("relationship_type_id",n).maybeSingle();if(i){const{error:l}=await V.from("user_plan_enrollments").update({active:a}).eq("id",i.id);if(l)throw l}else if(a){const{error:l}=await V.from("user_plan_enrollments").insert({owner_user_id:t,plan_id:r,relationship_type_id:n,active:!0,start_date:new Date().toISOString().split("T")[0]});if(l)throw l}},onSuccess:()=>{s.invalidateQueries({queryKey:["user-plan-enrollments"]}),En({title:"Plan enrollment updated"})}})},lz=(s=7)=>{const t=ba();return yt({queryKey:["contact-touch-logs",t,s],queryFn:async()=>{const r=new Date;r.setDate(r.getDate()-s);const{data:n,error:a}=await V.from("contact_touch_logs").select(` *, contact:innercircle_contacts(*), action_type:action_types(*) `).eq("owner_user_id",t).gte("completed_at",r.toISOString()).order("completed_at",{ascending:!1});if(a)throw a;return n},enabled:!!t})},mot=()=>{const s=ba();return yt({queryKey:["contacts-last-touch",s],queryFn:async()=>{const{data:t,error:r}=await V.from("contact_touch_logs").select("contact_id, completed_at").eq("owner_user_id",s).order("completed_at",{ascending:!1});if(r)throw r;const n={};return t==null||t.forEach(a=>{n[a.contact_id]||(n[a.contact_id]=a.completed_at)}),n},enabled:!!s})},aHt=(s=90)=>{const{data:t}=Cp(),{data:r}=mot();if(!t||!r)return{contacts:[],count:0};const n=new Date;n.setDate(n.getDate()-s);const a=t.filter(i=>{const l=r[i.id];return l?new Date(l){const s=ns(),t=ba();return Pt({mutationFn:async({contactId:r,actionTypeId:n,scriptUsedId:a,notes:i,completedAt:l})=>{const{data:o,error:c}=await V.from("contact_touch_logs").insert({owner_user_id:t,contact_id:r,action_type_id:n,script_used_id:a,notes:i,completed_at:l||new Date().toISOString()}).select().single();if(c)throw c;return o},onSuccess:async(r,n)=>{var a,i;s.invalidateQueries({queryKey:["contact-touch-logs"]}),s.invalidateQueries({queryKey:["contacts-last-touch"]}),s.invalidateQueries({queryKey:["today-actions"]}),En({title:"Action completed!"});try{const[l,o]=await Promise.all([V.from("innercircle_contacts").select("email").eq("id",n.contactId).single(),V.from("action_types").select("name").eq("id",n.actionTypeId).single()]),c=(a=l.data)==null?void 0:a.email,d=((i=o.data)==null?void 0:i.name)||"Touch";c&&V.functions.invoke("boldtrail-sync",{body:{action:"push_touch",contact_email:c,touch_type:d,touch_notes:n.notes||null,touch_date:n.completedAt||r.completed_at}}).catch(()=>{})}catch{}}})},fot="agentos_weekly_touch_goal",d9e=20,rme=()=>{if(typeof window>"u")return d9e;const s=localStorage.getItem(fot);if(s){const t=parseInt(s,10);if(!isNaN(t)&&t>0)return t}return d9e},pot=s=>{localStorage.setItem(fot,s.toString())},bTe=()=>{const{data:s}=lz(7),t=new Date;t.setHours(0,0,0,0);const r=new Date(t);r.setDate(t.getDate()-t.getDay());const n=(s==null?void 0:s.filter(l=>new Date(l.completed_at)>=r).length)||0;let a=0;if(s&&s.length>0){const l=new Set(s.map(c=>new Date(c.completed_at).toDateString()));let o=new Date(t);for(;l.has(o.toDateString());)a++,o.setDate(o.getDate()-1)}const i=rme();return{actionsThisWeek:n,weeklyGoal:i,streak:a,progress:Math.min(n/i*100,100)}},iHt=()=>{const s=ba();return yt({queryKey:["contact-plan-cycles",s],queryFn:async()=>{const{data:t,error:r}=await V.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 t},enabled:!!s})},oHt=()=>{const s=ns();return ba(),Pt({mutationFn:async()=>{const{data:t}=await V.from("user_plan_enrollments").select("*").eq("active",!0);if(!t||t.length===0)return;const{data:r}=await V.from("innercircle_contacts").select(` id, tags:innercircle_contact_tags(relationship_type_id) `);if(!r)return;const{data:n}=await V.from("contact_plan_cycles").select("contact_id, plan_id"),a=new Set((n==null?void 0:n.map(l=>`${l.contact_id}-${l.plan_id}`))||[]),i=[];for(const l of r)for(const o of l.tags||[]){const c=t.find(d=>d.relationship_type_id===o.relationship_type_id);c&&!a.has(`${l.id}-${c.plan_id}`)&&i.push({contact_id:l.id,plan_id:c.plan_id,relationship_type_id:o.relationship_type_id})}if(i.length>0){const{error:l}=await V.from("contact_plan_cycles").insert(i);if(l)throw l}return i.length},onSuccess:t=>{s.invalidateQueries({queryKey:["contact-plan-cycles"]}),t&&t>0&&En({title:`${t} contact(s) enrolled in plans`})}})},got=()=>{const s=ba(),{data:t}=iHt(),{data:r}=lz(30);return yt({queryKey:["today-actions",s,t==null?void 0:t.length,r==null?void 0:r.length],queryFn:async()=>{var y;if(!t||t.length===0)return[];const{data:n}=await V.from("contact_snoozes").select("contact_id").gte("snoozed_until",new Date().toISOString()),a=new Set((n==null?void 0:n.map(_=>_.contact_id))||[]),i=new Date,l=[],o=new Date(i.getFullYear(),i.getMonth(),1),c=new Set((r==null?void 0:r.filter(_=>new Date(_.completed_at)>=o).map(_=>`${_.contact_id}-${_.action_type_id}`))||[]);for(const _ of t){if(!((y=_.plan)!=null&&y.items)||_.plan.items.length===0||!_.contact||a.has(_.contact_id))continue;const b=new Date(_.cycle_start_date),k=Math.floor((i.getTime()-b.getTime())/(30.44*24*60*60*1e3))%12+1,T=_.plan.items.find(E=>E.month_number===k);if(T&&T.action_type){const E=`${_.contact_id}-${T.action_type_id}`;if(!c.has(E)){const{data:A}=await V.from("relationship_types").select("name").eq("id",_.relationship_type_id).single();l.push({contact:_.contact,actionType:T.action_type,script:T.default_script||void 0,planName:_.plan.name,relationshipTypeName:(A==null?void 0:A.name)||"",monthNumber:k})}}}const d=5,h=i.getDate(),m=l.sort((_,b)=>_.contact.first_name.localeCompare(b.contact.first_name)),p=(h-1)%Math.max(1,m.length);return[...m.slice(p),...m.slice(0,p)].slice(0,d)},enabled:!!s&&!!t})};function lHt(){const s=Fr(),{data:t,isLoading:r}=got(),{data:n}=Cp(),a=bTe(),[i,l]=S.useState(rme()),[o,c]=S.useState(""),[d,h]=S.useState(!1);S.useEffect(()=>{l(rme())},[]);const m=()=>{const D=parseInt(o,10);if(isNaN(D)||D<1){En({title:"Invalid goal",description:"Please enter a number greater than 0",variant:"destructive"});return}l(D),pot(D),h(!1),En({title:"Goal updated",description:`Weekly touch goal set to ${D}`})},p=()=>{c(i.toString()),h(!0)},x=jg(new Date),y=Lc(x,7),_=D=>{if(!D)return null;const R=D.split(/[-/T]/);if(R.length<3)return null;const z=parseInt(R[1],10)-1,O=parseInt(R[2],10);return isNaN(z)||isNaN(O)?null:new Date(x.getFullYear(),z,O)},b=(n==null?void 0:n.map(D=>{const R=_(D.birthday),z=_(D.home_anniversary),O=[];return R&&R>=x&&R<=y&&O.push({contact:D,type:"birthday",date:R,isToday:Cc(R,x)}),z&&z>=x&&z<=y&&O.push({contact:D,type:"anniversary",date:z,isToday:Cc(z,x)}),O}).flat().sort((D,R)=>D.date.getTime()-R.date.getTime()).slice(0,3))||[],j=(n==null?void 0:n.filter(D=>{const R=_(D.birthday),z=_(D.home_anniversary);return R&&Cc(R,x)||z&&Cc(z,x)}).length)||0,k=(t==null?void 0:t.length)||0,T=j+k,E=(a==null?void 0:a.actionsThisWeek)||0,A=(a==null?void 0:a.streak)||0;return r?e.jsx(ke,{className:"bg-gradient-to-br from-primary/5 via-primary/10 to-primary/5 border-primary/20",children:e.jsx(Oe,{className:"p-4",children:e.jsxs("div",{className:"animate-pulse flex items-center gap-4",children:[e.jsx("div",{className:"h-12 w-12 bg-primary/20 rounded-lg"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx("div",{className:"h-4 bg-primary/20 rounded w-1/3"}),e.jsx("div",{className:"h-3 bg-primary/10 rounded w-1/2"})]})]})})}):e.jsxs(ke,{className:"bg-gradient-to-br from-primary/5 via-primary/10 to-primary/5 border-primary/20",children:[e.jsxs(Ot,{className:"pb-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(zt,{className:"text-lg flex items-center gap-2",children:[e.jsx(Ar,{className:"h-5 w-5 text-primary"}),"Agent OS"]}),e.jsx("div",{className:"flex items-center gap-2",children:A>0&&e.jsxs(Xe,{variant:"secondary",className:"gap-1 bg-orange-500/10 text-orange-600 border-orange-200",children:[e.jsx(od,{className:"h-3 w-3"}),A," day streak"]})})]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[T>0?e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"text-primary font-medium",children:[T," tasks"]})," for today"]}):"No tasks for today",E>0&&e.jsxs("span",{className:"ml-2",children:["• ",e.jsx("span",{className:"text-emerald-600 font-medium",children:E})," touches this week"]})]})]}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(H,{size:"sm",variant:"outline",className:"gap-1.5",onClick:D=>{D.stopPropagation(),s("/mission-control/contacts?new=true")},children:[e.jsx(Vl,{className:"h-3.5 w-3.5"}),"Add Contact"]}),e.jsxs(H,{size:"sm",variant:"outline",className:"gap-1.5",onClick:D=>{D.stopPropagation(),s("/mission-control")},children:[e.jsx(Yn,{className:"h-3.5 w-3.5"}),"Log Touch"]}),e.jsxs(H,{size:"sm",variant:"outline",className:"gap-1.5 border-emerald-200 text-emerald-700 hover:bg-emerald-50 hover:text-emerald-800",onClick:D=>{D.stopPropagation(),s("/mission-control/video/record")},children:[e.jsx(xn,{className:"h-3.5 w-3.5"}),"Quick Video"]}),e.jsxs(H,{size:"sm",variant:"outline",className:"gap-1.5",onClick:D=>{D.stopPropagation(),s("/mission-control/popbys")},children:[e.jsx(Qa,{className:"h-3.5 w-3.5"}),"Pop-by Map"]}),e.jsxs(H,{size:"sm",variant:"outline",className:"gap-1.5 border-purple-200 text-purple-700 hover:bg-purple-50 hover:text-purple-800",onClick:D=>{D.stopPropagation(),s("/mission-control/pipeline")},children:[e.jsx(p_,{className:"h-3.5 w-3.5"}),"Pipeline"]})]}),e.jsxs("div",{className:"pt-3 border-t border-border/50",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Wu,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-sm font-medium",children:"Weekly Goal"}),e.jsxs(bs,{open:d,onOpenChange:h,children:[e.jsx(Qi,{asChild:!0,children:e.jsx("button",{onClick:p,className:"p-0.5 rounded hover:bg-muted transition-colors","aria-label":"Edit weekly goal",children:e.jsx(Go,{className:"h-3.5 w-3.5 text-muted-foreground hover:text-primary"})})}),e.jsxs(vs,{className:"sm:max-w-[360px]",children:[e.jsxs(Cs,{children:[e.jsx(Ns,{children:"Set Weekly Goal"}),e.jsx(nn,{children:"How many touches do you want to complete each week?"})]}),e.jsxs("div",{className:"space-y-4 pt-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"weekly-goal",children:"Weekly touch goal"}),e.jsx(Se,{id:"weekly-goal",type:"number",min:"1",value:o,onChange:D=>c(D.target.value),placeholder:"20",onKeyDown:D=>{D.key==="Enter"&&m()}})]}),e.jsx(H,{onClick:m,className:"w-full",children:"Save Goal"})]})]})]})]}),e.jsxs("span",{className:"text-sm",children:[e.jsx("span",{className:"font-medium text-primary",children:E}),e.jsxs("span",{className:"text-muted-foreground",children:[" / ",i," touches"]})]})]}),e.jsx(Mi,{value:Math.min(E/i*100,100),className:"h-2 bg-muted [&>div]:bg-primary"}),E>=i&&e.jsxs("p",{className:"text-xs text-emerald-600 mt-1.5 flex items-center gap-1",children:[e.jsx("span",{children:"🎉"})," Goal achieved! Keep the momentum going."]}),E0&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1.5",children:[i-E," more to hit your weekly goal"]})]}),b.length>0&&e.jsxs("div",{className:"pt-3 border-t border-border/50",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(gm,{className:"h-4 w-4 text-pink-500"}),e.jsx("span",{className:"text-sm font-medium",children:"Upcoming Milestones"})]}),e.jsx("div",{className:"space-y-2",children:b.map((D,R)=>e.jsxs("div",{className:`flex items-center justify-between p-2 rounded-lg cursor-pointer transition-colors ${D.isToday?"bg-pink-500/10 hover:bg-pink-500/15":"bg-muted/50 hover:bg-muted"}`,onClick:z=>{z.stopPropagation(),s(`/mission-control/contacts/${D.contact.id}`)},children:[e.jsxs("div",{className:"flex items-center gap-2",children:[D.type==="birthday"?e.jsx(gm,{className:"h-3.5 w-3.5 text-pink-500"}):e.jsx(Fn,{className:"h-3.5 w-3.5 text-blue-500"}),e.jsxs("span",{className:"text-sm",children:[D.contact.first_name," ",D.contact.last_name]}),D.isToday&&e.jsx(Xe,{variant:"secondary",className:"text-[10px] px-1.5 py-0 bg-pink-500/20 text-pink-600",children:"Today!"})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx("span",{children:D.isToday?D.type==="birthday"?"🎂":"🏠":As(D.date,"EEE, MMM d")}),e.jsx($a,{className:"h-3 w-3"})]})]},`${D.contact.id}-${D.type}-${R}`))})]}),e.jsxs(H,{variant:"ghost",size:"sm",className:"w-full gap-1 text-muted-foreground hover:text-primary",onClick:()=>s("/mission-control"),children:["Open Agent OS",e.jsx(bi,{className:"h-4 w-4"})]})]})]})}function cHt(s){return yt({queryKey:["brokerage-content-categories",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await V.from("brokerage_content_categories").select("*").eq("brokerage_id",s).order("sort_order");if(r)throw r;return t},enabled:!!s})}function dHt(s,t){return yt({queryKey:["brokerage-content",s,t],queryFn:async()=>{if(!s)return[];let r=V.from("brokerage_content").select("*, category:brokerage_content_categories(*)").eq("brokerage_id",s).order("created_at",{ascending:!1});t&&(r=r.eq("category_id",t));const{data:n,error:a}=await r;if(a)throw a;return n},enabled:!!s})}function uHt(s,t=4){return yt({queryKey:["brokerage-content-recent",s,t],queryFn:async()=>{if(!s)return[];const{data:r,error:n}=await V.from("brokerage_content").select("*, category:brokerage_content_categories(*)").eq("brokerage_id",s).order("created_at",{ascending:!1}).limit(t);if(n)throw n;return r},enabled:!!s})}function hHt(s){const t=ns();return Pt({mutationFn:async r=>{const{data:n,error:a}=await V.from("brokerage_content").insert(r).select().single();if(a)throw a;return n},onSuccess:()=>{t.invalidateQueries({queryKey:["brokerage-content"]}),t.invalidateQueries({queryKey:["brokerage-content-recent"]})}})}function mHt(){const s=ns();return Pt({mutationFn:async t=>{const{error:r}=await V.from("brokerage_content").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["brokerage-content"]}),s.invalidateQueries({queryKey:["brokerage-content-recent"]})}})}function fHt(s){const t=ns();return Pt({mutationFn:async r=>{const{data:n,error:a}=await V.from("brokerage_content_categories").insert({...r,brokerage_id:s}).select().single();if(a)throw a;return n},onSuccess:()=>{t.invalidateQueries({queryKey:["brokerage-content-categories"]})}})}function pHt(){const s=ns();return Pt({mutationFn:async t=>{const{error:r}=await V.from("brokerage_content_categories").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["brokerage-content-categories"]})}})}function gHt(s){const t=ns();return Pt({mutationFn:async()=>{const r=[{name:"Events",icon:"📅",sort_order:0,is_default:!0,brokerage_id:s},{name:"Videos",icon:"🎥",sort_order:1,is_default:!0,brokerage_id:s},{name:"Documents",icon:"📄",sort_order:2,is_default:!0,brokerage_id:s},{name:"Resources",icon:"🔗",sort_order:3,is_default:!0,brokerage_id:s},{name:"Graphics",icon:"🎨",sort_order:4,is_default:!0,brokerage_id:s}],{error:n}=await V.from("brokerage_content_categories").upsert(r,{onConflict:"brokerage_id,name"});if(n)throw n},onSuccess:()=>{t.invalidateQueries({queryKey:["brokerage-content-categories"]})}})}const xHt={video:El,pdf:kn,link:ql,event:Nn,graphic:pl},yHt={video:"bg-red-500/10 text-red-600 dark:text-red-400",pdf:"bg-blue-500/10 text-blue-600 dark:text-blue-400",link:"bg-green-500/10 text-green-600 dark:text-green-400",event:"bg-purple-500/10 text-purple-600 dark:text-purple-400",graphic:"bg-amber-500/10 text-amber-600 dark:text-amber-400"};function vHt(s){if(!s)return null;try{const t=new URL(s),r=t.hostname.replace("www.","");let n=null;if(r==="youtube.com"||r==="m.youtube.com"?n=t.searchParams.get("v"):r==="youtu.be"&&(n=t.pathname.slice(1)),n)return`https://img.youtube.com/vi/${n}/hqdefault.jpg`}catch{}return null}function bHt(s){if(!s)return!1;try{const t=new URL(s).hostname.replace("www.","");return["youtube.com","youtu.be","m.youtube.com"].includes(t)}catch{return!1}}function _Ht({item:s}){const t=Fr(),r=xHt[s.content_type]||ql,n=yHt[s.content_type]||"",[a,i]=S.useState(null),l=s.thumbnail_url||(s.content_type==="graphic"&&s.file_url?s.file_url:null)||(s.content_type==="video"?vHt(s.url):null);S.useEffect(()=>{l||!s.url||s.content_type!=="video"||!bHt(s.url)||fetch(`https://www.youtube.com/oembed?url=${encodeURIComponent(s.url)}&format=json`).then(c=>c.ok?c.json():null).then(c=>{c!=null&&c.thumbnail_url&&i(c.thumbnail_url)}).catch(()=>{})},[s.url,s.content_type,l]);const o=l||a;return e.jsxs(ke,{className:"group cursor-pointer overflow-hidden transition-all duration-200 hover:shadow-lg hover:border-primary/30",onClick:()=>t(`/brokerage-content/${s.id}`),children:[o?e.jsx("div",{className:"aspect-video bg-muted/50 overflow-hidden",children:e.jsx("img",{src:o,alt:s.title,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300",referrerPolicy:"no-referrer"})}):e.jsx("div",{className:"aspect-video bg-muted/20 flex items-center justify-center",children:e.jsx(r,{className:"h-8 w-8 text-muted-foreground/30"})}),e.jsxs(Oe,{className:"p-3",children:[e.jsx("div",{className:"flex items-center gap-1.5 mb-1.5",children:e.jsxs(Xe,{variant:"secondary",className:`text-[10px] px-1.5 py-0 ${n}`,children:[e.jsx(r,{className:"h-3 w-3 mr-0.5"}),s.content_type]})}),e.jsx("h4",{className:"font-medium text-sm text-foreground truncate group-hover:text-primary transition-colors",children:s.title}),s.content_type==="event"&&s.event_date&&e.jsx("p",{className:"text-xs text-primary mt-1 font-medium",children:As(new Date(s.event_date),"MMM d · h:mm a")})]})]})}function wHt(){const{brokerageId:s}=Ms(),t=Fr(),{data:r=[],isLoading:n}=uHt(s,4);return!s||n||r.length===0?null:e.jsxs("section",{className:"mb-10",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Xa,{className:"h-5 w-5 text-primary"}),e.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Brokerage Content"})]}),e.jsxs(H,{variant:"ghost",size:"sm",onClick:()=>t("/brokerage-content"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",e.jsx(bi,{className:"h-4 w-4"})]})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4",children:r.map(a=>e.jsx(_Ht,{item:a},a.id))})]})}const xot=()=>yt({queryKey:["listing-exchange-enabled"],queryFn:async()=>{const{data:s,error:t}=await V.from("feature_flags").select("enabled").eq("key","listing_exchange_enabled").maybeSingle();if(t)throw t;return(s==null?void 0:s.enabled)??!1}}),yot=s=>{const{user:t,brokerageId:r}=Ms();return yt({queryKey:["listings",s,r],queryFn:async()=>{let n=V.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);s!=null&&s.status&&(n=n.eq("status",s.status)),s!=null&&s.propertyType&&(n=n.eq("property_type",s.propertyType)),s!=null&&s.city&&(n=n.ilike("city",`%${s.city}%`)),s!=null&&s.minPrice&&(n=n.gte("price",s.minPrice)),s!=null&&s.maxPrice&&(n=n.lte("price",s.maxPrice)),s!=null&&s.openToReferrals&&(n=n.eq("open_to_referrals",!0));const{data:a,error:i}=await n;if(i)throw i;let l=a||[];if(r){const{data:o}=await V.from("profiles").select("id").eq("brokerage_id",r);if(o&&o.length>0){const c=o.map(m=>m.id);let d=V.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("share_with_brokerage",!0).eq("is_public",!1).in("agent_id",c);s!=null&&s.status&&(d=d.eq("status",s.status)),s!=null&&s.propertyType&&(d=d.eq("property_type",s.propertyType)),s!=null&&s.city&&(d=d.ilike("city",`%${s.city}%`)),s!=null&&s.minPrice&&(d=d.gte("price",s.minPrice)),s!=null&&s.maxPrice&&(d=d.lte("price",s.maxPrice)),s!=null&&s.openToReferrals&&(d=d.eq("open_to_referrals",!0));const{data:h}=await d;if(h){const m=new Set(l.map(x=>x.id)),p=h.filter(x=>!m.has(x.id));l=[...l,...p]}}}switch(s==null?void 0:s.sortBy){case"updated":l.sort((o,c)=>new Date(c.updated_at).getTime()-new Date(o.updated_at).getTime());break;case"price_asc":l.sort((o,c)=>o.price-c.price);break;case"price_desc":l.sort((o,c)=>c.price-o.price);break;default:l.sort((o,c)=>new Date(c.created_at).getTime()-new Date(o.created_at).getTime())}return l}})},vot=()=>{const{user:s}=Ms();return yt({queryKey:["my-listings",s==null?void 0:s.id],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await V.from("listings").select(` *, photos:listing_photos(*) `).eq("agent_id",s.id).order("created_at",{ascending:!1});if(r)throw r;return t},enabled:!!s})},_Te=s=>{const{user:t}=Ms();return yt({queryKey:["listing",s],queryFn:async()=>{const{data:r,error:n}=await V.from("listings").select(` *, photos:listing_photos(*), agent:profiles!listings_agent_id_fkey(id, name, email, brokerage_id, brokerage:brokerages(name)), video:agent_videos!listings_video_id_fkey(id, playback_url, thumbnail_url, title, duration_seconds) `).eq("id",s).single();if(n)throw n;return t&&await V.from("listing_views").insert({listing_id:s,viewer_id:t.id}),r},enabled:!!s})},jHt=()=>{const s=ns(),{user:t}=Ms();return Pt({mutationFn:async r=>{if(!t)throw new Error("Not authenticated");const{data:n,error:a}=await V.from("listings").insert({...r,agent_id:t.id}).select().single();if(a)throw a;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["listings"]}),s.invalidateQueries({queryKey:["my-listings"]})}})},NHt=()=>{const s=ns();return Pt({mutationFn:async({agentId:t,...r})=>{const{data:n,error:a}=await V.from("listings").insert({...r,agent_id:t}).select().single();if(a)throw a;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["listings"]}),s.invalidateQueries({queryKey:["my-listings"]}),s.invalidateQueries({queryKey:["brokerage-listings"]})}})},kHt=()=>{const s=ns();return Pt({mutationFn:async({id:t,...r})=>{const{data:n,error:a}=await V.from("listings").update(r).eq("id",t).select().single();if(a)throw a;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["listings"]}),s.invalidateQueries({queryKey:["my-listings"]}),s.invalidateQueries({queryKey:["listing",t.id]})}})},bot=()=>{const s=ns();return Pt({mutationFn:async t=>{const{error:r}=await V.from("listings").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["listings"]}),s.invalidateQueries({queryKey:["my-listings"]})}})},SHt=()=>{const s=ns();return Pt({mutationFn:async({listingId:t,photoUrl:r,isPrimary:n=!1})=>{const{data:a,error:i}=await V.from("listing_photos").insert({listing_id:t,photo_url:r,is_primary:n}).select().single();if(i)throw i;return a},onSuccess:t=>{s.invalidateQueries({queryKey:["listing",t.listing_id]}),s.invalidateQueries({queryKey:["my-listings"]})}})},CHt=()=>{const s=ns();return Pt({mutationFn:async({photoId:t,listingId:r})=>{const{error:n}=await V.from("listing_photos").delete().eq("id",t);if(n)throw n;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["listing",t]}),s.invalidateQueries({queryKey:["my-listings"]})}})},THt=()=>{const s=ns();return Pt({mutationFn:async({photos:t})=>{var i;const r=t.map(l=>V.from("listing_photos").update({sort_order:l.sort_order,is_primary:l.is_primary}).eq("id",l.id)),a=(i=(await Promise.all(r)).find(l=>l.error))==null?void 0:i.error;if(a)throw a;return t},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["listing"]}),s.invalidateQueries({queryKey:["my-listings"]})}})},EHt=()=>{const s=ns();return Pt({mutationFn:async({photoId:t,listingId:r})=>{const{error:n}=await V.from("listing_photos").update({is_primary:!1}).eq("listing_id",r);if(n)throw n;const{error:a}=await V.from("listing_photos").update({is_primary:!0}).eq("id",t);if(a)throw a;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["listing",t]}),s.invalidateQueries({queryKey:["my-listings"]})}})},AHt=()=>{const{user:s}=Ms();return yt({queryKey:["saved-listings",s==null?void 0:s.id],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await V.from("listing_saves").select(` *, listing:listings( *, photos:listing_photos(*), agent:profiles!listings_agent_id_fkey(id, name, email, brokerage_id) ) `).eq("agent_id",s.id);if(r)throw r;return t},enabled:!!s})},_ot=()=>{const s=ns(),{user:t}=Ms();return Pt({mutationFn:async r=>{if(!t)throw new Error("Not authenticated");const{data:n}=await V.from("listing_saves").select("id").eq("listing_id",r).eq("agent_id",t.id).maybeSingle();return n?(await V.from("listing_saves").delete().eq("id",n.id),{saved:!1}):(await V.from("listing_saves").insert({listing_id:r,agent_id:t.id}),{saved:!0})},onSuccess:()=>{s.invalidateQueries({queryKey:["saved-listings"]}),s.invalidateQueries({queryKey:["listings"]})}})},wot=s=>{const{user:t}=Ms();return yt({queryKey:["listing-saved",s,t==null?void 0:t.id],queryFn:async()=>{if(!t)return!1;const{data:r}=await V.from("listing_saves").select("id").eq("listing_id",s).eq("agent_id",t.id).maybeSingle();return!!r},enabled:!!t&&!!s})},MHt=()=>{const s=ns(),{user:t}=Ms();return Pt({mutationFn:async r=>{if(!t)throw new Error("Not authenticated");const{data:n}=await V.from("listing_follows").select("id").eq("listing_id",r).eq("agent_id",t.id).maybeSingle();return n?(await V.from("listing_follows").delete().eq("id",n.id),{following:!1}):(await V.from("listing_follows").insert({listing_id:r,agent_id:t.id}),{following:!0})},onSuccess:()=>{s.invalidateQueries({queryKey:["listing-following"]})}})},IHt=s=>{const{user:t}=Ms();return yt({queryKey:["listing-following",s,t==null?void 0:t.id],queryFn:async()=>{if(!t)return!1;const{data:r}=await V.from("listing_follows").select("id").eq("listing_id",s).eq("agent_id",t.id).maybeSingle();return!!r},enabled:!!t&&!!s})},PHt=()=>{const{user:s}=Ms();return Pt({mutationFn:async({listingId:t,shareType:r})=>{if(!s)throw new Error("Not authenticated");const{error:n}=await V.from("listing_shares").insert({listing_id:t,sharing_agent_id:s.id,share_type:r});if(n)throw n}})},LHt=()=>{const{user:s}=Ms();return yt({queryKey:["my-referrals",s==null?void 0:s.id],queryFn:async()=>{if(!s)return{sent:[],received:[]};const[t,r]=await Promise.all([V.from("listing_referrals").select(` *, listing:listings(*,photos:listing_photos(*)) `).eq("sender_agent_id",s.id).order("created_at",{ascending:!1}),V.from("listing_referrals").select(` *, sender:profiles!listing_referrals_sender_agent_id_fkey(id, name, email), listing:listings(*,photos:listing_photos(*)) `).eq("listing_agent_id",s.id).order("created_at",{ascending:!1})]);return{sent:t.data||[],received:r.data||[]}},enabled:!!s})},DHt=()=>{const s=ns(),{user:t}=Ms();return Pt({mutationFn:async({listingId:r,listingAgentId:n,buyerName:a,buyerType:i,notes:l})=>{if(!t)throw new Error("Not authenticated");const{data:o,error:c}=await V.from("listing_referrals").insert({listing_id:r,sender_agent_id:t.id,listing_agent_id:n,buyer_name:a,buyer_type:i,notes:l}).select().single();if(c)throw c;return o},onSuccess:()=>{s.invalidateQueries({queryKey:["my-referrals"]})}})},RHt=()=>yt({queryKey:["listing-leaderboard"],queryFn:async()=>{const{data:s}=await V.from("listing_shares").select("sharing_agent_id, profiles!listing_shares_agent_id_fkey(name)").order("created_at",{ascending:!1}),t=new Map;s==null||s.forEach(l=>{var d;const o=l.sharing_agent_id;if(!o)return;const c=t.get(o);c?c.count++:t.set(o,{name:((d=l.profiles)==null?void 0:d.name)||"Unknown",count:1})});const r=Array.from(t.entries()).map(([l,o])=>({agentId:l,...o})).sort((l,o)=>o.count-l.count).slice(0,10),{data:n}=await V.from("listings").select("agent_id, agent:profiles!listings_agent_id_fkey(name)").eq("is_approved",!0),a=new Map;n==null||n.forEach(l=>{var c;const o=a.get(l.agent_id);o?o.count++:a.set(l.agent_id,{name:((c=l.agent)==null?void 0:c.name)||"Unknown",count:1})});const i=Array.from(a.entries()).map(([l,o])=>({agentId:l,...o})).sort((l,o)=>o.count-l.count).slice(0,10);return{topSharers:r,topListers:i}}}),OHt=()=>{const{user:s,brokerageId:t}=Ms();return yt({queryKey:["brokerage-listings",t],queryFn:async()=>{if(!s||!t)return[];const{data:r}=await V.from("profiles").select("id").eq("brokerage_id",t);if(!r||r.length===0)return[];const n=r.map(l=>l.id),{data:a,error:i}=await V.from("listings").select(` *, photos:listing_photos(*), agent:profiles!listings_agent_id_fkey(id, name, email, brokerage_id, brokerage:brokerages(name)) `).in("agent_id",n).eq("is_approved",!0).order("created_at",{ascending:!1});if(i)throw i;return a},enabled:!!s&&!!t})},jot=({className:s,variant:t="default"})=>e.jsx(Xe,{variant:"outline",className:Ft("text-[10px] font-semibold uppercase tracking-wide px-1.5 py-0 h-4",t==="default"?"border-amber-500 text-amber-600 dark:text-amber-400 bg-amber-500/10":"border-muted-foreground/30 text-muted-foreground",s),children:"Beta"}),FHt={coming_soon:"bg-amber-500/10 text-amber-600 border-amber-200",office_exclusive:"bg-indigo-500/10 text-indigo-600 border-indigo-200",pre_market:"bg-cyan-500/10 text-cyan-600 border-cyan-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"},BHt={coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",active:"Active",under_contract:"Under Contract",sold:"Sold",withdrawn:"Withdrawn"};function zHt(s){return s>=1e6?`$${(s/1e6).toFixed(1)}M`:`$${(s/1e3).toFixed(0)}K`}function $Ht(){const s=Fr(),{data:t,isLoading:r}=xot(),{data:n,isLoading:a}=yot({status:void 0,propertyType:void 0,sortBy:"newest"}),i=(n==null?void 0:n.filter(h=>h.is_approved&&h.is_public))||[],l=i.filter(h=>h.is_featured),o=i.filter(h=>!h.is_featured),c=[...l,...o].slice(0,6),d=r||a;return!d&&!t?null:d?e.jsx(ke,{className:"bg-gradient-to-br from-emerald-500/5 via-emerald-500/10 to-emerald-500/5 border-emerald-500/20",children:e.jsx(Oe,{className:"p-4",children:e.jsxs("div",{className:"animate-pulse flex items-center gap-4",children:[e.jsx("div",{className:"h-12 w-12 bg-emerald-500/20 rounded-lg"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx("div",{className:"h-4 bg-emerald-500/20 rounded w-1/3"}),e.jsx("div",{className:"h-3 bg-emerald-500/10 rounded w-1/2"})]})]})})}):e.jsxs("section",{className:"mb-10",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Listing Exchange"}),e.jsx(jot,{})]}),e.jsxs(H,{variant:"ghost",size:"sm",onClick:()=>s("/mission-control/listings"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",e.jsx(bi,{className:"h-4 w-4"})]})]}),c.length===0?e.jsx(ke,{className:"bg-muted/30 border-dashed",children:e.jsx(Oe,{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Fn,{className:"h-8 w-8 text-muted-foreground/50 mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No listings available yet"}),e.jsx(H,{variant:"link",size:"sm",onClick:()=>s("/mission-control/listings/new"),className:"mt-2",children:"Add the first listing"})]})})}):e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-3",children:c.map(h=>{var p,x;const m=((p=h.photos)==null?void 0:p.find(y=>y.is_primary))||((x=h.photos)==null?void 0:x[0]);return e.jsxs("div",{onClick:()=>s(`/mission-control/listings/${h.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:[e.jsxs("div",{className:"aspect-[4/3] bg-muted/50 overflow-hidden relative",children:[m!=null&&m.photo_url?e.jsx("img",{src:m.photo_url,alt:`${h.city}, ${h.state}`,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(Fn,{className:"h-8 w-8 text-muted-foreground/50"})}),h.is_featured&&e.jsx("div",{className:"absolute top-1.5 left-1.5",children:e.jsxs(Xe,{className:"gap-1 bg-amber-500 text-white border-0 text-[10px] px-1.5 py-0.5",children:[e.jsx(ya,{className:"h-2.5 w-2.5 fill-current"}),"Featured"]})}),e.jsx("div",{className:"absolute top-1.5 right-1.5",children:e.jsx(Xe,{className:`text-[10px] px-1.5 py-0.5 ${FHt[h.status]}`,children:BHt[h.status]})})]}),e.jsxs("div",{className:"p-2",children:[e.jsx("p",{className:"font-bold text-sm text-foreground",children:zHt(h.price)}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[h.city,", ",h.state]}),(h.bedrooms||h.bathrooms)&&e.jsxs("p",{className:"text-[10px] text-muted-foreground mt-0.5",children:[h.bedrooms&&`${h.bedrooms} bed`,h.bedrooms&&h.bathrooms&&" · ",h.bathrooms&&`${h.bathrooms} bath`]})]})]},h.id)})})]})}function Not(s=10,t){return yt({queryKey:["event-leaderboard",s,t],queryFn:async()=>{const{data:r}=await V.from("user_roles").select("user_id").eq("role","admin"),n=new Set((r==null?void 0:r.map(p=>p.user_id))||[]);let a=null;if(t){const{data:p}=await V.from("profiles").select("id").eq("brokerage_id",t);a=new Set((p==null?void 0:p.map(x=>x.id))||[])}const{data:i,error:l}=await V.from("agent_attendance_stats").select("user_id, total_points, total_events_attended, current_streak").order("total_points",{ascending:!1}).limit(s+n.size+50);if(l)throw l;if(!i||i.length===0)return[];let o=i.filter(p=>!n.has(p.user_id));a&&(o=o.filter(p=>a.has(p.user_id)));const c=o.slice(0,s),d=c.map(p=>p.user_id),{data:h}=await V.from("profiles").select("id, name").in("id",d),m=new Map((h==null?void 0:h.map(p=>[p.id,{name:p.name}]))||[]);return c.map(p=>({user_id:p.user_id,total_points:p.total_points,total_events_attended:p.total_events_attended,current_streak:p.current_streak,profile:m.get(p.user_id)||null}))}})}function kot(s){return yt({queryKey:["user-attendance-stats",s],queryFn:async()=>{if(!s)return null;const{data:t,error:r}=await V.from("agent_attendance_stats").select("*").eq("user_id",s).single();if(r&&r.code!=="PGRST116")throw r;return t},enabled:!!s})}function Sot(s){return yt({queryKey:["user-badges",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await V.from("agent_badges").select("*").eq("user_id",s).order("earned_at",{ascending:!1});if(r)throw r;return t},enabled:!!s})}function Cot(s,t){return yt({queryKey:["user-rank",s,t],queryFn:async()=>{if(!s)return null;const{data:r}=await V.from("agent_attendance_stats").select("total_points").eq("user_id",s).single();if(!r)return null;const{data:n}=await V.from("user_roles").select("user_id").eq("role","admin"),a=new Set((n==null?void 0:n.map(c=>c.user_id))||[]),{data:i,error:l}=await V.from("agent_attendance_stats").select("user_id, total_points").gt("total_points",r.total_points);if(l)throw l;let o=(i==null?void 0:i.filter(c=>!a.has(c.user_id)))||[];if(t){const{data:c}=await V.from("profiles").select("id").eq("brokerage_id",t),d=new Set((c==null?void 0:c.map(h=>h.id))||[]);o=o.filter(h=>d.has(h.user_id))}return o.length+1},enabled:!!s})}function UHt(){const{user:s,brokerageId:t,isAdmin:r}=Ms();Fr();const n=!!t,[a,i]=S.useState("brokerage"),l=()=>{if(r)return null;if(n)return a==="global"?null:t},{data:o,isLoading:c}=Not(5,l()),{data:d}=kot(s==null?void 0:s.id),{data:h}=Cot(s==null?void 0:s.id,l()),{data:m}=Sot(s==null?void 0:s.id),p=r||n,x=()=>r?"Agent Leaderboard":n?a==="global"?"All LevelUp":"My Brokerage":"My Points";if(c)return e.jsxs(ke,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsxs(zt,{className:"text-base flex items-center gap-2",children:[e.jsx(To,{className:"h-4 w-4 text-yellow-500"}),x()]})}),e.jsx(Oe,{children:e.jsx("div",{className:"space-y-2",children:[...Array(p?5:3)].map((_,b)=>e.jsx(Ks,{className:"h-10 w-full"},b))})})]});const y=_=>_===0?e.jsx(To,{className:"h-4 w-4 text-yellow-500 mx-auto"}):_===1?e.jsx("span",{className:"text-sm font-medium text-gray-400",children:"2"}):_===2?e.jsx("span",{className:"text-sm font-medium text-amber-600",children:"3"}):e.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:_+1});if(p){const _=(o==null?void 0:o.slice(0,5))||[];return e.jsxs(ke,{children:[e.jsxs(Ot,{className:"pb-2",children:[e.jsxs(zt,{className:"text-base flex items-center gap-2",children:[e.jsx(To,{className:"h-4 w-4 text-yellow-500"}),x()]}),!r&&n&&e.jsxs("div",{className:"flex gap-1 mt-2",children:[e.jsx(H,{variant:a==="brokerage"?"default":"outline",size:"sm",className:"text-xs h-7 flex-1",onClick:()=>i("brokerage"),children:"My Brokerage"}),e.jsx(H,{variant:a==="global"?"default":"outline",size:"sm",className:"text-xs h-7 flex-1",onClick:()=>i("global"),children:"All LevelUp"})]})]}),e.jsxs(Oe,{children:[!r&&d&&e.jsx("div",{className:"mb-3 p-2 rounded-lg bg-primary/5 border border-primary/10",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Your Rank:"}),e.jsxs("span",{className:"font-bold text-primary",children:["#",h||"-"]})]}),e.jsxs("div",{className:"flex items-center gap-3 text-sm",children:[e.jsxs("span",{children:[e.jsx("strong",{className:"text-primary",children:d.total_points})," pts"]}),e.jsxs("span",{children:[e.jsx("strong",{children:d.total_events_attended})," events"]})]})]})}),e.jsxs("div",{className:"space-y-2",children:[_.map((b,j)=>{var k,T,E;return e.jsxs("div",{className:`flex items-center gap-2 p-2 rounded-lg ${b.user_id===(s==null?void 0:s.id)?"bg-primary/10 border border-primary/20":j===0?"bg-yellow-500/10":""}`,children:[e.jsx("div",{className:"w-5 text-center",children:y(j)}),e.jsx(Un,{className:"h-6 w-6",children:e.jsx(qn,{className:"text-xs",children:((T=(k=b.profile)==null?void 0:k.name)==null?void 0:T.charAt(0))||"?"})}),e.jsx("span",{className:"flex-1 text-sm font-medium truncate",children:((E=b.profile)==null?void 0:E.name)||"Unknown"}),e.jsx("span",{className:"text-sm font-bold text-primary",children:b.total_points})]},b.user_id)}),_.length===0&&e.jsx("div",{className:"text-center text-muted-foreground py-2 text-sm",children:"No data yet"})]}),e.jsxs(Xn,{to:"/reward-store",className:"mt-3 flex items-center justify-center gap-2 p-2 rounded-lg bg-primary/5 hover:bg-primary/10 transition-colors text-sm font-medium text-primary",children:[e.jsx(Di,{className:"h-4 w-4"}),"Spend Points in Reward Store",e.jsx($a,{className:"h-4 w-4"})]})]})]})}return e.jsxs(ke,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsxs(zt,{className:"text-base flex items-center gap-2",children:[e.jsx(To,{className:"h-4 w-4 text-yellow-500"}),"My Points"]})}),e.jsx(Oe,{children:d?e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"p-3 rounded-lg bg-primary/5 border border-primary/10 text-center",children:[e.jsx("div",{className:"text-2xl font-bold text-primary",children:d.total_points}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Total Points"})]}),e.jsxs("div",{className:"p-3 rounded-lg bg-muted/50 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:d.total_events_attended}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Events Attended"})]})]}),e.jsxs("div",{className:"flex items-center justify-between p-2 rounded-lg bg-orange-500/10 border border-orange-500/20",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(od,{className:"h-4 w-4 text-orange-500"}),e.jsx("span",{className:"text-sm font-medium",children:"Current Streak"})]}),e.jsxs("span",{className:"font-bold text-orange-500",children:[d.current_streak," 🔥"]})]}),m&&m.length>0&&e.jsxs("div",{className:"pt-2 border-t",children:[e.jsxs("div",{className:"flex items-center gap-1 mb-2",children:[e.jsx(Bc,{className:"h-3 w-3 text-muted-foreground"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Badges"})]}),e.jsxs("div",{className:"flex flex-wrap gap-1",children:[m.slice(0,4).map(_=>e.jsx("span",{className:"text-xs px-2 py-1 rounded-full bg-yellow-500/10 text-yellow-600 border border-yellow-500/20",children:_.badge_name},_.id)),m.length>4&&e.jsxs("span",{className:"text-xs text-muted-foreground px-2 py-1",children:["+",m.length-4," more"]})]})]}),e.jsxs(Xn,{to:"/reward-store",className:"mt-3 flex items-center justify-center gap-2 p-2 rounded-lg bg-primary/5 hover:bg-primary/10 transition-colors text-sm font-medium text-primary",children:[e.jsx(Di,{className:"h-4 w-4"}),"Spend Points in Reward Store",e.jsx($a,{className:"h-4 w-4"})]})]}):e.jsxs("div",{className:"text-center text-muted-foreground py-4 text-sm",children:[e.jsx(ya,{className:"h-8 w-8 mx-auto mb-2 text-muted-foreground/50"}),e.jsx("p",{children:"Attend events to earn points!"}),e.jsxs(Xn,{to:"/reward-store",className:"mt-3 inline-flex items-center gap-2 p-2 rounded-lg bg-primary/5 hover:bg-primary/10 transition-colors text-sm font-medium text-primary",children:[e.jsx(Di,{className:"h-4 w-4"}),"Visit Reward Store",e.jsx($a,{className:"h-4 w-4"})]})]})})]})}const v8=()=>yt({queryKey:["lead-sources"],queryFn:async()=>{const{data:s,error:t}=await V.from("lead_sources").select("*").eq("is_active",!0).order("sort_order");if(t)throw t;return s}}),wTe=()=>{const s=ns(),{user:t}=Ms();return Pt({mutationFn:async r=>{const{data:n}=await V.from("lead_sources").select("id, name").eq("is_active",!0).ilike("name",r.trim()),a=(n||[]).find(o=>o.name.toLowerCase()===r.trim().toLowerCase()&&!0);if(a)throw new Error(`Lead source "${a.name}" already exists`);const{data:i,error:l}=await V.from("lead_sources").insert({name:r,owner_user_id:t==null?void 0:t.id,sort_order:100}).select().single();if(l)throw l;return i},onSuccess:()=>{s.invalidateQueries({queryKey:["lead-sources"]}),he.success("Lead source added")},onError:r=>{he.error("Failed to add lead source"),console.error(r)}})},qHt=()=>{const s=ns();return Pt({mutationFn:async({id:t,name:r})=>{const{error:n}=await V.from("lead_sources").update({name:r}).eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["lead-sources"]}),he.success("Lead source updated")},onError:t=>{he.error(t.message||"Failed to update lead source")}})},VHt=()=>{const s=ns();return Pt({mutationFn:async t=>{const{error:r}=await V.from("lead_sources").update({is_active:!1}).eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["lead-sources"]}),he.success("Lead source removed")},onError:t=>{he.error(t.message||"Failed to remove lead source")}})},jTe=(s,t)=>{const{user:r,isAdmin:n}=Ms(),a=n&&t?t:r==null?void 0:r.id;return yt({queryKey:["scorecard-transactions",s,a],queryFn:async()=>{let i=V.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",a).order("close_date",{ascending:!1});s&&(i=i.gte("close_date",`${s}-01-01`).lte("close_date",`${s}-12-31`));const{data:l,error:o}=await i;if(o)throw o;return l},enabled:!!a})},NTe=s=>{const{user:t,isAdmin:r}=Ms(),n=r&&s?s:t==null?void 0:t.id;return yt({queryKey:["scorecard-transactions-all",n],queryFn:async()=>{const{data:a,error:i}=await V.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(i)throw i;return a},enabled:!!n})},exe=()=>{const s=ns(),{user:t}=Ms();return Pt({mutationFn:async r=>{const{data:n,error:a}=await V.from("scorecard_transactions").insert({...r,owner_user_id:t.id}).select().single();if(a)throw a;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["scorecard-transactions"]}),s.invalidateQueries({queryKey:["scorecard-transactions-all"]}),he.success("Transaction added")},onError:r=>{he.error("Failed to add transaction"),console.error(r)}})},HHt=()=>{const s=ns();return Pt({mutationFn:async({id:t,...r})=>{const{data:n,error:a}=await V.from("scorecard_transactions").update(r).eq("id",t).select().single();if(a)throw a;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["scorecard-transactions"]}),s.invalidateQueries({queryKey:["scorecard-transactions-all"]}),he.success("Transaction updated")},onError:t=>{he.error("Failed to update transaction"),console.error(t)}})},GHt=()=>{const s=ns();return Pt({mutationFn:async t=>{const{error:r}=await V.from("scorecard_transactions").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["scorecard-transactions"]}),s.invalidateQueries({queryKey:["scorecard-transactions-all"]}),he.success("Transaction deleted")},onError:t=>{he.error("Failed to delete transaction"),console.error(t)}})},Tot=(s,t)=>{const{user:r,isAdmin:n}=Ms(),a=n&&t?t:r==null?void 0:r.id;return yt({queryKey:["scorecard-goals",s,a],queryFn:async()=>{const{data:i,error:l}=await V.from("scorecard_goals").select("*").eq("owner_user_id",a).eq("year",s).maybeSingle();if(l)throw l;return i},enabled:!!a})},WHt=()=>{const s=ns(),{user:t}=Ms();return Pt({mutationFn:async r=>{const{data:n,error:a}=await V.from("scorecard_goals").upsert({...r,owner_user_id:t.id},{onConflict:"owner_user_id,year"}).select().single();if(a)throw a;return n},onSuccess:(r,n)=>{s.invalidateQueries({queryKey:["scorecard-goals",n.year]}),he.success("Goals saved")},onError:r=>{he.error("Failed to save goals"),console.error(r)}})},txe=()=>{const{user:s}=Ms();return yt({queryKey:["scorecard-settings",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:r}=await V.from("scorecard_settings").select("*").eq("user_id",s.id).maybeSingle();if(r)throw r;return t},enabled:!!(s!=null&&s.id)})},KHt=()=>{const s=ns(),{user:t}=Ms();return Pt({mutationFn:async r=>{const{data:n,error:a}=await V.from("scorecard_settings").upsert({...r,user_id:t.id},{onConflict:"user_id"}).select().single();if(a)throw a;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["scorecard-settings"]}),he.success("Settings saved")},onError:r=>{he.error("Failed to save settings"),console.error(r)}})},Eot=(s,t)=>{const{data:r,isLoading:n}=jTe(s,t),{data:a,isLoading:i}=NTe(t),{data:l}=txe(),o=(l==null?void 0:l.show_commission)??!0,c=d=>{if(!d||d.length===0)return{totalTransactions:0,buyerCount:0,sellerCount:0,totalVolume:0,averagePrice:0,totalCommission:0,totalNetToAgent:0,topLeadSource:null,transactionsByMonth:[],leadSourceBreakdown:[]};const h=d.filter(A=>A.transaction_type==="buyer").length,m=d.filter(A=>A.transaction_type==="seller").length,p=d.reduce((A,D)=>A+Number(D.sale_price),0),x=d.reduce((A,D)=>A+(Number(D.commission_amount)||0),0),y=d.reduce((A,D)=>{const R=Number(D.commission_amount)||0;if(!R)return A;let z=R;return D.brokerage_split_pct&&(z-=R*(D.brokerage_split_pct/100)),D.team_split_pct&&(z-=R*(D.team_split_pct/100)),D.franchise_fee_pct&&(z-=R*(D.franchise_fee_pct/100)),D.referral_fee_pct&&(z-=R*(D.referral_fee_pct/100)),D.transaction_fee&&(z-=D.transaction_fee),A+Math.max(0,z)},0),_={};d.forEach(A=>{var R;const D=((R=A.lead_source)==null?void 0:R.name)||"Unknown";_[D]=(_[D]||0)+1});const b=Object.entries(_).map(([A,D])=>({name:A,count:D})).sort((A,D)=>D.count-A.count),j=b[0]||null,k={};d.forEach(A=>{const D=Tc(A.close_date).toLocaleString("default",{month:"short"});k[D]=(k[D]||0)+1});const E=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"].map(A=>({month:A,count:k[A]||0}));return{totalTransactions:d.length,buyerCount:h,sellerCount:m,totalVolume:p,averagePrice:d.length>0?p/d.length:0,totalCommission:o?x:0,totalNetToAgent:o?y:0,topLeadSource:j,transactionsByMonth:E,leadSourceBreakdown:b}};return{yearStats:c(r),lifetimeStats:c(a),isLoading:n||i,showCommission:o}},YHt=()=>{const{isAdmin:s}=Ms();return yt({queryKey:["agents-with-transactions"],queryFn:async()=>{const{data:t,error:r}=await V.from("scorecard_transactions").select("owner_user_id").order("owner_user_id");if(r)throw r;const n=[...new Set(t.map(l=>l.owner_user_id))],{data:a,error:i}=await V.from("profiles").select("id, name, email").in("id",n);if(i)throw i;return a},enabled:s})},UN={recency:40,touchpoints:30,transactions:20,referrals:10},u9e={warm:70,cooling:40};function ZHt(s){return s===null?0:s<=14?UN.recency:s<=30?UN.recency*.85:s<=60?UN.recency*.65:s<=90?UN.recency*.4:s<=180?UN.recency*.2:UN.recency*.05}function XHt(s){const t=Math.min(s/12,1);return Math.round(UN.touchpoints*t)}function QHt(s){return s?UN.transactions:0}function JHt(){return 0}function eGt(s){return s>=u9e.warm?"warm":s>=u9e.cooling?"cooling":"at-risk"}function sxe(){const{data:s,isLoading:t}=Cp(),{data:r}=mot(),{data:n}=lz(365),{data:a}=NTe(),i=S.useMemo(()=>{if(!s)return[];const o=new Date,c=RT(o,12),d={};n==null||n.forEach(m=>{new Date(m.completed_at)>=c&&(d[m.contact_id]=(d[m.contact_id]||0)+1)});const h=new Set((a==null?void 0:a.filter(m=>m.contact_id).map(m=>m.contact_id))||[]);return s.map(m=>{const p=(r==null?void 0:r[m.id])||null,x=p?Jy(o,new Date(p)):null,y=d[m.id]||0,_=h.has(m.id),b=ZHt(x),j=XHt(y),k=QHt(_),T=JHt(),E=Math.round(b+j+k+T),A={score:E,status:eGt(E),breakdown:{recency:Math.round(b),touchpoints:Math.round(j),transactions:Math.round(k),referrals:Math.round(T)},lastTouchDate:p,daysSinceTouch:x,touchCountLast12Months:y,hasTransaction:_};return{...m,relationshipScore:A}})},[s,r,n,a]),l=S.useMemo(()=>{const o=i.filter(p=>p.relationshipScore.status==="warm").length,c=i.filter(p=>p.relationshipScore.status==="cooling").length,d=i.filter(p=>p.relationshipScore.status==="at-risk").length,h=i.length,m=h>0?Math.round(i.reduce((p,x)=>p+x.relationshipScore.score,0)/h):0;return{warm:o,cooling:c,atRisk:d,total:h,averageScore:m}},[i]);return{contactsWithScores:i,stats:l,isLoading:t}}function Aot(){const s=Fr(),{stats:t,contactsWithScores:r,isLoading:n}=sxe();if(n)return e.jsxs(ke,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsx(Ks,{className:"h-5 w-40"})}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsx(Ks,{className:"h-20 w-full"}),e.jsx(Ks,{className:"h-16 w-full"})]})]});if(t.total===0)return e.jsxs(ke,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsxs(zt,{className:"text-lg flex items-center gap-2",children:[e.jsx(Ar,{className:"h-5 w-5"}),"Relationship Health"]})}),e.jsxs(Oe,{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Add contacts to see your relationship health scores."}),e.jsx(H,{variant:"outline",size:"sm",className:"mt-3",onClick:()=>s("/mission-control/contacts?new=true"),children:"Add Your First Contact"})]})]});const a=Math.round(t.warm/t.total*100),i=Math.round(t.cooling/t.total*100),l=Math.round(t.atRisk/t.total*100),o=r.filter(c=>c.relationshipScore.status==="at-risk").sort((c,d)=>c.relationshipScore.score-d.relationshipScore.score).slice(0,3);return e.jsxs(ke,{children:[e.jsxs(Ot,{className:"pb-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(zt,{className:"text-lg flex items-center gap-2",children:[e.jsx(al,{className:"h-5 w-5 text-emerald-500"}),"Relationship Health"]}),e.jsx("span",{className:"text-2xl font-bold",children:t.averageScore})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Average score across ",t.total," contacts"]})]}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-emerald-500"}),e.jsx("span",{children:"Warm"})]}),e.jsxs("span",{className:"font-medium",children:[t.warm," (",a,"%)"]})]}),e.jsx(Mi,{value:a,className:"h-2 bg-muted [&>div]:bg-emerald-500"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-amber-500"}),e.jsx("span",{children:"Cooling Off"})]}),e.jsxs("span",{className:"font-medium",children:[t.cooling," (",i,"%)"]})]}),e.jsx(Mi,{value:i,className:"h-2 bg-muted [&>div]:bg-amber-500"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-red-500"}),e.jsx("span",{children:"At Risk"})]}),e.jsxs("span",{className:"font-medium",children:[t.atRisk," (",l,"%)"]})]}),e.jsx(Mi,{value:l,className:"h-2 bg-muted [&>div]:bg-red-500"})]})]}),o.length>0&&e.jsxs("div",{className:"pt-3 border-t",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(K2,{className:"h-4 w-4 text-red-500"}),e.jsx("span",{className:"text-sm font-medium",children:"Needs Attention"})]}),e.jsx("div",{className:"space-y-2",children:o.map(c=>e.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:()=>s(`/mission-control/contacts/${c.id}`),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-red-500"}),e.jsxs("span",{className:"text-sm",children:[c.first_name," ",c.last_name]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx("span",{children:c.relationshipScore.daysSinceTouch===null?"Never":`${c.relationshipScore.daysSinceTouch}d`}),e.jsx($a,{className:"h-3 w-3"})]})]},c.id))})]}),e.jsxs(H,{variant:"outline",size:"sm",className:"w-full",onClick:()=>s("/mission-control/contacts?filter=at-risk"),children:["View All At-Risk Contacts",e.jsx($a,{className:"h-4 w-4 ml-1"})]})]})]})}const tGt=()=>{var ie;const{user:s,isAdmin:t}=Ms(),r=Fr(),[n,a]=S.useState([]),[i,l]=S.useState([]),[o,c]=S.useState([]),[d,h]=S.useState([]),[m,p]=S.useState([]),[x,y]=S.useState([]),[_,b]=S.useState(new Set),[j,k]=S.useState([]),[T,E]=S.useState([]),[A,D]=S.useState([]),[R,z]=S.useState(null),[O,$]=S.useState(!0);S.useEffect(()=>{ee()},[s]);const ee=async()=>{var ce,ne,le,be,fe;try{const[je,ve,We,Ve,Le,Me,ze,Pe,Ie,De,pe]=await Promise.all([V.from("user_tags").select("tag").eq("user_id",s==null?void 0:s.id),V.from("app_tiles").select("*").order("name"),V.from("user_favorites").select("app_id").eq("user_id",s==null?void 0:s.id),V.from("events").select("*").order("event_date",{ascending:!0}),V.from("event_registrations").select("event_id, zoom_join_url").eq("user_id",s==null?void 0:s.id),V.from("canva_templates").select("id, name, preview_image_url, publish_date").order("publish_date",{ascending:!1}).limit(4),V.from("resource_kits").select("id, name, description, featured_image_url, publish_date").eq("is_published",!0).order("publish_date",{ascending:!1}).limit(4),V.from("academy_videos").select("id, title, description, thumbnail_url, duration, publish_date").eq("is_published",!0).order("publish_date",{ascending:!1}).limit(4),V.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),V.from("dashboard_banners").select("id, title, description, image_url, link_url, link_text, placement, section_after").eq("is_active",!0).order("sort_order"),V.from("profiles").select("name").eq("id",s==null?void 0:s.id).single()]);(ce=pe.data)!=null&&ce.name&&z(pe.data.name);const tt=((ne=je.data)==null?void 0:ne.map(Ne=>Ne.tag))||[],ge=new Set(((le=We.data)==null?void 0:le.map(Ne=>Ne.app_id))||[]);b(ge);const Ue=(((be=ve.data)==null?void 0:be.filter(Ne=>!Ne.required_tags||Ne.required_tags.length===0?!0:Ne.required_tags.some($e=>tt.includes($e))))||[]).sort((Ne,$e)=>Ne.name==="LevelUp Members Portal"?-1:$e.name==="LevelUp Members Portal"?1:0);a(Ue.slice(0,6));const et=((fe=Ve.data)==null?void 0:fe.filter(Ne=>oP(Ne.event_date)!=="ended"))||[];l(et.slice(0,4)),k(Le.data||[]),c(Me.data||[]),h(ze.data||[]),p(Pe.data||[]),y(Ie.data||[]);const Qe=De.data||[];E(Qe.filter(Ne=>Ne.placement==="top")),D(Qe.filter(Ne=>Ne.placement==="between"))}catch(je){console.error("Error loading dashboard:",je),he.error("Failed to load dashboard data")}finally{$(!1)}},Z=async ce=>{var le;const ne=window.open("about:blank","_blank");try{await V.from("activity_logs").insert({user_id:s==null?void 0:s.id,app_id:ce.app_id,app_name:ce.name,user_agent:navigator.userAgent});const{data:be,error:fe}=await V.functions.invoke("sso-launch",{body:{app_id:ce.app_id}});if(fe)throw fe;be!=null&&be.redirect_url?ne&&!ne.closed?(ne.location.href=be.redirect_url,(le=ne.focus)==null||le.call(ne)):window.location.assign(be.redirect_url):(ne==null||ne.close(),he.error("Launch link unavailable"))}catch(be){ne==null||ne.close(),console.error("Error launching app:",be),he.error("Failed to launch app")}},J=ce=>j==null?void 0:j.some(ne=>ne.event_id===ce),K=ce=>{const ne=j==null?void 0:j.find(le=>le.event_id===ce);return ne==null?void 0:ne.zoom_join_url};if(O)return e.jsx(Ss,{title:"Dashboard",children:e.jsx("div",{className:"flex items-center justify-center py-16",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent mx-auto mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:"Loading your dashboard..."})]})})});const re=ce=>A.filter(ne=>ne.section_after===ce);return e.jsxs(Ss,{title:"Dashboard",children:[e.jsx(qVt,{events:i,registrations:j,onNavigateToEvents:()=>r("/events")}),T.length>0&&e.jsx("div",{className:"mb-8",children:e.jsx(PR,{banners:T})}),e.jsx(WVt,{}),e.jsxs("div",{className:"mb-6",children:[e.jsxs("h2",{className:"text-2xl font-bold text-foreground",children:["Welcome back, ",(R||((ie=s==null?void 0:s.user_metadata)==null?void 0:ie.name)||"there").split(" ")[0],"!"]}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Are you ready to LevelUp today?"})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-4 mb-8",children:[e.jsx(lHt,{}),e.jsx(Aot,{}),e.jsx(UHt,{})]}),e.jsx(wHt,{}),e.jsxs("section",{className:"mb-10",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Upcoming Events"}),e.jsxs(H,{variant:"ghost",size:"sm",onClick:()=>r("/events"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",e.jsx(bi,{className:"h-4 w-4"})]})]}),i.length===0?e.jsx(ke,{className:"bg-muted/30 border-dashed",children:e.jsx(Oe,{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Nn,{className:"h-8 w-8 text-muted-foreground/50 mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No upcoming events"})]})})}):e.jsx("div",{className:"bg-card rounded-xl border border-border overflow-hidden divide-y divide-border max-w-full",children:i.map(ce=>{const ne=J(ce.id),le=K(ce.id)||ce.zoom_link;return e.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 ${c9e(ce.event_date)?"bg-red-500/5 border-l-2 border-l-red-500":""}`,onClick:()=>r("/events"),children:[c9e(ce.event_date)?e.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:[e.jsx("span",{className:"absolute inline-flex h-3 w-3 top-1 right-1 animate-ping rounded-full bg-red-500 opacity-75"}),e.jsx(G2,{className:"h-5 w-5 text-red-500"}),e.jsx("span",{className:"text-[10px] font-bold text-red-500 uppercase mt-0.5",children:"Live"})]}):e.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:[e.jsx("span",{className:"text-[10px] sm:text-xs font-medium text-primary uppercase",children:new Intl.DateTimeFormat("en-US",{month:"short",timeZone:"America/New_York"}).format(new Date(ce.event_date))}),e.jsx("span",{className:"text-lg sm:text-xl font-bold text-primary",children:new Intl.DateTimeFormat("en-US",{day:"numeric",timeZone:"America/New_York"}).format(new Date(ce.event_date))})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h4",{className:"font-medium text-sm sm:text-base text-foreground group-hover:text-primary transition-colors line-clamp-2 sm:truncate",children:ce.title}),e.jsxs("p",{className:"text-xs sm:text-sm text-muted-foreground mt-0.5",children:[new Intl.DateTimeFormat("en-US",{weekday:"long",timeZone:"America/New_York"}).format(new Date(ce.event_date))," at ",g9(new Date(ce.event_date))]})]}),e.jsx("div",{className:"hidden sm:flex flex-shrink-0",children:ne?e.jsxs(H,{size:"sm",variant:"default",className:"gap-1",onClick:be=>{be.stopPropagation(),window.open(le,"_blank")},children:[e.jsx(gn,{className:"h-3.5 w-3.5"}),"Join"]}):e.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground group-hover:text-primary transition-colors",children:[e.jsx("span",{className:"text-sm",children:"Register"}),e.jsx($a,{className:"h-4 w-4"})]})})]},ce.id)})})]}),re("events").length>0&&e.jsx("div",{className:"mb-10",children:e.jsx(PR,{banners:re("events")})}),e.jsxs("section",{className:"mb-10",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Academy Videos"}),e.jsxs(H,{variant:"ghost",size:"sm",onClick:()=>r("/academy"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",e.jsx(bi,{className:"h-4 w-4"})]})]}),m.length===0?e.jsx(ke,{className:"bg-muted/30 border-dashed",children:e.jsx(Oe,{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(cg,{className:"h-8 w-8 text-muted-foreground/50 mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No academy videos available"})]})})}):e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:m.map(ce=>e.jsxs("div",{onClick:()=>r(`/academy/${ce.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:[e.jsxs("div",{className:"aspect-[3/2] bg-muted/50 overflow-hidden relative",children:[ce.thumbnail_url?e.jsx("img",{src:ce.thumbnail_url,alt:ce.title,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(cg,{className:"h-8 w-8 text-muted-foreground/50"})}),ce.duration&&e.jsx("span",{className:"absolute bottom-2 right-2 bg-black/70 text-white text-xs px-1.5 py-0.5 rounded",children:ce.duration})]}),e.jsx("div",{className:"p-3",children:e.jsx("h4",{className:"font-medium text-sm text-foreground line-clamp-2 group-hover:text-primary transition-colors",children:ce.title})})]},ce.id))})]}),re("academy").length>0&&e.jsx("div",{className:"mb-10",children:e.jsx(PR,{banners:re("academy")})}),e.jsxs("section",{className:"mb-10",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Resource Kits"}),e.jsxs(H,{variant:"ghost",size:"sm",onClick:()=>r("/toolbox"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",e.jsx(bi,{className:"h-4 w-4"})]})]}),d.length===0?e.jsx(ke,{className:"bg-muted/30 border-dashed",children:e.jsx(Oe,{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Uf,{className:"h-8 w-8 text-muted-foreground/50 mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No resource kits available"})]})})}):e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:d.map(ce=>e.jsxs("div",{onClick:()=>r(`/toolbox/${ce.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:[e.jsx("div",{className:"aspect-[3/2] bg-muted/50 overflow-hidden",children:ce.featured_image_url?e.jsx("img",{src:ce.featured_image_url,alt:ce.name,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(Uf,{className:"h-8 w-8 text-muted-foreground/50"})})}),e.jsx("div",{className:"p-3",children:e.jsx("h4",{className:"font-medium text-sm text-foreground truncate group-hover:text-primary transition-colors",children:ce.name})})]},ce.id))})]}),re("toolbox").length>0&&e.jsx("div",{className:"mb-10",children:e.jsx(PR,{banners:re("toolbox")})}),e.jsxs("section",{className:"mb-10",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"New Templates"}),e.jsxs(H,{variant:"ghost",size:"sm",onClick:()=>r("/templates"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",e.jsx(bi,{className:"h-4 w-4"})]})]}),o.length===0?e.jsx(ke,{className:"bg-muted/30 border-dashed",children:e.jsx(Oe,{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(z2,{className:"h-8 w-8 text-muted-foreground/50 mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No templates available"})]})})}):e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:o.map(ce=>e.jsxs("div",{onClick:()=>r("/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:[e.jsx("div",{className:"aspect-[3/2] bg-muted/50 overflow-hidden",children:ce.preview_image_url?e.jsx("img",{src:ce.preview_image_url,alt:ce.name,className:"w-full h-full object-contain group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(z2,{className:"h-8 w-8 text-muted-foreground/50"})})}),e.jsx("div",{className:"p-3",children:e.jsx("h4",{className:"font-medium text-sm text-foreground truncate group-hover:text-primary transition-colors",children:ce.name})})]},ce.id))})]}),re("templates").length>0&&e.jsx("div",{className:"mb-10",children:e.jsx(PR,{banners:re("templates")})}),e.jsx("div",{className:"mb-10",children:e.jsx($Ht,{})}),e.jsxs("section",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Your Apps"}),e.jsxs(H,{variant:"ghost",size:"sm",onClick:()=>r("/apps"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",e.jsx(bi,{className:"h-4 w-4"})]})]}),n.length===0?e.jsx(ke,{className:"bg-muted/30 border-dashed",children:e.jsx(Oe,{className:"flex items-center justify-center py-12",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Uy,{className:"h-8 w-8 text-muted-foreground/50 mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No apps available"})]})})}):e.jsx("div",{className:"grid gap-4 md:grid-cols-2 xl:grid-cols-3",children:n.map(ce=>{const ne=_.has(ce.id);return e.jsxs("div",{onClick:()=>Z(ce),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:[e.jsx("div",{className:"flex-shrink-0 w-14 h-14 rounded-xl bg-primary/10 flex items-center justify-center text-3xl",children:ce.icon}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-semibold text-foreground group-hover:text-primary transition-colors truncate",children:ce.name}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 line-clamp-2",children:ce.description})]}),ne&&e.jsx(Uy,{className:"h-5 w-5 text-primary fill-current flex-shrink-0"})]},ce.id)})})]}),e.jsxs("section",{className:"mt-10",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Additional Services"}),e.jsxs(H,{variant:"ghost",size:"sm",onClick:()=>r("/additional-services"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",e.jsx(bi,{className:"h-4 w-4"})]})]}),x.length===0?e.jsx(ke,{className:"bg-muted/30 border-dashed",children:e.jsx(Oe,{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Lr,{className:"h-8 w-8 text-muted-foreground/50 mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No additional services available"})]})})}):e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:x.map(ce=>e.jsxs("div",{onClick:()=>window.open(ce.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:[e.jsx("div",{className:"aspect-[4/3] bg-muted/50 overflow-hidden",children:ce.preview_image_url?e.jsx("img",{src:ce.preview_image_url,alt:ce.name,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(Lr,{className:"h-8 w-8 text-muted-foreground/50"})})}),e.jsxs("div",{className:"p-3",children:[e.jsx("h4",{className:"font-medium text-sm text-foreground truncate group-hover:text-primary transition-colors",children:ce.name}),ce.description&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1 line-clamp-2",children:ce.description})]})]},ce.id))})]})]})};var Mot="AlertDialog",[sGt,UZs]=_u(Mot,[$tt]),bj=$tt(),Iot=s=>{const{__scopeAlertDialog:t,...r}=s,n=bj(t);return e.jsx(pge,{...n,...r,modal:!0})};Iot.displayName=Mot;var rGt="AlertDialogTrigger",Pot=S.forwardRef((s,t)=>{const{__scopeAlertDialog:r,...n}=s,a=bj(r);return e.jsx(r5e,{...a,...n,ref:t})});Pot.displayName=rGt;var nGt="AlertDialogPortal",Lot=s=>{const{__scopeAlertDialog:t,...r}=s,n=bj(t);return e.jsx(gge,{...n,...r})};Lot.displayName=nGt;var aGt="AlertDialogOverlay",Dot=S.forwardRef((s,t)=>{const{__scopeAlertDialog:r,...n}=s,a=bj(r);return e.jsx(h8,{...a,...n,ref:t})});Dot.displayName=aGt;var lP="AlertDialogContent",[iGt,oGt]=sGt(lP),lGt=nQe("AlertDialogContent"),Rot=S.forwardRef((s,t)=>{const{__scopeAlertDialog:r,children:n,...a}=s,i=bj(r),l=S.useRef(null),o=_i(t,l),c=S.useRef(null);return e.jsx(tPt,{contentName:lP,titleName:Oot,docsSlug:"alert-dialog",children:e.jsx(iGt,{scope:r,cancelRef:c,children:e.jsxs(m8,{role:"alertdialog",...i,...a,ref:o,onOpenAutoFocus:an(a.onOpenAutoFocus,d=>{var h;d.preventDefault(),(h=c.current)==null||h.focus({preventScroll:!0})}),onPointerDownOutside:d=>d.preventDefault(),onInteractOutside:d=>d.preventDefault(),children:[e.jsx(lGt,{children:n}),e.jsx(dGt,{contentRef:l})]})})})});Rot.displayName=lP;var Oot="AlertDialogTitle",Fot=S.forwardRef((s,t)=>{const{__scopeAlertDialog:r,...n}=s,a=bj(r);return e.jsx(YB,{...a,...n,ref:t})});Fot.displayName=Oot;var Bot="AlertDialogDescription",zot=S.forwardRef((s,t)=>{const{__scopeAlertDialog:r,...n}=s,a=bj(r);return e.jsx(ZB,{...a,...n,ref:t})});zot.displayName=Bot;var cGt="AlertDialogAction",$ot=S.forwardRef((s,t)=>{const{__scopeAlertDialog:r,...n}=s,a=bj(r);return e.jsx(XB,{...a,...n,ref:t})});$ot.displayName=cGt;var Uot="AlertDialogCancel",qot=S.forwardRef((s,t)=>{const{__scopeAlertDialog:r,...n}=s,{cancelRef:a}=oGt(Uot,r),i=bj(r),l=_i(t,a);return e.jsx(XB,{...i,...n,ref:l})});qot.displayName=Uot;var dGt=({contentRef:s})=>{const t=`\`${lP}\` requires a description for the component to be accessible for screen reader users. You can add a description to the \`${lP}\` by passing a \`${Bot}\` 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 \`${lP}\`. 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 S.useEffect(()=>{var n;document.getElementById((n=s.current)==null?void 0:n.getAttribute("aria-describedby"))||console.warn(t)},[t,s]),null},uGt=Iot,hGt=Pot,mGt=Lot,Vot=Dot,Hot=Rot,Got=$ot,Wot=qot,Kot=Fot,Yot=zot;const Rl=uGt,vp=hGt,fGt=mGt,Zot=S.forwardRef(({className:s,...t},r)=>e.jsx(Vot,{className:Ft("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",s),...t,ref:r}));Zot.displayName=Vot.displayName;const jl=S.forwardRef(({className:s,...t},r)=>e.jsxs(fGt,{children:[e.jsx(Zot,{}),e.jsx(Hot,{ref:r,className:Ft("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",s),...t})]}));jl.displayName=Hot.displayName;const Nl=({className:s,...t})=>e.jsx("div",{className:Ft("flex flex-col space-y-2 text-center sm:text-left",s),...t});Nl.displayName="AlertDialogHeader";const kl=({className:s,...t})=>e.jsx("div",{className:Ft("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",s),...t});kl.displayName="AlertDialogFooter";const Sl=S.forwardRef(({className:s,...t},r)=>e.jsx(Kot,{ref:r,className:Ft("text-lg font-semibold",s),...t}));Sl.displayName=Kot.displayName;const Cl=S.forwardRef(({className:s,...t},r)=>e.jsx(Yot,{ref:r,className:Ft("text-sm text-muted-foreground",s),...t}));Cl.displayName=Yot.displayName;const ml=S.forwardRef(({className:s,...t},r)=>e.jsx(Got,{ref:r,className:Ft(KP(),s),...t}));ml.displayName=Got.displayName;const Tl=S.forwardRef(({className:s,...t},r)=>e.jsx(Wot,{ref:r,className:Ft(KP({variant:"outline"}),"mt-2 sm:mt-0",s),...t}));Tl.displayName=Wot.displayName;const pGt=[{key:"contacts",label:"Contacts",icon:Yn,description:"View, add, and edit contacts"},{key:"pipeline",label:"Deal Pipeline",icon:wE,description:"View, add, and move deals"},{key:"client_portal",label:"Client Portals",icon:Uf,description:"Manage client portals on deals"},{key:"videos",label:"Videos",icon:xn,description:"View and upload videos"},{key:"listings",label:"Listings",icon:Fn,description:"View, create, and edit listings"},{key:"scorecard",label:"Scorecard",icon:Fk,description:"View and add transactions"},{key:"popbys",label:"Pop-bys",icon:Qa,description:"View and log pop-bys"},{key:"digital_card",label:"Digital Card",icon:u0,description:"Create and edit digital business card"},{key:"guest_book",label:"Guest Book",icon:tf,description:"Manage open house guest books"},{key:"presentations",label:"Presentations",icon:_1,description:"Create and manage smart presentations"}];function gGt(){var R;const{user:s}=Ms(),[t,r]=S.useState([]),[n,a]=S.useState(!0),[i,l]=S.useState(!1),[o,c]=S.useState(!1),[d,h]=S.useState(null),[m,p]=S.useState({email:"",name:"",password:""}),[x,y]=S.useState("create"),[_,b]=S.useState(!1),[j,k]=S.useState(null);S.useEffect(()=>{s&&T()},[s]);const T=async()=>{if(s){a(!0);try{const{data:z,error:O}=await V.from("agent_assistant_assignments").select("id, assistant_id, permissions, created_at").eq("agent_id",s.id);if(O)throw O;if(z&&z.length>0){const $=z.map(J=>J.assistant_id),{data:ee}=await V.from("profiles").select("id, name, email").in("id",$),Z=z.map(J=>{const K=ee==null?void 0:ee.find(re=>re.id===J.assistant_id);return{...J,permissions:J.permissions,assistant_profile:K?{name:K.name||"",email:K.email||""}:void 0}});r(Z)}else r([])}catch(z){console.error("Error loading assistants:",z)}finally{a(!1)}}},E=async()=>{if(s){if(x==="link"){if(!m.email.trim()){he.error("Please enter the assistant's email");return}b(!0);try{const{data:{session:z}}=await V.auth.getSession();if(!z)throw new Error("Not authenticated");const{data:O,error:$}=await V.from("profiles").select("id, name, email").eq("email",m.email.trim().toLowerCase()).single();if($||!O){he.error("No account found with that email. Try creating a new assistant instead.");return}const{data:ee}=await V.from("agent_assistant_assignments").select("id").eq("agent_id",s.id).eq("assistant_id",O.id);if(ee&&ee.length>0){he.error("This assistant is already assigned to you");return}const Z=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${z.access_token}`},body:JSON.stringify({userId:O.id,role:"assistant",action:"add",agentId:s.id})}),J=await Z.json();if(!Z.ok)throw new Error(J.error||"Failed to assign assistant role");const{error:K}=await V.from("agent_assistant_assignments").insert({agent_id:s.id,assistant_id:O.id,permissions:{contacts:!0,pipeline:!0,videos:!1,listings:!1,scorecard:!1,popbys:!1,digital_card:!1,client_portal:!1,guest_book:!1,presentations:!1}});if(K)throw K;he.success(`${O.name||O.email} linked as your assistant`),l(!1),p({email:"",name:"",password:""}),T()}catch(z){console.error("Error linking assistant:",z),he.error(z.message||"Failed to link assistant")}finally{b(!1)}return}if(!m.email.trim()||!m.name.trim()||!m.password.trim()){he.error("Please fill in all fields");return}if(m.password.length<6){he.error("Password must be at least 6 characters");return}b(!0);try{const{data:{session:z}}=await V.auth.getSession();if(!z)throw new Error("Not authenticated");const O=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/create-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${z.access_token}`},body:JSON.stringify({email:m.email.trim(),password:m.password,name:m.name.trim(),purpose:"assistant"})}),$=await O.json();if(!O.ok)throw new Error($.error||"Failed to create assistant account");const ee=$.userId||$.id;if(!ee)throw new Error("No user ID returned");const Z=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${z.access_token}`},body:JSON.stringify({userId:ee,role:"assistant",action:"add",agentId:s.id})}),J=await Z.json();if(!Z.ok)throw new Error(J.error||"Failed to assign assistant role");const{error:K}=await V.from("agent_assistant_assignments").insert({agent_id:s.id,assistant_id:ee,permissions:{contacts:!0,pipeline:!0,videos:!1,listings:!1,scorecard:!1,popbys:!1,digital_card:!1,client_portal:!1,guest_book:!1,presentations:!1}});if(K)throw K;he.success(`Assistant account created for ${m.name.trim()}`),l(!1),p({email:"",name:"",password:""}),T()}catch(z){console.error("Error adding assistant:",z),he.error(z.message||"Failed to add assistant")}finally{b(!1)}}},A=async()=>{if(!(!d||!s))try{const{data:{session:z}}=await V.auth.getSession();if(!z)throw new Error("Not authenticated");const{error:O}=await V.from("agent_assistant_assignments").delete().eq("id",d.id);if(O)throw O;const{data:$}=await V.from("agent_assistant_assignments").select("id").eq("assistant_id",d.assistant_id);(!$||$.length===0)&&await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${z.access_token}`},body:JSON.stringify({userId:d.assistant_id,role:"assistant",action:"remove"})}),he.success("Assistant removed"),c(!1),h(null),T()}catch(z){console.error("Error removing assistant:",z),he.error(z.message||"Failed to remove assistant")}},D=async(z,O,$)=>{k(z);try{const ee=t.find(K=>K.id===z);if(!ee)return;const Z={...ee.permissions,[O]:$},{error:J}=await V.from("agent_assistant_assignments").update({permissions:Z}).eq("id",z);if(J)throw J;r(K=>K.map(re=>re.id===z?{...re,permissions:Z}:re))}catch(ee){console.error("Error updating permissions:",ee),he.error("Failed to update permissions")}finally{k(null)}};return n?e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(Ar,{className:"h-5 w-5"}),"My Assistants"]})}),e.jsx(Oe,{children:e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(is,{className:"h-6 w-6 animate-spin text-muted-foreground"})})})]}):e.jsxs(e.Fragment,{children:[e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(Ar,{className:"h-5 w-5"}),"My Assistants"]}),e.jsx(Br,{children:"Add assistants to help manage your Agent OS"})]}),e.jsxs(H,{size:"sm",onClick:()=>{y("create"),l(!0)},children:[e.jsx(Ys,{className:"h-4 w-4 mr-1"}),"Add Assistant"]})]})}),e.jsx(Oe,{children:t.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No assistant assigned. Add one to help manage your contacts, deals, and more."}):e.jsx("div",{className:"space-y-4",children:t.map(z=>{var O,$,ee,Z;return e.jsxs("div",{className:"border rounded-lg p-4 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Un,{className:"h-10 w-10",children:e.jsx(qn,{children:(($=(O=z.assistant_profile)==null?void 0:O.name)==null?void 0:$.split(" ").map(J=>J[0]).join("").toUpperCase())||"A"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((ee=z.assistant_profile)==null?void 0:ee.name)||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:((Z=z.assistant_profile)==null?void 0:Z.email)||""})]}),e.jsxs(Xe,{variant:"secondary",className:"ml-2",children:[e.jsx(Fh,{className:"h-3 w-3 mr-1"}),"Assistant"]})]}),e.jsx(H,{variant:"ghost",size:"sm",className:"text-destructive hover:text-destructive",onClick:()=>{h(z),c(!0)},children:e.jsx(Dr,{className:"h-4 w-4"})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium mb-3",children:"Permissions"}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:pGt.map(J=>{const K=J.icon;return e.jsxs("div",{className:"flex items-center justify-between p-2 rounded-md border",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(K,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:J.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:J.description})]})]}),e.jsx(Or,{checked:z.permissions[J.key]||!1,onCheckedChange:re=>D(z.id,J.key,re),disabled:j===z.id})]},J.key)})})]})]},z.id)})})})]}),e.jsx(bs,{open:i,onOpenChange:l,children:e.jsxs(vs,{children:[e.jsxs(Cs,{children:[e.jsx(Ns,{children:"Add Assistant"}),e.jsx(nn,{children:x==="create"?"Create a new account for your assistant.":"Link an existing assistant account by their email."})]}),e.jsxs("div",{className:"flex gap-2 mb-2",children:[e.jsxs(H,{variant:x==="create"?"default":"outline",size:"sm",onClick:()=>y("create"),children:[e.jsx(Ys,{className:"h-3 w-3 mr-1"}),"Create New"]}),e.jsxs(H,{variant:x==="link"?"default":"outline",size:"sm",onClick:()=>y("link"),children:[e.jsx(Jo,{className:"h-3 w-3 mr-1"}),"Link Existing"]})]}),e.jsxs("div",{className:"space-y-4 py-2",children:[x==="create"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"assistant-name",children:"Name"}),e.jsx(Se,{id:"assistant-name",value:m.name,onChange:z=>p({...m,name:z.target.value}),placeholder:"Assistant's full name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"assistant-email",children:"Email"}),e.jsx(Se,{id:"assistant-email",type:"email",value:m.email,onChange:z=>p({...m,email:z.target.value}),placeholder:"assistant@email.com"})]}),x==="create"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"assistant-password",children:"Temporary Password"}),e.jsx(Se,{id:"assistant-password",type:"password",value:m.password,onChange:z=>p({...m,password:z.target.value}),placeholder:"Min 6 characters"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Your assistant can change this after their first login."})]})]}),e.jsxs(wn,{children:[e.jsx(H,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsxs(H,{onClick:E,disabled:_,children:[_&&e.jsx(is,{className:"h-4 w-4 mr-2 animate-spin"}),x==="create"?"Create Assistant":"Link Assistant"]})]})]})}),e.jsx(Rl,{open:o,onOpenChange:c,children:e.jsxs(jl,{children:[e.jsxs(Nl,{children:[e.jsx(Sl,{children:"Remove Assistant?"}),e.jsxs(Cl,{children:["This will remove ",(R=d==null?void 0:d.assistant_profile)==null?void 0:R.name,"'s access to your Agent OS. Their account will remain active but they won't be able to manage your data."]})]}),e.jsxs(kl,{children:[e.jsx(Tl,{children:"Cancel"}),e.jsx(ml,{onClick:A,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Remove"})]})]})})]})}function Af(s){this.content=s}Af.prototype={constructor:Af,find:function(s){for(var t=0;t>1}};Af.from=function(s){if(s instanceof Af)return s;var t=[];if(s)for(var r in s)t.push(r,s[r]);return new Af(t)};function Xot(s,t,r){for(let n=0;;n++){if(n==s.childCount||n==t.childCount)return s.childCount==t.childCount?null:r;let a=s.child(n),i=t.child(n);if(a==i){r+=a.nodeSize;continue}if(!a.sameMarkup(i))return r;if(a.isText&&a.text!=i.text){for(let l=0;a.text[l]==i.text[l];l++)r++;return r}if(a.content.size||i.content.size){let l=Xot(a.content,i.content,r+1);if(l!=null)return l}r+=a.nodeSize}}function Qot(s,t,r,n){for(let a=s.childCount,i=t.childCount;;){if(a==0||i==0)return a==i?null:{a:r,b:n};let l=s.child(--a),o=t.child(--i),c=l.nodeSize;if(l==o){r-=c,n-=c;continue}if(!l.sameMarkup(o))return{a:r,b:n};if(l.isText&&l.text!=o.text){let d=0,h=Math.min(l.text.length,o.text.length);for(;dt&&n(c,a+o,i||null,l)!==!1&&c.content.size){let h=o+1;c.nodesBetween(Math.max(0,t-h),Math.min(c.content.size,r-h),n,a+h)}o=d}}descendants(t){this.nodesBetween(0,this.size,t)}textBetween(t,r,n,a){let i="",l=!0;return this.nodesBetween(t,r,(o,c)=>{let d=o.isText?o.text.slice(Math.max(t,c)-c,r-c):o.isLeaf?a?typeof a=="function"?a(o):a:o.type.spec.leafText?o.type.spec.leafText(o):"":"";o.isBlock&&(o.isLeaf&&d||o.isTextblock)&&n&&(l?l=!1:i+=n),i+=d},0),i}append(t){if(!t.size)return this;if(!this.size)return t;let r=this.lastChild,n=t.firstChild,a=this.content.slice(),i=0;for(r.isText&&r.sameMarkup(n)&&(a[a.length-1]=r.withText(r.text+n.text),i=1);it)for(let i=0,l=0;lt&&((lr)&&(o.isText?o=o.cut(Math.max(0,t-l),Math.min(o.text.length,r-l)):o=o.cut(Math.max(0,t-l-1),Math.min(o.content.size,r-l-1))),n.push(o),a+=o.nodeSize),l=c}return new tg(n,a)}cutByIndex(t,r){return t==r?tg.empty:t==0&&r==this.content.length?this:new tg(this.content.slice(t,r))}replaceChild(t,r){let n=this.content[t];if(n==r)return this;let a=this.content.slice(),i=this.size+r.nodeSize-n.nodeSize;return a[t]=r,new tg(a,i)}addToStart(t){return new tg([t].concat(this.content),this.size+t.nodeSize)}addToEnd(t){return new tg(this.content.concat(t),this.size+t.nodeSize)}eq(t){if(this.content.length!=t.content.length)return!1;for(let r=0;rthis.size||t<0)throw new RangeError(`Position ${t} outside of fragment (${this})`);for(let r=0,n=0;;r++){let a=this.child(r),i=n+a.nodeSize;if(i>=t)return i==t?ZU(r+1,i):ZU(r,n);n=i}}toString(){return"<"+this.toStringInner()+">"}toStringInner(){return this.content.join(", ")}toJSON(){return this.content.length?this.content.map(t=>t.toJSON()):null}static fromJSON(t,r){if(!r)return tg.empty;if(!Array.isArray(r))throw new RangeError("Invalid input for Fragment.fromJSON");return new tg(r.map(t.nodeFromJSON))}static fromArray(t){if(!t.length)return tg.empty;let r,n=0;for(let a=0;athis.type.rank&&(r||(r=t.slice(0,a)),r.push(this),n=!0),r&&r.push(i)}}return r||(r=t.slice()),n||r.push(this),r}removeFromSet(t){for(let r=0;rn.type.rank-a.type.rank),r}};Fc.none=[];class ame extends Error{}class ua{constructor(t,r,n){this.content=t,this.openStart=r,this.openEnd=n}get size(){return this.content.size-this.openStart-this.openEnd}insertAt(t,r){let n=elt(this.content,t+this.openStart,r);return n&&new ua(n,this.openStart,this.openEnd)}removeBetween(t,r){return new ua(Jot(this.content,t+this.openStart,r+this.openStart),this.openStart,this.openEnd)}eq(t){return this.content.eq(t.content)&&this.openStart==t.openStart&&this.openEnd==t.openEnd}toString(){return this.content+"("+this.openStart+","+this.openEnd+")"}toJSON(){if(!this.content.size)return null;let t={content:this.content.toJSON()};return this.openStart>0&&(t.openStart=this.openStart),this.openEnd>0&&(t.openEnd=this.openEnd),t}static fromJSON(t,r){if(!r)return ua.empty;let n=r.openStart||0,a=r.openEnd||0;if(typeof n!="number"||typeof a!="number")throw new RangeError("Invalid input for Slice.fromJSON");return new ua(An.fromJSON(t,r.content),n,a)}static maxOpen(t,r=!0){let n=0,a=0;for(let i=t.firstChild;i&&!i.isLeaf&&(r||!i.type.spec.isolating);i=i.firstChild)n++;for(let i=t.lastChild;i&&!i.isLeaf&&(r||!i.type.spec.isolating);i=i.lastChild)a++;return new ua(t,n,a)}}ua.empty=new ua(An.empty,0,0);function Jot(s,t,r){let{index:n,offset:a}=s.findIndex(t),i=s.maybeChild(n),{index:l,offset:o}=s.findIndex(r);if(a==t||i.isText){if(o!=r&&!s.child(l).isText)throw new RangeError("Removing non-flat range");return s.cut(0,t).append(s.cut(r))}if(n!=l)throw new RangeError("Removing non-flat range");return s.replaceChild(n,i.copy(Jot(i.content,t-a-1,r-a-1)))}function elt(s,t,r,n){let{index:a,offset:i}=s.findIndex(t),l=s.maybeChild(a);if(i==t||l.isText)return n&&!n.canReplace(a,a,r)?null:s.cut(0,t).append(r).append(s.cut(t));let o=elt(l.content,t-i-1,r,l);return o&&s.replaceChild(a,l.copy(o))}function xGt(s,t,r){if(r.openStart>s.depth)throw new ame("Inserted content deeper than insertion position");if(s.depth-r.openStart!=t.depth-r.openEnd)throw new ame("Inconsistent open depths");return tlt(s,t,r,0)}function tlt(s,t,r,n){let a=s.index(n),i=s.node(n);if(a==t.index(n)&&n=0&&s.isText&&s.sameMarkup(t[r])?t[r]=s.withText(t[r].text+s.text):t.push(s)}function r7(s,t,r,n){let a=(t||s).node(r),i=0,l=t?t.index(r):a.childCount;s&&(i=s.index(r),s.depth>r?i++:s.textOffset&&(UE(s.nodeAfter,n),i++));for(let o=i;oa&&VNe(s,t,a+1),l=n.depth>a&&VNe(r,n,a+1),o=[];return r7(null,s,a,o),i&&l&&t.index(a)==r.index(a)?(slt(i,l),UE(qE(i,rlt(s,t,r,n,a+1)),o)):(i&&UE(qE(i,ime(s,t,a+1)),o),r7(t,r,a,o),l&&UE(qE(l,ime(r,n,a+1)),o)),r7(n,null,a,o),new An(o)}function ime(s,t,r){let n=[];if(r7(null,s,r,n),s.depth>r){let a=VNe(s,t,r+1);UE(qE(a,ime(s,t,r+1)),n)}return r7(t,null,r,n),new An(n)}function yGt(s,t){let r=t.depth-s.openStart,a=t.node(r).copy(s.content);for(let i=r-1;i>=0;i--)a=t.node(i).copy(An.from(a));return{start:a.resolveNoCache(s.openStart+r),end:a.resolveNoCache(a.content.size-s.openEnd-r)}}class x9{constructor(t,r,n){this.pos=t,this.path=r,this.parentOffset=n,this.depth=r.length/3-1}resolveDepth(t){return t==null?this.depth:t<0?this.depth+t:t}get parent(){return this.node(this.depth)}get doc(){return this.node(0)}node(t){return this.path[this.resolveDepth(t)*3]}index(t){return this.path[this.resolveDepth(t)*3+1]}indexAfter(t){return t=this.resolveDepth(t),this.index(t)+(t==this.depth&&!this.textOffset?0:1)}start(t){return t=this.resolveDepth(t),t==0?0:this.path[t*3-1]+1}end(t){return t=this.resolveDepth(t),this.start(t)+this.node(t).content.size}before(t){if(t=this.resolveDepth(t),!t)throw new RangeError("There is no position before the top-level node");return t==this.depth+1?this.pos:this.path[t*3-1]}after(t){if(t=this.resolveDepth(t),!t)throw new RangeError("There is no position after the top-level node");return t==this.depth+1?this.pos:this.path[t*3-1]+this.path[t*3].nodeSize}get textOffset(){return this.pos-this.path[this.path.length-1]}get nodeAfter(){let t=this.parent,r=this.index(this.depth);if(r==t.childCount)return null;let n=this.pos-this.path[this.path.length-1],a=t.child(r);return n?t.child(r).cut(n):a}get nodeBefore(){let t=this.index(this.depth),r=this.pos-this.path[this.path.length-1];return r?this.parent.child(t).cut(0,r):t==0?null:this.parent.child(t-1)}posAtIndex(t,r){r=this.resolveDepth(r);let n=this.path[r*3],a=r==0?0:this.path[r*3-1]+1;for(let i=0;i0;r--)if(this.start(r)<=t&&this.end(r)>=t)return r;return 0}blockRange(t=this,r){if(t.pos=0;n--)if(t.pos<=this.end(n)&&(!r||r(this.node(n))))return new ome(this,t,n);return null}sameParent(t){return this.pos-this.parentOffset==t.pos-t.parentOffset}max(t){return t.pos>this.pos?t:this}min(t){return t.pos=0&&r<=t.content.size))throw new RangeError("Position "+r+" out of range");let n=[],a=0,i=r;for(let l=t;;){let{index:o,offset:c}=l.content.findIndex(i),d=i-c;if(n.push(l,o,a+c),!d||(l=l.child(o),l.isText))break;i=d-1,a+=c+1}return new x9(r,n,i)}static resolveCached(t,r){let n=h9e.get(t);if(n)for(let i=0;it&&this.nodesBetween(t,r,i=>(n.isInSet(i.marks)&&(a=!0),!a)),a}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 t=this.type.name;return this.content.size&&(t+="("+this.content.toStringInner()+")"),nlt(this.marks,t)}contentMatchAt(t){let r=this.type.contentMatch.matchFragment(this.content,0,t);if(!r)throw new Error("Called contentMatchAt on a node with invalid content");return r}canReplace(t,r,n=An.empty,a=0,i=n.childCount){let l=this.contentMatchAt(t).matchFragment(n,a,i),o=l&&l.matchFragment(this.content,r);if(!o||!o.validEnd)return!1;for(let c=a;cr.type.name)}`);this.content.forEach(r=>r.check())}toJSON(){let t={type:this.type.name};for(let r in this.attrs){t.attrs=this.attrs;break}return this.content.size&&(t.content=this.content.toJSON()),this.marks.length&&(t.marks=this.marks.map(r=>r.toJSON())),t}static fromJSON(t,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(t.markFromJSON)}if(r.type=="text"){if(typeof r.text!="string")throw new RangeError("Invalid text node in JSON");return t.text(r.text,n)}let a=An.fromJSON(t,r.content),i=t.nodeType(r.type).create(r.attrs,a,n);return i.type.checkAttrs(i.attrs),i}};rS.prototype.text=void 0;class lme extends rS{constructor(t,r,n,a){if(super(t,r,null,a),!n)throw new RangeError("Empty text nodes are not allowed");this.text=n}toString(){return this.type.spec.toDebugString?this.type.spec.toDebugString(this):nlt(this.marks,JSON.stringify(this.text))}get textContent(){return this.text}textBetween(t,r){return this.text.slice(t,r)}get nodeSize(){return this.text.length}mark(t){return t==this.marks?this:new lme(this.type,this.attrs,this.text,t)}withText(t){return t==this.text?this:new lme(this.type,this.attrs,t,this.marks)}cut(t=0,r=this.text.length){return t==0&&r==this.text.length?this:this.withText(this.text.slice(t,r))}eq(t){return this.sameMarkup(t)&&this.text==t.text}toJSON(){let t=super.toJSON();return t.text=this.text,t}}function nlt(s,t){for(let r=s.length-1;r>=0;r--)t=s[r].type.name+"("+t+")";return t}class xA{constructor(t){this.validEnd=t,this.next=[],this.wrapCache=[]}static parse(t,r){let n=new wGt(t,r);if(n.next==null)return xA.empty;let a=alt(n);n.next&&n.err("Unexpected trailing text");let i=EGt(TGt(a));return AGt(i,n),i}matchType(t){for(let r=0;rd.createAndFill()));for(let d=0;d=this.next.length)throw new RangeError(`There's no ${t}th edge in this content match`);return this.next[t]}toString(){let t=[];function r(n){t.push(n);for(let a=0;a{let i=a+(n.validEnd?"*":" ")+" ";for(let l=0;l"+t.indexOf(n.next[l].next);return i}).join(` `)}}xA.empty=new xA(!0);class wGt{constructor(t,r){this.string=t,this.nodeTypes=r,this.inline=null,this.pos=0,this.tokens=t.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(t){return this.next==t&&(this.pos++||!0)}err(t){throw new SyntaxError(t+" (in content expression '"+this.string+"')")}}function alt(s){let t=[];do t.push(jGt(s));while(s.eat("|"));return t.length==1?t[0]:{type:"choice",exprs:t}}function jGt(s){let t=[];do t.push(NGt(s));while(s.next&&s.next!=")"&&s.next!="|");return t.length==1?t[0]:{type:"seq",exprs:t}}function NGt(s){let t=CGt(s);for(;;)if(s.eat("+"))t={type:"plus",expr:t};else if(s.eat("*"))t={type:"star",expr:t};else if(s.eat("?"))t={type:"opt",expr:t};else if(s.eat("{"))t=kGt(s,t);else break;return t}function m9e(s){/\D/.test(s.next)&&s.err("Expected number, got '"+s.next+"'");let t=Number(s.next);return s.pos++,t}function kGt(s,t){let r=m9e(s),n=r;return s.eat(",")&&(s.next!="}"?n=m9e(s):n=-1),s.eat("}")||s.err("Unclosed braced range"),{type:"range",min:r,max:n,expr:t}}function SGt(s,t){let r=s.nodeTypes,n=r[t];if(n)return[n];let a=[];for(let i in r){let l=r[i];l.isInGroup(t)&&a.push(l)}return a.length==0&&s.err("No node type or group '"+t+"' found"),a}function CGt(s){if(s.eat("(")){let t=alt(s);return s.eat(")")||s.err("Missing closing paren"),t}else if(/\W/.test(s.next))s.err("Unexpected token '"+s.next+"'");else{let t=SGt(s,s.next).map(r=>(s.inline==null?s.inline=r.isInline:s.inline!=r.isInline&&s.err("Mixing inline and block content"),{type:"name",value:r}));return s.pos++,t.length==1?t[0]:{type:"choice",exprs:t}}}function TGt(s){let t=[[]];return a(i(s,0),r()),t;function r(){return t.push([])-1}function n(l,o,c){let d={term:c,to:o};return t[l].push(d),d}function a(l,o){l.forEach(c=>c.to=o)}function i(l,o){if(l.type=="choice")return l.exprs.reduce((c,d)=>c.concat(i(d,o)),[]);if(l.type=="seq")for(let c=0;;c++){let d=i(l.exprs[c],o);if(c==l.exprs.length-1)return d;a(d,o=r())}else if(l.type=="star"){let c=r();return n(o,c),a(i(l.expr,c),c),[n(c)]}else if(l.type=="plus"){let c=r();return a(i(l.expr,o),c),a(i(l.expr,c),c),[n(c)]}else{if(l.type=="opt")return[n(o)].concat(i(l.expr,o));if(l.type=="range"){let c=o;for(let d=0;d{s[l].forEach(({term:o,to:c})=>{if(!o)return;let d;for(let h=0;h{d||a.push([o,d=[]]),d.indexOf(h)==-1&&d.push(h)})})});let i=t[n.join(",")]=new xA(n.indexOf(s.length-1)>-1);for(let l=0;l-1}get whitespace(){return this.spec.whitespace||(this.spec.code?"pre":"normal")}hasRequiredAttrs(){for(let t in this.attrs)if(this.attrs[t].isRequired)return!0;return!1}compatibleContent(t){return this==t||this.contentMatch.compatible(t.contentMatch)}computeAttrs(t){return!t&&this.defaultAttrs?this.defaultAttrs:llt(this.attrs,t)}create(t=null,r,n){if(this.isText)throw new Error("NodeType.create can't construct text nodes");return new rS(this,this.computeAttrs(t),An.from(r),Fc.setFrom(n))}createChecked(t=null,r,n){return r=An.from(r),this.checkContent(r),new rS(this,this.computeAttrs(t),r,Fc.setFrom(n))}createAndFill(t=null,r,n){if(t=this.computeAttrs(t),r=An.from(r),r.size){let l=this.contentMatch.fillBefore(r);if(!l)return null;r=l.append(r)}let a=this.contentMatch.matchFragment(r),i=a&&a.fillBefore(An.empty,!0);return i?new rS(this,t,r.append(i),Fc.setFrom(n)):null}validContent(t){let r=this.contentMatch.matchFragment(t);if(!r||!r.validEnd)return!1;for(let n=0;n-1}allowsMarks(t){if(this.markSet==null)return!0;for(let r=0;rn[i]=new ult(i,r,l));let a=r.spec.topNode||"doc";if(!n[a])throw new RangeError("Schema is missing its top node type ('"+a+"')");if(!n.text)throw new RangeError("Every schema needs a 'text' type");for(let i in n.text.attrs)throw new RangeError("The text node type should not have attributes");return n}};function MGt(s,t,r){let n=r.split("|");return a=>{let i=a===null?"null":typeof a;if(n.indexOf(i)<0)throw new RangeError(`Expected value of type ${n} for attribute ${t} on type ${s}, got ${i}`)}}class IGt{constructor(t,r,n){this.hasDefault=Object.prototype.hasOwnProperty.call(n,"default"),this.default=n.default,this.validate=typeof n.validate=="string"?MGt(t,r,n.validate):n.validate}get isRequired(){return!this.hasDefault}}class rxe{constructor(t,r,n,a){this.name=t,this.rank=r,this.schema=n,this.spec=a,this.attrs=dlt(t,a.attrs),this.excluded=null;let i=olt(this.attrs);this.instance=i?new Fc(this,i):null}create(t=null){return!t&&this.instance?this.instance:new Fc(this,llt(this.attrs,t))}static compile(t,r){let n=Object.create(null),a=0;return t.forEach((i,l)=>n[i]=new rxe(i,a++,r,l)),n}removeFromSet(t){for(var r=0;r-1}}class hlt{constructor(t){this.linebreakReplacement=null,this.cached=Object.create(null);let r=this.spec={};for(let a in t)r[a]=t[a];r.nodes=Af.from(t.nodes),r.marks=Af.from(t.marks||{}),this.nodes=p9e.compile(this.spec.nodes,this),this.marks=rxe.compile(this.spec.marks,this);let n=Object.create(null);for(let a in this.nodes){if(a in this.marks)throw new RangeError(a+" can not be both a node and a mark");let i=this.nodes[a],l=i.spec.content||"",o=i.spec.marks;if(i.contentMatch=n[l]||(n[l]=xA.parse(l,this.nodes)),i.inlineContent=i.contentMatch.inlineContent,i.spec.linebreakReplacement){if(this.linebreakReplacement)throw new RangeError("Multiple linebreak nodes defined");if(!i.isInline||!i.isLeaf)throw new RangeError("Linebreak replacement nodes must be inline leaf nodes");this.linebreakReplacement=i}i.markSet=o=="_"?null:o?g9e(this,o.split(" ")):o==""||!i.inlineContent?[]:null}for(let a in this.marks){let i=this.marks[a],l=i.spec.excludes;i.excluded=l==null?[i]:l==""?[]:g9e(this,l.split(" "))}this.nodeFromJSON=a=>rS.fromJSON(this,a),this.markFromJSON=a=>Fc.fromJSON(this,a),this.topNodeType=this.nodes[this.spec.topNode||"doc"],this.cached.wrappings=Object.create(null)}node(t,r=null,n,a){if(typeof t=="string")t=this.nodeType(t);else if(t instanceof p9e){if(t.schema!=this)throw new RangeError("Node type from different schema used ("+t.name+")")}else throw new RangeError("Invalid node type: "+t);return t.createChecked(r,n,a)}text(t,r){let n=this.nodes.text;return new lme(n,n.defaultAttrs,t,Fc.setFrom(r))}mark(t,r){return typeof t=="string"&&(t=this.marks[t]),t.create(r)}nodeType(t){let r=this.nodes[t];if(!r)throw new RangeError("Unknown node type: "+t);return r}}function g9e(s,t){let r=[];for(let n=0;n-1)&&r.push(l=c)}if(!l)throw new SyntaxError("Unknown mark type: '"+t[n]+"'")}return r}function PGt(s){return s.tag!=null}function LGt(s){return s.style!=null}let n7=class GNe{constructor(t,r){this.schema=t,this.rules=r,this.tags=[],this.styles=[];let n=this.matchedStyles=[];r.forEach(a=>{if(PGt(a))this.tags.push(a);else if(LGt(a)){let i=/[^=]*/.exec(a.style)[0];n.indexOf(i)<0&&n.push(i),this.styles.push(a)}}),this.normalizeLists=!this.tags.some(a=>{if(!/^(ul|ol)\b/.test(a.tag)||!a.node)return!1;let i=t.nodes[a.node];return i.contentMatch.matchType(i)})}parse(t,r={}){let n=new y9e(this,r,!1);return n.addAll(t,Fc.none,r.from,r.to),n.finish()}parseSlice(t,r={}){let n=new y9e(this,r,!0);return n.addAll(t,Fc.none,r.from,r.to),ua.maxOpen(n.finish())}matchTag(t,r,n){for(let a=n?this.tags.indexOf(n)+1:0;at.length&&(o.charCodeAt(t.length)!=61||o.slice(t.length+1)!=r))){if(l.getAttrs){let c=l.getAttrs(r);if(c===!1)continue;l.attrs=c||void 0}return l}}}static schemaRules(t){let r=[];function n(a){let i=a.priority==null?50:a.priority,l=0;for(;l{n(l=v9e(l)),l.mark||l.ignore||l.clearMark||(l.mark=a)})}for(let a in t.nodes){let i=t.nodes[a].spec.parseDOM;i&&i.forEach(l=>{n(l=v9e(l)),l.node||l.ignore||l.mark||(l.node=a)})}return r}static fromSchema(t){return t.cached.domParser||(t.cached.domParser=new GNe(t,GNe.schemaRules(t)))}};const mlt={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},DGt={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},flt={ol:!0,ul:!0},y9=1,WNe=2,a7=4;function x9e(s,t,r){return t!=null?(t?y9:0)|(t==="full"?WNe:0):s&&s.whitespace=="pre"?y9|WNe:r&~a7}class XU{constructor(t,r,n,a,i,l){this.type=t,this.attrs=r,this.marks=n,this.solid=a,this.options=l,this.content=[],this.activeMarks=Fc.none,this.match=i||(l&a7?null:t.contentMatch)}findWrapping(t){if(!this.match){if(!this.type)return[];let r=this.type.contentMatch.fillBefore(An.from(t));if(r)this.match=this.type.contentMatch.matchFragment(r);else{let n=this.type.contentMatch,a;return(a=n.findWrapping(t.type))?(this.match=n,a):null}}return this.match.findWrapping(t.type)}finish(t){if(!(this.options&y9)){let n=this.content[this.content.length-1],a;if(n&&n.isText&&(a=/[ \t\r\n\u000c]+$/.exec(n.text))){let i=n;n.text.length==a[0].length?this.content.pop():this.content[this.content.length-1]=i.withText(i.text.slice(0,i.text.length-a[0].length))}}let r=An.from(this.content);return!t&&this.match&&(r=r.append(this.match.fillBefore(An.empty,!0))),this.type?this.type.create(this.attrs,r,this.marks):r}inlineContext(t){return this.type?this.type.inlineContent:this.content.length?this.content[0].isInline:t.parentNode&&!mlt.hasOwnProperty(t.parentNode.nodeName.toLowerCase())}}class y9e{constructor(t,r,n){this.parser=t,this.options=r,this.isOpen=n,this.open=0,this.localPreserveWS=!1;let a=r.topNode,i,l=x9e(null,r.preserveWhitespace,0)|(n?a7:0);a?i=new XU(a.type,a.attrs,Fc.none,!0,r.topMatch||a.type.contentMatch,l):n?i=new XU(null,null,Fc.none,!0,null,l):i=new XU(t.schema.topNodeType,null,Fc.none,!0,null,l),this.nodes=[i],this.find=r.findPositions,this.needsBlock=!1}get top(){return this.nodes[this.open]}addDOM(t,r){t.nodeType==3?this.addTextNode(t,r):t.nodeType==1&&this.addElement(t,r)}addTextNode(t,r){let n=t.nodeValue,a=this.top,i=a.options&WNe?"full":this.localPreserveWS||(a.options&y9)>0,{schema:l}=this.parser;if(i==="full"||a.inlineContext(t)||/[^ \t\r\n\u000c]/.test(n)){if(i)if(i==="full")n=n.replace(/\r\n?/g,` `);else if(l.linebreakReplacement&&/[\r\n]/.test(n)&&this.top.findWrapping(l.linebreakReplacement.create())){let o=n.split(/\r?\n|\r/);for(let c=0;c!c.clearMark(d)):r=r.concat(this.parser.schema.marks[c.mark].create(c.attrs)),c.consuming===!1)o=c;else break}}return r}addElementByRule(t,r,n,a){let i,l;if(r.node)if(l=this.parser.schema.nodes[r.node],l.isLeaf)this.insertNode(l.create(r.attrs),n,t.nodeName=="BR")||this.leafFallback(t,n);else{let c=this.enter(l,r.attrs||null,n,r.preserveWhitespace);c&&(i=!0,n=c)}else{let c=this.parser.schema.marks[r.mark];n=n.concat(c.create(r.attrs))}let o=this.top;if(l&&l.isLeaf)this.findInside(t);else if(a)this.addElement(t,n,a);else if(r.getContent)this.findInside(t),r.getContent(t,this.parser.schema).forEach(c=>this.insertNode(c,n,!1));else{let c=t;typeof r.contentElement=="string"?c=t.querySelector(r.contentElement):typeof r.contentElement=="function"?c=r.contentElement(t):r.contentElement&&(c=r.contentElement),this.findAround(t,c,!0),this.addAll(c,n),this.findAround(t,c,!1)}i&&this.sync(o)&&this.open--}addAll(t,r,n,a){let i=n||0;for(let l=n?t.childNodes[n]:t.firstChild,o=a==null?null:t.childNodes[a];l!=o;l=l.nextSibling,++i)this.findAtPoint(t,i),this.addDOM(l,r);this.findAtPoint(t,i)}findPlace(t,r,n){let a,i;for(let l=this.open,o=0;l>=0;l--){let c=this.nodes[l],d=c.findWrapping(t);if(d&&(!a||a.length>d.length+o)&&(a=d,i=c,!d.length))break;if(c.solid){if(n)break;o+=2}}if(!a)return null;this.sync(i);for(let l=0;l(l.type?l.type.allowsMarkType(d.type):b9e(d.type,t))?(c=d.addToSet(c),!1):!0),this.nodes.push(new XU(t,r,c,a,null,o)),this.open++,n}closeExtra(t=!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(t));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(t){for(let r=this.open;r>=0;r--){if(this.nodes[r]==t)return this.open=r,!0;this.localPreserveWS&&(this.nodes[r].options|=y9)}return!1}get currentPos(){this.closeExtra();let t=0;for(let r=this.open;r>=0;r--){let n=this.nodes[r].content;for(let a=n.length-1;a>=0;a--)t+=n[a].nodeSize;r&&t++}return t}findAtPoint(t,r){if(this.find)for(let n=0;n-1)return t.split(/\s*\|\s*/).some(this.matchesContext,this);let r=t.split("/"),n=this.options.context,a=!this.isOpen&&(!n||n.parent.type==this.nodes[0].type),i=-(n?n.depth+1:0)+(a?0:1),l=(o,c)=>{for(;o>=0;o--){let d=r[o];if(d==""){if(o==r.length-1||o==0)continue;for(;c>=i;c--)if(l(o-1,c))return!0;return!1}else{let h=c>0||c==0&&a?this.nodes[c].type:n&&c>=i?n.node(c-i).type:null;if(!h||h.name!=d&&!h.isInGroup(d))return!1;c--}}return!0};return l(r.length-1,this.open)}textblockFromContext(){let t=this.options.context;if(t)for(let r=t.depth;r>=0;r--){let n=t.node(r).contentMatchAt(t.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 RGt(s){for(let t=s.firstChild,r=null;t;t=t.nextSibling){let n=t.nodeType==1?t.nodeName.toLowerCase():null;n&&flt.hasOwnProperty(n)&&r?(r.appendChild(t),t=r):n=="li"?r=t:n&&(r=null)}}function OGt(s,t){return(s.matches||s.msMatchesSelector||s.webkitMatchesSelector||s.mozMatchesSelector).call(s,t)}function v9e(s){let t={};for(let r in s)t[r]=s[r];return t}function b9e(s,t){let r=t.schema.nodes;for(let n in r){let a=r[n];if(!a.allowsMarkType(s))continue;let i=[],l=o=>{i.push(o);for(let c=0;c{if(i.length||l.marks.length){let o=0,c=0;for(;o=0;a--){let i=this.serializeMark(t.marks[a],t.isInline,r);i&&((i.contentDOM||i.dom).appendChild(n),n=i.dom)}return n}serializeMark(t,r,n={}){let a=this.marks[t.type.name];return a&&Nue(Rbe(n),a(t,r),null,t.attrs)}static renderSpec(t,r,n=null,a){return Nue(t,r,n,a)}static fromSchema(t){return t.cached.domSerializer||(t.cached.domSerializer=new VA(this.nodesFromSchema(t),this.marksFromSchema(t)))}static nodesFromSchema(t){let r=_9e(t.nodes);return r.text||(r.text=n=>n.text),r}static marksFromSchema(t){return _9e(t.marks)}}function _9e(s){let t={};for(let r in s){let n=s[r].spec.toDOM;n&&(t[r]=n)}return t}function Rbe(s){return s.document||window.document}const w9e=new WeakMap;function FGt(s){let t=w9e.get(s);return t===void 0&&w9e.set(s,t=BGt(s)),t}function BGt(s){let t=null;function r(n){if(n&&typeof n=="object")if(Array.isArray(n))if(typeof n[0]=="string")t||(t=[]),t.push(n);else for(let a=0;a-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 l=a.indexOf(" ");l>0&&(r=a.slice(0,l),a=a.slice(l+1));let o,c=r?s.createElementNS(r,a):s.createElement(a),d=t[1],h=1;if(d&&typeof d=="object"&&d.nodeType==null&&!Array.isArray(d)){h=2;for(let m in d)if(d[m]!=null){let p=m.indexOf(" ");p>0?c.setAttributeNS(m.slice(0,p),m.slice(p+1),d[m]):m=="style"&&c.style?c.style.cssText=d[m]:c.setAttribute(m,d[m])}}for(let m=h;mh)throw new RangeError("Content hole must be the only child of its parent node");return{dom:c,contentDOM:c}}else{let{dom:x,contentDOM:y}=Nue(s,p,r,n);if(c.appendChild(x),y){if(o)throw new RangeError("Multiple content holes");o=y}}}return{dom:c,contentDOM:o}}const plt=65535,glt=Math.pow(2,16);function zGt(s,t){return s+t*glt}function j9e(s){return s&plt}function $Gt(s){return(s-(s&plt))/glt}const xlt=1,ylt=2,kue=4,vlt=8;class KNe{constructor(t,r,n){this.pos=t,this.delInfo=r,this.recover=n}get deleted(){return(this.delInfo&vlt)>0}get deletedBefore(){return(this.delInfo&(xlt|kue))>0}get deletedAfter(){return(this.delInfo&(ylt|kue))>0}get deletedAcross(){return(this.delInfo&kue)>0}}class r0{constructor(t,r=!1){if(this.ranges=t,this.inverted=r,!t.length&&r0.empty)return r0.empty}recover(t){let r=0,n=j9e(t);if(!this.inverted)for(let a=0;at)break;let d=this.ranges[o+i],h=this.ranges[o+l],m=c+d;if(t<=m){let p=d?t==c?-1:t==m?1:r:r,x=c+a+(p<0?0:h);if(n)return x;let y=t==(r<0?c:m)?null:zGt(o/3,t-c),_=t==c?ylt:t==m?xlt:kue;return(r<0?t!=c:t!=m)&&(_|=vlt),new KNe(x,_,y)}a+=h-d}return n?t+a:new KNe(t+a,0,null)}touches(t,r){let n=0,a=j9e(r),i=this.inverted?2:1,l=this.inverted?1:2;for(let o=0;ot)break;let d=this.ranges[o+i],h=c+d;if(t<=h&&o==a*3)return!0;n+=this.ranges[o+l]-d}return!1}forEach(t){let r=this.inverted?2:1,n=this.inverted?1:2;for(let a=0,i=0;a=0;r--){let a=t.getMirror(r);this.appendMap(t._maps[r].invert(),a!=null&&a>r?n-a-1:void 0)}}invert(){let t=new v9;return t.appendMappingInverted(this),t}map(t,r=1){if(this.mirror)return this._map(t,r,!0);for(let n=this.from;ni&&c!l.isAtom||!o.type.allowsMarkType(this.mark.type)?l:l.mark(this.mark.addToSet(l.marks)),a),r.openStart,r.openEnd);return Dh.fromReplace(t,this.from,this.to,i)}invert(){return new r_(this.from,this.to,this.mark)}map(t){let r=t.mapResult(this.from,1),n=t.mapResult(this.to,-1);return r.deleted&&n.deleted||r.pos>=n.pos?null:new wk(r.pos,n.pos,this.mark)}merge(t){return t instanceof wk&&t.mark.eq(this.mark)&&this.from<=t.to&&this.to>=t.from?new wk(Math.min(this.from,t.from),Math.max(this.to,t.to),this.mark):null}toJSON(){return{stepType:"addMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(t,r){if(typeof r.from!="number"||typeof r.to!="number")throw new RangeError("Invalid input for AddMarkStep.fromJSON");return new wk(r.from,r.to,t.markFromJSON(r.mark))}}Tp.jsonID("addMark",wk);class r_ extends Tp{constructor(t,r,n){super(),this.from=t,this.to=r,this.mark=n}apply(t){let r=t.slice(this.from,this.to),n=new ua(kTe(r.content,a=>a.mark(this.mark.removeFromSet(a.marks)),t),r.openStart,r.openEnd);return Dh.fromReplace(t,this.from,this.to,n)}invert(){return new wk(this.from,this.to,this.mark)}map(t){let r=t.mapResult(this.from,1),n=t.mapResult(this.to,-1);return r.deleted&&n.deleted||r.pos>=n.pos?null:new r_(r.pos,n.pos,this.mark)}merge(t){return t instanceof r_&&t.mark.eq(this.mark)&&this.from<=t.to&&this.to>=t.from?new r_(Math.min(this.from,t.from),Math.max(this.to,t.to),this.mark):null}toJSON(){return{stepType:"removeMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(t,r){if(typeof r.from!="number"||typeof r.to!="number")throw new RangeError("Invalid input for RemoveMarkStep.fromJSON");return new r_(r.from,r.to,t.markFromJSON(r.mark))}}Tp.jsonID("removeMark",r_);class jk extends Tp{constructor(t,r){super(),this.pos=t,this.mark=r}apply(t){let r=t.nodeAt(this.pos);if(!r)return Dh.fail("No node at mark step's position");let n=r.type.create(r.attrs,null,this.mark.addToSet(r.marks));return Dh.fromReplace(t,this.pos,this.pos+1,new ua(An.from(n),0,r.isLeaf?0:1))}invert(t){let r=t.nodeAt(this.pos);if(r){let n=this.mark.addToSet(r.marks);if(n.length==r.marks.length){for(let a=0;an.pos?null:new rf(r.pos,n.pos,a,i,this.slice,this.insert,this.structure)}toJSON(){let t={stepType:"replaceAround",from:this.from,to:this.to,gapFrom:this.gapFrom,gapTo:this.gapTo,insert:this.insert};return this.slice.size&&(t.slice=this.slice.toJSON()),this.structure&&(t.structure=!0),t}static fromJSON(t,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 rf(r.from,r.to,r.gapFrom,r.gapTo,ua.fromJSON(t,r.slice),r.insert,!!r.structure)}}Tp.jsonID("replaceAround",rf);function YNe(s,t,r){let n=s.resolve(t),a=r-t,i=n.depth;for(;a>0&&i>0&&n.indexAfter(i)==n.node(i).childCount;)i--,a--;if(a>0){let l=n.node(i).maybeChild(n.indexAfter(i));for(;a>0;){if(!l||l.isLeaf)return!0;l=l.firstChild,a--}}return!1}function UGt(s,t,r,n){let a=[],i=[],l,o;s.doc.nodesBetween(t,r,(c,d,h)=>{if(!c.isInline)return;let m=c.marks;if(!n.isInSet(m)&&h.type.allowsMarkType(n.type)){let p=Math.max(d,t),x=Math.min(d+c.nodeSize,r),y=n.addToSet(m);for(let _=0;_s.step(c)),i.forEach(c=>s.step(c))}function qGt(s,t,r,n){let a=[],i=0;s.doc.nodesBetween(t,r,(l,o)=>{if(!l.isInline)return;i++;let c=null;if(n instanceof rxe){let d=l.marks,h;for(;h=n.isInSet(d);)(c||(c=[])).push(h),d=h.removeFromSet(d)}else n?n.isInSet(l.marks)&&(c=[n]):c=l.marks;if(c&&c.length){let d=Math.min(o+l.nodeSize,r);for(let h=0;hs.step(new r_(l.from,l.to,l.style)))}function STe(s,t,r,n=r.contentMatch,a=!0){let i=s.doc.nodeAt(t),l=[],o=t+1;for(let c=0;c=0;c--)s.step(l[c])}function VGt(s,t,r){return(t==0||s.canReplace(t,s.childCount))&&(r==s.childCount||s.canReplace(0,r))}function b8(s){let r=s.parent.content.cutByIndex(s.startIndex,s.endIndex);for(let n=s.depth,a=0,i=0;;--n){let l=s.$from.node(n),o=s.$from.index(n)+a,c=s.$to.indexAfter(n)-i;if(nr;y--)_||n.index(y)>0?(_=!0,h=An.from(n.node(y).copy(h)),m++):c--;let p=An.empty,x=0;for(let y=i,_=!1;y>r;y--)_||a.after(y+1)=0;l--){if(n.size){let o=r[l].type.contentMatch.matchFragment(n);if(!o||!o.validEnd)throw new RangeError("Wrapper type given to Transform.wrap does not form valid content of its parent wrapper")}n=An.from(r[l].type.create(r[l].attrs,n))}let a=t.start,i=t.end;s.step(new rf(a,i,a,i,new ua(n,0,0),r.length,!0))}function YGt(s,t,r,n,a){if(!n.isTextblock)throw new RangeError("Type given to setBlockType should be a textblock");let i=s.steps.length;s.doc.nodesBetween(t,r,(l,o)=>{let c=typeof a=="function"?a(l):a;if(l.isTextblock&&!l.hasMarkup(n,c)&&ZGt(s.doc,s.mapping.slice(i).map(o),n)){let d=null;if(n.schema.linebreakReplacement){let x=n.whitespace=="pre",y=!!n.contentMatch.matchType(n.schema.linebreakReplacement);x&&!y?d=!1:!x&&y&&(d=!0)}d===!1&&_lt(s,l,o,i),STe(s,s.mapping.slice(i).map(o,1),n,void 0,d===null);let h=s.mapping.slice(i),m=h.map(o,1),p=h.map(o+l.nodeSize,1);return s.step(new rf(m,p,m+1,p-1,new ua(An.from(n.create(c,null,l.marks)),0,0),1,!0)),d===!0&&blt(s,l,o,i),!1}})}function blt(s,t,r,n){t.forEach((a,i)=>{if(a.isText){let l,o=/\r?\n|\r/g;for(;l=o.exec(a.text);){let c=s.mapping.slice(n).map(r+1+i+l.index);s.replaceWith(c,c+1,t.type.schema.linebreakReplacement.create())}}})}function _lt(s,t,r,n){t.forEach((a,i)=>{if(a.type==a.type.schema.linebreakReplacement){let l=s.mapping.slice(n).map(r+1+i);s.replaceWith(l,l+1,t.type.schema.text(` `))}})}function ZGt(s,t,r){let n=s.resolve(t),a=n.index();return n.parent.canReplaceWith(a,a+1,r)}function XGt(s,t,r,n,a){let i=s.doc.nodeAt(t);if(!i)throw new RangeError("No node at given position");r||(r=i.type);let l=r.create(n,null,a||i.marks);if(i.isLeaf)return s.replaceWith(t,t+i.nodeSize,l);if(!r.validContent(i.content))throw new RangeError("Invalid content for node type "+r.name);s.step(new rf(t,t+i.nodeSize,t+1,t+i.nodeSize-1,new ua(An.from(l),0,0),1,!0))}function cP(s,t,r=1,n){let a=s.resolve(t),i=a.depth-r,l=n&&n[n.length-1]||a.parent;if(i<0||a.parent.type.spec.isolating||!a.parent.canReplace(a.index(),a.parent.childCount)||!l.type.validContent(a.parent.content.cutByIndex(a.index(),a.parent.childCount)))return!1;for(let d=a.depth-1,h=r-2;d>i;d--,h--){let m=a.node(d),p=a.index(d);if(m.type.spec.isolating)return!1;let x=m.content.cutByIndex(p,m.childCount),y=n&&n[h+1];y&&(x=x.replaceChild(0,y.type.create(y.attrs)));let _=n&&n[h]||m;if(!m.canReplace(p+1,m.childCount)||!_.type.validContent(x))return!1}let o=a.indexAfter(i),c=n&&n[0];return a.node(i).canReplaceWith(o,o,c?c.type:a.node(i+1).type)}function QGt(s,t,r=1,n){let a=s.doc.resolve(t),i=An.empty,l=An.empty;for(let o=a.depth,c=a.depth-r,d=r-1;o>c;o--,d--){i=An.from(a.node(o).copy(i));let h=n&&n[d];l=An.from(h?h.type.create(h.attrs,l):a.node(o).copy(l))}s.step(new Ih(t,t,new ua(i.append(l),r,r),!0))}function HS(s,t){let r=s.resolve(t),n=r.index();return wlt(r.nodeBefore,r.nodeAfter)&&r.parent.canReplace(n,n+1)}function JGt(s,t){t.content.size||s.type.compatibleContent(t.type);let r=s.contentMatchAt(s.childCount),{linebreakReplacement:n}=s.type.schema;for(let a=0;a0?(i=n.node(a+1),o++,l=n.node(a).maybeChild(o)):(i=n.node(a).maybeChild(o-1),l=n.node(a+1)),i&&!i.isTextblock&&wlt(i,l)&&n.node(a).canReplace(o,o+1))return t;if(a==0)break;t=r<0?n.before(a):n.after(a)}}function eWt(s,t,r){let n=null,{linebreakReplacement:a}=s.doc.type.schema,i=s.doc.resolve(t-r),l=i.node().type;if(a&&l.inlineContent){let h=l.whitespace=="pre",m=!!l.contentMatch.matchType(a);h&&!m?n=!1:!h&&m&&(n=!0)}let o=s.steps.length;if(n===!1){let h=s.doc.resolve(t+r);_lt(s,h.node(),h.before(),o)}l.inlineContent&&STe(s,t+r-1,l,i.node().contentMatchAt(i.index()),n==null);let c=s.mapping.slice(o),d=c.map(t-r);if(s.step(new Ih(d,c.map(t+r,-1),ua.empty,!0)),n===!0){let h=s.doc.resolve(d);blt(s,h.node(),h.before(),s.steps.length)}return s}function tWt(s,t,r){let n=s.resolve(t);if(n.parent.canReplaceWith(n.index(),n.index(),r))return t;if(n.parentOffset==0)for(let a=n.depth-1;a>=0;a--){let i=n.index(a);if(n.node(a).canReplaceWith(i,i,r))return n.before(a+1);if(i>0)return null}if(n.parentOffset==n.parent.content.size)for(let a=n.depth-1;a>=0;a--){let i=n.indexAfter(a);if(n.node(a).canReplaceWith(i,i,r))return n.after(a+1);if(i=0;l--){let o=l==n.depth?0:n.pos<=(n.start(l+1)+n.end(l+1))/2?-1:1,c=n.index(l)+(o>0?1:0),d=n.node(l),h=!1;if(i==1)h=d.canReplace(c,c,a);else{let m=d.contentMatchAt(c).findWrapping(a.firstChild.type);h=m&&d.canReplaceWith(c,c,m[0])}if(h)return o==0?n.pos:o<0?n.before(l+1):n.after(l+1)}return null}function axe(s,t,r=t,n=ua.empty){if(t==r&&!n.size)return null;let a=s.resolve(t),i=s.resolve(r);return Nlt(a,i,n)?new Ih(t,r,n):new sWt(a,i,n).fit()}function Nlt(s,t,r){return!r.openStart&&!r.openEnd&&s.start()==t.start()&&s.parent.canReplace(s.index(),t.index(),r.content)}class sWt{constructor(t,r,n){this.$from=t,this.$to=r,this.unplaced=n,this.frontier=[],this.placed=An.empty;for(let a=0;a<=t.depth;a++){let i=t.node(a);this.frontier.push({type:i.type,match:i.contentMatchAt(t.indexAfter(a))})}for(let a=t.depth;a>0;a--)this.placed=An.from(t.node(a).copy(this.placed))}get depth(){return this.frontier.length-1}fit(){for(;this.unplaced.size;){let d=this.findFittable();d?this.placeNodes(d):this.openMore()||this.dropNode()}let t=this.mustMoveInline(),r=this.placed.size-this.depth-this.$from.depth,n=this.$from,a=this.close(t<0?this.$to:n.doc.resolve(t));if(!a)return null;let i=this.placed,l=n.depth,o=a.depth;for(;l&&o&&i.childCount==1;)i=i.firstChild.content,l--,o--;let c=new ua(i,l,o);return t>-1?new rf(n.pos,t,this.$to.pos,this.$to.end(),c,r):c.size||n.pos!=this.$to.pos?new Ih(n.pos,a.pos,c):null}findFittable(){let t=this.unplaced.openStart;for(let r=this.unplaced.content,n=0,a=this.unplaced.openEnd;n1&&(a=0),i.type.spec.isolating&&a<=n){t=n;break}r=i.content}for(let r=1;r<=2;r++)for(let n=r==1?t:this.unplaced.openStart;n>=0;n--){let a,i=null;n?(i=Fbe(this.unplaced.content,n-1).firstChild,a=i.content):a=this.unplaced.content;let l=a.firstChild;for(let o=this.depth;o>=0;o--){let{type:c,match:d}=this.frontier[o],h,m=null;if(r==1&&(l?d.matchType(l.type)||(m=d.fillBefore(An.from(l),!1)):i&&c.compatibleContent(i.type)))return{sliceDepth:n,frontierDepth:o,parent:i,inject:m};if(r==2&&l&&(h=d.findWrapping(l.type)))return{sliceDepth:n,frontierDepth:o,parent:i,wrap:h};if(i&&d.matchType(i.type))break}}}openMore(){let{content:t,openStart:r,openEnd:n}=this.unplaced,a=Fbe(t,r);return!a.childCount||a.firstChild.isLeaf?!1:(this.unplaced=new ua(t,r+1,Math.max(n,a.size+r>=t.size-n?r+1:0)),!0)}dropNode(){let{content:t,openStart:r,openEnd:n}=this.unplaced,a=Fbe(t,r);if(a.childCount<=1&&r>0){let i=t.size-r<=r+a.size;this.unplaced=new ua(yO(t,r-1,1),r-1,i?r-1:n)}else this.unplaced=new ua(yO(t,r,1),r,n)}placeNodes({sliceDepth:t,frontierDepth:r,parent:n,inject:a,wrap:i}){for(;this.depth>r;)this.closeFrontierNode();if(i)for(let _=0;_1||c==0||_.content.size)&&(m=b,h.push(klt(_.mark(p.allowedMarks(_.marks)),d==1?c:0,d==o.childCount?x:-1)))}let y=d==o.childCount;y||(x=-1),this.placed=vO(this.placed,r,An.from(h)),this.frontier[r].match=m,y&&x<0&&n&&n.type==this.frontier[this.depth].type&&this.frontier.length>1&&this.closeFrontierNode();for(let _=0,b=o;_1&&a==this.$to.end(--n);)++a;return a}findCloseLevel(t){e:for(let r=Math.min(this.depth,t.depth);r>=0;r--){let{match:n,type:a}=this.frontier[r],i=r=0;o--){let{match:c,type:d}=this.frontier[o],h=Bbe(t,o,d,c,!0);if(!h||h.childCount)continue e}return{depth:r,fit:l,move:i?t.doc.resolve(t.after(r+1)):t}}}}close(t){let r=this.findCloseLevel(t);if(!r)return null;for(;this.depth>r.depth;)this.closeFrontierNode();r.fit.childCount&&(this.placed=vO(this.placed,r.depth,r.fit)),t=r.move;for(let n=r.depth+1;n<=t.depth;n++){let a=t.node(n),i=a.type.contentMatch.fillBefore(a.content,!0,t.index(n));this.openFrontierNode(a.type,a.attrs,i)}return t}openFrontierNode(t,r=null,n){let a=this.frontier[this.depth];a.match=a.match.matchType(t),this.placed=vO(this.placed,this.depth,An.from(t.create(r,n))),this.frontier.push({type:t,match:t.contentMatch})}closeFrontierNode(){let r=this.frontier.pop().match.fillBefore(An.empty,!0);r.childCount&&(this.placed=vO(this.placed,this.frontier.length,r))}}function yO(s,t,r){return t==0?s.cutByIndex(r,s.childCount):s.replaceChild(0,s.firstChild.copy(yO(s.firstChild.content,t-1,r)))}function vO(s,t,r){return t==0?s.append(r):s.replaceChild(s.childCount-1,s.lastChild.copy(vO(s.lastChild.content,t-1,r)))}function Fbe(s,t){for(let r=0;r1&&(n=n.replaceChild(0,klt(n.firstChild,t-1,n.childCount==1?r-1:0))),t>0&&(n=s.type.contentMatch.fillBefore(n).append(n),r<=0&&(n=n.append(s.type.contentMatch.matchFragment(n).fillBefore(An.empty,!0)))),s.copy(n)}function Bbe(s,t,r,n,a){let i=s.node(t),l=a?s.indexAfter(t):s.index(t);if(l==i.childCount&&!r.compatibleContent(i.type))return null;let o=n.fillBefore(i.content,!0,l);return o&&!rWt(r,i.content,l)?o:null}function rWt(s,t,r){for(let n=r;n0;p--,x--){let y=a.node(p).type.spec;if(y.defining||y.definingAsContext||y.isolating)break;l.indexOf(p)>-1?o=p:a.before(p)==x&&l.splice(1,0,-p)}let c=l.indexOf(o),d=[],h=n.openStart;for(let p=n.content,x=0;;x++){let y=p.firstChild;if(d.push(y),x==n.openStart)break;p=y.content}for(let p=h-1;p>=0;p--){let x=d[p],y=nWt(x.type);if(y&&!x.sameMarkup(a.node(Math.abs(o)-1)))h=p;else if(y||!x.type.isTextblock)break}for(let p=n.openStart;p>=0;p--){let x=(p+h+1)%(n.openStart+1),y=d[x];if(y)for(let _=0;_=0&&(s.replace(t,r,n),!(s.steps.length>m));p--){let x=l[p];x<0||(t=a.before(x),r=i.after(x))}}function Slt(s,t,r,n,a){if(tn){let i=a.contentMatchAt(0),l=i.fillBefore(s).append(s);s=l.append(i.matchFragment(l).fillBefore(An.empty,!0))}return s}function iWt(s,t,r,n){if(!n.isInline&&t==r&&s.doc.resolve(t).parent.content.size){let a=tWt(s.doc,t,n.type);a!=null&&(t=r=a)}s.replaceRange(t,r,new ua(An.from(n),0,0))}function oWt(s,t,r){let n=s.doc.resolve(t),a=s.doc.resolve(r);if(n.parent.isTextblock&&a.parent.isTextblock&&n.start()!=a.start()&&n.parentOffset==0&&a.parentOffset==0){let l=n.sharedDepth(r),o=!1;for(let c=n.depth;c>l;c--)n.node(c).type.spec.isolating&&(o=!0);for(let c=a.depth;c>l;c--)a.node(c).type.spec.isolating&&(o=!0);if(!o){for(let c=n.depth;c>0&&t==n.start(c);c--)t=n.before(c);for(let c=a.depth;c>0&&r==a.start(c);c--)r=a.before(c);n=s.doc.resolve(t),a=s.doc.resolve(r)}}let i=Clt(n,a);for(let l=0;l0&&(c||n.node(o-1).canReplace(n.index(o-1),a.indexAfter(o-1))))return s.delete(n.before(o),a.after(o))}for(let l=1;l<=n.depth&&l<=a.depth;l++)if(t-n.start(l)==n.depth-l&&r>n.end(l)&&a.end(l)-r!=a.depth-l&&n.start(l-1)==a.start(l-1)&&n.node(l-1).canReplace(n.index(l-1),a.index(l-1)))return s.delete(n.before(l),r);s.delete(t,r)}function Clt(s,t){let r=[],n=Math.min(s.depth,t.depth);for(let a=n;a>=0;a--){let i=s.start(a);if(it.pos+(t.depth-a)||s.node(a).type.spec.isolating||t.node(a).type.spec.isolating)break;(i==t.start(a)||a==s.depth&&a==t.depth&&s.parent.inlineContent&&t.parent.inlineContent&&a&&t.start(a-1)==i-1)&&r.push(a)}return r}class dP extends Tp{constructor(t,r,n){super(),this.pos=t,this.attr=r,this.value=n}apply(t){let r=t.nodeAt(this.pos);if(!r)return Dh.fail("No node at attribute step's position");let n=Object.create(null);for(let i in r.attrs)n[i]=r.attrs[i];n[this.attr]=this.value;let a=r.type.create(n,null,r.marks);return Dh.fromReplace(t,this.pos,this.pos+1,new ua(An.from(a),0,r.isLeaf?0:1))}getMap(){return r0.empty}invert(t){return new dP(this.pos,this.attr,t.nodeAt(this.pos).attrs[this.attr])}map(t){let r=t.mapResult(this.pos,1);return r.deletedAfter?null:new dP(r.pos,this.attr,this.value)}toJSON(){return{stepType:"attr",pos:this.pos,attr:this.attr,value:this.value}}static fromJSON(t,r){if(typeof r.pos!="number"||typeof r.attr!="string")throw new RangeError("Invalid input for AttrStep.fromJSON");return new dP(r.pos,r.attr,r.value)}}Tp.jsonID("attr",dP);class b9 extends Tp{constructor(t,r){super(),this.attr=t,this.value=r}apply(t){let r=Object.create(null);for(let a in t.attrs)r[a]=t.attrs[a];r[this.attr]=this.value;let n=t.type.create(r,t.content,t.marks);return Dh.ok(n)}getMap(){return r0.empty}invert(t){return new b9(this.attr,t.attrs[this.attr])}map(t){return this}toJSON(){return{stepType:"docAttr",attr:this.attr,value:this.value}}static fromJSON(t,r){if(typeof r.attr!="string")throw new RangeError("Invalid input for DocAttrStep.fromJSON");return new b9(r.attr,r.value)}}Tp.jsonID("docAttr",b9);let iL=class extends Error{};iL=function s(t){let r=Error.call(this,t);return r.__proto__=s.prototype,r};iL.prototype=Object.create(Error.prototype);iL.prototype.constructor=iL;iL.prototype.name="TransformError";let TTe=class{constructor(t){this.doc=t,this.steps=[],this.docs=[],this.mapping=new v9}get before(){return this.docs.length?this.docs[0]:this.doc}step(t){let r=this.maybeStep(t);if(r.failed)throw new iL(r.failed);return this}maybeStep(t){let r=t.apply(this.doc);return r.failed||this.addStep(t,r.doc),r}get docChanged(){return this.steps.length>0}changedRange(){let t=1e9,r=-1e9;for(let n=0;n{t=Math.min(t,o),r=Math.max(r,c)})}return t==1e9?null:{from:t,to:r}}addStep(t,r){this.docs.push(this.doc),this.steps.push(t),this.mapping.appendMap(t.getMap()),this.doc=r}replace(t,r=t,n=ua.empty){let a=axe(this.doc,t,r,n);return a&&this.step(a),this}replaceWith(t,r,n){return this.replace(t,r,new ua(An.from(n),0,0))}delete(t,r){return this.replace(t,r,ua.empty)}insert(t,r){return this.replaceWith(t,t,r)}replaceRange(t,r,n){return aWt(this,t,r,n),this}replaceRangeWith(t,r,n){return iWt(this,t,r,n),this}deleteRange(t,r){return oWt(this,t,r),this}lift(t,r){return HGt(this,t,r),this}join(t,r=1){return eWt(this,t,r),this}wrap(t,r){return KGt(this,t,r),this}setBlockType(t,r=t,n,a=null){return YGt(this,t,r,n,a),this}setNodeMarkup(t,r,n=null,a){return XGt(this,t,r,n,a),this}setNodeAttribute(t,r,n){return this.step(new dP(t,r,n)),this}setDocAttribute(t,r){return this.step(new b9(t,r)),this}addNodeMark(t,r){return this.step(new jk(t,r)),this}removeNodeMark(t,r){let n=this.doc.nodeAt(t);if(!n)throw new RangeError("No node at position "+t);if(r instanceof Fc)r.isInSet(n.marks)&&this.step(new yA(t,r));else{let a=n.marks,i,l=[];for(;i=r.isInSet(a);)l.push(new yA(t,i)),a=i.removeFromSet(a);for(let o=l.length-1;o>=0;o--)this.step(l[o])}return this}split(t,r=1,n){return QGt(this,t,r,n),this}addMark(t,r,n){return UGt(this,t,r,n),this}removeMark(t,r,n){return qGt(this,t,r,n),this}clearIncompatible(t,r,n){return STe(this,t,r,n),this}};const zbe=Object.create(null);class Hi{constructor(t,r,n){this.$anchor=t,this.$head=r,this.ranges=n||[new Tlt(t.min(r),t.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 t=this.ranges;for(let r=0;r=0;i--){let l=r<0?q6(t.node(0),t.node(i),t.before(i+1),t.index(i),r,n):q6(t.node(0),t.node(i),t.after(i+1),t.index(i)+1,r,n);if(l)return l}return null}static near(t,r=1){return this.findFrom(t,r)||this.findFrom(t,-r)||new Ky(t.node(0))}static atStart(t){return q6(t,t,0,0,1)||new Ky(t)}static atEnd(t){return q6(t,t,t.content.size,t.childCount,-1)||new Ky(t)}static fromJSON(t,r){if(!r||!r.type)throw new RangeError("Invalid input for Selection.fromJSON");let n=zbe[r.type];if(!n)throw new RangeError(`No selection type ${r.type} defined`);return n.fromJSON(t,r)}static jsonID(t,r){if(t in zbe)throw new RangeError("Duplicate use of selection JSON ID "+t);return zbe[t]=r,r.prototype.jsonID=t,r}getBookmark(){return Ri.between(this.$anchor,this.$head).getBookmark()}}Hi.prototype.visible=!0;class Tlt{constructor(t,r){this.$from=t,this.$to=r}}let k9e=!1;function S9e(s){!k9e&&!s.parent.inlineContent&&(k9e=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+s.parent.type.name+")"))}class Ri extends Hi{constructor(t,r=t){S9e(t),S9e(r),super(t,r)}get $cursor(){return this.$anchor.pos==this.$head.pos?this.$head:null}map(t,r){let n=t.resolve(r.map(this.head));if(!n.parent.inlineContent)return Hi.near(n);let a=t.resolve(r.map(this.anchor));return new Ri(a.parent.inlineContent?a:n,n)}replace(t,r=ua.empty){if(super.replace(t,r),r==ua.empty){let n=this.$from.marksAcross(this.$to);n&&t.ensureMarks(n)}}eq(t){return t instanceof Ri&&t.anchor==this.anchor&&t.head==this.head}getBookmark(){return new ixe(this.anchor,this.head)}toJSON(){return{type:"text",anchor:this.anchor,head:this.head}}static fromJSON(t,r){if(typeof r.anchor!="number"||typeof r.head!="number")throw new RangeError("Invalid input for TextSelection.fromJSON");return new Ri(t.resolve(r.anchor),t.resolve(r.head))}static create(t,r,n=r){let a=t.resolve(r);return new this(a,n==r?a:t.resolve(n))}static between(t,r,n){let a=t.pos-r.pos;if((!n||a)&&(n=a>=0?1:-1),!r.parent.inlineContent){let i=Hi.findFrom(r,n,!0)||Hi.findFrom(r,-n,!0);if(i)r=i.$head;else return Hi.near(r,n)}return t.parent.inlineContent||(a==0?t=r:(t=(Hi.findFrom(t,-n,!0)||Hi.findFrom(t,n,!0)).$anchor,t.pos0?0:1);a>0?l=0;l+=a){let o=t.child(l);if(o.isAtom){if(!i&&Si.isSelectable(o))return Si.create(s,r-(a<0?o.nodeSize:0))}else{let c=q6(s,o,r+a,a<0?o.childCount:0,a,i);if(c)return c}r+=o.nodeSize*a}return null}function C9e(s,t,r){let n=s.steps.length-1;if(n{l==null&&(l=h)}),s.setSelection(Hi.near(s.doc.resolve(l),r))}const T9e=1,QU=2,E9e=4;class cWt extends TTe{constructor(t){super(t.doc),this.curSelectionFor=0,this.updated=0,this.meta=Object.create(null),this.time=Date.now(),this.curSelection=t.selection,this.storedMarks=t.storedMarks}get selection(){return this.curSelectionFor0}setStoredMarks(t){return this.storedMarks=t,this.updated|=QU,this}ensureMarks(t){return Fc.sameSet(this.storedMarks||this.selection.$from.marks(),t)||this.setStoredMarks(t),this}addStoredMark(t){return this.ensureMarks(t.addToSet(this.storedMarks||this.selection.$head.marks()))}removeStoredMark(t){return this.ensureMarks(t.removeFromSet(this.storedMarks||this.selection.$head.marks()))}get storedMarksSet(){return(this.updated&QU)>0}addStep(t,r){super.addStep(t,r),this.updated=this.updated&~QU,this.storedMarks=null}setTime(t){return this.time=t,this}replaceSelection(t){return this.selection.replace(this,t),this}replaceSelectionWith(t,r=!0){let n=this.selection;return r&&(t=t.mark(this.storedMarks||(n.empty?n.$from.marks():n.$from.marksAcross(n.$to)||Fc.none))),n.replaceWith(this,t),this}deleteSelection(){return this.selection.replace(this),this}insertText(t,r,n){let a=this.doc.type.schema;if(r==null)return t?this.replaceSelectionWith(a.text(t),!0):this.deleteSelection();{if(n==null&&(n=r),!t)return this.deleteRange(r,n);let i=this.storedMarks;if(!i){let l=this.doc.resolve(r);i=n==r?l.marks():l.marksAcross(this.doc.resolve(n))}return this.replaceRangeWith(r,n,a.text(t,i)),!this.selection.empty&&this.selection.to==r+t.length&&this.setSelection(Hi.near(this.selection.$to)),this}}setMeta(t,r){return this.meta[typeof t=="string"?t:t.key]=r,this}getMeta(t){return this.meta[typeof t=="string"?t:t.key]}get isGeneric(){for(let t in this.meta)return!1;return!0}scrollIntoView(){return this.updated|=E9e,this}get scrolledIntoView(){return(this.updated&E9e)>0}}function A9e(s,t){return!t||!s?s:s.bind(t)}class bO{constructor(t,r,n){this.name=t,this.init=A9e(r.init,n),this.apply=A9e(r.apply,n)}}const dWt=[new bO("doc",{init(s){return s.doc||s.schema.topNodeType.createAndFill()},apply(s){return s.doc}}),new bO("selection",{init(s,t){return s.selection||Hi.atStart(t.doc)},apply(s){return s.selection}}),new bO("storedMarks",{init(s){return s.storedMarks||null},apply(s,t,r,n){return n.selection.$cursor?s.storedMarks:null}}),new bO("scrollToSelection",{init(){return 0},apply(s,t){return s.scrolledIntoView?t+1:t}})];class $be{constructor(t,r){this.schema=t,this.plugins=[],this.pluginsByKey=Object.create(null),this.fields=dWt.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 bO(n.key,n.spec.state,n))})}}class uI{constructor(t){this.config=t}get schema(){return this.config.schema}get plugins(){return this.config.plugins}apply(t){return this.applyTransaction(t).state}filterTransaction(t,r=-1){for(let n=0;nn.toJSON())),t&&typeof t=="object")for(let n in t){if(n=="doc"||n=="selection")throw new RangeError("The JSON fields `doc` and `selection` are reserved");let a=t[n],i=a.spec.state;i&&i.toJSON&&(r[n]=i.toJSON.call(a,this[a.key]))}return r}static fromJSON(t,r,n){if(!r)throw new RangeError("Invalid input for EditorState.fromJSON");if(!t.schema)throw new RangeError("Required config field 'schema' missing");let a=new $be(t.schema,t.plugins),i=new uI(a);return a.fields.forEach(l=>{if(l.name=="doc")i.doc=rS.fromJSON(t.schema,r.doc);else if(l.name=="selection")i.selection=Hi.fromJSON(i.doc,r.selection);else if(l.name=="storedMarks")r.storedMarks&&(i.storedMarks=r.storedMarks.map(t.schema.markFromJSON));else{if(n)for(let o in n){let c=n[o],d=c.spec.state;if(c.key==l.name&&d&&d.fromJSON&&Object.prototype.hasOwnProperty.call(r,o)){i[l.name]=d.fromJSON.call(c,t,r[o],i);return}}i[l.name]=l.init(t,i)}}),i}}function Elt(s,t,r){for(let n in s){let a=s[n];a instanceof Function?a=a.bind(t):n=="handleDOMEvents"&&(a=Elt(a,t,{})),r[n]=a}return r}class jm{constructor(t){this.spec=t,this.props={},t.props&&Elt(t.props,this,this.props),this.key=t.key?t.key.key:Alt("plugin")}getState(t){return t[this.key]}}const Ube=Object.create(null);function Alt(s){return s in Ube?s+"$"+ ++Ube[s]:(Ube[s]=0,s+"$")}class Ep{constructor(t="key"){this.key=Alt(t)}get(t){return t.config.pluginsByKey[this.key]}getState(t){return t[this.key]}}const Lf=function(s){for(var t=0;;t++)if(s=s.previousSibling,!s)return t},oL=function(s){let t=s.assignedSlot||s.parentNode;return t&&t.nodeType==11?t.host:t};let ZNe=null;const f2=function(s,t,r){let n=ZNe||(ZNe=document.createRange());return n.setEnd(s,r??s.nodeValue.length),n.setStart(s,t||0),n},uWt=function(){ZNe=null},vA=function(s,t,r,n){return r&&(M9e(s,t,r,n,-1)||M9e(s,t,r,n,1))},hWt=/^(img|br|input|textarea|hr)$/i;function M9e(s,t,r,n,a){for(var i;;){if(s==r&&t==n)return!0;if(t==(a<0?0:Iy(s))){let l=s.parentNode;if(!l||l.nodeType!=1||cz(s)||hWt.test(s.nodeName)||s.contentEditable=="false")return!1;t=Lf(s)+(a<0?0:1),s=l}else if(s.nodeType==1){let l=s.childNodes[t+(a<0?-1:0)];if(l.nodeType==1&&l.contentEditable=="false")if(!((i=l.pmViewDesc)===null||i===void 0)&&i.ignoreForSelection)t+=a;else return!1;else s=l,t=a<0?Iy(s):0}else return!1}}function Iy(s){return s.nodeType==3?s.nodeValue.length:s.childNodes.length}function mWt(s,t){for(;;){if(s.nodeType==3&&t)return s;if(s.nodeType==1&&t>0){if(s.contentEditable=="false")return null;s=s.childNodes[t-1],t=Iy(s)}else if(s.parentNode&&!cz(s))t=Lf(s),s=s.parentNode;else return null}}function fWt(s,t){for(;;){if(s.nodeType==3&&t2),Sy=lL||(P_?/Mac/.test(P_.platform):!1),Plt=P_?/Win/.test(P_.platform):!1,P2=/Android \d/.test(GS),dz=!!I9e&&"webkitFontSmoothing"in I9e.documentElement.style,yWt=dz?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0;function vWt(s){let t=s.defaultView&&s.defaultView.visualViewport;return t?{left:0,right:t.width,top:0,bottom:t.height}:{left:0,right:s.documentElement.clientWidth,top:0,bottom:s.documentElement.clientHeight}}function e2(s,t){return typeof s=="number"?s:s[t]}function bWt(s){let t=s.getBoundingClientRect(),r=t.width/s.offsetWidth||1,n=t.height/s.offsetHeight||1;return{left:t.left,right:t.left+s.clientWidth*r,top:t.top,bottom:t.top+s.clientHeight*n}}function P9e(s,t,r){let n=s.someProp("scrollThreshold")||0,a=s.someProp("scrollMargin")||5,i=s.dom.ownerDocument;for(let l=r||s.dom;l;){if(l.nodeType!=1){l=oL(l);continue}let o=l,c=o==i.body,d=c?vWt(i):bWt(o),h=0,m=0;if(t.topd.bottom-e2(n,"bottom")&&(m=t.bottom-t.top>d.bottom-d.top?t.top+e2(a,"top")-d.top:t.bottom-d.bottom+e2(a,"bottom")),t.leftd.right-e2(n,"right")&&(h=t.right-d.right+e2(a,"right")),h||m)if(c)i.defaultView.scrollBy(h,m);else{let x=o.scrollLeft,y=o.scrollTop;m&&(o.scrollTop+=m),h&&(o.scrollLeft+=h);let _=o.scrollLeft-x,b=o.scrollTop-y;t={left:t.left-_,top:t.top-b,right:t.right-_,bottom:t.bottom-b}}let p=c?"fixed":getComputedStyle(l).position;if(/^(fixed|sticky)$/.test(p))break;l=p=="absolute"?l.offsetParent:oL(l)}}function _Wt(s){let t=s.dom.getBoundingClientRect(),r=Math.max(0,t.top),n,a;for(let i=(t.left+t.right)/2,l=r+1;l=r-20){n=o,a=c.top;break}}return{refDOM:n,refTop:a,stack:Llt(s.dom)}}function Llt(s){let t=[],r=s.ownerDocument;for(let n=s;n&&(t.push({dom:n,top:n.scrollTop,left:n.scrollLeft}),s!=r);n=oL(n));return t}function wWt({refDOM:s,refTop:t,stack:r}){let n=s?s.getBoundingClientRect().top:0;Dlt(r,n==0?0:n-t)}function Dlt(s,t){for(let r=0;r=o){l=Math.max(y.bottom,l),o=Math.min(y.top,o);let _=y.left>t.left?y.left-t.left:y.right=(y.left+y.right)/2?1:0));continue}}else y.top>t.top&&!c&&y.left<=t.left&&y.right>=t.left&&(c=h,d={left:Math.max(y.left,Math.min(y.right,t.left)),top:y.top});!r&&(t.left>=y.right&&t.top>=y.top||t.left>=y.left&&t.top>=y.bottom)&&(i=m+1)}}return!r&&c&&(r=c,a=d,n=0),r&&r.nodeType==3?NWt(r,a):!r||n&&r.nodeType==1?{node:s,offset:i}:Rlt(r,a)}function NWt(s,t){let r=s.nodeValue.length,n=document.createRange(),a;for(let i=0;i=(l.left+l.right)/2?1:0)};break}}return n.detach(),a||{node:s,offset:0}}function ATe(s,t){return s.left>=t.left-1&&s.left<=t.right+1&&s.top>=t.top-1&&s.top<=t.bottom+1}function kWt(s,t){let r=s.parentNode;return r&&/^li$/i.test(r.nodeName)&&t.left(l.left+l.right)/2?1:-1}return s.docView.posFromDOM(n,a,i)}function CWt(s,t,r,n){let a=-1;for(let i=t,l=!1;i!=s.dom;){let o=s.docView.nearestDesc(i,!0),c;if(!o)return null;if(o.dom.nodeType==1&&(o.node.isBlock&&o.parent||!o.contentDOM)&&((c=o.dom.getBoundingClientRect()).width||c.height)&&(o.node.isBlock&&o.parent&&!/^T(R|BODY|HEAD|FOOT)$/.test(o.dom.nodeName)&&(!l&&c.left>n.left||c.top>n.top?a=o.posBefore:(!l&&c.right-1?a:s.docView.posFromDOM(t,r,-1)}function Olt(s,t,r){let n=s.childNodes.length;if(n&&r.topt.top&&a++}let d;dz&&a&&n.nodeType==1&&(d=n.childNodes[a-1]).nodeType==1&&d.contentEditable=="false"&&d.getBoundingClientRect().top>=t.top&&a--,n==s.dom&&a==n.childNodes.length-1&&n.lastChild.nodeType==1&&t.top>n.lastChild.getBoundingClientRect().bottom?o=s.state.doc.content.size:(a==0||n.nodeType!=1||n.childNodes[a-1].nodeName!="BR")&&(o=CWt(s,n,a,t))}o==null&&(o=SWt(s,l,t));let c=s.docView.nearestDesc(l,!0);return{pos:o,inside:c?c.posAtStart-c.border:-1}}function L9e(s){return s.top=0&&a==n.nodeValue.length?(c--,h=1):r<0?c--:d++,LR(LN(f2(n,c,d),h),h<0)}if(!s.state.doc.resolve(t-(i||0)).parent.inlineContent){if(i==null&&a&&(r<0||a==Iy(n))){let c=n.childNodes[a-1];if(c.nodeType==1)return qbe(c.getBoundingClientRect(),!1)}if(i==null&&a=0)}if(i==null&&a&&(r<0||a==Iy(n))){let c=n.childNodes[a-1],d=c.nodeType==3?f2(c,Iy(c)-(l?0:1)):c.nodeType==1&&(c.nodeName!="BR"||!c.nextSibling)?c:null;if(d)return LR(LN(d,1),!1)}if(i==null&&a=0)}function LR(s,t){if(s.width==0)return s;let r=t?s.left:s.right;return{top:s.top,bottom:s.bottom,left:r,right:r}}function qbe(s,t){if(s.height==0)return s;let r=t?s.top:s.bottom;return{top:r,bottom:r,left:s.left,right:s.right}}function Blt(s,t,r){let n=s.state,a=s.root.activeElement;n!=t&&s.updateState(t),a!=s.dom&&s.focus();try{return r()}finally{n!=t&&s.updateState(n),a!=s.dom&&a&&a.focus()}}function AWt(s,t,r){let n=t.selection,a=r=="up"?n.$from:n.$to;return Blt(s,t,()=>{let{node:i}=s.docView.domFromPos(a.pos,r=="up"?-1:1);for(;;){let o=s.docView.nearestDesc(i,!0);if(!o)break;if(o.node.isBlock){i=o.contentDOM||o.dom;break}i=o.dom.parentNode}let l=Flt(s,a.pos,1);for(let o=i.firstChild;o;o=o.nextSibling){let c;if(o.nodeType==1)c=o.getClientRects();else if(o.nodeType==3)c=f2(o,0,o.nodeValue.length).getClientRects();else continue;for(let d=0;dh.top+1&&(r=="up"?l.top-h.top>(h.bottom-l.top)*2:h.bottom-l.bottom>(l.bottom-h.top)*2))return!1}}return!0})}const MWt=/[\u0590-\u08ac]/;function IWt(s,t,r){let{$head:n}=t.selection;if(!n.parent.isTextblock)return!1;let a=n.parentOffset,i=!a,l=a==n.parent.content.size,o=s.domSelection();return o?!MWt.test(n.parent.textContent)||!o.modify?r=="left"||r=="backward"?i:l:Blt(s,t,()=>{let{focusNode:c,focusOffset:d,anchorNode:h,anchorOffset:m}=s.domSelectionRange(),p=o.caretBidiLevel;o.modify("move",r,"character");let x=n.depth?s.docView.domAfterPos(n.before()):s.dom,{focusNode:y,focusOffset:_}=s.domSelectionRange(),b=y&&!x.contains(y.nodeType==1?y:y.parentNode)||c==y&&d==_;try{o.collapse(h,m),c&&(c!=h||d!=m)&&o.extend&&o.extend(c,d)}catch{}return p!=null&&(o.caretBidiLevel=p),b}):n.pos==n.start()||n.pos==n.end()}let D9e=null,R9e=null,O9e=!1;function PWt(s,t,r){return D9e==t&&R9e==r?O9e:(D9e=t,R9e=r,O9e=r=="up"||r=="down"?AWt(s,t,r):IWt(s,t,r))}const Zy=0,F9e=1,zT=2,L_=3;class uz{constructor(t,r,n,a){this.parent=t,this.children=r,this.dom=n,this.contentDOM=a,this.dirty=Zy,n.pmViewDesc=this}matchesWidget(t){return!1}matchesMark(t){return!1}matchesNode(t,r,n){return!1}matchesHack(t){return!1}parseRule(){return null}stopEvent(t){return!1}get size(){let t=0;for(let r=0;rLf(this.contentDOM);else if(this.contentDOM&&this.contentDOM!=this.dom&&this.dom.contains(this.contentDOM))a=t.compareDocumentPosition(this.contentDOM)&2;else if(this.dom.firstChild){if(r==0)for(let i=t;;i=i.parentNode){if(i==this.dom){a=!1;break}if(i.previousSibling)break}if(a==null&&r==t.childNodes.length)for(let i=t;;i=i.parentNode){if(i==this.dom){a=!0;break}if(i.nextSibling)break}}return a??n>0?this.posAtEnd:this.posAtStart}nearestDesc(t,r=!1){for(let n=!0,a=t;a;a=a.parentNode){let i=this.getDesc(a),l;if(i&&(!r||i.node))if(n&&(l=i.nodeDOM)&&!(l.nodeType==1?l.contains(t.nodeType==1?t:t.parentNode):l==t))n=!1;else return i}}getDesc(t){let r=t.pmViewDesc;for(let n=r;n;n=n.parent)if(n==this)return r}posFromDOM(t,r,n){for(let a=t;a;a=a.parentNode){let i=this.getDesc(a);if(i)return i.localPosFromDOM(t,r,n)}return-1}descAt(t){for(let r=0,n=0;rt||l instanceof $lt){a=t-i;break}i=o}if(a)return this.children[n].domFromPos(a-this.children[n].border,r);for(let i;n&&!(i=this.children[n-1]).size&&i instanceof zlt&&i.side>=0;n--);if(r<=0){let i,l=!0;for(;i=n?this.children[n-1]:null,!(!i||i.dom.parentNode==this.contentDOM);n--,l=!1);return i&&r&&l&&!i.border&&!i.domAtom?i.domFromPos(i.size,r):{node:this.contentDOM,offset:i?Lf(i.dom)+1:0}}else{let i,l=!0;for(;i=n=h&&r<=d-c.border&&c.node&&c.contentDOM&&this.contentDOM.contains(c.contentDOM))return c.parseRange(t,r,h);t=l;for(let m=o;m>0;m--){let p=this.children[m-1];if(p.size&&p.dom.parentNode==this.contentDOM&&!p.emptyChildAt(1)){a=Lf(p.dom)+1;break}t-=p.size}a==-1&&(a=0)}if(a>-1&&(d>r||o==this.children.length-1)){r=d;for(let h=o+1;hy&&lr){let y=o;o=c,c=y}let x=document.createRange();x.setEnd(c.node,c.offset),x.setStart(o.node,o.offset),d.removeAllRanges(),d.addRange(x)}}ignoreMutation(t){return!this.contentDOM&&t.type!="selection"}get contentLost(){return this.contentDOM&&this.contentDOM!=this.dom&&!this.dom.contains(this.contentDOM)}markDirty(t,r){for(let n=0,a=0;a=n:tn){let o=n+i.border,c=l-i.border;if(t>=o&&r<=c){this.dirty=t==n||r==l?zT:F9e,t==o&&r==c&&(i.contentLost||i.dom.parentNode!=this.contentDOM)?i.dirty=L_:i.markDirty(t-o,r-o);return}else i.dirty=i.dom==i.contentDOM&&i.dom.parentNode==this.contentDOM&&!i.children.length?zT:L_}n=l}this.dirty=zT}markParentsDirty(){let t=1;for(let r=this.parent;r;r=r.parent,t++){let n=t==1?zT:F9e;r.dirty{if(!i)return a;if(i.parent)return i.parent.posBeforeChild(i)})),!r.type.spec.raw){if(l.nodeType!=1){let o=document.createElement("span");o.appendChild(l),l=o}l.contentEditable="false",l.classList.add("ProseMirror-widget")}super(t,[],l,null),this.widget=r,this.widget=r,i=this}matchesWidget(t){return this.dirty==Zy&&t.type.eq(this.widget.type)}parseRule(){return{ignore:!0}}stopEvent(t){let r=this.widget.spec.stopEvent;return r?r(t):!1}ignoreMutation(t){return t.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 LWt extends uz{constructor(t,r,n,a){super(t,[],r,null),this.textDOM=n,this.text=a}get size(){return this.text.length}localPosFromDOM(t,r){return t!=this.textDOM?this.posAtStart+(r?this.size:0):this.posAtStart+r}domFromPos(t){return{node:this.textDOM,offset:t}}ignoreMutation(t){return t.type==="characterData"&&t.target.nodeValue==t.oldValue}}class bA extends uz{constructor(t,r,n,a,i){super(t,[],n,a),this.mark=r,this.spec=i}static create(t,r,n,a){let i=a.nodeViews[r.type.name],l=i&&i(r,a,n);return(!l||!l.dom)&&(l=VA.renderSpec(document,r.type.spec.toDOM(r,n),null,r.attrs)),new bA(t,r,l.dom,l.contentDOM||l.dom,l)}parseRule(){return this.dirty&L_||this.mark.type.spec.reparseInView?null:{mark:this.mark.type.name,attrs:this.mark.attrs,contentElement:this.contentDOM}}matchesMark(t){return this.dirty!=L_&&this.mark.eq(t)}markDirty(t,r){if(super.markDirty(t,r),this.dirty!=Zy){let n=this.parent;for(;!n.node;)n=n.parent;n.dirty0&&(i=tke(i,0,t,n));for(let o=0;o{if(!c)return l;if(c.parent)return c.parent.posBeforeChild(c)},n,a),h=d&&d.dom,m=d&&d.contentDOM;if(r.isText){if(!h)h=document.createTextNode(r.text);else if(h.nodeType!=3)throw new RangeError("Text must be rendered as a DOM text node")}else h||({dom:h,contentDOM:m}=VA.renderSpec(document,r.type.spec.toDOM(r),null,r.attrs));!m&&!r.isText&&h.nodeName!="BR"&&(h.hasAttribute("contenteditable")||(h.contentEditable="false"),r.type.spec.draggable&&(h.draggable=!0));let p=h;return h=Vlt(h,n,r),d?c=new DWt(t,r,n,a,h,m||null,p,d,i,l+1):r.isText?new lxe(t,r,n,a,h,p,i):new aS(t,r,n,a,h,m||null,p,i,l+1)}parseRule(){if(this.node.type.spec.reparseInView)return null;let t={node:this.node.type.name,attrs:this.node.attrs};if(this.node.type.whitespace=="pre"&&(t.preserveWhitespace="full"),!this.contentDOM)t.getContent=()=>this.node.content;else if(!this.contentLost)t.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)){t.contentElement=n.dom.parentNode;break}}t.contentElement||(t.getContent=()=>An.empty)}return t}matchesNode(t,r,n){return this.dirty==Zy&&t.eq(this.node)&&cme(r,this.outerDeco)&&n.eq(this.innerDeco)}get size(){return this.node.nodeSize}get border(){return this.node.isLeaf?0:1}updateChildren(t,r){let n=this.node.inlineContent,a=r,i=t.composing?this.localCompositionInfo(t,r):null,l=i&&i.pos>-1?i:null,o=i&&i.pos<0,c=new OWt(this,l&&l.node,t);zWt(this.node,this.innerDeco,(d,h,m)=>{d.spec.marks?c.syncToMarks(d.spec.marks,n,t,h):d.type.side>=0&&!m&&c.syncToMarks(h==this.node.childCount?Fc.none:this.node.child(h).marks,n,t,h),c.placeWidget(d,t,a)},(d,h,m,p)=>{c.syncToMarks(d.marks,n,t,p);let x;c.findNodeMatch(d,h,m,p)||o&&t.state.selection.from>a&&t.state.selection.to-1&&c.updateNodeAt(d,h,m,x,t)||c.updateNextNode(d,h,m,t,p,a)||c.addNode(d,h,m,t,a),a+=d.nodeSize}),c.syncToMarks([],n,t,0),this.node.isTextblock&&c.addTextblockHacks(),c.destroyRest(),(c.changed||this.dirty==zT)&&(l&&this.protectLocalComposition(t,l),Ult(this.contentDOM,this.children,t),lL&&$Wt(this.dom))}localCompositionInfo(t,r){let{from:n,to:a}=t.state.selection;if(!(t.state.selection instanceof Ri)||nr+this.node.content.size)return null;let i=t.input.compositionNode;if(!i||!this.dom.contains(i.parentNode))return null;if(this.node.inlineContent){let l=i.nodeValue,o=UWt(this.node.content,l,n-r,a-r);return o<0?null:{node:i,pos:o,text:l}}else return{node:i,pos:-1,text:""}}protectLocalComposition(t,{node:r,pos:n,text:a}){if(this.getDesc(r))return;let i=r;for(;i.parentNode!=this.contentDOM;i=i.parentNode){for(;i.previousSibling;)i.parentNode.removeChild(i.previousSibling);for(;i.nextSibling;)i.parentNode.removeChild(i.nextSibling);i.pmViewDesc&&(i.pmViewDesc=void 0)}let l=new LWt(this,i,r,a);t.input.compositionNodes.push(l),this.children=tke(this.children,n,n+a.length,t,l)}update(t,r,n,a){return this.dirty==L_||!t.sameMarkup(this.node)?!1:(this.updateInner(t,r,n,a),!0)}updateInner(t,r,n,a){this.updateOuterDeco(r),this.node=t,this.innerDeco=n,this.contentDOM&&this.updateChildren(a,this.posAtStart),this.dirty=Zy}updateOuterDeco(t){if(cme(t,this.outerDeco))return;let r=this.nodeDOM.nodeType!=1,n=this.dom;this.dom=qlt(this.dom,this.nodeDOM,eke(this.outerDeco,this.node,r),eke(t,this.node,r)),this.dom!=n&&(n.pmViewDesc=void 0,this.dom.pmViewDesc=this),this.outerDeco=t}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 B9e(s,t,r,n,a){Vlt(n,t,s);let i=new aS(void 0,s,t,r,n,n,n,a,0);return i.contentDOM&&i.updateChildren(a,0),i}class lxe extends aS{constructor(t,r,n,a,i,l,o){super(t,r,n,a,i,null,l,o,0)}parseRule(){let t=this.nodeDOM.parentNode;for(;t&&t!=this.dom&&!t.pmIsDeco;)t=t.parentNode;return{skip:t||!0}}update(t,r,n,a){return this.dirty==L_||this.dirty!=Zy&&!this.inParent()||!t.sameMarkup(this.node)?!1:(this.updateOuterDeco(r),(this.dirty!=Zy||t.text!=this.node.text)&&t.text!=this.nodeDOM.nodeValue&&(this.nodeDOM.nodeValue=t.text,a.trackWrites==this.nodeDOM&&(a.trackWrites=null)),this.node=t,this.dirty=Zy,!0)}inParent(){let t=this.parent.contentDOM;for(let r=this.nodeDOM;r;r=r.parentNode)if(r==t)return!0;return!1}domFromPos(t){return{node:this.nodeDOM,offset:t}}localPosFromDOM(t,r,n){return t==this.nodeDOM?this.posAtStart+Math.min(r,this.node.text.length):super.localPosFromDOM(t,r,n)}ignoreMutation(t){return t.type!="characterData"&&t.type!="selection"}slice(t,r,n){let a=this.node.cut(t,r),i=document.createTextNode(a.text);return new lxe(this.parent,a,this.outerDeco,this.innerDeco,i,i,n)}markDirty(t,r){super.markDirty(t,r),this.dom!=this.nodeDOM&&(t==0||r==this.nodeDOM.nodeValue.length)&&(this.dirty=L_)}get domAtom(){return!1}isText(t){return this.node.text==t}}class $lt extends uz{parseRule(){return{ignore:!0}}matchesHack(t){return this.dirty==Zy&&this.dom.nodeName==t}get domAtom(){return!0}get ignoreForCoords(){return this.dom.nodeName=="IMG"}}class DWt extends aS{constructor(t,r,n,a,i,l,o,c,d,h){super(t,r,n,a,i,l,o,d,h),this.spec=c}update(t,r,n,a){if(this.dirty==L_)return!1;if(this.spec.update&&(this.node.type==t.type||this.spec.multiType)){let i=this.spec.update(t,r,n);return i&&this.updateInner(t,r,n,a),i}else return!this.contentDOM&&!t.isLeaf?!1:super.update(t,r,n,a)}selectNode(){this.spec.selectNode?this.spec.selectNode():super.selectNode()}deselectNode(){this.spec.deselectNode?this.spec.deselectNode():super.deselectNode()}setSelection(t,r,n,a){this.spec.setSelection?this.spec.setSelection(t,r,n.root):super.setSelection(t,r,n,a)}destroy(){this.spec.destroy&&this.spec.destroy(),super.destroy()}stopEvent(t){return this.spec.stopEvent?this.spec.stopEvent(t):!1}ignoreMutation(t){return this.spec.ignoreMutation?this.spec.ignoreMutation(t):super.ignoreMutation(t)}}function Ult(s,t,r){let n=s.firstChild,a=!1;for(let i=0;i>1,o=Math.min(l,t.length);for(;i-1)c>this.index&&(this.changed=!0,this.destroyBetween(this.index,c)),this.top=this.top.children[this.index];else{let h=bA.create(this.top,t[l],r,n);this.top.children.splice(this.index,0,h),this.top=h,this.changed=!0}this.index=0,l++}}findNodeMatch(t,r,n,a){let i=-1,l;if(a>=this.preMatch.index&&(l=this.preMatch.matches[a-this.preMatch.index]).parent==this.top&&l.matchesNode(t,r,n))i=this.top.children.indexOf(l,this.index);else for(let o=this.index,c=Math.min(this.top.children.length,o+5);o0;){let o;for(;;)if(n){let d=r.children[n-1];if(d instanceof bA)r=d,n=d.children.length;else{o=d,n--;break}}else{if(r==t)break e;n=r.parent.children.indexOf(r),r=r.parent}let c=o.node;if(c){if(c!=s.child(a-1))break;--a,i.set(o,a),l.push(o)}}return{index:a,matched:i,matches:l.reverse()}}function BWt(s,t){return s.type.side-t.type.side}function zWt(s,t,r,n){let a=t.locals(s),i=0;if(a.length==0){for(let d=0;di;)o.push(a[l++]);let y=i+p.nodeSize;if(p.isText){let b=y;l!b.inline):o.slice();n(p,_,t.forChild(i,p),x),i=y}}function $Wt(s){if(s.nodeName=="UL"||s.nodeName=="OL"){let t=s.style.cssText;s.style.cssText=t+"; list-style: square !important",window.getComputedStyle(s).listStyle,s.style.cssText=t}}function UWt(s,t,r,n){for(let a=0,i=0;a=r){if(i>=n&&c.slice(n-t.length-o,n-o)==t)return n-t.length;let d=o=0&&d+t.length+o>=r)return o+d;if(r==n&&c.length>=n+t.length-o&&c.slice(n-o,n-o+t.length)==t)return n}}return-1}function tke(s,t,r,n,a){let i=[];for(let l=0,o=0;l=r||h<=t?i.push(c):(dr&&i.push(c.slice(r-d,c.size,n)))}return i}function MTe(s,t=null){let r=s.domSelectionRange(),n=s.state.doc;if(!r.focusNode)return null;let a=s.docView.nearestDesc(r.focusNode),i=a&&a.size==0,l=s.docView.posFromDOM(r.focusNode,r.focusOffset,1);if(l<0)return null;let o=n.resolve(l),c,d;if(oxe(r)){for(c=l;a&&!a.node;)a=a.parent;let m=a.node;if(a&&m.isAtom&&Si.isSelectable(m)&&a.parent&&!(m.isInline&&pWt(r.focusNode,r.focusOffset,a.dom))){let p=a.posBefore;d=new Si(l==p?o:n.resolve(p))}}else{if(r instanceof s.dom.ownerDocument.defaultView.Selection&&r.rangeCount>1){let m=l,p=l;for(let x=0;x{(r.anchorNode!=n||r.anchorOffset!=a)&&(t.removeEventListener("selectionchange",s.input.hideSelectionGuard),setTimeout(()=>{(!Hlt(s)||s.state.selection.visible)&&s.dom.classList.remove("ProseMirror-hideselection")},20))})}function VWt(s){let t=s.domSelection();if(!t)return;let r=s.cursorWrapper.dom,n=r.nodeName=="IMG";n?t.collapse(r.parentNode,Lf(r)+1):t.collapse(r,0),!n&&!s.state.selection.visible&&hx&&nS<=11&&(r.disabled=!0,r.disabled=!1)}function Glt(s,t){if(t instanceof Si){let r=s.docView.descAt(t.from);r!=s.lastSelectedViewDesc&&(V9e(s),r&&r.selectNode(),s.lastSelectedViewDesc=r)}else V9e(s)}function V9e(s){s.lastSelectedViewDesc&&(s.lastSelectedViewDesc.parent&&s.lastSelectedViewDesc.deselectNode(),s.lastSelectedViewDesc=void 0)}function ITe(s,t,r,n){return s.someProp("createSelectionBetween",a=>a(s,t,r))||Ri.between(t,r,n)}function H9e(s){return s.editable&&!s.hasFocus()?!1:Wlt(s)}function Wlt(s){let t=s.domSelectionRange();if(!t.anchorNode)return!1;try{return s.dom.contains(t.anchorNode.nodeType==3?t.anchorNode.parentNode:t.anchorNode)&&(s.editable||s.dom.contains(t.focusNode.nodeType==3?t.focusNode.parentNode:t.focusNode))}catch{return!1}}function HWt(s){let t=s.docView.domFromPos(s.state.selection.anchor,0),r=s.domSelectionRange();return vA(t.node,t.offset,r.anchorNode,r.anchorOffset)}function ske(s,t){let{$anchor:r,$head:n}=s.selection,a=t>0?r.max(n):r.min(n),i=a.parent.inlineContent?a.depth?s.doc.resolve(t>0?a.after():a.before()):null:a;return i&&Hi.findFrom(i,t)}function qN(s,t){return s.dispatch(s.state.tr.setSelection(t).scrollIntoView()),!0}function G9e(s,t,r){let n=s.state.selection;if(n instanceof Ri)if(r.indexOf("s")>-1){let{$head:a}=n,i=a.textOffset?null:t<0?a.nodeBefore:a.nodeAfter;if(!i||i.isText||!i.isLeaf)return!1;let l=s.state.doc.resolve(a.pos+i.nodeSize*(t<0?-1:1));return qN(s,new Ri(n.$anchor,l))}else if(n.empty){if(s.endOfTextblock(t>0?"forward":"backward")){let a=ske(s.state,t);return a&&a instanceof Si?qN(s,a):!1}else if(!(Sy&&r.indexOf("m")>-1)){let a=n.$head,i=a.textOffset?null:t<0?a.nodeBefore:a.nodeAfter,l;if(!i||i.isText)return!1;let o=t<0?a.pos-i.nodeSize:a.pos;return i.isAtom||(l=s.docView.descAt(o))&&!l.contentDOM?Si.isSelectable(i)?qN(s,new Si(t<0?s.state.doc.resolve(a.pos-i.nodeSize):a)):dz?qN(s,new Ri(s.state.doc.resolve(t<0?o:o+i.nodeSize))):!1:!1}}else return!1;else{if(n instanceof Si&&n.node.isInline)return qN(s,new Ri(t>0?n.$to:n.$from));{let a=ske(s.state,t);return a?qN(s,a):!1}}}function dme(s){return s.nodeType==3?s.nodeValue.length:s.childNodes.length}function o7(s,t){let r=s.pmViewDesc;return r&&r.size==0&&(t<0||s.nextSibling||s.nodeName!="BR")}function g6(s,t){return t<0?GWt(s):WWt(s)}function GWt(s){let t=s.domSelectionRange(),r=t.focusNode,n=t.focusOffset;if(!r)return;let a,i,l=!1;for(Yy&&r.nodeType==1&&n0){if(r.nodeType!=1)break;{let o=r.childNodes[n-1];if(o7(o,-1))a=r,i=--n;else if(o.nodeType==3)r=o,n=r.nodeValue.length;else break}}else{if(Klt(r))break;{let o=r.previousSibling;for(;o&&o7(o,-1);)a=r.parentNode,i=Lf(o),o=o.previousSibling;if(o)r=o,n=dme(r);else{if(r=r.parentNode,r==s.dom)break;n=0}}}l?rke(s,r,n):a&&rke(s,a,i)}function WWt(s){let t=s.domSelectionRange(),r=t.focusNode,n=t.focusOffset;if(!r)return;let a=dme(r),i,l;for(;;)if(n{s.state==a&&Y2(s)},50)}function W9e(s,t){let r=s.state.doc.resolve(t);if(!(Ff||Plt)&&r.parent.inlineContent){let a=s.coordsAtPos(t);if(t>r.start()){let i=s.coordsAtPos(t-1),l=(i.top+i.bottom)/2;if(l>a.top&&l1)return i.lefta.top&&l1)return i.left>a.left?"ltr":"rtl"}}return getComputedStyle(s.dom).direction=="rtl"?"rtl":"ltr"}function K9e(s,t,r){let n=s.state.selection;if(n instanceof Ri&&!n.empty||r.indexOf("s")>-1||Sy&&r.indexOf("m")>-1)return!1;let{$from:a,$to:i}=n;if(!a.parent.inlineContent||s.endOfTextblock(t<0?"up":"down")){let l=ske(s.state,t);if(l&&l instanceof Si)return qN(s,l)}if(!a.parent.inlineContent){let l=t<0?a:i,o=n instanceof Ky?Hi.near(l,t):Hi.findFrom(l,t);return o?qN(s,o):!1}return!1}function Y9e(s,t){if(!(s.state.selection instanceof Ri))return!0;let{$head:r,$anchor:n,empty:a}=s.state.selection;if(!r.sameParent(n))return!0;if(!a)return!1;if(s.endOfTextblock(t>0?"forward":"backward"))return!0;let i=!r.textOffset&&(t<0?r.nodeBefore:r.nodeAfter);if(i&&!i.isText){let l=s.state.tr;return t<0?l.delete(r.pos-i.nodeSize,r.pos):l.delete(r.pos,r.pos+i.nodeSize),s.dispatch(l),!0}return!1}function Z9e(s,t,r){s.domObserver.stop(),t.contentEditable=r,s.domObserver.start()}function ZWt(s){if(!kp||s.state.selection.$head.parentOffset>0)return!1;let{focusNode:t,focusOffset:r}=s.domSelectionRange();if(t&&t.nodeType==1&&r==0&&t.firstChild&&t.firstChild.contentEditable=="false"){let n=t.firstChild;Z9e(s,n,"true"),setTimeout(()=>Z9e(s,n,"false"),20)}return!1}function XWt(s){let t="";return s.ctrlKey&&(t+="c"),s.metaKey&&(t+="m"),s.altKey&&(t+="a"),s.shiftKey&&(t+="s"),t}function QWt(s,t){let r=t.keyCode,n=XWt(t);if(r==8||Sy&&r==72&&n=="c")return Y9e(s,-1)||g6(s,-1);if(r==46&&!t.shiftKey||Sy&&r==68&&n=="c")return Y9e(s,1)||g6(s,1);if(r==13||r==27)return!0;if(r==37||Sy&&r==66&&n=="c"){let a=r==37?W9e(s,s.state.selection.from)=="ltr"?-1:1:-1;return G9e(s,a,n)||g6(s,a)}else if(r==39||Sy&&r==70&&n=="c"){let a=r==39?W9e(s,s.state.selection.from)=="ltr"?1:-1:1;return G9e(s,a,n)||g6(s,a)}else{if(r==38||Sy&&r==80&&n=="c")return K9e(s,-1,n)||g6(s,-1);if(r==40||Sy&&r==78&&n=="c")return ZWt(s)||K9e(s,1,n)||g6(s,1);if(n==(Sy?"m":"c")&&(r==66||r==73||r==89||r==90))return!0}return!1}function PTe(s,t){s.someProp("transformCopied",x=>{t=x(t,s)});let r=[],{content:n,openStart:a,openEnd:i}=t;for(;a>1&&i>1&&n.childCount==1&&n.firstChild.childCount==1;){a--,i--;let x=n.firstChild;r.push(x.type.name,x.attrs!=x.type.defaultAttrs?x.attrs:null),n=x.content}let l=s.someProp("clipboardSerializer")||VA.fromSchema(s.state.schema),o=ect(),c=o.createElement("div");c.appendChild(l.serializeFragment(n,{document:o}));let d=c.firstChild,h,m=0;for(;d&&d.nodeType==1&&(h=Jlt[d.nodeName.toLowerCase()]);){for(let x=h.length-1;x>=0;x--){let y=o.createElement(h[x]);for(;c.firstChild;)y.appendChild(c.firstChild);c.appendChild(y),m++}d=c.firstChild}d&&d.nodeType==1&&d.setAttribute("data-pm-slice",`${a} ${i}${m?` -${m}`:""} ${JSON.stringify(r)}`);let p=s.someProp("clipboardTextSerializer",x=>x(t,s))||t.content.textBetween(0,t.content.size,` `);return{dom:c,text:p,slice:t}}function Ylt(s,t,r,n,a){let i=a.parent.type.spec.code,l,o;if(!r&&!t)return null;let c=!!t&&(n||i||!r);if(c){if(s.someProp("transformPastedText",p=>{t=p(t,i||n,s)}),i)return o=new ua(An.from(s.state.schema.text(t.replace(/\r\n?/g,` `))),0,0),s.someProp("transformPasted",p=>{o=p(o,s,!0)}),o;let m=s.someProp("clipboardTextParser",p=>p(t,a,n,s));if(m)o=m;else{let p=a.marks(),{schema:x}=s.state,y=VA.fromSchema(x);l=document.createElement("div"),t.split(/(?:\r\n?|\n)+/).forEach(_=>{let b=l.appendChild(document.createElement("p"));_&&b.appendChild(y.serializeNode(x.text(_,p)))})}}else s.someProp("transformPastedHTML",m=>{r=m(r,s)}),l=sKt(r),dz&&rKt(l);let d=l&&l.querySelector("[data-pm-slice]"),h=d&&/^(\d+) (\d+)(?: -(\d+))? (.*)/.exec(d.getAttribute("data-pm-slice")||"");if(h&&h[3])for(let m=+h[3];m>0;m--){let p=l.firstChild;for(;p&&p.nodeType!=1;)p=p.nextSibling;if(!p)break;l=p}if(o||(o=(s.someProp("clipboardParser")||s.someProp("domParser")||n7.fromSchema(s.state.schema)).parseSlice(l,{preserveWhitespace:!!(c||h),context:a,ruleFromNode(p){return p.nodeName=="BR"&&!p.nextSibling&&p.parentNode&&!JWt.test(p.parentNode.nodeName)?{ignore:!0}:null}})),h)o=nKt(X9e(o,+h[1],+h[2]),h[4]);else if(o=ua.maxOpen(eKt(o.content,a),!0),o.openStart||o.openEnd){let m=0,p=0;for(let x=o.content.firstChild;m{o=m(o,s,c)}),o}const JWt=/^(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 eKt(s,t){if(s.childCount<2)return s;for(let r=t.depth;r>=0;r--){let a=t.node(r).contentMatchAt(t.index(r)),i,l=[];if(s.forEach(o=>{if(!l)return;let c=a.findWrapping(o.type),d;if(!c)return l=null;if(d=l.length&&i.length&&Xlt(c,i,o,l[l.length-1],0))l[l.length-1]=d;else{l.length&&(l[l.length-1]=Qlt(l[l.length-1],i.length));let h=Zlt(o,c);l.push(h),a=a.matchType(h.type),i=c}}),l)return An.from(l)}return s}function Zlt(s,t,r=0){for(let n=t.length-1;n>=r;n--)s=t[n].create(null,An.from(s));return s}function Xlt(s,t,r,n,a){if(a1&&(i=0),a=r&&(o=t<0?l.contentMatchAt(0).fillBefore(o,i<=a).append(o):o.append(l.contentMatchAt(l.childCount).fillBefore(An.empty,!0))),s.replaceChild(t<0?0:s.childCount-1,l.copy(o))}function X9e(s,t,r){return tr})),Hbe.createHTML(s)):s}function sKt(s){let t=/^(\s*]*>)*/.exec(s);t&&(s=s.slice(t[0].length));let r=ect().createElement("div"),n=/<([a-z][^>\s]+)/i.exec(s),a;if((a=n&&Jlt[n[1].toLowerCase()])&&(s=a.map(i=>"<"+i+">").join("")+s+a.map(i=>"").reverse().join("")),r.innerHTML=tKt(s),a)for(let i=0;i=0;o-=2){let c=r.nodes[n[o]];if(!c||c.hasRequiredAttrs())break;a=An.from(c.create(n[o+1],a)),i++,l++}return new ua(a,i,l)}const Ng={},kg={},aKt={touchstart:!0,touchmove:!0};class iKt{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.badSafariComposition=!1,this.compositionPendingChanges=0,this.domChangeCount=0,this.eventHandlers=Object.create(null),this.hideSelectionGuard=null}}function oKt(s){for(let t in Ng){let r=Ng[t];s.dom.addEventListener(t,s.input.eventHandlers[t]=n=>{cKt(s,n)&&!LTe(s,n)&&(s.editable||!(n.type in kg))&&r(s,n)},aKt[t]?{passive:!0}:void 0)}kp&&s.dom.addEventListener("input",()=>null),ake(s)}function Nk(s,t){s.input.lastSelectionOrigin=t,s.input.lastSelectionTime=Date.now()}function lKt(s){s.domObserver.stop();for(let t in s.input.eventHandlers)s.dom.removeEventListener(t,s.input.eventHandlers[t]);clearTimeout(s.input.composingTimeout),clearTimeout(s.input.lastIOSEnterFallbackTimeout)}function ake(s){s.someProp("handleDOMEvents",t=>{for(let r in t)s.input.eventHandlers[r]||s.dom.addEventListener(r,s.input.eventHandlers[r]=n=>LTe(s,n))})}function LTe(s,t){return s.someProp("handleDOMEvents",r=>{let n=r[t.type];return n?n(s,t)||t.defaultPrevented:!1})}function cKt(s,t){if(!t.bubbles)return!0;if(t.defaultPrevented)return!1;for(let r=t.target;r!=s.dom;r=r.parentNode)if(!r||r.nodeType==11||r.pmViewDesc&&r.pmViewDesc.stopEvent(t))return!1;return!0}function dKt(s,t){!LTe(s,t)&&Ng[t.type]&&(s.editable||!(t.type in kg))&&Ng[t.type](s,t)}kg.keydown=(s,t)=>{let r=t;if(s.input.shiftKey=r.keyCode==16||r.shiftKey,!sct(s,r)&&(s.input.lastKeyCode=r.keyCode,s.input.lastKeyCodeTime=Date.now(),!(P2&&Ff&&r.keyCode==13)))if(r.keyCode!=229&&s.domObserver.forceFlush(),lL&&r.keyCode==13&&!r.ctrlKey&&!r.altKey&&!r.metaKey){let n=Date.now();s.input.lastIOSEnter=n,s.input.lastIOSEnterFallbackTimeout=setTimeout(()=>{s.input.lastIOSEnter==n&&(s.someProp("handleKeyDown",a=>a(s,ET(13,"Enter"))),s.input.lastIOSEnter=0)},200)}else s.someProp("handleKeyDown",n=>n(s,r))||QWt(s,r)?r.preventDefault():Nk(s,"key")};kg.keyup=(s,t)=>{t.keyCode==16&&(s.input.shiftKey=!1)};kg.keypress=(s,t)=>{let r=t;if(sct(s,r)||!r.charCode||r.ctrlKey&&!r.altKey||Sy&&r.metaKey)return;if(s.someProp("handleKeyPress",a=>a(s,r))){r.preventDefault();return}let n=s.state.selection;if(!(n instanceof Ri)||!n.$from.sameParent(n.$to)){let a=String.fromCharCode(r.charCode),i=()=>s.state.tr.insertText(a).scrollIntoView();!/[\r\n]/.test(a)&&!s.someProp("handleTextInput",l=>l(s,n.$from.pos,n.$to.pos,a,i))&&s.dispatch(i()),r.preventDefault()}};function cxe(s){return{left:s.clientX,top:s.clientY}}function uKt(s,t){let r=t.x-s.clientX,n=t.y-s.clientY;return r*r+n*n<100}function DTe(s,t,r,n,a){if(n==-1)return!1;let i=s.state.doc.resolve(n);for(let l=i.depth+1;l>0;l--)if(s.someProp(t,o=>l>i.depth?o(s,r,i.nodeAfter,i.before(l),a,!0):o(s,r,i.node(l),i.before(l),a,!1)))return!0;return!1}function uP(s,t,r){if(s.focused||s.focus(),s.state.selection.eq(t))return;let n=s.state.tr.setSelection(t);n.setMeta("pointer",!0),s.dispatch(n)}function hKt(s,t){if(t==-1)return!1;let r=s.state.doc.resolve(t),n=r.nodeAfter;return n&&n.isAtom&&Si.isSelectable(n)?(uP(s,new Si(r)),!0):!1}function mKt(s,t){if(t==-1)return!1;let r=s.state.selection,n,a;r instanceof Si&&(n=r.node);let i=s.state.doc.resolve(t);for(let l=i.depth+1;l>0;l--){let o=l>i.depth?i.nodeAfter:i.node(l);if(Si.isSelectable(o)){n&&r.$from.depth>0&&l>=r.$from.depth&&i.before(r.$from.depth+1)==r.$from.pos?a=i.before(r.$from.depth):a=i.before(l);break}}return a!=null?(uP(s,Si.create(s.state.doc,a)),!0):!1}function fKt(s,t,r,n,a){return DTe(s,"handleClickOn",t,r,n)||s.someProp("handleClick",i=>i(s,t,n))||(a?mKt(s,r):hKt(s,r))}function pKt(s,t,r,n){return DTe(s,"handleDoubleClickOn",t,r,n)||s.someProp("handleDoubleClick",a=>a(s,t,n))}function gKt(s,t,r,n){return DTe(s,"handleTripleClickOn",t,r,n)||s.someProp("handleTripleClick",a=>a(s,t,n))||xKt(s,r,n)}function xKt(s,t,r){if(r.button!=0)return!1;let n=s.state.doc;if(t==-1)return n.inlineContent?(uP(s,Ri.create(n,0,n.content.size)),!0):!1;let a=n.resolve(t);for(let i=a.depth+1;i>0;i--){let l=i>a.depth?a.nodeAfter:a.node(i),o=a.before(i);if(l.inlineContent)uP(s,Ri.create(n,o+1,o+1+l.content.size));else if(Si.isSelectable(l))uP(s,Si.create(n,o));else continue;return!0}}function RTe(s){return ume(s)}const tct=Sy?"metaKey":"ctrlKey";Ng.mousedown=(s,t)=>{let r=t;s.input.shiftKey=r.shiftKey;let n=RTe(s),a=Date.now(),i="singleClick";a-s.input.lastClick.time<500&&uKt(r,s.input.lastClick)&&!r[tct]&&s.input.lastClick.button==r.button&&(s.input.lastClick.type=="singleClick"?i="doubleClick":s.input.lastClick.type=="doubleClick"&&(i="tripleClick")),s.input.lastClick={time:a,x:r.clientX,y:r.clientY,type:i,button:r.button};let l=s.posAtCoords(cxe(r));l&&(i=="singleClick"?(s.input.mouseDown&&s.input.mouseDown.done(),s.input.mouseDown=new yKt(s,l,r,!!n)):(i=="doubleClick"?pKt:gKt)(s,l.pos,l.inside,r)?r.preventDefault():Nk(s,"pointer"))};class yKt{constructor(t,r,n,a){this.view=t,this.pos=r,this.event=n,this.flushed=a,this.delayedSelectionSync=!1,this.mightDrag=null,this.startDoc=t.state.doc,this.selectNode=!!n[tct],this.allowDefault=n.shiftKey;let i,l;if(r.inside>-1)i=t.state.doc.nodeAt(r.inside),l=r.inside;else{let h=t.state.doc.resolve(r.pos);i=h.parent,l=h.depth?h.before():0}const o=a?null:n.target,c=o?t.docView.nearestDesc(o,!0):null;this.target=c&&c.nodeDOM.nodeType==1?c.nodeDOM:null;let{selection:d}=t.state;n.button==0&&(i.type.spec.draggable&&i.type.spec.selectable!==!1||d instanceof Si&&d.from<=l&&d.to>l)&&(this.mightDrag={node:i,pos:l,addAttr:!!(this.target&&!this.target.draggable),setUneditable:!!(this.target&&Yy&&!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()),t.root.addEventListener("mouseup",this.up=this.up.bind(this)),t.root.addEventListener("mousemove",this.move=this.move.bind(this)),Nk(t,"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(()=>Y2(this.view)),this.view.input.mouseDown=null}up(t){if(this.done(),!this.view.dom.contains(t.target))return;let r=this.pos;this.view.state.doc!=this.startDoc&&(r=this.view.posAtCoords(cxe(t))),this.updateAllowDefault(t),this.allowDefault||!r?Nk(this.view,"pointer"):fKt(this.view,r.pos,r.inside,t,this.selectNode)?t.preventDefault():t.button==0&&(this.flushed||kp&&this.mightDrag&&!this.mightDrag.node.isAtom||Ff&&!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)?(uP(this.view,Hi.near(this.view.state.doc.resolve(r.pos))),t.preventDefault()):Nk(this.view,"pointer")}move(t){this.updateAllowDefault(t),Nk(this.view,"pointer"),t.buttons==0&&this.done()}updateAllowDefault(t){!this.allowDefault&&(Math.abs(this.event.x-t.clientX)>4||Math.abs(this.event.y-t.clientY)>4)&&(this.allowDefault=!0)}}Ng.touchstart=s=>{s.input.lastTouch=Date.now(),RTe(s),Nk(s,"pointer")};Ng.touchmove=s=>{s.input.lastTouch=Date.now(),Nk(s,"pointer")};Ng.contextmenu=s=>RTe(s);function sct(s,t){return s.composing?!0:kp&&Math.abs(t.timeStamp-s.input.compositionEndedAt)<500?(s.input.compositionEndedAt=-2e8,!0):!1}const vKt=P2?5e3:-1;kg.compositionstart=kg.compositionupdate=s=>{if(!s.composing){s.domObserver.flush();let{state:t}=s,r=t.selection.$to;if(t.selection instanceof Ri&&(t.storedMarks||!r.textOffset&&r.parentOffset&&r.nodeBefore.marks.some(n=>n.type.spec.inclusive===!1)||Ff&&Plt&&bKt(s)))s.markCursor=s.state.storedMarks||r.marks(),ume(s,!0),s.markCursor=null;else if(ume(s,!t.selection.empty),Yy&&t.selection.empty&&r.parentOffset&&!r.textOffset&&r.nodeBefore.marks.length){let n=s.domSelectionRange();for(let a=n.focusNode,i=n.focusOffset;a&&a.nodeType==1&&i!=0;){let l=i<0?a.lastChild:a.childNodes[i-1];if(!l)break;if(l.nodeType==3){let o=s.domSelection();o&&o.collapse(l,l.nodeValue.length);break}else a=l,i=-1}}s.input.composing=!0}rct(s,vKt)};function bKt(s){let{focusNode:t,focusOffset:r}=s.domSelectionRange();if(!t||t.nodeType!=1||r>=t.childNodes.length)return!1;let n=t.childNodes[r];return n.nodeType==1&&n.contentEditable=="false"}kg.compositionend=(s,t)=>{s.composing&&(s.input.composing=!1,s.input.compositionEndedAt=t.timeStamp,s.input.compositionPendingChanges=s.domObserver.pendingRecords().length?s.input.compositionID:0,s.input.compositionNode=null,s.input.badSafariComposition?s.domObserver.forceFlush():s.input.compositionPendingChanges&&Promise.resolve().then(()=>s.domObserver.flush()),s.input.compositionID++,rct(s,20))};function rct(s,t){clearTimeout(s.input.composingTimeout),t>-1&&(s.input.composingTimeout=setTimeout(()=>ume(s),t))}function nct(s){for(s.composing&&(s.input.composing=!1,s.input.compositionEndedAt=wKt());s.input.compositionNodes.length>0;)s.input.compositionNodes.pop().markParentsDirty()}function _Kt(s){let t=s.domSelectionRange();if(!t.focusNode)return null;let r=mWt(t.focusNode,t.focusOffset),n=fWt(t.focusNode,t.focusOffset);if(r&&n&&r!=n){let a=n.pmViewDesc,i=s.domObserver.lastChangedTextNode;if(r==i||n==i)return i;if(!a||!a.isText(n.nodeValue))return n;if(s.input.compositionNode==n){let l=r.pmViewDesc;if(!(!l||!l.isText(r.nodeValue)))return n}}return r||n}function wKt(){let s=document.createEvent("Event");return s.initEvent("event",!0,!0),s.timeStamp}function ume(s,t=!1){if(!(P2&&s.domObserver.flushingSoon>=0)){if(s.domObserver.forceFlush(),nct(s),t||s.docView&&s.docView.dirty){let r=MTe(s),n=s.state.selection;return r&&!r.eq(n)?s.dispatch(s.state.tr.setSelection(r)):(s.markCursor||t)&&!n.$from.node(n.$from.sharedDepth(n.to)).inlineContent?s.dispatch(s.state.tr.deleteSelection()):s.updateState(s.state),!0}return!1}}function jKt(s,t){if(!s.dom.parentNode)return;let r=s.dom.parentNode.appendChild(document.createElement("div"));r.appendChild(t),r.style.cssText="position: fixed; left: -10000px; top: 10px";let n=getSelection(),a=document.createRange();a.selectNodeContents(t),s.dom.blur(),n.removeAllRanges(),n.addRange(a),setTimeout(()=>{r.parentNode&&r.parentNode.removeChild(r),s.focus()},50)}const _9=hx&&nS<15||lL&&yWt<604;Ng.copy=kg.cut=(s,t)=>{let r=t,n=s.state.selection,a=r.type=="cut";if(n.empty)return;let i=_9?null:r.clipboardData,l=n.content(),{dom:o,text:c}=PTe(s,l);i?(r.preventDefault(),i.clearData(),i.setData("text/html",o.innerHTML),i.setData("text/plain",c)):jKt(s,o),a&&s.dispatch(s.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent","cut"))};function NKt(s){return s.openStart==0&&s.openEnd==0&&s.content.childCount==1?s.content.firstChild:null}function kKt(s,t){if(!s.dom.parentNode)return;let r=s.input.shiftKey||s.state.selection.$from.parent.type.spec.code,n=s.dom.parentNode.appendChild(document.createElement(r?"textarea":"div"));r||(n.contentEditable="true"),n.style.cssText="position: fixed; left: -10000px; top: 10px",n.focus();let a=s.input.shiftKey&&s.input.lastKeyCode!=45;setTimeout(()=>{s.focus(),n.parentNode&&n.parentNode.removeChild(n),r?w9(s,n.value,null,a,t):w9(s,n.textContent,n.innerHTML,a,t)},50)}function w9(s,t,r,n,a){let i=Ylt(s,t,r,n,s.state.selection.$from);if(s.someProp("handlePaste",c=>c(s,a,i||ua.empty)))return!0;if(!i)return!1;let l=NKt(i),o=l?s.state.tr.replaceSelectionWith(l,n):s.state.tr.replaceSelection(i);return s.dispatch(o.scrollIntoView().setMeta("paste",!0).setMeta("uiEvent","paste")),!0}function act(s){let t=s.getData("text/plain")||s.getData("Text");if(t)return t;let r=s.getData("text/uri-list");return r?r.replace(/\r?\n/g," "):""}kg.paste=(s,t)=>{let r=t;if(s.composing&&!P2)return;let n=_9?null:r.clipboardData,a=s.input.shiftKey&&s.input.lastKeyCode!=45;n&&w9(s,act(n),n.getData("text/html"),a,r)?r.preventDefault():kKt(s,r)};class ict{constructor(t,r,n){this.slice=t,this.move=r,this.node=n}}const SKt=Sy?"altKey":"ctrlKey";function oct(s,t){let r;return s.someProp("dragCopies",n=>{r=r||n(t)}),r!=null?!r:!t[SKt]}Ng.dragstart=(s,t)=>{let r=t,n=s.input.mouseDown;if(n&&n.done(),!r.dataTransfer)return;let a=s.state.selection,i=a.empty?null:s.posAtCoords(cxe(r)),l;if(!(i&&i.pos>=a.from&&i.pos<=(a instanceof Si?a.to-1:a.to))){if(n&&n.mightDrag)l=Si.create(s.state.doc,n.mightDrag.pos);else if(r.target&&r.target.nodeType==1){let m=s.docView.nearestDesc(r.target,!0);m&&m.node.type.spec.draggable&&m!=s.docView&&(l=Si.create(s.state.doc,m.posBefore))}}let o=(l||s.state.selection).content(),{dom:c,text:d,slice:h}=PTe(s,o);(!r.dataTransfer.files.length||!Ff||Ilt>120)&&r.dataTransfer.clearData(),r.dataTransfer.setData(_9?"Text":"text/html",c.innerHTML),r.dataTransfer.effectAllowed="copyMove",_9||r.dataTransfer.setData("text/plain",d),s.dragging=new ict(h,oct(s,r),l)};Ng.dragend=s=>{let t=s.dragging;window.setTimeout(()=>{s.dragging==t&&(s.dragging=null)},50)};kg.dragover=kg.dragenter=(s,t)=>t.preventDefault();kg.drop=(s,t)=>{try{CKt(s,t,s.dragging)}finally{s.dragging=null}};function CKt(s,t,r){if(!t.dataTransfer)return;let n=s.posAtCoords(cxe(t));if(!n)return;let a=s.state.doc.resolve(n.pos),i=r&&r.slice;i?s.someProp("transformPasted",x=>{i=x(i,s,!1)}):i=Ylt(s,act(t.dataTransfer),_9?null:t.dataTransfer.getData("text/html"),!1,a);let l=!!(r&&oct(s,t));if(s.someProp("handleDrop",x=>x(s,t,i||ua.empty,l))){t.preventDefault();return}if(!i)return;t.preventDefault();let o=i?jlt(s.state.doc,a.pos,i):a.pos;o==null&&(o=a.pos);let c=s.state.tr;if(l){let{node:x}=r;x?x.replace(c):c.deleteSelection()}let d=c.mapping.map(o),h=i.openStart==0&&i.openEnd==0&&i.content.childCount==1,m=c.doc;if(h?c.replaceRangeWith(d,d,i.content.firstChild):c.replaceRange(d,d,i),c.doc.eq(m))return;let p=c.doc.resolve(d);if(h&&Si.isSelectable(i.content.firstChild)&&p.nodeAfter&&p.nodeAfter.sameMarkup(i.content.firstChild))c.setSelection(new Si(p));else{let x=c.mapping.map(o);c.mapping.maps[c.mapping.maps.length-1].forEach((y,_,b,j)=>x=j),c.setSelection(ITe(s,p,c.doc.resolve(x)))}s.focus(),s.dispatch(c.setMeta("uiEvent","drop"))}Ng.focus=s=>{s.input.lastFocus=Date.now(),s.focused||(s.domObserver.stop(),s.dom.classList.add("ProseMirror-focused"),s.domObserver.start(),s.focused=!0,setTimeout(()=>{s.docView&&s.hasFocus()&&!s.domObserver.currentSelection.eq(s.domSelectionRange())&&Y2(s)},20))};Ng.blur=(s,t)=>{let r=t;s.focused&&(s.domObserver.stop(),s.dom.classList.remove("ProseMirror-focused"),s.domObserver.start(),r.relatedTarget&&s.dom.contains(r.relatedTarget)&&s.domObserver.currentSelection.clear(),s.focused=!1)};Ng.beforeinput=(s,t)=>{if(Ff&&P2&&t.inputType=="deleteContentBackward"){s.domObserver.flushSoon();let{domChangeCount:n}=s.input;setTimeout(()=>{if(s.input.domChangeCount!=n||(s.dom.blur(),s.focus(),s.someProp("handleKeyDown",i=>i(s,ET(8,"Backspace")))))return;let{$cursor:a}=s.state.selection;a&&a.pos>0&&s.dispatch(s.state.tr.delete(a.pos-1,a.pos).scrollIntoView())},50)}};for(let s in kg)Ng[s]=kg[s];function j9(s,t){if(s==t)return!0;for(let r in s)if(s[r]!==t[r])return!1;for(let r in t)if(!(r in s))return!1;return!0}class hme{constructor(t,r){this.toDOM=t,this.spec=r||VE,this.side=this.spec.side||0}map(t,r,n,a){let{pos:i,deleted:l}=t.mapResult(r.from+a,this.side<0?-1:1);return l?null:new pg(i-n,i-n,this)}valid(){return!0}eq(t){return this==t||t instanceof hme&&(this.spec.key&&this.spec.key==t.spec.key||this.toDOM==t.toDOM&&j9(this.spec,t.spec))}destroy(t){this.spec.destroy&&this.spec.destroy(t)}}class iS{constructor(t,r){this.attrs=t,this.spec=r||VE}map(t,r,n,a){let i=t.map(r.from+a,this.spec.inclusiveStart?-1:1)-n,l=t.map(r.to+a,this.spec.inclusiveEnd?1:-1)-n;return i>=l?null:new pg(i,l,this)}valid(t,r){return r.from=t&&(!i||i(o.spec))&&n.push(o.copy(o.from+a,o.to+a))}for(let l=0;lt){let o=this.children[l]+1;this.children[l+2].findInner(t-o,r-o,n,a+o,i)}}map(t,r,n){return this==fp||t.maps.length==0?this:this.mapInner(t,r,0,0,n||VE)}mapInner(t,r,n,a,i){let l;for(let o=0;o{let d=c+n,h;if(h=cct(r,o,d)){for(a||(a=this.children.slice());io&&m.to=t){this.children[o]==t&&(n=this.children[o+2]);break}let i=t+1,l=i+r.content.size;for(let o=0;oi&&c.type instanceof iS){let d=Math.max(i,c.from)-i,h=Math.min(l,c.to)-i;da.map(t,r,VE));return tk.from(n)}forChild(t,r){if(r.isLeaf)return Bu.empty;let n=[];for(let a=0;ar instanceof Bu)?t:t.reduce((r,n)=>r.concat(n instanceof Bu?n:n.members),[]))}}forEachSet(t){for(let r=0;r{let b=_-y-(x-p);for(let j=0;jk+h-m)continue;let T=o[j]+h-m;x>=T?o[j+1]=p<=T?-2:-1:p>=h&&b&&(o[j]+=b,o[j+1]+=b)}m+=b}),h=r.maps[d].map(h,-1)}let c=!1;for(let d=0;d=n.content.size){c=!0;continue}let p=r.map(s[d+1]+i,-1),x=p-a,{index:y,offset:_}=n.content.findIndex(m),b=n.maybeChild(y);if(b&&_==m&&_+b.nodeSize==x){let j=o[d+2].mapInner(r,b,h+1,s[d]+i+1,l);j!=fp?(o[d]=m,o[d+1]=x,o[d+2]=j):(o[d+1]=-2,c=!0)}else c=!0}if(c){let d=EKt(o,s,t,r,a,i,l),h=mme(d,n,0,l);t=h.local;for(let m=0;mr&&l.to{let d=cct(s,o,c+r);if(d){i=!0;let h=mme(d,o,r+c+1,n);h!=fp&&a.push(c,c+o.nodeSize,h)}});let l=lct(i?dct(s):s,-r).sort(HE);for(let o=0;o0;)t++;s.splice(t,0,r)}function Gbe(s){let t=[];return s.someProp("decorations",r=>{let n=r(s.state);n&&n!=fp&&t.push(n)}),s.cursorWrapper&&t.push(Bu.create(s.state.doc,[s.cursorWrapper.deco])),tk.from(t)}const AKt={childList:!0,characterData:!0,characterDataOldValue:!0,attributes:!0,attributeOldValue:!0,subtree:!0},MKt=hx&&nS<=11;class IKt{constructor(){this.anchorNode=null,this.anchorOffset=0,this.focusNode=null,this.focusOffset=0}set(t){this.anchorNode=t.anchorNode,this.anchorOffset=t.anchorOffset,this.focusNode=t.focusNode,this.focusOffset=t.focusOffset}clear(){this.anchorNode=this.focusNode=null}eq(t){return t.anchorNode==this.anchorNode&&t.anchorOffset==this.anchorOffset&&t.focusNode==this.focusNode&&t.focusOffset==this.focusOffset}}class PKt{constructor(t,r){this.view=t,this.handleDOMChange=r,this.queue=[],this.flushingSoon=-1,this.observer=null,this.currentSelection=new IKt,this.onCharData=null,this.suppressingSelectionUpdates=!1,this.lastChangedTextNode=null,this.observer=window.MutationObserver&&new window.MutationObserver(n=>{for(let a=0;aa.type=="childList"&&a.removedNodes.length||a.type=="characterData"&&a.oldValue.length>a.target.nodeValue.length)?this.flushSoon():kp&&t.composing&&n.some(a=>a.type=="childList"&&a.target.nodeName=="TR")?(t.input.badSafariComposition=!0,this.flushSoon()):this.flush()}),MKt&&(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,AKt)),this.onCharData&&this.view.dom.addEventListener("DOMCharacterDataModified",this.onCharData),this.connectSelection()}stop(){if(this.observer){let t=this.observer.takeRecords();if(t.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(H9e(this.view)){if(this.suppressingSelectionUpdates)return Y2(this.view);if(hx&&nS<=11&&!this.view.state.selection.empty){let t=this.view.domSelectionRange();if(t.focusNode&&vA(t.focusNode,t.focusOffset,t.anchorNode,t.anchorOffset))return this.flushSoon()}this.flush()}}setCurSelection(){this.currentSelection.set(this.view.domSelectionRange())}ignoreSelectionChange(t){if(!t.focusNode)return!0;let r=new Set,n;for(let i=t.focusNode;i;i=oL(i))r.add(i);for(let i=t.anchorNode;i;i=oL(i))if(r.has(i)){n=i;break}let a=n&&this.view.docView.nearestDesc(n);if(a&&a.ignoreMutation({type:"selection",target:n.nodeType==3?n.parentNode:n}))return this.setCurSelection(),!0}pendingRecords(){if(this.observer)for(let t of this.observer.takeRecords())this.queue.push(t);return this.queue}flush(){let{view:t}=this;if(!t.docView||this.flushingSoon>-1)return;let r=this.pendingRecords();r.length&&(this.queue=[]);let n=t.domSelectionRange(),a=!this.suppressingSelectionUpdates&&!this.currentSelection.eq(n)&&H9e(t)&&!this.ignoreSelectionChange(n),i=-1,l=-1,o=!1,c=[];if(t.editable)for(let h=0;hh.nodeName=="BR")&&(t.input.lastKeyCode==8||t.input.lastKeyCode==46)){for(let h of c)if(h.nodeName=="BR"&&h.parentNode){let m=h.nextSibling;for(;m&&m.nodeType==1;){if(m.contentEditable=="false"){h.parentNode.removeChild(h);break}m=m.firstChild}}}else if(Yy&&c.length){let h=c.filter(m=>m.nodeName=="BR");if(h.length==2){let[m,p]=h;m.parentNode&&m.parentNode.parentNode==p.parentNode?p.remove():m.remove()}else{let{focusNode:m}=this.currentSelection;for(let p of h){let x=p.parentNode;x&&x.nodeName=="LI"&&(!m||RKt(t,m)!=x)&&p.remove()}}}let d=null;i<0&&a&&t.input.lastFocus>Date.now()-200&&Math.max(t.input.lastTouch,t.input.lastClick.time)-1||a)&&(i>-1&&(t.docView.markDirty(i,l),LKt(t)),t.input.badSafariComposition&&(t.input.badSafariComposition=!1,OKt(t,c)),this.handleDOMChange(i,l,o,c),t.docView&&t.docView.dirty?t.updateState(t.state):this.currentSelection.eq(n)||Y2(t),this.currentSelection.set(n))}registerMutation(t,r){if(r.indexOf(t.target)>-1)return null;let n=this.view.docView.nearestDesc(t.target);if(t.type=="attributes"&&(n==this.view.docView||t.attributeName=="contenteditable"||t.attributeName=="style"&&!t.oldValue&&!t.target.getAttribute("style"))||!n||n.ignoreMutation(t))return null;if(t.type=="childList"){for(let h=0;ha;b--){let j=n.childNodes[b-1],k=j.pmViewDesc;if(j.nodeName=="BR"&&!k){i=b;break}if(!k||k.size)break}let m=s.state.doc,p=s.someProp("domParser")||n7.fromSchema(s.state.schema),x=m.resolve(l),y=null,_=p.parse(n,{topNode:x.parent,topMatch:x.parent.contentMatchAt(x.index()),topOpen:!0,from:a,to:i,preserveWhitespace:x.parent.type.whitespace=="pre"?"full":!0,findPositions:d,ruleFromNode:BKt,context:x});if(d&&d[0].pos!=null){let b=d[0].pos,j=d[1]&&d[1].pos;j==null&&(j=b),y={anchor:b+l,head:j+l}}return{doc:_,sel:y,from:l,to:o}}function BKt(s){let t=s.pmViewDesc;if(t)return t.parseRule();if(s.nodeName=="BR"&&s.parentNode){if(kp&&/^(ul|ol)$/i.test(s.parentNode.nodeName)){let r=document.createElement("div");return r.appendChild(document.createElement("li")),{skip:r}}else if(s.parentNode.lastChild==s||kp&&/^(tr|table)$/i.test(s.parentNode.nodeName))return{ignore:!0}}else if(s.nodeName=="IMG"&&s.getAttribute("mark-placeholder"))return{ignore:!0};return null}const zKt=/^(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 $Kt(s,t,r,n,a){let i=s.input.compositionPendingChanges||(s.composing?s.input.compositionID:0);if(s.input.compositionPendingChanges=0,t<0){let R=s.input.lastSelectionTime>Date.now()-50?s.input.lastSelectionOrigin:null,z=MTe(s,R);if(z&&!s.state.selection.eq(z)){if(Ff&&P2&&s.input.lastKeyCode===13&&Date.now()-100$(s,ET(13,"Enter"))))return;let O=s.state.tr.setSelection(z);R=="pointer"?O.setMeta("pointer",!0):R=="key"&&O.scrollIntoView(),i&&O.setMeta("composition",i),s.dispatch(O)}return}let l=s.state.doc.resolve(t),o=l.sharedDepth(r);t=l.before(o+1),r=s.state.doc.resolve(r).after(o+1);let c=s.state.selection,d=FKt(s,t,r),h=s.state.doc,m=h.slice(d.from,d.to),p,x;s.input.lastKeyCode===8&&Date.now()-100Date.now()-225||P2)&&a.some(R=>R.nodeType==1&&!zKt.test(R.nodeName))&&(!y||y.endA>=y.endB)&&s.someProp("handleKeyDown",R=>R(s,ET(13,"Enter")))){s.input.lastIOSEnter=0;return}if(!y)if(n&&c instanceof Ri&&!c.empty&&c.$head.sameParent(c.$anchor)&&!s.composing&&!(d.sel&&d.sel.anchor!=d.sel.head))y={start:c.from,endA:c.to,endB:c.to};else{if(d.sel){let R=rBe(s,s.state.doc,d.sel);if(R&&!R.eq(s.state.selection)){let z=s.state.tr.setSelection(R);i&&z.setMeta("composition",i),s.dispatch(z)}}return}s.state.selection.froms.state.selection.from&&y.start<=s.state.selection.from+2&&s.state.selection.from>=d.from?y.start=s.state.selection.from:y.endA=s.state.selection.to-2&&s.state.selection.to<=d.to&&(y.endB+=s.state.selection.to-y.endA,y.endA=s.state.selection.to)),hx&&nS<=11&&y.endB==y.start+1&&y.endA==y.start&&y.start>d.from&&d.doc.textBetween(y.start-d.from-1,y.start-d.from+1)=="  "&&(y.start--,y.endA--,y.endB--);let _=d.doc.resolveNoCache(y.start-d.from),b=d.doc.resolveNoCache(y.endB-d.from),j=h.resolve(y.start),k=_.sameParent(b)&&_.parent.inlineContent&&j.end()>=y.endA;if((lL&&s.input.lastIOSEnter>Date.now()-225&&(!k||a.some(R=>R.nodeName=="DIV"||R.nodeName=="P"))||!k&&_.posR(s,ET(13,"Enter")))){s.input.lastIOSEnter=0;return}if(s.state.selection.anchor>y.start&&qKt(h,y.start,y.endA,_,b)&&s.someProp("handleKeyDown",R=>R(s,ET(8,"Backspace")))){P2&&Ff&&s.domObserver.suppressSelectionUpdates();return}Ff&&y.endB==y.start&&(s.input.lastChromeDelete=Date.now()),P2&&!k&&_.start()!=b.start()&&b.parentOffset==0&&_.depth==b.depth&&d.sel&&d.sel.anchor==d.sel.head&&d.sel.head==y.endA&&(y.endB-=2,b=d.doc.resolveNoCache(y.endB-d.from),setTimeout(()=>{s.someProp("handleKeyDown",function(R){return R(s,ET(13,"Enter"))})},20));let T=y.start,E=y.endA,A=R=>{let z=R||s.state.tr.replace(T,E,d.doc.slice(y.start-d.from,y.endB-d.from));if(d.sel){let O=rBe(s,z.doc,d.sel);O&&!(Ff&&s.composing&&O.empty&&(y.start!=y.endB||s.input.lastChromeDeleteY2(s),20));let R=A(s.state.tr.delete(T,E)),z=h.resolve(y.start).marksAcross(h.resolve(y.endA));z&&R.ensureMarks(z),s.dispatch(R)}else if(y.endA==y.endB&&(D=UKt(_.parent.content.cut(_.parentOffset,b.parentOffset),j.parent.content.cut(j.parentOffset,y.endA-j.start())))){let R=A(s.state.tr);D.type=="add"?R.addMark(T,E,D.mark):R.removeMark(T,E,D.mark),s.dispatch(R)}else if(_.parent.child(_.index()).isText&&_.index()==b.index()-(b.textOffset?0:1)){let R=_.parent.textBetween(_.parentOffset,b.parentOffset),z=()=>A(s.state.tr.insertText(R,T,E));s.someProp("handleTextInput",O=>O(s,T,E,R,z))||s.dispatch(z())}else s.dispatch(A());else s.dispatch(A())}function rBe(s,t,r){return Math.max(r.anchor,r.head)>t.content.size?null:ITe(s,t.resolve(r.anchor),t.resolve(r.head))}function UKt(s,t){let r=s.firstChild.marks,n=t.firstChild.marks,a=r,i=n,l,o,c;for(let h=0;hh.mark(o.addToSet(h.marks));else if(a.length==0&&i.length==1)o=i[0],l="remove",c=h=>h.mark(o.removeFromSet(h.marks));else return null;let d=[];for(let h=0;hr||Wbe(l,!0,!1)0&&(t||s.indexAfter(n)==s.node(n).childCount);)n--,a++,t=!1;if(r){let i=s.node(n).maybeChild(s.indexAfter(n));for(;i&&!i.isLeaf;)i=i.firstChild,a++}return a}function VKt(s,t,r,n,a){let i=s.findDiffStart(t,r);if(i==null)return null;let{a:l,b:o}=s.findDiffEnd(t,r+s.size,r+t.size);if(a=="end"){let c=Math.max(0,i-Math.min(l,o));n-=l+c-i}if(l=l?i-n:0;i-=c,i&&i=o?i-n:0;i-=c,i&&i=56320&&t<=57343&&r>=55296&&r<=56319}class uct{constructor(t,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 iKt,this.prevDirectPlugins=[],this.pluginViews=[],this.requiresGeckoHackNode=!1,this.dragging=null,this._props=r,this.state=r.state,this.directPlugins=r.plugins||[],this.directPlugins.forEach(cBe),this.dispatch=this.dispatch.bind(this),this.dom=t&&t.mount||document.createElement("div"),t&&(t.appendChild?t.appendChild(this.dom):typeof t=="function"?t(this.dom):t.mount&&(this.mounted=!0)),this.editable=oBe(this),iBe(this),this.nodeViews=lBe(this),this.docView=B9e(this.state.doc,aBe(this),Gbe(this),this.dom,this),this.domObserver=new PKt(this,(n,a,i,l)=>$Kt(this,n,a,i,l)),this.domObserver.start(),oKt(this),this.updatePluginViews()}get composing(){return this.input.composing}get props(){if(this._props.state!=this.state){let t=this._props;this._props={};for(let r in t)this._props[r]=t[r];this._props.state=this.state}return this._props}update(t){t.handleDOMEvents!=this._props.handleDOMEvents&&ake(this);let r=this._props;this._props=t,t.plugins&&(t.plugins.forEach(cBe),this.directPlugins=t.plugins),this.updateStateInner(t.state,r)}setProps(t){let r={};for(let n in this._props)r[n]=this._props[n];r.state=this.state;for(let n in t)r[n]=t[n];this.update(r)}updateState(t){this.updateStateInner(t,this._props)}updateStateInner(t,r){var n;let a=this.state,i=!1,l=!1;t.storedMarks&&this.composing&&(nct(this),l=!0),this.state=t;let o=a.plugins!=t.plugins||this._props.plugins!=r.plugins;if(o||this._props.plugins!=r.plugins||this._props.nodeViews!=r.nodeViews){let x=lBe(this);GKt(x,this.nodeViews)&&(this.nodeViews=x,i=!0)}(o||r.handleDOMEvents!=this._props.handleDOMEvents)&&ake(this),this.editable=oBe(this),iBe(this);let c=Gbe(this),d=aBe(this),h=a.plugins!=t.plugins&&!a.doc.eq(t.doc)?"reset":t.scrollToSelection>a.scrollToSelection?"to selection":"preserve",m=i||!this.docView.matchesNode(t.doc,d,c);(m||!t.selection.eq(a.selection))&&(l=!0);let p=h=="preserve"&&l&&this.dom.style.overflowAnchor==null&&_Wt(this);if(l){this.domObserver.stop();let x=m&&(hx||Ff)&&!this.composing&&!a.selection.empty&&!t.selection.empty&&HKt(a.selection,t.selection);if(m){let y=Ff?this.trackWrites=this.domSelectionRange().focusNode:null;this.composing&&(this.input.compositionNode=_Kt(this)),(i||!this.docView.update(t.doc,d,c,this))&&(this.docView.updateOuterDeco(d),this.docView.destroy(),this.docView=B9e(t.doc,d,c,this.dom,this)),y&&(!this.trackWrites||!this.dom.contains(this.trackWrites))&&(x=!0)}x||!(this.input.mouseDown&&this.domObserver.currentSelection.eq(this.domSelectionRange())&&HWt(this))?Y2(this,x):(Glt(this,t.selection),this.domObserver.setCurSelection()),this.domObserver.start()}this.updatePluginViews(a),!((n=this.dragging)===null||n===void 0)&&n.node&&!a.doc.eq(t.doc)&&this.updateDraggedNode(this.dragging,a),h=="reset"?this.dom.scrollTop=0:h=="to selection"?this.scrollToSelection():p&&wWt(p)}scrollToSelection(){let t=this.domSelectionRange().focusNode;if(!(!t||!this.dom.contains(t.nodeType==1?t:t.parentNode))){if(!this.someProp("handleScrollToSelection",r=>r(this)))if(this.state.selection instanceof Si){let r=this.docView.domAfterPos(this.state.selection.from);r.nodeType==1&&P9e(this,r.getBoundingClientRect(),t)}else P9e(this,this.coordsAtPos(this.state.selection.head,1),t)}}destroyPluginViews(){let t;for(;t=this.pluginViews.pop();)t.destroy&&t.destroy()}updatePluginViews(t){if(!t||t.plugins!=this.state.plugins||this.directPlugins!=this.prevDirectPlugins){this.prevDirectPlugins=this.directPlugins,this.destroyPluginViews();for(let r=0;r0&&ir.ownerDocument.getSelection()),this._root=r}return t||document}updateRoot(){this._root=null}posAtCoords(t){return TWt(this,t)}coordsAtPos(t,r=1){return Flt(this,t,r)}domAtPos(t,r=0){return this.docView.domFromPos(t,r)}nodeDOM(t){let r=this.docView.descAt(t);return r?r.nodeDOM:null}posAtDOM(t,r,n=-1){let a=this.docView.posFromDOM(t,r,n);if(a==null)throw new RangeError("DOM position not inside the editor");return a}endOfTextblock(t,r){return PWt(this,r||this.state,t)}pasteHTML(t,r){return w9(this,"",t,!1,r||new ClipboardEvent("paste"))}pasteText(t,r){return w9(this,t,null,!0,r||new ClipboardEvent("paste"))}serializeForClipboard(t){return PTe(this,t)}destroy(){this.docView&&(lKt(this),this.destroyPluginViews(),this.mounted?(this.docView.update(this.state.doc,[],Gbe(this),this),this.dom.textContent=""):this.dom.parentNode&&this.dom.parentNode.removeChild(this.dom),this.docView.destroy(),this.docView=null,uWt())}get isDestroyed(){return this.docView==null}dispatchEvent(t){return dKt(this,t)}domSelectionRange(){let t=this.domSelection();return t?kp&&this.root.nodeType===11&&gWt(this.dom.ownerDocument)==this.dom&&DKt(this,t)||t:{focusNode:null,focusOffset:0,anchorNode:null,anchorOffset:0}}domSelection(){return this.root.getSelection()}}uct.prototype.dispatch=function(s){let t=this._props.dispatchTransaction;t?t.call(this,s):this.updateState(this.state.apply(s))};function aBe(s){let t=Object.create(null);return t.class="ProseMirror",t.contenteditable=String(s.editable),s.someProp("attributes",r=>{if(typeof r=="function"&&(r=r(s.state)),r)for(let n in r)n=="class"?t.class+=" "+r[n]:n=="style"?t.style=(t.style?t.style+";":"")+r[n]:!t[n]&&n!="contenteditable"&&n!="nodeName"&&(t[n]=String(r[n]))}),t.translate||(t.translate="no"),[pg.node(0,s.state.doc.content.size,t)]}function iBe(s){if(s.markCursor){let t=document.createElement("img");t.className="ProseMirror-separator",t.setAttribute("mark-placeholder","true"),t.setAttribute("alt",""),s.cursorWrapper={dom:t,deco:pg.widget(s.state.selection.from,t,{raw:!0,marks:s.markCursor})}}else s.cursorWrapper=null}function oBe(s){return!s.someProp("editable",t=>t(s.state)===!1)}function HKt(s,t){let r=Math.min(s.$anchor.sharedDepth(s.head),t.$anchor.sharedDepth(t.head));return s.$anchor.start(r)!=t.$anchor.start(r)}function lBe(s){let t=Object.create(null);function r(n){for(let a in n)Object.prototype.hasOwnProperty.call(t,a)||(t[a]=n[a])}return s.someProp("nodeViews",r),s.someProp("markViews",r),t}function GKt(s,t){let r=0,n=0;for(let a in s){if(s[a]!=t[a])return!0;r++}for(let a in t)n++;return r!=n}function cBe(s){if(s.spec.state||s.spec.filterTransaction||s.spec.appendTransaction)throw new RangeError("Plugins passed directly to the view must not have a state component")}var NS={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:"'"},fme={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},WKt=typeof navigator<"u"&&/Mac/.test(navigator.platform),KKt=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);for(var Df=0;Df<10;Df++)NS[48+Df]=NS[96+Df]=String(Df);for(var Df=1;Df<=24;Df++)NS[Df+111]="F"+Df;for(var Df=65;Df<=90;Df++)NS[Df]=String.fromCharCode(Df+32),fme[Df]=String.fromCharCode(Df);for(var Kbe in NS)fme.hasOwnProperty(Kbe)||(fme[Kbe]=NS[Kbe]);function YKt(s){var t=WKt&&s.metaKey&&s.shiftKey&&!s.ctrlKey&&!s.altKey||KKt&&s.shiftKey&&s.key&&s.key.length==1||s.key=="Unidentified",r=!t&&s.key||(s.shiftKey?fme:NS)[s.keyCode]||s.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 ZKt=typeof navigator<"u"&&/Mac|iP(hone|[oa]d)/.test(navigator.platform),XKt=typeof navigator<"u"&&/Win/.test(navigator.platform);function QKt(s){let t=s.split(/-(?!$)/),r=t[t.length-1];r=="Space"&&(r=" ");let n,a,i,l;for(let o=0;os.selection.empty?!1:(t&&t(s.tr.deleteSelection().scrollIntoView()),!0);function hct(s,t){let{$cursor:r}=s.selection;return!r||(t?!t.endOfTextblock("backward",s):r.parentOffset>0)?null:r}const sYt=(s,t,r)=>{let n=hct(s,r);if(!n)return!1;let a=zTe(n);if(!a){let l=n.blockRange(),o=l&&b8(l);return o==null?!1:(t&&t(s.tr.lift(l,o).scrollIntoView()),!0)}let i=a.nodeBefore;if(gct(s,a,t,-1))return!0;if(n.parent.content.size==0&&(cL(i,"end")||Si.isSelectable(i)))for(let l=n.depth;;l--){let o=axe(s.doc,n.before(l),n.after(l),ua.empty);if(o&&o.slice.size1)break}return i.isAtom&&a.depth==n.depth-1?(t&&t(s.tr.delete(a.pos-i.nodeSize,a.pos).scrollIntoView()),!0):!1},rYt=(s,t,r)=>{let n=hct(s,r);if(!n)return!1;let a=zTe(n);return a?mct(s,a,t):!1},nYt=(s,t,r)=>{let n=fct(s,r);if(!n)return!1;let a=$Te(n);return a?mct(s,a,t):!1};function mct(s,t,r){let n=t.nodeBefore,a=n,i=t.pos-1;for(;!a.isTextblock;i--){if(a.type.spec.isolating)return!1;let h=a.lastChild;if(!h)return!1;a=h}let l=t.nodeAfter,o=l,c=t.pos+1;for(;!o.isTextblock;c++){if(o.type.spec.isolating)return!1;let h=o.firstChild;if(!h)return!1;o=h}let d=axe(s.doc,i,c,ua.empty);if(!d||d.from!=i||d instanceof Ih&&d.slice.size>=c-i)return!1;if(r){let h=s.tr.step(d);h.setSelection(Ri.create(h.doc,i)),r(h.scrollIntoView())}return!0}function cL(s,t,r=!1){for(let n=s;n;n=t=="start"?n.firstChild:n.lastChild){if(n.isTextblock)return!0;if(r&&n.childCount!=1)return!1}return!1}const aYt=(s,t,r)=>{let{$head:n,empty:a}=s.selection,i=n;if(!a)return!1;if(n.parent.isTextblock){if(r?!r.endOfTextblock("backward",s):n.parentOffset>0)return!1;i=zTe(n)}let l=i&&i.nodeBefore;return!l||!Si.isSelectable(l)?!1:(t&&t(s.tr.setSelection(Si.create(s.doc,i.pos-l.nodeSize)).scrollIntoView()),!0)};function zTe(s){if(!s.parent.type.spec.isolating)for(let t=s.depth-1;t>=0;t--){if(s.index(t)>0)return s.doc.resolve(s.before(t+1));if(s.node(t).type.spec.isolating)break}return null}function fct(s,t){let{$cursor:r}=s.selection;return!r||(t?!t.endOfTextblock("forward",s):r.parentOffset{let n=fct(s,r);if(!n)return!1;let a=$Te(n);if(!a)return!1;let i=a.nodeAfter;if(gct(s,a,t,1))return!0;if(n.parent.content.size==0&&(cL(i,"start")||Si.isSelectable(i))){let l=axe(s.doc,n.before(),n.after(),ua.empty);if(l&&l.slice.size{let{$head:n,empty:a}=s.selection,i=n;if(!a)return!1;if(n.parent.isTextblock){if(r?!r.endOfTextblock("forward",s):n.parentOffset=0;t--){let r=s.node(t);if(s.index(t)+1{let r=s.selection,n=r instanceof Si,a;if(n){if(r.node.isTextblock||!HS(s.doc,r.from))return!1;a=r.from}else if(a=nxe(s.doc,r.from,-1),a==null)return!1;if(t){let i=s.tr.join(a);n&&i.setSelection(Si.create(i.doc,a-s.doc.resolve(a).nodeBefore.nodeSize)),t(i.scrollIntoView())}return!0},cYt=(s,t)=>{let r=s.selection,n;if(r instanceof Si){if(r.node.isTextblock||!HS(s.doc,r.to))return!1;n=r.to}else if(n=nxe(s.doc,r.to,1),n==null)return!1;return t&&t(s.tr.join(n).scrollIntoView()),!0},dYt=(s,t)=>{let{$from:r,$to:n}=s.selection,a=r.blockRange(n),i=a&&b8(a);return i==null?!1:(t&&t(s.tr.lift(a,i).scrollIntoView()),!0)},uYt=(s,t)=>{let{$head:r,$anchor:n}=s.selection;return!r.parent.type.spec.code||!r.sameParent(n)?!1:(t&&t(s.tr.insertText(` `).scrollIntoView()),!0)};function pct(s){for(let t=0;t{let{$head:r,$anchor:n}=s.selection;if(!r.parent.type.spec.code||!r.sameParent(n))return!1;let a=r.node(-1),i=r.indexAfter(-1),l=pct(a.contentMatchAt(i));if(!l||!a.canReplaceWith(i,i,l))return!1;if(t){let o=r.after(),c=s.tr.replaceWith(o,o,l.createAndFill());c.setSelection(Hi.near(c.doc.resolve(o),1)),t(c.scrollIntoView())}return!0},mYt=(s,t)=>{let r=s.selection,{$from:n,$to:a}=r;if(r instanceof Ky||n.parent.inlineContent||a.parent.inlineContent)return!1;let i=pct(a.parent.contentMatchAt(a.indexAfter()));if(!i||!i.isTextblock)return!1;if(t){let l=(!n.parentOffset&&a.index(){let{$cursor:r}=s.selection;if(!r||r.parent.content.size)return!1;if(r.depth>1&&r.after()!=r.end(-1)){let i=r.before();if(cP(s.doc,i))return t&&t(s.tr.split(i).scrollIntoView()),!0}let n=r.blockRange(),a=n&&b8(n);return a==null?!1:(t&&t(s.tr.lift(n,a).scrollIntoView()),!0)},pYt=(s,t)=>{let{$from:r,to:n}=s.selection,a,i=r.sharedDepth(n);return i==0?!1:(a=r.before(i),t&&t(s.tr.setSelection(Si.create(s.doc,a))),!0)};function gYt(s,t,r){let n=t.nodeBefore,a=t.nodeAfter,i=t.index();return!n||!a||!n.type.compatibleContent(a.type)?!1:!n.content.size&&t.parent.canReplace(i-1,i)?(r&&r(s.tr.delete(t.pos-n.nodeSize,t.pos).scrollIntoView()),!0):!t.parent.canReplace(i,i+1)||!(a.isTextblock||HS(s.doc,t.pos))?!1:(r&&r(s.tr.join(t.pos).scrollIntoView()),!0)}function gct(s,t,r,n){let a=t.nodeBefore,i=t.nodeAfter,l,o,c=a.type.spec.isolating||i.type.spec.isolating;if(!c&&gYt(s,t,r))return!0;let d=!c&&t.parent.canReplace(t.index(),t.index()+1);if(d&&(l=(o=a.contentMatchAt(a.childCount)).findWrapping(i.type))&&o.matchType(l[0]||i.type).validEnd){if(r){let x=t.pos+i.nodeSize,y=An.empty;for(let j=l.length-1;j>=0;j--)y=An.from(l[j].create(null,y));y=An.from(a.copy(y));let _=s.tr.step(new rf(t.pos-1,x,t.pos,x,new ua(y,1,0),l.length,!0)),b=_.doc.resolve(x+2*l.length);b.nodeAfter&&b.nodeAfter.type==a.type&&HS(_.doc,b.pos)&&_.join(b.pos),r(_.scrollIntoView())}return!0}let h=i.type.spec.isolating||n>0&&c?null:Hi.findFrom(t,1),m=h&&h.$from.blockRange(h.$to),p=m&&b8(m);if(p!=null&&p>=t.depth)return r&&r(s.tr.lift(m,p).scrollIntoView()),!0;if(d&&cL(i,"start",!0)&&cL(a,"end")){let x=a,y=[];for(;y.push(x),!x.isTextblock;)x=x.lastChild;let _=i,b=1;for(;!_.isTextblock;_=_.firstChild)b++;if(x.canReplace(x.childCount,x.childCount,_.content)){if(r){let j=An.empty;for(let T=y.length-1;T>=0;T--)j=An.from(y[T].copy(j));let k=s.tr.step(new rf(t.pos-y.length,t.pos+i.nodeSize,t.pos+b,t.pos+i.nodeSize-b,new ua(j,y.length,0),0,!0));r(k.scrollIntoView())}return!0}}return!1}function xct(s){return function(t,r){let n=t.selection,a=s<0?n.$from:n.$to,i=a.depth;for(;a.node(i).isInline;){if(!i)return!1;i--}return a.node(i).isTextblock?(r&&r(t.tr.setSelection(Ri.create(t.doc,s<0?a.start(i):a.end(i)))),!0):!1}}const xYt=xct(-1),yYt=xct(1);function vYt(s,t=null){return function(r,n){let{$from:a,$to:i}=r.selection,l=a.blockRange(i),o=l&&CTe(l,s,t);return o?(n&&n(r.tr.wrap(l,o).scrollIntoView()),!0):!1}}function dBe(s,t=null){return function(r,n){let a=!1;for(let i=0;i{if(a)return!1;if(!(!c.isTextblock||c.hasMarkup(s,t)))if(c.type==s)a=!0;else{let h=r.doc.resolve(d),m=h.index();a=h.parent.canReplaceWith(m,m+1,s)}})}if(!a)return!1;if(n){let i=r.tr;for(let l=0;l=2&&t.$from.node(t.depth-1).type.compatibleContent(r)&&t.startIndex==0){if(t.$from.index(t.depth-1)==0)return!1;let c=l.resolve(t.start-2);i=new ome(c,c,t.depth),t.endIndex=0;h--)i=An.from(r[h].type.create(r[h].attrs,i));s.step(new rf(t.start-(n?2:0),t.end,t.start,t.end,new ua(i,0,0),r.length,!0));let l=0;for(let h=0;hl.childCount>0&&l.firstChild.type==s);return i?r?n.node(i.depth-1).type==s?NYt(t,r,s,i):kYt(t,r,i):!0:!1}}function NYt(s,t,r,n){let a=s.tr,i=n.end,l=n.$to.end(n.depth);i_;y--)x-=a.child(y).nodeSize,n.delete(x-1,x+1);let i=n.doc.resolve(r.start),l=i.nodeAfter;if(n.mapping.map(r.end)!=r.start+i.nodeAfter.nodeSize)return!1;let o=r.startIndex==0,c=r.endIndex==a.childCount,d=i.node(-1),h=i.index(-1);if(!d.canReplace(h+(o?0:1),h+1,l.content.append(c?An.empty:An.from(a))))return!1;let m=i.pos,p=m+l.nodeSize;return n.step(new rf(m-(o?1:0),p+(c?1:0),m+1,p-1,new ua((o?An.empty:An.from(a.copy(An.empty))).append(c?An.empty:An.from(a.copy(An.empty))),o?0:1,c?0:1),o?0:1)),t(n.scrollIntoView()),!0}function SYt(s){return function(t,r){let{$from:n,$to:a}=t.selection,i=n.blockRange(a,d=>d.childCount>0&&d.firstChild.type==s);if(!i)return!1;let l=i.startIndex;if(l==0)return!1;let o=i.parent,c=o.child(l-1);if(c.type!=s)return!1;if(r){let d=c.lastChild&&c.lastChild.type==o.type,h=An.from(d?s.create():null),m=new ua(An.from(s.create(null,An.from(o.type.create(null,h)))),d?3:1,0),p=i.start,x=i.end;r(t.tr.step(new rf(p-(d?3:1),x,p,x,m,1,!0)).scrollIntoView())}return!0}}function dxe(s){const{state:t,transaction:r}=s;let{selection:n}=r,{doc:a}=r,{storedMarks:i}=r;return{...t,apply:t.apply.bind(t),applyTransaction:t.applyTransaction.bind(t),plugins:t.plugins,schema:t.schema,reconfigure:t.reconfigure.bind(t),toJSON:t.toJSON.bind(t),get storedMarks(){return i},get selection(){return n},get doc(){return a},get tr(){return n=r.selection,a=r.doc,i=r.storedMarks,r}}}class uxe{constructor(t){this.editor=t.editor,this.rawCommands=this.editor.extensionManager.commands,this.customState=t.state}get hasCustomState(){return!!this.customState}get state(){return this.customState||this.editor.state}get commands(){const{rawCommands:t,editor:r,state:n}=this,{view:a}=r,{tr:i}=n,l=this.buildProps(i);return Object.fromEntries(Object.entries(t).map(([o,c])=>[o,(...h)=>{const m=c(...h)(l);return!i.getMeta("preventDispatch")&&!this.hasCustomState&&a.dispatch(i),m}]))}get chain(){return()=>this.createChain()}get can(){return()=>this.createCan()}createChain(t,r=!0){const{rawCommands:n,editor:a,state:i}=this,{view:l}=a,o=[],c=!!t,d=t||i.tr,h=()=>(!c&&r&&!d.getMeta("preventDispatch")&&!this.hasCustomState&&l.dispatch(d),o.every(p=>p===!0)),m={...Object.fromEntries(Object.entries(n).map(([p,x])=>[p,(..._)=>{const b=this.buildProps(d,r),j=x(..._)(b);return o.push(j),m}])),run:h};return m}createCan(t){const{rawCommands:r,state:n}=this,a=!1,i=t||n.tr,l=this.buildProps(i,a);return{...Object.fromEntries(Object.entries(r).map(([c,d])=>[c,(...h)=>d(...h)({...l,dispatch:void 0})])),chain:()=>this.createChain(i,a)}}buildProps(t,r=!0){const{rawCommands:n,editor:a,state:i}=this,{view:l}=a,o={tr:t,editor:a,view:l,state:dxe({state:i,transaction:t}),dispatch:r?()=>{}:void 0,chain:()=>this.createChain(t,r),can:()=>this.createCan(t),get commands(){return Object.fromEntries(Object.entries(n).map(([c,d])=>[c,(...h)=>d(...h)(o)]))}};return o}}let CYt=class{constructor(){this.callbacks={}}on(t,r){return this.callbacks[t]||(this.callbacks[t]=[]),this.callbacks[t].push(r),this}emit(t,...r){const n=this.callbacks[t];return n&&n.forEach(a=>a.apply(this,r)),this}off(t,r){const n=this.callbacks[t];return n&&(r?this.callbacks[t]=n.filter(a=>a!==r):delete this.callbacks[t]),this}once(t,r){const n=(...a)=>{this.off(t,n),r.apply(this,a)};return this.on(t,n)}removeAllListeners(){this.callbacks={}}};function si(s,t,r){return s.config[t]===void 0&&s.parent?si(s.parent,t,r):typeof s.config[t]=="function"?s.config[t].bind({...r,parent:s.parent?si(s.parent,t,r):null}):s.config[t]}function hxe(s){const t=s.filter(a=>a.type==="extension"),r=s.filter(a=>a.type==="node"),n=s.filter(a=>a.type==="mark");return{baseExtensions:t,nodeExtensions:r,markExtensions:n}}function yct(s){const t=[],{nodeExtensions:r,markExtensions:n}=hxe(s),a=[...r,...n],i={default:null,rendered:!0,renderHTML:null,parseHTML:null,keepOnSplit:!0,isRequired:!1};return s.forEach(l=>{const o={name:l.name,options:l.options,storage:l.storage,extensions:a},c=si(l,"addGlobalAttributes",o);if(!c)return;c().forEach(h=>{h.types.forEach(m=>{Object.entries(h.attributes).forEach(([p,x])=>{t.push({type:m,name:p,attribute:{...i,...x}})})})})}),a.forEach(l=>{const o={name:l.name,options:l.options,storage:l.storage},c=si(l,"addAttributes",o);if(!c)return;const d=c();Object.entries(d).forEach(([h,m])=>{const p={...i,...m};typeof(p==null?void 0:p.default)=="function"&&(p.default=p.default()),p!=null&&p.isRequired&&(p==null?void 0:p.default)===void 0&&delete p.default,t.push({type:l.name,name:h,attribute:p})})}),t}function of(s,t){if(typeof s=="string"){if(!t.nodes[s])throw Error(`There is no node type named '${s}'. Maybe you forgot to add the extension?`);return t.nodes[s]}return s}function Xd(...s){return s.filter(t=>!!t).reduce((t,r)=>{const n={...t};return Object.entries(r).forEach(([a,i])=>{if(!n[a]){n[a]=i;return}if(a==="class"){const o=i?String(i).split(" "):[],c=n[a]?n[a].split(" "):[],d=o.filter(h=>!c.includes(h));n[a]=[...c,...d].join(" ")}else if(a==="style"){const o=i?i.split(";").map(h=>h.trim()).filter(Boolean):[],c=n[a]?n[a].split(";").map(h=>h.trim()).filter(Boolean):[],d=new Map;c.forEach(h=>{const[m,p]=h.split(":").map(x=>x.trim());d.set(m,p)}),o.forEach(h=>{const[m,p]=h.split(":").map(x=>x.trim());d.set(m,p)}),n[a]=Array.from(d.entries()).map(([h,m])=>`${h}: ${m}`).join("; ")}else n[a]=i}),n},{})}function ike(s,t){return t.filter(r=>r.type===s.type.name).filter(r=>r.attribute.rendered).map(r=>r.attribute.renderHTML?r.attribute.renderHTML(s.attrs)||{}:{[r.name]:s.attrs[r.name]}).reduce((r,n)=>Xd(r,n),{})}function vct(s){return typeof s=="function"}function Fo(s,t=void 0,...r){return vct(s)?t?s.bind(t)(...r):s(...r):s}function TYt(s={}){return Object.keys(s).length===0&&s.constructor===Object}function EYt(s){return typeof s!="string"?s:s.match(/^[+-]?(?:\d*\.)?\d+$/)?Number(s):s==="true"?!0:s==="false"?!1:s}function uBe(s,t){return"style"in s?s:{...s,getAttrs:r=>{const n=s.getAttrs?s.getAttrs(r):s.attrs;if(n===!1)return!1;const a=t.reduce((i,l)=>{const o=l.attribute.parseHTML?l.attribute.parseHTML(r):EYt(r.getAttribute(l.name));return o==null?i:{...i,[l.name]:o}},{});return{...n,...a}}}}function hBe(s){return Object.fromEntries(Object.entries(s).filter(([t,r])=>t==="attrs"&&TYt(r)?!1:r!=null))}function AYt(s,t){var r;const n=yct(s),{nodeExtensions:a,markExtensions:i}=hxe(s),l=(r=a.find(d=>si(d,"topNode")))===null||r===void 0?void 0:r.name,o=Object.fromEntries(a.map(d=>{const h=n.filter(j=>j.type===d.name),m={name:d.name,options:d.options,storage:d.storage,editor:t},p=s.reduce((j,k)=>{const T=si(k,"extendNodeSchema",m);return{...j,...T?T(d):{}}},{}),x=hBe({...p,content:Fo(si(d,"content",m)),marks:Fo(si(d,"marks",m)),group:Fo(si(d,"group",m)),inline:Fo(si(d,"inline",m)),atom:Fo(si(d,"atom",m)),selectable:Fo(si(d,"selectable",m)),draggable:Fo(si(d,"draggable",m)),code:Fo(si(d,"code",m)),whitespace:Fo(si(d,"whitespace",m)),linebreakReplacement:Fo(si(d,"linebreakReplacement",m)),defining:Fo(si(d,"defining",m)),isolating:Fo(si(d,"isolating",m)),attrs:Object.fromEntries(h.map(j=>{var k;return[j.name,{default:(k=j==null?void 0:j.attribute)===null||k===void 0?void 0:k.default}]}))}),y=Fo(si(d,"parseHTML",m));y&&(x.parseDOM=y.map(j=>uBe(j,h)));const _=si(d,"renderHTML",m);_&&(x.toDOM=j=>_({node:j,HTMLAttributes:ike(j,h)}));const b=si(d,"renderText",m);return b&&(x.toText=b),[d.name,x]})),c=Object.fromEntries(i.map(d=>{const h=n.filter(b=>b.type===d.name),m={name:d.name,options:d.options,storage:d.storage,editor:t},p=s.reduce((b,j)=>{const k=si(j,"extendMarkSchema",m);return{...b,...k?k(d):{}}},{}),x=hBe({...p,inclusive:Fo(si(d,"inclusive",m)),excludes:Fo(si(d,"excludes",m)),group:Fo(si(d,"group",m)),spanning:Fo(si(d,"spanning",m)),code:Fo(si(d,"code",m)),attrs:Object.fromEntries(h.map(b=>{var j;return[b.name,{default:(j=b==null?void 0:b.attribute)===null||j===void 0?void 0:j.default}]}))}),y=Fo(si(d,"parseHTML",m));y&&(x.parseDOM=y.map(b=>uBe(b,h)));const _=si(d,"renderHTML",m);return _&&(x.toDOM=b=>_({mark:b,HTMLAttributes:ike(b,h)})),[d.name,x]}));return new hlt({topNode:l,nodes:o,marks:c})}function Zbe(s,t){return t.nodes[s]||t.marks[s]||null}function mBe(s,t){return Array.isArray(t)?t.some(r=>(typeof r=="string"?r:r.name)===s.name):t}function UTe(s,t){const r=VA.fromSchema(t).serializeFragment(s),a=document.implementation.createHTMLDocument().createElement("div");return a.appendChild(r),a.innerHTML}const MYt=(s,t=500)=>{let r="";const n=s.parentOffset;return s.parent.nodesBetween(Math.max(0,n-t),n,(a,i,l,o)=>{var c,d;const h=((d=(c=a.type.spec).toText)===null||d===void 0?void 0:d.call(c,{node:a,pos:i,parent:l,index:o}))||a.textContent||"%leaf%";r+=a.isAtom&&!a.isText?h:h.slice(0,Math.max(0,n-i))}),r};function qTe(s){return Object.prototype.toString.call(s)==="[object RegExp]"}class mxe{constructor(t){this.find=t.find,this.handler=t.handler}}const IYt=(s,t)=>{if(qTe(t))return t.exec(s);const r=t(s);if(!r)return null;const n=[r.text];return n.index=r.index,n.input=s,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 JU(s){var t;const{editor:r,from:n,to:a,text:i,rules:l,plugin:o}=s,{view:c}=r;if(c.composing)return!1;const d=c.state.doc.resolve(n);if(d.parent.type.spec.code||!((t=d.nodeBefore||d.nodeAfter)===null||t===void 0)&&t.marks.find(p=>p.type.spec.code))return!1;let h=!1;const m=MYt(d)+i;return l.forEach(p=>{if(h)return;const x=IYt(m,p.find);if(!x)return;const y=c.state.tr,_=dxe({state:c.state,transaction:y}),b={from:n-(x[0].length-i.length),to:a},{commands:j,chain:k,can:T}=new uxe({editor:r,state:_});p.handler({state:_,range:b,match:x,commands:j,chain:k,can:T})===null||!y.steps.length||(y.setMeta(o,{transform:y,from:n,to:a,text:i}),c.dispatch(y),h=!0)}),h}function PYt(s){const{editor:t,rules:r}=s,n=new jm({state:{init(){return null},apply(a,i,l){const o=a.getMeta(n);if(o)return o;const c=a.getMeta("applyInputRules");return!!c&&setTimeout(()=>{let{text:h}=c;typeof h=="string"?h=h:h=UTe(An.from(h),l.schema);const{from:m}=c,p=m+h.length;JU({editor:t,from:m,to:p,text:h,rules:r,plugin:n})}),a.selectionSet||a.docChanged?null:i}},props:{handleTextInput(a,i,l,o){return JU({editor:t,from:i,to:l,text:o,rules:r,plugin:n})},handleDOMEvents:{compositionend:a=>(setTimeout(()=>{const{$cursor:i}=a.state.selection;i&&JU({editor:t,from:i.pos,to:i.pos,text:"",rules:r,plugin:n})}),!1)},handleKeyDown(a,i){if(i.key!=="Enter")return!1;const{$cursor:l}=a.state.selection;return l?JU({editor:t,from:l.pos,to:l.pos,text:` `,rules:r,plugin:n}):!1}},isInputRules:!0});return n}function LYt(s){return Object.prototype.toString.call(s).slice(8,-1)}function eq(s){return LYt(s)!=="Object"?!1:s.constructor===Object&&Object.getPrototypeOf(s)===Object.prototype}function fxe(s,t){const r={...s};return eq(s)&&eq(t)&&Object.keys(t).forEach(n=>{eq(t[n])&&eq(s[n])?r[n]=fxe(s[n],t[n]):r[n]=t[n]}),r}class M1{constructor(t={}){this.type="mark",this.name="mark",this.parent=null,this.child=null,this.config={name:this.name,defaultOptions:{}},this.config={...this.config,...t},this.name=this.config.name,t.defaultOptions&&Object.keys(t.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=Fo(si(this,"addOptions",{name:this.name}))),this.storage=Fo(si(this,"addStorage",{name:this.name,options:this.options}))||{}}static create(t={}){return new M1(t)}configure(t={}){const r=this.extend({...this.config,addOptions:()=>fxe(this.options,t)});return r.name=this.name,r.parent=this.parent,r}extend(t={}){const r=new M1(t);return r.parent=this,this.child=r,r.name=t.name?t.name:r.parent.name,t.defaultOptions&&Object.keys(t.defaultOptions).length>0&&console.warn(`[tiptap warn]: BREAKING CHANGE: "defaultOptions" is deprecated. Please use "addOptions" instead. Found in extension: "${r.name}".`),r.options=Fo(si(r,"addOptions",{name:r.name})),r.storage=Fo(si(r,"addStorage",{name:r.name,options:r.options})),r}static handleExit({editor:t,mark:r}){const{tr:n}=t.state,a=t.state.selection.$from;if(a.pos===a.end()){const l=a.marks();if(!!!l.find(d=>(d==null?void 0:d.type.name)===r.name))return!1;const c=l.find(d=>(d==null?void 0:d.type.name)===r.name);return c&&n.removeStoredMark(c),n.insertText(" ",a.pos),t.view.dispatch(n),!0}return!1}}function DYt(s){return typeof s=="number"}class RYt{constructor(t){this.find=t.find,this.handler=t.handler}}const OYt=(s,t,r)=>{if(qTe(t))return[...s.matchAll(t)];const n=t(s,r);return n?n.map(a=>{const i=[a.text];return i.index=a.index,i.input=s,i.data=a.data,a.replaceWith&&(a.text.includes(a.replaceWith)||console.warn('[tiptap warn]: "pasteRuleMatch.replaceWith" must be part of "pasteRuleMatch.text".'),i.push(a.replaceWith)),i}):[]};function FYt(s){const{editor:t,state:r,from:n,to:a,rule:i,pasteEvent:l,dropEvent:o}=s,{commands:c,chain:d,can:h}=new uxe({editor:t,state:r}),m=[];return r.doc.nodesBetween(n,a,(x,y)=>{if(!x.isTextblock||x.type.spec.code)return;const _=Math.max(n,y),b=Math.min(a,y+x.content.size),j=x.textBetween(_-y,b-y,void 0,"");OYt(j,i.find,l).forEach(T=>{if(T.index===void 0)return;const E=_+T.index+1,A=E+T[0].length,D={from:r.tr.mapping.map(E),to:r.tr.mapping.map(A)},R=i.handler({state:r,range:D,match:T,commands:c,chain:d,can:h,pasteEvent:l,dropEvent:o});m.push(R)})}),m.every(x=>x!==null)}let tq=null;const BYt=s=>{var t;const r=new ClipboardEvent("paste",{clipboardData:new DataTransfer});return(t=r.clipboardData)===null||t===void 0||t.setData("text/html",s),r};function zYt(s){const{editor:t,rules:r}=s;let n=null,a=!1,i=!1,l=typeof ClipboardEvent<"u"?new ClipboardEvent("paste"):null,o;try{o=typeof DragEvent<"u"?new DragEvent("drop"):null}catch{o=null}const c=({state:h,from:m,to:p,rule:x,pasteEvt:y})=>{const _=h.tr,b=dxe({state:h,transaction:_});if(!(!FYt({editor:t,state:b,from:Math.max(m-1,0),to:p.b-1,rule:x,pasteEvent:y,dropEvent:o})||!_.steps.length)){try{o=typeof DragEvent<"u"?new DragEvent("drop"):null}catch{o=null}return l=typeof ClipboardEvent<"u"?new ClipboardEvent("paste"):null,_}};return r.map(h=>new jm({view(m){const p=y=>{var _;n=!((_=m.dom.parentElement)===null||_===void 0)&&_.contains(y.target)?m.dom.parentElement:null,n&&(tq=t)},x=()=>{tq&&(tq=null)};return window.addEventListener("dragstart",p),window.addEventListener("dragend",x),{destroy(){window.removeEventListener("dragstart",p),window.removeEventListener("dragend",x)}}},props:{handleDOMEvents:{drop:(m,p)=>{if(i=n===m.dom.parentElement,o=p,!i){const x=tq;x!=null&&x.isEditable&&setTimeout(()=>{const y=x.state.selection;y&&x.commands.deleteRange({from:y.from,to:y.to})},10)}return!1},paste:(m,p)=>{var x;const y=(x=p.clipboardData)===null||x===void 0?void 0:x.getData("text/html");return l=p,a=!!(y!=null&&y.includes("data-pm-slice")),!1}}},appendTransaction:(m,p,x)=>{const y=m[0],_=y.getMeta("uiEvent")==="paste"&&!a,b=y.getMeta("uiEvent")==="drop"&&!i,j=y.getMeta("applyPasteRules"),k=!!j;if(!_&&!b&&!k)return;if(k){let{text:A}=j;typeof A=="string"?A=A:A=UTe(An.from(A),x.schema);const{from:D}=j,R=D+A.length,z=BYt(A);return c({rule:h,state:x,from:D,to:{b:R},pasteEvt:z})}const T=p.doc.content.findDiffStart(x.doc.content),E=p.doc.content.findDiffEnd(x.doc.content);if(!(!DYt(T)||!E||T===E.b))return c({rule:h,state:x,from:T,to:E,pasteEvt:l})}}))}function $Yt(s){const t=s.filter((r,n)=>s.indexOf(r)!==n);return Array.from(new Set(t))}class hI{constructor(t,r){this.splittableMarks=[],this.editor=r,this.extensions=hI.resolve(t),this.schema=AYt(this.extensions,r),this.setupExtensions()}static resolve(t){const r=hI.sort(hI.flatten(t)),n=$Yt(r.map(a=>a.name));return n.length&&console.warn(`[tiptap warn]: Duplicate extension names found: [${n.map(a=>`'${a}'`).join(", ")}]. This can lead to issues.`),r}static flatten(t){return t.map(r=>{const n={name:r.name,options:r.options,storage:r.storage},a=si(r,"addExtensions",n);return a?[r,...this.flatten(a())]:r}).flat(10)}static sort(t){return t.sort((n,a)=>{const i=si(n,"priority")||100,l=si(a,"priority")||100;return i>l?-1:i{const n={name:r.name,options:r.options,storage:r.storage,editor:this.editor,type:Zbe(r.name,this.schema)},a=si(r,"addCommands",n);return a?{...t,...a()}:t},{})}get plugins(){const{editor:t}=this,r=hI.sort([...this.extensions].reverse()),n=[],a=[],i=r.map(l=>{const o={name:l.name,options:l.options,storage:l.storage,editor:t,type:Zbe(l.name,this.schema)},c=[],d=si(l,"addKeyboardShortcuts",o);let h={};if(l.type==="mark"&&si(l,"exitable",o)&&(h.ArrowRight=()=>M1.handleExit({editor:t,mark:l})),d){const _=Object.fromEntries(Object.entries(d()).map(([b,j])=>[b,()=>j({editor:t})]));h={...h,..._}}const m=eYt(h);c.push(m);const p=si(l,"addInputRules",o);mBe(l,t.options.enableInputRules)&&p&&n.push(...p());const x=si(l,"addPasteRules",o);mBe(l,t.options.enablePasteRules)&&x&&a.push(...x());const y=si(l,"addProseMirrorPlugins",o);if(y){const _=y();c.push(..._)}return c}).flat();return[PYt({editor:t,rules:n}),...zYt({editor:t,rules:a}),...i]}get attributes(){return yct(this.extensions)}get nodeViews(){const{editor:t}=this,{nodeExtensions:r}=hxe(this.extensions);return Object.fromEntries(r.filter(n=>!!si(n,"addNodeView")).map(n=>{const a=this.attributes.filter(c=>c.type===n.name),i={name:n.name,options:n.options,storage:n.storage,editor:t,type:of(n.name,this.schema)},l=si(n,"addNodeView",i);if(!l)return[];const o=(c,d,h,m,p)=>{const x=ike(c,a);return l()({node:c,view:d,getPos:h,decorations:m,innerDecorations:p,editor:t,extension:n,HTMLAttributes:x})};return[n.name,o]}))}setupExtensions(){this.extensions.forEach(t=>{var r;this.editor.extensionStorage[t.name]=t.storage;const n={name:t.name,options:t.options,storage:t.storage,editor:this.editor,type:Zbe(t.name,this.schema)};t.type==="mark"&&(!((r=Fo(si(t,"keepOnSplit",n)))!==null&&r!==void 0)||r)&&this.splittableMarks.push(t.name);const a=si(t,"onBeforeCreate",n),i=si(t,"onCreate",n),l=si(t,"onUpdate",n),o=si(t,"onSelectionUpdate",n),c=si(t,"onTransaction",n),d=si(t,"onFocus",n),h=si(t,"onBlur",n),m=si(t,"onDestroy",n);a&&this.editor.on("beforeCreate",a),i&&this.editor.on("create",i),l&&this.editor.on("update",l),o&&this.editor.on("selectionUpdate",o),c&&this.editor.on("transaction",c),d&&this.editor.on("focus",d),h&&this.editor.on("blur",h),m&&this.editor.on("destroy",m)})}}class Kf{constructor(t={}){this.type="extension",this.name="extension",this.parent=null,this.child=null,this.config={name:this.name,defaultOptions:{}},this.config={...this.config,...t},this.name=this.config.name,t.defaultOptions&&Object.keys(t.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=Fo(si(this,"addOptions",{name:this.name}))),this.storage=Fo(si(this,"addStorage",{name:this.name,options:this.options}))||{}}static create(t={}){return new Kf(t)}configure(t={}){const r=this.extend({...this.config,addOptions:()=>fxe(this.options,t)});return r.name=this.name,r.parent=this.parent,r}extend(t={}){const r=new Kf({...this.config,...t});return r.parent=this,this.child=r,r.name=t.name?t.name:r.parent.name,t.defaultOptions&&Object.keys(t.defaultOptions).length>0&&console.warn(`[tiptap warn]: BREAKING CHANGE: "defaultOptions" is deprecated. Please use "addOptions" instead. Found in extension: "${r.name}".`),r.options=Fo(si(r,"addOptions",{name:r.name})),r.storage=Fo(si(r,"addStorage",{name:r.name,options:r.options})),r}}function bct(s,t,r){const{from:n,to:a}=t,{blockSeparator:i=` `,textSerializers:l={}}=r||{};let o="";return s.nodesBetween(n,a,(c,d,h,m)=>{var p;c.isBlock&&d>n&&(o+=i);const x=l==null?void 0:l[c.type.name];if(x)return h&&(o+=x({node:c,pos:d,parent:h,index:m,range:t})),!1;c.isText&&(o+=(p=c==null?void 0:c.text)===null||p===void 0?void 0:p.slice(Math.max(n,d)-d,a-d))}),o}function _ct(s){return Object.fromEntries(Object.entries(s.nodes).filter(([,t])=>t.spec.toText).map(([t,r])=>[t,r.spec.toText]))}const UYt=Kf.create({name:"clipboardTextSerializer",addOptions(){return{blockSeparator:void 0}},addProseMirrorPlugins(){return[new jm({key:new Ep("clipboardTextSerializer"),props:{clipboardTextSerializer:()=>{const{editor:s}=this,{state:t,schema:r}=s,{doc:n,selection:a}=t,{ranges:i}=a,l=Math.min(...i.map(h=>h.$from.pos)),o=Math.max(...i.map(h=>h.$to.pos)),c=_ct(r);return bct(n,{from:l,to:o},{...this.options.blockSeparator!==void 0?{blockSeparator:this.options.blockSeparator}:{},textSerializers:c})}}})]}}),qYt=()=>({editor:s,view:t})=>(requestAnimationFrame(()=>{var r;s.isDestroyed||(t.dom.blur(),(r=window==null?void 0:window.getSelection())===null||r===void 0||r.removeAllRanges())}),!0),VYt=(s=!1)=>({commands:t})=>t.setContent("",s),HYt=()=>({state:s,tr:t,dispatch:r})=>{const{selection:n}=t,{ranges:a}=n;return r&&a.forEach(({$from:i,$to:l})=>{s.doc.nodesBetween(i.pos,l.pos,(o,c)=>{if(o.type.isText)return;const{doc:d,mapping:h}=t,m=d.resolve(h.map(c)),p=d.resolve(h.map(c+o.nodeSize)),x=m.blockRange(p);if(!x)return;const y=b8(x);if(o.type.isTextblock){const{defaultType:_}=m.parent.contentMatchAt(m.index());t.setNodeMarkup(x.start,_)}(y||y===0)&&t.lift(x,y)})}),!0},GYt=s=>t=>s(t),WYt=()=>({state:s,dispatch:t})=>mYt(s,t),KYt=(s,t)=>({editor:r,tr:n})=>{const{state:a}=r,i=a.doc.slice(s.from,s.to);n.deleteRange(s.from,s.to);const l=n.mapping.map(t);return n.insert(l,i.content),n.setSelection(new Ri(n.doc.resolve(Math.max(l-1,0)))),!0},YYt=()=>({tr:s,dispatch:t})=>{const{selection:r}=s,n=r.$anchor.node();if(n.content.size>0)return!1;const a=s.selection.$anchor;for(let i=a.depth;i>0;i-=1)if(a.node(i).type===n.type){if(t){const o=a.before(i),c=a.after(i);s.delete(o,c).scrollIntoView()}return!0}return!1},ZYt=s=>({tr:t,state:r,dispatch:n})=>{const a=of(s,r.schema),i=t.selection.$anchor;for(let l=i.depth;l>0;l-=1)if(i.node(l).type===a){if(n){const c=i.before(l),d=i.after(l);t.delete(c,d).scrollIntoView()}return!0}return!1},XYt=s=>({tr:t,dispatch:r})=>{const{from:n,to:a}=s;return r&&t.delete(n,a),!0},QYt=()=>({state:s,dispatch:t})=>tYt(s,t),JYt=()=>({commands:s})=>s.keyboardShortcut("Enter"),eZt=()=>({state:s,dispatch:t})=>hYt(s,t);function pme(s,t,r={strict:!0}){const n=Object.keys(t);return n.length?n.every(a=>r.strict?t[a]===s[a]:qTe(t[a])?t[a].test(s[a]):t[a]===s[a]):!0}function wct(s,t,r={}){return s.find(n=>n.type===t&&pme(Object.fromEntries(Object.keys(r).map(a=>[a,n.attrs[a]])),r))}function fBe(s,t,r={}){return!!wct(s,t,r)}function VTe(s,t,r){var n;if(!s||!t)return;let a=s.parent.childAfter(s.parentOffset);if((!a.node||!a.node.marks.some(h=>h.type===t))&&(a=s.parent.childBefore(s.parentOffset)),!a.node||!a.node.marks.some(h=>h.type===t)||(r=r||((n=a.node.marks[0])===null||n===void 0?void 0:n.attrs),!wct([...a.node.marks],t,r)))return;let l=a.index,o=s.start()+a.offset,c=l+1,d=o+a.node.nodeSize;for(;l>0&&fBe([...s.parent.child(l-1).marks],t,r);)l-=1,o-=s.parent.child(l).nodeSize;for(;c({tr:r,state:n,dispatch:a})=>{const i=WS(s,n.schema),{doc:l,selection:o}=r,{$from:c,from:d,to:h}=o;if(a){const m=VTe(c,i,t);if(m&&m.from<=d&&m.to>=h){const p=Ri.create(l,m.from,m.to);r.setSelection(p)}}return!0},sZt=s=>t=>{const r=typeof s=="function"?s(t):s;for(let n=0;n({editor:r,view:n,tr:a,dispatch:i})=>{t={scrollIntoView:!0,...t};const l=()=>{(gme()||pBe())&&n.dom.focus(),requestAnimationFrame(()=>{r.isDestroyed||(n.focus(),rZt()&&!gme()&&!pBe()&&n.dom.focus({preventScroll:!0}))})};if(n.hasFocus()&&s===null||s===!1)return!0;if(i&&s===null&&!jct(r.state.selection))return l(),!0;const o=Nct(a.doc,s)||r.state.selection,c=r.state.selection.eq(o);return i&&(c||a.setSelection(o),c&&a.storedMarks&&a.setStoredMarks(a.storedMarks),l()),!0},aZt=(s,t)=>r=>s.every((n,a)=>t(n,{...r,index:a})),iZt=(s,t)=>({tr:r,commands:n})=>n.insertContentAt({from:r.selection.from,to:r.selection.to},s,t),kct=s=>{const t=s.childNodes;for(let r=t.length-1;r>=0;r-=1){const n=t[r];n.nodeType===3&&n.nodeValue&&/^(\n\s\s|\n)$/.test(n.nodeValue)?s.removeChild(n):n.nodeType===1&&kct(n)}return s};function sq(s){const t=`${s}`,r=new window.DOMParser().parseFromString(t,"text/html").body;return kct(r)}function N9(s,t,r){if(s instanceof rS||s instanceof An)return s;r={slice:!0,parseOptions:{},...r};const n=typeof s=="object"&&s!==null,a=typeof s=="string";if(n)try{if(Array.isArray(s)&&s.length>0)return An.fromArray(s.map(o=>t.nodeFromJSON(o)));const l=t.nodeFromJSON(s);return r.errorOnInvalidContent&&l.check(),l}catch(i){if(r.errorOnInvalidContent)throw new Error("[tiptap error]: Invalid JSON content",{cause:i});return console.warn("[tiptap warn]: Invalid content.","Passed value:",s,"Error:",i),N9("",t,r)}if(a){if(r.errorOnInvalidContent){let l=!1,o="";const c=new hlt({topNode:t.spec.topNode,marks:t.spec.marks,nodes:t.spec.nodes.append({__tiptap__private__unknown__catch__all__node:{content:"inline*",group:"block",parseDOM:[{tag:"*",getAttrs:d=>(l=!0,o=typeof d=="string"?d:d.outerHTML,null)}]}})});if(r.slice?n7.fromSchema(c).parseSlice(sq(s),r.parseOptions):n7.fromSchema(c).parse(sq(s),r.parseOptions),r.errorOnInvalidContent&&l)throw new Error("[tiptap error]: Invalid HTML content",{cause:new Error(`Invalid element found: ${o}`)})}const i=n7.fromSchema(t);return r.slice?i.parseSlice(sq(s),r.parseOptions).content:i.parse(sq(s),r.parseOptions)}return N9("",t,r)}function oZt(s,t,r){const n=s.steps.length-1;if(n{l===0&&(l=h)}),s.setSelection(Hi.near(s.doc.resolve(l),r))}const lZt=s=>!("type"in s),cZt=(s,t,r)=>({tr:n,dispatch:a,editor:i})=>{var l;if(a){r={parseOptions:i.options.parseOptions,updateSelection:!0,applyInputRules:!1,applyPasteRules:!1,...r};let o;const c=b=>{i.emit("contentError",{editor:i,error:b,disableCollaboration:()=>{i.storage.collaboration&&(i.storage.collaboration.isDisabled=!0)}})},d={preserveWhitespace:"full",...r.parseOptions};if(!r.errorOnInvalidContent&&!i.options.enableContentCheck&&i.options.emitContentError)try{N9(t,i.schema,{parseOptions:d,errorOnInvalidContent:!0})}catch(b){c(b)}try{o=N9(t,i.schema,{parseOptions:d,errorOnInvalidContent:(l=r.errorOnInvalidContent)!==null&&l!==void 0?l:i.options.enableContentCheck})}catch(b){return c(b),!1}let{from:h,to:m}=typeof s=="number"?{from:s,to:s}:{from:s.from,to:s.to},p=!0,x=!0;if((lZt(o)?o:[o]).forEach(b=>{b.check(),p=p?b.isText&&b.marks.length===0:!1,x=x?b.isBlock:!1}),h===m&&x){const{parent:b}=n.doc.resolve(h);b.isTextblock&&!b.type.spec.code&&!b.childCount&&(h-=1,m+=1)}let _;if(p){if(Array.isArray(t))_=t.map(b=>b.text||"").join("");else if(t instanceof An){let b="";t.forEach(j=>{j.text&&(b+=j.text)}),_=b}else typeof t=="object"&&t&&t.text?_=t.text:_=t;n.insertText(_,h,m)}else _=o,n.replaceWith(h,m,_);r.updateSelection&&oZt(n,n.steps.length-1,-1),r.applyInputRules&&n.setMeta("applyInputRules",{from:h,text:_}),r.applyPasteRules&&n.setMeta("applyPasteRules",{from:h,text:_})}return!0},dZt=()=>({state:s,dispatch:t})=>lYt(s,t),uZt=()=>({state:s,dispatch:t})=>cYt(s,t),hZt=()=>({state:s,dispatch:t})=>sYt(s,t),mZt=()=>({state:s,dispatch:t})=>iYt(s,t),fZt=()=>({state:s,dispatch:t,tr:r})=>{try{const n=nxe(s.doc,s.selection.$from.pos,-1);return n==null?!1:(r.join(n,2),t&&t(r),!0)}catch{return!1}},pZt=()=>({state:s,dispatch:t,tr:r})=>{try{const n=nxe(s.doc,s.selection.$from.pos,1);return n==null?!1:(r.join(n,2),t&&t(r),!0)}catch{return!1}},gZt=()=>({state:s,dispatch:t})=>rYt(s,t),xZt=()=>({state:s,dispatch:t})=>nYt(s,t);function Sct(){return typeof navigator<"u"?/Mac/.test(navigator.platform):!1}function yZt(s){const t=s.split(/-(?!$)/);let r=t[t.length-1];r==="Space"&&(r=" ");let n,a,i,l;for(let o=0;o({editor:t,view:r,tr:n,dispatch:a})=>{const i=yZt(s).split(/-(?!$)/),l=i.find(d=>!["Alt","Ctrl","Meta","Shift"].includes(d)),o=new KeyboardEvent("keydown",{key:l==="Space"?" ":l,altKey:i.includes("Alt"),ctrlKey:i.includes("Ctrl"),metaKey:i.includes("Meta"),shiftKey:i.includes("Shift"),bubbles:!0,cancelable:!0}),c=t.captureTransaction(()=>{r.someProp("handleKeyDown",d=>d(r,o))});return c==null||c.steps.forEach(d=>{const h=d.map(n.mapping);h&&a&&n.maybeStep(h)}),!0};function k9(s,t,r={}){const{from:n,to:a,empty:i}=s.selection,l=t?of(t,s.schema):null,o=[];s.doc.nodesBetween(n,a,(m,p)=>{if(m.isText)return;const x=Math.max(n,p),y=Math.min(a,p+m.nodeSize);o.push({node:m,from:x,to:y})});const c=a-n,d=o.filter(m=>l?l.name===m.node.type.name:!0).filter(m=>pme(m.node.attrs,r,{strict:!1}));return i?!!d.length:d.reduce((m,p)=>m+p.to-p.from,0)>=c}const bZt=(s,t={})=>({state:r,dispatch:n})=>{const a=of(s,r.schema);return k9(r,a,t)?dYt(r,n):!1},_Zt=()=>({state:s,dispatch:t})=>fYt(s,t),wZt=s=>({state:t,dispatch:r})=>{const n=of(s,t.schema);return jYt(n)(t,r)},jZt=()=>({state:s,dispatch:t})=>uYt(s,t);function pxe(s,t){return t.nodes[s]?"node":t.marks[s]?"mark":null}function gBe(s,t){const r=typeof t=="string"?[t]:t;return Object.keys(s).reduce((n,a)=>(r.includes(a)||(n[a]=s[a]),n),{})}const NZt=(s,t)=>({tr:r,state:n,dispatch:a})=>{let i=null,l=null;const o=pxe(typeof s=="string"?s:s.name,n.schema);return o?(o==="node"&&(i=of(s,n.schema)),o==="mark"&&(l=WS(s,n.schema)),a&&r.selection.ranges.forEach(c=>{n.doc.nodesBetween(c.$from.pos,c.$to.pos,(d,h)=>{i&&i===d.type&&r.setNodeMarkup(h,void 0,gBe(d.attrs,t)),l&&d.marks.length&&d.marks.forEach(m=>{l===m.type&&r.addMark(h,h+d.nodeSize,l.create(gBe(m.attrs,t)))})})}),!0):!1},kZt=()=>({tr:s,dispatch:t})=>(t&&s.scrollIntoView(),!0),SZt=()=>({tr:s,dispatch:t})=>{if(t){const r=new Ky(s.doc);s.setSelection(r)}return!0},CZt=()=>({state:s,dispatch:t})=>aYt(s,t),TZt=()=>({state:s,dispatch:t})=>oYt(s,t),EZt=()=>({state:s,dispatch:t})=>pYt(s,t),AZt=()=>({state:s,dispatch:t})=>yYt(s,t),MZt=()=>({state:s,dispatch:t})=>xYt(s,t);function oke(s,t,r={},n={}){return N9(s,t,{slice:!1,parseOptions:r,errorOnInvalidContent:n.errorOnInvalidContent})}const IZt=(s,t=!1,r={},n={})=>({editor:a,tr:i,dispatch:l,commands:o})=>{var c,d;const{doc:h}=i;if(r.preserveWhitespace!=="full"){const m=oke(s,a.schema,r,{errorOnInvalidContent:(c=n.errorOnInvalidContent)!==null&&c!==void 0?c:a.options.enableContentCheck});return l&&i.replaceWith(0,h.content.size,m).setMeta("preventUpdate",!t),!0}return l&&i.setMeta("preventUpdate",!t),o.insertContentAt({from:0,to:h.content.size},s,{parseOptions:r,errorOnInvalidContent:(d=n.errorOnInvalidContent)!==null&&d!==void 0?d:a.options.enableContentCheck})};function Cct(s,t){const r=WS(t,s.schema),{from:n,to:a,empty:i}=s.selection,l=[];i?(s.storedMarks&&l.push(...s.storedMarks),l.push(...s.selection.$head.marks())):s.doc.nodesBetween(n,a,c=>{l.push(...c.marks)});const o=l.find(c=>c.type.name===r.name);return o?{...o.attrs}:{}}function PZt(s,t){const r=new TTe(s);return t.forEach(n=>{n.steps.forEach(a=>{r.step(a)})}),r}function LZt(s){for(let t=0;t{r(a)&&n.push({node:a,pos:i})}),n}function Tct(s,t){for(let r=s.depth;r>0;r-=1){const n=s.node(r);if(t(n))return{pos:r>0?s.before(r):0,start:s.start(r),depth:r,node:n}}}function HTe(s){return t=>Tct(t.$from,s)}function RZt(s,t){const r={from:0,to:s.content.size};return bct(s,r,t)}function OZt(s,t){const r=of(t,s.schema),{from:n,to:a}=s.selection,i=[];s.doc.nodesBetween(n,a,o=>{i.push(o)});const l=i.reverse().find(o=>o.type.name===r.name);return l?{...l.attrs}:{}}function Ect(s,t){const r=pxe(typeof t=="string"?t:t.name,s.schema);return r==="node"?OZt(s,t):r==="mark"?Cct(s,t):{}}function FZt(s,t=JSON.stringify){const r={};return s.filter(n=>{const a=t(n);return Object.prototype.hasOwnProperty.call(r,a)?!1:r[a]=!0})}function BZt(s){const t=FZt(s);return t.length===1?t:t.filter((r,n)=>!t.filter((i,l)=>l!==n).some(i=>r.oldRange.from>=i.oldRange.from&&r.oldRange.to<=i.oldRange.to&&r.newRange.from>=i.newRange.from&&r.newRange.to<=i.newRange.to))}function zZt(s){const{mapping:t,steps:r}=s,n=[];return t.maps.forEach((a,i)=>{const l=[];if(a.ranges.length)a.forEach((o,c)=>{l.push({from:o,to:c})});else{const{from:o,to:c}=r[i];if(o===void 0||c===void 0)return;l.push({from:o,to:c})}l.forEach(({from:o,to:c})=>{const d=t.slice(i).map(o,-1),h=t.slice(i).map(c),m=t.invert().map(d,-1),p=t.invert().map(h);n.push({oldRange:{from:m,to:p},newRange:{from:d,to:h}})})}),BZt(n)}function GTe(s,t,r){const n=[];return s===t?r.resolve(s).marks().forEach(a=>{const i=r.resolve(s),l=VTe(i,a.type);l&&n.push({mark:a,...l})}):r.nodesBetween(s,t,(a,i)=>{!a||(a==null?void 0:a.nodeSize)===void 0||n.push(...a.marks.map(l=>({from:i,to:i+a.nodeSize,mark:l})))}),n}function Sue(s,t,r){return Object.fromEntries(Object.entries(r).filter(([n])=>{const a=s.find(i=>i.type===t&&i.name===n);return a?a.attribute.keepOnSplit:!1}))}function lke(s,t,r={}){const{empty:n,ranges:a}=s.selection,i=t?WS(t,s.schema):null;if(n)return!!(s.storedMarks||s.selection.$from.marks()).filter(m=>i?i.name===m.type.name:!0).find(m=>pme(m.attrs,r,{strict:!1}));let l=0;const o=[];if(a.forEach(({$from:m,$to:p})=>{const x=m.pos,y=p.pos;s.doc.nodesBetween(x,y,(_,b)=>{if(!_.isText&&!_.marks.length)return;const j=Math.max(x,b),k=Math.min(y,b+_.nodeSize),T=k-j;l+=T,o.push(..._.marks.map(E=>({mark:E,from:j,to:k})))})}),l===0)return!1;const c=o.filter(m=>i?i.name===m.mark.type.name:!0).filter(m=>pme(m.mark.attrs,r,{strict:!1})).reduce((m,p)=>m+p.to-p.from,0),d=o.filter(m=>i?m.mark.type!==i&&m.mark.type.excludes(i):!0).reduce((m,p)=>m+p.to-p.from,0);return(c>0?c+d:c)>=l}function $Zt(s,t,r={}){if(!t)return k9(s,null,r)||lke(s,null,r);const n=pxe(t,s.schema);return n==="node"?k9(s,t,r):n==="mark"?lke(s,t,r):!1}function xBe(s,t){const{nodeExtensions:r}=hxe(t),n=r.find(l=>l.name===s);if(!n)return!1;const a={name:n.name,options:n.options,storage:n.storage},i=Fo(si(n,"group",a));return typeof i!="string"?!1:i.split(" ").includes("list")}function WTe(s,{checkChildren:t=!0,ignoreWhitespace:r=!1}={}){var n;if(r){if(s.type.name==="hardBreak")return!0;if(s.isText)return/^\s*$/m.test((n=s.text)!==null&&n!==void 0?n:"")}if(s.isText)return!s.text;if(s.isAtom||s.isLeaf)return!1;if(s.content.childCount===0)return!0;if(t){let a=!0;return s.content.forEach(i=>{a!==!1&&(WTe(i,{ignoreWhitespace:r,checkChildren:t})||(a=!1))}),a}return!1}function UZt(s){return s instanceof Si}function qZt(s,t,r){var n;const{selection:a}=t;let i=null;if(jct(a)&&(i=a.$cursor),i){const o=(n=s.storedMarks)!==null&&n!==void 0?n:i.marks();return!!r.isInSet(o)||!o.some(c=>c.type.excludes(r))}const{ranges:l}=a;return l.some(({$from:o,$to:c})=>{let d=o.depth===0?s.doc.inlineContent&&s.doc.type.allowsMarkType(r):!1;return s.doc.nodesBetween(o.pos,c.pos,(h,m,p)=>{if(d)return!1;if(h.isInline){const x=!p||p.type.allowsMarkType(r),y=!!r.isInSet(h.marks)||!h.marks.some(_=>_.type.excludes(r));d=x&&y}return!d}),d})}const VZt=(s,t={})=>({tr:r,state:n,dispatch:a})=>{const{selection:i}=r,{empty:l,ranges:o}=i,c=WS(s,n.schema);if(a)if(l){const d=Cct(n,c);r.addStoredMark(c.create({...d,...t}))}else o.forEach(d=>{const h=d.$from.pos,m=d.$to.pos;n.doc.nodesBetween(h,m,(p,x)=>{const y=Math.max(x,h),_=Math.min(x+p.nodeSize,m);p.marks.find(j=>j.type===c)?p.marks.forEach(j=>{c===j.type&&r.addMark(y,_,c.create({...j.attrs,...t}))}):r.addMark(y,_,c.create(t))})});return qZt(n,r,c)},HZt=(s,t)=>({tr:r})=>(r.setMeta(s,t),!0),GZt=(s,t={})=>({state:r,dispatch:n,chain:a})=>{const i=of(s,r.schema);let l;return r.selection.$anchor.sameParent(r.selection.$head)&&(l=r.selection.$anchor.parent.attrs),i.isTextblock?a().command(({commands:o})=>dBe(i,{...l,...t})(r)?!0:o.clearNodes()).command(({state:o})=>dBe(i,{...l,...t})(o,n)).run():(console.warn('[tiptap warn]: Currently "setNode()" only supports text block nodes.'),!1)},WZt=s=>({tr:t,dispatch:r})=>{if(r){const{doc:n}=t,a=UT(s,0,n.content.size),i=Si.create(n,a);t.setSelection(i)}return!0},KZt=s=>({tr:t,dispatch:r})=>{if(r){const{doc:n}=t,{from:a,to:i}=typeof s=="number"?{from:s,to:s}:s,l=Ri.atStart(n).from,o=Ri.atEnd(n).to,c=UT(a,l,o),d=UT(i,l,o),h=Ri.create(n,c,d);t.setSelection(h)}return!0},YZt=s=>({state:t,dispatch:r})=>{const n=of(s,t.schema);return SYt(n)(t,r)};function yBe(s,t){const r=s.storedMarks||s.selection.$to.parentOffset&&s.selection.$from.marks();if(r){const n=r.filter(a=>t==null?void 0:t.includes(a.type.name));s.tr.ensureMarks(n)}}const ZZt=({keepMarks:s=!0}={})=>({tr:t,state:r,dispatch:n,editor:a})=>{const{selection:i,doc:l}=t,{$from:o,$to:c}=i,d=a.extensionManager.attributes,h=Sue(d,o.node().type.name,o.node().attrs);if(i instanceof Si&&i.node.isBlock)return!o.parentOffset||!cP(l,o.pos)?!1:(n&&(s&&yBe(r,a.extensionManager.splittableMarks),t.split(o.pos).scrollIntoView()),!0);if(!o.parent.isBlock)return!1;const m=c.parentOffset===c.parent.content.size,p=o.depth===0?void 0:LZt(o.node(-1).contentMatchAt(o.indexAfter(-1)));let x=m&&p?[{type:p,attrs:h}]:void 0,y=cP(t.doc,t.mapping.map(o.pos),1,x);if(!x&&!y&&cP(t.doc,t.mapping.map(o.pos),1,p?[{type:p}]:void 0)&&(y=!0,x=p?[{type:p,attrs:h}]:void 0),n){if(y&&(i instanceof Ri&&t.deleteSelection(),t.split(t.mapping.map(o.pos),1,x),p&&!m&&!o.parentOffset&&o.parent.type!==p)){const _=t.mapping.map(o.before()),b=t.doc.resolve(_);o.node(-1).canReplaceWith(b.index(),b.index()+1,p)&&t.setNodeMarkup(t.mapping.map(o.before()),p)}s&&yBe(r,a.extensionManager.splittableMarks),t.scrollIntoView()}return y},XZt=(s,t={})=>({tr:r,state:n,dispatch:a,editor:i})=>{var l;const o=of(s,n.schema),{$from:c,$to:d}=n.selection,h=n.selection.node;if(h&&h.isBlock||c.depth<2||!c.sameParent(d))return!1;const m=c.node(-1);if(m.type!==o)return!1;const p=i.extensionManager.attributes;if(c.parent.content.size===0&&c.node(-1).childCount===c.indexAfter(-1)){if(c.depth===2||c.node(-3).type!==o||c.index(-2)!==c.node(-2).childCount-1)return!1;if(a){let j=An.empty;const k=c.index(-1)?1:c.index(-2)?2:3;for(let z=c.depth-k;z>=c.depth-3;z-=1)j=An.from(c.node(z).copy(j));const T=c.indexAfter(-1){if(R>-1)return!1;z.isTextblock&&z.content.size===0&&(R=O+1)}),R>-1&&r.setSelection(Ri.near(r.doc.resolve(R))),r.scrollIntoView()}return!0}const x=d.pos===c.end()?m.contentMatchAt(0).defaultType:null,y={...Sue(p,m.type.name,m.attrs),...t},_={...Sue(p,c.node().type.name,c.node().attrs),...t};r.delete(c.pos,d.pos);const b=x?[{type:o,attrs:y},{type:x,attrs:_}]:[{type:o,attrs:y}];if(!cP(r.doc,c.pos,2))return!1;if(a){const{selection:j,storedMarks:k}=n,{splittableMarks:T}=i.extensionManager,E=k||j.$to.parentOffset&&j.$from.marks();if(r.split(c.pos,2,b).scrollIntoView(),!E||!a)return!0;const A=E.filter(D=>T.includes(D.type.name));r.ensureMarks(A)}return!0},Xbe=(s,t)=>{const r=HTe(l=>l.type===t)(s.selection);if(!r)return!0;const n=s.doc.resolve(Math.max(0,r.pos-1)).before(r.depth);if(n===void 0)return!0;const a=s.doc.nodeAt(n);return r.node.type===(a==null?void 0:a.type)&&HS(s.doc,r.pos)&&s.join(r.pos),!0},Qbe=(s,t)=>{const r=HTe(l=>l.type===t)(s.selection);if(!r)return!0;const n=s.doc.resolve(r.start).after(r.depth);if(n===void 0)return!0;const a=s.doc.nodeAt(n);return r.node.type===(a==null?void 0:a.type)&&HS(s.doc,n)&&s.join(n),!0},QZt=(s,t,r,n={})=>({editor:a,tr:i,state:l,dispatch:o,chain:c,commands:d,can:h})=>{const{extensions:m,splittableMarks:p}=a.extensionManager,x=of(s,l.schema),y=of(t,l.schema),{selection:_,storedMarks:b}=l,{$from:j,$to:k}=_,T=j.blockRange(k),E=b||_.$to.parentOffset&&_.$from.marks();if(!T)return!1;const A=HTe(D=>xBe(D.type.name,m))(_);if(T.depth>=1&&A&&T.depth-A.depth<=1){if(A.node.type===x)return d.liftListItem(y);if(xBe(A.node.type.name,m)&&x.validContent(A.node.content)&&o)return c().command(()=>(i.setNodeMarkup(A.pos,x),!0)).command(()=>Xbe(i,x)).command(()=>Qbe(i,x)).run()}return!r||!E||!o?c().command(()=>h().wrapInList(x,n)?!0:d.clearNodes()).wrapInList(x,n).command(()=>Xbe(i,x)).command(()=>Qbe(i,x)).run():c().command(()=>{const D=h().wrapInList(x,n),R=E.filter(z=>p.includes(z.type.name));return i.ensureMarks(R),D?!0:d.clearNodes()}).wrapInList(x,n).command(()=>Xbe(i,x)).command(()=>Qbe(i,x)).run()},JZt=(s,t={},r={})=>({state:n,commands:a})=>{const{extendEmptyMarkRange:i=!1}=r,l=WS(s,n.schema);return lke(n,l,t)?a.unsetMark(l,{extendEmptyMarkRange:i}):a.setMark(l,t)},eXt=(s,t,r={})=>({state:n,commands:a})=>{const i=of(s,n.schema),l=of(t,n.schema),o=k9(n,i,r);let c;return n.selection.$anchor.sameParent(n.selection.$head)&&(c=n.selection.$anchor.parent.attrs),o?a.setNode(l,c):a.setNode(i,{...c,...r})},tXt=(s,t={})=>({state:r,commands:n})=>{const a=of(s,r.schema);return k9(r,a,t)?n.lift(a):n.wrapIn(a,t)},sXt=()=>({state:s,dispatch:t})=>{const r=s.plugins;for(let n=0;n=0;c-=1)l.step(o.steps[c].invert(o.docs[c]));if(i.text){const c=l.doc.resolve(i.from).marks();l.replaceWith(i.from,i.to,s.schema.text(i.text,c))}else l.delete(i.from,i.to)}return!0}}return!1},rXt=()=>({tr:s,dispatch:t})=>{const{selection:r}=s,{empty:n,ranges:a}=r;return n||t&&a.forEach(i=>{s.removeMark(i.$from.pos,i.$to.pos)}),!0},nXt=(s,t={})=>({tr:r,state:n,dispatch:a})=>{var i;const{extendEmptyMarkRange:l=!1}=t,{selection:o}=r,c=WS(s,n.schema),{$from:d,empty:h,ranges:m}=o;if(!a)return!0;if(h&&l){let{from:p,to:x}=o;const y=(i=d.marks().find(b=>b.type===c))===null||i===void 0?void 0:i.attrs,_=VTe(d,c,y);_&&(p=_.from,x=_.to),r.removeMark(p,x,c)}else m.forEach(p=>{r.removeMark(p.$from.pos,p.$to.pos,c)});return r.removeStoredMark(c),!0},aXt=(s,t={})=>({tr:r,state:n,dispatch:a})=>{let i=null,l=null;const o=pxe(typeof s=="string"?s:s.name,n.schema);return o?(o==="node"&&(i=of(s,n.schema)),o==="mark"&&(l=WS(s,n.schema)),a&&r.selection.ranges.forEach(c=>{const d=c.$from.pos,h=c.$to.pos;let m,p,x,y;r.selection.empty?n.doc.nodesBetween(d,h,(_,b)=>{i&&i===_.type&&(x=Math.max(b,d),y=Math.min(b+_.nodeSize,h),m=b,p=_)}):n.doc.nodesBetween(d,h,(_,b)=>{b=d&&b<=h&&(i&&i===_.type&&r.setNodeMarkup(b,void 0,{..._.attrs,...t}),l&&_.marks.length&&_.marks.forEach(j=>{if(l===j.type){const k=Math.max(b,d),T=Math.min(b+_.nodeSize,h);r.addMark(k,T,l.create({...j.attrs,...t}))}}))}),p&&(m!==void 0&&r.setNodeMarkup(m,void 0,{...p.attrs,...t}),l&&p.marks.length&&p.marks.forEach(_=>{l===_.type&&r.addMark(x,y,l.create({..._.attrs,...t}))}))}),!0):!1},iXt=(s,t={})=>({state:r,dispatch:n})=>{const a=of(s,r.schema);return vYt(a,t)(r,n)},oXt=(s,t={})=>({state:r,dispatch:n})=>{const a=of(s,r.schema);return bYt(a,t)(r,n)};var lXt=Object.freeze({__proto__:null,blur:qYt,clearContent:VYt,clearNodes:HYt,command:GYt,createParagraphNear:WYt,cut:KYt,deleteCurrentNode:YYt,deleteNode:ZYt,deleteRange:XYt,deleteSelection:QYt,enter:JYt,exitCode:eZt,extendMarkRange:tZt,first:sZt,focus:nZt,forEach:aZt,insertContent:iZt,insertContentAt:cZt,joinBackward:hZt,joinDown:uZt,joinForward:mZt,joinItemBackward:fZt,joinItemForward:pZt,joinTextblockBackward:gZt,joinTextblockForward:xZt,joinUp:dZt,keyboardShortcut:vZt,lift:bZt,liftEmptyBlock:_Zt,liftListItem:wZt,newlineInCode:jZt,resetAttributes:NZt,scrollIntoView:kZt,selectAll:SZt,selectNodeBackward:CZt,selectNodeForward:TZt,selectParentNode:EZt,selectTextblockEnd:AZt,selectTextblockStart:MZt,setContent:IZt,setMark:VZt,setMeta:HZt,setNode:GZt,setNodeSelection:WZt,setTextSelection:KZt,sinkListItem:YZt,splitBlock:ZZt,splitListItem:XZt,toggleList:QZt,toggleMark:JZt,toggleNode:eXt,toggleWrap:tXt,undoInputRule:sXt,unsetAllMarks:rXt,unsetMark:nXt,updateAttributes:aXt,wrapIn:iXt,wrapInList:oXt});const cXt=Kf.create({name:"commands",addCommands(){return{...lXt}}}),dXt=Kf.create({name:"drop",addProseMirrorPlugins(){return[new jm({key:new Ep("tiptapDrop"),props:{handleDrop:(s,t,r,n)=>{this.editor.emit("drop",{editor:this.editor,event:t,slice:r,moved:n})}}})]}}),uXt=Kf.create({name:"editable",addProseMirrorPlugins(){return[new jm({key:new Ep("editable"),props:{editable:()=>this.editor.options.editable}})]}}),hXt=new Ep("focusEvents"),mXt=Kf.create({name:"focusEvents",addProseMirrorPlugins(){const{editor:s}=this;return[new jm({key:hXt,props:{handleDOMEvents:{focus:(t,r)=>{s.isFocused=!0;const n=s.state.tr.setMeta("focus",{event:r}).setMeta("addToHistory",!1);return t.dispatch(n),!1},blur:(t,r)=>{s.isFocused=!1;const n=s.state.tr.setMeta("blur",{event:r}).setMeta("addToHistory",!1);return t.dispatch(n),!1}}}})]}}),fXt=Kf.create({name:"keymap",addKeyboardShortcuts(){const s=()=>this.editor.commands.first(({commands:l})=>[()=>l.undoInputRule(),()=>l.command(({tr:o})=>{const{selection:c,doc:d}=o,{empty:h,$anchor:m}=c,{pos:p,parent:x}=m,y=m.parent.isTextblock&&p>0?o.doc.resolve(p-1):m,_=y.parent.type.spec.isolating,b=m.pos-m.parentOffset,j=_&&y.parent.childCount===1?b===m.pos:Hi.atStart(d).from===p;return!h||!x.type.isTextblock||x.textContent.length||!j||j&&m.parent.type.name==="paragraph"?!1:l.clearNodes()}),()=>l.deleteSelection(),()=>l.joinBackward(),()=>l.selectNodeBackward()]),t=()=>this.editor.commands.first(({commands:l})=>[()=>l.deleteSelection(),()=>l.deleteCurrentNode(),()=>l.joinForward(),()=>l.selectNodeForward()]),n={Enter:()=>this.editor.commands.first(({commands:l})=>[()=>l.newlineInCode(),()=>l.createParagraphNear(),()=>l.liftEmptyBlock(),()=>l.splitBlock()]),"Mod-Enter":()=>this.editor.commands.exitCode(),Backspace:s,"Mod-Backspace":s,"Shift-Backspace":s,Delete:t,"Mod-Delete":t,"Mod-a":()=>this.editor.commands.selectAll()},a={...n},i={...n,"Ctrl-h":s,"Alt-Backspace":s,"Ctrl-d":t,"Ctrl-Alt-Backspace":t,"Alt-Delete":t,"Alt-d":t,"Ctrl-a":()=>this.editor.commands.selectTextblockStart(),"Ctrl-e":()=>this.editor.commands.selectTextblockEnd()};return gme()||Sct()?i:a},addProseMirrorPlugins(){return[new jm({key:new Ep("clearDocument"),appendTransaction:(s,t,r)=>{if(s.some(_=>_.getMeta("composition")))return;const n=s.some(_=>_.docChanged)&&!t.doc.eq(r.doc),a=s.some(_=>_.getMeta("preventClearDocument"));if(!n||a)return;const{empty:i,from:l,to:o}=t.selection,c=Hi.atStart(t.doc).from,d=Hi.atEnd(t.doc).to;if(i||!(l===c&&o===d)||!WTe(r.doc))return;const p=r.tr,x=dxe({state:r,transaction:p}),{commands:y}=new uxe({editor:this.editor,state:x});if(y.clearNodes(),!!p.steps.length)return p}})]}}),pXt=Kf.create({name:"paste",addProseMirrorPlugins(){return[new jm({key:new Ep("tiptapPaste"),props:{handlePaste:(s,t,r)=>{this.editor.emit("paste",{editor:this.editor,event:t,slice:r})}}})]}}),gXt=Kf.create({name:"tabindex",addProseMirrorPlugins(){return[new jm({key:new Ep("tabindex"),props:{attributes:()=>this.editor.isEditable?{tabindex:"0"}:{}}})]}});class AT{get name(){return this.node.type.name}constructor(t,r,n=!1,a=null){this.currentNode=null,this.actualDepth=null,this.isBlock=n,this.resolvedPos=t,this.editor=r,this.currentNode=a}get node(){return this.currentNode||this.resolvedPos.node()}get element(){return this.editor.view.domAtPos(this.pos).node}get depth(){var t;return(t=this.actualDepth)!==null&&t!==void 0?t:this.resolvedPos.depth}get pos(){return this.resolvedPos.pos}get content(){return this.node.content}set content(t){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},t)}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 t=this.resolvedPos.start(this.resolvedPos.depth-1),r=this.resolvedPos.doc.resolve(t);return new AT(r,this.editor)}get before(){let t=this.resolvedPos.doc.resolve(this.from-(this.isBlock?1:2));return t.depth!==this.depth&&(t=this.resolvedPos.doc.resolve(this.from-3)),new AT(t,this.editor)}get after(){let t=this.resolvedPos.doc.resolve(this.to+(this.isBlock?2:1));return t.depth!==this.depth&&(t=this.resolvedPos.doc.resolve(this.to+3)),new AT(t,this.editor)}get children(){const t=[];return this.node.content.forEach((r,n)=>{const a=r.isBlock&&!r.isTextblock,i=r.isAtom&&!r.isText,l=this.pos+n+(i?0:1);if(l<0||l>this.resolvedPos.doc.nodeSize-2)return;const o=this.resolvedPos.doc.resolve(l);if(!a&&o.depth<=this.depth)return;const c=new AT(o,this.editor,a,a?r:null);a&&(c.actualDepth=this.depth+1),t.push(new AT(o,this.editor,a,a?r:null))}),t}get firstChild(){return this.children[0]||null}get lastChild(){const t=this.children;return t[t.length-1]||null}closest(t,r={}){let n=null,a=this.parent;for(;a&&!n;){if(a.node.type.name===t)if(Object.keys(r).length>0){const i=a.node.attrs,l=Object.keys(r);for(let o=0;o{n&&a.length>0||(l.node.type.name===t&&i.every(c=>r[c]===l.node.attrs[c])&&a.push(l),!(n&&a.length>0)&&(a=a.concat(l.querySelectorAll(t,r,n))))}),a}setAttribute(t){const{tr:r}=this.editor.state;r.setNodeMarkup(this.from,void 0,{...this.node.attrs,...t}),this.editor.view.dispatch(r)}}const xXt=`.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 yXt(s,t,r){const n=document.querySelector("style[data-tiptap-style]");if(n!==null)return n;const a=document.createElement("style");return t&&a.setAttribute("nonce",t),a.setAttribute("data-tiptap-style",""),a.innerHTML=s,document.getElementsByTagName("head")[0].appendChild(a),a}class vXt extends CYt{constructor(t={}){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(t),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:a})=>this.options.onDrop(r,n,a)),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=yXt(xXt,this.options.injectNonce))}setOptions(t={}){this.options={...this.options,...t},!(!this.view||!this.state||this.isDestroyed)&&(this.options.editorProps&&this.view.setProps(this.options.editorProps),this.view.updateState(this.state))}setEditable(t,r=!0){this.setOptions({editable:t}),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(t,r){const n=vct(r)?r(t,[...this.state.plugins]):[...this.state.plugins,t],a=this.state.reconfigure({plugins:n});return this.view.updateState(a),a}unregisterPlugin(t){if(this.isDestroyed)return;const r=this.state.plugins;let n=r;if([].concat(t).forEach(i=>{const l=typeof i=="string"?`${i}$`:i.key;n=n.filter(o=>!o.key.startsWith(l))}),r.length===n.length)return;const a=this.state.reconfigure({plugins:n});return this.view.updateState(a),a}createExtensionManager(){var t,r;const a=[...this.options.enableCoreExtensions?[uXt,UYt.configure({blockSeparator:(r=(t=this.options.coreExtensionOptions)===null||t===void 0?void 0:t.clipboardTextSerializer)===null||r===void 0?void 0:r.blockSeparator}),cXt,mXt,fXt,gXt,dXt,pXt].filter(i=>typeof this.options.enableCoreExtensions=="object"?this.options.enableCoreExtensions[i.name]!==!1:!0):[],...this.options.extensions].filter(i=>["extension","node","mark"].includes(i==null?void 0:i.type));this.extensionManager=new hI(a,this)}createCommandManager(){this.commandManager=new uxe({editor:this})}createSchema(){this.schema=this.extensionManager.schema}createView(){var t;let r;try{r=oke(this.options.content,this.schema,this.options.parseOptions,{errorOnInvalidContent:this.options.enableContentCheck})}catch(l){if(!(l instanceof Error)||!["[tiptap error]: Invalid JSON content","[tiptap error]: Invalid HTML content"].includes(l.message))throw l;this.emit("contentError",{editor:this,error:l,disableCollaboration:()=>{this.storage.collaboration&&(this.storage.collaboration.isDisabled=!0),this.options.extensions=this.options.extensions.filter(o=>o.name!=="collaboration"),this.createExtensionManager()}}),r=oke(this.options.content,this.schema,this.options.parseOptions,{errorOnInvalidContent:!1})}const n=Nct(r,this.options.autofocus);this.view=new uct(this.options.element,{...this.options.editorProps,attributes:{role:"textbox",...(t=this.options.editorProps)===null||t===void 0?void 0:t.attributes},dispatchTransaction:this.dispatchTransaction.bind(this),state:uI.create({doc:r,selection:n||void 0})});const a=this.state.reconfigure({plugins:this.extensionManager.plugins});this.view.updateState(a),this.createNodeViews(),this.prependClass();const i=this.view.dom;i.editor=this}createNodeViews(){this.view.isDestroyed||this.view.setProps({nodeViews:this.extensionManager.nodeViews})}prependClass(){this.view.dom.className=`tiptap ${this.view.dom.className}`}captureTransaction(t){this.isCapturingTransaction=!0,t(),this.isCapturingTransaction=!1;const r=this.capturedTransaction;return this.capturedTransaction=null,r}dispatchTransaction(t){if(this.view.isDestroyed)return;if(this.isCapturingTransaction){if(!this.capturedTransaction){this.capturedTransaction=t;return}t.steps.forEach(l=>{var o;return(o=this.capturedTransaction)===null||o===void 0?void 0:o.step(l)});return}const r=this.state.apply(t),n=!this.state.selection.eq(r.selection);this.emit("beforeTransaction",{editor:this,transaction:t,nextState:r}),this.view.updateState(r),this.emit("transaction",{editor:this,transaction:t}),n&&this.emit("selectionUpdate",{editor:this,transaction:t});const a=t.getMeta("focus"),i=t.getMeta("blur");a&&this.emit("focus",{editor:this,event:a.event,transaction:t}),i&&this.emit("blur",{editor:this,event:i.event,transaction:t}),!(!t.docChanged||t.getMeta("preventUpdate"))&&this.emit("update",{editor:this,transaction:t})}getAttributes(t){return Ect(this.state,t)}isActive(t,r){const n=typeof t=="string"?t:null,a=typeof t=="string"?r:t;return $Zt(this.state,n,a)}getJSON(){return this.state.doc.toJSON()}getHTML(){return UTe(this.state.doc.content,this.schema)}getText(t){const{blockSeparator:r=` `,textSerializers:n={}}=t||{};return RZt(this.state.doc,{blockSeparator:r,textSerializers:{..._ct(this.schema),...n}})}get isEmpty(){return WTe(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 t=this.view.dom;t&&t.editor&&delete t.editor,this.view.destroy()}this.removeAllListeners()}get isDestroyed(){var t;return!(!((t=this.view)===null||t===void 0)&&t.docView)}$node(t,r){var n;return((n=this.$doc)===null||n===void 0?void 0:n.querySelector(t,r))||null}$nodes(t,r){var n;return((n=this.$doc)===null||n===void 0?void 0:n.querySelectorAll(t,r))||null}$pos(t){const r=this.state.doc.resolve(t);return new AT(r,this)}get $doc(){return this.$pos(0)}}function dL(s){return new mxe({find:s.find,handler:({state:t,range:r,match:n})=>{const a=Fo(s.getAttributes,void 0,n);if(a===!1||a===null)return null;const{tr:i}=t,l=n[n.length-1],o=n[0];if(l){const c=o.search(/\S/),d=r.from+o.indexOf(l),h=d+l.length;if(GTe(r.from,r.to,t.doc).filter(x=>x.mark.type.excluded.find(_=>_===s.type&&_!==x.mark.type)).filter(x=>x.to>d).length)return null;hr.from&&i.delete(r.from+c,d);const p=r.from+c+l.length;i.addMark(r.from+c,p,s.type.create(a||{})),i.removeStoredMark(s.type)}}})}function Act(s){return new mxe({find:s.find,handler:({state:t,range:r,match:n})=>{const a=Fo(s.getAttributes,void 0,n)||{},{tr:i}=t,l=r.from;let o=r.to;const c=s.type.create(a);if(n[1]){const d=n[0].lastIndexOf(n[1]);let h=l+d;h>o?h=o:o=h+n[1].length;const m=n[0][n[0].length-1];i.insertText(m,l+n[0].length-1),i.replaceWith(h,o,c)}else if(n[0]){const d=s.type.isInline?l:l-1;i.insert(d,s.type.create(a)).delete(i.mapping.map(l),i.mapping.map(o))}i.scrollIntoView()}})}function cke(s){return new mxe({find:s.find,handler:({state:t,range:r,match:n})=>{const a=t.doc.resolve(r.from),i=Fo(s.getAttributes,void 0,n)||{};if(!a.node(-1).canReplaceWith(a.index(-1),a.indexAfter(-1),s.type))return null;t.tr.delete(r.from,r.to).setBlockType(r.from,r.from,s.type,i)}})}function S9(s){return new mxe({find:s.find,handler:({state:t,range:r,match:n,chain:a})=>{const i=Fo(s.getAttributes,void 0,n)||{},l=t.tr.delete(r.from,r.to),c=l.doc.resolve(r.from).blockRange(),d=c&&CTe(c,s.type,i);if(!d)return null;if(l.wrap(c,d),s.keepMarks&&s.editor){const{selection:m,storedMarks:p}=t,{splittableMarks:x}=s.editor.extensionManager,y=p||m.$to.parentOffset&&m.$from.marks();if(y){const _=y.filter(b=>x.includes(b.type.name));l.ensureMarks(_)}}if(s.keepAttributes){const m=s.type.name==="bulletList"||s.type.name==="orderedList"?"listItem":"taskList";a().updateAttributes(m,i).run()}const h=l.doc.resolve(r.from-1).nodeBefore;h&&h.type===s.type&&HS(l.doc,r.from-1)&&(!s.joinPredicate||s.joinPredicate(n,h))&&l.join(r.from-1)}})}let Ap=class dke{constructor(t={}){this.type="node",this.name="node",this.parent=null,this.child=null,this.config={name:this.name,defaultOptions:{}},this.config={...this.config,...t},this.name=this.config.name,t.defaultOptions&&Object.keys(t.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=Fo(si(this,"addOptions",{name:this.name}))),this.storage=Fo(si(this,"addStorage",{name:this.name,options:this.options}))||{}}static create(t={}){return new dke(t)}configure(t={}){const r=this.extend({...this.config,addOptions:()=>fxe(this.options,t)});return r.name=this.name,r.parent=this.parent,r}extend(t={}){const r=new dke(t);return r.parent=this,this.child=r,r.name=t.name?t.name:r.parent.name,t.defaultOptions&&Object.keys(t.defaultOptions).length>0&&console.warn(`[tiptap warn]: BREAKING CHANGE: "defaultOptions" is deprecated. Please use "addOptions" instead. Found in extension: "${r.name}".`),r.options=Fo(si(r,"addOptions",{name:r.name})),r.storage=Fo(si(r,"addStorage",{name:r.name,options:r.options})),r}};function _A(s){return new RYt({find:s.find,handler:({state:t,range:r,match:n,pasteEvent:a})=>{const i=Fo(s.getAttributes,void 0,n,a);if(i===!1||i===null)return null;const{tr:l}=t,o=n[n.length-1],c=n[0];let d=r.to;if(o){const h=c.search(/\S/),m=r.from+c.indexOf(o),p=m+o.length;if(GTe(r.from,r.to,t.doc).filter(y=>y.mark.type.excluded.find(b=>b===s.type&&b!==y.mark.type)).filter(y=>y.to>m).length)return null;pr.from&&l.delete(r.from+h,m),d=r.from+h+o.length,l.addMark(r.from+h,d,s.type.create(i||{})),l.removeStoredMark(s.type)}}})}function bXt(s,t){const{selection:r}=s,{$from:n}=r;if(r instanceof Si){const i=n.index();return n.parent.canReplaceWith(i,i+1,t)}let a=n.depth;for(;a>=0;){const i=n.index(a);if(n.node(a).contentMatchAt(i).matchType(t))return!0;a-=1}return!1}function _Xt(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var Mct={exports:{}},Jbe={};/** * @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 vBe;function wXt(){if(vBe)return Jbe;vBe=1;var s=Nt;function t(m,p){return m===p&&(m!==0||1/m===1/p)||m!==m&&p!==p}var r=typeof Object.is=="function"?Object.is:t,n=s.useState,a=s.useEffect,i=s.useLayoutEffect,l=s.useDebugValue;function o(m,p){var x=p(),y=n({inst:{value:x,getSnapshot:p}}),_=y[0].inst,b=y[1];return i(function(){_.value=x,_.getSnapshot=p,c(_)&&b({inst:_})},[m,x,p]),a(function(){return c(_)&&b({inst:_}),m(function(){c(_)&&b({inst:_})})},[m]),l(x),x}function c(m){var p=m.getSnapshot;m=m.value;try{var x=p();return!r(m,x)}catch{return!0}}function d(m,p){return p()}var h=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?d:o;return Jbe.useSyncExternalStore=s.useSyncExternalStore!==void 0?s.useSyncExternalStore:h,Jbe}Mct.exports=wXt();var KTe=Mct.exports;const jXt=(...s)=>t=>{s.forEach(r=>{typeof r=="function"?r(t):r&&(r.current=t)})},NXt=({contentComponent:s})=>{const t=KTe.useSyncExternalStore(s.subscribe,s.getSnapshot,s.getServerSnapshot);return Nt.createElement(Nt.Fragment,null,Object.values(t))};function kXt(){const s=new Set;let t={};return{subscribe(r){return s.add(r),()=>{s.delete(r)}},getSnapshot(){return t},getServerSnapshot(){return t},setRenderer(r,n){t={...t,[r]:f3e.createPortal(n.reactElement,n.element,r)},s.forEach(a=>a())},removeRenderer(r){const n={...t};delete n[r],t=n,s.forEach(a=>a())}}}class SXt extends Nt.Component{constructor(t){var r;super(t),this.editorContentRef=Nt.createRef(),this.initialized=!1,this.state={hasContentComponentInitialized:!!(!((r=t.editor)===null||r===void 0)&&r.contentComponent)}}componentDidMount(){this.init()}componentDidUpdate(){this.init()}init(){const t=this.props.editor;if(t&&!t.isDestroyed&&t.options.element){if(t.contentComponent)return;const r=this.editorContentRef.current;r.append(...t.options.element.childNodes),t.setOptions({element:r}),t.contentComponent=kXt(),this.state.hasContentComponentInitialized||(this.unsubscribeToContentComponent=t.contentComponent.subscribe(()=>{this.setState(n=>n.hasContentComponentInitialized?n:{hasContentComponentInitialized:!0}),this.unsubscribeToContentComponent&&this.unsubscribeToContentComponent()})),t.createNodeViews(),this.initialized=!0}}componentWillUnmount(){const t=this.props.editor;if(!t||(this.initialized=!1,t.isDestroyed||t.view.setProps({nodeViews:{}}),this.unsubscribeToContentComponent&&this.unsubscribeToContentComponent(),t.contentComponent=null,!t.options.element.firstChild))return;const r=document.createElement("div");r.append(...t.options.element.childNodes),t.setOptions({element:r})}render(){const{editor:t,innerRef:r,...n}=this.props;return Nt.createElement(Nt.Fragment,null,Nt.createElement("div",{ref:jXt(r,this.editorContentRef),...n}),(t==null?void 0:t.contentComponent)&&Nt.createElement(NXt,{contentComponent:t.contentComponent}))}}const CXt=S.forwardRef((s,t)=>{const r=Nt.useMemo(()=>Math.floor(Math.random()*4294967295).toString(),[s.editor]);return Nt.createElement(SXt,{key:r,innerRef:t,...s})}),YTe=Nt.memo(CXt);var TXt=function s(t,r){if(t===r)return!0;if(t&&r&&typeof t=="object"&&typeof r=="object"){if(t.constructor!==r.constructor)return!1;var n,a,i;if(Array.isArray(t)){if(n=t.length,n!=r.length)return!1;for(a=n;a--!==0;)if(!s(t[a],r[a]))return!1;return!0}if(t instanceof Map&&r instanceof Map){if(t.size!==r.size)return!1;for(a of t.entries())if(!r.has(a[0]))return!1;for(a of t.entries())if(!s(a[1],r.get(a[0])))return!1;return!0}if(t instanceof Set&&r instanceof Set){if(t.size!==r.size)return!1;for(a of t.entries())if(!r.has(a[0]))return!1;return!0}if(ArrayBuffer.isView(t)&&ArrayBuffer.isView(r)){if(n=t.length,n!=r.length)return!1;for(a=n;a--!==0;)if(t[a]!==r[a])return!1;return!0}if(t.constructor===RegExp)return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();if(i=Object.keys(t),n=i.length,n!==Object.keys(r).length)return!1;for(a=n;a--!==0;)if(!Object.prototype.hasOwnProperty.call(r,i[a]))return!1;for(a=n;a--!==0;){var l=i[a];if(!(l==="_owner"&&t.$$typeof)&&!s(t[l],r[l]))return!1}return!0}return t!==t&&r!==r},EXt=_Xt(TXt),Ict={exports:{}},e_e={};/** * @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 bBe;function AXt(){if(bBe)return e_e;bBe=1;var s=Nt,t=KTe;function r(d,h){return d===h&&(d!==0||1/d===1/h)||d!==d&&h!==h}var n=typeof Object.is=="function"?Object.is:r,a=t.useSyncExternalStore,i=s.useRef,l=s.useEffect,o=s.useMemo,c=s.useDebugValue;return e_e.useSyncExternalStoreWithSelector=function(d,h,m,p,x){var y=i(null);if(y.current===null){var _={hasValue:!1,value:null};y.current=_}else _=y.current;y=o(function(){function j(D){if(!k){if(k=!0,T=D,D=p(D),x!==void 0&&_.hasValue){var R=_.value;if(x(R,D))return E=R}return E=D}if(R=E,n(T,D))return R;var z=p(D);return x!==void 0&&x(R,z)?R:(T=D,E=z)}var k=!1,T,E,A=m===void 0?null:m;return[function(){return j(h())},A===null?void 0:function(){return j(A())}]},[h,m,p,x]);var b=a(d,y[0],y[1]);return l(function(){_.hasValue=!0,_.value=b},[b]),c(b),b},e_e}Ict.exports=AXt();var MXt=Ict.exports;const IXt=typeof window<"u"?S.useLayoutEffect:S.useEffect;class PXt{constructor(t){this.transactionNumber=0,this.lastTransactionNumber=0,this.subscribers=new Set,this.editor=t,this.lastSnapshot={editor:t,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(t){return this.subscribers.add(t),()=>{this.subscribers.delete(t)}}watch(t){if(this.editor=t,this.editor){const r=()=>{this.transactionNumber+=1,this.subscribers.forEach(a=>a())},n=this.editor;return n.on("transaction",r),()=>{n.off("transaction",r)}}}}function LXt(s){var t;const[r]=S.useState(()=>new PXt(s.editor)),n=MXt.useSyncExternalStoreWithSelector(r.subscribe,r.getSnapshot,r.getServerSnapshot,s.selector,(t=s.equalityFn)!==null&&t!==void 0?t:EXt);return IXt(()=>r.watch(s.editor),[s.editor,r]),S.useDebugValue(n),n}const DXt=!1,uke=typeof window>"u",RXt=uke||!!(typeof window<"u"&&window.next);class ZTe{constructor(t){this.editor=null,this.subscriptions=new Set,this.isComponentMounted=!1,this.previousDeps=null,this.instanceId="",this.options=t,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(t){this.editor=t,this.instanceId=Math.random().toString(36).slice(2,9),this.subscriptions.forEach(r=>r())}getInitialEditor(){if(this.options.current.immediatelyRender===void 0)return uke||RXt?null:this.createEditor();if(this.options.current.immediatelyRender&&uke&&DXt)throw new Error("Tiptap Error: SSR has been detected, and `immediatelyRender` has been set to `true` this is an unsupported configuration that may result in errors, explicitly set `immediatelyRender` to `false` to avoid hydration mismatches.");return this.options.current.immediatelyRender?this.createEditor():null}createEditor(){const t={...this.options.current,onBeforeCreate:(...n)=>{var a,i;return(i=(a=this.options.current).onBeforeCreate)===null||i===void 0?void 0:i.call(a,...n)},onBlur:(...n)=>{var a,i;return(i=(a=this.options.current).onBlur)===null||i===void 0?void 0:i.call(a,...n)},onCreate:(...n)=>{var a,i;return(i=(a=this.options.current).onCreate)===null||i===void 0?void 0:i.call(a,...n)},onDestroy:(...n)=>{var a,i;return(i=(a=this.options.current).onDestroy)===null||i===void 0?void 0:i.call(a,...n)},onFocus:(...n)=>{var a,i;return(i=(a=this.options.current).onFocus)===null||i===void 0?void 0:i.call(a,...n)},onSelectionUpdate:(...n)=>{var a,i;return(i=(a=this.options.current).onSelectionUpdate)===null||i===void 0?void 0:i.call(a,...n)},onTransaction:(...n)=>{var a,i;return(i=(a=this.options.current).onTransaction)===null||i===void 0?void 0:i.call(a,...n)},onUpdate:(...n)=>{var a,i;return(i=(a=this.options.current).onUpdate)===null||i===void 0?void 0:i.call(a,...n)},onContentError:(...n)=>{var a,i;return(i=(a=this.options.current).onContentError)===null||i===void 0?void 0:i.call(a,...n)},onDrop:(...n)=>{var a,i;return(i=(a=this.options.current).onDrop)===null||i===void 0?void 0:i.call(a,...n)},onPaste:(...n)=>{var a,i;return(i=(a=this.options.current).onPaste)===null||i===void 0?void 0:i.call(a,...n)}};return new vXt(t)}getEditor(){return this.editor}getServerSnapshot(){return null}subscribe(t){return this.subscriptions.add(t),()=>{this.subscriptions.delete(t)}}static compareOptions(t,r){return Object.keys(t).every(n=>["onCreate","onBeforeCreate","onDestroy","onUpdate","onTransaction","onFocus","onBlur","onSelectionUpdate","onContentError","onDrop","onPaste"].includes(n)?!0:n==="extensions"&&t.extensions&&r.extensions?t.extensions.length!==r.extensions.length?!1:t.extensions.every((a,i)=>{var l;return a===((l=r.extensions)===null||l===void 0?void 0:l[i])}):t[n]===r[n])}onRender(t){return()=>(this.isComponentMounted=!0,clearTimeout(this.scheduledDestructionTimeout),this.editor&&!this.editor.isDestroyed&&t.length===0?ZTe.compareOptions(this.options.current,this.editor.options)||this.editor.setOptions({...this.options.current,editable:this.editor.isEditable}):this.refreshEditorInstance(t),()=>{this.isComponentMounted=!1,this.scheduleDestroy()})}refreshEditorInstance(t){if(this.editor&&!this.editor.isDestroyed){if(this.previousDeps===null){this.previousDeps=t;return}if(this.previousDeps.length===t.length&&this.previousDeps.every((n,a)=>n===t[a]))return}this.editor&&!this.editor.isDestroyed&&this.editor.destroy(),this.setEditor(this.createEditor()),this.previousDeps=t}scheduleDestroy(){const t=this.instanceId,r=this.editor;this.scheduledDestructionTimeout=setTimeout(()=>{if(this.isComponentMounted&&this.instanceId===t){r&&r.setOptions(this.options.current);return}r&&!r.isDestroyed&&(r.destroy(),this.instanceId===t&&this.setEditor(null))},1)}}function XTe(s={},t=[]){const r=S.useRef(s);r.current=s;const[n]=S.useState(()=>new ZTe(r)),a=KTe.useSyncExternalStore(n.subscribe,n.getEditor,n.getServerSnapshot);return S.useDebugValue(a),S.useEffect(n.onRender(t)),LXt({editor:a,selector:({transactionNumber:i})=>s.shouldRerenderOnTransaction===!1?null:s.immediatelyRender&&i===0?0:i+1}),a}const OXt=S.createContext({editor:null});OXt.Consumer;const FXt=S.createContext({onDragStart:void 0}),BXt=()=>S.useContext(FXt);Nt.forwardRef((s,t)=>{const{onDragStart:r}=BXt(),n=s.as||"div";return Nt.createElement(n,{...s,ref:t,"data-node-view-wrapper":"",onDragStart:r,style:{whiteSpace:"normal",...s.style}})});const zXt=/^\s*>\s$/,$Xt=Ap.create({name:"blockquote",addOptions(){return{HTMLAttributes:{}}},content:"block+",group:"block",defining:!0,parseHTML(){return[{tag:"blockquote"}]},renderHTML({HTMLAttributes:s}){return["blockquote",Xd(this.options.HTMLAttributes,s),0]},addCommands(){return{setBlockquote:()=>({commands:s})=>s.wrapIn(this.name),toggleBlockquote:()=>({commands:s})=>s.toggleWrap(this.name),unsetBlockquote:()=>({commands:s})=>s.lift(this.name)}},addKeyboardShortcuts(){return{"Mod-Shift-b":()=>this.editor.commands.toggleBlockquote()}},addInputRules(){return[S9({find:zXt,type:this.type})]}}),UXt=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))$/,qXt=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))/g,VXt=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))$/,HXt=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))/g,GXt=M1.create({name:"bold",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"strong"},{tag:"b",getAttrs:s=>s.style.fontWeight!=="normal"&&null},{style:"font-weight=400",clearMark:s=>s.type.name===this.name},{style:"font-weight",getAttrs:s=>/^(bold(er)?|[5-9]\d{2,})$/.test(s)&&null}]},renderHTML({HTMLAttributes:s}){return["strong",Xd(this.options.HTMLAttributes,s),0]},addCommands(){return{setBold:()=>({commands:s})=>s.setMark(this.name),toggleBold:()=>({commands:s})=>s.toggleMark(this.name),unsetBold:()=>({commands:s})=>s.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-b":()=>this.editor.commands.toggleBold(),"Mod-B":()=>this.editor.commands.toggleBold()}},addInputRules(){return[dL({find:UXt,type:this.type}),dL({find:VXt,type:this.type})]},addPasteRules(){return[_A({find:qXt,type:this.type}),_A({find:HXt,type:this.type})]}}),WXt="listItem",_Be="textStyle",wBe=/^\s*([-+*])\s$/,KXt=Ap.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:s}){return["ul",Xd(this.options.HTMLAttributes,s),0]},addCommands(){return{toggleBulletList:()=>({commands:s,chain:t})=>this.options.keepAttributes?t().toggleList(this.name,this.options.itemTypeName,this.options.keepMarks).updateAttributes(WXt,this.editor.getAttributes(_Be)).run():s.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-8":()=>this.editor.commands.toggleBulletList()}},addInputRules(){let s=S9({find:wBe,type:this.type});return(this.options.keepMarks||this.options.keepAttributes)&&(s=S9({find:wBe,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:()=>this.editor.getAttributes(_Be),editor:this.editor})),[s]}}),YXt=/(^|[^`])`([^`]+)`(?!`)/,ZXt=/(^|[^`])`([^`]+)`(?!`)/g,XXt=M1.create({name:"code",addOptions(){return{HTMLAttributes:{}}},excludes:"_",code:!0,exitable:!0,parseHTML(){return[{tag:"code"}]},renderHTML({HTMLAttributes:s}){return["code",Xd(this.options.HTMLAttributes,s),0]},addCommands(){return{setCode:()=>({commands:s})=>s.setMark(this.name),toggleCode:()=>({commands:s})=>s.toggleMark(this.name),unsetCode:()=>({commands:s})=>s.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-e":()=>this.editor.commands.toggleCode()}},addInputRules(){return[dL({find:YXt,type:this.type})]},addPasteRules(){return[_A({find:ZXt,type:this.type})]}}),QXt=/^```([a-z]+)?[\s\n]$/,JXt=/^~~~([a-z]+)?[\s\n]$/,eQt=Ap.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:s=>{var t;const{languageClassPrefix:r}=this.options,i=[...((t=s.firstElementChild)===null||t===void 0?void 0:t.classList)||[]].filter(l=>l.startsWith(r)).map(l=>l.replace(r,""))[0];return i||null},rendered:!1}}},parseHTML(){return[{tag:"pre",preserveWhitespace:"full"}]},renderHTML({node:s,HTMLAttributes:t}){return["pre",Xd(this.options.HTMLAttributes,t),["code",{class:s.attrs.language?this.options.languageClassPrefix+s.attrs.language:null},0]]},addCommands(){return{setCodeBlock:s=>({commands:t})=>t.setNode(this.name,s),toggleCodeBlock:s=>({commands:t})=>t.toggleNode(this.name,"paragraph",s)}},addKeyboardShortcuts(){return{"Mod-Alt-c":()=>this.editor.commands.toggleCodeBlock(),Backspace:()=>{const{empty:s,$anchor:t}=this.editor.state.selection,r=t.pos===1;return!s||t.parent.type.name!==this.name?!1:r||!t.parent.textContent.length?this.editor.commands.clearNodes():!1},Enter:({editor:s})=>{if(!this.options.exitOnTripleEnter)return!1;const{state:t}=s,{selection:r}=t,{$from:n,empty:a}=r;if(!a||n.parent.type!==this.type)return!1;const i=n.parentOffset===n.parent.nodeSize-2,l=n.parent.textContent.endsWith(` `);return!i||!l?!1:s.chain().command(({tr:o})=>(o.delete(n.pos-2,n.pos),!0)).exitCode().run()},ArrowDown:({editor:s})=>{if(!this.options.exitOnArrowDown)return!1;const{state:t}=s,{selection:r,doc:n}=t,{$from:a,empty:i}=r;if(!i||a.parent.type!==this.type||!(a.parentOffset===a.parent.nodeSize-2))return!1;const o=a.after();return o===void 0?!1:n.nodeAt(o)?s.commands.command(({tr:d})=>(d.setSelection(Hi.near(n.resolve(o))),!0)):s.commands.exitCode()}}},addInputRules(){return[cke({find:QXt,type:this.type,getAttributes:s=>({language:s[1]})}),cke({find:JXt,type:this.type,getAttributes:s=>({language:s[1]})})]},addProseMirrorPlugins(){return[new jm({key:new Ep("codeBlockVSCodeHandler"),props:{handlePaste:(s,t)=>{if(!t.clipboardData||this.editor.isActive(this.type.name))return!1;const r=t.clipboardData.getData("text/plain"),n=t.clipboardData.getData("vscode-editor-data"),a=n?JSON.parse(n):void 0,i=a==null?void 0:a.mode;if(!r||!i)return!1;const{tr:l,schema:o}=s.state,c=o.text(r.replace(/\r\n?/g,` `));return l.replaceSelectionWith(this.type.create({language:i},c)),l.selection.$from.parent.type!==this.type&&l.setSelection(Ri.near(l.doc.resolve(Math.max(0,l.selection.from-2)))),l.setMeta("paste",!0),s.dispatch(l),!0}}})]}}),tQt=Ap.create({name:"doc",topNode:!0,content:"block+"});function sQt(s={}){return new jm({view(t){return new rQt(t,s)}})}class rQt{constructor(t,r){var n;this.editorView=t,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(a=>{let i=l=>{this[a](l)};return t.dom.addEventListener(a,i),{name:a,handler:i}})}destroy(){this.handlers.forEach(({name:t,handler:r})=>this.editorView.dom.removeEventListener(t,r))}update(t,r){this.cursorPos!=null&&r.doc!=t.state.doc&&(this.cursorPos>t.state.doc.content.size?this.setCursor(null):this.updateOverlay())}setCursor(t){t!=this.cursorPos&&(this.cursorPos=t,t==null?(this.element.parentNode.removeChild(this.element),this.element=null):this.updateOverlay())}updateOverlay(){let t=this.editorView.state.doc.resolve(this.cursorPos),r=!t.parent.inlineContent,n,a=this.editorView.dom,i=a.getBoundingClientRect(),l=i.width/a.offsetWidth,o=i.height/a.offsetHeight;if(r){let m=t.nodeBefore,p=t.nodeAfter;if(m||p){let x=this.editorView.nodeDOM(this.cursorPos-(m?m.nodeSize:0));if(x){let y=x.getBoundingClientRect(),_=m?y.bottom:y.top;m&&p&&(_=(_+this.editorView.nodeDOM(this.cursorPos).getBoundingClientRect().top)/2);let b=this.width/2*o;n={left:y.left,right:y.right,top:_-b,bottom:_+b}}}}if(!n){let m=this.editorView.coordsAtPos(this.cursorPos),p=this.width/2*l;n={left:m.left-p,right:m.left+p,top:m.top,bottom:m.bottom}}let c=this.editorView.dom.offsetParent;this.element||(this.element=c.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 d,h;if(!c||c==document.body&&getComputedStyle(c).position=="static")d=-pageXOffset,h=-pageYOffset;else{let m=c.getBoundingClientRect(),p=m.width/c.offsetWidth,x=m.height/c.offsetHeight;d=m.left-c.scrollLeft*p,h=m.top-c.scrollTop*x}this.element.style.left=(n.left-d)/l+"px",this.element.style.top=(n.top-h)/o+"px",this.element.style.width=(n.right-n.left)/l+"px",this.element.style.height=(n.bottom-n.top)/o+"px"}scheduleRemoval(t){clearTimeout(this.timeout),this.timeout=setTimeout(()=>this.setCursor(null),t)}dragover(t){if(!this.editorView.editable)return;let r=this.editorView.posAtCoords({left:t.clientX,top:t.clientY}),n=r&&r.inside>=0&&this.editorView.state.doc.nodeAt(r.inside),a=n&&n.type.spec.disableDropCursor,i=typeof a=="function"?a(this.editorView,r,t):a;if(r&&!i){let l=r.pos;if(this.editorView.dragging&&this.editorView.dragging.slice){let o=jlt(this.editorView.state.doc,l,this.editorView.dragging.slice);o!=null&&(l=o)}this.setCursor(l),this.scheduleRemoval(5e3)}}dragend(){this.scheduleRemoval(20)}drop(){this.scheduleRemoval(20)}dragleave(t){this.editorView.dom.contains(t.relatedTarget)||this.setCursor(null)}}const nQt=Kf.create({name:"dropCursor",addOptions(){return{color:"currentColor",width:1,class:void 0}},addProseMirrorPlugins(){return[sQt(this.options)]}});class zu extends Hi{constructor(t){super(t,t)}map(t,r){let n=t.resolve(r.map(this.head));return zu.valid(n)?new zu(n):Hi.near(n)}content(){return ua.empty}eq(t){return t instanceof zu&&t.head==this.head}toJSON(){return{type:"gapcursor",pos:this.head}}static fromJSON(t,r){if(typeof r.pos!="number")throw new RangeError("Invalid input for GapCursor.fromJSON");return new zu(t.resolve(r.pos))}getBookmark(){return new QTe(this.anchor)}static valid(t){let r=t.parent;if(r.inlineContent||!aQt(t)||!iQt(t))return!1;let n=r.type.spec.allowGapCursor;if(n!=null)return n;let a=r.contentMatchAt(t.index()).defaultType;return a&&a.isTextblock}static findGapCursorFrom(t,r,n=!1){e:for(;;){if(!n&&zu.valid(t))return t;let a=t.pos,i=null;for(let l=t.depth;;l--){let o=t.node(l);if(r>0?t.indexAfter(l)0){i=o.child(r>0?t.indexAfter(l):t.index(l)-1);break}else if(l==0)return null;a+=r;let c=t.doc.resolve(a);if(zu.valid(c))return c}for(;;){let l=r>0?i.firstChild:i.lastChild;if(!l){if(i.isAtom&&!i.isText&&!Si.isSelectable(i)){t=t.doc.resolve(a+i.nodeSize*r),n=!1;continue e}break}i=l,a+=r;let o=t.doc.resolve(a);if(zu.valid(o))return o}return null}}}zu.prototype.visible=!1;zu.findFrom=zu.findGapCursorFrom;Hi.jsonID("gapcursor",zu);class QTe{constructor(t){this.pos=t}map(t){return new QTe(t.map(this.pos))}resolve(t){let r=t.resolve(this.pos);return zu.valid(r)?new zu(r):Hi.near(r)}}function Pct(s){return s.isAtom||s.spec.isolating||s.spec.createGapCursor}function aQt(s){for(let t=s.depth;t>=0;t--){let r=s.index(t),n=s.node(t);if(r==0){if(n.type.spec.isolating)return!0;continue}for(let a=n.child(r-1);;a=a.lastChild){if(a.childCount==0&&!a.inlineContent||Pct(a.type))return!0;if(a.inlineContent)return!1}}return!0}function iQt(s){for(let t=s.depth;t>=0;t--){let r=s.indexAfter(t),n=s.node(t);if(r==n.childCount){if(n.type.spec.isolating)return!0;continue}for(let a=n.child(r);;a=a.firstChild){if(a.childCount==0&&!a.inlineContent||Pct(a.type))return!0;if(a.inlineContent)return!1}}return!0}function oQt(){return new jm({props:{decorations:uQt,createSelectionBetween(s,t,r){return t.pos==r.pos&&zu.valid(r)?new zu(r):null},handleClick:cQt,handleKeyDown:lQt,handleDOMEvents:{beforeinput:dQt}}})}const lQt=BTe({ArrowLeft:rq("horiz",-1),ArrowRight:rq("horiz",1),ArrowUp:rq("vert",-1),ArrowDown:rq("vert",1)});function rq(s,t){const r=s=="vert"?t>0?"down":"up":t>0?"right":"left";return function(n,a,i){let l=n.selection,o=t>0?l.$to:l.$from,c=l.empty;if(l instanceof Ri){if(!i.endOfTextblock(r)||o.depth==0)return!1;c=!1,o=n.doc.resolve(t>0?o.after():o.before())}let d=zu.findGapCursorFrom(o,t,c);return d?(a&&a(n.tr.setSelection(new zu(d))),!0):!1}}function cQt(s,t,r){if(!s||!s.editable)return!1;let n=s.state.doc.resolve(t);if(!zu.valid(n))return!1;let a=s.posAtCoords({left:r.clientX,top:r.clientY});return a&&a.inside>-1&&Si.isSelectable(s.state.doc.nodeAt(a.inside))?!1:(s.dispatch(s.state.tr.setSelection(new zu(n))),!0)}function dQt(s,t){if(t.inputType!="insertCompositionText"||!(s.state.selection instanceof zu))return!1;let{$from:r}=s.state.selection,n=r.parent.contentMatchAt(r.index()).findWrapping(s.state.schema.nodes.text);if(!n)return!1;let a=An.empty;for(let l=n.length-1;l>=0;l--)a=An.from(n[l].createAndFill(null,a));let i=s.state.tr.replace(r.pos,r.pos,new ua(a,0,0));return i.setSelection(Ri.near(i.doc.resolve(r.pos+1))),s.dispatch(i),!1}function uQt(s){if(!(s.selection instanceof zu))return null;let t=document.createElement("div");return t.className="ProseMirror-gapcursor",Bu.create(s.doc,[pg.widget(s.selection.head,t,{key:"gapcursor"})])}const hQt=Kf.create({name:"gapCursor",addProseMirrorPlugins(){return[oQt()]},extendNodeSchema(s){var t;const r={name:s.name,options:s.options,storage:s.storage};return{allowGapCursor:(t=Fo(si(s,"allowGapCursor",r)))!==null&&t!==void 0?t:null}}}),mQt=Ap.create({name:"hardBreak",addOptions(){return{keepMarks:!0,HTMLAttributes:{}}},inline:!0,group:"inline",selectable:!1,linebreakReplacement:!0,parseHTML(){return[{tag:"br"}]},renderHTML({HTMLAttributes:s}){return["br",Xd(this.options.HTMLAttributes,s)]},renderText(){return` `},addCommands(){return{setHardBreak:()=>({commands:s,chain:t,state:r,editor:n})=>s.first([()=>s.exitCode(),()=>s.command(()=>{const{selection:a,storedMarks:i}=r;if(a.$from.parent.type.spec.isolating)return!1;const{keepMarks:l}=this.options,{splittableMarks:o}=n.extensionManager,c=i||a.$to.parentOffset&&a.$from.marks();return t().insertContent({type:this.name}).command(({tr:d,dispatch:h})=>{if(h&&c&&l){const m=c.filter(p=>o.includes(p.type.name));d.ensureMarks(m)}return!0}).run()})])}},addKeyboardShortcuts(){return{"Mod-Enter":()=>this.editor.commands.setHardBreak(),"Shift-Enter":()=>this.editor.commands.setHardBreak()}}}),fQt=Ap.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(s=>({tag:`h${s}`,attrs:{level:s}}))},renderHTML({node:s,HTMLAttributes:t}){return[`h${this.options.levels.includes(s.attrs.level)?s.attrs.level:this.options.levels[0]}`,Xd(this.options.HTMLAttributes,t),0]},addCommands(){return{setHeading:s=>({commands:t})=>this.options.levels.includes(s.level)?t.setNode(this.name,s):!1,toggleHeading:s=>({commands:t})=>this.options.levels.includes(s.level)?t.toggleNode(this.name,"paragraph",s):!1}},addKeyboardShortcuts(){return this.options.levels.reduce((s,t)=>({...s,[`Mod-Alt-${t}`]:()=>this.editor.commands.toggleHeading({level:t})}),{})},addInputRules(){return this.options.levels.map(s=>cke({find:new RegExp(`^(#{${Math.min(...this.options.levels)},${s}})\\s$`),type:this.type,getAttributes:{level:s}}))}});var xme=200,nf=function(){};nf.prototype.append=function(t){return t.length?(t=nf.from(t),!this.length&&t||t.length=r?nf.empty:this.sliceInner(Math.max(0,t),Math.min(this.length,r))};nf.prototype.get=function(t){if(!(t<0||t>=this.length))return this.getInner(t)};nf.prototype.forEach=function(t,r,n){r===void 0&&(r=0),n===void 0&&(n=this.length),r<=n?this.forEachInner(t,r,n,0):this.forEachInvertedInner(t,r,n,0)};nf.prototype.map=function(t,r,n){r===void 0&&(r=0),n===void 0&&(n=this.length);var a=[];return this.forEach(function(i,l){return a.push(t(i,l))},r,n),a};nf.from=function(t){return t instanceof nf?t:t&&t.length?new Lct(t):nf.empty};var Lct=function(s){function t(n){s.call(this),this.values=n}s&&(t.__proto__=s),t.prototype=Object.create(s&&s.prototype),t.prototype.constructor=t;var r={length:{configurable:!0},depth:{configurable:!0}};return t.prototype.flatten=function(){return this.values},t.prototype.sliceInner=function(a,i){return a==0&&i==this.length?this:new t(this.values.slice(a,i))},t.prototype.getInner=function(a){return this.values[a]},t.prototype.forEachInner=function(a,i,l,o){for(var c=i;c=l;c--)if(a(this.values[c],o+c)===!1)return!1},t.prototype.leafAppend=function(a){if(this.length+a.length<=xme)return new t(this.values.concat(a.flatten()))},t.prototype.leafPrepend=function(a){if(this.length+a.length<=xme)return new t(a.flatten().concat(this.values))},r.length.get=function(){return this.values.length},r.depth.get=function(){return 0},Object.defineProperties(t.prototype,r),t}(nf);nf.empty=new Lct([]);var pQt=function(s){function t(r,n){s.call(this),this.left=r,this.right=n,this.length=r.length+n.length,this.depth=Math.max(r.depth,n.depth)+1}return s&&(t.__proto__=s),t.prototype=Object.create(s&&s.prototype),t.prototype.constructor=t,t.prototype.flatten=function(){return this.left.flatten().concat(this.right.flatten())},t.prototype.getInner=function(n){return no&&this.right.forEachInner(n,Math.max(a-o,0),Math.min(this.length,i)-o,l+o)===!1)return!1},t.prototype.forEachInvertedInner=function(n,a,i,l){var o=this.left.length;if(a>o&&this.right.forEachInvertedInner(n,a-o,Math.max(i,o)-o,l+o)===!1||i=i?this.right.slice(n-i,a-i):this.left.slice(n,i).append(this.right.slice(0,a-i))},t.prototype.leafAppend=function(n){var a=this.right.leafAppend(n);if(a)return new t(this.left,a)},t.prototype.leafPrepend=function(n){var a=this.left.leafPrepend(n);if(a)return new t(a,this.right)},t.prototype.appendInner=function(n){return this.left.depth>=Math.max(this.right.depth,n.depth)+1?new t(this.left,new t(this.right,n)):new t(this,n)},t}(nf);const gQt=500;class c1{constructor(t,r){this.items=t,this.eventCount=r}popEvent(t,r){if(this.eventCount==0)return null;let n=this.items.length;for(;;n--)if(this.items.get(n-1).selection){--n;break}let a,i;r&&(a=this.remapping(n,this.items.length),i=a.maps.length);let l=t.tr,o,c,d=[],h=[];return this.items.forEach((m,p)=>{if(!m.step){a||(a=this.remapping(n,p+1),i=a.maps.length),i--,h.push(m);return}if(a){h.push(new Fb(m.map));let x=m.step.map(a.slice(i)),y;x&&l.maybeStep(x).doc&&(y=l.mapping.maps[l.mapping.maps.length-1],d.push(new Fb(y,void 0,void 0,d.length+h.length))),i--,y&&a.appendMap(y,i)}else l.maybeStep(m.step);if(m.selection)return o=a?m.selection.map(a.slice(i)):m.selection,c=new c1(this.items.slice(0,n).append(h.reverse().concat(d)),this.eventCount-1),!1},this.items.length,0),{remaining:c,transform:l,selection:o}}addTransform(t,r,n,a){let i=[],l=this.eventCount,o=this.items,c=!a&&o.length?o.get(o.length-1):null;for(let h=0;hyQt&&(o=xQt(o,d),l-=d),new c1(o.append(i),l)}remapping(t,r){let n=new v9;return this.items.forEach((a,i)=>{let l=a.mirrorOffset!=null&&i-a.mirrorOffset>=t?n.maps.length-a.mirrorOffset:void 0;n.appendMap(a.map,l)},t,r),n}addMaps(t){return this.eventCount==0?this:new c1(this.items.append(t.map(r=>new Fb(r))),this.eventCount)}rebased(t,r){if(!this.eventCount)return this;let n=[],a=Math.max(0,this.items.length-r),i=t.mapping,l=t.steps.length,o=this.eventCount;this.items.forEach(p=>{p.selection&&o--},a);let c=r;this.items.forEach(p=>{let x=i.getMirror(--c);if(x==null)return;l=Math.min(l,x);let y=i.maps[x];if(p.step){let _=t.steps[x].invert(t.docs[x]),b=p.selection&&p.selection.map(i.slice(c+1,x));b&&o++,n.push(new Fb(y,_,b))}else n.push(new Fb(y))},a);let d=[];for(let p=r;pgQt&&(m=m.compress(this.items.length-n.length)),m}emptyItemCount(){let t=0;return this.items.forEach(r=>{r.step||t++}),t}compress(t=this.items.length){let r=this.remapping(0,t),n=r.maps.length,a=[],i=0;return this.items.forEach((l,o)=>{if(o>=t)a.push(l),l.selection&&i++;else if(l.step){let c=l.step.map(r.slice(n)),d=c&&c.getMap();if(n--,d&&r.appendMap(d,n),c){let h=l.selection&&l.selection.map(r.slice(n));h&&i++;let m=new Fb(d.invert(),c,h),p,x=a.length-1;(p=a.length&&a[x].merge(m))?a[x]=p:a.push(m)}}else l.map&&n--},this.items.length,0),new c1(nf.from(a.reverse()),i)}}c1.empty=new c1(nf.empty,0);function xQt(s,t){let r;return s.forEach((n,a)=>{if(n.selection&&t--==0)return r=a,!1}),s.slice(r)}class Fb{constructor(t,r,n,a){this.map=t,this.step=r,this.selection=n,this.mirrorOffset=a}merge(t){if(this.step&&t.step&&!t.selection){let r=t.step.merge(this.step);if(r)return new Fb(r.getMap().invert(),r,this.selection)}}}class VN{constructor(t,r,n,a,i){this.done=t,this.undone=r,this.prevRanges=n,this.prevTime=a,this.prevComposition=i}}const yQt=20;function vQt(s,t,r,n){let a=r.getMeta(GE),i;if(a)return a.historyState;r.getMeta(wQt)&&(s=new VN(s.done,s.undone,null,0,-1));let l=r.getMeta("appendedTransaction");if(r.steps.length==0)return s;if(l&&l.getMeta(GE))return l.getMeta(GE).redo?new VN(s.done.addTransform(r,void 0,n,Cue(t)),s.undone,jBe(r.mapping.maps),s.prevTime,s.prevComposition):new VN(s.done,s.undone.addTransform(r,void 0,n,Cue(t)),null,s.prevTime,s.prevComposition);if(r.getMeta("addToHistory")!==!1&&!(l&&l.getMeta("addToHistory")===!1)){let o=r.getMeta("composition"),c=s.prevTime==0||!l&&s.prevComposition!=o&&(s.prevTime<(r.time||0)-n.newGroupDelay||!bQt(r,s.prevRanges)),d=l?t_e(s.prevRanges,r.mapping):jBe(r.mapping.maps);return new VN(s.done.addTransform(r,c?t.selection.getBookmark():void 0,n,Cue(t)),c1.empty,d,r.time,o??s.prevComposition)}else return(i=r.getMeta("rebased"))?new VN(s.done.rebased(r,i),s.undone.rebased(r,i),t_e(s.prevRanges,r.mapping),s.prevTime,s.prevComposition):new VN(s.done.addMaps(r.mapping.maps),s.undone.addMaps(r.mapping.maps),t_e(s.prevRanges,r.mapping),s.prevTime,s.prevComposition)}function bQt(s,t){if(!t)return!1;if(!s.docChanged)return!0;let r=!1;return s.mapping.maps[0].forEach((n,a)=>{for(let i=0;i=t[i]&&(r=!0)}),r}function jBe(s){let t=[];for(let r=s.length-1;r>=0&&t.length==0;r--)s[r].forEach((n,a,i,l)=>t.push(i,l));return t}function t_e(s,t){if(!s)return null;let r=[];for(let n=0;n{let a=GE.getState(r);if(!a||(s?a.undone:a.done).eventCount==0)return!1;if(n){let i=_Qt(a,r,s);i&&n(t?i.scrollIntoView():i)}return!0}}const Rct=Dct(!1,!0),Oct=Dct(!0,!0),NQt=Kf.create({name:"history",addOptions(){return{depth:100,newGroupDelay:500}},addCommands(){return{undo:()=>({state:s,dispatch:t})=>Rct(s,t),redo:()=>({state:s,dispatch:t})=>Oct(s,t)}},addProseMirrorPlugins(){return[jQt(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()}}}),kQt=Ap.create({name:"horizontalRule",addOptions(){return{HTMLAttributes:{}}},group:"block",parseHTML(){return[{tag:"hr"}]},renderHTML({HTMLAttributes:s}){return["hr",Xd(this.options.HTMLAttributes,s)]},addCommands(){return{setHorizontalRule:()=>({chain:s,state:t})=>{if(!bXt(t,t.schema.nodes[this.name]))return!1;const{selection:r}=t,{$from:n,$to:a}=r,i=s();return n.parentOffset===0?i.insertContentAt({from:Math.max(n.pos-1,0),to:a.pos},{type:this.name}):UZt(r)?i.insertContentAt(a.pos,{type:this.name}):i.insertContent({type:this.name}),i.command(({tr:l,dispatch:o})=>{var c;if(o){const{$to:d}=l.selection,h=d.end();if(d.nodeAfter)d.nodeAfter.isTextblock?l.setSelection(Ri.create(l.doc,d.pos+1)):d.nodeAfter.isBlock?l.setSelection(Si.create(l.doc,d.pos)):l.setSelection(Ri.create(l.doc,d.pos));else{const m=(c=d.parent.type.contentMatch.defaultType)===null||c===void 0?void 0:c.create();m&&(l.insert(h,m),l.setSelection(Ri.create(l.doc,h+1)))}l.scrollIntoView()}return!0}).run()}}},addInputRules(){return[Act({find:/^(?:---|—-|___\s|\*\*\*\s)$/,type:this.type})]}}),SQt=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))$/,CQt=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))/g,TQt=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))$/,EQt=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))/g,AQt=M1.create({name:"italic",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"em"},{tag:"i",getAttrs:s=>s.style.fontStyle!=="normal"&&null},{style:"font-style=normal",clearMark:s=>s.type.name===this.name},{style:"font-style=italic"}]},renderHTML({HTMLAttributes:s}){return["em",Xd(this.options.HTMLAttributes,s),0]},addCommands(){return{setItalic:()=>({commands:s})=>s.setMark(this.name),toggleItalic:()=>({commands:s})=>s.toggleMark(this.name),unsetItalic:()=>({commands:s})=>s.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-i":()=>this.editor.commands.toggleItalic(),"Mod-I":()=>this.editor.commands.toggleItalic()}},addInputRules(){return[dL({find:SQt,type:this.type}),dL({find:TQt,type:this.type})]},addPasteRules(){return[_A({find:CQt,type:this.type}),_A({find:EQt,type:this.type})]}}),MQt=Ap.create({name:"listItem",addOptions(){return{HTMLAttributes:{},bulletListTypeName:"bulletList",orderedListTypeName:"orderedList"}},content:"paragraph block*",defining:!0,parseHTML(){return[{tag:"li"}]},renderHTML({HTMLAttributes:s}){return["li",Xd(this.options.HTMLAttributes,s),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)}}}),IQt="listItem",kBe="textStyle",SBe=/^(\d+)\.\s$/,PQt=Ap.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:s=>s.hasAttribute("start")?parseInt(s.getAttribute("start")||"",10):1},type:{default:null,parseHTML:s=>s.getAttribute("type")}}},parseHTML(){return[{tag:"ol"}]},renderHTML({HTMLAttributes:s}){const{start:t,...r}=s;return t===1?["ol",Xd(this.options.HTMLAttributes,r),0]:["ol",Xd(this.options.HTMLAttributes,s),0]},addCommands(){return{toggleOrderedList:()=>({commands:s,chain:t})=>this.options.keepAttributes?t().toggleList(this.name,this.options.itemTypeName,this.options.keepMarks).updateAttributes(IQt,this.editor.getAttributes(kBe)).run():s.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-7":()=>this.editor.commands.toggleOrderedList()}},addInputRules(){let s=S9({find:SBe,type:this.type,getAttributes:t=>({start:+t[1]}),joinPredicate:(t,r)=>r.childCount+r.attrs.start===+t[1]});return(this.options.keepMarks||this.options.keepAttributes)&&(s=S9({find:SBe,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:t=>({start:+t[1],...this.editor.getAttributes(kBe)}),joinPredicate:(t,r)=>r.childCount+r.attrs.start===+t[1],editor:this.editor})),[s]}}),LQt=Ap.create({name:"paragraph",priority:1e3,addOptions(){return{HTMLAttributes:{}}},group:"block",content:"inline*",parseHTML(){return[{tag:"p"}]},renderHTML({HTMLAttributes:s}){return["p",Xd(this.options.HTMLAttributes,s),0]},addCommands(){return{setParagraph:()=>({commands:s})=>s.setNode(this.name)}},addKeyboardShortcuts(){return{"Mod-Alt-0":()=>this.editor.commands.setParagraph()}}}),DQt=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))$/,RQt=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))/g,OQt=M1.create({name:"strike",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"s"},{tag:"del"},{tag:"strike"},{style:"text-decoration",consuming:!1,getAttrs:s=>s.includes("line-through")?{}:!1}]},renderHTML({HTMLAttributes:s}){return["s",Xd(this.options.HTMLAttributes,s),0]},addCommands(){return{setStrike:()=>({commands:s})=>s.setMark(this.name),toggleStrike:()=>({commands:s})=>s.toggleMark(this.name),unsetStrike:()=>({commands:s})=>s.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-Shift-s":()=>this.editor.commands.toggleStrike()}},addInputRules(){return[dL({find:DQt,type:this.type})]},addPasteRules(){return[_A({find:RQt,type:this.type})]}}),FQt=Ap.create({name:"text",group:"inline"}),JTe=Kf.create({name:"starterKit",addExtensions(){const s=[];return this.options.bold!==!1&&s.push(GXt.configure(this.options.bold)),this.options.blockquote!==!1&&s.push($Xt.configure(this.options.blockquote)),this.options.bulletList!==!1&&s.push(KXt.configure(this.options.bulletList)),this.options.code!==!1&&s.push(XXt.configure(this.options.code)),this.options.codeBlock!==!1&&s.push(eQt.configure(this.options.codeBlock)),this.options.document!==!1&&s.push(tQt.configure(this.options.document)),this.options.dropcursor!==!1&&s.push(nQt.configure(this.options.dropcursor)),this.options.gapcursor!==!1&&s.push(hQt.configure(this.options.gapcursor)),this.options.hardBreak!==!1&&s.push(mQt.configure(this.options.hardBreak)),this.options.heading!==!1&&s.push(fQt.configure(this.options.heading)),this.options.history!==!1&&s.push(NQt.configure(this.options.history)),this.options.horizontalRule!==!1&&s.push(kQt.configure(this.options.horizontalRule)),this.options.italic!==!1&&s.push(AQt.configure(this.options.italic)),this.options.listItem!==!1&&s.push(MQt.configure(this.options.listItem)),this.options.orderedList!==!1&&s.push(PQt.configure(this.options.orderedList)),this.options.paragraph!==!1&&s.push(LQt.configure(this.options.paragraph)),this.options.strike!==!1&&s.push(OQt.configure(this.options.strike)),this.options.text!==!1&&s.push(FQt.configure(this.options.text)),s}}),BQt="aaa1rp3bb0ott3vie4c1le2ogado5udhabi7c0ademy5centure6ountant0s9o1tor4d0s1ult4e0g1ro2tna4f0l1rica5g0akhan5ency5i0g1rbus3force5tel5kdn3l0ibaba4pay4lfinanz6state5y2sace3tom5m0azon4ericanexpress7family11x2fam3ica3sterdam8nalytics7droid5quan4z2o0l2partments8p0le4q0uarelle8r0ab1mco4chi3my2pa2t0e3s0da2ia2sociates9t0hleta5torney7u0ction5di0ble3o3spost5thor3o0s4w0s2x0a2z0ure5ba0by2idu3namex4d1k2r0celona5laycard4s5efoot5gains6seball5ketball8uhaus5yern5b0c1t1va3cg1n2d1e0ats2uty4er2rlin4st0buy5t2f1g1h0arti5i0ble3d1ke2ng0o3o1z2j1lack0friday9ockbuster8g1omberg7ue3m0s1w2n0pparibas9o0ats3ehringer8fa2m1nd2o0k0ing5sch2tik2on4t1utique6x2r0adesco6idgestone9oadway5ker3ther5ussels7s1t1uild0ers6siness6y1zz3v1w1y1z0h3ca0b1fe2l0l1vinklein9m0era3p2non3petown5ital0one8r0avan4ds2e0er0s4s2sa1e1h1ino4t0ering5holic7ba1n1re3c1d1enter4o1rn3f0a1d2g1h0anel2nel4rity4se2t2eap3intai5ristmas6ome4urch5i0priani6rcle4sco3tadel4i0c2y3k1l0aims4eaning6ick2nic1que6othing5ud3ub0med6m1n1o0ach3des3ffee4llege4ogne5m0mbank4unity6pany2re3uter5sec4ndos3struction8ulting7tact3ractors9oking4l1p2rsica5untry4pon0s4rses6pa2r0edit0card4union9icket5own3s1uise0s6u0isinella9v1w1x1y0mru3ou3z2dad1nce3ta1e1ing3sun4y2clk3ds2e0al0er2s3gree4livery5l1oitte5ta3mocrat6ntal2ist5si0gn4v2hl2iamonds6et2gital5rect0ory7scount3ver5h2y2j1k1m1np2o0cs1tor4g1mains5t1wnload7rive4tv2ubai3nlop4pont4rban5vag2r2z2earth3t2c0o2deka3u0cation8e1g1mail3erck5nergy4gineer0ing9terprises10pson4quipment8r0icsson6ni3s0q1tate5t1u0rovision8s2vents5xchange6pert3osed4ress5traspace10fage2il1rwinds6th3mily4n0s2rm0ers5shion4t3edex3edback6rrari3ero6i0delity5o2lm2nal1nce1ial7re0stone6mdale6sh0ing5t0ness6j1k1lickr3ghts4r2orist4wers5y2m1o0o0d1tball6rd1ex2sale4um3undation8x2r0ee1senius7l1ogans4ntier7tr2ujitsu5n0d2rniture7tbol5yi3ga0l0lery3o1up4me0s3p1rden4y2b0iz3d0n2e0a1nt0ing5orge5f1g0ee3h1i0ft0s3ves2ing5l0ass3e1obal2o4m0ail3bh2o1x2n1odaddy5ld0point6f2o0dyear5g0le4p1t1v2p1q1r0ainger5phics5tis4een3ipe3ocery4up4s1t1u0cci3ge2ide2tars5ru3w1y2hair2mburg5ngout5us3bo2dfc0bank7ealth0care8lp1sinki6re1mes5iphop4samitsu7tachi5v2k0t2m1n1ockey4ldings5iday5medepot5goods5s0ense7nda3rse3spital5t0ing5t0els3mail5use3w2r1sbc3t1u0ghes5yatt3undai7ibm2cbc2e1u2d1e0ee3fm2kano4l1m0amat4db2mo0bilien9n0c1dustries8finiti5o2g1k1stitute6urance4e4t0ernational10uit4vestments10o1piranga7q1r0ish4s0maili5t0anbul7t0au2v3jaguar4va3cb2e0ep2tzt3welry6io2ll2m0p2nj2o0bs1urg4t1y2p0morgan6rs3uegos4niper7kaufen5ddi3e0rryhotels6properties14fh2g1h1i0a1ds2m1ndle4tchen5wi3m1n1oeln3matsu5sher5p0mg2n2r0d1ed3uokgroup8w1y0oto4z2la0caixa5mborghini8er3nd0rover6xess5salle5t0ino3robe5w0yer5b1c1ds2ease3clerc5frak4gal2o2xus4gbt3i0dl2fe0insurance9style7ghting6ke2lly3mited4o2ncoln4k2ve1ing5k1lc1p2oan0s3cker3us3l1ndon4tte1o3ve3pl0financial11r1s1t0d0a3u0ndbeck6xe1ury5v1y2ma0drid4if1son4keup4n0agement7go3p1rket0ing3s4riott5shalls7ttel5ba2c0kinsey7d1e0d0ia3et2lbourne7me1orial6n0u2rckmsd7g1h1iami3crosoft7l1ni1t2t0subishi9k1l0b1s2m0a2n1o0bi0le4da2e1i1m1nash3ey2ster5rmon3tgage6scow4to0rcycles9v0ie4p1q1r1s0d2t0n1r2u0seum3ic4v1w1x1y1z2na0b1goya4me2vy3ba2c1e0c1t0bank4flix4work5ustar5w0s2xt0direct7us4f0l2g0o2hk2i0co2ke1on3nja3ssan1y5l1o0kia3rton4w0ruz3tv4p1r0a1w2tt2u1yc2z2obi1server7ffice5kinawa6layan0group9lo3m0ega4ne1g1l0ine5oo2pen3racle3nge4g0anic5igins6saka4tsuka4t2vh3pa0ge2nasonic7ris2s1tners4s1y3y2ccw3e0t2f0izer5g1h0armacy6d1ilips5one2to0graphy6s4ysio5ics1tet2ures6d1n0g1k2oneer5zza4k1l0ace2y0station9umbing5s3m1n0c2ohl2ker3litie5rn2st3r0axi3ess3ime3o0d0uctions8f1gressive8mo2perties3y5tection8u0dential9s1t1ub2w0c2y2qa1pon3uebec3st5racing4dio4e0ad1lestate6tor2y4cipes5d0stone5umbrella9hab3ise0n3t2liance6n0t0als5pair3ort3ublican8st0aurant8view0s5xroth6ich0ardli6oh3l1o1p2o0cks3deo3gers4om3s0vp3u0gby3hr2n2w0e2yukyu6sa0arland6fe0ty4kura4le1on3msclub4ung5ndvik0coromant12ofi4p1rl2s1ve2xo3b0i1s2c0b1haeffler7midt4olarships8ol3ule3warz5ience5ot3d1e0arch3t2cure1ity6ek2lect4ner3rvices6ven3w1x0y3fr2g1h0angrila6rp3ell3ia1ksha5oes2p0ping5uji3w3i0lk2na1gles5te3j1k0i0n2y0pe4l0ing4m0art3ile4n0cf3o0ccer3ial4ftbank4ware6hu2lar2utions7ng1y2y2pa0ce3ort2t3r0l2s1t0ada2ples4r1tebank4farm7c0group6ockholm6rage3e3ream4udio2y3yle4u0cks3pplies3y2ort5rf1gery5zuki5v1watch4iss4x1y0dney4stems6z2tab1ipei4lk2obao4rget4tamotors6r2too4x0i3c0i2d0k2eam2ch0nology8l1masek5nnis4va3f1g1h0d1eater2re6iaa2ckets5enda4ps2res2ol4j0maxx4x2k0maxx5l1m0all4n1o0day3kyo3ols3p1ray3shiba5tal3urs3wn2yota3s3r0ade1ing4ining5vel0ers0insurance16ust3v2t1ube2i1nes3shu4v0s2w1z2ua1bank3s2g1k1nicom3versity8o2ol2ps2s1y1z2va0cations7na1guard7c1e0gas3ntures6risign5mögensberater2ung14sicherung10t2g1i0ajes4deo3g1king4llas4n1p1rgin4sa1ion4va1o3laanderen9n1odka3lvo3te1ing3o2yage5u2wales2mart4ter4ng0gou5tch0es6eather0channel12bcam3er2site5d0ding5ibo2r3f1hoswho6ien2ki2lliamhill9n0dows4e1ners6me2olterskluwer11odside6rk0s2ld3w2s1tc1f3xbox3erox4ihuan4n2xx2yz3yachts4hoo3maxun5ndex5e1odobashi7ga2kohama6u0tube6t1un3za0ppos4ra3ero3ip2m1one3uerich6w2",zQt="ελ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",hke="numeric",mke="ascii",fke="alpha",l7="asciinumeric",_O="alphanumeric",pke="domain",Fct="emoji",$Qt="scheme",UQt="slashscheme",r_e="whitespace";function qQt(s,t){return s in t||(t[s]=[]),t[s]}function qT(s,t,r){t[hke]&&(t[l7]=!0,t[_O]=!0),t[mke]&&(t[l7]=!0,t[fke]=!0),t[l7]&&(t[_O]=!0),t[fke]&&(t[_O]=!0),t[_O]&&(t[pke]=!0),t[Fct]&&(t[pke]=!0);for(const n in t){const a=qQt(n,r);a.indexOf(s)<0&&a.push(s)}}function VQt(s,t){const r={};for(const n in t)t[n].indexOf(s)>=0&&(r[n]=!0);return r}function Jg(s=null){this.j={},this.jr=[],this.jd=null,this.t=s}Jg.groups={};Jg.prototype={accepts(){return!!this.t},go(s){const t=this,r=t.j[s];if(r)return r;for(let n=0;ns.ta(t,r,n,a),Mu=(s,t,r,n,a)=>s.tr(t,r,n,a),CBe=(s,t,r,n,a)=>s.ts(t,r,n,a),Dn=(s,t,r,n,a)=>s.tt(t,r,n,a),c2="WORD",gke="UWORD",Bct="ASCIINUMERICAL",zct="ALPHANUMERICAL",C9="LOCALHOST",xke="TLD",yke="UTLD",Tue="SCHEME",H6="SLASH_SCHEME",eEe="NUM",vke="WS",tEe="NL",c7="OPENBRACE",d7="CLOSEBRACE",yme="OPENBRACKET",vme="CLOSEBRACKET",bme="OPENPAREN",_me="CLOSEPAREN",wme="OPENANGLEBRACKET",jme="CLOSEANGLEBRACKET",Nme="FULLWIDTHLEFTPAREN",kme="FULLWIDTHRIGHTPAREN",Sme="LEFTCORNERBRACKET",Cme="RIGHTCORNERBRACKET",Tme="LEFTWHITECORNERBRACKET",Eme="RIGHTWHITECORNERBRACKET",Ame="FULLWIDTHLESSTHAN",Mme="FULLWIDTHGREATERTHAN",Ime="AMPERSAND",Pme="APOSTROPHE",Lme="ASTERISK",HN="AT",Dme="BACKSLASH",Rme="BACKTICK",Ome="CARET",sk="COLON",sEe="COMMA",Fme="DOLLAR",Bb="DOT",Bme="EQUALS",rEe="EXCLAMATION",vy="HYPHEN",u7="PERCENT",zme="PIPE",$me="PLUS",Ume="POUND",h7="QUERY",nEe="QUOTE",$ct="FULLWIDTHMIDDLEDOT",aEe="SEMI",zb="SLASH",m7="TILDE",qme="UNDERSCORE",Uct="EMOJI",Vme="SYM";var qct=Object.freeze({__proto__:null,ALPHANUMERICAL:zct,AMPERSAND:Ime,APOSTROPHE:Pme,ASCIINUMERICAL:Bct,ASTERISK:Lme,AT:HN,BACKSLASH:Dme,BACKTICK:Rme,CARET:Ome,CLOSEANGLEBRACKET:jme,CLOSEBRACE:d7,CLOSEBRACKET:vme,CLOSEPAREN:_me,COLON:sk,COMMA:sEe,DOLLAR:Fme,DOT:Bb,EMOJI:Uct,EQUALS:Bme,EXCLAMATION:rEe,FULLWIDTHGREATERTHAN:Mme,FULLWIDTHLEFTPAREN:Nme,FULLWIDTHLESSTHAN:Ame,FULLWIDTHMIDDLEDOT:$ct,FULLWIDTHRIGHTPAREN:kme,HYPHEN:vy,LEFTCORNERBRACKET:Sme,LEFTWHITECORNERBRACKET:Tme,LOCALHOST:C9,NL:tEe,NUM:eEe,OPENANGLEBRACKET:wme,OPENBRACE:c7,OPENBRACKET:yme,OPENPAREN:bme,PERCENT:u7,PIPE:zme,PLUS:$me,POUND:Ume,QUERY:h7,QUOTE:nEe,RIGHTCORNERBRACKET:Cme,RIGHTWHITECORNERBRACKET:Eme,SCHEME:Tue,SEMI:aEe,SLASH:zb,SLASH_SCHEME:H6,SYM:Vme,TILDE:m7,TLD:xke,UNDERSCORE:qme,UTLD:yke,UWORD:gke,WORD:c2,WS:vke});const t2=/[a-z]/,DR=new RegExp("\\p{L}","u"),n_e=new RegExp("\\p{Emoji}","u"),s2=/\d/,a_e=/\s/,TBe="\r",i_e=` `,HQt="️",GQt="‍",o_e="";let nq=null,aq=null;function WQt(s=[]){const t={};Jg.groups=t;const r=new Jg;nq==null&&(nq=EBe(BQt)),aq==null&&(aq=EBe(zQt)),Dn(r,"'",Pme),Dn(r,"{",c7),Dn(r,"}",d7),Dn(r,"[",yme),Dn(r,"]",vme),Dn(r,"(",bme),Dn(r,")",_me),Dn(r,"<",wme),Dn(r,">",jme),Dn(r,"(",Nme),Dn(r,")",kme),Dn(r,"「",Sme),Dn(r,"」",Cme),Dn(r,"『",Tme),Dn(r,"』",Eme),Dn(r,"<",Ame),Dn(r,">",Mme),Dn(r,"&",Ime),Dn(r,"*",Lme),Dn(r,"@",HN),Dn(r,"`",Rme),Dn(r,"^",Ome),Dn(r,":",sk),Dn(r,",",sEe),Dn(r,"$",Fme),Dn(r,".",Bb),Dn(r,"=",Bme),Dn(r,"!",rEe),Dn(r,"-",vy),Dn(r,"%",u7),Dn(r,"|",zme),Dn(r,"+",$me),Dn(r,"#",Ume),Dn(r,"?",h7),Dn(r,'"',nEe),Dn(r,"/",zb),Dn(r,";",aEe),Dn(r,"~",m7),Dn(r,"_",qme),Dn(r,"\\",Dme),Dn(r,"・",$ct);const n=Mu(r,s2,eEe,{[hke]:!0});Mu(n,s2,n);const a=Mu(n,t2,Bct,{[l7]:!0}),i=Mu(n,DR,zct,{[_O]:!0}),l=Mu(r,t2,c2,{[mke]:!0});Mu(l,s2,a),Mu(l,t2,l),Mu(a,s2,a),Mu(a,t2,a);const o=Mu(r,DR,gke,{[fke]:!0});Mu(o,t2),Mu(o,s2,i),Mu(o,DR,o),Mu(i,s2,i),Mu(i,t2),Mu(i,DR,i);const c=Dn(r,i_e,tEe,{[r_e]:!0}),d=Dn(r,TBe,vke,{[r_e]:!0}),h=Mu(r,a_e,vke,{[r_e]:!0});Dn(r,o_e,h),Dn(d,i_e,c),Dn(d,o_e,h),Mu(d,a_e,h),Dn(h,TBe),Dn(h,i_e),Mu(h,a_e,h),Dn(h,o_e,h);const m=Mu(r,n_e,Uct,{[Fct]:!0});Dn(m,"#"),Mu(m,n_e,m),Dn(m,HQt,m);const p=Dn(m,GQt);Dn(p,"#"),Mu(p,n_e,m);const x=[[t2,l],[s2,a]],y=[[t2,null],[DR,o],[s2,i]];for(let _=0;__[0]>b[0]?1:-1);for(let _=0;_=0?k[pke]=!0:t2.test(b)?s2.test(b)?k[l7]=!0:k[mke]=!0:k[hke]=!0,CBe(r,b,b,k)}return CBe(r,"localhost",C9,{ascii:!0}),r.jd=new Jg(Vme),{start:r,tokens:Object.assign({groups:t},qct)}}function Vct(s,t){const r=KQt(t.replace(/[A-Z]/g,o=>o.toLowerCase())),n=r.length,a=[];let i=0,l=0;for(;l=0&&(m+=r[l].length,p++),d+=r[l].length,i+=r[l].length,l++;i-=m,l-=p,d-=m,a.push({t:h.t,v:t.slice(i-d,i),s:i-d,e:i})}return a}function KQt(s){const t=[],r=s.length;let n=0;for(;n56319||n+1===r||(i=s.charCodeAt(n+1))<56320||i>57343?s[n]:s.slice(n,n+2);t.push(l),n+=l.length}return t}function _N(s,t,r,n,a){let i;const l=t.length;for(let o=0;o=0;)i++;if(i>0){t.push(r.join(""));for(let l=parseInt(s.substring(n,n+i),10);l>0;l--)r.pop();n+=i}else r.push(s[n]),n++}return t}const T9={defaultProtocol:"http",events:null,format:ABe,formatHref:ABe,nl2br:!1,tagName:"a",target:null,rel:null,validate:!0,truncate:1/0,className:null,attributes:null,ignoreTags:[],render:null};function iEe(s,t=null){let r=Object.assign({},T9);s&&(r=Object.assign(r,s instanceof iEe?s.o:s));const n=r.ignoreTags,a=[];for(let i=0;ir?n.substring(0,r)+"…":n},toFormattedHref(s){return s.get("formatHref",this.toHref(s.get("defaultProtocol")),this)},startIndex(){return this.tk[0].s},endIndex(){return this.tk[this.tk.length-1].e},toObject(s=T9.defaultProtocol){return{type:this.t,value:this.toString(),isLink:this.isLink,href:this.toHref(s),start:this.startIndex(),end:this.endIndex()}},toFormattedObject(s){return{type:this.t,value:this.toFormattedString(s),isLink:this.isLink,href:this.toFormattedHref(s),start:this.startIndex(),end:this.endIndex()}},validate(s){return s.get("validate",this.toString(),this)},render(s){const t=this,r=this.toHref(s.get("defaultProtocol")),n=s.get("formatHref",r,this),a=s.get("tagName",r,t),i=this.toFormattedString(s),l={},o=s.get("className",r,t),c=s.get("target",r,t),d=s.get("rel",r,t),h=s.getObj("attributes",r,t),m=s.getObj("events",r,t);return l.href=n,o&&(l.class=o),c&&(l.target=c),d&&(l.rel=d),h&&Object.assign(l,h),{tagName:a,attributes:l,content:i,eventListeners:m}}};function gxe(s,t){class r extends Hct{constructor(a,i){super(a,i),this.t=s}}for(const n in t)r.prototype[n]=t[n];return r.t=s,r}const MBe=gxe("email",{isLink:!0,toHref(){return"mailto:"+this.toString()}}),IBe=gxe("text"),YQt=gxe("nl"),iq=gxe("url",{isLink:!0,toHref(s=T9.defaultProtocol){return this.hasProtocol()?this.v:`${s}://${this.v}`},hasProtocol(){const s=this.tk;return s.length>=2&&s[0].t!==C9&&s[1].t===sk}}),hy=s=>new Jg(s);function ZQt({groups:s}){const t=s.domain.concat([Ime,Lme,HN,Dme,Rme,Ome,Fme,Bme,vy,eEe,u7,zme,$me,Ume,zb,Vme,m7,qme]),r=[Pme,sk,sEe,Bb,rEe,u7,h7,nEe,aEe,wme,jme,c7,d7,vme,yme,bme,_me,Nme,kme,Sme,Cme,Tme,Eme,Ame,Mme],n=[Ime,Pme,Lme,Dme,Rme,Ome,Fme,Bme,vy,c7,d7,u7,zme,$me,Ume,h7,zb,Vme,m7,qme],a=hy(),i=Dn(a,m7);Oo(i,n,i),Oo(i,s.domain,i);const l=hy(),o=hy(),c=hy();Oo(a,s.domain,l),Oo(a,s.scheme,o),Oo(a,s.slashscheme,c),Oo(l,n,i),Oo(l,s.domain,l);const d=Dn(l,HN);Dn(i,HN,d),Dn(o,HN,d),Dn(c,HN,d);const h=Dn(i,Bb);Oo(h,n,i),Oo(h,s.domain,i);const m=hy();Oo(d,s.domain,m),Oo(m,s.domain,m);const p=Dn(m,Bb);Oo(p,s.domain,m);const x=hy(MBe);Oo(p,s.tld,x),Oo(p,s.utld,x),Dn(d,C9,x);const y=Dn(m,vy);Dn(y,vy,y),Oo(y,s.domain,m),Oo(x,s.domain,m),Dn(x,Bb,p),Dn(x,vy,y);const _=Dn(x,sk);Oo(_,s.numeric,MBe);const b=Dn(l,vy),j=Dn(l,Bb);Dn(b,vy,b),Oo(b,s.domain,l),Oo(j,n,i),Oo(j,s.domain,l);const k=hy(iq);Oo(j,s.tld,k),Oo(j,s.utld,k),Oo(k,s.domain,l),Oo(k,n,i),Dn(k,Bb,j),Dn(k,vy,b),Dn(k,HN,d);const T=Dn(k,sk),E=hy(iq);Oo(T,s.numeric,E);const A=hy(iq),D=hy();Oo(A,t,A),Oo(A,r,D),Oo(D,t,A),Oo(D,r,D),Dn(k,zb,A),Dn(E,zb,A);const R=Dn(o,sk),z=Dn(c,sk),O=Dn(z,zb),$=Dn(O,zb);Oo(o,s.domain,l),Dn(o,Bb,j),Dn(o,vy,b),Oo(c,s.domain,l),Dn(c,Bb,j),Dn(c,vy,b),Oo(R,s.domain,A),Dn(R,zb,A),Dn(R,h7,A),Oo($,s.domain,A),Oo($,t,A),Dn($,zb,A);const ee=[[c7,d7],[yme,vme],[bme,_me],[wme,jme],[Nme,kme],[Sme,Cme],[Tme,Eme],[Ame,Mme]];for(let Z=0;Z=0&&p++,a++,h++;if(p<0)a-=h,a0&&(i.push(l_e(IBe,t,l)),l=[]),a-=p,h-=p;const x=m.t,y=r.slice(a-h,a);i.push(l_e(x,t,y))}}return l.length>0&&i.push(l_e(IBe,t,l)),i}function l_e(s,t,r){const n=r[0].s,a=r[r.length-1].e,i=t.slice(n,a);return new s(i,r)}const QQt=typeof console<"u"&&console&&console.warn||(()=>{}),JQt="until manual call of linkify.init(). Register all schemes and plugins before invoking linkify the first time.",jd={scanner:null,parser:null,tokenQueue:[],pluginQueue:[],customSchemes:[],initialized:!1};function eJt(){return Jg.groups={},jd.scanner=null,jd.parser=null,jd.tokenQueue=[],jd.pluginQueue=[],jd.customSchemes=[],jd.initialized=!1,jd}function PBe(s,t=!1){if(jd.initialized&&QQt(`linkifyjs: already initialized - will not register custom scheme "${s}" ${JQt}`),!/^[0-9a-z]+(-[0-9a-z]+)*$/.test(s))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`);jd.customSchemes.push([s,t])}function tJt(){jd.scanner=WQt(jd.customSchemes);for(let s=0;s{const a=t.some(d=>d.docChanged)&&!r.doc.eq(n.doc),i=t.some(d=>d.getMeta("preventAutolink"));if(!a||i)return;const{tr:l}=n,o=PZt(r.doc,[...t]);if(zZt(o).forEach(({newRange:d})=>{const h=DZt(n.doc,d,x=>x.isTextblock);let m,p;if(h.length>1)m=h[0],p=n.doc.textBetween(m.pos,m.pos+m.node.nodeSize,void 0," ");else if(h.length){const x=n.doc.textBetween(d.from,d.to," "," ");if(!rJt.test(x))return;m=h[0],p=n.doc.textBetween(m.pos,d.to,void 0," ")}if(m&&p){const x=p.split(sJt).filter(Boolean);if(x.length<=0)return!1;const y=x[x.length-1],_=m.pos+p.lastIndexOf(y);if(!y)return!1;const b=oEe(y).map(j=>j.toObject(s.defaultProtocol));if(!aJt(b))return!1;b.filter(j=>j.isLink).map(j=>({...j,from:_+j.start+1,to:_+j.end+1})).filter(j=>n.schema.marks.code?!n.doc.rangeHasMark(j.from,j.to,n.schema.marks.code):!0).filter(j=>s.validate(j.value)).filter(j=>s.shouldAutoLink(j.value)).forEach(j=>{GTe(j.from,j.to,n.doc).some(k=>k.mark.type===s.type)||l.addMark(j.from,j.to,s.type.create({href:j.href}))})}}),!!l.steps.length)return l}})}function oJt(s){return new jm({key:new Ep("handleClickLink"),props:{handleClick:(t,r,n)=>{var a,i;if(n.button!==0||!t.editable)return!1;let l=n.target;const o=[];for(;l.nodeName!=="DIV";)o.push(l),l=l.parentNode;if(!o.find(p=>p.nodeName==="A"))return!1;const c=Ect(t.state,s.type.name),d=n.target,h=(a=d==null?void 0:d.href)!==null&&a!==void 0?a:c.href,m=(i=d==null?void 0:d.target)!==null&&i!==void 0?i:c.target;return d&&h?(window.open(h,m),!0):!1}}})}function lJt(s){return new jm({key:new Ep("handlePasteLink"),props:{handlePaste:(t,r,n)=>{const{state:a}=t,{selection:i}=a,{empty:l}=i;if(l)return!1;let o="";n.content.forEach(d=>{o+=d.textContent});const c=Gct(o,{defaultProtocol:s.defaultProtocol}).find(d=>d.isLink&&d.value===o);return!o||!c?!1:s.editor.commands.setMark(s.type,{href:c.href})}}})}function tC(s,t){const r=["http","https","ftp","ftps","mailto","tel","callto","sms","cid","xmpp"];return t&&t.forEach(n=>{const a=typeof n=="string"?n:n.scheme;a&&r.push(a)}),!s||s.replace(nJt,"").match(new RegExp(`^(?:(?:${r.join("|")}):|[^a-z]|[a-z0-9+.-]+(?:[^a-z+.-:]|$))`,"i"))}const cEe=M1.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(s=>{if(typeof s=="string"){PBe(s);return}PBe(s.scheme,s.optionalSlashes)})},onDestroy(){eJt()},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:(s,t)=>!!tC(s,t.protocols),validate:s=>!!s,shouldAutoLink:s=>!!s}},addAttributes(){return{href:{default:null,parseHTML(s){return s.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:s=>{const t=s.getAttribute("href");return!t||!this.options.isAllowedUri(t,{defaultValidate:r=>!!tC(r,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?!1:null}}]},renderHTML({HTMLAttributes:s}){return this.options.isAllowedUri(s.href,{defaultValidate:t=>!!tC(t,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?["a",Xd(this.options.HTMLAttributes,s),0]:["a",Xd(this.options.HTMLAttributes,{...s,href:""}),0]},addCommands(){return{setLink:s=>({chain:t})=>{const{href:r}=s;return this.options.isAllowedUri(r,{defaultValidate:n=>!!tC(n,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?t().setMark(this.name,s).setMeta("preventAutolink",!0).run():!1},toggleLink:s=>({chain:t})=>{const{href:r}=s;return this.options.isAllowedUri(r,{defaultValidate:n=>!!tC(n,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?t().toggleMark(this.name,s,{extendEmptyMarkRange:!0}).setMeta("preventAutolink",!0).run():!1},unsetLink:()=>({chain:s})=>s().unsetMark(this.name,{extendEmptyMarkRange:!0}).setMeta("preventAutolink",!0).run()}},addPasteRules(){return[_A({find:s=>{const t=[];if(s){const{protocols:r,defaultProtocol:n}=this.options,a=Gct(s).filter(i=>i.isLink&&this.options.isAllowedUri(i.value,{defaultValidate:l=>!!tC(l,r),protocols:r,defaultProtocol:n}));a.length&&a.forEach(i=>t.push({text:i.value,data:{href:i.href},index:i.start}))}return t},type:this.type,getAttributes:s=>{var t;return{href:(t=s.data)===null||t===void 0?void 0:t.href}}})]},addProseMirrorPlugins(){const s=[],{protocols:t,defaultProtocol:r}=this.options;return this.options.autolink&&s.push(iJt({type:this.type,defaultProtocol:this.options.defaultProtocol,validate:n=>this.options.isAllowedUri(n,{defaultValidate:a=>!!tC(a,t),protocols:t,defaultProtocol:r}),shouldAutoLink:this.options.shouldAutoLink})),this.options.openOnClick===!0&&s.push(oJt({type:this.type})),this.options.linkOnPaste&&s.push(lJt({editor:this.editor,defaultProtocol:this.options.defaultProtocol,type:this.type})),s}}),dEe=Kf.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:s=>{const t=s.style.textAlign;return this.options.alignments.includes(t)?t:this.options.defaultAlignment},renderHTML:s=>s.textAlign?{style:`text-align: ${s.textAlign}`}:{}}}}]},addCommands(){return{setTextAlign:s=>({commands:t})=>this.options.alignments.includes(s)?this.options.types.map(r=>t.updateAttributes(r,{textAlign:s})).every(r=>r):!1,unsetTextAlign:()=>({commands:s})=>this.options.types.map(t=>s.resetAttributes(t,"textAlign")).every(t=>t),toggleTextAlign:s=>({editor:t,commands:r})=>this.options.alignments.includes(s)?t.isActive({textAlign:s})?r.unsetTextAlign():r.setTextAlign(s):!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")}}}),cJt=s=>{if(!s.children.length)return;const t=s.querySelectorAll("span");t&&t.forEach(r=>{var n,a;const i=r.getAttribute("style"),l=(a=(n=r.parentElement)===null||n===void 0?void 0:n.closest("span"))===null||a===void 0?void 0:a.getAttribute("style");r.setAttribute("style",`${l};${i}`)})},uEe=M1.create({name:"textStyle",priority:101,addOptions(){return{HTMLAttributes:{},mergeNestedSpanStyles:!1}},parseHTML(){return[{tag:"span",getAttrs:s=>s.hasAttribute("style")?(this.options.mergeNestedSpanStyles&&cJt(s),{}):!1}]},renderHTML({HTMLAttributes:s}){return["span",Xd(this.options.HTMLAttributes,s),0]},addCommands(){return{removeEmptyTextStyle:()=>({tr:s})=>{const{selection:t}=s;return s.doc.nodesBetween(t.from,t.to,(r,n)=>{if(r.isTextblock)return!0;r.marks.filter(a=>a.type===this.type).some(a=>Object.values(a.attrs).some(i=>!!i))||s.removeMark(n,n+r.nodeSize,this.type)}),!0}}}}),dJt=/(?:^|\s)(!\[(.+|:?)]\((\S+)(?:(?:\s+)["'](\S+)["'])?\))$/,uJt=Ap.create({name:"image",addOptions(){return{inline:!1,allowBase64:!1,HTMLAttributes:{}}},inline(){return this.options.inline},group(){return this.options.inline?"inline":"block"},draggable:!0,addAttributes(){return{src:{default:null},alt:{default:null},title:{default:null}}},parseHTML(){return[{tag:this.options.allowBase64?"img[src]":'img[src]:not([src^="data:"])'}]},renderHTML({HTMLAttributes:s}){return["img",Xd(this.options.HTMLAttributes,s)]},addCommands(){return{setImage:s=>({commands:t})=>t.insertContent({type:this.name,attrs:s})}},addInputRules(){return[Act({find:dJt,type:this.type,getAttributes:s=>{const[,,t,r,n]=s;return{src:r,alt:t,title:n}}})]}});let bke,_ke;if(typeof WeakMap<"u"){let s=new WeakMap;bke=t=>s.get(t),_ke=(t,r)=>(s.set(t,r),r)}else{const s=[];let r=0;bke=n=>{for(let a=0;a(r==10&&(r=0),s[r++]=n,s[r++]=a)}var $u=class{constructor(s,t,r,n){this.width=s,this.height=t,this.map=r,this.problems=n}findCell(s){for(let t=0;t=r){(i||(i=[])).push({type:"overlong_rowspan",pos:h,n:j-T});break}const E=a+T*t;for(let A=0;An&&(i+=d.attrs.colspan)}}for(let l=0;l1&&(r=!0)}t==-1?t=i:t!=i&&(t=Math.max(t,i))}return t}function fJt(s,t,r){s.problems||(s.problems=[]);const n={};for(let a=0;a0;t--)if(s.node(t).type.spec.tableRole=="row")return s.node(0).resolve(s.before(t+1));return null}function gJt(s){for(let t=s.depth;t>0;t--){const r=s.node(t).type.spec.tableRole;if(r==="cell"||r==="header_cell")return s.node(t)}return null}function D1(s){const t=s.selection.$head;for(let r=t.depth;r>0;r--)if(t.node(r).type.spec.tableRole=="row")return!0;return!1}function xxe(s){const t=s.selection;if("$anchorCell"in t&&t.$anchorCell)return t.$anchorCell.pos>t.$headCell.pos?t.$anchorCell:t.$headCell;if("node"in t&&t.node&&t.node.type.spec.tableRole=="cell")return t.$anchor;const r=wA(t.$head)||xJt(t.$head);if(r)return r;throw new RangeError(`No cell found around position ${t.head}`)}function xJt(s){for(let t=s.nodeAfter,r=s.pos;t;t=t.firstChild,r++){const n=t.type.spec.tableRole;if(n=="cell"||n=="header_cell")return s.doc.resolve(r)}for(let t=s.nodeBefore,r=s.pos;t;t=t.lastChild,r--){const n=t.type.spec.tableRole;if(n=="cell"||n=="header_cell")return s.doc.resolve(r-t.nodeSize)}}function wke(s){return s.parent.type.spec.tableRole=="row"&&!!s.nodeAfter}function yJt(s){return s.node(0).resolve(s.pos+s.nodeAfter.nodeSize)}function hEe(s,t){return s.depth==t.depth&&s.pos>=t.start(-1)&&s.pos<=t.end(-1)}function Wct(s,t,r){const n=s.node(-1),a=$u.get(n),i=s.start(-1),l=a.nextCell(s.pos-i,t,r);return l==null?null:s.node(0).resolve(i+l)}function jA(s,t,r=1){const n={...s,colspan:s.colspan-r};return n.colwidth&&(n.colwidth=n.colwidth.slice(),n.colwidth.splice(t,r),n.colwidth.some(a=>a>0)||(n.colwidth=null)),n}function Kct(s,t,r=1){const n={...s,colspan:s.colspan+r};if(n.colwidth){n.colwidth=n.colwidth.slice();for(let a=0;ah!=r.pos-i);c.unshift(r.pos-i);const d=c.map(h=>{const m=n.nodeAt(h);if(!m)throw new RangeError(`No cell with offset ${h} found`);const p=i+h+1;return new Tlt(o.resolve(p),o.resolve(p+m.content.size))});super(d[0].$from,d[0].$to,d),this.$anchorCell=t,this.$headCell=r}map(t,r){const n=t.resolve(r.map(this.$anchorCell.pos)),a=t.resolve(r.map(this.$headCell.pos));if(wke(n)&&wke(a)&&hEe(n,a)){const i=this.$anchorCell.node(-1)!=n.node(-1);return i&&this.isRowSelection()?d2.rowSelection(n,a):i&&this.isColSelection()?d2.colSelection(n,a):new d2(n,a)}return Ri.between(n,a)}content(){const t=this.$anchorCell.node(-1),r=$u.get(t),n=this.$anchorCell.start(-1),a=r.rectBetween(this.$anchorCell.pos-n,this.$headCell.pos-n),i={},l=[];for(let c=a.top;c0||b>0){let j=y.attrs;if(_>0&&(j=jA(j,0,_)),b>0&&(j=jA(j,j.colspan-b,b)),x.lefta.bottom){const j={...y.attrs,rowspan:Math.min(x.bottom,a.bottom)-Math.max(x.top,a.top)};x.top0)return!1;const n=t+this.$anchorCell.nodeAfter.attrs.rowspan,a=r+this.$headCell.nodeAfter.attrs.rowspan;return Math.max(n,a)==this.$headCell.node(-1).childCount}static colSelection(t,r=t){const n=t.node(-1),a=$u.get(n),i=t.start(-1),l=a.findCell(t.pos-i),o=a.findCell(r.pos-i),c=t.node(0);return l.top<=o.top?(l.top>0&&(t=c.resolve(i+a.map[l.left])),o.bottom0&&(r=c.resolve(i+a.map[o.left])),l.bottom0)return!1;const l=a+this.$anchorCell.nodeAfter.attrs.colspan,o=i+this.$headCell.nodeAfter.attrs.colspan;return Math.max(l,o)==r.width}eq(t){return t instanceof d2&&t.$anchorCell.pos==this.$anchorCell.pos&&t.$headCell.pos==this.$headCell.pos}static rowSelection(t,r=t){const n=t.node(-1),a=$u.get(n),i=t.start(-1),l=a.findCell(t.pos-i),o=a.findCell(r.pos-i),c=t.node(0);return l.left<=o.left?(l.left>0&&(t=c.resolve(i+a.map[l.top*a.width])),o.right0&&(r=c.resolve(i+a.map[o.top*a.width])),l.right{t.push(pg.node(n,n+r.nodeSize,{class:"selectedCell"}))}),Bu.create(s.doc,t)}function wJt({$from:s,$to:t}){if(s.pos==t.pos||s.pos=0&&!(s.after(a+1)=0&&!(t.before(i+1)>t.start(i));i--,n--);return r==n&&/row|table/.test(s.node(a).type.spec.tableRole)}function jJt({$from:s,$to:t}){let r,n;for(let a=s.depth;a>0;a--){const i=s.node(a);if(i.type.spec.tableRole==="cell"||i.type.spec.tableRole==="header_cell"){r=i;break}}for(let a=t.depth;a>0;a--){const i=t.node(a);if(i.type.spec.tableRole==="cell"||i.type.spec.tableRole==="header_cell"){n=i;break}}return r!==n&&t.parentOffset===0}function NJt(s,t,r){const n=(t||s).selection,a=(t||s).doc;let i,l;if(n instanceof Si&&(l=n.node.type.spec.tableRole)){if(l=="cell"||l=="header_cell")i=dd.create(a,n.from);else if(l=="row"){const o=a.resolve(n.from+1);i=dd.rowSelection(o,o)}else if(!r){const o=$u.get(n.node),c=n.from+1,d=c+o.map[o.width*o.height-1];i=dd.create(a,c+1,d)}}else n instanceof Ri&&wJt(n)?i=Ri.create(a,n.from):n instanceof Ri&&jJt(n)&&(i=Ri.create(a,n.$from.start(),n.$from.end()));return i&&(t||(t=s.tr)).setSelection(i),t}const kJt=new Ep("fix-tables");function Zct(s,t,r,n){const a=s.childCount,i=t.childCount;e:for(let l=0,o=0;l{a.type.spec.tableRole=="table"&&(r=SJt(s,a,i,r))};return t?t.doc!=s.doc&&Zct(t.doc,s.doc,0,n):s.doc.descendants(n),r}function SJt(s,t,r,n){const a=$u.get(t);if(!a.problems)return n;n||(n=s.tr);const i=[];for(let c=0;c0){let x="cell";h.firstChild&&(x=h.firstChild.type.spec.tableRole);const y=[];for(let b=0;b0?-1:0;vJt(t,n,a+i)&&(i=a==0||a==t.width?null:0);for(let l=0;l0&&a0&&t.map[o-1]==c||a0?-1:0;MJt(t,n,a+o)&&(o=a==0||a==t.height?null:0);for(let d=0,h=t.width*a;d0&&a0&&m==t.map[h-t.width]){const p=r.nodeAt(m).attrs;s.setNodeMarkup(s.mapping.slice(o).map(m+n),null,{...p,rowspan:p.rowspan-1}),d+=p.colspan-1}else if(a0&&r[i]==r[i-1]||n.right0&&r[a]==r[a-s]||n.bottom0){const h=c+1+d.content.size,m=LBe(d)?c+1:h;i.replaceWith(m+n.tableStart,h+n.tableStart,o)}i.setSelection(new dd(i.doc.resolve(c+n.tableStart))),t(i)}return!0}function RBe(s,t){const r=Sp(s.schema);return OJt(({node:n})=>r[n.type.spec.tableRole])(s,t)}function OJt(s){return(t,r)=>{const n=t.selection;let a,i;if(n instanceof dd){if(n.$anchorCell.pos!=n.$headCell.pos)return!1;a=n.$anchorCell.nodeAfter,i=n.$anchorCell.pos}else{var l;if(a=gJt(n.$from),!a)return!1;i=(l=wA(n.$from))===null||l===void 0?void 0:l.pos}if(a==null||i==null||a.attrs.colspan==1&&a.attrs.rowspan==1)return!1;if(r){let o=a.attrs;const c=[],d=o.colwidth;o.rowspan>1&&(o={...o,rowspan:1}),o.colspan>1&&(o={...o,colspan:1});const h=G_(t),m=t.tr;for(let x=0;x{l.attrs[s]!==t&&i.setNodeMarkup(o,null,{...l.attrs,[s]:t})}):i.setNodeMarkup(a.pos,null,{...a.nodeAfter.attrs,[s]:t}),n(i)}return!0}}function BJt(s){return function(t,r){if(!D1(t))return!1;if(r){const n=Sp(t.schema),a=G_(t),i=t.tr,l=a.map.cellsInRect(s=="column"?{left:a.left,top:0,right:a.right,bottom:a.map.height}:s=="row"?{left:0,top:a.top,right:a.map.width,bottom:a.bottom}:a),o=l.map(c=>a.table.nodeAt(c));for(let c=0;c{const x=p+i.tableStart,y=l.doc.nodeAt(x);y&&l.setNodeMarkup(x,m,y.attrs)}),n(l)}return!0}}E9("row",{useDeprecatedLogic:!0});E9("column",{useDeprecatedLogic:!0});const zJt=E9("cell",{useDeprecatedLogic:!0});function $Jt(s,t){if(t<0){const r=s.nodeBefore;if(r)return s.pos-r.nodeSize;for(let n=s.index(-1)-1,a=s.before();n>=0;n--){const i=s.node(-1).child(n),l=i.lastChild;if(l)return a-1-l.nodeSize;a-=i.nodeSize}}else{if(s.index()0;n--)if(r.node(n).type.spec.tableRole=="table")return t&&t(s.tr.delete(r.before(n),r.after(n)).scrollIntoView()),!0;return!1}function oq(s,t){const r=s.selection;if(!(r instanceof dd))return!1;if(t){const n=s.tr,a=Sp(s.schema).cell.createAndFill().content;r.forEachCell((i,l)=>{i.content.eq(a)||n.replace(n.mapping.map(l+1),n.mapping.map(l+i.nodeSize-1),new ua(a,0,0))}),n.docChanged&&t(n)}return!0}function qJt(s){if(s.size===0)return null;let{content:t,openStart:r,openEnd:n}=s;for(;t.childCount==1&&(r>0&&n>0||t.child(0).type.spec.tableRole=="table");)r--,n--,t=t.child(0).content;const a=t.child(0),i=a.type.spec.tableRole,l=a.type.schema,o=[];if(i=="row")for(let c=0;c=0;l--){const{rowspan:o,colspan:c}=i.child(l).attrs;for(let d=a;d=t.length&&t.push(An.empty),r[a]n&&(p=p.type.createChecked(jA(p.attrs,p.attrs.colspan,h+p.attrs.colspan-n),p.content)),d.push(p),h+=p.attrs.colspan;for(let x=1;xa&&(m=m.type.create({...m.attrs,rowspan:Math.max(1,a-m.attrs.rowspan)},m.content)),c.push(m)}i.push(An.from(c))}r=i,t=a}return{width:s,height:t,rows:r}}function GJt(s,t,r,n,a,i,l){const o=s.doc.type.schema,c=Sp(o);let d,h;if(a>t.width)for(let m=0,p=0;mt.height){const m=[];for(let y=0,_=(t.height-1)*t.width;y=t.width?!1:r.nodeAt(t.map[_+y]).type==c.header_cell;m.push(b?h||(h=c.header_cell.createAndFill()):d||(d=c.cell.createAndFill()))}const p=c.row.create(null,An.from(m)),x=[];for(let y=t.height;y{if(!a)return!1;const i=r.selection;if(i instanceof dd)return Eue(r,n,Hi.near(i.$headCell,t));if(s!="horiz"&&!i.empty)return!1;const l=edt(a,s,t);if(l==null)return!1;if(s=="horiz")return Eue(r,n,Hi.near(r.doc.resolve(i.head+t),t));{const o=r.doc.resolve(l),c=Wct(o,s,t);let d;return c?d=Hi.near(c,1):t<0?d=Hi.near(r.doc.resolve(o.before(-1)),-1):d=Hi.near(r.doc.resolve(o.after(-1)),1),Eue(r,n,d)}}}function cq(s,t){return(r,n,a)=>{if(!a)return!1;const i=r.selection;let l;if(i instanceof dd)l=i;else{const c=edt(a,s,t);if(c==null)return!1;l=new dd(r.doc.resolve(c))}const o=Wct(l.$headCell,s,t);return o?Eue(r,n,new dd(l.$anchorCell,o)):!1}}function KJt(s,t){const r=s.state.doc,n=wA(r.resolve(t));return n?(s.dispatch(s.state.tr.setSelection(new dd(n))),!0):!1}function YJt(s,t,r){if(!D1(s.state))return!1;let n=qJt(r);const a=s.state.selection;if(a instanceof dd){n||(n={width:1,height:1,rows:[An.from(jke(Sp(s.state.schema).cell,r))]});const i=a.$anchorCell.node(-1),l=a.$anchorCell.start(-1),o=$u.get(i).rectBetween(a.$anchorCell.pos-l,a.$headCell.pos-l);return n=HJt(n,o.right-o.left,o.bottom-o.top),$Be(s.state,s.dispatch,l,o,n),!0}else if(n){const i=xxe(s.state),l=i.start(-1);return $Be(s.state,s.dispatch,l,$u.get(i.node(-1)).findCell(i.pos-l),n),!0}else return!1}function ZJt(s,t){var r;if(t.button!=0||t.ctrlKey||t.metaKey)return;const n=UBe(s,t.target);let a;if(t.shiftKey&&s.state.selection instanceof dd)i(s.state.selection.$anchorCell,t),t.preventDefault();else if(t.shiftKey&&n&&(a=wA(s.state.selection.$anchor))!=null&&((r=c_e(s,t))===null||r===void 0?void 0:r.pos)!=a.pos)i(a,t),t.preventDefault();else if(!n)return;function i(c,d){let h=c_e(s,d);const m=rk.getState(s.state)==null;if(!h||!hEe(c,h))if(m)h=c;else return;const p=new dd(c,h);if(m||!s.state.selection.eq(p)){const x=s.state.tr.setSelection(p);m&&x.setMeta(rk,c.pos),s.dispatch(x)}}function l(){s.root.removeEventListener("mouseup",l),s.root.removeEventListener("dragstart",l),s.root.removeEventListener("mousemove",o),rk.getState(s.state)!=null&&s.dispatch(s.state.tr.setMeta(rk,-1))}function o(c){const d=c,h=rk.getState(s.state);let m;if(h!=null)m=s.state.doc.resolve(h);else if(UBe(s,d.target)!=n&&(m=c_e(s,t),!m))return l();m&&i(m,d)}s.root.addEventListener("mouseup",l),s.root.addEventListener("dragstart",l),s.root.addEventListener("mousemove",o)}function edt(s,t,r){if(!(s.state.selection instanceof Ri))return null;const{$head:n}=s.state.selection;for(let a=n.depth-1;a>=0;a--){const i=n.node(a);if((r<0?n.index(a):n.indexAfter(a))!=(r<0?0:i.childCount))return null;if(i.type.spec.tableRole=="cell"||i.type.spec.tableRole=="header_cell"){const l=n.before(a),o=t=="vert"?r>0?"down":"up":r>0?"right":"left";return s.endOfTextblock(o)?l:null}}return null}function UBe(s,t){for(;t&&t!=s.dom;t=t.parentNode)if(t.nodeName=="TD"||t.nodeName=="TH")return t;return null}function c_e(s,t){const r=s.posAtCoords({left:t.clientX,top:t.clientY});if(!r)return null;let{inside:n,pos:a}=r;return n>=0&&wA(s.state.doc.resolve(n))||wA(s.state.doc.resolve(a))}var XJt=class{constructor(t,r){this.node=t,this.defaultCellMinWidth=r,this.dom=document.createElement("div"),this.dom.className="tableWrapper",this.table=this.dom.appendChild(document.createElement("table")),this.table.style.setProperty("--default-cell-min-width",`${r}px`),this.colgroup=this.table.appendChild(document.createElement("colgroup")),Nke(t,this.colgroup,this.table,r),this.contentDOM=this.table.appendChild(document.createElement("tbody"))}update(t){return t.type!=this.node.type?!1:(this.node=t,Nke(t,this.colgroup,this.table,this.defaultCellMinWidth),!0)}ignoreMutation(t){return t.type=="attributes"&&(t.target==this.table||this.colgroup.contains(t.target))}};function Nke(s,t,r,n,a,i){let l=0,o=!0,c=t.firstChild;const d=s.firstChild;if(d){for(let m=0,p=0;mnew n(m,r,p)),new JJt(-1,!1)},apply(l,o){return o.apply(l)}},props:{attributes:l=>{const o=n0.getState(l);return o&&o.activeHandle>-1?{class:"resize-cursor"}:{}},handleDOMEvents:{mousemove:(l,o)=>{ees(l,o,s,a)},mouseleave:l=>{tes(l)},mousedown:(l,o)=>{ses(l,o,t,r)}},decorations:l=>{const o=n0.getState(l);if(o&&o.activeHandle>-1)return oes(l,o.activeHandle)},nodeViews:{}}});return i}var JJt=class Aue{constructor(t,r){this.activeHandle=t,this.dragging=r}apply(t){const r=this,n=t.getMeta(n0);if(n&&n.setHandle!=null)return new Aue(n.setHandle,!1);if(n&&n.setDragging!==void 0)return new Aue(r.activeHandle,n.setDragging);if(r.activeHandle>-1&&t.docChanged){let a=t.mapping.map(r.activeHandle,-1);return wke(t.doc.resolve(a))||(a=-1),new Aue(a,r.dragging)}return r}};function ees(s,t,r,n){if(!s.editable)return;const a=n0.getState(s.state);if(a&&!a.dragging){const i=nes(t.target);let l=-1;if(i){const{left:o,right:c}=i.getBoundingClientRect();t.clientX-o<=r?l=qBe(s,t,"left",r):c-t.clientX<=r&&(l=qBe(s,t,"right",r))}if(l!=a.activeHandle){if(!n&&l!==-1){const o=s.state.doc.resolve(l),c=o.node(-1),d=$u.get(c),h=o.start(-1);if(d.colCount(o.pos-h)+o.nodeAfter.attrs.colspan-1==d.width-1)return}tdt(s,l)}}}function tes(s){if(!s.editable)return;const t=n0.getState(s.state);t&&t.activeHandle>-1&&!t.dragging&&tdt(s,-1)}function ses(s,t,r,n){var a;if(!s.editable)return!1;const i=(a=s.dom.ownerDocument.defaultView)!==null&&a!==void 0?a:window,l=n0.getState(s.state);if(!l||l.activeHandle==-1||l.dragging)return!1;const o=s.state.doc.nodeAt(l.activeHandle),c=res(s,l.activeHandle,o.attrs);s.dispatch(s.state.tr.setMeta(n0,{setDragging:{startX:t.clientX,startWidth:c}}));function d(m){i.removeEventListener("mouseup",d),i.removeEventListener("mousemove",h);const p=n0.getState(s.state);p!=null&&p.dragging&&(aes(s,p.activeHandle,VBe(p.dragging,m,r)),s.dispatch(s.state.tr.setMeta(n0,{setDragging:null})))}function h(m){if(!m.which)return d(m);const p=n0.getState(s.state);if(p&&p.dragging){const x=VBe(p.dragging,m,r);HBe(s,p.activeHandle,x,n)}}return HBe(s,l.activeHandle,c,n),i.addEventListener("mouseup",d),i.addEventListener("mousemove",h),t.preventDefault(),!0}function res(s,t,{colspan:r,colwidth:n}){const a=n&&n[n.length-1];if(a)return a;const i=s.domAtPos(t);let l=i.node.childNodes[i.offset].offsetWidth,o=r;if(n)for(let c=0;c{const n=s.nodes[r];n.spec.tableRole&&(t[n.spec.tableRole]=n)}),s.cached.tableNodeTypes=t,t}function hes(s,t,r,n,a){const i=ues(s),l=[],o=[];for(let d=0;d{const{selection:t}=s.state;if(!mes(t))return!1;let r=0;const n=Tct(t.ranges[0].$from,i=>i.type.name==="table");return n==null||n.node.descendants(i=>{if(i.type.name==="table")return!1;["tableCell","tableHeader"].includes(i.type.name)&&(r+=1)}),r===t.ranges.length?(s.commands.deleteTable(),!0):!1},fes=Ap.create({name:"table",addOptions(){return{HTMLAttributes:{},resizable:!1,renderWrapper:!1,handleWidth:5,cellMinWidth:25,View:ces,lastColumnResizable:!0,allowTableNodeSelection:!1}},content:"tableRow+",tableRole:"table",isolating:!0,group:"block",parseHTML(){return[{tag:"table"}]},renderHTML({node:s,HTMLAttributes:t}){const{colgroup:r,tableWidth:n,tableMinWidth:a}=des(s,this.options.cellMinWidth),i=["table",Xd(this.options.HTMLAttributes,t,{style:n?`width: ${n}`:`min-width: ${a}`}),r,["tbody",0]];return this.options.renderWrapper?["div",{class:"tableWrapper"},i]:i},addCommands(){return{insertTable:({rows:s=3,cols:t=3,withHeaderRow:r=!0}={})=>({tr:n,dispatch:a,editor:i})=>{const l=hes(i.schema,s,t,r);if(a){const o=n.selection.from+1;n.replaceSelectionWith(l).scrollIntoView().setSelection(Ri.near(n.doc.resolve(o)))}return!0},addColumnBefore:()=>({state:s,dispatch:t})=>CJt(s,t),addColumnAfter:()=>({state:s,dispatch:t})=>TJt(s,t),deleteColumn:()=>({state:s,dispatch:t})=>AJt(s,t),addRowBefore:()=>({state:s,dispatch:t})=>IJt(s,t),addRowAfter:()=>({state:s,dispatch:t})=>PJt(s,t),deleteRow:()=>({state:s,dispatch:t})=>DJt(s,t),deleteTable:()=>({state:s,dispatch:t})=>UJt(s,t),mergeCells:()=>({state:s,dispatch:t})=>DBe(s,t),splitCell:()=>({state:s,dispatch:t})=>RBe(s,t),toggleHeaderColumn:()=>({state:s,dispatch:t})=>E9("column")(s,t),toggleHeaderRow:()=>({state:s,dispatch:t})=>E9("row")(s,t),toggleHeaderCell:()=>({state:s,dispatch:t})=>zJt(s,t),mergeOrSplit:()=>({state:s,dispatch:t})=>DBe(s,t)?!0:RBe(s,t),setCellAttribute:(s,t)=>({state:r,dispatch:n})=>FJt(s,t)(r,n),goToNextCell:()=>({state:s,dispatch:t})=>FBe(1)(s,t),goToPreviousCell:()=>({state:s,dispatch:t})=>FBe(-1)(s,t),fixTables:()=>({state:s,dispatch:t})=>(t&&Xct(s),!0),setCellSelection:s=>({tr:t,dispatch:r})=>{if(r){const n=dd.create(t.doc,s.anchorCell,s.headCell);t.setSelection(n)}return!0}}},addKeyboardShortcuts(){return{Tab:()=>this.editor.commands.goToNextCell()?!0:this.editor.can().addRowAfter()?this.editor.chain().addRowAfter().goToNextCell().run():!1,"Shift-Tab":()=>this.editor.commands.goToPreviousCell(),Backspace:dq,"Mod-Backspace":dq,Delete:dq,"Mod-Delete":dq}},addProseMirrorPlugins(){return[...this.options.resizable&&this.editor.isEditable?[QJt({handleWidth:this.options.handleWidth,cellMinWidth:this.options.cellMinWidth,defaultCellMinWidth:this.options.cellMinWidth,View:this.options.View,lastColumnResizable:this.options.lastColumnResizable})]:[],les({allowTableNodeSelection:this.options.allowTableNodeSelection})]},extendNodeSchema(s){const t={name:s.name,options:s.options,storage:s.storage};return{tableRole:Fo(si(s,"tableRole",t))}}}),pes=Ap.create({name:"tableRow",addOptions(){return{HTMLAttributes:{}}},content:"(tableCell | tableHeader)*",tableRole:"row",parseHTML(){return[{tag:"tr"}]},renderHTML({HTMLAttributes:s}){return["tr",Xd(this.options.HTMLAttributes,s),0]}}),ges=Ap.create({name:"tableCell",addOptions(){return{HTMLAttributes:{}}},content:"block+",addAttributes(){return{colspan:{default:1},rowspan:{default:1},colwidth:{default:null,parseHTML:s=>{const t=s.getAttribute("colwidth");return t?t.split(",").map(n=>parseInt(n,10)):null}}}},tableRole:"cell",isolating:!0,parseHTML(){return[{tag:"td"}]},renderHTML({HTMLAttributes:s}){return["td",Xd(this.options.HTMLAttributes,s),0]}}),xes=Ap.create({name:"tableHeader",addOptions(){return{HTMLAttributes:{}}},content:"block+",addAttributes(){return{colspan:{default:1},rowspan:{default:1},colwidth:{default:null,parseHTML:s=>{const t=s.getAttribute("colwidth");return t?t.split(",").map(n=>parseInt(n,10)):null}}}},tableRole:"header_cell",isolating:!0,parseHTML(){return[{tag:"th"}]},renderHTML({HTMLAttributes:s}){return["th",Xd(this.options.HTMLAttributes,s),0]}});function R1({content:s,onChange:t,placeholder:r="Enter content...",minHeight:n="150px",compact:a=!1}){const[i,l]=S.useState(!1),[o,c]=S.useState(""),[d,h]=S.useState(!0),m=XTe({extensions:[JTe,cEe.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline"}}),dEe.configure({types:["heading","paragraph"]}),uEe,uJt.extend({addAttributes(){var _;return{...(_=this.parent)==null?void 0:_.call(this),width:{default:null},height:{default:null},style:{default:null}}}}).configure({inline:!0,allowBase64:!0}),fes.extend({addAttributes(){var _;return{...(_=this.parent)==null?void 0:_.call(this),style:{default:null},width:{default:null},cellpadding:{default:null},cellspacing:{default:null},border:{default:null}}}}).configure({resizable:!1}),pes.extend({addAttributes(){var _;return{...(_=this.parent)==null?void 0:_.call(this),style:{default:null}}}}),ges.extend({addAttributes(){var _;return{...(_=this.parent)==null?void 0:_.call(this),style:{default:null},width:{default:null},colspan:{default:1},rowspan:{default:1},valign:{default:null}}}}),xes.extend({addAttributes(){var _;return{...(_=this.parent)==null?void 0:_.call(this),style:{default:null},width:{default:null},colspan:{default:1},rowspan:{default:1}}}})],content:s,onUpdate:({editor:_})=>{t(_.getHTML())},editorProps:{attributes:{class:"outline-none","data-placeholder":r},handlePaste:(_,b)=>{var k;const j=(k=b.clipboardData)==null?void 0:k.items;if(!j)return!1;for(const T of Array.from(j))if(T.type.startsWith("image/")){b.preventDefault();const E=T.getAsFile();if(!E)continue;const A=new FileReader;return A.onload=D=>{var z;const R=(z=D.target)==null?void 0:z.result;_.dispatch(_.state.tr.replaceSelectionWith(_.state.schema.nodes.image.create({src:R})))},A.readAsDataURL(E),!0}return!1}}});S.useEffect(()=>{m&&s!==m.getHTML()&&m.commands.setContent(s)},[s,m]);const p=()=>{if(!m)return;const _=m.getAttributes("link").href||"",b=m.getAttributes("link").target;c(_),h(b==="_blank"),l(!0)},x=()=>{m&&(o===""?m.chain().focus().extendMarkRange("link").unsetLink().run():m.chain().focus().extendMarkRange("link").setLink({href:o,target:d?"_blank":null,rel:d?"noopener noreferrer nofollow":null}).run(),l(!1),c(""))},y=()=>{m&&m.chain().focus().extendMarkRange("link").unsetLink().run()};return m?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-0.5 p-2 border-b bg-muted/30",children:[e.jsx(H,{type:"button",variant:"ghost",size:"sm",onClick:()=>m.chain().focus().toggleHeading({level:1}).run(),className:m.isActive("heading",{level:1})?"bg-muted":"",title:"Heading 1",children:e.jsx(OI,{className:"h-4 w-4"})}),e.jsx(H,{type:"button",variant:"ghost",size:"sm",onClick:()=>m.chain().focus().toggleHeading({level:2}).run(),className:m.isActive("heading",{level:2})?"bg-muted":"",title:"Heading 2",children:e.jsx(FI,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(H,{type:"button",variant:"ghost",size:"sm",onClick:()=>m.chain().focus().toggleBold().run(),className:m.isActive("bold")?"bg-muted":"",title:"Bold",children:e.jsx(Ok,{className:"h-4 w-4"})}),e.jsx(H,{type:"button",variant:"ghost",size:"sm",onClick:()=>m.chain().focus().toggleItalic().run(),className:m.isActive("italic")?"bg-muted":"",title:"Italic",children:e.jsx(qk,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(H,{type:"button",variant:"ghost",size:"sm",onClick:()=>m.chain().focus().toggleBulletList().run(),className:m.isActive("bulletList")?"bg-muted":"",title:"Bullet List",children:e.jsx(Vf,{className:"h-4 w-4"})}),e.jsx(H,{type:"button",variant:"ghost",size:"sm",onClick:()=>m.chain().focus().toggleOrderedList().run(),className:m.isActive("orderedList")?"bg-muted":"",title:"Numbered List",children:e.jsx(b1,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(H,{type:"button",variant:"ghost",size:"sm",onClick:()=>m.chain().focus().setTextAlign("left").run(),className:m.isActive({textAlign:"left"})?"bg-muted":"",title:"Align Left",children:e.jsx(uE,{className:"h-4 w-4"})}),e.jsx(H,{type:"button",variant:"ghost",size:"sm",onClick:()=>m.chain().focus().setTextAlign("center").run(),className:m.isActive({textAlign:"center"})?"bg-muted":"",title:"Align Center",children:e.jsx(dE,{className:"h-4 w-4"})}),e.jsx(H,{type:"button",variant:"ghost",size:"sm",onClick:()=>m.chain().focus().setTextAlign("right").run(),className:m.isActive({textAlign:"right"})?"bg-muted":"",title:"Align Right",children:e.jsx(hE,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(H,{type:"button",variant:"ghost",size:"sm",onClick:p,className:m.isActive("link")?"bg-muted":"",title:"Add Link",children:e.jsx(Jo,{className:"h-4 w-4"})}),m.isActive("link")&&e.jsx(H,{type:"button",variant:"ghost",size:"sm",onClick:y,title:"Remove Link",children:e.jsx(Jo,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(H,{type:"button",variant:"ghost",size:"sm",onClick:()=>m.chain().focus().undo().run(),disabled:!m.can().undo(),title:"Undo",children:e.jsx(Xk,{className:"h-4 w-4"})}),e.jsx(H,{type:"button",variant:"ghost",size:"sm",onClick:()=>m.chain().focus().redo().run(),disabled:!m.can().redo(),title:"Redo",children:e.jsx(Yk,{className:"h-4 w-4"})})]}),e.jsx(YTe,{editor:m,className:"prose prose-sm max-w-none p-3 focus:outline-none [&_.ProseMirror]:outline-none [&_.ProseMirror_img]:max-w-none [&_.ProseMirror_table]:border-none [&_.ProseMirror_table]:border-collapse [&_.ProseMirror_td]:border-none [&_.ProseMirror_td]:p-0 [&_.ProseMirror_td]:align-top [&_.ProseMirror_th]:border-none [&_.ProseMirror_th]:p-0 [&_.ProseMirror_tr]:border-none",style:{minHeight:n}})]}),e.jsx(bs,{open:i,onOpenChange:l,children:e.jsxs(vs,{className:"sm:max-w-md",children:[e.jsx(Cs,{children:e.jsx(Ns,{children:"Insert Link"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"link-url",children:"URL"}),e.jsx(Se,{id:"link-url",value:o,onChange:_=>c(_.target.value),placeholder:"https://example.com"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Or,{id:"link-new-tab",checked:d,onCheckedChange:h}),e.jsx(ue,{htmlFor:"link-new-tab",children:"Open in new tab"})]})]}),e.jsxs(wn,{children:[e.jsx(H,{type:"button",variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx(H,{type:"button",onClick:x,children:o?"Apply Link":"Remove Link"})]})]})})]}):null}var yes=Object.defineProperty,ves=(s,t,r)=>t in s?yes(s,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):s[t]=r,$d=(s,t,r)=>ves(s,typeof t!="symbol"?t+"":t,r);const Hme={x:0,y:0,width:0,height:0,unit:"px"},x6=(s,t,r)=>Math.min(Math.max(s,t),r),bes=(...s)=>s.filter(t=>t&&typeof t=="string").join(" "),KBe=(s,t)=>s===t||s.width===t.width&&s.height===t.height&&s.x===t.x&&s.y===t.y&&s.unit===t.unit;function _es(s,t,r,n){const a=$b(s,r,n);return s.width&&(a.height=a.width/t),s.height&&(a.width=a.height*t),a.y+a.height>n&&(a.height=n-a.y,a.width=a.height*t),a.x+a.width>r&&(a.width=r-a.x,a.height=a.width/t),s.unit==="%"?GN(a,r,n):a}function wes(s,t,r){const n=$b(s,t,r);return n.x=(t-n.width)/2,n.y=(r-n.height)/2,s.unit==="%"?GN(n,t,r):n}function GN(s,t,r){return s.unit==="%"?{...Hme,...s,unit:"%"}:{unit:"%",x:s.x?s.x/t*100:0,y:s.y?s.y/r*100:0,width:s.width?s.width/t*100:0,height:s.height?s.height/r*100:0}}function $b(s,t,r){return s.unit?s.unit==="px"?{...Hme,...s,unit:"px"}:{unit:"px",x:s.x?s.x*t/100:0,y:s.y?s.y*r/100:0,width:s.width?s.width*t/100:0,height:s.height?s.height*r/100:0}:{...Hme,...s,unit:"px"}}function YBe(s,t,r,n,a,i=0,l=0,o=n,c=a){const d={...s};let h=Math.min(i,n),m=Math.min(l,a),p=Math.min(o,n),x=Math.min(c,a);t&&(t>1?(h=l?l*t:h,m=h/t,p=o*t):(m=i?i/t:m,h=m*t,x=c/t)),d.y<0&&(d.height=Math.max(d.height+d.y,m),d.y=0),d.x<0&&(d.width=Math.max(d.width+d.x,h),d.x=0);const y=n-(d.x+d.width);y<0&&(d.x=Math.min(d.x,n-h),d.width+=y);const _=a-(d.y+d.height);if(_<0&&(d.y=Math.min(d.y,a-m),d.height+=_),d.widthp&&((r==="sw"||r=="nw")&&(d.x-=p-d.width),d.width=p),d.height>x&&((r==="nw"||r=="ne")&&(d.y-=x-d.height),d.height=x),t){const b=d.width/d.height;if(bt){const j=Math.max(d.height*t,h);(r==="sw"||r=="nw")&&(d.x-=j-d.width),d.width=j}}return d}function jes(s,t,r,n){const a={...s};return t==="ArrowLeft"?n==="nw"?(a.x-=r,a.y-=r,a.width+=r,a.height+=r):n==="w"?(a.x-=r,a.width+=r):n==="sw"?(a.x-=r,a.width+=r,a.height+=r):n==="ne"?(a.y+=r,a.width-=r,a.height-=r):n==="e"?a.width-=r:n==="se"&&(a.width-=r,a.height-=r):t==="ArrowRight"&&(n==="nw"?(a.x+=r,a.y+=r,a.width-=r,a.height-=r):n==="w"?(a.x+=r,a.width-=r):n==="sw"?(a.x+=r,a.width-=r,a.height-=r):n==="ne"?(a.y-=r,a.width+=r,a.height+=r):n==="e"?a.width+=r:n==="se"&&(a.width+=r,a.height+=r)),t==="ArrowUp"?n==="nw"?(a.x-=r,a.y-=r,a.width+=r,a.height+=r):n==="n"?(a.y-=r,a.height+=r):n==="ne"?(a.y-=r,a.width+=r,a.height+=r):n==="sw"?(a.x+=r,a.width-=r,a.height-=r):n==="s"?a.height-=r:n==="se"&&(a.width-=r,a.height-=r):t==="ArrowDown"&&(n==="nw"?(a.x+=r,a.y+=r,a.width-=r,a.height-=r):n==="n"?(a.y+=r,a.height-=r):n==="ne"?(a.y+=r,a.width-=r,a.height-=r):n==="sw"?(a.x-=r,a.width+=r,a.height+=r):n==="s"?a.height+=r:n==="se"&&(a.width+=r,a.height+=r)),a}const y6={capture:!0,passive:!1};let Nes=0;const DN=class Wv extends S.PureComponent{constructor(){super(...arguments),$d(this,"docMoveBound",!1),$d(this,"mouseDownOnCrop",!1),$d(this,"dragStarted",!1),$d(this,"evData",{startClientX:0,startClientY:0,startCropX:0,startCropY:0,clientX:0,clientY:0,isResize:!0}),$d(this,"componentRef",S.createRef()),$d(this,"mediaRef",S.createRef()),$d(this,"resizeObserver"),$d(this,"initChangeCalled",!1),$d(this,"instanceId",`rc-${Nes++}`),$d(this,"state",{cropIsActive:!1,newCropIsBeingDrawn:!1}),$d(this,"onCropPointerDown",t=>{const{crop:r,disabled:n}=this.props,a=this.getBox();if(!r)return;const i=$b(r,a.width,a.height);if(n)return;t.cancelable&&t.preventDefault(),this.bindDocMove(),this.componentRef.current.focus({preventScroll:!0});const l=t.target.dataset.ord,o=!!l;let c=t.clientX,d=t.clientY,h=i.x,m=i.y;if(l){const p=t.clientX-a.x,x=t.clientY-a.y;let y=0,_=0;l==="ne"||l=="e"?(y=p-(i.x+i.width),_=x-i.y,h=i.x,m=i.y+i.height):l==="se"||l==="s"?(y=p-(i.x+i.width),_=x-(i.y+i.height),h=i.x,m=i.y):l==="sw"||l=="w"?(y=p-i.x,_=x-(i.y+i.height),h=i.x+i.width,m=i.y):(l==="nw"||l=="n")&&(y=p-i.x,_=x-i.y,h=i.x+i.width,m=i.y+i.height),c=h+a.x+y,d=m+a.y+_}this.evData={startClientX:c,startClientY:d,startCropX:h,startCropY:m,clientX:t.clientX,clientY:t.clientY,isResize:o,ord:l},this.mouseDownOnCrop=!0,this.setState({cropIsActive:!0})}),$d(this,"onComponentPointerDown",t=>{const{crop:r,disabled:n,locked:a,keepSelection:i,onChange:l}=this.props,o=this.getBox();if(n||a||i&&r)return;t.cancelable&&t.preventDefault(),this.bindDocMove(),this.componentRef.current.focus({preventScroll:!0});const c=t.clientX-o.x,d=t.clientY-o.y,h={unit:"px",x:c,y:d,width:0,height:0};this.evData={startClientX:t.clientX,startClientY:t.clientY,startCropX:c,startCropY:d,clientX:t.clientX,clientY:t.clientY,isResize:!0},this.mouseDownOnCrop=!0,l($b(h,o.width,o.height),GN(h,o.width,o.height)),this.setState({cropIsActive:!0,newCropIsBeingDrawn:!0})}),$d(this,"onDocPointerMove",t=>{const{crop:r,disabled:n,onChange:a,onDragStart:i}=this.props,l=this.getBox();if(n||!r||!this.mouseDownOnCrop)return;t.cancelable&&t.preventDefault(),this.dragStarted||(this.dragStarted=!0,i&&i(t));const{evData:o}=this;o.clientX=t.clientX,o.clientY=t.clientY;let c;o.isResize?c=this.resizeCrop():c=this.dragCrop(),KBe(r,c)||a($b(c,l.width,l.height),GN(c,l.width,l.height))}),$d(this,"onComponentKeyDown",t=>{const{crop:r,disabled:n,onChange:a,onComplete:i}=this.props;if(n)return;const l=t.key;let o=!1;if(!r)return;const c=this.getBox(),d=this.makePixelCrop(c),h=(navigator.platform.match("Mac")?t.metaKey:t.ctrlKey)?Wv.nudgeStepLarge:t.shiftKey?Wv.nudgeStepMedium:Wv.nudgeStep;if(l==="ArrowLeft"?(d.x-=h,o=!0):l==="ArrowRight"?(d.x+=h,o=!0):l==="ArrowUp"?(d.y-=h,o=!0):l==="ArrowDown"&&(d.y+=h,o=!0),o){t.cancelable&&t.preventDefault(),d.x=x6(d.x,0,c.width-d.width),d.y=x6(d.y,0,c.height-d.height);const m=$b(d,c.width,c.height),p=GN(d,c.width,c.height);a(m,p),i&&i(m,p)}}),$d(this,"onHandlerKeyDown",(t,r)=>{const{aspect:n=0,crop:a,disabled:i,minWidth:l=0,minHeight:o=0,maxWidth:c,maxHeight:d,onChange:h,onComplete:m}=this.props,p=this.getBox();if(i||!a)return;if(t.key==="ArrowUp"||t.key==="ArrowDown"||t.key==="ArrowLeft"||t.key==="ArrowRight")t.stopPropagation(),t.preventDefault();else return;const x=(navigator.platform.match("Mac")?t.metaKey:t.ctrlKey)?Wv.nudgeStepLarge:t.shiftKey?Wv.nudgeStepMedium:Wv.nudgeStep,y=$b(a,p.width,p.height),_=jes(y,t.key,x,r),b=YBe(_,n,r,p.width,p.height,l,o,c,d);if(!KBe(a,b)){const j=GN(b,p.width,p.height);h(b,j),m&&m(b,j)}}),$d(this,"onDocPointerDone",t=>{const{crop:r,disabled:n,onComplete:a,onDragEnd:i}=this.props,l=this.getBox();this.unbindDocMove(),!(n||!r)&&this.mouseDownOnCrop&&(this.mouseDownOnCrop=!1,this.dragStarted=!1,i&&i(t),a&&a($b(r,l.width,l.height),GN(r,l.width,l.height)),this.setState({cropIsActive:!1,newCropIsBeingDrawn:!1}))}),$d(this,"onDragFocus",()=>{var t;(t=this.componentRef.current)==null||t.scrollTo(0,0)})}get document(){return document}getBox(){const t=this.mediaRef.current;if(!t)return{x:0,y:0,width:0,height:0};const{x:r,y:n,width:a,height:i}=t.getBoundingClientRect();return{x:r,y:n,width:a,height:i}}componentDidUpdate(t){const{crop:r,onComplete:n}=this.props;if(n&&!t.crop&&r){const{width:a,height:i}=this.getBox();a&&i&&n($b(r,a,i),GN(r,a,i))}}componentWillUnmount(){this.resizeObserver&&this.resizeObserver.disconnect(),this.unbindDocMove()}bindDocMove(){this.docMoveBound||(this.document.addEventListener("pointermove",this.onDocPointerMove,y6),this.document.addEventListener("pointerup",this.onDocPointerDone,y6),this.document.addEventListener("pointercancel",this.onDocPointerDone,y6),this.docMoveBound=!0)}unbindDocMove(){this.docMoveBound&&(this.document.removeEventListener("pointermove",this.onDocPointerMove,y6),this.document.removeEventListener("pointerup",this.onDocPointerDone,y6),this.document.removeEventListener("pointercancel",this.onDocPointerDone,y6),this.docMoveBound=!1)}getCropStyle(){const{crop:t}=this.props;if(t)return{top:`${t.y}${t.unit}`,left:`${t.x}${t.unit}`,width:`${t.width}${t.unit}`,height:`${t.height}${t.unit}`}}dragCrop(){const{evData:t}=this,r=this.getBox(),n=this.makePixelCrop(r),a=t.clientX-t.startClientX,i=t.clientY-t.startClientY;return n.x=x6(t.startCropX+a,0,r.width-n.width),n.y=x6(t.startCropY+i,0,r.height-n.height),n}getPointRegion(t,r,n,a){const{evData:i}=this,l=i.clientX-t.x,o=i.clientY-t.y;let c;a&&r?c=r==="nw"||r==="n"||r==="ne":c=o1?i?[i,i/r]:[l*r,l]:l?[l*r,l]:[i,i/r]}resizeCrop(){const{evData:t}=this,{aspect:r=0,maxWidth:n,maxHeight:a}=this.props,i=this.getBox(),[l,o]=this.resolveMinDimensions(i,r,this.props.minWidth,this.props.minHeight);let c=this.makePixelCrop(i);const d=this.getPointRegion(i,t.ord,l,o),h=t.ord||d;let m=t.clientX-t.startClientX,p=t.clientY-t.startClientY;(l&&h==="nw"||h==="w"||h==="sw")&&(m=Math.min(m,-l)),(o&&h==="nw"||h==="n"||h==="ne")&&(p=Math.min(p,-o));const x={unit:"px",x:0,y:0,width:0,height:0};d==="ne"?(x.x=t.startCropX,x.width=m,r?(x.height=x.width/r,x.y=t.startCropY-x.height):(x.height=Math.abs(p),x.y=t.startCropY-x.height)):d==="se"?(x.x=t.startCropX,x.y=t.startCropY,x.width=m,r?x.height=x.width/r:x.height=p):d==="sw"?(x.x=t.startCropX+m,x.y=t.startCropY,x.width=Math.abs(m),r?x.height=x.width/r:x.height=p):d==="nw"&&(x.x=t.startCropX+m,x.width=Math.abs(m),r?(x.height=x.width/r,x.y=t.startCropY-x.height):(x.height=Math.abs(p),x.y=t.startCropY+p));const y=YBe(x,r,d,i.width,i.height,l,o,n,a);return r||Wv.xyOrds.indexOf(h)>-1?c=y:Wv.xOrds.indexOf(h)>-1?(c.x=y.x,c.width=y.width):Wv.yOrds.indexOf(h)>-1&&(c.y=y.y,c.height=y.height),c.x=x6(c.x,0,i.width-c.width),c.y=x6(c.y,0,i.height-c.height),c}renderCropSelection(){const{ariaLabels:t=Wv.defaultProps.ariaLabels,disabled:r,locked:n,renderSelectionAddon:a,ruleOfThirds:i,crop:l}=this.props,o=this.getCropStyle();if(l)return Nt.createElement("div",{style:o,className:"ReactCrop__crop-selection",onPointerDown:this.onCropPointerDown,"aria-label":t.cropArea,tabIndex:0,onKeyDown:this.onComponentKeyDown,role:"group"},!r&&!n&&Nt.createElement("div",{className:"ReactCrop__drag-elements",onFocus:this.onDragFocus},Nt.createElement("div",{className:"ReactCrop__drag-bar ord-n","data-ord":"n"}),Nt.createElement("div",{className:"ReactCrop__drag-bar ord-e","data-ord":"e"}),Nt.createElement("div",{className:"ReactCrop__drag-bar ord-s","data-ord":"s"}),Nt.createElement("div",{className:"ReactCrop__drag-bar ord-w","data-ord":"w"}),Nt.createElement("div",{className:"ReactCrop__drag-handle ord-nw","data-ord":"nw",tabIndex:0,"aria-label":t.nwDragHandle,onKeyDown:c=>this.onHandlerKeyDown(c,"nw"),role:"button"}),Nt.createElement("div",{className:"ReactCrop__drag-handle ord-n","data-ord":"n",tabIndex:0,"aria-label":t.nDragHandle,onKeyDown:c=>this.onHandlerKeyDown(c,"n"),role:"button"}),Nt.createElement("div",{className:"ReactCrop__drag-handle ord-ne","data-ord":"ne",tabIndex:0,"aria-label":t.neDragHandle,onKeyDown:c=>this.onHandlerKeyDown(c,"ne"),role:"button"}),Nt.createElement("div",{className:"ReactCrop__drag-handle ord-e","data-ord":"e",tabIndex:0,"aria-label":t.eDragHandle,onKeyDown:c=>this.onHandlerKeyDown(c,"e"),role:"button"}),Nt.createElement("div",{className:"ReactCrop__drag-handle ord-se","data-ord":"se",tabIndex:0,"aria-label":t.seDragHandle,onKeyDown:c=>this.onHandlerKeyDown(c,"se"),role:"button"}),Nt.createElement("div",{className:"ReactCrop__drag-handle ord-s","data-ord":"s",tabIndex:0,"aria-label":t.sDragHandle,onKeyDown:c=>this.onHandlerKeyDown(c,"s"),role:"button"}),Nt.createElement("div",{className:"ReactCrop__drag-handle ord-sw","data-ord":"sw",tabIndex:0,"aria-label":t.swDragHandle,onKeyDown:c=>this.onHandlerKeyDown(c,"sw"),role:"button"}),Nt.createElement("div",{className:"ReactCrop__drag-handle ord-w","data-ord":"w",tabIndex:0,"aria-label":t.wDragHandle,onKeyDown:c=>this.onHandlerKeyDown(c,"w"),role:"button"})),a&&Nt.createElement("div",{className:"ReactCrop__selection-addon",onPointerDown:c=>c.stopPropagation()},a(this.state)),i&&Nt.createElement(Nt.Fragment,null,Nt.createElement("div",{className:"ReactCrop__rule-of-thirds-hz"}),Nt.createElement("div",{className:"ReactCrop__rule-of-thirds-vt"})))}makePixelCrop(t){const r={...Hme,...this.props.crop||{}};return $b(r,t.width,t.height)}render(){const{aspect:t,children:r,circularCrop:n,className:a,crop:i,disabled:l,locked:o,style:c,ruleOfThirds:d}=this.props,{cropIsActive:h,newCropIsBeingDrawn:m}=this.state,p=i?this.renderCropSelection():null,x=bes("ReactCrop",a,h&&"ReactCrop--active",l&&"ReactCrop--disabled",o&&"ReactCrop--locked",m&&"ReactCrop--new-crop",i&&t&&"ReactCrop--fixed-aspect",i&&n&&"ReactCrop--circular-crop",i&&d&&"ReactCrop--rule-of-thirds",!this.dragStarted&&i&&!i.width&&!i.height&&"ReactCrop--invisible-crop",n&&"ReactCrop--no-animate");return Nt.createElement("div",{ref:this.componentRef,className:x,style:c},Nt.createElement("div",{ref:this.mediaRef,className:"ReactCrop__child-wrapper",onPointerDown:this.onComponentPointerDown},r),i?Nt.createElement("svg",{className:"ReactCrop__crop-mask",width:"100%",height:"100%"},Nt.createElement("defs",null,Nt.createElement("mask",{id:`hole-${this.instanceId}`},Nt.createElement("rect",{width:"100%",height:"100%",fill:"white"}),n?Nt.createElement("ellipse",{cx:`${i.x+i.width/2}${i.unit}`,cy:`${i.y+i.height/2}${i.unit}`,rx:`${i.width/2}${i.unit}`,ry:`${i.height/2}${i.unit}`,fill:"black"}):Nt.createElement("rect",{x:`${i.x}${i.unit}`,y:`${i.y}${i.unit}`,width:`${i.width}${i.unit}`,height:`${i.height}${i.unit}`,fill:"black"}))),Nt.createElement("rect",{fill:"black",fillOpacity:.5,width:"100%",height:"100%",mask:`url(#hole-${this.instanceId})`})):void 0,p)}};$d(DN,"xOrds",["e","w"]),$d(DN,"yOrds",["n","s"]),$d(DN,"xyOrds",["nw","ne","se","sw"]),$d(DN,"nudgeStep",1),$d(DN,"nudgeStepMedium",10),$d(DN,"nudgeStepLarge",100),$d(DN,"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 kes=DN;var sdt=["PageUp","PageDown"],rdt=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],ndt={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},_8="Slider",[Ske,Ses,Ces]=DB(_8),[adt,WZs]=_u(_8,[Ces]),[Tes,yxe]=adt(_8),idt=S.forwardRef((s,t)=>{const{name:r,min:n=0,max:a=100,step:i=1,orientation:l="horizontal",disabled:o=!1,minStepsBetweenThumbs:c=0,defaultValue:d=[n],value:h,onValueChange:m=()=>{},onValueCommit:p=()=>{},inverted:x=!1,form:y,..._}=s,b=S.useRef(new Set),j=S.useRef(0),T=l==="horizontal"?Ees:Aes,[E=[],A]=af({prop:h,defaultProp:d,onChange:ee=>{var J;(J=[...b.current][j.current])==null||J.focus(),m(ee)}}),D=S.useRef(E);function R(ee){const Z=Des(E,ee);$(ee,Z)}function z(ee){$(ee,j.current)}function O(){const ee=D.current[j.current];E[j.current]!==ee&&p(E)}function $(ee,Z,{commit:J}={commit:!1}){const K=Bes(i),re=zes(Math.round((ee-n)/i)*i+n,K),ie=c9(re,[n,a]);A((ce=[])=>{const ne=Pes(ce,ie,Z);if(Fes(ne,c*i)){j.current=ne.indexOf(ie);const le=String(ne)!==String(ce);return le&&J&&p(ne),le?ne:ce}else return ce})}return e.jsx(Tes,{scope:s.__scopeSlider,name:r,disabled:o,min:n,max:a,valueIndexToChangeRef:j,thumbs:b.current,values:E,orientation:l,form:y,children:e.jsx(Ske.Provider,{scope:s.__scopeSlider,children:e.jsx(Ske.Slot,{scope:s.__scopeSlider,children:e.jsx(T,{"aria-disabled":o,"data-disabled":o?"":void 0,..._,ref:t,onPointerDown:an(_.onPointerDown,()=>{o||(D.current=E)}),min:n,max:a,inverted:x,onSlideStart:o?void 0:R,onSlideMove:o?void 0:z,onSlideEnd:o?void 0:O,onHomeKeyDown:()=>!o&&$(n,0,{commit:!0}),onEndKeyDown:()=>!o&&$(a,E.length-1,{commit:!0}),onStepKeyDown:({event:ee,direction:Z})=>{if(!o){const re=sdt.includes(ee.key)||ee.shiftKey&&rdt.includes(ee.key)?10:1,ie=j.current,ce=E[ie],ne=i*re*Z;$(ce+ne,ie,{commit:!0})}}})})})})});idt.displayName=_8;var[odt,ldt]=adt(_8,{startEdge:"left",endEdge:"right",size:"width",direction:1}),Ees=S.forwardRef((s,t)=>{const{min:r,max:n,dir:a,inverted:i,onSlideStart:l,onSlideMove:o,onSlideEnd:c,onStepKeyDown:d,...h}=s,[m,p]=S.useState(null),x=_i(t,T=>p(T)),y=S.useRef(void 0),_=RS(a),b=_==="ltr",j=b&&!i||!b&&i;function k(T){const E=y.current||m.getBoundingClientRect(),A=[0,E.width],R=mEe(A,j?[r,n]:[n,r]);return y.current=E,R(T-E.left)}return e.jsx(odt,{scope:s.__scopeSlider,startEdge:j?"left":"right",endEdge:j?"right":"left",direction:j?1:-1,size:"width",children:e.jsx(cdt,{dir:_,"data-orientation":"horizontal",...h,ref:x,style:{...h.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:T=>{const E=k(T.clientX);l==null||l(E)},onSlideMove:T=>{const E=k(T.clientX);o==null||o(E)},onSlideEnd:()=>{y.current=void 0,c==null||c()},onStepKeyDown:T=>{const A=ndt[j?"from-left":"from-right"].includes(T.key);d==null||d({event:T,direction:A?-1:1})}})})}),Aes=S.forwardRef((s,t)=>{const{min:r,max:n,inverted:a,onSlideStart:i,onSlideMove:l,onSlideEnd:o,onStepKeyDown:c,...d}=s,h=S.useRef(null),m=_i(t,h),p=S.useRef(void 0),x=!a;function y(_){const b=p.current||h.current.getBoundingClientRect(),j=[0,b.height],T=mEe(j,x?[n,r]:[r,n]);return p.current=b,T(_-b.top)}return e.jsx(odt,{scope:s.__scopeSlider,startEdge:x?"bottom":"top",endEdge:x?"top":"bottom",size:"height",direction:x?1:-1,children:e.jsx(cdt,{"data-orientation":"vertical",...d,ref:m,style:{...d.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:_=>{const b=y(_.clientY);i==null||i(b)},onSlideMove:_=>{const b=y(_.clientY);l==null||l(b)},onSlideEnd:()=>{p.current=void 0,o==null||o()},onStepKeyDown:_=>{const j=ndt[x?"from-bottom":"from-top"].includes(_.key);c==null||c({event:_,direction:j?-1:1})}})})}),cdt=S.forwardRef((s,t)=>{const{__scopeSlider:r,onSlideStart:n,onSlideMove:a,onSlideEnd:i,onHomeKeyDown:l,onEndKeyDown:o,onStepKeyDown:c,...d}=s,h=yxe(_8,r);return e.jsx(Vn.span,{...d,ref:t,onKeyDown:an(s.onKeyDown,m=>{m.key==="Home"?(l(m),m.preventDefault()):m.key==="End"?(o(m),m.preventDefault()):sdt.concat(rdt).includes(m.key)&&(c(m),m.preventDefault())}),onPointerDown:an(s.onPointerDown,m=>{const p=m.target;p.setPointerCapture(m.pointerId),m.preventDefault(),h.thumbs.has(p)?p.focus():n(m)}),onPointerMove:an(s.onPointerMove,m=>{m.target.hasPointerCapture(m.pointerId)&&a(m)}),onPointerUp:an(s.onPointerUp,m=>{const p=m.target;p.hasPointerCapture(m.pointerId)&&(p.releasePointerCapture(m.pointerId),i(m))})})}),ddt="SliderTrack",udt=S.forwardRef((s,t)=>{const{__scopeSlider:r,...n}=s,a=yxe(ddt,r);return e.jsx(Vn.span,{"data-disabled":a.disabled?"":void 0,"data-orientation":a.orientation,...n,ref:t})});udt.displayName=ddt;var Cke="SliderRange",hdt=S.forwardRef((s,t)=>{const{__scopeSlider:r,...n}=s,a=yxe(Cke,r),i=ldt(Cke,r),l=S.useRef(null),o=_i(t,l),c=a.values.length,d=a.values.map(p=>pdt(p,a.min,a.max)),h=c>1?Math.min(...d):0,m=100-Math.max(...d);return e.jsx(Vn.span,{"data-orientation":a.orientation,"data-disabled":a.disabled?"":void 0,...n,ref:o,style:{...s.style,[i.startEdge]:h+"%",[i.endEdge]:m+"%"}})});hdt.displayName=Cke;var Tke="SliderThumb",mdt=S.forwardRef((s,t)=>{const r=Ses(s.__scopeSlider),[n,a]=S.useState(null),i=_i(t,o=>a(o)),l=S.useMemo(()=>n?r().findIndex(o=>o.ref.current===n):-1,[r,n]);return e.jsx(Mes,{...s,ref:i,index:l})}),Mes=S.forwardRef((s,t)=>{const{__scopeSlider:r,index:n,name:a,...i}=s,l=yxe(Tke,r),o=ldt(Tke,r),[c,d]=S.useState(null),h=_i(t,k=>d(k)),m=c?l.form||!!c.closest("form"):!0,p=FB(c),x=l.values[n],y=x===void 0?0:pdt(x,l.min,l.max),_=Les(n,l.values.length),b=p==null?void 0:p[o.size],j=b?Res(b,y,o.direction):0;return S.useEffect(()=>{if(c)return l.thumbs.add(c),()=>{l.thumbs.delete(c)}},[c,l.thumbs]),e.jsxs("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[o.startEdge]:`calc(${y}% + ${j}px)`},children:[e.jsx(Ske.ItemSlot,{scope:s.__scopeSlider,children:e.jsx(Vn.span,{role:"slider","aria-label":s["aria-label"]||_,"aria-valuemin":l.min,"aria-valuenow":x,"aria-valuemax":l.max,"aria-orientation":l.orientation,"data-orientation":l.orientation,"data-disabled":l.disabled?"":void 0,tabIndex:l.disabled?void 0:0,...i,ref:h,style:x===void 0?{display:"none"}:s.style,onFocus:an(s.onFocus,()=>{l.valueIndexToChangeRef.current=n})})}),m&&e.jsx(fdt,{name:a??(l.name?l.name+(l.values.length>1?"[]":""):void 0),form:l.form,value:x},n)]})});mdt.displayName=Tke;var Ies="RadioBubbleInput",fdt=S.forwardRef(({__scopeSlider:s,value:t,...r},n)=>{const a=S.useRef(null),i=_i(a,n),l=QB(t);return S.useEffect(()=>{const o=a.current;if(!o)return;const c=window.HTMLInputElement.prototype,h=Object.getOwnPropertyDescriptor(c,"value").set;if(l!==t&&h){const m=new Event("input",{bubbles:!0});h.call(o,t),o.dispatchEvent(m)}},[l,t]),e.jsx(Vn.input,{style:{display:"none"},...r,ref:i,defaultValue:t})});fdt.displayName=Ies;function Pes(s=[],t,r){const n=[...s];return n[r]=t,n.sort((a,i)=>a-i)}function pdt(s,t,r){const i=100/(r-t)*(s-t);return c9(i,[0,100])}function Les(s,t){return t>2?`Value ${s+1} of ${t}`:t===2?["Minimum","Maximum"][s]:void 0}function Des(s,t){if(s.length===1)return 0;const r=s.map(a=>Math.abs(a-t)),n=Math.min(...r);return r.indexOf(n)}function Res(s,t,r){const n=s/2,i=mEe([0,50],[0,n]);return(n-i(t)*r)*r}function Oes(s){return s.slice(0,-1).map((t,r)=>s[r+1]-t)}function Fes(s,t){if(t>0){const r=Oes(s);return Math.min(...r)>=t}return!0}function mEe(s,t){return r=>{if(s[0]===s[1]||t[0]===t[1])return t[0];const n=(t[1]-t[0])/(s[1]-s[0]);return t[0]+n*(r-s[0])}}function Bes(s){return(String(s).split(".")[1]||"").length}function zes(s,t){const r=Math.pow(10,t);return Math.round(s*r)/r}var gdt=idt,$es=udt,Ues=hdt,qes=mdt;const f1=S.forwardRef(({className:s,...t},r)=>e.jsxs(gdt,{ref:r,className:Ft("relative flex w-full touch-none select-none items-center",s),...t,children:[e.jsx($es,{className:"relative h-2 w-full grow overflow-hidden rounded-full bg-secondary",children:e.jsx(Ues,{className:"absolute h-full bg-primary"})}),e.jsx(qes,{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"})]}));f1.displayName=gdt.displayName;function Ves(s,t,r){return wes(_es({unit:"%",width:90},r,s,t),s,t)}const fEe=({open:s,onClose:t,imageSrc:r,onCropComplete:n,aspectRatio:a=1})=>{const i=S.useRef(null),[l,o]=S.useState(),[c,d]=S.useState(),[h,m]=S.useState(1),[p,x]=S.useState(0),y=S.useCallback(j=>{const{width:k,height:T}=j.currentTarget;o(Ves(k,T,a))},[a]),_=S.useCallback(async()=>{const j=i.current;if(!j||!c)return;const k=document.createElement("canvas"),T=k.getContext("2d");if(!T)return;const E=j.naturalWidth/j.width,A=j.naturalHeight/j.height,D=400;k.width=D,k.height=D,T.imageSmoothingQuality="high";const R=c.x*E,z=c.y*A,O=c.width*E,$=c.height*A,ee=p*Math.PI/180,Z=k.width/2,J=k.height/2;return T.save(),T.translate(Z,J),T.rotate(ee),T.scale(h,h),T.translate(-Z,-J),T.drawImage(j,R,z,O,$,0,0,D,D),T.restore(),new Promise((K,re)=>{k.toBlob(ie=>{ie?K(ie):re(new Error("Canvas is empty"))},"image/jpeg",.95)})},[c,h,p]),b=async()=>{try{const j=await _();j&&(n(j),t())}catch(j){console.error("Error cropping image:",j)}};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-lg",children:[e.jsx(Cs,{children:e.jsx(Ns,{children:"Crop Your Photo"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"relative max-h-[400px] overflow-hidden rounded-lg bg-muted flex items-center justify-center",children:e.jsx(kes,{crop:l,onChange:(j,k)=>o(k),onComplete:j=>d(j),aspect:a,circularCrop:!0,className:"max-h-[400px]",children:e.jsx("img",{ref:i,src:r,alt:"Crop preview",style:{transform:`scale(${h}) rotate(${p}deg)`,maxHeight:"400px",width:"auto"},onLoad:y})})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(JI,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(f1,{value:[h],min:.5,max:3,step:.1,onValueChange:([j])=>m(j),className:"flex-1"}),e.jsx(Qk,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(PE,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(f1,{value:[p],min:-180,max:180,step:1,onValueChange:([j])=>x(j),className:"flex-1"}),e.jsxs("span",{className:"text-sm text-muted-foreground w-12",children:[p,"°"]})]})]})]}),e.jsxs(wn,{children:[e.jsx(H,{variant:"outline",onClick:t,children:"Cancel"}),e.jsx(H,{onClick:b,children:"Save Photo"})]})]})})},Hes=()=>{const{user:s}=Ms(),{toast:t}=li(),[r,n]=S.useState(!1),[a,i]=S.useState(!1),[l,o]=S.useState(null);S.useEffect(()=>{s&&c()},[s]);const c=async()=>{n(!0);try{const{data:m}=await V.from("profiles").select("subscription_status, subscription_product_id, subscription_end_date, is_grandfathered").eq("id",s==null?void 0:s.id).single();m&&o({status:m.subscription_status||"none",productId:m.subscription_product_id,endDate:m.subscription_end_date,isGrandfathered:m.is_grandfathered||!1})}catch(m){console.error("Error loading subscription:",m)}finally{n(!1)}},d=async()=>{i(!0);try{const{data:{session:m}}=await V.auth.getSession();if(!m)throw new Error("Not authenticated");const{data:p,error:x}=await V.functions.invoke("customer-portal",{headers:{Authorization:`Bearer ${m.access_token}`}});if(x)throw x;p!=null&&p.url&&window.open(p.url,"_blank")}catch(m){console.error("Error opening customer portal:",m),t({title:"Error",description:m.message||"Failed to open billing portal",variant:"destructive"})}finally{i(!1)}},h=()=>{if(l!=null&&l.isGrandfathered)return e.jsx(Xe,{className:"bg-amber-500",children:"Grandfathered"});switch(l==null?void 0:l.status){case"active":return e.jsx(Xe,{className:"bg-green-500",children:"Active"});case"trialing":return e.jsx(Xe,{className:"bg-blue-500",children:"Trial"});case"past_due":return e.jsx(Xe,{variant:"destructive",children:"Past Due"});case"canceled":return e.jsx(Xe,{variant:"secondary",children:"Canceled"});default:return e.jsx(Xe,{variant:"outline",children:"No Subscription"})}};return r?e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(u0,{className:"h-5 w-5"}),"Subscription"]})}),e.jsx(Oe,{children:e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(is,{className:"h-6 w-6 animate-spin text-muted-foreground"})})})]}):e.jsxs(ke,{children:[e.jsxs(Ot,{children:[e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(u0,{className:"h-5 w-5"}),"Subscription"]}),e.jsx(Br,{children:"Manage your subscription and billing"})]}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Status"}),e.jsx("div",{className:"mt-1",children:h()})]}),(l==null?void 0:l.endDate)&&l.status==="active"&&e.jsxs("div",{className:"text-right",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Next billing date"}),e.jsx("p",{className:"font-medium",children:new Date(l.endDate).toLocaleDateString()})]})]}),l!=null&&l.isGrandfathered?e.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."}):(l==null?void 0:l.status)==="active"||(l==null?void 0:l.status)==="trialing"?e.jsxs(e.Fragment,{children:[(l==null?void 0:l.status)==="trialing"&&(l==null?void 0:l.endDate)&&e.jsxs("p",{className:"text-sm text-muted-foreground mb-3",children:["Your trial ends on ",new Date(l.endDate).toLocaleDateString(),". After the trial, you'll be charged automatically."]}),e.jsxs(H,{onClick:d,variant:"outline",disabled:a,children:[a?e.jsx(is,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(gn,{className:"mr-2 h-4 w-4"}),"Manage Billing"]})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"You don't have an active subscription."})]})]})},Ges=()=>{const{user:s}=Ms(),t=Fr(),{toast:r}=li(),[n]=Ed(),a=n.get("setup")==="true",i=n.get("reset")==="true",{isSupported:l,isSubscribed:o,isLoading:c,subscribe:d,unsubscribe:h}=Bit(),[m,p]=S.useState(!1),[x,y]=S.useState(""),[_,b]=S.useState(!1),[j,k]=S.useState(!1),[T,E]=S.useState(""),[A,D]=S.useState({name:"",email:"",phone:"",title:"",bio:"",areas_served:"",years_experience:"",instagram_url:"",facebook_url:"",linkedin_url:"",email_signature:"",use_email_signature:!1}),[R,z]=S.useState(!1),[O,$]=S.useState(!1),[ee,Z]=S.useState({newPassword:"",confirmPassword:""});S.useEffect(()=>{s&&J()},[s]),S.useEffect(()=>{i&&s&&setTimeout(()=>{var ne;(ne=document.getElementById("change-password-section"))==null||ne.scrollIntoView({behavior:"smooth",block:"center"})},500)},[i,s]);const J=async()=>{var ne,le,be;if(!(s!=null&&s.id)){console.log("No user ID available yet");return}try{console.log("Loading profile for user:",s.id);const{data:fe,error:je}=await V.from("profiles").select("name, email, phone, digest_opt_out, title, bio, areas_served, years_experience, instagram_url, facebook_url, linkedin_url, email_signature, use_email_signature").eq("id",s.id).maybeSingle();if(je)throw console.error("Profile query error:",je),je;fe?(console.log("Profile loaded successfully:",fe),D({name:fe.name||"",email:fe.email||"",phone:fe.phone||"",title:fe.title||"",bio:fe.bio||"",areas_served:fe.areas_served||"",years_experience:((ne=fe.years_experience)==null?void 0:ne.toString())||"",instagram_url:fe.instagram_url||"",facebook_url:fe.facebook_url||"",linkedin_url:fe.linkedin_url||"",email_signature:fe.email_signature||"",use_email_signature:fe.use_email_signature||!1}),z(fe.digest_opt_out||!1)):(console.warn("No profile found for user"),D({name:((le=s.user_metadata)==null?void 0:le.name)||((be=s.email)==null?void 0:be.split("@")[0])||"",email:s.email||"",phone:"",title:"",bio:"",areas_served:"",years_experience:"",instagram_url:"",facebook_url:"",linkedin_url:"",email_signature:"",use_email_signature:!1}));const{data:ve}=await V.storage.from("avatars").list(`${s.id}`);if(ve&&ve.length>0){const{data:We}=V.storage.from("avatars").getPublicUrl(`${s.id}/${ve[0].name}`);y(We.publicUrl)}}catch(fe){console.error("Error loading profile:",fe),r({title:"Error",description:fe.message||"Failed to load profile",variant:"destructive"})}},K=ne=>{var fe;const le=(fe=ne.target.files)==null?void 0:fe[0];if(!le)return;const be=new FileReader;be.onloadend=()=>{E(be.result),k(!0)},be.readAsDataURL(le),ne.target.value=""},re=async ne=>{if(s){b(!0);try{const{data:le}=await V.storage.from("avatars").list(`${s.id}`);le&&le.length>0&&await V.storage.from("avatars").remove(le.map(Ve=>`${s.id}/${Ve.name}`));const fe=`${s.id}/avatar.jpg`,{error:je}=await V.storage.from("avatars").upload(fe,ne,{upsert:!0,contentType:"image/jpeg"});if(je)throw je;const{data:ve}=V.storage.from("avatars").getPublicUrl(fe),We=ve.publicUrl;y(`${We}?t=${Date.now()}`),await V.from("profiles").update({avatar_url:We}).eq("id",s.id),r({title:"Success",description:"Profile photo updated successfully"})}catch(le){console.error("Error uploading avatar:",le),r({title:"Error",description:le.message||"Failed to upload photo",variant:"destructive"})}finally{b(!1)}}},ie=async()=>{if(!A.name.trim()||!A.email.trim()){r({title:"Error",description:"Name and email are required",variant:"destructive"});return}p(!0);try{const{error:ne}=await V.from("profiles").update({name:A.name.trim(),email:A.email.trim(),phone:A.phone.trim()||null,title:A.title.trim()||null,bio:A.bio.trim()||null,areas_served:A.areas_served.trim()||null,years_experience:A.years_experience?parseInt(A.years_experience):null,instagram_url:A.instagram_url.trim()||null,facebook_url:A.facebook_url.trim()||null,linkedin_url:A.linkedin_url.trim()||null,email_signature:A.email_signature||"",use_email_signature:A.use_email_signature}).eq("id",s==null?void 0:s.id);if(ne)throw ne;r({title:"Success",description:"Profile updated successfully"})}catch(ne){console.error("Error updating profile:",ne),r({title:"Error",description:ne.message||"Failed to update profile",variant:"destructive"})}finally{p(!1)}},ce=async()=>{if(!ee.newPassword){r({title:"Error",description:"Please enter a new password",variant:"destructive"});return}if(ee.newPassword.length<6){r({title:"Error",description:"Password must be at least 6 characters",variant:"destructive"});return}if(ee.newPassword!==ee.confirmPassword){r({title:"Error",description:"Passwords do not match",variant:"destructive"});return}p(!0);try{const{error:ne}=await V.auth.updateUser({password:ee.newPassword});if(ne)throw ne;r({title:"Success",description:"Password updated successfully"}),Z({newPassword:"",confirmPassword:""}),a&&setTimeout(()=>t("/dashboard"),1e3)}catch(ne){console.error("Error updating password:",ne),r({title:"Error",description:ne.message||"Failed to update password",variant:"destructive"})}finally{p(!1)}};return e.jsx(Ss,{title:a?"Complete Your Profile":i?"Reset Your Password":"Profile Settings",description:a?"Welcome! Please complete your profile setup":i?"Please set a new password for your account":"Manage your account information and password",children:e.jsxs("div",{className:"mx-auto max-w-4xl",children:[!a&&!i&&e.jsx("div",{className:"mb-6",children:e.jsxs(H,{variant:"outline",onClick:()=>{var ne;(ne=document.getElementById("change-password-section"))==null||ne.scrollIntoView({behavior:"smooth",block:"center"})},className:"gap-2",children:[e.jsx(_E,{className:"h-4 w-4"}),"Change Password"]})}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs(ke,{children:[e.jsxs(Ot,{children:[e.jsx(zt,{children:"Profile Photo"}),e.jsx(Br,{children:"Upload a professional photo for your profile"})]}),e.jsxs(Oe,{className:"flex items-center gap-6",children:[e.jsxs(Un,{className:"h-24 w-24",children:[e.jsx(Ka,{src:x}),e.jsx(qn,{className:"text-2xl",children:A.name.split(" ").map(ne=>ne[0]).join("").toUpperCase()||"U"})]}),e.jsxs("div",{className:"flex-1",children:[e.jsx("input",{type:"file",id:"avatar-upload",accept:"image/*",className:"hidden",onChange:K,disabled:_}),e.jsxs(H,{variant:"outline",onClick:()=>{var ne;return(ne=document.getElementById("avatar-upload"))==null?void 0:ne.click()},disabled:_,children:[e.jsx(Ea,{className:"mr-2 h-4 w-4"}),_?"Uploading...":"Upload Photo"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:"Upload an image and crop it to your liking."})]})]})]}),e.jsxs(ke,{children:[e.jsxs(Ot,{children:[e.jsx(zt,{children:"Personal Information"}),e.jsx(Br,{children:"Update your profile details"})]}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"name",children:"Name"}),e.jsx(Se,{id:"name",value:A.name,onChange:ne=>D({...A,name:ne.target.value}),maxLength:100})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"email",children:"Email"}),e.jsx(Se,{id:"email",type:"email",value:A.email,onChange:ne=>D({...A,email:ne.target.value}),maxLength:255})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"phone",children:"Phone Number"}),e.jsx(Se,{id:"phone",type:"tel",value:A.phone,onChange:ne=>D({...A,phone:ne.target.value}),placeholder:"e.g., +14155551234",maxLength:20}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Used for SMS lead notifications from your website — if you have a local authority site"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"title",children:"Job Title"}),e.jsx(Se,{id:"title",value:A.title,onChange:ne=>D({...A,title:ne.target.value}),placeholder:"e.g., Broker Associate, Team Lead",maxLength:100})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"bio",children:"Bio"}),e.jsx(vr,{id:"bio",value:A.bio,onChange:ne=>D({...A,bio:ne.target.value}),placeholder:"A short description about yourself",maxLength:500,className:"min-h-[120px] resize-y"})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"areas_served",children:"Areas Served"}),e.jsx(Se,{id:"areas_served",value:A.areas_served,onChange:ne=>D({...A,areas_served:ne.target.value}),placeholder:"e.g., Downtown, Suburbs"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"years_experience",children:"Years Experience"}),e.jsx(Se,{id:"years_experience",type:"number",min:"0",value:A.years_experience,onChange:ne=>D({...A,years_experience:ne.target.value}),placeholder:"e.g., 5"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Social Links"}),e.jsxs("div",{className:"grid grid-cols-1 gap-3",children:[e.jsx(Se,{value:A.linkedin_url,onChange:ne=>D({...A,linkedin_url:ne.target.value}),placeholder:"LinkedIn URL"}),e.jsx(Se,{value:A.instagram_url,onChange:ne=>D({...A,instagram_url:ne.target.value}),placeholder:"Instagram URL"}),e.jsx(Se,{value:A.facebook_url,onChange:ne=>D({...A,facebook_url:ne.target.value}),placeholder:"Facebook URL"})]})]}),e.jsxs(H,{onClick:ie,disabled:m,children:[e.jsx(vc,{className:"mr-2 h-4 w-4"}),"Save Changes"]})]})]}),e.jsxs(ke,{children:[e.jsxs(Ot,{children:[e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(Gb,{className:"h-5 w-5"}),"Email Signature"]}),e.jsx(Br,{children:"Add a signature that will be appended to emails sent via Gmail"})]}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Use email signature in all emails"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:A.use_email_signature?"Your signature will be added to every email sent via Gmail":"Signature is currently disabled"})]}),e.jsx(Or,{checked:A.use_email_signature,onCheckedChange:ne=>D({...A,use_email_signature:ne})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Signature"}),e.jsx(R1,{content:A.email_signature,onChange:ne=>D({...A,email_signature:ne}),placeholder:"Paste your Gmail signature here or create one...",minHeight:"120px",compact:!0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Tip: Copy your signature from Gmail Settings and paste it here — images and formatting will be preserved."})]}),e.jsxs(H,{onClick:ie,disabled:m,children:[e.jsx(vc,{className:"mr-2 h-4 w-4"}),"Save Signature"]})]})]}),e.jsxs(ke,{id:"change-password-section",children:[e.jsxs(Ot,{children:[e.jsx(zt,{children:a?"Set Your Password":"Change Password"}),e.jsx(Br,{children:a?"Create a secure password for your account":"Update your password to keep your account secure"})]}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"newPassword",children:"New Password"}),e.jsx(Se,{id:"newPassword",type:"password",value:ee.newPassword,onChange:ne=>Z({...ee,newPassword:ne.target.value}),placeholder:"Min 6 characters"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"confirmPassword",children:"Confirm Password"}),e.jsx(Se,{id:"confirmPassword",type:"password",value:ee.confirmPassword,onChange:ne=>Z({...ee,confirmPassword:ne.target.value}),placeholder:"Re-enter your new password"})]}),e.jsxs(H,{onClick:ce,disabled:m,children:[e.jsx(vc,{className:"mr-2 h-4 w-4"}),a?"Complete Setup":"Update Password"]}),a&&e.jsx(H,{variant:"outline",onClick:()=>t("/dashboard"),className:"ml-2",children:"Skip for Now"})]})]}),e.jsxs(ke,{children:[e.jsxs(Ot,{children:[e.jsxs(zt,{className:"flex items-center gap-2",children:[o?e.jsx(wp,{className:"h-5 w-5"}):e.jsx(u_,{className:"h-5 w-5"}),"Push Notifications"]}),e.jsx(Br,{children:"Receive browser notifications when new content is added"})]}),e.jsx(Oe,{children:l?e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:o?"Notifications enabled":"Notifications disabled"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:o?"You'll receive notifications about new templates, videos, and events":"Enable to get notified about new content"})]}),e.jsx(Or,{checked:o,onCheckedChange:ne=>{ne?d():h()},disabled:c})]}):e.jsxs("div",{className:"text-sm text-muted-foreground space-y-2",children:[e.jsx("p",{children:"Push notifications are not available in this browser."}),e.jsxs("p",{className:"text-xs space-y-1",children:[e.jsx("strong",{children:"Desktop:"})," Use Chrome, Firefox, or Edge.",e.jsx("br",{}),e.jsx("strong",{children:"Android:"})," Use Chrome or Firefox.",e.jsx("br",{}),e.jsx("strong",{children:"iPhone/iPad:"})," Push notifications on iOS ",e.jsx("em",{children:"only"})," work when this site is installed as an app from ",e.jsx("strong",{children:"Safari"}),". Open this site in Safari → tap the ",e.jsx("strong",{children:"Share"})," button → ",e.jsx("strong",{children:"Add to Home Screen"}),". Other browsers (Chrome, Firefox, etc.) on iOS do not support push notifications due to Apple restrictions."]})]})})]}),e.jsxs(ke,{children:[e.jsxs(Ot,{children:[e.jsxs(zt,{className:"flex items-center gap-2",children:[R?e.jsx(qI,{className:"h-5 w-5"}):e.jsx(er,{className:"h-5 w-5"}),"Email Preferences"]}),e.jsx(Br,{children:"Manage your email subscription settings"})]}),e.jsx(Oe,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Weekly Digest"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:R?"You won't receive weekly digest emails":"Receive a weekly summary of new content, events, and your progress"})]}),e.jsx(Or,{checked:!R,onCheckedChange:async ne=>{$(!0);try{const{error:le}=await V.from("profiles").update({digest_opt_out:!ne}).eq("id",s==null?void 0:s.id);if(le)throw le;z(!ne),r({title:ne?"Subscribed":"Unsubscribed",description:ne?"You will now receive weekly digest emails":"You will no longer receive weekly digest emails"})}catch(le){r({title:"Error",description:le.message||"Failed to update preference",variant:"destructive"})}finally{$(!1)}},disabled:O})]})})]}),e.jsx(gGt,{}),e.jsx(Hes,{})]}),e.jsx(fEe,{open:j,onClose:()=>k(!1),imageSrc:T,onCropComplete:re,aspectRatio:1})]})})};var Wes="AspectRatio",xdt=S.forwardRef((s,t)=>{const{ratio:r=1/1,style:n,...a}=s;return e.jsx("div",{style:{position:"relative",width:"100%",paddingBottom:`${100/r}%`},"data-radix-aspect-ratio-wrapper":"",children:e.jsx(Vn.div,{...a,ref:t,style:{...n,position:"absolute",top:0,right:0,bottom:0,left:0}})})});xdt.displayName=Wes;var Kes=xdt;const Yes=Kes;function Zes(){const{user:s}=Ms(),t=ns(),[r,n]=S.useState(!1),[a,i]=S.useState(!1),{data:l,isLoading:o}=yt({queryKey:["calendar-token",s==null?void 0:s.id],queryFn:async()=>{const{data:y,error:_}=await V.from("profiles").select("calendar_token").eq("id",s==null?void 0:s.id).single();if(_)throw _;return y},enabled:!!s&&a}),c=Pt({mutationFn:async()=>{const y=new Uint8Array(12);crypto.getRandomValues(y);const _=btoa(String.fromCharCode(...y)).replace(/\+/g,"x").replace(/\//g,"y").replace(/=/g,"").substring(0,16),{error:b}=await V.from("profiles").update({calendar_token:_}).eq("id",s==null?void 0:s.id);if(b)throw b;return _},onSuccess:()=>{t.invalidateQueries({queryKey:["calendar-token",s==null?void 0:s.id]}),he.success("Calendar subscription URL generated!")},onError:y=>{he.error("Failed to generate calendar URL: "+y.message)}}),d=l!=null&&l.calendar_token?`https://dashboard.relevelup.com/api/calendar/${l.calendar_token}.ics`:null,h=async()=>{d&&(await navigator.clipboard.writeText(d),n(!0),he.success("Calendar URL copied to clipboard!"),setTimeout(()=>n(!1),2e3))},m=()=>{d&&(window.location.href=d.replace("https://","webcal://"))},p=()=>{if(d){const y=d.replace("https://","webcal://"),_=`https://calendar.google.com/calendar/r?cid=${encodeURIComponent(y)}`;window.open(_,"_blank")}},x=()=>{if(d){const y=`https://outlook.live.com/calendar/0/addfromweb?url=${encodeURIComponent(d)}&name=Level%20Up%20Events`;window.open(y,"_blank")}};return e.jsxs(bs,{open:a,onOpenChange:i,children:[e.jsx(Qi,{asChild:!0,children:e.jsxs(H,{variant:"outline",className:"gap-2",children:[e.jsx(Nn,{className:"h-4 w-4"}),"Subscribe to Calendar"]})}),e.jsxs(vs,{className:"sm:max-w-md",children:[e.jsxs(Cs,{children:[e.jsxs(Ns,{className:"flex items-center gap-2",children:[e.jsx(Nn,{className:"h-5 w-5 text-primary"}),"Subscribe to Events Calendar"]}),e.jsx(nn,{children:"Add all Level Up events to your personal calendar. Events will sync automatically and update when we add or change events."})]}),e.jsx("div",{className:"space-y-4 py-4",children:o?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(is,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):d?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Your Calendar URL"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Se,{value:d,readOnly:!0,className:"text-xs font-mono"}),e.jsx(H,{variant:"outline",size:"icon",onClick:h,children:r?e.jsx(va,{className:"h-4 w-4 text-green-500"}):e.jsx(ui,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Quick Add"}),e.jsxs("div",{className:"grid gap-2",children:[e.jsxs(H,{variant:"outline",className:"w-full justify-start gap-2",onClick:m,children:[e.jsx("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("path",{d:"M18.71 19.5c-.83 1.24-1.71 2.45-3.05 2.47-1.34.03-1.77-.79-3.29-.79-1.53 0-2 .77-3.27.82-1.31.05-2.3-1.32-3.14-2.53C4.25 17 2.94 12.45 4.7 9.39c.87-1.52 2.43-2.48 4.12-2.51 1.28-.02 2.5.87 3.29.87.78 0 2.26-1.07 3.81-.91.65.03 2.47.26 3.64 1.98-.09.06-2.17 1.28-2.15 3.81.03 3.02 2.65 4.03 2.68 4.04-.03.07-.42 1.44-1.38 2.83M13 3.5c.73-.83 1.94-1.46 2.94-1.5.13 1.17-.34 2.35-1.04 3.19-.69.85-1.83 1.51-2.95 1.42-.15-1.15.41-2.35 1.05-3.11z"})}),"Add to Apple Calendar",e.jsx(gn,{className:"h-3 w-3 ml-auto opacity-50"})]}),e.jsxs(H,{variant:"outline",className:"w-full justify-start gap-2",onClick:p,children:[e.jsxs("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"currentColor",children:[e.jsx("path",{d:"M19.5 22h-15A2.5 2.5 0 0 1 2 19.5v-15A2.5 2.5 0 0 1 4.5 2H9v2H4.5a.5.5 0 0 0-.5.5v15a.5.5 0 0 0 .5.5h15a.5.5 0 0 0 .5-.5V15h2v4.5a2.5 2.5 0 0 1-2.5 2.5z"}),e.jsx("path",{d:"M12 2v8.5a1.5 1.5 0 0 0 1.5 1.5H22V2h-10z",fill:"#4285F4"}),e.jsx("path",{d:"M12 12V2H4.5A2.5 2.5 0 0 0 2 4.5V12h10z",fill:"#34A853"}),e.jsx("path",{d:"M2 12v7.5A2.5 2.5 0 0 0 4.5 22H12v-10H2z",fill:"#FBBC05"}),e.jsx("path",{d:"M12 22h7.5a2.5 2.5 0 0 0 2.5-2.5V12h-10v10z",fill:"#EA4335"})]}),"Add to Google Calendar",e.jsx(gn,{className:"h-3 w-3 ml-auto opacity-50"})]}),e.jsxs(H,{variant:"outline",className:"w-full justify-start gap-2",onClick:x,children:[e.jsx("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("path",{d:"M7.88 12.04q0 .45-.11.87-.1.41-.33.74-.22.33-.58.52-.37.2-.87.2t-.85-.2q-.35-.21-.57-.55-.22-.33-.33-.75-.1-.42-.1-.86t.1-.87q.1-.43.34-.76.22-.34.59-.54.36-.2.87-.2t.86.2q.35.21.57.55.22.34.31.77.1.43.1.88zM24 12v9.38q0 .46-.33.8-.33.32-.8.32H7.13q-.46 0-.8-.33-.32-.33-.32-.8V18H1q-.41 0-.7-.3-.3-.29-.3-.7V7q0-.41.3-.7Q.58 6 1 6h6.5V2.55q0-.44.3-.75.3-.3.75-.3h12.9q.44 0 .75.3.3.3.3.75V12zm-6-8.25v3h3v-3zm0 4.5v3h3v-3zm0 4.5v1.83l3.05-1.83zm-5.25-9v3h3.75v-3zm0 4.5v3h3.75v-3zm0 4.5v2.03l2.41 1.5 1.34-.81v-2.72zM9 3.75V6h2l.13.01.12.04v-2.3zM5.98 15.98q.9 0 1.6-.3.7-.32 1.19-.86.48-.55.73-1.28.25-.74.25-1.61 0-.83-.25-1.55-.24-.71-.71-1.24t-1.15-.83q-.68-.3-1.55-.3-.92 0-1.64.3-.71.3-1.2.85-.5.54-.75 1.3-.25.74-.25 1.63 0 .85.26 1.56.26.72.74 1.23.48.52 1.17.81.69.3 1.56.3zM7.5 21h12.39L12 16.08V17q0 .41-.3.7-.29.3-.7.3H7.5zm15-.13v-7.24l-5.9 3.54Z"})}),"Add to Outlook",e.jsx(gn,{className:"h-3 w-3 ml-auto opacity-50"})]})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground text-center pt-2",children:"Events sync automatically. If your membership expires, the calendar will show as empty."})]}):e.jsxs("div",{className:"text-center space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Generate your personal calendar subscription URL to get started."}),e.jsx(H,{onClick:()=>c.mutate(),disabled:c.isPending,className:"w-full",children:c.isPending?e.jsxs(e.Fragment,{children:[e.jsx(is,{className:"h-4 w-4 mr-2 animate-spin"}),"Generating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Nn,{className:"h-4 w-4 mr-2"}),"Generate Calendar URL"]})})]})})]})]})}const Xes={first_timer:ya,regular:H2,dedicated:Bc,veteran:To,streak_master:od,century:To},Qes={first_timer:"bg-green-500/10 text-green-500 border-green-500/20",regular:"bg-blue-500/10 text-blue-500 border-blue-500/20",dedicated:"bg-purple-500/10 text-purple-500 border-purple-500/20",veteran:"bg-amber-500/10 text-amber-500 border-amber-500/20",streak_master:"bg-orange-500/10 text-orange-500 border-orange-500/20",century:"bg-yellow-500/10 text-yellow-500 border-yellow-500/20"};function ZBe(s){return s===1?e.jsx(To,{className:"h-5 w-5 text-yellow-500"}):s===2?e.jsx(H2,{className:"h-5 w-5 text-gray-400"}):s===3?e.jsx(Bc,{className:"h-5 w-5 text-amber-600"}):e.jsx("span",{className:"w-5 text-center text-sm font-medium text-muted-foreground",children:s})}function ydt({showUserStats:s=!0,compact:t=!1,brokerageId:r,title:n="Event Leaderboard"}){const{user:a}=Ms(),{data:i,isLoading:l}=Not(t?5:10,r),{data:o}=kot(a==null?void 0:a.id),{data:c}=Cot(a==null?void 0:a.id),{data:d}=Sot(a==null?void 0:a.id);return l?e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(To,{className:"h-5 w-5 text-yellow-500"}),n]})}),e.jsx(Oe,{children:e.jsx("div",{className:"space-y-3",children:[...Array(5)].map((h,m)=>e.jsx(Ks,{className:"h-12 w-full"},m))})})]}):e.jsxs(ke,{children:[e.jsx(Ot,{className:"pb-3",children:e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(To,{className:"h-5 w-5 text-yellow-500"}),n]})}),e.jsxs(Oe,{children:[s&&o&&e.jsxs("div",{className:"mb-4 p-3 rounded-lg bg-primary/5 border border-primary/10",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("span",{className:"text-sm font-medium",children:"Your Stats"}),c&&e.jsxs(Xe,{variant:"secondary",className:"text-xs",children:["Rank #",c]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 text-center",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-lg font-bold text-primary",children:o.total_points}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Points"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-lg font-bold",children:o.total_events_attended}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Events"})]}),e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(od,{className:"h-4 w-4 text-orange-500"}),e.jsx("div",{className:"text-lg font-bold",children:o.current_streak}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Streak"})]})]}),d&&d.length>0&&e.jsxs("div",{className:"mt-3 flex flex-wrap gap-1",children:[d.slice(0,4).map(h=>{const m=Xes[h.badge_type]||ya;return e.jsxs(Xe,{variant:"outline",className:`text-xs ${Qes[h.badge_type]||""}`,title:h.badge_description||"",children:[e.jsx(m,{className:"h-3 w-3 mr-1"}),h.badge_name]},h.id)}),d.length>4&&e.jsxs(Xe,{variant:"outline",className:"text-xs",children:["+",d.length-4," more"]})]})]}),e.jsxs(ta,{defaultValue:"points",className:"w-full",children:[e.jsxs(Qn,{className:"w-full mb-3",children:[e.jsx(ts,{value:"points",className:"flex-1",children:"By Points"}),e.jsx(ts,{value:"events",className:"flex-1",children:"By Events"})]}),e.jsx(cs,{value:"points",className:"mt-0",children:e.jsxs("div",{className:"space-y-2",children:[i==null?void 0:i.map((h,m)=>{var p,x,y;return e.jsxs("div",{className:`flex items-center gap-3 p-2 rounded-lg ${h.user_id===(a==null?void 0:a.id)?"bg-primary/5 border border-primary/10":""} ${m===0?"bg-yellow-500/5":""}`,children:[e.jsx("div",{className:"w-6 flex justify-center",children:ZBe(m+1)}),e.jsx(Un,{className:"h-8 w-8",children:e.jsx(qn,{className:"text-xs",children:((x=(p=h.profile)==null?void 0:p.name)==null?void 0:x.charAt(0))||"?"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-medium text-sm truncate",children:[((y=h.profile)==null?void 0:y.name)||"Unknown",h.user_id===(a==null?void 0:a.id)&&e.jsx("span",{className:"text-xs text-muted-foreground ml-1",children:"(You)"})]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[h.total_events_attended," events"]})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("div",{className:"font-bold text-primary",children:h.total_points}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"pts"})]})]},h.user_id)}),(!i||i.length===0)&&e.jsx("div",{className:"text-center text-muted-foreground py-4 text-sm",children:"No attendance data yet. Attend an event to get on the leaderboard!"})]})}),e.jsx(cs,{value:"events",className:"mt-0",children:e.jsx("div",{className:"space-y-2",children:[...i||[]].sort((h,m)=>m.total_events_attended-h.total_events_attended).map((h,m)=>{var p,x,y;return e.jsxs("div",{className:`flex items-center gap-3 p-2 rounded-lg ${h.user_id===(a==null?void 0:a.id)?"bg-primary/5 border border-primary/10":""} ${m===0?"bg-yellow-500/5":""}`,children:[e.jsx("div",{className:"w-6 flex justify-center",children:ZBe(m+1)}),e.jsx(Un,{className:"h-8 w-8",children:e.jsx(qn,{className:"text-xs",children:((x=(p=h.profile)==null?void 0:p.name)==null?void 0:x.charAt(0))||"?"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-medium text-sm truncate",children:[((y=h.profile)==null?void 0:y.name)||"Unknown",h.user_id===(a==null?void 0:a.id)&&e.jsx("span",{className:"text-xs text-muted-foreground ml-1",children:"(You)"})]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[h.total_points," points"]})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("div",{className:"font-bold",children:h.total_events_attended}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"events"})]})]},h.user_id)})})})]})]})]})}function Jes(){const s=Fr(),{user:t,isAdmin:r}=Ms(),n=ns(),{data:a,isLoading:i}=yt({queryKey:["public-events"],queryFn:async()=>{const{data:_,error:b}=await V.from("events").select("*").order("event_date",{ascending:!0});if(b)throw b;return _}}),{data:l}=yt({queryKey:["my-registrations"],queryFn:async()=>{if(!t)return[];const{data:_,error:b}=await V.from("event_registrations").select("event_id, zoom_join_url").eq("user_id",t.id);if(b)throw b;return _},enabled:!!t}),{data:o}=yt({queryKey:["event-registration-counts"],queryFn:async()=>{let _=[],b=0;const j=1e3;for(;;){const{data:T,error:E}=await V.from("event_registrations").select("event_id").range(b,b+j-1);if(E)throw E;if(!T||T.length===0||(_=_.concat(T),T.length{k[T.event_id]=(k[T.event_id]||0)+1}),k}}),c=Pt({mutationFn:async _=>{await V.auth.refreshSession();const{data:b,error:j}=await V.functions.invoke("zoom-register",{body:{event_id:_}});if(j)throw j;if(b!=null&&b.error)throw new Error(b.error);return b},onSuccess:_=>{n.invalidateQueries({queryKey:["my-registrations"]}),n.invalidateQueries({queryKey:["event-registration-counts"]}),_!=null&&_.join_url?he.success("Successfully registered! You'll receive a Zoom confirmation email."):he.success("Successfully registered for the event!")},onError:_=>{he.error("Failed to register: "+_.message)}}),d=Pt({mutationFn:async _=>{const{data:b,error:j}=await V.functions.invoke("zoom-unregister",{body:{event_id:_}});if(j)throw j;if(b!=null&&b.error)throw new Error(b.error);return b},onSuccess:()=>{n.invalidateQueries({queryKey:["my-registrations"]}),n.invalidateQueries({queryKey:["event-registration-counts"]}),he.success("Registration cancelled and removed from Zoom")},onError:_=>{he.error("Failed to cancel: "+_.message)}}),h=_=>l==null?void 0:l.some(b=>b.event_id===_),m=_=>{const b=l==null?void 0:l.find(j=>j.event_id===_);return b==null?void 0:b.zoom_join_url},p=_=>_.capacity?((o==null?void 0:o[_.id])||0)>=_.capacity:!1,x=(a==null?void 0:a.filter(_=>oP(_.event_date)!=="ended"))||[],y=(a==null?void 0:a.filter(_=>oP(_.event_date)==="ended"))||[];return e.jsx(Ss,{title:"Events",children:e.jsxs("div",{className:"max-w-6xl mx-auto",children:[e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold text-foreground",children:"Events"}),e.jsx("p",{className:"text-muted-foreground",children:"Browse and register for upcoming events"})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Zes,{}),r&&e.jsx(H,{variant:"outline",onClick:()=>s("/admin/events"),children:"Manage Events"})]})]}),e.jsxs("div",{className:`grid grid-cols-1 ${r?"lg:grid-cols-3":""} gap-6`,children:[e.jsxs("div",{className:r?"lg:col-span-2":"",children:[i?e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading events..."}):x.length===0?e.jsx(ke,{className:"text-center py-12",children:e.jsx(Oe,{children:e.jsx("p",{className:"text-muted-foreground",children:"No upcoming events at the moment. Check back soon!"})})}):e.jsx("div",{className:"grid gap-6 md:grid-cols-2",children:x.map(_=>{const b=oP(_.event_date),j=xTe(_.event_date),k=b==="live",T=b==="starting_soon";return e.jsxs(ke,{className:`flex flex-col overflow-hidden cursor-pointer hover:shadow-lg transition-all ${k?"border-red-500 ring-2 ring-red-500/20":T?"border-amber-500 ring-2 ring-amber-500/20":"hover:border-primary/50"}`,onClick:()=>s(`/events/${_.id}`),children:[j&&e.jsxs("div",{className:`${k?"bg-red-500":"bg-amber-500"} text-white px-3 py-1.5 flex items-center gap-2 text-sm font-medium`,children:[e.jsxs("span",{className:"relative flex h-2 w-2",children:[e.jsx("span",{className:"absolute inline-flex h-full w-full animate-ping rounded-full bg-white opacity-75"}),e.jsx("span",{className:"relative inline-flex rounded-full h-2 w-2 bg-white"})]}),k?e.jsxs(e.Fragment,{children:[e.jsx(G2,{className:"h-3.5 w-3.5"}),"LIVE NOW"]}):e.jsxs(e.Fragment,{children:[e.jsx(Pn,{className:"h-3.5 w-3.5"}),"STARTING SOON"]})]}),_.image_url&&e.jsx(Yes,{ratio:3/2,className:"overflow-hidden",children:e.jsx("img",{src:_.image_url,alt:_.title,className:"w-full h-full object-cover group-hover:scale-105 transition-transform"})}),e.jsxs(Ot,{children:[e.jsx(zt,{className:"line-clamp-2",children:_.title}),_.description&&e.jsx(Br,{className:"line-clamp-2",children:_.description.replace(/<[^>]*>/g,"")})]}),e.jsxs(Oe,{className:"flex-1 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Nn,{className:"h-4 w-4"}),new Intl.DateTimeFormat("en-US",{weekday:"long",year:"numeric",month:"long",day:"numeric",timeZone:"America/New_York"}).format(new Date(_.event_date))]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Pn,{className:"h-4 w-4"}),g9(new Date(_.event_date))]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Ar,{className:"h-4 w-4"}),(o==null?void 0:o[_.id])||0," registered",_.capacity&&` / ${_.capacity} spots`]})]}),e.jsx(WF,{className:"flex gap-2",onClick:E=>E.stopPropagation(),children:h(_.id)?e.jsxs(e.Fragment,{children:[e.jsxs(H,{variant:"outline",className:"flex-1",onClick:()=>d.mutate(_.id),disabled:d.isPending,children:[e.jsx(Rr,{className:"h-4 w-4 mr-2"}),"Cancel"]}),e.jsxs(H,{className:"flex-1",onClick:()=>window.open(m(_.id)||_.zoom_link,"_blank"),children:[e.jsx(gn,{className:"h-4 w-4 mr-2"}),"Join Zoom"]})]}):e.jsx(H,{className:"w-full",onClick:()=>c.mutate(_.id),disabled:c.isPending||p(_),children:p(_)?"Event Full":e.jsxs(e.Fragment,{children:[e.jsx(va,{className:"h-4 w-4 mr-2"}),"Register"]})})})]},_.id)})}),y.length>0&&e.jsxs("div",{className:"mt-12",children:[e.jsx("h3",{className:"text-xl font-semibold mb-4 text-muted-foreground",children:"Past Events"}),e.jsx("div",{className:"grid gap-4 md:grid-cols-2",children:y.map(_=>e.jsx(ke,{className:"opacity-60 cursor-pointer hover:opacity-80 transition-opacity",onClick:()=>s(`/events/${_.id}`),children:e.jsxs(Ot,{children:[e.jsx(zt,{className:"text-base line-clamp-1",children:_.title}),e.jsx(Br,{children:new Intl.DateTimeFormat("en-US",{year:"numeric",month:"long",day:"numeric",timeZone:"America/New_York"}).format(new Date(_.event_date))})]})},_.id))})]})]}),r&&e.jsx("div",{className:"lg:col-span-1",children:e.jsx(ydt,{showUserStats:!0})})]})]})})}const d_e=[{value:"all",label:"All Roles",icon:Ar},{value:"newest",label:"Newest Members",icon:Pn},{value:"brokerage_manager",label:"Brokerage Managers",icon:FF},{value:"admin",label:"Admins",icon:Fh}];function ets({open:s,onOpenChange:t,resourceType:r,resourceId:n,resourceTitle:a}){var Ie,De;const{user:i,isAdmin:l,isBrokerageManager:o}=Ms(),[c,d]=S.useState([]),[h,m]=S.useState([]),[p,x]=S.useState([]),[y,_]=S.useState([]),[b,j]=S.useState(""),[k,T]=S.useState(""),[E,A]=S.useState(""),[D,R]=S.useState(!1),[z,O]=S.useState(!1),[$,ee]=S.useState("agents"),[Z,J]=S.useState("all"),[K,re]=S.useState({}),ie=l||o;S.useEffect(()=>{s&&i&&(l?ce():ne())},[s,i,l]),S.useEffect(()=>{s||(x([]),_([]),j(""),T(""),A(""),ee("agents"),J("all"))},[s]);const ce=async()=>{if(i){R(!0);try{const{data:pe,error:tt}=await V.from("brokerages").select("id, name").order("name");if(tt)throw tt;const ge=1e3,ct={};let Ue=0,et=!0;for(;et;){const{data:$e,error:it}=await V.from("profiles").select("brokerage_id").range(Ue*ge,(Ue+1)*ge-1);if(it)throw it;$e==null||$e.forEach(Je=>{Je.brokerage_id&&(ct[Je.brokerage_id]=(ct[Je.brokerage_id]||0)+1)}),et=($e==null?void 0:$e.length)===ge,Ue++}m((pe==null?void 0:pe.map($e=>({...$e,agent_count:ct[$e.id]||0})))||[]);const Qe=[];for(Ue=0,et=!0;et;){const{data:$e,error:it}=await V.from("profiles").select("id, name, email, brokerage_id, created_at, brokerages(name)").neq("id",i.id).order("name").range(Ue*ge,(Ue+1)*ge-1);if(it)throw it;$e&&Qe.push(...$e),et=($e==null?void 0:$e.length)===ge,Ue++}const Ne={};for(Ue=0,et=!0;et;){const{data:$e,error:it}=await V.from("user_roles").select("user_id, role").range(Ue*ge,(Ue+1)*ge-1);if(it)throw it;$e==null||$e.forEach(Je=>{Ne[Je.user_id]||(Ne[Je.user_id]=[]),Ne[Je.user_id].push(Je.role)}),et=($e==null?void 0:$e.length)===ge,Ue++}re(Ne),d(Qe.map($e=>{var it;return{id:$e.id,name:$e.name,email:$e.email,brokerage_name:((it=$e.brokerages)==null?void 0:it.name)||"No Brokerage",roles:Ne[$e.id]||[],created_at:$e.created_at}}))}catch(pe){console.error("Error loading data:",pe),he.error("Failed to load agents and brokerages")}finally{R(!1)}}},ne=async()=>{if(i){R(!0);try{const{data:pe}=await V.from("profiles").select("brokerage_id").eq("id",i.id).single();if(!(pe!=null&&pe.brokerage_id)){he.error("You must be part of a brokerage to share resources"),t(!1);return}const{data:tt,error:ge}=await V.from("profiles").select("id, name, email").eq("brokerage_id",pe.brokerage_id).neq("id",i.id).order("name");if(ge)throw ge;d(tt||[])}catch(pe){console.error("Error loading agents:",pe),he.error("Failed to load agents")}finally{R(!1)}}},le=c.filter(pe=>{var ge;const tt=pe.name.toLowerCase().includes(b.toLowerCase())||pe.email.toLowerCase().includes(b.toLowerCase())||((ge=pe.brokerage_name)==null?void 0:ge.toLowerCase().includes(b.toLowerCase()));if(l&&Z!=="all"&&Z!=="newest"){const ct=K[pe.id]||[];return tt&&ct.includes(Z)}return tt}).sort((pe,tt)=>Z==="newest"?(tt.created_at||"").localeCompare(pe.created_at||""):0),be=h.filter(pe=>pe.name.toLowerCase().includes(k.toLowerCase())),fe=()=>{p.length===le.length?x([]):x(le.map(pe=>pe.id))},je=()=>{y.length===be.length?_([]):_(be.map(pe=>pe.id))},ve=pe=>{if(!ie){x([pe]);return}x(tt=>tt.includes(pe)?tt.filter(ge=>ge!==pe):[...tt,pe])},We=pe=>{_(tt=>tt.includes(pe)?tt.filter(ge=>ge!==pe):[...tt,pe])},Ve=async()=>{if(!(p.length>0||y.length>0)){he.error("Please select at least one agent or brokerage to share with");return}O(!0);try{const{data:tt,error:ge}=await V.functions.invoke("send-share-notification",{body:{recipientIds:p,brokerageIds:y,resourceType:r,resourceId:n,resourceTitle:a,message:E.trim()||void 0}});if(ge)throw ge;const ct=(tt==null?void 0:tt.sharesCreated)||p.length;he.success(`Shared with ${ct} agent${ct!==1?"s":""}`),t(!1)}catch(tt){console.error("Error sharing resource:",tt),he.error("Failed to share resource")}finally{O(!1)}},Le=pe=>pe.split(" ").map(tt=>tt[0]).join("").toUpperCase().slice(0,2),Me=pe=>{const tt=K[pe]||[];return tt.includes("admin")?e.jsx(Xe,{variant:"secondary",className:"text-[10px] px-1.5 py-0",children:"Admin"}):tt.includes("brokerage_manager")?e.jsx(Xe,{variant:"outline",className:"text-[10px] px-1.5 py-0",children:"Manager"}):null},ze=p.length+y.length,Pe=Z!=="all"&&Z!=="newest"?le.length:null;return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"sm:max-w-lg max-h-[90vh] overflow-hidden flex flex-col",children:[e.jsxs(Cs,{className:"flex-shrink-0",children:[e.jsxs(Ns,{className:"flex items-center gap-2",children:[e.jsx(yn,{className:"h-5 w-5 text-primary"}),"Share Resource"]}),e.jsxs(nn,{className:"line-clamp-2",children:['Share "',a,'" with ',l?"agents or brokerages":"agents in your brokerage"]})]}),e.jsxs("div",{className:"flex-1 overflow-hidden flex flex-col space-y-4",children:[l?e.jsxs(ta,{value:$,onValueChange:ee,className:"flex-1 flex flex-col overflow-hidden",children:[e.jsxs(Qn,{className:"grid w-full grid-cols-2 flex-shrink-0",children:[e.jsxs(ts,{value:"agents",className:"flex items-center gap-2",children:[e.jsx(Ar,{className:"h-4 w-4"}),e.jsx("span",{children:"Agents"}),p.length>0&&e.jsx(Xe,{variant:"default",className:"h-5 min-w-5 px-1.5 text-xs",children:p.length})]}),e.jsxs(ts,{value:"brokerages",className:"flex items-center gap-2",children:[e.jsx(Xa,{className:"h-4 w-4"}),e.jsx("span",{children:"Brokerages"}),y.length>0&&e.jsx(Xe,{variant:"default",className:"h-5 min-w-5 px-1.5 text-xs",children:y.length})]})]}),e.jsxs(cs,{value:"agents",className:"flex-1 flex flex-col space-y-3 mt-3 overflow-hidden",children:[e.jsxs("div",{className:"flex gap-2 flex-shrink-0",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Mn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Se,{placeholder:"Search by name, email, or brokerage...",value:b,onChange:pe=>j(pe.target.value),className:"pl-9"})]}),e.jsxs(Bs,{value:Z,onValueChange:J,children:[e.jsxs(Os,{className:"w-[180px]",children:[e.jsx(v1,{className:"h-4 w-4 mr-2 text-muted-foreground"}),e.jsx(Us,{placeholder:"Filter by role"})]}),e.jsx(Fs,{children:d_e.map(pe=>e.jsx(pt,{value:pe.value,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pe.icon,{className:"h-4 w-4"}),e.jsx("span",{children:pe.label})]})},pe.value))})]})]}),e.jsxs("div",{className:"flex items-center justify-between px-1 flex-shrink-0",children:[e.jsxs(H,{variant:"ghost",size:"sm",onClick:fe,className:"text-xs h-8",disabled:le.length===0,children:[e.jsx(Ar,{className:"h-3.5 w-3.5 mr-1.5"}),p.length===le.length&&le.length>0?"Deselect All":"Select All"]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[Pe!==null&&e.jsxs("span",{className:"text-primary font-medium",children:[Pe," ",(Ie=d_e.find(pe=>pe.value===Z))==null?void 0:Ie.label]}),e.jsxs("span",{className:"font-medium",children:[p.length," selected"]})]})]}),e.jsx(Ci,{className:"h-[300px] border rounded-lg",children:D?e.jsx("div",{className:"flex items-center justify-center h-[200px]",children:e.jsx(is,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):le.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center h-[200px] text-muted-foreground",children:[e.jsx(Ar,{className:"h-8 w-8 mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:Z!=="all"?`No ${(De=d_e.find(pe=>pe.value===Z))==null?void 0:De.label.toLowerCase()} found`:"No agents found"})]}):e.jsx("div",{className:"p-2 space-y-1",children:le.map(pe=>e.jsxs("div",{className:`flex items-center gap-3 p-2.5 rounded-lg cursor-pointer hover:bg-accent/50 transition-colors ${p.includes(pe.id)?"bg-accent":""}`,onClick:()=>ve(pe.id),children:[e.jsx(ao,{checked:p.includes(pe.id),onCheckedChange:()=>ve(pe.id),className:"flex-shrink-0"}),e.jsx(Un,{className:"h-9 w-9 flex-shrink-0",children:e.jsx(qn,{className:"text-xs bg-primary/10 text-primary",children:Le(pe.name)})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:pe.name}),Me(pe.id)]}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[pe.email,pe.brokerage_name&&e.jsxs("span",{className:"ml-1 opacity-75",children:["• ",pe.brokerage_name]})]})]})]},pe.id))})})]}),e.jsxs(cs,{value:"brokerages",className:"flex-1 flex flex-col space-y-3 mt-3 overflow-hidden",children:[e.jsxs("div",{className:"relative flex-shrink-0",children:[e.jsx(Mn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Se,{placeholder:"Search brokerages...",value:k,onChange:pe=>T(pe.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"flex items-center justify-between px-1 flex-shrink-0",children:[e.jsxs(H,{variant:"ghost",size:"sm",onClick:je,className:"text-xs h-8",disabled:be.length===0,children:[e.jsx(Xa,{className:"h-3.5 w-3.5 mr-1.5"}),y.length===be.length&&be.length>0?"Deselect All":"Select All"]}),e.jsxs("span",{className:"text-xs text-muted-foreground font-medium",children:[y.length," selected"]})]}),e.jsx("p",{className:"text-xs text-muted-foreground px-1 flex-shrink-0",children:"Selecting a brokerage will send to all agents in that brokerage."}),e.jsx(Ci,{className:"h-[250px] border rounded-lg",children:D?e.jsx("div",{className:"flex items-center justify-center h-[180px]",children:e.jsx(is,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):be.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center h-[180px] text-muted-foreground",children:[e.jsx(Xa,{className:"h-8 w-8 mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No brokerages found"})]}):e.jsx("div",{className:"p-2 space-y-1",children:be.map(pe=>e.jsxs("div",{className:`flex items-center gap-3 p-2.5 rounded-lg cursor-pointer hover:bg-accent/50 transition-colors ${y.includes(pe.id)?"bg-accent":""}`,onClick:()=>We(pe.id),children:[e.jsx(ao,{checked:y.includes(pe.id),onCheckedChange:()=>We(pe.id),className:"flex-shrink-0"}),e.jsx("div",{className:"h-9 w-9 rounded-lg bg-primary/10 flex items-center justify-center flex-shrink-0",children:e.jsx(Xa,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:pe.name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[pe.agent_count," agent",pe.agent_count!==1?"s":""]})]})]},pe.id))})})]})]}):e.jsxs("div",{className:"flex-1 flex flex-col space-y-3 overflow-hidden",children:[e.jsxs("div",{className:"relative flex-shrink-0",children:[e.jsx(Mn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Se,{placeholder:"Search agents...",value:b,onChange:pe=>j(pe.target.value),className:"pl-9"})]}),ie&&e.jsxs("div",{className:"flex items-center justify-between px-1 flex-shrink-0",children:[e.jsxs(H,{variant:"ghost",size:"sm",onClick:fe,className:"text-xs h-8",disabled:le.length===0,children:[e.jsx(Ar,{className:"h-3.5 w-3.5 mr-1.5"}),p.length===le.length&&le.length>0?"Deselect All":"Select All"]}),e.jsxs("span",{className:"text-xs text-muted-foreground font-medium",children:[p.length," selected"]})]}),e.jsx(Ci,{className:"h-[300px] border rounded-lg",children:D?e.jsx("div",{className:"flex items-center justify-center h-[200px]",children:e.jsx(is,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):le.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center h-[200px] text-muted-foreground",children:[e.jsx(Ar,{className:"h-8 w-8 mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No agents found"})]}):e.jsx("div",{className:"p-2 space-y-1",children:le.map(pe=>e.jsxs("div",{className:`flex items-center gap-3 p-2.5 rounded-lg cursor-pointer hover:bg-accent/50 transition-colors ${p.includes(pe.id)?"bg-accent":""}`,onClick:()=>ve(pe.id),children:[e.jsx(ao,{checked:p.includes(pe.id),onCheckedChange:()=>ve(pe.id),className:"flex-shrink-0"}),e.jsx(Un,{className:"h-9 w-9 flex-shrink-0",children:e.jsx(qn,{className:"text-xs bg-primary/10 text-primary",children:Le(pe.name)})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:pe.name}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:pe.email})]})]},pe.id))})})]}),e.jsxs("div",{className:"space-y-2 flex-shrink-0",children:[e.jsx(ue,{htmlFor:"message",className:"text-sm font-medium",children:"Add a message (optional)"}),e.jsx(vr,{id:"message",placeholder:"I thought you might find this useful...",value:E,onChange:pe=>A(pe.target.value),rows:2,className:"resize-none"})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2 flex-shrink-0",children:[e.jsx(H,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(H,{onClick:Ve,disabled:ze===0||z,children:z?e.jsxs(e.Fragment,{children:[e.jsx(is,{className:"h-4 w-4 mr-2 animate-spin"}),"Sharing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(yn,{className:"h-4 w-4 mr-2"}),"Share"]})})]})]})]})})}function w8({resourceType:s,resourceId:t,resourceTitle:r,variant:n="outline",size:a="sm",className:i=""}){const[l,o]=S.useState(!1),{user:c}=Ms();return c?e.jsxs(e.Fragment,{children:[e.jsxs(H,{variant:n,size:a,onClick:()=>o(!0),className:i,children:[e.jsx(cd,{className:"h-4 w-4 mr-2"}),"Share"]}),e.jsx(ets,{open:l,onOpenChange:o,resourceType:s,resourceId:t,resourceTitle:r})]}):null}function tts(){const{eventId:s}=Po(),t=Fr(),{user:r}=Ms(),[n,a]=S.useState(null),[i,l]=S.useState(null),[o,c]=S.useState(0),[d,h]=S.useState(!0),[m,p]=S.useState(!1);S.useEffect(()=>{s&&x()},[s,r]);const x=async()=>{try{const{data:T,error:E}=await V.from("events").select("*").eq("id",s).single();if(E)throw E;a(T);const{count:A}=await V.from("event_registrations").select("*",{count:"exact",head:!0}).eq("event_id",s);if(c(A||0),r){const{data:D}=await V.from("event_registrations").select("id, zoom_join_url").eq("event_id",s).eq("user_id",r.id).maybeSingle();l(D)}}catch(T){console.error("Error loading event:",T),he.error("Failed to load event"),t("/events")}finally{h(!1)}},y=async()=>{if(!(!r||!n)){p(!0);try{const{error:T}=await V.auth.refreshSession();if(T){console.error("Session refresh failed:",T),he.error("Your session has expired. Please log in again.");return}if(i){const{error:E}=await V.functions.invoke("zoom-unregister",{body:{event_id:n.id}});if(E)throw E;he.success("Successfully cancelled registration"),l(null),c(A=>A-1)}else{const{data:E,error:A}=await V.functions.invoke("zoom-register",{body:{event_id:n.id}});if(A)throw A;he.success("Successfully registered for event!"),l({id:E.registration_id,zoom_join_url:E.zoom_join_url}),c(D=>D+1)}}catch(T){console.error("Registration error:",T),he.error(i?"Failed to cancel registration":"Failed to register for event")}finally{p(!1)}}},_=T=>{var E,A,D;if(T.includes("iframe.mediadelivery.net")||T.includes("video.bunnycdn.com")){const R=T.match(/embed\/(\d+)\/([a-f0-9-]+)/);if(R)return`https://iframe.mediadelivery.net/embed/${R[1]}/${R[2]}?autoplay=false&preload=true`}if(T.includes("youtube.com")||T.includes("youtu.be")){const R=T.includes("youtu.be")?(E=T.split("youtu.be/")[1])==null?void 0:E.split("?")[0]:(A=T.split("v=")[1])==null?void 0:A.split("&")[0];if(R)return`https://www.youtube.com/embed/${R}`}if(T.includes("vimeo.com")){const R=(D=T.split("vimeo.com/")[1])==null?void 0:D.split("?")[0];if(R)return`https://player.vimeo.com/video/${R}`}return T};if(d)return e.jsx(Ss,{title:"Event",children:e.jsx("div",{className:"flex items-center justify-center py-16",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent mx-auto mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:"Loading event..."})]})})});if(!n)return e.jsx(Ss,{title:"Event Not Found",children:e.jsxs("div",{className:"text-center py-16",children:[e.jsx("p",{className:"text-muted-foreground",children:"Event not found"}),e.jsx(H,{onClick:()=>t("/events"),className:"mt-4",children:"Back to Events"})]})});const b=__(new Date(n.event_date)),j=n.capacity&&o>=n.capacity,k=(i==null?void 0:i.zoom_join_url)||n.zoom_link;return e.jsx(Ss,{title:n.title,children:e.jsxs("div",{className:"max-w-4xl mx-auto",children:[e.jsxs(H,{variant:"ghost",className:"mb-6 gap-2",onClick:()=>t("/events"),children:[e.jsx(za,{className:"h-4 w-4"}),"Back to Events"]}),n.image_url&&e.jsxs("div",{className:"relative aspect-video rounded-xl overflow-hidden mb-6",children:[e.jsx("img",{src:n.image_url,alt:n.title,className:"w-full h-full object-cover"}),b&&e.jsx("div",{className:"absolute inset-0 bg-black/50 flex items-center justify-center",children:e.jsx(Xe,{variant:"secondary",className:"text-lg px-4 py-2",children:"Event Ended"})})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsxs("div",{className:"lg:col-span-2 space-y-6",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-start justify-between gap-4 mb-4",children:[e.jsx("h1",{className:"text-3xl font-bold text-foreground",children:n.title}),e.jsx(w8,{resourceType:"event",resourceId:n.id,resourceTitle:n.title})]}),n.description&&e.jsx("div",{className:"prose prose-sm max-w-none text-muted-foreground dark:prose-invert",dangerouslySetInnerHTML:{__html:n.description}})]}),n.video_url&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("h3",{className:"text-lg font-semibold flex items-center gap-2",children:[e.jsx(cg,{className:"h-5 w-5"}),"Event Preview"]}),e.jsx("div",{className:"relative w-full aspect-video rounded-xl overflow-hidden border bg-muted",children:e.jsx("iframe",{src:_(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"})})]})]}),e.jsx("div",{className:"space-y-4",children:e.jsx(ke,{children:e.jsxs(Oe,{className:"p-6 space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Nn,{className:"h-5 w-5 text-primary mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:new Intl.DateTimeFormat("en-US",{weekday:"long",year:"numeric",month:"long",day:"numeric",timeZone:"America/New_York"}).format(new Date(n.event_date))}),e.jsx("p",{className:"text-sm text-muted-foreground",children:g9(new Date(n.event_date))})]})]}),n.capacity&&e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Ar,{className:"h-5 w-5 text-primary mt-0.5"}),e.jsxs("div",{children:[e.jsxs("p",{className:"font-medium",children:[o," / ",n.capacity]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Registered"})]})]}),i&&e.jsxs("div",{className:"flex items-center gap-2 p-3 bg-green-500/10 rounded-lg",children:[e.jsx(zi,{className:"h-5 w-5 text-green-600"}),e.jsx("span",{className:"text-sm font-medium text-green-700",children:"You're registered!"})]}),e.jsxs("div",{className:"space-y-2 pt-2",children:[!b&&e.jsx(e.Fragment,{children:i?e.jsxs(e.Fragment,{children:[e.jsxs(H,{className:"w-full gap-2",onClick:()=>window.open(k,"_blank"),children:[e.jsx(gn,{className:"h-4 w-4"}),"Join Event"]}),e.jsxs(H,{variant:"outline",className:"w-full",onClick:y,disabled:m,children:[m?e.jsx(is,{className:"h-4 w-4 animate-spin mr-2"}):null,"Cancel Registration"]})]}):e.jsx(H,{className:"w-full gap-2",onClick:y,disabled:m||(j??!1),children:m?e.jsx(is,{className:"h-4 w-4 animate-spin"}):j?"Event Full":"Register Now"})}),b&&i&&e.jsxs(H,{variant:"outline",className:"w-full gap-2",onClick:()=>window.open(n.zoom_link,"_blank"),children:[e.jsx(gn,{className:"h-4 w-4"}),"View Recording"]})]})]})})})]})]})})}const sts=[{id:"quickvid",name:"QuickVid",description:"Record, manage, and share personalized video messages",icon:e.jsx(xn,{className:"h-6 w-6"}),path:"/mission-control/video/record",category:"Marketing",color:"bg-rose-500/15 text-rose-600"},{id:"smart-card",name:"Smart Card",description:"Your digital business card — share your info with a single link",icon:e.jsx(u0,{className:"h-6 w-6"}),path:"/mission-control/my-card",category:"Marketing",color:"bg-sky-500/15 text-sky-600"},{id:"smart-presentations",name:"Smart Presentations",description:"Create beautiful listing and buyer presentations",icon:e.jsx(_1,{className:"h-6 w-6"}),path:"/mission-control/presentations",category:"Marketing",color:"bg-amber-500/15 text-amber-600"},{id:"landing-pages",name:"Landing Pages",description:"Build custom landing pages to capture leads",icon:e.jsx(kn,{className:"h-6 w-6"}),path:"/mission-control/landing-pages",category:"Marketing",color:"bg-emerald-500/15 text-emerald-600"},{id:"guest-book",name:"Guest Book",description:"Digital open house sign-in to capture visitor info",icon:e.jsx(tf,{className:"h-6 w-6"}),path:"/mission-control/guest-book",category:"Open House",color:"bg-orange-500/15 text-orange-600"},{id:"card-studio",name:"Card Studio",description:"Send beautiful animated digital cards for birthdays, anniversaries & milestones",icon:e.jsx(Lr,{className:"h-6 w-6"}),path:"/mission-control/card-studio",category:"Marketing",color:"bg-pink-500/15 text-pink-600"},{id:"direct-mail",name:"Direct Mail",description:"Send professional postcards to your contacts via direct mail",icon:e.jsx(er,{className:"h-6 w-6"}),path:"/mission-control/direct-mail",category:"Marketing",adminOnly:!0,beta:!0,color:"bg-indigo-500/15 text-indigo-600"},{id:"reelflow",name:"ReelFlow",description:"Turn property photos into cinematic video clips and reels — powered by AI",icon:e.jsx(Qm,{className:"h-6 w-6"}),path:"/admin/beta/homereel",category:"Marketing",beta:!0,isNew:!0,color:"bg-violet-500/15 text-violet-600"},{id:"mass-emails",name:"Mass Emails",description:"Create and send bulk email campaigns to your contacts",icon:e.jsx(yn,{className:"h-6 w-6"}),path:"/admin/email-campaigns",category:"Marketing",beta:!0,color:"bg-teal-500/15 text-teal-600"},{id:"listing-studio",name:"Listing Studio",description:"Generate MLS descriptions, luxury copy, open house blurbs and more — powered by AI",icon:e.jsx(Gb,{className:"h-6 w-6"}),path:"/mission-control/listing-studio",category:"Marketing",isNew:!0,color:"bg-fuchsia-500/15 text-fuchsia-600"},{id:"website-apps",name:"Website Apps",description:"Drop-in conversion widgets for your website — Video Greeter & more",icon:e.jsx(_F,{className:"h-6 w-6"}),path:"/website-apps",category:"Website",isNew:!0,color:"bg-cyan-500/15 text-cyan-600"}],rts=()=>{const{user:s,isAdmin:t}=Ms(),r=Fr(),[n,a]=S.useState([]),[i,l]=S.useState(!0),[o,c]=S.useState(""),[d,h]=S.useState("all"),[m,p]=S.useState(new Set),[x,y]=S.useState(new Set);S.useEffect(()=>{_()},[s]);const _=async()=>{try{const{data:O}=await V.from("user_tags").select("tag").eq("user_id",s==null?void 0:s.id),$=(O==null?void 0:O.map(le=>le.tag))||[],{data:ee,error:Z}=await V.from("app_tiles").select("*").order("name");if(Z)throw Z;const[{data:J},{data:K}]=await Promise.all([V.from("user_favorites").select("app_id").eq("user_id",s==null?void 0:s.id),V.from("user_tool_favorites").select("tool_id").eq("user_id",s==null?void 0:s.id)]),re=new Set((J==null?void 0:J.map(le=>le.app_id))||[]);p(re);const ie=new Set((K||[]).map(le=>le.tool_id));y(ie);const ne=((ee==null?void 0:ee.filter(le=>!le.required_tags||le.required_tags.length===0?!0:le.required_tags.some(be=>$.includes(be))))||[]).sort((le,be)=>le.name==="LevelUp Members Portal"?-1:be.name==="LevelUp Members Portal"?1:0);a(ne)}catch(O){console.error("Error loading apps:",O),he.error("Failed to load apps")}finally{l(!1)}},b=async O=>{var ee;const $=window.open("about:blank","_blank");try{const{data:Z,error:J}=await V.auth.getSession();if(J||!Z.session){$==null||$.close(),he.error("Session expired. Please refresh the page and try again.");return}const K=Z.session.access_token;await V.from("activity_logs").insert({user_id:s==null?void 0:s.id,app_id:O.app_id,app_name:O.name,user_agent:navigator.userAgent});const{data:re,error:ie}=await V.functions.invoke("sso-launch",{body:{app_id:O.app_id},headers:{Authorization:`Bearer ${K}`}});if(ie)throw ie;re!=null&&re.redirect_url?$&&!$.closed?($.location.href=re.redirect_url,(ee=$.focus)==null||ee.call($)):window.location.assign(re.redirect_url):($==null||$.close(),he.error("Launch link unavailable"))}catch(Z){$==null||$.close(),console.error("Error launching app:",Z),he.error("Failed to launch app. Please try again.")}},j=async(O,$)=>{O.stopPropagation();const ee=m.has($);try{if(ee){const{error:Z}=await V.from("user_favorites").delete().eq("user_id",s==null?void 0:s.id).eq("app_id",$);if(Z)throw Z;p(J=>{const K=new Set(J);return K.delete($),K}),he.success("Removed from favorites")}else{const{error:Z}=await V.from("user_favorites").insert({user_id:s==null?void 0:s.id,app_id:$});if(Z)throw Z;p(J=>new Set(J).add($)),he.success("Added to favorites")}}catch(Z){console.error("Error toggling favorite:",Z),he.error("Failed to update favorites")}},k=async(O,$)=>{O.stopPropagation();const ee=x.has($);try{if(ee){const{error:Z}=await V.from("user_tool_favorites").delete().eq("user_id",s==null?void 0:s.id).eq("tool_id",$);if(Z)throw Z;y(J=>{const K=new Set(J);return K.delete($),K}),he.success("Removed from favorites")}else{const{error:Z}=await V.from("user_tool_favorites").insert({user_id:s==null?void 0:s.id,tool_id:$});if(Z)throw Z;y(J=>new Set(J).add($)),he.success("Added to favorites")}}catch(Z){console.error("Error toggling tool favorite:",Z),he.error("Failed to update favorites")}},T=n.filter(O=>{var ee;const $=O.name.toLowerCase().includes(o.toLowerCase())||((ee=O.description)==null?void 0:ee.toLowerCase().includes(o.toLowerCase()));return d==="favorites"?$&&m.has(O.id):$}),E=sts.filter(O=>{if(O.adminOnly&&!t)return!1;const $=O.name.toLowerCase().includes(o.toLowerCase())||O.description.toLowerCase().includes(o.toLowerCase());return d==="favorites"?$&&x.has(O.id):$}),A=E.reduce((O,$)=>(O[$.category]||(O[$.category]=[]),O[$.category].push($),O),{}),D=[{id:"all",label:"All"},{id:"tools",label:"Built-in Tools"},{id:"apps",label:"Connected Apps"},{id:"favorites",label:"Favorites"}];if(i)return e.jsx(Ss,{title:"Apps & Tools",children:e.jsx("div",{className:"flex items-center justify-center py-16",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent mx-auto mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:"Loading apps & tools..."})]})})});const R=d==="all"||d==="tools"||d==="favorites",z=d==="all"||d==="apps"||d==="favorites";return e.jsxs(Ss,{title:"Apps & Tools",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6",children:[e.jsx("h2",{className:"text-2xl font-bold text-foreground",children:"Apps & Tools"}),e.jsxs("div",{className:"relative max-w-sm w-full",children:[e.jsx(Mn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Se,{placeholder:"Search apps & tools...",className:"pl-10 bg-muted/50 border-0 focus-visible:ring-1",value:o,onChange:O=>c(O.target.value)})]})]}),e.jsx("div",{className:"flex gap-6 border-b border-border mb-8",children:D.map(O=>e.jsxs("button",{onClick:()=>h(O.id),className:Ft("pb-3 text-sm font-medium transition-colors relative",d===O.id?"text-primary":"text-muted-foreground hover:text-foreground"),children:[O.label,d===O.id&&e.jsx("span",{className:"absolute bottom-0 left-0 right-0 h-0.5 bg-primary"})]},O.id))}),R&&Object.keys(A).length>0&&e.jsxs("div",{className:"mb-10",children:[d==="all"&&e.jsxs("div",{className:"flex items-center gap-2 mb-5",children:[e.jsx(N1,{className:"h-5 w-5 text-primary"}),e.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Built-in Tools"})]}),Object.entries(A).map(([O,$])=>e.jsxs("div",{className:"mb-6",children:[e.jsx("div",{className:"flex items-center gap-2 mb-3",children:e.jsx("span",{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground bg-muted px-2.5 py-1 rounded-full",children:O})}),e.jsx("div",{className:"grid gap-4 md:grid-cols-2 xl:grid-cols-3",children:$.map(ee=>{const Z=x.has(ee.id);return e.jsxs("div",{onClick:()=>r(ee.path),className:Ft("group flex items-start gap-4 p-5 bg-card rounded-xl border transition-all duration-200 hover:shadow-lg cursor-pointer relative overflow-hidden",ee.isNew?"border-primary/40 ring-1 ring-primary/20 hover:border-primary/60":"border-border hover:border-primary/30"),children:[ee.isNew&&e.jsx("div",{className:"absolute top-0 right-0 bg-gradient-to-r from-violet-500 to-indigo-500 text-white text-[10px] font-bold uppercase px-3 py-0.5 rounded-bl-lg tracking-wider shadow-sm",children:"✨ New"}),e.jsx("div",{className:Ft("flex-shrink-0 w-14 h-14 rounded-xl flex items-center justify-center transition-transform group-hover:scale-105",ee.color||"bg-primary/10 text-primary"),children:ee.icon}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("h3",{className:"font-semibold text-foreground group-hover:text-primary transition-colors truncate flex items-center gap-2",children:[ee.name,ee.beta&&e.jsx("span",{className:"text-[10px] font-semibold bg-amber-100 text-amber-700 px-1.5 py-0.5 rounded-full border border-amber-200",children:"Beta"})]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 line-clamp-2",children:ee.description})]}),e.jsx("button",{className:Ft("flex-shrink-0 p-1 transition-colors",Z?"text-primary":"text-muted-foreground/50 hover:text-primary"),onClick:J=>k(J,ee.id),children:e.jsx(Uy,{className:Ft("h-5 w-5",Z&&"fill-current")})})]},ee.id)})})]},O))]}),z&&e.jsxs("div",{children:[d==="all"&&T.length>0&&e.jsxs("div",{className:"flex items-center gap-2 mb-5",children:[e.jsx(gn,{className:"h-5 w-5 text-primary"}),e.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Connected Apps"})]}),T.length===0&&d!=="all"&&!(d==="favorites"&&E.length>0)?e.jsx("div",{className:"flex flex-col items-center justify-center py-16 bg-card rounded-xl border border-border",children:d==="favorites"?e.jsxs(e.Fragment,{children:[e.jsx(Uy,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("p",{className:"text-lg font-medium mb-2 text-foreground",children:"No favorites yet"}),e.jsx("p",{className:"text-sm text-muted-foreground text-center max-w-md",children:"Click the bookmark icon on any app or tool to add it to your favorites"})]}):e.jsxs(e.Fragment,{children:[e.jsx(Td,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("p",{className:"text-lg font-medium mb-2 text-foreground",children:"No apps available"}),e.jsx("p",{className:"text-sm text-muted-foreground text-center max-w-md",children:t?"Get started by adding apps in the admin panel":"Contact your administrator to get access to apps"}),t&&e.jsx(H,{className:"mt-4",onClick:()=>r("/admin/apps"),children:"Add Apps"})]})}):e.jsx("div",{className:"grid gap-4 md:grid-cols-2 xl:grid-cols-3",children:T.map(O=>{const $=m.has(O.id),ee=O.name.toLowerCase().includes("agent review")||O.app_id==="agent_review";return e.jsxs("div",{className:"group flex flex-col p-5 bg-card rounded-xl border border-border transition-all duration-200 hover:shadow-lg hover:border-primary/30",children:[e.jsxs("div",{className:"flex items-start gap-4 cursor-pointer",onClick:()=>b(O),children:[e.jsx("div",{className:"flex-shrink-0 w-14 h-14 rounded-xl bg-primary/10 flex items-center justify-center text-3xl",children:O.icon}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-semibold text-foreground group-hover:text-primary transition-colors truncate",children:O.name}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 line-clamp-2",children:O.description})]}),e.jsx("button",{className:Ft("flex-shrink-0 p-1 transition-colors",$?"text-primary":"text-muted-foreground/50 hover:text-primary"),onClick:Z=>j(Z,O.id),children:e.jsx(Uy,{className:Ft("h-5 w-5",$&&"fill-current")})})]}),ee&&e.jsx("a",{href:"https://forms.gle/vXnrzgSnPbw7CKPV6",target:"_blank",rel:"noopener noreferrer",onClick:Z=>Z.stopPropagation(),className:"mt-3 text-sm text-primary hover:underline flex items-center gap-1",children:"Create your account with this link →"})]},O.id)})})]}),R&&z&&T.length===0&&E.length===0&&o&&e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 bg-card rounded-xl border border-border",children:[e.jsx(Mn,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("p",{className:"text-lg font-medium mb-2 text-foreground",children:"No results found"}),e.jsx("p",{className:"text-sm text-muted-foreground text-center max-w-md",children:"Try a different search term"})]})]})},nts=()=>{var T;const s=Fr(),{isAdmin:t}=Ms(),[r,n]=S.useState(""),[a,i]=S.useState("all"),[l,o]=S.useState("all"),[c,d]=S.useState("grid"),{data:h=[]}=yt({queryKey:["template-categories"],queryFn:async()=>{const{data:E,error:A}=await V.from("template_categories").select("*").order("name");if(A)throw A;return E}}),{data:m=[]}=yt({queryKey:["template-types"],queryFn:async()=>{const{data:E,error:A}=await V.from("template_types").select("*").order("name");if(A)throw A;return E}}),{data:p=[],isLoading:x}=yt({queryKey:["canva-templates",t],queryFn:async()=>{const{data:E,error:A}=await V.from("canva_templates").select(` *, category:template_categories(id, name), type:template_types(id, name) `).order("publish_date",{ascending:!1});if(A)throw A;const{data:D,error:R}=await V.from("template_links").select("*").order("sort_order");if(R)throw R;const z=async re=>{let ce=0;const ne=[];for(;;){const{data:le,error:be}=await re().range(ce,ce+1e3-1);if(be)throw be;if(!le||le.length===0||(ne.push(...le),le.length<1e3))break;ce+=1e3}return ne},O=await z(()=>V.from("template_likes").select("template_id")),$=await z(()=>V.from("template_comments").select("template_id")),ee=new Map;O.forEach(re=>{ee.set(re.template_id,(ee.get(re.template_id)||0)+1)});const Z=new Map;$.forEach(re=>{Z.set(re.template_id,(Z.get(re.template_id)||0)+1)});const J=new Map;return t&&(await z(()=>V.from("content_engagement_logs").select("resource_id").eq("resource_type","template").eq("action_type","view"))).forEach(ie=>{J.set(ie.resource_id,(J.get(ie.resource_id)||0)+1)}),(E||[]).map(re=>({...re,links:(D||[]).filter(ie=>ie.template_id===re.id)||[],likesCount:ee.get(re.id)||0,commentsCount:Z.get(re.id)||0,viewsCount:J.get(re.id)||0}))}}),y=p.filter(E=>{var z;const A=E.name.toLowerCase().includes(r.toLowerCase())||((z=E.description)==null?void 0:z.toLowerCase().includes(r.toLowerCase())),D=a==="all"||E.category_id===a,R=l==="all"||E.type_id===l;return A&&D&&R}),_=()=>{n(""),i("all"),o("all")},b=r||a!=="all"||l!=="all",j=(T=[...p].sort((E,A)=>new Date(A.publish_date||A.created_at).getTime()-new Date(E.publish_date||E.created_at).getTime())[0])==null?void 0:T.id,k=E=>{s(`/templates/${E}`)};return e.jsx(Ss,{title:"Canva Templates",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"font-bold text-foreground text-5xl",children:"Canva Templates"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Browse and use our collection of professionally designed templates"})]}),!x&&p.filter(E=>E.is_featured).length>0&&e.jsxs("div",{className:"rounded-xl p-5 space-y-3",style:{backgroundColor:"#9aa8b2"},children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ya,{className:"h-5 w-5 fill-foreground text-foreground"}),e.jsx("h2",{className:"text-xl font-semibold text-foreground",children:"Featured Templates"})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4",children:p.filter(E=>E.is_featured).slice(0,4).map(E=>e.jsxs(ke,{className:"group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer relative",onClick:()=>k(E.id),children:[e.jsxs("div",{className:"aspect-[3/2] relative overflow-hidden bg-muted",children:[E.id===j&&e.jsx(Xe,{className:"absolute top-2 left-2 z-10 font-bold border-0 hover:opacity-90",style:{backgroundColor:"#e8c369",color:"#3d2f0a"},children:"NEW!"}),E.preview_image_url?e.jsx("img",{src:E.preview_image_url,alt:E.name,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground",children:"No Preview"})]}),e.jsxs(Oe,{className:"p-3",children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1 text-sm",children:E.name}),E.description&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 mt-1",children:Q7(E.description)})]})]},E.id))})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1 max-w-sm",children:[e.jsx(Mn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Se,{placeholder:"Search templates...",value:r,onChange:E=>n(E.target.value),className:"pl-9"})]}),e.jsxs(Bs,{value:a,onValueChange:i,children:[e.jsx(Os,{className:"w-full sm:w-48",children:e.jsx(Us,{placeholder:"All Categories"})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"all",children:"All Categories"}),h.map(E=>e.jsx(pt,{value:E.id,children:E.name},E.id))]})]}),e.jsxs(Bs,{value:l,onValueChange:o,children:[e.jsx(Os,{className:"w-full sm:w-48",children:e.jsx(Us,{placeholder:"All Types"})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"all",children:"All Types"}),m.map(E=>e.jsx(pt,{value:E.id,children:E.name},E.id))]})]}),e.jsxs("div",{className:"flex gap-2",children:[b&&e.jsx(H,{variant:"outline",size:"sm",onClick:_,children:"Clear Filters"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(H,{variant:c==="grid"?"secondary":"outline",size:"icon",onClick:()=>d("grid"),className:"rounded-full",children:e.jsx(_g,{className:"h-4 w-4"})}),e.jsx(H,{variant:c==="list"?"secondary":"outline",size:"icon",onClick:()=>d("list"),className:"rounded-full",children:e.jsx(Vf,{className:"h-4 w-4"})})]})]})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[y.length," template",y.length!==1?"s":""," found"]}),x&&e.jsx("div",{className:c==="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((E,A)=>e.jsx(ke,{children:e.jsxs(Oe,{className:"p-4",children:[e.jsx(Ks,{className:"aspect-[4/3] w-full rounded-lg mb-4"}),e.jsx(Ks,{className:"h-5 w-3/4 mb-2"}),e.jsx(Ks,{className:"h-4 w-full mb-4"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ks,{className:"h-5 w-16"}),e.jsx(Ks,{className:"h-5 w-20"})]})]})},A))}),!x&&y.length===0&&e.jsxs("div",{className:"text-center py-12",children:[e.jsx("div",{className:"text-muted-foreground mb-4",children:b?"No templates match your filters":"No templates available yet"}),b&&e.jsx(H,{variant:"outline",onClick:_,children:"Clear Filters"})]}),!x&&y.length>0&&e.jsx("div",{className:c==="grid"?"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6":"space-y-4",children:y.map(E=>e.jsxs(ke,{className:`group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer ${c==="list"?"flex flex-row":""}`,onClick:()=>k(E.id),children:[e.jsxs("div",{className:`relative overflow-hidden bg-muted ${c==="list"?"w-48 shrink-0":"aspect-[3/2]"}`,children:[E.id===j&&e.jsx(Xe,{className:"absolute top-2 left-2 z-10 font-bold border-0 hover:opacity-90",style:{backgroundColor:"#e8c369",color:"#3d2f0a"},children:"NEW!"}),E.preview_image_url?e.jsx("img",{src:E.preview_image_url,alt:E.name,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground",children:"No Preview"}),E.links.length>1&&e.jsx("div",{className:"absolute top-2 right-2",children:e.jsxs(Xe,{variant:"secondary",className:"gap-1 bg-background/90 backdrop-blur-sm !text-secondary",children:[e.jsx(Jo,{className:"h-3 w-3"}),E.links.length]})})]}),e.jsxs(Oe,{className:`p-4 flex flex-col ${c==="list"?"flex-1":""}`,children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1 mb-1",children:E.name}),E.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-3 flex-1",children:Q7(E.description)}),e.jsxs("div",{className:"flex flex-wrap gap-2 mb-3",children:[E.category&&e.jsx(Xe,{variant:"secondary",className:"text-xs",children:E.category.name}),E.type&&e.jsx(Xe,{variant:"outline",className:"text-xs",children:E.type.name})]}),e.jsxs("div",{className:"flex items-center gap-4 text-sm text-muted-foreground mb-3",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(sf,{className:"h-3.5 w-3.5"}),E.likesCount]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(qc,{className:"h-3.5 w-3.5"}),E.commentsCount]}),t&&e.jsxs("span",{className:"flex items-center gap-1",title:"Total views (admin only)",children:[e.jsx(Bn,{className:"h-3.5 w-3.5"}),E.viewsCount]})]}),e.jsxs(H,{size:"sm",className:"w-full gap-2",onClick:A=>{A.stopPropagation(),k(E.id)},children:[e.jsx(gn,{className:"h-4 w-4"}),"View Template"]})]})]},E.id))})]})})};var ats="Separator",XBe="horizontal",its=["horizontal","vertical"],vdt=S.forwardRef((s,t)=>{const{decorative:r,orientation:n=XBe,...a}=s,i=ots(n)?n:XBe,o=r?{role:"none"}:{"aria-orientation":i==="vertical"?i:void 0,role:"separator"};return e.jsx(Vn.div,{"data-orientation":i,...o,...a,ref:t})});vdt.displayName=ats;function ots(s){return its.includes(s)}var bdt=vdt;const Qo=S.forwardRef(({className:s,orientation:t="horizontal",decorative:r=!0,...n},a)=>e.jsx(bdt,{ref:a,decorative:r,orientation:t,className:Ft("shrink-0 bg-border",t==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",s),...n}));Qo.displayName=bdt.displayName;const lts=()=>{const{templateId:s}=Po(),t=Fr(),{user:r,isAdmin:n}=Ms(),{toast:a}=li(),i=ns(),{trackEngagement:l}=y8(),[o,c]=S.useState(""),{data:d,isLoading:h}=yt({queryKey:["template-detail",s],queryFn:async()=>{const{data:E,error:A}=await V.from("canva_templates").select(` *, category:template_categories(id, name), type:template_types(id, name) `).eq("id",s).single();if(A)throw A;const{data:D}=await V.from("template_links").select("*").eq("template_id",s).order("sort_order"),{data:R}=await V.from("template_guides").select("*").eq("template_id",s).order("sort_order");return{...E,links:D||[],guides:R||[]}},enabled:!!s}),{data:m=[]}=yt({queryKey:["template-linked-toolkits",s],queryFn:async()=>{const{data:E,error:A}=await V.from("resource_kit_templates").select("kit_id, resource_kits:kit_id(id, name, featured_image_url)").eq("template_id",s);if(A)throw A;return(E||[]).map(D=>D.resource_kits).filter(Boolean)},enabled:!!s});S.useEffect(()=>{d&&l("template",d.id,d.name,"view")},[d==null?void 0:d.id]);const{data:p=[]}=yt({queryKey:["template-likes",s],queryFn:async()=>{const{data:E,error:A}=await V.from("template_likes").select("*").eq("template_id",s);if(A)throw A;return E},enabled:!!s}),{data:x=[]}=yt({queryKey:["template-comments",s],queryFn:async()=>{const{data:E,error:A}=await V.from("template_comments").select("*").eq("template_id",s).order("created_at",{ascending:!1});if(A)throw A;const D=[...new Set(E.map(O=>O.user_id))],{data:R}=await V.from("profiles").select("id, name").in("id",D),z=new Map((R==null?void 0:R.map(O=>[O.id,O.name]))||[]);return E.map(O=>({...O,user_name:z.get(O.user_id)||"Unknown User"}))},enabled:!!s}),y=Pt({mutationFn:async E=>{const{error:A}=await V.from("template_comments").insert({template_id:s,user_id:r.id,content:E});if(A)throw A},onSuccess:()=>{i.invalidateQueries({queryKey:["template-comments",s]}),c(""),a({title:"Comment added!"})},onError:E=>{a({title:"Error adding comment",description:E.message,variant:"destructive"})}}),_=Pt({mutationFn:async E=>{const{error:A}=await V.from("template_comments").delete().eq("id",E);if(A)throw A},onSuccess:()=>{i.invalidateQueries({queryKey:["template-comments",s]}),a({title:"Comment deleted"})}}),b=Pt({mutationFn:async()=>{const E=p.find(A=>A.user_id===(r==null?void 0:r.id));if(E){const{error:A}=await V.from("template_likes").delete().eq("id",E.id);if(A)throw A}else{const{error:A}=await V.from("template_likes").insert({template_id:s,user_id:r.id});if(A)throw A}},onSuccess:()=>{i.invalidateQueries({queryKey:["template-likes",s]})}}),j=p.some(E=>E.user_id===(r==null?void 0:r.id)),k=E=>E.split(" ").map(A=>A[0]).join("").toUpperCase().slice(0,2),T=E=>{E.preventDefault(),!(!o.trim()||!r)&&y.mutate(o.trim())};return h?e.jsx(Ss,{title:"Templates",children:e.jsx("div",{className:"flex justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):d?e.jsx(Ss,{title:d.name,children:e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsx(H,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(Xn,{to:"/templates",children:[e.jsx(za,{className:"h-4 w-4"}),"Back to Templates"]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-start sm:justify-between gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:d.name}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[d.category&&e.jsx(Xe,{variant:"secondary",children:d.category.name}),d.type&&e.jsx(Xe,{variant:"outline",children:d.type.name})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[n&&e.jsx(H,{variant:"outline",className:"gap-2 rounded-full",asChild:!0,children:e.jsxs(Xn,{to:`/admin/templates?edit=${d.id}`,children:[e.jsx(ni,{className:"h-4 w-4"}),e.jsx("span",{children:"Edit"})]})}),e.jsx(w8,{resourceType:"template",resourceId:d.id,resourceTitle:d.name,size:"default",className:"rounded-full"}),e.jsxs(H,{variant:j?"default":"outline",className:"gap-2 rounded-full",onClick:()=>b.mutate(),disabled:!r||b.isPending,children:[e.jsx(sf,{className:`h-4 w-4 ${j?"fill-current":""}`}),p.length," ",p.length===1?"Like":"Likes"]})]})]}),d.description&&e.jsx("div",{className:"text-muted-foreground prose prose-sm max-w-none dark:prose-invert [&>p]:mb-4 [&>p:last-child]:mb-0 whitespace-pre-line",dangerouslySetInnerHTML:{__html:d.description}})]}),e.jsx(ke,{children:e.jsxs(Oe,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Jo,{className:"h-4 w-4"}),d.links.length===1?"Template Link":"Template Links"]}),e.jsx("div",{className:"grid gap-2",children:d.links.map(E=>e.jsxs(H,{variant:"outline",className:"w-full justify-between gap-2 h-auto py-3",onClick:()=>{l("template",d.id,d.name,"click_canva"),window.open(E.canva_share_link,"_blank")},children:[e.jsx("span",{className:"font-medium",children:E.title}),e.jsx(gn,{className:"h-4 w-4 text-muted-foreground"})]},E.id))})]})}),d.video_url&&e.jsx(ke,{children:e.jsx(Oe,{className:"pt-6",children:e.jsx("div",{className:"aspect-video w-full rounded-lg overflow-hidden",children:e.jsx("iframe",{src:d.video_url,className:"w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})})})}),d.guides&&d.guides.length>0&&e.jsx(ke,{children:e.jsxs(Oe,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(kn,{className:"h-4 w-4"}),"Guide Files"]}),e.jsx("div",{className:"grid gap-2",children:d.guides.map(E=>e.jsxs(H,{variant:"outline",className:"w-full justify-between gap-2 h-auto py-3",onClick:()=>{l("template",d.id,d.name,"click_pdf"),window.open(E.file_url,"_blank")},children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(kn,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"font-medium",children:E.name}),E.file_size&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",(E.file_size/1024).toFixed(0)," KB)"]})]}),e.jsx(hi,{className:"h-4 w-4 text-muted-foreground"})]},E.id))})]})}),m.length>0&&e.jsx(ke,{children:e.jsxs(Oe,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(yc,{className:"h-4 w-4"}),"Related Toolkits"]}),e.jsx("div",{className:"grid gap-2",children:m.map(E=>e.jsxs(H,{variant:"outline",className:"w-full justify-start gap-3 h-auto py-3",onClick:()=>t(`/toolbox/${E.id}`),children:[E.featured_image_url?e.jsx("img",{src:E.featured_image_url,alt:"",className:"w-10 h-10 rounded object-cover flex-shrink-0"}):e.jsx("div",{className:"w-10 h-10 rounded bg-muted flex items-center justify-center flex-shrink-0",children:e.jsx(yc,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{className:"font-medium",children:E.name})]},E.id))})]})}),e.jsx(Qo,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 text-lg",children:[e.jsx(qc,{className:"h-5 w-5"}),"Comments (",x.length,")"]}),r?e.jsxs("form",{onSubmit:T,className:"flex gap-2",children:[e.jsx(vr,{placeholder:"Add a comment...",value:o,onChange:E=>c(E.target.value),className:"min-h-[80px] resize-none flex-1"}),e.jsx(H,{type:"submit",size:"icon",className:"h-10 w-10",disabled:!o.trim()||y.isPending,children:e.jsx(yn,{className:"h-4 w-4"})})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Log in to add a comment"}),e.jsx("div",{className:"space-y-4",children:x.length===0?e.jsx(ke,{children:e.jsx(Oe,{className:"py-8 text-center",children:e.jsx("p",{className:"text-muted-foreground",children:"No comments yet. Be the first to share your thoughts!"})})}):x.map(E=>e.jsx(ke,{children:e.jsx(Oe,{className:"pt-4 pb-4",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Un,{className:"h-10 w-10 flex-shrink-0",children:e.jsx(qn,{className:"text-sm",children:k(E.user_name||"U")})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"font-medium",children:E.user_name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:Hl(new Date(E.created_at),{addSuffix:!0})}),E.user_id===(r==null?void 0:r.id)&&e.jsx(H,{variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>_.mutate(E.id),children:e.jsx(Dr,{className:"h-3 w-3 text-muted-foreground"})})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:E.content})]})]})})},E.id))})]})]})}):e.jsx(Ss,{title:"Templates",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Jo,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold",children:"Template not found"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"This template may have been removed or is not available."}),e.jsx(H,{asChild:!0,className:"mt-4",children:e.jsx(Xn,{to:"/templates",children:"Back to Templates"})})]})})},cts=()=>{const{user:s}=Ms(),[t,r]=S.useState(""),[n,a]=S.useState("all"),{data:i=[]}=yt({queryKey:["academy-categories"],queryFn:async()=>{const{data:p,error:x}=await V.from("academy_categories").select("*").order("sort_order",{ascending:!0});if(x)throw x;return p}}),{data:l=[],isLoading:o}=yt({queryKey:["academy-videos"],queryFn:async()=>{const{data:p,error:x}=await V.from("academy_videos").select(` *, category:academy_categories(id, name) `).eq("is_published",!0).order("publish_date",{ascending:!1});if(x)throw x;const{data:y,error:_}=await V.from("academy_resources").select("*").order("sort_order");if(_)throw _;return p.map(j=>({...j,resources:(y==null?void 0:y.filter(k=>k.video_id===j.id))||[]}))}}),{data:c=[]}=yt({queryKey:["academy-video-likes"],queryFn:async()=>{const{data:p,error:x}=await V.from("academy_video_likes").select("video_id, user_id");if(x)throw x;return p}}),d=l.filter(p=>{var _;const x=t===""||p.title.toLowerCase().includes(t.toLowerCase())||((_=p.description)==null?void 0:_.toLowerCase().includes(t.toLowerCase())),y=n==="all"||p.category_id===n;return x&&y}),h=p=>c.filter(x=>x.video_id===p).length,m=p=>c.some(x=>x.video_id===p&&x.user_id===(s==null?void 0:s.id));return e.jsx(Ss,{title:"Academy",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-5xl font-bold text-foreground",children:"Academy"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"On-demand training videos and resources"})]}),e.jsx("div",{className:"flex flex-col sm:flex-row gap-4",children:e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Mn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Se,{placeholder:"Search videos...",value:t,onChange:p=>r(p.target.value),className:"pl-10"})]})}),e.jsx(ta,{value:n,onValueChange:a,children:e.jsxs(Qn,{className:"w-full justify-start flex-wrap h-auto gap-2 bg-transparent p-0",children:[e.jsx(ts,{value:"all",className:"data-[state=active]:bg-primary data-[state=active]:text-primary-foreground",children:"All Videos"}),i.map(p=>e.jsx(ts,{value:p.id,className:"data-[state=active]:bg-primary data-[state=active]:text-primary-foreground",children:p.name},p.id))]})}),o?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):d.length===0?e.jsx(ke,{children:e.jsxs(Oe,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(xn,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold",children:"No videos found"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:t?"Try adjusting your search terms":"Check back soon for new content"})]})}):e.jsx("div",{className:"grid gap-6 sm:grid-cols-2 lg:grid-cols-3",children:d.map(p=>e.jsx(Xn,{to:`/academy/${p.id}`,children:e.jsxs(ke,{className:"overflow-hidden cursor-pointer hover:shadow-lg transition-shadow group h-full",children:[e.jsxs("div",{className:"relative aspect-video bg-muted",children:[p.thumbnail_url?e.jsx("img",{src:p.thumbnail_url,alt:p.title,className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(xn,{className:"h-12 w-12 text-muted-foreground"})}),e.jsx("div",{className:"absolute inset-0 bg-black/40 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center",children:e.jsx("div",{className:"w-16 h-16 rounded-full bg-primary/90 flex items-center justify-center",children:e.jsx(El,{className:"h-8 w-8 text-primary-foreground ml-1"})})}),p.duration&&e.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:[e.jsx(Pn,{className:"h-3 w-3"}),p.duration]})]}),e.jsxs(Ot,{className:"pb-2",children:[e.jsx("div",{className:"flex items-start justify-between gap-2",children:e.jsx(zt,{className:"text-lg line-clamp-2",children:p.title})}),p.category&&e.jsx(Xe,{variant:"secondary",className:"w-fit",children:p.category.name})]}),e.jsxs(Oe,{className:"pt-0",children:[p.description&&e.jsx(Br,{className:"line-clamp-2",children:p.description.replace(/<[^>]*>/g,"")}),e.jsxs("div",{className:"flex items-center gap-4 mt-3 text-sm text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(sf,{className:`h-4 w-4 ${m(p.id)?"fill-primary text-primary":""}`}),h(p.id)]}),p.resources&&p.resources.length>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(kn,{className:"h-4 w-4"}),p.resources.length]})]})]})]})},p.id))})]})})};function _dt({resourceType:s,resourceId:t}){const{data:r=[]}=yt({queryKey:["linked-templates",s,t],queryFn:async()=>{if(s==="academy_video"){const{data:n,error:a}=await V.from("academy_video_templates").select("template_id, canva_templates:template_id(id, name, preview_image_url)").eq("video_id",t);if(a)throw a;return(n||[]).map(i=>i.canva_templates).filter(Boolean)}else{const{data:n,error:a}=await V.from("resource_kit_templates").select("template_id, canva_templates:template_id(id, name, preview_image_url)").eq("kit_id",t);if(a)throw a;return(n||[]).map(i=>i.canva_templates).filter(Boolean)}},enabled:!!t});return r.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 text-sm",children:[e.jsx(pl,{className:"h-4 w-4"}),"Related Templates"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:r.map(n=>e.jsx(Xn,{to:`/templates/${n.id}`,children:e.jsxs(Xe,{variant:"secondary",className:"cursor-pointer hover:bg-secondary/80 transition-colors gap-1.5 px-3 py-1.5 text-xs font-medium rounded-full",children:[e.jsx(pl,{className:"h-3 w-3"}),n.name]})},n.id))})]})}const dts=(s,t)=>{if(t==="bunny_stream"){let r=s.replace("iframe.mediadelivery.net","player.mediadelivery.net");return r.includes("?")||(r+="?autoplay=false&loop=false&muted=false&preload=true&responsive=true"),r}if(t==="youtube"){const r=/(?:youtube\.com\/(?:watch\?v=|embed\/)|youtu\.be\/)([a-zA-Z0-9_-]{11})/,n=s.match(r);if(n)return`https://www.youtube.com/embed/${n[1]}`}if(t==="vimeo"){const r=/vimeo\.com\/(?:video\/)?(\d+)/,n=s.match(r);if(n)return`https://player.vimeo.com/video/${n[1]}`}if(t==="loom"){const r=/loom\.com\/share\/([a-zA-Z0-9]+)/,n=s.match(r);if(n)return`https://www.loom.com/embed/${n[1]}`}return s},uts=()=>{const{videoId:s}=Po();Fr();const{user:t,isAdmin:r}=Ms(),{toast:n}=li(),a=ns(),{trackEngagement:i}=y8(),[l,o]=S.useState(""),{data:c,isLoading:d}=yt({queryKey:["academy-video",s],queryFn:async()=>{const{data:T,error:E}=await V.from("academy_videos").select(` *, category:academy_categories(id, name) `).eq("id",s).eq("is_published",!0).single();if(E)throw E;const{data:A}=await V.from("academy_resources").select("*").eq("video_id",s).order("sort_order");return{...T,resources:A||[]}},enabled:!!s});S.useEffect(()=>{c&&i("academy_video",c.id,c.title,"view")},[c==null?void 0:c.id]);const{data:h=[]}=yt({queryKey:["academy-video-likes",s],queryFn:async()=>{const{data:T,error:E}=await V.from("academy_video_likes").select("*").eq("video_id",s);if(E)throw E;return T},enabled:!!s}),{data:m=[]}=yt({queryKey:["academy-video-comments",s],queryFn:async()=>{const{data:T,error:E}=await V.from("academy_video_comments").select("*").eq("video_id",s).order("created_at",{ascending:!1});if(E)throw E;const A=[...new Set(T.map(z=>z.user_id))],{data:D}=await V.from("profiles").select("id, name").in("id",A),R=new Map((D==null?void 0:D.map(z=>[z.id,z.name]))||[]);return T.map(z=>({...z,user_name:R.get(z.user_id)||"Unknown User"}))},enabled:!!s}),p=Pt({mutationFn:async T=>{const{error:E}=await V.from("academy_video_comments").insert({video_id:s,user_id:t.id,content:T});if(E)throw E},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-video-comments",s]}),o(""),n({title:"Comment added!"})},onError:T=>{n({title:"Error adding comment",description:T.message,variant:"destructive"})}}),x=Pt({mutationFn:async T=>{const{error:E}=await V.from("academy_video_comments").delete().eq("id",T);if(E)throw E},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-video-comments",s]}),n({title:"Comment deleted"})}}),y=Pt({mutationFn:async()=>{const T=h.find(E=>E.user_id===(t==null?void 0:t.id));if(T){const{error:E}=await V.from("academy_video_likes").delete().eq("id",T.id);if(E)throw E}else{const{error:E}=await V.from("academy_video_likes").insert({video_id:s,user_id:t.id});if(E)throw E}},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-video-likes",s]})}}),_=h.some(T=>T.user_id===(t==null?void 0:t.id)),b=T=>{switch(T==null?void 0:T.toLowerCase()){case"pdf":return"📄";case"pptx":case"ppt":return"📊";case"xlsx":case"xls":return"📈";case"docx":case"doc":return"📝";case"zip":return"📦";default:return"📁"}},j=T=>T.split(" ").map(E=>E[0]).join("").toUpperCase().slice(0,2),k=T=>{T.preventDefault(),!(!l.trim()||!t)&&p.mutate(l.trim())};return d?e.jsx(Ss,{title:"Academy",children:e.jsx("div",{className:"flex justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):c?e.jsx(Ss,{title:c.title,children:e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsx(H,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(Xn,{to:"/academy",children:[e.jsx(za,{className:"h-4 w-4"}),"Back to Academy"]})}),e.jsx("div",{className:"relative w-full rounded-lg overflow-hidden bg-black",style:{paddingTop:"56.25%"},children:["youtube","vimeo","loom","bunny_stream"].includes(c.video_type)?e.jsx("iframe",{src:dts(c.video_url,c.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}):e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center text-white gap-4",children:[e.jsx(xn,{className:"h-16 w-16 opacity-50"}),e.jsx(H,{variant:"secondary",asChild:!0,children:e.jsxs("a",{href:c.video_url,target:"_blank",rel:"noopener noreferrer",className:"gap-2",children:[e.jsx(gn,{className:"h-4 w-4"}),"Open Video"]})})]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-start sm:justify-between gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:c.title}),c.category&&e.jsx(Xe,{variant:"secondary",children:c.category.name})]}),e.jsxs("div",{className:"flex gap-2",children:[r&&e.jsx(H,{variant:"outline",className:"gap-2 rounded-full",asChild:!0,children:e.jsxs(Xn,{to:`/admin/academy?edit=${c.id}`,children:[e.jsx(ni,{className:"h-4 w-4"}),e.jsx("span",{children:"Edit"})]})}),e.jsx(w8,{resourceType:"academy_video",resourceId:c.id,resourceTitle:c.title}),e.jsxs(H,{variant:_?"default":"outline",className:"gap-2 w-fit",onClick:()=>y.mutate(),disabled:!t||y.isPending,children:[e.jsx(sf,{className:`h-4 w-4 ${_?"fill-current":""}`}),h.length," ",h.length===1?"Like":"Likes"]})]})]}),c.description&&e.jsx("div",{className:"text-muted-foreground prose prose-sm max-w-none dark:prose-invert",dangerouslySetInnerHTML:{__html:c.description}})]}),c.resources&&c.resources.length>0&&e.jsx(ke,{children:e.jsxs(Oe,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(kn,{className:"h-4 w-4"}),"Resources"]}),e.jsx("div",{className:"grid gap-2",children:c.resources.map(T=>e.jsxs("a",{href:T.file_url,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-3 p-3 rounded-lg border hover:bg-muted transition-colors",children:[e.jsx("span",{className:"text-2xl",children:b(T.file_type)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:T.title}),e.jsx("p",{className:"text-xs text-muted-foreground uppercase",children:T.file_type})]}),e.jsx(hi,{className:"h-4 w-4 text-muted-foreground"})]},T.id))})]})}),e.jsx(_dt,{resourceType:"academy_video",resourceId:c.id}),e.jsx(Qo,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 text-lg",children:[e.jsx(qc,{className:"h-5 w-5"}),"Comments (",m.length,")"]}),t?e.jsxs("form",{onSubmit:k,className:"flex gap-2",children:[e.jsx(vr,{placeholder:"Add a comment...",value:l,onChange:T=>o(T.target.value),className:"min-h-[80px] resize-none flex-1"}),e.jsx(H,{type:"submit",size:"icon",className:"h-10 w-10",disabled:!l.trim()||p.isPending,children:e.jsx(yn,{className:"h-4 w-4"})})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Log in to add a comment"}),e.jsx("div",{className:"space-y-4",children:m.length===0?e.jsx(ke,{children:e.jsx(Oe,{className:"py-8 text-center",children:e.jsx("p",{className:"text-muted-foreground",children:"No comments yet. Be the first to share your thoughts!"})})}):m.map(T=>e.jsx(ke,{children:e.jsx(Oe,{className:"pt-4 pb-4",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Un,{className:"h-10 w-10 flex-shrink-0",children:e.jsx(qn,{className:"text-sm",children:j(T.user_name||"U")})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"font-medium",children:T.user_name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:Hl(new Date(T.created_at),{addSuffix:!0})}),T.user_id===(t==null?void 0:t.id)&&e.jsx(H,{variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>x.mutate(T.id),children:e.jsx(Dr,{className:"h-3 w-3 text-muted-foreground"})})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:T.content})]})]})})},T.id))})]})]})}):e.jsx(Ss,{title:"Academy",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(xn,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold",children:"Video not found"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"This video may have been removed or is not available."}),e.jsx(H,{asChild:!0,className:"mt-4",children:e.jsx(Xn,{to:"/academy",children:"Back to Academy"})})]})})};function hts(){const s=Fr(),[t,r]=S.useState(""),{data:n,isLoading:a}=yt({queryKey:["resource-kits-published"],queryFn:async()=>{const{data:x,error:y}=await V.from("resource_kits").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(y)throw y;return x}}),{data:i}=yt({queryKey:["resource-kit-files-all"],queryFn:async()=>{const{data:x,error:y}=await V.from("resource_kit_files").select("*").order("sort_order",{ascending:!0});if(y)throw y;return x}}),{data:l}=yt({queryKey:["resource-kit-likes-all"],queryFn:async()=>{const{data:x,error:y}=await V.from("resource_kit_likes").select("kit_id");if(y)throw y;return x}}),{data:o}=yt({queryKey:["resource-kit-comments-all"],queryFn:async()=>{const{data:x,error:y}=await V.from("resource_kit_comments").select("kit_id");if(y)throw y;return x}}),c=n==null?void 0:n.filter(x=>{var y;return x.name.toLowerCase().includes(t.toLowerCase())||((y=x.description)==null?void 0:y.toLowerCase().includes(t.toLowerCase()))}),d=x=>(i==null?void 0:i.filter(y=>y.kit_id===x))||[],h=x=>(l==null?void 0:l.filter(y=>y.kit_id===x).length)||0,m=x=>(o==null?void 0:o.filter(y=>y.kit_id===x).length)||0,p=x=>{s(`/toolbox/${x}`)};return e.jsx(Ss,{title:"Toolbox",description:"Download resource kits and tools to help grow your business",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-5xl font-bold text-foreground",children:"Toolbox"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Download resource kits and tools to help grow your business"})]}),e.jsxs("div",{className:"relative max-w-md",children:[e.jsx(Mn,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Se,{placeholder:"Search resource kits...",value:t,onChange:x=>r(x.target.value),className:"pl-10"})]}),!a&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:[(c==null?void 0:c.length)||0," resource kit",(c==null?void 0:c.length)!==1?"s":""," available"]}),a?e.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((x,y)=>e.jsx(ke,{children:e.jsxs(Oe,{className:"p-4",children:[e.jsx(Ks,{className:"aspect-[4/3] w-full rounded-lg mb-4"}),e.jsx(Ks,{className:"h-5 w-3/4 mb-2"}),e.jsx(Ks,{className:"h-4 w-full mb-4"}),e.jsx(Ks,{className:"h-4 w-2/3"})]})},y))}):(c==null?void 0:c.length)===0?e.jsxs(ke,{className:"p-12 text-center",children:[e.jsx(yc,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-medium mb-2",children:"No resource kits found"}),e.jsx("p",{className:"text-muted-foreground",children:t?"Try adjusting your search terms":"Check back later for new resources"})]}):e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6",children:c==null?void 0:c.map(x=>{const y=d(x.id).length,_=h(x.id),b=m(x.id);return e.jsxs(ke,{className:"group overflow-hidden cursor-pointer hover:shadow-lg transition-all duration-200",onClick:()=>p(x.id),children:[e.jsx("div",{className:"relative overflow-hidden bg-muted aspect-[3/2]",children:x.featured_image_url?e.jsx("img",{src:x.featured_image_url,alt:x.name,className:"w-full h-full object-contain group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(yc,{className:"h-16 w-16 text-muted-foreground"})})}),e.jsxs(Oe,{className:"p-4",children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1 mb-1",children:x.name}),x.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-3",children:Q7(x.description)}),e.jsxs("div",{className:"flex items-center justify-between text-sm text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(kn,{className:"h-4 w-4"}),y," file",y!==1?"s":""]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(sf,{className:"h-3.5 w-3.5"}),_]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(qc,{className:"h-3.5 w-3.5"}),b]})]})]})]})]},x.id)})})]})})}const mts=()=>{const{kitId:s}=Po(),{user:t,isAdmin:r}=Ms(),{toast:n}=li(),a=ns(),{trackEngagement:i}=y8(),[l,o]=S.useState(""),{data:c,isLoading:d}=yt({queryKey:["resource-kit-detail",s],queryFn:async()=>{const{data:T,error:E}=await V.from("resource_kits").select("*").eq("id",s).eq("is_published",!0).single();if(E)throw E;const{data:A}=await V.from("resource_kit_files").select("*").eq("kit_id",s).order("sort_order"),{data:D}=await V.from("resource_kit_links").select("*").eq("kit_id",s).order("sort_order");return{...T,files:A||[],links:D||[]}},enabled:!!s});S.useEffect(()=>{c&&i("toolbox",c.id,c.name,"view")},[c==null?void 0:c.id]);const{data:h=[]}=yt({queryKey:["resource-kit-likes",s],queryFn:async()=>{const{data:T,error:E}=await V.from("resource_kit_likes").select("*").eq("kit_id",s);if(E)throw E;return T},enabled:!!s}),{data:m=[]}=yt({queryKey:["resource-kit-comments",s],queryFn:async()=>{const{data:T,error:E}=await V.from("resource_kit_comments").select("*").eq("kit_id",s).order("created_at",{ascending:!1});if(E)throw E;const A=[...new Set(T.map(z=>z.user_id))],{data:D}=await V.from("profiles").select("id, name").in("id",A),R=new Map((D==null?void 0:D.map(z=>[z.id,z.name]))||[]);return T.map(z=>({...z,user_name:R.get(z.user_id)||"Unknown User"}))},enabled:!!s}),p=Pt({mutationFn:async T=>{const{error:E}=await V.from("resource_kit_comments").insert({kit_id:s,user_id:t.id,content:T});if(E)throw E},onSuccess:()=>{a.invalidateQueries({queryKey:["resource-kit-comments",s]}),o(""),n({title:"Comment added!"})},onError:T=>{n({title:"Error adding comment",description:T.message,variant:"destructive"})}}),x=Pt({mutationFn:async T=>{const{error:E}=await V.from("resource_kit_comments").delete().eq("id",T);if(E)throw E},onSuccess:()=>{a.invalidateQueries({queryKey:["resource-kit-comments",s]}),n({title:"Comment deleted"})}}),y=Pt({mutationFn:async()=>{const T=h.find(E=>E.user_id===(t==null?void 0:t.id));if(T){const{error:E}=await V.from("resource_kit_likes").delete().eq("id",T.id);if(E)throw E}else{const{error:E}=await V.from("resource_kit_likes").insert({kit_id:s,user_id:t.id});if(E)throw E}},onSuccess:()=>{a.invalidateQueries({queryKey:["resource-kit-likes",s]})}}),_=h.some(T=>T.user_id===(t==null?void 0:t.id)),b=T=>T.split(" ").map(E=>E[0]).join("").toUpperCase().slice(0,2),j=T=>T?T<1024?T+" B":T<1024*1024?(T/1024).toFixed(1)+" KB":(T/(1024*1024)).toFixed(1)+" MB":"",k=T=>{T.preventDefault(),!(!l.trim()||!t)&&p.mutate(l.trim())};return d?e.jsx(Ss,{title:"Toolbox",children:e.jsx("div",{className:"flex justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):c?e.jsx(Ss,{title:c.name,children:e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsx(H,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(Xn,{to:"/toolbox",children:[e.jsx(za,{className:"h-4 w-4"}),"Back to Toolbox"]})}),c.featured_image_url&&e.jsx("div",{className:"relative w-full rounded-lg overflow-hidden bg-muted",children:e.jsx("img",{src:c.featured_image_url,alt:c.name,className:"w-full max-h-[400px] object-cover"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-start sm:justify-between gap-4",children:[e.jsx("div",{className:"space-y-2",children:e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:c.name})}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&e.jsx(H,{variant:"outline",className:"gap-2 rounded-full",asChild:!0,children:e.jsxs(Xn,{to:`/admin/toolbox?edit=${c.id}`,children:[e.jsx(ni,{className:"h-4 w-4"}),e.jsx("span",{children:"Edit"})]})}),e.jsx(w8,{resourceType:"resource_kit",resourceId:c.id,resourceTitle:c.name,size:"default",className:"rounded-full"}),e.jsxs(H,{variant:_?"default":"outline",className:"gap-2 rounded-full",onClick:()=>y.mutate(),disabled:!t||y.isPending,children:[e.jsx(sf,{className:`h-4 w-4 ${_?"fill-current":""}`}),h.length," ",h.length===1?"Like":"Likes"]})]})]}),c.description&&e.jsx("div",{className:"text-muted-foreground prose prose-sm max-w-none dark:prose-invert",dangerouslySetInnerHTML:{__html:c.description}})]}),c.files&&c.files.length>0&&e.jsx(ke,{children:e.jsxs(Oe,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(kn,{className:"h-4 w-4"}),"Included Resources (",c.files.length,")"]}),e.jsx("div",{className:"grid gap-2",children:c.files.map(T=>e.jsxs("a",{href:T.file_url,target:"_blank",rel:"noopener noreferrer",onClick:()=>i("toolbox",c.id,c.name,"click_pdf"),className:"flex items-center justify-between p-3 rounded-lg border hover:bg-muted transition-colors group",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 rounded-md bg-primary/10",children:e.jsx(kn,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-sm",children:T.name}),T.file_size&&e.jsx("div",{className:"text-xs text-muted-foreground",children:j(T.file_size)})]})]}),e.jsx(hi,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors"})]},T.id))})]})}),c.links&&c.links.length>0&&e.jsx(ke,{children:e.jsxs(Oe,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(gn,{className:"h-4 w-4"}),"Canva Templates (",c.links.length,")"]}),e.jsx("div",{className:"grid gap-2",children:c.links.map(T=>e.jsxs("a",{href:T.canva_share_link,target:"_blank",rel:"noopener noreferrer",onClick:()=>i("toolbox",c.id,c.name,"click_canva"),className:"flex items-center justify-between p-3 rounded-lg border hover:bg-muted transition-colors group",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 rounded-md bg-purple-500/10",children:e.jsx(gn,{className:"h-4 w-4 text-purple-600"})}),e.jsx("div",{className:"font-medium text-sm",children:T.title})]}),e.jsx("span",{className:"text-xs text-muted-foreground group-hover:text-primary transition-colors",children:"Open in Canva"})]},T.id))})]})}),e.jsx(_dt,{resourceType:"resource_kit",resourceId:c.id}),e.jsx(Qo,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 text-lg",children:[e.jsx(qc,{className:"h-5 w-5"}),"Comments (",m.length,")"]}),t?e.jsxs("form",{onSubmit:k,className:"flex gap-2",children:[e.jsx(vr,{placeholder:"Add a comment...",value:l,onChange:T=>o(T.target.value),className:"min-h-[80px] resize-none flex-1"}),e.jsx(H,{type:"submit",size:"icon",className:"h-10 w-10",disabled:!l.trim()||p.isPending,children:e.jsx(yn,{className:"h-4 w-4"})})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Log in to add a comment"}),e.jsx("div",{className:"space-y-4",children:m.length===0?e.jsx(ke,{children:e.jsx(Oe,{className:"py-8 text-center",children:e.jsx("p",{className:"text-muted-foreground",children:"No comments yet. Be the first to share your thoughts!"})})}):m.map(T=>e.jsx(ke,{children:e.jsx(Oe,{className:"pt-4 pb-4",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Un,{className:"h-10 w-10 flex-shrink-0",children:e.jsx(qn,{className:"text-sm",children:b(T.user_name||"U")})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"font-medium",children:T.user_name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:Hl(new Date(T.created_at),{addSuffix:!0})}),T.user_id===(t==null?void 0:t.id)&&e.jsx(H,{variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>x.mutate(T.id),children:e.jsx(Dr,{className:"h-3 w-3 text-muted-foreground"})})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:T.content})]})]})})},T.id))})]})]})}):e.jsx(Ss,{title:"Toolbox",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(yc,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold",children:"Resource kit not found"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"This resource kit may have been removed or is not available."}),e.jsx(H,{asChild:!0,className:"mt-4",children:e.jsx(Xn,{to:"/toolbox",children:"Back to Toolbox"})})]})})},fts=()=>{const s=Fr(),[t,r]=S.useState(""),[n,a]=S.useState("grid"),{data:i=[],isLoading:l}=yt({queryKey:["social-swag"],queryFn:async()=>{const{data:d,error:h}=await V.from("social_swag").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(h)throw h;const{data:m,error:p}=await V.from("social_swag_links").select("*").order("sort_order");if(p)throw p;const{data:x}=await V.from("social_swag_likes").select("swag_id"),{data:y}=await V.from("social_swag_comments").select("swag_id"),_=new Map;x==null||x.forEach(k=>{_.set(k.swag_id,(_.get(k.swag_id)||0)+1)});const b=new Map;return y==null||y.forEach(k=>{b.set(k.swag_id,(b.get(k.swag_id)||0)+1)}),(d||[]).map(k=>({...k,links:(m||[]).filter(T=>T.swag_id===k.id)||[],likesCount:_.get(k.id)||0,commentsCount:b.get(k.id)||0}))}}),o=i.filter(d=>{var m;return d.title.toLowerCase().includes(t.toLowerCase())||((m=d.description)==null?void 0:m.toLowerCase().includes(t.toLowerCase()))}),c=d=>{s(`/social-swag/${d}`)};return e.jsx(Ss,{title:"Social Swag",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Social Swag"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Browse our collection of social media content and graphics"})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1 max-w-sm",children:[e.jsx(Mn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Se,{placeholder:"Search social swag...",value:t,onChange:d=>r(d.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"flex gap-2",children:[t&&e.jsx(H,{variant:"outline",size:"sm",onClick:()=>r(""),children:"Clear"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(H,{variant:n==="grid"?"secondary":"outline",size:"icon",onClick:()=>a("grid"),className:"rounded-full",children:e.jsx(_g,{className:"h-4 w-4"})}),e.jsx(H,{variant:n==="list"?"secondary":"outline",size:"icon",onClick:()=>a("list"),className:"rounded-full",children:e.jsx(Vf,{className:"h-4 w-4"})})]})]})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[o.length," item",o.length!==1?"s":""," found"]}),l&&e.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((d,h)=>e.jsx(ke,{children:e.jsxs(Oe,{className:"p-4",children:[e.jsx(Ks,{className:"aspect-[4/3] w-full rounded-lg mb-4"}),e.jsx(Ks,{className:"h-5 w-3/4 mb-2"}),e.jsx(Ks,{className:"h-4 w-full mb-4"})]})},h))}),!l&&o.length===0&&e.jsxs("div",{className:"text-center py-12",children:[e.jsx("div",{className:"text-muted-foreground mb-4",children:t?"No items match your search":"No social swag available yet"}),t&&e.jsx(H,{variant:"outline",onClick:()=>r(""),children:"Clear Search"})]}),!l&&o.length>0&&e.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:o.map(d=>e.jsxs(ke,{className:`group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer ${n==="list"?"flex flex-row":""}`,onClick:()=>c(d.id),children:[e.jsxs("div",{className:`relative overflow-hidden bg-muted ${n==="list"?"w-48 shrink-0":"aspect-[3/2]"}`,children:[d.preview_image_url?e.jsx("img",{src:d.preview_image_url,alt:d.title,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground",children:"No Preview"}),d.links.length>1&&e.jsx("div",{className:"absolute top-2 right-2",children:e.jsxs(Xe,{variant:"secondary",className:"gap-1 bg-background/90 backdrop-blur-sm",children:[e.jsx(Jo,{className:"h-3 w-3"}),d.links.length]})})]}),e.jsxs(Oe,{className:`p-4 flex flex-col ${n==="list"?"flex-1":""}`,children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1 mb-1",children:d.title}),d.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-3 flex-1",children:d.description.replace(/<[^>]*>/g,"")}),e.jsxs("div",{className:"flex items-center gap-4 text-sm text-muted-foreground mb-3",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(sf,{className:"h-3.5 w-3.5"}),d.likesCount]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(qc,{className:"h-3.5 w-3.5"}),d.commentsCount]})]}),e.jsxs(H,{size:"sm",className:"w-full gap-2",onClick:h=>{h.stopPropagation(),c(d.id)},children:[e.jsx(gn,{className:"h-4 w-4"}),"View Details"]})]})]},d.id))})]})})};var Xi=function(){return Xi=Object.assign||function(t){for(var r,n=1,a=arguments.length;n1&&(c||!d),m=t>1&&(d||!c),p=function(){n&&i(n)},x=function(){a&&i(a)};return e.jsx(Wts,{displayMonth:s.displayMonth,hideNext:h,hidePrevious:m,nextMonth:a,previousMonth:n,onPreviousClick:p,onNextClick:x})}function Kts(s){var t,r=hd(),n=r.classNames,a=r.disableNavigation,i=r.styles,l=r.captionLayout,o=r.components,c=(t=o==null?void 0:o.CaptionLabel)!==null&&t!==void 0?t:Ndt,d;return a?d=e.jsx(c,{id:s.id,displayMonth:s.displayMonth}):l==="dropdown"?d=e.jsx(QBe,{displayMonth:s.displayMonth,id:s.id}):l==="dropdown-buttons"?d=e.jsxs(e.Fragment,{children:[e.jsx(QBe,{displayMonth:s.displayMonth,displayIndex:s.displayIndex,id:s.id}),e.jsx(JBe,{displayMonth:s.displayMonth,displayIndex:s.displayIndex,id:s.id})]}):d=e.jsxs(e.Fragment,{children:[e.jsx(c,{id:s.id,displayMonth:s.displayMonth,displayIndex:s.displayIndex}),e.jsx(JBe,{displayMonth:s.displayMonth,id:s.id})]}),e.jsx("div",{className:n.caption,style:i.caption,children:d})}function Yts(s){var t=hd(),r=t.footer,n=t.styles,a=t.classNames.tfoot;return r?e.jsx("tfoot",{className:a,style:n.tfoot,children:e.jsx("tr",{children:e.jsx("td",{colSpan:8,children:r})})}):e.jsx(e.Fragment,{})}function Zts(s,t,r){for(var n=r?oj(new Date):Np(new Date,{locale:s,weekStartsOn:t}),a=[],i=0;i<7;i++){var l=Lc(n,i);a.push(l)}return a}function Xts(){var s=hd(),t=s.classNames,r=s.styles,n=s.showWeekNumber,a=s.locale,i=s.weekStartsOn,l=s.ISOWeek,o=s.formatters.formatWeekdayName,c=s.labels.labelWeekday,d=Zts(a,i,l);return e.jsxs("tr",{style:r.head_row,className:t.head_row,children:[n&&e.jsx("td",{style:r.head_cell,className:t.head_cell}),d.map(function(h,m){return e.jsx("th",{scope:"col",className:t.head_cell,style:r.head_cell,"aria-label":c(h,{locale:a}),children:o(h,{locale:a})},m)})]})}function Qts(){var s,t=hd(),r=t.classNames,n=t.styles,a=t.components,i=(s=a==null?void 0:a.HeadRow)!==null&&s!==void 0?s:Xts;return e.jsx("thead",{style:n.head,className:r.head,children:e.jsx(i,{})})}function Jts(s){var t=hd(),r=t.locale,n=t.formatters.formatDay;return e.jsx(e.Fragment,{children:n(s.date,{locale:r})})}var pEe=S.createContext(void 0);function ess(s){if(!hz(s.initialProps)){var t={selected:void 0,modifiers:{disabled:[]}};return e.jsx(pEe.Provider,{value:t,children:s.children})}return e.jsx(tss,{initialProps:s.initialProps,children:s.children})}function tss(s){var t=s.initialProps,r=s.children,n=t.selected,a=t.min,i=t.max,l=function(d,h,m){var p,x;(p=t.onDayClick)===null||p===void 0||p.call(t,d,h,m);var y=!!(h.selected&&a&&(n==null?void 0:n.length)===a);if(!y){var _=!!(!h.selected&&i&&(n==null?void 0:n.length)===i);if(!_){var b=n?wdt([],n):[];if(h.selected){var j=b.findIndex(function(k){return Cc(d,k)});b.splice(j,1)}else b.push(d);(x=t.onSelect)===null||x===void 0||x.call(t,b,d,h,m)}}},o={disabled:[]};n&&o.disabled.push(function(d){var h=i&&n.length>i-1,m=n.some(function(p){return Cc(p,d)});return!!(h&&!m)});var c={selected:n,onDayClick:l,modifiers:o};return e.jsx(pEe.Provider,{value:c,children:r})}function gEe(){var s=S.useContext(pEe);if(!s)throw new Error("useSelectMultiple must be used within a SelectMultipleProvider");return s}function sss(s,t){var r=t||{},n=r.from,a=r.to;return n&&a?Cc(a,s)&&Cc(n,s)?void 0:Cc(a,s)?{from:a,to:void 0}:Cc(n,s)?void 0:mA(n,s)?{from:s,to:a}:{from:n,to:s}:a?mA(s,a)?{from:a,to:s}:{from:s,to:a}:n?fA(s,n)?{from:s,to:n}:{from:n,to:s}:{from:s,to:void 0}}var xEe=S.createContext(void 0);function rss(s){if(!mz(s.initialProps)){var t={selected:void 0,modifiers:{range_start:[],range_end:[],range_middle:[],disabled:[]}};return e.jsx(xEe.Provider,{value:t,children:s.children})}return e.jsx(nss,{initialProps:s.initialProps,children:s.children})}function nss(s){var t=s.initialProps,r=s.children,n=t.selected,a=n||{},i=a.from,l=a.to,o=t.min,c=t.max,d=function(x,y,_){var b,j;(b=t.onDayClick)===null||b===void 0||b.call(t,x,y,_);var k=sss(x,n);(j=t.onSelect)===null||j===void 0||j.call(t,k,x,y,_)},h={range_start:[],range_end:[],range_middle:[],disabled:[]};if(i?(h.range_start=[i],l?(h.range_end=[l],Cc(i,l)||(h.range_middle=[{after:i,before:l}])):h.range_end=[i]):l&&(h.range_start=[l],h.range_end=[l]),o&&(i&&!l&&h.disabled.push({after:mue(i,o-1),before:Lc(i,o-1)}),i&&l&&h.disabled.push({after:i,before:Lc(i,o-1)}),!i&&l&&h.disabled.push({after:mue(l,o-1),before:Lc(l,o-1)})),c){if(i&&!l&&(h.disabled.push({before:Lc(i,-c+1)}),h.disabled.push({after:Lc(i,c-1)})),i&&l){var m=l0(l,i)+1,p=c-m;h.disabled.push({before:mue(i,p)}),h.disabled.push({after:Lc(l,p)})}!i&&l&&(h.disabled.push({before:Lc(l,-c+1)}),h.disabled.push({after:Lc(l,c-1)}))}return e.jsx(xEe.Provider,{value:{selected:n,onDayClick:d,modifiers:h},children:r})}function yEe(){var s=S.useContext(xEe);if(!s)throw new Error("useSelectRange must be used within a SelectRangeProvider");return s}function Mue(s){return Array.isArray(s)?wdt([],s):s!==void 0?[s]:[]}function ass(s){var t={};return Object.entries(s).forEach(function(r){var n=r[0],a=r[1];t[n]=Mue(a)}),t}var I1;(function(s){s.Outside="outside",s.Disabled="disabled",s.Selected="selected",s.Hidden="hidden",s.Today="today",s.RangeStart="range_start",s.RangeEnd="range_end",s.RangeMiddle="range_middle"})(I1||(I1={}));var iss=I1.Selected,r2=I1.Disabled,oss=I1.Hidden,lss=I1.Today,u_e=I1.RangeEnd,h_e=I1.RangeMiddle,m_e=I1.RangeStart,css=I1.Outside;function dss(s,t,r){var n,a=(n={},n[iss]=Mue(s.selected),n[r2]=Mue(s.disabled),n[oss]=Mue(s.hidden),n[lss]=[s.today],n[u_e]=[],n[h_e]=[],n[m_e]=[],n[css]=[],n);return s.fromDate&&a[r2].push({before:s.fromDate}),s.toDate&&a[r2].push({after:s.toDate}),hz(s)?a[r2]=a[r2].concat(t.modifiers[r2]):mz(s)&&(a[r2]=a[r2].concat(r.modifiers[r2]),a[m_e]=r.modifiers[m_e],a[h_e]=r.modifiers[h_e],a[u_e]=r.modifiers[u_e]),a}var Cdt=S.createContext(void 0);function uss(s){var t=hd(),r=gEe(),n=yEe(),a=dss(t,r,n),i=ass(t.modifiers),l=Xi(Xi({},a),i);return e.jsx(Cdt.Provider,{value:l,children:s.children})}function Tdt(){var s=S.useContext(Cdt);if(!s)throw new Error("useModifiers must be used within a ModifiersProvider");return s}function hss(s){return!!(s&&typeof s=="object"&&"before"in s&&"after"in s)}function mss(s){return!!(s&&typeof s=="object"&&"from"in s)}function fss(s){return!!(s&&typeof s=="object"&&"after"in s)}function pss(s){return!!(s&&typeof s=="object"&&"before"in s)}function gss(s){return!!(s&&typeof s=="object"&&"dayOfWeek"in s)}function xss(s,t){var r,n=t.from,a=t.to;if(n&&a){var i=l0(a,n)<0;i&&(r=[a,n],n=r[0],a=r[1]);var l=l0(s,n)>=0&&l0(a,s)>=0;return l}return a?Cc(a,s):n?Cc(n,s):!1}function yss(s){return d5e(s)}function vss(s){return Array.isArray(s)&&s.every(d5e)}function bss(s,t){return t.some(function(r){if(typeof r=="boolean")return r;if(yss(r))return Cc(s,r);if(vss(r))return r.includes(s);if(mss(r))return xss(s,r);if(gss(r))return r.dayOfWeek.includes(s.getDay());if(hss(r)){var n=l0(r.before,s),a=l0(r.after,s),i=n>0,l=a<0,o=mA(r.before,r.after);return o?l&&i:i||l}return fss(r)?l0(s,r.after)>0:pss(r)?l0(r.before,s)>0:typeof r=="function"?r(s):!1})}function vEe(s,t,r){var n=Object.keys(t).reduce(function(i,l){var o=t[l];return bss(s,o)&&i.push(l),i},[]),a={};return n.forEach(function(i){return a[i]=!0}),r&&!Tge(s,r)&&(a.outside=!0),a}function _ss(s,t){for(var r=Gd(s[0]),n=Ny(s[s.length-1]),a,i,l=r;l<=n;){var o=vEe(l,t),c=!o.disabled&&!o.hidden;if(!c){l=Lc(l,1);continue}if(o.selected)return l;o.today&&!i&&(i=l),a||(a=l),l=Lc(l,1)}return i||a}var wss=365;function Edt(s,t){var r=t.moveBy,n=t.direction,a=t.context,i=t.modifiers,l=t.retry,o=l===void 0?{count:0,lastFocused:s}:l,c=a.weekStartsOn,d=a.fromDate,h=a.toDate,m=a.locale,p={day:Lc,week:DT,month:wg,year:d8t,startOfWeek:function(b){return a.ISOWeek?oj(b):Np(b,{locale:m,weekStartsOn:c})},endOfWeek:function(b){return a.ISOWeek?mrt(b):Sge(b,{locale:m,weekStartsOn:c})}},x=p[r](s,n==="after"?1:-1);n==="before"&&d?x=u8t([d,x]):n==="after"&&h&&(x=h8t([h,x]));var y=!0;if(i){var _=vEe(x,i);y=!_.disabled&&!_.hidden}return y?x:o.count>wss?o.lastFocused:Edt(x,{moveBy:r,direction:n,context:a,modifiers:i,retry:Xi(Xi({},o),{count:o.count+1})})}var Adt=S.createContext(void 0);function jss(s){var t=fz(),r=Tdt(),n=S.useState(),a=n[0],i=n[1],l=S.useState(),o=l[0],c=l[1],d=_ss(t.displayMonths,r),h=a??(o&&t.isDateDisplayed(o))?o:d,m=function(){c(a),i(void 0)},p=function(b){i(b)},x=hd(),y=function(b,j){if(a){var k=Edt(a,{moveBy:b,direction:j,context:x,modifiers:r});Cc(a,k)||(t.goToDate(k,a),p(k))}},_={focusedDay:a,focusTarget:h,blur:m,focus:p,focusDayAfter:function(){return y("day","after")},focusDayBefore:function(){return y("day","before")},focusWeekAfter:function(){return y("week","after")},focusWeekBefore:function(){return y("week","before")},focusMonthBefore:function(){return y("month","before")},focusMonthAfter:function(){return y("month","after")},focusYearBefore:function(){return y("year","before")},focusYearAfter:function(){return y("year","after")},focusStartOfWeek:function(){return y("startOfWeek","before")},focusEndOfWeek:function(){return y("endOfWeek","after")}};return e.jsx(Adt.Provider,{value:_,children:s.children})}function bEe(){var s=S.useContext(Adt);if(!s)throw new Error("useFocusContext must be used within a FocusProvider");return s}function Nss(s,t){var r=Tdt(),n=vEe(s,r,t);return n}var _Ee=S.createContext(void 0);function kss(s){if(!vxe(s.initialProps)){var t={selected:void 0};return e.jsx(_Ee.Provider,{value:t,children:s.children})}return e.jsx(Sss,{initialProps:s.initialProps,children:s.children})}function Sss(s){var t=s.initialProps,r=s.children,n=function(i,l,o){var c,d,h;if((c=t.onDayClick)===null||c===void 0||c.call(t,i,l,o),l.selected&&!t.required){(d=t.onSelect)===null||d===void 0||d.call(t,void 0,i,l,o);return}(h=t.onSelect)===null||h===void 0||h.call(t,i,i,l,o)},a={selected:t.selected,onDayClick:n};return e.jsx(_Ee.Provider,{value:a,children:r})}function Mdt(){var s=S.useContext(_Ee);if(!s)throw new Error("useSelectSingle must be used within a SelectSingleProvider");return s}function Css(s,t){var r=hd(),n=Mdt(),a=gEe(),i=yEe(),l=bEe(),o=l.focusDayAfter,c=l.focusDayBefore,d=l.focusWeekAfter,h=l.focusWeekBefore,m=l.blur,p=l.focus,x=l.focusMonthBefore,y=l.focusMonthAfter,_=l.focusYearBefore,b=l.focusYearAfter,j=l.focusStartOfWeek,k=l.focusEndOfWeek,T=function(ce){var ne,le,be,fe;vxe(r)?(ne=n.onDayClick)===null||ne===void 0||ne.call(n,s,t,ce):hz(r)?(le=a.onDayClick)===null||le===void 0||le.call(a,s,t,ce):mz(r)?(be=i.onDayClick)===null||be===void 0||be.call(i,s,t,ce):(fe=r.onDayClick)===null||fe===void 0||fe.call(r,s,t,ce)},E=function(ce){var ne;p(s),(ne=r.onDayFocus)===null||ne===void 0||ne.call(r,s,t,ce)},A=function(ce){var ne;m(),(ne=r.onDayBlur)===null||ne===void 0||ne.call(r,s,t,ce)},D=function(ce){var ne;(ne=r.onDayMouseEnter)===null||ne===void 0||ne.call(r,s,t,ce)},R=function(ce){var ne;(ne=r.onDayMouseLeave)===null||ne===void 0||ne.call(r,s,t,ce)},z=function(ce){var ne;(ne=r.onDayPointerEnter)===null||ne===void 0||ne.call(r,s,t,ce)},O=function(ce){var ne;(ne=r.onDayPointerLeave)===null||ne===void 0||ne.call(r,s,t,ce)},$=function(ce){var ne;(ne=r.onDayTouchCancel)===null||ne===void 0||ne.call(r,s,t,ce)},ee=function(ce){var ne;(ne=r.onDayTouchEnd)===null||ne===void 0||ne.call(r,s,t,ce)},Z=function(ce){var ne;(ne=r.onDayTouchMove)===null||ne===void 0||ne.call(r,s,t,ce)},J=function(ce){var ne;(ne=r.onDayTouchStart)===null||ne===void 0||ne.call(r,s,t,ce)},K=function(ce){var ne;(ne=r.onDayKeyUp)===null||ne===void 0||ne.call(r,s,t,ce)},re=function(ce){var ne;switch(ce.key){case"ArrowLeft":ce.preventDefault(),ce.stopPropagation(),r.dir==="rtl"?o():c();break;case"ArrowRight":ce.preventDefault(),ce.stopPropagation(),r.dir==="rtl"?c():o();break;case"ArrowDown":ce.preventDefault(),ce.stopPropagation(),d();break;case"ArrowUp":ce.preventDefault(),ce.stopPropagation(),h();break;case"PageUp":ce.preventDefault(),ce.stopPropagation(),ce.shiftKey?_():x();break;case"PageDown":ce.preventDefault(),ce.stopPropagation(),ce.shiftKey?b():y();break;case"Home":ce.preventDefault(),ce.stopPropagation(),j();break;case"End":ce.preventDefault(),ce.stopPropagation(),k();break}(ne=r.onDayKeyDown)===null||ne===void 0||ne.call(r,s,t,ce)},ie={onClick:T,onFocus:E,onBlur:A,onKeyDown:re,onKeyUp:K,onMouseEnter:D,onMouseLeave:R,onPointerEnter:z,onPointerLeave:O,onTouchCancel:$,onTouchEnd:ee,onTouchMove:Z,onTouchStart:J};return ie}function Tss(){var s=hd(),t=Mdt(),r=gEe(),n=yEe(),a=vxe(s)?t.selected:hz(s)?r.selected:mz(s)?n.selected:void 0;return a}function Ess(s){return Object.values(I1).includes(s)}function Ass(s,t){var r=[s.classNames.day];return Object.keys(t).forEach(function(n){var a=s.modifiersClassNames[n];if(a)r.push(a);else if(Ess(n)){var i=s.classNames["day_".concat(n)];i&&r.push(i)}}),r}function Mss(s,t){var r=Xi({},s.styles.day);return Object.keys(t).forEach(function(n){var a;r=Xi(Xi({},r),(a=s.modifiersStyles)===null||a===void 0?void 0:a[n])}),r}function Iss(s,t,r){var n,a,i,l=hd(),o=bEe(),c=Nss(s,t),d=Css(s,c),h=Tss(),m=!!(l.onDayClick||l.mode!=="default");S.useEffect(function(){var D;c.outside||o.focusedDay&&m&&Cc(o.focusedDay,s)&&((D=r.current)===null||D===void 0||D.focus())},[o.focusedDay,s,r,m,c.outside]);var p=Ass(l,c).join(" "),x=Mss(l,c),y=!!(c.outside&&!l.showOutsideDays||c.hidden),_=(i=(a=l.components)===null||a===void 0?void 0:a.DayContent)!==null&&i!==void 0?i:Jts,b=e.jsx(_,{date:s,displayMonth:t,activeModifiers:c}),j={style:x,className:p,children:b,role:"gridcell"},k=o.focusTarget&&Cc(o.focusTarget,s)&&!c.outside,T=o.focusedDay&&Cc(o.focusedDay,s),E=Xi(Xi(Xi({},j),(n={disabled:c.disabled,role:"gridcell"},n["aria-selected"]=c.selected,n.tabIndex=T||k?0:-1,n)),d),A={isButton:m,isHidden:y,activeModifiers:c,selectedDays:h,buttonProps:E,divProps:j};return A}function Pss(s){var t=S.useRef(null),r=Iss(s.date,s.displayMonth,t);return r.isHidden?e.jsx("div",{role:"gridcell"}):r.isButton?e.jsx(Gme,Xi({name:"day",ref:t},r.buttonProps)):e.jsx("div",Xi({},r.divProps))}function Lss(s){var t=s.number,r=s.dates,n=hd(),a=n.onWeekNumberClick,i=n.styles,l=n.classNames,o=n.locale,c=n.labels.labelWeekNumber,d=n.formatters.formatWeekNumber,h=d(Number(t),{locale:o});if(!a)return e.jsx("span",{className:l.weeknumber,style:i.weeknumber,children:h});var m=c(Number(t),{locale:o}),p=function(x){a(t,r,x)};return e.jsx(Gme,{name:"week-number","aria-label":m,className:l.weeknumber,style:i.weeknumber,onClick:p,children:h})}function Dss(s){var t,r,n=hd(),a=n.styles,i=n.classNames,l=n.showWeekNumber,o=n.components,c=(t=o==null?void 0:o.Day)!==null&&t!==void 0?t:Pss,d=(r=o==null?void 0:o.WeekNumber)!==null&&r!==void 0?r:Lss,h;return l&&(h=e.jsx("td",{className:i.cell,style:a.cell,children:e.jsx(d,{number:s.weekNumber,dates:s.dates})})),e.jsxs("tr",{className:i.row,style:a.row,children:[h,s.dates.map(function(m){return e.jsx("td",{className:i.cell,style:a.cell,role:"presentation",children:e.jsx(c,{displayMonth:s.displayMonth,date:m})},pDt(m))})]})}function eze(s,t,r){for(var n=r!=null&&r.ISOWeek?mrt(t):Sge(t,r),a=r!=null&&r.ISOWeek?oj(s):Np(s,r),i=l0(n,a),l=[],o=0;o<=i;o++)l.push(Lc(a,o));var c=l.reduce(function(d,h){var m=r!=null&&r.ISOWeek?u5e(h):m5e(h,r),p=d.find(function(x){return x.weekNumber===m});return p?(p.dates.push(h),d):(d.push({weekNumber:m,dates:[h]}),d)},[]);return c}function Rss(s,t){var r=eze(Gd(s),Ny(s),t);if(t!=null&&t.useFixedWeeks){var n=xDt(s,t);if(n<6){var a=r[r.length-1],i=a.dates[a.dates.length-1],l=DT(i,6-n),o=eze(DT(i,1),l,t);r.push.apply(r,o)}}return r}function Oss(s){var t,r,n,a=hd(),i=a.locale,l=a.classNames,o=a.styles,c=a.hideHead,d=a.fixedWeeks,h=a.components,m=a.weekStartsOn,p=a.firstWeekContainsDate,x=a.ISOWeek,y=Rss(s.displayMonth,{useFixedWeeks:!!d,ISOWeek:x,locale:i,weekStartsOn:m,firstWeekContainsDate:p}),_=(t=h==null?void 0:h.Head)!==null&&t!==void 0?t:Qts,b=(r=h==null?void 0:h.Row)!==null&&r!==void 0?r:Dss,j=(n=h==null?void 0:h.Footer)!==null&&n!==void 0?n:Yts;return e.jsxs("table",{id:s.id,className:l.table,style:o.table,role:"grid","aria-labelledby":s["aria-labelledby"],children:[!c&&e.jsx(_,{}),e.jsx("tbody",{className:l.tbody,style:o.tbody,children:y.map(function(k){return e.jsx(b,{displayMonth:s.displayMonth,dates:k.dates,weekNumber:k.weekNumber},k.weekNumber)})}),e.jsx(j,{displayMonth:s.displayMonth})]})}function Fss(){return!!(typeof window<"u"&&window.document&&window.document.createElement)}var Bss=Fss()?S.useLayoutEffect:S.useEffect,f_e=!1,zss=0;function tze(){return"react-day-picker-".concat(++zss)}function $ss(s){var t,r=s??(f_e?tze():null),n=S.useState(r),a=n[0],i=n[1];return Bss(function(){a===null&&i(tze())},[]),S.useEffect(function(){f_e===!1&&(f_e=!0)},[]),(t=s??a)!==null&&t!==void 0?t:void 0}function Uss(s){var t,r,n=hd(),a=n.dir,i=n.classNames,l=n.styles,o=n.components,c=fz().displayMonths,d=$ss(n.id?"".concat(n.id,"-").concat(s.displayIndex):void 0),h=n.id?"".concat(n.id,"-grid-").concat(s.displayIndex):void 0,m=[i.month],p=l.month,x=s.displayIndex===0,y=s.displayIndex===c.length-1,_=!x&&!y;a==="rtl"&&(t=[x,y],y=t[0],x=t[1]),x&&(m.push(i.caption_start),p=Xi(Xi({},p),l.caption_start)),y&&(m.push(i.caption_end),p=Xi(Xi({},p),l.caption_end)),_&&(m.push(i.caption_between),p=Xi(Xi({},p),l.caption_between));var b=(r=o==null?void 0:o.Caption)!==null&&r!==void 0?r:Kts;return e.jsxs("div",{className:m.join(" "),style:p,children:[e.jsx(b,{id:d,displayMonth:s.displayMonth,displayIndex:s.displayIndex}),e.jsx(Oss,{id:h,"aria-labelledby":d,displayMonth:s.displayMonth})]},s.displayIndex)}function qss(s){var t=hd(),r=t.classNames,n=t.styles;return e.jsx("div",{className:r.months,style:n.months,children:s.children})}function Vss(s){var t,r,n=s.initialProps,a=hd(),i=bEe(),l=fz(),o=S.useState(!1),c=o[0],d=o[1];S.useEffect(function(){a.initialFocus&&i.focusTarget&&(c||(i.focus(i.focusTarget),d(!0)))},[a.initialFocus,c,i.focus,i.focusTarget,i]);var h=[a.classNames.root,a.className];a.numberOfMonths>1&&h.push(a.classNames.multiple_months),a.showWeekNumber&&h.push(a.classNames.with_weeknumber);var m=Xi(Xi({},a.styles.root),a.style),p=Object.keys(n).filter(function(y){return y.startsWith("data-")}).reduce(function(y,_){var b;return Xi(Xi({},y),(b={},b[_]=n[_],b))},{}),x=(r=(t=n.components)===null||t===void 0?void 0:t.Months)!==null&&r!==void 0?r:qss;return e.jsx("div",Xi({className:h.join(" "),style:m,dir:a.dir,id:a.id,nonce:n.nonce,title:n.title,lang:n.lang},p,{children:e.jsx(x,{children:l.displayMonths.map(function(y,_){return e.jsx(Uss,{displayIndex:_,displayMonth:y},_)})})}))}function Hss(s){var t=s.children,r=pts(s,["children"]);return e.jsx(Lts,{initialProps:r,children:e.jsx(Vts,{children:e.jsx(kss,{initialProps:r,children:e.jsx(ess,{initialProps:r,children:e.jsx(rss,{initialProps:r,children:e.jsx(uss,{children:e.jsx(jss,{children:t})})})})})})})}function Gss(s){return e.jsx(Hss,Xi({},s,{children:e.jsx(Vss,{initialProps:s})}))}function g0({className:s,classNames:t,showOutsideDays:r=!0,...n}){return e.jsx(Gss,{showOutsideDays:r,className:Ft("p-3",s),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:Ft(KP({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:Ft(KP({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",...t},components:{IconLeft:({...a})=>e.jsx(fl,{className:"h-4 w-4"}),IconRight:({...a})=>e.jsx($a,{className:"h-4 w-4"})},...n})}g0.displayName="Calendar";var bxe="Popover",[Idt,KZs]=_u(bxe,[q_]),pz=q_(),[Wss,KS]=Idt(bxe),Pdt=s=>{const{__scopePopover:t,children:r,open:n,defaultOpen:a,onOpenChange:i,modal:l=!1}=s,o=pz(t),c=S.useRef(null),[d,h]=S.useState(!1),[m,p]=af({prop:n,defaultProp:a??!1,onChange:i,caller:bxe});return e.jsx(BB,{...o,children:e.jsx(Wss,{scope:t,contentId:vm(),triggerRef:c,open:m,onOpenChange:p,onOpenToggle:S.useCallback(()=>p(x=>!x),[p]),hasCustomAnchor:d,onCustomAnchorAdd:S.useCallback(()=>h(!0),[]),onCustomAnchorRemove:S.useCallback(()=>h(!1),[]),modal:l,children:r})})};Pdt.displayName=bxe;var Ldt="PopoverAnchor",Kss=S.forwardRef((s,t)=>{const{__scopePopover:r,...n}=s,a=KS(Ldt,r),i=pz(r),{onCustomAnchorAdd:l,onCustomAnchorRemove:o}=a;return S.useEffect(()=>(l(),()=>o()),[l,o]),e.jsx(i8,{...i,...n,ref:t})});Kss.displayName=Ldt;var Ddt="PopoverTrigger",Rdt=S.forwardRef((s,t)=>{const{__scopePopover:r,...n}=s,a=KS(Ddt,r),i=pz(r),l=_i(t,a.triggerRef),o=e.jsx(Vn.button,{type:"button","aria-haspopup":"dialog","aria-expanded":a.open,"aria-controls":a.contentId,"data-state":$dt(a.open),...n,ref:l,onClick:an(s.onClick,a.onOpenToggle)});return a.hasCustomAnchor?o:e.jsx(i8,{asChild:!0,...i,children:o})});Rdt.displayName=Ddt;var wEe="PopoverPortal",[Yss,Zss]=Idt(wEe,{forceMount:void 0}),Odt=s=>{const{__scopePopover:t,forceMount:r,children:n,container:a}=s,i=KS(wEe,t);return e.jsx(Yss,{scope:t,forceMount:r,children:e.jsx(vh,{present:r||i.open,children:e.jsx(s8,{asChild:!0,container:a,children:n})})})};Odt.displayName=wEe;var uL="PopoverContent",Fdt=S.forwardRef((s,t)=>{const r=Zss(uL,s.__scopePopover),{forceMount:n=r.forceMount,...a}=s,i=KS(uL,s.__scopePopover);return e.jsx(vh,{present:n||i.open,children:i.modal?e.jsx(Qss,{...a,ref:t}):e.jsx(Jss,{...a,ref:t})})});Fdt.displayName=uL;var Xss=mS("PopoverContent.RemoveScroll"),Qss=S.forwardRef((s,t)=>{const r=KS(uL,s.__scopePopover),n=S.useRef(null),a=_i(t,n),i=S.useRef(!1);return S.useEffect(()=>{const l=n.current;if(l)return cge(l)},[]),e.jsx(GB,{as:Xss,allowPinchZoom:!0,children:e.jsx(Bdt,{...s,ref:a,trapFocus:r.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:an(s.onCloseAutoFocus,l=>{var o;l.preventDefault(),i.current||(o=r.triggerRef.current)==null||o.focus()}),onPointerDownOutside:an(s.onPointerDownOutside,l=>{const o=l.detail.originalEvent,c=o.button===0&&o.ctrlKey===!0,d=o.button===2||c;i.current=d},{checkForDefaultPrevented:!1}),onFocusOutside:an(s.onFocusOutside,l=>l.preventDefault(),{checkForDefaultPrevented:!1})})})}),Jss=S.forwardRef((s,t)=>{const r=KS(uL,s.__scopePopover),n=S.useRef(!1),a=S.useRef(!1);return e.jsx(Bdt,{...s,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{var l,o;(l=s.onCloseAutoFocus)==null||l.call(s,i),i.defaultPrevented||(n.current||(o=r.triggerRef.current)==null||o.focus(),i.preventDefault()),n.current=!1,a.current=!1},onInteractOutside:i=>{var c,d;(c=s.onInteractOutside)==null||c.call(s,i),i.defaultPrevented||(n.current=!0,i.detail.originalEvent.type==="pointerdown"&&(a.current=!0));const l=i.target;((d=r.triggerRef.current)==null?void 0:d.contains(l))&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&a.current&&i.preventDefault()}})}),Bdt=S.forwardRef((s,t)=>{const{__scopePopover:r,trapFocus:n,onOpenAutoFocus:a,onCloseAutoFocus:i,disableOutsidePointerEvents:l,onEscapeKeyDown:o,onPointerDownOutside:c,onFocusOutside:d,onInteractOutside:h,...m}=s,p=KS(uL,r),x=pz(r);return ige(),e.jsx(VB,{asChild:!0,loop:!0,trapped:n,onMountAutoFocus:a,onUnmountAutoFocus:i,children:e.jsx(PS,{asChild:!0,disableOutsidePointerEvents:l,onInteractOutside:h,onEscapeKeyDown:o,onPointerDownOutside:c,onFocusOutside:d,onDismiss:()=>p.onOpenChange(!1),children:e.jsx(zB,{"data-state":$dt(p.open),role:"dialog",id:p.contentId,...x,...m,ref:t,style:{...m.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)"}})})})}),zdt="PopoverClose",ers=S.forwardRef((s,t)=>{const{__scopePopover:r,...n}=s,a=KS(zdt,r);return e.jsx(Vn.button,{type:"button",...n,ref:t,onClick:an(s.onClick,()=>a.onOpenChange(!1))})});ers.displayName=zdt;var trs="PopoverArrow",srs=S.forwardRef((s,t)=>{const{__scopePopover:r,...n}=s,a=pz(r);return e.jsx($B,{...a,...n,ref:t})});srs.displayName=trs;function $dt(s){return s?"open":"closed"}var rrs=Pdt,nrs=Rdt,ars=Odt,Udt=Fdt;const gl=rrs,xl=nrs,il=S.forwardRef(({className:s,align:t="center",sideOffset:r=4,...n},a)=>e.jsx(ars,{children:e.jsx(Udt,{ref:a,align:t,sideOffset:r,className:Ft("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",s),...n})}));il.displayName=Udt.displayName;const irs=zA("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"}}),jEe=S.forwardRef(({className:s,variant:t,...r},n)=>e.jsx("div",{ref:n,role:"alert",className:Ft(irs({variant:t}),s),...r}));jEe.displayName="Alert";const ors=S.forwardRef(({className:s,...t},r)=>e.jsx("h5",{ref:r,className:Ft("mb-1 font-medium leading-none tracking-tight",s),...t}));ors.displayName="AlertTitle";const NEe=S.forwardRef(({className:s,...t},r)=>e.jsx("div",{ref:r,className:Ft("text-sm [&_p]:leading-relaxed",s),...t}));NEe.displayName="AlertDescription";function lrs({open:s,onOpenChange:t,imageUrl:r,imageId:n,defaultCaption:a="",swagItemId:i,reelId:l}){const o=ns(),[c,d]=S.useState(a),[h,m]=S.useState([]),[p,x]=S.useState(null),[y,_]=S.useState("now"),[b,j]=S.useState(VOe(ZOe(new Date),1)),[k,T]=S.useState("12"),[E,A]=S.useState("00"),[D,R]=S.useState("PM");S.useEffect(()=>{if(s){d(a),_("now"),m([]);const ve=VOe(ZOe(new Date),1);j(ve);const We=ve.getHours();T(String(We>12?We-12:We===0?12:We)),A("00"),R(We>=12?"PM":"AM")}},[s,a]);const z=()=>{if(!b)return null;let ve=parseInt(k);const We=parseInt(E);return D==="PM"&&ve!==12&&(ve+=12),D==="AM"&&ve===12&&(ve=0),YF(KF(b,ve),We)},{data:O,isLoading:$}=yt({queryKey:["social-accounts-for-post"],queryFn:async()=>{const{data:{user:ve}}=await V.auth.getUser();if(!ve)return[];const{data:We,error:Ve}=await V.from("social_accounts").select("*").eq("user_id",ve.id).eq("is_active",!0).order("platform",{ascending:!0});if(Ve)throw Ve;return console.log("Fetched social accounts for posting:",We),We},enabled:s,staleTime:0}),ee=Pt({mutationFn:async({accountId:ve,platform:We})=>{x(ve);const{data:Ve,error:Le}=await V.functions.invoke("social-post",{body:{platform:We,accountId:ve,imageUrl:r,caption:c}});if(Le)throw Le;if(Ve!=null&&Ve.error)throw new Error(Ve.error);return Ve},onSuccess:ve=>{const We=ve.platform==="facebook"?"Facebook":ve.platform==="instagram"?"Instagram":ve.platform==="linkedin"?"LinkedIn":"Google Business";he.success(`Posted to ${We}!`)},onError:ve=>{he.error(`Failed to post: ${ve.message}`)},onSettled:()=>{x(null)}}),Z=Pt({mutationFn:async({accountId:ve,platform:We,scheduledFor:Ve})=>{const{data:{user:Le}}=await V.auth.getUser();if(!Le)throw new Error("Not authenticated");const{error:Me}=await V.from("scheduled_posts").insert({user_id:Le.id,social_account_id:ve,platform:We,image_url:r,caption:c,swag_item_id:i||null,reel_id:l||null,scheduled_for:Ve.toISOString(),status:"scheduled"});if(Me)throw Me;return{platform:We}},onSuccess:ve=>{const We=ve.platform==="facebook"?"Facebook":ve.platform==="instagram"?"Instagram":"LinkedIn";he.success(`Post scheduled for ${We}!`)},onError:ve=>{he.error(`Failed to schedule: ${ve.message}`)}}),J=async()=>{if(h.length===0){he.error("Please select at least one account");return}if(y==="schedule"){const ve=z();if(!ve||ve<=new Date){he.error("Please select a future date and time");return}for(const We of h){const Ve=O==null?void 0:O.find(Le=>Le.id===We);Ve&&await Z.mutateAsync({accountId:We,platform:Ve.platform,scheduledFor:ve})}o.invalidateQueries({queryKey:["scheduled-posts"]}),he.success(`${h.length} post(s) scheduled for ${As(ve,"PPp")}`)}else for(const ve of h){const We=O==null?void 0:O.find(Ve=>Ve.id===ve);We&&await ee.mutateAsync({accountId:ve,platform:We.platform})}o.invalidateQueries({queryKey:["scheduled-posts"]}),d(""),m([]),t(!1)},K=ve=>{m(We=>We.includes(ve)?We.filter(Ve=>Ve!==ve):[...We,ve])},re=(O==null?void 0:O.filter(ve=>ve.platform==="facebook"))||[],ie=(O==null?void 0:O.filter(ve=>ve.platform==="instagram"))||[],ce=(O==null?void 0:O.filter(ve=>ve.platform==="linkedin"))||[],ne=(O==null?void 0:O.filter(ve=>ve.platform==="google_business"))||[],le=((O==null?void 0:O.length)||0)>0,be=ee.isPending||Z.isPending,fe=Array.from({length:12},(ve,We)=>String(We+1)),je=["00","15","30","45"];return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(Cs,{children:[e.jsx(Ns,{children:"Create Social Post"}),e.jsx(nn,{children:"Share this image to your connected social accounts"})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsx("div",{className:"aspect-square w-full max-w-[200px] mx-auto overflow-hidden rounded-lg border",children:e.jsx("img",{src:r,alt:"Post preview",className:"h-full w-full object-cover"})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"caption",children:"Caption"}),e.jsx(vr,{id:"caption",placeholder:"Write a caption for your post...",value:c,onChange:ve=>d(ve.target.value),rows:3}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[c.length,"/2200 characters"]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(ue,{children:"Publish Time"}),e.jsxs("div",{className:"flex items-center gap-1 p-1 bg-muted rounded-lg",children:[e.jsx("button",{type:"button",onClick:()=>_("now"),className:Ft("flex-1 px-4 py-2 rounded-md text-sm font-medium transition-all",y==="now"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:"Post Now"}),e.jsx("button",{type:"button",onClick:()=>_("schedule"),className:Ft("flex-1 px-4 py-2 rounded-md text-sm font-medium transition-all",y==="schedule"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:"Schedule"})]})]}),y==="schedule"&&e.jsxs("div",{className:"space-y-3 p-4 border rounded-lg bg-muted/30",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium",children:[e.jsx(Pn,{className:"h-4 w-4"}),"Schedule for"]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs(gl,{children:[e.jsx(xl,{asChild:!0,children:e.jsxs(H,{variant:"outline",className:Ft("justify-start text-left font-normal flex-1",!b&&"text-muted-foreground"),children:[e.jsx(Nn,{className:"mr-2 h-4 w-4"}),b?As(b,"PPP"):e.jsx("span",{children:"Pick a date"})]})}),e.jsx(il,{className:"w-auto p-0",align:"start",children:e.jsx(g0,{mode:"single",selected:b,onSelect:j,disabled:ve=>vee.jsx(pt,{value:ve,children:ve},ve))})]}),e.jsx("span",{className:"text-muted-foreground",children:":"}),e.jsxs(Bs,{value:E,onValueChange:A,children:[e.jsx(Os,{className:"w-[70px]",children:e.jsx(Us,{})}),e.jsx(Fs,{children:je.map(ve=>e.jsx(pt,{value:ve,children:ve},ve))})]}),e.jsxs(Bs,{value:D,onValueChange:ve=>R(ve),children:[e.jsx(Os,{className:"w-[70px]",children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"AM",children:"AM"}),e.jsx(pt,{value:"PM",children:"PM"})]})]})]})]}),b&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Post will be published on ",As(z()||new Date,"PPP 'at' p")]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(ue,{children:"Post to"}),$&&e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(is,{className:"h-6 w-6 animate-spin"})}),!$&&!le&&e.jsxs(jEe,{children:[e.jsx(wo,{className:"h-4 w-4"}),e.jsxs(NEe,{className:"flex flex-col gap-2",children:[e.jsx("span",{children:"No social accounts connected yet."}),e.jsxs(Xn,{to:"/social-connections",className:"inline-flex items-center gap-1.5 text-primary hover:underline font-medium",children:[e.jsx(Go,{className:"h-3.5 w-3.5"}),"Connect your Facebook, Instagram & LinkedIn"]})]})]}),re.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(fh,{className:"h-4 w-4 text-blue-600"})," Facebook"]}),re.map(ve=>e.jsxs("label",{className:"flex items-center gap-3 rounded-lg border p-3 cursor-pointer hover:bg-muted/50 transition-colors",children:[e.jsx(ao,{checked:h.includes(ve.id),onCheckedChange:()=>K(ve.id),disabled:p===ve.id}),e.jsxs(Un,{className:"h-8 w-8",children:[e.jsx(Ka,{src:ve.profile_picture_url||""}),e.jsx(qn,{children:e.jsx(fh,{className:"h-4 w-4"})})]}),e.jsx("span",{className:"flex-1 text-sm font-medium",children:ve.page_name||ve.platform_username}),p===ve.id&&e.jsx(is,{className:"h-4 w-4 animate-spin"})]},ve.id))]}),ie.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(yu,{className:"h-4 w-4 text-pink-600"})," Instagram"]}),ie.map(ve=>e.jsxs("label",{className:"flex items-center gap-3 rounded-lg border p-3 cursor-pointer hover:bg-muted/50 transition-colors",children:[e.jsx(ao,{checked:h.includes(ve.id),onCheckedChange:()=>K(ve.id),disabled:p===ve.id}),e.jsxs(Un,{className:"h-8 w-8",children:[e.jsx(Ka,{src:ve.profile_picture_url||""}),e.jsx(qn,{children:e.jsx(yu,{className:"h-4 w-4"})})]}),e.jsxs("span",{className:"flex-1 text-sm font-medium",children:["@",ve.platform_username]}),p===ve.id&&e.jsx(is,{className:"h-4 w-4 animate-spin"})]},ve.id))]}),ce.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(qf,{className:"h-4 w-4 text-blue-700"})," LinkedIn"]}),ce.map(ve=>e.jsxs("label",{className:"flex items-center gap-3 rounded-lg border p-3 cursor-pointer hover:bg-muted/50 transition-colors",children:[e.jsx(ao,{checked:h.includes(ve.id),onCheckedChange:()=>K(ve.id),disabled:p===ve.id}),e.jsxs(Un,{className:"h-8 w-8",children:[e.jsx(Ka,{src:ve.profile_picture_url||""}),e.jsx(qn,{children:e.jsx(qf,{className:"h-4 w-4"})})]}),e.jsx("span",{className:"flex-1 text-sm font-medium",children:ve.platform_username}),p===ve.id&&e.jsx(is,{className:"h-4 w-4 animate-spin"})]},ve.id))]}),ne.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(Qa,{className:"h-4 w-4 text-red-600"})," Google Business"]}),ne.map(ve=>e.jsxs("label",{className:"flex items-center gap-3 rounded-lg border p-3 cursor-pointer hover:bg-muted/50 transition-colors",children:[e.jsx(ao,{checked:h.includes(ve.id),onCheckedChange:()=>K(ve.id),disabled:p===ve.id}),e.jsxs(Un,{className:"h-8 w-8",children:[e.jsx(Ka,{src:ve.profile_picture_url||""}),e.jsx(qn,{children:e.jsx(Qa,{className:"h-4 w-4"})})]}),e.jsx("span",{className:"flex-1 text-sm font-medium",children:ve.page_name||ve.platform_username}),p===ve.id&&e.jsx(is,{className:"h-4 w-4 animate-spin"})]},ve.id))]})]})]}),e.jsxs(wn,{children:[e.jsx(H,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(H,{onClick:J,disabled:h.length===0||be,className:"gap-2",children:[be?e.jsx(is,{className:"h-4 w-4 animate-spin"}):y==="schedule"?e.jsx(Nn,{className:"h-4 w-4"}):e.jsx(yn,{className:"h-4 w-4"}),y==="schedule"?`Schedule ${h.length} post${h.length!==1?"s":""}`:`Post to ${h.length} account${h.length!==1?"s":""}`]})]})]})})}function crs(){const s=ns(),[t,r]=S.useState(void 0),[n,a]=S.useState("all"),[i,l]=S.useState(null),[o,c]=S.useState(""),[d,h]=S.useState(void 0),[m,p]=S.useState("12"),[x,y]=S.useState("00"),[_,b]=S.useState("PM"),{data:j=[],isLoading:k}=yt({queryKey:["scheduled-posts"],queryFn:async()=>{const{data:ne,error:le}=await V.from("scheduled_posts").select(` *, social_accounts ( page_name, platform_username, profile_picture_url ) `).order("scheduled_for",{ascending:!1});if(le)throw le;return ne}}),T=j.filter(ne=>{if(n!=="all"&&ne.status!==n)return!1;if(t&&ne.scheduled_for){const le=new Date(ne.scheduled_for);if(!Cc(le,t))return!1}return!0}),E=j.filter(ne=>ne.scheduled_for).map(ne=>jg(new Date(ne.scheduled_for))),A=Pt({mutationFn:async ne=>{const{error:le}=await V.from("scheduled_posts").update({caption:ne.caption,scheduled_for:ne.scheduled_for}).eq("id",ne.id);if(le)throw le},onSuccess:()=>{he.success("Post updated!"),s.invalidateQueries({queryKey:["scheduled-posts"]}),l(null)},onError:ne=>{he.error(`Failed to update: ${ne.message}`)}}),D=Pt({mutationFn:async ne=>{const{error:le}=await V.from("scheduled_posts").update({status:"cancelled"}).eq("id",ne);if(le)throw le},onSuccess:()=>{he.success("Post cancelled"),s.invalidateQueries({queryKey:["scheduled-posts"]})},onError:ne=>{he.error(`Failed to cancel: ${ne.message}`)}}),R=Pt({mutationFn:async ne=>{const{error:le}=await V.from("scheduled_posts").delete().eq("id",ne);if(le)throw le},onSuccess:()=>{he.success("Post deleted"),s.invalidateQueries({queryKey:["scheduled-posts"]})},onError:ne=>{he.error(`Failed to delete: ${ne.message}`)}}),z=Pt({mutationFn:async ne=>{const{data:le,error:be}=await V.functions.invoke("social-post",{body:{platform:ne.platform,accountId:ne.social_account_id,imageUrl:ne.image_url,caption:ne.caption}});if(be)throw be;if(le!=null&&le.error)throw new Error(le.error);return await V.from("scheduled_posts").update({status:"posted",posted_at:new Date().toISOString(),post_id:le.postId}).eq("id",ne.id),le},onSuccess:ne=>{const le=ne.platform==="facebook"?"Facebook":ne.platform==="instagram"?"Instagram":"LinkedIn";he.success(`Posted to ${le}!`),s.invalidateQueries({queryKey:["scheduled-posts"]})},onError:ne=>{he.error(`Failed to post: ${ne.message}`)}}),O=ne=>{if(l(ne),c(ne.caption||""),ne.scheduled_for){const le=new Date(ne.scheduled_for);h(le);const be=le.getHours();p(String(be>12?be-12:be===0?12:be)),y(String(le.getMinutes()).padStart(2,"0")),b(be>=12?"PM":"AM")}},$=()=>{if(!i||!d)return;let ne=parseInt(m);const le=parseInt(x);_==="PM"&&ne!==12&&(ne+=12),_==="AM"&&ne===12&&(ne=0);const be=YF(KF(d,ne),le);A.mutate({id:i.id,caption:o,scheduled_for:be.toISOString()})},ee=ne=>{switch(ne){case"facebook":return e.jsx(fh,{className:"h-4 w-4 text-blue-600"});case"instagram":return e.jsx(yu,{className:"h-4 w-4 text-pink-600"});case"linkedin":return e.jsx(qf,{className:"h-4 w-4 text-blue-700"});default:return null}},Z=ne=>{switch(ne){case"scheduled":return e.jsxs(Xe,{variant:"secondary",className:"gap-1",children:[e.jsx(Pn,{className:"h-3 w-3"}),"Scheduled"]});case"posted":return e.jsxs(Xe,{variant:"default",className:"gap-1 bg-green-600",children:[e.jsx(zi,{className:"h-3 w-3"}),"Posted"]});case"failed":return e.jsxs(Xe,{variant:"destructive",className:"gap-1",children:[e.jsx(kd,{className:"h-3 w-3"}),"Failed"]});case"cancelled":return e.jsxs(Xe,{variant:"outline",className:"gap-1 text-muted-foreground",children:[e.jsx(wo,{className:"h-3 w-3"}),"Cancelled"]});default:return e.jsx(Xe,{variant:"outline",children:ne})}},J=Array.from({length:12},(ne,le)=>String(le+1)),K=["00","15","30","45"],re=j.filter(ne=>ne.status==="scheduled").length,ie=j.filter(ne=>ne.status==="posted").length,ce=j.filter(ne=>ne.status==="scheduled"&&ne.scheduled_for&&yDt(new Date(ne.scheduled_for))).length;return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsxs(ke,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:re}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Scheduled"})]}),e.jsxs(ke,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:ce}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Upcoming"})]}),e.jsxs(ke,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:ie}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Posted"})]}),e.jsxs(ke,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:j.length}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Total"})]})]}),e.jsxs("div",{className:"flex flex-col lg:flex-row gap-6",children:[e.jsxs(ke,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx(xu,{className:"h-5 w-5"}),e.jsx("h3",{className:"font-semibold",children:"Calendar"})]}),e.jsx(g0,{mode:"single",selected:t,onSelect:r,className:Ft("pointer-events-auto"),modifiers:{hasPost:E},modifiersStyles:{hasPost:{fontWeight:"bold",backgroundColor:"hsl(var(--primary) / 0.1)",borderRadius:"50%"}}}),t&&e.jsx(H,{variant:"ghost",size:"sm",onClick:()=>r(void 0),className:"w-full mt-2",children:"Clear date filter"})]}),e.jsxs("div",{className:"flex-1 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(v1,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("div",{className:"flex flex-wrap gap-1",children:["all","scheduled","posted","failed","cancelled"].map(ne=>e.jsx(H,{variant:n===ne?"default":"outline",size:"sm",onClick:()=>a(ne),className:"capitalize",children:ne},ne))})]}),k&&e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(is,{className:"h-8 w-8 animate-spin text-muted-foreground"})}),!k&&T.length===0&&e.jsxs(ke,{className:"p-8 text-center",children:[e.jsx(Nn,{className:"h-12 w-12 mx-auto text-muted-foreground/50 mb-4"}),e.jsx("h3",{className:"font-medium mb-2",children:"No posts found"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:t?`No posts scheduled for ${As(t,"PPP")}`:"Schedule a post from Social Swag to get started!"})]}),e.jsx("div",{className:"space-y-4",children:T.map(ne=>{var le,be;return e.jsx(ke,{className:"overflow-hidden",children:e.jsxs("div",{className:"flex flex-col sm:flex-row",children:[e.jsx("div",{className:"sm:w-32 h-32 sm:h-auto bg-muted flex-shrink-0",children:e.jsx("img",{src:ne.image_url,alt:"Post preview",className:"w-full h-full object-cover"})}),e.jsxs(Oe,{className:"flex-1 p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-2 mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[ee(ne.platform),e.jsx("span",{className:"font-medium",children:((le=ne.social_accounts)==null?void 0:le.page_name)||((be=ne.social_accounts)==null?void 0:be.platform_username)||"Unknown"}),Z(ne.status)]}),e.jsxs("div",{className:"flex items-center gap-1",children:[ne.status==="scheduled"&&e.jsxs(xj,{children:[e.jsxs(rd,{children:[e.jsx(nd,{asChild:!0,children:e.jsx(H,{variant:"ghost",size:"icon",onClick:()=>O(ne),children:e.jsx(ni,{className:"h-4 w-4"})})}),e.jsx(Rc,{children:"Edit post"})]}),e.jsxs(rd,{children:[e.jsx(nd,{asChild:!0,children:e.jsx(H,{variant:"ghost",size:"icon",onClick:()=>z.mutate(ne),disabled:z.isPending,children:z.isPending?e.jsx(is,{className:"h-4 w-4 animate-spin"}):e.jsx(yn,{className:"h-4 w-4"})})}),e.jsx(Rc,{children:"Post now"})]}),e.jsxs(Rl,{children:[e.jsx(vp,{asChild:!0,children:e.jsx(H,{variant:"ghost",size:"icon",className:"text-destructive",children:e.jsx(Dr,{className:"h-4 w-4"})})}),e.jsxs(jl,{children:[e.jsxs(Nl,{children:[e.jsx(Sl,{children:"Cancel this scheduled post?"}),e.jsx(Cl,{children:"This will cancel the post. You can delete it entirely or keep it in your history."})]}),e.jsxs(kl,{children:[e.jsx(Tl,{children:"Keep"}),e.jsx(ml,{onClick:()=>D.mutate(ne.id),className:"bg-amber-600 hover:bg-amber-700",children:"Cancel Post"}),e.jsx(ml,{onClick:()=>R.mutate(ne.id),className:"bg-destructive hover:bg-destructive/90",children:"Delete"})]})]})]})]}),(ne.status==="posted"||ne.status==="cancelled"||ne.status==="failed")&&e.jsxs(Rl,{children:[e.jsx(vp,{asChild:!0,children:e.jsx(H,{variant:"ghost",size:"icon",className:"text-destructive",children:e.jsx(Dr,{className:"h-4 w-4"})})}),e.jsxs(jl,{children:[e.jsxs(Nl,{children:[e.jsx(Sl,{children:"Delete this post?"}),e.jsx(Cl,{children:"This will permanently remove this post from your history."})]}),e.jsxs(kl,{children:[e.jsx(Tl,{children:"Cancel"}),e.jsx(ml,{onClick:()=>R.mutate(ne.id),className:"bg-destructive hover:bg-destructive/90",children:"Delete"})]})]})]})]})]}),ne.caption&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-2",children:ne.caption}),e.jsxs("div",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Pn,{className:"h-3 w-3"}),ne.status==="posted"&&ne.posted_at?`Posted ${As(new Date(ne.posted_at),"PPp")}`:ne.scheduled_for?`Scheduled for ${As(new Date(ne.scheduled_for),"PPp")}`:"Not scheduled"]}),ne.status==="failed"&&ne.error_message&&e.jsxs("p",{className:"text-xs text-destructive mt-2",children:["Error: ",ne.error_message]})]})]})},ne.id)})})]})]}),e.jsx(bs,{open:!!i,onOpenChange:ne=>!ne&&l(null),children:e.jsxs(vs,{className:"max-w-lg",children:[e.jsxs(Cs,{children:[e.jsx(Ns,{children:"Edit Scheduled Post"}),e.jsx(nn,{children:"Update the caption or reschedule this post"})]}),i&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsx("div",{className:"aspect-square w-32 mx-auto overflow-hidden rounded-lg border",children:e.jsx("img",{src:i.image_url,alt:"Post preview",className:"h-full w-full object-cover"})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Caption"}),e.jsx(vr,{value:o,onChange:ne=>c(ne.target.value),rows:3})]}),e.jsxs("div",{className:"space-y-3 p-4 border rounded-lg",children:[e.jsx(ue,{children:"Schedule for"}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs(gl,{children:[e.jsx(xl,{asChild:!0,children:e.jsxs(H,{variant:"outline",className:Ft("justify-start text-left font-normal flex-1",!d&&"text-muted-foreground"),children:[e.jsx(Nn,{className:"mr-2 h-4 w-4"}),d?As(d,"PPP"):"Pick a date"]})}),e.jsx(il,{className:"w-auto p-0",align:"start",children:e.jsx(g0,{mode:"single",selected:d,onSelect:h,disabled:ne=>nee.jsx(pt,{value:ne,children:ne},ne))})]}),e.jsx("span",{className:"text-muted-foreground",children:":"}),e.jsxs(Bs,{value:x,onValueChange:y,children:[e.jsx(Os,{className:"w-[70px]",children:e.jsx(Us,{})}),e.jsx(Fs,{children:K.map(ne=>e.jsx(pt,{value:ne,children:ne},ne))})]}),e.jsxs(Bs,{value:_,onValueChange:ne=>b(ne),children:[e.jsx(Os,{className:"w-[70px]",children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"AM",children:"AM"}),e.jsx(pt,{value:"PM",children:"PM"})]})]})]})]})]})]}),e.jsxs(wn,{children:[e.jsx(H,{variant:"outline",onClick:()=>l(null),children:"Cancel"}),e.jsxs(H,{onClick:$,disabled:A.isPending,children:[A.isPending?e.jsx(is,{className:"h-4 w-4 animate-spin mr-2"}):null,"Save Changes"]})]})]})})]})}function uq(s){throw new Error('Could not dynamically require "'+s+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var qdt={exports:{}};/*! JSZip v3.10.1 - A JavaScript class for generating and reading zip files (c) 2009-2016 Stuart Knightley Dual licenced under the MIT license or GPLv3. See https://raw.github.com/Stuk/jszip/main/LICENSE.markdown. JSZip uses the library pako released under the MIT license : https://github.com/nodeca/pako/blob/main/LICENSE */(function(s,t){(function(r){s.exports=r()})(function(){return function r(n,a,i){function l(d,h){if(!a[d]){if(!n[d]){var m=typeof uq=="function"&&uq;if(!h&&m)return m(d,!0);if(o)return o(d,!0);var p=new Error("Cannot find module '"+d+"'");throw p.code="MODULE_NOT_FOUND",p}var x=a[d]={exports:{}};n[d][0].call(x.exports,function(y){var _=n[d][1][y];return l(_||y)},x,x.exports,r,n,a,i)}return a[d].exports}for(var o=typeof uq=="function"&&uq,c=0;c>2,x=(3&d)<<4|h>>4,y=1>6:64,_=2>4,h=(15&p)<<4|(x=o.indexOf(c.charAt(_++)))>>2,m=(3&x)<<6|(y=o.indexOf(c.charAt(_++))),k[b++]=d,x!==64&&(k[b++]=h),y!==64&&(k[b++]=m);return k}},{"./support":30,"./utils":32}],2:[function(r,n,a){var i=r("./external"),l=r("./stream/DataWorker"),o=r("./stream/Crc32Probe"),c=r("./stream/DataLengthProbe");function d(h,m,p,x,y){this.compressedSize=h,this.uncompressedSize=m,this.crc32=p,this.compression=x,this.compressedContent=y}d.prototype={getContentWorker:function(){var h=new l(i.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new c("data_length")),m=this;return h.on("end",function(){if(this.streamInfo.data_length!==m.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),h},getCompressedWorker:function(){return new l(i.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},d.createWorkerFrom=function(h,m,p){return h.pipe(new o).pipe(new c("uncompressedSize")).pipe(m.compressWorker(p)).pipe(new c("compressedSize")).withStreamInfo("compression",m)},n.exports=d},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(r,n,a){var i=r("./stream/GenericWorker");a.STORE={magic:"\0\0",compressWorker:function(){return new i("STORE compression")},uncompressWorker:function(){return new i("STORE decompression")}},a.DEFLATE=r("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(r,n,a){var i=r("./utils"),l=function(){for(var o,c=[],d=0;d<256;d++){o=d;for(var h=0;h<8;h++)o=1&o?3988292384^o>>>1:o>>>1;c[d]=o}return c}();n.exports=function(o,c){return o!==void 0&&o.length?i.getTypeOf(o)!=="string"?function(d,h,m,p){var x=l,y=p+m;d^=-1;for(var _=p;_>>8^x[255&(d^h[_])];return-1^d}(0|c,o,o.length,0):function(d,h,m,p){var x=l,y=p+m;d^=-1;for(var _=p;_>>8^x[255&(d^h.charCodeAt(_))];return-1^d}(0|c,o,o.length,0):0}},{"./utils":32}],5:[function(r,n,a){a.base64=!1,a.binary=!1,a.dir=!1,a.createFolders=!0,a.date=null,a.compression=null,a.compressionOptions=null,a.comment=null,a.unixPermissions=null,a.dosPermissions=null},{}],6:[function(r,n,a){var i=null;i=typeof Promise<"u"?Promise:r("lie"),n.exports={Promise:i}},{lie:37}],7:[function(r,n,a){var i=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Uint32Array<"u",l=r("pako"),o=r("./utils"),c=r("./stream/GenericWorker"),d=i?"uint8array":"array";function h(m,p){c.call(this,"FlateWorker/"+m),this._pako=null,this._pakoAction=m,this._pakoOptions=p,this.meta={}}a.magic="\b\0",o.inherits(h,c),h.prototype.processChunk=function(m){this.meta=m.meta,this._pako===null&&this._createPako(),this._pako.push(o.transformTo(d,m.data),!1)},h.prototype.flush=function(){c.prototype.flush.call(this),this._pako===null&&this._createPako(),this._pako.push([],!0)},h.prototype.cleanUp=function(){c.prototype.cleanUp.call(this),this._pako=null},h.prototype._createPako=function(){this._pako=new l[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var m=this;this._pako.onData=function(p){m.push({data:p,meta:m.meta})}},a.compressWorker=function(m){return new h("Deflate",m)},a.uncompressWorker=function(){return new h("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(r,n,a){function i(x,y){var _,b="";for(_=0;_>>=8;return b}function l(x,y,_,b,j,k){var T,E,A=x.file,D=x.compression,R=k!==d.utf8encode,z=o.transformTo("string",k(A.name)),O=o.transformTo("string",d.utf8encode(A.name)),$=A.comment,ee=o.transformTo("string",k($)),Z=o.transformTo("string",d.utf8encode($)),J=O.length!==A.name.length,K=Z.length!==$.length,re="",ie="",ce="",ne=A.dir,le=A.date,be={crc32:0,compressedSize:0,uncompressedSize:0};y&&!_||(be.crc32=x.crc32,be.compressedSize=x.compressedSize,be.uncompressedSize=x.uncompressedSize);var fe=0;y&&(fe|=8),R||!J&&!K||(fe|=2048);var je=0,ve=0;ne&&(je|=16),j==="UNIX"?(ve=798,je|=function(Ve,Le){var Me=Ve;return Ve||(Me=Le?16893:33204),(65535&Me)<<16}(A.unixPermissions,ne)):(ve=20,je|=function(Ve){return 63&(Ve||0)}(A.dosPermissions)),T=le.getUTCHours(),T<<=6,T|=le.getUTCMinutes(),T<<=5,T|=le.getUTCSeconds()/2,E=le.getUTCFullYear()-1980,E<<=4,E|=le.getUTCMonth()+1,E<<=5,E|=le.getUTCDate(),J&&(ie=i(1,1)+i(h(z),4)+O,re+="up"+i(ie.length,2)+ie),K&&(ce=i(1,1)+i(h(ee),4)+Z,re+="uc"+i(ce.length,2)+ce);var We="";return We+=` \0`,We+=i(fe,2),We+=D.magic,We+=i(T,2),We+=i(E,2),We+=i(be.crc32,4),We+=i(be.compressedSize,4),We+=i(be.uncompressedSize,4),We+=i(z.length,2),We+=i(re.length,2),{fileRecord:m.LOCAL_FILE_HEADER+We+z+re,dirRecord:m.CENTRAL_FILE_HEADER+i(ve,2)+We+i(ee.length,2)+"\0\0\0\0"+i(je,4)+i(b,4)+z+re+ee}}var o=r("../utils"),c=r("../stream/GenericWorker"),d=r("../utf8"),h=r("../crc32"),m=r("../signature");function p(x,y,_,b){c.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=y,this.zipPlatform=_,this.encodeFileName=b,this.streamFiles=x,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}o.inherits(p,c),p.prototype.push=function(x){var y=x.meta.percent||0,_=this.entriesCount,b=this._sources.length;this.accumulate?this.contentBuffer.push(x):(this.bytesWritten+=x.data.length,c.prototype.push.call(this,{data:x.data,meta:{currentFile:this.currentFile,percent:_?(y+100*(_-b-1))/_:100}}))},p.prototype.openedSource=function(x){this.currentSourceOffset=this.bytesWritten,this.currentFile=x.file.name;var y=this.streamFiles&&!x.file.dir;if(y){var _=l(x,y,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:_.fileRecord,meta:{percent:0}})}else this.accumulate=!0},p.prototype.closedSource=function(x){this.accumulate=!1;var y=this.streamFiles&&!x.file.dir,_=l(x,y,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(_.dirRecord),y)this.push({data:function(b){return m.DATA_DESCRIPTOR+i(b.crc32,4)+i(b.compressedSize,4)+i(b.uncompressedSize,4)}(x),meta:{percent:100}});else for(this.push({data:_.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},p.prototype.flush=function(){for(var x=this.bytesWritten,y=0;y=this.index;c--)d=(d<<8)+this.byteAt(c);return this.index+=o,d},readString:function(o){return i.transformTo("string",this.readData(o))},readData:function(){},lastIndexOfSignature:function(){},readAndCheckSignature:function(){},readDate:function(){var o=this.readInt(4);return new Date(Date.UTC(1980+(o>>25&127),(o>>21&15)-1,o>>16&31,o>>11&31,o>>5&63,(31&o)<<1))}},n.exports=l},{"../utils":32}],19:[function(r,n,a){var i=r("./Uint8ArrayReader");function l(o){i.call(this,o)}r("../utils").inherits(l,i),l.prototype.readData=function(o){this.checkOffset(o);var c=this.data.slice(this.zero+this.index,this.zero+this.index+o);return this.index+=o,c},n.exports=l},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(r,n,a){var i=r("./DataReader");function l(o){i.call(this,o)}r("../utils").inherits(l,i),l.prototype.byteAt=function(o){return this.data.charCodeAt(this.zero+o)},l.prototype.lastIndexOfSignature=function(o){return this.data.lastIndexOf(o)-this.zero},l.prototype.readAndCheckSignature=function(o){return o===this.readData(4)},l.prototype.readData=function(o){this.checkOffset(o);var c=this.data.slice(this.zero+this.index,this.zero+this.index+o);return this.index+=o,c},n.exports=l},{"../utils":32,"./DataReader":18}],21:[function(r,n,a){var i=r("./ArrayReader");function l(o){i.call(this,o)}r("../utils").inherits(l,i),l.prototype.readData=function(o){if(this.checkOffset(o),o===0)return new Uint8Array(0);var c=this.data.subarray(this.zero+this.index,this.zero+this.index+o);return this.index+=o,c},n.exports=l},{"../utils":32,"./ArrayReader":17}],22:[function(r,n,a){var i=r("../utils"),l=r("../support"),o=r("./ArrayReader"),c=r("./StringReader"),d=r("./NodeBufferReader"),h=r("./Uint8ArrayReader");n.exports=function(m){var p=i.getTypeOf(m);return i.checkSupport(p),p!=="string"||l.uint8array?p==="nodebuffer"?new d(m):l.uint8array?new h(i.transformTo("uint8array",m)):new o(i.transformTo("array",m)):new c(m)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(r,n,a){a.LOCAL_FILE_HEADER="PK",a.CENTRAL_FILE_HEADER="PK",a.CENTRAL_DIRECTORY_END="PK",a.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK\x07",a.ZIP64_CENTRAL_DIRECTORY_END="PK",a.DATA_DESCRIPTOR="PK\x07\b"},{}],24:[function(r,n,a){var i=r("./GenericWorker"),l=r("../utils");function o(c){i.call(this,"ConvertWorker to "+c),this.destType=c}l.inherits(o,i),o.prototype.processChunk=function(c){this.push({data:l.transformTo(this.destType,c.data),meta:c.meta})},n.exports=o},{"../utils":32,"./GenericWorker":28}],25:[function(r,n,a){var i=r("./GenericWorker"),l=r("../crc32");function o(){i.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}r("../utils").inherits(o,i),o.prototype.processChunk=function(c){this.streamInfo.crc32=l(c.data,this.streamInfo.crc32||0),this.push(c)},n.exports=o},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(r,n,a){var i=r("../utils"),l=r("./GenericWorker");function o(c){l.call(this,"DataLengthProbe for "+c),this.propName=c,this.withStreamInfo(c,0)}i.inherits(o,l),o.prototype.processChunk=function(c){if(c){var d=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=d+c.data.length}l.prototype.processChunk.call(this,c)},n.exports=o},{"../utils":32,"./GenericWorker":28}],27:[function(r,n,a){var i=r("../utils"),l=r("./GenericWorker");function o(c){l.call(this,"DataWorker");var d=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,c.then(function(h){d.dataIsReady=!0,d.data=h,d.max=h&&h.length||0,d.type=i.getTypeOf(h),d.isPaused||d._tickAndRepeat()},function(h){d.error(h)})}i.inherits(o,l),o.prototype.cleanUp=function(){l.prototype.cleanUp.call(this),this.data=null},o.prototype.resume=function(){return!!l.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,i.delay(this._tickAndRepeat,[],this)),!0)},o.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(i.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))},o.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var c=null,d=Math.min(this.max,this.index+16384);if(this.index>=this.max)return this.end();switch(this.type){case"string":c=this.data.substring(this.index,d);break;case"uint8array":c=this.data.subarray(this.index,d);break;case"array":case"nodebuffer":c=this.data.slice(this.index,d)}return this.index=d,this.push({data:c,meta:{percent:this.max?this.index/this.max*100:0}})},n.exports=o},{"../utils":32,"./GenericWorker":28}],28:[function(r,n,a){function i(l){this.name=l||"default",this.streamInfo={},this.generatedError=null,this.extraStreamInfo={},this.isPaused=!0,this.isFinished=!1,this.isLocked=!1,this._listeners={data:[],end:[],error:[]},this.previous=null}i.prototype={push:function(l){this.emit("data",l)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(l){this.emit("error",l)}return!0},error:function(l){return!this.isFinished&&(this.isPaused?this.generatedError=l:(this.isFinished=!0,this.emit("error",l),this.previous&&this.previous.error(l),this.cleanUp()),!0)},on:function(l,o){return this._listeners[l].push(o),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(l,o){if(this._listeners[l])for(var c=0;c "+l:l}},n.exports=i},{}],29:[function(r,n,a){var i=r("../utils"),l=r("./ConvertWorker"),o=r("./GenericWorker"),c=r("../base64"),d=r("../support"),h=r("../external"),m=null;if(d.nodestream)try{m=r("../nodejs/NodejsStreamOutputAdapter")}catch{}function p(y,_){return new h.Promise(function(b,j){var k=[],T=y._internalType,E=y._outputType,A=y._mimeType;y.on("data",function(D,R){k.push(D),_&&_(R)}).on("error",function(D){k=[],j(D)}).on("end",function(){try{var D=function(R,z,O){switch(R){case"blob":return i.newBlob(i.transformTo("arraybuffer",z),O);case"base64":return c.encode(z);default:return i.transformTo(R,z)}}(E,function(R,z){var O,$=0,ee=null,Z=0;for(O=0;O"u")a.blob=!1;else{var i=new ArrayBuffer(0);try{a.blob=new Blob([i],{type:"application/zip"}).size===0}catch{try{var l=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);l.append(i),a.blob=l.getBlob("application/zip").size===0}catch{a.blob=!1}}}try{a.nodestream=!!r("readable-stream").Readable}catch{a.nodestream=!1}},{"readable-stream":16}],31:[function(r,n,a){for(var i=r("./utils"),l=r("./support"),o=r("./nodejsUtils"),c=r("./stream/GenericWorker"),d=new Array(256),h=0;h<256;h++)d[h]=252<=h?6:248<=h?5:240<=h?4:224<=h?3:192<=h?2:1;d[254]=d[254]=1;function m(){c.call(this,"utf-8 decode"),this.leftOver=null}function p(){c.call(this,"utf-8 encode")}a.utf8encode=function(x){return l.nodebuffer?o.newBufferFrom(x,"utf-8"):function(y){var _,b,j,k,T,E=y.length,A=0;for(k=0;k>>6:(b<65536?_[T++]=224|b>>>12:(_[T++]=240|b>>>18,_[T++]=128|b>>>12&63),_[T++]=128|b>>>6&63),_[T++]=128|63&b);return _}(x)},a.utf8decode=function(x){return l.nodebuffer?i.transformTo("nodebuffer",x).toString("utf-8"):function(y){var _,b,j,k,T=y.length,E=new Array(2*T);for(_=b=0;_>10&1023,E[b++]=56320|1023&j)}return E.length!==b&&(E.subarray?E=E.subarray(0,b):E.length=b),i.applyFromCharCode(E)}(x=i.transformTo(l.uint8array?"uint8array":"array",x))},i.inherits(m,c),m.prototype.processChunk=function(x){var y=i.transformTo(l.uint8array?"uint8array":"array",x.data);if(this.leftOver&&this.leftOver.length){if(l.uint8array){var _=y;(y=new Uint8Array(_.length+this.leftOver.length)).set(this.leftOver,0),y.set(_,this.leftOver.length)}else y=this.leftOver.concat(y);this.leftOver=null}var b=function(k,T){var E;for((T=T||k.length)>k.length&&(T=k.length),E=T-1;0<=E&&(192&k[E])==128;)E--;return E<0||E===0?T:E+d[k[E]]>T?E:T}(y),j=y;b!==y.length&&(l.uint8array?(j=y.subarray(0,b),this.leftOver=y.subarray(b,y.length)):(j=y.slice(0,b),this.leftOver=y.slice(b,y.length))),this.push({data:a.utf8decode(j),meta:x.meta})},m.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:a.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},a.Utf8DecodeWorker=m,i.inherits(p,c),p.prototype.processChunk=function(x){this.push({data:a.utf8encode(x.data),meta:x.meta})},a.Utf8EncodeWorker=p},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(r,n,a){var i=r("./support"),l=r("./base64"),o=r("./nodejsUtils"),c=r("./external");function d(_){return _}function h(_,b){for(var j=0;j<_.length;++j)b[j]=255&_.charCodeAt(j);return b}r("setimmediate"),a.newBlob=function(_,b){a.checkSupport("blob");try{return new Blob([_],{type:b})}catch{try{var j=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);return j.append(_),j.getBlob(b)}catch{throw new Error("Bug : can't construct the Blob.")}}};var m={stringifyByChunk:function(_,b,j){var k=[],T=0,E=_.length;if(E<=j)return String.fromCharCode.apply(null,_);for(;T>8;this.dir=!!(16&this.externalFileAttributes),x==0&&(this.dosPermissions=63&this.externalFileAttributes),x==3&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||this.fileNameStr.slice(-1)!=="/"||(this.dir=!0)},parseZIP64ExtraField:function(){if(this.extraFields[1]){var x=i(this.extraFields[1].value);this.uncompressedSize===l.MAX_VALUE_32BITS&&(this.uncompressedSize=x.readInt(8)),this.compressedSize===l.MAX_VALUE_32BITS&&(this.compressedSize=x.readInt(8)),this.localHeaderOffset===l.MAX_VALUE_32BITS&&(this.localHeaderOffset=x.readInt(8)),this.diskNumberStart===l.MAX_VALUE_32BITS&&(this.diskNumberStart=x.readInt(4))}},readExtraFields:function(x){var y,_,b,j=x.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});x.index+4>>6:(x<65536?p[b++]=224|x>>>12:(p[b++]=240|x>>>18,p[b++]=128|x>>>12&63),p[b++]=128|x>>>6&63),p[b++]=128|63&x);return p},a.buf2binstring=function(m){return h(m,m.length)},a.binstring2buf=function(m){for(var p=new i.Buf8(m.length),x=0,y=p.length;x>10&1023,k[y++]=56320|1023&_)}return h(k,y)},a.utf8border=function(m,p){var x;for((p=p||m.length)>m.length&&(p=m.length),x=p-1;0<=x&&(192&m[x])==128;)x--;return x<0||x===0?p:x+c[m[x]]>p?x:p}},{"./common":41}],43:[function(r,n,a){n.exports=function(i,l,o,c){for(var d=65535&i|0,h=i>>>16&65535|0,m=0;o!==0;){for(o-=m=2e3>>1:l>>>1;o[c]=l}return o}();n.exports=function(l,o,c,d){var h=i,m=d+c;l^=-1;for(var p=d;p>>8^h[255&(l^o[p])];return-1^l}},{}],46:[function(r,n,a){var i,l=r("../utils/common"),o=r("./trees"),c=r("./adler32"),d=r("./crc32"),h=r("./messages"),m=0,p=4,x=0,y=-2,_=-1,b=4,j=2,k=8,T=9,E=286,A=30,D=19,R=2*E+1,z=15,O=3,$=258,ee=$+O+1,Z=42,J=113,K=1,re=2,ie=3,ce=4;function ne(ge,ct){return ge.msg=h[ct],ct}function le(ge){return(ge<<1)-(4ge.avail_out&&(Ue=ge.avail_out),Ue!==0&&(l.arraySet(ge.output,ct.pending_buf,ct.pending_out,Ue,ge.next_out),ge.next_out+=Ue,ct.pending_out+=Ue,ge.total_out+=Ue,ge.avail_out-=Ue,ct.pending-=Ue,ct.pending===0&&(ct.pending_out=0))}function je(ge,ct){o._tr_flush_block(ge,0<=ge.block_start?ge.block_start:-1,ge.strstart-ge.block_start,ct),ge.block_start=ge.strstart,fe(ge.strm)}function ve(ge,ct){ge.pending_buf[ge.pending++]=ct}function We(ge,ct){ge.pending_buf[ge.pending++]=ct>>>8&255,ge.pending_buf[ge.pending++]=255&ct}function Ve(ge,ct){var Ue,et,Qe=ge.max_chain_length,Ne=ge.strstart,$e=ge.prev_length,it=ge.nice_match,Je=ge.strstart>ge.w_size-ee?ge.strstart-(ge.w_size-ee):0,st=ge.window,mt=ge.w_mask,wt=ge.prev,at=ge.strstart+$,rt=st[Ne+$e-1],Et=st[Ne+$e];ge.prev_length>=ge.good_match&&(Qe>>=2),it>ge.lookahead&&(it=ge.lookahead);do if(st[(Ue=ct)+$e]===Et&&st[Ue+$e-1]===rt&&st[Ue]===st[Ne]&&st[++Ue]===st[Ne+1]){Ne+=2,Ue++;do;while(st[++Ne]===st[++Ue]&&st[++Ne]===st[++Ue]&&st[++Ne]===st[++Ue]&&st[++Ne]===st[++Ue]&&st[++Ne]===st[++Ue]&&st[++Ne]===st[++Ue]&&st[++Ne]===st[++Ue]&&st[++Ne]===st[++Ue]&&NeJe&&--Qe!=0);return $e<=ge.lookahead?$e:ge.lookahead}function Le(ge){var ct,Ue,et,Qe,Ne,$e,it,Je,st,mt,wt=ge.w_size;do{if(Qe=ge.window_size-ge.lookahead-ge.strstart,ge.strstart>=wt+(wt-ee)){for(l.arraySet(ge.window,ge.window,wt,wt,0),ge.match_start-=wt,ge.strstart-=wt,ge.block_start-=wt,ct=Ue=ge.hash_size;et=ge.head[--ct],ge.head[ct]=wt<=et?et-wt:0,--Ue;);for(ct=Ue=wt;et=ge.prev[--ct],ge.prev[ct]=wt<=et?et-wt:0,--Ue;);Qe+=wt}if(ge.strm.avail_in===0)break;if($e=ge.strm,it=ge.window,Je=ge.strstart+ge.lookahead,st=Qe,mt=void 0,mt=$e.avail_in,st=O)for(Ne=ge.strstart-ge.insert,ge.ins_h=ge.window[Ne],ge.ins_h=(ge.ins_h<=O&&(ge.ins_h=(ge.ins_h<=O)if(et=o._tr_tally(ge,ge.strstart-ge.match_start,ge.match_length-O),ge.lookahead-=ge.match_length,ge.match_length<=ge.max_lazy_match&&ge.lookahead>=O){for(ge.match_length--;ge.strstart++,ge.ins_h=(ge.ins_h<=O&&(ge.ins_h=(ge.ins_h<=O&&ge.match_length<=ge.prev_length){for(Qe=ge.strstart+ge.lookahead-O,et=o._tr_tally(ge,ge.strstart-1-ge.prev_match,ge.prev_length-O),ge.lookahead-=ge.prev_length-1,ge.prev_length-=2;++ge.strstart<=Qe&&(ge.ins_h=(ge.ins_h<ge.pending_buf_size-5&&(Ue=ge.pending_buf_size-5);;){if(ge.lookahead<=1){if(Le(ge),ge.lookahead===0&&ct===m)return K;if(ge.lookahead===0)break}ge.strstart+=ge.lookahead,ge.lookahead=0;var et=ge.block_start+Ue;if((ge.strstart===0||ge.strstart>=et)&&(ge.lookahead=ge.strstart-et,ge.strstart=et,je(ge,!1),ge.strm.avail_out===0)||ge.strstart-ge.block_start>=ge.w_size-ee&&(je(ge,!1),ge.strm.avail_out===0))return K}return ge.insert=0,ct===p?(je(ge,!0),ge.strm.avail_out===0?ie:ce):(ge.strstart>ge.block_start&&(je(ge,!1),ge.strm.avail_out),K)}),new Pe(4,4,8,4,Me),new Pe(4,5,16,8,Me),new Pe(4,6,32,32,Me),new Pe(4,4,16,16,ze),new Pe(8,16,32,32,ze),new Pe(8,16,128,128,ze),new Pe(8,32,128,256,ze),new Pe(32,128,258,1024,ze),new Pe(32,258,258,4096,ze)],a.deflateInit=function(ge,ct){return tt(ge,ct,k,15,8,0)},a.deflateInit2=tt,a.deflateReset=pe,a.deflateResetKeep=De,a.deflateSetHeader=function(ge,ct){return ge&&ge.state?ge.state.wrap!==2?y:(ge.state.gzhead=ct,x):y},a.deflate=function(ge,ct){var Ue,et,Qe,Ne;if(!ge||!ge.state||5>8&255),ve(et,et.gzhead.time>>16&255),ve(et,et.gzhead.time>>24&255),ve(et,et.level===9?2:2<=et.strategy||et.level<2?4:0),ve(et,255&et.gzhead.os),et.gzhead.extra&&et.gzhead.extra.length&&(ve(et,255&et.gzhead.extra.length),ve(et,et.gzhead.extra.length>>8&255)),et.gzhead.hcrc&&(ge.adler=d(ge.adler,et.pending_buf,et.pending,0)),et.gzindex=0,et.status=69):(ve(et,0),ve(et,0),ve(et,0),ve(et,0),ve(et,0),ve(et,et.level===9?2:2<=et.strategy||et.level<2?4:0),ve(et,3),et.status=J);else{var $e=k+(et.w_bits-8<<4)<<8;$e|=(2<=et.strategy||et.level<2?0:et.level<6?1:et.level===6?2:3)<<6,et.strstart!==0&&($e|=32),$e+=31-$e%31,et.status=J,We(et,$e),et.strstart!==0&&(We(et,ge.adler>>>16),We(et,65535&ge.adler)),ge.adler=1}if(et.status===69)if(et.gzhead.extra){for(Qe=et.pending;et.gzindex<(65535&et.gzhead.extra.length)&&(et.pending!==et.pending_buf_size||(et.gzhead.hcrc&&et.pending>Qe&&(ge.adler=d(ge.adler,et.pending_buf,et.pending-Qe,Qe)),fe(ge),Qe=et.pending,et.pending!==et.pending_buf_size));)ve(et,255&et.gzhead.extra[et.gzindex]),et.gzindex++;et.gzhead.hcrc&&et.pending>Qe&&(ge.adler=d(ge.adler,et.pending_buf,et.pending-Qe,Qe)),et.gzindex===et.gzhead.extra.length&&(et.gzindex=0,et.status=73)}else et.status=73;if(et.status===73)if(et.gzhead.name){Qe=et.pending;do{if(et.pending===et.pending_buf_size&&(et.gzhead.hcrc&&et.pending>Qe&&(ge.adler=d(ge.adler,et.pending_buf,et.pending-Qe,Qe)),fe(ge),Qe=et.pending,et.pending===et.pending_buf_size)){Ne=1;break}Ne=et.gzindexQe&&(ge.adler=d(ge.adler,et.pending_buf,et.pending-Qe,Qe)),Ne===0&&(et.gzindex=0,et.status=91)}else et.status=91;if(et.status===91)if(et.gzhead.comment){Qe=et.pending;do{if(et.pending===et.pending_buf_size&&(et.gzhead.hcrc&&et.pending>Qe&&(ge.adler=d(ge.adler,et.pending_buf,et.pending-Qe,Qe)),fe(ge),Qe=et.pending,et.pending===et.pending_buf_size)){Ne=1;break}Ne=et.gzindexQe&&(ge.adler=d(ge.adler,et.pending_buf,et.pending-Qe,Qe)),Ne===0&&(et.status=103)}else et.status=103;if(et.status===103&&(et.gzhead.hcrc?(et.pending+2>et.pending_buf_size&&fe(ge),et.pending+2<=et.pending_buf_size&&(ve(et,255&ge.adler),ve(et,ge.adler>>8&255),ge.adler=0,et.status=J)):et.status=J),et.pending!==0){if(fe(ge),ge.avail_out===0)return et.last_flush=-1,x}else if(ge.avail_in===0&&le(ct)<=le(Ue)&&ct!==p)return ne(ge,-5);if(et.status===666&&ge.avail_in!==0)return ne(ge,-5);if(ge.avail_in!==0||et.lookahead!==0||ct!==m&&et.status!==666){var it=et.strategy===2?function(Je,st){for(var mt;;){if(Je.lookahead===0&&(Le(Je),Je.lookahead===0)){if(st===m)return K;break}if(Je.match_length=0,mt=o._tr_tally(Je,0,Je.window[Je.strstart]),Je.lookahead--,Je.strstart++,mt&&(je(Je,!1),Je.strm.avail_out===0))return K}return Je.insert=0,st===p?(je(Je,!0),Je.strm.avail_out===0?ie:ce):Je.last_lit&&(je(Je,!1),Je.strm.avail_out===0)?K:re}(et,ct):et.strategy===3?function(Je,st){for(var mt,wt,at,rt,Et=Je.window;;){if(Je.lookahead<=$){if(Le(Je),Je.lookahead<=$&&st===m)return K;if(Je.lookahead===0)break}if(Je.match_length=0,Je.lookahead>=O&&0Je.lookahead&&(Je.match_length=Je.lookahead)}if(Je.match_length>=O?(mt=o._tr_tally(Je,1,Je.match_length-O),Je.lookahead-=Je.match_length,Je.strstart+=Je.match_length,Je.match_length=0):(mt=o._tr_tally(Je,0,Je.window[Je.strstart]),Je.lookahead--,Je.strstart++),mt&&(je(Je,!1),Je.strm.avail_out===0))return K}return Je.insert=0,st===p?(je(Je,!0),Je.strm.avail_out===0?ie:ce):Je.last_lit&&(je(Je,!1),Je.strm.avail_out===0)?K:re}(et,ct):i[et.level].func(et,ct);if(it!==ie&&it!==ce||(et.status=666),it===K||it===ie)return ge.avail_out===0&&(et.last_flush=-1),x;if(it===re&&(ct===1?o._tr_align(et):ct!==5&&(o._tr_stored_block(et,0,0,!1),ct===3&&(be(et.head),et.lookahead===0&&(et.strstart=0,et.block_start=0,et.insert=0))),fe(ge),ge.avail_out===0))return et.last_flush=-1,x}return ct!==p?x:et.wrap<=0?1:(et.wrap===2?(ve(et,255&ge.adler),ve(et,ge.adler>>8&255),ve(et,ge.adler>>16&255),ve(et,ge.adler>>24&255),ve(et,255&ge.total_in),ve(et,ge.total_in>>8&255),ve(et,ge.total_in>>16&255),ve(et,ge.total_in>>24&255)):(We(et,ge.adler>>>16),We(et,65535&ge.adler)),fe(ge),0=Ue.w_size&&(Ne===0&&(be(Ue.head),Ue.strstart=0,Ue.block_start=0,Ue.insert=0),st=new l.Buf8(Ue.w_size),l.arraySet(st,ct,mt-Ue.w_size,Ue.w_size,0),ct=st,mt=Ue.w_size),$e=ge.avail_in,it=ge.next_in,Je=ge.input,ge.avail_in=mt,ge.next_in=0,ge.input=ct,Le(Ue);Ue.lookahead>=O;){for(et=Ue.strstart,Qe=Ue.lookahead-(O-1);Ue.ins_h=(Ue.ins_h<>>=O=z>>>24,T-=O,(O=z>>>16&255)===0)re[h++]=65535&z;else{if(!(16&O)){if(!(64&O)){z=E[(65535&z)+(k&(1<>>=O,T-=O),T<15&&(k+=K[c++]<>>=O=z>>>24,T-=O,!(16&(O=z>>>16&255))){if(!(64&O)){z=A[(65535&z)+(k&(1<>>=O,T-=O,(O=h-m)>3,k&=(1<<(T-=$<<3))-1,i.next_in=c,i.next_out=h,i.avail_in=c>>24&255)+(Z>>>8&65280)+((65280&Z)<<8)+((255&Z)<<24)}function k(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new i.Buf16(320),this.work=new i.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function T(Z){var J;return Z&&Z.state?(J=Z.state,Z.total_in=Z.total_out=J.total=0,Z.msg="",J.wrap&&(Z.adler=1&J.wrap),J.mode=y,J.last=0,J.havedict=0,J.dmax=32768,J.head=null,J.hold=0,J.bits=0,J.lencode=J.lendyn=new i.Buf32(_),J.distcode=J.distdyn=new i.Buf32(b),J.sane=1,J.back=-1,p):x}function E(Z){var J;return Z&&Z.state?((J=Z.state).wsize=0,J.whave=0,J.wnext=0,T(Z)):x}function A(Z,J){var K,re;return Z&&Z.state?(re=Z.state,J<0?(K=0,J=-J):(K=1+(J>>4),J<48&&(J&=15)),J&&(J<8||15=ce.wsize?(i.arraySet(ce.window,J,K-ce.wsize,ce.wsize,0),ce.wnext=0,ce.whave=ce.wsize):(re<(ie=ce.wsize-ce.wnext)&&(ie=re),i.arraySet(ce.window,J,K-re,ie,ce.wnext),(re-=ie)?(i.arraySet(ce.window,J,K-re,re,0),ce.wnext=re,ce.whave=ce.wsize):(ce.wnext+=ie,ce.wnext===ce.wsize&&(ce.wnext=0),ce.whave>>8&255,K.check=o(K.check,Ne,2,0),je=fe=0,K.mode=2;break}if(K.flags=0,K.head&&(K.head.done=!1),!(1&K.wrap)||(((255&fe)<<8)+(fe>>8))%31){Z.msg="incorrect header check",K.mode=30;break}if((15&fe)!=8){Z.msg="unknown compression method",K.mode=30;break}if(je-=4,ge=8+(15&(fe>>>=4)),K.wbits===0)K.wbits=ge;else if(ge>K.wbits){Z.msg="invalid window size",K.mode=30;break}K.dmax=1<>8&1),512&K.flags&&(Ne[0]=255&fe,Ne[1]=fe>>>8&255,K.check=o(K.check,Ne,2,0)),je=fe=0,K.mode=3;case 3:for(;je<32;){if(le===0)break e;le--,fe+=re[ce++]<>>8&255,Ne[2]=fe>>>16&255,Ne[3]=fe>>>24&255,K.check=o(K.check,Ne,4,0)),je=fe=0,K.mode=4;case 4:for(;je<16;){if(le===0)break e;le--,fe+=re[ce++]<>8),512&K.flags&&(Ne[0]=255&fe,Ne[1]=fe>>>8&255,K.check=o(K.check,Ne,2,0)),je=fe=0,K.mode=5;case 5:if(1024&K.flags){for(;je<16;){if(le===0)break e;le--,fe+=re[ce++]<>>8&255,K.check=o(K.check,Ne,2,0)),je=fe=0}else K.head&&(K.head.extra=null);K.mode=6;case 6:if(1024&K.flags&&(le<(Ve=K.length)&&(Ve=le),Ve&&(K.head&&(ge=K.head.extra_len-K.length,K.head.extra||(K.head.extra=new Array(K.head.extra_len)),i.arraySet(K.head.extra,re,ce,Ve,ge)),512&K.flags&&(K.check=o(K.check,re,Ve,ce)),le-=Ve,ce+=Ve,K.length-=Ve),K.length))break e;K.length=0,K.mode=7;case 7:if(2048&K.flags){if(le===0)break e;for(Ve=0;ge=re[ce+Ve++],K.head&&ge&&K.length<65536&&(K.head.name+=String.fromCharCode(ge)),ge&&Ve>9&1,K.head.done=!0),Z.adler=K.check=0,K.mode=12;break;case 10:for(;je<32;){if(le===0)break e;le--,fe+=re[ce++]<>>=7&je,je-=7&je,K.mode=27;break}for(;je<3;){if(le===0)break e;le--,fe+=re[ce++]<>>=1)){case 0:K.mode=14;break;case 1:if($(K),K.mode=20,J!==6)break;fe>>>=2,je-=2;break e;case 2:K.mode=17;break;case 3:Z.msg="invalid block type",K.mode=30}fe>>>=2,je-=2;break;case 14:for(fe>>>=7&je,je-=7&je;je<32;){if(le===0)break e;le--,fe+=re[ce++]<>>16^65535)){Z.msg="invalid stored block lengths",K.mode=30;break}if(K.length=65535&fe,je=fe=0,K.mode=15,J===6)break e;case 15:K.mode=16;case 16:if(Ve=K.length){if(le>>=5,je-=5,K.ndist=1+(31&fe),fe>>>=5,je-=5,K.ncode=4+(15&fe),fe>>>=4,je-=4,286>>=3,je-=3}for(;K.have<19;)K.lens[$e[K.have++]]=0;if(K.lencode=K.lendyn,K.lenbits=7,Ue={bits:K.lenbits},ct=d(0,K.lens,0,19,K.lencode,0,K.work,Ue),K.lenbits=Ue.bits,ct){Z.msg="invalid code lengths set",K.mode=30;break}K.have=0,K.mode=19;case 19:for(;K.have>>16&255,Ie=65535&Qe,!((ze=Qe>>>24)<=je);){if(le===0)break e;le--,fe+=re[ce++]<>>=ze,je-=ze,K.lens[K.have++]=Ie;else{if(Ie===16){for(et=ze+2;je>>=ze,je-=ze,K.have===0){Z.msg="invalid bit length repeat",K.mode=30;break}ge=K.lens[K.have-1],Ve=3+(3&fe),fe>>>=2,je-=2}else if(Ie===17){for(et=ze+3;je>>=ze)),fe>>>=3,je-=3}else{for(et=ze+7;je>>=ze)),fe>>>=7,je-=7}if(K.have+Ve>K.nlen+K.ndist){Z.msg="invalid bit length repeat",K.mode=30;break}for(;Ve--;)K.lens[K.have++]=ge}}if(K.mode===30)break;if(K.lens[256]===0){Z.msg="invalid code -- missing end-of-block",K.mode=30;break}if(K.lenbits=9,Ue={bits:K.lenbits},ct=d(h,K.lens,0,K.nlen,K.lencode,0,K.work,Ue),K.lenbits=Ue.bits,ct){Z.msg="invalid literal/lengths set",K.mode=30;break}if(K.distbits=6,K.distcode=K.distdyn,Ue={bits:K.distbits},ct=d(m,K.lens,K.nlen,K.ndist,K.distcode,0,K.work,Ue),K.distbits=Ue.bits,ct){Z.msg="invalid distances set",K.mode=30;break}if(K.mode=20,J===6)break e;case 20:K.mode=21;case 21:if(6<=le&&258<=be){Z.next_out=ne,Z.avail_out=be,Z.next_in=ce,Z.avail_in=le,K.hold=fe,K.bits=je,c(Z,We),ne=Z.next_out,ie=Z.output,be=Z.avail_out,ce=Z.next_in,re=Z.input,le=Z.avail_in,fe=K.hold,je=K.bits,K.mode===12&&(K.back=-1);break}for(K.back=0;Pe=(Qe=K.lencode[fe&(1<>>16&255,Ie=65535&Qe,!((ze=Qe>>>24)<=je);){if(le===0)break e;le--,fe+=re[ce++]<>De)])>>>16&255,Ie=65535&Qe,!(De+(ze=Qe>>>24)<=je);){if(le===0)break e;le--,fe+=re[ce++]<>>=De,je-=De,K.back+=De}if(fe>>>=ze,je-=ze,K.back+=ze,K.length=Ie,Pe===0){K.mode=26;break}if(32&Pe){K.back=-1,K.mode=12;break}if(64&Pe){Z.msg="invalid literal/length code",K.mode=30;break}K.extra=15&Pe,K.mode=22;case 22:if(K.extra){for(et=K.extra;je>>=K.extra,je-=K.extra,K.back+=K.extra}K.was=K.length,K.mode=23;case 23:for(;Pe=(Qe=K.distcode[fe&(1<>>16&255,Ie=65535&Qe,!((ze=Qe>>>24)<=je);){if(le===0)break e;le--,fe+=re[ce++]<>De)])>>>16&255,Ie=65535&Qe,!(De+(ze=Qe>>>24)<=je);){if(le===0)break e;le--,fe+=re[ce++]<>>=De,je-=De,K.back+=De}if(fe>>>=ze,je-=ze,K.back+=ze,64&Pe){Z.msg="invalid distance code",K.mode=30;break}K.offset=Ie,K.extra=15&Pe,K.mode=24;case 24:if(K.extra){for(et=K.extra;je>>=K.extra,je-=K.extra,K.back+=K.extra}if(K.offset>K.dmax){Z.msg="invalid distance too far back",K.mode=30;break}K.mode=25;case 25:if(be===0)break e;if(Ve=We-be,K.offset>Ve){if((Ve=K.offset-Ve)>K.whave&&K.sane){Z.msg="invalid distance too far back",K.mode=30;break}Le=Ve>K.wnext?(Ve-=K.wnext,K.wsize-Ve):K.wnext-Ve,Ve>K.length&&(Ve=K.length),Me=K.window}else Me=ie,Le=ne-K.offset,Ve=K.length;for(beR?(O=Le[Me+b[J]],je[ve+b[J]]):(O=96,0),k=1<>ne)+(T-=k)]=z<<24|O<<16|$|0,T!==0;);for(k=1<>=1;if(k!==0?(fe&=k-1,fe+=k):fe=0,J++,--We[Z]==0){if(Z===re)break;Z=m[p+b[J]]}if(ie>>7)]}function ve(Qe,Ne){Qe.pending_buf[Qe.pending++]=255&Ne,Qe.pending_buf[Qe.pending++]=Ne>>>8&255}function We(Qe,Ne,$e){Qe.bi_valid>j-$e?(Qe.bi_buf|=Ne<>j-Qe.bi_valid,Qe.bi_valid+=$e-j):(Qe.bi_buf|=Ne<>>=1,$e<<=1,0<--Ne;);return $e>>>1}function Me(Qe,Ne,$e){var it,Je,st=new Array(b+1),mt=0;for(it=1;it<=b;it++)st[it]=mt=mt+$e[it-1]<<1;for(Je=0;Je<=Ne;Je++){var wt=Qe[2*Je+1];wt!==0&&(Qe[2*Je]=Le(st[wt]++,wt))}}function ze(Qe){var Ne;for(Ne=0;Ne>1;1<=$e;$e--)De(Qe,st,$e);for(Je=at;$e=Qe.heap[1],Qe.heap[1]=Qe.heap[Qe.heap_len--],De(Qe,st,1),it=Qe.heap[1],Qe.heap[--Qe.heap_max]=$e,Qe.heap[--Qe.heap_max]=it,st[2*Je]=st[2*$e]+st[2*it],Qe.depth[Je]=(Qe.depth[$e]>=Qe.depth[it]?Qe.depth[$e]:Qe.depth[it])+1,st[2*$e+1]=st[2*it+1]=Je,Qe.heap[1]=Je++,De(Qe,st,1),2<=Qe.heap_len;);Qe.heap[--Qe.heap_max]=Qe.heap[1],function(Et,hs){var Is,lr,us,St,xs,kt,fs=hs.dyn_tree,Gs=hs.max_code,_s=hs.stat_desc.static_tree,br=hs.stat_desc.has_stree,zr=hs.stat_desc.extra_bits,Yr=hs.stat_desc.extra_base,rn=hs.stat_desc.max_length,sn=0;for(St=0;St<=b;St++)Et.bl_count[St]=0;for(fs[2*Et.heap[Et.heap_max]+1]=0,Is=Et.heap_max+1;Is<_;Is++)rn<(St=fs[2*fs[2*(lr=Et.heap[Is])+1]+1]+1)&&(St=rn,sn++),fs[2*lr+1]=St,Gs>=7;Je>>=1)if(1&rt&&wt.dyn_ltree[2*at]!==0)return l;if(wt.dyn_ltree[18]!==0||wt.dyn_ltree[20]!==0||wt.dyn_ltree[26]!==0)return o;for(at=32;at>>3,(st=Qe.static_len+3+7>>>3)<=Je&&(Je=st)):Je=st=$e+5,$e+4<=Je&&Ne!==-1?et(Qe,Ne,$e,it):Qe.strategy===4||st===Je?(We(Qe,2+(it?1:0),3),pe(Qe,ee,Z)):(We(Qe,4+(it?1:0),3),function(wt,at,rt,Et){var hs;for(We(wt,at-257,5),We(wt,rt-1,5),We(wt,Et-4,4),hs=0;hs>>8&255,Qe.pending_buf[Qe.d_buf+2*Qe.last_lit+1]=255&Ne,Qe.pending_buf[Qe.l_buf+Qe.last_lit]=255&$e,Qe.last_lit++,Ne===0?Qe.dyn_ltree[2*$e]++:(Qe.matches++,Ne--,Qe.dyn_ltree[2*(K[$e]+m+1)]++,Qe.dyn_dtree[2*je(Ne)]++),Qe.last_lit===Qe.lit_bufsize-1},a._tr_align=function(Qe){We(Qe,2,3),Ve(Qe,T,ee),function(Ne){Ne.bi_valid===16?(ve(Ne,Ne.bi_buf),Ne.bi_buf=0,Ne.bi_valid=0):8<=Ne.bi_valid&&(Ne.pending_buf[Ne.pending++]=255&Ne.bi_buf,Ne.bi_buf>>=8,Ne.bi_valid-=8)}(Qe)}},{"../utils/common":41}],53:[function(r,n,a){n.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],54:[function(r,n,a){(function(i){(function(l,o){if(!l.setImmediate){var c,d,h,m,p=1,x={},y=!1,_=l.document,b=Object.getPrototypeOf&&Object.getPrototypeOf(l);b=b&&b.setTimeout?b:l,c={}.toString.call(l.process)==="[object process]"?function(E){process.nextTick(function(){k(E)})}:function(){if(l.postMessage&&!l.importScripts){var E=!0,A=l.onmessage;return l.onmessage=function(){E=!1},l.postMessage("","*"),l.onmessage=A,E}}()?(m="setImmediate$"+Math.random()+"$",l.addEventListener?l.addEventListener("message",T,!1):l.attachEvent("onmessage",T),function(E){l.postMessage(m+E,"*")}):l.MessageChannel?((h=new MessageChannel).port1.onmessage=function(E){k(E.data)},function(E){h.port2.postMessage(E)}):_&&"onreadystatechange"in _.createElement("script")?(d=_.documentElement,function(E){var A=_.createElement("script");A.onreadystatechange=function(){k(E),A.onreadystatechange=null,d.removeChild(A),A=null},d.appendChild(A)}):function(E){setTimeout(k,0,E)},b.setImmediate=function(E){typeof E!="function"&&(E=new Function(""+E));for(var A=new Array(arguments.length-1),D=0;D"u"?i===void 0?this:i:self)}).call(this,typeof uh<"u"?uh:typeof self<"u"?self:typeof window<"u"?window:{})},{}]},{},[10])(10)})})(qdt);var drs=qdt.exports;const Vdt=ol(drs);function p_e(s,t=400,r=75){return s&&`${s.replace("/storage/v1/object/public/","/storage/v1/render/image/public/")}?width=${t}&quality=${r}&resize=contain`}const urs=()=>{Ms();const[s,t]=S.useState(null),[r,n]=S.useState(null),[a,i]=S.useState("all"),[l,o]=S.useState(new Set),[c,d]=S.useState(!1),[h,m]=S.useState(!1),[p,x]=S.useState("images"),[y,_]=S.useState(null),{data:b=[],isLoading:j}=yt({queryKey:["social-swag-2"],queryFn:async()=>{const{data:ne,error:le}=await V.from("social_swag_2").select("*").order("month",{ascending:!1}).order("sort_order");if(le)throw le;return ne}}),{data:k=[]}=yt({queryKey:["social-swag-2-months"],queryFn:async()=>{const{data:ne,error:le}=await V.from("social_swag_2_months").select("*").order("month",{ascending:!1});if(le)throw le;return ne}}),{data:T=[]}=yt({queryKey:["social-swag-2-reels"],queryFn:async()=>{const{data:ne,error:le}=await V.from("social_swag_2_reels").select("*").order("month",{ascending:!1});if(le)throw le;return ne}}),{data:E=[]}=yt({queryKey:["my-social-accounts-count"],queryFn:async()=>{const{data:ne,error:le}=await V.from("social_accounts").select("id, platform").eq("is_active",!0);if(le)throw le;return ne||[]}}),A=E.length>0,D=S.useMemo(()=>a==="all"?null:T.find(ne=>ne.month===a)||null,[a,T]),R=S.useMemo(()=>[...new Set(b.map(le=>le.month))].sort((le,be)=>be.localeCompare(le)),[b]);S.useEffect(()=>{R.length>0&&a==="all"&&i(R[0])},[R,a]);const z=ne=>{try{const le=g5e(ne,"yyyy-MM",new Date);return As(le,"MMMM yyyy")}catch{return ne}},O=S.useMemo(()=>a==="all"?b:b.filter(ne=>ne.month===a),[a,b]),$=S.useMemo(()=>{var ne;return a==="all"?null:((ne=k.find(le=>le.month===a))==null?void 0:ne.canva_link)||null},[a,k]),ee=async ne=>{try{await navigator.clipboard.writeText(ne),he.success("Caption copied to clipboard!")}catch{he.error("Failed to copy caption")}},Z=async(ne,le)=>{try{const fe=await(await fetch(ne)).blob(),je=/iPhone|iPad|iPod|Android/i.test(navigator.userAgent),ve=navigator.canShare&&navigator.canShare({files:[new File([fe],"test.jpg",{type:"image/jpeg"})]});if(je&&ve){const We=new File([fe],`social-swag-${le}.jpg`,{type:"image/jpeg"});await navigator.share({files:[We],title:"Social Swag Image"}),he.success("Image ready to save!")}else{const We=window.URL.createObjectURL(fe),Ve=document.createElement("a");Ve.href=We,Ve.download=`social-swag-${le}.jpg`,document.body.appendChild(Ve),Ve.click(),document.body.removeChild(Ve),window.URL.revokeObjectURL(We),he.success("Image downloaded!")}}catch(be){be.name!=="AbortError"&&he.error("Failed to download image")}},J=ne=>{o(le=>{const be=new Set(le);return be.has(ne)?be.delete(ne):be.add(ne),be})},K=()=>{o(new Set(O.map(ne=>ne.id)))},re=()=>{o(new Set),d(!1)},ie=async()=>{const ne=O.filter(le=>l.has(le.id));if(ne.length===0){he.error("No images selected");return}m(!0),he.info(`Preparing ${ne.length} images for download...`);try{const le=new Vdt,be=[...ne].sort((Ve,Le)=>Ve.sort_order-Le.sort_order);for(let Ve=0;Ve{c?J(ne.id):t(ne)};return e.jsx(Ss,{title:"Social Swag 2.0",children:e.jsxs("div",{className:"space-y-8",children:[e.jsxs("div",{className:"relative overflow-hidden rounded-2xl bg-gradient-to-br from-primary via-primary/80 to-info p-8 text-primary-foreground",children:[e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmYiIGZpbGwtb3BhY2l0eT0iMC4xIj48cGF0aCBkPSJNMzYgMzRjMC0yIDItNCAyLTRzMiAyIDIgNC0yIDQtMiA0LTItMi0yLTR6Ii8+PC9nPjwvZz48L3N2Zz4=')] opacity-30"}),e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3 mb-4",children:[e.jsxs(Xe,{variant:"secondary",className:"bg-white/20 text-white border-0 backdrop-blur-sm",children:[e.jsx(Lr,{className:"h-3 w-3 mr-1"}),"New content monthly"]}),e.jsxs(Xe,{variant:"secondary",className:"bg-white/20 text-white border-0 backdrop-blur-sm",children:[e.jsx(wl,{className:"h-3 w-3 mr-1"}),b.length," images"]})]}),e.jsx("h1",{className:"text-3xl md:text-4xl font-bold mb-3",children:"Social Swag 📸"}),e.jsx("p",{className:"text-lg text-primary-foreground/90 max-w-2xl",children:"Ready-to-post social media images delivered to you monthly. Just download, copy the caption, and share with your audience!"})]})]}),e.jsxs(ta,{defaultValue:"gallery",className:"space-y-6",children:[e.jsxs(Qn,{className:"grid w-full max-w-md grid-cols-2",children:[e.jsxs(ts,{value:"gallery",className:"gap-2",children:[e.jsx(wl,{className:"h-4 w-4"}),"Gallery"]}),e.jsxs(ts,{value:"scheduled",className:"gap-2",children:[e.jsx(xu,{className:"h-4 w-4"}),"Scheduled"]})]}),e.jsxs(cs,{value:"gallery",className:"space-y-6",children:[A?e.jsx(ke,{className:"border rounded-xl",children:e.jsx(Oe,{className:"p-6",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"p-3 rounded-full bg-muted text-2xl",children:"📸"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"font-semibold text-foreground mb-1",children:"Ready to post!"}),e.jsx("p",{className:"text-muted-foreground",children:'Click any image and use "Create Post" to share directly to your connected accounts.'})]}),e.jsx(H,{variant:"outline",size:"sm",asChild:!0,className:"gap-2",children:e.jsx(Xn,{to:"/mission-control/integrations",children:"Manage Accounts"})})]})})}):e.jsx(ke,{className:"border-2 border-dashed border-primary/30 bg-gradient-to-r from-pink-500/5 via-purple-500/5 to-blue-500/5 rounded-xl",children:e.jsx(Oe,{className:"p-6",children:e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"p-2 rounded-full bg-blue-500/10",children:e.jsx(fh,{className:"h-5 w-5 text-blue-600"})}),e.jsx("div",{className:"p-2 rounded-full bg-pink-500/10",children:e.jsx(yu,{className:"h-5 w-5 text-pink-600"})})]}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"font-semibold text-foreground mb-1",children:"Post directly to social media"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Connect your Facebook & Instagram accounts to post images with one click!"})]}),e.jsx(H,{asChild:!0,className:"gap-2 bg-gradient-to-r from-pink-500 via-purple-500 to-blue-500 hover:from-pink-600 hover:via-purple-600 hover:to-blue-600",children:e.jsxs(Xn,{to:"/social-connections",children:[e.jsx(ql,{className:"h-4 w-4"}),"Connect Accounts"]})})]})})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"flex flex-wrap gap-2",children:R.map(ne=>e.jsx("button",{onClick:()=>i(ne),className:Ft("px-4 py-2 rounded-full text-sm font-medium transition-all",a===ne?"bg-primary text-primary-foreground shadow-sm":"bg-muted text-muted-foreground hover:text-foreground"),children:z(ne)},ne))}),a!=="all"&&($?e.jsxs("a",{href:$,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-2 text-sm text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx("span",{className:"text-base",children:"🎨"}),"Edit ",z(a)," Images in Canva"]}):e.jsxs("span",{className:"inline-flex items-center gap-2 text-sm text-muted-foreground/50",children:[e.jsx("span",{className:"text-base",children:"🎨"}),"Edit ",z(a)," Images in Canva"]}))]}),e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-1 p-1 bg-muted rounded-full",children:[e.jsxs("button",{onClick:()=>{x("images"),re()},className:Ft("flex items-center gap-2 px-4 py-2 rounded-full text-sm font-medium transition-all",p==="images"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:[e.jsx(wl,{className:"h-4 w-4"}),"Images"]}),e.jsxs("button",{onClick:()=>{x("reels"),re()},className:Ft("flex items-center gap-2 px-4 py-2 rounded-full text-sm font-medium transition-all",p==="reels"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:[e.jsx(Qm,{className:"h-4 w-4"}),"Reels"]})]}),p==="images"&&e.jsx("div",{className:"flex flex-wrap items-center gap-3",children:c?e.jsxs(e.Fragment,{children:[e.jsxs(H,{variant:"outline",size:"sm",onClick:K,className:"gap-2",children:["Select All (",O.length,")"]}),e.jsxs(H,{variant:"outline",size:"sm",onClick:re,className:"gap-2",children:[e.jsx(Rr,{className:"h-4 w-4"}),"Cancel"]}),l.size>0&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(H,{size:"sm",onClick:ie,disabled:h,className:"gap-2",children:[e.jsx(hi,{className:"h-4 w-4"}),h?"Downloading...":`Download ${l.size} Selected`]}),e.jsx("span",{className:"text-xs text-muted-foreground hidden sm:inline",children:"Please ensure your browser allows downloads from the LevelUp Dashboard."})]})]}):e.jsxs(H,{variant:"outline",size:"sm",onClick:()=>d(!0),className:"gap-2",children:[e.jsx(va,{className:"h-4 w-4"}),"Select Images"]})})]}),j&&e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading..."}),!j&&p==="images"&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4",children:O.map(ne=>{const le=l.has(ne.id);return e.jsx(ke,{className:Ft("group cursor-pointer overflow-hidden border-0 shadow-md hover:shadow-xl transition-all duration-300 rounded-2xl",c&&le&&"ring-2 ring-primary ring-offset-2"),onClick:()=>ce(ne),children:e.jsxs("div",{className:"relative aspect-[4/5] overflow-hidden",children:[e.jsx("img",{src:p_e(ne.image_url,400,75),alt:"Social swag",className:"w-full h-full object-cover transition-transform duration-300 group-hover:scale-110",loading:"lazy",decoding:"async"}),ne.post_date&&!c&&e.jsx("div",{className:"absolute top-0 left-0 w-24 h-24 overflow-hidden pointer-events-none",children:e.jsx("div",{className:"absolute flex items-center justify-center text-white font-bold text-[10px] tracking-wider uppercase",style:{top:"20px",left:"-34px",width:"136px",transform:"rotate(-45deg)",backgroundColor:"#2d5052",padding:"5px 0",boxShadow:"0 2px 4px rgba(0,0,0,0.25)"},children:As(new Date(ne.post_date+"T00:00:00"),"MMM d")})}),c&&e.jsx("div",{className:Ft("absolute top-2 right-2 w-6 h-6 rounded-full border-2 flex items-center justify-center transition-all",le?"bg-primary border-primary text-primary-foreground":"bg-white/80 border-muted-foreground/50"),children:le&&e.jsx(va,{className:"h-4 w-4"})}),!c&&e.jsx("div",{className:"absolute inset-0 bg-black/0 group-hover:bg-black/40 transition-colors duration-300 flex items-center justify-center",children:e.jsx("span",{className:"text-white font-medium opacity-0 group-hover:opacity-100 transition-opacity duration-300 bg-primary px-4 py-2 rounded-full text-sm",children:"View Details"})})]})},ne.id)})}),O.length===0&&e.jsxs("div",{className:"text-center py-12",children:[e.jsx(wl,{className:"h-12 w-12 text-muted-foreground/50 mx-auto mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:"No images available for this month yet."})]})]}),!j&&p==="reels"&&e.jsx(e.Fragment,{children:D?e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 gap-4",children:e.jsx(ke,{className:"group overflow-hidden rounded-2xl cursor-pointer transition-all duration-300 hover:shadow-xl hover:scale-[1.02]",onClick:()=>n(D),children:e.jsxs("div",{className:"relative aspect-[9/16] overflow-hidden",children:[e.jsx("img",{src:p_e(D.image_url,400,75),alt:"Reel preview",className:"w-full h-full object-cover transition-transform duration-300 group-hover:scale-105",loading:"lazy",decoding:"async"}),e.jsx("div",{className:"absolute top-2 left-2",children:e.jsxs(Xe,{variant:"secondary",className:"bg-black/50 text-white border-0 backdrop-blur-sm text-xs",children:[e.jsx(Qm,{className:"h-3 w-3 mr-1"}),"Reel"]})}),e.jsx("div",{className:"absolute inset-0 bg-black/0 group-hover:bg-black/40 transition-colors duration-300 flex items-center justify-center",children:e.jsx("span",{className:"text-white font-medium opacity-0 group-hover:opacity-100 transition-opacity duration-300 bg-primary px-4 py-2 rounded-full text-sm",children:"View Details"})})]})})}):e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Qm,{className:"h-12 w-12 text-muted-foreground/50 mx-auto mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:"No reel available for this month yet."})]})})]}),e.jsx(bs,{open:!!s,onOpenChange:()=>t(null),children:e.jsx(vs,{className:"max-w-4xl max-h-[90vh] overflow-hidden p-0",children:e.jsx("div",{className:"max-h-[90vh] overflow-y-auto touch-pan-y",style:{WebkitOverflowScrolling:"touch"},children:s&&e.jsxs("div",{className:"flex flex-col md:flex-row",children:[e.jsx("div",{className:"md:w-1/2 bg-muted",children:e.jsx("div",{className:"aspect-[4/5]",children:e.jsx("img",{src:p_e(s.image_url,900,85),alt:"Social swag",className:"w-full h-full object-cover",decoding:"async"})})}),e.jsxs("div",{className:"md:w-1/2 p-6 flex flex-col",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-sm text-muted-foreground mb-4",children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Nn,{className:"h-4 w-4"}),As(new Date(s.created_at),"MMMM d, yyyy")]}),s.post_date&&e.jsxs("span",{className:"inline-flex items-center gap-1.5 font-medium rounded-full px-3 py-1 text-xs text-white",style:{background:"#406E71"},children:[e.jsx(Nn,{className:"h-3.5 w-3.5"}),"Post on ",As(new Date(s.post_date+"T00:00:00"),"MMMM d, yyyy")]})]}),e.jsxs("div",{className:"flex-1 min-h-0",children:[e.jsx("h4",{className:"text-sm font-medium text-foreground mb-2",children:"Caption"}),e.jsx("div",{className:"bg-muted/50 rounded-lg p-4 max-h-64 overflow-y-auto",children:e.jsx("p",{className:"text-sm text-foreground whitespace-pre-wrap",children:s.caption})})]}),e.jsxs("div",{className:"flex flex-col gap-3 mt-6",children:[e.jsxs(H,{onClick:()=>{_({imageUrl:s.image_url,imageId:s.id,caption:s.caption})},className:"w-full gap-2 bg-gradient-to-r from-pink-500 via-purple-500 to-blue-500 hover:from-pink-600 hover:via-purple-600 hover:to-blue-600 text-white",children:[e.jsx(yn,{className:"h-4 w-4"}),"Create Post"]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs(H,{variant:"outline",onClick:()=>ee(s.caption),className:"flex-1 gap-2",children:[e.jsx(ui,{className:"h-4 w-4"}),"Copy Caption"]}),e.jsxs(H,{variant:"outline",onClick:()=>Z(s.image_url,s.id),className:"flex-1 gap-2",children:[e.jsx(hi,{className:"h-4 w-4"}),"Download"]})]})]})]})]})})})}),e.jsx(bs,{open:!!r,onOpenChange:()=>n(null),children:e.jsx(vs,{className:"max-w-4xl max-h-[90vh] overflow-hidden p-0",children:e.jsx("div",{className:"max-h-[90vh] overflow-y-auto touch-pan-y",style:{WebkitOverflowScrolling:"touch"},children:r&&e.jsxs("div",{className:"flex flex-col md:flex-row",children:[e.jsx("div",{className:"md:w-1/2 bg-black flex items-center justify-center",children:e.jsx("div",{className:"aspect-[9/16] max-h-[70vh]",children:e.jsx("img",{src:r.image_url,alt:"Reel preview",className:"w-full h-full object-contain"})})}),e.jsxs("div",{className:"md:w-1/2 p-6 flex flex-col",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground mb-4",children:[e.jsx(Qm,{className:"h-4 w-4"}),"Monthly Reel"]}),r.caption&&e.jsxs("div",{className:"flex-1 min-h-0",children:[e.jsx("h4",{className:"text-sm font-medium text-foreground mb-2",children:"Caption"}),e.jsx("div",{className:"bg-muted/50 rounded-lg p-4 max-h-64 overflow-y-auto",children:e.jsx("p",{className:"text-sm text-foreground whitespace-pre-wrap",children:r.caption})})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3 mt-6",children:[r.caption&&e.jsxs(H,{onClick:()=>ee(r.caption||""),className:"flex-1 gap-2",children:[e.jsx(ui,{className:"h-4 w-4"}),"Copy Caption"]}),r.canva_link&&e.jsxs(H,{variant:"outline",onClick:()=>window.open(r.canva_link,"_blank"),className:"flex-1 gap-2",children:[e.jsx(gn,{className:"h-4 w-4"}),"Open in Canva"]})]})]})]})})})}),e.jsx(lrs,{open:!!y,onOpenChange:ne=>!ne&&_(null),imageUrl:(y==null?void 0:y.imageUrl)||"",imageId:(y==null?void 0:y.imageId)||"",defaultCaption:(y==null?void 0:y.caption)||"",swagItemId:y==null?void 0:y.imageId})]}),e.jsx(cs,{value:"scheduled",children:e.jsx(crs,{})})]})]})})},hrs=[{id:"branding-bar",title:"Branding Bar Studio",description:"Drop in any image — get a branded version with your headshot, logo, and contact info.",icon:wl,to:"/marketing-studio/branding-bar",color:"from-violet-500 to-fuchsia-500"},{id:"listing-templates",title:"Listing Templates",description:"Just Listed, Just Sold, Open House, Price Drop — pulled from your MLS in one click.",icon:Fn,to:"/marketing-studio/listing-templates",color:"from-blue-500 to-cyan-500"},{id:"personal-branding",title:"Personal Branding",description:'"Meet your agent", testimonials, milestones, pro tips — four editorial styles.',icon:io,to:"/marketing-studio/personal-branding",color:"from-emerald-500 to-teal-500"},{id:"market-updates",title:"Market Updates",description:"Auto-built from your MLS data — median price, days on market, year-over-year.",icon:Bo,comingSoon:!0,color:"from-orange-500 to-red-500"},{id:"milestones",title:"Client Milestones",description:"Closing day, home anniversaries, birthdays, referral thank-yous.",icon:gm,comingSoon:!0,color:"from-pink-500 to-rose-500"},{id:"holiday",title:"Holiday & Seasonal",description:"Pre-designed templates for every holiday, restyled to your brand.",icon:h1,comingSoon:!0,color:"from-sky-500 to-indigo-500"},{id:"testimonial",title:"Testimonial Generator",description:"Paste a Zillow or Google review → branded testimonial graphic.",icon:HI,comingSoon:!0,color:"from-amber-500 to-yellow-500"}];function mrs(){return e.jsx(Ss,{title:"Marketing Studio",children:e.jsxs("div",{className:"container max-w-6xl py-8 space-y-6",children:[e.jsxs(el,{children:[e.jsx("title",{children:"Marketing Studio | LevelUp"}),e.jsx("meta",{name:"description",content:"Brand any image, video, listing, or milestone in seconds — no AI credits used."})]}),e.jsxs("div",{className:"flex flex-col md:flex-row md:items-end md:justify-between gap-4",children:[e.jsxs("div",{children:[e.jsxs(Xe,{variant:"secondary",className:"mb-2 gap-1",children:[e.jsx(Lr,{className:"h-3 w-3"})," New"]}),e.jsx("h1",{className:"text-3xl md:text-4xl font-bold tracking-tight",children:"Marketing Studio"}),e.jsx("p",{className:"text-muted-foreground max-w-2xl mt-1",children:"Your one-stop creative hub. Drop in any photo or video, and walk away with a fully branded export — no design skills, no AI credits."})]}),e.jsx(H,{variant:"outline",asChild:!0,children:e.jsxs(Xn,{to:"/marketing-studio/brand-kit",children:[e.jsx(pl,{className:"h-4 w-4 mr-1"})," Manage Brand Kit"]})})]}),e.jsx("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3",children:hrs.map(s=>{const t=s.icon,r=e.jsxs(ke,{className:`group relative overflow-hidden transition-all h-full ${s.comingSoon?"opacity-70":"hover:shadow-xl hover:-translate-y-0.5 cursor-pointer"}`,children:[e.jsx("div",{className:`absolute inset-x-0 top-0 h-1 bg-gradient-to-r ${s.color}`}),e.jsxs(Oe,{className:"p-5 space-y-3",children:[e.jsx("div",{className:`inline-flex h-10 w-10 items-center justify-center rounded-lg bg-gradient-to-br ${s.color} text-white shadow-md`,children:e.jsx(t,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"font-semibold",children:s.title}),s.comingSoon&&e.jsx(Xe,{variant:"outline",className:"text-[10px]",children:"Coming soon"})]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:s.description})]})]})]});return s.to&&!s.comingSoon?e.jsx(Xn,{to:s.to,className:"block",children:r},s.id):e.jsx("div",{children:r},s.id)})})]})})}function gz(){const s=ba();return yt({queryKey:["marketing-brand-presets",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await V.from("marketing_brand_presets").select("*").eq("user_id",s).order("is_default",{ascending:!1}).order("created_at",{ascending:!0});if(r)throw r;return t||[]},enabled:!!s})}function frs(){const{data:s,...t}=gz();return{data:(s==null?void 0:s.find(r=>r.is_default))??(s==null?void 0:s[0])??null,...t}}function prs(){const s=ba(),t=ns();return Pt({mutationFn:async r=>{if(!s)throw new Error("Not signed in");if(r.is_default&&await V.from("marketing_brand_presets").update({is_default:!1}).eq("user_id",s),r.id){const{id:n,...a}=r,{data:i,error:l}=await V.from("marketing_brand_presets").update(a).eq("id",n).eq("user_id",s).select().single();if(l)throw l;return i}else{const{data:n,error:a}=await V.from("marketing_brand_presets").insert({...r,user_id:s}).select().single();if(a)throw a;return n}},onSuccess:()=>t.invalidateQueries({queryKey:["marketing-brand-presets",s]})})}function grs(){const s=ba(),t=ns();return Pt({mutationFn:async r=>{const{error:n}=await V.from("marketing_brand_presets").delete().eq("id",r);if(n)throw n},onSuccess:()=>t.invalidateQueries({queryKey:["marketing-brand-presets",s]})})}async function xrs(s,t,r){var o;const n=((o=t.name.split(".").pop())==null?void 0:o.toLowerCase())||"png",a=`${s}/${r}-${Date.now()}.${n}`,{error:i}=await V.storage.from("marketing-studio-uploads").upload(a,t,{upsert:!0,cacheControl:"3600"});if(i)throw i;const{data:l}=await V.storage.from("marketing-studio-uploads").createSignedUrl(a,60*60*24*365*5);return(l==null?void 0:l.signedUrl)??""}function yrs({preset:s,onSaved:t,onCancel:r}){var _;const n=ba(),a=prs(),i=grs(),l=S.useRef(null),o=S.useRef(null),[c,d]=S.useState(null),[h,m]=S.useState({name:(s==null?void 0:s.name)??"My Brand",is_default:(s==null?void 0:s.is_default)??!0,display_name:(s==null?void 0:s.display_name)??"",phone:(s==null?void 0:s.phone)??"",email:(s==null?void 0:s.email)??"",license_number:(s==null?void 0:s.license_number)??"",tagline:(s==null?void 0:s.tagline)??"",website_url:(s==null?void 0:s.website_url)??"",headshot_url:(s==null?void 0:s.headshot_url)??"",brokerage_logo_url:(s==null?void 0:s.brokerage_logo_url)??"",brand_color:(s==null?void 0:s.brand_color)??"#0f172a",accent_color:(s==null?void 0:s.accent_color)??"#3b82f6"});S.useEffect(()=>{s||(async()=>{if(!n)return;const{supabase:b}=await Ti(async()=>{const{supabase:k}=await Promise.resolve().then(()=>iMt);return{supabase:k}},[]),{data:j}=await b.from("profiles").select("name, email, phone, avatar_url, website_url, title, brokerage_id").eq("id",n).maybeSingle();j&&m(k=>({...k,display_name:k.display_name||(j.name??""),email:k.email||(j.email??""),phone:k.phone||(j.phone??""),headshot_url:k.headshot_url||(j.avatar_url??""),website_url:k.website_url||(j.website_url??""),tagline:k.tagline||(j.title??"")}))})()},[n]);const p=async(b,j)=>{if(n){d(b);try{const k=await xrs(n,j,b);m(T=>({...T,[b==="headshot"?"headshot_url":"brokerage_logo_url"]:k}))}catch(k){he.error(k.message||"Upload failed")}finally{d(null)}}},x=async()=>{try{const b=await a.mutateAsync({id:s==null?void 0:s.id,...h});he.success("Brand preset saved"),t==null||t(b)}catch(b){he.error(b.message||"Save failed")}},y=async()=>{s!=null&&s.id&&confirm("Delete this brand preset?")&&(await i.mutateAsync(s.id),he.success("Preset deleted"),r==null||r())};return e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(ue,{children:"Preset name"}),e.jsx(Se,{value:h.name,onChange:b=>m({...h,name:b.target.value}),placeholder:"Personal, Team, Luxury..."})]}),e.jsxs("div",{className:"flex items-end gap-3 pb-1",children:[e.jsx(Or,{checked:h.is_default,onCheckedChange:b=>m({...h,is_default:b})}),e.jsx(ue,{children:"Use as default"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(ue,{children:"Display name"}),e.jsx(Se,{value:h.display_name,onChange:b=>m({...h,display_name:b.target.value})})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Phone"}),e.jsx(Se,{value:h.phone,onChange:b=>m({...h,phone:b.target.value})})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Email"}),e.jsx(Se,{value:h.email,onChange:b=>m({...h,email:b.target.value})})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"License #"}),e.jsx(Se,{value:h.license_number,onChange:b=>m({...h,license_number:b.target.value})})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(ue,{children:"Tagline"}),e.jsx(Se,{value:h.tagline,onChange:b=>m({...h,tagline:b.target.value}),placeholder:"Helping families find home"})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(ue,{children:"Website"}),e.jsx(Se,{value:h.website_url,onChange:b=>m({...h,website_url:b.target.value})})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Headshot"}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(Un,{className:"h-16 w-16",children:[e.jsx(Ka,{src:h.headshot_url||void 0}),e.jsx(qn,{children:((_=h.display_name)==null?void 0:_[0])??"A"})]}),e.jsxs(H,{type:"button",variant:"outline",size:"sm",onClick:()=>{var b;return(b=l.current)==null?void 0:b.click()},disabled:c==="headshot",children:[c==="headshot"?e.jsx(is,{className:"h-4 w-4 animate-spin"}):e.jsx(Ea,{className:"h-4 w-4 mr-1"}),"Upload"]}),e.jsx("input",{ref:l,type:"file",accept:"image/*",hidden:!0,onChange:b=>{var j;return((j=b.target.files)==null?void 0:j[0])&&p("headshot",b.target.files[0])}})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Brokerage logo"}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-16 w-24 bg-muted rounded flex items-center justify-center overflow-hidden border",children:h.brokerage_logo_url?e.jsx("img",{src:h.brokerage_logo_url,alt:"logo",className:"max-h-full max-w-full object-contain"}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"No logo"})}),e.jsxs(H,{type:"button",variant:"outline",size:"sm",onClick:()=>{var b;return(b=o.current)==null?void 0:b.click()},disabled:c==="logo",children:[c==="logo"?e.jsx(is,{className:"h-4 w-4 animate-spin"}):e.jsx(Ea,{className:"h-4 w-4 mr-1"}),"Upload"]}),e.jsx("input",{ref:o,type:"file",accept:"image/*",hidden:!0,onChange:b=>{var j;return((j=b.target.files)==null?void 0:j[0])&&p("logo",b.target.files[0])}})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(ue,{children:"Brand color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:h.brand_color,onChange:b=>m({...h,brand_color:b.target.value}),className:"h-10 w-14 rounded cursor-pointer border"}),e.jsx(Se,{value:h.brand_color,onChange:b=>m({...h,brand_color:b.target.value})})]})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Accent color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:h.accent_color,onChange:b=>m({...h,accent_color:b.target.value}),className:"h-10 w-14 rounded cursor-pointer border"}),e.jsx(Se,{value:h.accent_color,onChange:b=>m({...h,accent_color:b.target.value})})]})]})]}),e.jsxs("div",{className:"flex justify-between pt-2",children:[e.jsx("div",{children:(s==null?void 0:s.id)&&e.jsxs(H,{variant:"ghost",size:"sm",onClick:y,className:"text-destructive",children:[e.jsx(Dr,{className:"h-4 w-4 mr-1"})," Delete"]})}),e.jsxs("div",{className:"flex gap-2",children:[r&&e.jsx(H,{variant:"outline",onClick:r,children:"Cancel"}),e.jsxs(H,{onClick:x,disabled:a.isPending,children:[a.isPending&&e.jsx(is,{className:"h-4 w-4 mr-1 animate-spin"}),"Save preset"]})]})]})]})}function vrs(){const{data:s,isLoading:t}=gz(),[r,n]=S.useState(null);return e.jsx(Ss,{title:"Brand Kit",children:e.jsxs("div",{className:"container max-w-5xl py-6 md:py-8 space-y-6 px-4",children:[e.jsx(el,{children:e.jsx("title",{children:"Brand Kit | Marketing Studio"})}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs(Xn,{to:"/marketing-studio",className:"text-sm text-muted-foreground inline-flex items-center gap-1 hover:underline",children:[e.jsx(za,{className:"h-3 w-3"})," Back to Marketing Studio"]}),e.jsx("h1",{className:"text-2xl md:text-3xl font-bold tracking-tight mt-1",children:"Brand Kit"}),e.jsx("p",{className:"text-sm md:text-base text-muted-foreground",children:"Save your branding once — apply it across every Marketing Studio module."})]}),e.jsxs(H,{onClick:()=>n("new"),className:"w-full sm:w-auto",children:[e.jsx(Ys,{className:"h-4 w-4 mr-1"})," New preset"]})]}),t&&e.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading..."}),!t&&s&&s.length===0&&e.jsx(ke,{className:"border-dashed",children:e.jsxs(Oe,{className:"py-12 text-center space-y-3",children:[e.jsx("h3",{className:"font-semibold",children:"Create your first brand preset"}),e.jsx("p",{className:"text-sm text-muted-foreground max-w-md mx-auto",children:"We'll pre-fill from your profile. You can have multiple presets — Personal, Team, Luxury division — and switch between them."}),e.jsxs(H,{onClick:()=>n("new"),children:[e.jsx(Ys,{className:"h-4 w-4 mr-1"})," Create preset"]})]})}),e.jsx("div",{className:"grid gap-4 md:grid-cols-2",children:s==null?void 0:s.map(a=>e.jsxs(ke,{className:"overflow-hidden",children:[e.jsx("div",{className:"h-3",style:{background:`linear-gradient(90deg, ${a.brand_color}, ${a.accent_color})`}}),e.jsxs(Ot,{className:"pb-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(zt,{className:"text-lg flex items-center gap-2",children:[a.name,a.is_default&&e.jsxs(Xe,{variant:"secondary",className:"gap-1",children:[e.jsx(ya,{className:"h-3 w-3"})," Default"]})]}),e.jsx(H,{size:"sm",variant:"ghost",onClick:()=>n(a),children:e.jsx(ni,{className:"h-4 w-4"})})]}),e.jsx(Br,{children:a.display_name})]}),e.jsxs(Oe,{className:"text-sm text-muted-foreground space-y-1",children:[a.tagline&&e.jsxs("div",{className:"italic",children:['"',a.tagline,'"']}),a.phone&&e.jsx("div",{children:a.phone}),a.email&&e.jsx("div",{children:a.email})]})]},a.id))}),e.jsx(bs,{open:r!==null,onOpenChange:a=>!a&&n(null),children:e.jsxs(vs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto w-[calc(100vw-2rem)] sm:w-full",children:[e.jsx(Cs,{children:e.jsx(Ns,{children:r==="new"?"New brand preset":"Edit brand preset"})}),e.jsx(yrs,{preset:r==="new"?null:r,onSaved:()=>n(null),onCancel:()=>n(null)})]})})]})})}const Eke=[{id:"minimal-stripe",name:"Minimal Stripe",description:"Thin bottom strip with name + phone",appliesTo:["image","video"],position:"bottom",heightRatio:.085,background:"brand",fields:["headshot","name","phone"],circularHeadshot:!0,textColor:"auto"},{id:"full-footer",name:"Full Footer",description:"Generous footer with logo, tagline, and full contact",appliesTo:["image","video"],position:"bottom",heightRatio:.16,background:"brand",fields:["headshot","name","tagline","phone","email","logo"],circularHeadshot:!0,textColor:"auto"},{id:"corner-badge",name:"Corner Badge",description:"Subtle headshot + name in the bottom-right corner",appliesTo:["image","video"],position:"corner-br",heightRatio:.18,background:"gradient",fields:["headshot","name","phone"],circularHeadshot:!0,textColor:"light"},{id:"side-rail",name:"Side Rail",description:"Vertical strip on the right — great for stories",appliesTo:["image","video"],position:"side-right",heightRatio:.18,background:"brand",fields:["headshot","name","phone","logo"],circularHeadshot:!0,textColor:"auto"},{id:"letterbox",name:"Letterbox",description:"Cinematic top + bottom bars with logo and name",appliesTo:["image","video"],position:"letterbox",heightRatio:.09,background:"dark",fields:["headshot","name","phone","logo"],circularHeadshot:!0,textColor:"light"},{id:"top-banner",name:"Top Banner",description:"Bold banner across the top with logo and contact",appliesTo:["image","video"],position:"top",heightRatio:.1,background:"brand",fields:["logo","name","phone"],textColor:"auto"}],brs=s=>Eke.find(t=>t.id===s)??Eke[0];function _rs(s){if(!s)return"#ffffff";const t=s.replace("#","");if(t.length!==6)return"#ffffff";const r=parseInt(t.slice(0,2),16),n=parseInt(t.slice(2,4),16),a=parseInt(t.slice(4,6),16);return(r*299+n*587+a*114)/1e3>=150?"#0f172a":"#ffffff"}function wrs({value:s,onChange:t,mediaType:r}){const n=Eke.filter(a=>a.appliesTo.includes(r));return e.jsx("div",{className:"grid grid-cols-2 gap-2",children:n.map(a=>e.jsxs("button",{type:"button",onClick:()=>t(a.id),className:Ft("text-left rounded-lg border p-3 transition-all hover:border-primary/50",s===a.id&&"border-primary ring-2 ring-primary/20 bg-primary/5"),children:[e.jsx(jrs,{style:a}),e.jsx("div",{className:"mt-2 text-sm font-medium",children:a.name}),e.jsx("div",{className:"text-xs text-muted-foreground line-clamp-1",children:a.description})]},a.id))})}function jrs({style:s}){const t="#cbd5e1",r="#0f172a";return e.jsxs("div",{className:"aspect-video w-full rounded relative overflow-hidden",style:{background:t},children:[s.position==="bottom"&&e.jsx("div",{className:"absolute left-0 right-0 bottom-0",style:{height:`${s.heightRatio*100}%`,background:r}}),s.position==="top"&&e.jsx("div",{className:"absolute left-0 right-0 top-0",style:{height:`${s.heightRatio*100}%`,background:r}}),s.position==="corner-br"&&e.jsx("div",{className:"absolute bottom-2 right-2 w-1/3 h-1/3 rounded",style:{background:r,opacity:.85}}),s.position==="side-right"&&e.jsx("div",{className:"absolute top-0 bottom-0 right-0",style:{width:`${s.heightRatio*100}%`,background:r}}),s.position==="letterbox"&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"absolute left-0 right-0 top-0",style:{height:`${s.heightRatio*100}%`,background:r}}),e.jsx("div",{className:"absolute left-0 right-0 bottom-0",style:{height:`${s.heightRatio*100}%`,background:r}})]})]})}const Nrs=Math.PI/180;function krs(){return typeof window<"u"&&({}.toString.call(window)==="[object Window]"||{}.toString.call(window)==="[object global]")}const VT=typeof global<"u"?global:typeof window<"u"?window:typeof WorkerGlobalScope<"u"?self:{},Jn={_global:VT,version:"10.2.5",isBrowser:krs(),isUnminified:/param/.test((function(s){}).toString()),dblClickWindow:400,getAngle(s){return Jn.angleDeg?s*Nrs:s},enableTrace:!1,pointerEventsEnabled:!0,autoDrawEnabled:!0,hitOnDragEnabled:!1,capturePointerEventsEnabled:!1,_mouseListenClick:!1,_touchListenClick:!1,_pointerListenClick:!1,_mouseInDblClickWindow:!1,_touchInDblClickWindow:!1,_pointerInDblClickWindow:!1,_mouseDblClickPointerId:null,_touchDblClickPointerId:null,_pointerDblClickPointerId:null,_renderBackend:"web",legacyTextRendering:!1,pixelRatio:typeof window<"u"&&window.devicePixelRatio||1,dragDistance:3,angleDeg:!0,showWarnings:!0,dragButtons:[0,1],isDragging(){return Jn.DD.isDragging},isTransforming(){var s,t;return(t=(s=Jn.Transformer)===null||s===void 0?void 0:s.isTransforming())!==null&&t!==void 0?t:!1},isDragReady(){return!!Jn.DD.node},releaseCanvasOnDestroy:!0,document:VT.document,_injectGlobal(s){typeof VT.Konva<"u"&&console.error("Several Konva instances detected. It is not recommended to use multiple Konva instances in the same environment."),VT.Konva=s}},ju=s=>{Jn[s.prototype.getClassName()]=s};Jn._injectGlobal(Jn);const Srs=`Konva.js unsupported environment. Looks like you are trying to use Konva.js in Node.js environment. because "document" object is undefined. To use Konva.js in Node.js environment, you need to use the "canvas-backend" or "skia-backend" module. bash: npm install canvas js: import "konva/canvas-backend"; or bash: npm install skia-canvas js: import "konva/skia-backend"; `,sze=()=>{if(typeof document>"u")throw new Error(Srs)};class a0{constructor(t=[1,0,0,1,0,0]){this.dirty=!1,this.m=t&&t.slice()||[1,0,0,1,0,0]}reset(){this.m[0]=1,this.m[1]=0,this.m[2]=0,this.m[3]=1,this.m[4]=0,this.m[5]=0}copy(){return new a0(this.m)}copyInto(t){t.m[0]=this.m[0],t.m[1]=this.m[1],t.m[2]=this.m[2],t.m[3]=this.m[3],t.m[4]=this.m[4],t.m[5]=this.m[5]}point(t){const r=this.m;return{x:r[0]*t.x+r[2]*t.y+r[4],y:r[1]*t.x+r[3]*t.y+r[5]}}translate(t,r){return this.m[4]+=this.m[0]*t+this.m[2]*r,this.m[5]+=this.m[1]*t+this.m[3]*r,this}scale(t,r){return this.m[0]*=t,this.m[1]*=t,this.m[2]*=r,this.m[3]*=r,this}rotate(t){const r=Math.cos(t),n=Math.sin(t),a=this.m[0]*r+this.m[2]*n,i=this.m[1]*r+this.m[3]*n,l=this.m[0]*-n+this.m[2]*r,o=this.m[1]*-n+this.m[3]*r;return this.m[0]=a,this.m[1]=i,this.m[2]=l,this.m[3]=o,this}getTranslation(){return{x:this.m[4],y:this.m[5]}}skew(t,r){const n=this.m[0]+this.m[2]*r,a=this.m[1]+this.m[3]*r,i=this.m[2]+this.m[0]*t,l=this.m[3]+this.m[1]*t;return this.m[0]=n,this.m[1]=a,this.m[2]=i,this.m[3]=l,this}multiply(t){const r=this.m[0]*t.m[0]+this.m[2]*t.m[1],n=this.m[1]*t.m[0]+this.m[3]*t.m[1],a=this.m[0]*t.m[2]+this.m[2]*t.m[3],i=this.m[1]*t.m[2]+this.m[3]*t.m[3],l=this.m[0]*t.m[4]+this.m[2]*t.m[5]+this.m[4],o=this.m[1]*t.m[4]+this.m[3]*t.m[5]+this.m[5];return this.m[0]=r,this.m[1]=n,this.m[2]=a,this.m[3]=i,this.m[4]=l,this.m[5]=o,this}invert(){const t=1/(this.m[0]*this.m[3]-this.m[1]*this.m[2]),r=this.m[3]*t,n=-this.m[1]*t,a=-this.m[2]*t,i=this.m[0]*t,l=t*(this.m[2]*this.m[5]-this.m[3]*this.m[4]),o=t*(this.m[1]*this.m[4]-this.m[0]*this.m[5]);return this.m[0]=r,this.m[1]=n,this.m[2]=a,this.m[3]=i,this.m[4]=l,this.m[5]=o,this}getMatrix(){return this.m}decompose(){const t=this.m[0],r=this.m[1],n=this.m[2],a=this.m[3],i=this.m[4],l=this.m[5],o=t*a-r*n,c={x:i,y:l,rotation:0,scaleX:0,scaleY:0,skewX:0,skewY:0};if(t!=0||r!=0){const d=Math.sqrt(t*t+r*r);c.rotation=r>0?Math.acos(t/d):-Math.acos(t/d),c.scaleX=d,c.scaleY=o/d,c.skewX=(t*n+r*a)/o,c.skewY=0}else if(n!=0||a!=0){const d=Math.sqrt(n*n+a*a);c.rotation=Math.PI/2-(a>0?Math.acos(-n/d):-Math.acos(n/d)),c.scaleX=o/d,c.scaleY=d,c.skewX=0,c.skewY=(t*n+r*a)/o}return c.rotation=or._getRotation(c.rotation),c}}const Crs="[object Array]",Trs="[object Number]",Ers="[object String]",Ars="[object Boolean]",Mrs=Math.PI/180,Irs=180/Math.PI,RR="#",Prs="",Lrs="0",Drs="Konva warning: ",rze="Konva error: ",Rrs="rgb(",g_e={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,132,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,255,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,203],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[119,128,144],slategrey:[119,128,144],snow:[255,255,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],transparent:[255,255,255,0],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,5]},Ors=/rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)/;let hq=[],OR=null;const Frs=typeof requestAnimationFrame<"u"&&requestAnimationFrame||function(s){setTimeout(s,16)},or={_isElement(s){return!!(s&&s.nodeType==1)},_isFunction(s){return!!(s&&s.constructor&&s.call&&s.apply)},_isPlainObject(s){return!!s&&s.constructor===Object},_isArray(s){return Object.prototype.toString.call(s)===Crs},_isNumber(s){return Object.prototype.toString.call(s)===Trs&&!isNaN(s)&&isFinite(s)},_isString(s){return Object.prototype.toString.call(s)===Ers},_isBoolean(s){return Object.prototype.toString.call(s)===Ars},isObject(s){return s instanceof Object},isValidSelector(s){if(typeof s!="string")return!1;const t=s[0];return t==="#"||t==="."||t===t.toUpperCase()},_sign(s){return s===0||s>0?1:-1},requestAnimFrame(s){hq.push(s),hq.length===1&&Frs(function(){const t=hq;hq=[],t.forEach(function(r){r()})})},createCanvasElement(){sze();const s=document.createElement("canvas");try{s.style=s.style||{}}catch{}return s},createImageElement(){return sze(),document.createElement("img")},_isInDocument(s){for(;s=s.parentNode;)if(s==document)return!0;return!1},_urlToImage(s,t){const r=or.createImageElement();r.onload=function(){t(r)},r.src=s},_rgbToHex(s,t,r){return((1<<24)+(s<<16)+(t<<8)+r).toString(16).slice(1)},_hexToRgb(s){s=s.replace(RR,Prs);const t=parseInt(s,16);return{r:t>>16&255,g:t>>8&255,b:t&255}},getRandomColor(){let s=(Math.random()*16777215<<0).toString(16);for(;s.length<6;)s=Lrs+s;return RR+s},isCanvasFarblingActive(){if(OR!==null)return OR;if(typeof document>"u")return OR=!1,!1;const s=this.createCanvasElement();s.width=10,s.height=10;const t=s.getContext("2d",{willReadFrequently:!0});t.clearRect(0,0,10,10),t.fillStyle="#282828",t.fillRect(0,0,10,10);const r=t.getImageData(0,0,10,10).data;let n=!1;for(let a=0;a<100;a++)if(r[a*4]!==40||r[a*4+1]!==40||r[a*4+2]!==40||r[a*4+3]!==255){n=!0;break}return OR=n,this.releaseCanvas(s),OR},getHitColor(){const s=this.getRandomColor();return this.isCanvasFarblingActive()?this.getSnappedHexColor(s):s},getHitColorKey(s,t,r){return this.isCanvasFarblingActive()&&(s=Math.round(s/5)*5,t=Math.round(t/5)*5,r=Math.round(r/5)*5),RR+this._rgbToHex(s,t,r)},getSnappedHexColor(s){const t=this._hexToRgb(s);return RR+this._rgbToHex(Math.round(t.r/5)*5,Math.round(t.g/5)*5,Math.round(t.b/5)*5)},getRGB(s){let t;return s in g_e?(t=g_e[s],{r:t[0],g:t[1],b:t[2]}):s[0]===RR?this._hexToRgb(s.substring(1)):s.substr(0,4)===Rrs?(t=Ors.exec(s.replace(/ /g,"")),{r:parseInt(t[1],10),g:parseInt(t[2],10),b:parseInt(t[3],10)}):{r:0,g:0,b:0}},colorToRGBA(s){return s=s||"black",or._namedColorToRBA(s)||or._hex3ColorToRGBA(s)||or._hex4ColorToRGBA(s)||or._hex6ColorToRGBA(s)||or._hex8ColorToRGBA(s)||or._rgbColorToRGBA(s)||or._rgbaColorToRGBA(s)||or._hslColorToRGBA(s)},_namedColorToRBA(s){const t=g_e[s.toLowerCase()];return t?{r:t[0],g:t[1],b:t[2],a:1}:null},_rgbColorToRGBA(s){if(s.indexOf("rgb(")===0){s=s.match(/rgb\(([^)]+)\)/)[1];const t=s.split(/ *, */).map(Number);return{r:t[0],g:t[1],b:t[2],a:1}}},_rgbaColorToRGBA(s){if(s.indexOf("rgba(")===0){s=s.match(/rgba\(([^)]+)\)/)[1];const t=s.split(/ *, */).map((r,n)=>r.slice(-1)==="%"?n===3?parseInt(r)/100:parseInt(r)/100*255:Number(r));return{r:t[0],g:t[1],b:t[2],a:t[3]}}},_hex8ColorToRGBA(s){if(s[0]==="#"&&s.length===9)return{r:parseInt(s.slice(1,3),16),g:parseInt(s.slice(3,5),16),b:parseInt(s.slice(5,7),16),a:parseInt(s.slice(7,9),16)/255}},_hex6ColorToRGBA(s){if(s[0]==="#"&&s.length===7)return{r:parseInt(s.slice(1,3),16),g:parseInt(s.slice(3,5),16),b:parseInt(s.slice(5,7),16),a:1}},_hex4ColorToRGBA(s){if(s[0]==="#"&&s.length===5)return{r:parseInt(s[1]+s[1],16),g:parseInt(s[2]+s[2],16),b:parseInt(s[3]+s[3],16),a:parseInt(s[4]+s[4],16)/255}},_hex3ColorToRGBA(s){if(s[0]==="#"&&s.length===4)return{r:parseInt(s[1]+s[1],16),g:parseInt(s[2]+s[2],16),b:parseInt(s[3]+s[3],16),a:1}},_hslColorToRGBA(s){if(/hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/g.test(s)){const[t,...r]=/hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/g.exec(s),n=Number(r[0])/360,a=Number(r[1])/100,i=Number(r[2])/100;let l,o,c;if(a===0)return c=i*255,{r:Math.round(c),g:Math.round(c),b:Math.round(c),a:1};i<.5?l=i*(1+a):l=i+a-i*a;const d=2*i-l,h=[0,0,0];for(let m=0;m<3;m++)o=n+1/3*-(m-1),o<0&&o++,o>1&&o--,6*o<1?c=d+(l-d)*6*o:2*o<1?c=l:3*o<2?c=d+(l-d)*(2/3-o)*6:c=d,h[m]=c*255;return{r:Math.round(h[0]),g:Math.round(h[1]),b:Math.round(h[2]),a:1}}},haveIntersection(s,t){return!(t.x>s.x+s.width||t.x+t.widths.y+s.height||t.y+t.height1?(l=r,o=n,c=(r-a)*(r-a)+(n-i)*(n-i)):(l=s+h*(r-s),o=t+h*(n-t),c=(l-a)*(l-a)+(o-i)*(o-i))}return[l,o,c]},_getProjectionToLine(s,t,r){const n=or.cloneObject(s);let a=Number.MAX_VALUE;return t.forEach(function(i,l){if(!r&&l===t.length-1)return;const o=t[(l+1)%t.length],c=or._getProjectionToSegment(i.x,i.y,o.x,o.y,s.x,s.y),d=c[0],h=c[1],m=c[2];mt.length){const l=t;t=s,s=l}for(let l=0;l{t.width=0,t.height=0})},drawRoundedRectPath(s,t,r,n){let a=t<0?t:0,i=r<0?r:0;t=Math.abs(t),r=Math.abs(r);let l=0,o=0,c=0,d=0;typeof n=="number"?l=o=c=d=Math.min(n,t/2,r/2):(l=Math.min(n[0]||0,t/2,r/2),o=Math.min(n[1]||0,t/2,r/2),d=Math.min(n[2]||0,t/2,r/2),c=Math.min(n[3]||0,t/2,r/2)),s.moveTo(a+l,i),s.lineTo(a+t-o,i),s.arc(a+t-o,i+o,o,Math.PI*3/2,0,!1),s.lineTo(a+t,i+r-d),s.arc(a+t-d,i+r-d,d,0,Math.PI/2,!1),s.lineTo(a+c,i+r),s.arc(a+c,i+r-c,c,Math.PI/2,Math.PI,!1),s.lineTo(a,i+l),s.arc(a+l,i+l,l,Math.PI,Math.PI*3/2,!1)},drawRoundedPolygonPath(s,t,r,n,a){n=Math.abs(n);for(let i=0;itypeof h=="number"?Math.floor(h):h)),i+=zrs+d.join(nze)+$rs)):(i+=o.property,t||(i+=Grs+o.val)),i+=Vrs;return i}clearTrace(){this.traceArr=[]}_trace(t){let r=this.traceArr,n;r.push(t),n=r.length,n>=Krs&&r.shift()}reset(){const t=this.getCanvas().getPixelRatio();this.setTransform(1*t,0,0,1*t,0,0)}getCanvas(){return this.canvas}clear(t){const r=this.getCanvas();t?this.clearRect(t.x||0,t.y||0,t.width||0,t.height||0):this.clearRect(0,0,r.getWidth()/r.pixelRatio,r.getHeight()/r.pixelRatio)}_applyLineCap(t){const r=t.attrs.lineCap;r&&this.setAttr("lineCap",r)}_applyOpacity(t){const r=t.getAbsoluteOpacity();r!==1&&this.setAttr("globalAlpha",r)}_applyLineJoin(t){const r=t.attrs.lineJoin;r&&this.setAttr("lineJoin",r)}_applyMiterLimit(t){const r=t.attrs.miterLimit;r!=null&&this.setAttr("miterLimit",r)}setAttr(t,r){this._context[t]=r}arc(t,r,n,a,i,l){this._context.arc(t,r,n,a,i,l)}arcTo(t,r,n,a,i){this._context.arcTo(t,r,n,a,i)}beginPath(){this._context.beginPath()}bezierCurveTo(t,r,n,a,i,l){this._context.bezierCurveTo(t,r,n,a,i,l)}clearRect(t,r,n,a){this._context.clearRect(t,r,n,a)}clip(...t){this._context.clip.apply(this._context,t)}closePath(){this._context.closePath()}createImageData(t,r){const n=arguments;if(n.length===2)return this._context.createImageData(t,r);if(n.length===1)return this._context.createImageData(t)}createLinearGradient(t,r,n,a){return this._context.createLinearGradient(t,r,n,a)}createPattern(t,r){return this._context.createPattern(t,r)}createRadialGradient(t,r,n,a,i,l){return this._context.createRadialGradient(t,r,n,a,i,l)}drawImage(t,r,n,a,i,l,o,c,d){const h=arguments,m=this._context;h.length===3?m.drawImage(t,r,n):h.length===5?m.drawImage(t,r,n,a,i):h.length===9&&m.drawImage(t,r,n,a,i,l,o,c,d)}ellipse(t,r,n,a,i,l,o,c){this._context.ellipse(t,r,n,a,i,l,o,c)}isPointInPath(t,r,n,a){return n?this._context.isPointInPath(n,t,r,a):this._context.isPointInPath(t,r,a)}fill(...t){this._context.fill.apply(this._context,t)}fillRect(t,r,n,a){this._context.fillRect(t,r,n,a)}strokeRect(t,r,n,a){this._context.strokeRect(t,r,n,a)}fillText(t,r,n,a){a?this._context.fillText(t,r,n,a):this._context.fillText(t,r,n)}measureText(t){return this._context.measureText(t)}getImageData(t,r,n,a){return this._context.getImageData(t,r,n,a)}lineTo(t,r){this._context.lineTo(t,r)}moveTo(t,r){this._context.moveTo(t,r)}rect(t,r,n,a){this._context.rect(t,r,n,a)}roundRect(t,r,n,a,i){this._context.roundRect(t,r,n,a,i)}putImageData(t,r,n){this._context.putImageData(t,r,n)}quadraticCurveTo(t,r,n,a){this._context.quadraticCurveTo(t,r,n,a)}restore(){this._context.restore()}rotate(t){this._context.rotate(t)}save(){this._context.save()}scale(t,r){this._context.scale(t,r)}setLineDash(t){this._context.setLineDash?this._context.setLineDash(t):"mozDash"in this._context?this._context.mozDash=t:"webkitLineDash"in this._context&&(this._context.webkitLineDash=t)}getLineDash(){return this._context.getLineDash()}setTransform(t,r,n,a,i,l){this._context.setTransform(t,r,n,a,i,l)}stroke(t){t?this._context.stroke(t):this._context.stroke()}strokeText(t,r,n,a){this._context.strokeText(t,r,n,a)}transform(t,r,n,a,i,l){this._context.transform(t,r,n,a,i,l)}translate(t,r){this._context.translate(t,r)}_enableTrace(){let t=this,r=aze.length,n=this.setAttr,a,i;const l=function(o){let c=t[o],d;t[o]=function(){return i=Brs(Array.prototype.slice.call(arguments,0)),d=c.apply(t,arguments),t._trace({method:o,args:i}),d}};for(a=0;a{t.dragStatus==="dragging"&&(s=!0)}),s},justDragged:!1,get node(){let s;return Ll._dragElements.forEach(t=>{s=t.node}),s},_dragElements:new Map,_drag(s){const t=[];Ll._dragElements.forEach((r,n)=>{const{node:a}=r,i=a.getStage();i.setPointersPositions(s),r.pointerId===void 0&&(r.pointerId=or._getFirstPointerId(s));const l=i._changedPointerPositions.find(o=>o.id===r.pointerId);if(l){if(r.dragStatus!=="dragging"){const o=a.dragDistance();if(Math.max(Math.abs(l.x-r.startPointerPos.x),Math.abs(l.y-r.startPointerPos.y)){r.getStage()&&r.fire("dragmove",{type:"dragmove",target:r,evt:s},!0)})},_endDragBefore(s){const t=[];Ll._dragElements.forEach(r=>{const{node:n}=r,a=n.getStage();if(s&&a.setPointersPositions(s),!a._changedPointerPositions.find(o=>o.id===r.pointerId))return;(r.dragStatus==="dragging"||r.dragStatus==="stopped")&&(Ll.justDragged=!0,Jn._mouseListenClick=!1,Jn._touchListenClick=!1,Jn._pointerListenClick=!1,r.dragStatus="stopped");const l=r.node.getLayer()||r.node instanceof Jn.Stage&&r.node;l&&t.indexOf(l)===-1&&t.push(l)}),t.forEach(r=>{r.draw()})},_endDragAfter(s){Ll._dragElements.forEach((t,r)=>{t.dragStatus==="stopped"&&t.node.fire("dragend",{type:"dragend",target:t.node,evt:s},!0),t.dragStatus!=="dragging"&&Ll._dragElements.delete(r)})}};Jn.isBrowser&&(window.addEventListener("mouseup",Ll._endDragBefore,!0),window.addEventListener("touchend",Ll._endDragBefore,!0),window.addEventListener("touchcancel",Ll._endDragBefore,!0),window.addEventListener("mousemove",Ll._drag),window.addEventListener("touchmove",Ll._drag),window.addEventListener("mouseup",Ll._endDragAfter,!1),window.addEventListener("touchend",Ll._endDragAfter,!1),window.addEventListener("touchcancel",Ll._endDragAfter,!1));function YS(s){return or._isString(s)?'"'+s+'"':Object.prototype.toString.call(s)==="[object Number]"||or._isBoolean(s)?s:Object.prototype.toString.call(s)}function Hdt(s){return s>255?255:s<0?0:Math.round(s)}function Hn(){if(Jn.isUnminified)return function(s,t){return or._isNumber(s)||or.warn(YS(s)+' is a not valid value for "'+t+'" attribute. The value should be a number.'),s}}function wxe(s){if(Jn.isUnminified)return function(t,r){let n=or._isNumber(t),a=or._isArray(t)&&t.length==s;return!n&&!a&&or.warn(YS(t)+' is a not valid value for "'+r+'" attribute. The value should be a number or Array('+s+")"),t}}function CEe(){if(Jn.isUnminified)return function(s,t){return or._isNumber(s)||s==="auto"||or.warn(YS(s)+' is a not valid value for "'+t+'" attribute. The value should be a number or "auto".'),s}}function HA(){if(Jn.isUnminified)return function(s,t){return or._isString(s)||or.warn(YS(s)+' is a not valid value for "'+t+'" attribute. The value should be a string.'),s}}function Gdt(){if(Jn.isUnminified)return function(s,t){const r=or._isString(s),n=Object.prototype.toString.call(s)==="[object CanvasGradient]"||s&&s.addColorStop;return r||n||or.warn(YS(s)+' is a not valid value for "'+t+'" attribute. The value should be a string or a native gradient.'),s}}function Qrs(){if(Jn.isUnminified)return function(s,t){const r=Int8Array?Object.getPrototypeOf(Int8Array):null;return r&&s instanceof r||(or._isArray(s)?s.forEach(function(n){or._isNumber(n)||or.warn('"'+t+'" attribute has non numeric element '+n+". Make sure that all elements are numbers.")}):or.warn(YS(s)+' is a not valid value for "'+t+'" attribute. The value should be a array of numbers.')),s}}function O1(){if(Jn.isUnminified)return function(s,t){return s===!0||s===!1||or.warn(YS(s)+' is a not valid value for "'+t+'" attribute. The value should be a boolean.'),s}}function Jrs(s){if(Jn.isUnminified)return function(t,r){return t==null||or.isObject(t)||or.warn(YS(t)+' is a not valid value for "'+r+'" attribute. The value should be an object with properties '+s),t}}const FR="get",BR="set",ps={addGetterSetter(s,t,r,n,a){ps.addGetter(s,t,r),ps.addSetter(s,t,n,a),ps.addOverloadedGetterSetter(s,t)},addGetter(s,t,r){const n=FR+or._capitalize(t);s.prototype[n]=s.prototype[n]||function(){const a=this.attrs[t];return a===void 0?r:a}},addSetter(s,t,r,n){const a=BR+or._capitalize(t);s.prototype[a]||ps.overWriteSetter(s,t,r,n)},overWriteSetter(s,t,r,n){const a=BR+or._capitalize(t);s.prototype[a]=function(i){return r&&i!==void 0&&i!==null&&(i=r.call(this,i,t)),this._setAttr(t,i),n&&n.call(this),this}},addComponentsGetterSetter(s,t,r,n,a){const i=r.length,l=or._capitalize,o=FR+l(t),c=BR+l(t);s.prototype[o]=function(){const h={};for(let m=0;m{this._setAttr(t+l(p),void 0)}),this._fireChangeEvent(t,m,h),a&&a.call(this),this},ps.addOverloadedGetterSetter(s,t)},addOverloadedGetterSetter(s,t){const r=or._capitalize(t),n=BR+r,a=FR+r;s.prototype[t]=function(){return arguments.length?(this[n](arguments[0]),this):this[a]()}},addDeprecatedGetterSetter(s,t,r,n){or.error("Adding deprecated "+t);const a=FR+or._capitalize(t),i=t+" property is deprecated and will be removed soon. Look at Konva change log for more information.";s.prototype[a]=function(){or.error(i);const l=this.attrs[t];return l===void 0?r:l},ps.addSetter(s,t,n,function(){or.error(i)}),ps.addOverloadedGetterSetter(s,t)},backCompat(s,t){or.each(t,function(r,n){const a=s.prototype[n],i=FR+or._capitalize(r),l=BR+or._capitalize(r);function o(){a.apply(this,arguments),or.error('"'+r+'" method is deprecated and will be removed soon. Use ""'+n+'" instead.')}s.prototype[r]=o,s.prototype[i]=o,s.prototype[l]=o})},afterSetFilter(){this._filterUpToDate=!1}};function ens(s){const t=/(\w+)\(([^)]+)\)/g;let r;for(;(r=t.exec(s))!==null;){const[,n,a]=r;switch(n){case"blur":{const i=parseFloat(a.replace("px",""));return function(l){this.blurRadius(i*.5);const o=Jn.Filters;o&&o.Blur&&o.Blur.call(this,l)}}case"brightness":{const i=a.includes("%")?parseFloat(a)/100:parseFloat(a);return function(l){this.brightness(i);const o=Jn.Filters;o&&o.Brightness&&o.Brightness.call(this,l)}}case"contrast":{const i=parseFloat(a);return function(l){const o=100*(Math.sqrt(i)-1);this.contrast(o);const c=Jn.Filters;c&&c.Contrast&&c.Contrast.call(this,l)}}case"grayscale":return function(i){const l=Jn.Filters;l&&l.Grayscale&&l.Grayscale.call(this,i)};case"sepia":return function(i){const l=Jn.Filters;l&&l.Sepia&&l.Sepia.call(this,i)};case"invert":return function(i){const l=Jn.Filters;l&&l.Invert&&l.Invert.call(this,i)};default:or.warn(`CSS filter "${n}" is not supported in fallback mode. Consider using function filters for better compatibility.`);break}}return()=>{}}const Iue="absoluteOpacity",oze="allEventListeners",u2="absoluteTransform",lze="absoluteScale",sC="canvas",tns="Change",sns="children",rns="konva",Ake="listening",nns="mouseenter",ans="mouseleave",ins="pointerenter",ons="pointerleave",lns="touchenter",cns="touchleave",cze="set",dze="Shape",Pue=" ",uze="stage",RN="transform",dns="Stage",Mke="visible",uns=["xChange.konva","yChange.konva","scaleXChange.konva","scaleYChange.konva","skewXChange.konva","skewYChange.konva","rotationChange.konva","offsetXChange.konva","offsetYChange.konva","transformsEnabledChange.konva"].join(Pue);let hns=1,aa=class wO{constructor(t){this._id=hns++,this.eventListeners={},this.attrs={},this.index=0,this._allEventListeners=null,this.parent=null,this._cache=new Map,this._attachedDepsListeners=new Map,this._lastPos=null,this._batchingTransformChange=!1,this._needClearTransformCache=!1,this._filterUpToDate=!1,this._isUnderCache=!1,this._dragEventId=null,this._shouldFireChangeEvents=!1,this.setAttrs(t),this._shouldFireChangeEvents=!0}hasChildren(){return!1}_clearCache(t){(t===RN||t===u2)&&this._cache.get(t)?this._cache.get(t).dirty=!0:t?this._cache.delete(t):this._cache.clear()}_getCache(t,r){let n=this._cache.get(t);return(n===void 0||(t===RN||t===u2)&&n.dirty===!0)&&(n=r.call(this),this._cache.set(t,n)),n}_calculate(t,r,n){if(!this._attachedDepsListeners.get(t)){const a=r.map(i=>i+"Change.konva").join(Pue);this.on(a,()=>{this._clearCache(t)}),this._attachedDepsListeners.set(t,!0)}return this._getCache(t,n)}_getCanvasCache(){return this._cache.get(sC)}_clearSelfAndDescendantCache(t){this._clearCache(t),t===u2&&this.fire("absoluteTransformChange")}clearCache(){if(this._cache.has(sC)){const{scene:t,filter:r,hit:n}=this._cache.get(sC);or.releaseCanvas(t._canvas,r._canvas,n._canvas),this._cache.delete(sC)}return this._clearSelfAndDescendantCache(),this._requestDraw(),this}cache(t){const r=t||{};let n={};(r.x===void 0||r.y===void 0||r.width===void 0||r.height===void 0)&&(n=this.getClientRect({skipTransform:!0,relativeTo:this.getParent()||void 0}));let a=Math.ceil(r.width||n.width),i=Math.ceil(r.height||n.height),l=r.pixelRatio,o=r.x===void 0?Math.floor(n.x):r.x,c=r.y===void 0?Math.floor(n.y):r.y,d=r.offset||0,h=r.drawBorder||!1,m=r.hitCanvasPixelRatio||1;if(!a||!i){or.error("Can not cache the node. Width or height of the node equals 0. Caching is skipped.");return}const p=Math.abs(Math.round(n.x)-o)>.5?1:0,x=Math.abs(Math.round(n.y)-c)>.5?1:0;a+=d*2+p,i+=d*2+x,o-=d,c-=d;const y=new nk({pixelRatio:l,width:a,height:i}),_=new nk({pixelRatio:l,width:0,height:0,willReadFrequently:!0}),b=new SEe({pixelRatio:m,width:a,height:i}),j=y.getContext(),k=b.getContext(),T=new nk({width:y.width/y.pixelRatio+Math.abs(o),height:y.height/y.pixelRatio+Math.abs(c),pixelRatio:y.pixelRatio}),E=T.getContext();return b.isCache=!0,y.isCache=!0,this._cache.delete(sC),this._filterUpToDate=!1,r.imageSmoothingEnabled===!1&&(y.getContext()._context.imageSmoothingEnabled=!1,_.getContext()._context.imageSmoothingEnabled=!1),j.save(),k.save(),E.save(),j.translate(-o,-c),k.translate(-o,-c),E.translate(-o,-c),T.x=o,T.y=c,this._isUnderCache=!0,this._clearSelfAndDescendantCache(Iue),this._clearSelfAndDescendantCache(lze),this.drawScene(y,this,T),this.drawHit(b,this),this._isUnderCache=!1,j.restore(),k.restore(),h&&(j.save(),j.beginPath(),j.rect(0,0,a,i),j.closePath(),j.setAttr("strokeStyle","red"),j.setAttr("lineWidth",5),j.stroke(),j.restore()),or.releaseCanvas(T._canvas),this._cache.set(sC,{scene:y,filter:_,hit:b,x:o,y:c}),this._requestDraw(),this}isCached(){return this._cache.has(sC)}getClientRect(t){throw new Error('abstract "getClientRect" method call')}_transformedRect(t,r){const n=[{x:t.x,y:t.y},{x:t.x+t.width,y:t.y},{x:t.x+t.width,y:t.y+t.height},{x:t.x,y:t.y+t.height}];let a=1/0,i=1/0,l=-1/0,o=-1/0;const c=this.getAbsoluteTransform(r);return n.forEach(function(d){const h=c.point(d);a===void 0&&(a=l=h.x,i=o=h.y),a=Math.min(a,h.x),i=Math.min(i,h.y),l=Math.max(l,h.x),o=Math.max(o,h.y)}),{x:a,y:i,width:l-a,height:o-i}}_drawCachedSceneCanvas(t){t.save(),t._applyOpacity(this),t._applyGlobalCompositeOperation(this);const r=this._getCanvasCache();t.translate(r.x,r.y);const n=this._getCachedSceneCanvas(),a=n.pixelRatio;t.drawImage(n._canvas,0,0,n.width/a,n.height/a),t.restore()}_drawCachedHitCanvas(t){const r=this._getCanvasCache(),n=r.hit;t.save(),t.translate(r.x,r.y),t.drawImage(n._canvas,0,0,n.width/n.pixelRatio,n.height/n.pixelRatio),t.restore()}_getCachedSceneCanvas(){let t=this.filters(),r=this._getCanvasCache(),n=r.scene,a=r.filter,i=a.getContext(),l,o,c,d;if(!t||t.length===0)return n;if(this._filterUpToDate)return a;let h=!0;for(let p=0;p{this.isAncestorOf(t.node)&&Ll._dragElements.delete(r)}),this._remove(),this}_clearCaches(){this._clearSelfAndDescendantCache(u2),this._clearSelfAndDescendantCache(Iue),this._clearSelfAndDescendantCache(lze),this._clearSelfAndDescendantCache(uze),this._clearSelfAndDescendantCache(Mke),this._clearSelfAndDescendantCache(Ake)}_remove(){this._clearCaches();const t=this.getParent();t&&t.children&&(t.children.splice(this.index,1),t._setChildrenIndices(),this.parent=null)}destroy(){return this.remove(),this.clearCache(),this}getAttr(t){const r="get"+or._capitalize(t);return or._isFunction(this[r])?this[r]():this.attrs[t]}getAncestors(){let t=this.getParent(),r=[];for(;t;)r.push(t),t=t.getParent();return r}getAttrs(){return this.attrs||{}}setAttrs(t){return this._batchTransformChanges(()=>{let r,n;if(!t)return this;for(r in t)r!==sns&&(n=cze+or._capitalize(r),or._isFunction(this[n])?this[n](t[r]):this._setAttr(r,t[r]))}),this}isListening(){return this._getCache(Ake,this._isListening)}_isListening(t){if(!this.listening())return!1;const n=this.getParent();return n&&n!==t&&this!==t?n._isListening(t):!0}isVisible(){return this._getCache(Mke,this._isVisible)}_isVisible(t){if(!this.visible())return!1;const n=this.getParent();return n&&n!==t&&this!==t?n._isVisible(t):!0}shouldDrawHit(t,r=!1){if(t)return this._isVisible(t)&&this._isListening(t);const n=this.getLayer();let a=!1;Ll._dragElements.forEach(l=>{l.dragStatus==="dragging"&&(l.node.nodeType==="Stage"||l.node.getLayer()===n)&&(a=!0)});const i=!r&&!Jn.hitOnDragEnabled&&(a||Jn.isTransforming());return this.isListening()&&this.isVisible()&&!i}show(){return this.visible(!0),this}hide(){return this.visible(!1),this}getZIndex(){return this.index||0}getAbsoluteZIndex(){let t=this.getDepth(),r=this,n=0,a,i,l,o;function c(h){for(a=[],i=h.length,l=0;l0&&a[0].getDepth()<=t&&c(a)}const d=this.getStage();return r.nodeType!==dns&&d&&c(d.getChildren()),n}getDepth(){let t=0,r=this.parent;for(;r;)t++,r=r.parent;return t}_batchTransformChanges(t){this._batchingTransformChange=!0,t(),this._batchingTransformChange=!1,this._needClearTransformCache&&(this._clearCache(RN),this._clearSelfAndDescendantCache(u2)),this._needClearTransformCache=!1}setPosition(t){return this._batchTransformChanges(()=>{this.x(t.x),this.y(t.y)}),this}getPosition(){return{x:this.x(),y:this.y()}}getRelativePointerPosition(){const t=this.getStage();if(!t)return null;const r=t.getPointerPosition();if(!r)return null;const n=this.getAbsoluteTransform().copy();return n.invert(),n.point(r)}getAbsolutePosition(t){let r=!1,n=this.parent;for(;n;){if(n.isCached()){r=!0;break}n=n.parent}r&&!t&&(t=!0);const a=this.getAbsoluteTransform(t).getMatrix(),i=new a0,l=this.offset();return i.m=a.slice(),i.translate(l.x,l.y),i.getTranslation()}setAbsolutePosition(t){const{x:r,y:n,...a}=this._clearTransform();this.attrs.x=r,this.attrs.y=n,this._clearCache(RN);const i=this._getAbsoluteTransform().copy();return i.invert(),i.translate(t.x,t.y),t={x:this.attrs.x+i.getTranslation().x,y:this.attrs.y+i.getTranslation().y},this._setTransform(a),this.setPosition({x:t.x,y:t.y}),this._clearCache(RN),this._clearSelfAndDescendantCache(u2),this}_setTransform(t){let r;for(r in t)this.attrs[r]=t[r]}_clearTransform(){const t={x:this.x(),y:this.y(),rotation:this.rotation(),scaleX:this.scaleX(),scaleY:this.scaleY(),offsetX:this.offsetX(),offsetY:this.offsetY(),skewX:this.skewX(),skewY:this.skewY()};return this.attrs.x=0,this.attrs.y=0,this.attrs.rotation=0,this.attrs.scaleX=1,this.attrs.scaleY=1,this.attrs.offsetX=0,this.attrs.offsetY=0,this.attrs.skewX=0,this.attrs.skewY=0,t}move(t){let r=t.x,n=t.y,a=this.x(),i=this.y();return r!==void 0&&(a+=r),n!==void 0&&(i+=n),this.setPosition({x:a,y:i}),this}_eachAncestorReverse(t,r){let n=[],a=this.getParent(),i,l;if(!(r&&r._id===this._id)){for(n.unshift(this);a&&(!r||a._id!==r._id);)n.unshift(a),a=a.parent;for(i=n.length,l=0;l0?(this.parent.children.splice(t,1),this.parent.children.splice(t-1,0,this),this.parent._setChildrenIndices(),!0):!1}moveToBottom(){if(!this.parent)return or.warn("Node has no parent. moveToBottom function is ignored."),!1;const t=this.index;return t>0?(this.parent.children.splice(t,1),this.parent.children.unshift(this),this.parent._setChildrenIndices(),!0):!1}setZIndex(t){if(!this.parent)return or.warn("Node has no parent. zIndex parameter is ignored."),this;(t<0||t>=this.parent.children.length)&&or.warn("Unexpected value "+t+" for zIndex property. zIndex is just index of a node in children of its parent. Expected value is from 0 to "+(this.parent.children.length-1)+".");const r=this.index;return this.parent.children.splice(r,1),this.parent.children.splice(t,0,this),this.parent._setChildrenIndices(),this}getAbsoluteOpacity(){return this._getCache(Iue,this._getAbsoluteOpacity)}_getAbsoluteOpacity(){let t=this.opacity();const r=this.getParent();return r&&!r._isUnderCache&&(t*=r.getAbsoluteOpacity()),t}moveTo(t){return this.getParent()!==t&&(this._remove(),t.add(this)),this}toObject(){let t=this.getAttrs(),r,n,a,i,l;const o={attrs:{},className:this.getClassName()};for(r in t)n=t[r],l=or.isObject(n)&&!or._isPlainObject(n)&&!or._isArray(n),!l&&(a=typeof this[r]=="function"&&this[r],delete t[r],i=a?a.call(this):null,t[r]=n,i!==n&&(o.attrs[r]=n));return or._prepareToStringify(o)}toJSON(){return JSON.stringify(this.toObject())}getParent(){return this.parent}findAncestors(t,r,n){const a=[];r&&this._isMatch(t)&&a.push(this);let i=this.parent;for(;i;){if(i===n)return a;i._isMatch(t)&&a.push(i),i=i.parent}return a}isAncestorOf(t){return!1}findAncestor(t,r,n){return this.findAncestors(t,r,n)[0]}_isMatch(t){if(!t)return!1;if(typeof t=="function")return t(this);let r=t.replace(/ /g,"").split(","),n=r.length,a,i;for(a=0;a{try{const a=t==null?void 0:t.callback;a&&delete t.callback,or._urlToImage(this.toDataURL(t),function(i){r(i),a==null||a(i)})}catch(a){n(a)}})}toBlob(t){return new Promise((r,n)=>{try{const a=t==null?void 0:t.callback;a&&delete t.callback,this.toCanvas(t).toBlob(i=>{r(i),a==null||a(i)},t==null?void 0:t.mimeType,t==null?void 0:t.quality)}catch(a){n(a)}})}setSize(t){return this.width(t.width),this.height(t.height),this}getSize(){return{width:this.width(),height:this.height()}}getClassName(){return this.className||this.nodeType}getType(){return this.nodeType}getDragDistance(){return this.attrs.dragDistance!==void 0?this.attrs.dragDistance:this.parent?this.parent.getDragDistance():Jn.dragDistance}_off(t,r,n){let a=this.eventListeners[t],i,l,o;for(i=0;i=0)||this.isDragging())return;let a=!1;Ll._dragElements.forEach(i=>{this.isAncestorOf(i.node)&&(a=!0)}),a||this._createDragElement(t)})}_dragChange(){if(this.attrs.draggable)this._listenDrag();else{if(this._dragCleanup(),!this.getStage())return;const r=Ll._dragElements.get(this._id),n=r&&r.dragStatus==="dragging",a=r&&r.dragStatus==="ready";n?this.stopDrag():a&&Ll._dragElements.delete(this._id)}}_dragCleanup(){this.off("mousedown.konva"),this.off("touchstart.konva")}isClientRectOnScreen(t={x:0,y:0}){const r=this.getStage();if(!r)return!1;const n={x:-t.x,y:-t.y,width:r.width()+2*t.x,height:r.height()+2*t.y};return or.haveIntersection(n,this.getClientRect())}static create(t,r){return or._isString(t)&&(t=JSON.parse(t)),this._createNode(t,r)}static _createNode(t,r){let n=wO.prototype.getClassName.call(t),a=t.children,i,l,o;r&&(t.attrs.container=r),Jn[n]||(or.warn('Can not find a node with class name "'+n+'". Fallback to "Shape".'),n="Shape");const c=Jn[n];if(i=new c(t.attrs),a)for(l=a.length,o=0;o0}removeChildren(){return this.getChildren().forEach(t=>{t.parent=null,t.index=0,t.remove()}),this.children=[],this._requestDraw(),this}destroyChildren(){return this.getChildren().forEach(t=>{t.parent=null,t.index=0,t.destroy()}),this.children=[],this._requestDraw(),this}add(...t){if(t.length===0)return this;if(t.length>1){for(let n=0;n0?r[0]:void 0}_generalFind(t,r){const n=[];return this._descendants(a=>{const i=a._isMatch(t);return i&&n.push(a),!!(i&&r)}),n}_descendants(t){let r=!1;const n=this.getChildren();for(const a of n){if(r=t(a),r)return!0;if(a.hasChildren()&&(r=a._descendants(t),r))return!0}return!1}toObject(){const t=aa.prototype.toObject.call(this);return t.children=[],this.getChildren().forEach(r=>{t.children.push(r.toObject())}),t}isAncestorOf(t){let r=t.getParent();for(;r;){if(r._id===this._id)return!0;r=r.getParent()}return!1}clone(t){const r=aa.prototype.clone.call(this,t);return this.getChildren().forEach(function(n){r.add(n.clone())}),r}getAllIntersections(t){const r=[];return this.find("Shape").forEach(n=>{n.isVisible()&&n.intersects(t)&&r.push(n)}),r}_clearSelfAndDescendantCache(t){var r;super._clearSelfAndDescendantCache(t),!this.isCached()&&((r=this.children)===null||r===void 0||r.forEach(function(n){n._clearSelfAndDescendantCache(t)}))}_setChildrenIndices(){var t;(t=this.children)===null||t===void 0||t.forEach(function(r,n){r.index=n}),this._requestDraw()}drawScene(t,r,n){const a=this.getLayer(),i=t||a&&a.getCanvas(),l=i&&i.getContext(),o=this._getCanvasCache(),c=o&&o.scene,d=i&&i.isCache;if(!this.isVisible()&&!d)return this;if(c){l.save();const h=this.getAbsoluteTransform(r).getMatrix();l.transform(h[0],h[1],h[2],h[3],h[4],h[5]),this._drawCachedSceneCanvas(l),l.restore()}else this._drawChildren("drawScene",i,r,n);return this}drawHit(t,r){if(!this.shouldDrawHit(r))return this;const n=this.getLayer(),a=t||n&&n.hitCanvas,i=a&&a.getContext(),l=this._getCanvasCache();if(l&&l.hit){i.save();const c=this.getAbsoluteTransform(r).getMatrix();i.transform(c[0],c[1],c[2],c[3],c[4],c[5]),this._drawCachedHitCanvas(i),i.restore()}else this._drawChildren("drawHit",a,r);return this}_drawChildren(t,r,n,a){var i;const l=r&&r.getContext(),o=this.clipWidth(),c=this.clipHeight(),d=this.clipFunc(),h=typeof o=="number"&&typeof c=="number"||d,m=n===this;if(h){l.save();const x=this.getAbsoluteTransform(n);let y=x.getMatrix();l.transform(y[0],y[1],y[2],y[3],y[4],y[5]),l.beginPath();let _;if(d)_=d.call(this,l,this);else{const b=this.clipX(),j=this.clipY();l.rect(b||0,j||0,o,c)}l.clip.apply(l,_),y=x.copy().invert().getMatrix(),l.transform(y[0],y[1],y[2],y[3],y[4],y[5])}const p=!m&&this.globalCompositeOperation()!=="source-over"&&t==="drawScene";p&&(l.save(),l._applyGlobalCompositeOperation(this)),(i=this.children)===null||i===void 0||i.forEach(function(x){x[t](r,n,a)}),p&&l.restore(),h&&l.restore()}getClientRect(t={}){var r;const n=t.skipTransform,a=t.relativeTo;let i,l,o,c,d={x:1/0,y:1/0,width:0,height:0};const h=this;(r=this.children)===null||r===void 0||r.forEach(function(x){if(!x.visible())return;const y=x.getClientRect({relativeTo:h,skipShadow:t.skipShadow,skipStroke:t.skipStroke});y.width===0&&y.height===0||(i===void 0?(i=y.x,l=y.y,o=y.x+y.width,c=y.y+y.height):(i=Math.min(i,y.x),l=Math.min(l,y.y),o=Math.max(o,y.x+y.width),c=Math.max(c,y.y+y.height)))});const m=this.find("Shape");let p=!1;for(let x=0;xs.indexOf("pointer")>=0?"pointer":s.indexOf("touch")>=0?"touch":"mouse",v6=s=>{const t=CO(s);if(t==="pointer")return Jn.pointerEventsEnabled&&y_e.pointer;if(t==="touch")return y_e.touch;if(t==="mouse")return y_e.mouse};function mze(s={}){return(s.clipFunc||s.clipWidth||s.clipHeight)&&or.warn("Stage does not support clipping. Please use clip for Layers or Groups."),s}const vns="Pointer position is missing and not registered by the stage. Looks like it is outside of the stage container. You can set it manually from event: stage.setPointersPositions(event);",p7=[];let jxe=class extends x0{constructor(t){super(mze(t)),this._pointerPositions=[],this._changedPointerPositions=[],this._buildDOM(),this._bindContentEvents(),p7.push(this),this.on("widthChange.konva heightChange.konva",this._resizeDOM),this.on("visibleChange.konva",this._checkVisibility),this.on("clipWidthChange.konva clipHeightChange.konva clipFuncChange.konva",()=>{mze(this.attrs)}),this._checkVisibility()}_validateAdd(t){const r=t.getType()==="Layer",n=t.getType()==="FastLayer";r||n||or.throw("You may only add layers to the stage.")}_checkVisibility(){if(!this.content)return;const t=this.visible()?"":"none";this.content.style.display=t}setContainer(t){if(typeof t===fns){let r;if(t.charAt(0)==="."){const n=t.slice(1);t=document.getElementsByClassName(n)[0]}else t.charAt(0)!=="#"?r=t:r=t.slice(1),t=document.getElementById(r);if(!t)throw"Can not find container in document with id "+r}return this._setAttr("container",t),this.content&&(this.content.parentElement&&this.content.parentElement.removeChild(this.content),t.appendChild(this.content)),this}shouldDrawHit(){return!0}clear(){const t=this.children,r=t.length;for(let n=0;n-1&&p7.splice(r,1),or.releaseCanvas(this.bufferCanvas._canvas,this.bufferHitCanvas._canvas),this}getPointerPosition(){const t=this._pointerPositions[0]||this._changedPointerPositions[0];return t?{x:t.x,y:t.y}:(or.warn(vns),null)}_getPointerById(t){return this._pointerPositions.find(r=>r.id===t)}getPointersPositions(){return this._pointerPositions}getStage(){return this}getContent(){return this.content}_toKonvaCanvas(t){t={...t},t.x=t.x||0,t.y=t.y||0,t.width=t.width||this.width(),t.height=t.height||this.height();const r=new nk({width:t.width,height:t.height,pixelRatio:t.pixelRatio||1}),n=r.getContext()._context,a=this.children;return(t.x||t.y)&&n.translate(-1*t.x,-1*t.y),a.forEach(function(i){if(!i.isVisible())return;const l=i._toKonvaCanvas(t);n.drawImage(l._canvas,t.x,t.y,l.getWidth()/l.getPixelRatio(),l.getHeight()/l.getPixelRatio())}),r}getIntersection(t){if(!t)return null;const r=this.children,n=r.length,a=n-1;for(let i=a;i>=0;i--){const l=r[i].getIntersection(t);if(l)return l}return null}_resizeDOM(){const t=this.width(),r=this.height();this.content&&(this.content.style.width=t+hze,this.content.style.height=r+hze),this.bufferCanvas.setSize(t,r),this.bufferHitCanvas.setSize(t,r),this.children.forEach(n=>{n.setSize({width:t,height:r}),n.draw()})}add(t,...r){if(arguments.length>1){for(let a=0;axns&&or.warn("The stage has "+n+" layers. Recommended maximum number of layers is 3-5. Adding more layers into the stage may drop the performance. Rethink your tree structure, you can use Konva.Group."),t.setSize({width:this.width(),height:this.height()}),t.draw(),Jn.isBrowser&&this.content.appendChild(t.canvas._canvas),this}getParent(){return null}getLayer(){return null}hasPointerCapture(t){return Kdt(t,this)}setPointerCapture(t){Ydt(t,this)}releaseCapture(t){f7(t)}getLayers(){return this.children}_bindContentEvents(){Jn.isBrowser&&yns.forEach(([t,r])=>{this.content.addEventListener(t,n=>{this[r](n)},{passive:!1})})}_pointerenter(t){this.setPointersPositions(t);const r=v6(t.type);r&&this._fire(r.pointerenter,{evt:t,target:this,currentTarget:this})}_pointerover(t){this.setPointersPositions(t);const r=v6(t.type);r&&this._fire(r.pointerover,{evt:t,target:this,currentTarget:this})}_getTargetShape(t){let r=this[t+"targetShape"];return r&&!r.getStage()&&(r=null),r}_pointerleave(t){const r=v6(t.type),n=CO(t.type);if(!r)return;this.setPointersPositions(t);const a=this._getTargetShape(n),i=!(Jn.isDragging()||Jn.isTransforming())||Jn.hitOnDragEnabled;a&&i?(a._fireAndBubble(r.pointerout,{evt:t}),a._fireAndBubble(r.pointerleave,{evt:t}),this._fire(r.pointerleave,{evt:t,target:this,currentTarget:this}),this[n+"targetShape"]=null):i&&(this._fire(r.pointerleave,{evt:t,target:this,currentTarget:this}),this._fire(r.pointerout,{evt:t,target:this,currentTarget:this})),this.pointerPos=null,this._pointerPositions=[]}_pointerdown(t){const r=v6(t.type),n=CO(t.type);if(!r)return;this.setPointersPositions(t);let a=!1;this._changedPointerPositions.forEach(i=>{const l=this.getIntersection(i);if(Ll.justDragged=!1,Jn["_"+n+"ListenClick"]=!0,!l||!l.isListening()){this[n+"ClickStartShape"]=void 0;return}Jn.capturePointerEventsEnabled&&l.setPointerCapture(i.id),this[n+"ClickStartShape"]=l,l._fireAndBubble(r.pointerdown,{evt:t,pointerId:i.id}),a=!0;const o=t.type.indexOf("touch")>=0;l.preventDefault()&&t.cancelable&&o&&t.preventDefault()}),a||this._fire(r.pointerdown,{evt:t,target:this,currentTarget:this,pointerId:this._pointerPositions[0].id})}_pointermove(t){const r=v6(t.type),n=CO(t.type);if(!r)return;const a=t.type.indexOf("touch")>=0||t.pointerType==="touch";if(Jn.isDragging()&&Ll.node.preventDefault()&&t.cancelable&&a&&t.preventDefault(),this.setPointersPositions(t),!(!(Jn.isDragging()||Jn.isTransforming())||Jn.hitOnDragEnabled))return;const l={};let o=!1;const c=this._getTargetShape(n);this._changedPointerPositions.forEach(d=>{const h=x_e(d.id)||this.getIntersection(d),m=d.id,p={evt:t,pointerId:m},x=c!==h;if(x&&c&&(c._fireAndBubble(r.pointerout,{...p},h),c._fireAndBubble(r.pointerleave,{...p},h)),h){if(l[h._id])return;l[h._id]=!0}h&&h.isListening()?(o=!0,x&&(h._fireAndBubble(r.pointerover,{...p},c),h._fireAndBubble(r.pointerenter,{...p},c),this[n+"targetShape"]=h),h._fireAndBubble(r.pointermove,{...p})):c&&(this._fire(r.pointerover,{evt:t,target:this,currentTarget:this,pointerId:m}),this[n+"targetShape"]=null)}),o||this._fire(r.pointermove,{evt:t,target:this,currentTarget:this,pointerId:this._changedPointerPositions[0].id})}_pointerup(t){const r=v6(t.type),n=CO(t.type);if(!r)return;this.setPointersPositions(t);const a=this[n+"ClickStartShape"],i=this[n+"ClickEndShape"],l={};let o=!1;this._changedPointerPositions.forEach(c=>{const d=x_e(c.id)||this.getIntersection(c);if(d){if(d.releaseCapture(c.id),l[d._id])return;l[d._id]=!0}const h=c.id,m={evt:t,pointerId:h};let p=!1;Jn["_"+n+"InDblClickWindow"]?(p=!0,clearTimeout(this[n+"DblTimeout"])):Ll.justDragged||(Jn["_"+n+"InDblClickWindow"]=!0,clearTimeout(this[n+"DblTimeout"])),this[n+"DblTimeout"]=setTimeout(function(){Jn["_"+n+"InDblClickWindow"]=!1},Jn.dblClickWindow),d&&d.isListening()?(o=!0,this[n+"ClickEndShape"]=d,d._fireAndBubble(r.pointerup,{...m}),Jn["_"+n+"ListenClick"]&&a&&a===d&&(d._fireAndBubble(r.pointerclick,{...m}),p&&i&&i===d&&d._fireAndBubble(r.pointerdblclick,{...m}))):(this[n+"ClickEndShape"]=null,o||(this._fire(r.pointerup,{evt:t,target:this,currentTarget:this,pointerId:this._changedPointerPositions[0].id}),o=!0),Jn["_"+n+"ListenClick"]&&this._fire(r.pointerclick,{evt:t,target:this,currentTarget:this,pointerId:h}),p&&this._fire(r.pointerdblclick,{evt:t,target:this,currentTarget:this,pointerId:h}))}),o||this._fire(r.pointerup,{evt:t,target:this,currentTarget:this,pointerId:this._changedPointerPositions[0].id}),Jn["_"+n+"ListenClick"]=!1,t.cancelable&&n!=="touch"&&n!=="pointer"&&t.preventDefault()}_contextmenu(t){this.setPointersPositions(t);const r=this.getIntersection(this.getPointerPosition());r&&r.isListening()?r._fireAndBubble(Ike,{evt:t}):this._fire(Ike,{evt:t,target:this,currentTarget:this})}_wheel(t){this.setPointersPositions(t);const r=this.getIntersection(this.getPointerPosition());r&&r.isListening()?r._fireAndBubble(Pke,{evt:t}):this._fire(Pke,{evt:t,target:this,currentTarget:this})}_pointercancel(t){this.setPointersPositions(t);const r=x_e(t.pointerId)||this.getIntersection(this.getPointerPosition());r&&r._fireAndBubble(mI,TEe(t)),f7(t.pointerId)}_lostpointercapture(t){f7(t.pointerId)}setPointersPositions(t){const r=this._getContentPosition();let n=null,a=null;t=t||window.event,t.touches!==void 0?(this._pointerPositions=[],this._changedPointerPositions=[],Array.prototype.forEach.call(t.touches,i=>{this._pointerPositions.push({id:i.identifier,x:(i.clientX-r.left)/r.scaleX,y:(i.clientY-r.top)/r.scaleY})}),Array.prototype.forEach.call(t.changedTouches||t.touches,i=>{this._changedPointerPositions.push({id:i.identifier,x:(i.clientX-r.left)/r.scaleX,y:(i.clientY-r.top)/r.scaleY})})):(n=(t.clientX-r.left)/r.scaleX,a=(t.clientY-r.top)/r.scaleY,this.pointerPos={x:n,y:a},this._pointerPositions=[{x:n,y:a,id:or._getFirstPointerId(t)}],this._changedPointerPositions=[{x:n,y:a,id:or._getFirstPointerId(t)}])}_setPointerPosition(t){or.warn('Method _setPointerPosition is deprecated. Use "stage.setPointersPositions(event)" instead.'),this.setPointersPositions(t)}_getContentPosition(){if(!this.content||!this.content.getBoundingClientRect)return{top:0,left:0,scaleX:1,scaleY:1};const t=this.content.getBoundingClientRect();return{top:t.top,left:t.left,scaleX:t.width/this.content.clientWidth||1,scaleY:t.height/this.content.clientHeight||1}}_buildDOM(){if(this.bufferCanvas=new nk({width:this.width(),height:this.height()}),this.bufferHitCanvas=new SEe({pixelRatio:1,width:this.width(),height:this.height()}),!Jn.isBrowser)return;const t=this.container();if(!t)throw"Stage has no container. A container is required.";t.innerHTML="",this.content=document.createElement("div"),this.content.style.position="relative",this.content.style.userSelect="none",this.content.className="konvajs-content",this.content.setAttribute("role","presentation"),t.appendChild(this.content),this._resizeDOM()}cache(){return or.warn("Cache function is not allowed for stage. You may use cache only for layers, groups and shapes."),this}clearCache(){return this}batchDraw(){return this.getChildren().forEach(function(t){t.batchDraw()}),this}};jxe.prototype.nodeType=mns;ju(jxe);ps.addGetterSetter(jxe,"container");Jn.isBrowser&&document.addEventListener("visibilitychange",()=>{p7.forEach(s=>{s.batchDraw()})});const iut="hasShadow",out="shadowRGBA",lut="patternImage",cut="linearGradient",dut="radialGradient";let yq;function v_e(){return yq||(yq=or.createCanvasElement().getContext("2d"),yq)}const g7={};function bns(s){const t=this.attrs.fillRule;t?s.fill(t):s.fill()}function _ns(s){s.stroke()}function wns(s){const t=this.attrs.fillRule;t?s.fill(t):s.fill()}function jns(s){s.stroke()}function Nns(){this._clearCache(iut)}function kns(){this._clearCache(out)}function Sns(){this._clearCache(lut)}function Cns(){this._clearCache(cut)}function Tns(){this._clearCache(dut)}let On=class extends aa{constructor(t){super(t);let r,n=0;for(;r=or.getHitColor(),!(r&&!(r in g7));)if(n++,n>=1e4){or.warn("Failed to find a unique color key for a shape. Konva may work incorrectly. Most likely your browser is using canvas farbling. Consider disabling it."),r=or.getRandomColor();break}this.colorKey=r,g7[r]=this}getContext(){return or.warn("shape.getContext() method is deprecated. Please do not use it."),this.getLayer().getContext()}getCanvas(){return or.warn("shape.getCanvas() method is deprecated. Please do not use it."),this.getLayer().getCanvas()}getSceneFunc(){return this.attrs.sceneFunc||this._sceneFunc}getHitFunc(){return this.attrs.hitFunc||this._hitFunc}hasShadow(){return this._getCache(iut,this._hasShadow)}_hasShadow(){return this.shadowEnabled()&&this.shadowOpacity()!==0&&!!(this.shadowColor()||this.shadowBlur()||this.shadowOffsetX()||this.shadowOffsetY())}_getFillPattern(){return this._getCache(lut,this.__getFillPattern)}__getFillPattern(){if(this.fillPatternImage()){const r=v_e().createPattern(this.fillPatternImage(),this.fillPatternRepeat()||"repeat");if(r&&r.setTransform){const n=new a0;n.translate(this.fillPatternX(),this.fillPatternY()),n.rotate(Jn.getAngle(this.fillPatternRotation())),n.scale(this.fillPatternScaleX(),this.fillPatternScaleY()),n.translate(-1*this.fillPatternOffsetX(),-1*this.fillPatternOffsetY());const a=n.getMatrix(),i=typeof DOMMatrix>"u"?{a:a[0],b:a[1],c:a[2],d:a[3],e:a[4],f:a[5]}:new DOMMatrix(a);r.setTransform(i)}return r}}_getLinearGradient(){return this._getCache(cut,this.__getLinearGradient)}__getLinearGradient(){const t=this.fillLinearGradientColorStops();if(t){const r=v_e(),n=this.fillLinearGradientStartPoint(),a=this.fillLinearGradientEndPoint(),i=r.createLinearGradient(n.x,n.y,a.x,a.y);for(let l=0;lthis.fillEnabled()&&!!(this.fill()||this.fillPatternImage()||this.fillLinearGradientColorStops()||this.fillRadialGradientColorStops()))}hasStroke(){return this._calculate("hasStroke",["strokeEnabled","strokeWidth","stroke","strokeLinearGradientColorStops"],()=>this.strokeEnabled()&&this.strokeWidth()&&!!(this.stroke()||this.strokeLinearGradientColorStops()))}hasHitStroke(){const t=this.hitStrokeWidth();return t==="auto"?this.hasStroke():this.strokeEnabled()&&!!t}intersects(t){const r=this.getStage();if(!r)return!1;const n=r.bufferHitCanvas;return n.getContext().clear(),this.drawHit(n,void 0,!0),n.context.getImageData(Math.round(t.x),Math.round(t.y),1,1).data[3]>0}destroy(){return aa.prototype.destroy.call(this),delete g7[this.colorKey],delete this.colorKey,this}_useBufferCanvas(t){var r;if(!((r=this.attrs.perfectDrawEnabled)!==null&&r!==void 0?r:!0))return!1;const a=t||this.hasFill(),i=this.hasStroke(),l=this.getAbsoluteOpacity()!==1;if(a&&i&&l)return!0;const o=this.hasShadow(),c=this.shadowForStrokeEnabled();return!!(a&&i&&o&&c)}setStrokeHitEnabled(t){or.warn("strokeHitEnabled property is deprecated. Please use hitStrokeWidth instead."),t?this.hitStrokeWidth("auto"):this.hitStrokeWidth(0)}getStrokeHitEnabled(){return this.hitStrokeWidth()!==0}getSelfRect(){const t=this.size();return{x:this._centroid?-t.width/2:0,y:this._centroid?-t.height/2:0,width:t.width,height:t.height}}getClientRect(t={}){let r=!1,n=this.getParent();for(;n;){if(n.isCached()){r=!0;break}n=n.getParent()}const a=t.skipTransform,i=t.relativeTo||r&&this.getStage()||void 0,l=this.getSelfRect(),c=!t.skipStroke&&this.hasStroke()&&this.strokeWidth()||0,d=l.width+c,h=l.height+c,m=!t.skipShadow&&this.hasShadow(),p=m?this.shadowOffsetX():0,x=m?this.shadowOffsetY():0,y=d+Math.abs(p),_=h+Math.abs(x),b=m&&this.shadowBlur()||0,j=y+b*2,k=_+b*2,T={width:j,height:k,x:-(c/2+b)+Math.min(p,0)+l.x,y:-(c/2+b)+Math.min(x,0)+l.y};return a?T:this._transformedRect(T,i)}drawScene(t,r,n){const a=this.getLayer(),i=t||a.getCanvas(),l=i.getContext(),o=this._getCanvasCache(),c=this.getSceneFunc(),d=this.hasShadow();let h;const m=!1,p=r===this;if(!this.isVisible()&&!p)return this;if(o){l.save();const x=this.getAbsoluteTransform(r).getMatrix();return l.transform(x[0],x[1],x[2],x[3],x[4],x[5]),this._drawCachedSceneCanvas(l),l.restore(),this}if(!c)return this;if(l.save(),this._useBufferCanvas()&&!m){h=this.getStage();const x=n||h.bufferCanvas,y=x.getContext();n?(y.save(),y.setTransform(1,0,0,1,0,0),y.clearRect(0,0,x.width,x.height),y.restore()):y.clear(),y.save(),y._applyLineJoin(this),y._applyMiterLimit(this);const _=this.getAbsoluteTransform(r).getMatrix();y.transform(_[0],_[1],_[2],_[3],_[4],_[5]),c.call(this,y,this),y.restore();const b=x.pixelRatio;d&&l._applyShadow(this),p||(l._applyOpacity(this),l._applyGlobalCompositeOperation(this)),l.drawImage(x._canvas,x.x||0,x.y||0,x.width/b,x.height/b)}else{if(l._applyLineJoin(this),l._applyMiterLimit(this),!p){const x=this.getAbsoluteTransform(r).getMatrix();l.transform(x[0],x[1],x[2],x[3],x[4],x[5]),l._applyOpacity(this),l._applyGlobalCompositeOperation(this)}d&&l._applyShadow(this),c.call(this,l,this)}return l.restore(),this}drawHit(t,r,n=!1){if(!this.shouldDrawHit(r,n))return this;const a=this.getLayer(),i=t||a.hitCanvas,l=i&&i.getContext(),o=this.hitFunc()||this.sceneFunc(),c=this._getCanvasCache(),d=c&&c.hit;if(this.colorKey||or.warn("Looks like your canvas has a destroyed shape in it. Do not reuse shape after you destroyed it. If you want to reuse shape you should call remove() instead of destroy()"),d){l.save();const m=this.getAbsoluteTransform(r).getMatrix();return l.transform(m[0],m[1],m[2],m[3],m[4],m[5]),this._drawCachedHitCanvas(l),l.restore(),this}if(!o)return this;if(l.save(),l._applyLineJoin(this),l._applyMiterLimit(this),!(this===r)){const m=this.getAbsoluteTransform(r).getMatrix();l.transform(m[0],m[1],m[2],m[3],m[4],m[5])}return o.call(this,l,this),l.restore(),this}drawHitFromCache(t=0){const r=this._getCanvasCache(),n=this._getCachedSceneCanvas(),a=r.hit,i=a.getContext(),l=a.getWidth(),o=a.getHeight();i.clear(),i.drawImage(n._canvas,0,0,l,o);try{const c=i.getImageData(0,0,l,o),d=c.data,h=d.length,m=or._hexToRgb(this.colorKey);for(let p=0;pt?(d[p]=m.r,d[p+1]=m.g,d[p+2]=m.b,d[p+3]=255):d[p+3]=0;i.putImageData(c,0,0)}catch(c){or.error("Unable to draw hit graph from cached scene canvas. "+c.message)}return this}hasPointerCapture(t){return Kdt(t,this)}setPointerCapture(t){Ydt(t,this)}releaseCapture(t){f7(t)}};On.prototype._fillFunc=bns;On.prototype._strokeFunc=_ns;On.prototype._fillFuncHit=wns;On.prototype._strokeFuncHit=jns;On.prototype._centroid=!1;On.prototype.nodeType="Shape";ju(On);On.prototype.eventListeners={};On.prototype.on("shadowColorChange.konva shadowBlurChange.konva shadowOffsetChange.konva shadowOpacityChange.konva shadowEnabledChange.konva",Nns);On.prototype.on("shadowColorChange.konva shadowOpacityChange.konva shadowEnabledChange.konva",kns);On.prototype.on("fillPriorityChange.konva fillPatternImageChange.konva fillPatternRepeatChange.konva fillPatternScaleXChange.konva fillPatternScaleYChange.konva fillPatternOffsetXChange.konva fillPatternOffsetYChange.konva fillPatternXChange.konva fillPatternYChange.konva fillPatternRotationChange.konva",Sns);On.prototype.on("fillPriorityChange.konva fillLinearGradientColorStopsChange.konva fillLinearGradientStartPointXChange.konva fillLinearGradientStartPointYChange.konva fillLinearGradientEndPointXChange.konva fillLinearGradientEndPointYChange.konva",Cns);On.prototype.on("fillPriorityChange.konva fillRadialGradientColorStopsChange.konva fillRadialGradientStartPointXChange.konva fillRadialGradientStartPointYChange.konva fillRadialGradientEndPointXChange.konva fillRadialGradientEndPointYChange.konva fillRadialGradientStartRadiusChange.konva fillRadialGradientEndRadiusChange.konva",Tns);ps.addGetterSetter(On,"stroke",void 0,Gdt());ps.addGetterSetter(On,"strokeWidth",2,Hn());ps.addGetterSetter(On,"fillAfterStrokeEnabled",!1);ps.addGetterSetter(On,"hitStrokeWidth","auto",CEe());ps.addGetterSetter(On,"strokeHitEnabled",!0,O1());ps.addGetterSetter(On,"perfectDrawEnabled",!0,O1());ps.addGetterSetter(On,"shadowForStrokeEnabled",!0,O1());ps.addGetterSetter(On,"lineJoin");ps.addGetterSetter(On,"lineCap");ps.addGetterSetter(On,"miterLimit");ps.addGetterSetter(On,"sceneFunc");ps.addGetterSetter(On,"hitFunc");ps.addGetterSetter(On,"dash");ps.addGetterSetter(On,"dashOffset",0,Hn());ps.addGetterSetter(On,"shadowColor",void 0,HA());ps.addGetterSetter(On,"shadowBlur",0,Hn());ps.addGetterSetter(On,"shadowOpacity",1,Hn());ps.addComponentsGetterSetter(On,"shadowOffset",["x","y"]);ps.addGetterSetter(On,"shadowOffsetX",0,Hn());ps.addGetterSetter(On,"shadowOffsetY",0,Hn());ps.addGetterSetter(On,"fillPatternImage");ps.addGetterSetter(On,"fill",void 0,Gdt());ps.addGetterSetter(On,"fillPatternX",0,Hn());ps.addGetterSetter(On,"fillPatternY",0,Hn());ps.addGetterSetter(On,"fillLinearGradientColorStops");ps.addGetterSetter(On,"strokeLinearGradientColorStops");ps.addGetterSetter(On,"fillRadialGradientStartRadius",0);ps.addGetterSetter(On,"fillRadialGradientEndRadius",0);ps.addGetterSetter(On,"fillRadialGradientColorStops");ps.addGetterSetter(On,"fillPatternRepeat","repeat");ps.addGetterSetter(On,"fillEnabled",!0);ps.addGetterSetter(On,"strokeEnabled",!0);ps.addGetterSetter(On,"shadowEnabled",!0);ps.addGetterSetter(On,"dashEnabled",!0);ps.addGetterSetter(On,"strokeScaleEnabled",!0);ps.addGetterSetter(On,"fillPriority","color");ps.addComponentsGetterSetter(On,"fillPatternOffset",["x","y"]);ps.addGetterSetter(On,"fillPatternOffsetX",0,Hn());ps.addGetterSetter(On,"fillPatternOffsetY",0,Hn());ps.addComponentsGetterSetter(On,"fillPatternScale",["x","y"]);ps.addGetterSetter(On,"fillPatternScaleX",1,Hn());ps.addGetterSetter(On,"fillPatternScaleY",1,Hn());ps.addComponentsGetterSetter(On,"fillLinearGradientStartPoint",["x","y"]);ps.addComponentsGetterSetter(On,"strokeLinearGradientStartPoint",["x","y"]);ps.addGetterSetter(On,"fillLinearGradientStartPointX",0);ps.addGetterSetter(On,"strokeLinearGradientStartPointX",0);ps.addGetterSetter(On,"fillLinearGradientStartPointY",0);ps.addGetterSetter(On,"strokeLinearGradientStartPointY",0);ps.addComponentsGetterSetter(On,"fillLinearGradientEndPoint",["x","y"]);ps.addComponentsGetterSetter(On,"strokeLinearGradientEndPoint",["x","y"]);ps.addGetterSetter(On,"fillLinearGradientEndPointX",0);ps.addGetterSetter(On,"strokeLinearGradientEndPointX",0);ps.addGetterSetter(On,"fillLinearGradientEndPointY",0);ps.addGetterSetter(On,"strokeLinearGradientEndPointY",0);ps.addComponentsGetterSetter(On,"fillRadialGradientStartPoint",["x","y"]);ps.addGetterSetter(On,"fillRadialGradientStartPointX",0);ps.addGetterSetter(On,"fillRadialGradientStartPointY",0);ps.addComponentsGetterSetter(On,"fillRadialGradientEndPoint",["x","y"]);ps.addGetterSetter(On,"fillRadialGradientEndPointX",0);ps.addGetterSetter(On,"fillRadialGradientEndPointY",0);ps.addGetterSetter(On,"fillPatternRotation",0);ps.addGetterSetter(On,"fillRule",void 0,HA());ps.backCompat(On,{dashArray:"dash",getDashArray:"getDash",setDashArray:"getDash",drawFunc:"sceneFunc",getDrawFunc:"getSceneFunc",setDrawFunc:"setSceneFunc",drawHitFunc:"hitFunc",getDrawHitFunc:"getHitFunc",setDrawHitFunc:"setHitFunc"});const Ens="beforeDraw",Ans="draw",uut=[{x:0,y:0},{x:-1,y:-1},{x:1,y:-1},{x:1,y:1},{x:-1,y:1}],Mns=uut.length;let GA=class extends x0{constructor(t){super(t),this.canvas=new nk,this.hitCanvas=new SEe({pixelRatio:1}),this._waitingForDraw=!1,this.on("visibleChange.konva",this._checkVisibility),this._checkVisibility(),this.on("imageSmoothingEnabledChange.konva",this._setSmoothEnabled),this._setSmoothEnabled()}createPNGStream(){return this.canvas._canvas.createPNGStream()}getCanvas(){return this.canvas}getNativeCanvasElement(){return this.canvas._canvas}getHitCanvas(){return this.hitCanvas}getContext(){return this.getCanvas().getContext()}clear(t){return this.getContext().clear(t),this.getHitCanvas().getContext().clear(t),this}setZIndex(t){super.setZIndex(t);const r=this.getStage();return r&&r.content&&(r.content.removeChild(this.getNativeCanvasElement()),t{this.draw(),this._waitingForDraw=!1})),this}getIntersection(t){if(!this.isListening()||!this.isVisible())return null;let r=1,n=!1;for(;;){for(let a=0;a0)return{antialiased:!0};return{}}drawScene(t,r,n){const a=this.getLayer(),i=t||a&&a.getCanvas();return this._fire(Ens,{node:this}),this.clearBeforeDraw()&&i.getContext().clear(),x0.prototype.drawScene.call(this,i,r,n),this._fire(Ans,{node:this}),this}drawHit(t,r){const n=this.getLayer(),a=t||n&&n.hitCanvas;return n&&n.clearBeforeDraw()&&n.getHitCanvas().getContext().clear(),x0.prototype.drawHit.call(this,a,r),this}enableHitGraph(){return this.hitGraphEnabled(!0),this}disableHitGraph(){return this.hitGraphEnabled(!1),this}setHitGraphEnabled(t){or.warn("hitGraphEnabled method is deprecated. Please use layer.listening() instead."),this.listening(t)}getHitGraphEnabled(t){return or.warn("hitGraphEnabled method is deprecated. Please use layer.listening() instead."),this.listening()}toggleHitCanvas(){if(!this.parent||!this.parent.content)return;const t=this.parent;!!this.hitCanvas._canvas.parentNode?t.content.removeChild(this.hitCanvas._canvas):t.content.appendChild(this.hitCanvas._canvas)}destroy(){return or.releaseCanvas(this.getNativeCanvasElement(),this.getHitCanvas()._canvas),super.destroy()}};GA.prototype.nodeType="Layer";ju(GA);ps.addGetterSetter(GA,"imageSmoothingEnabled",!0);ps.addGetterSetter(GA,"clearBeforeDraw",!0);ps.addGetterSetter(GA,"hitGraphEnabled",!0,O1());class EEe extends GA{constructor(t){super(t),this.listening(!1),or.warn('Konva.Fast layer is deprecated. Please use "new Konva.Layer({ listening: false })" instead.')}}EEe.prototype.nodeType="FastLayer";ju(EEe);let hL=class extends x0{_validateAdd(t){const r=t.getType();r!=="Group"&&r!=="Shape"&&or.throw("You may only add groups and shapes to groups.")}};hL.prototype.nodeType="Group";ju(hL);const b_e=function(){return VT.performance&&VT.performance.now?function(){return VT.performance.now()}:function(){return new Date().getTime()}}();class Py{constructor(t,r){this.id=Py.animIdCounter++,this.frame={time:0,timeDiff:0,lastTime:b_e(),frameRate:0},this.func=t,this.setLayers(r)}setLayers(t){let r=[];return t&&(r=Array.isArray(t)?t:[t]),this.layers=r,this}getLayers(){return this.layers}addLayer(t){const r=this.layers,n=r.length;for(let a=0;athis.duration?this.yoyo?(this._time=this.duration,this.reverse()):this.finish():t<0?this.yoyo?(this._time=0,this.play()):this.reset():(this._time=t,this.update())}getTime(){return this._time}setPosition(t){this.prevPos=this._pos,this.propFunc(t),this._pos=t}getPosition(t){return t===void 0&&(t=this._time),this.func(t,this.begin,this._change,this.duration)}play(){this.state=fze,this._startTime=this.getTimer()-this._time,this.onEnterFrame(),this.fire("onPlay")}reverse(){this.state=pze,this._time=this.duration-this._time,this._startTime=this.getTimer()-this._time,this.onEnterFrame(),this.fire("onReverse")}seek(t){this.pause(),this._time=t,this.update(),this.fire("onSeek")}reset(){this.pause(),this._time=0,this.update(),this.fire("onReset")}finish(){this.pause(),this._time=this.duration,this.update(),this.fire("onFinish")}update(){this.setPosition(this.getPosition(this._time)),this.fire("onUpdate")}onEnterFrame(){const t=this.getTimer()-this._startTime;this.state===fze?this.setTime(t):this.state===pze&&this.setTime(this.duration-t)}pause(){this.state=Pns,this.fire("onPause")}getTimer(){return new Date().getTime()}}class Jc{constructor(t){const r=this,n=t.node,a=n._id,i=t.easing||x7.Linear,l=!!t.yoyo;let o,c;typeof t.duration>"u"?o=.3:t.duration===0?o=.001:o=t.duration,this.node=n,this._id=Lns++;const d=n.getLayer()||(n instanceof Jn.Stage?n.getLayers():null);d||or.error("Tween constructor have `node` that is not in a layer. Please add node into layer first."),this.anim=new Py(function(){r.tween.onEnterFrame()},d),this.tween=new Dns(c,function(h){r._tweenFunc(h)},i,0,1,o*1e3,l),this._addListeners(),Jc.attrs[a]||(Jc.attrs[a]={}),Jc.attrs[a][this._id]||(Jc.attrs[a][this._id]={}),Jc.tweens[a]||(Jc.tweens[a]={});for(c in t)Ins[c]===void 0&&this._addAttr(c,t[c]);this.reset(),this.onFinish=t.onFinish,this.onReset=t.onReset,this.onUpdate=t.onUpdate}_addAttr(t,r){const n=this.node,a=n._id;let i,l,o,c,d;const h=Jc.tweens[a][t];h&&delete Jc.attrs[a][h][t];let m=n.getAttr(t);if(or._isArray(r))if(i=[],l=Math.max(r.length,m.length),t==="points"&&r.length!==m.length&&(r.length>m.length?(c=m,m=or._prepareArrayForTween(m,r,n.closed())):(o=r,r=or._prepareArrayForTween(r,m,n.closed()))),t.indexOf("fill")===0)for(let p=0;p{this.anim.start()},this.tween.onReverse=()=>{this.anim.start()},this.tween.onPause=()=>{this.anim.stop()},this.tween.onFinish=()=>{const t=this.node,r=Jc.attrs[t._id][this._id];r.points&&r.points.trueEnd&&t.setAttr("points",r.points.trueEnd),this.onFinish&&this.onFinish.call(this)},this.tween.onReset=()=>{const t=this.node,r=Jc.attrs[t._id][this._id];r.points&&r.points.trueStart&&t.points(r.points.trueStart),this.onReset&&this.onReset()},this.tween.onUpdate=()=>{this.onUpdate&&this.onUpdate.call(this)}}play(){return this.tween.play(),this}reverse(){return this.tween.reverse(),this}reset(){return this.tween.reset(),this}seek(t){return this.tween.seek(t*1e3),this}pause(){return this.tween.pause(),this}finish(){return this.tween.finish(),this}destroy(){const t=this.node._id,r=this._id,n=Jc.tweens[t];this.pause(),this.anim&&this.anim.stop();for(const a in n)delete Jc.tweens[t][a];delete Jc.attrs[t][r],Jc.tweens[t]&&(Object.keys(Jc.tweens[t]).length===0&&delete Jc.tweens[t],Object.keys(Jc.attrs[t]).length===0&&delete Jc.attrs[t])}}Jc.attrs={};Jc.tweens={};aa.prototype.to=function(s){const t=s.onFinish;s.node=this,s.onFinish=function(){this.destroy(),t&&t()},new Jc(s).play()};const x7={BackEaseIn(s,t,r,n){return r*(s/=n)*s*((1.70158+1)*s-1.70158)+t},BackEaseOut(s,t,r,n){return r*((s=s/n-1)*s*((1.70158+1)*s+1.70158)+1)+t},BackEaseInOut(s,t,r,n){let a=1.70158;return(s/=n/2)<1?r/2*(s*s*(((a*=1.525)+1)*s-a))+t:r/2*((s-=2)*s*(((a*=1.525)+1)*s+a)+2)+t},ElasticEaseIn(s,t,r,n,a,i){let l=0;return s===0?t:(s/=n)===1?t+r:(i||(i=n*.3),!a||a0?t:r),h=l*r,m=o*(o>0?t:r),p=c*(c>0?r:t);return{x:d,y:n?-1*p:m,width:h-d,height:p-m}}}_j.prototype._centroid=!0;_j.prototype.className="Arc";_j.prototype._attrsAffectingSize=["innerRadius","outerRadius","angle","clockwise"];ju(_j);ps.addGetterSetter(_j,"innerRadius",0,Hn());ps.addGetterSetter(_j,"outerRadius",0,Hn());ps.addGetterSetter(_j,"angle",0,Hn());ps.addGetterSetter(_j,"clockwise",!1,O1());function Lke(s,t,r,n,a,i,l){const o=Math.sqrt(Math.pow(r-s,2)+Math.pow(n-t,2)),c=Math.sqrt(Math.pow(a-r,2)+Math.pow(i-n,2)),d=l*o/(o+c),h=l*c/(o+c),m=r-d*(a-s),p=n-d*(i-t),x=r+h*(a-s),y=n+h*(i-t);return[m,p,x,y]}function xze(s,t){const r=s.length,n=[];for(let a=2;a=0){const c=Math.sqrt(o);r.push((-i+c)/(2*a)),r.push((-i-c)/(2*a))}}}return r.filter(n=>n>0&&n<1).flatMap(n=>t.map(a=>{const i=1-n;return i*i*i*a[0]+3*i*i*n*a[1]+3*i*n*n*a[2]+n*n*n*a[3]}))}let wj=class extends On{constructor(t){super(t),this.on("pointsChange.konva tensionChange.konva closedChange.konva bezierChange.konva",function(){this._clearCache("tensionPoints")})}_sceneFunc(t){const r=this.points(),n=r.length,a=this.tension(),i=this.closed(),l=this.bezier();if(!n)return;let o=0;if(t.beginPath(),t.moveTo(r[0],r[1]),a!==0&&n>4){const c=this.getTensionPoints(),d=c.length;for(o=i?0:4,i||t.quadraticCurveTo(c[0],c[1],c[2],c[3]);o{let n,a;const l=r/2;n=0;for(let o=0;o<20;o++)a=l*Ons[20][o]+l,n+=Fns[20][o]*zns(s,t,a);return l*n},vze=(s,t,r)=>{r===void 0&&(r=1);const n=s[0]-2*s[1]+s[2],a=t[0]-2*t[1]+t[2],i=2*s[1]-2*s[0],l=2*t[1]-2*t[0],o=4*(n*n+a*a),c=4*(n*i+a*l),d=i*i+l*l;if(o===0)return r*Math.sqrt(Math.pow(s[2]-s[0],2)+Math.pow(t[2]-t[0],2));const h=c/(2*o),m=d/o,p=r+h,x=m-h*h,y=p*p+x>0?Math.sqrt(p*p+x):0,_=h*h+x>0?Math.sqrt(h*h+x):0,b=h+Math.sqrt(h*h+x)!==0?x*Math.log(Math.abs((p+y)/(h+_))):0;return Math.sqrt(o)/2*(p*y-h*_+b)};function zns(s,t,r){const n=Dke(1,r,s),a=Dke(1,r,t),i=n*n+a*a;return Math.sqrt(i)}const Dke=(s,t,r)=>{const n=r.length-1;let a,i;if(n===0)return 0;if(s===0){i=0;for(let l=0;l<=n;l++)i+=Bns[n][l]*Math.pow(1-t,n-l)*Math.pow(t,l)*r[l];return i}else{a=new Array(n);for(let l=0;l{let n=1,a=s/t,i=(s-r(a))/t,l=0;for(;n>.001;){const o=r(a+i),c=Math.abs(s-o)/t;if(c500)break}return a};let Ly=class Hg extends On{constructor(t){super(t),this.dataArray=[],this.pathLength=0,this._readDataAttribute(),this.on("dataChange.konva",function(){this._readDataAttribute()})}_readDataAttribute(){this.dataArray=Hg.parsePathData(this.data()),this.pathLength=Hg.getPathLength(this.dataArray)}_sceneFunc(t){const r=this.dataArray;t.beginPath();let n=!1;for(let a=0;ah?d:h,b=d>h?1:d/h,j=d>h?h/d:1;t.translate(o,c),t.rotate(x),t.scale(b,j),t.arc(0,0,_,m,m+p,1-y),t.scale(1/b,1/j),t.rotate(-x),t.translate(-o,-c);break;case"z":n=!0,t.closePath();break}}!n&&!this.hasFill()?t.strokeShape(this):t.fillStrokeShape(this)}getSelfRect(){let t=[];this.dataArray.forEach(function(c){if(c.command==="A"){const d=c.points[4],h=c.points[5],m=c.points[4]+h;let p=Math.PI/180;if(Math.abs(d-m)m;x-=p){const y=Hg.getPointOnEllipticalArc(c.points[0],c.points[1],c.points[2],c.points[3],x,0);t.push(y.x,y.y)}else for(let x=d+p;xr[a].pathLength;)t-=r[a].pathLength,++a;if(a===i)return n=r[a-1].points.slice(-2),{x:n[0],y:n[1]};if(t<.01)return r[a].command==="M"?(n=r[a].points.slice(0,2),{x:n[0],y:n[1]}):{x:r[a].start.x,y:r[a].start.y};const l=r[a],o=l.points;switch(l.command){case"L":return Hg.getPointOnLine(t,l.start.x,l.start.y,o[0],o[1]);case"C":return Hg.getPointOnCubicBezier(bze(t,Hg.getPathLength(r),_=>yze([l.start.x,o[0],o[2],o[4]],[l.start.y,o[1],o[3],o[5]],_)),l.start.x,l.start.y,o[0],o[1],o[2],o[3],o[4],o[5]);case"Q":return Hg.getPointOnQuadraticBezier(bze(t,Hg.getPathLength(r),_=>vze([l.start.x,o[0],o[2]],[l.start.y,o[1],o[3]],_)),l.start.x,l.start.y,o[0],o[1],o[2],o[3]);case"A":const c=o[0],d=o[1],h=o[2],m=o[3],p=o[5],x=o[6];let y=o[4];return y+=p*t/l.pathLength,Hg.getPointOnEllipticalArc(c,d,h,m,y,x)}return null}static getPointOnLine(t,r,n,a,i,l,o){l=l??r,o=o??n;const c=this.getLineLength(r,n,a,i);if(c<1e-10)return{x:r,y:n};if(a===r)return{x:l,y:o+(i>n?t:-t)};const d=(i-n)/(a-r),h=Math.sqrt(t*t/(1+d*d))*(a=0&&(_+=2,_>=7&&(_-=7));continue}if(_>=0){if(_===3){if(/^[01]{2}\d+(?:\.\d+)?$/.test(k)){y.push(parseInt(k[0],10)),y.push(parseInt(k[1],10)),y.push(parseFloat(k.slice(2))),_+=3,_>=7&&(_-=7);continue}if(k==="11"||k==="10"||k==="01"){y.push(parseInt(k[0],10)),y.push(parseInt(k[1],10)),_+=2,_>=7&&(_-=7);continue}if(k==="0"||k==="1"){y.push(parseInt(k,10)),_+=1,_>=7&&(_-=7);continue}}else if(_===4){if(/^[01]\d+(?:\.\d+)?$/.test(k)){y.push(parseInt(k[0],10)),y.push(parseFloat(k.slice(1))),_+=2,_>=7&&(_-=7);continue}if(k==="0"||k==="1"){y.push(parseInt(k,10)),_+=1,_>=7&&(_-=7);continue}}const T=parseFloat(k);isNaN(T)?y.push(0):y.push(T),_+=1,_>=7&&(_-=7)}else{const T=parseFloat(k);isNaN(T)?y.push(0):y.push(T)}}for(;y.length>0&&!isNaN(y[0]);){let b="",j=[];const k=o,T=c;let E,A,D,R,z,O,$,ee,Z,J;switch(x){case"l":o+=y.shift(),c+=y.shift(),b="L",j.push(o,c);break;case"L":o=y.shift(),c=y.shift(),j.push(o,c);break;case"m":const K=y.shift(),re=y.shift();if(o+=K,c+=re,b="M",i.length>2&&i[i.length-1].command==="z"){for(let ie=i.length-2;ie>=0;ie--)if(i[ie].command==="M"){o=i[ie].points[0]+K,c=i[ie].points[1]+re;break}}j.push(o,c),x="l";break;case"M":o=y.shift(),c=y.shift(),b="M",j.push(o,c),x="L";break;case"h":o+=y.shift(),b="L",j.push(o,c);break;case"H":o=y.shift(),b="L",j.push(o,c);break;case"v":c+=y.shift(),b="L",j.push(o,c);break;case"V":c=y.shift(),b="L",j.push(o,c);break;case"C":j.push(y.shift(),y.shift(),y.shift(),y.shift()),o=y.shift(),c=y.shift(),j.push(o,c);break;case"c":j.push(o+y.shift(),c+y.shift(),o+y.shift(),c+y.shift()),o+=y.shift(),c+=y.shift(),b="C",j.push(o,c);break;case"S":A=o,D=c,E=i[i.length-1],E.command==="C"&&(A=o+(o-E.points[2]),D=c+(c-E.points[3])),j.push(A,D,y.shift(),y.shift()),o=y.shift(),c=y.shift(),b="C",j.push(o,c);break;case"s":A=o,D=c,E=i[i.length-1],E.command==="C"&&(A=o+(o-E.points[2]),D=c+(c-E.points[3])),j.push(A,D,o+y.shift(),c+y.shift()),o+=y.shift(),c+=y.shift(),b="C",j.push(o,c);break;case"Q":j.push(y.shift(),y.shift()),o=y.shift(),c=y.shift(),j.push(o,c);break;case"q":j.push(o+y.shift(),c+y.shift()),o+=y.shift(),c+=y.shift(),b="Q",j.push(o,c);break;case"T":A=o,D=c,E=i[i.length-1],E.command==="Q"&&(A=o+(o-E.points[0]),D=c+(c-E.points[1])),o=y.shift(),c=y.shift(),b="Q",j.push(A,D,o,c);break;case"t":A=o,D=c,E=i[i.length-1],E.command==="Q"&&(A=o+(o-E.points[0]),D=c+(c-E.points[1])),o+=y.shift(),c+=y.shift(),b="Q",j.push(A,D,o,c);break;case"A":R=y.shift(),z=y.shift(),O=y.shift(),$=y.shift(),ee=y.shift(),Z=o,J=c,o=y.shift(),c=y.shift(),b="A",j=this.convertEndpointToCenterParameterization(Z,J,o,c,$,ee,R,z,O);break;case"a":R=y.shift(),z=y.shift(),O=y.shift(),$=y.shift(),ee=y.shift(),Z=o,J=c,o+=y.shift(),c+=y.shift(),b="A",j=this.convertEndpointToCenterParameterization(Z,J,o,c,$,ee,R,z,O);break}i.push({command:b||x,points:j,start:{x:k,y:T},pathLength:this.calcLength(k,T,b||x,j)})}(x==="z"||x==="Z")&&i.push({command:"z",points:[],start:void 0,pathLength:0})}return i}static calcLength(t,r,n,a){let i,l,o,c;const d=Hg;switch(n){case"L":return d.getLineLength(t,r,a[0],a[1]);case"C":return yze([t,a[0],a[2],a[4]],[r,a[1],a[3],a[5]],1);case"Q":return vze([t,a[0],a[2]],[r,a[1],a[3]],1);case"A":i=0;const h=a[4],m=a[5],p=a[4]+m;let x=Math.PI/180;if(Math.abs(h-p)p;c-=x)o=d.getPointOnEllipticalArc(a[0],a[1],a[2],a[3],c,0),i+=d.getLineLength(l.x,l.y,o.x,o.y),l=o;else for(c=h+x;c1&&(o*=Math.sqrt(x),c*=Math.sqrt(x));let y=Math.sqrt((o*o*(c*c)-o*o*(p*p)-c*c*(m*m))/(o*o*(p*p)+c*c*(m*m)));i===l&&(y*=-1),isNaN(y)&&(y=0);const _=y*o*p/c,b=y*-c*m/o,j=(t+n)/2+Math.cos(h)*_-Math.sin(h)*b,k=(r+a)/2+Math.sin(h)*_+Math.cos(h)*b,T=function($){return Math.sqrt($[0]*$[0]+$[1]*$[1])},E=function($,ee){return($[0]*ee[0]+$[1]*ee[1])/(T($)*T(ee))},A=function($,ee){return($[0]*ee[1]<$[1]*ee[0]?-1:1)*Math.acos(E($,ee))},D=A([1,0],[(m-_)/o,(p-b)/c]),R=[(m-_)/o,(p-b)/c],z=[(-1*m-_)/o,(-1*p-b)/c];let O=A(R,z);return E(R,z)<=-1&&(O=Math.PI),E(R,z)>=1&&(O=0),l===0&&O>0&&(O=O-2*Math.PI),l===1&&O<0&&(O=O+2*Math.PI),[j,k,o,c,D,O,h,l]}};Ly.prototype.className="Path";Ly.prototype._attrsAffectingSize=["data"];ju(Ly);ps.addGetterSetter(Ly,"data");class WA extends wj{_sceneFunc(t){super._sceneFunc(t);const r=Math.PI*2,n=this.points();let a=n;const i=this.tension()!==0&&n.length>4;i&&(a=this.getTensionPoints());const l=this.pointerLength(),o=n.length;let c,d;if(i){const p=[a[a.length-4],a[a.length-3],a[a.length-2],a[a.length-1],n[o-2],n[o-1]],x=Ly.calcLength(a[a.length-4],a[a.length-3],"C",p),y=Ly.getPointOnQuadraticBezier(Math.min(1,1-l/x),p[0],p[1],p[2],p[3],p[4],p[5]);c=n[o-2]-y.x,d=n[o-1]-y.y}else c=n[o-2]-n[o-4],d=n[o-1]-n[o-3];const h=(Math.atan2(d,c)+r)%r,m=this.pointerWidth();this.pointerAtEnding()&&(t.save(),t.beginPath(),t.translate(n[o-2],n[o-1]),t.rotate(h),t.moveTo(0,0),t.lineTo(-l,m/2),t.lineTo(-l,-m/2),t.closePath(),t.restore(),this.__fillStroke(t)),this.pointerAtBeginning()&&(t.save(),t.beginPath(),t.translate(n[0],n[1]),i?(c=(a[0]+a[2])/2-n[0],d=(a[1]+a[3])/2-n[1]):(c=n[2]-n[0],d=n[3]-n[1]),t.rotate((Math.atan2(-d,-c)+r)%r),t.moveTo(0,0),t.lineTo(-l,m/2),t.lineTo(-l,-m/2),t.closePath(),t.restore(),this.__fillStroke(t))}__fillStroke(t){const r=this.dashEnabled();r&&(this.attrs.dashEnabled=!1,t.setLineDash([])),t.fillStrokeShape(this),r&&(this.attrs.dashEnabled=!0)}getSelfRect(){const t=super.getSelfRect(),r=this.pointerWidth()/2;return{x:t.x,y:t.y-r,width:t.width,height:t.height+r*2}}}WA.prototype.className="Arrow";ju(WA);ps.addGetterSetter(WA,"pointerLength",10,Hn());ps.addGetterSetter(WA,"pointerWidth",10,Hn());ps.addGetterSetter(WA,"pointerAtBeginning",!1);ps.addGetterSetter(WA,"pointerAtEnding",!0);class j8 extends On{_sceneFunc(t){t.beginPath(),t.arc(0,0,this.attrs.radius||0,0,Math.PI*2,!1),t.closePath(),t.fillStrokeShape(this)}getWidth(){return this.radius()*2}getHeight(){return this.radius()*2}setWidth(t){this.radius()!==t/2&&this.radius(t/2)}setHeight(t){this.radius()!==t/2&&this.radius(t/2)}}j8.prototype._centroid=!0;j8.prototype.className="Circle";j8.prototype._attrsAffectingSize=["radius"];ju(j8);ps.addGetterSetter(j8,"radius",0,Hn());class ZS extends On{_sceneFunc(t){const r=this.radiusX(),n=this.radiusY();t.beginPath(),t.save(),r!==n&&t.scale(1,n/r),t.arc(0,0,r,0,Math.PI*2,!1),t.restore(),t.closePath(),t.fillStrokeShape(this)}getWidth(){return this.radiusX()*2}getHeight(){return this.radiusY()*2}setWidth(t){this.radiusX(t/2)}setHeight(t){this.radiusY(t/2)}}ZS.prototype.className="Ellipse";ZS.prototype._centroid=!0;ZS.prototype._attrsAffectingSize=["radiusX","radiusY"];ju(ZS);ps.addComponentsGetterSetter(ZS,"radius",["x","y"]);ps.addGetterSetter(ZS,"radiusX",0,Hn());ps.addGetterSetter(ZS,"radiusY",0,Hn());let F1=class hut extends On{constructor(t){super(t),this._loadListener=()=>{this._requestDraw()},this.on("imageChange.konva",r=>{this._removeImageLoad(r.oldVal),this._setImageLoad()}),this._setImageLoad()}_setImageLoad(){const t=this.image();t&&t.complete||t&&t.readyState===4||t&&t.addEventListener&&t.addEventListener("load",this._loadListener)}_removeImageLoad(t){t&&t.removeEventListener&&t.removeEventListener("load",this._loadListener)}destroy(){return this._removeImageLoad(this.image()),super.destroy(),this}_useBufferCanvas(){const t=!!this.cornerRadius(),r=this.hasShadow();return t&&r?!0:super._useBufferCanvas(!0)}_sceneFunc(t){const r=this.getWidth(),n=this.getHeight(),a=this.cornerRadius(),i=this.attrs.image;let l;if(i){const o=this.attrs.cropWidth,c=this.attrs.cropHeight;o&&c?l=[i,this.cropX(),this.cropY(),o,c,0,0,r,n]:l=[i,0,0,r,n]}(this.hasFill()||this.hasStroke()||a)&&(t.beginPath(),a?or.drawRoundedRectPath(t,r,n,a):t.rect(0,0,r,n),t.closePath(),t.fillStrokeShape(this)),i&&(a&&t.clip(),t.drawImage.apply(t,l))}_hitFunc(t){const r=this.width(),n=this.height(),a=this.cornerRadius();t.beginPath(),a?or.drawRoundedRectPath(t,r,n,a):t.rect(0,0,r,n),t.closePath(),t.fillStrokeShape(this)}getWidth(){var t,r,n;return(n=(t=this.attrs.width)!==null&&t!==void 0?t:(r=this.image())===null||r===void 0?void 0:r.width)!==null&&n!==void 0?n:0}getHeight(){var t,r,n;return(n=(t=this.attrs.height)!==null&&t!==void 0?t:(r=this.image())===null||r===void 0?void 0:r.height)!==null&&n!==void 0?n:0}static fromURL(t,r,n=null){const a=or.createImageElement();a.onload=function(){const i=new hut({image:a});r(i)},a.onerror=n,a.crossOrigin="Anonymous",a.src=t}};F1.prototype.className="Image";F1.prototype._attrsAffectingSize=["image"];ju(F1);ps.addGetterSetter(F1,"cornerRadius",0,wxe(4));ps.addGetterSetter(F1,"image");ps.addComponentsGetterSetter(F1,"crop",["x","y","width","height"]);ps.addGetterSetter(F1,"cropX",0,Hn());ps.addGetterSetter(F1,"cropY",0,Hn());ps.addGetterSetter(F1,"cropWidth",0,Hn());ps.addGetterSetter(F1,"cropHeight",0,Hn());const mut=["fontFamily","fontSize","fontStyle","padding","lineHeight","text","width","height","pointerDirection","pointerWidth","pointerHeight"],$ns="Change.konva",Uns="none",Rke="up",Oke="right",Fke="down",Bke="left",qns=mut.length;let AEe=class extends hL{constructor(t){super(t),this.on("add.konva",function(r){this._addListeners(r.child),this._sync()})}getText(){return this.find("Text")[0]}getTag(){return this.find("Tag")[0]}_addListeners(t){let r=this,n;const a=function(){r._sync()};for(n=0;n{r=Math.min(r,l.x),n=Math.max(n,l.x),a=Math.min(a,l.y),i=Math.max(i,l.y)}),{x:r,y:a,width:n-r,height:i-a}}getWidth(){return this.radius()*2}getHeight(){return this.radius()*2}setWidth(t){this.radius(t/2)}setHeight(t){this.radius(t/2)}}XS.prototype.className="RegularPolygon";XS.prototype._centroid=!0;XS.prototype._attrsAffectingSize=["radius"];ju(XS);ps.addGetterSetter(XS,"radius",0,Hn());ps.addGetterSetter(XS,"sides",0,Hn());ps.addGetterSetter(XS,"cornerRadius",0,wxe(4));const _ze=Math.PI*2;class YA extends On{_sceneFunc(t){t.beginPath(),t.arc(0,0,this.innerRadius(),0,_ze,!1),t.moveTo(this.outerRadius(),0),t.arc(0,0,this.outerRadius(),_ze,0,!0),t.closePath(),t.fillStrokeShape(this)}getWidth(){return this.outerRadius()*2}getHeight(){return this.outerRadius()*2}setWidth(t){this.outerRadius(t/2)}setHeight(t){this.outerRadius(t/2)}}YA.prototype.className="Ring";YA.prototype._centroid=!0;YA.prototype._attrsAffectingSize=["innerRadius","outerRadius"];ju(YA);ps.addGetterSetter(YA,"innerRadius",0,Hn());ps.addGetterSetter(YA,"outerRadius",0,Hn());class W_ extends On{constructor(t){super(t),this._updated=!0,this.anim=new Py(()=>{const r=this._updated;return this._updated=!1,r}),this.on("animationChange.konva",function(){this.frameIndex(0)}),this.on("frameIndexChange.konva",function(){this._updated=!0}),this.on("frameRateChange.konva",function(){this.anim.isRunning()&&(clearInterval(this.interval),this._setInterval())})}_sceneFunc(t){const r=this.animation(),n=this.frameIndex(),a=n*4,i=this.animations()[r],l=this.frameOffsets(),o=i[a+0],c=i[a+1],d=i[a+2],h=i[a+3],m=this.image();if((this.hasFill()||this.hasStroke())&&(t.beginPath(),t.rect(0,0,d,h),t.closePath(),t.fillStrokeShape(this)),m)if(l){const p=l[r],x=n*2;t.drawImage(m,o,c,d,h,p[x+0],p[x+1],d,h)}else t.drawImage(m,o,c,d,h,0,0,d,h)}_hitFunc(t){const r=this.animation(),n=this.frameIndex(),a=n*4,i=this.animations()[r],l=this.frameOffsets(),o=i[a+2],c=i[a+3];if(t.beginPath(),l){const d=l[r],h=n*2;t.rect(d[h+0],d[h+1],o,c)}else t.rect(0,0,o,c);t.closePath(),t.fillShape(this)}_useBufferCanvas(){return super._useBufferCanvas(!0)}_setInterval(){const t=this;this.interval=setInterval(function(){t._updateIndex()},1e3/this.frameRate())}start(){if(this.isRunning())return;const t=this.getLayer();this.anim.setLayers(t),this._setInterval(),this.anim.start()}stop(){this.anim.stop(),clearInterval(this.interval)}isRunning(){return this.anim.isRunning()}_updateIndex(){const t=this.frameIndex(),r=this.animation(),n=this.animations(),a=n[r],i=a.length/4;t{if(new RegExp("\\p{Emoji}","u").test(r)){const i=a[n+1];i&&new RegExp("\\p{Emoji_Modifier}|\\u200D","u").test(i)?(t.push(r+i),a[n+1]=""):t.push(r)}else new RegExp("\\p{Regional_Indicator}{2}","u").test(r+(a[n+1]||""))?t.push(r+a[n+1]):n>0&&new RegExp("\\p{Mn}|\\p{Me}|\\p{Mc}","u").test(r)?t[t.length-1]+=r:r&&t.push(r);return t},[])}const b6="auto",Vns="center",fut="inherit",zR="justify",Hns="Change.konva",put="2d",wze="-",gut="left",Gns="text",Wns="Text",Kns="top",Yns="bottom",jze="middle",xut="normal",Zns="px ",vq=" ",Xns="right",Nze="rtl",Qns="word",Jns="char",kze="none",__e="…",yut=["direction","fontFamily","fontSize","fontStyle","fontVariant","padding","align","verticalAlign","lineHeight","text","width","height","wrap","ellipsis","letterSpacing"],eas=yut.length;let $R=null;function tas(){if($R!==null)return $R;$R=!1;try{const s=document.createElement("canvas");s.width=10,s.height=10;const t=s.getContext(put);if(t){t.globalAlpha=0,t.shadowColor="black",t.shadowBlur=5,t.shadowOffsetX=5,t.shadowOffsetY=5,t.fillStyle="black",t.font="10px Arial",t.fillText("X",0,10);const r=t.getImageData(0,0,10,10).data;for(let n=3;n0){$R=!0;break}}}catch{}return $R}function sas(s){return s.split(",").map(t=>{t=t.trim();const r=t.indexOf(" ")>=0,n=t.indexOf('"')>=0||t.indexOf("'")>=0;return r&&!n&&(t=`"${t}"`),t}).join(", ")}let bq;function w_e(){return bq||(bq=or.createCanvasElement().getContext(put),bq)}function ras(s){s.fillText(this._partialText,this._partialTextX,this._partialTextY)}function nas(s){s.setAttr("miterLimit",2),s.strokeText(this._partialText,this._partialTextX,this._partialTextY)}function aas(s){return s=s||{},!s.fillLinearGradientColorStops&&!s.fillRadialGradientColorStops&&!s.fillPatternImage&&(s.fill=s.fill||"black"),s}let ud=class extends On{constructor(t){super(aas(t)),this._partialTextX=0,this._partialTextY=0;for(let r=0;rje+ON(ve.text).length,0),fe=ce+be;_({char:ne,index:fe,x:z,y:D+O,lineIndex:A,column:ce,isLastInLine:J,width:this.measureSize(ne).width,context:t})}t.fillStrokeShape(this),_&&t.restore(),z+=this.measureSize(ne).width+y}}else y!==0&&t.setAttr("letterSpacing",`${y}px`),this._partialTextX=z,this._partialTextY=D+O,this._partialText=ee,t.fillStrokeShape(this);if(E){t.save(),t.beginPath();const re=Jn.legacyTextRendering?0:-Math.round(o/4),ie=K;t.moveTo(ie,D+O+re);const ce=p===zR&&!J?x-l*2:Z;t.lineTo(ie+Math.round(ce),D+O+re),t.lineWidth=o/15;const ne=this._getLinearGradient();t.strokeStyle=ne||b,t.stroke(),t.restore()}t.restore(),i>1&&(D+=c)}}_hitFunc(t){const r=this.getWidth(),n=this.getHeight();t.beginPath(),t.rect(0,0,r,n),t.closePath(),t.fillStrokeShape(this)}setText(t){const r=or._isString(t)?t:t==null?"":t+"";return this._setAttr(Gns,r),this}getWidth(){return this.attrs.width===b6||this.attrs.width===void 0?this.getTextWidth()+this.padding()*2:this.attrs.width}getHeight(){return this.attrs.height===b6||this.attrs.height===void 0?this.fontSize()*this.textArr.length*this.lineHeight()+this.padding()*2:this.attrs.height}getTextWidth(){return this.textWidth}getTextHeight(){return or.warn("text.getTextHeight() method is deprecated. Use text.height() - for full height and text.fontSize() - for one line height."),this.textHeight}measureSize(t){var r,n,a,i,l,o,c,d,h,m,p;let x=w_e(),y=this.fontSize(),_;x.save(),x.font=this._getContextFont(),_=x.measureText(t),x.restore();const b=y/100;return{actualBoundingBoxAscent:(r=_.actualBoundingBoxAscent)!==null&&r!==void 0?r:71.58203125*b,actualBoundingBoxDescent:(n=_.actualBoundingBoxDescent)!==null&&n!==void 0?n:0,actualBoundingBoxLeft:(a=_.actualBoundingBoxLeft)!==null&&a!==void 0?a:-7.421875*b,actualBoundingBoxRight:(i=_.actualBoundingBoxRight)!==null&&i!==void 0?i:75.732421875*b,alphabeticBaseline:(l=_.alphabeticBaseline)!==null&&l!==void 0?l:0,emHeightAscent:(o=_.emHeightAscent)!==null&&o!==void 0?o:100*b,emHeightDescent:(c=_.emHeightDescent)!==null&&c!==void 0?c:-20*b,fontBoundingBoxAscent:(d=_.fontBoundingBoxAscent)!==null&&d!==void 0?d:91*b,fontBoundingBoxDescent:(h=_.fontBoundingBoxDescent)!==null&&h!==void 0?h:21*b,hangingBaseline:(m=_.hangingBaseline)!==null&&m!==void 0?m:72.80000305175781*b,ideographicBaseline:(p=_.ideographicBaseline)!==null&&p!==void 0?p:-21*b,width:_.width,height:y}}_getContextFont(){return this.fontStyle()+vq+this.fontVariant()+vq+(this.fontSize()+Zns)+sas(this.fontFamily())}_addTextLine(t){this.align()===zR&&(t=t.trim());const n=this._getTextWidth(t);return this.textArr.push({text:t,width:n,lastInParagraph:!1})}_getTextWidth(t){const r=this.letterSpacing(),n=t.length;return w_e().measureText(t).width+r*n}_setTextData(){let t=this.text().split(` `),r=+this.fontSize(),n=0,a=this.lineHeight()*r,i=this.attrs.width,l=this.attrs.height,o=i!==b6&&i!==void 0,c=l!==b6&&l!==void 0,d=this.padding(),h=i-d*2,m=l-d*2,p=0,x=this.wrap(),y=x!==kze,_=x!==Jns&&y,b=this.ellipsis();this.textArr=[],w_e().font=this._getContextFont();const j=b?this._getTextWidth(__e):0;for(let k=0,T=t.length;kh)for(;E.length>0;){let D=0,R=ON(E).length,z="",O=0;for(;D>>1,ee=ON(E),Z=ee.slice(0,$+1).join(""),J=this._getTextWidth(Z);(b&&c&&p+a>m?J+j:J)<=h?(D=$+1,z=Z,O=J):R=$}if(z){if(_){const Z=ON(E),J=ON(z),K=Z[J.length],re=K===vq||K===wze;let ie;if(re&&O<=h)ie=J.length;else{const ce=J.lastIndexOf(vq),ne=J.lastIndexOf(wze);ie=Math.max(ce,ne)+1}ie>0&&(D=ie,z=Z.slice(0,D).join(""),O=this._getTextWidth(z))}if(z=z.trimRight(),this._addTextLine(z),n=Math.max(n,O),p+=a,this._shouldHandleEllipsis(p)){this._tryToAddEllipsisToLastLine();break}if(E=ON(E).slice(D).join("").trimLeft(),E.length>0&&(A=this._getTextWidth(E),A<=h)){this._addTextLine(E),p+=a,n=Math.max(n,A);break}}else break}else this._addTextLine(E),p+=a,n=Math.max(n,A),this._shouldHandleEllipsis(p)&&km)break}this.textHeight=r,this.textWidth=n}_shouldHandleEllipsis(t){const r=+this.fontSize(),n=this.lineHeight()*r,a=this.attrs.height,i=a!==b6&&a!==void 0,l=this.padding(),o=a-l*2;return!(this.wrap()!==kze)||i&&t+n>o}_tryToAddEllipsisToLastLine(){const t=this.attrs.width,r=t!==b6&&t!==void 0,n=this.padding(),a=t-n*2,i=this.ellipsis(),l=this.textArr[this.textArr.length-1];!l||!i||(r&&(this._getTextWidth(l.text+__e)r?null:Ly.getPointAtLengthOfDataArray(t,this.dataArray)}_readDataAttribute(){this.dataArray=Ly.parsePathData(this.attrs.data),this.pathLength=this._getTextPathLength()}_sceneFunc(t){t.setAttr("font",this._getContextFont()),t.setAttr("textBaseline",this.textBaseline()),t.setAttr("textAlign","left"),t.save();const r=this.textDecoration(),n=this.fill(),a=this.fontSize(),i=this.glyphInfo,l=r.indexOf("underline")!==-1,o=r.indexOf("line-through")!==-1;l&&t.beginPath();for(let c=0;c=1){const n=r[0].p0;t.moveTo(n.x,n.y)}for(let n=0;nthis.pathLength&&j-this.pathLength<=d?this.pathLength:j);if(!k)return;const T=Ly.getLineLength(y.x,y.y,k.x,k.y);let E=0;if(c)try{E=c(r[x-1].char,_)*this.fontSize()}catch{E=0}y.x+=E,k.x+=E,this.textWidth+=E;const A=Ly.getPointOnLine(E+T/2,y.x,y.y,k.x,k.y),D=Math.atan2(k.y-y.y,k.x-y.x);this.glyphInfo.push({transposeX:A.x,transposeY:A.y,text:t[x],rotation:D,p0:y,p1:k,width:T}),p+=b}}getSelfRect(){if(!this.glyphInfo.length)return{x:0,y:0,width:0,height:0};const t=[];this.glyphInfo.forEach(function(d){t.push(d.p0.x),t.push(d.p0.y),t.push(d.p1.x),t.push(d.p1.y)});let r=t[0]||0,n=t[0]||0,a=t[1]||0,i=t[1]||0,l,o;for(let d=0;ds+`.${wut}`).join(" "),Sze="nodesRect",las=["widthChange","heightChange","scaleXChange","scaleYChange","skewXChange","skewYChange","rotationChange","offsetXChange","offsetYChange","transformsEnabledChange","strokeWidthChange","draggableChange"],cas={"top-left":-45,"top-center":0,"top-right":45,"middle-right":-90,"middle-left":90,"bottom-left":-135,"bottom-center":180,"bottom-right":135},das="ontouchstart"in Jn._global;function uas(s,t,r){if(s==="rotater")return r;t+=or.degToRad(cas[s]||0);const n=(or.radToDeg(t)%360+360)%360;return or._inRange(n,315+22.5,360)||or._inRange(n,0,22.5)?"ns-resize":or._inRange(n,45-22.5,45+22.5)?"nesw-resize":or._inRange(n,90-22.5,90+22.5)?"ew-resize":or._inRange(n,135-22.5,135+22.5)?"nwse-resize":or._inRange(n,180-22.5,180+22.5)?"ns-resize":or._inRange(n,225-22.5,225+22.5)?"nesw-resize":or._inRange(n,270-22.5,270+22.5)?"ew-resize":or._inRange(n,315-22.5,315+22.5)?"nwse-resize":(or.error("Transformer has unknown angle for cursor detection: "+n),"pointer")}const Wme=["top-left","top-center","top-right","middle-right","middle-left","bottom-left","bottom-center","bottom-right"],Cze=1e8;function has(s){return{x:s.x+s.width/2*Math.cos(s.rotation)+s.height/2*Math.sin(-s.rotation),y:s.y+s.height/2*Math.cos(s.rotation)+s.width/2*Math.sin(s.rotation)}}function jut(s,t,r){const n=r.x+(s.x-r.x)*Math.cos(t)-(s.y-r.y)*Math.sin(t),a=r.y+(s.x-r.x)*Math.sin(t)+(s.y-r.y)*Math.cos(t);return{...s,rotation:s.rotation+t,x:n,y:a}}function mas(s,t){const r=has(s);return jut(s,t,r)}function fas(s,t,r){let n=t;for(let a=0;aa.isAncestorOf(this)?(or.error("Konva.Transformer cannot be an a child of the node you are trying to attach"),!1):!0);return this._nodes=t=r,t.length===1&&this.useSingleNodeRotation()?this.rotation(t[0].getAbsoluteRotation()):this.rotation(0),this._nodes.forEach(a=>{const i=()=>{this.nodes().length===1&&this.useSingleNodeRotation()&&this.rotation(this.nodes()[0].getAbsoluteRotation()),this._resetTransformCache(),!this._transforming&&!this.isDragging()&&this.update()};if(a._attrsAffectingSize.length){const l=a._attrsAffectingSize.map(o=>o+"Change."+this._getEventNamespace()).join(" ");a.on(l,i)}a.on(las.map(l=>l+`.${this._getEventNamespace()}`).join(" "),i),a.on(`absoluteTransformChange.${this._getEventNamespace()}`,i),this._proxyDrag(a)}),this._resetTransformCache(),!!this.findOne(".top-left")&&this.update(),this}_proxyDrag(t){let r;t.on(`dragstart.${this._getEventNamespace()}`,n=>{r=t.getAbsolutePosition(),!this.isDragging()&&t!==this.findOne(".back")&&this.startDrag(n,!1)}),t.on(`dragmove.${this._getEventNamespace()}`,n=>{if(!r)return;const a=t.getAbsolutePosition(),i=a.x-r.x,l=a.y-r.y;this.nodes().forEach(o=>{if(o===t||o.isDragging())return;const c=o.getAbsolutePosition();o.setAbsolutePosition({x:c.x+i,y:c.y+l}),o.startDrag(n)}),r=null})}getNodes(){return this._nodes||[]}getActiveAnchor(){return this._movingAnchorName}detach(){this._nodes&&this._nodes.forEach(t=>{t.off("."+this._getEventNamespace())}),this._nodes=[],this._resetTransformCache()}_resetTransformCache(){this._clearCache(Sze),this._clearCache("transform"),this._clearSelfAndDescendantCache("absoluteTransform")}_getNodeRect(){return this._getCache(Sze,this.__getNodeRect)}__getNodeShape(t,r=this.rotation(),n){const a=t.getClientRect({skipTransform:!0,skipShadow:!0,skipStroke:this.ignoreStroke()}),i=t.getAbsoluteScale(n),l=t.getAbsolutePosition(n),o=a.x*i.x-t.offsetX()*i.x,c=a.y*i.y-t.offsetY()*i.y,d=(Jn.getAngle(t.getAbsoluteRotation())+Math.PI*2)%(Math.PI*2),h={x:l.x+o*Math.cos(d)+c*Math.sin(-d),y:l.y+c*Math.cos(d)+o*Math.sin(d),width:a.width*i.x,height:a.height*i.y,rotation:d};return jut(h,-Jn.getAngle(r),{x:0,y:0})}__getNodeRect(){if(!this.getNode())return{x:-Cze,y:-Cze,width:0,height:0,rotation:0};const r=[];this.nodes().map(d=>{const h=d.getClientRect({skipTransform:!0,skipShadow:!0,skipStroke:this.ignoreStroke()}),m=[{x:h.x,y:h.y},{x:h.x+h.width,y:h.y},{x:h.x+h.width,y:h.y+h.height},{x:h.x,y:h.y+h.height}],p=d.getAbsoluteTransform();m.forEach(function(x){const y=p.point(x);r.push(y)})});const n=new a0;n.rotate(-Jn.getAngle(this.rotation()));let a=1/0,i=1/0,l=-1/0,o=-1/0;r.forEach(function(d){const h=n.point(d);a===void 0&&(a=l=h.x,i=o=h.y),a=Math.min(a,h.x),i=Math.min(i,h.y),l=Math.max(l,h.x),o=Math.max(o,h.y)}),n.invert();const c=n.point({x:a,y:i});return{x:c.x,y:c.y,width:l-a,height:o-i,rotation:Jn.getAngle(this.rotation())}}getX(){return this._getNodeRect().x}getY(){return this._getNodeRect().y}getWidth(){return this._getNodeRect().width}getHeight(){return this._getNodeRect().height}_createElements(){this._createBack(),Wme.forEach(t=>{this._createAnchor(t)}),this._createAnchor("rotater"),this._elementsCreated=!0}_createAnchor(t){const r=new xz({stroke:"rgb(0, 161, 255)",fill:"white",strokeWidth:1,name:t+" _anchor",dragDistance:0,draggable:!0,hitStrokeWidth:das?10:"auto"}),n=this;r.on("mousedown touchstart",function(a){n._handleMouseDown(a)}),r.on("dragstart",a=>{r.stopDrag(),a.cancelBubble=!0}),r.on("dragend",a=>{a.cancelBubble=!0}),r.on("mouseenter",()=>{const a=Jn.getAngle(this.rotation()),i=this.rotateAnchorCursor(),l=uas(t,a,i);r.getStage().content&&(r.getStage().content.style.cursor=l),this._cursorChange=!0}),r.on("mouseout",()=>{r.getStage().content&&(r.getStage().content.style.cursor=""),this._cursorChange=!1}),this.add(r)}_createBack(){const t=new On({name:"back",width:0,height:0,sceneFunc(r,n){const a=n.getParent(),i=a.padding(),l=n.width(),o=n.height();if(r.beginPath(),r.rect(-i,-i,l+i*2,o+i*2),a.rotateEnabled()&&a.rotateLineVisible()){const c=a.rotateAnchorAngle(),d=a.rotateAnchorOffset(),h=or.degToRad(c),m=Math.sin(h),p=-Math.cos(h),x=l/2,y=o/2;let _=1/0;p<0?_=Math.min(_,-y/p):p>0&&(_=Math.min(_,(o-y)/p)),m<0?_=Math.min(_,-x/m):m>0&&(_=Math.min(_,(l-x)/m));const b=x+m*_,j=y+p*_,k=or._sign(o),T=b+m*d*k,E=j+p*d*k;r.moveTo(b,j),r.lineTo(T,E)}r.fillStrokeShape(n)},hitFunc:(r,n)=>{if(!this.shouldOverdrawWholeArea())return;const a=this.padding();r.beginPath(),r.rect(-a,-a,n.width()+a*2,n.height()+a*2),r.fillStrokeShape(n)}});this.add(t),this._proxyDrag(t),t.on("dragstart",r=>{r.cancelBubble=!0}),t.on("dragmove",r=>{r.cancelBubble=!0}),t.on("dragend",r=>{r.cancelBubble=!0}),this.on("dragmove",r=>{this.update()})}_handleMouseDown(t){if(this._transforming)return;this._movingAnchorName=t.target.name().split(" ")[0];const r=this._getNodeRect(),n=r.width,a=r.height,i=Math.sqrt(Math.pow(n,2)+Math.pow(a,2));this.sin=Math.abs(a/i),this.cos=Math.abs(n/i),typeof window<"u"&&(window.addEventListener("mousemove",this._handleMouseMove),window.addEventListener("touchmove",this._handleMouseMove),window.addEventListener("mouseup",this._handleMouseUp,!0),window.addEventListener("touchend",this._handleMouseUp,!0)),this._transforming=!0;const l=t.target.getAbsolutePosition(),o=t.target.getStage().getPointerPosition();this._anchorDragOffset={x:o.x-l.x,y:o.y-l.y},zke++,this._fire("transformstart",{evt:t.evt,target:this.getNode()}),this._nodes.forEach(c=>{c._fire("transformstart",{evt:t.evt,target:c})})}_handleMouseMove(t){let r,n,a;const i=this.findOne("."+this._movingAnchorName),l=i.getStage();l.setPointersPositions(t);const o=l.getPointerPosition();let c={x:o.x-this._anchorDragOffset.x,y:o.y-this._anchorDragOffset.y};const d=i.getAbsolutePosition();this.anchorDragBoundFunc()&&(c=this.anchorDragBoundFunc()(d,c,t)),i.setAbsolutePosition(c);const h=i.getAbsolutePosition();if(d.x===h.x&&d.y===h.y)return;if(this._movingAnchorName==="rotater"){const k=this._getNodeRect();r=i.x()-k.width/2,n=-i.y()+k.height/2;const T=Jn.getAngle(this.rotateAnchorAngle());let E=Math.atan2(-n,r)+Math.PI/2-T;k.height<0&&(E-=Math.PI);const D=Jn.getAngle(this.rotation())+E,R=Jn.getAngle(this.rotationSnapTolerance()),O=fas(this.rotationSnaps(),D,R)-k.rotation,$=mas(k,O);this._fitNodesInto($,t);return}const m=this.shiftBehavior();let p;m==="inverted"?p=this.keepRatio()&&!t.shiftKey:m==="none"?p=this.keepRatio():p=this.keepRatio()||t.shiftKey;let x=this.centeredScaling()||t.altKey;if(this._movingAnchorName==="top-left"){if(p){const k=x?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".bottom-right").x(),y:this.findOne(".bottom-right").y()};a=Math.sqrt(Math.pow(k.x-i.x(),2)+Math.pow(k.y-i.y(),2));const T=this.findOne(".top-left").x()>k.x?-1:1,E=this.findOne(".top-left").y()>k.y?-1:1;r=a*this.cos*T,n=a*this.sin*E,this.findOne(".top-left").x(k.x-r),this.findOne(".top-left").y(k.y-n)}}else if(this._movingAnchorName==="top-center")this.findOne(".top-left").y(i.y());else if(this._movingAnchorName==="top-right"){if(p){const k=x?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".bottom-left").x(),y:this.findOne(".bottom-left").y()};a=Math.sqrt(Math.pow(i.x()-k.x,2)+Math.pow(k.y-i.y(),2));const T=this.findOne(".top-right").x()k.y?-1:1;r=a*this.cos*T,n=a*this.sin*E,this.findOne(".top-right").x(k.x+r),this.findOne(".top-right").y(k.y-n)}var y=i.position();this.findOne(".top-left").y(y.y),this.findOne(".bottom-right").x(y.x)}else if(this._movingAnchorName==="middle-left")this.findOne(".top-left").x(i.x());else if(this._movingAnchorName==="middle-right")this.findOne(".bottom-right").x(i.x());else if(this._movingAnchorName==="bottom-left"){if(p){const k=x?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".top-right").x(),y:this.findOne(".top-right").y()};a=Math.sqrt(Math.pow(k.x-i.x(),2)+Math.pow(i.y()-k.y,2));const T=k.x{var i;a._fire("transformend",{evt:t,target:a}),(i=a.getLayer())===null||i===void 0||i.batchDraw()}),this._movingAnchorName=null}}_fitNodesInto(t,r){const n=this._getNodeRect(),a=1;if(or._inRange(t.width,-this.padding()*2-a,a)){this.update();return}if(or._inRange(t.height,-this.padding()*2-a,a)){this.update();return}const i=new a0;if(i.rotate(Jn.getAngle(this.rotation())),this._movingAnchorName&&t.width<0&&this._movingAnchorName.indexOf("left")>=0){const p=i.point({x:-this.padding()*2,y:0});t.x+=p.x,t.y+=p.y,t.width+=this.padding()*2,this._movingAnchorName=this._movingAnchorName.replace("left","right"),this._anchorDragOffset.x-=p.x,this._anchorDragOffset.y-=p.y}else if(this._movingAnchorName&&t.width<0&&this._movingAnchorName.indexOf("right")>=0){const p=i.point({x:this.padding()*2,y:0});this._movingAnchorName=this._movingAnchorName.replace("right","left"),this._anchorDragOffset.x-=p.x,this._anchorDragOffset.y-=p.y,t.width+=this.padding()*2}if(this._movingAnchorName&&t.height<0&&this._movingAnchorName.indexOf("top")>=0){const p=i.point({x:0,y:-this.padding()*2});t.x+=p.x,t.y+=p.y,this._movingAnchorName=this._movingAnchorName.replace("top","bottom"),this._anchorDragOffset.x-=p.x,this._anchorDragOffset.y-=p.y,t.height+=this.padding()*2}else if(this._movingAnchorName&&t.height<0&&this._movingAnchorName.indexOf("bottom")>=0){const p=i.point({x:0,y:this.padding()*2});this._movingAnchorName=this._movingAnchorName.replace("bottom","top"),this._anchorDragOffset.x-=p.x,this._anchorDragOffset.y-=p.y,t.height+=this.padding()*2}if(this.boundBoxFunc()){const p=this.boundBoxFunc()(n,t);p?t=p:or.warn("boundBoxFunc returned falsy. You should return new bound rect from it!")}const l=1e7,o=new a0;o.translate(n.x,n.y),o.rotate(n.rotation),o.scale(n.width/l,n.height/l);const c=new a0,d=t.width/l,h=t.height/l;this.flipEnabled()===!1?(c.translate(t.x,t.y),c.rotate(t.rotation),c.translate(t.width<0?t.width:0,t.height<0?t.height:0),c.scale(Math.abs(d),Math.abs(h))):(c.translate(t.x,t.y),c.rotate(t.rotation),c.scale(d,h));const m=c.multiply(o.invert());this._nodes.forEach(p=>{var x;if(!p.getStage())return;const y=p.getParent().getAbsoluteTransform(),_=p.getTransform().copy();_.translate(p.offsetX(),p.offsetY());const b=new a0;b.multiply(y.copy().invert()).multiply(m).multiply(y).multiply(_);const j=b.decompose();p.setAttrs(j),(x=p.getLayer())===null||x===void 0||x.batchDraw()}),this.rotation(or._getRotation(t.rotation)),this._nodes.forEach(p=>{this._fire("transform",{evt:r,target:p}),p._fire("transform",{evt:r,target:p})}),this._resetTransformCache(),this.update(),this.getLayer().batchDraw()}forceUpdate(){this._resetTransformCache(),this.update()}_batchChangeChild(t,r){this.findOne(t).setAttrs(r)}update(){var t;const r=this._getNodeRect();this.rotation(or._getRotation(r.rotation));const n=r.width,a=r.height,i=this.enabledAnchors(),l=this.resizeEnabled(),o=this.padding(),c=this.anchorSize(),d=this.find("._anchor");d.forEach(D=>{D.setAttrs({width:c,height:c,offsetX:c/2,offsetY:c/2,stroke:this.anchorStroke(),strokeWidth:this.anchorStrokeWidth(),fill:this.anchorFill(),cornerRadius:this.anchorCornerRadius()})}),this._batchChangeChild(".top-left",{x:0,y:0,offsetX:c/2+o,offsetY:c/2+o,visible:l&&i.indexOf("top-left")>=0}),this._batchChangeChild(".top-center",{x:n/2,y:0,offsetY:c/2+o,visible:l&&i.indexOf("top-center")>=0}),this._batchChangeChild(".top-right",{x:n,y:0,offsetX:c/2-o,offsetY:c/2+o,visible:l&&i.indexOf("top-right")>=0}),this._batchChangeChild(".middle-left",{x:0,y:a/2,offsetX:c/2+o,visible:l&&i.indexOf("middle-left")>=0}),this._batchChangeChild(".middle-right",{x:n,y:a/2,offsetX:c/2-o,visible:l&&i.indexOf("middle-right")>=0}),this._batchChangeChild(".bottom-left",{x:0,y:a,offsetX:c/2+o,offsetY:c/2-o,visible:l&&i.indexOf("bottom-left")>=0}),this._batchChangeChild(".bottom-center",{x:n/2,y:a,offsetY:c/2-o,visible:l&&i.indexOf("bottom-center")>=0}),this._batchChangeChild(".bottom-right",{x:n,y:a,offsetX:c/2-o,offsetY:c/2-o,visible:l&&i.indexOf("bottom-right")>=0});const h=this.rotateAnchorAngle(),m=this.rotateAnchorOffset(),p=or.degToRad(h),x=Math.sin(p),y=-Math.cos(p),_=n/2,b=a/2;let j=1/0;y<0?j=Math.min(j,-b/y):y>0&&(j=Math.min(j,(a-b)/y)),x<0?j=Math.min(j,-_/x):x>0&&(j=Math.min(j,(n-_)/x));const k=_+x*j,T=b+y*j,E=or._sign(a);this._batchChangeChild(".rotater",{x:k+x*m*E,y:T+y*m*E-o*y,visible:this.rotateEnabled()}),this._batchChangeChild(".back",{width:n,height:a,visible:this.borderEnabled(),stroke:this.borderStroke(),strokeWidth:this.borderStrokeWidth(),dash:this.borderDash(),draggable:this.nodes().some(D=>D.draggable()),x:0,y:0});const A=this.anchorStyleFunc();A&&d.forEach(D=>{A(D)}),(t=this.getLayer())===null||t===void 0||t.batchDraw()}isTransforming(){return this._transforming}stopTransform(){if(this._transforming){this._removeEvents();const t=this.findOne("."+this._movingAnchorName);t&&t.stopDrag()}}destroy(){return this.getStage()&&this._cursorChange&&this.getStage().content&&(this.getStage().content.style.cursor=""),hL.prototype.destroy.call(this),this.detach(),this._removeEvents(),this}add(...t){return this._elementsCreated?(or.error("You cannot add external nodes to the Transformer. Use tr.nodes([node]) instead."),this):super.add(...t)}toObject(){return aa.prototype.toObject.call(this)}clone(t){return aa.prototype.clone.call(this,t)}getClientRect(){return this.nodes().length>0?super.getClientRect():{x:0,y:0,width:0,height:0}}};ll.isTransforming=()=>zke>0;function pas(s){return s instanceof Array||or.warn("enabledAnchors value should be an array"),s instanceof Array&&s.forEach(function(t){Wme.indexOf(t)===-1&&or.warn("Unknown anchor name: "+t+". Available names are: "+Wme.join(", "))}),s||[]}ll.prototype.className="Transformer";ju(ll);ps.addGetterSetter(ll,"enabledAnchors",Wme,pas);ps.addGetterSetter(ll,"flipEnabled",!0,O1());ps.addGetterSetter(ll,"resizeEnabled",!0);ps.addGetterSetter(ll,"anchorSize",10,Hn());ps.addGetterSetter(ll,"rotateEnabled",!0);ps.addGetterSetter(ll,"rotateLineVisible",!0);ps.addGetterSetter(ll,"rotationSnaps",[]);ps.addGetterSetter(ll,"rotateAnchorOffset",50,Hn());ps.addGetterSetter(ll,"rotateAnchorAngle",0,Hn());ps.addGetterSetter(ll,"rotateAnchorCursor","crosshair");ps.addGetterSetter(ll,"rotationSnapTolerance",5,Hn());ps.addGetterSetter(ll,"borderEnabled",!0);ps.addGetterSetter(ll,"anchorStroke","rgb(0, 161, 255)");ps.addGetterSetter(ll,"anchorStrokeWidth",1,Hn());ps.addGetterSetter(ll,"anchorFill","white");ps.addGetterSetter(ll,"anchorCornerRadius",0,Hn());ps.addGetterSetter(ll,"borderStroke","rgb(0, 161, 255)");ps.addGetterSetter(ll,"borderStrokeWidth",1,Hn());ps.addGetterSetter(ll,"borderDash");ps.addGetterSetter(ll,"keepRatio",!0);ps.addGetterSetter(ll,"shiftBehavior","default");ps.addGetterSetter(ll,"centeredScaling",!1);ps.addGetterSetter(ll,"ignoreStroke",!1);ps.addGetterSetter(ll,"padding",0,Hn());ps.addGetterSetter(ll,"nodes");ps.addGetterSetter(ll,"node");ps.addGetterSetter(ll,"boundBoxFunc");ps.addGetterSetter(ll,"anchorDragBoundFunc");ps.addGetterSetter(ll,"anchorStyleFunc");ps.addGetterSetter(ll,"shouldOverdrawWholeArea",!1);ps.addGetterSetter(ll,"useSingleNodeRotation",!0);ps.backCompat(ll,{lineEnabled:"borderEnabled",rotateHandlerOffset:"rotateAnchorOffset",enabledHandlers:"enabledAnchors"});class jj extends On{_sceneFunc(t){t.beginPath(),t.arc(0,0,this.radius(),0,Jn.getAngle(this.angle()),this.clockwise()),t.lineTo(0,0),t.closePath(),t.fillStrokeShape(this)}getWidth(){return this.radius()*2}getHeight(){return this.radius()*2}setWidth(t){this.radius(t/2)}setHeight(t){this.radius(t/2)}}jj.prototype.className="Wedge";jj.prototype._centroid=!0;jj.prototype._attrsAffectingSize=["radius"];ju(jj);ps.addGetterSetter(jj,"radius",0,Hn());ps.addGetterSetter(jj,"angle",0,Hn());ps.addGetterSetter(jj,"clockwise",!1);ps.backCompat(jj,{angleDeg:"angle",getAngleDeg:"getAngle",setAngleDeg:"setAngle"});function Tze(){this.r=0,this.g=0,this.b=0,this.a=0,this.next=null}const gas=[512,512,456,512,328,456,335,512,405,328,271,456,388,335,292,512,454,405,364,328,298,271,496,456,420,388,360,335,312,292,273,512,482,454,428,405,383,364,345,328,312,298,284,271,259,496,475,456,437,420,404,388,374,360,347,335,323,312,302,292,282,273,265,512,497,482,468,454,441,428,417,405,394,383,373,364,354,345,337,328,320,312,305,298,291,284,278,271,265,259,507,496,485,475,465,456,446,437,428,420,412,404,396,388,381,374,367,360,354,347,341,335,329,323,318,312,307,302,297,292,287,282,278,273,269,265,261,512,505,497,489,482,475,468,461,454,447,441,435,428,422,417,411,405,399,394,389,383,378,373,368,364,359,354,350,345,341,337,332,328,324,320,316,312,309,305,301,298,294,291,287,284,281,278,274,271,268,265,262,259,257,507,501,496,491,485,480,475,470,465,460,456,451,446,442,437,433,428,424,420,416,412,408,404,400,396,392,388,385,381,377,374,370,367,363,360,357,354,350,347,344,341,338,335,332,329,326,323,320,318,315,312,310,307,304,302,299,297,294,292,289,287,285,282,280,278,275,273,271,269,267,265,263,261,259],xas=[9,11,12,13,13,14,14,15,15,15,15,16,16,16,16,17,17,17,17,17,17,17,18,18,18,18,18,18,18,18,18,19,19,19,19,19,19,19,19,19,19,19,19,19,19,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24];function yas(s,t){const r=s.data,n=s.width,a=s.height;let i,l,o,c,d,h,m,p,x,y,_,b,j,k,T,E,A,D,R,z;const O=t+t+1,$=n-1,ee=a-1,Z=t+1,J=Z*(Z+1)/2,K=new Tze,re=gas[t],ie=xas[t];let ce=null,ne=K,le=null,be=null;for(let fe=1;fe>ie,R!==0?(R=255/R,r[l]=(c*re>>ie)*R,r[l+1]=(d*re>>ie)*R,r[l+2]=(h*re>>ie)*R):r[l]=r[l+1]=r[l+2]=0,c-=p,d-=x,h-=y,m-=_,p-=le.r,x-=le.g,y-=le.b,_-=le.a,i=o+((i=je+t+1)<$?i:$)<<2,b+=le.r=r[i],j+=le.g=r[i+1],k+=le.b=r[i+2],T+=le.a=r[i+3],c+=b,d+=j,h+=k,m+=T,le=le.next,p+=E=be.r,x+=A=be.g,y+=D=be.b,_+=R=be.a,b-=E,j-=A,k-=D,T-=R,be=be.next,l+=4;o+=n}for(let fe=0;fe>ie,R>0?(R=255/R,r[i]=(c*re>>ie)*R,r[i+1]=(d*re>>ie)*R,r[i+2]=(h*re>>ie)*R):r[i]=r[i+1]=r[i+2]=0,c-=p,d-=x,h-=y,m-=_,p-=le.r,x-=le.g,y-=le.b,_-=le.a,i=fe+((i=ve+Z)0&&yas(t,r)};ps.addGetterSetter(aa,"blurRadius",0,Hn(),ps.afterSetFilter);const bas=function(s){const t=this.brightness()*255,r=s.data,n=r.length;for(let a=0;a255?255:a,i=i<0?0:i>255?255:i,l=l<0?0:l>255?255:l,r[o]=a,r[o+1]=i,r[o+2]=l};ps.addGetterSetter(aa,"contrast",0,Hn(),ps.afterSetFilter);const jas=function(s){var t,r,n,a,i,l,o,c,d;const h=s.data,m=s.width,p=s.height,x=Math.min(1,Math.max(0,(r=(t=this.embossStrength)===null||t===void 0?void 0:t.call(this))!==null&&r!==void 0?r:.5)),y=Math.min(1,Math.max(0,(a=(n=this.embossWhiteLevel)===null||n===void 0?void 0:n.call(this))!==null&&a!==void 0?a:.5)),b=(o={"top-left":315,top:270,"top-right":225,right:180,"bottom-right":135,bottom:90,"bottom-left":45,left:0}[(l=(i=this.embossDirection)===null||i===void 0?void 0:i.call(this))!==null&&l!==void 0?l:"top-left"])!==null&&o!==void 0?o:315,j=!!((d=(c=this.embossBlend)===null||c===void 0?void 0:c.call(this))!==null&&d!==void 0&&d),k=x*10,T=y*255,E=b*Math.PI/180,A=Math.cos(E),D=Math.sin(E),R=128/1020*k,z=new Uint8ClampedArray(h),O=new Float32Array(m*p);for(let K=0,re=0;reK<0?0:K>255?255:K;for(let K=1;Ka&&(a=i),c=t[T+1],co&&(o=c),m=t[T+2],mh&&(h=m);a===n&&(a=255,n=0),o===l&&(o=255,l=0),h===d&&(h=255,d=0);let x,y,_,b,j,k;if(p>0)x=a+p*(255-a),y=n-p*(n-0),_=o+p*(255-o),b=l-p*(l-0),j=h+p*(255-h),k=d-p*(d-0);else{const T=(a+n)*.5;x=a+p*(a-T),y=n+p*(n-T);const E=(o+l)*.5;_=o+p*(o-E),b=l+p*(l-E);const A=(h+d)*.5;j=h+p*(h-A),k=d+p*(d-A)}for(let T=0;Td?p:d;const x=l,y=i,_=360/y*Math.PI/180;for(let b=0;bd?p:d;const x=l,y=i,_=0;let b,j;for(h=0;ht&&(E=T,A=0,D=-1),a=0;a=0&&x=0&&y=0&&x=0&&y=255*4?255:0}return l}function Oas(s,t,r){const n=[.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111],a=Math.round(Math.sqrt(n.length)),i=Math.floor(a/2),l=[];for(let o=0;o=0&&x=0&&y=r))for(let T=_;T=n)continue;const E=(r*T+k)*4;d+=l[E+0],h+=l[E+1],m+=l[E+2],p+=l[E+3],j+=1}d=d/j,h=h/j,m=m/j,p=p/j;for(let k=x;k=r))for(let T=_;T=n)continue;const E=(r*T+k)*4;l[E+0]=d,l[E+1]=h,l[E+2]=m,l[E+3]=p}}};ps.addGetterSetter(aa,"pixelSize",8,Hn(),ps.afterSetFilter);const $as=function(s){const t=Math.round(this.levels()*254)+1,r=s.data,n=r.length,a=255/t;for(let i=0;i255?255:s<0?0:Math.round(s)});ps.addGetterSetter(aa,"green",0,function(s){return this._filterUpToDate=!1,s>255?255:s<0?0:Math.round(s)});ps.addGetterSetter(aa,"blue",0,Hdt,ps.afterSetFilter);const qas=function(s){const t=s.data,r=t.length,n=this.red(),a=this.green(),i=this.blue(),l=this.alpha();for(let o=0;o255?255:s<0?0:Math.round(s)});ps.addGetterSetter(aa,"green",0,function(s){return this._filterUpToDate=!1,s>255?255:s<0?0:Math.round(s)});ps.addGetterSetter(aa,"blue",0,Hdt,ps.afterSetFilter);ps.addGetterSetter(aa,"alpha",1,function(s){return this._filterUpToDate=!1,s>1?1:s<0?0:s});const Vas=function(s){const t=s.data,r=t.length;for(let n=0;n=128&&(r[n]=255-a,r[n+1]=255-i,r[n+2]=255-l)}return s},Gas=function(s){const t=this.threshold()*255,r=s.data,n=r.length;for(let a=0;arr||Ke[Qt]!==ft[rr]){var Ir=` `+Ke[Qt].replace(" at new "," at ");return W.displayName&&Ir.includes("")&&(Ir=Ir.replace("",W.displayName)),Ir}while(1<=Qt&&0<=rr);break}}}finally{fn=!1,Error.prepareStackTrace=_e}return(W=W?W.displayName||W.name:"")?Gr(W):""}var Sn=Object.prototype.hasOwnProperty,Aa=[],vo=-1;function fo(W){return{current:W}}function ai(W){0>vo||(W.current=Aa[vo],Aa[vo]=null,vo--)}function Cn(W,X){vo++,Aa[vo]=W.current,W.current=X}var Wi={},Ki=fo(Wi),ii=fo(!1),Ji=Wi;function co(W,X){var _e=W.type.contextTypes;if(!_e)return Wi;var Be=W.stateNode;if(Be&&Be.__reactInternalMemoizedUnmaskedChildContext===X)return Be.__reactInternalMemoizedMaskedChildContext;var Ke={},ft;for(ft in _e)Ke[ft]=X[ft];return Be&&(W=W.stateNode,W.__reactInternalMemoizedUnmaskedChildContext=X,W.__reactInternalMemoizedMaskedChildContext=Ke),Ke}function ia(W){return W=W.childContextTypes,W!=null}function hr(){ai(ii),ai(Ki)}function Sa(W,X,_e){if(Ki.current!==Wi)throw Error(l(168));Cn(Ki,X),Cn(ii,_e)}function Yi(W,X,_e){var Be=W.stateNode;if(X=X.childContextTypes,typeof Be.getChildContext!="function")return _e;Be=Be.getChildContext();for(var Ke in Be)if(!(Ke in X))throw Error(l(108,z(W)||"Unknown",Ke));return i({},_e,Be)}function $o(W){return W=(W=W.stateNode)&&W.__reactInternalMemoizedMergedChildContext||Wi,Ji=Ki.current,Cn(Ki,W),Cn(ii,ii.current),!0}function cl(W,X,_e){var Be=W.stateNode;if(!Be)throw Error(l(169));_e?(W=Yi(W,X,Ji),Be.__reactInternalMemoizedMergedChildContext=W,ai(ii),ai(Ki),Cn(Ki,W)):ai(ii),Cn(ii,_e)}var bo=Math.clz32?Math.clz32:Yf,md=Math.log,Nu=Math.LN2;function Yf(W){return W>>>=0,W===0?32:31-(md(W)/Nu|0)|0}var ku=64,$h=4194304;function Su(W){switch(W&-W){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 W&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return W&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return W}}function Ad(W,X){var _e=W.pendingLanes;if(_e===0)return 0;var Be=0,Ke=W.suspendedLanes,ft=W.pingedLanes,Qt=_e&268435455;if(Qt!==0){var rr=Qt&~Ke;rr!==0?Be=Su(rr):(ft&=Qt,ft!==0&&(Be=Su(ft)))}else Qt=_e&~Ke,Qt!==0?Be=Su(Qt):ft!==0&&(Be=Su(ft));if(Be===0)return 0;if(X!==0&&X!==Be&&!(X&Ke)&&(Ke=Be&-Be,ft=X&-X,Ke>=ft||Ke===16&&(ft&4194240)!==0))return X;if(Be&4&&(Be|=_e&16),X=W.entangledLanes,X!==0)for(W=W.entanglements,X&=Be;0_e;_e++)X.push(W);return X}function Zf(W,X,_e){W.pendingLanes|=X,X!==536870912&&(W.suspendedLanes=0,W.pingedLanes=0),W=W.eventTimes,X=31-bo(X),W[X]=_e}function Ju(W,X){var _e=W.pendingLanes&~X;W.pendingLanes=X,W.suspendedLanes=0,W.pingedLanes=0,W.expiredLanes&=X,W.mutableReadLanes&=X,W.entangledLanes&=X,X=W.entanglements;var Be=W.eventTimes;for(W=W.expirationTimes;0<_e;){var Ke=31-bo(_e),ft=1<>=Qt,Ke-=Qt,Ac=1<<32-bo(X)+Ke|_e<Zi?(Rd=Ya,Ya=null):Rd=Ya.sibling;var qo=ha(Tr,Ya,Qs[Zi],ja);if(qo===null){Ya===null&&(Ya=Rd);break}W&&Ya&&qo.alternate===null&&X(Tr,Ya),Ps=ft(qo,Ps,Zi),Ei===null?Da=qo:Ei.sibling=qo,Ei=qo,Ya=Rd}if(Zi===Qs.length)return _e(Tr,Ya),sa&&hf(Tr,Zi),Da;if(Ya===null){for(;ZiZi?(Rd=Ya,Ya=null):Rd=Ya.sibling;var Og=ha(Tr,Ya,qo.value,ja);if(Og===null){Ya===null&&(Ya=Rd);break}W&&Ya&&Og.alternate===null&&X(Tr,Ya),Ps=ft(Og,Ps,Zi),Ei===null?Da=Og:Ei.sibling=Og,Ei=Og,Ya=Rd}if(qo.done)return _e(Tr,Ya),sa&&hf(Tr,Zi),Da;if(Ya===null){for(;!qo.done;Zi++,qo=Qs.next())qo=eo(Tr,qo.value,ja),qo!==null&&(Ps=ft(qo,Ps,Zi),Ei===null?Da=qo:Ei.sibling=qo,Ei=qo);return sa&&hf(Tr,Zi),Da}for(Ya=Be(Tr,Ya);!qo.done;Zi++,qo=Qs.next())qo=lc(Ya,Tr,Zi,qo.value,ja),qo!==null&&(W&&qo.alternate!==null&&Ya.delete(qo.key===null?Zi:qo.key),Ps=ft(qo,Ps,Zi),Ei===null?Da=qo:Ei.sibling=qo,Ei=qo);return W&&Ya.forEach(function(T4){return X(Tr,T4)}),sa&&hf(Tr,Zi),Da}function jf(Tr,Ps,Qs,ja){if(typeof Qs=="object"&&Qs!==null&&Qs.type===h&&Qs.key===null&&(Qs=Qs.props.children),typeof Qs=="object"&&Qs!==null){switch(Qs.$$typeof){case c:e:{for(var Da=Qs.key,Ei=Ps;Ei!==null;){if(Ei.key===Da){if(Da=Qs.type,Da===h){if(Ei.tag===7){_e(Tr,Ei.sibling),Ps=Ke(Ei,Qs.props.children),Ps.return=Tr,Tr=Ps;break e}}else if(Ei.elementType===Da||typeof Da=="object"&&Da!==null&&Da.$$typeof===T&&G1(Da)===Ei.type){_e(Tr,Ei.sibling),Ps=Ke(Ei,Qs.props),Ps.ref=Op(Tr,Ei,Qs),Ps.return=Tr,Tr=Ps;break e}_e(Tr,Ei);break}else X(Tr,Ei);Ei=Ei.sibling}Qs.type===h?(Ps=es(Qs.props.children,Tr.mode,ja,Qs.key),Ps.return=Tr,Tr=Ps):(ja=Lo(Qs.type,Qs.key,Qs.props,null,Tr.mode,ja),ja.ref=Op(Tr,Ps,Qs),ja.return=Tr,Tr=ja)}return Qt(Tr);case d:e:{for(Ei=Qs.key;Ps!==null;){if(Ps.key===Ei)if(Ps.tag===4&&Ps.stateNode.containerInfo===Qs.containerInfo&&Ps.stateNode.implementation===Qs.implementation){_e(Tr,Ps.sibling),Ps=Ke(Ps,Qs.children||[]),Ps.return=Tr,Tr=Ps;break e}else{_e(Tr,Ps);break}else X(Tr,Ps);Ps=Ps.sibling}Ps=Fw(Qs,Tr.mode,ja),Ps.return=Tr,Tr=Ps}return Qt(Tr);case T:return Ei=Qs._init,jf(Tr,Ps,Ei(Qs._payload),ja)}if(re(Qs))return to(Tr,Ps,Qs,ja);if(D(Qs))return sh(Tr,Ps,Qs,ja);V0(Tr,Qs)}return typeof Qs=="string"&&Qs!==""||typeof Qs=="number"?(Qs=""+Qs,Ps!==null&&Ps.tag===6?(_e(Tr,Ps.sibling),Ps=Ke(Ps,Qs),Ps.return=Tr,Tr=Ps):(_e(Tr,Ps),Ps=pb(Qs,Tr.mode,ja),Ps.return=Tr,Tr=Ps),Qt(Tr)):_e(Tr,Ps)}return jf}var Al=Eu(!0),iM=Eu(!1),H0=fo(null),W1=null,Fp=null,Bp=null;function aw(){Bp=Fp=W1=null}function K1(W,X,_e){Ie?(Cn(H0,X._currentValue),X._currentValue=_e):(Cn(H0,X._currentValue2),X._currentValue2=_e)}function Md(W){var X=H0.current;ai(H0),Ie?W._currentValue=X:W._currentValue2=X}function Im(W,X,_e){for(;W!==null;){var Be=W.alternate;if((W.childLanes&X)!==X?(W.childLanes|=X,Be!==null&&(Be.childLanes|=X)):Be!==null&&(Be.childLanes&X)!==X&&(Be.childLanes|=X),W===_e)break;W=W.return}}function Id(W,X){W1=W,Bp=Fp=null,W=W.dependencies,W!==null&&W.firstContext!==null&&(W.lanes&X&&(Kh=!0),W.firstContext=null)}function mf(W){var X=Ie?W._currentValue:W._currentValue2;if(Bp!==W)if(W={context:W,memoizedValue:X,next:null},Fp===null){if(W1===null)throw Error(l(308));Fp=W,W1.dependencies={lanes:0,firstContext:W}}else Fp=Fp.next=W;return X}var ep=null;function yl(W){ep===null?ep=[W]:ep.push(W)}function zn(W,X,_e,Be){var Ke=X.interleaved;return Ke===null?(_e.next=_e,yl(X)):(_e.next=Ke.next,Ke.next=_e),X.interleaved=_e,Wr(W,Be)}function Wr(W,X){W.lanes|=X;var _e=W.alternate;for(_e!==null&&(_e.lanes|=X),_e=W,W=W.return;W!==null;)W.childLanes|=X,_e=W.alternate,_e!==null&&(_e.childLanes|=X),_e=W,W=W.return;return _e.tag===3?_e.stateNode:null}var sl=!1;function Gn(W){W.updateQueue={baseState:W.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function Pm(W,X){W=W.updateQueue,X.updateQueue===W&&(X.updateQueue={baseState:W.baseState,firstBaseUpdate:W.firstBaseUpdate,lastBaseUpdate:W.lastBaseUpdate,shared:W.shared,effects:W.effects})}function Hh(W,X){return{eventTime:W,lane:X,tag:0,payload:null,callback:null,next:null}}function _n(W,X,_e){var Be=W.updateQueue;if(Be===null)return null;if(Be=Be.shared,lo&2){var Ke=Be.pending;return Ke===null?X.next=X:(X.next=Ke.next,Ke.next=X),Be.pending=X,Wr(W,_e)}return Ke=Be.interleaved,Ke===null?(X.next=X,yl(Be)):(X.next=Ke.next,Ke.next=X),Be.interleaved=X,Wr(W,_e)}function G0(W,X,_e){if(X=X.updateQueue,X!==null&&(X=X.shared,(_e&4194240)!==0)){var Be=X.lanes;Be&=W.pendingLanes,_e|=Be,X.lanes=_e,Pp(W,_e)}}function iw(W,X){var _e=W.updateQueue,Be=W.alternate;if(Be!==null&&(Be=Be.updateQueue,_e===Be)){var Ke=null,ft=null;if(_e=_e.firstBaseUpdate,_e!==null){do{var Qt={eventTime:_e.eventTime,lane:_e.lane,tag:_e.tag,payload:_e.payload,callback:_e.callback,next:null};ft===null?Ke=ft=Qt:ft=ft.next=Qt,_e=_e.next}while(_e!==null);ft===null?Ke=ft=X:ft=ft.next=X}else Ke=ft=X;_e={baseState:Be.baseState,firstBaseUpdate:Ke,lastBaseUpdate:ft,shared:Be.shared,effects:Be.effects},W.updateQueue=_e;return}W=_e.lastBaseUpdate,W===null?_e.firstBaseUpdate=X:W.next=X,_e.lastBaseUpdate=X}function hv(W,X,_e,Be){var Ke=W.updateQueue;sl=!1;var ft=Ke.firstBaseUpdate,Qt=Ke.lastBaseUpdate,rr=Ke.shared.pending;if(rr!==null){Ke.shared.pending=null;var Ir=rr,Tn=Ir.next;Ir.next=null,Qt===null?ft=Tn:Qt.next=Tn,Qt=Ir;var Ia=W.alternate;Ia!==null&&(Ia=Ia.updateQueue,rr=Ia.lastBaseUpdate,rr!==Qt&&(rr===null?Ia.firstBaseUpdate=Tn:rr.next=Tn,Ia.lastBaseUpdate=Ir))}if(ft!==null){var eo=Ke.baseState;Qt=0,Ia=Tn=Ir=null,rr=ft;do{var ha=rr.lane,lc=rr.eventTime;if((Be&ha)===ha){Ia!==null&&(Ia=Ia.next={eventTime:lc,lane:0,tag:rr.tag,payload:rr.payload,callback:rr.callback,next:null});e:{var to=W,sh=rr;switch(ha=X,lc=_e,sh.tag){case 1:if(to=sh.payload,typeof to=="function"){eo=to.call(lc,eo,ha);break e}eo=to;break e;case 3:to.flags=to.flags&-65537|128;case 0:if(to=sh.payload,ha=typeof to=="function"?to.call(lc,eo,ha):to,ha==null)break e;eo=i({},eo,ha);break e;case 2:sl=!0}}rr.callback!==null&&rr.lane!==0&&(W.flags|=64,ha=Ke.effects,ha===null?Ke.effects=[rr]:ha.push(rr))}else lc={eventTime:lc,lane:ha,tag:rr.tag,payload:rr.payload,callback:rr.callback,next:null},Ia===null?(Tn=Ia=lc,Ir=eo):Ia=Ia.next=lc,Qt|=ha;if(rr=rr.next,rr===null){if(rr=Ke.shared.pending,rr===null)break;ha=rr,rr=ha.next,ha.next=null,Ke.lastBaseUpdate=ha,Ke.shared.pending=null}}while(!0);if(Ia===null&&(Ir=eo),Ke.baseState=Ir,Ke.firstBaseUpdate=Tn,Ke.lastBaseUpdate=Ia,X=Ke.shared.interleaved,X!==null){Ke=X;do Qt|=Ke.lane,Ke=Ke.next;while(Ke!==X)}else ft===null&&(Ke.shared.lanes=0);Mx|=Qt,W.lanes=Qt,W.memoizedState=eo}}function Y1(W,X,_e){if(W=X.effects,X.effects=null,W!==null)for(X=0;X_e?_e:4,W(!0);var Be=i4.transition;i4.transition={};try{W(!1),X()}finally{oo=_e,i4.transition=Be}}function d4(){return Mc().memoizedState}function u4(W,X,_e){var Be=Dg(W);if(_e={lane:Be,action:_e,hasEagerState:!1,eagerState:null,next:null},h4(W))oM(X,_e);else if(_e=zn(W,X,_e,Be),_e!==null){var Ke=th();Fm(_e,W,Be,Ke),Ko(_e,X,Be)}}function oD(W,X,_e){var Be=Dg(W),Ke={lane:Be,action:_e,hasEagerState:!1,eagerState:null,next:null};if(h4(W))oM(X,Ke);else{var ft=W.alternate;if(W.lanes===0&&(ft===null||ft.lanes===0)&&(ft=X.lastRenderedReducer,ft!==null))try{var Qt=X.lastRenderedState,rr=ft(Qt,_e);if(Ke.hasEagerState=!0,Ke.eagerState=rr,Cm(rr,Qt)){var Ir=X.interleaved;Ir===null?(Ke.next=Ke,yl(X)):(Ke.next=Ir.next,Ir.next=Ke),X.interleaved=Ke;return}}catch{}finally{}_e=zn(W,X,Ke,Be),_e!==null&&(Ke=th(),Fm(_e,W,Be,Ke),Ko(_e,X,Be))}}function h4(W){var X=W.alternate;return W===Bl||X!==null&&X===Bl}function oM(W,X){rp=Z1=!0;var _e=W.pending;_e===null?X.next=X:(X.next=_e.next,_e.next=X),W.pending=X}function Ko(W,X,_e){if(_e&4194240){var Be=X.lanes;Be&=W.pendingLanes,_e|=Be,X.lanes=_e,Pp(W,_e)}}var fw={readContext:mf,useCallback:wh,useContext:wh,useEffect:wh,useImperativeHandle:wh,useInsertionEffect:wh,useLayoutEffect:wh,useMemo:wh,useReducer:wh,useRef:wh,useState:wh,useDebugValue:wh,useDeferredValue:wh,useTransition:wh,useMutableSource:wh,useSyncExternalStore:wh,useId:wh,unstable_isNewReconciler:!1},lD={readContext:mf,useCallback:function(W,X){return np().memoizedState=[W,X===void 0?null:X],W},useContext:mf,useEffect:K0,useImperativeHandle:function(W,X,_e){return _e=_e!=null?_e.concat([W]):null,hw(4194308,4,J1.bind(null,X,W),_e)},useLayoutEffect:function(W,X){return hw(4194308,4,W,X)},useInsertionEffect:function(W,X){return hw(4,2,W,X)},useMemo:function(W,X){var _e=np();return X=X===void 0?null:X,W=W(),_e.memoizedState=[W,X],W},useReducer:function(W,X,_e){var Be=np();return X=_e!==void 0?_e(X):X,Be.memoizedState=Be.baseState=X,W={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:W,lastRenderedState:X},Be.queue=W,W=W.dispatch=u4.bind(null,Bl,W),[Be.memoizedState,W]},useRef:function(W){var X=np();return W={current:W},X.memoizedState=W},useState:Dm,useDebugValue:o4,useDeferredValue:function(W){return np().memoizedState=W},useTransition:function(){var W=Dm(!1),X=W[0];return W=mi.bind(null,W[1]),np().memoizedState=W,[X,W]},useMutableSource:function(){},useSyncExternalStore:function(W,X,_e){var Be=Bl,Ke=np();if(sa){if(_e===void 0)throw Error(l(407));_e=_e()}else{if(_e=X(),tc===null)throw Error(l(349));_x&30||Ij(Be,X,_e)}Ke.memoizedState=_e;var ft={value:_e,getSnapshot:X};return Ke.queue=ft,K0(xv.bind(null,Be,ft,W),[W]),Be.flags|=2048,wx(9,gv.bind(null,Be,ft,_e,X),void 0,null),_e},useId:function(){var W=np(),X=tc.identifierPrefix;if(sa){var _e=Mm,Be=Ac;_e=(Be&~(1<<32-bo(Be)-1)).toString(32)+_e,X=":"+X+"R"+_e,_e=lw++,0<_e&&(X+="H"+_e.toString(32)),X+=":"}else _e=fv++,X=":"+X+"r"+_e.toString(32)+":";return W.memoizedState=X},unstable_isNewReconciler:!1},Lj={readContext:mf,useCallback:l4,useContext:mf,useEffect:gf,useImperativeHandle:vv,useInsertionEffect:yv,useLayoutEffect:jx,useMemo:Ig,useReducer:dw,useRef:Sr,useState:function(){return dw(pv)},useDebugValue:o4,useDeferredValue:function(W){var X=Mc();return c4(X,Pd.memoizedState,W)},useTransition:function(){var W=dw(pv)[0],X=Mc().memoizedState;return[W,X]},useMutableSource:Q1,useSyncExternalStore:Mj,useId:d4,unstable_isNewReconciler:!1},cD={readContext:mf,useCallback:l4,useContext:mf,useEffect:gf,useImperativeHandle:vv,useInsertionEffect:yv,useLayoutEffect:jx,useMemo:Ig,useReducer:Mg,useRef:Sr,useState:function(){return Mg(pv)},useDebugValue:o4,useDeferredValue:function(W){var X=Mc();return Pd===null?X.memoizedState=W:c4(X,Pd.memoizedState,W)},useTransition:function(){var W=Mg(pv)[0],X=Mc().memoizedState;return[W,X]},useMutableSource:Q1,useSyncExternalStore:Mj,useId:d4,unstable_isNewReconciler:!1};function ap(W,X){if(W&&W.defaultProps){X=i({},X),W=W.defaultProps;for(var _e in W)X[_e]===void 0&&(X[_e]=W[_e]);return X}return X}function pw(W,X,_e,Be){X=W.memoizedState,_e=_e(Be,X),_e=_e==null?X:i({},X,_e),W.memoizedState=_e,W.lanes===0&&(W.updateQueue.baseState=_e)}var bv={isMounted:function(W){return(W=W._reactInternals)?O(W)===W:!1},enqueueSetState:function(W,X,_e){W=W._reactInternals;var Be=th(),Ke=Dg(W),ft=Hh(Be,Ke);ft.payload=X,_e!=null&&(ft.callback=_e),X=_n(W,ft,Ke),X!==null&&(Fm(X,W,Ke,Be),G0(X,W,Ke))},enqueueReplaceState:function(W,X,_e){W=W._reactInternals;var Be=th(),Ke=Dg(W),ft=Hh(Be,Ke);ft.tag=1,ft.payload=X,_e!=null&&(ft.callback=_e),X=_n(W,ft,Ke),X!==null&&(Fm(X,W,Ke,Be),G0(X,W,Ke))},enqueueForceUpdate:function(W,X){W=W._reactInternals;var _e=th(),Be=Dg(W),Ke=Hh(_e,Be);Ke.tag=2,X!=null&&(Ke.callback=X),X=_n(W,Ke,Be),X!==null&&(Fm(X,W,Be,_e),G0(X,W,Be))}};function Dj(W,X,_e,Be,Ke,ft,Qt){return W=W.stateNode,typeof W.shouldComponentUpdate=="function"?W.shouldComponentUpdate(Be,ft,Qt):X.prototype&&X.prototype.isPureReactComponent?!Rp(_e,Be)||!Rp(Ke,ft):!0}function Y0(W,X,_e){var Be=!1,Ke=Wi,ft=X.contextType;return typeof ft=="object"&&ft!==null?ft=mf(ft):(Ke=ia(X)?Ji:Ki.current,Be=X.contextTypes,ft=(Be=Be!=null)?co(W,Ke):Wi),X=new X(_e,ft),W.memoizedState=X.state!==null&&X.state!==void 0?X.state:null,X.updater=bv,W.stateNode=X,X._reactInternals=W,Be&&(W=W.stateNode,W.__reactInternalMemoizedUnmaskedChildContext=Ke,W.__reactInternalMemoizedMaskedChildContext=ft),X}function Z0(W,X,_e,Be){W=X.state,typeof X.componentWillReceiveProps=="function"&&X.componentWillReceiveProps(_e,Be),typeof X.UNSAFE_componentWillReceiveProps=="function"&&X.UNSAFE_componentWillReceiveProps(_e,Be),X.state!==W&&bv.enqueueReplaceState(X,X.state,null)}function X0(W,X,_e,Be){var Ke=W.stateNode;Ke.props=_e,Ke.state=W.memoizedState,Ke.refs={},Gn(W);var ft=X.contextType;typeof ft=="object"&&ft!==null?Ke.context=mf(ft):(ft=ia(X)?Ji:Ki.current,Ke.context=co(W,ft)),Ke.state=W.memoizedState,ft=X.getDerivedStateFromProps,typeof ft=="function"&&(pw(W,X,ft,_e),Ke.state=W.memoizedState),typeof X.getDerivedStateFromProps=="function"||typeof Ke.getSnapshotBeforeUpdate=="function"||typeof Ke.UNSAFE_componentWillMount!="function"&&typeof Ke.componentWillMount!="function"||(X=Ke.state,typeof Ke.componentWillMount=="function"&&Ke.componentWillMount(),typeof Ke.UNSAFE_componentWillMount=="function"&&Ke.UNSAFE_componentWillMount(),X!==Ke.state&&bv.enqueueReplaceState(Ke,Ke.state,null),hv(W,_e,Ke,Be),Ke.state=W.memoizedState),typeof Ke.componentDidMount=="function"&&(W.flags|=4194308)}function Wh(W,X){try{var _e="",Be=X;do _e+=qi(Be),Be=Be.return;while(Be);var Ke=_e}catch(ft){Ke=` Error generating stack: `+ft.message+` `+ft.stack}return{value:W,source:X,stack:Ke,digest:null}}function Rj(W,X,_e){return{value:W,source:null,stack:_e??null,digest:X??null}}function gw(W,X){try{console.error(X.value)}catch(_e){setTimeout(function(){throw _e})}}var lM=typeof WeakMap=="function"?WeakMap:Map;function _v(W,X,_e){_e=Hh(-1,_e),_e.tag=3,_e.payload={element:null};var Be=X.value;return _e.callback=function(){Mw||(Mw=!0,Iw=Be),gw(W,X)},_e}function xw(W,X,_e){_e=Hh(-1,_e),_e.tag=3;var Be=W.type.getDerivedStateFromError;if(typeof Be=="function"){var Ke=X.value;_e.payload=function(){return Be(Ke)},_e.callback=function(){gw(W,X)}}var ft=W.stateNode;return ft!==null&&typeof ft.componentDidCatch=="function"&&(_e.callback=function(){gw(W,X),typeof Be!="function"&&(Hp===null?Hp=new Set([this]):Hp.add(this));var Qt=X.stack;this.componentDidCatch(X.value,{componentStack:Qt!==null?Qt:""})}),_e}function yw(W,X,_e){var Be=W.pingCache;if(Be===null){Be=W.pingCache=new lM;var Ke=new Set;Be.set(X,Ke)}else Ke=Be.get(X),Ke===void 0&&(Ke=new Set,Be.set(X,Ke));Ke.has(_e)||(Ke.add(_e),W=mb.bind(null,W,X,_e),X.then(W,W))}function Oj(W){do{var X;if((X=W.tag===13)&&(X=W.memoizedState,X=X!==null?X.dehydrated!==null:!0),X)return W;W=W.return}while(W!==null);return null}function vw(W,X,_e,Be,Ke){return W.mode&1?(W.flags|=65536,W.lanes=Ke,W):(W===X?W.flags|=65536:(W.flags|=128,_e.flags|=131072,_e.flags&=-52805,_e.tag===1&&(_e.alternate===null?_e.tag=17:(X=Hh(-1,1),X.tag=2,_n(_e,X,1))),_e.lanes|=1),W)}var bw=o.ReactCurrentOwner,Kh=!1;function jh(W,X,_e,Be){X.child=W===null?iM(X,null,_e,Be):Al(X,W.child,_e,Be)}function m4(W,X,_e,Be,Ke){_e=_e.render;var ft=X.ref;return Id(X,Ke),Be=cw(W,X,_e,Be,ft,Ke),_e=X1(),W!==null&&!Kh?(X.updateQueue=W.updateQueue,X.flags&=-2053,W.lanes&=~Ke,xf(W,X,Ke)):(sa&&_e&&tr(X),X.flags|=1,jh(W,X,Be,Ke),X.child)}function wv(W,X,_e,Be,Ke){if(W===null){var ft=_e.type;return typeof ft=="function"&&!ur(ft)&&ft.defaultProps===void 0&&_e.compare===null&&_e.defaultProps===void 0?(X.tag=15,X.type=ft,f4(W,X,ft,Be,Ke)):(W=Lo(_e.type,null,Be,X,X.mode,Ke),W.ref=X.ref,W.return=X,X.child=W)}if(ft=W.child,!(W.lanes&Ke)){var Qt=ft.memoizedProps;if(_e=_e.compare,_e=_e!==null?_e:Rp,_e(Qt,Be)&&W.ref===X.ref)return xf(W,X,Ke)}return X.flags|=1,W=wf(ft,Be),W.ref=X.ref,W.return=X,X.child=W}function f4(W,X,_e,Be,Ke){if(W!==null){var ft=W.memoizedProps;if(Rp(ft,Be)&&W.ref===X.ref)if(Kh=!1,X.pendingProps=Be=ft,(W.lanes&Ke)!==0)W.flags&131072&&(Kh=!0);else return X.lanes=W.lanes,xf(W,X,Ke)}return p4(W,X,_e,Be,Ke)}function cM(W,X,_e){var Be=X.pendingProps,Ke=Be.children,ft=W!==null?W.memoizedState:null;if(Be.mode==="hidden")if(!(X.mode&1))X.memoizedState={baseLanes:0,cachePool:null,transitions:null},Cn(Ax,Nh),Nh|=_e;else{if(!(_e&1073741824))return W=ft!==null?ft.baseLanes|_e:_e,X.lanes=X.childLanes=1073741824,X.memoizedState={baseLanes:W,cachePool:null,transitions:null},X.updateQueue=null,Cn(Ax,Nh),Nh|=W,null;X.memoizedState={baseLanes:0,cachePool:null,transitions:null},Be=ft!==null?ft.baseLanes:_e,Cn(Ax,Nh),Nh|=Be}else ft!==null?(Be=ft.baseLanes|_e,X.memoizedState=null):Be=_e,Cn(Ax,Nh),Nh|=Be;return jh(W,X,Ke,_e),X.child}function dM(W,X){var _e=X.ref;(W===null&&_e!==null||W!==null&&W.ref!==_e)&&(X.flags|=512,X.flags|=2097152)}function p4(W,X,_e,Be,Ke){var ft=ia(_e)?Ji:Ki.current;return ft=co(X,ft),Id(X,Ke),_e=cw(W,X,_e,Be,ft,Ke),Be=X1(),W!==null&&!Kh?(X.updateQueue=W.updateQueue,X.flags&=-2053,W.lanes&=~Ke,xf(W,X,Ke)):(sa&&Be&&tr(X),X.flags|=1,jh(W,X,_e,Ke),X.child)}function Fj(W,X,_e,Be,Ke){if(ia(_e)){var ft=!0;$o(X)}else ft=!1;if(Id(X,Ke),X.stateNode===null)kv(W,X),Y0(X,_e,Be),X0(X,_e,Be,Ke),Be=!0;else if(W===null){var Qt=X.stateNode,rr=X.memoizedProps;Qt.props=rr;var Ir=Qt.context,Tn=_e.contextType;typeof Tn=="object"&&Tn!==null?Tn=mf(Tn):(Tn=ia(_e)?Ji:Ki.current,Tn=co(X,Tn));var Ia=_e.getDerivedStateFromProps,eo=typeof Ia=="function"||typeof Qt.getSnapshotBeforeUpdate=="function";eo||typeof Qt.UNSAFE_componentWillReceiveProps!="function"&&typeof Qt.componentWillReceiveProps!="function"||(rr!==Be||Ir!==Tn)&&Z0(X,Qt,Be,Tn),sl=!1;var ha=X.memoizedState;Qt.state=ha,hv(X,Be,Qt,Ke),Ir=X.memoizedState,rr!==Be||ha!==Ir||ii.current||sl?(typeof Ia=="function"&&(pw(X,_e,Ia,Be),Ir=X.memoizedState),(rr=sl||Dj(X,_e,rr,Be,ha,Ir,Tn))?(eo||typeof Qt.UNSAFE_componentWillMount!="function"&&typeof Qt.componentWillMount!="function"||(typeof Qt.componentWillMount=="function"&&Qt.componentWillMount(),typeof Qt.UNSAFE_componentWillMount=="function"&&Qt.UNSAFE_componentWillMount()),typeof Qt.componentDidMount=="function"&&(X.flags|=4194308)):(typeof Qt.componentDidMount=="function"&&(X.flags|=4194308),X.memoizedProps=Be,X.memoizedState=Ir),Qt.props=Be,Qt.state=Ir,Qt.context=Tn,Be=rr):(typeof Qt.componentDidMount=="function"&&(X.flags|=4194308),Be=!1)}else{Qt=X.stateNode,Pm(W,X),rr=X.memoizedProps,Tn=X.type===X.elementType?rr:ap(X.type,rr),Qt.props=Tn,eo=X.pendingProps,ha=Qt.context,Ir=_e.contextType,typeof Ir=="object"&&Ir!==null?Ir=mf(Ir):(Ir=ia(_e)?Ji:Ki.current,Ir=co(X,Ir));var lc=_e.getDerivedStateFromProps;(Ia=typeof lc=="function"||typeof Qt.getSnapshotBeforeUpdate=="function")||typeof Qt.UNSAFE_componentWillReceiveProps!="function"&&typeof Qt.componentWillReceiveProps!="function"||(rr!==eo||ha!==Ir)&&Z0(X,Qt,Be,Ir),sl=!1,ha=X.memoizedState,Qt.state=ha,hv(X,Be,Qt,Ke);var to=X.memoizedState;rr!==eo||ha!==to||ii.current||sl?(typeof lc=="function"&&(pw(X,_e,lc,Be),to=X.memoizedState),(Tn=sl||Dj(X,_e,Tn,Be,ha,to,Ir)||!1)?(Ia||typeof Qt.UNSAFE_componentWillUpdate!="function"&&typeof Qt.componentWillUpdate!="function"||(typeof Qt.componentWillUpdate=="function"&&Qt.componentWillUpdate(Be,to,Ir),typeof Qt.UNSAFE_componentWillUpdate=="function"&&Qt.UNSAFE_componentWillUpdate(Be,to,Ir)),typeof Qt.componentDidUpdate=="function"&&(X.flags|=4),typeof Qt.getSnapshotBeforeUpdate=="function"&&(X.flags|=1024)):(typeof Qt.componentDidUpdate!="function"||rr===W.memoizedProps&&ha===W.memoizedState||(X.flags|=4),typeof Qt.getSnapshotBeforeUpdate!="function"||rr===W.memoizedProps&&ha===W.memoizedState||(X.flags|=1024),X.memoizedProps=Be,X.memoizedState=to),Qt.props=Be,Qt.state=to,Qt.context=Ir,Be=Tn):(typeof Qt.componentDidUpdate!="function"||rr===W.memoizedProps&&ha===W.memoizedState||(X.flags|=4),typeof Qt.getSnapshotBeforeUpdate!="function"||rr===W.memoizedProps&&ha===W.memoizedState||(X.flags|=1024),Be=!1)}return _w(W,X,_e,Be,ft,Ke)}function _w(W,X,_e,Be,Ke,ft){dM(W,X);var Qt=(X.flags&128)!==0;if(!Be&&!Qt)return Ke&&cl(X,_e,!1),xf(W,X,ft);Be=X.stateNode,bw.current=X;var rr=Qt&&typeof _e.getDerivedStateFromError!="function"?null:Be.render();return X.flags|=1,W!==null&&Qt?(X.child=Al(X,W.child,null,ft),X.child=Al(X,null,rr,ft)):jh(W,X,rr,ft),X.memoizedState=Be.state,Ke&&cl(X,_e,!0),X.child}function eb(W){var X=W.stateNode;X.pendingContext?Sa(W,X.pendingContext,X.pendingContext!==X.context):X.context&&Sa(W,X.context,!1),wc(W,X.containerInfo)}function jv(W,X,_e,Be,Ke){return wi(),Oi(Ke),X.flags|=256,jh(W,X,_e,Be),X.child}var ww={dehydrated:null,treeContext:null,retryLane:0};function Bj(W){return{baseLanes:W,cachePool:null,transitions:null}}function uM(W,X,_e){var Be=X.pendingProps,Ke=Wl.current,ft=!1,Qt=(X.flags&128)!==0,rr;if((rr=Qt)||(rr=W!==null&&W.memoizedState===null?!1:(Ke&2)!==0),rr?(ft=!0,X.flags&=-129):(W===null||W.memoizedState!==null)&&(Ke|=1),Cn(Wl,Ke&1),W===null)return Tu(X),W=X.memoizedState,W!==null&&(W=W.dehydrated,W!==null)?(X.mode&1?Hr(W)?X.lanes=8:X.lanes=1073741824:X.lanes=1,null):(Qt=Be.children,W=Be.fallback,ft?(Be=X.mode,ft=X.child,Qt={mode:"hidden",children:Qt},!(Be&1)&&ft!==null?(ft.childLanes=0,ft.pendingProps=Qt):ft=Ow(Qt,Be,0,null),W=es(W,Be,_e,null),ft.return=X,W.return=X,ft.sibling=W,X.child=ft,X.child.memoizedState=Bj(_e),X.memoizedState=ww,W):Nv(X,Qt));if(Ke=W.memoizedState,Ke!==null&&(rr=Ke.dehydrated,rr!==null))return g4(W,X,Qt,Be,rr,Ke,_e);if(ft){ft=Be.fallback,Qt=X.mode,Ke=W.child,rr=Ke.sibling;var Ir={mode:"hidden",children:Be.children};return!(Qt&1)&&X.child!==Ke?(Be=X.child,Be.childLanes=0,Be.pendingProps=Ir,X.deletions=null):(Be=wf(Ke,Ir),Be.subtreeFlags=Ke.subtreeFlags&14680064),rr!==null?ft=wf(rr,ft):(ft=es(ft,Qt,_e,null),ft.flags|=2),ft.return=X,Be.return=X,Be.sibling=ft,X.child=Be,Be=ft,ft=X.child,Qt=W.child.memoizedState,Qt=Qt===null?Bj(_e):{baseLanes:Qt.baseLanes|_e,cachePool:null,transitions:Qt.transitions},ft.memoizedState=Qt,ft.childLanes=W.childLanes&~_e,X.memoizedState=ww,Be}return ft=W.child,W=ft.sibling,Be=wf(ft,{mode:"visible",children:Be.children}),!(X.mode&1)&&(Be.lanes=_e),Be.return=X,Be.sibling=null,W!==null&&(_e=X.deletions,_e===null?(X.deletions=[W],X.flags|=16):_e.push(W)),X.child=Be,X.memoizedState=null,Be}function Nv(W,X){return X=Ow({mode:"visible",children:X},W.mode,0,null),X.return=W,W.child=X}function Nx(W,X,_e,Be){return Be!==null&&Oi(Be),Al(X,W.child,null,_e),W=Nv(X,X.pendingProps.children),W.flags|=2,X.memoizedState=null,W}function g4(W,X,_e,Be,Ke,ft,Qt){if(_e)return X.flags&256?(X.flags&=-257,Be=Rj(Error(l(422))),Nx(W,X,Qt,Be)):X.memoizedState!==null?(X.child=W.child,X.flags|=128,null):(ft=Be.fallback,Ke=X.mode,Be=Ow({mode:"visible",children:Be.children},Ke,0,null),ft=es(ft,Ke,Qt,null),ft.flags|=2,Be.return=X,ft.return=X,Be.sibling=ft,X.child=Be,X.mode&1&&Al(X,W.child,null,Qt),X.child.memoizedState=Bj(Qt),X.memoizedState=ww,ft);if(!(X.mode&1))return Nx(W,X,Qt,null);if(Hr(Ke))return Be=_a(Ke).digest,ft=Error(l(419)),Be=Rj(ft,Be,void 0),Nx(W,X,Qt,Be);if(_e=(Qt&W.childLanes)!==0,Kh||_e){if(Be=tc,Be!==null){switch(Qt&-Qt){case 4:Ke=2;break;case 16:Ke=8;break;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:Ke=32;break;case 536870912:Ke=268435456;break;default:Ke=0}Ke=Ke&(Be.suspendedLanes|Qt)?0:Ke,Ke!==0&&Ke!==ft.retryLane&&(ft.retryLane=Ke,Wr(W,Ke),Fm(Be,W,Ke,-1))}return op(),Be=Rj(Error(l(421))),Nx(W,X,Qt,Be)}return _r(Ke)?(X.flags|=128,X.child=W.child,X=Zj.bind(null,W),Jt(Ke,X),null):(W=ft.treeContext,tt&&(Mr=He(Ke),bn=X,sa=!0,Ja=null,qa=!1,W!==null&&(fd[_c++]=Ac,fd[_c++]=Mm,fd[_c++]=Am,Ac=W.id,Mm=W.overflow,Am=X)),X=Nv(X,Be.children),X.flags|=4096,X)}function Jd(W,X,_e){W.lanes|=X;var Be=W.alternate;Be!==null&&(Be.lanes|=X),Im(W.return,X,_e)}function tb(W,X,_e,Be,Ke){var ft=W.memoizedState;ft===null?W.memoizedState={isBackwards:X,rendering:null,renderingStartTime:0,last:Be,tail:_e,tailMode:Ke}:(ft.isBackwards=X,ft.rendering=null,ft.renderingStartTime=0,ft.last=Be,ft.tail=_e,ft.tailMode=Ke)}function sb(W,X,_e){var Be=X.pendingProps,Ke=Be.revealOrder,ft=Be.tail;if(jh(W,X,Be.children,_e),Be=Wl.current,Be&2)Be=Be&1|2,X.flags|=128;else{if(W!==null&&W.flags&128)e:for(W=X.child;W!==null;){if(W.tag===13)W.memoizedState!==null&&Jd(W,_e,X);else if(W.tag===19)Jd(W,_e,X);else if(W.child!==null){W.child.return=W,W=W.child;continue}if(W===X)break e;for(;W.sibling===null;){if(W.return===null||W.return===X)break e;W=W.return}W.sibling.return=W.return,W=W.sibling}Be&=1}if(Cn(Wl,Be),!(X.mode&1))X.memoizedState=null;else switch(Ke){case"forwards":for(_e=X.child,Ke=null;_e!==null;)W=_e.alternate,W!==null&&mv(W)===null&&(Ke=_e),_e=_e.sibling;_e=Ke,_e===null?(Ke=X.child,X.child=null):(Ke=_e.sibling,_e.sibling=null),tb(X,!1,Ke,_e,ft);break;case"backwards":for(_e=null,Ke=X.child,X.child=null;Ke!==null;){if(W=Ke.alternate,W!==null&&mv(W)===null){X.child=Ke;break}W=Ke.sibling,Ke.sibling=_e,_e=Ke,Ke=W}tb(X,!0,_e,null,ft);break;case"together":tb(X,!1,null,null,void 0);break;default:X.memoizedState=null}return X.child}function kv(W,X){!(X.mode&1)&&W!==null&&(W.alternate=null,X.alternate=null,X.flags|=2)}function xf(W,X,_e){if(W!==null&&(X.dependencies=W.dependencies),Mx|=X.lanes,!(_e&X.childLanes))return null;if(W!==null&&X.child!==W.child)throw Error(l(153));if(X.child!==null){for(W=X.child,_e=wf(W,W.pendingProps),X.child=_e,_e.return=X;W.sibling!==null;)W=W.sibling,_e=_e.sibling=wf(W,W.pendingProps),_e.return=X;_e.sibling=null}return X.child}function jw(W,X,_e){switch(X.tag){case 3:eb(X),wi();break;case 5:ow(X);break;case 1:ia(X.type)&&$o(X);break;case 4:wc(X,X.stateNode.containerInfo);break;case 10:K1(X,X.type._context,X.memoizedProps.value);break;case 13:var Be=X.memoizedState;if(Be!==null)return Be.dehydrated!==null?(Cn(Wl,Wl.current&1),X.flags|=128,null):_e&X.child.childLanes?uM(W,X,_e):(Cn(Wl,Wl.current&1),W=xf(W,X,_e),W!==null?W.sibling:null);Cn(Wl,Wl.current&1);break;case 19:if(Be=(_e&X.childLanes)!==0,W.flags&128){if(Be)return sb(W,X,_e);X.flags|=128}var Ke=X.memoizedState;if(Ke!==null&&(Ke.rendering=null,Ke.tail=null,Ke.lastEffect=null),Cn(Wl,Wl.current),Be)break;return null;case 22:case 23:return X.lanes=0,cM(W,X,_e)}return xf(W,X,_e)}function Rm(W){W.flags|=4}function Nw(W,X){if(W!==null&&W.child===X.child)return!0;if(X.flags&16)return!1;for(W=X.child;W!==null;){if(W.flags&12854||W.subtreeFlags&12854)return!1;W=W.sibling}return!0}var Sv,Q0,J0,rb;if(De)Sv=function(W,X){for(var _e=X.child;_e!==null;){if(_e.tag===5||_e.tag===6)je(W,_e.stateNode);else if(_e.tag!==4&&_e.child!==null){_e.child.return=_e,_e=_e.child;continue}if(_e===X)break;for(;_e.sibling===null;){if(_e.return===null||_e.return===X)return;_e=_e.return}_e.sibling.return=_e.return,_e=_e.sibling}},Q0=function(){},J0=function(W,X,_e,Be,Ke){if(W=W.memoizedProps,W!==Be){var ft=X.stateNode,Qt=Lm(tp.current);_e=We(ft,_e,W,Be,Ke,Qt),(X.updateQueue=_e)&&Rm(X)}},rb=function(W,X,_e,Be){_e!==Be&&Rm(X)};else if(pe){Sv=function(W,X,_e,Be){for(var Ke=X.child;Ke!==null;){if(Ke.tag===5){var ft=Ke.stateNode;_e&&Be&&(ft=cr(ft,Ke.type,Ke.memoizedProps,Ke)),je(W,ft)}else if(Ke.tag===6)ft=Ke.stateNode,_e&&Be&&(ft=on(ft,Ke.memoizedProps,Ke)),je(W,ft);else if(Ke.tag!==4){if(Ke.tag===22&&Ke.memoizedState!==null)ft=Ke.child,ft!==null&&(ft.return=Ke),Sv(W,Ke,!0,!0);else if(Ke.child!==null){Ke.child.return=Ke,Ke=Ke.child;continue}}if(Ke===X)break;for(;Ke.sibling===null;){if(Ke.return===null||Ke.return===X)return;Ke=Ke.return}Ke.sibling.return=Ke.return,Ke=Ke.sibling}};var x4=function(W,X,_e,Be){for(var Ke=X.child;Ke!==null;){if(Ke.tag===5){var ft=Ke.stateNode;_e&&Be&&(ft=cr(ft,Ke.type,Ke.memoizedProps,Ke)),$r(W,ft)}else if(Ke.tag===6)ft=Ke.stateNode,_e&&Be&&(ft=on(ft,Ke.memoizedProps,Ke)),$r(W,ft);else if(Ke.tag!==4){if(Ke.tag===22&&Ke.memoizedState!==null)ft=Ke.child,ft!==null&&(ft.return=Ke),x4(W,Ke,!0,!0);else if(Ke.child!==null){Ke.child.return=Ke,Ke=Ke.child;continue}}if(Ke===X)break;for(;Ke.sibling===null;){if(Ke.return===null||Ke.return===X)return;Ke=Ke.return}Ke.sibling.return=Ke.return,Ke=Ke.sibling}};Q0=function(W,X){var _e=X.stateNode;if(!Nw(W,X)){W=_e.containerInfo;var Be=Vr(W);x4(Be,X,!1,!1),_e.pendingChildren=Be,Rm(X),hn(W,Be)}},J0=function(W,X,_e,Be,Ke){var ft=W.stateNode,Qt=W.memoizedProps;if((W=Nw(W,X))&&Qt===Be)X.stateNode=ft;else{var rr=X.stateNode,Ir=Lm(tp.current),Tn=null;Qt!==Be&&(Tn=We(rr,_e,Qt,Be,Ke,Ir)),W&&Tn===null?X.stateNode=ft:(ft=sn(ft,Tn,_e,Qt,Be,X,W,rr),ve(ft,_e,Be,Ke,Ir)&&Rm(X),X.stateNode=ft,W?Rm(X):Sv(ft,X,!1,!1))}},rb=function(W,X,_e,Be){_e!==Be?(W=Lm(sp.current),_e=Lm(tp.current),X.stateNode=Le(Be,W,_e,X),Rm(X)):X.stateNode=W.stateNode}}else Q0=function(){},J0=function(){},rb=function(){};function nb(W,X){if(!sa)switch(W.tailMode){case"hidden":X=W.tail;for(var _e=null;X!==null;)X.alternate!==null&&(_e=X),X=X.sibling;_e===null?W.tail=null:_e.sibling=null;break;case"collapsed":_e=W.tail;for(var Be=null;_e!==null;)_e.alternate!==null&&(Be=_e),_e=_e.sibling;Be===null?X||W.tail===null?W.tail=null:W.tail.sibling=null:Be.sibling=null}}function Wc(W){var X=W.alternate!==null&&W.alternate.child===W.child,_e=0,Be=0;if(X)for(var Ke=W.child;Ke!==null;)_e|=Ke.lanes|Ke.childLanes,Be|=Ke.subtreeFlags&14680064,Be|=Ke.flags&14680064,Ke.return=W,Ke=Ke.sibling;else for(Ke=W.child;Ke!==null;)_e|=Ke.lanes|Ke.childLanes,Be|=Ke.subtreeFlags,Be|=Ke.flags,Ke.return=W,Ke=Ke.sibling;return W.subtreeFlags|=Be,W.childLanes=_e,X}function hM(W,X,_e){var Be=X.pendingProps;switch(kr(X),X.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return Wc(X),null;case 1:return ia(X.type)&&hr(),Wc(X),null;case 3:return _e=X.stateNode,ff(),ai(ii),ai(Ki),pf(),_e.pendingContext&&(_e.context=_e.pendingContext,_e.pendingContext=null),(W===null||W.child===null)&&(Jf(X)?Rm(X):W===null||W.memoizedState.isDehydrated&&!(X.flags&256)||(X.flags|=1024,Ja!==null&&(_4(Ja),Ja=null))),Q0(W,X),Wc(X),null;case 5:Tj(X),_e=Lm(sp.current);var Ke=X.type;if(W!==null&&X.stateNode!=null)J0(W,X,Ke,Be,_e),W.ref!==X.ref&&(X.flags|=512,X.flags|=2097152);else{if(!Be){if(X.stateNode===null)throw Error(l(166));return Wc(X),null}if(W=Lm(tp.current),Jf(X)){if(!tt)throw Error(l(175));W=ot(X.stateNode,X.type,X.memoizedProps,_e,W,X,!qa),X.updateQueue=W,W!==null&&Rm(X)}else{var ft=fe(Ke,Be,_e,W,X);Sv(ft,X,!1,!1),X.stateNode=ft,ve(ft,Ke,Be,_e,W)&&Rm(X)}X.ref!==null&&(X.flags|=512,X.flags|=2097152)}return Wc(X),null;case 6:if(W&&X.stateNode!=null)rb(W,X,W.memoizedProps,Be);else{if(typeof Be!="string"&&X.stateNode===null)throw Error(l(166));if(W=Lm(sp.current),_e=Lm(tp.current),Jf(X)){if(!tt)throw Error(l(176));if(W=X.stateNode,_e=X.memoizedProps,(Be=jt(W,_e,X,!qa))&&(Ke=bn,Ke!==null))switch(Ke.tag){case 3:Er(Ke.stateNode.containerInfo,W,_e,(Ke.mode&1)!==0);break;case 5:ln(Ke.type,Ke.memoizedProps,Ke.stateNode,W,_e,(Ke.mode&1)!==0)}Be&&Rm(X)}else X.stateNode=Le(Be,W,_e,X)}return Wc(X),null;case 13:if(ai(Wl),Be=X.memoizedState,W===null||W.memoizedState!==null&&W.memoizedState.dehydrated!==null){if(sa&&Mr!==null&&X.mode&1&&!(X.flags&128))un(),wi(),X.flags|=98560,Ke=!1;else if(Ke=Jf(X),Be!==null&&Be.dehydrated!==null){if(W===null){if(!Ke)throw Error(l(318));if(!tt)throw Error(l(344));if(Ke=X.memoizedState,Ke=Ke!==null?Ke.dehydrated:null,!Ke)throw Error(l(317));Dt(Ke,X)}else wi(),!(X.flags&128)&&(X.memoizedState=null),X.flags|=4;Wc(X),Ke=!1}else Ja!==null&&(_4(Ja),Ja=null),Ke=!0;if(!Ke)return X.flags&65536?X:null}return X.flags&128?(X.lanes=_e,X):(_e=Be!==null,_e!==(W!==null&&W.memoizedState!==null)&&_e&&(X.child.flags|=8192,X.mode&1&&(W===null||Wl.current&1?Kc===0&&(Kc=3):op())),X.updateQueue!==null&&(X.flags|=4),Wc(X),null);case 4:return ff(),Q0(W,X),W===null&&ct(X.stateNode.containerInfo),Wc(X),null;case 10:return Md(X.type._context),Wc(X),null;case 17:return ia(X.type)&&hr(),Wc(X),null;case 19:if(ai(Wl),Ke=X.memoizedState,Ke===null)return Wc(X),null;if(Be=(X.flags&128)!==0,ft=Ke.rendering,ft===null)if(Be)nb(Ke,!1);else{if(Kc!==0||W!==null&&W.flags&128)for(W=X.child;W!==null;){if(ft=mv(W),ft!==null){for(X.flags|=128,nb(Ke,!1),W=ft.updateQueue,W!==null&&(X.updateQueue=W,X.flags|=4),X.subtreeFlags=0,W=_e,_e=X.child;_e!==null;)Be=_e,Ke=W,Be.flags&=14680066,ft=Be.alternate,ft===null?(Be.childLanes=0,Be.lanes=Ke,Be.child=null,Be.subtreeFlags=0,Be.memoizedProps=null,Be.memoizedState=null,Be.updateQueue=null,Be.dependencies=null,Be.stateNode=null):(Be.childLanes=ft.childLanes,Be.lanes=ft.lanes,Be.child=ft.child,Be.subtreeFlags=0,Be.deletions=null,Be.memoizedProps=ft.memoizedProps,Be.memoizedState=ft.memoizedState,Be.updateQueue=ft.updateQueue,Be.type=ft.type,Ke=ft.dependencies,Be.dependencies=Ke===null?null:{lanes:Ke.lanes,firstContext:Ke.firstContext}),_e=_e.sibling;return Cn(Wl,Wl.current&1|2),X.child}W=W.sibling}Ke.tail!==null&&Uo()>ip&&(X.flags|=128,Be=!0,nb(Ke,!1),X.lanes=4194304)}else{if(!Be)if(W=mv(ft),W!==null){if(X.flags|=128,Be=!0,W=W.updateQueue,W!==null&&(X.updateQueue=W,X.flags|=4),nb(Ke,!0),Ke.tail===null&&Ke.tailMode==="hidden"&&!ft.alternate&&!sa)return Wc(X),null}else 2*Uo()-Ke.renderingStartTime>ip&&_e!==1073741824&&(X.flags|=128,Be=!0,nb(Ke,!1),X.lanes=4194304);Ke.isBackwards?(ft.sibling=X.child,X.child=ft):(W=Ke.last,W!==null?W.sibling=ft:X.child=ft,Ke.last=ft)}return Ke.tail!==null?(X=Ke.tail,Ke.rendering=X,Ke.tail=X.sibling,Ke.renderingStartTime=Uo(),X.sibling=null,W=Wl.current,Cn(Wl,Be?W&1|2:W&1),X):(Wc(X),null);case 22:case 23:return Dw(),_e=X.memoizedState!==null,W!==null&&W.memoizedState!==null!==_e&&(X.flags|=8192),_e&&X.mode&1?Nh&1073741824&&(Wc(X),De&&X.subtreeFlags&6&&(X.flags|=8192)):Wc(X),null;case 24:return null;case 25:return null}throw Error(l(156,X.tag))}function zj(W,X){switch(kr(X),X.tag){case 1:return ia(X.type)&&hr(),W=X.flags,W&65536?(X.flags=W&-65537|128,X):null;case 3:return ff(),ai(ii),ai(Ki),pf(),W=X.flags,W&65536&&!(W&128)?(X.flags=W&-65537|128,X):null;case 5:return Tj(X),null;case 13:if(ai(Wl),W=X.memoizedState,W!==null&&W.dehydrated!==null){if(X.alternate===null)throw Error(l(340));wi()}return W=X.flags,W&65536?(X.flags=W&-65537|128,X):null;case 19:return ai(Wl),null;case 4:return ff(),null;case 10:return Md(X.type._context),null;case 22:case 23:return Dw(),null;case 24:return null;default:return null}}var $j=!1,eh=!1,dD=typeof WeakSet=="function"?WeakSet:Set,Ma=null;function kx(W,X){var _e=W.ref;if(_e!==null)if(typeof _e=="function")try{_e(null)}catch(Be){wa(W,X,Be)}else _e.current=null}function ab(W,X,_e){try{_e()}catch(Be){wa(W,X,Be)}}var y4=!1;function ib(W,X){for(le(W.containerInfo),Ma=X;Ma!==null;)if(W=Ma,X=W.child,(W.subtreeFlags&1028)!==0&&X!==null)X.return=W,Ma=X;else for(;Ma!==null;){W=Ma;try{var _e=W.alternate;if(W.flags&1024)switch(W.tag){case 0:case 11:case 15:break;case 1:if(_e!==null){var Be=_e.memoizedProps,Ke=_e.memoizedState,ft=W.stateNode,Qt=ft.getSnapshotBeforeUpdate(W.elementType===W.type?Be:ap(W.type,Be),Ke);ft.__reactInternalSnapshotBeforeUpdate=Qt}break;case 3:De&&rn(W.stateNode.containerInfo);break;case 5:case 6:case 4:case 17:break;default:throw Error(l(163))}}catch(rr){wa(W,W.return,rr)}if(X=W.sibling,X!==null){X.return=W.return,Ma=X;break}Ma=W.return}return _e=y4,y4=!1,_e}function ob(W,X,_e){var Be=X.updateQueue;if(Be=Be!==null?Be.lastEffect:null,Be!==null){var Ke=Be=Be.next;do{if((Ke.tag&W)===W){var ft=Ke.destroy;Ke.destroy=void 0,ft!==void 0&&ab(X,_e,ft)}Ke=Ke.next}while(Ke!==Be)}}function kw(W,X){if(X=X.updateQueue,X=X!==null?X.lastEffect:null,X!==null){var _e=X=X.next;do{if((_e.tag&W)===W){var Be=_e.create;_e.destroy=Be()}_e=_e.next}while(_e!==X)}}function Cv(W){var X=W.ref;if(X!==null){var _e=W.stateNode;switch(W.tag){case 5:W=ie(_e);break;default:W=_e}typeof X=="function"?X(W):X.current=W}}function Sw(W){var X=W.alternate;X!==null&&(W.alternate=null,Sw(X)),W.child=null,W.deletions=null,W.sibling=null,W.tag===5&&(X=W.stateNode,X!==null&&et(X)),W.stateNode=null,W.return=null,W.dependencies=null,W.memoizedProps=null,W.memoizedState=null,W.pendingProps=null,W.stateNode=null,W.updateQueue=null}function Sx(W){return W.tag===5||W.tag===3||W.tag===4}function Cw(W){e:for(;;){for(;W.sibling===null;){if(W.return===null||Sx(W.return))return null;W=W.return}for(W.sibling.return=W.return,W=W.sibling;W.tag!==5&&W.tag!==6&&W.tag!==18;){if(W.flags&2||W.child===null||W.tag===4)continue e;W.child.return=W,W=W.child}if(!(W.flags&2))return W.stateNode}}function lb(W,X,_e){var Be=W.tag;if(Be===5||Be===6)W=W.stateNode,X?xs(_e,W,X):hs(_e,W);else if(Be!==4&&(W=W.child,W!==null))for(lb(W,X,_e),W=W.sibling;W!==null;)lb(W,X,_e),W=W.sibling}function Uj(W,X,_e){var Be=W.tag;if(Be===5||Be===6)W=W.stateNode,X?St(_e,W,X):Et(_e,W);else if(Be!==4&&(W=W.child,W!==null))for(Uj(W,X,_e),W=W.sibling;W!==null;)Uj(W,X,_e),W=W.sibling}var jc=null,Yh=!1;function yf(W,X,_e){for(_e=_e.child;_e!==null;)qj(W,X,_e),_e=_e.sibling}function qj(W,X,_e){if(Ua&&typeof Ua.onCommitFiberUnmount=="function")try{Ua.onCommitFiberUnmount(Xf,_e)}catch{}switch(_e.tag){case 5:eh||kx(_e,X);case 6:if(De){var Be=jc,Ke=Yh;jc=null,yf(W,X,_e),jc=Be,Yh=Ke,jc!==null&&(Yh?fs(jc,_e.stateNode):kt(jc,_e.stateNode))}else yf(W,X,_e);break;case 18:De&&jc!==null&&(Yh?Xs(jc,_e.stateNode):ls(jc,_e.stateNode));break;case 4:De?(Be=jc,Ke=Yh,jc=_e.stateNode.containerInfo,Yh=!0,yf(W,X,_e),jc=Be,Yh=Ke):(pe&&(Be=_e.stateNode.containerInfo,Ke=Vr(Be),Zn(Be,Ke)),yf(W,X,_e));break;case 0:case 11:case 14:case 15:if(!eh&&(Be=_e.updateQueue,Be!==null&&(Be=Be.lastEffect,Be!==null))){Ke=Be=Be.next;do{var ft=Ke,Qt=ft.destroy;ft=ft.tag,Qt!==void 0&&(ft&2||ft&4)&&ab(_e,X,Qt),Ke=Ke.next}while(Ke!==Be)}yf(W,X,_e);break;case 1:if(!eh&&(kx(_e,X),Be=_e.stateNode,typeof Be.componentWillUnmount=="function"))try{Be.props=_e.memoizedProps,Be.state=_e.memoizedState,Be.componentWillUnmount()}catch(rr){wa(_e,X,rr)}yf(W,X,_e);break;case 21:yf(W,X,_e);break;case 22:_e.mode&1?(eh=(Be=eh)||_e.memoizedState!==null,yf(W,X,_e),eh=Be):yf(W,X,_e);break;default:yf(W,X,_e)}}function Vj(W){var X=W.updateQueue;if(X!==null){W.updateQueue=null;var _e=W.stateNode;_e===null&&(_e=W.stateNode=new dD),X.forEach(function(Be){var Ke=fb.bind(null,W,Be);_e.has(Be)||(_e.add(Be),Be.then(Ke,Ke))})}}function Om(W,X){var _e=X.deletions;if(_e!==null)for(var Be=0;Be<_e.length;Be++){var Ke=_e[Be];try{var ft=W,Qt=X;if(De){var rr=Qt;e:for(;rr!==null;){switch(rr.tag){case 5:jc=rr.stateNode,Yh=!1;break e;case 3:jc=rr.stateNode.containerInfo,Yh=!0;break e;case 4:jc=rr.stateNode.containerInfo,Yh=!0;break e}rr=rr.return}if(jc===null)throw Error(l(160));qj(ft,Qt,Ke),jc=null,Yh=!1}else qj(ft,Qt,Ke);var Ir=Ke.alternate;Ir!==null&&(Ir.return=null),Ke.return=null}catch(Tn){wa(Ke,X,Tn)}}if(X.subtreeFlags&12854)for(X=X.child;X!==null;)Hj(X,W),X=X.sibling}function Hj(W,X){var _e=W.alternate,Be=W.flags;switch(W.tag){case 0:case 11:case 14:case 15:if(Om(X,W),zp(W),Be&4){try{ob(3,W,W.return),kw(3,W)}catch(ha){wa(W,W.return,ha)}try{ob(5,W,W.return)}catch(ha){wa(W,W.return,ha)}}break;case 1:Om(X,W),zp(W),Be&512&&_e!==null&&kx(_e,_e.return);break;case 5:if(Om(X,W),zp(W),Be&512&&_e!==null&&kx(_e,_e.return),De){if(W.flags&32){var Ke=W.stateNode;try{Gs(Ke)}catch(ha){wa(W,W.return,ha)}}if(Be&4&&(Ke=W.stateNode,Ke!=null)){var ft=W.memoizedProps;if(_e=_e!==null?_e.memoizedProps:ft,Be=W.type,X=W.updateQueue,W.updateQueue=null,X!==null)try{us(Ke,X,Be,_e,ft,W)}catch(ha){wa(W,W.return,ha)}}}break;case 6:if(Om(X,W),zp(W),Be&4&&De){if(W.stateNode===null)throw Error(l(162));Ke=W.stateNode,ft=W.memoizedProps,_e=_e!==null?_e.memoizedProps:ft;try{Is(Ke,_e,ft)}catch(ha){wa(W,W.return,ha)}}break;case 3:if(Om(X,W),zp(W),Be&4){if(De&&tt&&_e!==null&&_e.memoizedState.isDehydrated)try{ss(X.containerInfo)}catch(ha){wa(W,W.return,ha)}if(pe){Ke=X.containerInfo,ft=X.pendingChildren;try{Zn(Ke,ft)}catch(ha){wa(W,W.return,ha)}}}break;case 4:if(Om(X,W),zp(W),Be&4&&pe){ft=W.stateNode,Ke=ft.containerInfo,ft=ft.pendingChildren;try{Zn(Ke,ft)}catch(ha){wa(W,W.return,ha)}}break;case 13:Om(X,W),zp(W),Ke=W.child,Ke.flags&8192&&(ft=Ke.memoizedState!==null,Ke.stateNode.isHidden=ft,!ft||Ke.alternate!==null&&Ke.alternate.memoizedState!==null||(db=Uo())),Be&4&&Vj(W);break;case 22:var Qt=_e!==null&&_e.memoizedState!==null;if(W.mode&1?(eh=(_e=eh)||Qt,Om(X,W),eh=_e):Om(X,W),zp(W),Be&8192){if(_e=W.memoizedState!==null,(W.stateNode.isHidden=_e)&&!Qt&&W.mode&1)for(Ma=W,Be=W.child;Be!==null;){for(X=Ma=Be;Ma!==null;){Qt=Ma;var rr=Qt.child;switch(Qt.tag){case 0:case 11:case 14:case 15:ob(4,Qt,Qt.return);break;case 1:kx(Qt,Qt.return);var Ir=Qt.stateNode;if(typeof Ir.componentWillUnmount=="function"){var Tn=Qt,Ia=Qt.return;try{var eo=Tn;Ir.props=eo.memoizedProps,Ir.state=eo.memoizedState,Ir.componentWillUnmount()}catch(ha){wa(Tn,Ia,ha)}}break;case 5:kx(Qt,Qt.return);break;case 22:if(Qt.memoizedState!==null){pM(X);continue}}rr!==null?(rr.return=Qt,Ma=rr):pM(X)}Be=Be.sibling}if(De){e:if(Be=null,De)for(X=W;;){if(X.tag===5){if(Be===null){Be=X;try{Ke=X.stateNode,_e?_s(Ke):zr(X.stateNode,X.memoizedProps)}catch(ha){wa(W,W.return,ha)}}}else if(X.tag===6){if(Be===null)try{ft=X.stateNode,_e?br(ft):Yr(ft,X.memoizedProps)}catch(ha){wa(W,W.return,ha)}}else if((X.tag!==22&&X.tag!==23||X.memoizedState===null||X===W)&&X.child!==null){X.child.return=X,X=X.child;continue}if(X===W)break e;for(;X.sibling===null;){if(X.return===null||X.return===W)break e;Be===X&&(Be=null),X=X.return}Be===X&&(Be=null),X.sibling.return=X.return,X=X.sibling}}}break;case 19:Om(X,W),zp(W),Be&4&&Vj(W);break;case 21:break;default:Om(X,W),zp(W)}}function zp(W){var X=W.flags;if(X&2){try{if(De){e:{for(var _e=W.return;_e!==null;){if(Sx(_e)){var Be=_e;break e}_e=_e.return}throw Error(l(160))}switch(Be.tag){case 5:var Ke=Be.stateNode;Be.flags&32&&(Gs(Ke),Be.flags&=-33);var ft=Cw(W);Uj(W,ft,Ke);break;case 3:case 4:var Qt=Be.stateNode.containerInfo,rr=Cw(W);lb(W,rr,Qt);break;default:throw Error(l(161))}}}catch(Ir){wa(W,W.return,Ir)}W.flags&=-3}X&4096&&(W.flags&=-4097)}function mM(W,X,_e){Ma=W,$p(W)}function $p(W,X,_e){for(var Be=(W.mode&1)!==0;Ma!==null;){var Ke=Ma,ft=Ke.child;if(Ke.tag===22&&Be){var Qt=Ke.memoizedState!==null||$j;if(!Qt){var rr=Ke.alternate,Ir=rr!==null&&rr.memoizedState!==null||eh;rr=$j;var Tn=eh;if($j=Qt,(eh=Ir)&&!Tn)for(Ma=Ke;Ma!==null;)Qt=Ma,Ir=Qt.child,Qt.tag===22&&Qt.memoizedState!==null?v4(Ke):Ir!==null?(Ir.return=Qt,Ma=Ir):v4(Ke);for(;ft!==null;)Ma=ft,$p(ft),ft=ft.sibling;Ma=Ke,$j=rr,eh=Tn}fM(W)}else Ke.subtreeFlags&8772&&ft!==null?(ft.return=Ke,Ma=ft):fM(W)}}function fM(W){for(;Ma!==null;){var X=Ma;if(X.flags&8772){var _e=X.alternate;try{if(X.flags&8772)switch(X.tag){case 0:case 11:case 15:eh||kw(5,X);break;case 1:var Be=X.stateNode;if(X.flags&4&&!eh)if(_e===null)Be.componentDidMount();else{var Ke=X.elementType===X.type?_e.memoizedProps:ap(X.type,_e.memoizedProps);Be.componentDidUpdate(Ke,_e.memoizedState,Be.__reactInternalSnapshotBeforeUpdate)}var ft=X.updateQueue;ft!==null&&Y1(X,ft,Be);break;case 3:var Qt=X.updateQueue;if(Qt!==null){if(_e=null,X.child!==null)switch(X.child.tag){case 5:_e=ie(X.child.stateNode);break;case 1:_e=X.child.stateNode}Y1(X,Qt,_e)}break;case 5:var rr=X.stateNode;_e===null&&X.flags&4&&lr(rr,X.type,X.memoizedProps,X);break;case 6:break;case 4:break;case 12:break;case 13:if(tt&&X.memoizedState===null){var Ir=X.alternate;if(Ir!==null){var Tn=Ir.memoizedState;if(Tn!==null){var Ia=Tn.dehydrated;Ia!==null&&Yt(Ia)}}}break;case 19:case 17:case 21:case 22:case 23:case 25:break;default:throw Error(l(163))}eh||X.flags&512&&Cv(X)}catch(eo){wa(X,X.return,eo)}}if(X===W){Ma=null;break}if(_e=X.sibling,_e!==null){_e.return=X.return,Ma=_e;break}Ma=X.return}}function pM(W){for(;Ma!==null;){var X=Ma;if(X===W){Ma=null;break}var _e=X.sibling;if(_e!==null){_e.return=X.return,Ma=_e;break}Ma=X.return}}function v4(W){for(;Ma!==null;){var X=Ma;try{switch(X.tag){case 0:case 11:case 15:var _e=X.return;try{kw(4,X)}catch(Ir){wa(X,_e,Ir)}break;case 1:var Be=X.stateNode;if(typeof Be.componentDidMount=="function"){var Ke=X.return;try{Be.componentDidMount()}catch(Ir){wa(X,Ke,Ir)}}var ft=X.return;try{Cv(X)}catch(Ir){wa(X,ft,Ir)}break;case 5:var Qt=X.return;try{Cv(X)}catch(Ir){wa(X,Qt,Ir)}}}catch(Ir){wa(X,X.return,Ir)}if(X===W){Ma=null;break}var rr=X.sibling;if(rr!==null){rr.return=X.return,Ma=rr;break}Ma=X.return}}var Tw=0,Tv=1,ey=2,Up=3,Cx=4;if(typeof Symbol=="function"&&Symbol.for){var qp=Symbol.for;Tw=qp("selector.component"),Tv=qp("selector.has_pseudo_class"),ey=qp("selector.role"),Up=qp("selector.test_id"),Cx=qp("selector.text")}function Ew(W){var X=ge(W);if(X!=null){if(typeof X.memoizedProps["data-testname"]!="string")throw Error(l(364));return X}if(W=it(W),W===null)throw Error(l(362));return W.stateNode.current}function cb(W,X){switch(X.$$typeof){case Tw:if(W.type===X.value)return!0;break;case Tv:e:{X=X.value,W=[W,0];for(var _e=0;_e";case Tv:return":has("+(vf(W)||"")+")";case ey:return'[role="'+W.value+'"]';case Cx:return'"'+W.value+'"';case Up:return'[data-testname="'+W.value+'"]';default:throw Error(l(365))}}function Gj(W,X){var _e=[];W=[W,0];for(var Be=0;BeKe&&(Ke=Qt),Be&=~ft}if(Be=Ke,Be=Uo()-Be,Be=(120>Be?120:480>Be?480:1080>Be?1080:1920>Be?1920:3e3>Be?3e3:4320>Be?4320:1960*Aw(Be/1960))-Be,10W?16:W,Lg===null)var Be=!1;else{if(W=Lg,Lg=null,ub=0,lo&6)throw Error(l(331));var Ke=lo;for(lo|=4,Ma=W.current;Ma!==null;){var ft=Ma,Qt=ft.child;if(Ma.flags&16){var rr=ft.deletions;if(rr!==null){for(var Ir=0;IrUo()-db?Rg(W,0):Ev|=_e),Sh(W,X)}function Rw(W,X){X===0&&(W.mode&1?(X=$h,$h<<=1,!($h&130023424)&&($h=4194304)):X=1);var _e=th();W=Wr(W,X),W!==null&&(Zf(W,X,_e),Sh(W,_e))}function Zj(W){var X=W.memoizedState,_e=0;X!==null&&(_e=X.retryLane),Rw(W,_e)}function fb(W,X){var _e=0;switch(W.tag){case 13:var Be=W.stateNode,Ke=W.memoizedState;Ke!==null&&(_e=Ke.retryLane);break;case 19:Be=W.stateNode;break;default:throw Error(l(314))}Be!==null&&Be.delete(X),Rw(W,_e)}var Xj;Xj=function(W,X,_e){if(W!==null)if(W.memoizedProps!==X.pendingProps||ii.current)Kh=!0;else{if(!(W.lanes&_e)&&!(X.flags&128))return Kh=!1,jw(W,X,_e);Kh=!!(W.flags&131072)}else Kh=!1,sa&&X.flags&1048576&&Mt(X,H1,X.index);switch(X.lanes=0,X.tag){case 2:var Be=X.type;kv(W,X),W=X.pendingProps;var Ke=co(X,Ki.current);Id(X,_e),Ke=cw(null,X,Be,W,Ke,_e);var ft=X1();return X.flags|=1,typeof Ke=="object"&&Ke!==null&&typeof Ke.render=="function"&&Ke.$$typeof===void 0?(X.tag=1,X.memoizedState=null,X.updateQueue=null,ia(Be)?(ft=!0,$o(X)):ft=!1,X.memoizedState=Ke.state!==null&&Ke.state!==void 0?Ke.state:null,Gn(X),Ke.updater=bv,X.stateNode=Ke,Ke._reactInternals=X,X0(X,Be,W,_e),X=_w(null,X,Be,!0,ft,_e)):(X.tag=0,sa&&ft&&tr(X),jh(null,X,Ke,_e),X=X.child),X;case 16:Be=X.elementType;e:{switch(kv(W,X),W=X.pendingProps,Ke=Be._init,Be=Ke(Be._payload),X.type=Be,Ke=X.tag=dr(Be),W=ap(Be,W),Ke){case 0:X=p4(null,X,Be,W,_e);break e;case 1:X=Fj(null,X,Be,W,_e);break e;case 11:X=m4(null,X,Be,W,_e);break e;case 14:X=wv(null,X,Be,ap(Be.type,W),_e);break e}throw Error(l(306,Be,""))}return X;case 0:return Be=X.type,Ke=X.pendingProps,Ke=X.elementType===Be?Ke:ap(Be,Ke),p4(W,X,Be,Ke,_e);case 1:return Be=X.type,Ke=X.pendingProps,Ke=X.elementType===Be?Ke:ap(Be,Ke),Fj(W,X,Be,Ke,_e);case 3:e:{if(eb(X),W===null)throw Error(l(387));Be=X.pendingProps,ft=X.memoizedState,Ke=ft.element,Pm(W,X),hv(X,Be,null,_e);var Qt=X.memoizedState;if(Be=Qt.element,tt&&ft.isDehydrated)if(ft={element:Be,isDehydrated:!1,cache:Qt.cache,pendingSuspenseBoundaries:Qt.pendingSuspenseBoundaries,transitions:Qt.transitions},X.updateQueue.baseState=ft,X.memoizedState=ft,X.flags&256){Ke=Wh(Error(l(423)),X),X=jv(W,X,Be,_e,Ke);break e}else if(Be!==Ke){Ke=Wh(Error(l(424)),X),X=jv(W,X,Be,_e,Ke);break e}else for(tt&&(Mr=Ee(X.stateNode.containerInfo),bn=X,sa=!0,Ja=null,qa=!1),_e=iM(X,null,Be,_e),X.child=_e;_e;)_e.flags=_e.flags&-3|4096,_e=_e.sibling;else{if(wi(),Be===Ke){X=xf(W,X,_e);break e}jh(W,X,Be,_e)}X=X.child}return X;case 5:return ow(X),W===null&&Tu(X),Be=X.type,Ke=X.pendingProps,ft=W!==null?W.memoizedProps:null,Qt=Ke.children,Ve(Be,Ke)?Qt=null:ft!==null&&Ve(Be,ft)&&(X.flags|=32),dM(W,X),jh(W,X,Qt,_e),X.child;case 6:return W===null&&Tu(X),null;case 13:return uM(W,X,_e);case 4:return wc(X,X.stateNode.containerInfo),Be=X.pendingProps,W===null?X.child=Al(X,null,Be,_e):jh(W,X,Be,_e),X.child;case 11:return Be=X.type,Ke=X.pendingProps,Ke=X.elementType===Be?Ke:ap(Be,Ke),m4(W,X,Be,Ke,_e);case 7:return jh(W,X,X.pendingProps,_e),X.child;case 8:return jh(W,X,X.pendingProps.children,_e),X.child;case 12:return jh(W,X,X.pendingProps.children,_e),X.child;case 10:e:{if(Be=X.type._context,Ke=X.pendingProps,ft=X.memoizedProps,Qt=Ke.value,K1(X,Be,Qt),ft!==null)if(Cm(ft.value,Qt)){if(ft.children===Ke.children&&!ii.current){X=xf(W,X,_e);break e}}else for(ft=X.child,ft!==null&&(ft.return=X);ft!==null;){var rr=ft.dependencies;if(rr!==null){Qt=ft.child;for(var Ir=rr.firstContext;Ir!==null;){if(Ir.context===Be){if(ft.tag===1){Ir=Hh(-1,_e&-_e),Ir.tag=2;var Tn=ft.updateQueue;if(Tn!==null){Tn=Tn.shared;var Ia=Tn.pending;Ia===null?Ir.next=Ir:(Ir.next=Ia.next,Ia.next=Ir),Tn.pending=Ir}}ft.lanes|=_e,Ir=ft.alternate,Ir!==null&&(Ir.lanes|=_e),Im(ft.return,_e,X),rr.lanes|=_e;break}Ir=Ir.next}}else if(ft.tag===10)Qt=ft.type===X.type?null:ft.child;else if(ft.tag===18){if(Qt=ft.return,Qt===null)throw Error(l(341));Qt.lanes|=_e,rr=Qt.alternate,rr!==null&&(rr.lanes|=_e),Im(Qt,_e,X),Qt=ft.sibling}else Qt=ft.child;if(Qt!==null)Qt.return=ft;else for(Qt=ft;Qt!==null;){if(Qt===X){Qt=null;break}if(ft=Qt.sibling,ft!==null){ft.return=Qt.return,Qt=ft;break}Qt=Qt.return}ft=Qt}jh(W,X,Ke.children,_e),X=X.child}return X;case 9:return Ke=X.type,Be=X.pendingProps.children,Id(X,_e),Ke=mf(Ke),Be=Be(Ke),X.flags|=1,jh(W,X,Be,_e),X.child;case 14:return Be=X.type,Ke=ap(Be,X.pendingProps),Ke=ap(Be.type,Ke),wv(W,X,Be,Ke,_e);case 15:return f4(W,X,X.type,X.pendingProps,_e);case 17:return Be=X.type,Ke=X.pendingProps,Ke=X.elementType===Be?Ke:ap(Be,Ke),kv(W,X),X.tag=1,ia(Be)?(W=!0,$o(X)):W=!1,Id(X,_e),Y0(X,Be,Ke),X0(X,Be,Ke,_e),_w(null,X,Be,!0,W,_e);case 19:return sb(W,X,_e);case 22:return cM(W,X,_e)}throw Error(l(156,X.tag))};function Qj(W,X){return qh(W,X)}function Mv(W,X,_e,Be){this.tag=W,this.key=_e,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=X,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=Be,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Dd(W,X,_e,Be){return new Mv(W,X,_e,Be)}function ur(W){return W=W.prototype,!(!W||!W.isReactComponent)}function dr(W){if(typeof W=="function")return ur(W)?1:0;if(W!=null){if(W=W.$$typeof,W===_)return 11;if(W===k)return 14}return 2}function wf(W,X){var _e=W.alternate;return _e===null?(_e=Dd(W.tag,X,W.key,W.mode),_e.elementType=W.elementType,_e.type=W.type,_e.stateNode=W.stateNode,_e.alternate=W,W.alternate=_e):(_e.pendingProps=X,_e.type=W.type,_e.flags=0,_e.subtreeFlags=0,_e.deletions=null),_e.flags=W.flags&14680064,_e.childLanes=W.childLanes,_e.lanes=W.lanes,_e.child=W.child,_e.memoizedProps=W.memoizedProps,_e.memoizedState=W.memoizedState,_e.updateQueue=W.updateQueue,X=W.dependencies,_e.dependencies=X===null?null:{lanes:X.lanes,firstContext:X.firstContext},_e.sibling=W.sibling,_e.index=W.index,_e.ref=W.ref,_e}function Lo(W,X,_e,Be,Ke,ft){var Qt=2;if(Be=W,typeof W=="function")ur(W)&&(Qt=1);else if(typeof W=="string")Qt=5;else e:switch(W){case h:return es(_e.children,Ke,ft,X);case m:Qt=8,Ke|=8;break;case p:return W=Dd(12,_e,X,Ke|2),W.elementType=p,W.lanes=ft,W;case b:return W=Dd(13,_e,X,Ke),W.elementType=b,W.lanes=ft,W;case j:return W=Dd(19,_e,X,Ke),W.elementType=j,W.lanes=ft,W;case E:return Ow(_e,Ke,ft,X);default:if(typeof W=="object"&&W!==null)switch(W.$$typeof){case x:Qt=10;break e;case y:Qt=9;break e;case _:Qt=11;break e;case k:Qt=14;break e;case T:Qt=16,Be=null;break e}throw Error(l(130,W==null?W:typeof W,""))}return X=Dd(Qt,_e,X,Ke),X.elementType=W,X.type=Be,X.lanes=ft,X}function es(W,X,_e,Be){return W=Dd(7,W,Be,X),W.lanes=_e,W}function Ow(W,X,_e,Be){return W=Dd(22,W,Be,X),W.elementType=E,W.lanes=_e,W.stateNode={isHidden:!1},W}function pb(W,X,_e){return W=Dd(6,W,null,X),W.lanes=_e,W}function Fw(W,X,_e){return X=Dd(4,W.children!==null?W.children:[],W.key,X),X.lanes=_e,X.stateNode={containerInfo:W.containerInfo,pendingChildren:null,implementation:W.implementation},X}function Jj(W,X,_e,Be,Ke){this.tag=X,this.containerInfo=W,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=Pe,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=z0(0),this.expirationTimes=z0(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=z0(0),this.identifierPrefix=Be,this.onRecoverableError=Ke,tt&&(this.mutableSourceEagerHydrationData=null)}function k4(W,X,_e,Be,Ke,ft,Qt,rr,Ir){return W=new Jj(W,X,_e,rr,Ir),X===1?(X=1,ft===!0&&(X|=8)):X=0,ft=Dd(3,null,null,X),W.current=ft,ft.stateNode=W,ft.memoizedState={element:Be,isDehydrated:_e,cache:null,transitions:null,pendingSuspenseBoundaries:null},Gn(ft),W}function S4(W){if(!W)return Wi;W=W._reactInternals;e:{if(O(W)!==W||W.tag!==1)throw Error(l(170));var X=W;do{switch(X.tag){case 3:X=X.stateNode.context;break e;case 1:if(ia(X.type)){X=X.stateNode.__reactInternalMemoizedMergedChildContext;break e}}X=X.return}while(X!==null);throw Error(l(171))}if(W.tag===1){var _e=W.type;if(ia(_e))return Yi(W,_e,X)}return X}function Iv(W){var X=W._reactInternals;if(X===void 0)throw typeof W.render=="function"?Error(l(188)):(W=Object.keys(W).join(","),Error(l(268,W)));return W=Z(X),W===null?null:W.stateNode}function C4(W,X){if(W=W.memoizedState,W!==null&&W.dehydrated!==null){var _e=W.retryLane;W.retryLane=_e!==0&&_e=Tn&&ft>=eo&&Ke<=Ia&&Qt<=ha){W.splice(X,1);break}else if(Be!==Tn||_e.width!==Ir.width||haQt){if(!(ft!==eo||_e.height!==Ir.height||IaKe)){Tn>Be&&(Ir.width+=Tn-Be,Ir.x=Be),Iaft&&(Ir.height+=eo-ft,Ir.y=ft),ha_e&&(_e=Qt)),Qt ")+` No matching component was found for: `)+W.join(" > ")}return null},r.getPublicRootInstance=function(W){if(W=W.current,!W.child)return null;switch(W.child.tag){case 5:return ie(W.child.stateNode);default:return W.child.stateNode}},r.injectIntoDevTools=function(W){if(W={bundleType:W.bundleType,version:W.version,rendererPackageName:W.rendererPackageName,rendererConfig:W.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:o.ReactCurrentDispatcher,findHostInstanceByFiber:bM,findFiberByHostInstance:W.findFiberByHostInstance||tN,findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null,reconcilerVersion:"18.3.1"},typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u")W=!1;else{var X=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(X.isDisabled||!X.supportsFiber)W=!0;else{try{Xf=X.inject(W),Ua=X}catch{}W=!!X.checkDCE}}return W},r.isAlreadyRendering=function(){return!1},r.observeVisibleRects=function(W,X,_e,Be){if(!$e)throw Error(l(363));W=Wj(W,X);var Ke=rt(W,_e,Be).disconnect;return{disconnect:function(){Ke()}}},r.registerMutableSourceForHydration=function(W,X){var _e=X._getVersion;_e=_e(X._source),W.mutableSourceEagerHydrationData==null?W.mutableSourceEagerHydrationData=[X,_e]:W.mutableSourceEagerHydrationData.push(X,_e)},r.runWithPriority=function(W,X){var _e=oo;try{return oo=W,X()}finally{oo=_e}},r.shouldError=function(){return null},r.shouldSuspend=function(){return!1},r.updateContainer=function(W,X,_e,Be){var Ke=X.current,ft=th(),Qt=Dg(Ke);return _e=S4(_e),X.context===null?X.context=_e:X.pendingContext=_e,X=Hh(ft,Qt),X.payload={element:W},Be=Be===void 0?null:Be,Be!==null&&(X.callback=Be),W=_n(Ke,X,Qt),W!==null&&(Fm(W,Ke,Qt,ft),G0(W,Ke,Qt)),Qt},r};Nut.exports=Was;var Kas=Nut.exports;const Yas=ol(Kas);var kut={exports:{}},ZA={};/** * @license React * react-reconciler-constants.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. */ZA.ConcurrentRoot=1;ZA.ContinuousEventPriority=4;ZA.DefaultEventPriority=16;ZA.DiscreteEventPriority=1;ZA.IdleEventPriority=536870912;ZA.LegacyRoot=0;kut.exports=ZA;var Sut=kut.exports;const Eze={children:!0,ref:!0,key:!0,style:!0,forwardedRef:!0,unstable_applyCache:!0,unstable_applyDrawHitFromCache:!0};let Aze=!1,Mze=!1;const MEe=".react-konva-event",Zas=`ReactKonva: You have a Konva node with draggable = true and position defined but no onDragMove or onDragEnd events are handled. Position of a node will be changed during drag&drop, so you should update state of the react app as well. Consider to add onDragMove or onDragEnd events. For more info see: https://github.com/konvajs/react-konva/issues/256 `,Xas=`ReactKonva: You are using "zIndex" attribute for a Konva node. react-konva may get confused with ordering. Just define correct order of elements in your render function of a component. For more info see: https://github.com/konvajs/react-konva/issues/194 `,Qas={};function Nxe(s,t,r=Qas){if(!Aze&&"zIndex"in t&&(console.warn(Xas),Aze=!0),!Mze&&t.draggable){var n=t.x!==void 0||t.y!==void 0,a=t.onDragEnd||t.onDragMove;n&&!a&&(console.warn(Zas),Mze=!0)}for(var i in r)if(!Eze[i]){var l=i.slice(0,2)==="on",o=r[i]!==t[i];if(l&&o){var c=i.substr(2).toLowerCase();c.substr(0,7)==="content"&&(c="content"+c.substr(7,1).toUpperCase()+c.substr(8)),s.off(c,r[i])}var d=!t.hasOwnProperty(i);d&&s.setAttr(i,void 0)}var h=t._useStrictMode,m={},p=!1;const x={};for(var i in t)if(!Eze[i]){var l=i.slice(0,2)==="on",y=r[i]!==t[i];if(l&&y){var c=i.substr(2).toLowerCase();c.substr(0,7)==="content"&&(c="content"+c.substr(7,1).toUpperCase()+c.substr(8)),t[i]&&(x[c]=t[i])}!l&&(t[i]!==r[i]||h&&t[i]!==s.getAttr(i))&&(p=!0,m[i]=t[i])}p&&(s.setAttrs(m),JS(s));for(var c in x)s.on(c+MEe,x[c])}function JS(s){if(!Jn.autoDrawEnabled){var t=s.getLayer()||s.getStage();t&&t.batchDraw()}}const Cut={},Jas={};NA.Node.prototype._applyProps=Nxe;function eis(s,t){if(typeof t=="string"){console.error(`Do not use plain text as child of Konva.Node. You are using text: ${t}`);return}s.add(t),JS(s)}function tis(s,t,r){let n=NA[s];n||(console.error(`Konva has no node with the type ${s}. Group will be used instead. If you use minimal version of react-konva, just import required nodes into Konva: "import "konva/lib/shapes/${s}" If you want to render DOM elements as part of canvas tree take a look into this demo: https://konvajs.github.io/docs/react/DOM_Portal.html`),n=NA.Group);const a={},i={};for(var l in t){var o=l.slice(0,2)==="on";o?i[l]=t[l]:a[l]=t[l]}const c=new n(a);return Nxe(c,i),c}function sis(s,t,r){console.error(`Text components are not supported for now in ReactKonva. Your text is: "${s}"`)}function ris(s,t,r){return!1}function nis(s){return s}function ais(){return null}function iis(){return null}function ois(s,t,r,n){return Jas}function lis(){}function cis(s){}function dis(s,t){return!1}function uis(){return Cut}function his(){return Cut}const mis=setTimeout,fis=clearTimeout,pis=-1;function gis(s,t){return!1}const xis=!1,yis=!0,vis=!0;function bis(s,t){t.parent===s?t.moveToTop():s.add(t),JS(s)}function _is(s,t){t.parent===s?t.moveToTop():s.add(t),JS(s)}function Tut(s,t,r){t._remove(),s.add(t),t.setZIndex(r.getZIndex()),JS(s)}function wis(s,t,r){Tut(s,t,r)}function jis(s,t){t.destroy(),t.off(MEe),JS(s)}function Nis(s,t){t.destroy(),t.off(MEe),JS(s)}function kis(s,t,r){console.error(`Text components are not yet supported in ReactKonva. You text is: "${r}"`)}function Sis(s,t,r){}function Cis(s,t,r,n,a){Nxe(s,a,n)}function Tis(s){s.hide(),JS(s)}function Eis(s){}function Ais(s,t){(t.visible==null||t.visible)&&s.show()}function Mis(s,t){}function Iis(s){}function Pis(){}const Lis=()=>Sut.DefaultEventPriority,Dis=Object.freeze(Object.defineProperty({__proto__:null,appendChild:bis,appendChildToContainer:_is,appendInitialChild:eis,cancelTimeout:fis,clearContainer:Iis,commitMount:Sis,commitTextUpdate:kis,commitUpdate:Cis,createInstance:tis,createTextInstance:sis,detachDeletedInstance:Pis,finalizeInitialChildren:ris,getChildHostContext:his,getCurrentEventPriority:Lis,getPublicInstance:nis,getRootHostContext:uis,hideInstance:Tis,hideTextInstance:Eis,idlePriority:OO.unstable_IdlePriority,insertBefore:Tut,insertInContainerBefore:wis,isPrimaryRenderer:xis,noTimeout:pis,now:OO.unstable_now,prepareForCommit:ais,preparePortalMount:iis,prepareUpdate:ois,removeChild:jis,removeChildFromContainer:Nis,resetAfterCommit:lis,resetTextContent:cis,run:OO.unstable_runWithPriority,scheduleTimeout:mis,shouldDeprioritizeSubtree:dis,shouldSetTextContent:gis,supportsMutation:vis,unhideInstance:Ais,unhideTextInstance:Mis,warnsIfNotActing:yis},Symbol.toStringTag,{value:"Module"}));var Ris=Object.defineProperty,Ois=Object.defineProperties,Fis=Object.getOwnPropertyDescriptors,Ize=Object.getOwnPropertySymbols,Bis=Object.prototype.hasOwnProperty,zis=Object.prototype.propertyIsEnumerable,Pze=(s,t,r)=>t in s?Ris(s,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):s[t]=r,Lze=(s,t)=>{for(var r in t||(t={}))Bis.call(t,r)&&Pze(s,r,t[r]);if(Ize)for(var r of Ize(t))zis.call(t,r)&&Pze(s,r,t[r]);return s},$is=(s,t)=>Ois(s,Fis(t)),Dze,Rze;typeof window<"u"&&((Dze=window.document)!=null&&Dze.createElement||((Rze=window.navigator)==null?void 0:Rze.product)==="ReactNative")?S.useLayoutEffect:S.useEffect;function Eut(s,t,r){if(!s)return;if(r(s)===!0)return s;let n=s.child;for(;n;){const a=Eut(n,t,r);if(a)return a;n=n.sibling}}function Aut(s){try{return Object.defineProperties(s,{_currentRenderer:{get(){return null},set(){}},_currentRenderer2:{get(){return null},set(){}}})}catch{return s}}const Oze=console.error;console.error=function(){const s=[...arguments].join("");if(s!=null&&s.startsWith("Warning:")&&s.includes("useContext")){console.error=Oze;return}return Oze.apply(this,arguments)};const IEe=Aut(S.createContext(null));class Mut extends S.Component{render(){return S.createElement(IEe.Provider,{value:this._reactInternals},this.props.children)}}function Uis(){const s=S.useContext(IEe);if(s===null)throw new Error("its-fine: useFiber must be called within a !");const t=S.useId();return S.useMemo(()=>{for(const n of[s,s==null?void 0:s.alternate]){if(!n)continue;const a=Eut(n,!1,i=>{let l=i.memoizedState;for(;l;){if(l.memoizedState===t)return!0;l=l.next}});if(a)return a}},[s,t])}function qis(){const s=Uis(),[t]=S.useState(()=>new Map);t.clear();let r=s;for(;r;){if(r.type&&typeof r.type=="object"){const a=r.type._context===void 0&&r.type.Provider===r.type?r.type:r.type._context;a&&a!==IEe&&!t.has(a)&&t.set(a,S.useContext(Aut(a)))}r=r.return}return t}function Vis(){const s=qis();return S.useMemo(()=>Array.from(s.keys()).reduce((t,r)=>n=>S.createElement(t,null,S.createElement(r.Provider,$is(Lze({},n),{value:s.get(r)}))),t=>S.createElement(Mut,Lze({},t))),[s])}function His(s){const t=Nt.useRef({});return Nt.useLayoutEffect(()=>{t.current=s}),Nt.useLayoutEffect(()=>()=>{t.current={}},[]),t.current}const Gis=s=>{const t=Nt.useRef(null),r=Nt.useRef(null),n=Nt.useRef(null),a=His(s),i=Vis(),l=o=>{const{forwardedRef:c}=s;c&&(typeof c=="function"?c(o):c.current=o)};return Nt.useLayoutEffect(()=>(r.current=new NA.Stage({width:s.width,height:s.height,container:t.current}),l(r.current),n.current=TO.createContainer(r.current,Sut.LegacyRoot,!1,null),TO.updateContainer(Nt.createElement(i,{},s.children),n.current),()=>{NA.isBrowser&&(l(null),TO.updateContainer(null,n.current,null),r.current.destroy())}),[]),Nt.useLayoutEffect(()=>{l(r.current),Nxe(r.current,s,a),TO.updateContainer(Nt.createElement(i,{},s.children),n.current,null)}),Nt.createElement("div",{ref:t,id:s.id,accessKey:s.accessKey,className:s.className,role:s.role,style:s.style,tabIndex:s.tabIndex,title:s.title})},Wis="Layer",kk="Group",Db="Rect",fI="Image",_6="Text",aXs="Transformer",TO=Yas(Dis);TO.injectIntoDevTools({findHostInstanceByFiber:()=>null,bundleType:0,version:Nt.version,rendererPackageName:"react-konva"});const Kis=Nt.forwardRef((s,t)=>Nt.createElement(Mut,{},Nt.createElement(Gis,{...s,forwardedRef:t})));function Yis({imageUrl:s,preset:t,barStyleId:r,overrides:n,maxDisplayWidth:a=720,stageRef:i}){const l=S.useRef(null),[o,c]=S.useState(null),[d,h]=S.useState(null),[m,p]=S.useState(null),x=(t==null?void 0:t.headshot_url)??"",y=(t==null?void 0:t.brokerage_logo_url)??"";S.useEffect(()=>{if(!s){c(null);return}const J=new window.Image;J.crossOrigin="anonymous",J.onload=()=>c(J),J.onerror=()=>c(null),J.src=s},[s]),S.useEffect(()=>{if(!x){h(null);return}const J=new window.Image;J.crossOrigin="anonymous",J.onload=()=>h(J),J.onerror=()=>h(null),J.src=x},[x]),S.useEffect(()=>{if(!y){p(null);return}const J=new window.Image;J.crossOrigin="anonymous",J.onload=()=>p(J),J.onerror=()=>p(null),J.src=y},[y]);const _=brs(r),b=(o==null?void 0:o.naturalWidth)??1080,j=(o==null?void 0:o.naturalHeight)??1080,k=S.useMemo(()=>Math.min(1,a/b),[b,a]),T=b*k,E=j*k,A=(n==null?void 0:n.brand_color)??(t==null?void 0:t.brand_color)??"#0f172a",D=(n==null?void 0:n.accent_color)??(t==null?void 0:t.accent_color)??"#3b82f6",R=(n==null?void 0:n.display_name)??(t==null?void 0:t.display_name)??"",z=(n==null?void 0:n.phone)??(t==null?void 0:t.phone)??"",O=(n==null?void 0:n.email)??(t==null?void 0:t.email)??"",$=(n==null?void 0:n.tagline)??(t==null?void 0:t.tagline)??"",ee=new Set((n==null?void 0:n.hidden_fields)??(t==null?void 0:t.hidden_fields)??[]),Z=J=>_.fields.includes(J)&&!ee.has(J);return e.jsx("div",{className:"border rounded-lg overflow-hidden bg-muted/40 inline-block",children:e.jsx(Kis,{ref:J=>{l.current=J,i&&(i.current=J)},width:T,height:E,scaleX:k,scaleY:k,children:e.jsxs(Wis,{children:[o&&e.jsx(fI,{image:o,width:b,height:j,listening:!1}),!o&&e.jsx(Db,{x:0,y:0,width:b,height:j,fill:"#e2e8f0"}),e.jsx(Zis,{style:_,canvasW:b,canvasH:j,brandColor:A,accentColor:D,name:R,phone:z,email:O,tagline:$,headshot:d,logo:m,hidden:ee,has:Z})]})})})}function Zis({style:s,canvasW:t,canvasH:r,brandColor:n,accentColor:a,name:i,phone:l,email:o,tagline:c,headshot:d,logo:h,has:m}){const p=r*s.heightRatio,x=p*.18,y=s.textColor==="light"?"#ffffff":s.textColor==="dark"?"#0f172a":s.background==="dark"||s.background==="gradient"?"#ffffff":_rs(n),_=y==="#ffffff"?"rgba(255,255,255,0.78)":"rgba(15,23,42,0.7)";if(s.position==="bottom"||s.position==="top"){const b=s.position==="bottom"?r-p:0;return e.jsxs(kk,{children:[e.jsx(Db,{x:0,y:b,width:t,height:p,fill:n}),e.jsx(Db,{x:0,y:s.position==="bottom"?b:p-4,width:t,height:4,fill:a}),e.jsx(wq,{x,y:b+x,width:t-x*2,height:p-x*2,textColor:y,subTextColor:_,name:i,phone:l,email:o,tagline:c,headshot:d,logo:h,has:m,circular:s.circularHeadshot})]})}if(s.position==="corner-br"){const b=t*.42,j=p,k=t-b-r*.025,T=r-j-r*.025;return e.jsxs(kk,{children:[e.jsx(Db,{x:k,y:T,width:b,height:j,fill:n,cornerRadius:j*.12,opacity:.92}),e.jsx(Db,{x:k,y:T+j-4,width:b,height:4,fill:a,cornerRadius:2}),e.jsx(wq,{x:k+x,y:T+x,width:b-x*2,height:j-x*2,textColor:y,subTextColor:_,name:i,phone:l,email:o,tagline:c,headshot:d,logo:h,has:m,circular:s.circularHeadshot})]})}if(s.position==="side-right"){const b=Math.max(t*.22,Math.min(t*.3,260)),j=b*.12;return e.jsxs(kk,{children:[e.jsx(Db,{x:t-b,y:0,width:b,height:r,fill:n}),e.jsx(Db,{x:t-b,y:0,width:4,height:r,fill:a}),e.jsx(wq,{x:t-b+j,y:r*.08,width:b-j*2,height:r*.84,textColor:y,subTextColor:_,name:i,phone:l,email:o,tagline:c,headshot:d,logo:h,has:m,circular:s.circularHeadshot,vertical:!0,railWidth:b})]})}return s.position==="letterbox"?e.jsxs(kk,{children:[e.jsx(Db,{x:0,y:0,width:t,height:p,fill:"#0a0a0a"}),e.jsx(Db,{x:0,y:r-p,width:t,height:p,fill:"#0a0a0a"}),e.jsx(Db,{x:0,y:r-p,width:t,height:3,fill:a}),e.jsx(wq,{x,y:r-p+x,width:t-x*2,height:p-x*2,textColor:"#ffffff",subTextColor:"rgba(255,255,255,0.75)",name:i,phone:l,email:o,tagline:c,headshot:d,logo:h,has:m,circular:s.circularHeadshot}),h&&m("logo")&&e.jsx(fI,{image:h,x:t-x-p*.7,y:x,height:p-x*2,width:p*.7})]}):null}function wq({x:s,y:t,width:r,height:n,textColor:a,subTextColor:i,name:l,phone:o,email:c,tagline:d,headshot:h,logo:m,has:p,circular:x,vertical:y,railWidth:_}){if(y){const J=_??r,K=Math.min(r,J*.7),re=Math.max(14,J*.13),ie=Math.max(11,J*.085),ce=J*.08,ne=J*.35;let le=t;const be=le;le+=K+ce;const fe=le,je=l.length>12?2:1;le+=re*1.15*je+ce*.5;const ve=le;p("phone")&&o&&(le+=ie*1.3+ce*.4);const We=le;p("email")&&c&&(le+=ie*1.3+ce*.4);const Ve=le+ce*.5;return e.jsxs(kk,{children:[p("headshot")&&h&&e.jsx(kk,{clipFunc:x?Le=>{Le.beginPath(),Le.arc(s+r/2,be+K/2,K/2,0,Math.PI*2),Le.closePath()}:void 0,children:e.jsx(fI,{image:h,x:s+(r-K)/2,y:be,width:K,height:K})}),p("name")&&l&&e.jsx(_6,{text:l,x:s,y:fe,width:r,align:"center",fontSize:re,fontStyle:"bold",fill:a}),p("phone")&&o&&e.jsx(_6,{text:o,x:s,y:ve,width:r,align:"center",fontSize:ie,fill:i}),p("email")&&c&&e.jsx(_6,{text:c,x:s,y:We,width:r,align:"center",fontSize:ie,fill:i,ellipsis:!0,wrap:"none"}),p("logo")&&m&&e.jsx(fI,{image:m,x:s,y:Ve,width:r,height:ne})]})}const b=n*.95,j=h&&p("headshot")?s+b+n*.18:s,k=r-(j-s)-(m&&p("logo")?n*1.6:0),T=Math.max(20,n*.34),E=Math.max(13,n*.22),A=n*.06,D=p("tagline")&&d?1:0,R=p("phone")&&o?1:0,z=p("email")&&c?1:0,O=1+D+(R||z?1:0),$=O*T+(O-1)*A;let Z=t+(n-$)/2;return e.jsxs(kk,{children:[p("headshot")&&h&&e.jsx(kk,{clipFunc:x?J=>{J.beginPath(),J.arc(s+b/2,t+b/2,b/2,0,Math.PI*2),J.closePath()}:void 0,children:e.jsx(fI,{image:h,x:s,y:t+(n-b)/2,width:b,height:b})}),p("name")&&l&&e.jsx(_6,{text:l,x:j,y:Z,width:k,fontSize:T,fontStyle:"bold",fill:a,ellipsis:!0,wrap:"none"}),(Z+=T+A,null),p("tagline")&&d&&e.jsxs(e.Fragment,{children:[e.jsx(_6,{text:d,x:j,y:Z,width:k,fontSize:E*1.1,fontStyle:"italic",fill:i,ellipsis:!0,wrap:"none"}),(Z+=E*1.1+A,null)]}),R||z?e.jsx(_6,{text:[o,c].filter(Boolean).join(" • "),x:j,y:Z,width:k,fontSize:E,fill:i,ellipsis:!0,wrap:"none"}):null,p("logo")&&m&&e.jsx(fI,{image:m,x:s+r-n*1.4,y:t+(n-n*.8)/2,width:n*1.4,height:n*.8})]})}function Xis(){const{data:s}=gz(),t=(s==null?void 0:s.find(Z=>Z.is_default))??(s==null?void 0:s[0])??null,[r,n]=S.useState(void 0),a=(s==null?void 0:s.find(Z=>Z.id===r))??t,[i,l]=S.useState([]),[o,c]=S.useState(0),[d,h]=S.useState("minimal-stripe"),[m,p]=S.useState({}),[x,y]=S.useState(!1),_=S.useRef(null),[b,j]=S.useState(780),k=S.useRef(null),T=Z=>{if(k.current&&(k.current.disconnect(),k.current=null),!Z)return;const J=()=>{const re=Z.clientWidth;re>0&&j(Math.min(780,re-16))};J();const K=new ResizeObserver(J);K.observe(Z),k.current=K};S.useEffect(()=>()=>{var Z;(Z=k.current)==null||Z.disconnect()},[]);const E=S.useRef(null),A=Z=>{if(!Z)return;const J=[];Array.from(Z).forEach(K=>{K.type.startsWith("image/")&&J.push({id:crypto.randomUUID(),url:URL.createObjectURL(K),file:K,name:K.name})}),l(K=>[...K,...J])},D=Z=>{l(J=>{const K=J.find(re=>re.id===Z);return K&&URL.revokeObjectURL(K.url),J.filter(re=>re.id!==Z)}),c(0)},R=typeof navigator<"u"&&/iPad|iPhone|iPod/.test(navigator.userAgent),z=Z=>{var ne;const[J,K]=Z.split(","),re=((ne=J.match(/:(.*?);/))==null?void 0:ne[1])??"image/jpeg",ie=atob(K),ce=new Uint8Array(ie.length);for(let le=0;le{var Z;if(E.current){y(!0);try{const J=E.current,K=J.toDataURL({pixelRatio:1/(J.scaleX()||1),mimeType:"image/jpeg",quality:.95}),ie=`${((Z=i[o])==null?void 0:Z.name.replace(/\.[^.]+$/,""))||"branded"}-branded.jpg`,ce=z(K),ne=URL.createObjectURL(ce);if(R)window.open(ne,"_blank")||(window.location.href=ne),he.success('Long-press the image and tap "Save to Photos"');else{const le=document.createElement("a");le.href=ne,le.download=ie,document.body.appendChild(le),le.click(),le.remove(),he.success("Image exported")}setTimeout(()=>URL.revokeObjectURL(ne),6e4)}catch(J){he.error(J.message||"Export failed")}finally{y(!1)}}},$=async()=>{if(i.length){y(!0);try{const Z=new Vdt,J=i.length,K=o;for(let ce=0;cesetTimeout(je,600)),!E.current)continue;const ne=E.current,be=ne.toDataURL({pixelRatio:1/(ne.scaleX()||1),mimeType:"image/jpeg",quality:.95}).split(",")[1],fe=i[ce].name.replace(/\.[^.]+$/,"")||`image-${ce+1}`;Z.file(`${fe}-branded.jpg`,be,{base64:!0})}c(K);const re=await Z.generateAsync({type:"blob"}),ie=document.createElement("a");ie.href=URL.createObjectURL(re),ie.download=`branded-images-${Date.now()}.zip`,ie.click(),URL.revokeObjectURL(ie.href),he.success(`${J} images exported`)}catch(Z){he.error(Z.message||"Batch export failed")}finally{y(!1)}}},ee=i[o];return e.jsx(Ss,{title:"Branding Bar Studio",children:e.jsxs("div",{className:"container max-w-7xl py-4 md:py-6 space-y-4 px-3 md:px-6",children:[e.jsx(el,{children:e.jsx("title",{children:"Branding Bar Studio | Marketing Studio"})}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-end sm:justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs(Xn,{to:"/marketing-studio",className:"text-sm text-muted-foreground inline-flex items-center gap-1 hover:underline",children:[e.jsx(za,{className:"h-3 w-3"})," Marketing Studio"]}),e.jsx("h1",{className:"text-2xl md:text-3xl font-bold tracking-tight mt-1",children:"Branding Bar Studio"}),e.jsx("p",{className:"text-sm md:text-base text-muted-foreground",children:"Drop in any image, get a branded export. No AI credits used."})]}),e.jsx(H,{variant:"outline",asChild:!0,className:"w-full sm:w-auto",children:e.jsxs(Xn,{to:"/marketing-studio/brand-kit",children:[e.jsx(pl,{className:"h-4 w-4 mr-1"})," Brand Kit"]})})]}),!a&&e.jsx(ke,{className:"border-dashed border-amber-500/50 bg-amber-500/5",children:e.jsxs(Oe,{className:"py-5 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold",children:"Create your brand kit first"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"We'll pre-fill it from your profile so you can be exporting in seconds."})]}),e.jsx(H,{asChild:!0,className:"w-full sm:w-auto",children:e.jsx(Xn,{to:"/marketing-studio/brand-kit",children:"Set up brand"})})]})}),e.jsxs("div",{className:"grid gap-6 lg:grid-cols-[1fr_360px]",children:[e.jsxs("div",{className:"space-y-4 min-w-0",children:[e.jsx(ke,{className:"overflow-hidden",children:e.jsxs(Oe,{className:"p-4",children:[ee?e.jsx("div",{ref:T,className:"flex justify-center bg-muted/30 rounded p-2 overflow-hidden",children:e.jsx(Yis,{imageUrl:ee.url,preset:a,barStyleId:d,overrides:m,maxDisplayWidth:b,stageRef:E})}):e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-12 text-center space-y-3 cursor-pointer hover:bg-muted/30 transition-colors",onClick:()=>{var Z;return(Z=_.current)==null?void 0:Z.click()},onDragOver:Z=>Z.preventDefault(),onDrop:Z=>{Z.preventDefault(),A(Z.dataTransfer.files)},children:[e.jsx(wl,{className:"h-12 w-12 mx-auto text-muted-foreground/60"}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-medium",children:"Drop images here or click to browse"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Add up to 50 photos at once. We'll batch-brand them all."})]}),e.jsxs(H,{type:"button",children:[e.jsx(Ea,{className:"h-4 w-4 mr-1"})," Choose images"]})]}),e.jsx("input",{ref:_,type:"file",accept:"image/*",multiple:!0,hidden:!0,onChange:Z=>A(Z.target.files)})]})}),i.length>0&&e.jsx(ke,{className:"overflow-hidden",children:e.jsx(Oe,{className:"p-3",children:e.jsxs("div",{className:"flex gap-2 overflow-x-auto py-1",children:[i.map((Z,J)=>e.jsxs("div",{className:"relative group flex-shrink-0",children:[e.jsx("button",{onClick:()=>c(J),className:`block h-16 w-16 rounded overflow-hidden border-2 transition-all ${J===o?"border-primary":"border-transparent hover:border-muted-foreground/30"}`,children:e.jsx("img",{src:Z.url,alt:"",className:"h-full w-full object-cover"})}),e.jsx("button",{onClick:()=>D(Z.id),className:"absolute -top-1 -right-1 bg-destructive text-destructive-foreground rounded-full p-0.5 opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx(Rr,{className:"h-3 w-3"})})]},Z.id)),e.jsx("button",{onClick:()=>{var Z;return(Z=_.current)==null?void 0:Z.click()},className:"flex-shrink-0 h-16 w-16 rounded border-2 border-dashed flex items-center justify-center hover:bg-muted/40",children:e.jsx(Ys,{className:"h-5 w-5 text-muted-foreground"})})]})})}),i.length>0&&e.jsxs("div",{className:"flex flex-wrap gap-2 justify-end",children:[e.jsx(H,{variant:"outline",onClick:()=>{i.forEach(Z=>URL.revokeObjectURL(Z.url)),l([])},children:"Clear all"}),e.jsxs(H,{onClick:O,disabled:x||!ee,children:[x?e.jsx(is,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(hi,{className:"h-4 w-4 mr-1"}),"Download this image"]}),i.length>1&&e.jsxs(H,{onClick:$,disabled:x,children:[x?e.jsx(is,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(hi,{className:"h-4 w-4 mr-1"}),"Download all (",i.length,") as ZIP"]})]})]}),e.jsxs("div",{className:"space-y-4 min-w-0",children:[e.jsxs(ke,{className:"overflow-hidden",children:[e.jsx(Ot,{className:"pb-2",children:e.jsx(zt,{className:"text-base",children:"Brand preset"})}),e.jsx(Oe,{children:e.jsxs(Bs,{value:(a==null?void 0:a.id)??"",onValueChange:n,children:[e.jsx(Os,{children:e.jsx(Us,{placeholder:"Choose preset"})}),e.jsx(Fs,{children:s==null?void 0:s.map(Z=>e.jsxs(pt,{value:Z.id,children:[Z.name," ",Z.is_default?"(default)":""]},Z.id))})]})})]}),e.jsxs(ke,{className:"overflow-hidden",children:[e.jsx(Ot,{className:"pb-2",children:e.jsx(zt,{className:"text-base",children:"Bar style"})}),e.jsx(Oe,{children:e.jsx(wrs,{value:d,onChange:h,mediaType:"image"})})]}),e.jsxs(ke,{className:"overflow-hidden",children:[e.jsx(Ot,{className:"pb-2",children:e.jsx(zt,{className:"text-base",children:"Tweak this design"})}),e.jsx(Oe,{children:e.jsxs(ta,{defaultValue:"text",children:[e.jsxs(Qn,{className:"grid grid-cols-2 w-full",children:[e.jsx(ts,{value:"text",children:"Text"}),e.jsx(ts,{value:"colors",children:"Colors"})]}),e.jsxs(cs,{value:"text",className:"space-y-3 pt-3",children:[e.jsxs("div",{children:[e.jsx(ue,{children:"Display name"}),e.jsx(Se,{value:m.display_name??(a==null?void 0:a.display_name)??"",onChange:Z=>p({...m,display_name:Z.target.value})})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Phone"}),e.jsx(Se,{value:m.phone??(a==null?void 0:a.phone)??"",onChange:Z=>p({...m,phone:Z.target.value})})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Email"}),e.jsx(Se,{value:m.email??(a==null?void 0:a.email)??"",onChange:Z=>p({...m,email:Z.target.value})})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Tagline"}),e.jsx(Se,{value:m.tagline??(a==null?void 0:a.tagline)??"",onChange:Z=>p({...m,tagline:Z.target.value})})]})]}),e.jsxs(cs,{value:"colors",className:"space-y-3 pt-3",children:[e.jsxs("div",{children:[e.jsx(ue,{children:"Bar color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:m.brand_color??(a==null?void 0:a.brand_color)??"#0f172a",onChange:Z=>p({...m,brand_color:Z.target.value}),className:"h-10 w-14 rounded border cursor-pointer"}),e.jsx(Se,{value:m.brand_color??(a==null?void 0:a.brand_color)??"#0f172a",onChange:Z=>p({...m,brand_color:Z.target.value})})]})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Accent line"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:m.accent_color??(a==null?void 0:a.accent_color)??"#3b82f6",onChange:Z=>p({...m,accent_color:Z.target.value}),className:"h-10 w-14 rounded border cursor-pointer"}),e.jsx(Se,{value:m.accent_color??(a==null?void 0:a.accent_color)??"#3b82f6",onChange:Z=>p({...m,accent_color:Z.target.value})})]})]}),e.jsx(H,{variant:"ghost",size:"sm",onClick:()=>p({}),children:"Reset to preset"})]})]})})]})]})]})]})})}function Qis(s,t){if(s.match(/^[a-z]+:\/\//i))return s;if(s.match(/^\/\//))return window.location.protocol+s;if(s.match(/^[a-z]+:/i))return s;const r=document.implementation.createHTMLDocument(),n=r.createElement("base"),a=r.createElement("a");return r.head.appendChild(n),r.body.appendChild(a),t&&(n.href=t),a.href=s,a.href}const Jis=(()=>{let s=0;const t=()=>`0000${(Math.random()*36**4<<0).toString(36)}`.slice(-4);return()=>(s+=1,`u${t()}${s}`)})();function oS(s){const t=[];for(let r=0,n=s.length;rFx||s.height>Fx)&&(s.width>Fx&&s.height>Fx?s.width>s.height?(s.height*=Fx/s.width,s.width=Fx):(s.width*=Fx/s.height,s.height=Fx):s.width>Fx?(s.height*=Fx/s.width,s.width=Fx):(s.width*=Fx/s.height,s.height=Fx))}function Yme(s){return new Promise((t,r)=>{const n=new Image;n.onload=()=>{n.decode().then(()=>{requestAnimationFrame(()=>t(n))})},n.onerror=r,n.crossOrigin="anonymous",n.decoding="async",n.src=s})}async function nos(s){return Promise.resolve().then(()=>new XMLSerializer().serializeToString(s)).then(encodeURIComponent).then(t=>`data:image/svg+xml;charset=utf-8,${t}`)}async function aos(s,t,r){const n="http://www.w3.org/2000/svg",a=document.createElementNS(n,"svg"),i=document.createElementNS(n,"foreignObject");return a.setAttribute("width",`${t}`),a.setAttribute("height",`${r}`),a.setAttribute("viewBox",`0 0 ${t} ${r}`),i.setAttribute("width","100%"),i.setAttribute("height","100%"),i.setAttribute("x","0"),i.setAttribute("y","0"),i.setAttribute("externalResourcesRequired","true"),a.appendChild(i),i.appendChild(s),nos(a)}const mx=(s,t)=>{if(s instanceof t)return!0;const r=Object.getPrototypeOf(s);return r===null?!1:r.constructor.name===t.name||mx(r,t)};function ios(s){const t=s.getPropertyValue("content");return`${s.cssText} content: '${t.replace(/'|"/g,"")}';`}function oos(s,t){return Iut(t).map(r=>{const n=s.getPropertyValue(r),a=s.getPropertyPriority(r);return`${r}: ${n}${a?" !important":""};`}).join(" ")}function los(s,t,r,n){const a=`.${s}:${t}`,i=r.cssText?ios(r):oos(r,n);return document.createTextNode(`${a}{${i}}`)}function Fze(s,t,r,n){const a=window.getComputedStyle(s,r),i=a.getPropertyValue("content");if(i===""||i==="none")return;const l=Jis();try{t.className=`${t.className} ${l}`}catch{return}const o=document.createElement("style");o.appendChild(los(l,r,a,n)),t.appendChild(o)}function cos(s,t,r){Fze(s,t,":before",r),Fze(s,t,":after",r)}const Bze="application/font-woff",zze="image/jpeg",dos={woff:Bze,woff2:Bze,ttf:"application/font-truetype",eot:"application/vnd.ms-fontobject",png:"image/png",jpg:zze,jpeg:zze,gif:"image/gif",tiff:"image/tiff",svg:"image/svg+xml",webp:"image/webp"};function uos(s){const t=/\.([^./]*?)$/g.exec(s);return t?t[1]:""}function PEe(s){const t=uos(s).toLowerCase();return dos[t]||""}function hos(s){return s.split(/,/)[1]}function $ke(s){return s.search(/^(data:)/)!==-1}function mos(s,t){return`data:${t};base64,${s}`}async function Lut(s,t,r){const n=await fetch(s,t);if(n.status===404)throw new Error(`Resource "${n.url}" not found`);const a=await n.blob();return new Promise((i,l)=>{const o=new FileReader;o.onerror=l,o.onloadend=()=>{try{i(r({res:n,result:o.result}))}catch(c){l(c)}},o.readAsDataURL(a)})}const N_e={};function fos(s,t,r){let n=s.replace(/\?.*/,"");return r&&(n=s),/ttf|otf|eot|woff2?/i.test(n)&&(n=n.replace(/.*\//,"")),t?`[${t}]${n}`:n}async function LEe(s,t,r){const n=fos(s,t,r.includeQueryParams);if(N_e[n]!=null)return N_e[n];r.cacheBust&&(s+=(/\?/.test(s)?"&":"?")+new Date().getTime());let a;try{const i=await Lut(s,r.fetchRequestInit,({res:l,result:o})=>(t||(t=l.headers.get("Content-Type")||""),hos(o)));a=mos(i,t)}catch(i){a=r.imagePlaceholder||"";let l=`Failed to fetch resource: ${s}`;i&&(l=typeof i=="string"?i:i.message),l&&console.warn(l)}return N_e[n]=a,a}async function pos(s){const t=s.toDataURL();return t==="data:,"?s.cloneNode(!1):Yme(t)}async function gos(s,t){if(s.currentSrc){const i=document.createElement("canvas"),l=i.getContext("2d");i.width=s.clientWidth,i.height=s.clientHeight,l==null||l.drawImage(s,0,0,i.width,i.height);const o=i.toDataURL();return Yme(o)}const r=s.poster,n=PEe(r),a=await LEe(r,n,t);return Yme(a)}async function xos(s,t){var r;try{if(!((r=s==null?void 0:s.contentDocument)===null||r===void 0)&&r.body)return await kxe(s.contentDocument.body,t,!0)}catch{}return s.cloneNode(!1)}async function yos(s,t){return mx(s,HTMLCanvasElement)?pos(s):mx(s,HTMLVideoElement)?gos(s,t):mx(s,HTMLIFrameElement)?xos(s,t):s.cloneNode(Dut(s))}const vos=s=>s.tagName!=null&&s.tagName.toUpperCase()==="SLOT",Dut=s=>s.tagName!=null&&s.tagName.toUpperCase()==="SVG";async function bos(s,t,r){var n,a;if(Dut(t))return t;let i=[];return vos(s)&&s.assignedNodes?i=oS(s.assignedNodes()):mx(s,HTMLIFrameElement)&&(!((n=s.contentDocument)===null||n===void 0)&&n.body)?i=oS(s.contentDocument.body.childNodes):i=oS(((a=s.shadowRoot)!==null&&a!==void 0?a:s).childNodes),i.length===0||mx(s,HTMLVideoElement)||await i.reduce((l,o)=>l.then(()=>kxe(o,r)).then(c=>{c&&t.appendChild(c)}),Promise.resolve()),t}function _os(s,t,r){const n=t.style;if(!n)return;const a=window.getComputedStyle(s);a.cssText?(n.cssText=a.cssText,n.transformOrigin=a.transformOrigin):Iut(r).forEach(i=>{let l=a.getPropertyValue(i);i==="font-size"&&l.endsWith("px")&&(l=`${Math.floor(parseFloat(l.substring(0,l.length-2)))-.1}px`),mx(s,HTMLIFrameElement)&&i==="display"&&l==="inline"&&(l="block"),i==="d"&&t.getAttribute("d")&&(l=`path(${t.getAttribute("d")})`),n.setProperty(i,l,a.getPropertyPriority(i))})}function wos(s,t){mx(s,HTMLTextAreaElement)&&(t.innerHTML=s.value),mx(s,HTMLInputElement)&&t.setAttribute("value",s.value)}function jos(s,t){if(mx(s,HTMLSelectElement)){const r=t,n=Array.from(r.children).find(a=>s.value===a.getAttribute("value"));n&&n.setAttribute("selected","")}}function Nos(s,t,r){return mx(t,Element)&&(_os(s,t,r),cos(s,t,r),wos(s,t),jos(s,t)),t}async function kos(s,t){const r=s.querySelectorAll?s.querySelectorAll("use"):[];if(r.length===0)return s;const n={};for(let i=0;iyos(n,t)).then(n=>bos(s,n,t)).then(n=>Nos(s,n,t)).then(n=>kos(n,t))}const Rut=/url\((['"]?)([^'"]+?)\1\)/g,Sos=/url\([^)]+\)\s*format\((["']?)([^"']+)\1\)/g,Cos=/src:\s*(?:url\([^)]+\)\s*format\([^)]+\)[,;]\s*)+/g;function Tos(s){const t=s.replace(/([.*+?^${}()|\[\]\/\\])/g,"\\$1");return new RegExp(`(url\\(['"]?)(${t})(['"]?\\))`,"g")}function Eos(s){const t=[];return s.replace(Rut,(r,n,a)=>(t.push(a),r)),t.filter(r=>!$ke(r))}async function Aos(s,t,r,n,a){try{const i=r?Qis(t,r):t,l=PEe(t);let o;return a||(o=await LEe(i,l,n)),s.replace(Tos(t),`$1${o}$3`)}catch{}return s}function Mos(s,{preferredFontFormat:t}){return t?s.replace(Cos,r=>{for(;;){const[n,,a]=Sos.exec(r)||[];if(!a)return"";if(a===t)return`src: ${n};`}}):s}function Out(s){return s.search(Rut)!==-1}async function Fut(s,t,r){if(!Out(s))return s;const n=Mos(s,r);return Eos(n).reduce((i,l)=>i.then(o=>Aos(o,l,t,r)),Promise.resolve(n))}async function j6(s,t,r){var n;const a=(n=t.style)===null||n===void 0?void 0:n.getPropertyValue(s);if(a){const i=await Fut(a,null,r);return t.style.setProperty(s,i,t.style.getPropertyPriority(s)),!0}return!1}async function Ios(s,t){await j6("background",s,t)||await j6("background-image",s,t),await j6("mask",s,t)||await j6("-webkit-mask",s,t)||await j6("mask-image",s,t)||await j6("-webkit-mask-image",s,t)}async function Pos(s,t){const r=mx(s,HTMLImageElement);if(!(r&&!$ke(s.src))&&!(mx(s,SVGImageElement)&&!$ke(s.href.baseVal)))return;const n=r?s.src:s.href.baseVal,a=await LEe(n,PEe(n),t);await new Promise((i,l)=>{s.onload=i,s.onerror=t.onImageErrorHandler?(...c)=>{try{i(t.onImageErrorHandler(...c))}catch(d){l(d)}}:l;const o=s;o.decode&&(o.decode=i),o.loading==="lazy"&&(o.loading="eager"),r?(s.srcset="",s.src=a):s.href.baseVal=a})}async function Los(s,t){const n=oS(s.childNodes).map(a=>But(a,t));await Promise.all(n).then(()=>s)}async function But(s,t){mx(s,Element)&&(await Ios(s,t),await Pos(s,t),await Los(s,t))}function Dos(s,t){const{style:r}=s;t.backgroundColor&&(r.backgroundColor=t.backgroundColor),t.width&&(r.width=`${t.width}px`),t.height&&(r.height=`${t.height}px`);const n=t.style;return n!=null&&Object.keys(n).forEach(a=>{r[a]=n[a]}),s}const $ze={};async function Uze(s){let t=$ze[s];if(t!=null)return t;const n=await(await fetch(s)).text();return t={url:s,cssText:n},$ze[s]=t,t}async function qze(s,t){let r=s.cssText;const n=/url\(["']?([^"')]+)["']?\)/g,i=(r.match(/url\([^)]+\)/g)||[]).map(async l=>{let o=l.replace(n,"$1");return o.startsWith("https://")||(o=new URL(o,s.url).href),Lut(o,t.fetchRequestInit,({result:c})=>(r=r.replace(l,`url(${c})`),[l,c]))});return Promise.all(i).then(()=>r)}function Vze(s){if(s==null)return[];const t=[],r=/(\/\*[\s\S]*?\*\/)/gi;let n=s.replace(r,"");const a=new RegExp("((@.*?keyframes [\\s\\S]*?){([\\s\\S]*?}\\s*?)})","gi");for(;;){const c=a.exec(n);if(c===null)break;t.push(c[0])}n=n.replace(a,"");const i=/@import[\s\S]*?url\([^)]*\)[\s\S]*?;/gi,l="((\\s*?(?:\\/\\*[\\s\\S]*?\\*\\/)?\\s*?@media[\\s\\S]*?){([\\s\\S]*?)}\\s*?})|(([\\s\\S]*?){([\\s\\S]*?)})",o=new RegExp(l,"gi");for(;;){let c=i.exec(n);if(c===null){if(c=o.exec(n),c===null)break;i.lastIndex=o.lastIndex}else o.lastIndex=i.lastIndex;t.push(c[0])}return t}async function Ros(s,t){const r=[],n=[];return s.forEach(a=>{if("cssRules"in a)try{oS(a.cssRules||[]).forEach((i,l)=>{if(i.type===CSSRule.IMPORT_RULE){let o=l+1;const c=i.href,d=Uze(c).then(h=>qze(h,t)).then(h=>Vze(h).forEach(m=>{try{a.insertRule(m,m.startsWith("@import")?o+=1:a.cssRules.length)}catch(p){console.error("Error inserting rule from remote css",{rule:m,error:p})}})).catch(h=>{console.error("Error loading remote css",h.toString())});n.push(d)}})}catch(i){const l=s.find(o=>o.href==null)||document.styleSheets[0];a.href!=null&&n.push(Uze(a.href).then(o=>qze(o,t)).then(o=>Vze(o).forEach(c=>{l.insertRule(c,l.cssRules.length)})).catch(o=>{console.error("Error loading remote stylesheet",o)})),console.error("Error inlining remote css file",i)}}),Promise.all(n).then(()=>(s.forEach(a=>{if("cssRules"in a)try{oS(a.cssRules||[]).forEach(i=>{r.push(i)})}catch(i){console.error(`Error while reading CSS rules from ${a.href}`,i)}}),r))}function Oos(s){return s.filter(t=>t.type===CSSRule.FONT_FACE_RULE).filter(t=>Out(t.style.getPropertyValue("src")))}async function Fos(s,t){if(s.ownerDocument==null)throw new Error("Provided element is not within a Document");const r=oS(s.ownerDocument.styleSheets),n=await Ros(r,t);return Oos(n)}function zut(s){return s.trim().replace(/["']/g,"")}function Bos(s){const t=new Set;function r(n){(n.style.fontFamily||getComputedStyle(n).fontFamily).split(",").forEach(i=>{t.add(zut(i))}),Array.from(n.children).forEach(i=>{i instanceof HTMLElement&&r(i)})}return r(s),t}async function zos(s,t){const r=await Fos(s,t),n=Bos(s);return(await Promise.all(r.filter(i=>n.has(zut(i.style.fontFamily))).map(i=>{const l=i.parentStyleSheet?i.parentStyleSheet.href:null;return Fut(i.cssText,l,t)}))).join(` `)}async function $os(s,t){const r=t.fontEmbedCSS!=null?t.fontEmbedCSS:t.skipFonts?null:await zos(s,t);if(r){const n=document.createElement("style"),a=document.createTextNode(r);n.appendChild(a),s.firstChild?s.insertBefore(n,s.firstChild):s.appendChild(n)}}async function Uos(s,t={}){const{width:r,height:n}=Put(s,t),a=await kxe(s,t,!0);return await $os(a,t),await But(a,t),Dos(a,t),await aos(a,r,n)}async function qos(s,t={}){const{width:r,height:n}=Put(s,t),a=await Uos(s,t),i=await Yme(a),l=document.createElement("canvas"),o=l.getContext("2d"),c=t.pixelRatio||sos(),d=t.canvasWidth||r,h=t.canvasHeight||n;return l.width=d*c,l.height=h*c,t.skipAutoScale||ros(l),l.style.width=`${d}`,l.style.height=`${h}`,t.backgroundColor&&(o.fillStyle=t.backgroundColor,o.fillRect(0,0,l.width,l.height)),o.drawImage(i,0,0,l.width,l.height),l}async function DEe(s,t={}){return(await qos(s,t)).toDataURL()}const mL=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s),Sxe={"just-listed":"JUST LISTED","just-sold":"JUST SOLD","open-house":"OPEN HOUSE","price-drop":"PRICE DROP"},Sk={"instagram-square":{width:1080,height:1080},"instagram-story":{width:1080,height:1920},"facebook-post":{width:1200,height:630}},Vos=({branding:s,dim:t})=>!(s!=null&&s.enabled)||!s.agentName?null:e.jsxs("div",{style:{marginTop:t.w*.03,borderTop:"2px solid rgba(201,168,76,0.4)",paddingTop:t.w*.025,display:"flex",alignItems:"center",gap:t.w*.025},children:[s.agentPhotoUrl&&e.jsx("img",{src:s.agentPhotoUrl,alt:"",crossOrigin:"anonymous",style:{width:t.w*.12,height:t.w*.12,borderRadius:"50%",objectFit:"cover",border:"3px solid rgba(201,168,76,0.7)"}}),e.jsxs("div",{children:[e.jsx("div",{style:{fontSize:t.w*.038,fontWeight:700,letterSpacing:"0.03em"},children:s.agentName}),s.brokerage&&e.jsx("div",{style:{fontSize:t.w*.026,opacity:.8,marginTop:t.w*.005},children:s.brokerage})]})]}),REe=Nt.forwardRef(({listing:s,postType:t,format:r,branding:n,selectedPhotoIndex:a},i)=>{var m;const l=r==="instagram-story"?{w:1080,h:1920}:r==="facebook-post"?{w:1200,h:630}:{w:1080,h:1080},o=400/l.w,c=(m=s.photos)==null?void 0:m[a],d=Sxe[t],h=[s.bedrooms?`${s.bedrooms} Bed`:null,s.bathrooms?`${s.bathrooms} Bath`:null,s.sqft?`${s.sqft.toLocaleString()} Sq Ft`:null].filter(Boolean).join(" • ");return e.jsxs("div",{ref:i,style:{width:l.w,height:l.h,transform:`scale(${o})`,transformOrigin:"top left",position:"relative",overflow:"hidden",fontFamily:"'Georgia', 'Times New Roman', serif",color:"#FFFFFF"},children:[c&&e.jsx("img",{src:c,alt:"",crossOrigin:"anonymous",style:{position:"absolute",inset:0,width:"100%",height:"100%",objectFit:"cover"}}),e.jsx("div",{style:{position:"absolute",inset:0,background:"linear-gradient(180deg, rgba(10,10,30,0.3) 0%, rgba(10,10,30,0.85) 100%)"}}),e.jsxs("div",{style:{position:"relative",height:"100%",display:"flex",flexDirection:"column",justifyContent:"space-between",padding:l.w*.06},children:[e.jsx("div",{children:e.jsx("div",{style:{display:"inline-block",background:"linear-gradient(135deg, #C9A84C, #E8D48B)",color:"#1A1A2E",padding:`${l.w*.012}px ${l.w*.035}px`,fontSize:l.w*.032,fontWeight:700,letterSpacing:"0.25em",textTransform:"uppercase"},children:d})}),e.jsxs("div",{children:[e.jsx("div",{style:{fontSize:l.w*.07,fontWeight:700,lineHeight:1.1,marginBottom:l.w*.015,textShadow:"0 2px 12px rgba(0,0,0,0.5)"},children:mL(s.price)}),t==="just-sold"&&s.soldPrice&&e.jsxs("div",{style:{fontSize:l.w*.028,color:"#C9A84C",marginBottom:l.w*.01},children:["Sold for ",mL(s.soldPrice)]}),e.jsx("div",{style:{fontSize:l.w*.028,opacity:.9,marginBottom:l.w*.008},children:s.address}),e.jsxs("div",{style:{fontSize:l.w*.022,opacity:.7,marginBottom:l.w*.02},children:[s.city,", ",s.state," ",s.zip]}),e.jsx("div",{style:{display:"flex",gap:l.w*.015,fontSize:l.w*.022,letterSpacing:"0.05em",borderTop:"1px solid rgba(201,168,76,0.4)",paddingTop:l.w*.02},children:e.jsx("span",{children:h})}),t==="open-house"&&e.jsx("div",{style:{marginTop:l.w*.02,background:"rgba(201,168,76,0.15)",border:"1px solid rgba(201,168,76,0.4)",padding:`${l.w*.01}px ${l.w*.02}px`,fontSize:l.w*.024,letterSpacing:"0.1em",display:"inline-block"},children:"SAT & SUN • 1–4 PM"}),e.jsx(Vos,{branding:n,dim:l})]})]})]})});REe.displayName="LuxuryDarkTemplate";const Hos=({branding:s,dim:t,accentColor:r})=>!(s!=null&&s.enabled)||!s.agentName?null:e.jsxs("div",{style:{borderTop:"2px solid #E5E7EB",paddingTop:t.w*.025,display:"flex",alignItems:"center",justifyContent:"center",gap:t.w*.025},children:[s.agentPhotoUrl&&e.jsx("img",{src:s.agentPhotoUrl,alt:"",crossOrigin:"anonymous",style:{width:t.w*.14,height:t.w*.14,borderRadius:"50%",objectFit:"cover",border:`3px solid ${r}`,flexShrink:0}}),e.jsxs("div",{children:[e.jsx("div",{style:{fontSize:t.w*.042,fontWeight:800,color:"#1A1A1A"},children:s.agentName}),s.brokerage&&e.jsx("div",{style:{fontSize:t.w*.028,color:"#6B7280",marginTop:t.w*.005},children:s.brokerage})]})]}),OEe=Nt.forwardRef(({listing:s,postType:t,format:r,branding:n,selectedPhotoIndex:a},i)=>{var x;const l=r==="instagram-story"?{w:1080,h:1920}:r==="facebook-post"?{w:1200,h:630}:{w:1080,h:1080},o=400/l.w,c=(x=s.photos)==null?void 0:x[a],d=Sxe[t],h=r==="instagram-story",m=r==="facebook-post",p=t==="just-sold"?"#7C3AED":t==="open-house"?"#2563EB":t==="price-drop"?"#DC2626":"#059669";return e.jsxs("div",{ref:i,style:{width:l.w,height:l.h,transform:`scale(${o})`,transformOrigin:"top left",position:"relative",overflow:"hidden",fontFamily:"'Helvetica Neue', Arial, sans-serif",color:"#1A1A1A",background:"#FFFFFF",display:"flex",flexDirection:m?"row":"column"},children:[e.jsxs("div",{style:{width:m?"55%":"100%",height:m?"100%":h?"50%":"52%",position:"relative",overflow:"hidden",flexShrink:0},children:[c&&e.jsx("img",{src:c,alt:"",crossOrigin:"anonymous",style:{width:"100%",height:"100%",objectFit:"cover"}}),e.jsx("div",{style:{position:"absolute",top:l.w*.04,left:0,background:p,color:"#FFFFFF",padding:`${l.w*.012}px ${l.w*.04}px`,fontSize:l.w*.026,fontWeight:800,letterSpacing:"0.15em"},children:d})]}),e.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",justifyContent:"center",padding:l.w*.05},children:[e.jsx("div",{style:{fontSize:l.w*(m?.055:.065),fontWeight:800,lineHeight:1.1,color:p,marginBottom:l.w*.012},children:mL(s.price)}),e.jsx("div",{style:{fontSize:l.w*.026,fontWeight:600,marginBottom:l.w*.006},children:s.address}),e.jsxs("div",{style:{fontSize:l.w*.02,color:"#6B7280",marginBottom:l.w*.02},children:[s.city,", ",s.state," ",s.zip]}),e.jsxs("div",{style:{display:"flex",gap:l.w*.03,marginBottom:l.w*.02},children:[s.bedrooms>0&&e.jsxs("div",{style:{textAlign:"center"},children:[e.jsx("div",{style:{fontSize:l.w*.035,fontWeight:700},children:s.bedrooms}),e.jsx("div",{style:{fontSize:l.w*.016,color:"#9CA3AF",textTransform:"uppercase",letterSpacing:"0.1em"},children:"Beds"})]}),s.bathrooms>0&&e.jsxs("div",{style:{textAlign:"center"},children:[e.jsx("div",{style:{fontSize:l.w*.035,fontWeight:700},children:s.bathrooms}),e.jsx("div",{style:{fontSize:l.w*.016,color:"#9CA3AF",textTransform:"uppercase",letterSpacing:"0.1em"},children:"Baths"})]}),s.sqft>0&&e.jsxs("div",{style:{textAlign:"center"},children:[e.jsx("div",{style:{fontSize:l.w*.035,fontWeight:700},children:s.sqft.toLocaleString()}),e.jsx("div",{style:{fontSize:l.w*.016,color:"#9CA3AF",textTransform:"uppercase",letterSpacing:"0.1em"},children:"Sq Ft"})]})]}),t==="open-house"&&e.jsx("div",{style:{background:`${p}10`,border:`2px solid ${p}`,borderRadius:l.w*.01,padding:`${l.w*.01}px ${l.w*.02}px`,fontSize:l.w*.022,fontWeight:700,color:p,display:"inline-block",marginBottom:l.w*.015},children:"SAT & SUN • 1–4 PM"}),e.jsx(Hos,{branding:n,dim:l,accentColor:p})]})]})});OEe.displayName="ModernCleanTemplate";const Gos=({branding:s,dim:t})=>!(s!=null&&s.enabled)||!s.agentName?null:e.jsxs("div",{style:{marginTop:t.w*.025,display:"flex",alignItems:"center",gap:t.w*.02},children:[s.agentPhotoUrl&&e.jsx("img",{src:s.agentPhotoUrl,alt:"",crossOrigin:"anonymous",style:{width:t.w*.12,height:t.w*.12,borderRadius:"50%",objectFit:"cover",border:"3px solid rgba(255,255,255,0.5)"}}),e.jsxs("div",{children:[e.jsx("div",{style:{fontSize:t.w*.035,fontWeight:900},children:s.agentName}),s.brokerage&&e.jsx("div",{style:{fontSize:t.w*.024,opacity:.8,marginTop:t.w*.004,fontFamily:"'Helvetica Neue', sans-serif",fontWeight:400},children:s.brokerage})]})]}),FEe=Nt.forwardRef(({listing:s,postType:t,format:r,branding:n,selectedPhotoIndex:a},i)=>{var p;const l=r==="instagram-story"?{w:1080,h:1920}:r==="facebook-post"?{w:1200,h:630}:{w:1080,h:1080},o=400/l.w,c=(p=s.photos)==null?void 0:p[a],d=Sxe[t],h={"just-listed":"linear-gradient(135deg, #059669, #10B981)","just-sold":"linear-gradient(135deg, #7C3AED, #A855F7)","open-house":"linear-gradient(135deg, #2563EB, #3B82F6)","price-drop":"linear-gradient(135deg, #DC2626, #F43F5E)"},m=[s.bedrooms?`${s.bedrooms} BD`:null,s.bathrooms?`${s.bathrooms} BA`:null,s.sqft?`${s.sqft.toLocaleString()} SF`:null].filter(Boolean).join(" | ");return e.jsxs("div",{ref:i,style:{width:l.w,height:l.h,transform:`scale(${o})`,transformOrigin:"top left",position:"relative",overflow:"hidden",fontFamily:"'Arial Black', 'Helvetica Neue', sans-serif",color:"#FFFFFF"},children:[c&&e.jsx("img",{src:c,alt:"",crossOrigin:"anonymous",style:{position:"absolute",inset:0,width:"100%",height:"100%",objectFit:"cover"}}),e.jsx("div",{style:{position:"absolute",inset:0,background:"rgba(0,0,0,0.4)"}}),e.jsxs("div",{style:{position:"relative",height:"100%",display:"flex",flexDirection:"column",padding:l.w*.05},children:[e.jsx("div",{style:{background:h[t],padding:`${l.w*.025}px ${l.w*.04}px`,fontSize:l.w*.055,fontWeight:900,letterSpacing:"0.08em",alignSelf:"flex-start",borderRadius:l.w*.01,boxShadow:"0 8px 32px rgba(0,0,0,0.3)",transform:"rotate(-2deg)",marginBottom:l.w*.03},children:d}),e.jsx("div",{style:{flex:1}}),e.jsxs("div",{style:{background:"rgba(0,0,0,0.65)",backdropFilter:"blur(10px)",borderRadius:l.w*.015,padding:l.w*.04},children:[e.jsx("div",{style:{fontSize:l.w*.08,fontWeight:900,lineHeight:1,marginBottom:l.w*.01},children:mL(s.price)}),e.jsx("div",{style:{fontSize:l.w*.028,fontWeight:700,marginBottom:l.w*.005},children:s.address}),e.jsxs("div",{style:{fontSize:l.w*.022,opacity:.8,marginBottom:l.w*.015},children:[s.city,", ",s.state," ",s.zip]}),e.jsx("div",{style:{display:"inline-block",background:"rgba(255,255,255,0.15)",borderRadius:l.w*.008,padding:`${l.w*.01}px ${l.w*.02}px`,fontSize:l.w*.022,fontWeight:700,letterSpacing:"0.08em"},children:m}),t==="open-house"&&e.jsx("div",{style:{marginTop:l.w*.015,background:h["open-house"],borderRadius:l.w*.008,padding:`${l.w*.012}px ${l.w*.025}px`,fontSize:l.w*.024,fontWeight:800,display:"inline-block",marginLeft:l.w*.01},children:"SAT & SUN 1–4 PM"}),e.jsx(Gos,{branding:n,dim:l})]})]})]})});FEe.displayName="BoldColorfulTemplate";const Wos=({branding:s,dim:t})=>!(s!=null&&s.enabled)||!s.agentName?null:e.jsxs("div",{style:{marginTop:"auto",display:"flex",alignItems:"center",gap:t.w*.02},children:[s.agentPhotoUrl&&e.jsx("img",{src:s.agentPhotoUrl,alt:"",crossOrigin:"anonymous",style:{width:t.w*.11,height:t.w*.11,borderRadius:"50%",objectFit:"cover",border:"3px solid #8B7355"}}),e.jsxs("div",{children:[e.jsx("div",{style:{fontSize:t.w*.032,fontWeight:700,color:"#1A1A1A"},children:s.agentName}),s.brokerage&&e.jsx("div",{style:{fontSize:t.w*.022,color:"#8B7355",marginTop:t.w*.004},children:s.brokerage})]})]}),BEe=Nt.forwardRef(({listing:s,postType:t,format:r,branding:n,selectedPhotoIndex:a},i)=>{var m;const l=r==="instagram-story"?{w:1080,h:1920}:r==="facebook-post"?{w:1200,h:630}:{w:1080,h:1080},o=400/l.w,c=(m=s.photos)==null?void 0:m[a],d=Sxe[t],h=r==="instagram-story";return e.jsx("div",{ref:i,style:{width:l.w,height:l.h,transform:`scale(${o})`,transformOrigin:"top left",position:"relative",overflow:"hidden",fontFamily:"'Georgia', 'Times New Roman', serif",color:"#1A1A1A",background:"#F5F0EB"},children:e.jsxs("div",{style:{display:"flex",flexDirection:h?"column":"row",height:"100%"},children:[e.jsxs("div",{style:{width:h?"100%":"42%",height:h?"40%":"100%",display:"flex",flexDirection:"column",justifyContent:"center",padding:l.w*.05,order:h?2:1},children:[e.jsx("div",{style:{fontSize:l.w*.016,letterSpacing:"0.3em",textTransform:"uppercase",color:"#8B7355",borderBottom:"2px solid #8B7355",paddingBottom:l.w*.01,marginBottom:l.w*.025,display:"inline-block",alignSelf:"flex-start"},children:d}),e.jsx("div",{style:{fontSize:l.w*(h?.06:.055),fontWeight:700,lineHeight:1.1,marginBottom:l.w*.015,fontStyle:"italic"},children:mL(s.price)}),t==="just-sold"&&s.soldPrice&&e.jsxs("div",{style:{fontSize:l.w*.02,color:"#8B7355",marginBottom:l.w*.01},children:["Sold: ",mL(s.soldPrice)]}),e.jsxs("div",{style:{fontSize:l.w*.022,lineHeight:1.5,marginBottom:l.w*.02},children:[s.address,e.jsx("br",{}),s.city,", ",s.state," ",s.zip]}),e.jsxs("div",{style:{display:"flex",gap:l.w*.02,fontSize:l.w*.016,color:"#6B5D4E",borderTop:"1px solid #D1C7B7",paddingTop:l.w*.015,marginBottom:l.w*.015,flexWrap:"wrap"},children:[s.bedrooms>0&&e.jsxs("span",{children:[s.bedrooms," Bedrooms"]}),s.bedrooms>0&&s.bathrooms>0&&e.jsx("span",{children:"·"}),s.bathrooms>0&&e.jsxs("span",{children:[s.bathrooms," Bathrooms"]}),s.sqft>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"·"}),e.jsxs("span",{children:[s.sqft.toLocaleString()," Sq Ft"]})]})]}),t==="open-house"&&e.jsx("div",{style:{fontSize:l.w*.018,fontStyle:"italic",color:"#8B7355",marginBottom:l.w*.01},children:"Open House: Saturday & Sunday, 1–4 PM"}),e.jsx(Wos,{branding:n,dim:l})]}),e.jsxs("div",{style:{width:h?"100%":"58%",height:h?"60%":"100%",position:"relative",overflow:"hidden",order:h?1:2},children:[c&&e.jsx("img",{src:c,alt:"",crossOrigin:"anonymous",style:{width:"100%",height:"100%",objectFit:"cover"}}),e.jsx("div",{style:{position:"absolute",inset:l.w*.02,border:"1px solid rgba(255,255,255,0.4)",pointerEvents:"none"}})]})]})})});BEe.displayName="EditorialTemplate";const Kos=[{value:"just-listed",label:"Just Listed",icon:"🏠"},{value:"just-sold",label:"Just Sold",icon:"🎉"},{value:"open-house",label:"Open House",icon:"🚪"},{value:"price-drop",label:"Price Drop",icon:"📉"}],Hze=[{value:"instagram-square",label:"IG Post",dimensions:"1080×1080",icon:e.jsx(yu,{className:"h-4 w-4"})},{value:"instagram-story",label:"IG Story",dimensions:"1080×1920",icon:e.jsx(yu,{className:"h-4 w-4"})},{value:"facebook-post",label:"Facebook",dimensions:"1200×630",icon:e.jsx(fh,{className:"h-4 w-4"})}],Yos=[{value:"luxury-dark",label:"Luxury Dark",description:"Black & gold, high-end",preview:"🌙"},{value:"modern-clean",label:"Modern Clean",description:"White, bold, contemporary",preview:"✨"},{value:"bold-colorful",label:"Bold & Vibrant",description:"Energetic gradients",preview:"🔥"},{value:"editorial",label:"Editorial",description:"Magazine-style",preview:"📰"}],Gze={"luxury-dark":REe,"modern-clean":OEe,"bold-colorful":FEe,editorial:BEe},k_e=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s);function Zos(s){var l;const[t,r]=s.split(","),n=((l=t.match(/:(.*?);/))==null?void 0:l[1])||"image/png",a=atob(r),i=new Uint8Array(a.length);for(let o=0;oze.is_default))??(s==null?void 0:s[0])??null,[r,n]=S.useState(void 0),a=(s==null?void 0:s.find(ze=>ze.id===r))??t,i=ba(),[l,o]=S.useState("mine"),[c,d]=S.useState(""),[h,m]=S.useState("address"),[p,x]=S.useState(!1),[y,_]=S.useState([]),[b,j]=S.useState(null),[k,T]=S.useState(0),[E,A]=S.useState("just-listed"),[D,R]=S.useState(["instagram-square"]),[z,O]=S.useState("luxury-dark"),[$,ee]=S.useState(!0),[Z,J]=S.useState(!1),[K,re]=S.useState([]),[ie,ce]=S.useState("search"),ne=S.useRef({}),{data:le=[],isLoading:be}=yt({queryKey:["marketing-studio-my-listings",i],enabled:!!i,queryFn:async()=>{const{data:ze,error:Pe}=await V.from("listings").select("id, property_address, city, state, price, status, bedrooms, bathrooms, square_footage, year_built, property_type, description, created_at, listing_photos(photo_url, sort_order, is_primary)").eq("agent_id",i).order("created_at",{ascending:!1}).limit(60);if(Pe)throw Pe;return(ze||[]).map(Ie=>{const De=(Ie.listing_photos||[]).slice().sort((tt,ge)=>(ge.is_primary?1:0)-(tt.is_primary?1:0)||(tt.sort_order??0)-(ge.sort_order??0)).map(tt=>tt.photo_url).filter(Boolean),pe=String(Ie.status||"");return{mlsNumber:Ie.id,address:Ie.property_address||"",city:Ie.city||"",state:Ie.state||"",zip:"",price:Number(Ie.price||0),status:pe,bedrooms:Number(Ie.bedrooms||0),bathrooms:Number(Ie.bathrooms||0),sqft:Number(Ie.square_footage||0),lotSize:"",yearBuilt:Ie.year_built??null,propertyType:Ie.property_type||"",description:Ie.description||"",photos:De,listDate:Ie.created_at,soldDate:pe.toLowerCase().includes("sold")?Ie.created_at:null,soldPrice:null,agent:{name:"",office:""}}})}}),fe=S.useMemo(()=>!$||!a?{enabled:!1}:{enabled:!0,agentName:a.display_name||"",brokerage:a.tagline||"",agentPhotoUrl:a.headshot_url||void 0},[$,a]),je=async()=>{if(c.trim()){x(!0),_([]);try{const{data:ze,error:Pe}=await V.functions.invoke("repliers-mls-search",{body:{searchType:h,query:c.trim()}});if(Pe)throw Pe;if(ze!=null&&ze.error)throw new Error(ze.error);_((ze==null?void 0:ze.listings)||[]),((ze==null?void 0:ze.listings)||[]).length===0&&he.info("No listings found. Try a different search.")}catch(ze){he.error(ze.message||"Search failed")}finally{x(!1)}}},ve=ze=>{var Pe;j(ze),T(0),ce("customize"),ze.soldDate||(Pe=ze.status)!=null&&Pe.toLowerCase().includes("sold")?A("just-sold"):A("just-listed")},We=ze=>R(Pe=>Pe.includes(ze)?Pe.filter(Ie=>Ie!==ze):[...Pe,ze]),Ve=b?{listing:b,postType:E,format:"instagram-square",branding:fe,selectedPhotoIndex:k}:null,Le=S.useCallback(async()=>{if(!(!b||D.length===0)){J(!0),re([]),ce("generate");try{await new Promise(Pe=>setTimeout(Pe,600));const ze=[];for(const Pe of D){const Ie=`${z}-${Pe}`,De=ne.current[Ie];if(!De)continue;const pe=Sk[Pe],tt=await DEe(De,{width:pe.width,height:pe.height,pixelRatio:1,cacheBust:!0,style:{transform:"none",transformOrigin:"top left"}});ze.push({format:Pe,url:tt})}re(ze),he.success(`Generated ${ze.length} design${ze.length>1?"s":""}!`)}catch(ze){he.error(ze.message||"Generation failed")}finally{J(!1)}}},[b,D,z]),Me=(ze,Pe)=>{const Ie=`${((b==null?void 0:b.address)||"listing").replace(/\s+/g,"-")}-${E}-${Pe}.png`;try{const De=Zos(ze),pe=URL.createObjectURL(De);if(Xos)window.open(pe,"_blank"),he.message("Long-press the image to save to Photos");else{const tt=document.createElement("a");tt.href=pe,tt.download=Ie,document.body.appendChild(tt),tt.click(),document.body.removeChild(tt)}setTimeout(()=>URL.revokeObjectURL(pe),6e4)}catch{const De=document.createElement("a");De.href=ze,De.download=Ie,De.click()}};return S.useEffect(()=>{!r&&t&&n(t.id)},[t,r]),e.jsx(Ss,{title:"Listing Templates",children:e.jsxs("div",{className:"container max-w-6xl py-4 md:py-8 px-3 md:px-6 space-y-5",children:[e.jsxs(el,{children:[e.jsx("title",{children:"Listing Templates | Marketing Studio"}),e.jsx("meta",{name:"description",content:"Just Listed, Just Sold, Open House and Price Drop templates pulled directly from your MLS."})]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(H,{variant:"ghost",size:"sm",asChild:!0,children:e.jsxs(Xn,{to:"/marketing-studio",children:[e.jsx(za,{className:"h-4 w-4 mr-1"})," Marketing Studio"]})})}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-end sm:justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs(Xe,{variant:"secondary",className:"mb-2 gap-1",children:[e.jsx(Lr,{className:"h-3 w-3"})," Listing Templates"]}),e.jsx("h1",{className:"text-2xl md:text-3xl font-bold tracking-tight",children:"Just Listed. Just Stunning."}),e.jsx("p",{className:"text-sm md:text-base text-muted-foreground max-w-2xl mt-1",children:"Search any MLS listing and get pixel-perfect, on-brand graphics for Instagram, Stories and Facebook in one click."})]}),s&&s.length>0&&e.jsxs("div",{className:"min-w-0 sm:min-w-[220px]",children:[e.jsx(ue,{className:"text-xs text-muted-foreground",children:"Brand preset"}),e.jsxs(Bs,{value:r,onValueChange:n,children:[e.jsx(Os,{children:e.jsx(Us,{placeholder:"Default"})}),e.jsx(Fs,{children:s.map(ze=>e.jsxs(pt,{value:ze.id,children:[ze.name,ze.is_default?" (default)":""]},ze.id))})]})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 text-xs sm:text-sm overflow-x-auto -mx-1 px-1 pb-1",children:[e.jsxs("button",{onClick:()=>ce("search"),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full whitespace-nowrap ${ie==="search"?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground"}`,children:[e.jsx(Mn,{className:"h-3.5 w-3.5"})," 1. Find listing"]}),e.jsx($a,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs("button",{onClick:()=>b&&ce("customize"),disabled:!b,className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full whitespace-nowrap ${ie==="customize"?"bg-primary text-primary-foreground":b?"bg-muted text-muted-foreground":"bg-muted text-muted-foreground/50"}`,children:[e.jsx(Lr,{className:"h-3.5 w-3.5"})," 2. Customize"]}),e.jsx($a,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs("div",{className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full whitespace-nowrap ${ie==="generate"?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground/50"}`,children:[e.jsx(hi,{className:"h-3.5 w-3.5"})," 3. Download"]})]}),ie==="search"&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(ta,{value:l,onValueChange:ze=>o(ze),children:e.jsxs(Qn,{className:"grid grid-cols-2 w-full sm:w-auto",children:[e.jsxs(ts,{value:"mine",children:[e.jsx(Fn,{className:"h-4 w-4 mr-1.5"})," My Listings"]}),e.jsxs(ts,{value:"mls",children:[e.jsx(Mn,{className:"h-4 w-4 mr-1.5"})," MLS Search"]})]})}),l==="mine"&&e.jsx("div",{className:"space-y-3",children:be?e.jsx(ke,{children:e.jsx(Oe,{className:"py-12 flex items-center justify-center",children:e.jsx(is,{className:"h-6 w-6 animate-spin text-muted-foreground"})})}):le.length===0?e.jsx(ke,{children:e.jsxs(Oe,{className:"py-10 text-center space-y-2",children:[e.jsx(Fn,{className:"h-10 w-10 mx-auto text-muted-foreground/40"}),e.jsx("p",{className:"text-sm font-medium",children:"No listings yet"}),e.jsx("p",{className:"text-xs text-muted-foreground max-w-sm mx-auto",children:"Add a listing to your Listing Exchange first, and it'll show up here ready to brand."}),e.jsx(H,{variant:"outline",size:"sm",asChild:!0,className:"mt-2",children:e.jsx(Xn,{to:"/listings",children:"Go to Listings"})})]})}):e.jsxs(e.Fragment,{children:[e.jsxs("h3",{className:"text-sm font-medium text-muted-foreground",children:[le.length," listing",le.length!==1?"s":""," from your Listing Exchange"]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:le.map((ze,Pe)=>{var Ie;return e.jsx(ke,{className:"cursor-pointer hover:border-primary/50 hover:shadow-md transition-all group overflow-hidden",onClick:()=>ve(ze),children:e.jsx(Oe,{className:"p-0",children:e.jsxs("div",{className:"flex",children:[e.jsx("div",{className:"w-28 h-28 sm:w-32 sm:h-28 flex-shrink-0 bg-muted overflow-hidden",children:(Ie=ze.photos)!=null&&Ie[0]?e.jsx("img",{src:ze.photos[0],alt:ze.address,className:"w-full h-full object-cover group-hover:scale-105 transition-transform"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(Fn,{className:"h-8 w-8 text-muted-foreground/40"})})}),e.jsxs("div",{className:"flex-1 p-3 min-w-0",children:[e.jsx("p",{className:"font-bold",children:ze.price>0?k_e(ze.price):"—"}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:ze.address}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[ze.city,ze.state?`, ${ze.state}`:""]}),e.jsxs("div",{className:"flex items-center gap-3 mt-1.5 text-xs text-muted-foreground",children:[ze.bedrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(B2,{className:"h-3 w-3"})," ",ze.bedrooms]}),ze.bathrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(_p,{className:"h-3 w-3"})," ",ze.bathrooms]}),ze.sqft>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(CE,{className:"h-3 w-3"})," ",ze.sqft.toLocaleString()]})]}),ze.status&&e.jsx("div",{className:"flex items-center gap-2 mt-1 flex-wrap",children:e.jsx(Xe,{variant:"outline",className:"text-[10px]",children:ze.status})})]})]})})},ze.mlsNumber||Pe)})})]})}),l==="mls"&&e.jsxs(e.Fragment,{children:[e.jsxs(ke,{className:"overflow-hidden",children:[e.jsxs(Ot,{children:[e.jsxs(zt,{className:"flex items-center gap-2 text-base md:text-lg",children:[e.jsx(Mn,{className:"h-5 w-5 text-primary"})," Search MLS"]}),e.jsxs(Br,{children:["Search by address or MLS number. Requires an MLS data connection — if your account doesn't have one, use ",e.jsx("button",{type:"button",className:"underline",onClick:()=>o("mine"),children:"My Listings"})," instead."]})]}),e.jsxs(Oe,{className:"space-y-3",children:[e.jsx(ta,{value:h,onValueChange:ze=>m(ze),children:e.jsxs(Qn,{children:[e.jsxs(ts,{value:"address",children:[e.jsx(Qa,{className:"h-4 w-4 mr-1.5"})," Address"]}),e.jsxs(ts,{value:"mls",children:[e.jsx(xm,{className:"h-4 w-4 mr-1.5"})," MLS #"]})]})}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2",children:[e.jsx(Se,{value:c,onChange:ze=>d(ze.target.value),placeholder:h==="mls"?"Enter MLS number...":"Enter property address...",className:"flex-1",onKeyDown:ze=>ze.key==="Enter"&&je()}),e.jsxs(H,{onClick:je,disabled:p||!c.trim(),className:"sm:w-auto w-full",children:[p?e.jsx(is,{className:"h-4 w-4 animate-spin mr-1.5"}):e.jsx(Mn,{className:"h-4 w-4 mr-1.5"})," Search"]})]})]})]}),y.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("h3",{className:"text-sm font-medium text-muted-foreground",children:[y.length," listing",y.length!==1?"s":""," found"]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:y.map((ze,Pe)=>{var Ie;return e.jsx(ke,{className:"cursor-pointer hover:border-primary/50 hover:shadow-md transition-all group overflow-hidden",onClick:()=>ve(ze),children:e.jsx(Oe,{className:"p-0",children:e.jsxs("div",{className:"flex",children:[e.jsx("div",{className:"w-28 h-28 sm:w-32 sm:h-28 flex-shrink-0 bg-muted overflow-hidden",children:(Ie=ze.photos)!=null&&Ie[0]?e.jsx("img",{src:ze.photos[0],alt:ze.address,className:"w-full h-full object-cover group-hover:scale-105 transition-transform"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(Fn,{className:"h-8 w-8 text-muted-foreground/40"})})}),e.jsxs("div",{className:"flex-1 p-3 min-w-0",children:[e.jsx("p",{className:"font-bold",children:k_e(ze.price)}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:ze.address}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[ze.city,", ",ze.state," ",ze.zip]}),e.jsxs("div",{className:"flex items-center gap-3 mt-1.5 text-xs text-muted-foreground",children:[ze.bedrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(B2,{className:"h-3 w-3"})," ",ze.bedrooms]}),ze.bathrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(_p,{className:"h-3 w-3"})," ",ze.bathrooms]}),ze.sqft>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(CE,{className:"h-3 w-3"})," ",ze.sqft.toLocaleString()]})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 flex-wrap",children:[ze.mlsNumber&&e.jsx(Xe,{variant:"outline",className:"text-[10px]",children:ze.mlsNumber}),ze.status&&e.jsx(Xe,{variant:"outline",className:"text-[10px]",children:ze.status})]})]})]})})},ze.mlsNumber||Pe)})})]})]})]}),ie==="customize"&&b&&Ve&&e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-4 md:gap-6",children:[e.jsxs(ke,{className:"lg:col-span-1 overflow-hidden min-w-0",children:[e.jsx(Ot,{className:"pb-3",children:e.jsx(zt,{className:"text-base",children:"Selected listing"})}),e.jsxs(Oe,{className:"space-y-3",children:[b.photos.length>0&&e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"aspect-[4/3] rounded-lg overflow-hidden bg-muted",children:e.jsx("img",{src:b.photos[k],alt:"",className:"w-full h-full object-cover"})}),b.photos.length>1&&e.jsxs("div",{className:"flex items-center justify-between mt-2",children:[e.jsx(H,{variant:"outline",size:"icon",className:"h-7 w-7",onClick:()=>T(ze=>Math.max(0,ze-1)),disabled:k===0,children:e.jsx(fl,{className:"h-4 w-4"})}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[k+1," of ",b.photos.length]}),e.jsx(H,{variant:"outline",size:"icon",className:"h-7 w-7",onClick:()=>T(ze=>Math.min(b.photos.length-1,ze+1)),disabled:k===b.photos.length-1,children:e.jsx($a,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-bold text-lg",children:k_e(b.price)}),e.jsx("p",{className:"text-sm text-muted-foreground",children:b.address}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[b.city,", ",b.state," ",b.zip]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 text-center",children:[b.bedrooms>0&&e.jsxs("div",{className:"bg-muted/50 rounded-lg p-2",children:[e.jsx("p",{className:"text-sm font-semibold",children:b.bedrooms}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Beds"})]}),b.bathrooms>0&&e.jsxs("div",{className:"bg-muted/50 rounded-lg p-2",children:[e.jsx("p",{className:"text-sm font-semibold",children:b.bathrooms}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Baths"})]}),b.sqft>0&&e.jsxs("div",{className:"bg-muted/50 rounded-lg p-2",children:[e.jsx("p",{className:"text-sm font-semibold",children:b.sqft.toLocaleString()}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Sq Ft"})]})]}),e.jsxs(H,{variant:"outline",size:"sm",className:"w-full",onClick:()=>{ce("search"),j(null)},children:[e.jsx(qy,{className:"h-3.5 w-3.5 mr-1.5"})," Choose different listing"]})]})]}),e.jsxs(ke,{className:"lg:col-span-2 overflow-hidden min-w-0",children:[e.jsxs(Ot,{children:[e.jsxs(zt,{className:"flex items-center gap-2 text-base",children:[e.jsx(Lr,{className:"h-5 w-5 text-primary"})," Customize"]}),e.jsx(Br,{children:"Pick a template, post type, and output format."})]}),e.jsxs(Oe,{className:"space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ue,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(pl,{className:"h-4 w-4"})," Template style"]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2",children:Yos.map(ze=>e.jsxs("button",{onClick:()=>O(ze.value),className:`flex flex-col items-center gap-1 px-2 py-3 rounded-lg border-2 transition-all text-center ${z===ze.value?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("span",{className:"text-2xl",children:ze.preview}),e.jsx("span",{className:"text-sm font-medium",children:ze.label}),e.jsx("span",{className:"text-[10px] text-muted-foreground leading-tight",children:ze.description})]},ze.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{className:"text-sm font-medium",children:"Post type"}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2",children:Kos.map(ze=>e.jsxs("button",{onClick:()=>A(ze.value),className:`flex items-center justify-center gap-2 px-3 py-2.5 rounded-lg border-2 transition-all text-sm font-medium ${E===ze.value?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("span",{className:"text-lg",children:ze.icon})," ",e.jsx("span",{className:"truncate",children:ze.label})]},ze.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{className:"text-sm font-medium",children:"Output formats"}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-2",children:Hze.map(ze=>e.jsxs("button",{onClick:()=>We(ze.value),className:`flex items-center gap-2 px-3 py-2.5 rounded-lg border-2 transition-all text-sm ${D.includes(ze.value)?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[ze.icon,e.jsxs("div",{className:"text-left min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:ze.label}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:ze.dimensions})]})]},ze.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(ue,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(io,{className:"h-4 w-4"})," Show my branding"]}),e.jsx(Or,{checked:$,onCheckedChange:ee})]}),$&&!a&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["No brand preset yet. ",e.jsx(Xn,{to:"/marketing-studio/brand-kit",className:"underline",children:"Create one"})," to add your headshot and name."]}),$&&a&&e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg border bg-muted/30",children:[a.headshot_url&&e.jsx("img",{src:a.headshot_url,alt:"",className:"w-10 h-10 rounded-full object-cover border"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:a.display_name||"Unnamed agent"}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:a.tagline||a.email||""})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{className:"text-sm font-medium",children:"Preview"}),e.jsx("div",{className:"bg-muted/30 rounded-lg p-3 md:p-4 flex justify-center overflow-hidden",children:e.jsx("div",{style:{width:360,maxWidth:"100%",height:360*(Sk[D[0]||"instagram-square"].height/Sk[D[0]||"instagram-square"].width)},children:(()=>{const ze=Gze[z],Pe=D[0]||"instagram-square";return e.jsx(ze,{...Ve,format:Pe})})()})})]}),e.jsx(H,{onClick:Le,disabled:D.length===0||Z,size:"lg",className:"w-full gap-2",children:Z?e.jsxs(e.Fragment,{children:[e.jsx(is,{className:"h-5 w-5 animate-spin"})," Generating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Lr,{className:"h-5 w-5"})," Generate ",D.length," design",D.length>1?"s":""]})})]})]})]}),ie==="generate"&&e.jsxs("div",{className:"space-y-4",children:[Z&&e.jsx(ke,{children:e.jsxs(Oe,{className:"flex flex-col items-center justify-center py-16",children:[e.jsx(is,{className:"h-12 w-12 animate-spin text-primary mb-3"}),e.jsx("p",{className:"text-base font-medium",children:"Rendering your designs..."}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"High-resolution PNGs, no AI credits used."})]})}),K.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-2",children:[e.jsx("h3",{className:"text-lg font-semibold",children:"Your designs"}),e.jsxs(H,{variant:"outline",size:"sm",onClick:()=>ce("customize"),children:[e.jsx(qy,{className:"h-3.5 w-3.5 mr-1.5"})," Tweak & regenerate"]})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:K.map((ze,Pe)=>{const Ie=Hze.find(De=>De.value===ze.format);return e.jsxs(ke,{className:"overflow-hidden",children:[e.jsx("div",{className:"bg-muted/30 p-1",children:e.jsx("img",{src:ze.url,alt:"",className:"w-full rounded"})}),e.jsxs(Oe,{className:"p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[Ie==null?void 0:Ie.icon,e.jsx("span",{className:"text-sm font-medium",children:Ie==null?void 0:Ie.label})]}),e.jsx(Xe,{variant:"outline",className:"text-[10px]",children:Ie==null?void 0:Ie.dimensions})]}),e.jsxs(H,{size:"sm",className:"w-full gap-1.5",onClick:()=>Me(ze.url,ze.format),children:[e.jsx(hi,{className:"h-3.5 w-3.5"})," Download"]})]})]},Pe)})})]})]}),ie==="generate"&&b&&Ve&&e.jsx("div",{style:{position:"fixed",left:"-99999px",top:0,pointerEvents:"none"},"aria-hidden":!0,children:D.map(ze=>{const Pe=Gze[z],Ie=Sk[ze];return e.jsx("div",{style:{width:Ie.width,height:Ie.height},children:e.jsx(Pe,{ref:De=>{ne.current[`${z}-${ze}`]=De},...Ve,format:ze})},`${z}-${ze}`)})})]})})}var $ut="Toggle",zEe=S.forwardRef((s,t)=>{const{pressed:r,defaultPressed:n,onPressedChange:a,...i}=s,[l,o]=af({prop:r,onChange:a,defaultProp:n??!1,caller:$ut});return e.jsx(Vn.button,{type:"button","aria-pressed":l,"data-state":l?"on":"off","data-disabled":s.disabled?"":void 0,...i,ref:t,onClick:an(s.onClick,()=>{s.disabled||o(!l)})})});zEe.displayName=$ut;var Uut=zEe,e4="ToggleGroup",[qut,iXs]=_u(e4,[OS]),Vut=OS(),$Ee=Nt.forwardRef((s,t)=>{const{type:r,...n}=s;if(r==="single"){const a=n;return e.jsx(Jos,{...a,ref:t})}if(r==="multiple"){const a=n;return e.jsx(els,{...a,ref:t})}throw new Error(`Missing prop \`type\` expected on \`${e4}\``)});$Ee.displayName=e4;var[Hut,Gut]=qut(e4),Jos=Nt.forwardRef((s,t)=>{const{value:r,defaultValue:n,onValueChange:a=()=>{},...i}=s,[l,o]=af({prop:r,defaultProp:n??"",onChange:a,caller:e4});return e.jsx(Hut,{scope:s.__scopeToggleGroup,type:"single",value:Nt.useMemo(()=>l?[l]:[],[l]),onItemActivate:o,onItemDeactivate:Nt.useCallback(()=>o(""),[o]),children:e.jsx(Wut,{...i,ref:t})})}),els=Nt.forwardRef((s,t)=>{const{value:r,defaultValue:n,onValueChange:a=()=>{},...i}=s,[l,o]=af({prop:r,defaultProp:n??[],onChange:a,caller:e4}),c=Nt.useCallback(h=>o((m=[])=>[...m,h]),[o]),d=Nt.useCallback(h=>o((m=[])=>m.filter(p=>p!==h)),[o]);return e.jsx(Hut,{scope:s.__scopeToggleGroup,type:"multiple",value:l,onItemActivate:c,onItemDeactivate:d,children:e.jsx(Wut,{...i,ref:t})})});$Ee.displayName=e4;var[tls,sls]=qut(e4),Wut=Nt.forwardRef((s,t)=>{const{__scopeToggleGroup:r,disabled:n=!1,rovingFocus:a=!0,orientation:i,dir:l,loop:o=!0,...c}=s,d=Vut(r),h=RS(l),m={role:"group",dir:h,...c};return e.jsx(tls,{scope:r,rovingFocus:a,disabled:n,children:a?e.jsx(oge,{asChild:!0,...d,orientation:i,dir:h,loop:o,children:e.jsx(Vn.div,{...m,ref:t})}):e.jsx(Vn.div,{...m,ref:t})})}),Zme="ToggleGroupItem",Kut=Nt.forwardRef((s,t)=>{const r=Gut(Zme,s.__scopeToggleGroup),n=sls(Zme,s.__scopeToggleGroup),a=Vut(s.__scopeToggleGroup),i=r.value.includes(s.value),l=n.disabled||s.disabled,o={...s,pressed:i,disabled:l},c=Nt.useRef(null);return n.rovingFocus?e.jsx(lge,{asChild:!0,...a,focusable:!l,active:i,ref:c,children:e.jsx(Wze,{...o,ref:t})}):e.jsx(Wze,{...o,ref:t})});Kut.displayName=Zme;var Wze=Nt.forwardRef((s,t)=>{const{__scopeToggleGroup:r,value:n,...a}=s,i=Gut(Zme,r),l={role:"radio","aria-checked":s.pressed,"aria-pressed":void 0},o=i.type==="single"?l:void 0;return e.jsx(zEe,{...o,...a,ref:t,onPressedChange:c=>{c?i.onItemActivate(n):i.onItemDeactivate(n)}})}),Yut=$Ee,Zut=Kut;const Xut=zA("inline-flex items-center justify-center rounded-md text-sm font-medium ring-offset-background transition-colors hover:bg-muted hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground",{variants:{variant:{default:"bg-transparent",outline:"border border-input bg-transparent hover:bg-accent hover:text-accent-foreground"},size:{default:"h-10 px-3",sm:"h-9 px-2.5",lg:"h-11 px-5"}},defaultVariants:{variant:"default",size:"default"}}),rls=S.forwardRef(({className:s,variant:t,size:r,...n},a)=>e.jsx(Uut,{ref:a,className:Ft(Xut({variant:t,size:r,className:s})),...n}));rls.displayName=Uut.displayName;const Qut=S.createContext({size:"default",variant:"default"}),hP=S.forwardRef(({className:s,variant:t,size:r,children:n,...a},i)=>e.jsx(Yut,{ref:i,className:Ft("flex items-center justify-center gap-1",s),...a,children:e.jsx(Qut.Provider,{value:{variant:t,size:r},children:n})}));hP.displayName=Yut.displayName;const WE=S.forwardRef(({className:s,children:t,variant:r,size:n,...a},i)=>{const l=S.useContext(Qut);return e.jsx(Zut,{ref:i,className:Ft(Xut({variant:l.variant||r,size:l.size||n}),s),...a,children:t})});WE.displayName=Zut.displayName;const nls=[{id:"meet",label:"Meet Your Agent",icon:io,description:"Polished intro card with your headshot, story, and contact."},{id:"testimonial",label:"Testimonial",icon:Kk,description:"Turn a Zillow / Google review into a branded graphic."},{id:"milestone",label:"Milestone",icon:To,description:"Celebrate homes sold, awards, anniversaries, achievements."},{id:"tip",label:"Pro Tip",icon:q2,description:"Drop a value-bomb tip — buyer/seller advice, market insight."},{id:"quote",label:"Quote / Mantra",icon:ph,description:"Personal philosophy, mantra, or rallying call."}],S_e={square:{w:1080,h:1080,label:"1:1 Feed"},portrait:{w:1080,h:1350,label:"4:5 Portrait"},story:{w:1080,h:1920,label:"9:16 Story"}},als=[{id:"editorial",label:"Editorial",description:"Magazine-style with serif accents."},{id:"bold",label:"Bold",description:"Big type, high contrast, gradient."},{id:"minimal",label:"Minimal",description:"Clean white space, hairline rules."},{id:"luxury",label:"Luxury",description:"Dark, gold accents, refined."}],Kze={meet:{headline:"Meet your agent",subline:"Helping families find home, one keys-in-hand moment at a time.",body:"15 years of negotiating wins, 200+ families moved, and a love for this city that runs deep.",attribution:"",badgeText:"REALTOR®"},testimonial:{headline:"What our clients say",subline:"",body:"She made the entire process feel effortless. From first showing to closing day, every detail was handled with care and expertise. We could not have asked for a better experience.",attribution:"The Bennett Family",rating:5,badgeText:"CLIENT REVIEW"},milestone:{headline:"100 homes sold",subline:"and counting…",body:"Thank you to every client, partner, and friend who trusted me with the biggest move of their life. Here is to the next 100.",attribution:"",badgeText:"MILESTONE"},tip:{headline:`Stop guessing. Start pricing.`,subline:"Pro tip · #03",body:"Homes priced within 3% of market value sell 2.4× faster than those priced higher. Pricing strategy is leverage — not a guess.",attribution:"",badgeText:"PRO TIP"},quote:{headline:`"Real estate is not about houses. It is about people."`,subline:"",body:"",attribution:"",badgeText:"PHILOSOPHY"}};function ils(){const{data:s}=frs(),{data:t}=gz(),[r,n]=S.useState(void 0),a=S.useMemo(()=>(t==null?void 0:t.find(y=>y.id===r))??s??null,[t,r,s]),[i,l]=S.useState({template:"meet",style:"editorial",aspect:"portrait",rating:5,...Kze.meet}),o=y=>l(_=>({..._,...y})),c=y=>l(_=>({..._,template:y,...Kze[y]})),d=S.useRef(null),[h,m]=S.useState(!1),p=async()=>{if(!d.current)return;m(!0);const y=d.current,_=y.style.transform;try{y.style.transform="none",await new Promise(k=>requestAnimationFrame(()=>k(null)));const b=await DEe(y,{cacheBust:!0,pixelRatio:2,width:y.offsetWidth,height:y.offsetHeight,backgroundColor:"#ffffff"}),j=document.createElement("a");j.href=b,j.download=`personal-branding-${i.template}-${Date.now()}.png`,document.body.appendChild(j),j.click(),j.remove(),he.success("Downloaded to your device")}catch(b){he.error((b==null?void 0:b.message)||"Export failed")}finally{y.style.transform=_,m(!1)}},x=S_e[i.aspect];return e.jsx(Ss,{title:"Personal Branding",children:e.jsxs("div",{className:"container max-w-7xl py-6 md:py-8 space-y-6 px-4",children:[e.jsxs(el,{children:[e.jsx("title",{children:"Personal Branding | Marketing Studio"}),e.jsx("meta",{name:"description",content:"Editorial-grade personal branding graphics — meet your agent, testimonials, milestones, and pro tips."})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-end sm:justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs(Xn,{to:"/marketing-studio",className:"text-sm text-muted-foreground inline-flex items-center gap-1 hover:underline",children:[e.jsx(za,{className:"h-3 w-3"})," Back to Marketing Studio"]}),e.jsx("div",{className:"flex items-center gap-2 mt-1",children:e.jsxs(Xe,{variant:"secondary",className:"gap-1",children:[e.jsx(Lr,{className:"h-3 w-3"})," New"]})}),e.jsx("h1",{className:"text-2xl md:text-3xl font-bold tracking-tight mt-1",children:"Personal Branding"}),e.jsx("p",{className:"text-sm md:text-base text-muted-foreground max-w-2xl",children:"Five editorial-grade templates, four distinct aesthetics. Pick one, drop in your story, export in seconds."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(H,{variant:"outline",asChild:!0,children:e.jsxs(Xn,{to:"/marketing-studio/brand-kit",children:[e.jsx(pl,{className:"h-4 w-4 mr-1"})," Brand Kit"]})}),e.jsxs(H,{onClick:p,disabled:h,children:[e.jsx(hi,{className:"h-4 w-4 mr-1"})," ",h?"Exporting…":"Download"]})]})]}),e.jsxs("div",{className:"grid lg:grid-cols-[380px_1fr] gap-6",children:[e.jsxs("div",{className:"space-y-5",children:[e.jsx(ke,{children:e.jsxs(Oe,{className:"p-4 space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Template"}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:nls.map(y=>{const _=y.icon,b=i.template===y.id;return e.jsxs("button",{onClick:()=>c(y.id),className:`text-left rounded-lg border p-3 transition-all ${b?"border-primary bg-primary/5 ring-2 ring-primary/30":"border-border hover:border-primary/50"}`,children:[e.jsx(_,{className:"h-4 w-4 mb-1"}),e.jsx("div",{className:"text-xs font-semibold",children:y.label})]},y.id)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Style"}),e.jsx(hP,{type:"single",value:i.style,onValueChange:y=>y&&o({style:y}),className:"grid grid-cols-2 gap-1",children:als.map(y=>e.jsx(WE,{value:y.id,className:"text-xs h-9",children:y.label},y.id))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Format"}),e.jsx(hP,{type:"single",value:i.aspect,onValueChange:y=>y&&o({aspect:y}),className:"grid grid-cols-3 gap-1",children:Object.keys(S_e).map(y=>e.jsx(WE,{value:y,className:"text-xs h-9",children:S_e[y].label},y))})]}),t&&t.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Brand preset"}),e.jsxs(Bs,{value:r??(s==null?void 0:s.id)??"",onValueChange:n,children:[e.jsx(Os,{children:e.jsx(Us,{placeholder:"Choose preset"})}),e.jsx(Fs,{children:t.map(y=>e.jsx(pt,{value:y.id,children:y.name},y.id))})]})]})]})}),e.jsx(ke,{children:e.jsxs(Oe,{className:"p-4 space-y-3",children:[e.jsx(ue,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Content"}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{htmlFor:"headline",className:"text-xs",children:"Headline"}),e.jsx(vr,{id:"headline",value:i.headline,onChange:y=>o({headline:y.target.value}),rows:2})]}),i.template!=="quote"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{htmlFor:"subline",className:"text-xs",children:"Subline"}),e.jsx(Se,{id:"subline",value:i.subline,onChange:y=>o({subline:y.target.value})})]}),i.template!=="quote"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{htmlFor:"body",className:"text-xs",children:"Body"}),e.jsx(vr,{id:"body",value:i.body,onChange:y=>o({body:y.target.value}),rows:4})]}),(i.template==="testimonial"||i.template==="quote")&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{htmlFor:"attribution",className:"text-xs",children:"Attribution"}),e.jsx(Se,{id:"attribution",value:i.attribution,onChange:y=>o({attribution:y.target.value}),placeholder:"— Client name / Source"})]}),i.template==="testimonial"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{className:"text-xs",children:"Rating"}),e.jsx(hP,{type:"single",value:String(i.rating),onValueChange:y=>y&&o({rating:Number(y)}),className:"grid grid-cols-5 gap-1",children:[1,2,3,4,5].map(y=>e.jsxs(WE,{value:String(y),className:"text-xs h-9",children:[y,"★"]},y))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{htmlFor:"badge",className:"text-xs",children:"Eyebrow tag"}),e.jsx(Se,{id:"badge",value:i.badgeText,onChange:y=>o({badgeText:y.target.value})})]})]})})]}),e.jsx(ols,{aspect:x,canvasRef:d,children:e.jsx(lls,{form:i,preset:a,width:x.w,height:x.h})})]})]})})}function ols({aspect:s,canvasRef:t,children:r}){const n=S.useRef(null),[a,i]=S.useState(.5);return S.useEffect(()=>{const l=n.current;if(!l)return;const o=()=>{const d=l.clientWidth-32;i(Math.min(1,d/s.w))};o();const c=new ResizeObserver(o);return c.observe(l),()=>c.disconnect()},[s.w]),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{ref:n,className:"rounded-xl bg-muted/40 p-4 md:p-6 flex justify-center overflow-hidden",children:e.jsx("div",{style:{width:s.w*a,height:s.h*a,position:"relative"},className:"shadow-2xl",children:e.jsx("div",{ref:t,style:{width:s.w,height:s.h,transform:`scale(${a})`,transformOrigin:"top left",position:"absolute",top:0,left:0},children:r})})}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-2 text-center",children:["Preview scaled. Export is ",s.w,"×",s.h,"px @ 2× retina."]})]})}function lls({form:s,preset:t,width:r,height:n}){const a=(t==null?void 0:t.brand_color)||"#0F172A",i=(t==null?void 0:t.accent_color)||"#D4AF37",l=t==null?void 0:t.headshot_url,o=t==null?void 0:t.brokerage_logo_url,c=(t==null?void 0:t.display_name)||"Your Name",d=(t==null?void 0:t.phone)||"",h=(t==null?void 0:t.email)||"",m=(t==null?void 0:t.tagline)||"",p=(t==null?void 0:t.website_url)||"",x={form:s,brandColor:a,accentColor:i,headshot:l,logo:o,name:c,phone:d,email:h,tagline:m,website:p,width:r,height:n};return s.style==="editorial"?e.jsx(cls,{...x}):s.style==="bold"?e.jsx(dls,{...x}):s.style==="luxury"?e.jsx(hls,{...x}):e.jsx(uls,{...x})}function Jut({name:s,phone:t,email:r,website:n,color:a}){const i=[t,r,n].filter(Boolean);return e.jsxs("div",{style:{color:a,fontFamily:"Inter, system-ui, sans-serif"},children:[e.jsx("div",{style:{fontSize:22,fontWeight:700,letterSpacing:"0.02em"},children:s}),e.jsx("div",{style:{fontSize:16,opacity:.85,marginTop:4},children:i.join(" · ")})]})}function Cxe({rating:s,color:t}){return e.jsx("div",{style:{display:"flex",gap:4},children:Array.from({length:5}).map((r,n)=>e.jsx(ya,{size:28,fill:n1.5;return e.jsxs("div",{style:{width:m,height:p,background:"#FAF7F2",position:"relative",fontFamily:"Georgia, serif",color:"#1a1a1a",overflow:"hidden"},children:[e.jsxs("div",{style:{position:"absolute",top:64,left:64,right:64,display:"flex",justifyContent:"space-between",alignItems:"center"},children:[e.jsx("div",{style:{fontFamily:"Inter, sans-serif",fontSize:14,letterSpacing:"0.3em",color:r},children:t.badgeText}),e.jsxs("div",{style:{fontFamily:"Inter, sans-serif",fontSize:12,letterSpacing:"0.2em",color:"#888"},children:["EST. ",new Date().getFullYear()]})]}),e.jsx("div",{style:{position:"absolute",top:100,left:64,right:64,height:1,background:"#1a1a1a",opacity:.15}}),a&&(t.template==="meet"||t.template==="milestone")&&e.jsx("div",{style:{position:"absolute",top:140,left:64,width:m-128,height:x?700:480,overflow:"hidden",borderRadius:4},children:e.jsx("img",{src:a,crossOrigin:"anonymous",style:{width:"100%",height:"100%",objectFit:"cover",objectPosition:"center top",filter:"grayscale(0.15)"}})}),e.jsxs("div",{style:{position:"absolute",left:64,right:64,bottom:220,textAlign:t.template==="quote"?"center":"left"},children:[t.template==="testimonial"&&e.jsx("div",{style:{fontSize:120,lineHeight:.7,color:n,fontFamily:"Georgia, serif"},children:'"'}),e.jsx("h1",{style:{fontSize:t.template==="quote"?76:92,lineHeight:1.05,fontWeight:400,margin:0,letterSpacing:"-0.02em",whiteSpace:"pre-wrap"},children:t.headline}),t.subline&&e.jsx("div",{style:{fontFamily:"Inter, sans-serif",fontSize:22,marginTop:16,color:"#555",fontStyle:"italic"},children:t.subline}),t.body&&e.jsx("p",{style:{fontFamily:"Inter, sans-serif",fontSize:22,lineHeight:1.5,color:"#333",marginTop:28,maxWidth:820},children:t.body}),t.template==="testimonial"&&e.jsxs("div",{style:{marginTop:24,display:"flex",alignItems:"center",gap:16},children:[e.jsx(Cxe,{rating:t.rating,color:n}),t.attribution&&e.jsxs("div",{style:{fontFamily:"Inter, sans-serif",fontSize:18,color:"#555"},children:["— ",t.attribution]})]}),t.template==="quote"&&t.attribution&&e.jsxs("div",{style:{fontFamily:"Inter, sans-serif",fontSize:18,marginTop:24,color:"#555",letterSpacing:"0.1em"},children:["— ",t.attribution]})]}),e.jsxs("div",{style:{position:"absolute",left:64,right:64,bottom:64},children:[e.jsx("div",{style:{height:1,background:"#1a1a1a",opacity:.15,marginBottom:24}}),e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[e.jsx(Jut,{name:l,phone:o,email:c,website:d,color:"#1a1a1a"}),i&&e.jsx("img",{src:i,crossOrigin:"anonymous",style:{height:56,objectFit:"contain"}})]}),h&&e.jsx("div",{style:{fontFamily:"Inter, sans-serif",fontSize:13,color:"#888",marginTop:12,fontStyle:"italic"},children:h})]})]})}function dls(s){const{form:t,brandColor:r,accentColor:n,headshot:a,logo:i,name:l,phone:o,email:c,website:d,width:h,height:m}=s;return e.jsxs("div",{style:{width:h,height:m,position:"relative",overflow:"hidden",fontFamily:"Inter, system-ui, sans-serif",background:`linear-gradient(135deg, ${r} 0%, ${mls(r,-20)} 100%)`,color:"#fff"},children:[e.jsx("div",{style:{position:"absolute",top:-200,right:-200,width:700,height:700,borderRadius:"50%",background:n,opacity:.25,filter:"blur(40px)"}}),e.jsxs("div",{style:{position:"absolute",top:64,left:64,right:64,display:"flex",justifyContent:"space-between",alignItems:"center"},children:[e.jsx("div",{style:{fontSize:14,letterSpacing:"0.4em",fontWeight:700,background:n,color:"#000",padding:"8px 16px",display:"inline-block"},children:t.badgeText}),i&&e.jsx("img",{src:i,crossOrigin:"anonymous",style:{height:48,objectFit:"contain",filter:"brightness(0) invert(1)"}})]}),a&&(t.template==="meet"||t.template==="milestone")&&e.jsx("div",{style:{position:"absolute",right:64,top:180,width:380,height:380,borderRadius:"50%",overflow:"hidden",border:`6px solid ${n}`},children:e.jsx("img",{src:a,crossOrigin:"anonymous",style:{width:"100%",height:"100%",objectFit:"cover",objectPosition:"center top"}})}),e.jsxs("div",{style:{position:"absolute",left:64,right:64,bottom:240},children:[t.template==="testimonial"&&e.jsx("div",{style:{fontSize:180,lineHeight:.6,color:n},children:'"'}),e.jsx("h1",{style:{fontSize:t.template==="quote"?110:128,lineHeight:.95,fontWeight:900,margin:0,letterSpacing:"-0.04em",textTransform:t.template==="milestone"?"uppercase":"none",whiteSpace:"pre-wrap",maxWidth:h-128},children:t.headline}),t.subline&&e.jsx("div",{style:{fontSize:28,marginTop:16,color:n,fontWeight:700,letterSpacing:"0.04em"},children:t.subline}),t.body&&e.jsx("p",{style:{fontSize:24,lineHeight:1.45,marginTop:28,maxWidth:820,opacity:.92},children:t.body}),t.template==="testimonial"&&e.jsxs("div",{style:{marginTop:24,display:"flex",alignItems:"center",gap:16},children:[e.jsx(Cxe,{rating:t.rating,color:n}),t.attribution&&e.jsxs("div",{style:{fontSize:20,opacity:.9},children:["— ",t.attribution]})]})]}),e.jsxs("div",{style:{position:"absolute",left:64,right:64,bottom:64},children:[e.jsx("div",{style:{height:2,background:n,marginBottom:20,width:80}}),e.jsx(Jut,{name:l,phone:o,email:c,website:d,color:"#fff"})]})]})}function uls(s){const{form:t,brandColor:r,accentColor:n,headshot:a,logo:i,name:l,phone:o,email:c,website:d,width:h,height:m}=s;return e.jsxs("div",{style:{width:h,height:m,background:"#fff",position:"relative",fontFamily:"Inter, system-ui, sans-serif",color:"#0a0a0a",overflow:"hidden"},children:[e.jsx("div",{style:{position:"absolute",top:0,left:0,right:0,height:8,background:n}}),e.jsxs("div",{style:{position:"absolute",top:80,left:80,right:80,display:"flex",justifyContent:"space-between",alignItems:"center"},children:[e.jsx("div",{style:{fontSize:13,letterSpacing:"0.3em",color:r,fontWeight:600},children:t.badgeText}),i&&e.jsx("img",{src:i,crossOrigin:"anonymous",style:{height:44,objectFit:"contain"}})]}),a&&(t.template==="meet"||t.template==="milestone")&&e.jsx("div",{style:{position:"absolute",top:160,left:"50%",transform:"translateX(-50%)",width:260,height:260,borderRadius:"50%",overflow:"hidden"},children:e.jsx("img",{src:a,crossOrigin:"anonymous",style:{width:"100%",height:"100%",objectFit:"cover",objectPosition:"center top"}})}),e.jsxs("div",{style:{position:"absolute",left:80,right:80,top:a&&(t.template==="meet"||t.template==="milestone")?460:220,textAlign:"center"},children:[e.jsx("h1",{style:{fontSize:84,lineHeight:1.05,fontWeight:300,margin:0,letterSpacing:"-0.03em",whiteSpace:"pre-wrap"},children:t.headline}),t.subline&&e.jsx("div",{style:{fontSize:22,marginTop:16,color:"#666"},children:t.subline}),t.body&&e.jsx("p",{style:{fontSize:22,lineHeight:1.55,color:"#444",marginTop:32,maxWidth:760,marginLeft:"auto",marginRight:"auto"},children:t.body}),t.template==="testimonial"&&e.jsx("div",{style:{marginTop:24,display:"flex",alignItems:"center",gap:16,justifyContent:"center"},children:e.jsx(Cxe,{rating:t.rating,color:n})}),t.attribution&&e.jsxs("div",{style:{fontSize:18,marginTop:16,color:"#666",letterSpacing:"0.1em"},children:["— ",t.attribution]})]}),e.jsxs("div",{style:{position:"absolute",left:80,right:80,bottom:80,textAlign:"center"},children:[e.jsx("div",{style:{width:60,height:1,background:"#0a0a0a",opacity:.3,margin:"0 auto 20px"}}),e.jsx("div",{style:{fontSize:20,fontWeight:600},children:l}),e.jsx("div",{style:{fontSize:14,color:"#666",marginTop:4},children:[o,c,d].filter(Boolean).join(" · ")})]})]})}function hls(s){const{form:t,accentColor:r,headshot:n,logo:a,name:i,phone:l,email:o,website:c,width:d,height:h}=s,m=r||"#D4AF37";return e.jsxs("div",{style:{width:d,height:h,background:"#0B0B0E",position:"relative",fontFamily:"Georgia, serif",color:"#EAE6DC",overflow:"hidden"},children:[e.jsx("div",{style:{position:"absolute",inset:40,border:`1px solid ${m}`,opacity:.6}}),e.jsx("div",{style:{position:"absolute",inset:50,border:`1px solid ${m}`,opacity:.25}}),e.jsxs("div",{style:{position:"absolute",top:96,left:96,right:96,textAlign:"center"},children:[e.jsx("div",{style:{fontFamily:"Inter, sans-serif",fontSize:13,letterSpacing:"0.5em",color:m},children:t.badgeText}),e.jsx("div",{style:{width:40,height:1,background:m,margin:"20px auto 0"}})]}),n&&(t.template==="meet"||t.template==="milestone")&&e.jsx("div",{style:{position:"absolute",top:200,left:"50%",transform:"translateX(-50%)",width:340,height:420,overflow:"hidden",border:`1px solid ${m}`},children:e.jsx("img",{src:n,crossOrigin:"anonymous",style:{width:"100%",height:"100%",objectFit:"cover",objectPosition:"center top",filter:"sepia(0.15) brightness(0.95)"}})}),e.jsxs("div",{style:{position:"absolute",left:96,right:96,top:n&&(t.template==="meet"||t.template==="milestone")?680:280,textAlign:"center"},children:[t.template==="testimonial"&&e.jsx("div",{style:{fontSize:100,lineHeight:.6,color:m},children:'"'}),e.jsx("h1",{style:{fontSize:t.template==="quote"?68:80,lineHeight:1.1,fontWeight:400,margin:0,letterSpacing:"-0.01em",whiteSpace:"pre-wrap",fontStyle:t.template==="quote"?"italic":"normal"},children:t.headline}),t.subline&&e.jsx("div",{style:{fontFamily:"Inter, sans-serif",fontSize:18,marginTop:16,color:m,letterSpacing:"0.3em",textTransform:"uppercase"},children:t.subline}),t.body&&e.jsx("p",{style:{fontFamily:"Inter, sans-serif",fontSize:20,lineHeight:1.65,color:"#C9C2B3",marginTop:28,maxWidth:760,marginLeft:"auto",marginRight:"auto",fontWeight:300},children:t.body}),t.template==="testimonial"&&e.jsx("div",{style:{marginTop:24,display:"flex",alignItems:"center",gap:16,justifyContent:"center"},children:e.jsx(Cxe,{rating:t.rating,color:m})}),t.attribution&&e.jsxs("div",{style:{fontFamily:"Inter, sans-serif",fontSize:16,marginTop:16,color:m,letterSpacing:"0.2em",textTransform:"uppercase"},children:["— ",t.attribution]})]}),e.jsxs("div",{style:{position:"absolute",left:96,right:96,bottom:96,textAlign:"center"},children:[e.jsx("div",{style:{width:40,height:1,background:m,margin:"0 auto 20px"}}),e.jsx("div",{style:{fontFamily:"Georgia, serif",fontSize:24,letterSpacing:"0.15em",color:"#EAE6DC"},children:i.toUpperCase()}),e.jsx("div",{style:{fontFamily:"Inter, sans-serif",fontSize:13,color:"#9A9285",marginTop:8,letterSpacing:"0.2em"},children:[l,o,c].filter(Boolean).join(" · ")}),a&&e.jsx("img",{src:a,crossOrigin:"anonymous",style:{height:40,objectFit:"contain",marginTop:20,filter:"brightness(0) invert(1) opacity(0.7)"}})]})]})}function mls(s,t){const r=s.replace("#",""),n=parseInt(r.length===3?r.split("").map(o=>o+o).join(""):r,16);let a=(n>>16)+Math.round(t/100*255),i=(n>>8&255)+Math.round(t/100*255),l=(n&255)+Math.round(t/100*255);return a=Math.max(0,Math.min(255,a)),i=Math.max(0,Math.min(255,i)),l=Math.max(0,Math.min(255,l)),`#${(a<<16|i<<8|l).toString(16).padStart(6,"0")}`}const fls=()=>{const{swagId:s}=Po(),{user:t}=Ms(),{toast:r}=li(),n=ns(),{trackEngagement:a}=y8(),[i,l]=S.useState(""),{data:o,isLoading:c}=yt({queryKey:["social-swag-detail",s],queryFn:async()=>{const{data:j,error:k}=await V.from("social_swag").select("*").eq("id",s).single();if(k)throw k;const{data:T}=await V.from("social_swag_links").select("*").eq("swag_id",s).order("sort_order");return{...j,links:T||[]}},enabled:!!s});S.useEffect(()=>{o&&a("social_swag",o.id,o.title,"view")},[o==null?void 0:o.id]);const{data:d=[]}=yt({queryKey:["social-swag-likes",s],queryFn:async()=>{const{data:j,error:k}=await V.from("social_swag_likes").select("*").eq("swag_id",s);if(k)throw k;return j},enabled:!!s}),{data:h=[]}=yt({queryKey:["social-swag-comments",s],queryFn:async()=>{const{data:j,error:k}=await V.from("social_swag_comments").select("*").eq("swag_id",s).order("created_at",{ascending:!1});if(k)throw k;const T=[...new Set(j.map(D=>D.user_id))],{data:E}=await V.from("profiles").select("id, name").in("id",T),A=new Map((E==null?void 0:E.map(D=>[D.id,D.name]))||[]);return j.map(D=>({...D,user_name:A.get(D.user_id)||"Unknown User"}))},enabled:!!s}),m=Pt({mutationFn:async j=>{const{error:k}=await V.from("social_swag_comments").insert({swag_id:s,user_id:t.id,content:j});if(k)throw k},onSuccess:()=>{n.invalidateQueries({queryKey:["social-swag-comments",s]}),l(""),r({title:"Comment added!"})},onError:j=>{r({title:"Error adding comment",description:j.message,variant:"destructive"})}}),p=Pt({mutationFn:async j=>{const{error:k}=await V.from("social_swag_comments").delete().eq("id",j);if(k)throw k},onSuccess:()=>{n.invalidateQueries({queryKey:["social-swag-comments",s]}),r({title:"Comment deleted"})}}),x=Pt({mutationFn:async()=>{const j=d.find(k=>k.user_id===(t==null?void 0:t.id));if(j){const{error:k}=await V.from("social_swag_likes").delete().eq("id",j.id);if(k)throw k}else{const{error:k}=await V.from("social_swag_likes").insert({swag_id:s,user_id:t.id});if(k)throw k}},onSuccess:()=>{n.invalidateQueries({queryKey:["social-swag-likes",s]})}}),y=d.some(j=>j.user_id===(t==null?void 0:t.id)),_=j=>j.split(" ").map(k=>k[0]).join("").toUpperCase().slice(0,2),b=j=>{j.preventDefault(),!(!i.trim()||!t)&&m.mutate(i.trim())};return c?e.jsx(Ss,{title:"Social Swag",children:e.jsx("div",{className:"flex justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):o?e.jsx(Ss,{title:o.title,children:e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsx(H,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(Xn,{to:"/social-swag",children:[e.jsx(za,{className:"h-4 w-4"}),"Back to Social Swag"]})}),o.preview_image_url&&e.jsx("div",{className:"relative w-full rounded-lg overflow-hidden bg-muted",children:e.jsx("img",{src:o.preview_image_url,alt:o.title,className:"w-full max-h-[500px] object-contain"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-start sm:justify-between gap-4",children:[e.jsx("div",{className:"space-y-2",children:e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:o.title})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(w8,{resourceType:"social_swag",resourceId:o.id,resourceTitle:o.title}),e.jsxs(H,{variant:y?"default":"outline",className:"gap-2 w-fit",onClick:()=>x.mutate(),disabled:!t||x.isPending,children:[e.jsx(sf,{className:`h-4 w-4 ${y?"fill-current":""}`}),d.length," ",d.length===1?"Like":"Likes"]})]})]}),o.description&&e.jsx("div",{className:"text-muted-foreground prose prose-sm max-w-none dark:prose-invert",dangerouslySetInnerHTML:{__html:o.description}})]}),o.links.length>0&&e.jsx(ke,{children:e.jsxs(Oe,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Jo,{className:"h-4 w-4"}),o.links.length===1?"Canva Link":"Canva Links"]}),e.jsx("div",{className:"grid gap-2",children:o.links.map(j=>e.jsxs(H,{variant:"outline",className:"w-full justify-between gap-2 h-auto py-3",onClick:()=>{a("social_swag",o.id,o.title,"click_canva"),window.open(j.canva_share_link,"_blank")},children:[e.jsx("span",{className:"font-medium",children:j.title}),e.jsx(gn,{className:"h-4 w-4 text-muted-foreground"})]},j.id))})]})}),e.jsx(Qo,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 text-lg",children:[e.jsx(qc,{className:"h-5 w-5"}),"Comments (",h.length,")"]}),t?e.jsxs("form",{onSubmit:b,className:"flex gap-2",children:[e.jsx(vr,{placeholder:"Add a comment...",value:i,onChange:j=>l(j.target.value),className:"min-h-[80px] resize-none flex-1"}),e.jsx(H,{type:"submit",size:"icon",className:"h-10 w-10",disabled:!i.trim()||m.isPending,children:e.jsx(yn,{className:"h-4 w-4"})})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Log in to add a comment"}),e.jsx("div",{className:"space-y-4",children:h.length===0?e.jsx(ke,{children:e.jsx(Oe,{className:"py-8 text-center",children:e.jsx("p",{className:"text-muted-foreground",children:"No comments yet. Be the first to share your thoughts!"})})}):h.map(j=>e.jsx(ke,{children:e.jsx(Oe,{className:"pt-4 pb-4",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Un,{className:"h-10 w-10 flex-shrink-0",children:e.jsx(qn,{className:"text-sm",children:_(j.user_name||"U")})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"font-medium",children:j.user_name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:Hl(new Date(j.created_at),{addSuffix:!0})}),j.user_id===(t==null?void 0:t.id)&&e.jsx(H,{variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>p.mutate(j.id),children:e.jsx(Dr,{className:"h-3 w-3 text-muted-foreground"})})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:j.content})]})]})})},j.id))})]})]})}):e.jsx(Ss,{title:"Social Swag",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Jo,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold",children:"Item not found"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"This item may have been removed or is not available."}),e.jsx(H,{asChild:!0,className:"mt-4",children:e.jsx(Xn,{to:"/social-swag",children:"Back to Social Swag"})})]})})},pls=({categories:s,privateGroups:t,selectedFilter:r,onFilterChange:n,onlineUsers:a})=>{const[i,l]=S.useState(!0),[o,c]=S.useState(!0),[d,h]=S.useState(!0),m=p=>p.split(" ").map(x=>x[0]).join("").toUpperCase().slice(0,2);return e.jsx("aside",{className:"w-64 shrink-0 hidden lg:block relative z-0",children:e.jsx("div",{className:"sticky top-4 space-y-4 max-h-[calc(100vh-8rem)] overflow-y-auto overscroll-contain",children:e.jsxs("div",{className:"space-y-2 pr-4",children:[e.jsxs(H,{variant:r==="all"?"secondary":"ghost",className:"w-full justify-start",onClick:()=>n("all"),children:[e.jsx($k,{className:"h-4 w-4 mr-2"}),"All Posts"]}),e.jsxs(m0,{open:i,onOpenChange:l,children:[e.jsx(f0,{asChild:!0,children:e.jsxs(H,{variant:"ghost",className:"w-full justify-between text-muted-foreground hover:text-foreground",children:[e.jsx("span",{className:"text-xs font-semibold uppercase tracking-wider",children:"Categories"}),i?e.jsx(Io,{className:"h-4 w-4"}):e.jsx($a,{className:"h-4 w-4"})]})}),e.jsx(p0,{className:"space-y-1 pl-2",children:s.map(p=>e.jsxs(H,{variant:r===p.id?"secondary":"ghost",size:"sm",className:"w-full justify-start h-9",onClick:()=>n(p.id),children:[e.jsx("span",{className:"mr-2",children:p.icon||"📂"}),e.jsx("span",{className:"truncate",children:p.name})]},p.id))})]}),t.length>0&&e.jsxs(m0,{open:o,onOpenChange:c,children:[e.jsx(f0,{asChild:!0,children:e.jsxs(H,{variant:"ghost",className:"w-full justify-between text-muted-foreground hover:text-foreground",children:[e.jsxs("span",{className:"text-xs font-semibold uppercase tracking-wider flex items-center gap-1",children:[e.jsx(Td,{className:"h-3 w-3"}),"Your Groups"]}),o?e.jsx(Io,{className:"h-4 w-4"}):e.jsx($a,{className:"h-4 w-4"})]})}),e.jsx(p0,{className:"space-y-1 pl-2",children:t.map(p=>e.jsxs(H,{variant:r===`group:${p.id}`?"secondary":"ghost",size:"sm",className:"w-full justify-start h-9",onClick:()=>n(`group:${p.id}`),children:[e.jsx("span",{className:"mr-2",children:p.icon||"🔒"}),e.jsx("span",{className:"truncate",children:p.name})]},p.id))})]}),e.jsxs(m0,{open:d,onOpenChange:h,children:[e.jsx(f0,{asChild:!0,children:e.jsxs(H,{variant:"ghost",className:"w-full justify-between text-muted-foreground hover:text-foreground",children:[e.jsxs("span",{className:"text-xs font-semibold uppercase tracking-wider flex items-center gap-1",children:[e.jsx(Ar,{className:"h-3 w-3"}),"Online Now",a.length>0&&e.jsx("span",{className:"ml-1 bg-green-500 text-white text-xs rounded-full px-1.5 py-0.5 min-w-[20px] text-center",children:a.length})]}),d?e.jsx(Io,{className:"h-4 w-4"}):e.jsx($a,{className:"h-4 w-4"})]})}),e.jsx(p0,{className:"pl-2 space-y-1",children:a.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-2 px-2",children:"No one else online right now"}):a.map(p=>e.jsxs("div",{className:"flex items-center gap-2 py-1.5 px-2 rounded-md hover:bg-muted transition-colors",children:[e.jsxs("div",{className:"relative",children:[e.jsxs(Un,{className:"h-7 w-7",children:[e.jsx(Ka,{src:p.avatarUrl}),e.jsx(qn,{className:"text-xs",children:m(p.name)})]}),e.jsx(Gu,{className:"h-2.5 w-2.5 fill-green-500 text-green-500 absolute -bottom-0.5 -right-0.5"})]}),e.jsx("span",{className:"text-sm truncate",children:p.name})]},p.id))})]})]})})})},gls=({categories:s,privateGroups:t,selectedFilter:r,onFilterChange:n,onlineUsers:a})=>{const[i,l]=S.useState(!1),o=d=>d.split(" ").map(h=>h[0]).join("").toUpperCase().slice(0,2),c=()=>{if(r==="all")return"All Posts";if(r.startsWith("group:")){const h=r.replace("group:",""),m=t.find(p=>p.id===h);return m?`🔒 ${m.name}`:"Private Group"}const d=s.find(h=>h.id===r);return d?`${d.icon||"📂"} ${d.name}`:"Category"};return e.jsxs("div",{className:"lg:hidden flex items-center gap-2 mb-4",children:[e.jsxs(Xu,{children:[e.jsx(Qu,{asChild:!0,children:e.jsxs(H,{variant:"outline",className:"flex-1 justify-between",children:[e.jsx("span",{className:"truncate",children:c()}),e.jsx(Io,{className:"h-4 w-4 ml-2 shrink-0"})]})}),e.jsxs(wu,{className:"w-56 bg-background border",children:[e.jsxs(di,{onClick:()=>n("all"),children:[e.jsx($k,{className:"h-4 w-4 mr-2"}),"All Posts"]}),e.jsx(A_,{}),e.jsx(l9,{className:"text-xs text-muted-foreground",children:"Categories"}),s.map(d=>e.jsxs(di,{onClick:()=>n(d.id),children:[e.jsx("span",{className:"mr-2",children:d.icon||"📂"}),d.name]},d.id)),t.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(A_,{}),e.jsxs(l9,{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Td,{className:"h-3 w-3"}),"Your Groups"]}),t.map(d=>e.jsxs(di,{onClick:()=>n(`group:${d.id}`),children:[e.jsx("span",{className:"mr-2",children:d.icon||"🔒"}),d.name]},d.id))]})]})]}),e.jsxs($S,{open:i,onOpenChange:l,children:[e.jsx(b5e,{asChild:!0,children:e.jsxs(H,{variant:"outline",size:"icon",className:"relative",children:[e.jsx(Ar,{className:"h-4 w-4"}),a.length>0&&e.jsx("span",{className:"absolute -top-1 -right-1 bg-green-500 text-white text-xs rounded-full h-4 w-4 flex items-center justify-center",children:a.length})]})}),e.jsxs(vj,{children:[e.jsx(US,{children:e.jsxs(qS,{className:"flex items-center gap-2",children:[e.jsx(Ar,{className:"h-5 w-5"}),"Online Now (",a.length,")"]})}),e.jsx(Ci,{className:"h-[calc(100vh-8rem)] mt-4",children:a.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"No one else online right now"}):e.jsx("div",{className:"space-y-2",children:a.map(d=>e.jsxs("div",{className:"flex items-center gap-3 py-2 px-3 rounded-lg hover:bg-muted transition-colors",children:[e.jsxs("div",{className:"relative",children:[e.jsxs(Un,{className:"h-10 w-10",children:[e.jsx(Ka,{src:d.avatarUrl}),e.jsx(qn,{children:o(d.name)})]}),e.jsx(Gu,{className:"h-3 w-3 fill-green-500 text-green-500 absolute -bottom-0.5 -right-0.5"})]}),e.jsx("span",{className:"font-medium",children:d.name})]},d.id))})})]})]})]})};var C_e,Txe="HoverCard",[eht,oXs]=_u(Txe,[q_]),Exe=q_(),[xls,UEe]=eht(Txe),tht=s=>{const{__scopeHoverCard:t,children:r,open:n,defaultOpen:a,onOpenChange:i,openDelay:l=700,closeDelay:o=300}=s,c=Exe(t),d=S.useRef(0),h=S.useRef(0),m=S.useRef(!1),p=S.useRef(!1),[x,y]=af({prop:n,defaultProp:a??!1,onChange:i,caller:Txe}),_=S.useCallback(()=>{clearTimeout(h.current),d.current=window.setTimeout(()=>y(!0),l)},[l,y]),b=S.useCallback(()=>{clearTimeout(d.current),!m.current&&!p.current&&(h.current=window.setTimeout(()=>y(!1),o))},[o,y]),j=S.useCallback(()=>y(!1),[y]);return S.useEffect(()=>()=>{clearTimeout(d.current),clearTimeout(h.current)},[]),e.jsx(xls,{scope:t,open:x,onOpenChange:y,onOpen:_,onClose:b,onDismiss:j,hasSelectionRef:m,isPointerDownOnContentRef:p,children:e.jsx(BB,{...c,children:r})})};tht.displayName=Txe;var sht="HoverCardTrigger",rht=S.forwardRef((s,t)=>{const{__scopeHoverCard:r,...n}=s,a=UEe(sht,r),i=Exe(r);return e.jsx(i8,{asChild:!0,...i,children:e.jsx(Vn.a,{"data-state":a.open?"open":"closed",...n,ref:t,onPointerEnter:an(s.onPointerEnter,Qme(a.onOpen)),onPointerLeave:an(s.onPointerLeave,Qme(a.onClose)),onFocus:an(s.onFocus,a.onOpen),onBlur:an(s.onBlur,a.onClose),onTouchStart:an(s.onTouchStart,l=>l.preventDefault())})})});rht.displayName=sht;var yls="HoverCardPortal",[lXs,vls]=eht(yls,{forceMount:void 0}),Xme="HoverCardContent",nht=S.forwardRef((s,t)=>{const r=vls(Xme,s.__scopeHoverCard),{forceMount:n=r.forceMount,...a}=s,i=UEe(Xme,s.__scopeHoverCard);return e.jsx(vh,{present:n||i.open,children:e.jsx(bls,{"data-state":i.open?"open":"closed",...a,onPointerEnter:an(s.onPointerEnter,Qme(i.onOpen)),onPointerLeave:an(s.onPointerLeave,Qme(i.onClose)),ref:t})})});nht.displayName=Xme;var bls=S.forwardRef((s,t)=>{const{__scopeHoverCard:r,onEscapeKeyDown:n,onPointerDownOutside:a,onFocusOutside:i,onInteractOutside:l,...o}=s,c=UEe(Xme,r),d=Exe(r),h=S.useRef(null),m=_i(t,h),[p,x]=S.useState(!1);return S.useEffect(()=>{if(p){const y=document.body;return C_e=y.style.userSelect||y.style.webkitUserSelect,y.style.userSelect="none",y.style.webkitUserSelect="none",()=>{y.style.userSelect=C_e,y.style.webkitUserSelect=C_e}}},[p]),S.useEffect(()=>{if(h.current){const y=()=>{x(!1),c.isPointerDownOnContentRef.current=!1,setTimeout(()=>{var b;((b=document.getSelection())==null?void 0:b.toString())!==""&&(c.hasSelectionRef.current=!0)})};return document.addEventListener("pointerup",y),()=>{document.removeEventListener("pointerup",y),c.hasSelectionRef.current=!1,c.isPointerDownOnContentRef.current=!1}}},[c.isPointerDownOnContentRef,c.hasSelectionRef]),S.useEffect(()=>{h.current&&jls(h.current).forEach(_=>_.setAttribute("tabindex","-1"))}),e.jsx(PS,{asChild:!0,disableOutsidePointerEvents:!1,onInteractOutside:l,onEscapeKeyDown:n,onPointerDownOutside:a,onFocusOutside:an(i,y=>{y.preventDefault()}),onDismiss:c.onDismiss,children:e.jsx(zB,{...d,...o,onPointerDown:an(o.onPointerDown,y=>{y.currentTarget.contains(y.target)&&x(!0),c.hasSelectionRef.current=!1,c.isPointerDownOnContentRef.current=!0}),ref:m,style:{...o.style,userSelect:p?"text":void 0,WebkitUserSelect:p?"text":void 0,"--radix-hover-card-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-hover-card-content-available-width":"var(--radix-popper-available-width)","--radix-hover-card-content-available-height":"var(--radix-popper-available-height)","--radix-hover-card-trigger-width":"var(--radix-popper-anchor-width)","--radix-hover-card-trigger-height":"var(--radix-popper-anchor-height)"}})})}),_ls="HoverCardArrow",wls=S.forwardRef((s,t)=>{const{__scopeHoverCard:r,...n}=s,a=Exe(r);return e.jsx($B,{...a,...n,ref:t})});wls.displayName=_ls;function Qme(s){return t=>t.pointerType==="touch"?void 0:s()}function jls(s){const t=[],r=document.createTreeWalker(s,NodeFilter.SHOW_ELEMENT,{acceptNode:n=>n.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP});for(;r.nextNode();)t.push(r.currentNode);return t}var Nls=tht,kls=rht,aht=nht;const Sls=Nls,Cls=kls,iht=S.forwardRef(({className:s,align:t="center",sideOffset:r=4,...n},a)=>e.jsx(aht,{ref:a,align:t,sideOffset:r,className:Ft("z-50 w-64 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",s),...n}));iht.displayName=aht.displayName;const Tls=[{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"}],Els=s=>s.split(" ").map(t=>t[0]).join("").toUpperCase().slice(0,2),oht=({reactions:s,children:t})=>{if(s.length===0)return e.jsx(e.Fragment,{children:t});const r={};return s.forEach(n=>{r[n.reaction_type]||(r[n.reaction_type]=[]),r[n.reaction_type].push(n)}),e.jsxs(Sls,{openDelay:200,closeDelay:100,children:[e.jsx(Cls,{asChild:!0,children:e.jsx("div",{className:"cursor-pointer",children:t})}),e.jsx(iht,{className:"w-64 p-3 bg-popover border shadow-lg z-50",side:"top",align:"start",children:e.jsx("div",{className:"space-y-3",children:Object.entries(r).map(([n,a])=>{const i=Tls.find(l=>l.type===n);return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("span",{className:"text-lg",children:i==null?void 0:i.emoji}),e.jsxs("span",{className:"text-sm font-medium text-foreground",children:[i==null?void 0:i.label," (",a.length,")"]})]}),e.jsxs("div",{className:"space-y-1.5",children:[a.slice(0,10).map(l=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Un,{className:"h-6 w-6",children:[e.jsx(Ka,{src:l.user_avatar||void 0}),e.jsx(qn,{className:"text-[10px]",children:Els(l.user_name||"U")})]}),e.jsx("span",{className:"text-sm text-foreground truncate",children:l.user_name||"Unknown User"})]},l.id)),a.length>10&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["+",a.length-10," more"]})]})]},n)})})})]})};function Als({images:s,initialIndex:t=0,open:r,onOpenChange:n}){const[a,i]=S.useState(t),[l,o]=S.useState(!1);S.useEffect(()=>{r&&(i(t),o(!1))},[r,t]);const c=()=>{i(p=>p>0?p-1:s.length-1),o(!1)},d=()=>{i(p=>p{r&&(p.key==="ArrowLeft"&&c(),p.key==="ArrowRight"&&d(),p.key==="Escape"&&n(!1))},[r,s.length]);S.useEffect(()=>(window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)),[h]);const m=s[a];return e.jsx(bs,{open:r,onOpenChange:n,children:e.jsxs(vs,{className:"max-w-[95vw] max-h-[95vh] w-auto h-auto p-0 border-none bg-black/95 overflow-hidden",children:[e.jsx(H,{variant:"ghost",size:"icon",className:"absolute top-2 right-2 z-50 text-white hover:bg-white/20 h-10 w-10",onClick:()=>n(!1),children:e.jsx(Rr,{className:"h-6 w-6"})}),s.length>1&&e.jsxs(e.Fragment,{children:[e.jsx(H,{variant:"ghost",size:"icon",className:"absolute left-2 top-1/2 -translate-y-1/2 z-50 text-white hover:bg-white/20 h-12 w-12",onClick:c,children:e.jsx(fl,{className:"h-8 w-8"})}),e.jsx(H,{variant:"ghost",size:"icon",className:"absolute right-2 top-1/2 -translate-y-1/2 z-50 text-white hover:bg-white/20 h-12 w-12",onClick:d,children:e.jsx($a,{className:"h-8 w-8"})})]}),s.length>1&&e.jsxs("div",{className:"absolute bottom-4 left-1/2 -translate-x-1/2 z-50 text-white text-sm bg-black/50 px-3 py-1 rounded-full",children:[a+1," / ",s.length]}),(m==null?void 0:m.type)==="image"&&e.jsx(H,{variant:"ghost",size:"icon",className:"absolute top-2 left-2 z-50 text-white hover:bg-white/20 h-10 w-10",onClick:()=>o(!l),children:l?e.jsx(JI,{className:"h-5 w-5"}):e.jsx(Qk,{className:"h-5 w-5"})}),e.jsx("div",{className:Ft("flex items-center justify-center w-full h-full min-h-[50vh] p-4",l?"cursor-zoom-out overflow-auto":"cursor-zoom-in"),onClick:()=>(m==null?void 0:m.type)==="image"&&o(!l),children:(m==null?void 0:m.type)==="video"?e.jsx("video",{src:m.url,controls:!0,autoPlay:!0,className:"max-w-full max-h-[85vh] object-contain",onClick:p=>p.stopPropagation()}):e.jsx("img",{src:m==null?void 0:m.url,alt:"",className:Ft("object-contain transition-transform duration-200",l?"max-w-none max-h-none scale-150":"max-w-full max-h-[85vh]")})}),s.length>1&&e.jsx("div",{className:"absolute bottom-12 left-1/2 -translate-x-1/2 z-50 flex gap-2 bg-black/50 p-2 rounded-lg max-w-[90vw] overflow-x-auto",children:s.map((p,x)=>e.jsx("button",{onClick:()=>{i(x),o(!1)},className:Ft("w-12 h-12 rounded overflow-hidden flex-shrink-0 border-2 transition-all",a===x?"border-white":"border-transparent opacity-60 hover:opacity-100"),children:p.type==="video"?e.jsx("video",{src:p.url,className:"w-full h-full object-cover"}):e.jsx("img",{src:p.url,alt:"",className:"w-full h-full object-cover"})},x))})]})})}const jq=[{type:"like",emoji:"👍",label:"Like"},{type:"love",emoji:"❤️",label:"Love"}],Mls=({commentId:s,reactions:t,currentUserId:r})=>{var d,h;const n=ns(),[a,i]=S.useState(!1),l=t.find(m=>m.user_id===r),o=Pt({mutationFn:async m=>{l?l.reaction_type===m?await V.from("community_comment_reactions").delete().eq("id",l.id):await V.from("community_comment_reactions").update({reaction_type:m}).eq("id",l.id):await V.from("community_comment_reactions").insert({comment_id:s,user_id:r,reaction_type:m})},onSuccess:()=>{n.invalidateQueries({queryKey:["community-posts"]}),i(!1)}}),c={};return t.forEach(m=>{c[m.reaction_type]=(c[m.reaction_type]||0)+1}),e.jsxs("div",{className:"flex items-center gap-2",children:[t.length>0&&e.jsx(oht,{reactions:t,children:e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx("div",{className:"flex -space-x-0.5",children:Object.keys(c).slice(0,2).map(m=>{var p;return e.jsx("span",{className:"text-sm",children:(p=jq.find(x=>x.type===m))==null?void 0:p.emoji},m)})}),e.jsx("span",{children:t.length})]})}),r&&e.jsxs(gl,{open:a,onOpenChange:i,children:[e.jsx(xl,{asChild:!0,children:e.jsx("button",{className:`text-xs hover:text-primary transition-colors ${l?"text-primary font-medium":"text-muted-foreground"}`,children:l?e.jsxs("span",{children:[(d=jq.find(m=>m.type===l.reaction_type))==null?void 0:d.emoji," ",(h=jq.find(m=>m.type===l.reaction_type))==null?void 0:h.label]}):e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Bi,{className:"h-3 w-3"}),"Like"]})})}),e.jsx(il,{className:"w-auto p-1.5 bg-popover border shadow-lg z-50",side:"top",children:e.jsx("div",{className:"flex gap-0.5",children:jq.map(m=>e.jsx("button",{onClick:()=>o.mutate(m.type),className:"text-xl hover:scale-125 transition-transform p-1",title:m.label,children:m.emoji},m.type))})})]})]})};function qEe({content:s,className:t}){const r=/([@#])\[([^\]]+)\]\(([^)]+)\)|(https?:\/\/[^\s<>]+)/g,n=[];let a=0,i,l=0;for(;(i=r.exec(s))!==null;){if(i.index>a&&n.push(s.substring(a,i.index)),i[1]){const o=i[1],c=i[2],d=i[3],h=o==="#";n.push(e.jsx(Xn,{to:h?`/templates/${d}`:`/profile?user=${d}`,className:Ft("font-medium hover:underline",h?"text-white bg-[#2a4c64] px-1.5 py-0.5 rounded":"text-primary"),onClick:m=>m.stopPropagation(),children:h?c:`@${c}`},`mention-${l++}`))}else if(i[4]){const o=i[4],c=o.replace(/[.,;:!?)]+$/,""),d=o.slice(c.length);let h;try{const m=new URL(c);h=m.hostname+(m.pathname!=="/"?m.pathname.slice(0,20)+(m.pathname.length>20?"...":""):"")}catch{h=c.length>40?c.slice(0,40)+"...":c}n.push(e.jsx("a",{href:c,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline break-all",onClick:m=>m.stopPropagation(),children:h},`url-${l++}`)),d&&n.push(d)}a=i.index+i[0].length}return ae.jsx(S.Fragment,{children:o},c))})}function Jme({value:s,onChange:t,placeholder:r="What's on your mind? Use @ to mention someone",className:n,minHeight:a="80px",onMentionsChange:i,onTemplatesChange:l,onKeyDown:o,mentionFormat:c="encoded",enableTemplateMentions:d=!1}){const h=S.useRef(null),m=S.useRef(null),[p,x]=S.useState(!1),[y,_]=S.useState("user"),[b,j]=S.useState(""),[k,T]=S.useState(null),[E,A]=S.useState(0),[D,R]=S.useState({top:0,left:0,width:0}),z=S.useRef(new Map),O=S.useRef(new Map),$=je=>{if(c==="plain"){const Le=[];return z.current.forEach((ze,Pe)=>{je.includes(`@${Pe}`)&&Le.push(ze)}),[...new Set(Le)]}const ve=/@\[([^\]]+)\]\(([^)]+)\)/g,We=[];let Ve;for(;(Ve=ve.exec(je))!==null;)We.push(Ve[2]);return[...new Set(We)]},ee=je=>{if(c==="plain"){const Le=[];return O.current.forEach((ze,Pe)=>{je.includes(`#${Pe}`)&&Le.push(ze)}),[...new Set(Le)]}const ve=/#\[([^\]]+)\]\(([^)]+)\)/g,We=[];let Ve;for(;(Ve=ve.exec(je))!==null;)We.push(Ve[2]);return[...new Set(We)]};S.useEffect(()=>{if(i){const je=$(s);i(je)}if(l){const je=ee(s);l(je)}},[s,i,l,c]);const{data:Z=[],isLoading:J}=yt({queryKey:["mention-users",b],queryFn:async()=>{const je=V.from("profiles").select("id, name").limit(8),ve=b.length>=1?je.ilike("name",`%${b}%`):je.order("name"),{data:We,error:Ve}=await ve;if(Ve)throw Ve;const Le=We.map(ze=>ze.id),Me=await Yat(Le);return We.map(ze=>({id:ze.id,name:ze.name||"Unknown",avatar_url:Me.get(ze.id)}))},enabled:p&&y==="user",staleTime:3e4}),{data:K=[],isLoading:re}=yt({queryKey:["mention-templates",b],queryFn:async()=>{let je=V.from("canva_templates").select("id, name, preview_image_url").lte("publish_date",new Date().toISOString()).order("publish_date",{ascending:!1}).limit(8);b.length>=1&&(je=je.ilike("name",`%${b}%`));const{data:ve,error:We}=await je;if(We)throw We;return ve||[]},enabled:p&&y==="template"&&d,staleTime:3e4}),ie=y==="user"?J:re,ce=y==="user"?Z:K,ne=je=>je.split(" ").map(ve=>ve[0]).join("").toUpperCase().slice(0,2),le=je=>{const ve=je.target.value,We=je.target.selectionStart;t(ve);const Ve=ve.substring(0,We),Le=Ve.lastIndexOf("@"),Me=d?Ve.lastIndexOf("#"):-1;let ze=-1,Pe="user";if(Le>Me?(ze=Le,Pe="user"):Me>Le&&d&&(ze=Me,Pe="template"),ze!==-1){const Ie=Ve.substring(ze+1),De=Ie.includes(" "),pe=Ie.includes(` `);if(!De&&!pe&&Ie.length<=30){T(ze),j(Ie),_(Pe),x(!0),A(0);return}}x(!1),T(null)},be=je=>{if(k===null)return;const ve=s.substring(0,k),We=s.substring(k+b.length+1),Ve=y==="user"?"@":"#",Le=c==="plain"?`${Ve}${je.name} `:`${Ve}[${je.name}](${je.id}) `;c==="plain"&&(y==="user"?z.current.set(je.name,je.id):O.current.set(je.name,je.id));const Me=ve+Le+We;t(Me),x(!1),T(null),j(""),setTimeout(()=>{if(h.current){const ze=ve.length+Le.length;h.current.focus(),h.current.setSelectionRange(ze,ze)}},0)},fe=je=>{if(!(!p||ce.length===0))switch(je.key){case"ArrowDown":je.preventDefault(),A(ve=>(ve+1)%ce.length);break;case"ArrowUp":je.preventDefault(),A(ve=>(ve-1+ce.length)%ce.length);break;case"Enter":ce[E]&&(je.preventDefault(),be(ce[E]));break;case"Escape":je.preventDefault(),x(!1);break;case"Tab":ce[E]&&(je.preventDefault(),be(ce[E]));break}};return S.useEffect(()=>{const je=ve=>{m.current&&!m.current.contains(ve.target)&&h.current&&!h.current.contains(ve.target)&&x(!1)};return document.addEventListener("mousedown",je),()=>document.removeEventListener("mousedown",je)},[]),S.useEffect(()=>{if(!p)return;const je=()=>{const ve=h.current;if(!ve)return;const We=ve.getBoundingClientRect();R({top:We.bottom+4,left:We.left,width:We.width})};return je(),window.addEventListener("resize",je),window.addEventListener("scroll",je,!0),()=>{window.removeEventListener("resize",je),window.removeEventListener("scroll",je,!0)}},[p,s]),e.jsxs("div",{className:"relative flex-1",children:[e.jsx(vr,{ref:h,value:s,onChange:le,onKeyDown:je=>{fe(je),je.defaultPrevented||o==null||o(je)},placeholder:r,className:Ft("resize-none",n),style:{minHeight:a}}),p&&tx.createPortal(e.jsxs("div",{ref:m,className:"fixed z-[1000] max-h-[220px] overflow-hidden rounded-lg border bg-popover shadow-lg",style:{top:D.top,left:D.left,width:D.width,maxWidth:"320px"},children:[e.jsx("div",{className:"px-3 py-1.5 text-xs font-medium text-muted-foreground border-b bg-muted/30",children:y==="user"?"👤 Mention a person":"📋 Link a template"}),ie?e.jsx("div",{className:"px-3 py-2 text-sm text-muted-foreground",children:"Searching..."}):ce.length===0?e.jsx("div",{className:"px-3 py-2 text-sm text-muted-foreground",children:b.length<1?`Type to search ${y==="user"?"people":"templates"}...`:`No ${y==="user"?"users":"templates"} found`}):e.jsx("ul",{className:"py-1 max-h-[180px] overflow-y-auto",children:ce.map((je,ve)=>e.jsx("li",{className:Ft("flex items-center gap-2 px-3 py-2 cursor-pointer transition-colors",ve===E?"bg-accent":"hover:bg-accent/50"),onClick:()=>be(je),onMouseEnter:()=>A(ve),children:y==="user"?e.jsxs(e.Fragment,{children:[e.jsxs(Un,{className:"h-6 w-6",children:[e.jsx(Ka,{src:je.avatar_url}),e.jsx(qn,{className:"text-xs",children:ne(je.name)})]}),e.jsx("span",{className:"text-sm font-medium truncate",children:je.name})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"h-8 w-8 rounded bg-muted flex items-center justify-center overflow-hidden flex-shrink-0",children:je.preview_image_url?e.jsx("img",{src:je.preview_image_url,alt:"",className:"w-full h-full object-cover"}):e.jsx(pl,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{className:"text-sm font-medium truncate",children:je.name})]})},je.id))})]}),document.body)]})}function Ils(s){const t=/#\[([^\]]+)\]\(([^)]+)\)/g,r=[];let n;for(;(n=t.exec(s))!==null;)r.push(n[2]);return[...new Set(r)]}const Yze=s=>s.split(" ").map(t=>t[0]).join("").toUpperCase().slice(0,2);function lht({comment:s,postId:t,currentUserId:r,currentUserAvatar:n,currentUserEmail:a,canModerate:i,depth:l=0}){const o=ns(),[c,d]=S.useState(!1),[h,m]=S.useState(""),[p,x]=S.useState([]),y=Pt({mutationFn:async({content:k,parentCommentId:T})=>{const{data:E,error:A}=await V.from("community_comments").insert({post_id:t,user_id:r,content:k,parent_comment_id:T}).select("id").single();if(A)throw A;const D=p;if(D.length>0&&E){const R=D.filter(z=>z!==r).map(z=>({comment_id:E.id,mentioned_user_id:z,mentioned_by_user_id:r}));R.length>0&&await V.from("community_comment_mentions").insert(R)}},onSuccess:()=>{o.invalidateQueries({queryKey:["community-posts"]}),m(""),x([]),d(!1)}}),_=Pt({mutationFn:async k=>{const{error:T}=await V.from("community_comments").delete().eq("id",k);if(T)throw T},onSuccess:()=>o.invalidateQueries({queryKey:["community-posts"]})}),b=()=>{h.trim()&&y.mutate({content:h,parentCommentId:s.id})};return e.jsxs("div",{className:l>0?"ml-8 border-l-2 border-muted pl-3":"",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Un,{className:"h-8 w-8 shrink-0",children:[e.jsx(Ka,{src:s.user_avatar||void 0}),e.jsx(qn,{className:"text-xs",children:Yze(s.user_name||"U")})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"bg-muted rounded-lg px-3 py-2",children:[e.jsx("div",{className:"font-medium text-sm",children:s.user_name}),e.jsx(qEe,{content:s.content,className:"text-sm break-words"})]}),e.jsxs("div",{className:"flex items-center gap-3 mt-1 text-xs text-muted-foreground flex-wrap",children:[e.jsx("span",{children:Hl(new Date(s.created_at),{addSuffix:!0})}),e.jsx(Mls,{commentId:s.id,reactions:s.reactions,currentUserId:r}),r&&l<2&&e.jsxs("button",{onClick:()=>d(!c),className:"hover:text-primary flex items-center gap-1",children:[e.jsx(TF,{className:"h-3 w-3"}),"Reply"]}),(s.user_id===r||i)&&e.jsx("button",{onClick:()=>_.mutate(s.id),className:"hover:text-destructive",children:s.user_id!==r?"Remove":"Delete"})]}),c&&r&&e.jsxs("div",{className:"flex gap-2 mt-2",children:[e.jsxs(Un,{className:"h-6 w-6 shrink-0 mt-1",children:[e.jsx(Ka,{src:n||void 0}),e.jsx(qn,{className:"text-xs",children:Yze((a==null?void 0:a.split("@")[0])||"U")})]}),e.jsxs("div",{className:"flex-1 flex gap-2 items-start",children:[e.jsx(Jme,{placeholder:`Reply to ${s.user_name}...`,value:h,onChange:m,onMentionsChange:x,mentionFormat:"plain",className:"text-sm min-h-0 py-1.5",minHeight:"32px"}),e.jsx(H,{size:"sm",variant:"ghost",onClick:b,disabled:!h.trim()||y.isPending,className:"h-8 px-2 mt-0.5",children:e.jsx(yn,{className:"h-3 w-3"})})]})]})]})]}),s.replies&&s.replies.length>0&&e.jsx("div",{className:"mt-2 space-y-2",children:s.replies.map(k=>e.jsx(lht,{comment:k,postId:t,currentUserId:r,currentUserAvatar:n,currentUserEmail:a,canModerate:i,depth:l+1},k.id))})]})}const Nq=[{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"}],Pls=()=>{const{user:s,isBrokerageManager:t,managedBrokerages:r,isAdmin:n}=Ms(),{avatarUrl:a}=Kat(s==null?void 0:s.id),{onlineUsers:i}=yet(),{toast:l}=li(),o=ns(),c=S.useRef(null),[d,h]=S.useState("all"),[m,p]=S.useState(""),[x,y]=S.useState(""),[_,b]=S.useState(""),[j,k]=S.useState([]),[T,E]=S.useState([]),[A,D]=S.useState(""),[R,z]=S.useState(!1),[O,$]=S.useState(null),[ee,Z]=S.useState(""),[J,K]=S.useState(new Set),[re,ie]=S.useState({}),[ce,ne]=S.useState({}),[le,be]=S.useState([]),[fe,je]=S.useState([]),[ve,We]=S.useState({open:!1,images:[],index:0});S.useEffect(()=>{if(d.startsWith("group:")){const rt=d.replace("group:","");b(rt),y("")}else d!=="all"?(y(d),b("")):(y(""),b(""))},[d]);const{data:Ve=[]}=yt({queryKey:["community-categories"],queryFn:async()=>{const{data:rt,error:Et}=await V.from("community_categories").select("*").order("sort_order");if(Et)throw Et;return rt}}),{data:Le=[]}=yt({queryKey:["community-private-groups"],queryFn:async()=>{const{data:rt,error:Et}=await V.from("community_private_groups").select("id, name, description, icon, brokerage_id, sort_order").order("sort_order");if(Et)throw Et;return rt}}),Me=20,{data:ze,isLoading:Pe,hasNextPage:Ie,fetchNextPage:De,isFetchingNextPage:pe}=p5t({queryKey:["community-posts",d],initialPageParam:0,queryFn:async({pageParam:rt})=>{var He;const Et=rt*Me,hs=Et+Me;let Is=V.from("community_posts").select("*").order("is_pinned",{ascending:!1}).order("pinned_at",{ascending:!1,nullsFirst:!1}).order("created_at",{ascending:!1}).range(Et,hs);if(d.startsWith("group:")){const ot=d.replace("group:","");Is=Is.eq("private_group_id",ot)}else d==="all"||(Is=Is.eq("category_id",d).is("private_group_id",null));const{data:lr,error:us}=await Is;if(us)throw us;const St=((lr==null?void 0:lr.length)||0)>Me,xs=(lr||[]).slice(0,Me);if(xs.length===0)return{posts:[],hasMore:!1,nextPage:rt+1};const kt=xs.map(ot=>ot.id),fs=[...new Set(xs.filter(ot=>ot.category_id).map(ot=>ot.category_id))].filter(Boolean),[Gs,_s,br,zr,Yr]=await Promise.all([fs.length?V.from("community_categories").select("*").in("id",fs):Promise.resolve({data:[]}),V.from("community_post_media").select("*").in("post_id",kt).order("sort_order"),V.from("community_reactions").select("*").in("post_id",kt),V.from("community_comments").select("*").in("post_id",kt).order("created_at",{ascending:!0}),V.from("community_post_resources").select("*").in("post_id",kt)]),rn=Gs==null?void 0:Gs.data,sn=_s==null?void 0:_s.data,Vr=br==null?void 0:br.data,$r=zr==null?void 0:zr.data,hn=Yr==null?void 0:Yr.data,Zn=($r||[]).map(ot=>ot.id),[cr,on]=await Promise.all([Zn.length?V.from("community_comment_reactions").select("*").in("comment_id",Zn):Promise.resolve({data:[]}),(()=>{const ot=(hn||[]).filter(jt=>jt.resource_type==="template").map(jt=>jt.resource_id);return ot.length===0?Promise.resolve({data:[]}):V.from("canva_templates").select("id, name, preview_image_url").in("id",ot)})()]),ds=(cr==null?void 0:cr.data)||[],Na=(on==null?void 0:on.data)||[],vn=new Map(Na.map(ot=>[ot.id,{name:ot.name,preview_image_url:ot.preview_image_url}])),_r=Array.from(new Set([...xs.map(ot=>ot.user_id),...(Vr||[]).map(ot=>ot.user_id),...($r||[]).map(ot=>ot.user_id),...ds.map(ot=>ot.user_id)])),[Hr,_a]=await Promise.all([_r.length?V.from("profiles").select("id, name").in("id",_r):Promise.resolve({data:[]}),Yat(_r)]),Jt=new Map(((He=Hr==null?void 0:Hr.data)==null?void 0:He.map(ot=>[ot.id,ot.name]))||[]),Cr=new Map((rn||[]).map(ot=>[ot.id,ot])),Gt=ot=>{const jt=new Map,Dt=[];return ot.forEach(qt=>{jt.set(qt.id,{...qt,user_name:Jt.get(qt.user_id)||"Unknown User",user_avatar:_a.get(qt.user_id),reactions:ds.filter(ss=>ss.comment_id===qt.id).map(ss=>({...ss,user_name:Jt.get(ss.user_id)||"Unknown User",user_avatar:_a.get(ss.user_id)})),replies:[]})}),ot.forEach(qt=>{const ss=jt.get(qt.id);if(qt.parent_comment_id&&jt.has(qt.parent_comment_id)){const Yt=jt.get(qt.parent_comment_id);Yt.replies=Yt.replies||[],Yt.replies.push(ss)}else Dt.push(ss)}),Dt};return{posts:xs.map(ot=>{const jt=(hn||[]).filter(Dt=>Dt.post_id===ot.id).map(Dt=>{let qt="",ss=null;if(Dt.resource_type==="template"){const Yt=vn.get(Dt.resource_id);qt=(Yt==null?void 0:Yt.name)||"Unknown Template",ss=(Yt==null?void 0:Yt.preview_image_url)||null}return{id:Dt.id,resource_type:Dt.resource_type,resource_id:Dt.resource_id,resource_name:qt,resource_preview_url:ss}});return{...ot,user_name:Jt.get(ot.user_id)||"Unknown User",user_avatar:_a.get(ot.user_id),category:ot.category_id?Cr.get(ot.category_id):null,media:(sn||[]).filter(Dt=>Dt.post_id===ot.id),reactions:((Vr||[]).filter(Dt=>Dt.post_id===ot.id)||[]).map(Dt=>({...Dt,user_name:Jt.get(Dt.user_id)||"Unknown User",user_avatar:_a.get(Dt.user_id)})),comments:Gt(($r||[]).filter(Dt=>Dt.post_id===ot.id)),resources:jt}}),hasMore:St,nextPage:rt+1}},getNextPageParam:rt=>rt.hasMore?rt.nextPage:void 0}),tt=S.useMemo(()=>(ze==null?void 0:ze.pages.flatMap(rt=>rt.posts))??[],[ze]),ge=Pt({mutationFn:async()=>{z(!0);const{data:rt,error:Et}=await V.from("community_posts").insert({user_id:s.id,category_id:_?null:x||null,private_group_id:_||null,content:m,link_url:A||null}).select().single();if(Et)throw Et;for(let Is=0;Is0){const Is=le.filter(lr=>lr!==s.id).map(lr=>({post_id:rt.id,mentioned_user_id:lr,mentioned_by_user_id:s.id}));Is.length>0&&await V.from("community_post_mentions").insert(Is)}const hs=Ils(m);if(hs.length>0){const Is=hs.map(lr=>({post_id:rt.id,resource_type:"template",resource_id:lr}));await V.from("community_post_resources").insert(Is)}return rt},onSuccess:async rt=>{var Et;o.invalidateQueries({queryKey:["community-posts"]}),p(""),be([]),je([]),y(""),b(""),k([]),E([]),D(""),l({title:"Post created!"});try{const hs=((Et=s==null?void 0:s.user_metadata)==null?void 0:Et.name)||"Someone",Is=m.replace(/@\[([^\]]+)\]\([^)]+\)/g,"@$1"),lr=Is.length>50?Is.substring(0,50)+"...":Is;await V.functions.invoke("send-push-notification",{body:{title:"New Community Post",body:`${hs}: ${lr}`,url:"/community"}})}catch(hs){console.error("Failed to send push notification:",hs)}},onError:rt=>{l({title:"Error creating post",description:rt.message,variant:"destructive"})},onSettled:()=>z(!1)}),ct=Pt({mutationFn:async({postId:rt,content:Et})=>{const{error:hs}=await V.from("community_posts").update({content:Et}).eq("id",rt);if(hs)throw hs},onSuccess:()=>{o.invalidateQueries({queryKey:["community-posts"]}),$(null),Z(""),l({title:"Post updated!"})}}),Ue=Pt({mutationFn:async rt=>{const{error:Et}=await V.from("community_posts").delete().eq("id",rt);if(Et)throw Et},onSuccess:()=>{o.invalidateQueries({queryKey:["community-posts"]}),l({title:"Post deleted"})}}),et=Pt({mutationFn:async({postId:rt,isPinned:Et})=>{const{error:hs}=await V.from("community_posts").update({is_pinned:!Et,pinned_at:Et?null:new Date().toISOString(),pinned_by:Et?null:s==null?void 0:s.id}).eq("id",rt);if(hs)throw hs},onSuccess:(rt,{isPinned:Et})=>{o.invalidateQueries({queryKey:["community-posts"]}),l({title:Et?"Post unpinned":"Post pinned to top"})}}),Qe=Pt({mutationFn:async({postId:rt,reactionType:Et})=>{var Is;const hs=(Is=tt.find(lr=>lr.id===rt))==null?void 0:Is.reactions.find(lr=>lr.user_id===(s==null?void 0:s.id));hs?hs.reaction_type===Et?await V.from("community_reactions").delete().eq("id",hs.id):await V.from("community_reactions").update({reaction_type:Et}).eq("id",hs.id):await V.from("community_reactions").insert({post_id:rt,user_id:s.id,reaction_type:Et})},onSuccess:()=>o.invalidateQueries({queryKey:["community-posts"]})}),Ne=Pt({mutationFn:async({postId:rt,content:Et})=>{const{data:hs,error:Is}=await V.from("community_comments").insert({post_id:rt,user_id:s.id,content:Et}).select("id").single();if(Is)throw Is;const lr=ce[rt]||[];if(lr.length>0&&hs){const us=lr.filter(St=>St!==s.id).map(St=>({comment_id:hs.id,mentioned_user_id:St,mentioned_by_user_id:s.id}));us.length>0&&await V.from("community_comment_mentions").insert(us)}},onSuccess:(rt,{postId:Et})=>{o.invalidateQueries({queryKey:["community-posts"]}),ie(hs=>({...hs,[Et]:""})),ne(hs=>({...hs,[Et]:[]}))}});Pt({mutationFn:async rt=>{const{error:Et}=await V.from("community_comments").delete().eq("id",rt);if(Et)throw Et},onSuccess:()=>o.invalidateQueries({queryKey:["community-posts"]})});const $e=rt=>{const Et=Array.from(rt.target.files||[]);if(Et.length+j.length>10){l({title:"Maximum 10 files allowed",variant:"destructive"});return}k(hs=>[...hs,...Et]),Et.forEach(hs=>{const Is=new FileReader;Is.onloadend=()=>{E(lr=>[...lr,Is.result])},Is.readAsDataURL(hs)})},it=rt=>{k(Et=>Et.filter((hs,Is)=>Is!==rt)),E(Et=>Et.filter((hs,Is)=>Is!==rt))},Je=rt=>rt.split(" ").map(Et=>Et[0]).join("").toUpperCase().slice(0,2),st=rt=>{const Et={};return rt.forEach(hs=>{Et[hs.reaction_type]=(Et[hs.reaction_type]||0)+1}),Et},mt=rt=>{var Et;return(Et=rt.find(hs=>hs.user_id===(s==null?void 0:s.id)))==null?void 0:Et.reaction_type},wt=rt=>rt.reduce((Et,hs)=>Et+1+(hs.replies?wt(hs.replies):0),0),at=rt=>{if(n)return!0;if(!t||!rt.private_group_id)return!1;const Et=Le.find(hs=>hs.id===rt.private_group_id);return Et!=null&&Et.brokerage_id?r.some(hs=>hs.id===Et.brokerage_id):!1};return e.jsx(Ss,{title:"Community",children:e.jsxs("div",{className:"flex gap-6 w-full isolate z-0",children:[e.jsx(pls,{categories:Ve,privateGroups:Le,selectedFilter:d,onFilterChange:h,onlineUsers:i}),e.jsxs("div",{className:"flex-1 min-w-0 max-w-2xl mx-auto lg:mx-0 space-y-6",children:[e.jsxs("div",{className:"px-1",children:[e.jsx("h1",{className:"text-4xl lg:text-5xl font-bold text-foreground",children:"Community"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Connect and share with fellow agents"})]}),e.jsx(gls,{categories:Ve,privateGroups:Le,selectedFilter:d,onFilterChange:h,onlineUsers:i}),e.jsx(ke,{children:e.jsx(Oe,{className:"pt-6",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsxs(Un,{className:"h-10 w-10",children:[e.jsx(Ka,{src:a||void 0}),e.jsx(qn,{children:s!=null&&s.email?Je(s.email.split("@")[0]):"U"})]}),e.jsxs("div",{className:"flex-1 space-y-3",children:[e.jsx(Jme,{placeholder:n?"What's on your mind? Use @ to mention someone, # to link a template":"What's on your mind? Use @ to mention someone",value:m,onChange:p,onMentionsChange:be,onTemplatesChange:je,mentionFormat:"encoded",minHeight:"80px",enableTemplateMentions:n}),T.length>0&&e.jsx("div",{className:"grid grid-cols-3 gap-2",children:T.map((rt,Et)=>{var hs;return e.jsxs("div",{className:"relative aspect-square rounded-lg overflow-hidden bg-muted",children:[(hs=j[Et])!=null&&hs.type.startsWith("video/")?e.jsx("video",{src:rt,className:"w-full h-full object-cover"}):e.jsx("img",{src:rt,alt:"",className:"w-full h-full object-cover"}),e.jsx(H,{variant:"destructive",size:"icon",className:"absolute top-1 right-1 h-6 w-6",onClick:()=>it(Et),children:e.jsx(Rr,{className:"h-3 w-3"})})]},Et)})}),A&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Jo,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(Se,{value:A,onChange:rt=>D(rt.target.value),placeholder:"https://...",className:"flex-1"}),e.jsx(H,{variant:"ghost",size:"icon",onClick:()=>D(""),children:e.jsx(Rr,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex gap-1 flex-wrap",children:[e.jsx("input",{type:"file",ref:c,onChange:$e,accept:"image/*,video/*",multiple:!0,className:"hidden"}),e.jsxs(H,{variant:"ghost",size:"sm",onClick:()=>{var rt;return(rt=c.current)==null?void 0:rt.click()},children:[e.jsx(wl,{className:"h-4 w-4 mr-1"}),"Photo"]}),e.jsxs(H,{variant:"ghost",size:"sm",onClick:()=>{var rt;return(rt=c.current)==null?void 0:rt.click()},children:[e.jsx(xn,{className:"h-4 w-4 mr-1"}),"Video"]}),e.jsxs(H,{variant:"ghost",size:"sm",onClick:()=>D("https://"),children:[e.jsx(Jo,{className:"h-4 w-4 mr-1"}),"Link"]})]}),e.jsxs("div",{className:"flex items-center gap-2 w-full sm:w-auto justify-end",children:[Le.length>0?e.jsxs(Bs,{value:_||x||"none",onValueChange:rt=>{rt==="none"?(y(""),b("")):rt.startsWith("group:")?(b(rt.replace("group:","")),y("")):(y(rt),b(""))},children:[e.jsx(Os,{className:"w-[130px] sm:w-[160px] h-8 text-xs sm:text-sm",children:e.jsx(Us,{placeholder:"Select..."})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"none",children:"No category"}),Ve.map(rt=>e.jsxs(pt,{value:rt.id,children:[rt.icon," ",rt.name]},rt.id)),Le.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-2 py-1 text-xs font-semibold text-muted-foreground border-t mt-1 pt-1",children:"🔒 Private Groups"}),Le.map(rt=>e.jsxs(pt,{value:`group:${rt.id}`,children:[rt.icon||"🔒"," ",rt.name]},rt.id))]})]})]}):e.jsxs(Bs,{value:x,onValueChange:y,children:[e.jsx(Os,{className:"w-[110px] sm:w-[140px] h-8 text-xs sm:text-sm",children:e.jsx(Us,{placeholder:"Category"})}),e.jsx(Fs,{children:Ve.map(rt=>e.jsxs(pt,{value:rt.id,children:[rt.icon," ",rt.name]},rt.id))})]}),e.jsxs(H,{size:"sm",onClick:()=>ge.mutate(),disabled:!m.trim()||R,children:[e.jsx(yn,{className:"h-4 w-4 mr-1"}),"Post"]})]})]})]})]})})}),Pe?e.jsx("div",{className:"space-y-4",children:[...Array(3)].map((rt,Et)=>e.jsx(ke,{children:e.jsx(Oe,{className:"pt-6",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Ks,{className:"h-10 w-10 rounded-full"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(Ks,{className:"h-4 w-32"}),e.jsx(Ks,{className:"h-4 w-full"}),e.jsx(Ks,{className:"h-4 w-3/4"})]})]})})},Et))}):tt.length===0?e.jsx(ke,{children:e.jsxs(Oe,{className:"py-12 text-center",children:[e.jsx(qc,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"font-semibold mb-2",children:"No posts yet"}),e.jsx("p",{className:"text-muted-foreground",children:"Be the first to start a conversation!"})]})}):e.jsxs("div",{className:"space-y-4",children:[tt.map(rt=>{var Et,hs,Is,lr;return e.jsx(ke,{children:e.jsxs(Oe,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-start justify-between mb-3",children:[e.jsxs("div",{className:"flex gap-3 min-w-0",children:[e.jsxs(Un,{className:"h-10 w-10",children:[e.jsx(Ka,{src:rt.user_avatar||void 0}),e.jsx(qn,{children:Je(rt.user_name||"U")})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-semibold break-words",children:rt.user_name}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-sm text-muted-foreground",children:[e.jsx("span",{children:Hl(new Date(rt.created_at),{addSuffix:!0})}),rt.category&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"•"}),e.jsxs(Xe,{variant:"secondary",className:"text-xs",children:[rt.category.icon," ",rt.category.name]})]})]})]})]}),(rt.user_id===(s==null?void 0:s.id)||at(rt))&&e.jsxs(Xu,{children:[e.jsx(Qu,{asChild:!0,children:e.jsx(H,{variant:"ghost",size:"icon",className:"h-8 w-8",children:e.jsx(Jx,{className:"h-4 w-4"})})}),e.jsxs(wu,{align:"end",children:[at(rt)&&rt.private_group_id&&e.jsx(di,{onClick:()=>et.mutate({postId:rt.id,isPinned:rt.is_pinned}),children:rt.is_pinned?e.jsxs(e.Fragment,{children:[e.jsx(jF,{className:"h-4 w-4 mr-2"}),"Unpin Post"]}):e.jsxs(e.Fragment,{children:[e.jsx(Wk,{className:"h-4 w-4 mr-2"}),"Pin to Top"]})}),rt.user_id===(s==null?void 0:s.id)&&e.jsxs(di,{onClick:()=>{$(rt),Z(rt.content)},children:[e.jsx(ni,{className:"h-4 w-4 mr-2"}),"Edit"]}),e.jsxs(di,{className:"text-destructive",onClick:()=>Ue.mutate(rt.id),children:[e.jsx(Dr,{className:"h-4 w-4 mr-2"}),rt.user_id!==(s==null?void 0:s.id)?"Remove (Moderate)":"Delete"]})]})]})]}),rt.is_pinned&&e.jsxs("div",{className:"flex items-center gap-2 mb-2 text-sm text-primary",children:[e.jsx(Wk,{className:"h-4 w-4"}),e.jsx("span",{className:"font-medium",children:"Pinned"})]}),e.jsx("div",{className:"mb-3",children:e.jsx(qEe,{content:rt.content})}),rt.media.length>0&&e.jsx("div",{className:`grid gap-2 mb-3 ${rt.media.length===1?"grid-cols-1":rt.media.length===2?"grid-cols-2":rt.media.length===3?"grid-cols-3":"grid-cols-2"}`,children:rt.media.slice(0,4).map((us,St)=>{const xs=St===3&&rt.media.length>4,kt=rt.media.length-4;return e.jsxs("div",{className:`relative rounded-lg overflow-hidden bg-muted cursor-pointer group ${rt.media.length===1?"max-h-[500px]":rt.media.length===2?"aspect-[4/3]":"aspect-square"}`,onClick:()=>We({open:!0,images:rt.media.map(fs=>({url:fs.media_url,type:fs.media_type==="video"?"video":"image"})),index:St}),children:[us.media_type==="video"?e.jsx("video",{src:us.media_url,className:"w-full h-full object-cover transition-transform group-hover:scale-105"}):e.jsx("img",{src:us.media_url,alt:"",className:"w-full h-full object-cover transition-transform group-hover:scale-105"}),e.jsx("div",{className:"absolute inset-0 bg-black/0 group-hover:bg-black/20 transition-colors flex items-center justify-center",children:e.jsx("div",{className:"opacity-0 group-hover:opacity-100 transition-opacity text-white",children:e.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-8 w-8",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0zM10 7v3m0 0v3m0-3h3m-3 0H7"})})})}),xs&&e.jsx("div",{className:"absolute inset-0 bg-black/60 flex items-center justify-center",children:e.jsxs("span",{className:"text-white text-2xl font-bold",children:["+",kt]})})]},us.id)})}),rt.link_url&&e.jsxs("a",{href:rt.link_url,target:"_blank",rel:"noopener noreferrer",className:"block rounded-lg border hover:bg-muted transition-colors mb-3 overflow-hidden",children:[rt.link_image&&e.jsx("div",{className:"aspect-video bg-muted",children:e.jsx("img",{src:rt.link_image,alt:rt.link_title||"Link preview",className:"w-full h-full object-cover",onError:us=>{us.currentTarget.style.display="none"}})}),e.jsx("div",{className:"p-3",children:rt.link_title?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"font-medium text-foreground line-clamp-2",children:rt.link_title}),rt.link_description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mt-1",children:rt.link_description}),e.jsx("p",{className:"text-xs text-muted-foreground mt-2 truncate",children:new URL(rt.link_url).hostname})]}):e.jsxs("div",{className:"flex items-center gap-2 text-sm text-primary",children:[e.jsx(Jo,{className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:rt.link_url})]})})]}),rt.reactions.length>0&&e.jsx(oht,{reactions:rt.reactions,children:e.jsxs("div",{className:"flex items-center gap-2 mb-3 text-sm text-muted-foreground hover:text-foreground transition-colors cursor-pointer",children:[e.jsx("div",{className:"flex -space-x-1",children:Object.entries(st(rt.reactions)).slice(0,3).map(([us])=>{var St;return e.jsx("span",{className:"text-base",children:(St=Nq.find(xs=>xs.type===us))==null?void 0:St.emoji},us)})}),e.jsx("span",{children:rt.reactions.length})]})}),e.jsxs("div",{className:"flex items-center gap-1 border-t border-b py-1 my-2",children:[e.jsxs(gl,{children:[e.jsx(xl,{asChild:!0,children:e.jsxs(H,{variant:"ghost",size:"sm",className:"flex-1",children:[mt(rt.reactions)?e.jsx("span",{className:"mr-1",children:(Et=Nq.find(us=>us.type===mt(rt.reactions)))==null?void 0:Et.emoji}):e.jsx(sf,{className:"h-4 w-4 mr-1"}),mt(rt.reactions)?(hs=Nq.find(us=>us.type===mt(rt.reactions)))==null?void 0:hs.label:"Like"]})}),e.jsx(il,{className:"w-auto p-2",side:"top",children:e.jsx("div",{className:"flex gap-1",children:Nq.map(us=>e.jsx("button",{onClick:()=>Qe.mutate({postId:rt.id,reactionType:us.type}),className:"text-2xl hover:scale-125 transition-transform p-1",title:us.label,children:us.emoji},us.type))})})]}),e.jsxs(H,{variant:"ghost",size:"sm",className:"flex-1",onClick:()=>K(us=>{const St=new Set(us);return St.has(rt.id)?St.delete(rt.id):St.add(rt.id),St}),children:[e.jsx(qc,{className:"h-4 w-4 mr-1"}),(()=>{const us=wt(rt.comments);return us>0?`Comment (${us})`:"Comment"})()]})]}),J.has(rt.id)&&e.jsxs("div",{className:"space-y-3 mt-3",children:[rt.comments.map(us=>e.jsx(lht,{comment:us,postId:rt.id,currentUserId:s==null?void 0:s.id,currentUserAvatar:a,currentUserEmail:s==null?void 0:s.email,canModerate:at(rt)},us.id)),s&&e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Un,{className:"h-8 w-8",children:[e.jsx(Ka,{src:a||void 0}),e.jsx(qn,{className:"text-xs",children:Je(((Is=s.email)==null?void 0:Is.split("@")[0])||"U")})]}),e.jsxs("div",{className:"flex-1 flex gap-2",children:[e.jsx(Jme,{placeholder:"Write a comment... (use @ to mention)",value:re[rt.id]||"",onChange:us=>ie(St=>({...St,[rt.id]:us})),onMentionsChange:us=>ne(St=>({...St,[rt.id]:us})),mentionFormat:"plain",onKeyDown:us=>{var St;us.defaultPrevented||us.key==="Enter"&&!us.shiftKey&&((St=re[rt.id])!=null&&St.trim())&&(us.preventDefault(),Ne.mutate({postId:rt.id,content:re[rt.id]}))},className:"text-sm min-h-0 py-1.5",minHeight:"32px"}),e.jsx(H,{size:"sm",variant:"ghost",onClick:()=>{var us;(us=re[rt.id])!=null&&us.trim()&&Ne.mutate({postId:rt.id,content:re[rt.id]})},disabled:!((lr=re[rt.id])!=null&&lr.trim()),className:"h-8 px-2 mt-0.5",children:e.jsx(yn,{className:"h-4 w-4"})})]})]})]})]})},rt.id)}),Ie&&e.jsx("div",{className:"flex justify-center pt-2",children:e.jsx(H,{variant:"outline",onClick:()=>De(),disabled:pe,children:pe?"Loading…":"Load more posts"})})]}),e.jsx(bs,{open:!!O,onOpenChange:()=>$(null),children:e.jsxs(vs,{children:[e.jsx(Cs,{children:e.jsx(Ns,{children:"Edit Post"})}),e.jsx(vr,{value:ee,onChange:rt=>Z(rt.target.value),className:"min-h-[120px]"}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(H,{variant:"outline",onClick:()=>$(null),children:"Cancel"}),e.jsx(H,{onClick:()=>{O&&ct.mutate({postId:O.id,content:ee})},disabled:!ee.trim(),children:"Save Changes"})]})]})}),e.jsx(Als,{images:ve.images,initialIndex:ve.index,open:ve.open,onOpenChange:rt=>We(Et=>({...Et,open:rt}))})]})]})})},Lls=50*1024*1024;function cht({value:s,onChange:t,disabled:r}){const{user:n}=Ms(),a=S.useRef(null),[i,l]=S.useState(!1),o=async d=>{if(!d||!n)return;const h=[];l(!0);try{for(const m of Array.from(d)){if(!m.type.startsWith("image/")&&!m.type.startsWith("video/")){he.error(`${m.name}: only images and videos allowed`);continue}if(m.size>Lls){he.error(`${m.name}: must be under 50MB`);continue}const p=m.name.split(".").pop()||"bin",x=`${n.id}/${Date.now()}-${Math.random().toString(36).slice(2,8)}.${p}`,{error:y}=await V.storage.from("support-attachments").upload(x,m,{contentType:m.type,upsert:!1});if(y){he.error(`${m.name}: ${y.message}`);continue}h.push({path:x,type:m.type,name:m.name,size:m.size})}h.length&&t([...s,...h])}finally{l(!1),a.current&&(a.current.value="")}},c=async d=>{const h=s[d];t(s.filter((m,p)=>p!==d)),await V.storage.from("support-attachments").remove([h.path])};return e.jsxs("div",{className:"space-y-2",children:[s.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2",children:s.map((d,h)=>e.jsxs("div",{className:"flex items-center gap-2 px-2 py-1 rounded-md border bg-muted/40 text-xs",children:[d.type.startsWith("video/")?e.jsx(cF,{className:"h-3.5 w-3.5 text-muted-foreground"}):e.jsx(z2,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"max-w-[160px] truncate",children:d.name}),e.jsx("button",{type:"button",onClick:()=>c(h),className:"text-muted-foreground hover:text-foreground",children:e.jsx(Rr,{className:"h-3 w-3"})})]},d.path))}),e.jsxs(H,{type:"button",variant:"outline",size:"sm",onClick:()=>{var d;return(d=a.current)==null?void 0:d.click()},disabled:r||i,className:"gap-1.5",children:[i?e.jsx(is,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Hk,{className:"h-3.5 w-3.5"}),i?"Uploading...":"Attach photo or video"]}),e.jsx("input",{ref:a,type:"file",accept:"image/*,video/*",multiple:!0,className:"hidden",onChange:d=>o(d.target.files)})]})}function dht({attachments:s}){const[t,r]=S.useState({}),[n,a]=S.useState(!0);return S.useEffect(()=>{if(!(s!=null&&s.length)){a(!1);return}let i=!1;return(async()=>{const l=s.map(d=>d.path),{data:o}=await V.storage.from("support-attachments").createSignedUrls(l,60*60*24);if(i||!o)return;const c={};o.forEach((d,h)=>{d.signedUrl&&(c[l[h]]=d.signedUrl)}),r(c),a(!1)})(),()=>{i=!0}},[s]),s!=null&&s.length?n?e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground mt-2",children:[e.jsx(is,{className:"h-3 w-3 animate-spin"})," Loading attachments..."]}):e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2 mt-3",children:s.map(i=>{const l=t[i.path];return l?i.type.startsWith("video/")?e.jsx("video",{src:l,controls:!0,className:"rounded-md border w-full h-auto max-h-64 bg-black"},i.path):e.jsx("a",{href:l,target:"_blank",rel:"noopener noreferrer",className:"block",children:e.jsx("img",{src:l,alt:i.name,className:"rounded-md border w-full h-32 object-cover hover:opacity-90 transition-opacity"})},i.path):null})}):null}const N6={open:{label:"Open",icon:Pn,color:"bg-yellow-500"},in_progress:{label:"In Progress",icon:qc,color:"bg-blue-500"},resolved:{label:"Resolved",icon:zi,color:"bg-green-500"},closed:{label:"Closed",icon:kd,color:"bg-muted-foreground"}},Zze={general:"General Support",technology:"Technology Support",crm:"CRM Support",marketing:"Marketing Support"};function Dls(){const{user:s}=Ms(),t=ns(),[r,n]=S.useState(null),[a,i]=S.useState(""),[l,o]=S.useState([]),{data:c=[],isLoading:d}=yt({queryKey:["support-tickets"],queryFn:async()=>{const{data:x,error:y}=await V.from("support_tickets").select("*").eq("user_id",s==null?void 0:s.id).order("created_at",{ascending:!1});if(y)throw y;return x},enabled:!!s}),{data:h=[]}=yt({queryKey:["ticket-replies",r==null?void 0:r.id],queryFn:async()=>{if(!r)return[];const{data:x,error:y}=await V.from("support_ticket_replies").select("*, profiles(name)").eq("ticket_id",r.id).order("created_at",{ascending:!0});if(y)throw y;return x},enabled:!!r}),m=Pt({mutationFn:async({content:x,attachments:y})=>{if(!r||!s)throw new Error("Missing data");const{error:_}=await V.from("support_ticket_replies").insert({ticket_id:r.id,user_id:s.id,content:x,is_admin_reply:!1,attachments:y});if(_)throw _},onSuccess:()=>{t.invalidateQueries({queryKey:["ticket-replies",r==null?void 0:r.id]}),i(""),o([]),he.success("Reply sent!")},onError:()=>{he.error("Failed to send reply")}}),p=()=>{!a.trim()&&l.length===0||m.mutate({content:a,attachments:l})};if(r){const x=N6[r.status].icon;return e.jsx(Ss,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(H,{variant:"ghost",size:"icon",onClick:()=>n(null),children:e.jsx(za,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h1",{className:"text-2xl font-bold",children:r.subject}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(Xe,{variant:"secondary",children:Zze[r.category]}),e.jsxs(Xe,{className:N6[r.status].color,children:[e.jsx(x,{className:"h-3 w-3 mr-1"}),N6[r.status].label]})]})]})]}),e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsxs(Br,{children:["Created on ",As(new Date(r.created_at),"MMM d, yyyy 'at' h:mm a")]})}),e.jsx(Oe,{children:e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:r.description})})]}),e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-lg",children:"Conversation"})}),e.jsxs(Oe,{children:[e.jsx(Ci,{className:"h-[300px] pr-4",children:h.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-8",children:"No replies yet"}):e.jsx("div",{className:"space-y-4",children:h.map(y=>{var _;return e.jsxs("div",{className:`p-4 rounded-lg ${y.is_admin_reply?"bg-primary/10 ml-4":"bg-muted mr-4"}`,children:[e.jsxs("div",{className:"flex justify-between items-start mb-2",children:[e.jsx("span",{className:"font-medium text-sm",children:y.is_admin_reply?"Support Team":((_=y.profiles)==null?void 0:_.name)||"You"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:As(new Date(y.created_at),"MMM d, h:mm a")})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:y.content}),y.attachments&&y.attachments.length>0&&e.jsx(dht,{attachments:y.attachments})]},y.id)})})}),r.status!=="closed"&&e.jsxs(e.Fragment,{children:[e.jsx(Qo,{className:"my-4"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(vr,{placeholder:"Type your reply...",value:a,onChange:y=>i(y.target.value),className:"min-h-[80px]"}),e.jsx(H,{onClick:p,disabled:!a.trim()&&l.length===0||m.isPending,className:"self-end",children:e.jsx(yn,{className:"h-4 w-4"})})]}),e.jsx(cht,{value:l,onChange:o,disabled:m.isPending})]})]})]})]})]})})}return e.jsx(Ss,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(ke,{className:"bg-gradient-to-br from-primary/10 via-primary/5 to-background border-primary/20",children:e.jsx(Oe,{className:"p-6 sm:p-8",children:e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center gap-6",children:[e.jsx("div",{className:"p-4 bg-primary/20 rounded-full",children:e.jsx(v2,{className:"h-8 w-8 text-primary"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h1",{className:"text-2xl font-bold mb-2",children:"Need Help?"}),e.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."}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsx(ONe,{trigger:e.jsxs(H,{size:"lg",className:"gap-2",children:[e.jsx(Ys,{className:"h-5 w-5"}),"Submit a Ticket"]})}),e.jsxs("div",{className:"flex items-center gap-2 px-4 py-2 bg-muted rounded-lg",children:[e.jsx(Yn,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:["Or text us: ",e.jsx("span",{className:"font-semibold text-foreground",children:"1-866-527-8668"})]})]})]})]})]})})}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Your Tickets"}),e.jsx(ONe,{trigger:e.jsxs(H,{variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(Ys,{className:"h-4 w-4"}),"New Ticket"]})})]}),d?e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading tickets..."}):c.length===0?e.jsx(ke,{className:"border-dashed",children:e.jsxs(Oe,{className:"text-center py-12",children:[e.jsx(qc,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-medium mb-2",children:"No tickets yet"}),e.jsx("p",{className:"text-muted-foreground",children:"You haven't submitted any support tickets. Use the button above to get started!"})]})}):e.jsx("div",{className:"space-y-3",children:c.map(x=>{const y=N6[x.status].icon;return e.jsx(ke,{className:"cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>n(x),children:e.jsx(Oe,{className:"p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-medium truncate",children:x.subject}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(Xe,{variant:"outline",className:"text-xs",children:Zze[x.category]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:As(new Date(x.created_at),"MMM d, yyyy")})]})]}),e.jsxs(Xe,{className:N6[x.status].color,children:[e.jsx(y,{className:"h-3 w-3 mr-1"}),N6[x.status].label]})]})})},x.id)})})]})})}function Rls({open:s,onOpenChange:t}){return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-3xl max-h-[90vh] overflow-hidden",children:[e.jsx(Cs,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(Nn,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(Ns,{children:"Schedule Agent Onboarding"}),e.jsx(nn,{children:"Book a one-on-one onboarding session with LevelUp"})]})]})}),s&&e.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 Ols({open:s,onOpenChange:t}){const{brokerageId:r}=Ms(),[n,a]=S.useState(""),[i,l]=S.useState([]),[o,c]=S.useState(!1),{data:d,isLoading:h}=yt({queryKey:["brokerage-agents-for-onboarding",r],queryFn:async()=>{if(!r)return[];const{data:_,error:b}=await V.from("profiles").select("id, name, email").eq("brokerage_id",r).order("name",{ascending:!0});if(b)throw b;return _},enabled:s&&!!r}),m=d==null?void 0:d.filter(_=>_.name.toLowerCase().includes(n.toLowerCase())||_.email.toLowerCase().includes(n.toLowerCase())),p=_=>{l(b=>b.includes(_)?b.filter(j=>j!==_):[...b,_])},x=async()=>{if(i.length===0){he.error("Please select at least one agent");return}c(!0);try{const{data:_,error:b}=await V.functions.invoke("send-onboarding-link",{body:{agentIds:i}});if(b)throw b;he.success(`Onboarding link sent to ${i.length} agent${i.length>1?"s":""}`),l([]),t(!1)}catch(_){console.error("Error sending onboarding link:",_),he.error(_.message||"Failed to send onboarding link")}finally{c(!1)}},y=_=>{_||(l([]),a("")),t(_)};return e.jsx(bs,{open:s,onOpenChange:y,children:e.jsxs(vs,{className:"max-w-md",children:[e.jsx(Cs,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(yn,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(Ns,{children:"Send Onboarding Link"}),e.jsx(nn,{children:"Select agents to receive the onboarding booking link"})]})]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Mn,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Se,{placeholder:"Search agents...",value:n,onChange:_=>a(_.target.value),className:"pl-10"})]}),h?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(is,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):(m==null?void 0:m.length)===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Ar,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),e.jsx("p",{children:"No agents found"})]}):e.jsx(Ci,{className:"h-[300px] border rounded-lg",children:e.jsx("div",{className:"p-2 space-y-1",children:m==null?void 0:m.map(_=>e.jsxs("div",{className:"flex items-center gap-3 p-2 rounded-lg hover:bg-muted cursor-pointer",onClick:()=>p(_.id),children:[e.jsx(ao,{checked:i.includes(_.id),onCheckedChange:()=>p(_.id)}),e.jsx(Un,{className:"h-8 w-8",children:e.jsx(qn,{className:"text-xs",children:_.name.split(" ").map(b=>b[0]).join("").toUpperCase()})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:_.name}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:_.email})]})]},_.id))})}),i.length>0&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:[i.length," agent",i.length>1?"s":""," selected"]})]}),e.jsxs(wn,{children:[e.jsx(H,{variant:"outline",onClick:()=>y(!1),children:"Cancel"}),e.jsx(H,{onClick:x,disabled:i.length===0||o,children:o?e.jsxs(e.Fragment,{children:[e.jsx(is,{className:"h-4 w-4 mr-2 animate-spin"}),"Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(yn,{className:"h-4 w-4 mr-2"}),"Send Link"]})})]})]})})}function Fls(){const[s,t]=S.useState(!1),[r,n]=S.useState(!1);return e.jsxs(e.Fragment,{children:[e.jsxs(ke,{className:"mb-8",children:[e.jsx(Ot,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(Ar,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx(zt,{children:"Agent Onboarding"}),e.jsx(Br,{children:"Schedule onboarding sessions for yourself or your agents"})]})]})}),e.jsx(Oe,{children:e.jsxs("div",{className:"flex flex-wrap gap-4",children:[e.jsxs(H,{onClick:()=>t(!0),className:"flex items-center gap-2",children:[e.jsx(Nn,{className:"h-4 w-4"}),"Schedule Agent Onboarding"]}),e.jsxs(H,{variant:"outline",onClick:()=>n(!0),className:"flex items-center gap-2",children:[e.jsx(yn,{className:"h-4 w-4"}),"Send New Agent Onboarding Link"]})]})})]}),e.jsx(Rls,{open:s,onOpenChange:t}),e.jsx(Ols,{open:r,onOpenChange:n})]})}function Bls({open:s,onOpenChange:t}){return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-3xl max-h-[90vh] overflow-hidden",children:[e.jsx(Cs,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(v_,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(Ns,{children:"Schedule Launch Meeting"}),e.jsx(nn,{children:"Book a private LevelUp information session for your brokerage"})]})]})}),s&&e.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 zls(){const[s,t]=S.useState(!1);return e.jsxs(e.Fragment,{children:[e.jsxs(ke,{className:"mb-8",children:[e.jsx(Ot,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(v_,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx(zt,{children:"Launch or ReLaunch Meeting"}),e.jsx(Br,{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."})]})]})}),e.jsx(Oe,{children:e.jsxs(H,{onClick:()=>t(!0),className:"flex items-center gap-2",children:[e.jsx(v_,{className:"h-4 w-4"}),"Schedule Launch Meeting"]})})]}),e.jsx(Bls,{open:s,onOpenChange:t})]})}function $ls(){const s=Fr(),[t,r]=S.useState(""),[n,a]=S.useState(null),{data:i,isLoading:l}=yt({queryKey:["brokerage-resources-published"],queryFn:async()=>{const{data:_,error:b}=await V.from("brokerage_resources").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(b)throw b;return _}}),{data:o}=yt({queryKey:["brokerage-resource-categories"],queryFn:async()=>{const{data:_,error:b}=await V.from("brokerage_resource_categories").select("*").order("sort_order",{ascending:!0});if(b)throw b;return _}}),{data:c}=yt({queryKey:["brokerage-resource-pdfs-all"],queryFn:async()=>{const{data:_,error:b}=await V.from("brokerage_resource_pdfs").select("resource_id");if(b)throw b;return _}}),{data:d}=yt({queryKey:["brokerage-resource-videos-all"],queryFn:async()=>{const{data:_,error:b}=await V.from("brokerage_resource_videos").select("resource_id");if(b)throw b;return _}}),{data:h}=yt({queryKey:["brokerage-resource-links-all"],queryFn:async()=>{const{data:_,error:b}=await V.from("brokerage_resource_links").select("resource_id");if(b)throw b;return _}}),m=i==null?void 0:i.filter(_=>{var k;const b=_.title.toLowerCase().includes(t.toLowerCase())||((k=_.description)==null?void 0:k.toLowerCase().includes(t.toLowerCase())),j=!n||_.category_id===n;return b&&j}),p=o==null?void 0:o.filter(_=>i==null?void 0:i.some(b=>b.category_id===_.id)),x=_=>{const b=(c==null?void 0:c.filter(T=>T.resource_id===_).length)||0,j=(d==null?void 0:d.filter(T=>T.resource_id===_).length)||0,k=(h==null?void 0:h.filter(T=>T.resource_id===_).length)||0;return{pdfCount:b,videoCount:j,linkCount:k}},y=_=>{s(`/brokerage-resources/${_}`)};return e.jsx(Ss,{title:"Brokerage Resources",description:"Access exclusive resources for brokerage managers",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Fls,{}),e.jsx(zls,{}),e.jsxs("div",{className:"relative max-w-md",children:[e.jsx(Mn,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Se,{placeholder:"Search resources...",value:t,onChange:_=>r(_.target.value),className:"pl-10"})]}),p&&p.length>0&&e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(Xe,{variant:n===null?"default":"outline",className:"cursor-pointer",onClick:()=>a(null),children:"All"}),p.map(_=>e.jsx(Xe,{variant:n===_.id?"default":"outline",className:"cursor-pointer",onClick:()=>a(_.id),children:_.name},_.id))]}),!l&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:[(m==null?void 0:m.length)||0," resource",(m==null?void 0:m.length)!==1?"s":""," available"]}),l?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6",children:[...Array(6)].map((_,b)=>e.jsxs(ke,{children:[e.jsx(Ks,{className:"h-40 w-full"}),e.jsx(Ot,{children:e.jsx(Ks,{className:"h-5 w-3/4"})}),e.jsxs(Oe,{children:[e.jsx(Ks,{className:"h-4 w-full mb-2"}),e.jsx(Ks,{className:"h-4 w-2/3"})]})]},b))}):(m==null?void 0:m.length)===0?e.jsxs(ke,{className:"p-12 text-center",children:[e.jsx(pm,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-medium mb-2",children:"No resources found"}),e.jsx("p",{className:"text-muted-foreground",children:t||n?"Try adjusting your filters":"Check back later for new resources"})]}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6",children:m==null?void 0:m.map(_=>{const{pdfCount:b,videoCount:j,linkCount:k}=x(_.id),T=o==null?void 0:o.find(E=>E.id===_.category_id);return e.jsxs(ke,{className:"overflow-hidden cursor-pointer hover:shadow-lg transition-shadow",onClick:()=>y(_.id),children:[_.preview_image_url?e.jsx("img",{src:_.preview_image_url,alt:_.title,className:"w-full h-40 object-cover"}):e.jsx("div",{className:"w-full h-40 bg-muted flex items-center justify-center",children:e.jsx(pm,{className:"h-16 w-16 text-muted-foreground"})}),e.jsx(Ot,{className:"pb-2",children:e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx(zt,{className:"text-lg line-clamp-1",children:_.title}),T&&e.jsx(Xe,{variant:"secondary",className:"shrink-0 text-xs",children:T.name})]})}),e.jsxs(Oe,{children:[_.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-3",children:_.description}),e.jsxs("div",{className:"flex items-center gap-4 text-sm text-muted-foreground",children:[b>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(kn,{className:"h-4 w-4"}),b]}),j>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(xn,{className:"h-4 w-4"}),j]}),k>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Jo,{className:"h-4 w-4"}),k]})]})]})]},_.id)})})]})})}const Uls=()=>{const{resourceId:s}=Po(),{data:t,isLoading:r}=yt({queryKey:["brokerage-resource-detail",s],queryFn:async()=>{const{data:a,error:i}=await V.from("brokerage_resources").select("*").eq("id",s).eq("is_published",!0).single();if(i)throw i;const{data:l}=await V.from("brokerage_resource_pdfs").select("*").eq("resource_id",s).order("sort_order"),{data:o}=await V.from("brokerage_resource_videos").select("*").eq("resource_id",s).order("sort_order"),{data:c}=await V.from("brokerage_resource_links").select("*").eq("resource_id",s).order("sort_order");return{...a,pdfs:l||[],videos:o||[],links:c||[]}},enabled:!!s}),n=a=>a?a<1024?a+" B":a<1024*1024?(a/1024).toFixed(1)+" KB":(a/(1024*1024)).toFixed(1)+" MB":"";return r?e.jsx(Ss,{title:"Brokerage Resources",children:e.jsx("div",{className:"flex justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):t?e.jsx(Ss,{title:t.title,children:e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsx(H,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(Xn,{to:"/brokerage-resources",children:[e.jsx(za,{className:"h-4 w-4"}),"Back to Resources"]})}),t.preview_image_url&&e.jsx("div",{className:"relative w-full rounded-lg overflow-hidden bg-muted",children:e.jsx("img",{src:t.preview_image_url,alt:t.title,className:"w-full max-h-[400px] object-cover"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:t.title}),t.description&&e.jsx("div",{className:"text-muted-foreground prose prose-sm max-w-none dark:prose-invert",dangerouslySetInnerHTML:{__html:t.description}})]}),t.videos&&t.videos.length>0&&e.jsx(ke,{children:e.jsxs(Oe,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(xn,{className:"h-4 w-4"}),"Videos (",t.videos.length,")"]}),e.jsx("div",{className:"space-y-4",children:t.videos.map(a=>e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium",children:a.title}),e.jsx("div",{className:"relative w-full",style:{paddingTop:"56.25%"},children:e.jsx("iframe",{src:a.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})})]},a.id))})]})}),t.pdfs&&t.pdfs.length>0&&e.jsx(ke,{children:e.jsxs(Oe,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(kn,{className:"h-4 w-4"}),"Documents (",t.pdfs.length,")"]}),e.jsx("div",{className:"grid gap-2",children:t.pdfs.map(a=>e.jsxs("a",{href:a.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:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 rounded-md bg-primary/10",children:e.jsx(kn,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-sm",children:a.name}),a.file_size&&e.jsx("div",{className:"text-xs text-muted-foreground",children:n(a.file_size)})]})]}),e.jsx(hi,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors"})]},a.id))})]})}),t.links&&t.links.length>0&&e.jsx(ke,{children:e.jsxs(Oe,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(gn,{className:"h-4 w-4"}),"Canva Templates (",t.links.length,")"]}),e.jsx("div",{className:"grid gap-2",children:t.links.map(a=>e.jsxs("a",{href:a.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:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 rounded-md bg-primary/10",children:e.jsx(gn,{className:"h-4 w-4 text-primary"})}),e.jsx("div",{className:"font-medium text-sm",children:a.title})]}),e.jsx(gn,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors"})]},a.id))})]})})]})}):e.jsx(Ss,{title:"Brokerage Resources",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(pm,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold",children:"Resource not found"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"This resource may have been removed or is not available."}),e.jsx(H,{asChild:!0,className:"mt-4",children:e.jsx(Xn,{to:"/brokerage-resources",children:"Back to Resources"})})]})})};function qls(){const{onlineUsers:s,totalOnline:t}=yet();return e.jsxs(ke,{children:[e.jsx(Ot,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(zt,{className:"text-base flex items-center gap-2",children:[e.jsx(Ar,{className:"h-4 w-4"}),"Online Now"]}),e.jsxs(Xe,{variant:"secondary",className:"bg-green-100 text-green-700",children:[e.jsx(Gu,{className:"h-2 w-2 fill-green-500 text-green-500 mr-1"}),t," online"]})]})}),e.jsx(Oe,{children:s.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No other users online right now"}):e.jsx(Ci,{className:"h-[300px] pr-4",children:e.jsx("div",{className:"space-y-3",children:s.map(r=>{var n;return e.jsxs("div",{className:"flex items-center gap-3 p-2 rounded-lg hover:bg-muted/50 transition-colors",children:[e.jsxs("div",{className:"relative",children:[e.jsxs(Un,{className:"h-9 w-9",children:[e.jsx(Ka,{src:r.avatarUrl,alt:r.name}),e.jsx(qn,{className:"text-xs",children:(n=r.name)==null?void 0:n.split(" ").map(a=>a[0]).join("").slice(0,2).toUpperCase()})]}),e.jsx("span",{className:"absolute bottom-0 right-0 h-2.5 w-2.5 rounded-full bg-green-500 ring-2 ring-background"})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:r.name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Online ",Hl(new Date(r.onlineSince),{addSuffix:!1})]})]})]},r.id)})})})})]})}const Xze={users:{label:"Users & Access",sections:[{title:"Members",description:"Manage users, roles, and brokerage assignments",icon:Ar,path:"/admin/members",color:"bg-blue-500/10 text-blue-600"},{title:"Invite Codes",description:"Create and manage signup invite codes",icon:RF,path:"/admin/invite-codes",color:"bg-amber-500/10 text-amber-600"},{title:"Subscriptions",description:"Track and manage user subscriptions",icon:u0,path:"/admin/subscriptions",color:"bg-gradient-to-br from-green-500/20 to-green-500/10 text-green-600"},{title:"Credit Management",description:"View and manage ReelFlow, Postcard, Letter & Check credits for all agents",icon:aF,path:"/admin/credits",color:"bg-gradient-to-br from-emerald-500/20 to-teal-500/10 text-emerald-600"},{title:"Subscription Discounts",description:"Create and manage coupon codes",icon:xm,path:"/admin/discounts",color:"bg-red-500/10 text-red-600"},{title:"Referral Program",description:"Track brokerage referrals and discounts",icon:cd,path:"/admin/referrals",color:"bg-teal-500/10 text-teal-600"},{title:"Teams",description:"Manage agent teams across all brokerages",icon:Ar,path:"/admin/members?tab=teams",color:"bg-violet-500/10 text-violet-600"},{title:"Prospector",description:"Send free trial invites and track conversions",icon:Wu,path:"/admin/prospector",color:"bg-gradient-to-br from-orange-500/20 to-amber-500/10 text-orange-600"},{title:"Recruiting",description:"Manage agent recruit pipeline and outreach",icon:Vl,path:"/admin/recruiting",color:"bg-gradient-to-br from-emerald-500/20 to-green-500/10 text-emerald-600"},{title:"Coaching",description:"Promote coaches and manage agent coaching assignments",icon:To,path:"/admin/coaching",color:"bg-gradient-to-br from-teal-500/20 to-cyan-500/10 text-teal-600"}]},content:{label:"Content",sections:[{title:"Manage Templates",description:"Upload and organize Canva templates",icon:pl,path:"/admin/templates",color:"bg-pink-500/10 text-pink-600"},{title:"Manage Academy",description:"Upload videos and training content",icon:Vu,path:"/admin/academy",color:"bg-indigo-500/10 text-indigo-600"},{title:"Manage Toolbox",description:"Create and manage resource kits",icon:N1,path:"/admin/toolbox",color:"bg-orange-500/10 text-orange-600"},{title:"Social Swag",description:"Manage social media content and links",icon:Lr,path:"/admin/social-swag",color:"bg-fuchsia-500/10 text-fuchsia-600"},{title:"Social Swag 2.0",description:"New monthly social media images",icon:Lr,path:"/admin/social-swag-2",color:"bg-cyan-500/10 text-cyan-600"},{title:"Newsletters",description:"Manage monthly newsletter templates",icon:x_,path:"/admin/newsletters",color:"bg-violet-500/10 text-violet-600"},{title:"Manage Events",description:"Create and publish events with Zoom integration",icon:xu,path:"/admin/events",color:"bg-green-500/10 text-green-600"},{title:"Additional Services",description:"Manage additional service offerings",icon:pm,path:"/admin/additional-services",color:"bg-lime-500/10 text-lime-600"},{title:"Brokerage Resources",description:"Manage resources for brokerage managers",icon:pm,path:"/admin/brokerage-resources",color:"bg-slate-500/10 text-slate-600"},{title:"Agent Email Templates",description:"Manage curated email templates for agents",icon:er,path:"/admin/agent-email-templates",color:"bg-rose-500/10 text-rose-600"},{title:"Mass Email Templates",description:"Create and manage shared campaign templates",icon:ph,path:"/admin/email-campaigns/templates",color:"bg-teal-500/10 text-teal-600"}]},platform:{label:"Platform",sections:[{title:"Dashboard Management",description:"Configure banners and dashboard modules",icon:wE,path:"/admin/dashboard-management",color:"bg-teal-500/10 text-teal-600"},{title:"Manage Apps",description:"Configure app tiles and access requirements",icon:by,path:"/admin/apps",color:"bg-purple-500/10 text-purple-600"},{title:"Email Templates",description:"Customize system email templates",icon:er,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:ph,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:PI,path:"/admin/onboarding-checklist",color:"bg-emerald-500/10 text-emerald-600"},{title:"Marketplace",description:"Manage store categories, products, and orders",icon:b_,path:"/admin/marketplace",color:"bg-gradient-to-br from-orange-500/20 to-amber-500/10 text-orange-600"},{title:"Reward Store",description:"Manage reward items agents can redeem with points",icon:Di,path:"/admin/reward-store",color:"bg-purple-500/10 text-purple-600"},{title:"Agent Points",description:"View agent points, leaderboard, and award bonus points",icon:To,path:"/admin/agent-points",color:"bg-amber-500/10 text-amber-600"},{title:"Integrations",description:"Connect Canva, Facebook & Instagram for platform-level features",icon:ql,path:"/admin/integrations",color:"bg-blue-500/10 text-blue-600"},{title:"Agent Cards",description:"Manage digital business cards for agents",icon:Ar,path:"/admin/agent-cards",color:"bg-gradient-to-br from-violet-500/20 to-purple-500/10 text-violet-600"},{title:"Notification Settings",description:"Test and manage push notifications",icon:ph,path:"/admin/notification-settings",color:"bg-rose-500/10 text-rose-600"}]},community:{label:"Community & Support",sections:[{title:"Community Management",description:"Manage categories and private groups",icon:Gi,path:"/admin/community",color:"bg-cyan-500/10 text-cyan-600"},{title:"Support Tickets",description:"View and respond to agent support requests",icon:zI,path:"/admin/support-tickets",color:"bg-rose-500/10 text-rose-600"},{title:"Wishlist",description:"Review and manage community feature requests",icon:q2,path:"/admin/wishlist",color:"bg-yellow-500/10 text-yellow-600"},{title:"Membership Reviews",description:"View member feedback and ratings",icon:ya,path:"/admin/membership-reviews",color:"bg-amber-500/10 text-amber-600"},{title:"Weekly Digest",description:"Configure automated weekly email digests",icon:er,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:Bo,path:"/admin/analytics",color:"bg-emerald-500/10 text-emerald-600"},{title:"Brokerage Content Activity",description:"See which brokerages are creating custom content for agents",icon:tf,path:"/admin/brokerage-content-activity",color:"bg-sky-500/10 text-sky-600"}]},lms:{label:"LevelUp U",sections:[{title:"Manage Courses",description:"Create and manage LMS training courses, modules, and access",icon:Vu,path:"/admin/lms",color:"bg-gradient-to-br from-primary/20 to-primary/10 text-primary"}]},"agent-os":{label:"Agent OS",sections:[{title:"Agent OS Control Center",description:"Manage InnerCircle feature: relationship types, action types, scripts, plans & feature flags",icon:Bi,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:Fn,path:"/admin/listing-exchange",color:"bg-gradient-to-br from-blue-500/20 to-sky-500/10 text-blue-600"},{title:"Presentation Analytics",description:"Track agent presentation usage, views, and leads",icon:_1,path:"/admin/presentation-analytics",color:"bg-gradient-to-br from-violet-500/20 to-indigo-500/10 text-violet-600"},{title:"Guest Book Analytics",description:"Track open house sign-in usage, visitors, and lead generation",icon:tf,path:"/admin/guest-book-analytics",color:"bg-gradient-to-br from-emerald-500/20 to-teal-500/10 text-emerald-600"}]},beta:{label:"🧪 Beta Lab",sections:[{title:"Social Post Generator",description:"Auto-generate branded social media posts from MLS listing data",icon:wl,path:"/admin/beta/social-post-generator",color:"bg-gradient-to-br from-fuchsia-500/20 to-pink-500/10 text-fuchsia-600"},{title:"Postcard Direct Mail",description:"Upload monthly postcard designs and manage agent direct mail via Postalytics",icon:er,path:"/admin/beta/postcard-manager",color:"bg-gradient-to-br from-orange-500/20 to-amber-500/10 text-orange-600"},{title:"ReelFlow",description:"Turn property photos into cinematic video reels for social media",icon:Bk,path:"/admin/beta/homereel",color:"bg-gradient-to-br from-violet-500/20 to-indigo-500/10 text-violet-600"}]},"lead-sites":{label:"Lead Sites",sections:[{title:"All Sites",description:"Overview of all agent websites with status and quick actions",icon:ld,path:"/admin/lead-sites",color:"bg-gradient-to-br from-sky-500/20 to-blue-500/10 text-sky-600"},{title:"MLS Feeds",description:"Manage MLS data feed connections, API keys, and coverage areas",icon:iF,path:"/admin/mls-feeds",color:"bg-gradient-to-br from-emerald-500/20 to-green-500/10 text-emerald-600"},{title:"Lead Analytics",description:"Cross-site lead capture stats, conversions, and top-performing sites",icon:al,path:"/admin/lead-site-analytics",color:"bg-gradient-to-br from-amber-500/20 to-orange-500/10 text-amber-600"},{title:"Website Interests",description:"Track interest form submissions from TheLocalMove.com",icon:kn,path:"/admin/website-interests",color:"bg-gradient-to-br from-rose-500/20 to-pink-500/10 text-rose-600"},{title:"Website Order Tracker",description:"Full setup requests with all build details from /get-started",icon:kn,path:"/admin/website-orders",color:"bg-gradient-to-br from-emerald-500/20 to-teal-500/10 text-emerald-600"},{title:"MLS Fee Tracker",description:"Track MLS providers, setup fees, and monthly costs",icon:oc,path:"/admin/mls-fee-tracker",color:"bg-gradient-to-br from-teal-500/20 to-cyan-500/10 text-teal-600"}]}};function Qze(){const s=Fr();return console.log("[AdminDashboard] render"),e.jsx(Ss,{title:"Admin Dashboard",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col lg:flex-row gap-6",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Admin Dashboard"}),e.jsx("p",{className:"text-muted-foreground",children:"Manage all aspects of your platform"})]}),e.jsx("div",{className:"w-full lg:w-80",children:e.jsx(qls,{})})]}),e.jsxs(ta,{defaultValue:"users",className:"w-full",children:[e.jsx(Qn,{className:"w-full justify-start flex-wrap h-auto gap-1 bg-muted/50 p-1 overflow-x-auto",children:Object.entries(Xze).map(([t,r])=>e.jsx(ts,{value:t,className:"data-[state=active]:bg-background",children:r.label},t))}),Object.entries(Xze).map(([t,r])=>e.jsx(cs,{value:t,className:"mt-6",children:e.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=>e.jsxs(ke,{className:"cursor-pointer hover:shadow-md transition-all hover:border-primary/50 group",onClick:()=>s(n.path),children:[e.jsxs(Ot,{className:"pb-3",children:[e.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:e.jsx(n.icon,{className:"h-5 w-5"})}),e.jsx(zt,{className:"text-base",children:n.title})]}),e.jsx(Oe,{className:"pt-0",children:e.jsx(Br,{className:"text-sm",children:n.description})})]},n.path))})},t))]})]})})}const la=S.forwardRef(({className:s,...t},r)=>e.jsx("div",{className:"relative w-full overflow-auto",children:e.jsx("table",{ref:r,className:Ft("w-full caption-bottom text-sm",s),...t})}));la.displayName="Table";const ca=S.forwardRef(({className:s,...t},r)=>e.jsx("thead",{ref:r,className:Ft("[&_tr]:border-b",s),...t}));ca.displayName="TableHeader";const da=S.forwardRef(({className:s,...t},r)=>e.jsx("tbody",{ref:r,className:Ft("[&_tr:last-child]:border-0",s),...t}));da.displayName="TableBody";const Vls=S.forwardRef(({className:s,...t},r)=>e.jsx("tfoot",{ref:r,className:Ft("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",s),...t}));Vls.displayName="TableFooter";const Vs=S.forwardRef(({className:s,...t},r)=>e.jsx("tr",{ref:r,className:Ft("border-b transition-colors data-[state=selected]:bg-muted hover:bg-muted/50",s),...t}));Vs.displayName="TableRow";const At=S.forwardRef(({className:s,...t},r)=>e.jsx("th",{ref:r,className:Ft("h-12 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0",s),...t}));At.displayName="TableHead";const gt=S.forwardRef(({className:s,...t},r)=>e.jsx("td",{ref:r,className:Ft("p-4 align-middle [&:has([role=checkbox])]:pr-0",s),...t}));gt.displayName="TableCell";const Hls=S.forwardRef(({className:s,...t},r)=>e.jsx("caption",{ref:r,className:Ft("mt-4 text-sm text-muted-foreground",s),...t}));Hls.displayName="TableCaption";const Gls=()=>{const{isAdmin:s}=Ms(),t=Fr(),[r,n]=S.useState([]),[a,i]=S.useState(!0),[l,o]=S.useState(!1),[c,d]=S.useState(null);S.useEffect(()=>{if(!s){t("/dashboard");return}h()},[s]);const h=async()=>{try{const{data:_,error:b}=await V.from("app_tiles").select("*").order("name");if(b)throw b;n(_||[])}catch(_){console.error("Error loading apps:",_),he.error("Failed to load apps")}finally{i(!1)}},m=async _=>{_.preventDefault();const b=new FormData(_.currentTarget),j={name:b.get("name"),description:b.get("description"),icon:b.get("icon"),app_id:b.get("app_id"),target_url:b.get("target_url"),required_tags:b.get("required_tags").split(",").map(k=>k.trim()).filter(Boolean)};try{if(c){const{error:k}=await V.from("app_tiles").update(j).eq("id",c.id);if(k)throw k;he.success("App updated successfully")}else{const{error:k}=await V.from("app_tiles").insert([j]);if(k)throw k;he.success("App created successfully")}o(!1),d(null),h()}catch(k){console.error("Error saving app:",k),he.error("Failed to save app")}},p=async _=>{if(confirm("Are you sure you want to delete this app?"))try{const{error:b}=await V.from("app_tiles").delete().eq("id",_);if(b)throw b;he.success("App deleted successfully"),h()}catch(b){console.error("Error deleting app:",b),he.error("Failed to delete app")}},x=_=>{d(_),o(!0)},y=()=>{d(null),o(!0)};return a?e.jsx("div",{className:"flex items-center justify-center min-h-screen",children:"Loading..."}):e.jsxs("div",{className:"min-h-screen bg-background",children:[e.jsx("header",{className:"border-b bg-card",children:e.jsx("div",{className:"container mx-auto px-4 py-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs(H,{variant:"ghost",size:"sm",onClick:()=>t("/dashboard"),children:[e.jsx(za,{className:"h-4 w-4 mr-2"}),"Back"]}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Manage Apps"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Create and configure application tiles"})]})]}),e.jsxs(bs,{open:l,onOpenChange:o,children:[e.jsx(Qi,{asChild:!0,children:e.jsxs(H,{onClick:y,children:[e.jsx(Ys,{className:"mr-2 h-4 w-4"}),"Add App"]})}),e.jsxs(vs,{className:"max-w-2xl",children:[e.jsxs(Cs,{children:[e.jsx(Ns,{children:c?"Edit App":"Create New App"}),e.jsx(nn,{children:"Configure the application tile settings"})]}),e.jsxs("form",{onSubmit:m,className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"name",children:"App Name"}),e.jsx(Se,{id:"name",name:"name",defaultValue:c==null?void 0:c.name,required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"app_id",children:"App ID"}),e.jsx(Se,{id:"app_id",name:"app_id",defaultValue:c==null?void 0:c.app_id,placeholder:"agent_connect",required:!0})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"description",children:"Description"}),e.jsx(vr,{id:"description",name:"description",defaultValue:c==null?void 0:c.description})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"icon",children:"Icon (emoji)"}),e.jsx(Se,{id:"icon",name:"icon",defaultValue:c==null?void 0:c.icon,placeholder:"🚀",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"target_url",children:"Target URL"}),e.jsx(Se,{id:"target_url",name:"target_url",type:"url",defaultValue:c==null?void 0:c.target_url,required:!0})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"required_tags",children:"Required Tags (comma-separated)"}),e.jsx(Se,{id:"required_tags",name:"required_tags",defaultValue:c==null?void 0:c.required_tags.join(", "),placeholder:"levelup-member, agent-connect"})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(H,{type:"button",variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsx(H,{type:"submit",children:c?"Update":"Create"})]})]})]})]})]})})}),e.jsx("div",{className:"container mx-auto px-4 py-8",children:e.jsxs(ke,{children:[e.jsxs(Ot,{children:[e.jsx(zt,{children:"Application Tiles"}),e.jsx(Br,{children:"Manage the apps that appear on the member dashboard"})]}),e.jsx(Oe,{children:r.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx("p",{className:"text-muted-foreground mb-4",children:"No apps configured yet"}),e.jsxs(H,{onClick:y,children:[e.jsx(Ys,{className:"mr-2 h-4 w-4"}),"Create First App"]})]}):e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Vs,{children:[e.jsx(At,{children:"Icon"}),e.jsx(At,{children:"Name"}),e.jsx(At,{children:"App ID"}),e.jsx(At,{children:"Target URL"}),e.jsx(At,{children:"Tags"}),e.jsx(At,{className:"text-right",children:"Actions"})]})}),e.jsx(da,{children:r.map(_=>e.jsxs(Vs,{children:[e.jsx(gt,{className:"text-2xl",children:_.icon}),e.jsx(gt,{className:"font-medium",children:_.name}),e.jsx(gt,{className:"font-mono text-sm",children:_.app_id}),e.jsx(gt,{className:"text-sm text-muted-foreground max-w-xs truncate",children:_.target_url}),e.jsx(gt,{children:e.jsx("div",{className:"flex flex-wrap gap-1",children:_.required_tags.map(b=>e.jsx("span",{className:"text-xs bg-secondary text-secondary-foreground px-2 py-1 rounded",children:b},b))})}),e.jsx(gt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(H,{size:"sm",variant:"ghost",onClick:()=>x(_),children:e.jsx(ni,{className:"h-4 w-4"})}),e.jsx(H,{size:"sm",variant:"ghost",onClick:()=>p(_.id),children:e.jsx(Dr,{className:"h-4 w-4"})})]})})]},_.id))})]})})]})})]})};function km({title:s,description:t,children:r}){return e.jsxs("div",{className:"space-y-4",children:[e.jsx(Xn,{to:"/admin",children:e.jsxs(H,{variant:"ghost",size:"sm",className:"gap-2 text-muted-foreground hover:text-foreground",children:[e.jsx(za,{className:"h-4 w-4"}),"Back to Admin Dashboard"]})}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:s}),t&&e.jsx("p",{className:"text-muted-foreground",children:t})]}),r]})]})}const Jze=({expiresAt:s,className:t})=>{const r=new Date().getTime(),n=new Date(s).getTime(),a=Math.ceil((n-r)/(1e3*60*60*24));return a<=0?e.jsxs(Xe,{variant:"destructive",className:Ft("gap-1",t),children:[e.jsx(uu,{className:"h-3 w-3"}),"Trial Expired"]}):a<=1?e.jsxs(Xe,{variant:"destructive",className:Ft("gap-1",t),children:[e.jsx(Pn,{className:"h-3 w-3"}),"Trial: <1 day left"]}):a<=3?e.jsxs(Xe,{className:Ft("gap-1 bg-amber-500 hover:bg-amber-600",t),children:[e.jsx(Pn,{className:"h-3 w-3"}),"Trial: ",a," days left"]}):e.jsxs(Xe,{variant:"secondary",className:Ft("gap-1",t),children:[e.jsx(Pn,{className:"h-3 w-3"}),"Trial: ",a," days left"]})},uht=({open:s,onOpenChange:t,brokerages:r,fixedBrokerageId:n,onSuccess:a})=>{const{toast:i}=li(),l=S.useRef(null),[o,c]=S.useState([]),[d,h]=S.useState(""),[m,p]=S.useState(!1),[x,y]=S.useState("upload"),[_,b]=S.useState(null),j=()=>{c([]),h(""),y("upload"),b(null),l.current&&(l.current.value="")},k=()=>{j(),t(!1)},T=z=>{const O=z.split(` `).map(K=>K.trim()).filter(K=>K);if(O.length===0)return[];const $=O[0].toLowerCase(),Z=$.includes("first")||$.includes("last")||$.includes("email")||$.includes("name")||$.includes("phone")||$.includes("sms")||$.includes("consent")?O.slice(1):O,J=[];for(const K of Z){const ie=(K.includes(" ")?K.split(" "):K.split(",")).map(ce=>ce.trim().replace(/^["']|["']$/g,""));if(ie.length>=2){let ce="",ne="",le="",be="",fe;if(ie.length===2){const We=ie[0].split(" ");ce=We[0]||"",ne=We.slice(1).join(" ")||"",le=ie[1]}else if(ie.length===3)ce=ie[0],ne=ie[1],le=ie[2];else if(ie.length===4)ce=ie[0],ne=ie[1],le=ie[2],be=ie[3];else if(ie.length>=5){ce=ie[0],ne=ie[1],le=ie[2],be=ie[3];const We=ie[4].toLowerCase();fe=We==="true"||We==="yes"||We==="1"||We==="y"}const ve=/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(le);J.push({firstName:ce.trim(),lastName:ne.trim(),email:le.trim().toLowerCase(),phone:be.trim()||void 0,smsConsent:fe,isValid:ve&&ce.trim().length>0,error:ve?ce.trim()?void 0:"Missing name":"Invalid email"})}}return J},E=z=>{var ee;const O=(ee=z.target.files)==null?void 0:ee[0];if(!O)return;const $=new FileReader;$.onload=Z=>{var re;const J=(re=Z.target)==null?void 0:re.result,K=T(J);if(K.length===0){i({title:"No data found",description:"The CSV file appears to be empty or in an unsupported format.",variant:"destructive"});return}c(K),y("preview")},$.readAsText(O)},A=async()=>{const z=o.filter($=>$.isValid);if(z.length===0){i({title:"No valid users",description:"There are no valid users to import.",variant:"destructive"});return}const O=n||d||null;p(!0);try{const{data:{session:$}}=await V.auth.getSession(),ee=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/bulk-create-users",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${$==null?void 0:$.access_token}`},body:JSON.stringify({users:z.map(J=>({firstName:J.firstName,lastName:J.lastName,email:J.email,phone:J.phone,smsConsent:J.smsConsent})),brokerageId:O})}),Z=await ee.json();if(!ee.ok)throw new Error(Z.error||"Failed to import users");b(Z),y("result"),Z.created>0&&a(),i({title:"Import Complete",description:`${Z.created} user(s) created successfully.${Z.failed>0?` ${Z.failed} failed.`:""}`})}catch($){console.error("Import error:",$),i({title:"Import Failed",description:$.message||"Failed to import users",variant:"destructive"})}finally{p(!1)}},D=o.filter(z=>z.isValid).length,R=o.filter(z=>!z.isValid).length;return e.jsx(bs,{open:s,onOpenChange:k,children:e.jsxs(vs,{className:"max-w-2xl max-h-[85vh] overflow-hidden flex flex-col",children:[e.jsxs(Cs,{children:[e.jsxs(Ns,{className:"flex items-center gap-2",children:[e.jsx($2,{className:"h-5 w-5"}),"Import Agents from CSV"]}),e.jsx(nn,{children:"Upload a CSV file with agent information. Each row should contain First Name, Last Name, and Email."})]}),x==="upload"&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-8 text-center",children:[e.jsx("input",{type:"file",accept:".csv,.txt",ref:l,onChange:E,className:"hidden"}),e.jsx(Ea,{className:"h-10 w-10 mx-auto text-muted-foreground mb-4"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Click to upload or drag and drop a CSV file"}),e.jsx(H,{onClick:()=>{var z;return(z=l.current)==null?void 0:z.click()},children:"Select CSV File"})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-4 text-sm",children:[e.jsx("p",{className:"font-medium mb-2",children:"Expected CSV Format:"}),e.jsxs("code",{className:"text-xs block bg-background p-2 rounded",children:["First Name, Last Name, Email, Phone, SMS Consent",e.jsx("br",{}),"John, Doe, john@example.com, 555-123-4567, yes",e.jsx("br",{}),"Jane, Smith, jane@example.com, 555-987-6543, true"]}),e.jsx("p",{className:"text-muted-foreground mt-2 text-xs",children:"Phone and SMS Consent columns are optional. SMS Consent accepts: yes/no, true/false, 1/0, y/n."})]})]}),x==="preview"&&e.jsxs("div",{className:"flex-1 overflow-hidden flex flex-col space-y-4",children:[!n&&r&&r.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Assign to Brokerage (optional)"}),e.jsxs(Bs,{value:d||"none",onValueChange:z=>h(z==="none"?"":z),children:[e.jsx(Os,{children:e.jsx(Us,{placeholder:"Select a brokerage..."})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"none",children:"No brokerage"}),r.map(z=>e.jsx(pt,{value:z.id,children:z.name},z.id))]})]})]}),e.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ea,{className:"h-4 w-4 text-green-500"}),e.jsxs("span",{children:[D," valid"]})]}),R>0&&e.jsxs("div",{className:"flex items-center gap-2 text-destructive",children:[e.jsx(wo,{className:"h-4 w-4"}),e.jsxs("span",{children:[R," invalid"]})]})]}),e.jsxs("div",{className:"flex-1 overflow-auto border rounded-lg",children:[e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Vs,{className:"bg-muted/30",children:[e.jsx(At,{children:"First Name"}),e.jsx(At,{children:"Last Name"}),e.jsx(At,{children:"Email"}),e.jsx(At,{children:"Phone"}),e.jsx(At,{children:"SMS"}),e.jsx(At,{children:"Status"})]})}),e.jsx(da,{children:o.slice(0,100).map((z,O)=>e.jsxs(Vs,{children:[e.jsx(gt,{children:z.firstName}),e.jsx(gt,{children:z.lastName}),e.jsx(gt,{children:z.email}),e.jsx(gt,{className:"text-muted-foreground",children:z.phone||"-"}),e.jsx(gt,{className:"text-muted-foreground",children:z.smsConsent===!0?"✓":z.smsConsent===!1?"✗":"-"}),e.jsx(gt,{children:z.isValid?e.jsx(Xe,{variant:"default",className:"bg-green-500/10 text-green-600",children:"Valid"}):e.jsx(Xe,{variant:"destructive",children:z.error||"Invalid"})})]},O))})]}),o.length>100&&e.jsxs("p",{className:"text-sm text-muted-foreground text-center py-2",children:["Showing first 100 of ",o.length," users"]})]})]}),x==="result"&&_&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"text-center",children:[e.jsx(ea,{className:"h-12 w-12 mx-auto text-green-500 mb-4"}),e.jsx("h3",{className:"text-lg font-semibold",children:"Import Complete"}),e.jsxs("p",{className:"text-muted-foreground mt-2",children:[_.created," agent(s) created and invited"]}),_.failed>0&&e.jsxs("p",{className:"text-destructive mt-1",children:[_.failed," failed to create"]})]}),_.errors.length>0&&e.jsxs("div",{className:"bg-destructive/10 border border-destructive/20 rounded-lg p-4 max-h-40 overflow-auto",children:[e.jsx("p",{className:"font-medium text-destructive text-sm mb-2",children:"Errors:"}),e.jsxs("ul",{className:"text-sm text-muted-foreground space-y-1",children:[_.errors.slice(0,10).map((z,O)=>e.jsxs("li",{children:["• ",z]},O)),_.errors.length>10&&e.jsxs("li",{children:["...and ",_.errors.length-10," more"]})]})]})]}),e.jsxs(wn,{children:[x==="upload"&&e.jsx(H,{variant:"outline",onClick:k,children:"Cancel"}),x==="preview"&&e.jsxs(e.Fragment,{children:[e.jsx(H,{variant:"outline",onClick:j,children:"Back"}),e.jsx(H,{onClick:A,disabled:m||D===0,children:m?e.jsxs(e.Fragment,{children:[e.jsx(is,{className:"mr-2 h-4 w-4 animate-spin"}),"Importing..."]}):`Import ${D} Agent${D!==1?"s":""}`})]}),x==="result"&&e.jsx(H,{onClick:k,children:"Done"})]})]})})};function pc({sortKey:s,currentSortKey:t,currentDirection:r,onSort:n,children:a,className:i,...l}){const o=t===s;return e.jsx(At,{className:Ft("cursor-pointer select-none",i),...l,children:e.jsxs("button",{type:"button",className:"flex items-center gap-1 font-semibold hover:text-foreground transition-colors w-full text-left",onClick:()=>n(s),children:[a,o?r==="asc"?e.jsx(Hu,{className:"h-3.5 w-3.5 shrink-0"}):e.jsx(fm,{className:"h-3.5 w-3.5 shrink-0"}):e.jsx(qu,{className:"h-3.5 w-3.5 shrink-0 opacity-40"})]})})}function yz(s=null,t=null){const[r,n]=S.useState(s),[a,i]=S.useState(t),l=S.useCallback(c=>{r===c?a==="asc"?i("desc"):a==="desc"?(n(null),i(null)):i("asc"):(n(c),i("asc"))},[r,a]),o=S.useCallback((c,d)=>{if(!r||!a||!d[r])return c;const h=d[r];return[...c].sort((m,p)=>{const x=h(m),y=h(p);if(x==null&&y==null)return 0;if(x==null)return 1;if(y==null)return-1;let _;return typeof x=="string"&&typeof y=="string"?_=x.localeCompare(y,void 0,{sensitivity:"base"}):_=x-y,a==="asc"?_:-_})},[r,a]);return{sortKey:r,sortDirection:a,handleSort:l,sortData:o}}const Wls=[{type:"custom",title:"Great job!",message:"Keep up the amazing work!",icon:ya},{type:"custom",title:"You're on fire!",message:"Your dedication is inspiring!",icon:To},{type:"custom",title:"Congratulations!",message:"You earned this celebration!",icon:gh}];function hht({open:s,onOpenChange:t,userId:r,userName:n}){const[a,i]=S.useState("custom"),[l,o]=S.useState(""),[c,d]=S.useState(""),h=KIt(),m=x=>{i(x.type),o(x.title),d(x.message)},p=async x=>{if(x.preventDefault(),!l.trim()){En({title:"Title required",description:"Please enter a celebration title",variant:"destructive"});return}try{await h.mutateAsync({user_id:r,celebration_type:a,title:l.trim(),message:c.trim()||void 0}),En({title:"Celebration sent! 🎉",description:`${n} will see confetti on their next visit!`}),t(!1),o(""),d(""),i("custom")}catch{En({title:"Error",description:"Failed to send celebration",variant:"destructive"})}};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"sm:max-w-md",children:[e.jsxs(Cs,{children:[e.jsxs(Ns,{className:"flex items-center gap-2",children:[e.jsx(gh,{className:"h-5 w-5 text-primary"}),"Send Celebration to ",n]}),e.jsx(nn,{children:"They'll see confetti and this message next time they log in!"})]}),e.jsxs("div",{className:"mb-4",children:[e.jsx(ue,{className:"text-sm text-muted-foreground mb-2 block",children:"Quick presets:"}),e.jsx("div",{className:"flex gap-2 flex-wrap",children:Wls.map((x,y)=>e.jsxs(H,{variant:"outline",size:"sm",onClick:()=>m(x),className:"text-xs",children:[e.jsx(x.icon,{className:"h-3 w-3 mr-1"}),x.title]},y))})]}),e.jsxs("form",{onSubmit:p,className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"type",children:"Celebration Type"}),e.jsxs(Bs,{value:a,onValueChange:x=>i(x),children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"custom",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ya,{className:"h-4 w-4"})," Custom"]})}),e.jsx(pt,{value:"points_earned",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(To,{className:"h-4 w-4"})," Points Earned"]})}),e.jsx(pt,{value:"listing_created",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Fn,{className:"h-4 w-4"})," Listing Created"]})}),e.jsx(pt,{value:"deal_closed",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(oc,{className:"h-4 w-4"})," Deal Closed"]})})]})]})]}),e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"title",children:"Title *"}),e.jsx(Se,{id:"title",value:l,onChange:x=>o(x.target.value),placeholder:"e.g., Congratulations!",maxLength:100})]}),e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"message",children:"Message (optional)"}),e.jsx(vr,{id:"message",value:c,onChange:x=>d(x.target.value),placeholder:"Add a personal message...",rows:3,maxLength:500})]}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(H,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(H,{type:"submit",disabled:h.isPending,children:[e.jsx(gh,{className:"h-4 w-4 mr-2"}),h.isPending?"Sending...":"Send Celebration"]})]})]})]})})}const T_e={points_earned:{label:"Points Earned",icon:To,color:"bg-yellow-500"},listing_created:{label:"Listing Created",icon:Fn,color:"bg-blue-500"},deal_closed:{label:"Deal Closed",icon:oc,color:"bg-green-500"},custom:{label:"Custom",icon:Lr,color:"bg-purple-500"}};function Kls(){const[s,t]=S.useState(""),[r,n]=S.useState("all"),[a,i]=S.useState("all"),{data:l=[],isLoading:o}=yt({queryKey:["admin-celebrations"],queryFn:async()=>{const{data:h,error:m}=await V.from("celebration_queue").select("*").order("created_at",{ascending:!1}).limit(500);if(m)throw m;const p=[...new Set([...h.map(_=>_.user_id),...h.map(_=>_.created_by).filter(Boolean)])],{data:x}=await V.from("profiles").select("id, name, email").in("id",p),y=new Map((x==null?void 0:x.map(_=>[_.id,_]))||[]);return h.map(_=>{var b,j,k;return{..._,user_name:((b=y.get(_.user_id))==null?void 0:b.name)||"Unknown",user_email:((j=y.get(_.user_id))==null?void 0:j.email)||"",creator_name:_.created_by?((k=y.get(_.created_by))==null?void 0:k.name)||"System":"Auto-triggered"}})}}),c=l.filter(h=>{var y,_;const m=((y=h.user_name)==null?void 0:y.toLowerCase().includes(s.toLowerCase()))||((_=h.user_email)==null?void 0:_.toLowerCase().includes(s.toLowerCase()))||h.title.toLowerCase().includes(s.toLowerCase()),p=r==="all"||h.celebration_type===r,x=a==="all"||a==="seen"&&h.seen_at||a==="unseen"&&!h.seen_at;return m&&p&&x}),d={total:l.length,seen:l.filter(h=>h.seen_at).length,unseen:l.filter(h=>!h.seen_at).length,byType:Object.keys(T_e).reduce((h,m)=>(h[m]=l.filter(p=>p.celebration_type===m).length,h),{})};return o?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(is,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-4",children:[e.jsxs(ke,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsx(zt,{className:"text-sm font-medium",children:"Total Celebrations"})}),e.jsx(Oe,{children:e.jsx("div",{className:"text-2xl font-bold",children:d.total})})]}),e.jsxs(ke,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsx(zt,{className:"text-sm font-medium text-green-600",children:"Seen"})}),e.jsx(Oe,{children:e.jsx("div",{className:"text-2xl font-bold text-green-600",children:d.seen})})]}),e.jsxs(ke,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsx(zt,{className:"text-sm font-medium text-orange-600",children:"Pending"})}),e.jsx(Oe,{children:e.jsx("div",{className:"text-2xl font-bold text-orange-600",children:d.unseen})})]}),e.jsxs(ke,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsx(zt,{className:"text-sm font-medium text-purple-600",children:"Custom Sent"})}),e.jsx(Oe,{children:e.jsx("div",{className:"text-2xl font-bold text-purple-600",children:d.byType.custom||0})})]})]}),e.jsxs(ke,{children:[e.jsxs(Ot,{children:[e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(gh,{className:"h-5 w-5"}),"Celebration History"]}),e.jsx(Br,{children:"View all celebrations awarded to agents"})]}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Mn,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Se,{placeholder:"Search by agent name, email, or title...",value:s,onChange:h=>t(h.target.value),className:"pl-9"})]}),e.jsxs(Bs,{value:r,onValueChange:n,children:[e.jsx(Os,{className:"w-[180px]",children:e.jsx(Us,{placeholder:"Filter by type"})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"all",children:"All Types"}),Object.entries(T_e).map(([h,m])=>e.jsx(pt,{value:h,children:m.label},h))]})]}),e.jsxs(Bs,{value:a,onValueChange:i,children:[e.jsx(Os,{className:"w-[140px]",children:e.jsx(Us,{placeholder:"Status"})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"all",children:"All Status"}),e.jsx(pt,{value:"seen",children:"Seen"}),e.jsx(pt,{value:"unseen",children:"Pending"})]})]})]}),e.jsx("div",{className:"rounded-md border",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Vs,{children:[e.jsx(At,{children:"Type"}),e.jsx(At,{children:"Agent"}),e.jsx(At,{children:"Title"}),e.jsx(At,{children:"Points"}),e.jsx(At,{children:"Created By"}),e.jsx(At,{children:"Created"}),e.jsx(At,{children:"Status"})]})}),e.jsx(da,{children:c.length===0?e.jsx(Vs,{children:e.jsx(gt,{colSpan:7,className:"text-center py-8 text-muted-foreground",children:"No celebrations found"})}):c.map(h=>{const m=T_e[h.celebration_type],p=m.icon;return e.jsxs(Vs,{children:[e.jsx(gt,{children:e.jsxs(Xe,{variant:"outline",className:"gap-1",children:[e.jsx(p,{className:"h-3 w-3"}),m.label]})}),e.jsx(gt,{children:e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:h.user_name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:h.user_email})]})}),e.jsx(gt,{children:e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:h.title}),h.message&&e.jsx("div",{className:"text-xs text-muted-foreground truncate max-w-[200px]",children:h.message})]})}),e.jsx(gt,{children:h.points_amount?e.jsxs(Xe,{variant:"secondary",children:["+",h.points_amount]}):e.jsx("span",{className:"text-muted-foreground",children:"-"})}),e.jsx(gt,{children:e.jsx("span",{className:"text-sm text-muted-foreground",children:h.creator_name})}),e.jsx(gt,{children:e.jsx("span",{className:"text-sm text-muted-foreground",children:As(new Date(h.created_at),"MMM d, yyyy h:mm a")})}),e.jsx(gt,{children:h.seen_at?e.jsx(Xe,{variant:"outline",className:"bg-green-50 text-green-700 border-green-200",children:"Seen"}):e.jsx(Xe,{variant:"outline",className:"bg-orange-50 text-orange-700 border-orange-200",children:"Pending"})})]},h.id)})})]})}),c.length>0&&e.jsxs("p",{className:"text-sm text-muted-foreground text-right",children:["Showing ",c.length," of ",l.length," celebrations"]})]})]})]})}const Yls=()=>{const{user:s}=Ms(),{toast:t}=li(),[r,n]=S.useState([]),[a,i]=S.useState(!0),[l,o]=S.useState(!1),[c,d]=S.useState("all"),[h,m]=S.useState("all"),[p,x]=S.useState("new"),[y,_]=S.useState(new Set),b=S.useCallback(async()=>{try{i(!0);const{data:J,error:K}=await V.from("profiles").select("id, name, email, phone, is_trial, trial_started_at, trial_expires_at, subscription_status, subscription_end_date, converted_from_trial_at, created_at, last_login").or("is_trial.eq.true,subscription_status.eq.trialing,converted_from_trial_at.not.is.null");if(K)throw K;const{data:re,error:ie}=await V.from("trial_email_exports").select("user_id");if(ie)throw ie;const ce=new Set((re||[]).map(le=>le.user_id)),ne=(J||[]).map(le=>({...le,converted_from_trial_at:le.converted_from_trial_at??null,already_exported:ce.has(le.id)}));ne.sort((le,be)=>new Date(be.created_at).getTime()-new Date(le.created_at).getTime()),n(ne)}catch(J){console.error("Error loading trial users:",J),t({title:"Error",description:"Failed to load trial users",variant:"destructive"})}finally{i(!1)}},[t]);S.useEffect(()=>{b()},[b]);const j=J=>J.trial_started_at?"ghl":"stripe",k=J=>J.trial_expires_at?J.trial_expires_at:J.subscription_end_date?J.subscription_end_date:null,T=J=>J.converted_from_trial_at!==null,E=J=>{if(T(J))return!1;const K=k(J);return K?new Date(K).getTime()<=Date.now():!1},A=r.filter(J=>!(c!=="all"&&j(J)!==c||h==="active"&&(E(J)||T(J))||h==="expired"&&!E(J)||h==="converted"&&!T(J)||p==="new"&&J.already_exported||p==="exported"&&!J.already_exported)),D=()=>{y.size===A.length?_(new Set):_(new Set(A.map(J=>J.id)))},R=J=>{const K=new Set(y);K.has(J)?K.delete(J):K.add(J),_(K)},z=async()=>{if(y.size===0){t({title:"No users selected",description:"Select users to export",variant:"destructive"});return}o(!0);try{const J=r.filter(fe=>y.has(fe.id)),K="First Name,Last Name,Email,Phone,Trial Type,Status,Signup Date,Expiry Date",re=J.map(fe=>{const je=(fe.name||"").split(" "),ve=je[0]||"",We=je.slice(1).join(" ")||"",Ve=j(fe)==="stripe"?"Credit Card Trial":"Free Trial (No CC)",Le=T(fe)?"Converted":E(fe)?"Expired":"Active",Me=fe.created_at?new Date(fe.created_at).toLocaleDateString():"",ze=k(fe)?new Date(k(fe)).toLocaleDateString():"";return`"${ve}","${We}","${fe.email}","${fe.phone||""}","${Ve}","${Le}","${Me}","${ze}"`}),ie=[K,...re].join(` `),ce=new Blob([ie],{type:"text/csv"}),ne=URL.createObjectURL(ce),le=document.createElement("a");le.href=ne,le.download=`trial-users-${new Date().toISOString().split("T")[0]}.csv`,le.click(),URL.revokeObjectURL(ne);const be=J.filter(fe=>!fe.already_exported).map(fe=>({user_id:fe.id,exported_by:s.id}));if(be.length>0){const{error:fe}=await V.from("trial_email_exports").upsert(be,{onConflict:"user_id"});fe&&console.error("Error marking exports:",fe)}t({title:"Export complete",description:`Downloaded ${J.length} trial user(s). ${be.length} newly marked as exported.`}),_(new Set),b()}catch(J){console.error("Export error:",J),t({title:"Error",description:"Failed to export",variant:"destructive"})}finally{o(!1)}},O=r.filter(J=>!J.already_exported).length,$=r.filter(J=>J.already_exported).length,ee=r.filter(J=>T(J)).length,Z=r.filter(J=>!E(J)&&!T(J)).length;return a?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(is,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-5 gap-4",children:[e.jsx(ke,{children:e.jsxs(Ot,{className:"pb-2",children:[e.jsx(Br,{children:"Total"}),e.jsx(zt,{className:"text-2xl",children:r.length})]})}),e.jsx(ke,{children:e.jsxs(Ot,{className:"pb-2",children:[e.jsx(Br,{children:"New (Not Exported)"}),e.jsx(zt,{className:"text-2xl text-green-600",children:O})]})}),e.jsx(ke,{children:e.jsxs(Ot,{className:"pb-2",children:[e.jsx(Br,{children:"Active Trials"}),e.jsx(zt,{className:"text-2xl",children:Z})]})}),e.jsx(ke,{children:e.jsxs(Ot,{className:"pb-2",children:[e.jsx(Br,{children:"Converted 🎉"}),e.jsx(zt,{className:"text-2xl text-primary",children:ee})]})}),e.jsx(ke,{children:e.jsxs(Ot,{className:"pb-2",children:[e.jsx(Br,{children:"Already Exported"}),e.jsx(zt,{className:"text-2xl text-muted-foreground",children:$})]})})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs(Bs,{value:p,onValueChange:J=>x(J),children:[e.jsx(Os,{className:"w-[160px]",children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"all",children:"All Users"}),e.jsx(pt,{value:"new",children:"New Only"}),e.jsx(pt,{value:"exported",children:"Already Exported"})]})]}),e.jsxs(Bs,{value:c,onValueChange:J=>d(J),children:[e.jsx(Os,{className:"w-[180px]",children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"all",children:"All Trial Types"}),e.jsx(pt,{value:"stripe",children:"Credit Card Trial"}),e.jsx(pt,{value:"ghl",children:"Free Trial (No CC)"})]})]}),e.jsxs(Bs,{value:h,onValueChange:J=>m(J),children:[e.jsx(Os,{className:"w-[160px]",children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"all",children:"All Statuses"}),e.jsx(pt,{value:"active",children:"Active Trial"}),e.jsx(pt,{value:"expired",children:"Expired"}),e.jsx(pt,{value:"converted",children:"Converted ✓"})]})]}),e.jsx("div",{className:"ml-auto",children:e.jsxs(H,{onClick:z,disabled:l||y.size===0,children:[l?e.jsx(is,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(hi,{className:"h-4 w-4 mr-2"}),"Export Selected (",y.size,")"]})})]}),e.jsx("div",{className:"border rounded-lg",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Vs,{className:"bg-muted/30 hover:bg-muted/30",children:[e.jsx(At,{className:"w-[40px]",children:e.jsx(ao,{checked:A.length>0&&y.size===A.length,onCheckedChange:D})}),e.jsx(At,{children:"Name"}),e.jsx(At,{children:"Email"}),e.jsx(At,{children:"Trial Type"}),e.jsx(At,{children:"Status"}),e.jsx(At,{children:"Signup Date"}),e.jsx(At,{children:"Last Login"}),e.jsx(At,{children:"Expires / Renews"}),e.jsx(At,{children:"Exported"})]})}),e.jsx(da,{children:A.length===0?e.jsx(Vs,{children:e.jsx(gt,{colSpan:9,className:"text-center py-8 text-muted-foreground",children:"No trial users match the current filters"})}):A.map(J=>{const K=j(J),re=T(J),ie=E(J),ce=k(J);return e.jsxs(Vs,{className:`hover:bg-muted/30 ${re?"bg-primary/5":""}`,children:[e.jsx(gt,{children:e.jsx(ao,{checked:y.has(J.id),onCheckedChange:()=>R(J.id)})}),e.jsx(gt,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2",children:[J.name,re&&e.jsx(al,{className:"h-3.5 w-3.5 text-primary"})]})}),e.jsx(gt,{className:"text-muted-foreground",children:J.email}),e.jsx(gt,{children:K==="stripe"?e.jsxs(Xe,{variant:"outline",className:"gap-1",children:[e.jsx(u0,{className:"h-3 w-3"}),"Credit Card"]}):e.jsxs(Xe,{variant:"secondary",className:"gap-1",children:[e.jsx(er,{className:"h-3 w-3"}),"Free (No CC)"]})}),e.jsx(gt,{children:re?e.jsxs(Xe,{className:"bg-primary/10 text-primary hover:bg-primary/20 gap-1",children:[e.jsx(al,{className:"h-3 w-3"}),"Converted"]}):ie?e.jsx(Xe,{variant:"destructive",children:"Expired"}):e.jsx(Xe,{className:"bg-green-500/10 text-green-600 hover:bg-green-500/20",children:"Active Trial"})}),e.jsx(gt,{className:"text-sm",children:J.created_at?new Date(J.created_at).toLocaleDateString():"—"}),e.jsx(gt,{className:"text-sm",children:J.last_login?e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{children:new Date(J.last_login).toLocaleDateString()}),e.jsx("span",{className:"text-xs text-muted-foreground",children:new Date(J.last_login).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]}):e.jsx("span",{className:"text-muted-foreground",children:"Never"})}),e.jsx(gt,{className:"text-sm",children:re&&ce?e.jsxs("span",{className:"text-muted-foreground",children:["Renews ",new Date(ce).toLocaleDateString()]}):ce?new Date(ce).toLocaleDateString():"—"}),e.jsx(gt,{children:J.already_exported?e.jsx(ea,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(Xe,{variant:"outline",className:"text-green-600 border-green-300",children:"New"})})]},J.id)})})]})}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Showing ",A.length," of ",r.length," trial users · ",ee," converted to paid"]})]})},Zls=()=>{const[s,t]=S.useState([]),[r,n]=S.useState(!0);return S.useEffect(()=>{(async()=>{const{data:i,error:l}=await V.from("user_deletion_log").select("*").order("created_at",{ascending:!1});!l&&i&&t(i),n(!1)})()},[]),r?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(is,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):s.length===0?e.jsx(ke,{children:e.jsxs(Oe,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(Dr,{className:"h-10 w-10 mx-auto mb-3 opacity-40"}),e.jsx("p",{children:"No deletion records yet"})]})}):e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-lg",children:"User Deletion History"})}),e.jsx(Oe,{children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Vs,{children:[e.jsx(At,{children:"Date"}),e.jsx(At,{children:"User"}),e.jsx(At,{children:"Email"}),e.jsx(At,{children:"Brokerage"}),e.jsx(At,{children:"Type"}),e.jsx(At,{children:"Deleted By"})]})}),e.jsx(da,{children:s.map(a=>e.jsxs(Vs,{children:[e.jsx(gt,{className:"whitespace-nowrap text-sm",children:As(new Date(a.created_at),"MMM d, yyyy h:mm a")}),e.jsx(gt,{className:"font-medium",children:a.deleted_user_name||"—"}),e.jsx(gt,{className:"text-sm text-muted-foreground",children:a.deleted_user_email||"—"}),e.jsx(gt,{children:a.brokerage_name||"—"}),e.jsx(gt,{children:e.jsx(Xe,{variant:a.deletion_type==="deleted"?"destructive":"secondary",children:a.deletion_type==="deleted"?"Account Deleted":"Removed"})}),e.jsx(gt,{className:"text-sm",children:a.deleted_by_name||a.deleted_by_email||"—"})]},a.id))})]})})]})},XA=s=>{const{user:t}=Ms(),r=ns(),n=yt({queryKey:["teams",s],queryFn:async()=>{let m=V.from("teams").select("*").order("created_at",{ascending:!1});s&&(m=m.eq("brokerage_id",s));const{data:p,error:x}=await m;if(x)throw x;return p||[]},enabled:!!t}),a=m=>yt({queryKey:["team-members",m],queryFn:async()=>{const{data:p,error:x}=await V.from("team_members").select("*").eq("team_id",m).order("role",{ascending:!0});if(x)throw x;const y=(p||[]).map(j=>j.user_id),{data:_}=await V.from("profiles").select("id, name, email, avatar_url").in("id",y),b=new Map((_||[]).map(j=>[j.id,j]));return(p||[]).map(j=>({...j,profile:b.get(j.user_id)||null}))},enabled:!!m}),i=Pt({mutationFn:async m=>{const p={name:m.name,created_by:t.id,description:m.description,contact_visibility:m.contact_visibility,lead_pond_enabled:m.lead_pond_enabled,shared_assets_enabled:m.shared_assets_enabled};m.brokerage_id&&(p.brokerage_id=m.brokerage_id);const{data:x,error:y}=await V.from("teams").insert(p).select().single();if(y)throw y;return x},onSuccess:()=>{r.invalidateQueries({queryKey:["teams"]}),he.success("Team created!")},onError:m=>{he.error("Failed to create team: "+m.message)}}),l=Pt({mutationFn:async({id:m,...p})=>{const{data:x,error:y}=await V.from("teams").update(p).eq("id",m).select().single();if(y)throw y;return x},onSuccess:()=>{r.invalidateQueries({queryKey:["teams"]}),he.success("Team updated")},onError:m=>{he.error("Failed to update team: "+m.message)}}),o=Pt({mutationFn:async m=>{const{error:p}=await V.from("teams").delete().eq("id",m);if(p)throw p},onSuccess:()=>{r.invalidateQueries({queryKey:["teams"]}),he.success("Team deleted")},onError:m=>{he.error("Failed to delete team: "+m.message)}}),c=Pt({mutationFn:async m=>{const{data:p,error:x}=await V.from("team_members").insert({team_id:m.team_id,user_id:m.user_id,role:m.role||"team_member"}).select().single();if(x)throw x.message.includes("duplicate")||x.message.includes("unique")?new Error("This agent is already on a team. They must be removed from their current team first."):x;return p},onSuccess:(m,p)=>{r.invalidateQueries({queryKey:["team-members",p.team_id]}),he.success("Member added to team")},onError:m=>{he.error(m.message)}}),d=Pt({mutationFn:async m=>{const{error:p}=await V.from("team_members").delete().eq("id",m.member_id);if(p)throw p},onSuccess:(m,p)=>{r.invalidateQueries({queryKey:["team-members",p.team_id]}),he.success("Member removed from team")},onError:m=>{he.error("Failed to remove member: "+m.message)}}),h=Pt({mutationFn:async m=>{const{error:p}=await V.from("team_members").update({role:m.role}).eq("id",m.member_id);if(p)throw p},onSuccess:(m,p)=>{r.invalidateQueries({queryKey:["team-members",p.team_id]}),he.success("Member role updated")},onError:m=>{he.error("Failed to update role: "+m.message)}});return{teams:n.data||[],isLoading:n.isLoading,createTeam:i,updateTeam:l,deleteTeam:o,addMember:c,removeMember:d,updateMemberRole:h,useTeamMembers:a}},Xls=()=>{const{user:s}=Ms();return yt({queryKey:["team-contacts",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:r}=await V.rpc("get_team_contacts",{_user_id:s.id});if(r)throw r;return t||[]},enabled:!!s})},mht=s=>{const{user:t}=Ms(),r=ns(),n=yt({queryKey:["lead-pond",s],queryFn:async()=>{const{data:o,error:c}=await V.from("team_lead_pond").select("*").eq("team_id",s).order("created_at",{ascending:!1});if(c)throw c;if(!o||o.length===0)return[];const d=o.map(j=>j.contact_id),h=[...new Set(o.map(j=>j.added_by))],m=o.filter(j=>j.claimed_by).map(j=>j.claimed_by),p=[...new Set([...h,...m])],[x,y]=await Promise.all([V.from("innercircle_contacts").select("id, first_name, last_name, email, phone").in("id",d),V.from("profiles").select("id, name, avatar_url").in("id",p)]),_=new Map((x.data||[]).map(j=>[j.id,j])),b=new Map((y.data||[]).map(j=>[j.id,j]));return o.map(j=>({...j,status:j.claimed_by?"claimed":"available",contact:_.get(j.contact_id)||null,contributor:b.get(j.added_by)||null,claimer:j.claimed_by&&b.get(j.claimed_by)||null}))},enabled:!!s&&!!t}),a=Pt({mutationFn:async o=>{const{data:c,error:d}=await V.rpc("add_to_lead_pond",{_contact_id:o.contact_id,_team_id:o.team_id,_notes:o.notes||null});if(d)throw d;return c},onSuccess:()=>{r.invalidateQueries({queryKey:["lead-pond"]}),he.success("Contact added to Lead Pond")},onError:o=>{he.error(o.message)}}),i=Pt({mutationFn:async o=>{const{error:c}=await V.rpc("claim_lead_pond_contact",{_lead_pond_id:o});if(c)throw c},onSuccess:()=>{r.invalidateQueries({queryKey:["lead-pond"]}),he.success("Lead claimed!")},onError:o=>{he.error(o.message)}}),l=Pt({mutationFn:async o=>{const{error:c}=await V.rpc("return_lead_pond_contact",{_lead_pond_id:o});if(c)throw c},onSuccess:()=>{r.invalidateQueries({queryKey:["lead-pond"]}),he.success("Lead returned to pond")},onError:o=>{he.error(o.message)}});return{leadPondItems:n.data||[],isLoading:n.isLoading,addToLeadPond:a,claimLead:i,returnLead:l}},Qls=()=>{const s=ns();return Pt({mutationFn:async t=>{const{data:r,error:n}=await V.rpc("transfer_contact",{_contact_id:t.contactId,_to_user_id:t.toUserId,_notes:t.notes||null});if(n)throw n;const a=r;if(!a.success)throw new Error(a.error);return a},onSuccess:()=>{s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["team-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact-counts"]}),he.success("Contact transferred successfully")},onError:t=>{he.error(t.message||"Failed to transfer contact")}})};function fht({open:s,onOpenChange:t,contactIds:r,contactNames:n=[],onComplete:a}){var A;const{user:i}=Ms(),{data:l}=sv(),{useTeamMembers:o}=XA(),{data:c=[]}=o((l==null?void 0:l.teamId)||""),d=Qls(),[h,m]=S.useState(null),[p,x]=S.useState(""),[y,_]=S.useState(!1),b=c.filter(D=>D.user_id!==(i==null?void 0:i.id)),j=async()=>{if(h){_(!0);try{for(const D of r)await d.mutateAsync({contactId:D,toUserId:h,notes:p||void 0});t(!1),m(null),x(""),a==null||a()}catch{}finally{_(!1)}}},k=b.find(D=>D.user_id===h),T=r.length>1,E=n.length>0?T?`${n.length} contacts`:n[0]:T?`${r.length} contacts`:"this contact";return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"sm:max-w-md",children:[e.jsxs(Cs,{children:[e.jsxs(Ns,{className:"flex items-center gap-2",children:[e.jsx(F2,{className:"h-5 w-5"}),"Transfer ",E]}),e.jsxs(nn,{children:["Select a team member to transfer ",T?"these contacts":"this contact"," to. The contact will be removed from the current owner's CRM and added to the selected member's."]})]}),e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{children:[e.jsx(ue,{className:"text-sm font-medium mb-2 block",children:"Transfer to:"}),e.jsx("div",{className:"space-y-1 max-h-[240px] overflow-y-auto",children:b.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No other team members available"}):b.map(D=>{var R,z,O;return e.jsxs("button",{onClick:()=>m(D.user_id),className:`w-full flex items-center gap-3 p-3 rounded-lg text-left transition-colors ${h===D.user_id?"bg-primary/10 border border-primary/30":"hover:bg-accent border border-transparent"}`,children:[e.jsxs(Un,{className:"h-8 w-8",children:[e.jsx(Ka,{src:((R=D.profile)==null?void 0:R.avatar_url)||""}),e.jsx(qn,{className:"text-xs",children:(((z=D.profile)==null?void 0:z.name)||"?").charAt(0).toUpperCase()})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:((O=D.profile)==null?void 0:O.name)||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground capitalize",children:D.role.replace("_"," ")})]})]},D.user_id)})})]}),e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"transfer-notes",className:"text-sm font-medium",children:"Notes (optional)"}),e.jsx(vr,{id:"transfer-notes",value:p,onChange:D=>x(D.target.value),placeholder:"Reason for transfer...",className:"mt-1",rows:2})]})]}),e.jsxs(wn,{children:[e.jsx(H,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(H,{onClick:j,disabled:!h||y,children:[y?e.jsx(is,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(F2,{className:"h-4 w-4 mr-2"}),"Transfer",k?` to ${(A=k.profile)==null?void 0:A.name}`:""]})]})]})})}const VEe=()=>{const s=Fr(),{data:t,isLoading:r}=Xls(),{data:n}=sv(),[a,i]=S.useState(""),[l,o]=S.useState("all"),[c,d]=S.useState(null),[h,m]=S.useState(""),p=(n==null?void 0:n.role)==="team_leader",x=S.useMemo(()=>{if(!t)return[];const _=new Map;return t.forEach(b=>{_.has(b.owner_user_id)||_.set(b.owner_user_id,{id:b.owner_user_id,name:b.owner_name||"Unknown",avatar:b.owner_avatar_url})}),Array.from(_.values())},[t]),y=S.useMemo(()=>{if(!t)return[];let _=t;if(l!=="all"&&(_=_.filter(b=>b.owner_user_id===l)),a.trim()){const b=a.toLowerCase();_=_.filter(j=>{var k,T,E;return(j.first_name+" "+(j.last_name||"")).toLowerCase().includes(b)||((k=j.email)==null?void 0:k.toLowerCase().includes(b))||((T=j.phone)==null?void 0:T.includes(b))||((E=j.owner_name)==null?void 0:E.toLowerCase().includes(b))})}return _},[t,a,l]);return r?e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ks,{className:"h-10 w-full"}),e.jsx(Ks,{className:"h-64 w-full"})]}):!t||t.length===0?e.jsx(ke,{children:e.jsxs(Oe,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Ar,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold mb-2",children:"No Team Contacts"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Team contact sharing is not enabled, or you're not on a team. Ask your manager about contact visibility settings."})]})}):e.jsxs("div",{className:"space-y-4",children:[e.jsx(ke,{children:e.jsx(Oe,{className:"p-4",children:e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Mn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Se,{placeholder:"Search by name, email, phone, or agent...",value:a,onChange:_=>i(_.target.value),className:"pl-9"})]}),e.jsxs(Bs,{value:l,onValueChange:o,children:[e.jsx(Os,{className:"w-[200px]",children:e.jsx(Us,{placeholder:"Filter by agent"})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"all",children:"All Team Members"}),x.map(_=>e.jsx(pt,{value:_.id,children:_.name},_.id))]})]})]})})}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[y.length," contact",y.length!==1?"s":""," from ",x.length," teammate",x.length!==1?"s":""]}),e.jsx(ke,{children:e.jsx(Oe,{className:"p-0 overflow-x-auto",children:e.jsxs(la,{className:"min-w-[800px]",children:[e.jsx(ca,{children:e.jsxs(Vs,{children:[e.jsx(At,{children:"Name"}),e.jsx(At,{children:"Agent"}),e.jsx(At,{children:"Contact Info"}),e.jsx(At,{children:"Address"}),e.jsx(At,{children:"Lead Source"}),e.jsx(At,{children:"Date Added"}),p&&e.jsx(At,{className:"w-[80px]",children:"Actions"})]})}),e.jsx(da,{children:y.length===0?e.jsx(Vs,{children:e.jsx(gt,{colSpan:p?7:6,className:"text-center py-8 text-muted-foreground",children:a||l!=="all"?"No contacts match your filters":"No team contacts available"})}):y.map(_=>e.jsxs(Vs,{className:`hover:bg-accent/50 ${p?"cursor-pointer":""}`,onClick:p?()=>s(`/mission-control/contacts/${_.id}`):void 0,children:[e.jsx(gt,{className:"font-medium",children:e.jsxs("span",{className:p?"hover:text-primary hover:underline transition-colors":"",children:[_.first_name," ",_.last_name||""]})}),e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Un,{className:"h-6 w-6",children:[e.jsx(Ka,{src:_.owner_avatar_url||""}),e.jsx(qn,{className:"text-[10px]",children:(_.owner_name||"?").charAt(0).toUpperCase()})]}),e.jsx("span",{className:"text-sm text-muted-foreground truncate max-w-[120px]",children:_.owner_name||"Unknown"})]})}),e.jsx(gt,{children:e.jsxs("div",{className:"space-y-1 text-sm",children:[_.email&&e.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground",children:[e.jsx(er,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate",children:_.email})]}),_.phone&&e.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground",children:[e.jsx(Yn,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{children:_.phone})]}),!_.email&&!_.phone&&e.jsx("span",{className:"text-xs text-muted-foreground italic",children:"No contact info"})]})}),e.jsx(gt,{children:_.address?e.jsxs("div",{className:"flex items-center gap-1 text-sm text-muted-foreground",children:[e.jsx(Qa,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate max-w-[180px]",children:_.address})]}):e.jsx("span",{className:"text-xs text-muted-foreground italic",children:"—"})}),e.jsx(gt,{children:_.lead_source?e.jsx(Xe,{variant:"outline",className:"text-xs border-primary/30 text-primary",children:_.lead_source}):e.jsx("span",{className:"text-xs text-muted-foreground italic",children:"—"})}),e.jsx(gt,{children:e.jsx("span",{className:"text-sm text-muted-foreground",children:As(new Date(_.created_at),"MMM d, yyyy")})}),p&&e.jsx(gt,{children:e.jsx(H,{variant:"ghost",size:"sm",className:"h-8 px-2",onClick:b=>{b.stopPropagation(),d(_.id),m(`${_.first_name} ${_.last_name||""}`.trim())},title:"Transfer to team member",children:e.jsx(F2,{className:"h-4 w-4"})})})]},_.id))})]})})}),e.jsx(fht,{open:!!c,onOpenChange:_=>{_||d(null)},contactIds:c?[c]:[],contactNames:h?[h]:[],onComplete:()=>d(null)})]})},HEe=({teamId:s})=>{const{user:t}=Ms(),{leadPondItems:r,isLoading:n,claimLead:a,returnLead:i}=mht(s);if(console.log("[LeadPondView] render — teamId:",s,"itemCount:",r.length,"loading:",n),n)return e.jsx("div",{className:"space-y-3",children:[1,2,3].map(c=>e.jsx(Ks,{className:"h-20 w-full"},c))});if(r.length===0)return e.jsx(ke,{children:e.jsxs(Oe,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(y1,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Lead Pond is Empty"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Team members can contribute contacts here for others to claim and follow up with."})]})});const l=r.filter(c=>c.status==="available"),o=r.filter(c=>c.status==="claimed");return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsxs("h3",{className:"text-sm font-semibold text-muted-foreground mb-3",children:["Available (",l.length,")"]}),l.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No leads available right now."}):e.jsx("div",{className:"space-y-2",children:l.map(c=>{var d,h,m,p,x,y,_;return e.jsx(ke,{children:e.jsxs(Oe,{className:"flex items-center justify-between p-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("p",{className:"font-medium text-sm",children:[(d=c.contact)==null?void 0:d.first_name," ",((h=c.contact)==null?void 0:h.last_name)||""]}),e.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1 mt-1",children:[((m=c.contact)==null?void 0:m.email)&&e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(er,{className:"h-3 w-3"})," ",c.contact.email]}),((p=c.contact)==null?void 0:p.phone)&&e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Yn,{className:"h-3 w-3"})," ",c.contact.phone]})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsxs(Un,{className:"h-4 w-4",children:[e.jsx(Ka,{src:((x=c.contributor)==null?void 0:x.avatar_url)||""}),e.jsx(qn,{className:"text-[8px]",children:(((y=c.contributor)==null?void 0:y.name)||"?").charAt(0)})]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["from ",((_=c.contributor)==null?void 0:_.name)||"Unknown"]})]})]}),e.jsxs(H,{size:"sm",onClick:()=>a.mutate(c.id),disabled:a.isPending,children:[e.jsx(hF,{className:"mr-1 h-3 w-3"}),"Claim"]})]})},c.id)})})]}),o.length>0&&e.jsxs("div",{children:[e.jsxs("h3",{className:"text-sm font-semibold text-muted-foreground mb-3",children:["Claimed (",o.length,")"]}),e.jsx("div",{className:"space-y-2",children:o.map(c=>{var d,h,m;return e.jsx(ke,{className:"opacity-75",children:e.jsxs(Oe,{className:"flex items-center justify-between p-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("p",{className:"font-medium text-sm",children:[(d=c.contact)==null?void 0:d.first_name," ",((h=c.contact)==null?void 0:h.last_name)||""]}),e.jsx("div",{className:"flex items-center gap-2 mt-1",children:e.jsxs(Xe,{variant:"secondary",className:"text-xs",children:["Claimed by ",((m=c.claimer)==null?void 0:m.name)||"Unknown"]})})]}),c.claimed_by===(t==null?void 0:t.id)&&e.jsxs(H,{size:"sm",variant:"outline",onClick:()=>i.mutate(c.id),disabled:i.isPending,children:[e.jsx(qy,{className:"mr-1 h-3 w-3"}),"Return"]})]})},c.id)})})]})]})},pht=({teamId:s})=>{const{useTeamMembers:t}=XA(),{data:r=[]}=t(s),n=r.map(x=>x.user_id),a=new Map(r.map(x=>[x.user_id,x.profile])),{data:i=[],isLoading:l}=yt({queryKey:["team-shared-presentations",s,n],queryFn:async()=>{if(n.length===0)return[];const{data:x,error:y}=await V.from("smart_presentations").select("id, owner_user_id, title, client_name, status, view_count, cta_clicked_count, share_token, created_at, published_at").in("owner_user_id",n).neq("status","archived").order("created_at",{ascending:!1});if(y)throw y;return x||[]},enabled:n.length>0}),{data:o=[],isLoading:c}=yt({queryKey:["team-shared-open-houses",s,n],queryFn:async()=>{if(n.length===0)return[];const{data:x,error:y}=await V.from("open_houses").select("id, agent_id, property_address, city, state, event_date, is_active, visitor_count, slug, created_at").in("agent_id",n).order("event_date",{ascending:!1});if(y)throw y;return x||[]},enabled:n.length>0}),{data:d=[],isLoading:h}=yt({queryKey:["team-shared-videos",s,n],queryFn:async()=>{if(n.length===0)return[];const{data:x,error:y}=await V.from("agent_videos").select("id, owner_user_id, title, recipient_name, status, view_count, touch_type, share_token, created_at").in("owner_user_id",n).eq("is_deleted",!1).order("created_at",{ascending:!1}).limit(50);if(y)throw y;return x||[]},enabled:n.length>0});if(l||c||h)return e.jsx("div",{className:"space-y-3",children:[1,2,3].map(x=>e.jsx(Ks,{className:"h-20 w-full"},x))});const p=x=>{const y=a.get(x);return{name:(y==null?void 0:y.name)||"Unknown",avatar:(y==null?void 0:y.avatar_url)||"",initials:((y==null?void 0:y.name)||"?").charAt(0).toUpperCase()}};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 grid-cols-3",children:[e.jsx(ke,{children:e.jsxs(Oe,{className:"flex items-center gap-3 p-4",children:[e.jsx(_1,{className:"h-5 w-5 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:i.length}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Presentations"})]})]})}),e.jsx(ke,{children:e.jsxs(Oe,{className:"flex items-center gap-3 p-4",children:[e.jsx(Fn,{className:"h-5 w-5 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:o.length}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Guest Books"})]})]})}),e.jsx(ke,{children:e.jsxs(Oe,{className:"flex items-center gap-3 p-4",children:[e.jsx(xn,{className:"h-5 w-5 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:d.length}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Videos"})]})]})})]}),e.jsxs(ta,{defaultValue:"presentations",className:"space-y-4",children:[e.jsxs(Qn,{children:[e.jsxs(ts,{value:"presentations",children:["Presentations (",i.length,")"]}),e.jsxs(ts,{value:"guest-books",children:["Guest Books (",o.length,")"]}),e.jsxs(ts,{value:"videos",children:["Videos (",d.length,")"]})]}),e.jsx(cs,{value:"presentations",className:"space-y-2",children:i.length===0?e.jsx(E_e,{icon:e.jsx(_1,{className:"h-10 w-10"}),label:"No presentations yet"}):i.map(x=>{const y=p(x.owner_user_id);return e.jsx(ke,{children:e.jsxs(Oe,{className:"flex items-center justify-between p-4",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsxs(Un,{className:"h-8 w-8 shrink-0",children:[e.jsx(Ka,{src:y.avatar}),e.jsx(qn,{className:"text-xs",children:y.initials})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:x.title||"Untitled"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[y.name," · ",As(new Date(x.created_at),"MMM d, yyyy")]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e.jsx(Xe,{variant:x.status==="published"?"default":"secondary",className:"text-xs capitalize",children:x.status}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(Bn,{className:"h-3 w-3"}),x.view_count||0]})]})]})},x.id)})}),e.jsx(cs,{value:"guest-books",className:"space-y-2",children:o.length===0?e.jsx(E_e,{icon:e.jsx(Fn,{className:"h-10 w-10"}),label:"No guest books yet"}):o.map(x=>{const y=p(x.agent_id);return e.jsx(ke,{children:e.jsxs(Oe,{className:"flex items-center justify-between p-4",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsxs(Un,{className:"h-8 w-8 shrink-0",children:[e.jsx(Ka,{src:y.avatar}),e.jsx(qn,{className:"text-xs",children:y.initials})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:x.property_address}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[y.name," · ",As(new Date(x.event_date),"MMM d, yyyy")]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[x.is_active?e.jsx(Xe,{className:"text-xs",children:"Active"}):e.jsx(Xe,{variant:"secondary",className:"text-xs",children:"Inactive"}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(Ar,{className:"h-3 w-3"}),x.visitor_count||0]})]})]})},x.id)})}),e.jsx(cs,{value:"videos",className:"space-y-2",children:d.length===0?e.jsx(E_e,{icon:e.jsx(xn,{className:"h-10 w-10"}),label:"No videos yet"}):d.map(x=>{const y=p(x.owner_user_id);return e.jsx(ke,{children:e.jsxs(Oe,{className:"flex items-center justify-between p-4",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsxs(Un,{className:"h-8 w-8 shrink-0",children:[e.jsx(Ka,{src:y.avatar}),e.jsx(qn,{className:"text-xs",children:y.initials})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:x.title||x.recipient_name||"Untitled Video"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[y.name," · ",As(new Date(x.created_at),"MMM d, yyyy")]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e.jsx(Xe,{variant:"secondary",className:"text-xs capitalize",children:x.touch_type}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(Bn,{className:"h-3 w-3"}),x.view_count||0]})]})]})},x.id)})})]})]})},E_e=({icon:s,label:t})=>e.jsx(ke,{children:e.jsxs(Oe,{className:"flex flex-col items-center justify-center py-8 text-center text-muted-foreground",children:[s,e.jsx("p",{className:"mt-2 text-sm",children:t})]})}),ght=({team:s,brokerageAgents:t,onBack:r,onUpdate:n,onAddMember:a,onRemoveMember:i,onUpdateRole:l,onDeleteTeam:o,isUpdating:c,isAddingMember:d})=>{var R,z;const{useTeamMembers:h}=XA(),{data:m=[],isLoading:p}=h(s.id),[x,y]=S.useState(!1),[_,b]=S.useState(""),[j,k]=S.useState("team_member"),{data:T}=yt({queryKey:["agents-on-other-teams",s.id],queryFn:async()=>{const{data:O}=await V.from("team_members").select("user_id, team_id, teams:team_id(name)").neq("team_id",s.id),$=new Map;return(O||[]).forEach(ee=>{var Z;$.set(ee.user_id,((Z=ee.teams)==null?void 0:Z.name)||"another team")}),$}}),E=new Set(m.map(O=>O.user_id)),A=t.filter(O=>!E.has(O.id)),D=async()=>{_&&(await a(_,j),b(""),k("team_member"),y(!1))};return e.jsxs("div",{className:"space-y-6",children:[e.jsx(H,{variant:"ghost",onClick:r,className:"mb-2",children:"← Back to Teams"}),e.jsxs(ta,{defaultValue:"members",className:"space-y-4",children:[e.jsxs(Qn,{children:[e.jsx(ts,{value:"members",children:"Members"}),e.jsxs(ts,{value:"contacts",children:[e.jsx(xE,{className:"mr-1 h-3.5 w-3.5"}),"Team Contacts"]}),s.lead_pond_enabled&&e.jsxs(ts,{value:"lead-pond",children:[e.jsx(y1,{className:"mr-1 h-3.5 w-3.5"}),"Lead Pond"]}),s.shared_assets_enabled&&e.jsxs(ts,{value:"shared-assets",children:[e.jsx(Uf,{className:"mr-1 h-3.5 w-3.5"}),"Shared Assets"]}),e.jsx(ts,{value:"settings",children:"Settings"})]}),e.jsxs(cs,{value:"members",className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h3",{className:"text-lg font-semibold",children:[s.name," — Members"]}),e.jsxs(bs,{open:x,onOpenChange:y,children:[e.jsx(Qi,{asChild:!0,children:e.jsxs(H,{size:"sm",children:[e.jsx(Vl,{className:"mr-2 h-4 w-4"}),"Add Member"]})}),e.jsxs(vs,{children:[e.jsxs(Cs,{children:[e.jsx(Ns,{children:"Add Team Member"}),e.jsxs(nn,{children:["Select an agent from your brokerage to add to ",s.name,"."]})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Agent"}),e.jsxs(gl,{children:[e.jsx(xl,{asChild:!0,children:e.jsxs(H,{variant:"outline",role:"combobox",className:"w-full justify-between font-normal",children:[_&&(((R=A.find(O=>O.id===_))==null?void 0:R.name)||((z=A.find(O=>O.id===_))==null?void 0:z.email))||"Select an agent",e.jsx(d0,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(il,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(k0,{children:[e.jsx(S0,{placeholder:"Search agents..."}),e.jsxs(C0,{children:[e.jsx(T0,{children:"No agents found."}),e.jsx(E0,{children:A.map(O=>{const $=T==null?void 0:T.get(O.id);return e.jsxs(fg,{value:O.name||O.email||O.id,disabled:!!$,onSelect:()=>b(O.id),children:[e.jsx(va,{className:Ft("mr-2 h-4 w-4",_===O.id?"opacity-100":"opacity-0")}),O.name||O.email,$&&e.jsxs("span",{className:"text-xs text-muted-foreground ml-1",children:["(on ",$,")"]})]},O.id)})})]})]})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Role"}),e.jsxs(Bs,{value:j,onValueChange:k,children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"team_leader",children:"Team Leader"}),e.jsx(pt,{value:"team_member",children:"Team Member"})]})]})]})]}),e.jsxs(wn,{children:[e.jsx(H,{variant:"outline",onClick:()=>y(!1),children:"Cancel"}),e.jsx(H,{onClick:D,disabled:!_||d,children:d?"Adding...":"Add to Team"})]})]})]})]}),p?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(O=>e.jsx(Ks,{className:"h-16 w-full"},O))}):m.length===0?e.jsx(ke,{children:e.jsxs(Oe,{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx(Ar,{className:"h-10 w-10 text-muted-foreground mb-3"}),e.jsx("p",{className:"text-muted-foreground",children:"No members yet. Add agents to this team."})]})}):e.jsx("div",{className:"space-y-2",children:m.map(O=>{var $,ee,Z,J,K;return e.jsx(ke,{children:e.jsxs(Oe,{className:"flex items-center justify-between p-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(Un,{className:"h-10 w-10",children:[e.jsx(Ka,{src:(($=O.profile)==null?void 0:$.avatar_url)||""}),e.jsx(qn,{children:(((ee=O.profile)==null?void 0:ee.name)||"?").charAt(0).toUpperCase()})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((Z=O.profile)==null?void 0:Z.name)||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(J=O.profile)==null?void 0:J.email})]}),O.role==="team_leader"?e.jsxs(Xe,{className:"bg-[hsl(var(--chart-4)/0.1)] text-[hsl(var(--chart-4))] border-[hsl(var(--chart-4))]",children:[e.jsx(zf,{className:"mr-1 h-3 w-3"})," Leader"]}):e.jsx(Xe,{variant:"secondary",children:"Member"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Bs,{value:O.role,onValueChange:re=>l(O.id,re),children:[e.jsx(Os,{className:"w-[140px]",children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"team_leader",children:"Team Leader"}),e.jsx(pt,{value:"team_member",children:"Team Member"})]})]}),e.jsxs(Rl,{children:[e.jsx(vp,{asChild:!0,children:e.jsx(H,{variant:"ghost",size:"icon",className:"text-muted-foreground hover:text-destructive",children:e.jsx(BF,{className:"h-4 w-4"})})}),e.jsxs(jl,{children:[e.jsxs(Nl,{children:[e.jsx(Sl,{children:"Remove Member?"}),e.jsxs(Cl,{children:["Remove ",((K=O.profile)==null?void 0:K.name)||"this member"," from ",s.name,"?"]})]}),e.jsxs(kl,{children:[e.jsx(Tl,{children:"Cancel"}),e.jsx(ml,{onClick:()=>i(O.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Remove"})]})]})]})]})]})},O.id)})})]}),e.jsx(cs,{value:"contacts",className:"space-y-4",children:e.jsx(VEe,{})}),s.lead_pond_enabled&&e.jsx(cs,{value:"lead-pond",className:"space-y-4",children:e.jsx(HEe,{teamId:s.id})}),s.shared_assets_enabled&&e.jsx(cs,{value:"shared-assets",className:"space-y-4",children:e.jsx(pht,{teamId:s.id})}),e.jsxs(cs,{value:"settings",className:"space-y-4",children:[e.jsxs(ke,{children:[e.jsxs(Ot,{children:[e.jsx(zt,{className:"text-lg",children:"Team Settings"}),e.jsx(Br,{children:"Configure how this team operates."})]}),e.jsxs(Oe,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Team Name"}),e.jsx(Se,{defaultValue:s.name,onBlur:O=>{O.target.value!==s.name&&n({name:O.target.value})}})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Description"}),e.jsx(vr,{defaultValue:s.description||"",onBlur:O=>{O.target.value!==(s.description||"")&&n({description:O.target.value||null})},rows:3})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Contact Visibility"}),e.jsxs(Bs,{defaultValue:s.contact_visibility,onValueChange:O=>n({contact_visibility:O}),children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"private",children:"Private — Members keep their contacts private"}),e.jsx(pt,{value:"leader_only",children:"Leader Only — Only team leaders can see member contacts"}),e.jsx(pt,{value:"full_team",children:"Full Team — All team members can see shared contacts"})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Controls whether team leaders and members can view each other's contacts."})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ue,{children:"Lead Pond"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Enable a shared lead pool where leaders can drop leads for members to claim."})]}),e.jsx(Or,{checked:s.lead_pond_enabled,onCheckedChange:O=>n({lead_pond_enabled:O})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ue,{children:"Shared Assets"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Allow team members to access shared presentations, guest books, and videos."})]}),e.jsx(Or,{checked:s.shared_assets_enabled,onCheckedChange:O=>n({shared_assets_enabled:O})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ue,{children:"Shared Video Library"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Let team members browse and use each other's videos from the Video Library."})]}),e.jsx(Or,{checked:s.shared_videos_enabled??!1,onCheckedChange:O=>n({shared_videos_enabled:O})})]})]})]}),e.jsxs(Rl,{children:[e.jsx(vp,{asChild:!0,children:e.jsxs(H,{variant:"destructive",size:"sm",children:[e.jsx(Dr,{className:"mr-2 h-4 w-4"}),"Delete Team"]})}),e.jsxs(jl,{children:[e.jsxs(Nl,{children:[e.jsx(Sl,{children:"Delete Team?"}),e.jsxs(Cl,{children:['This will permanently delete "',s.name,'" and remove all team members. This cannot be undone.']})]}),e.jsxs(kl,{children:[e.jsx(Tl,{children:"Cancel"}),e.jsx(ml,{onClick:()=>{o(),r()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete Team"})]})]})]})]})]})]})},xht=({open:s,onOpenChange:t,onCreateTeam:r,isCreating:n,brokerageAgents:a,isAdmin:i,allBrokerages:l,activeBrokerageId:o})=>{const[c,d]=S.useState(1),[h,m]=S.useState(""),[p,x]=S.useState(""),[y,_]=S.useState(""),[b,j]=S.useState(""),[k,T]=S.useState([]),E=()=>{d(1),m(""),x(""),_(""),j(""),T([])},A=O=>{O||E(),t(O)},D=async()=>{const O=y&&y!=="none"?y:o||null;await r({name:h.trim(),description:p.trim()||void 0,brokerage_id:O,leaderId:b||void 0,memberIds:k.length>0?k:void 0}),E()},R=O=>{O!==b&&T($=>$.includes(O)?$.filter(ee=>ee!==O):[...$,O])},z=a.filter(O=>O.id!==b);return e.jsx(bs,{open:s,onOpenChange:A,children:e.jsxs(vs,{className:"sm:max-w-lg max-h-[90vh] flex flex-col",children:[e.jsxs(Cs,{children:[e.jsx(Ns,{children:c===1?"Create New Team":"Assign Team Members"}),e.jsx(nn,{children:c===1?"Name your team and add a description.":"Pick a leader and optionally add initial members."}),e.jsxs("div",{className:"flex items-center gap-2 pt-2",children:[e.jsx("div",{className:Ft("h-1.5 flex-1 rounded-full transition-colors","bg-primary")}),e.jsx("div",{className:Ft("h-1.5 flex-1 rounded-full transition-colors",c===2?"bg-primary":"bg-muted")})]})]}),e.jsx("div",{className:"overflow-y-auto flex-1 pr-1",children:c===1?e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"team-name",children:"Team Name *"}),e.jsx(Se,{id:"team-name",value:h,onChange:O=>m(O.target.value),placeholder:"e.g., Downtown Squad",autoFocus:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"team-desc",children:"Description"}),e.jsx(vr,{id:"team-desc",value:p,onChange:O=>x(O.target.value),placeholder:"What is this team focused on?",rows:3})]}),i&&l&&l.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Brokerage"}),e.jsxs(Bs,{value:y,onValueChange:_,children:[e.jsx(Os,{children:e.jsx(Us,{placeholder:"No brokerage (independent team)"})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"none",children:"No brokerage (independent)"}),l.map(O=>e.jsx(pt,{value:O.id,children:O.name},O.id))]})]})]})]}):e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ue,{className:"flex items-center gap-1.5",children:[e.jsx(zf,{className:"h-3.5 w-3.5 text-[hsl(var(--chart-4))]"}),"Team Leader"]}),e.jsxs(Bs,{value:b,onValueChange:O=>{j(O),T($=>$.filter(ee=>ee!==O))},children:[e.jsx(Os,{children:e.jsx(Us,{placeholder:"Select a team leader (optional)"})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"none",children:"No leader for now"}),a.map(O=>e.jsx(pt,{value:O.id,children:O.name||O.email||"Unknown"},O.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ue,{className:"flex items-center gap-1.5",children:[e.jsx(Vl,{className:"h-3.5 w-3.5"}),"Initial Members",k.length>0&&e.jsxs(Xe,{variant:"secondary",className:"ml-1 text-xs",children:[k.length," selected"]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Click agents to add them. You can always add more later."}),e.jsx("div",{className:"border rounded-lg max-h-[240px] overflow-y-auto divide-y",children:z.length===0?e.jsxs("div",{className:"p-4 text-center text-sm text-muted-foreground",children:[e.jsx(Ar,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),"No agents available"]}):z.map(O=>{const $=k.includes(O.id);return e.jsxs("button",{type:"button",className:Ft("w-full flex items-center gap-3 p-3 text-left transition-colors hover:bg-accent/50",$&&"bg-primary/5"),onClick:()=>R(O.id),children:[e.jsxs(Un,{className:"h-8 w-8",children:[e.jsx(Ka,{src:O.avatar_url||""}),e.jsx(qn,{className:"text-xs",children:(O.name||"?").charAt(0).toUpperCase()})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:O.name||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:O.email})]}),e.jsx("div",{className:Ft("h-5 w-5 rounded-full border-2 flex items-center justify-center transition-colors shrink-0",$?"bg-primary border-primary text-primary-foreground":"border-muted-foreground/30"),children:$&&e.jsx(va,{className:"h-3 w-3"})})]},O.id)})})]})]})}),e.jsx(wn,{className:"gap-2 sm:gap-0",children:c===1?e.jsxs(e.Fragment,{children:[e.jsx(H,{variant:"outline",onClick:()=>A(!1),children:"Cancel"}),e.jsxs(H,{onClick:()=>d(2),disabled:!h.trim(),children:["Next",e.jsx(bi,{className:"ml-2 h-4 w-4"})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(H,{variant:"outline",onClick:()=>d(1),children:[e.jsx(za,{className:"mr-2 h-4 w-4"}),"Back"]}),e.jsx(H,{onClick:D,disabled:n,children:n?"Creating…":"Create Team"})]})})]})})},Jls=()=>{const{teams:s,isLoading:t,createTeam:r,updateTeam:n,deleteTeam:a,addMember:i,removeMember:l,updateMemberRole:o}=XA(),[c,d]=S.useState(!1),[h,m]=S.useState(null),[p,x]=S.useState(""),{data:y}=yt({queryKey:["all-brokerages-for-teams"],queryFn:async()=>{const{data:A,error:D}=await V.from("brokerages").select("id, name").order("name");if(D)throw D;return A||[]}}),{data:_}=yt({queryKey:["admin-team-member-info",s.map(A=>A.id).join(",")],queryFn:async()=>{var O;if(s.length===0)return{};const{data:A}=await V.from("team_members").select("team_id, user_id, role").in("team_id",s.map($=>$.id));if(!A)return{};const D=A.filter($=>$.role==="team_leader").map($=>$.user_id);let R={};if(D.length>0){const{data:$}=await V.from("profiles").select("id, name").in("id",D);$&&(R=Object.fromEntries($.map(ee=>[ee.id,{name:ee.name}])))}const z={};for(const $ of s){const ee=A.filter(J=>J.team_id===$.id),Z=ee.find(J=>J.role==="team_leader");z[$.id]={count:ee.length,leaderName:Z&&((O=R[Z.user_id])==null?void 0:O.name)||null}}return z},enabled:s.length>0}),b=(h==null?void 0:h.brokerage_id)||null,{data:j}=yt({queryKey:["brokerage-agents-for-teams",b],queryFn:async()=>{let A=V.from("profiles").select("id, name, email, avatar_url").order("name");b&&(A=A.eq("brokerage_id",b));const{data:D,error:R}=await A;if(R)throw R;return D||[]},enabled:!!h}),k=Object.fromEntries((y||[]).map(A=>[A.id,A.name])),T=async A=>{const D=await r.mutateAsync({name:A.name,brokerage_id:A.brokerage_id||null,description:A.description});if(A.leaderId&&A.leaderId!=="none"&&await i.mutateAsync({team_id:D.id,user_id:A.leaderId,role:"team_leader"}),A.memberIds)for(const R of A.memberIds)await i.mutateAsync({team_id:D.id,user_id:R,role:"team_member"});d(!1)};if(h)return e.jsx(ght,{team:h,brokerageAgents:j||[],onBack:()=>m(null),onUpdate:A=>n.mutateAsync({id:h.id,...A}).then(D=>m(D)),onAddMember:(A,D)=>i.mutateAsync({team_id:h.id,user_id:A,role:D}),onRemoveMember:A=>l.mutateAsync({team_id:h.id,member_id:A}),onUpdateRole:(A,D)=>o.mutateAsync({team_id:h.id,member_id:A,role:D}),onDeleteTeam:()=>{a.mutate(h.id),m(null)},isUpdating:n.isPending,isAddingMember:i.isPending});const E=s.filter(A=>A.name.toLowerCase().includes(p.toLowerCase())||(A.description||"").toLowerCase().includes(p.toLowerCase()));return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-1",children:[e.jsxs("div",{className:"relative flex-1 max-w-sm",children:[e.jsx(Mn,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Se,{placeholder:"Search teams...",value:p,onChange:A=>x(A.target.value),className:"pl-10"})]}),e.jsxs("span",{className:"text-sm text-muted-foreground whitespace-nowrap",children:[E.length," of ",s.length," teams"]})]}),e.jsxs(H,{size:"sm",onClick:()=>d(!0),children:[e.jsx(Ys,{className:"mr-2 h-4 w-4"}),"Create Team"]})]}),e.jsx(xht,{open:c,onOpenChange:d,onCreateTeam:T,isCreating:r.isPending,brokerageAgents:[],isAdmin:!0,allBrokerages:y,activeBrokerageId:null}),e.jsx("div",{className:"border rounded-lg bg-card overflow-hidden",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Vs,{className:"bg-muted/30 hover:bg-muted/30",children:[e.jsx(At,{className:"font-semibold",children:"Team Name"}),e.jsx(At,{className:"font-semibold",children:"Brokerage"}),e.jsx(At,{className:"font-semibold",children:"Leader"}),e.jsx(At,{className:"font-semibold",children:"Members"}),e.jsx(At,{className:"font-semibold",children:"Visibility"}),e.jsx(At,{className:"w-[100px]"})]})}),e.jsx(da,{children:t?e.jsx(e.Fragment,{children:[1,2,3].map(A=>e.jsxs(Vs,{children:[e.jsx(gt,{children:e.jsx(Ks,{className:"h-4 w-32"})}),e.jsx(gt,{children:e.jsx(Ks,{className:"h-4 w-24"})}),e.jsx(gt,{children:e.jsx(Ks,{className:"h-4 w-28"})}),e.jsx(gt,{children:e.jsx(Ks,{className:"h-4 w-12"})}),e.jsx(gt,{children:e.jsx(Ks,{className:"h-4 w-20"})}),e.jsx(gt,{children:e.jsx(Ks,{className:"h-4 w-16"})})]},A))}):E.length===0?e.jsx(Vs,{children:e.jsx(gt,{colSpan:6,className:"text-center py-12 text-muted-foreground",children:p?"No teams match your search":"No teams found. Create one to get started."})}):E.map(A=>{const D=_==null?void 0:_[A.id];return e.jsxs(Vs,{className:"hover:bg-muted/30",children:[e.jsxs(gt,{children:[e.jsx("button",{onClick:()=>m(A),className:"text-primary hover:underline font-medium",children:A.name}),A.description&&e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-1",children:A.description})]}),e.jsx(gt,{children:A.brokerage_id?e.jsx("span",{className:"text-sm",children:k[A.brokerage_id]||"—"}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"Independent"})}),e.jsx(gt,{children:D!=null&&D.leaderName?e.jsxs("span",{className:"text-sm flex items-center gap-1",children:[e.jsx(zf,{className:"h-3 w-3 text-[hsl(var(--chart-4))]"}),D.leaderName]}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"No leader"})}),e.jsx(gt,{children:e.jsxs(Xe,{variant:"secondary",className:"text-xs",children:[e.jsx(Ar,{className:"h-3 w-3 mr-1"}),(D==null?void 0:D.count)??0]})}),e.jsx(gt,{children:e.jsxs("span",{className:"text-xs text-muted-foreground capitalize flex items-center gap-1",children:[e.jsx(Fh,{className:"h-3 w-3"}),A.contact_visibility.replace("_"," ")]})}),e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(H,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>m(A),title:"Edit team",children:e.jsx(ni,{className:"h-3.5 w-3.5"})}),e.jsx(H,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:text-destructive",onClick:()=>{confirm(`Delete team "${A.name}"? This cannot be undone.`)&&a.mutate(A.id)},title:"Delete team",children:e.jsx(Dr,{className:"h-3.5 w-3.5"})})]})})]},A.id)})})]})})]})};function e$e(s){const t=new Date(s);return new Intl.DateTimeFormat("en-US",{weekday:"short",month:"short",day:"numeric",hour:"numeric",minute:"2-digit",timeZone:"America/New_York"}).format(t)+" ET"}function ecs({open:s,onOpenChange:t,recipients:r}){const{toast:n}=li(),[a,i]=S.useState([]),[l,o]=S.useState(!1),[c,d]=S.useState(""),[h,m]=S.useState(""),[p,x]=S.useState(""),[y,_]=S.useState(!1),[b,j]=S.useState(!1),k=S.useMemo(()=>a.find(D=>D.id===c)||null,[a,c]);S.useEffect(()=>{s&&(o(!0),(async()=>{const D=new Date().toISOString(),{data:R,error:z}=await V.from("events").select("id,title,description,event_date,zoom_link,image_url,is_published").gte("event_date",D).order("event_date",{ascending:!0}).limit(50);z?n({title:"Could not load events",description:z.message,variant:"destructive"}):i(R||[]),o(!1)})())},[s,n]);const T=S.useMemo(()=>r.filter(D=>D.email&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(D.email)),[r]),E=()=>{if(!k){n({title:"Pick an event first",variant:"destructive"});return}if(T.length===0){n({title:"No valid recipient emails",variant:"destructive"});return}j(!0)},A=async()=>{if(k){j(!1),_(!0);try{const{data:{session:D}}=await V.auth.getSession(),R=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/admin-send-event-invite",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${D==null?void 0:D.access_token}`},body:JSON.stringify({event_id:k.id,recipients:T.map(ee=>({email:ee.email,name:ee.name,user_id:ee.id})),custom_subject:h.trim()||void 0,custom_intro:p.trim()||void 0})}),z=await R.json().catch(()=>({}));if(!R.ok)throw new Error((z==null?void 0:z.error)||"Failed to send event invite");const O=(z==null?void 0:z.sent)??0,$=(z==null?void 0:z.failed)??0;n({title:"Invites sent",description:`Sent: ${O}${$?` · Failed: ${$}`:""}`}),t(!1),x(""),m(""),d("")}catch(D){const R=D instanceof Error?D.message:"Send failed";n({title:"Send failed",description:R,variant:"destructive"})}finally{_(!1)}}};return e.jsxs(e.Fragment,{children:[e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Cs,{children:[e.jsxs(Ns,{className:"flex items-center gap-2",children:[e.jsx(er,{className:"h-5 w-5 text-primary"}),"Send Event Invite"]}),e.jsxs(nn,{children:["Send a beautiful event invitation to ",T.length," selected member",T.length===1?"":"s",".",r.length!==T.length&&e.jsxs("span",{className:"block text-amber-600 mt-1",children:[r.length-T.length," skipped (missing or invalid email)"]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"event-select",children:"Event"}),l?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground py-2",children:[e.jsx(is,{className:"h-4 w-4 animate-spin"})," Loading upcoming events..."]}):a.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-2",children:"No upcoming events found. Create an event first."}):e.jsxs(Bs,{value:c,onValueChange:d,children:[e.jsx(Os,{id:"event-select",children:e.jsx(Us,{placeholder:"Pick an upcoming event..."})}),e.jsx(Fs,{children:a.map(D=>e.jsx(pt,{value:D.id,children:e.jsxs("div",{className:"flex flex-col text-left",children:[e.jsx("span",{className:"font-medium",children:D.title}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[e$e(D.event_date),!D.is_published&&" · (Draft)"]})]})},D.id))})]})]}),k&&e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-3 space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium",children:[e.jsx(Nn,{className:"h-4 w-4 text-primary"}),k.title]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:e$e(k.event_date)}),k.description&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 mt-1",children:k.description})]}),e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"subject",children:"Subject line (optional)"}),e.jsx(Se,{id:"subject",placeholder:k?`You're invited: ${k.title}`:"You're invited to...",value:h,onChange:D=>m(D.target.value)}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Leave blank to use the default."})]}),e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"intro",children:"Personal message (optional)"}),e.jsx(vr,{id:"intro",placeholder:"Add a custom intro message... e.g. 'As a new member, we'd love to have you at our weekly onboarding event!'",value:p,onChange:D=>x(D.target.value),rows:4}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"This appears at the top of the email. Leave blank for a friendly default."})]}),e.jsxs("div",{className:"rounded-lg border p-3 bg-muted/20",children:[e.jsxs("div",{className:"text-xs font-medium text-muted-foreground mb-2",children:["RECIPIENTS (",T.length,")"]}),e.jsxs("div",{className:"flex flex-wrap gap-1 max-h-24 overflow-y-auto",children:[T.slice(0,30).map(D=>e.jsx(Xe,{variant:"secondary",className:"text-xs font-normal",children:D.name||D.email},D.id)),T.length>30&&e.jsxs(Xe,{variant:"outline",className:"text-xs",children:["+",T.length-30," more"]})]})]})]}),e.jsxs(wn,{children:[e.jsx(H,{variant:"outline",onClick:()=>t(!1),disabled:y,children:"Cancel"}),e.jsx(H,{onClick:E,disabled:y||!c||T.length===0,children:y?e.jsxs(e.Fragment,{children:[e.jsx(is,{className:"h-4 w-4 mr-2 animate-spin"})," Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(yn,{className:"h-4 w-4 mr-2"})," Send to ",T.length]})})]})]})}),e.jsx(Rl,{open:b,onOpenChange:j,children:e.jsxs(jl,{children:[e.jsxs(Nl,{children:[e.jsx(Sl,{children:"Send event invite?"}),e.jsx(Cl,{children:k?e.jsxs(e.Fragment,{children:["Send invite for ",e.jsxs("span",{className:"font-medium text-foreground",children:['"',k.title,'"']})," to"," ",e.jsxs("span",{className:"font-medium text-foreground",children:[T.length," member",T.length===1?"":"s"]}),"?"]}):null})]}),e.jsxs(kl,{children:[e.jsx(Tl,{children:"Cancel"}),e.jsxs(ml,{onClick:A,children:[e.jsx(yn,{className:"h-4 w-4 mr-2"})," Send"]})]})]})})]})}const tcs=()=>{const s=Fr(),{user:t,isAdmin:r}=Ms(),{startImpersonation:n,isLoading:a}=age(),{toast:i}=li(),[l,o]=S.useState([]),[c,d]=S.useState([]),[h,m]=S.useState([]),[p,x]=S.useState({}),[y,_]=S.useState(!0);S.useState({});const[b,j]=S.useState(!1),[k,T]=S.useState({email:"",name:"",password:"",brokerage_id:"",role:"user",phone:"",trial_days:""}),[E,A]=S.useState(!1),[D,R]=S.useState(""),[z,O]=S.useState(1),[$,ee]=S.useState(50),[Z,J]=S.useState("all"),[K,re]=S.useState("all"),[ie,ce]=S.useState("all"),[ne,le]=S.useState("all"),[be,fe]=S.useState("all"),[je,ve]=S.useState(!1),[We,Ve]=S.useState(!1),[Le,Me]=S.useState(!1),[ze,Pe]=S.useState(null),[Ie,De]=S.useState(null),[pe,tt]=S.useState(!1),[ge,ct]=S.useState({name:"",email:"",brokerage_id:"",phone:""}),[Ue,et]=S.useState(null),[Qe,Ne]=S.useState(!1),[$e,it]=S.useState(""),[Je,st]=S.useState(!1),[mt,wt]=S.useState(!1),[at,rt]=S.useState(null),[Et,hs]=S.useState(""),[Is,lr]=S.useState(!1),[us,St]=S.useState(!1),[xs,kt]=S.useState(null),[fs,Gs]=S.useState(!1),[_s,br]=S.useState(!1),[zr,Yr]=S.useState(null),[rn,sn]=S.useState(""),[Vr,$r]=S.useState(!1),[hn,Zn]=S.useState({email:"",name:"",password:"",phone:""}),[cr,on]=S.useState(!1),[ds,Na]=S.useState(!1),[vn,_r]=S.useState(""),[Hr,_a]=S.useState(!1),[Jt,Cr]=S.useState(!1),[Gt,Ee]=S.useState(""),[He,ot]=S.useState(new Set),[jt,Dt]=S.useState(!1),[qt,ss]=S.useState(!1),[Yt,ls]=S.useState(null),[Xs,Rs]=S.useState(!1),[Er,ln]=S.useState(null),[mn,Gr]=S.useState([]),[fn,pn]=S.useState([]),[Sn,Aa]=S.useState(!1),[vo,fo]=S.useState({});S.useEffect(()=>{!t||!r||(Cn(),Wi())},[t,r]);const ai=async()=>{try{const{data:Mt,error:tr}=await V.from("brokerage_manager_assignments").select("user_id, brokerage_id");if(tr)throw tr;const kr={};for(const bn of Mt??[])kr[bn.brokerage_id]||(kr[bn.brokerage_id]=[]),kr[bn.brokerage_id].push(bn.user_id);x(kr)}catch(Mt){console.error("Error loading brokerage manager assignments:",Mt)}},Cn=async()=>{try{_(!0);const{data:Mt,error:tr}=await V.functions.invoke("get-user-details");if(tr)throw tr;const kr=Mt.users||[];o(kr),m(Mt.brokerages||[]),await ai();const bn=kr.filter(Mr=>Mr.roles.includes("assistant"));if(bn.length>0){const Mr=bn.map(qa=>qa.id),{data:sa}=await V.from("agent_assistant_assignments").select("agent_id, assistant_id").in("assistant_id",Mr);if(sa&&sa.length>0){const qa=[...new Set(sa.map(pd=>pd.agent_id))],{data:Ja}=await V.from("profiles").select("id, name, email").in("id",qa),jn={};for(const pd of sa){const Vh=Ja==null?void 0:Ja.find(Tu=>Tu.id===pd.agent_id);Vh&&(jn[pd.assistant_id]={agent_name:Vh.name||"",agent_email:Vh.email||""})}fo(jn)}}}catch(Mt){console.error("Error loading members:",Mt),i({title:"Error",description:"Failed to load members",variant:"destructive"})}finally{_(!1)}},Wi=async()=>{try{const{data:Mt,error:tr}=await V.from("app_tiles").select("id, name, icon, app_id, required_tags").order("name");if(tr)throw tr;d(Mt||[])}catch(Mt){console.error("Error loading apps:",Mt),i({title:"Error",description:"Failed to load apps",variant:"destructive"})}},Ki=async Mt=>{if(!ge.name.trim()||!ge.email.trim()){i({title:"Error",description:"Name and email are required",variant:"destructive"});return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(ge.email)){i({title:"Error",description:"Please enter a valid email address",variant:"destructive"});return}try{const{error:kr}=await V.from("profiles").update({name:ge.name.trim(),email:ge.email.trim(),brokerage_id:ge.brokerage_id||null,phone:ge.phone.trim()||null}).eq("id",Mt);if(kr)throw kr;i({title:"Success",description:"Member details updated successfully"}),Pe(null),Cn()}catch(kr){console.error("Error updating member:",kr),i({title:"Error",description:kr.message||"Failed to update member",variant:"destructive"})}},ii=async Mt=>{try{const{data:{session:tr}}=await V.auth.getSession(),kr=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/resend-welcome-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${tr==null?void 0:tr.access_token}`},body:JSON.stringify({userId:Mt})}),bn=await kr.json();if(!kr.ok)throw new Error(bn.error||"Failed to resend welcome email");i({title:"Success",description:"Welcome email sent successfully"})}catch(tr){console.error("Error resending welcome email:",tr),i({title:"Error",description:tr.message||"Failed to resend welcome email",variant:"destructive"})}},Ji=async(Mt,tr)=>{try{const{error:kr}=await V.functions.invoke("send-password-reset",{body:{email:Mt,redirectTo:window.location.origin}});if(kr)throw kr;i({title:"Password Reset Sent",description:`Password reset email sent to ${tr}`})}catch(kr){console.error("Error sending password reset:",kr),i({title:"Error",description:kr.message||"Failed to send password reset email",variant:"destructive"})}},co=async(Mt,tr)=>{if(confirm(`Are you sure you want to delete ${tr}? This action cannot be undone.`))try{const{data:{session:kr}}=await V.auth.getSession(),bn=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/delete-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${kr==null?void 0:kr.access_token}`},body:JSON.stringify({userId:Mt})}),Mr=await bn.json();if(!bn.ok)throw new Error(Mr.error||"Failed to delete user");i({title:"Success",description:"User deleted successfully"}),Cn()}catch(kr){console.error("Error deleting user:",kr),i({title:"Error",description:kr.message||"Failed to delete user",variant:"destructive"})}},ia=async()=>{if(!k.email||!k.name||!k.password){i({title:"Error",description:"Please fill in all fields",variant:"destructive"});return}if(k.role==="brokerage_manager"&&!k.brokerage_id){i({title:"Error",description:"Please select a brokerage for this manager",variant:"destructive"});return}j(!0);try{const{data:{session:Mt}}=await V.auth.getSession(),tr=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/create-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Mt==null?void 0:Mt.access_token}`},body:JSON.stringify(k)}),kr=await tr.json();if(!tr.ok)throw new Error(kr.error||"Failed to create user");if(k.role&&k.role!=="user"&&kr.userId){const bn=k.role==="brokerage_manager"?k.brokerage_id:void 0;await hr(kr.userId,k.role,"add",bn)}i({title:"Success",description:`User ${k.email} created successfully`}),T({email:"",name:"",password:"",brokerage_id:"",role:"user",phone:"",trial_days:""}),A(!1),Cn()}catch(Mt){console.error("Error creating user:",Mt),i({title:"Error",description:Mt.message||"Failed to create user",variant:"destructive"})}finally{j(!1)}},hr=async(Mt,tr,kr,bn)=>{try{const{data:{session:Mr}}=await V.auth.getSession(),sa={userId:Mt,role:tr,action:kr};if(tr==="brokerage_manager"){if(!bn){i({title:"Error",description:"Please choose a brokerage for this manager assignment",variant:"destructive"});return}sa.brokerageId=bn}const qa=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Mr==null?void 0:Mr.access_token}`},body:JSON.stringify(sa)}),Ja=await qa.json();if(!qa.ok)throw new Error(Ja.error||"Failed to manage user role");i({title:"Success",description:`Role ${kr==="add"?"added":"removed"} successfully`}),Cn()}catch(Mr){console.error("Error managing user role:",Mr),i({title:"Error",description:Mr.message||"Failed to manage user role",variant:"destructive"})}},Sa=(Mt,tr)=>tr.length===0?!0:tr.some(kr=>Mt.includes(kr)),Yi=async(Mt,tr,kr)=>{const bn=`${Mt}-${tr.id}`;et(bn);try{if(kr){const Mr=l.find(qa=>qa.id===Mt),sa=tr.required_tags.filter(qa=>Mr==null?void 0:Mr.tags.includes(qa));for(const qa of sa){const{error:Ja}=await V.from("user_tags").delete().eq("user_id",Mt).eq("tag",qa);if(Ja)throw Ja}i({title:"Access Removed",description:`Removed access to ${tr.name}`})}else if(tr.required_tags.length>0){const{error:Mr}=await V.from("user_tags").insert({user_id:Mt,tag:tr.required_tags[0]});if(Mr)throw Mr;i({title:"Access Granted",description:`Granted access to ${tr.name}`})}await Cn()}catch(Mr){console.error("Error toggling access:",Mr),i({title:"Error",description:Mr.message||"Failed to update access",variant:"destructive"})}finally{et(null)}},$o=async()=>{const Mt=$e.trim();if(!Mt){i({title:"Error",description:"Brokerage name is required",variant:"destructive"});return}if(Mt.length>100){i({title:"Error",description:"Brokerage name must be less than 100 characters",variant:"destructive"});return}if(h.find(kr=>kr.name.toLowerCase()===Mt.toLowerCase())){i({title:"Error",description:"A brokerage with this name already exists",variant:"destructive"});return}st(!0);try{const{error:kr}=await V.from("brokerages").insert({name:Mt});if(kr)throw kr;i({title:"Success",description:`Brokerage "${Mt}" created successfully`}),it(""),Ne(!1),Cn()}catch(kr){console.error("Error creating brokerage:",kr),i({title:"Error",description:kr.message||"Failed to create brokerage",variant:"destructive"})}finally{st(!1)}},cl=Mt=>{rt(Mt),hs(Mt.name),wt(!0)},bo=()=>{rt(null),hs(""),wt(!1)},md=async()=>{if(!at)return;const Mt=Et.trim();if(!Mt){i({title:"Error",description:"Brokerage name is required",variant:"destructive"});return}if(Mt.length>100){i({title:"Error",description:"Brokerage name must be less than 100 characters",variant:"destructive"});return}lr(!0);try{const{error:tr}=await V.from("brokerages").update({name:Mt}).eq("id",at.id);if(tr)throw tr;i({title:"Success",description:"Brokerage updated successfully"}),bo(),Cn()}catch(tr){console.error("Error updating brokerage:",tr),i({title:"Error",description:tr.message||"Failed to update brokerage",variant:"destructive"})}finally{lr(!1)}},Nu=async(Mt,tr)=>{var kr;if(!tr||typeof tr!="string"){i({title:"Error",description:"Please select a brokerage first",variant:"destructive"});return}try{const bn={userId:Mt,role:"brokerage_manager",action:"add",brokerageId:tr};console.debug("[assignManagerToBrokerage] payload",bn);const{data:{session:Mr}}=await V.auth.getSession(),sa=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Mr==null?void 0:Mr.access_token}`},body:JSON.stringify(bn)}),qa=await sa.json();if(!sa.ok&&!((kr=qa.error)!=null&&kr.includes("duplicate")))throw new Error(qa.error||"Failed to add role");i({title:"Success",description:"Manager assigned to brokerage"}),await Cn()}catch(bn){console.error("Error assigning manager:",bn),i({title:"Error",description:bn.message||"Failed to assign manager",variant:"destructive"})}},Yf=Mt=>{kt(Mt),St(!0)},ku=async()=>{if(xs){Gs(!0);try{const Mt=l.filter(bn=>bn.brokerage_id===xs.id),{data:{session:tr}}=await V.auth.getSession();for(const bn of Mt){const Mr=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/delete-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${tr==null?void 0:tr.access_token}`},body:JSON.stringify({userId:bn.id})});if(!Mr.ok){const sa=await Mr.json();console.error(`Failed to delete user ${bn.email}:`,sa.error)}}const{error:kr}=await V.from("brokerages").delete().eq("id",xs.id);if(kr)throw kr;i({title:"Success",description:`Brokerage "${xs.name}" and ${Mt.length} member(s) deleted`}),St(!1),kt(null),Cn()}catch(Mt){console.error("Error deleting brokerage:",Mt),i({title:"Error",description:Mt.message||"Failed to delete brokerage",variant:"destructive"})}finally{Gs(!1)}}},$h=Mt=>{Yr(Mt),sn(""),br(!0)},Su=()=>{Yr(null),sn(""),br(!1)},Ad=async Mt=>{try{const{error:tr}=await V.from("profiles").update({brokerage_id:null}).eq("id",Mt);if(tr)throw tr;i({title:"Success",description:"User removed from brokerage"}),Cn()}catch(tr){console.error("Error removing user from brokerage:",tr),i({title:"Error",description:tr.message||"Failed to remove user",variant:"destructive"})}},uv=async(Mt,tr)=>{try{const{error:kr}=await V.from("profiles").update({brokerage_id:tr}).eq("id",Mt);if(kr)throw kr;i({title:"Success",description:"User added to brokerage"}),Cn()}catch(kr){console.error("Error adding user to brokerage:",kr),i({title:"Error",description:kr.message||"Failed to add user",variant:"destructive"})}},rw=async()=>{if(!zr||!hn.email||!hn.name||!hn.password){i({title:"Error",description:"Please fill in all fields",variant:"destructive"});return}on(!0);try{const{data:{session:Mt}}=await V.auth.getSession(),tr=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/create-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Mt==null?void 0:Mt.access_token}`},body:JSON.stringify({...hn,brokerage_id:zr.id,role:"user"})}),kr=await tr.json();if(!tr.ok)throw new Error(kr.error||"Failed to create agent");i({title:"Success",description:`Agent ${hn.email} created successfully`}),Zn({email:"",name:"",password:"",phone:""}),$r(!1),Cn()}catch(Mt){console.error("Error creating agent:",Mt),i({title:"Error",description:Mt.message||"Failed to create agent",variant:"destructive"})}finally{on(!1)}},Uh=Mt=>l.filter(tr=>tr.brokerage_id===Mt),B0=Mt=>{const tr=Uh(Mt);if(!rn)return tr;const kr=rn.toLowerCase();return tr.filter(bn=>bn.name.toLowerCase().includes(kr)||bn.email.toLowerCase().includes(kr))},z0=Mt=>l.filter(tr=>tr.brokerage_id!==Mt),Zf=l.filter(Mt=>{var kr;if(D){const bn=D.toLowerCase();if(!(Mt.name.toLowerCase().includes(bn)||Mt.email.toLowerCase().includes(bn)||((kr=Mt.brokerage_name)==null?void 0:kr.toLowerCase().includes(bn))))return!1}if(Z==="claimed"&&!Mt.claimed||Z==="unclaimed"&&Mt.claimed||K!=="all"&&!Mt.roles.includes(K))return!1;const tr=Mt.is_trial||Mt.subscription_status==="trialing";if(ie==="trial"&&!tr||ie==="non-trial"&&tr||ne==="none"&&Mt.brokerage_id||ne!=="all"&&ne!=="none"&&Mt.brokerage_id!==ne)return!1;if(be!=="all"){if(!Mt.created_at)return!1;const bn=parseInt(be,10),Mr=Date.now()-bn*24*60*60*1e3;if(new Date(Mt.created_at).getTime(){var tr;return((tr=Mt.name)==null?void 0:tr.toLowerCase())||""},brokerage:Mt=>{var tr;return((tr=Mt.brokerage_name)==null?void 0:tr.toLowerCase())||""},status:Mt=>Mt.claimed?"active":"pending",role:Mt=>Mt.roles[0]||"",last_login:Mt=>Mt.last_sign_in_at?new Date(Mt.last_sign_in_at).getTime():null,created_at:Mt=>Mt.created_at?new Date(Mt.created_at).getTime():null}),bh=qh.length,Lp=$===0,Cu=Lp?1:Math.ceil(bh/$),Uo=Lp?0:(z-1)*$,yx=Lp?bh:Uo+$,Qd=qh.slice(Uo,yx),vx=Mt=>{R(Mt),O(1)},nw=Mt=>{ee(Mt),O(1)},Xf=(Mt,tr)=>{Mt(tr),O(1)},Ua=async(Mt,tr)=>{Ve(!0);try{const kr=l.find(qa=>qa.id===Mt);if(!kr)return;const bn=kr.trial_expires_at?new Date(kr.trial_expires_at):new Date,Mr=new Date(bn.getTime()+tr*24*60*60*1e3),{error:sa}=await V.from("profiles").update({trial_expires_at:Mr.toISOString()}).eq("id",Mt);if(sa)throw sa;i({title:"Trial Extended",description:`Trial extended by ${tr} days`}),Cn()}catch(kr){console.error("Error extending trial:",kr),i({title:"Error",description:kr.message||"Failed to extend trial",variant:"destructive"})}finally{Ve(!1)}},$0=async Mt=>{Me(!0);try{const{error:tr}=await V.from("profiles").update({is_trial:!1,trial_expires_at:null,trial_started_at:null,trial_claimed_at:null}).eq("id",Mt);if(tr)throw tr;i({title:"Account Converted",description:"User has been converted to a full account"}),Cn(),Eg()}catch(tr){console.error("Error converting trial:",tr),i({title:"Error",description:tr.message||"Failed to convert account",variant:"destructive"})}finally{Me(!1)}},[U0,Cm]=S.useState(!1),Tm=async(Mt,tr)=>{if(confirm(`Revert this user to a ${tr}-day free trial? This will clear their paid/grandfathered status. Any active Stripe subscription will need to be cancelled separately.`)){Cm(!0);try{const kr=new Date,bn=new Date(kr.getTime()+tr*24*60*60*1e3),{error:Mr}=await V.from("profiles").update({is_trial:!0,trial_started_at:kr.toISOString(),trial_expires_at:bn.toISOString(),trial_claimed_at:kr.toISOString(),is_grandfathered:!1,subscription_status:"none",subscription_end_date:null,subscription_product_id:null,subscription_price_id:null,converted_from_trial_at:null}).eq("id",Mt);if(Mr)throw Mr;i({title:"Reverted to Trial",description:`User is now on a ${tr}-day free trial.`}),Cn()}catch(kr){console.error("Error reverting to trial:",kr),i({title:"Error",description:kr.message||"Failed to revert to trial",variant:"destructive"})}finally{Cm(!1)}}},df=async Mt=>{Aa(!0);try{const{data:tr}=await V.from("agent_assistant_assignments").select("id, assistant_id, permissions").eq("agent_id",Mt);if(tr&&tr.length>0){const bn=tr.map(sa=>sa.assistant_id),{data:Mr}=await V.from("profiles").select("id, name, email").in("id",bn);Gr(tr.map(sa=>{const qa=Mr==null?void 0:Mr.find(Ja=>Ja.id===sa.assistant_id);return{id:sa.id,assistant_id:sa.assistant_id,assistant_name:(qa==null?void 0:qa.name)||"Unknown",assistant_email:(qa==null?void 0:qa.email)||"",permissions:sa.permissions||{}}}))}else Gr([]);const{data:kr}=await V.from("agent_assistant_assignments").select("id, agent_id, permissions").eq("assistant_id",Mt);if(kr&&kr.length>0){const bn=kr.map(sa=>sa.agent_id),{data:Mr}=await V.from("profiles").select("id, name, email").in("id",bn);pn(kr.map(sa=>{const qa=Mr==null?void 0:Mr.find(Ja=>Ja.id===sa.agent_id);return{id:sa.id,agent_id:sa.agent_id,agent_name:(qa==null?void 0:qa.name)||"Unknown",agent_email:(qa==null?void 0:qa.email)||"",permissions:sa.permissions||{}}}))}else pn([])}catch(tr){console.error("Error loading assistant data:",tr)}finally{Aa(!1)}},Dp=Mt=>{De(Mt),ct({name:Mt.name,email:Mt.email,brokerage_id:Mt.brokerage_id||"",phone:Mt.phone||""}),tt(!0),df(Mt.id)},Eg=()=>{De(null),tt(!1),ct({name:"",email:"",brokerage_id:"",phone:""})},V1=async()=>{Ie&&(await Ki(Ie.id),Eg())},uf=Mt=>{ot(tr=>{const kr=new Set(tr);return kr.has(Mt)?kr.delete(Mt):kr.add(Mt),kr})},Em=()=>{if(He.size===Qd.length&&Qd.every(Mt=>He.has(Mt.id))){const Mt=new Set(He);Qd.forEach(tr=>Mt.delete(tr.id)),ot(Mt)}else{const Mt=new Set(He);Qd.forEach(tr=>Mt.add(tr.id)),ot(Mt)}},Qf=()=>{ot(new Set)},q0=async()=>{if(He.size===0)return;Dt(!0);let Mt=0,tr=0;try{const{data:{session:kr}}=await V.auth.getSession();for(const bn of He)try{(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/resend-welcome-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${kr==null?void 0:kr.access_token}`},body:JSON.stringify({userId:bn})})).ok?Mt++:tr++}catch{tr++}i({title:"Bulk Email Complete",description:`Sent ${Mt} emails${tr>0?`, ${tr} failed`:""}`}),Qf()}catch(kr){i({title:"Error",description:kr.message||"Failed to send emails",variant:"destructive"})}finally{Dt(!1)}},H1=async()=>{if(He.size===0)return;Dt(!0);let Mt=0,tr=0;try{const{data:{session:kr}}=await V.auth.getSession();for(const bn of He)try{(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/send-password-reset",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${kr==null?void 0:kr.access_token}`},body:JSON.stringify({userId:bn})})).ok?Mt++:tr++}catch{tr++}i({title:"Bulk Password Reset Complete",description:`Sent ${Mt} reset emails${tr>0?`, ${tr} failed`:""}`}),Qf()}catch(kr){i({title:"Error",description:kr.message||"Failed to send password reset emails",variant:"destructive"})}finally{Dt(!1)}},fd=async()=>{if(He.size===0)return;const Mt=l.filter(Mr=>He.has(Mr.id)).map(Mr=>Mr.name).slice(0,5).join(", "),tr=He.size>5?` and ${He.size-5} more`:"";if(!confirm(`Are you sure you want to delete ${He.size} users (${Mt}${tr})? This action cannot be undone.`))return;Dt(!0);let kr=0,bn=0;try{const{data:{session:Mr}}=await V.auth.getSession();for(const sa of He)try{(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/delete-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Mr==null?void 0:Mr.access_token}`},body:JSON.stringify({userId:sa})})).ok?kr++:bn++}catch{bn++}i({title:"Bulk Delete Complete",description:`Deleted ${kr} users${bn>0?`, ${bn} failed`:""}`}),Qf(),Cn()}catch(Mr){i({title:"Error",description:Mr.message||"Failed to delete users",variant:"destructive"})}finally{Dt(!1)}},_c=async()=>{ss(!0);try{const{data:{session:Mt}}=await V.auth.getSession(),tr=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ghl-phone-sync",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Mt==null?void 0:Mt.access_token}`}});if(!tr.ok){const bn=await tr.json();throw new Error(bn.error||"Failed to sync phones")}const kr=await tr.json();i({title:"Phone Sync Complete",description:`Pulled ${kr.summary.pulledFromGHL} from GHL, pushed ${kr.summary.pushedToGHL} to GHL, ${kr.summary.alreadySynced} already synced`}),Cn()}catch(Mt){i({title:"Error",description:Mt.message||"Failed to sync phones with GHL",variant:"destructive"})}finally{ss(!1)}},Am=async(Mt,tr)=>{ls(Mt);try{const{data:{session:kr}}=await V.auth.getSession(),{data:bn}=await V.from("profiles").select("phone").eq("id",Mt).single(),Mr=(bn==null?void 0:bn.phone)||"",sa=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ghl-tag-sync",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${kr==null?void 0:kr.access_token}`},body:JSON.stringify({email:tr,action:"update",phone:Mr||void 0})});if(!sa.ok){const Ja=await sa.json();throw new Error(Ja.error||"Failed to sync with GHL")}const qa=await fetch(`https://services.leadconnectorhq.com/contacts/lookup?locationId=&email=${encodeURIComponent(tr)}`,{method:"GET",headers:{"Content-Type":"application/json"}});i({title:"Phone Synced",description:Mr?`Phone ${Mr} synced to GHL`:"Sync attempted - run bulk sync to pull phone from GHL"}),Cn()}catch(kr){i({title:"Error",description:kr.message||"Failed to sync phone",variant:"destructive"})}finally{ls(null)}},Ac=async Mt=>{await n(Mt)},Mm=()=>{if(He.size===0){i({title:"No members selected",description:"Please select members to export",variant:"destructive"});return}const Mt=l.filter(Ja=>He.has(Ja.id)),tr=["Name","Email","Phone","Brokerage","Roles","Status","Created At"],kr=Mt.map(Ja=>[Ja.name,Ja.email,Ja.phone||"",Ja.brokerage_name||"",Ja.roles.join("; "),Ja.claimed?"Claimed":"Unclaimed",new Date(Ja.created_at).toLocaleDateString()]),bn=[tr.join(","),...kr.map(Ja=>Ja.map(jn=>`"${(jn||"").replace(/"/g,'""')}"`).join(","))].join(` `),Mr=new Blob([bn],{type:"text/csv"}),sa=URL.createObjectURL(Mr),qa=document.createElement("a");qa.href=sa,qa.download=`members-export-${new Date().toISOString().split("T")[0]}.csv`,qa.click(),URL.revokeObjectURL(sa),i({title:"Export complete",description:`Exported ${Mt.length} member(s)`})},hf=()=>{if(Zf.length===0){i({title:"No members to export",description:"Adjust filters to include at least one member",variant:"destructive"});return}const Mt=["Name","Email","Phone","Brokerage","Roles","Status","Created At"],tr=Zf.map(Ja=>[Ja.name,Ja.email,Ja.phone||"",Ja.brokerage_name||"",Ja.roles.join("; "),Ja.claimed?"Claimed":"Unclaimed",Ja.created_at?new Date(Ja.created_at).toLocaleDateString():""]),kr=[Mt.join(","),...tr.map(Ja=>Ja.map(jn=>`"${(jn||"").replace(/"/g,'""')}"`).join(","))].join(` `),bn=new Blob([kr],{type:"text/csv"}),Mr=URL.createObjectURL(bn),sa=document.createElement("a"),qa=be!=="all"?`-last-${be}days`:"";sa.href=Mr,sa.download=`members-export${qa}-${new Date().toISOString().split("T")[0]}.csv`,sa.click(),URL.revokeObjectURL(Mr),i({title:"Export complete",description:`Exported ${Zf.length} member(s)`})};return y?e.jsx(Ss,{title:"Members",children:e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):e.jsxs(Ss,{title:"Members",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsx(km,{title:"Member Management",description:"Manage users, roles, and permissions"}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(H,{size:"sm",variant:"outline",onClick:_c,disabled:qt,children:[qt?e.jsx(is,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Yn,{className:"mr-2 h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:qt?"Syncing...":"Sync Phones with GHL"}),e.jsx("span",{className:"sm:hidden",children:qt?"Syncing...":"Sync GHL"})]}),e.jsxs(H,{size:"sm",variant:"outline",onClick:()=>Na(!0),children:[e.jsx($2,{className:"mr-2 h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Import CSV"}),e.jsx("span",{className:"sm:hidden",children:"Import"})]}),e.jsxs(bs,{open:E,onOpenChange:A,children:[e.jsx(Qi,{asChild:!0,children:e.jsxs(H,{size:"sm",children:[e.jsx(Vl,{className:"mr-2 h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Add Member"}),e.jsx("span",{className:"sm:hidden",children:"Add"})]})}),e.jsxs(vs,{children:[e.jsxs(Cs,{children:[e.jsx(Ns,{children:"Create New User"}),e.jsx(nn,{children:"Add a new user to the system. They'll be able to sign in immediately."})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"name",children:"Name"}),e.jsx(Se,{id:"name",placeholder:"John Doe",value:k.name,onChange:Mt=>T({...k,name:Mt.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"email",children:"Email"}),e.jsx(Se,{id:"email",type:"email",placeholder:"john@example.com",value:k.email,onChange:Mt=>T({...k,email:Mt.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"password",children:"Password"}),e.jsx(Se,{id:"password",type:"password",placeholder:"Min 6 characters",value:k.password,onChange:Mt=>T({...k,password:Mt.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"phone",children:"Phone (optional)"}),e.jsx(Se,{id:"phone",type:"tel",placeholder:"555-123-4567",value:k.phone,onChange:Mt=>T({...k,phone:Mt.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ue,{htmlFor:"brokerage",children:["Brokerage",k.role==="brokerage_manager"?" (required)":""]}),e.jsxs(Bs,{value:k.brokerage_id||"none",onValueChange:Mt=>T({...k,brokerage_id:Mt==="none"?"":Mt}),children:[e.jsx(Os,{id:"brokerage",children:e.jsx(Us,{placeholder:k.role==="brokerage_manager"?"Select brokerage":"Select brokerage (optional)"})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"none",children:"None"}),h.map(Mt=>e.jsx(pt,{value:Mt.id,children:Mt.name},Mt.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"role",children:"Role"}),e.jsxs(Bs,{value:k.role,onValueChange:Mt=>T({...k,role:Mt}),children:[e.jsx(Os,{id:"role",children:e.jsx(Us,{placeholder:"Select role"})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"user",children:"User"}),e.jsx(pt,{value:"moderator",children:"Moderator"}),e.jsx(pt,{value:"brokerage_manager",children:"Brokerage Manager"}),e.jsx(pt,{value:"admin",children:"Admin"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"trial_days",children:"Trial Period (optional)"}),e.jsxs(Bs,{value:k.trial_days||"none",onValueChange:Mt=>T({...k,trial_days:Mt==="none"?"":Mt}),children:[e.jsx(Os,{id:"trial_days",children:e.jsx(Us,{placeholder:"No trial (full access)"})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"none",children:"No trial (full access)"}),e.jsx(pt,{value:"7",children:"7-day trial"}),e.jsx(pt,{value:"30",children:"30-day trial"}),e.jsx(pt,{value:"60",children:"60-day trial"}),e.jsx(pt,{value:"90",children:"90-day trial"}),e.jsx(pt,{value:"365",children:"1-year trial"})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Trial accounts don't require a credit card. Access expires after the trial period."})]})]}),e.jsxs(wn,{children:[e.jsx(H,{variant:"outline",onClick:()=>A(!1),children:"Cancel"}),e.jsx(H,{onClick:ia,disabled:b,children:b?"Creating...":"Create User"})]})]})]})]})]}),e.jsxs(ta,{defaultValue:new URLSearchParams(window.location.search).get("tab")||"members",className:"space-y-6",children:[e.jsxs(Qn,{children:[e.jsx(ts,{value:"members",children:"Members"}),e.jsx(ts,{value:"brokerages",children:"Brokerages"}),e.jsx(ts,{value:"teams",children:"Teams"}),e.jsx(ts,{value:"trials",children:"Trial Users"}),e.jsx(ts,{value:"access",children:"Access Matrix"}),e.jsx(ts,{value:"celebrations",children:"Celebrations"}),e.jsx(ts,{value:"deletions",children:"Deletion Log"})]}),e.jsxs(cs,{value:"members",className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsxs("div",{className:"relative flex-1 min-w-[200px] max-w-md",children:[e.jsx(Mn,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Se,{placeholder:"Search members...",value:D,onChange:Mt=>vx(Mt.target.value),className:"pl-10 h-9"})]}),e.jsxs(Bs,{value:Z,onValueChange:Mt=>Xf(J,Mt),children:[e.jsx(Os,{className:"w-[130px] h-9",children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"all",children:"All Status"}),e.jsx(pt,{value:"claimed",children:"Active"}),e.jsx(pt,{value:"unclaimed",children:"Pending"})]})]}),e.jsxs(Bs,{value:K,onValueChange:Mt=>Xf(re,Mt),children:[e.jsx(Os,{className:"w-[130px] h-9",children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"all",children:"All Roles"}),e.jsx(pt,{value:"admin",children:"Admin"}),e.jsx(pt,{value:"brokerage_manager",children:"Manager"}),e.jsx(pt,{value:"assistant",children:"Assistant"}),e.jsx(pt,{value:"user",children:"User"})]})]}),e.jsxs(Bs,{value:ie,onValueChange:Mt=>Xf(ce,Mt),children:[e.jsx(Os,{className:"w-[130px] h-9",children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"all",children:"All Users"}),e.jsx(pt,{value:"trial",children:"Trial Only"}),e.jsx(pt,{value:"non-trial",children:"Full Only"})]})]}),e.jsxs(Bs,{value:ne,onValueChange:Mt=>Xf(le,Mt),children:[e.jsx(Os,{className:"w-[150px] h-9",children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"all",children:"All Brokerages"}),e.jsx(pt,{value:"none",children:"No Brokerage"}),h.map(Mt=>e.jsx(pt,{value:Mt.id,children:Mt.name},Mt.id))]})]}),e.jsxs(Bs,{value:be,onValueChange:Mt=>Xf(fe,Mt),children:[e.jsx(Os,{className:"w-[150px] h-9",children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"all",children:"Any Join Date"}),e.jsx(pt,{value:"30",children:"Joined Last 30 Days"}),e.jsx(pt,{value:"60",children:"Joined Last 60 Days"}),e.jsx(pt,{value:"90",children:"Joined Last 90 Days"})]})]}),e.jsxs(H,{size:"sm",variant:"outline",className:"h-9",onClick:hf,title:"Export currently filtered members to CSV",children:[e.jsx(hi,{className:"h-4 w-4 mr-1"}),"Export Filtered"]}),(D||Z!=="all"||K!=="all"||ie!=="all"||ne!=="all"||be!=="all")&&e.jsxs(H,{variant:"ghost",size:"sm",className:"h-9",onClick:()=>{R(""),J("all"),re("all"),ce("all"),le("all"),fe("all"),O(1)},children:[e.jsx(Rr,{className:"h-4 w-4 mr-1"}),"Clear"]}),e.jsxs("div",{className:"flex items-center gap-2 ml-auto",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:Lp?`Showing all ${bh} members`:`Showing ${Uo+1}-${Math.min(yx,bh)} of ${bh} members`}),e.jsxs(Bs,{value:$.toString(),onValueChange:Mt=>nw(Number(Mt)),children:[e.jsx(Os,{className:"h-9 w-[110px]",children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"50",children:"50 / page"}),e.jsx(pt,{value:"100",children:"100 / page"}),e.jsx(pt,{value:"250",children:"250 / page"}),e.jsx(pt,{value:"0",children:"All"})]})]})]})]}),He.size>0&&e.jsxs("div",{className:"flex flex-col gap-2 p-3 bg-primary/10 border border-primary/20 rounded-lg",children:[Qd.length>0&&Qd.every(Mt=>He.has(Mt.id))&&qh.length>He.size&&e.jsxs("div",{className:"flex items-center justify-between gap-2 px-1 text-sm",children:[e.jsxs("span",{className:"text-muted-foreground",children:["All ",He.size," on this page are selected."]}),e.jsxs(H,{size:"sm",variant:"link",className:"h-auto p-0 text-primary",onClick:()=>ot(new Set(qh.map(Mt=>Mt.id))),children:["Select all ",qh.length," filtered members"]})]}),qh.length>0&&He.size===qh.length&&e.jsxs("div",{className:"px-1 text-sm text-muted-foreground",children:["All ",qh.length," filtered members are selected."]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(j2,{className:"h-4 w-4 text-primary"}),e.jsxs("span",{className:"text-sm font-medium",children:[He.size," selected"]})]}),e.jsx("div",{className:"flex-1"}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(H,{size:"sm",variant:"outline",onClick:q0,disabled:jt,children:[jt?e.jsx(is,{className:"h-4 w-4 animate-spin mr-1"}):e.jsx(er,{className:"h-4 w-4 mr-1"}),e.jsx("span",{className:"hidden sm:inline",children:"Resend Invite"}),e.jsx("span",{className:"sm:hidden",children:"Invite"})]}),e.jsxs(H,{size:"sm",variant:"outline",onClick:H1,disabled:jt,children:[jt?e.jsx(is,{className:"h-4 w-4 animate-spin mr-1"}):e.jsx(dx,{className:"h-4 w-4 mr-1"}),e.jsx("span",{className:"hidden sm:inline",children:"Password Reset"}),e.jsx("span",{className:"sm:hidden",children:"Reset"})]}),e.jsxs(H,{size:"sm",variant:"outline",onClick:()=>ve(!0),disabled:jt,className:"bg-primary/5 border-primary/30 text-primary hover:bg-primary/10",children:[e.jsx(sF,{className:"h-4 w-4 mr-1"}),e.jsx("span",{className:"hidden sm:inline",children:"Send Event Invite"}),e.jsx("span",{className:"sm:hidden",children:"Invite"})]}),e.jsxs(H,{size:"sm",variant:"outline",onClick:Mm,children:[e.jsx(hi,{className:"h-4 w-4 mr-1"}),e.jsx("span",{className:"hidden sm:inline",children:"Export"}),e.jsx("span",{className:"sm:hidden",children:"CSV"})]}),e.jsxs(H,{size:"sm",variant:"destructive",onClick:fd,disabled:jt,children:[jt?e.jsx(is,{className:"h-4 w-4 animate-spin mr-1"}):e.jsx(Dr,{className:"h-4 w-4 mr-1"}),e.jsx("span",{className:"hidden sm:inline",children:"Delete"}),e.jsx("span",{className:"sm:hidden",children:"Del"})]}),e.jsx(H,{size:"sm",variant:"ghost",onClick:Qf,disabled:jt,children:e.jsx(Rr,{className:"h-4 w-4"})})]})]})]}),e.jsx("div",{className:"border rounded-lg bg-card overflow-hidden",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Vs,{className:"bg-muted/30 hover:bg-muted/30",children:[e.jsx(At,{className:"w-[50px]",children:e.jsx(ao,{checked:Qd.length>0&&Qd.every(Mt=>He.has(Mt.id)),onCheckedChange:Em,"aria-label":"Select all on page"})}),e.jsx(pc,{sortKey:"name",currentSortKey:Ju,currentDirection:Pp,onSort:oo,children:"Name"}),e.jsx(pc,{sortKey:"brokerage",currentSortKey:Ju,currentDirection:Pp,onSort:oo,children:"Brokerage"}),e.jsx(pc,{sortKey:"status",currentSortKey:Ju,currentDirection:Pp,onSort:oo,children:"Status"}),e.jsx(pc,{sortKey:"role",currentSortKey:Ju,currentDirection:Pp,onSort:oo,children:"Role"}),e.jsx(pc,{sortKey:"last_login",currentSortKey:Ju,currentDirection:Pp,onSort:oo,children:"Last Login"}),e.jsx(pc,{sortKey:"created_at",currentSortKey:Ju,currentDirection:Pp,onSort:oo,children:"Member Since"}),e.jsx(At,{className:"w-[100px]"})]})}),e.jsx(da,{children:Qd.length===0?e.jsx(Vs,{children:e.jsx(gt,{colSpan:8,className:"text-center py-12 text-muted-foreground",children:"No members found"})}):Qd.map(Mt=>e.jsxs(Vs,{className:`hover:bg-muted/30 ${He.has(Mt.id)?"bg-primary/5":""}`,children:[e.jsx(gt,{children:e.jsx(ao,{checked:He.has(Mt.id),onCheckedChange:()=>uf(Mt.id),"aria-label":`Select ${Mt.name}`})}),e.jsx(gt,{children:e.jsxs("div",{children:[e.jsx("button",{onClick:()=>Dp(Mt),className:"text-primary hover:underline font-medium text-left",children:Mt.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Mt.email})]})}),e.jsx(gt,{className:"text-muted-foreground",children:Mt.brokerage_name||"—"}),e.jsx(gt,{children:e.jsx("div",{className:"flex flex-col",children:(()=>{const tr=Mt.trial_expires_at||Mt.subscription_end_date;if((Mt.is_trial||Mt.subscription_status==="trialing")&&tr){const bn=Math.ceil((new Date(tr).getTime()-Date.now())/864e5),Mr=bn<=0,sa=bn<=3;return e.jsx(Xe,{variant:"outline",className:Ft("w-fit",Mr?"border-destructive text-destructive":sa?"border-amber-500 text-amber-600":"border-violet-300 text-violet-700 bg-violet-50"),children:Mr?"Trial Expired":`Trial · ${bn}d left`})}return e.jsx(Xe,{variant:Mt.claimed?"default":"secondary",className:Mt.claimed?"bg-primary text-primary-foreground w-fit":"w-fit",children:Mt.claimed?"Active":"Pending"})})()})}),e.jsx(gt,{children:e.jsxs("div",{className:"flex flex-col",children:[Mt.roles.length>0?e.jsx("span",{className:"text-sm capitalize",children:Mt.roles[0]}):e.jsx("span",{className:"text-muted-foreground",children:"—"}),Mt.roles.includes("assistant")&&vo[Mt.id]&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["→ ",vo[Mt.id].agent_name||vo[Mt.id].agent_email]})]})}),e.jsx(gt,{className:"text-muted-foreground",children:Mt.last_sign_in_at?new Date(Mt.last_sign_in_at).toLocaleDateString():"—"}),e.jsx(gt,{className:"text-muted-foreground",children:Mt.created_at?new Date(Mt.created_at).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):"—"}),e.jsx(gt,{children:e.jsxs("div",{className:"flex gap-1 justify-end",children:[e.jsx(H,{size:"icon",variant:"ghost",className:"h-8 w-8 text-yellow-500 hover:text-yellow-600 hover:bg-yellow-50",onClick:()=>{ln(Mt),Rs(!0)},title:"Send celebration",children:e.jsx(gh,{className:"h-4 w-4"})}),e.jsx(H,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>Dp(Mt),title:"Edit member",children:e.jsx(ni,{className:"h-4 w-4"})}),e.jsx(H,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>Am(Mt.id,Mt.email),disabled:Yt===Mt.id,title:"Sync phone with GHL",children:Yt===Mt.id?e.jsx(is,{className:"h-4 w-4 animate-spin"}):e.jsx(Yn,{className:"h-4 w-4"})}),e.jsx(H,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>ii(Mt.id),title:"Resend welcome email",children:e.jsx(er,{className:"h-4 w-4"})}),e.jsx(H,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>Ji(Mt.email,Mt.name),title:"Send password reset",children:e.jsx(_E,{className:"h-4 w-4"})}),e.jsx(H,{size:"icon",variant:"ghost",className:"h-8 w-8 text-blue-600 hover:text-blue-700 hover:bg-blue-50",onClick:()=>Ac(Mt.id),disabled:a||Mt.id===(t==null?void 0:t.id),title:Mt.id===(t==null?void 0:t.id)?"Cannot impersonate yourself":`Login as ${Mt.name}`,children:a?e.jsx(is,{className:"h-4 w-4 animate-spin"}):e.jsx(kE,{className:"h-4 w-4"})}),e.jsx(H,{size:"icon",variant:"ghost",className:"h-8 w-8 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:()=>co(Mt.id,Mt.name),title:"Delete user",children:e.jsx(Dr,{className:"h-4 w-4"})})]})})]},Mt.id))})]})}),Cu>1&&e.jsxs("div",{className:"flex items-center justify-between px-2 py-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:["Page ",z," of ",Cu]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(H,{variant:"outline",size:"sm",onClick:()=>O(1),disabled:z===1,children:"First"}),e.jsx(H,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>O(Mt=>Math.max(1,Mt-1)),disabled:z===1,children:e.jsx(fl,{className:"h-4 w-4"})}),e.jsx("div",{className:"flex items-center gap-1",children:Array.from({length:Math.min(5,Cu)},(Mt,tr)=>{let kr;return Cu<=5||z<=3?kr=tr+1:z>=Cu-2?kr=Cu-4+tr:kr=z-2+tr,e.jsx(H,{variant:z===kr?"default":"outline",size:"sm",className:"h-8 w-8 p-0",onClick:()=>O(kr),children:kr},kr)})}),e.jsx(H,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>O(Mt=>Math.min(Cu,Mt+1)),disabled:z===Cu,children:e.jsx($a,{className:"h-4 w-4"})}),e.jsx(H,{variant:"outline",size:"sm",onClick:()=>O(Cu),disabled:z===Cu,children:"Last"})]})]})]}),e.jsx(bs,{open:pe,onOpenChange:tt,children:e.jsxs(vs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Cs,{children:[e.jsx(Ns,{children:"Edit Member"}),e.jsx(nn,{children:"Update member details, roles, and app access"})]}),Ie&&e.jsxs("div",{className:"space-y-6 py-4",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx("h3",{className:"text-sm font-semibold",children:"Basic Information"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"edit-name",children:"Name"}),e.jsx(Se,{id:"edit-name",value:ge.name,onChange:Mt=>ct({...ge,name:Mt.target.value}),maxLength:100})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"edit-email",children:"Email"}),e.jsx(Se,{id:"edit-email",type:"email",value:ge.email,onChange:Mt=>ct({...ge,email:Mt.target.value}),maxLength:255})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"edit-phone",children:"Phone"}),e.jsx(Se,{id:"edit-phone",type:"tel",value:ge.phone,onChange:Mt=>ct({...ge,phone:Mt.target.value}),placeholder:"555-123-4567"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"edit-brokerage",children:"Brokerage"}),e.jsxs(Bs,{value:ge.brokerage_id||"none",onValueChange:Mt=>ct({...ge,brokerage_id:Mt==="none"?"":Mt}),children:[e.jsx(Os,{id:"edit-brokerage",children:e.jsx(Us,{placeholder:"Select brokerage"})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"none",children:"None"}),h.map(Mt=>e.jsx(pt,{value:Mt.id,children:Mt.name},Mt.id))]})]})]})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("h3",{className:"text-sm font-semibold",children:"Roles"}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[Ie.roles.map(Mt=>e.jsxs(Xe,{variant:"default",className:"gap-1",children:[e.jsx(Fh,{className:"h-3 w-3"}),Mt,Mt==="brokerage_manager"?e.jsx("span",{className:"text-xs text-muted-foreground ml-1",children:"(manage in Brokerages tab)"}):e.jsx("button",{onClick:()=>hr(Ie.id,Mt,"remove"),className:"ml-1 rounded-full hover:bg-destructive/20",title:"Remove role",children:e.jsx(Rr,{className:"h-3 w-3"})})]},Mt)),Ie.roles.length===0&&e.jsx("span",{className:"text-sm text-muted-foreground",children:"No roles assigned"})]}),e.jsxs(Bs,{onValueChange:Mt=>hr(Ie.id,Mt,"add"),children:[e.jsx(Os,{className:"w-[200px]",children:e.jsx(Us,{placeholder:"Add role..."})}),e.jsxs(Fs,{children:[!Ie.roles.includes("admin")&&e.jsx(pt,{value:"admin",children:"Admin"}),!Ie.roles.includes("user")&&e.jsx(pt,{value:"user",children:"User"})]})]}),!Ie.roles.includes("brokerage_manager")&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"To add as brokerage manager, use Brokerages tab → Manage"})]}),(mn.length>0||fn.length>0||Ie.roles.includes("assistant"))&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("h3",{className:"text-sm font-semibold flex items-center gap-2",children:[e.jsx(Ar,{className:"h-4 w-4"}),"Assistant Relationships"]}),Sn?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(is,{className:"h-4 w-4 animate-spin"}),"Loading..."]}):e.jsxs("div",{className:"space-y-3",children:[mn.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Has assistants:"}),mn.map(Mt=>e.jsxs("div",{className:"p-3 rounded-lg border bg-muted/30 space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm font-medium",children:Mt.assistant_name}),e.jsx(Xe,{variant:"outline",className:"text-xs",children:"Assistant"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Mt.assistant_email}),e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:Object.entries(Mt.permissions).filter(([,tr])=>tr).map(([tr])=>e.jsx(Xe,{variant:"secondary",className:"text-[10px] capitalize",children:tr},tr))})]},Mt.id))]}),fn.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Assists agents:"}),fn.map(Mt=>e.jsxs("div",{className:"p-3 rounded-lg border bg-muted/30 space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm font-medium",children:Mt.agent_name}),e.jsx(Xe,{variant:"outline",className:"text-xs",children:"Agent"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Mt.agent_email}),e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:Object.entries(Mt.permissions).filter(([,tr])=>tr).map(([tr])=>e.jsx(Xe,{variant:"secondary",className:"text-[10px] capitalize",children:tr},tr))})]},Mt.id))]})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("h3",{className:"text-sm font-semibold",children:"App Access"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Toggle which apps this member can access"}),e.jsx("div",{className:"grid gap-3",children:c.map(Mt=>{const tr=Sa(Ie.tags,Mt.required_tags),kr=`${Ie.id}-${Mt.id}`,bn=Ue===kr,Mr=Mt.required_tags.length===0;return e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border bg-muted/30",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-xl",children:Mt.icon}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-sm",children:Mt.name}),Mr&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"Available to all members"})]})]}),e.jsx("div",{className:"flex items-center gap-2",children:bn?e.jsx(is,{className:"h-4 w-4 animate-spin text-muted-foreground"}):Mr?e.jsx(Xe,{variant:"secondary",className:"text-xs",children:"Always On"}):e.jsx(Or,{checked:tr,onCheckedChange:()=>Yi(Ie.id,Mt,tr)})})]},Mt.id)})})]}),(Ie.is_trial||Ie.subscription_status==="trialing")&&e.jsxs("div",{className:"space-y-3 pt-4 border-t",children:[e.jsxs("h3",{className:"text-sm font-semibold flex items-center gap-2",children:[e.jsx(Pn,{className:"h-4 w-4"}),"Trial Status"]}),e.jsxs("div",{className:"p-4 rounded-lg border bg-amber-50 dark:bg-amber-950/20 border-amber-200 dark:border-amber-800",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{children:[Ie.trial_expires_at&&e.jsx(Jze,{expiresAt:Ie.trial_expires_at}),!Ie.trial_expires_at&&Ie.subscription_status==="trialing"&&Ie.subscription_end_date&&e.jsx(Jze,{expiresAt:Ie.subscription_end_date})]}),(Ie.trial_expires_at||Ie.subscription_end_date)&&e.jsxs("span",{className:"text-sm text-muted-foreground",children:["Expires: ",new Date(Ie.trial_expires_at||Ie.subscription_end_date).toLocaleDateString()]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(H,{size:"sm",variant:"outline",onClick:()=>Ua(Ie.id,7),disabled:We,children:[e.jsx(A2,{className:"h-4 w-4 mr-1"}),"+7 Days"]}),e.jsxs(H,{size:"sm",variant:"outline",onClick:()=>Ua(Ie.id,14),disabled:We,children:[e.jsx(A2,{className:"h-4 w-4 mr-1"}),"+14 Days"]}),e.jsxs(H,{size:"sm",variant:"outline",onClick:()=>Ua(Ie.id,30),disabled:We,children:[e.jsx(A2,{className:"h-4 w-4 mr-1"}),"+30 Days"]}),e.jsxs(H,{size:"sm",variant:"default",onClick:()=>$0(Ie.id),disabled:Le,className:"bg-green-600 hover:bg-green-700",children:[e.jsx(j1,{className:"h-4 w-4 mr-1"}),"Convert to Full Account"]})]}),Ie.trial_started_at&&e.jsxs("div",{className:"mt-3 text-xs text-muted-foreground",children:["Trial started: ",new Date(Ie.trial_started_at).toLocaleDateString(),Ie.trial_claimed_at&&e.jsxs("span",{children:[" • Claimed: ",new Date(Ie.trial_claimed_at).toLocaleDateString()]})]})]})]}),!(Ie.is_trial||Ie.subscription_status==="trialing")&&e.jsxs("div",{className:"space-y-3 pt-4 border-t",children:[e.jsxs("h3",{className:"text-sm font-semibold flex items-center gap-2",children:[e.jsx(Pn,{className:"h-4 w-4"}),"Revert to Free Trial"]}),e.jsxs("div",{className:"p-4 rounded-lg border bg-blue-50 dark:bg-blue-950/20 border-blue-200 dark:border-blue-800",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-3",children:"Move this user back to a free trial. Clears paid/grandfathered status. If they have an active Stripe subscription, cancel it separately in Stripe."}),e.jsx("div",{className:"flex flex-wrap gap-2",children:[7,14,30,60,90].map(Mt=>e.jsxs(H,{size:"sm",variant:"outline",onClick:()=>Tm(Ie.id,Mt),disabled:U0,children:[e.jsx(A2,{className:"h-4 w-4 mr-1"}),Mt,"-day trial"]},Mt))})]})]}),e.jsxs("div",{className:"space-y-2 pt-4 border-t",children:[e.jsx("h3",{className:"text-sm font-semibold",children:"Account Information"}),e.jsxs("div",{className:"text-sm space-y-1 text-muted-foreground",children:[Ie.email_confirmed_at&&e.jsxs("div",{children:["Claimed: ",new Date(Ie.email_confirmed_at).toLocaleString()]}),Ie.last_sign_in_at&&e.jsxs("div",{children:["Last login: ",new Date(Ie.last_sign_in_at).toLocaleString()]}),e.jsxs("div",{children:["Created: ",new Date(Ie.created_at).toLocaleString()]})]})]})]}),e.jsxs(wn,{children:[e.jsx(H,{variant:"outline",onClick:Eg,children:"Cancel"}),e.jsx(H,{onClick:V1,children:"Save Changes"})]})]})}),e.jsxs(cs,{value:"access",children:[c.length===0?e.jsx(ke,{children:e.jsxs(Oe,{className:"py-12 text-center",children:[e.jsx("p",{className:"text-muted-foreground mb-4",children:"No apps configured yet"}),e.jsx(H,{onClick:()=>s("/admin/apps"),children:"Configure Apps"})]})}):e.jsxs(ke,{children:[e.jsxs(Ot,{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 space-y-0",children:[e.jsxs("div",{children:[e.jsx(zt,{children:"Member Access Matrix"}),e.jsx(Br,{children:"Toggle switches to grant or revoke app access for each member"})]}),e.jsxs("div",{className:"relative w-full sm:w-72",children:[e.jsx(Mn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Se,{placeholder:"Search agents by name or email...",value:D,onChange:Mt=>{R(Mt.target.value),O(1)},className:"pl-9"})]})]}),e.jsxs(Oe,{children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b",children:[e.jsx("th",{className:"text-left p-4 font-semibold sticky left-0 bg-card z-10",children:"Member"}),c.map(Mt=>e.jsx("th",{className:"text-center p-4 font-semibold min-w-[120px]",children:e.jsxs("div",{className:"flex flex-col items-center gap-1",children:[e.jsx("span",{className:"text-2xl",children:Mt.icon}),e.jsx("span",{className:"text-sm",children:Mt.name})]})},Mt.id))]})}),e.jsxs("tbody",{children:[Qd.map(Mt=>e.jsxs("tr",{className:"border-b hover:bg-muted/50",children:[e.jsx("td",{className:"p-4 sticky left-0 bg-card z-10",children:e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:Mt.name}),e.jsx("div",{className:"text-sm text-muted-foreground",children:Mt.email})]})}),c.map(tr=>{const kr=Sa(Mt.tags,tr.required_tags),bn=`${Mt.id}-${tr.id}`,Mr=Ue===bn;return e.jsx("td",{className:"p-4 text-center",children:e.jsx("div",{className:"flex items-center justify-center",children:Mr?e.jsx(is,{className:"h-5 w-5 animate-spin text-muted-foreground"}):e.jsx(Or,{checked:kr,onCheckedChange:()=>Yi(Mt.id,tr,kr),disabled:tr.required_tags.length===0})})},tr.id)})]},Mt.id)),Qd.length===0&&e.jsx("tr",{children:e.jsx("td",{colSpan:c.length+1,className:"p-8 text-center text-muted-foreground",children:"No members found"})})]})]})}),Cu>1&&e.jsxs("div",{className:"flex items-center justify-between px-2 py-4 border-t",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:["Showing ",Uo+1,"-",Math.min(yx,bh)," of ",bh," • Page ",z," of ",Cu]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(H,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>O(Mt=>Math.max(1,Mt-1)),disabled:z===1,children:e.jsx(fl,{className:"h-4 w-4"})}),e.jsx(H,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>O(Mt=>Math.min(Cu,Mt+1)),disabled:z===Cu,children:e.jsx($a,{className:"h-4 w-4"})})]})]})]})]}),e.jsx("div",{className:"mt-6",children:e.jsx(H,{variant:"outline",onClick:()=>s("/admin/apps"),children:"Manage Apps"})})]}),e.jsxs(cs,{value:"brokerages",className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-1",children:[e.jsxs("div",{className:"relative flex-1 max-w-sm",children:[e.jsx(Mn,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Se,{placeholder:"Search brokerages...",value:vn,onChange:Mt=>_r(Mt.target.value),className:"pl-10"})]}),e.jsxs("span",{className:"text-sm text-muted-foreground whitespace-nowrap",children:[h.filter(Mt=>Mt.name.toLowerCase().includes(vn.toLowerCase())).length," of ",h.length," brokerages"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(H,{size:"sm",variant:"outline",onClick:()=>{const Mt=[];for(const qa of h){const Ja=p[qa.id]??[];for(const jn of Ja){const pd=l.find(Vh=>Vh.id===jn);if(pd){const Vh=(pd.name||"").trim().split(/\s+/),Tu=Vh[0]||"",Ag=Vh.slice(1).join(" ")||"";Mt.push({firstName:Tu,lastName:Ag,email:pd.email,brokerageName:qa.name})}}}if(Mt.length===0){i({title:"No managers found to export"});return}const kr=[["First Name","Last Name","Email","Brokerage Name"].join(","),...Mt.map(qa=>[qa.firstName,qa.lastName,qa.email,qa.brokerageName].map(Ja=>`"${(Ja||"").replace(/"/g,'""')}"`).join(","))].join(` `),bn=new Blob([kr],{type:"text/csv"}),Mr=URL.createObjectURL(bn),sa=document.createElement("a");sa.href=Mr,sa.download=`brokerage-managers-${new Date().toISOString().slice(0,10)}.csv`,sa.click(),URL.revokeObjectURL(Mr),i({title:`Exported ${Mt.length} managers`})},children:[e.jsx(hi,{className:"mr-2 h-4 w-4"}),"Export Managers"]}),e.jsxs(bs,{open:Qe,onOpenChange:Ne,children:[e.jsx(Qi,{asChild:!0,children:e.jsxs(H,{size:"sm",children:[e.jsx(Xa,{className:"mr-2 h-4 w-4"}),"Add Brokerage"]})}),e.jsxs(vs,{children:[e.jsxs(Cs,{children:[e.jsx(Ns,{children:"Create New Brokerage"}),e.jsx(nn,{children:"Add a new brokerage to the system."})]}),e.jsx("div",{className:"space-y-4 py-4",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"brokerage-name",children:"Brokerage Name"}),e.jsx(Se,{id:"brokerage-name",placeholder:"Enter brokerage name",value:$e,onChange:Mt=>it(Mt.target.value),maxLength:100})]})}),e.jsxs(wn,{children:[e.jsx(H,{variant:"outline",onClick:()=>Ne(!1),children:"Cancel"}),e.jsx(H,{onClick:$o,disabled:Je,children:Je?"Creating...":"Create Brokerage"})]})]})]})]})]}),e.jsx("div",{className:"border rounded-lg bg-card overflow-hidden",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Vs,{className:"bg-muted/30 hover:bg-muted/30",children:[e.jsx(At,{className:"font-semibold",children:"Brokerage Name"}),e.jsx(At,{className:"font-semibold",children:"Manager(s)"}),e.jsx(At,{className:"font-semibold",children:"Agents"}),e.jsx(At,{className:"w-[150px]"})]})}),e.jsx(da,{children:(()=>{const Mt=h.filter(tr=>tr.name.toLowerCase().includes(vn.toLowerCase()));return Mt.length===0?e.jsx(Vs,{children:e.jsx(gt,{colSpan:4,className:"text-center py-12 text-muted-foreground",children:vn?"No brokerages match your search":"No brokerages found"})}):Mt.map(tr=>{const kr=l.filter(qa=>qa.brokerage_id===tr.id),Mr=(p[tr.id]??[]).map(qa=>l.find(Ja=>Ja.id===qa)).filter(Boolean),sa=kr.length;return e.jsxs(Vs,{className:"hover:bg-muted/30",children:[e.jsx(gt,{children:e.jsx("button",{onClick:()=>cl(tr),className:"text-primary hover:underline font-medium",children:tr.name})}),e.jsx(gt,{children:Mr.length>0?e.jsx("div",{className:"flex flex-wrap gap-1",children:Mr.map(qa=>e.jsx(Xe,{variant:"secondary",className:"text-xs",children:qa.name},qa.id))}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"No manager"})}),e.jsxs(gt,{children:[sa," member",sa!==1?"s":""]}),e.jsx(gt,{children:e.jsxs("div",{className:"flex gap-1 justify-end",children:[e.jsxs(H,{size:"sm",variant:"outline",className:"h-8",onClick:()=>$h(tr),children:[e.jsx(Ar,{className:"h-4 w-4 mr-1"}),"Manage"]}),e.jsx(H,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>cl(tr),title:"Edit brokerage",children:e.jsx(ni,{className:"h-4 w-4"})}),e.jsx(H,{size:"icon",variant:"ghost",className:"h-8 w-8 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:()=>Yf(tr),title:"Delete brokerage",children:e.jsx(Dr,{className:"h-4 w-4"})})]})})]},tr.id)})})()})]})}),e.jsx(bs,{open:mt,onOpenChange:wt,children:e.jsxs(vs,{className:"max-w-lg",children:[e.jsxs(Cs,{children:[e.jsx(Ns,{children:"Edit Brokerage"}),e.jsx(nn,{children:"Update brokerage details and manage managers"})]}),at&&e.jsxs("div",{className:"space-y-6 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"edit-brokerage-name",children:"Brokerage Name"}),e.jsx(Se,{id:"edit-brokerage-name",value:Et,onChange:Mt=>hs(Mt.target.value),maxLength:100})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(ue,{children:"Managers"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Click × to remove manager access for this brokerage (keeps them as a member)"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:(()=>{const tr=(p[at.id]??[]).map(kr=>l.find(bn=>bn.id===kr)).filter(Boolean);return tr.length===0?e.jsx("span",{className:"text-sm text-muted-foreground",children:"No managers assigned"}):tr.map(kr=>e.jsxs(Xe,{variant:"default",className:"gap-1",children:[e.jsx(Fh,{className:"h-3 w-3"}),kr.name,e.jsx("button",{onClick:()=>hr(kr.id,"brokerage_manager","remove",at.id),className:"ml-1 rounded-full hover:bg-destructive/20",title:"Remove manager from this brokerage",children:e.jsx(Rr,{className:"h-3 w-3"})})]},kr.id))})()}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{className:"text-sm text-muted-foreground",children:"Assign manager from existing members:"}),e.jsxs(gl,{open:Hr,onOpenChange:_a,children:[e.jsx(xl,{asChild:!0,children:e.jsxs(H,{variant:"outline",role:"combobox","aria-expanded":Hr,className:"w-full justify-between",children:["Search for a member...",e.jsx(Mn,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(il,{className:"w-full p-0",align:"start",children:e.jsxs(k0,{children:[e.jsx(S0,{placeholder:"Search by name or email..."}),e.jsxs(C0,{className:"max-h-[200px]",children:[e.jsx(T0,{children:"No members found."}),e.jsx(E0,{children:(()=>{const Mt=new Set(p[at.id]??[]);return l.filter(tr=>!Mt.has(tr.id)&&(r||tr.brokerage_id===at.id)).map(tr=>e.jsxs(fg,{value:`${tr.name} ${tr.email}`,onSelect:()=>{Nu(tr.id,at.id),_a(!1)},children:[tr.name," (",tr.email,")"]},tr.id))})()})]})]})})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Members in this Brokerage"}),e.jsx("div",{className:"max-h-32 overflow-y-auto border rounded p-2",children:l.filter(Mt=>Mt.brokerage_id===at.id).length===0?e.jsx("span",{className:"text-sm text-muted-foreground",children:"No members"}):l.filter(Mt=>Mt.brokerage_id===at.id).map(Mt=>e.jsxs("div",{className:"text-sm py-1 flex items-center justify-between",children:[e.jsx("span",{children:Mt.name}),Mt.roles.includes("brokerage_manager")&&e.jsx(Xe,{variant:"outline",className:"text-xs",children:"Manager"})]},Mt.id))})]})]}),e.jsxs(wn,{children:[e.jsx(H,{variant:"outline",onClick:bo,children:"Cancel"}),e.jsx(H,{onClick:md,disabled:Is,children:Is?"Saving...":"Save Changes"})]})]})}),e.jsx(bs,{open:us,onOpenChange:St,children:e.jsxs(vs,{children:[e.jsxs(Cs,{children:[e.jsx(Ns,{className:"text-destructive",children:"Delete Brokerage"}),e.jsxs(nn,{children:['Are you sure you want to delete "',xs==null?void 0:xs.name,'"?']})]}),e.jsx("div",{className:"py-4",children:e.jsxs("div",{className:"bg-destructive/10 border border-destructive/20 rounded-lg p-4 space-y-2",children:[e.jsx("p",{className:"text-sm font-medium text-destructive",children:"Warning: This action cannot be undone!"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"This will permanently delete:"}),e.jsxs("ul",{className:"text-sm text-muted-foreground list-disc list-inside",children:[e.jsxs("li",{children:['The brokerage "',xs==null?void 0:xs.name,'"']}),e.jsxs("li",{children:["All ",l.filter(Mt=>Mt.brokerage_id===(xs==null?void 0:xs.id)).length," member(s) assigned to this brokerage"]}),e.jsx("li",{children:"All their data, roles, and access"})]})]})}),e.jsxs(wn,{children:[e.jsx(H,{variant:"outline",onClick:()=>St(!1),children:"Cancel"}),e.jsx(H,{variant:"destructive",onClick:ku,disabled:fs,children:fs?"Deleting...":"Yes, Delete Brokerage"})]})]})}),e.jsx(bs,{open:_s,onOpenChange:br,children:e.jsxs(vs,{className:"max-w-4xl max-h-[85vh] overflow-hidden flex flex-col",children:[e.jsxs(Cs,{children:[e.jsxs(Ns,{className:"flex items-center gap-2",children:[e.jsx(Xa,{className:"h-5 w-5"}),"Manage ",zr==null?void 0:zr.name]}),e.jsx(nn,{children:"Add, remove, or manage users in this brokerage"})]}),zr&&e.jsxs("div",{className:"flex-1 overflow-hidden flex flex-col space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsxs("div",{className:"relative flex-1 min-w-[200px]",children:[e.jsx(Mn,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Se,{placeholder:"Search members...",value:rn,onChange:Mt=>sn(Mt.target.value),className:"pl-10 h-9"})]}),e.jsxs(bs,{open:Vr,onOpenChange:$r,children:[e.jsx(Qi,{asChild:!0,children:e.jsxs(H,{size:"sm",children:[e.jsx(Vl,{className:"h-4 w-4 mr-1"}),"Add New Agent"]})}),e.jsxs(vs,{children:[e.jsxs(Cs,{children:[e.jsx(Ns,{children:"Add New Agent"}),e.jsxs(nn,{children:["Create a new agent for ",zr.name]})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"agent-name",children:"Name"}),e.jsx(Se,{id:"agent-name",placeholder:"John Doe",value:hn.name,onChange:Mt=>Zn({...hn,name:Mt.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"agent-email",children:"Email"}),e.jsx(Se,{id:"agent-email",type:"email",placeholder:"john@example.com",value:hn.email,onChange:Mt=>Zn({...hn,email:Mt.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"agent-password",children:"Password"}),e.jsx(Se,{id:"agent-password",type:"password",placeholder:"Min 6 characters",value:hn.password,onChange:Mt=>Zn({...hn,password:Mt.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"agent-phone",children:"Phone (optional)"}),e.jsx(Se,{id:"agent-phone",type:"tel",placeholder:"555-123-4567",value:hn.phone,onChange:Mt=>Zn({...hn,phone:Mt.target.value})})]})]}),e.jsxs(wn,{children:[e.jsx(H,{variant:"outline",onClick:()=>$r(!1),children:"Cancel"}),e.jsx(H,{onClick:rw,disabled:cr,children:cr?"Creating...":"Create Agent"})]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ue,{className:"text-sm text-muted-foreground whitespace-nowrap",children:"Add existing user:"}),e.jsxs(gl,{open:Jt,onOpenChange:Cr,children:[e.jsx(xl,{asChild:!0,children:e.jsxs(H,{variant:"outline",role:"combobox","aria-expanded":Jt,className:"w-[300px] justify-between",children:["Select a user to add...",e.jsx(Mn,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(il,{className:"w-[300px] p-0",align:"start",children:e.jsxs(k0,{children:[e.jsx(S0,{placeholder:"Search users...",value:Gt,onValueChange:Ee}),e.jsxs(C0,{children:[e.jsx(T0,{children:"No users found."}),e.jsx(E0,{children:z0(zr.id).filter(Mt=>Gt===""||Mt.name.toLowerCase().includes(Gt.toLowerCase())||Mt.email.toLowerCase().includes(Gt.toLowerCase())).map(Mt=>e.jsxs(fg,{value:`${Mt.name} ${Mt.email}`,onSelect:()=>{uv(Mt.id,zr.id),Cr(!1),Ee("")},children:[Mt.name," (",Mt.email,")"]},Mt.id))})]})]})})]})]}),e.jsx("div",{className:"flex-1 overflow-auto border rounded-lg",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Vs,{className:"bg-muted/30 hover:bg-muted/30",children:[e.jsx(At,{className:"font-semibold",children:"Name"}),e.jsx(At,{className:"font-semibold",children:"Email"}),e.jsx(At,{className:"font-semibold",children:"Status"}),e.jsx(At,{className:"font-semibold",children:"Role"}),e.jsx(At,{className:"w-[120px]"})]})}),e.jsx(da,{children:B0(zr.id).length===0?e.jsx(Vs,{children:e.jsx(gt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:rn?"No matching members found":"No members in this brokerage"})}):B0(zr.id).map(Mt=>e.jsxs(Vs,{className:"hover:bg-muted/30",children:[e.jsx(gt,{className:"font-medium",children:Mt.name}),e.jsx(gt,{className:"text-muted-foreground",children:Mt.email}),e.jsx(gt,{children:Mt.claimed?e.jsx(Xe,{variant:"default",className:"bg-green-500/10 text-green-600 hover:bg-green-500/20",children:"Active"}):e.jsx(Xe,{variant:"secondary",children:"Pending"})}),e.jsx(gt,{children:Mt.roles.includes("brokerage_manager")?e.jsxs(Xe,{variant:"outline",className:"gap-1",children:[e.jsx(Fh,{className:"h-3 w-3"}),"Manager"]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"Agent"})}),e.jsx(gt,{children:e.jsxs("div",{className:"flex gap-1 justify-end",children:[!Mt.claimed&&e.jsx(H,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>ii(Mt.id),title:"Resend welcome email",children:e.jsx(er,{className:"h-4 w-4"})}),e.jsx(H,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>Ad(Mt.id),title:"Remove from brokerage",children:e.jsx(Rr,{className:"h-4 w-4"})}),e.jsx(H,{size:"icon",variant:"ghost",className:"h-8 w-8 text-blue-600 hover:text-blue-700 hover:bg-blue-50",onClick:()=>Ac(Mt.id),disabled:a||Mt.id===(t==null?void 0:t.id),title:Mt.id===(t==null?void 0:t.id)?"Cannot impersonate yourself":`Login as ${Mt.name}`,children:a?e.jsx(is,{className:"h-4 w-4 animate-spin"}):e.jsx(kE,{className:"h-4 w-4"})}),e.jsx(H,{size:"icon",variant:"ghost",className:"h-8 w-8 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:()=>co(Mt.id,Mt.name),title:"Delete user",children:e.jsx(Dr,{className:"h-4 w-4"})})]})})]},Mt.id))})]})}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[Uh(zr.id).length," total member",Uh(zr.id).length!==1?"s":""," •",Uh(zr.id).filter(Mt=>Mt.roles.includes("brokerage_manager")).length," manager",Uh(zr.id).filter(Mt=>Mt.roles.includes("brokerage_manager")).length!==1?"s":""]})]}),e.jsx(wn,{children:e.jsx(H,{variant:"outline",onClick:Su,children:"Close"})})]})})]}),e.jsx(cs,{value:"teams",children:e.jsx(Jls,{})}),e.jsx(cs,{value:"trials",children:e.jsx(Yls,{})}),e.jsx(cs,{value:"celebrations",children:e.jsx(Kls,{})}),e.jsx(cs,{value:"deletions",children:e.jsx(Zls,{})})]})]}),e.jsx(uht,{open:ds,onOpenChange:Na,brokerages:h,onSuccess:Cn}),Er&&e.jsx(hht,{open:Xs,onOpenChange:Mt=>{Rs(Mt),Mt||ln(null)},userId:Er.id,userName:Er.name}),e.jsx(ecs,{open:je,onOpenChange:ve,recipients:l.filter(Mt=>He.has(Mt.id)).map(Mt=>({id:Mt.id,name:Mt.name,email:Mt.email}))})]})},scs=()=>{const[s,t]=S.useState([]),[r,n]=S.useState(!0),[a,i]=S.useState(!1),[l,o]=S.useState(""),[c,d]=S.useState(""),[h,m]=S.useState(""),[p,x]=S.useState("");S.useEffect(()=>{y()},[]);const y=async()=>{const{data:A,error:D}=await V.from("invite_codes").select("*").order("created_at",{ascending:!1});D?(he.error("Failed to load invite codes"),console.error(D)):t(A||[]),n(!1)},_=async A=>{if(A.preventDefault(),!l.trim()){he.error("Please enter a code");return}i(!0);const{error:D}=await V.from("invite_codes").insert({code:l.trim().toUpperCase(),description:c.trim()||null,max_uses:h?parseInt(h):null,trial_days:p?parseInt(p):null});D?D.code==="23505"?he.error("This code already exists"):(he.error("Failed to create invite code"),console.error(D)):(he.success("Invite code created"),o(""),d(""),m(""),x(""),y()),i(!1)},b=async(A,D)=>{const{error:R}=await V.from("invite_codes").update({is_active:!D}).eq("id",A);R?he.error("Failed to update code"):t(s.map(z=>z.id===A?{...z,is_active:!D}:z))},j=async A=>{const{error:D}=await V.from("invite_codes").delete().eq("id",A);D?he.error("Failed to delete code"):(he.success("Code deleted"),t(s.filter(R=>R.id!==A)))},k="https://dashboard.relevelup.com",T=A=>{const D=`${k}/join?code=${A}`;navigator.clipboard.writeText(D),he.success("Link copied to clipboard")},E=`${k}/join`;return e.jsx(Ss,{title:"Invite Codes",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(km,{title:"Invite Codes",description:"Manage signup invite codes"}),e.jsxs(ke,{children:[e.jsxs(Ot,{children:[e.jsx(zt,{children:"Create New Code"}),e.jsxs(Br,{children:["Share link: ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded text-sm",children:E})]})]}),e.jsx(Oe,{children:e.jsxs("form",{onSubmit:_,className:"flex flex-wrap gap-4 items-end",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"code",children:"Code"}),e.jsx(Se,{id:"code",placeholder:"WELCOME2024",value:l,onChange:A=>o(A.target.value),className:"w-40"})]}),e.jsxs("div",{className:"space-y-2 flex-1 min-w-[200px]",children:[e.jsx(ue,{htmlFor:"description",children:"Description (optional)"}),e.jsx(Se,{id:"description",placeholder:"For marketing campaign",value:c,onChange:A=>d(A.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"maxUses",children:"Max Uses"}),e.jsx(Se,{id:"maxUses",type:"number",placeholder:"Unlimited",value:h,onChange:A=>m(A.target.value),className:"w-28"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"trialDays",children:"Trial Days"}),e.jsx(Se,{id:"trialDays",type:"number",placeholder:"None",value:p,onChange:A=>x(A.target.value),className:"w-28"})]}),e.jsxs(H,{type:"submit",disabled:a,children:[a?e.jsx(is,{className:"h-4 w-4 animate-spin"}):e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Create"]})]})})]}),e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsx(zt,{children:"Active Codes"})}),e.jsx(Oe,{children:r?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(is,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):s.length===0?e.jsx("p",{className:"text-center py-8 text-muted-foreground",children:"No invite codes yet"}):e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Vs,{children:[e.jsx(At,{children:"Code"}),e.jsx(At,{children:"Description"}),e.jsx(At,{children:"Uses"}),e.jsx(At,{children:"Trial"}),e.jsx(At,{children:"Created"}),e.jsx(At,{children:"Active"}),e.jsx(At,{className:"w-24",children:"Actions"})]})}),e.jsx(da,{children:s.map(A=>e.jsxs(Vs,{children:[e.jsx(gt,{className:"font-mono font-medium",children:A.code}),e.jsx(gt,{className:"text-muted-foreground",children:A.description||"—"}),e.jsxs(gt,{children:[A.uses_count,A.max_uses&&` / ${A.max_uses}`]}),e.jsx(gt,{children:A.trial_days?e.jsxs("span",{className:"text-amber-600 dark:text-amber-400 font-medium",children:[A.trial_days," days"]}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(gt,{className:"text-muted-foreground",children:As(new Date(A.created_at),"MMM d, yyyy")}),e.jsx(gt,{children:e.jsx(Or,{checked:A.is_active,onCheckedChange:()=>b(A.id,A.is_active)})}),e.jsx(gt,{children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx(H,{variant:"ghost",size:"icon",onClick:()=>T(A.code),title:"Copy invite link",children:e.jsx(ui,{className:"h-4 w-4"})}),e.jsx(H,{variant:"ghost",size:"icon",onClick:()=>j(A.id),className:"text-destructive hover:text-destructive",title:"Delete code",children:e.jsx(Dr,{className:"h-4 w-4"})})]})})]},A.id))})]})})]})]})})},vz=async s=>{try{const{data:t,error:r}=await V.from("push_notification_settings").select("is_enabled").eq("setting_key",s).maybeSingle();return r?(console.error("Error checking notification setting:",r),!0):(t==null?void 0:t.is_enabled)??!0}catch(t){return console.error("Error checking notification setting:",t),!0}},N8=async s=>{try{const{data:t,error:r}=await V.functions.invoke("send-push-notification",{body:s});return r?(console.error("Error sending notification:",r),{success:!1,error:r}):(console.log("Notification sent:",t),{success:!0,data:t})}catch(t){return console.error("Error sending notification:",t),{success:!1,error:t}}},rcs=async(s,t)=>await vz("new_templates")?N8({title:"New Template Available",body:`Check out the new template: ${s}`,url:`/templates/${t}`}):(console.log("New template notifications are disabled"),{success:!1,skipped:!0}),ncs=async(s,t)=>N8({title:"New Academy Video",body:`New video added: ${s}`,url:`/academy/${t}`}),acs=async(s,t)=>await vz("new_events")?N8({title:"New Event",body:`New event: ${s}`,url:`/events/${t}`}):(console.log("New event notifications are disabled"),{success:!1,skipped:!0}),ics=async(s,t)=>await vz("new_toolbox")?N8({title:"New Resource Kit",body:`New resource kit available: ${s}`,url:`/toolbox/${t}`}):(console.log("New toolbox notifications are disabled"),{success:!1,skipped:!0}),Uke=async(s,t)=>await vz("new_social_swag")?N8({title:"New Social Swag",body:`New social swag available: ${s}`,url:`/social-swag/${t}`}):(console.log("New social swag notifications are disabled"),{success:!1,skipped:!0}),ocs=async(s,t)=>await vz("new_newsletters")?N8({title:"New Newsletter",body:`New newsletter available: ${s}`,url:`/newsletters/${t}`}):(console.log("New newsletter notifications are disabled"),{success:!1,skipped:!0}),kq={title:"",description:"",image_url:"",video_url:"",event_date:void 0,event_time:"12:00",zoom_link:"",zoom_meeting_id:"",capacity:"",is_published:!1,is_recurring:!1,recurrence_pattern:"weekly",recurrence_end_date:void 0};function lcs(){const s=Fr(),t=ns(),[r,n]=S.useState(!1),[a,i]=S.useState(null),[l,o]=S.useState(kq),[c,d]=S.useState(null),[h,m]=S.useState(null),[p,x]=S.useState(!1),y=S.useRef(null),[_,b]=S.useState(!1),[j,k]=S.useState(null),[T,E]=S.useState(!1),[A,D]=S.useState(null),[R,z]=S.useState(null),[O,$]=S.useState(!0),[ee,Z]=S.useState(""),{data:J,isLoading:K}=yt({queryKey:["admin-events"],queryFn:async()=>{const{data:Ne,error:$e}=await V.from("events").select("*").order("event_date",{ascending:!0});if($e)throw $e;return Ne}}),{data:re}=yt({queryKey:["event-registrations-count"],queryFn:async()=>{let Ne=[],$e=0;const it=1e3;for(;;){const{data:st,error:mt}=await V.from("event_registrations").select("event_id").range($e,$e+it-1);if(mt)throw mt;if(!st||st.length===0||(Ne=Ne.concat(st),st.length{Je[st.event_id]=(Je[st.event_id]||0)+1}),Je}}),{data:ie,isLoading:ce}=yt({queryKey:["event-registrations-details",j==null?void 0:j.id],queryFn:async()=>{if(!j)return[];const{data:Ne,error:$e}=await V.from("event_registrations").select("id, user_id, registered_at, zoom_join_url, zoom_name, zoom_email").eq("event_id",j.id).order("registered_at",{ascending:!1});if($e)throw $e;if(!Ne||Ne.length===0)return[];const it=Ne.map(mt=>mt.user_id).filter(Boolean);let Je=[];if(it.length>0){const{data:mt,error:wt}=await V.from("profiles").select("id, name, email").in("id",it);if(wt)throw wt;Je=mt||[]}const st=new Map((Je==null?void 0:Je.map(mt=>[mt.id,mt]))||[]);return Ne.map(mt=>({...mt,profiles:mt.user_id&&st.get(mt.user_id)||null}))},enabled:!!j}),{data:ne,isLoading:le}=yt({queryKey:["event-attendees-details",j==null?void 0:j.id],queryFn:async()=>{if(!j)return[];const{data:Ne,error:$e}=await V.from("event_attendees").select("id, user_id, zoom_email, zoom_name, join_time, leave_time, duration_minutes, manually_added, created_at").eq("event_id",j.id).order("created_at",{ascending:!1});if($e)throw $e;if(!Ne||Ne.length===0)return[];const it=Ne.map(at=>at.user_id).filter(Boolean);let Je=[];if(it.length>0){const{data:at,error:rt}=await V.from("profiles").select("id, name, email").in("id",it);if(rt)throw rt;Je=at||[]}const{data:st}=await V.from("agent_points").select("user_id").eq("event_id",j.id),mt=new Set((st==null?void 0:st.map(at=>at.user_id))||[]),wt=new Map((Je==null?void 0:Je.map(at=>[at.id,at]))||[]);return Ne.map(at=>({...at,profiles:at.user_id&&wt.get(at.user_id)||null,points_awarded:at.user_id?mt.has(at.user_id):!1}))},enabled:!!j}),be=Ne=>{k(Ne),b(!0)},fe=Pt({mutationFn:async Ne=>{const{data:{session:$e}}=await V.auth.getSession();if(!$e)throw new Error("Not authenticated");const it=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/zoom-sync-registrations",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${$e.access_token}`},body:JSON.stringify({event_id:Ne})}),Je=await it.json();if(!it.ok)throw new Error(Je.error||"Failed to sync");return Je},onSuccess:Ne=>{t.invalidateQueries({queryKey:["event-registrations-details",j==null?void 0:j.id]}),t.invalidateQueries({queryKey:["event-registrations-count"]}),he.success(Ne.message)},onError:Ne=>{he.error("Failed to sync: "+Ne.message)}}),je=Pt({mutationFn:async Ne=>{const{data:{session:$e}}=await V.auth.getSession();if(!$e)throw new Error("Not authenticated");const it=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/zoom-sync-attendees",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${$e.access_token}`},body:JSON.stringify({event_id:Ne})}),Je=await it.json();if(!it.ok)throw new Error(Je.error||"Failed to sync attendees");return Je},onSuccess:Ne=>{t.invalidateQueries({queryKey:["event-attendees-details",j==null?void 0:j.id]}),t.invalidateQueries({queryKey:["event-leaderboard"]}),t.invalidateQueries({queryKey:["admin-agent-points"]}),Ne!=null&&Ne.message?he.success(Ne.message):he.success(`Synced ${Ne.synced||0} attendees. ${Ne.points_awarded||0} points awarded!`)},onError:Ne=>{he.error("Failed to sync attendees: "+Ne.message)}}),ve=Pt({mutationFn:async()=>{const{data:Ne,error:$e}=await V.functions.invoke("zoom-retry-registrations",{body:{}});if($e)throw $e;return Ne},onSuccess:Ne=>{t.invalidateQueries({queryKey:["event-registrations-details",j==null?void 0:j.id]}),t.invalidateQueries({queryKey:["event-registrations-count"]}),he.success(`Retry complete: ${(Ne==null?void 0:Ne.successCount)??0} fixed, ${(Ne==null?void 0:Ne.failCount)??0} still failing, ${(Ne==null?void 0:Ne.rateLimitedCount)??0} rate-limited`)},onError:Ne=>{he.error("Retry failed: "+Ne.message)}}),We=Pt({mutationFn:async({eventId:Ne,testMode:$e})=>{const{data:{session:it}}=await V.auth.getSession();if(!it)throw new Error("Not authenticated");const Je=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/send-event-reminder",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${it.access_token}`},body:JSON.stringify({event_id:Ne,test_mode:$e})}),st=await Je.json();if(!Je.ok)throw new Error(st.error||"Failed to send reminders");return st},onSuccess:Ne=>{Ne.test?he.success(Ne.message||"Test email sent!"):he.success(Ne.message||`Reminder emails sent to ${Ne.sent} registrants!`)},onError:Ne=>{he.error("Failed to send reminders: "+Ne.message)}}),{data:Ve}=yt({queryKey:["all-profiles-for-linking"],queryFn:async()=>{let Ne=[],$e=0;const it=1e3;for(;;){const{data:Je,error:st}=await V.from("profiles").select("id, name, email").order("name",{ascending:!0}).range($e,$e+it-1);if(st)throw st;if(!Je||Je.length===0||(Ne=[...Ne,...Je],Je.length{const{error:st}=await V.from("event_attendees").update({user_id:$e}).eq("id",Ne);if(st)throw st;if(Je&&it){const{error:wt}=await V.from("zoom_email_aliases").upsert({user_id:$e,zoom_email:it.toLowerCase()},{onConflict:"zoom_email"});wt&&console.error("Failed to save alias:",wt)}const mt=j==null?void 0:j.id;if(mt){const{data:wt}=await V.from("user_roles").select("id").eq("user_id",$e).eq("role","admin").single();if(!wt){const{data:at}=await V.from("agent_points").select("id").eq("user_id",$e).eq("event_id",mt).single();at||(await V.rpc("award_attendance_points",{p_user_id:$e,p_event_id:mt,p_points:10,p_reason:"Event Attendance (Manual Link)"}),await V.rpc("check_and_award_badges",{p_user_id:$e}))}}return{userId:$e,zoomEmail:it,shouldSaveAlias:Je}},onSuccess:Ne=>{t.invalidateQueries({queryKey:["event-attendees-details",j==null?void 0:j.id]}),t.invalidateQueries({queryKey:["event-leaderboard"]}),t.invalidateQueries({queryKey:["admin-agent-points"]});let $e="Attendee linked and points awarded!";Ne.shouldSaveAlias&&Ne.zoomEmail&&($e+=` Email "${Ne.zoomEmail}" will be auto-matched in the future.`),he.success($e),E(!1),D(null),z(null),Z("")},onError:Ne=>{he.error("Failed to link attendee: "+Ne.message)}}),Me=Ne=>{D(Ne),z(null),$(!0),Z(""),E(!0)},ze=()=>{!A||!R||Le.mutate({attendeeId:A.id,userId:R,zoomEmail:A.zoom_email,shouldSaveAlias:O})},Pe=(Ve==null?void 0:Ve.filter(Ne=>{var it,Je;if(!ee)return!0;const $e=ee.toLowerCase();return((it=Ne.name)==null?void 0:it.toLowerCase().includes($e))||((Je=Ne.email)==null?void 0:Je.toLowerCase().includes($e))}))||[],Ie=async Ne=>{const $e=Ne.name.split(".").pop(),Je=`${`${crypto.randomUUID()}.${$e}`}`,{error:st}=await V.storage.from("event-images").upload(Je,Ne);if(st)throw st;const{data:{publicUrl:mt}}=V.storage.from("event-images").getPublicUrl(Je);return mt},De=Ne=>{var it;const $e=(it=Ne.target.files)==null?void 0:it[0];if($e){if($e.size>5*1024*1024){he.error("Image must be less than 5MB");return}d($e),m(URL.createObjectURL($e))}},pe=()=>{d(null),m(null),o({...l,image_url:""}),y.current&&(y.current.value="")},tt=Pt({mutationFn:async Ne=>{x(!0);let $e=Ne.image_url;c&&($e=await Ie(c)||"");const it=new Date(Ne.event_date),[Je,st]=Ne.event_time.split(":");it.setHours(parseInt(Je),parseInt(st));const mt=[new Date(it)];if(Ne.is_recurring&&Ne.recurrence_end_date){let Et=new Date(it);for(;Ne.recurrence_pattern==="weekly"?Et=DT(Et,1):Ne.recurrence_pattern==="biweekly"?Et=DT(Et,2):Et=wg(Et,1),!(Et>Ne.recurrence_end_date);)mt.push(new Date(Et))}const wt=mt.map(Et=>({title:Ne.title,description:Ne.description||null,image_url:$e||null,video_url:Ne.video_url||null,event_date:Et.toISOString(),zoom_link:Ne.zoom_link,zoom_meeting_id:Ne.zoom_meeting_id||null,capacity:Ne.capacity?parseInt(Ne.capacity):null,is_published:Ne.is_published})),{data:at,error:rt}=await V.from("events").insert(wt).select();if(rt)throw rt;return at&&at.length>0&&acs(Ne.title,at[0].id),mt.length},onSuccess:Ne=>{t.invalidateQueries({queryKey:["admin-events"]}),he.success(Ne>1?`${Ne} recurring events created successfully`:"Event created successfully"),n(!1),o(kq),d(null),m(null),x(!1)},onError:Ne=>{he.error("Failed to create event: "+Ne.message),x(!1)}}),ge=Pt({mutationFn:async({id:Ne,data:$e})=>{x(!0);let it=$e.image_url;c&&(it=await Ie(c)||"");const Je=new Date($e.event_date),[st,mt]=$e.event_time.split(":");Je.setHours(parseInt(st),parseInt(mt));const{error:wt}=await V.from("events").update({title:$e.title,description:$e.description||null,image_url:it||null,video_url:$e.video_url||null,event_date:Je.toISOString(),zoom_link:$e.zoom_link,zoom_meeting_id:$e.zoom_meeting_id||null,capacity:$e.capacity?parseInt($e.capacity):null,is_published:$e.is_published}).eq("id",Ne);if(wt)throw wt},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-events"]}),he.success("Event updated successfully"),n(!1),i(null),o(kq),d(null),m(null),x(!1)},onError:Ne=>{he.error("Failed to update event: "+Ne.message),x(!1)}}),ct=Pt({mutationFn:async Ne=>{const{error:$e}=await V.from("events").delete().eq("id",Ne);if($e)throw $e},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-events"]}),he.success("Event deleted successfully")},onError:Ne=>{he.error("Failed to delete event: "+Ne.message)}}),Ue=Ne=>{var it;const $e=new Date(Ne.event_date);i(Ne),o({title:Ne.title,description:Ne.description||"",image_url:Ne.image_url||"",video_url:Ne.video_url||"",event_date:$e,event_time:As($e,"HH:mm"),zoom_link:Ne.zoom_link,zoom_meeting_id:Ne.zoom_meeting_id||"",capacity:((it=Ne.capacity)==null?void 0:it.toString())||"",is_published:Ne.is_published,is_recurring:!1,recurrence_pattern:"weekly",recurrence_end_date:void 0}),m(Ne.image_url||null),d(null),n(!0)},et=Ne=>{if(Ne.preventDefault(),!l.event_date){he.error("Please select a date");return}if(l.is_recurring&&!l.recurrence_end_date){he.error("Please select an end date for recurring events");return}a?ge.mutate({id:a.id,data:l}):tt.mutate(l)},Qe=()=>{n(!1),i(null),o(kq),d(null),m(null)};return e.jsx("div",{className:"min-h-screen bg-background p-6",children:e.jsxs("div",{className:"max-w-6xl mx-auto",children:[e.jsxs("div",{className:"flex items-center gap-4 mb-6",children:[e.jsx(H,{variant:"ghost",size:"icon",onClick:()=>s("/dashboard"),children:e.jsx(za,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Event Management"}),e.jsx("p",{className:"text-muted-foreground",children:"Create and manage upcoming events"})]})]}),e.jsxs(ke,{className:"mb-6",children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between",children:[e.jsx(zt,{children:"All Events"}),e.jsxs(bs,{open:r,onOpenChange:Ne=>!Ne&&Qe(),children:[e.jsx(Qi,{asChild:!0,children:e.jsxs(H,{onClick:()=>n(!0),children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Add Event"]})}),e.jsxs(vs,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(Cs,{children:e.jsx(Ns,{children:a?"Edit Event":"Create New Event"})}),e.jsxs("form",{onSubmit:et,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"title",children:"Title *"}),e.jsx(Se,{id:"title",value:l.title,onChange:Ne=>o({...l,title:Ne.target.value}),placeholder:"Event title",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Description"}),e.jsx(R1,{content:l.description,onChange:Ne=>o({...l,description:Ne}),placeholder:"Event description",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Event Image"}),e.jsx("input",{type:"file",ref:y,accept:"image/*",onChange:De,className:"hidden"}),h?e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:h,alt:"Event preview",className:"w-full h-32 object-cover rounded-lg border"}),e.jsx(H,{type:"button",variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-6 w-6",onClick:pe,children:e.jsx(Rr,{className:"h-4 w-4"})})]}):e.jsxs(H,{type:"button",variant:"outline",className:"w-full h-32 border-dashed flex flex-col gap-2",onClick:()=>{var Ne;return(Ne=y.current)==null?void 0:Ne.click()},children:[e.jsx(Ea,{className:"h-6 w-6"}),e.jsx("span",{className:"text-sm",children:"Click to upload image"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Date *"}),e.jsxs(gl,{children:[e.jsx(xl,{asChild:!0,children:e.jsxs(H,{variant:"outline",className:Ft("w-full justify-start text-left font-normal",!l.event_date&&"text-muted-foreground"),children:[e.jsx(Nn,{className:"mr-2 h-4 w-4"}),l.event_date?As(l.event_date,"PPP"):"Pick a date"]})}),e.jsx(il,{className:"w-auto p-0",align:"start",children:e.jsx(g0,{mode:"single",selected:l.event_date,onSelect:Ne=>o({...l,event_date:Ne}),initialFocus:!0,className:"p-3 pointer-events-auto"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"time",children:"Time *"}),e.jsx(Se,{id:"time",type:"time",value:l.event_time,onChange:Ne=>o({...l,event_time:Ne.target.value}),required:!0})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"zoom_link",children:"Zoom Link *"}),e.jsx(Se,{id:"zoom_link",value:l.zoom_link,onChange:Ne=>o({...l,zoom_link:Ne.target.value}),placeholder:"https://zoom.us/j/...",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"zoom_meeting_id",children:"Zoom Meeting ID (for API registration)"}),e.jsx(Se,{id:"zoom_meeting_id",value:l.zoom_meeting_id,onChange:Ne=>o({...l,zoom_meeting_id:Ne.target.value}),placeholder:"e.g., 1234567890 (find in Zoom dashboard)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Optional: Enter the numeric meeting ID for automatic Zoom registration"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"video_url",children:"Promo Video URL (optional)"}),e.jsx(Se,{id:"video_url",value:l.video_url,onChange:Ne=>o({...l,video_url:Ne.target.value}),placeholder:"YouTube, Vimeo, or Bunny.net embed URL"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Add a preview/promo video for this event"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"capacity",children:"Capacity (optional)"}),e.jsx(Se,{id:"capacity",type:"number",value:l.capacity,onChange:Ne=>o({...l,capacity:Ne.target.value}),placeholder:"Leave empty for unlimited",min:"1"})]}),!a&&e.jsxs("div",{className:"space-y-3 rounded-lg border p-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(CF,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(ue,{htmlFor:"is_recurring",children:"Recurring Event"})]}),e.jsx(Or,{id:"is_recurring",checked:l.is_recurring,onCheckedChange:Ne=>o({...l,is_recurring:Ne})})]}),l.is_recurring&&e.jsxs("div",{className:"space-y-3 pt-1",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Frequency"}),e.jsxs(Bs,{value:l.recurrence_pattern,onValueChange:Ne=>o({...l,recurrence_pattern:Ne}),children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"weekly",children:"Weekly"}),e.jsx(pt,{value:"biweekly",children:"Every 2 Weeks"}),e.jsx(pt,{value:"monthly",children:"Monthly"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Repeat Until"}),e.jsxs(gl,{children:[e.jsx(xl,{asChild:!0,children:e.jsxs(H,{variant:"outline",className:Ft("w-full justify-start text-left font-normal",!l.recurrence_end_date&&"text-muted-foreground"),children:[e.jsx(Nn,{className:"mr-2 h-4 w-4"}),l.recurrence_end_date?As(l.recurrence_end_date,"PPP"):"Pick end date"]})}),e.jsx(il,{className:"w-auto p-0",align:"start",children:e.jsx(g0,{mode:"single",selected:l.recurrence_end_date,onSelect:Ne=>o({...l,recurrence_end_date:Ne}),disabled:Ne=>Ne<(l.event_date||new Date),initialFocus:!0,className:"p-3 pointer-events-auto"})})]})]}),l.event_date&&l.recurrence_end_date&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["This will create ",(()=>{let Ne=1,$e=new Date(l.event_date);for(;$e=l.recurrence_pattern==="weekly"?DT($e,1):l.recurrence_pattern==="biweekly"?DT($e,2):wg($e,1),!($e>l.recurrence_end_date);)Ne++;return Ne})()," events with the same Zoom link"]})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ue,{htmlFor:"is_published",children:"Published"}),e.jsx(Or,{id:"is_published",checked:l.is_published,onCheckedChange:Ne=>o({...l,is_published:Ne})})]}),e.jsxs("div",{className:"flex gap-2 pt-4",children:[e.jsx(H,{type:"button",variant:"outline",onClick:Qe,className:"flex-1",children:"Cancel"}),e.jsx(H,{type:"submit",className:"flex-1",disabled:tt.isPending||ge.isPending||p,children:p?"Uploading...":a?"Update Event":l.is_recurring&&l.event_date&&l.recurrence_end_date?"Create Recurring Events":"Create Event"})]})]})]})]})]}),e.jsx(Oe,{children:K?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading events..."}):(J==null?void 0:J.length)===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No events yet. Create your first event!"}):e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Vs,{children:[e.jsx(At,{children:"Title"}),e.jsx(At,{children:"Date & Time"}),e.jsx(At,{children:"Registrations"}),e.jsx(At,{children:"Status"}),e.jsx(At,{className:"text-right",children:"Actions"})]})}),e.jsx(da,{children:J==null?void 0:J.map(Ne=>e.jsxs(Vs,{children:[e.jsx(gt,{className:"font-medium",children:Ne.title}),e.jsx(gt,{children:As(new Date(Ne.event_date),"PPP p")}),e.jsx(gt,{children:e.jsxs(H,{variant:"ghost",size:"sm",className:"gap-1",onClick:()=>be(Ne),children:[e.jsx(Ar,{className:"h-4 w-4"}),(re==null?void 0:re[Ne.id])||0,Ne.capacity&&` / ${Ne.capacity}`]})}),e.jsx(gt,{children:e.jsx("span",{className:Ft("px-2 py-1 rounded-full text-xs font-medium",Ne.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:Ne.is_published?"Published":"Draft"})}),e.jsx(gt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(H,{variant:"ghost",size:"icon",onClick:()=>window.open(Ne.zoom_link,"_blank"),title:"Open Zoom Link",children:e.jsx(gn,{className:"h-4 w-4"})}),e.jsx(H,{variant:"ghost",size:"icon",onClick:()=>Ue(Ne),children:e.jsx(ni,{className:"h-4 w-4"})}),e.jsx(H,{variant:"ghost",size:"icon",onClick:()=>{confirm("Are you sure you want to delete this event?")&&ct.mutate(Ne.id)},children:e.jsx(Dr,{className:"h-4 w-4 text-destructive"})})]})})]},Ne.id))})]})})]}),e.jsx(bs,{open:_,onOpenChange:b,children:e.jsxs(vs,{className:"max-w-3xl max-h-[80vh] overflow-y-auto",children:[e.jsxs(Cs,{children:[e.jsxs(Ns,{className:"flex items-center gap-2",children:[e.jsx(Ar,{className:"h-5 w-5"}),j==null?void 0:j.title]}),e.jsx(nn,{children:"View registrations and attendees for this event"})]}),e.jsxs("div",{className:"flex items-center justify-end mb-4 gap-2 flex-wrap",children:[e.jsxs(H,{variant:"ghost",size:"sm",onClick:()=>We.mutate({eventId:j.id,testMode:!0}),disabled:We.isPending,children:[e.jsx(er,{className:Ft("h-4 w-4 mr-2",We.isPending&&"animate-spin")}),"Send Test to Me"]}),e.jsxs(H,{variant:"outline",size:"sm",onClick:()=>We.mutate({eventId:j.id}),disabled:We.isPending||!(ie!=null&&ie.length),children:[e.jsx(er,{className:Ft("h-4 w-4 mr-2",We.isPending&&"animate-spin")}),We.isPending?"Sending...":"Send Reminder to All"]}),(j==null?void 0:j.zoom_meeting_id)&&e.jsxs(e.Fragment,{children:[e.jsxs(H,{variant:"outline",size:"sm",onClick:()=>fe.mutate(j.id),disabled:fe.isPending,children:[e.jsx(po,{className:Ft("h-4 w-4 mr-2",fe.isPending&&"animate-spin")}),fe.isPending?"Syncing...":"Sync Registrations"]}),e.jsxs(H,{variant:"outline",size:"sm",onClick:()=>ve.mutate(),disabled:ve.isPending,children:[e.jsx(po,{className:Ft("h-4 w-4 mr-2",ve.isPending&&"animate-spin")}),ve.isPending?"Retrying...":"Retry Failed Registrations"]}),e.jsxs(H,{variant:"default",size:"sm",onClick:()=>je.mutate(j.id),disabled:je.isPending,children:[e.jsx(To,{className:Ft("h-4 w-4 mr-2",je.isPending&&"animate-spin")}),je.isPending?"Syncing...":"Sync Attendees & Award Points"]})]})]}),e.jsxs(ta,{defaultValue:"registrations",className:"w-full",children:[e.jsxs(Qn,{className:"grid w-full grid-cols-2",children:[e.jsxs(ts,{value:"registrations",className:"gap-2",children:[e.jsx(Ar,{className:"h-4 w-4"}),"Registrations (",(ie==null?void 0:ie.length)||0,")"]}),e.jsxs(ts,{value:"attendees",className:"gap-2",children:[e.jsx(ea,{className:"h-4 w-4"}),"Attendees (",(ne==null?void 0:ne.length)||0,")"]})]}),e.jsx(cs,{value:"registrations",className:"mt-4",children:ce?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading registrations..."}):(ie==null?void 0:ie.length)===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx("p",{children:"No registrations yet for this event."}),(j==null?void 0:j.zoom_meeting_id)&&e.jsx("p",{className:"text-xs mt-2",children:'Click "Sync Registrations" to import from Zoom.'})]}):e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Vs,{children:[e.jsx(At,{children:"Name"}),e.jsx(At,{children:"Email"}),e.jsx(At,{children:"Registered"}),e.jsx(At,{children:"Status"})]})}),e.jsx(da,{children:ie==null?void 0:ie.map(Ne=>{var st,mt;const $e=((st=Ne.profiles)==null?void 0:st.name)||Ne.zoom_name||"Unknown",it=((mt=Ne.profiles)==null?void 0:mt.email)||Ne.zoom_email||null,Je=!Ne.user_id;return e.jsxs(Vs,{children:[e.jsx(gt,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2",children:[$e,Je&&e.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-muted text-muted-foreground",children:"External"})]})}),e.jsx(gt,{children:it?e.jsxs("a",{href:`mailto:${it}`,className:"flex items-center gap-1 text-primary hover:underline",children:[e.jsx(er,{className:"h-3 w-3"}),it]}):e.jsx("span",{className:"text-muted-foreground",children:"No email"})}),e.jsx(gt,{className:"text-muted-foreground text-sm",children:As(new Date(Ne.registered_at),"MMM d, yyyy h:mm a")}),e.jsx(gt,{children:Ne.zoom_join_url?e.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"}):e.jsx("span",{className:"inline-flex items-center gap-1 text-xs px-2 py-1 rounded-full bg-muted text-muted-foreground",children:"Pending"})})]},Ne.id)})})]})}),e.jsx(cs,{value:"attendees",className:"mt-4",children:le?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading attendees..."}):(ne==null?void 0:ne.length)===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx("p",{children:"No attendees recorded yet."}),(j==null?void 0:j.zoom_meeting_id)&&e.jsx("p",{className:"text-xs mt-2",children:'Click "Sync Attendees & Award Points" after the event ends to import actual participants from Zoom.'})]}):e.jsxs(e.Fragment,{children:[(ne==null?void 0:ne.filter(Ne=>!Ne.user_id).length)>0&&e.jsxs("div",{className:"mb-6 p-4 border border-amber-200 bg-amber-50 dark:border-amber-800 dark:bg-amber-950 rounded-lg",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(wo,{className:"h-4 w-4 text-amber-600 dark:text-amber-400"}),e.jsxs("h4",{className:"font-medium text-amber-800 dark:text-amber-200",children:["Unmatched Attendees (",ne==null?void 0:ne.filter(Ne=>!Ne.user_id).length,")"]})]}),e.jsx("p",{className:"text-xs text-amber-700 dark:text-amber-300 mb-3",children:"These attendees couldn't be matched to a profile. Link them to award points."}),e.jsx("div",{className:"space-y-2",children:ne==null?void 0:ne.filter(Ne=>!Ne.user_id).map(Ne=>e.jsxs("div",{className:"flex items-center justify-between p-2 bg-background rounded border",children:[e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"font-medium text-sm",children:Ne.zoom_name||"Unknown"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Ne.zoom_email||"No email"})]}),e.jsxs(H,{variant:"outline",size:"sm",onClick:()=>Me(Ne),className:"gap-1",children:[e.jsx(ql,{className:"h-3 w-3"}),"Link to Profile"]})]},Ne.id))})]}),e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Vs,{children:[e.jsx(At,{children:"Name"}),e.jsx(At,{children:"Email"}),e.jsx(At,{children:"Duration"}),e.jsx(At,{children:"Points"})]})}),e.jsx(da,{children:ne==null?void 0:ne.filter(Ne=>Ne.user_id).map(Ne=>{var Je,st;const $e=((Je=Ne.profiles)==null?void 0:Je.name)||Ne.zoom_name||"Unknown",it=((st=Ne.profiles)==null?void 0:st.email)||Ne.zoom_email||null;return e.jsxs(Vs,{children:[e.jsx(gt,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2",children:[$e,Ne.manually_added&&e.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200",children:"Manual"})]})}),e.jsx(gt,{children:it?e.jsxs("a",{href:`mailto:${it}`,className:"flex items-center gap-1 text-primary hover:underline",children:[e.jsx(er,{className:"h-3 w-3"}),it]}):e.jsx("span",{className:"text-muted-foreground",children:"No email"})}),e.jsx(gt,{children:Ne.duration_minutes?e.jsxs("span",{className:"flex items-center gap-1 text-muted-foreground text-sm",children:[e.jsx(Pn,{className:"h-3 w-3"}),Ne.duration_minutes," min"]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsx(gt,{children:Ne.points_awarded?e.jsxs("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:[e.jsx(To,{className:"h-3 w-3"}),"+10 pts"]}):e.jsx("span",{className:"inline-flex items-center gap-1 text-xs px-2 py-1 rounded-full bg-muted text-muted-foreground",children:"Pending"})})]},Ne.id)})})]})]})})]})]})}),e.jsx(bs,{open:T,onOpenChange:E,children:e.jsxs(vs,{className:"max-w-md",children:[e.jsxs(Cs,{children:[e.jsxs(Ns,{className:"flex items-center gap-2",children:[e.jsx(ql,{className:"h-5 w-5"}),"Link Attendee to Profile"]}),e.jsx(nn,{children:"Link this Zoom attendee to an existing member profile to award them points."})]}),A&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"p-3 bg-muted rounded-lg",children:[e.jsx("p",{className:"text-sm font-medium",children:A.zoom_name||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:A.zoom_email||"No email"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Search for a profile"}),e.jsxs("div",{className:"relative",children:[e.jsx(Mn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Se,{placeholder:"Search by name or email...",value:ee,onChange:Ne=>Z(Ne.target.value),className:"pl-9"})]})]}),e.jsx("div",{className:"max-h-48 overflow-y-auto border rounded-md",children:Pe.length===0?e.jsx("div",{className:"p-4 text-center text-sm text-muted-foreground",children:"No profiles found"}):e.jsx("div",{className:"divide-y",children:Pe.slice(0,20).map(Ne=>e.jsxs("button",{type:"button",onClick:()=>z(Ne.id),className:Ft("w-full p-3 text-left hover:bg-muted/50 transition-colors",R===Ne.id&&"bg-primary/10 border-l-2 border-primary"),children:[e.jsx("p",{className:"text-sm font-medium",children:Ne.name||"Unnamed"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Ne.email})]},Ne.id))})}),A.zoom_email&&e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(ao,{id:"save-alias",checked:O,onCheckedChange:Ne=>$(Ne)}),e.jsx("label",{htmlFor:"save-alias",className:"text-sm text-muted-foreground cursor-pointer",children:"Remember this email for future auto-matching"})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(H,{variant:"outline",onClick:()=>E(!1),children:"Cancel"}),e.jsx(H,{onClick:ze,disabled:!R||Le.isPending,children:Le.isPending?"Linking...":"Link & Award Points"})]})]})]})})]})})}function ccs({selectedKitIds:s,onChange:t}){const[r,n]=S.useState(""),[a,i]=S.useState(!1),{data:l=[]}=yt({queryKey:["all-resource-kits-picker"],queryFn:async()=>{const{data:m,error:p}=await V.from("resource_kits").select("id, name, featured_image_url").eq("is_published",!0).order("name");if(p)throw p;return m}}),o=l.filter(m=>s.includes(m.id)),c=l.filter(m=>!s.includes(m.id)&&m.name.toLowerCase().includes(r.toLowerCase())),d=m=>{t([...s,m])},h=m=>{t(s.filter(p=>p!==m))};return e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ue,{className:"flex items-center gap-2",children:[e.jsx(yc,{className:"h-4 w-4"}),"Linked Toolkits"]}),o.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:o.map(m=>e.jsxs(Xe,{variant:"secondary",className:"gap-1 pr-1",children:[m.name,e.jsx("button",{type:"button",onClick:()=>h(m.id),className:"ml-1 rounded-full hover:bg-muted-foreground/20 p-0.5",children:e.jsx(Rr,{className:"h-3 w-3"})})]},m.id))}),e.jsxs(gl,{open:a,onOpenChange:i,children:[e.jsx(xl,{asChild:!0,children:e.jsxs(H,{type:"button",variant:"outline",size:"sm",className:"gap-1",children:[e.jsx(yc,{className:"h-3.5 w-3.5"}),"Add Toolkit"]})}),e.jsxs(il,{className:"w-80 p-2",align:"start",children:[e.jsxs("div",{className:"relative mb-2",children:[e.jsx(Mn,{className:"absolute left-2 top-2.5 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(Se,{placeholder:"Search toolkits...",value:r,onChange:m=>n(m.target.value),className:"pl-7 h-8 text-sm"})]}),e.jsx("div",{className:"max-h-48 overflow-y-auto space-y-0.5",children:c.length===0?e.jsx("p",{className:"text-xs text-muted-foreground text-center py-3",children:r?"No toolkits found":"All toolkits selected"}):c.map(m=>e.jsxs("button",{type:"button",onClick:()=>{d(m.id),n("")},className:"w-full flex items-center gap-2 px-2 py-1.5 rounded-md hover:bg-muted text-left text-sm transition-colors",children:[m.featured_image_url?e.jsx("img",{src:m.featured_image_url,alt:"",className:"w-8 h-8 rounded object-cover flex-shrink-0"}):e.jsx("div",{className:"w-8 h-8 rounded bg-muted flex items-center justify-center flex-shrink-0",children:e.jsx(yc,{className:"h-3.5 w-3.5 text-muted-foreground"})}),e.jsx("span",{className:"truncate",children:m.name})]},m.id))})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Link toolkits that agents can download alongside this template."})]})}const dcs=()=>{const{user:s}=Ms(),{toast:t}=li(),r=ns(),[n,a]=Ed(),[i,l]=S.useState(!1),[o,c]=S.useState(null),[d,h]=S.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:""}),[m,p]=S.useState(null),[x,y]=S.useState(0),[_,b]=S.useState(!1),[j,k]=S.useState(null),[T,E]=S.useState(""),[A,D]=S.useState([]),[R,z]=S.useState(""),[O,$]=S.useState(""),[ee,Z]=S.useState(!1),[J,K]=S.useState(!1),{data:re=[]}=yt({queryKey:["template-categories"],queryFn:async()=>{const{data:Ue,error:et}=await V.from("template_categories").select("*").order("name");if(et)throw et;return Ue}}),{data:ie=[]}=yt({queryKey:["template-types"],queryFn:async()=>{const{data:Ue,error:et}=await V.from("template_types").select("*").order("name");if(et)throw et;return Ue}}),{data:ce=[],isLoading:ne}=yt({queryKey:["canva-templates-admin"],queryFn:async()=>{const{data:Ue,error:et}=await V.from("canva_templates").select(` *, category:template_categories(id, name), type:template_types(id, name) `).order("publish_date",{ascending:!1});if(et)throw et;const{data:Qe,error:Ne}=await V.from("template_links").select("*").order("sort_order");if(Ne)throw Ne;const{data:$e,error:it}=await V.from("template_guides").select("*").order("sort_order");if(it)throw it;return Ue.map(st=>({...st,links:(Qe==null?void 0:Qe.filter(mt=>mt.template_id===st.id))||[],guides:($e==null?void 0:$e.filter(mt=>mt.template_id===st.id))||[]}))}});S.useEffect(()=>{const Ue=n.get("edit");if(Ue&&ce.length>0){const et=ce.find(Qe=>Qe.id===Ue);et&&(Ve(et),a({},{replace:!0}))}},[ce,n]);const le=Pt({mutationFn:async Ue=>{const{data:et,error:Qe}=await V.from("template_categories").insert({name:Ue}).select().single();if(Qe)throw Qe;return et},onSuccess:Ue=>{r.invalidateQueries({queryKey:["template-categories"]}),h({...d,category_id:Ue.id}),z(""),Z(!1),t({title:"Category added"})},onError:Ue=>{t({title:"Error adding category",description:Ue.message,variant:"destructive"})}}),be=Pt({mutationFn:async Ue=>{const{data:et,error:Qe}=await V.from("template_types").insert({name:Ue}).select().single();if(Qe)throw Qe;return et},onSuccess:Ue=>{r.invalidateQueries({queryKey:["template-types"]}),h({...d,type_id:Ue.id}),$(""),K(!1),t({title:"Type added"})},onError:Ue=>{t({title:"Error adding type",description:Ue.message,variant:"destructive"})}}),fe=Pt({mutationFn:async Ue=>{var it;let et=Ue.existingImageUrl;if(Ue.image){const Je=Ue.image.name.split(".").pop(),st=`${Date.now()}-${Math.random().toString(36).substring(7)}.${Je}`,{error:mt}=await V.storage.from("template-previews").upload(st,Ue.image);if(mt)throw mt;const{data:wt}=V.storage.from("template-previews").getPublicUrl(st);et=wt.publicUrl}const Qe={name:Ue.template.name,description:Ue.template.description||null,category_id:Ue.template.category_id||null,type_id:Ue.template.type_id||null,preview_image_url:et,video_url:Ue.videoUrl||null,publish_date:Ue.template.publish_date?new Date(Ue.template.publish_date).toISOString():new Date().toISOString(),created_by:s==null?void 0:s.id};let Ne=Ue.templateId;if(Ne){const{error:Je}=await V.from("canva_templates").update(Qe).eq("id",Ne);if(Je)throw Je;const{error:st}=await V.from("template_links").delete().eq("template_id",Ne);if(st)throw st;const mt=((it=Ue.existingGuides)==null?void 0:it.map(rt=>rt.id).filter(Boolean))||[],wt=Ue.template.guides.map(rt=>rt.id).filter(Boolean),at=mt.filter(rt=>!wt.includes(rt));at.length>0&&await V.from("template_guides").delete().in("id",at)}else{const{data:Je,error:st}=await V.from("canva_templates").insert(Qe).select().single();if(st)throw st;Ne=Je.id,rcs(Ue.template.name,Je.id)}const $e=Ue.template.links.filter(Je=>Je.title.trim()&&Je.canva_share_link.trim());if($e.length>0){const Je=$e.map((mt,wt)=>({template_id:Ne,title:mt.title.trim(),canva_share_link:mt.canva_share_link.trim(),sort_order:wt})),{error:st}=await V.from("template_links").insert(Je);if(st)throw st}for(let Je=0;Je0)){const{error:Je}=await V.from("resource_kit_templates").insert(Ue.linkedKitIds.map(st=>({template_id:Ne,kit_id:st})));if(Je)throw Je}},onSuccess:()=>{r.invalidateQueries({queryKey:["canva-templates-admin"]}),r.invalidateQueries({queryKey:["canva-templates"]}),We(),l(!1),t({title:o?"Template updated":"Template created"})},onError:Ue=>{t({title:"Error saving template",description:Ue.message,variant:"destructive"})}}),je=Pt({mutationFn:async Ue=>{const{error:et}=await V.from("canva_templates").delete().eq("id",Ue);if(et)throw et},onSuccess:()=>{r.invalidateQueries({queryKey:["canva-templates-admin"]}),r.invalidateQueries({queryKey:["canva-templates"]}),t({title:"Template deleted"})},onError:Ue=>{t({title:"Error deleting template",description:Ue.message,variant:"destructive"})}}),ve=Pt({mutationFn:async({id:Ue,is_featured:et})=>{const{error:Qe}=await V.from("canva_templates").update({is_featured:et}).eq("id",Ue);if(Qe)throw Qe},onSuccess:()=>{r.invalidateQueries({queryKey:["canva-templates-admin"]}),r.invalidateQueries({queryKey:["canva-templates"]})},onError:Ue=>{t({title:"Error updating featured",description:Ue.message,variant:"destructive"})}}),We=()=>{h({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:""}),k(null),E(""),c(null),Z(!1),K(!1),z(""),$(""),p(null),y(0),b(!1),D([])},Ve=async Ue=>{var Qe;c(Ue),h({name:Ue.name,description:Ue.description||"",category_id:Ue.category_id||"",type_id:Ue.type_id||"",publish_date:Ue.publish_date?new Date(Ue.publish_date).toISOString().split("T")[0]:new Date().toISOString().split("T")[0],links:Ue.links&&Ue.links.length>0?Ue.links.map(Ne=>({id:Ne.id,title:Ne.title,canva_share_link:Ne.canva_share_link,sort_order:Ne.sort_order})):[{title:"",canva_share_link:"",sort_order:0}],guides:((Qe=Ue.guides)==null?void 0:Qe.map(Ne=>({id:Ne.id,name:Ne.name,file_url:Ne.file_url,file_type:Ne.file_type,file_size:Ne.file_size,sort_order:Ne.sort_order})))||[],video_url:Ue.video_url||""}),E(Ue.preview_image_url||""),p(null);const{data:et}=await V.from("resource_kit_templates").select("kit_id").eq("template_id",Ue.id);D((et||[]).map(Ne=>Ne.kit_id)),l(!0)},Le=Ue=>{var Qe;const et=(Qe=Ue.target.files)==null?void 0:Qe[0];et&&(k(et),E(URL.createObjectURL(et)))},Me=()=>{h({...d,links:[...d.links,{title:"",canva_share_link:"",sort_order:d.links.length}]})},ze=Ue=>{if(d.links.length<=1)return;const et=d.links.filter((Qe,Ne)=>Ne!==Ue);h({...d,links:et})},Pe=(Ue,et,Qe)=>{const Ne=[...d.links];Ne[Ue]={...Ne[Ue],[et]:Qe},h({...d,links:Ne})},Ie=Ue=>{const et=Ue.target.files;if(!et)return;const Qe=Array.from(et).map((Ne,$e)=>({name:Ne.name.replace(/\.[^/.]+$/,""),file_url:"",file_type:Ne.type,file_size:Ne.size,sort_order:d.guides.length+$e,file:Ne}));h({...d,guides:[...d.guides,...Qe]}),Ue.target.value=""},De=Ue=>{const et=d.guides.filter((Qe,Ne)=>Ne!==Ue);h({...d,guides:et})},pe=(Ue,et)=>{const Qe=[...d.guides];Qe[Ue]={...Qe[Ue],name:et},h({...d,guides:Qe})},tt=async()=>{if(!m)return null;b(!0),y(0);try{const{data:Ue,error:et}=await V.functions.invoke("bunny-upload",{body:{action:"create",title:d.name||m.name}});if(et)throw new Error(et.message);const{videoId:Qe,libraryId:Ne}=Ue,{data:$e,error:it}=await V.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:Qe}});if(it)throw new Error(it.message);const Je=new XMLHttpRequest;return await new Promise((mt,wt)=>{Je.upload.addEventListener("progress",at=>{if(at.lengthComputable){const rt=Math.round(at.loaded/at.total*100);y(rt)}}),Je.addEventListener("load",()=>{Je.status>=200&&Je.status<300?mt():wt(new Error(`Upload failed with status ${Je.status}`))}),Je.addEventListener("error",()=>wt(new Error("Upload failed"))),Je.open("PUT",$e.uploadUrl),Je.setRequestHeader("AccessKey",$e.apiKey),Je.send(m)}),`https://player.mediadelivery.net/embed/${Ne}/${Qe}`}catch(Ue){return console.error("Bunny upload error:",Ue),t({title:"Video upload failed",description:Ue instanceof Error?Ue.message:"Unknown error",variant:"destructive"}),null}finally{b(!1)}},ge=Ue=>{var Qe;const et=(Qe=Ue.target.files)==null?void 0:Qe[0];et&&p(et),Ue.target.value=""},ct=async Ue=>{if(Ue.preventDefault(),!d.name.trim()){t({title:"Please enter a template name",variant:"destructive"});return}if(d.links.filter(Ne=>Ne.title.trim()&&Ne.canva_share_link.trim()).length===0){t({title:"Please add at least one Canva link",variant:"destructive"});return}let Qe=d.video_url;if(m){const Ne=await tt();if(!Ne)return;Qe=Ne}fe.mutate({template:d,image:j,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:Qe,linkedKitIds:A})};return e.jsx(Ss,{title:"Manage Templates",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(km,{title:"Manage Templates",description:"Create and manage Canva templates"}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs(ke,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsx(zt,{className:"text-sm font-medium text-muted-foreground",children:"Total Templates"})}),e.jsx(Oe,{children:e.jsx("div",{className:"text-2xl font-bold",children:ce.length})})]}),e.jsxs(ke,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsx(zt,{className:"text-sm font-medium text-muted-foreground",children:"Categories"})}),e.jsx(Oe,{children:e.jsx("div",{className:"text-2xl font-bold",children:re.length})})]}),e.jsxs(ke,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsx(zt,{className:"text-sm font-medium text-muted-foreground",children:"Template Types"})}),e.jsx(Oe,{children:e.jsx("div",{className:"text-2xl font-bold",children:ie.length})})]})]}),e.jsxs(bs,{open:i,onOpenChange:Ue=>{l(Ue),Ue||We()},children:[e.jsx(Qi,{asChild:!0,children:e.jsxs(H,{className:"gap-2",children:[e.jsx(Ys,{className:"h-4 w-4"}),"Add Template"]})}),e.jsxs(vs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Cs,{children:e.jsx(Ns,{children:o?"Edit Template":"Add New Template"})}),e.jsxs("form",{onSubmit:ct,className:"space-y-6 pt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"name",children:"Name *"}),e.jsx(Se,{id:"name",value:d.name,onChange:Ue=>h({...d,name:Ue.target.value}),placeholder:"Template name",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Description"}),e.jsx(R1,{content:d.description,onChange:Ue=>h({...d,description:Ue}),placeholder:"Brief description of the template",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ue,{children:"Canva Links *"}),e.jsxs(H,{type:"button",variant:"outline",size:"sm",onClick:Me,className:"gap-1",children:[e.jsx(Ys,{className:"h-3 w-3"}),"Add Link"]})]}),e.jsx("div",{className:"space-y-3",children:d.links.map((Ue,et)=>e.jsxs("div",{className:"flex gap-2 items-start p-3 border rounded-lg bg-muted/30",children:[e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(Se,{value:Ue.title,onChange:Qe=>Pe(et,"title",Qe.target.value),placeholder:"Link title (e.g., Instagram Post, Story)"}),e.jsx(Se,{value:Ue.canva_share_link,onChange:Qe=>Pe(et,"canva_share_link",Qe.target.value),placeholder:"https://www.canva.com/design/..."})]}),d.links.length>1&&e.jsx(H,{type:"button",variant:"ghost",size:"icon",className:"shrink-0 text-muted-foreground hover:text-destructive",onClick:()=>ze(et),children:e.jsx(Rr,{className:"h-4 w-4"})})]},et))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Category"}),ee?e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Se,{value:R,onChange:Ue=>z(Ue.target.value),placeholder:"New category name",className:"flex-1"}),e.jsx(H,{type:"button",size:"sm",onClick:()=>R.trim()&&le.mutate(R.trim()),disabled:le.isPending,children:"Add"}),e.jsx(H,{type:"button",size:"sm",variant:"ghost",onClick:()=>{Z(!1),z("")},children:e.jsx(Rr,{className:"h-4 w-4"})})]}):e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Bs,{value:d.category_id,onValueChange:Ue=>h({...d,category_id:Ue}),children:[e.jsx(Os,{className:"flex-1",children:e.jsx(Us,{placeholder:"Select category"})}),e.jsx(Fs,{children:re.map(Ue=>e.jsx(pt,{value:Ue.id,children:Ue.name},Ue.id))})]}),e.jsx(H,{type:"button",variant:"outline",size:"icon",onClick:()=>Z(!0),children:e.jsx(Ys,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Template Type"}),J?e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Se,{value:O,onChange:Ue=>$(Ue.target.value),placeholder:"New type name",className:"flex-1"}),e.jsx(H,{type:"button",size:"sm",onClick:()=>O.trim()&&be.mutate(O.trim()),disabled:be.isPending,children:"Add"}),e.jsx(H,{type:"button",size:"sm",variant:"ghost",onClick:()=>{K(!1),$("")},children:e.jsx(Rr,{className:"h-4 w-4"})})]}):e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Bs,{value:d.type_id,onValueChange:Ue=>h({...d,type_id:Ue}),children:[e.jsx(Os,{className:"flex-1",children:e.jsx(Us,{placeholder:"Select type"})}),e.jsx(Fs,{children:ie.map(Ue=>e.jsx(pt,{value:Ue.id,children:Ue.name},Ue.id))})]}),e.jsx(H,{type:"button",variant:"outline",size:"icon",onClick:()=>K(!0),children:e.jsx(Ys,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(Se,{id:"publish_date",type:"date",value:d.publish_date,onChange:Ue=>h({...d,publish_date:Ue.target.value})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Templates are sorted by publish date (newest first) on the member page"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Preview Image"}),e.jsxs("div",{className:"flex items-start gap-4",children:[T?e.jsxs("div",{className:"relative w-32 h-24 rounded-lg overflow-hidden border bg-muted",children:[e.jsx("img",{src:T,alt:"Preview",className:"w-full h-full object-cover"}),e.jsx(H,{type:"button",size:"icon",variant:"destructive",className:"absolute top-1 right-1 h-6 w-6",onClick:()=>{k(null),E("")},children:e.jsx(Rr,{className:"h-3 w-3"})})]}):e.jsx("div",{className:"w-32 h-24 rounded-lg border-2 border-dashed border-muted-foreground/25 flex items-center justify-center",children:e.jsx(wl,{className:"h-8 w-8 text-muted-foreground/50"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx(Se,{type:"file",accept:"image/*",onChange:Le,className:"cursor-pointer"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Upload a preview image for this template"})]})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(ue,{children:"Video (Optional)"}),d.video_url&&!m?e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 p-3 border rounded-lg bg-muted/30",children:[e.jsx(xn,{className:"h-5 w-5 text-primary shrink-0"}),e.jsx("span",{className:"text-sm flex-1 truncate",children:"Video uploaded"}),e.jsx(H,{type:"button",variant:"ghost",size:"sm",onClick:()=>h({...d,video_url:""}),className:"text-destructive hover:text-destructive",children:"Remove"})]}),e.jsx("div",{className:"aspect-video max-w-md rounded-lg overflow-hidden border",children:e.jsx("iframe",{src:d.video_url,className:"w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})})]}):_?e.jsxs("div",{className:"space-y-2 p-4 border rounded-lg bg-muted/30",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(is,{className:"h-4 w-4 animate-spin"}),e.jsxs("span",{className:"text-sm",children:["Uploading video... ",x,"%"]})]}),e.jsx(Mi,{value:x,className:"h-2"})]}):m?e.jsxs("div",{className:"flex items-center gap-2 p-3 border rounded-lg bg-muted/30",children:[e.jsx(xn,{className:"h-5 w-5 text-muted-foreground shrink-0"}),e.jsx("span",{className:"text-sm flex-1 truncate",children:m.name}),e.jsxs("span",{className:"text-xs text-muted-foreground shrink-0",children:[(m.size/1024/1024).toFixed(1)," MB"]}),e.jsx(H,{type:"button",variant:"ghost",size:"icon",className:"shrink-0 text-muted-foreground hover:text-destructive h-8 w-8",onClick:()=>p(null),children:e.jsx(Rr,{className:"h-4 w-4"})})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(Se,{type:"file",accept:"video/*",onChange:ge,className:"hidden"}),e.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:[e.jsx(xn,{className:"h-8 w-8 text-muted-foreground/50"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Click to upload a video"})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Upload a video to embed on the template page (Bunny.net)"})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ue,{children:"Guide Files (PDFs)"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(Se,{type:"file",accept:".pdf,.doc,.docx",multiple:!0,onChange:Ie,className:"hidden"}),e.jsx(H,{type:"button",variant:"outline",size:"sm",className:"gap-1",asChild:!0,children:e.jsxs("span",{children:[e.jsx(Ea,{className:"h-3 w-3"}),"Add Files"]})})]})]}),d.guides.length>0?e.jsx("div",{className:"space-y-2",children:d.guides.map((Ue,et)=>e.jsxs("div",{className:"flex gap-2 items-center p-3 border rounded-lg bg-muted/30",children:[e.jsx(kn,{className:"h-5 w-5 text-muted-foreground shrink-0"}),e.jsx(Se,{value:Ue.name,onChange:Qe=>pe(et,Qe.target.value),placeholder:"Guide name",className:"flex-1"}),Ue.file_size&&e.jsxs("span",{className:"text-xs text-muted-foreground shrink-0",children:[(Ue.file_size/1024).toFixed(0)," KB"]}),e.jsx(H,{type:"button",variant:"ghost",size:"icon",className:"shrink-0 text-muted-foreground hover:text-destructive h-8 w-8",onClick:()=>De(et),children:e.jsx(Rr,{className:"h-4 w-4"})})]},Ue.id||et))}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"No guide files added. Upload PDFs to help agents understand how to use this template."})]}),e.jsx(ccs,{selectedKitIds:A,onChange:D}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(H,{type:"button",variant:"outline",onClick:()=>{l(!1),We()},children:"Cancel"}),e.jsx(H,{type:"submit",disabled:fe.isPending,children:fe.isPending?"Saving...":o?"Update":"Create"})]})]})]})]})]}),e.jsx(ke,{children:e.jsx(Oe,{className:"p-0",children:ne?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading..."}):ce.length===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No templates yet. Add your first template!"}):e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Vs,{children:[e.jsx(At,{children:"Preview"}),e.jsx(At,{children:"Name"}),e.jsx(At,{children:"Links"}),e.jsx(At,{children:"Category"}),e.jsx(At,{children:"Type"}),e.jsx(At,{children:"Publish Date"}),e.jsx(At,{className:"w-[72px] text-center",children:"Featured"}),e.jsx(At,{className:"text-right",children:"Actions"})]})}),e.jsx(da,{children:ce.map(Ue=>{var et,Qe,Ne,$e,it;return e.jsxs(Vs,{children:[e.jsx(gt,{children:e.jsx("div",{className:"w-16 h-12 rounded overflow-hidden bg-muted",children:Ue.preview_image_url?e.jsx("img",{src:Ue.preview_image_url,alt:Ue.name,className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(wl,{className:"h-4 w-4 text-muted-foreground"})})})}),e.jsx(gt,{className:"font-medium",children:Ue.name}),e.jsx(gt,{children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsxs(Xe,{variant:"secondary",children:[((et=Ue.links)==null?void 0:et.length)||0," link",(((Qe=Ue.links)==null?void 0:Qe.length)||0)!==1?"s":""]}),(((Ne=Ue.guides)==null?void 0:Ne.length)||0)>0&&e.jsxs(Xe,{variant:"outline",className:"gap-1",children:[e.jsx(kn,{className:"h-3 w-3"}),($e=Ue.guides)==null?void 0:$e.length," guide",(((it=Ue.guides)==null?void 0:it.length)||0)!==1?"s":""]})]})}),e.jsx(gt,{children:Ue.category?e.jsx(Xe,{variant:"secondary",children:Ue.category.name}):e.jsx("span",{className:"text-muted-foreground",children:"-"})}),e.jsx(gt,{children:Ue.type?e.jsx(Xe,{variant:"outline",children:Ue.type.name}):e.jsx("span",{className:"text-muted-foreground",children:"-"})}),e.jsx(gt,{className:"text-muted-foreground",children:new Date(Ue.publish_date).toLocaleDateString()}),e.jsx(gt,{className:"text-center",children:e.jsx(H,{type:"button",size:"icon",variant:"ghost",className:"mx-auto",title:Ue.is_featured?"Remove from featured templates":"Add to featured templates",onClick:()=>ve.mutate({id:Ue.id,is_featured:!Ue.is_featured}),children:e.jsx(ya,{className:`h-4 w-4 ${Ue.is_featured?"fill-yellow-400 text-yellow-400":"text-muted-foreground"}`})})}),e.jsx(gt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(H,{size:"icon",variant:"ghost",onClick:()=>Ve(Ue),children:e.jsx(ni,{className:"h-4 w-4"})}),e.jsx(H,{size:"icon",variant:"ghost",className:"text-destructive hover:text-destructive",onClick:()=>{confirm("Delete this template?")&&je.mutate(Ue.id)},children:e.jsx(Dr,{className:"h-4 w-4"})})]})})]},Ue.id)})})]})})})]})})};function yht({selectedTemplateIds:s,onChange:t}){const[r,n]=S.useState(""),[a,i]=S.useState(!1),{data:l=[]}=yt({queryKey:["all-canva-templates-picker"],queryFn:async()=>{const{data:m,error:p}=await V.from("canva_templates").select("id, name, preview_image_url").order("name");if(p)throw p;return m}}),o=l.filter(m=>s.includes(m.id)),c=l.filter(m=>!s.includes(m.id)&&m.name.toLowerCase().includes(r.toLowerCase())),d=m=>{t([...s,m])},h=m=>{t(s.filter(p=>p!==m))};return e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ue,{className:"flex items-center gap-2",children:[e.jsx(jE,{className:"h-4 w-4"}),"Linked Templates"]}),o.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:o.map(m=>e.jsxs(Xe,{variant:"secondary",className:"gap-1 pr-1",children:[m.name,e.jsx("button",{type:"button",onClick:()=>h(m.id),className:"ml-1 rounded-full hover:bg-muted-foreground/20 p-0.5",children:e.jsx(Rr,{className:"h-3 w-3"})})]},m.id))}),e.jsxs(gl,{open:a,onOpenChange:i,children:[e.jsx(xl,{asChild:!0,children:e.jsxs(H,{type:"button",variant:"outline",size:"sm",className:"gap-1",children:[e.jsx(jE,{className:"h-3.5 w-3.5"}),"Add Template"]})}),e.jsxs(il,{className:"w-80 p-2",align:"start",children:[e.jsxs("div",{className:"relative mb-2",children:[e.jsx(Mn,{className:"absolute left-2 top-2.5 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(Se,{placeholder:"Search templates...",value:r,onChange:m=>n(m.target.value),className:"pl-7 h-8 text-sm"})]}),e.jsx("div",{className:"max-h-48 overflow-y-auto space-y-0.5",children:c.length===0?e.jsx("p",{className:"text-xs text-muted-foreground text-center py-3",children:r?"No templates found":"All templates selected"}):c.map(m=>e.jsxs("button",{type:"button",onClick:()=>{d(m.id),n("")},className:"w-full flex items-center gap-2 px-2 py-1.5 rounded-md hover:bg-muted text-left text-sm transition-colors",children:[m.preview_image_url?e.jsx("img",{src:m.preview_image_url,alt:"",className:"w-8 h-8 rounded object-cover flex-shrink-0"}):e.jsx("div",{className:"w-8 h-8 rounded bg-muted flex items-center justify-center flex-shrink-0",children:e.jsx(jE,{className:"h-3.5 w-3.5 text-muted-foreground"})}),e.jsx("span",{className:"truncate",children:m.name})]},m.id))})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Link templates that agents can use alongside this content."})]})}const ucs=[{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"}],hcs=()=>{const{user:s}=Ms(),[t,r]=Ed(),{toast:n}=li(),a=ns(),[i,l]=S.useState(!1),[o,c]=S.useState(null),[d,h]=S.useState({title:"",description:"",video_url:"",video_type:"youtube",duration:"",category_id:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),[m,p]=S.useState(null),[x,y]=S.useState(""),[_,b]=S.useState([]),[j,k]=S.useState([]),[T,E]=S.useState([]),[A,D]=S.useState([]),[R,z]=S.useState(""),[O,$]=S.useState(!1),[ee,Z]=S.useState(null),[J,K]=S.useState(0),[re,ie]=S.useState(!1),[ce,ne]=S.useState(null),{data:le=[]}=yt({queryKey:["academy-categories"],queryFn:async()=>{const{data:ge,error:ct}=await V.from("academy_categories").select("*").order("sort_order",{ascending:!0});if(ct)throw ct;return ge}}),{data:be=[],isLoading:fe}=yt({queryKey:["academy-videos-admin"],queryFn:async()=>{const{data:ge,error:ct}=await V.from("academy_videos").select(` *, category:academy_categories(id, name) `).order("publish_date",{ascending:!1});if(ct)throw ct;const{data:Ue,error:et}=await V.from("academy_resources").select("*").order("sort_order");if(et)throw et;return ge.map(Ne=>({...Ne,resources:(Ue==null?void 0:Ue.filter($e=>$e.video_id===Ne.id))||[]}))}});S.useEffect(()=>{const ge=t.get("edit");if(ge&&be.length>0){const ct=be.find(Ue=>Ue.id===ge);ct&&(Me(ct),r({},{replace:!0}))}},[be,t]);const je=Pt({mutationFn:async ge=>{const{data:ct,error:Ue}=await V.from("academy_categories").insert({name:ge,sort_order:le.length}).select().single();if(Ue)throw Ue;return ct},onSuccess:ge=>{a.invalidateQueries({queryKey:["academy-categories"]}),h({...d,category_id:ge.id}),z(""),$(!1),n({title:"Category added"})},onError:ge=>{n({title:"Error adding category",description:ge.message,variant:"destructive"})}}),ve=Pt({mutationFn:async ge=>{let ct=ge.existingThumbnailUrl;if(ge.thumbnail){const Qe=ge.thumbnail.name.split(".").pop(),Ne=`thumbnails/${Date.now()}-${Math.random().toString(36).substring(7)}.${Qe}`,{error:$e}=await V.storage.from("academy-resources").upload(Ne,ge.thumbnail);if($e)throw $e;const{data:it}=V.storage.from("academy-resources").getPublicUrl(Ne);ct=it.publicUrl}const Ue={title:ge.video.title,description:ge.video.description||null,video_url:ge.video.video_url,video_type:ge.video.video_type,duration:ge.video.duration||null,thumbnail_url:ct,category_id:ge.video.category_id||null,publish_date:ge.video.publish_date?new Date(ge.video.publish_date).toISOString():new Date().toISOString(),is_published:ge.video.is_published,created_by:s==null?void 0:s.id};let et=ge.videoId;if(et){const{error:Qe}=await V.from("academy_videos").update(Ue).eq("id",et);if(Qe)throw Qe}else{const{data:Qe,error:Ne}=await V.from("academy_videos").insert(Ue).select().single();if(Ne)throw Ne;et=Qe.id,ncs(ge.video.title,Qe.id)}if(ge.resourcesToDelete.length>0){const{error:Qe}=await V.from("academy_resources").delete().in("id",ge.resourcesToDelete);if(Qe)throw Qe}for(let Qe=0;Qe0){const{error:Qe}=await V.from("academy_video_templates").insert(A.map(Ne=>({video_id:et,template_id:Ne})));if(Qe)throw Qe}},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-videos-admin"]}),a.invalidateQueries({queryKey:["academy-videos"]}),Le(),l(!1),n({title:o?"Video updated":"Video created"})},onError:ge=>{n({title:"Error saving video",description:ge.message,variant:"destructive"})}}),We=Pt({mutationFn:async ge=>{const{error:ct}=await V.from("academy_videos").delete().eq("id",ge);if(ct)throw ct},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-videos-admin"]}),a.invalidateQueries({queryKey:["academy-videos"]}),n({title:"Video deleted"})},onError:ge=>{n({title:"Error deleting video",description:ge.message,variant:"destructive"})}}),Ve=Pt({mutationFn:async({id:ge,is_published:ct})=>{const{error:Ue}=await V.from("academy_videos").update({is_published:ct}).eq("id",ge);if(Ue)throw Ue},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-videos-admin"]}),a.invalidateQueries({queryKey:["academy-videos"]})},onError:ge=>{n({title:"Error updating video",description:ge.message,variant:"destructive"})}}),Le=()=>{h({title:"",description:"",video_url:"",video_type:"bunny_stream",duration:"",category_id:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),p(null),y(""),b([]),k([]),E([]),c(null),D([]),z(""),Z(null),K(0),ie(!1),ne(null)},Me=async ge=>{c(ge),h({title:ge.title,description:ge.description||"",video_url:ge.video_url,video_type:ge.video_type,duration:ge.duration||"",category_id:ge.category_id||"",publish_date:ge.publish_date?new Date(ge.publish_date).toISOString().split("T")[0]:new Date().toISOString().split("T")[0],is_published:ge.is_published}),y(ge.thumbnail_url||""),k(ge.resources||[]),b([]),E([]);const{data:ct}=await V.from("academy_video_templates").select("template_id").eq("video_id",ge.id);D((ct||[]).map(Ue=>Ue.template_id)),l(!0)},ze=ge=>{var Ue;const ct=(Ue=ge.target.files)==null?void 0:Ue[0];ct&&(p(ct),y(URL.createObjectURL(ct)))},Pe=ge=>{const ct=ge.target.files;if(ct){const Ue=Array.from(ct).map(et=>({file:et,title:et.name.replace(/\.[^/.]+$/,"")}));b([..._,...Ue])}ge.target.value=""},Ie=ge=>{b(_.filter((ct,Ue)=>Ue!==ge))},De=ge=>{E([...T,ge]),k(j.filter(ct=>ct.id!==ge))},pe=async()=>{if(!ee)return null;ie(!0),K(0);try{const{data:ge,error:ct}=await V.functions.invoke("bunny-upload",{body:{action:"create",title:d.title||ee.name}});if(ct)throw new Error(ct.message);const{videoId:Ue,libraryId:et}=ge;ne(Ue);const{data:Qe,error:Ne}=await V.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:Ue}});if(Ne)throw new Error(Ne.message);const $e=new XMLHttpRequest;return await new Promise((Je,st)=>{$e.upload.addEventListener("progress",mt=>{if(mt.lengthComputable){const wt=Math.round(mt.loaded/mt.total*100);K(wt)}}),$e.addEventListener("load",()=>{$e.status>=200&&$e.status<300?Je():st(new Error(`Upload failed with status ${$e.status}`))}),$e.addEventListener("error",()=>st(new Error("Upload failed"))),$e.open("PUT",Qe.uploadUrl),$e.setRequestHeader("AccessKey",Qe.apiKey),$e.send(ee)}),`https://player.mediadelivery.net/embed/${et}/${Ue}`}catch(ge){return console.error("Bunny upload error:",ge),n({title:"Video upload failed",description:ge instanceof Error?ge.message:"Unknown error",variant:"destructive"}),null}finally{ie(!1)}},tt=async ge=>{if(ge.preventDefault(),!d.title.trim()){n({title:"Please enter a video title",variant:"destructive"});return}let ct=d.video_url;if(d.video_type==="bunny_stream"&&ee&&!o){const Ue=await pe();if(!Ue)return;ct=Ue}else if(!d.video_url.trim()&&d.video_type!=="bunny_stream"){n({title:"Please enter a video URL",variant:"destructive"});return}else if(d.video_type==="bunny_stream"&&!ee&&!d.video_url&&!o){n({title:"Please select a video file to upload",variant:"destructive"});return}ve.mutate({video:{...d,video_url:ct},thumbnail:m,existingThumbnailUrl:(o==null?void 0:o.thumbnail_url)||null,videoId:o==null?void 0:o.id,newResources:_,resourcesToDelete:T})};return e.jsx(Ss,{title:"Manage Academy",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(km,{title:"Manage Academy",description:"Create and manage training videos and resources"}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs(ke,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsx(zt,{className:"text-sm font-medium text-muted-foreground",children:"Total Videos"})}),e.jsx(Oe,{children:e.jsx("div",{className:"text-2xl font-bold",children:be.length})})]}),e.jsxs(ke,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsx(zt,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Oe,{children:e.jsx("div",{className:"text-2xl font-bold",children:be.filter(ge=>ge.is_published).length})})]})]}),e.jsxs(bs,{open:i,onOpenChange:ge=>{l(ge),ge||Le()},children:[e.jsx(Qi,{asChild:!0,children:e.jsxs(H,{className:"gap-2",children:[e.jsx(Ys,{className:"h-4 w-4"}),"Add Video"]})}),e.jsxs(vs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Cs,{children:e.jsx(Ns,{children:o?"Edit Video":"Add New Video"})}),e.jsxs("form",{onSubmit:tt,className:"space-y-6 pt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"title",children:"Title *"}),e.jsx(Se,{id:"title",value:d.title,onChange:ge=>h({...d,title:ge.target.value}),placeholder:"Video title",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Description"}),e.jsx(R1,{content:d.description,onChange:ge=>h({...d,description:ge}),placeholder:"Brief description of the video",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Video Type"}),e.jsxs(Bs,{value:d.video_type,onValueChange:ge=>{h({...d,video_type:ge,video_url:""}),Z(null)},disabled:re,children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsx(Fs,{children:ucs.map(ge=>e.jsx(pt,{value:ge.value,children:ge.label},ge.value))})]})]}),d.video_type==="bunny_stream"?e.jsxs("div",{className:"space-y-3",children:[e.jsxs(ue,{children:["Upload Video File ",!o&&"*"]}),o&&d.video_url&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Current video: ",e.jsx("a",{href:d.video_url,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline",children:"View"})]}),!o&&e.jsxs(e.Fragment,{children:[e.jsx(Se,{type:"file",accept:"video/*",onChange:ge=>{var Ue;const ct=(Ue=ge.target.files)==null?void 0:Ue[0];ct&&Z(ct)},disabled:re}),ee&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(xn,{className:"h-4 w-4"}),ee.name," (",(ee.size/(1024*1024)).toFixed(1)," MB)"]}),re&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(is,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{className:"text-sm",children:"Uploading to Bunny.net..."})]}),e.jsx(Mi,{value:J,className:"h-2"}),e.jsxs("p",{className:"text-xs text-muted-foreground text-right",children:[J,"%"]})]})]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"video_url",children:"Video URL *"}),e.jsx(Se,{id:"video_url",value:d.video_url,onChange:ge=>h({...d,video_url:ge.target.value}),placeholder:"https://...",required:!0})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"duration",children:"Duration"}),e.jsx(Se,{id:"duration",value:d.duration,onChange:ge=>h({...d,duration:ge.target.value}),placeholder:"e.g., 45:30"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(Se,{id:"publish_date",type:"date",value:d.publish_date,onChange:ge=>h({...d,publish_date:ge.target.value})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Category"}),O?e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Se,{value:R,onChange:ge=>z(ge.target.value),placeholder:"New category name",className:"flex-1"}),e.jsx(H,{type:"button",size:"sm",onClick:()=>R.trim()&&je.mutate(R.trim()),disabled:je.isPending,children:"Add"}),e.jsx(H,{type:"button",size:"sm",variant:"ghost",onClick:()=>{$(!1),z("")},children:e.jsx(Rr,{className:"h-4 w-4"})})]}):e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Bs,{value:d.category_id,onValueChange:ge=>h({...d,category_id:ge}),children:[e.jsx(Os,{className:"flex-1",children:e.jsx(Us,{placeholder:"Select category"})}),e.jsx(Fs,{children:le.map(ge=>e.jsx(pt,{value:ge.id,children:ge.name},ge.id))})]}),e.jsx(H,{type:"button",variant:"outline",size:"sm",onClick:()=>$(!0),children:e.jsx(Ys,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Thumbnail Image"}),e.jsxs("div",{className:"flex items-start gap-4",children:[x&&e.jsx("img",{src:x,alt:"Thumbnail preview",className:"w-32 h-20 object-cover rounded-md border"}),e.jsxs("div",{className:"flex-1",children:[e.jsx(Se,{type:"file",accept:"image/*",onChange:ze,className:"cursor-pointer"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Recommended: 16:9 aspect ratio"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ue,{children:"Resource Files"}),e.jsx(H,{type:"button",variant:"outline",size:"sm",asChild:!0,children:e.jsxs("label",{className:"cursor-pointer gap-1",children:[e.jsx(Ea,{className:"h-3 w-3"}),"Add Files",e.jsx("input",{type:"file",multiple:!0,accept:".pdf,.pptx,.ppt,.xlsx,.xls,.docx,.doc,.zip",onChange:Pe,className:"hidden"})]})})]}),(j.length>0||_.length>0)&&e.jsxs("div",{className:"space-y-2 mt-2",children:[j.map(ge=>e.jsxs("div",{className:"flex items-center gap-2 p-2 border rounded-md bg-muted/30",children:[e.jsx(kn,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"flex-1 text-sm truncate",children:ge.title}),e.jsx(Xe,{variant:"outline",className:"text-xs",children:ge.file_type}),e.jsx(H,{type:"button",variant:"ghost",size:"sm",onClick:()=>De(ge.id),className:"text-destructive hover:text-destructive",children:e.jsx(Rr,{className:"h-4 w-4"})})]},ge.id)),_.map((ge,ct)=>e.jsxs("div",{className:"flex items-center gap-2 p-2 border rounded-md bg-muted/30",children:[e.jsx(kn,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(Se,{value:ge.title,onChange:Ue=>{const et=[..._];et[ct].title=Ue.target.value,b(et)},className:"flex-1 h-8",placeholder:"Resource title"}),e.jsx(Xe,{variant:"secondary",className:"text-xs",children:"New"}),e.jsx(H,{type:"button",variant:"ghost",size:"sm",onClick:()=>Ie(ct),className:"text-destructive hover:text-destructive",children:e.jsx(Rr,{className:"h-4 w-4"})})]},ct))]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Supported: PDF, PowerPoint, Excel, Word, ZIP"})]}),e.jsx(yht,{selectedTemplateIds:A,onChange:D}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Or,{id:"is_published",checked:d.is_published,onCheckedChange:ge=>h({...d,is_published:ge})}),e.jsx(ue,{htmlFor:"is_published",children:"Published"})]}),e.jsxs(wn,{children:[e.jsx(H,{type:"button",variant:"outline",onClick:()=>l(!1),disabled:re,children:"Cancel"}),e.jsx(H,{type:"submit",disabled:ve.isPending||re,children:re?e.jsxs(e.Fragment,{children:[e.jsx(is,{className:"h-4 w-4 mr-2 animate-spin"}),"Uploading..."]}):ve.isPending?"Saving...":o?"Update Video":"Add Video"})]})]})]})]})]}),e.jsx(ke,{children:e.jsx(Oe,{className:"p-0",children:fe?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):be.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(xn,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No videos yet"}),e.jsx("p",{className:"text-sm",children:"Add your first academy video"})]}):e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Vs,{children:[e.jsx(At,{children:"Title"}),e.jsx(At,{children:"Category"}),e.jsx(At,{children:"Duration"}),e.jsx(At,{children:"Resources"}),e.jsx(At,{children:"Publish Date"}),e.jsx(At,{children:"Status"}),e.jsx(At,{className:"w-[120px]",children:"Actions"})]})}),e.jsx(da,{children:be.map(ge=>e.jsxs(Vs,{children:[e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[ge.thumbnail_url?e.jsx("img",{src:ge.thumbnail_url,alt:"",className:"w-16 h-10 object-cover rounded"}):e.jsx("div",{className:"w-16 h-10 bg-muted rounded flex items-center justify-center",children:e.jsx(xn,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:ge.title}),e.jsx("p",{className:"text-xs text-muted-foreground capitalize",children:ge.video_type.replace("_"," ")})]})]})}),e.jsx(gt,{children:ge.category?e.jsx(Xe,{variant:"outline",children:ge.category.name}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"-"})}),e.jsx(gt,{children:ge.duration||"-"}),e.jsx(gt,{children:ge.resources&&ge.resources.length>0?e.jsxs(Xe,{variant:"secondary",children:[ge.resources.length," file(s)"]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"-"})}),e.jsx(gt,{children:new Date(ge.publish_date).toLocaleDateString()}),e.jsx(gt,{children:e.jsx(Or,{checked:ge.is_published,onCheckedChange:ct=>Ve.mutate({id:ge.id,is_published:ct})})}),e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(H,{variant:"ghost",size:"sm",onClick:()=>Me(ge),children:e.jsx(ni,{className:"h-4 w-4"})}),e.jsx(H,{variant:"ghost",size:"sm",onClick:()=>We.mutate(ge.id),className:"text-destructive hover:text-destructive",children:e.jsx(Dr,{className:"h-4 w-4"})})]})})]},ge.id))})]})})})]})})};function mcs(){var ve,We,Ve;const s=ns(),[t,r]=Ed(),[n,a]=S.useState(!1),[i,l]=S.useState(null),[o,c]=S.useState({name:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),[d,h]=S.useState(null),[m,p]=S.useState(""),[x,y]=S.useState([]),[_,b]=S.useState([]),[j,k]=S.useState([]),[T,E]=S.useState(null),{data:A,isLoading:D}=yt({queryKey:["resource-kits"],queryFn:async()=>{const{data:Le,error:Me}=await V.from("resource_kits").select("*").order("publish_date",{ascending:!1});if(Me)throw Me;return Le}}),{data:R}=yt({queryKey:["resource-kit-files"],queryFn:async()=>{const{data:Le,error:Me}=await V.from("resource_kit_files").select("*").order("sort_order",{ascending:!0});if(Me)throw Me;return Le}}),{data:z}=yt({queryKey:["resource-kit-links"],queryFn:async()=>{const{data:Le,error:Me}=await V.from("resource_kit_links").select("*").order("sort_order",{ascending:!0});if(Me)throw Me;return Le}});S.useEffect(()=>{const Le=t.get("edit");if(Le&&A&&A.length>0&&R&&z){const Me=A.find(ze=>ze.id===Le);Me&&($(Me),r({},{replace:!0}))}},[A,R,z,t]);const O=()=>{c({name:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),h(null),p(""),y([]),b([]),k([]),l(null)},$=async Le=>{l(Le),c({name:Le.name,description:Le.description||"",publish_date:Le.publish_date.split("T")[0],is_published:Le.is_published}),p(Le.featured_image_url||"");const Me=(R==null?void 0:R.filter(Ie=>Ie.kit_id===Le.id))||[];y(Me.map(Ie=>({id:Ie.id,name:Ie.name,file_url:Ie.file_url,file_type:Ie.file_type,file_size:Ie.file_size,sort_order:Ie.sort_order})));const ze=(z==null?void 0:z.filter(Ie=>Ie.kit_id===Le.id))||[];b(ze.map(Ie=>({id:Ie.id,title:Ie.title,canva_share_link:Ie.canva_share_link,sort_order:Ie.sort_order})));const{data:Pe}=await V.from("resource_kit_templates").select("template_id").eq("kit_id",Le.id);k((Pe||[]).map(Ie=>Ie.template_id)),a(!0)},ee=Le=>{var ze;const Me=(ze=Le.target.files)==null?void 0:ze[0];Me&&(h(Me),p(URL.createObjectURL(Me)))},Z=()=>{y([...x,{name:"",file_url:"",sort_order:x.length}])},J=Le=>{y(x.filter((Me,ze)=>ze!==Le))},K=(Le,Me,ze)=>{const Pe=[...x];Pe[Le]={...Pe[Le],[Me]:ze},y(Pe)},re=()=>{b([..._,{title:"",canva_share_link:"",sort_order:_.length}])},ie=Le=>{b(_.filter((Me,ze)=>ze!==Le))},ce=(Le,Me,ze)=>{const Pe=[..._];Pe[Le]={...Pe[Le],[Me]:ze},b(Pe)},ne=(Le,Me)=>{var Pe;const ze=(Pe=Me.target.files)==null?void 0:Pe[0];if(ze){const Ie=[...x],De=ze.name.replace(/\.[^/.]+$/,"");Ie[Le]={...Ie[Le],file:ze,file_type:ze.type,file_size:ze.size,name:Ie[Le].name||De},y(Ie)}},le=Pt({mutationFn:async()=>{let Le=(i==null?void 0:i.featured_image_url)||null;if(d){const De=d.name.split(".").pop(),pe=`${Date.now()}.${De}`,{error:tt}=await V.storage.from("resource-kits").upload(`featured/${pe}`,d);if(tt)throw tt;const{data:ge}=V.storage.from("resource-kits").getPublicUrl(`featured/${pe}`);Le=ge.publicUrl}const Me={name:o.name,description:o.description||null,featured_image_url:Le,publish_date:o.publish_date,is_published:o.is_published};let ze;const Pe=!i,Ie=(i==null?void 0:i.is_published)||!1;if(i){const{error:De}=await V.from("resource_kits").update(Me).eq("id",i.id);if(De)throw De;ze=i.id;const pe=(R==null?void 0:R.filter(Qe=>Qe.kit_id===i.id).map(Qe=>Qe.id))||[],tt=x.filter(Qe=>Qe.id).map(Qe=>Qe.id),ge=pe.filter(Qe=>!tt.includes(Qe));ge.length>0&&await V.from("resource_kit_files").delete().in("id",ge);const ct=(z==null?void 0:z.filter(Qe=>Qe.kit_id===i.id).map(Qe=>Qe.id))||[],Ue=_.filter(Qe=>Qe.id).map(Qe=>Qe.id),et=ct.filter(Qe=>!Ue.includes(Qe));et.length>0&&await V.from("resource_kit_links").delete().in("id",et)}else{const{data:De,error:pe}=await V.from("resource_kits").insert(Me).select().single();if(pe)throw pe;ze=De.id}for(let De=0;De0){const{error:De}=await V.from("resource_kit_templates").insert(j.map(pe=>({kit_id:ze,template_id:pe})));if(De)throw De}return{kitId:ze,kitName:o.name,isNewKit:Pe,wasPublished:Ie,isPublished:o.is_published}},onSuccess:Le=>{s.invalidateQueries({queryKey:["resource-kits"]}),s.invalidateQueries({queryKey:["resource-kit-files"]}),s.invalidateQueries({queryKey:["resource-kit-links"]}),he.success(i?"Resource kit updated":"Resource kit created"),Le.isPublished&&(Le.isNewKit||!Le.wasPublished)&&ics(Le.kitName,Le.kitId),a(!1),O()},onError:Le=>{he.error("Failed to save resource kit: "+Le.message)}}),be=Pt({mutationFn:async Le=>{const{error:Me}=await V.from("resource_kits").delete().eq("id",Le);if(Me)throw Me},onSuccess:()=>{s.invalidateQueries({queryKey:["resource-kits"]}),s.invalidateQueries({queryKey:["resource-kit-files"]}),he.success("Resource kit deleted")},onError:Le=>{he.error("Failed to delete: "+Le.message)}}),fe=Le=>{if(Le.preventDefault(),!o.name){he.error("Please enter a name");return}le.mutate()},je=Le=>(R==null?void 0:R.filter(Me=>Me.kit_id===Le).length)||0;return e.jsx(Ss,{title:"Toolbox Management",description:"Create and manage resource kits for agents",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs(ke,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsx(zt,{className:"text-sm font-medium text-muted-foreground",children:"Total Kits"})}),e.jsx(Oe,{children:e.jsx("div",{className:"text-2xl font-bold",children:(A==null?void 0:A.length)||0})})]}),e.jsxs(ke,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsx(zt,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Oe,{children:e.jsx("div",{className:"text-2xl font-bold",children:(A==null?void 0:A.filter(Le=>Le.is_published).length)||0})})]})]}),e.jsxs(H,{onClick:()=>{O(),a(!0)},children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Add Resource Kit"]})]}),e.jsx(ke,{children:e.jsx(Oe,{className:"p-0",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Vs,{children:[e.jsx(At,{children:"Name"}),e.jsx(At,{children:"Files"}),e.jsx(At,{children:"Publish Date"}),e.jsx(At,{children:"Status"}),e.jsx(At,{className:"text-right",children:"Actions"})]})}),e.jsx(da,{children:D?e.jsx(Vs,{children:e.jsx(gt,{colSpan:5,className:"text-center py-8",children:"Loading..."})}):(A==null?void 0:A.length)===0?e.jsx(Vs,{children:e.jsx(gt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No resource kits yet. Create your first one!"})}):A==null?void 0:A.map(Le=>e.jsxs(Vs,{children:[e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[Le.featured_image_url?e.jsx("img",{src:Le.featured_image_url,alt:Le.name,className:"w-10 h-10 rounded object-cover"}):e.jsx("div",{className:"w-10 h-10 rounded bg-muted flex items-center justify-center",children:e.jsx(yc,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:Le.name}),Le.description&&e.jsx("div",{className:"text-sm text-muted-foreground line-clamp-1",children:Le.description})]})]})}),e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(kn,{className:"h-4 w-4 text-muted-foreground"}),je(Le.id)]})}),e.jsx(gt,{children:As(new Date(Le.publish_date),"MMM d, yyyy")}),e.jsx(gt,{children:e.jsx("span",{className:`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${Le.is_published?"bg-green-100 text-green-800":"bg-yellow-100 text-yellow-800"}`,children:Le.is_published?"Published":"Draft"})}),e.jsx(gt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(H,{variant:"ghost",size:"icon",onClick:()=>{const Me=(R==null?void 0:R.filter(Pe=>Pe.kit_id===Le.id))||[],ze=(z==null?void 0:z.filter(Pe=>Pe.kit_id===Le.id))||[];E({...Le,files:Me,links:ze})},children:e.jsx(Bn,{className:"h-4 w-4"})}),e.jsx(H,{variant:"ghost",size:"icon",onClick:()=>$(Le),children:e.jsx(ni,{className:"h-4 w-4"})}),e.jsx(H,{variant:"ghost",size:"icon",onClick:()=>{confirm("Delete this resource kit?")&&be.mutate(Le.id)},children:e.jsx(Dr,{className:"h-4 w-4 text-destructive"})})]})})]},Le.id))})]})})}),e.jsx(bs,{open:n,onOpenChange:a,children:e.jsxs(vs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Cs,{children:e.jsx(Ns,{children:i?"Edit Resource Kit":"Add Resource Kit"})}),e.jsxs("form",{onSubmit:fe,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Featured Image"}),e.jsxs("div",{className:"flex items-center gap-4",children:[m?e.jsx("img",{src:m,alt:"Preview",className:"w-24 h-24 rounded object-cover"}):e.jsx("div",{className:"w-24 h-24 rounded bg-muted flex items-center justify-center",children:e.jsx(yc,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx(Se,{type:"file",accept:"image/*",onChange:ee})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"name",children:"Name *"}),e.jsx(Se,{id:"name",value:o.name,onChange:Le=>c({...o,name:Le.target.value}),placeholder:"Resource Kit Name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Description"}),e.jsx(R1,{content:o.description,onChange:Le=>c({...o,description:Le}),placeholder:"Brief description of this resource kit",minHeight:"120px"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(Se,{id:"publish_date",type:"date",value:o.publish_date,onChange:Le=>c({...o,publish_date:Le.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Published"}),e.jsxs("div",{className:"flex items-center space-x-2 pt-2",children:[e.jsx(Or,{checked:o.is_published,onCheckedChange:Le=>c({...o,is_published:Le})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:o.is_published?"Visible to agents":"Hidden from agents"})]})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(ue,{children:"Resource Files"}),e.jsxs(H,{type:"button",variant:"outline",size:"sm",onClick:Z,children:[e.jsx(Ys,{className:"h-4 w-4 mr-1"}),"Add File"]})]}),x.length===0?e.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.'}):e.jsx("div",{className:"space-y-3",children:x.map((Le,Me)=>e.jsxs("div",{className:"border rounded-md p-3 space-y-2",children:[e.jsxs("div",{className:"flex justify-between items-start",children:[e.jsxs("span",{className:"text-sm font-medium",children:["File ",Me+1]}),e.jsx(H,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>J(Me),children:e.jsx(Rr,{className:"h-4 w-4"})})]}),e.jsx(Se,{placeholder:"File name (e.g., Getting Started Guide)",value:Le.name,onChange:ze=>K(Me,"name",ze.target.value)}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Se,{type:"file",onChange:ze=>ne(Me,ze),className:"flex-1"}),Le.file_url&&!Le.file&&e.jsx("a",{href:Le.file_url,target:"_blank",rel:"noopener noreferrer",className:"text-sm text-primary hover:underline whitespace-nowrap",children:"Current file"}),Le.file&&e.jsx("span",{className:"text-sm text-green-600 whitespace-nowrap",children:"New file selected"})]})]},Me))})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(ue,{children:"Canva Links"}),e.jsxs(H,{type:"button",variant:"outline",size:"sm",onClick:re,children:[e.jsx(Ys,{className:"h-4 w-4 mr-1"}),"Add Canva Link"]})]}),_.length===0?e.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.'}):e.jsx("div",{className:"space-y-3",children:_.map((Le,Me)=>e.jsxs("div",{className:"border rounded-md p-3 space-y-2",children:[e.jsxs("div",{className:"flex justify-between items-start",children:[e.jsxs("span",{className:"text-sm font-medium",children:["Canva Link ",Me+1]}),e.jsx(H,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>ie(Me),children:e.jsx(Rr,{className:"h-4 w-4"})})]}),e.jsx(Se,{placeholder:"Link title (e.g., Social Media Post Template)",value:Le.title,onChange:ze=>ce(Me,"title",ze.target.value)}),e.jsx(Se,{placeholder:"Canva share link (e.g., https://www.canva.com/design/...)",value:Le.canva_share_link,onChange:ze=>ce(Me,"canva_share_link",ze.target.value)})]},Me))})]}),e.jsx(yht,{selectedTemplateIds:j,onChange:k}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(H,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(H,{type:"submit",disabled:le.isPending,children:le.isPending?"Saving...":i?"Update":"Create"})]})]})]})}),e.jsx(bs,{open:!!T,onOpenChange:()=>E(null),children:e.jsxs(vs,{className:"max-w-lg",children:[e.jsx(Cs,{children:e.jsx(Ns,{children:T==null?void 0:T.name})}),e.jsxs("div",{className:"space-y-4",children:[(T==null?void 0:T.featured_image_url)&&e.jsx("img",{src:T.featured_image_url,alt:T.name,className:"w-full h-48 object-cover rounded-lg"}),(T==null?void 0:T.description)&&e.jsx("p",{className:"text-muted-foreground",children:T.description}),e.jsxs("div",{children:[e.jsxs("h4",{className:"font-medium mb-2",children:["Resource Files (",((ve=T==null?void 0:T.files)==null?void 0:ve.length)||0,")"]}),((We=T==null?void 0:T.files)==null?void 0:We.length)===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No files in this kit"}):e.jsx("div",{className:"space-y-2",children:(Ve=T==null?void 0:T.files)==null?void 0:Ve.map(Le=>e.jsxs("a",{href:Le.file_url,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-2 p-2 rounded-md hover:bg-muted transition-colors",children:[e.jsx(kn,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-sm",children:Le.name})]},Le.id))})]}),(T==null?void 0:T.links)&&T.links.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"font-medium mb-2",children:["Canva Links (",T.links.length,")"]}),e.jsx("div",{className:"space-y-2",children:T.links.map(Le=>e.jsxs("a",{href:Le.canva_share_link,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-2 p-2 rounded-md hover:bg-muted transition-colors",children:[e.jsx(Jo,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-sm",children:Le.title})]},Le.id))})]})]})]})})]})})}const fcs=()=>{const{user:s}=Ms(),{toast:t}=li(),r=ns(),[n,a]=S.useState(!1),[i,l]=S.useState(null),[o,c]=S.useState({title:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1,links:[{title:"",canva_share_link:"",sort_order:0}]}),[d,h]=S.useState(null),[m,p]=S.useState(""),{data:x=[],isLoading:y}=yt({queryKey:["social-swag-admin"],queryFn:async()=>{const{data:z,error:O}=await V.from("social_swag").select("*").order("publish_date",{ascending:!1});if(O)throw O;const{data:$,error:ee}=await V.from("social_swag_links").select("*").order("sort_order");if(ee)throw ee;return z.map(J=>({...J,links:($==null?void 0:$.filter(K=>K.swag_id===J.id))||[]}))}}),_=Pt({mutationFn:async z=>{let O=z.existingImageUrl;if(z.image){const re=z.image.name.split(".").pop(),ie=`${Date.now()}-${Math.random().toString(36).substring(7)}.${re}`,{error:ce}=await V.storage.from("template-previews").upload(ie,z.image);if(ce)throw ce;const{data:ne}=V.storage.from("template-previews").getPublicUrl(ie);O=ne.publicUrl}const $={title:z.item.title,description:z.item.description||null,preview_image_url:O,publish_date:z.item.publish_date?new Date(z.item.publish_date).toISOString():new Date().toISOString(),is_published:z.item.is_published,created_by:s==null?void 0:s.id};let ee=z.itemId;const Z=!ee,J=(i==null?void 0:i.is_published)||!1;if(ee){const{error:re}=await V.from("social_swag").update($).eq("id",ee);if(re)throw re;await V.from("social_swag_links").delete().eq("swag_id",ee)}else{const{data:re,error:ie}=await V.from("social_swag").insert($).select().single();if(ie)throw ie;ee=re.id}const K=z.item.links.filter(re=>re.title.trim()&&re.canva_share_link.trim());if(K.length>0){const re=K.map((ce,ne)=>({swag_id:ee,title:ce.title.trim(),canva_share_link:ce.canva_share_link.trim(),sort_order:ne})),{error:ie}=await V.from("social_swag_links").insert(re);if(ie)throw ie}return{itemId:ee,itemTitle:z.item.title,isNewItem:Z,wasPublished:J,isPublished:z.item.is_published}},onSuccess:z=>{r.invalidateQueries({queryKey:["social-swag-admin"]}),r.invalidateQueries({queryKey:["social-swag"]}),t({title:i?"Item updated":"Item created"}),z.isPublished&&(z.isNewItem||!z.wasPublished)&&Uke(z.itemTitle,z.itemId),a(!1),j()},onError:z=>{t({title:"Error saving item",description:z.message,variant:"destructive"})}}),b=Pt({mutationFn:async z=>{const{error:O}=await V.from("social_swag").delete().eq("id",z);if(O)throw O},onSuccess:()=>{r.invalidateQueries({queryKey:["social-swag-admin"]}),r.invalidateQueries({queryKey:["social-swag"]}),t({title:"Item deleted"})},onError:z=>{t({title:"Error deleting item",description:z.message,variant:"destructive"})}}),j=()=>{c({title:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1,links:[{title:"",canva_share_link:"",sort_order:0}]}),h(null),p(""),l(null)},k=z=>{l(z),c({title:z.title,description:z.description||"",publish_date:z.publish_date?new Date(z.publish_date).toISOString().split("T")[0]:new Date().toISOString().split("T")[0],is_published:z.is_published,links:z.links&&z.links.length>0?z.links.map(O=>({id:O.id,title:O.title,canva_share_link:O.canva_share_link,sort_order:O.sort_order})):[{title:"",canva_share_link:"",sort_order:0}]}),p(z.preview_image_url||""),a(!0)},T=z=>{var $;const O=($=z.target.files)==null?void 0:$[0];O&&(h(O),p(URL.createObjectURL(O)))},E=()=>{c({...o,links:[...o.links,{title:"",canva_share_link:"",sort_order:o.links.length}]})},A=z=>{if(o.links.length<=1)return;const O=o.links.filter(($,ee)=>ee!==z);c({...o,links:O})},D=(z,O,$)=>{const ee=[...o.links];ee[z]={...ee[z],[O]:$},c({...o,links:ee})},R=z=>{if(z.preventDefault(),!o.title.trim()){t({title:"Title is required",variant:"destructive"});return}_.mutate({item:o,image:d,existingImageUrl:(i==null?void 0:i.preview_image_url)||null,itemId:i==null?void 0:i.id})};return e.jsx(Ss,{title:"Manage Social Swag",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(km,{title:"Manage Social Swag",description:"Create and manage social media content"}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs(ke,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsx(zt,{className:"text-sm font-medium text-muted-foreground",children:"Total Items"})}),e.jsx(Oe,{children:e.jsx("div",{className:"text-2xl font-bold",children:x.length})})]}),e.jsxs(ke,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsx(zt,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Oe,{children:e.jsx("div",{className:"text-2xl font-bold",children:x.filter(z=>z.is_published).length})})]})]}),e.jsxs(bs,{open:n,onOpenChange:z=>{a(z),z||j()},children:[e.jsx(Qi,{asChild:!0,children:e.jsxs(H,{className:"gap-2",children:[e.jsx(Ys,{className:"h-4 w-4"}),"Add Item"]})}),e.jsxs(vs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Cs,{children:e.jsx(Ns,{children:i?"Edit Item":"Add New Item"})}),e.jsxs("form",{onSubmit:R,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"title",children:"Title *"}),e.jsx(Se,{id:"title",value:o.title,onChange:z=>c({...o,title:z.target.value}),placeholder:"Enter title"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Description"}),e.jsx(R1,{content:o.description,onChange:z=>c({...o,description:z}),placeholder:"Enter description",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(Se,{id:"publish_date",type:"date",value:o.publish_date,onChange:z=>c({...o,publish_date:z.target.value})})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Or,{id:"is_published",checked:o.is_published,onCheckedChange:z=>c({...o,is_published:z})}),e.jsx(ue,{htmlFor:"is_published",children:"Published"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Preview Image"}),m?e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:m,alt:"Preview",className:"w-full max-h-48 object-contain rounded-lg border"}),e.jsx(H,{type:"button",variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-6 w-6",onClick:()=>{h(null),p("")},children:e.jsx(Rr,{className:"h-3 w-3"})})]}):e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-4 text-center",children:[e.jsx(wl,{className:"h-8 w-8 mx-auto text-muted-foreground mb-2"}),e.jsx(Se,{type:"file",accept:"image/*",onChange:T,className:"cursor-pointer"})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ue,{children:"Canva Links"}),e.jsxs(H,{type:"button",variant:"outline",size:"sm",onClick:E,children:[e.jsx(Ys,{className:"h-3 w-3 mr-1"}),"Add Link"]})]}),o.links.map((z,O)=>e.jsx(ke,{children:e.jsxs(Oe,{className:"pt-4 pb-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"text-sm font-medium text-muted-foreground",children:["Link ",O+1]}),o.links.length>1&&e.jsx(H,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>A(O),children:e.jsx(Rr,{className:"h-3 w-3"})})]}),e.jsx(Se,{placeholder:"Link title (e.g., Instagram Post)",value:z.title,onChange:$=>D(O,"title",$.target.value)}),e.jsx(Se,{placeholder:"Canva share link",value:z.canva_share_link,onChange:$=>D(O,"canva_share_link",$.target.value)})]})},O))]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(H,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(H,{type:"submit",disabled:_.isPending,children:_.isPending?"Saving...":i?"Update":"Create"})]})]})]})]})]}),e.jsx(ke,{children:e.jsx(Oe,{className:"p-0",children:y?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):x.length===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:'No items yet. Click "Add Item" to create your first one.'}):e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Vs,{children:[e.jsx(At,{className:"w-16",children:"Preview"}),e.jsx(At,{children:"Title"}),e.jsx(At,{children:"Links"}),e.jsx(At,{children:"Publish Date"}),e.jsx(At,{children:"Status"}),e.jsx(At,{className:"text-right",children:"Actions"})]})}),e.jsx(da,{children:x.map(z=>{var O;return e.jsxs(Vs,{children:[e.jsx(gt,{children:z.preview_image_url?e.jsx("img",{src:z.preview_image_url,alt:"",className:"w-12 h-12 object-cover rounded"}):e.jsx("div",{className:"w-12 h-12 bg-muted rounded flex items-center justify-center",children:e.jsx(wl,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsx(gt,{className:"font-medium",children:z.title}),e.jsxs(gt,{children:[((O=z.links)==null?void 0:O.length)||0," links"]}),e.jsx(gt,{children:new Date(z.publish_date).toLocaleDateString()}),e.jsx(gt,{children:e.jsx(Xe,{variant:z.is_published?"default":"secondary",children:z.is_published?"Published":"Draft"})}),e.jsx(gt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(H,{variant:"ghost",size:"icon",onClick:()=>window.open(`/social-swag/${z.id}`,"_blank"),children:e.jsx(Bn,{className:"h-4 w-4"})}),e.jsx(H,{variant:"ghost",size:"icon",onClick:()=>k(z),children:e.jsx(ni,{className:"h-4 w-4"})}),e.jsx(H,{variant:"ghost",size:"icon",onClick:()=>{confirm("Are you sure you want to delete this item?")&&b.mutate(z.id)},children:e.jsx(Dr,{className:"h-4 w-4"})})]})})]},z.id)})})]})})})]})})};function pcs(){for(var s=arguments.length,t=new Array(s),r=0;rn=>{t.forEach(a=>a(n))},t)}const Axe=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function k8(s){const t=Object.prototype.toString.call(s);return t==="[object Window]"||t==="[object global]"}function GEe(s){return"nodeType"in s}function px(s){var t,r;return s?k8(s)?s:GEe(s)&&(t=(r=s.ownerDocument)==null?void 0:r.defaultView)!=null?t:window:window}function WEe(s){const{Document:t}=px(s);return s instanceof t}function bz(s){return k8(s)?!1:s instanceof px(s).HTMLElement}function vht(s){return s instanceof px(s).SVGElement}function S8(s){return s?k8(s)?s.document:GEe(s)?WEe(s)?s:bz(s)||vht(s)?s.ownerDocument:document:document:document}const D_=Axe?S.useLayoutEffect:S.useEffect;function KEe(s){const t=S.useRef(s);return D_(()=>{t.current=s}),S.useCallback(function(){for(var r=arguments.length,n=new Array(r),a=0;a{s.current=setInterval(n,a)},[]),r=S.useCallback(()=>{s.current!==null&&(clearInterval(s.current),s.current=null)},[]);return[t,r]}function M9(s,t){t===void 0&&(t=[s]);const r=S.useRef(s);return D_(()=>{r.current!==s&&(r.current=s)},t),r}function _z(s,t){const r=S.useRef();return S.useMemo(()=>{const n=s(r.current);return r.current=n,n},[...t])}function efe(s){const t=KEe(s),r=S.useRef(null),n=S.useCallback(a=>{a!==r.current&&(t==null||t(a,r.current)),r.current=a},[]);return[r,n]}function qke(s){const t=S.useRef();return S.useEffect(()=>{t.current=s},[s]),t.current}let A_e={};function wz(s,t){return S.useMemo(()=>{if(t)return t;const r=A_e[s]==null?0:A_e[s]+1;return A_e[s]=r,s+"-"+r},[s,t])}function bht(s){return function(t){for(var r=arguments.length,n=new Array(r>1?r-1:0),a=1;a{const o=Object.entries(l);for(const[c,d]of o){const h=i[c];h!=null&&(i[c]=h+s*d)}return i},{...t})}}const mP=bht(1),I9=bht(-1);function xcs(s){return"clientX"in s&&"clientY"in s}function YEe(s){if(!s)return!1;const{KeyboardEvent:t}=px(s.target);return t&&s instanceof t}function ycs(s){if(!s)return!1;const{TouchEvent:t}=px(s.target);return t&&s instanceof t}function Vke(s){if(ycs(s)){if(s.touches&&s.touches.length){const{clientX:t,clientY:r}=s.touches[0];return{x:t,y:r}}else if(s.changedTouches&&s.changedTouches.length){const{clientX:t,clientY:r}=s.changedTouches[0];return{x:t,y:r}}}return xcs(s)?{x:s.clientX,y:s.clientY}:null}const kS=Object.freeze({Translate:{toString(s){if(!s)return;const{x:t,y:r}=s;return"translate3d("+(t?Math.round(t):0)+"px, "+(r?Math.round(r):0)+"px, 0)"}},Scale:{toString(s){if(!s)return;const{scaleX:t,scaleY:r}=s;return"scaleX("+t+") scaleY("+r+")"}},Transform:{toString(s){if(s)return[kS.Translate.toString(s),kS.Scale.toString(s)].join(" ")}},Transition:{toString(s){let{property:t,duration:r,easing:n}=s;return t+" "+r+"ms "+n}}}),t$e="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function vcs(s){return s.matches(t$e)?s:s.querySelector(t$e)}const bcs={display:"none"};function _cs(s){let{id:t,value:r}=s;return Nt.createElement("div",{id:t,style:bcs},r)}function wcs(s){let{id:t,announcement:r,ariaLiveType:n="assertive"}=s;const a={position:"fixed",top:0,left:0,width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(100%)",whiteSpace:"nowrap"};return Nt.createElement("div",{id:t,style:a,role:"status","aria-live":n,"aria-atomic":!0},r)}function jcs(){const[s,t]=S.useState("");return{announce:S.useCallback(n=>{n!=null&&t(n)},[]),announcement:s}}const _ht=S.createContext(null);function Ncs(s){const t=S.useContext(_ht);S.useEffect(()=>{if(!t)throw new Error("useDndMonitor must be used within a children of ");return t(s)},[s,t])}function kcs(){const[s]=S.useState(()=>new Set),t=S.useCallback(n=>(s.add(n),()=>s.delete(n)),[s]);return[S.useCallback(n=>{let{type:a,event:i}=n;s.forEach(l=>{var o;return(o=l[a])==null?void 0:o.call(l,i)})},[s]),t]}const Scs={draggable:` To pick up a draggable item, press the space bar. While dragging, use the arrow keys to move the item. Press space again to drop the item in its new position, or press escape to cancel. `},Ccs={onDragStart(s){let{active:t}=s;return"Picked up draggable item "+t.id+"."},onDragOver(s){let{active:t,over:r}=s;return r?"Draggable item "+t.id+" was moved over droppable area "+r.id+".":"Draggable item "+t.id+" is no longer over a droppable area."},onDragEnd(s){let{active:t,over:r}=s;return r?"Draggable item "+t.id+" was dropped over droppable area "+r.id:"Draggable item "+t.id+" was dropped."},onDragCancel(s){let{active:t}=s;return"Dragging was cancelled. Draggable item "+t.id+" was dropped."}};function Tcs(s){let{announcements:t=Ccs,container:r,hiddenTextDescribedById:n,screenReaderInstructions:a=Scs}=s;const{announce:i,announcement:l}=jcs(),o=wz("DndLiveRegion"),[c,d]=S.useState(!1);if(S.useEffect(()=>{d(!0)},[]),Ncs(S.useMemo(()=>({onDragStart(m){let{active:p}=m;i(t.onDragStart({active:p}))},onDragMove(m){let{active:p,over:x}=m;t.onDragMove&&i(t.onDragMove({active:p,over:x}))},onDragOver(m){let{active:p,over:x}=m;i(t.onDragOver({active:p,over:x}))},onDragEnd(m){let{active:p,over:x}=m;i(t.onDragEnd({active:p,over:x}))},onDragCancel(m){let{active:p,over:x}=m;i(t.onDragCancel({active:p,over:x}))}}),[i,t])),!c)return null;const h=Nt.createElement(Nt.Fragment,null,Nt.createElement(_cs,{id:n,value:a.draggable}),Nt.createElement(wcs,{id:o,announcement:l}));return r?tx.createPortal(h,r):h}var am;(function(s){s.DragStart="dragStart",s.DragMove="dragMove",s.DragEnd="dragEnd",s.DragCancel="dragCancel",s.DragOver="dragOver",s.RegisterDroppable="registerDroppable",s.SetDroppableDisabled="setDroppableDisabled",s.UnregisterDroppable="unregisterDroppable"})(am||(am={}));function tfe(){}function fL(s,t){return S.useMemo(()=>({sensor:s,options:t??{}}),[s,t])}function Mxe(){for(var s=arguments.length,t=new Array(s),r=0;r[...t].filter(n=>n!=null),[...t])}const P1=Object.freeze({x:0,y:0});function wht(s,t){return Math.sqrt(Math.pow(s.x-t.x,2)+Math.pow(s.y-t.y,2))}function jht(s,t){let{data:{value:r}}=s,{data:{value:n}}=t;return r-n}function Ecs(s,t){let{data:{value:r}}=s,{data:{value:n}}=t;return n-r}function s$e(s){let{left:t,top:r,height:n,width:a}=s;return[{x:t,y:r},{x:t+a,y:r},{x:t,y:r+n},{x:t+a,y:r+n}]}function Nht(s,t){if(!s||s.length===0)return null;const[r]=s;return r[t]}function r$e(s,t,r){return t===void 0&&(t=s.left),r===void 0&&(r=s.top),{x:t+s.width*.5,y:r+s.height*.5}}const Ixe=s=>{let{collisionRect:t,droppableRects:r,droppableContainers:n}=s;const a=r$e(t,t.left,t.top),i=[];for(const l of n){const{id:o}=l,c=r.get(o);if(c){const d=wht(r$e(c),a);i.push({id:o,data:{droppableContainer:l,value:d}})}}return i.sort(jht)},Acs=s=>{let{collisionRect:t,droppableRects:r,droppableContainers:n}=s;const a=s$e(t),i=[];for(const l of n){const{id:o}=l,c=r.get(o);if(c){const d=s$e(c),h=a.reduce((p,x,y)=>p+wht(d[y],x),0),m=Number((h/4).toFixed(4));i.push({id:o,data:{droppableContainer:l,value:m}})}}return i.sort(jht)};function Mcs(s,t){const r=Math.max(t.top,s.top),n=Math.max(t.left,s.left),a=Math.min(t.left+t.width,s.left+s.width),i=Math.min(t.top+t.height,s.top+s.height),l=a-n,o=i-r;if(n{let{collisionRect:t,droppableRects:r,droppableContainers:n}=s;const a=[];for(const i of n){const{id:l}=i,o=r.get(l);if(o){const c=Mcs(o,t);c>0&&a.push({id:l,data:{droppableContainer:i,value:c}})}}return a.sort(Ecs)};function Pcs(s,t,r){return{...s,scaleX:t&&r?t.width/r.width:1,scaleY:t&&r?t.height/r.height:1}}function kht(s,t){return s&&t?{x:s.left-t.left,y:s.top-t.top}:P1}function Lcs(s){return function(r){for(var n=arguments.length,a=new Array(n>1?n-1:0),i=1;i({...l,top:l.top+s*o.y,bottom:l.bottom+s*o.y,left:l.left+s*o.x,right:l.right+s*o.x}),{...r})}}const Dcs=Lcs(1);function Rcs(s){if(s.startsWith("matrix3d(")){const t=s.slice(9,-1).split(/, /);return{x:+t[12],y:+t[13],scaleX:+t[0],scaleY:+t[5]}}else if(s.startsWith("matrix(")){const t=s.slice(7,-1).split(/, /);return{x:+t[4],y:+t[5],scaleX:+t[0],scaleY:+t[3]}}return null}function Ocs(s,t,r){const n=Rcs(t);if(!n)return s;const{scaleX:a,scaleY:i,x:l,y:o}=n,c=s.left-l-(1-a)*parseFloat(r),d=s.top-o-(1-i)*parseFloat(r.slice(r.indexOf(" ")+1)),h=a?s.width/a:s.width,m=i?s.height/i:s.height;return{width:h,height:m,top:d,right:c+h,bottom:d+m,left:c}}const Fcs={ignoreTransform:!1};function C8(s,t){t===void 0&&(t=Fcs);let r=s.getBoundingClientRect();if(t.ignoreTransform){const{transform:d,transformOrigin:h}=px(s).getComputedStyle(s);d&&(r=Ocs(r,d,h))}const{top:n,left:a,width:i,height:l,bottom:o,right:c}=r;return{top:n,left:a,width:i,height:l,bottom:o,right:c}}function n$e(s){return C8(s,{ignoreTransform:!0})}function Bcs(s){const t=s.innerWidth,r=s.innerHeight;return{top:0,left:0,right:t,bottom:r,width:t,height:r}}function zcs(s,t){return t===void 0&&(t=px(s).getComputedStyle(s)),t.position==="fixed"}function $cs(s,t){t===void 0&&(t=px(s).getComputedStyle(s));const r=/(auto|scroll|overlay)/;return["overflow","overflowX","overflowY"].some(a=>{const i=t[a];return typeof i=="string"?r.test(i):!1})}function Pxe(s,t){const r=[];function n(a){if(t!=null&&r.length>=t||!a)return r;if(WEe(a)&&a.scrollingElement!=null&&!r.includes(a.scrollingElement))return r.push(a.scrollingElement),r;if(!bz(a)||vht(a)||r.includes(a))return r;const i=px(s).getComputedStyle(a);return a!==s&&$cs(a,i)&&r.push(a),zcs(a,i)?r:n(a.parentNode)}return s?n(s):r}function Sht(s){const[t]=Pxe(s,1);return t??null}function M_e(s){return!Axe||!s?null:k8(s)?s:GEe(s)?WEe(s)||s===S8(s).scrollingElement?window:bz(s)?s:null:null}function Cht(s){return k8(s)?s.scrollX:s.scrollLeft}function Tht(s){return k8(s)?s.scrollY:s.scrollTop}function Hke(s){return{x:Cht(s),y:Tht(s)}}var Ym;(function(s){s[s.Forward=1]="Forward",s[s.Backward=-1]="Backward"})(Ym||(Ym={}));function Eht(s){return!Axe||!s?!1:s===document.scrollingElement}function Aht(s){const t={x:0,y:0},r=Eht(s)?{height:window.innerHeight,width:window.innerWidth}:{height:s.clientHeight,width:s.clientWidth},n={x:s.scrollWidth-r.width,y:s.scrollHeight-r.height},a=s.scrollTop<=t.y,i=s.scrollLeft<=t.x,l=s.scrollTop>=n.y,o=s.scrollLeft>=n.x;return{isTop:a,isLeft:i,isBottom:l,isRight:o,maxScroll:n,minScroll:t}}const Ucs={x:.2,y:.2};function qcs(s,t,r,n,a){let{top:i,left:l,right:o,bottom:c}=r;n===void 0&&(n=10),a===void 0&&(a=Ucs);const{isTop:d,isBottom:h,isLeft:m,isRight:p}=Aht(s),x={x:0,y:0},y={x:0,y:0},_={height:t.height*a.y,width:t.width*a.x};return!d&&i<=t.top+_.height?(x.y=Ym.Backward,y.y=n*Math.abs((t.top+_.height-i)/_.height)):!h&&c>=t.bottom-_.height&&(x.y=Ym.Forward,y.y=n*Math.abs((t.bottom-_.height-c)/_.height)),!p&&o>=t.right-_.width?(x.x=Ym.Forward,y.x=n*Math.abs((t.right-_.width-o)/_.width)):!m&&l<=t.left+_.width&&(x.x=Ym.Backward,y.x=n*Math.abs((t.left+_.width-l)/_.width)),{direction:x,speed:y}}function Vcs(s){if(s===document.scrollingElement){const{innerWidth:i,innerHeight:l}=window;return{top:0,left:0,right:i,bottom:l,width:i,height:l}}const{top:t,left:r,right:n,bottom:a}=s.getBoundingClientRect();return{top:t,left:r,right:n,bottom:a,width:s.clientWidth,height:s.clientHeight}}function Mht(s){return s.reduce((t,r)=>mP(t,Hke(r)),P1)}function Hcs(s){return s.reduce((t,r)=>t+Cht(r),0)}function Gcs(s){return s.reduce((t,r)=>t+Tht(r),0)}function Wcs(s,t){if(t===void 0&&(t=C8),!s)return;const{top:r,left:n,bottom:a,right:i}=t(s);Sht(s)&&(a<=0||i<=0||r>=window.innerHeight||n>=window.innerWidth)&&s.scrollIntoView({block:"center",inline:"center"})}const Kcs=[["x",["left","right"],Hcs],["y",["top","bottom"],Gcs]];class ZEe{constructor(t,r){this.rect=void 0,this.width=void 0,this.height=void 0,this.top=void 0,this.bottom=void 0,this.right=void 0,this.left=void 0;const n=Pxe(r),a=Mht(n);this.rect={...t},this.width=t.width,this.height=t.height;for(const[i,l,o]of Kcs)for(const c of l)Object.defineProperty(this,c,{get:()=>{const d=o(n),h=a[i]-d;return this.rect[c]+h},enumerable:!0});Object.defineProperty(this,"rect",{enumerable:!1})}}class y7{constructor(t){this.target=void 0,this.listeners=[],this.removeAll=()=>{this.listeners.forEach(r=>{var n;return(n=this.target)==null?void 0:n.removeEventListener(...r)})},this.target=t}add(t,r,n){var a;(a=this.target)==null||a.addEventListener(t,r,n),this.listeners.push([t,r,n])}}function Ycs(s){const{EventTarget:t}=px(s);return s instanceof t?s:S8(s)}function I_e(s,t){const r=Math.abs(s.x),n=Math.abs(s.y);return typeof t=="number"?Math.sqrt(r**2+n**2)>t:"x"in t&&"y"in t?r>t.x&&n>t.y:"x"in t?r>t.x:"y"in t?n>t.y:!1}var Cy;(function(s){s.Click="click",s.DragStart="dragstart",s.Keydown="keydown",s.ContextMenu="contextmenu",s.Resize="resize",s.SelectionChange="selectionchange",s.VisibilityChange="visibilitychange"})(Cy||(Cy={}));function a$e(s){s.preventDefault()}function Zcs(s){s.stopPropagation()}var hl;(function(s){s.Space="Space",s.Down="ArrowDown",s.Right="ArrowRight",s.Left="ArrowLeft",s.Up="ArrowUp",s.Esc="Escape",s.Enter="Enter",s.Tab="Tab"})(hl||(hl={}));const Iht={start:[hl.Space,hl.Enter],cancel:[hl.Esc],end:[hl.Space,hl.Enter,hl.Tab]},Xcs=(s,t)=>{let{currentCoordinates:r}=t;switch(s.code){case hl.Right:return{...r,x:r.x+25};case hl.Left:return{...r,x:r.x-25};case hl.Down:return{...r,y:r.y+25};case hl.Up:return{...r,y:r.y-25}}};class Lxe{constructor(t){this.props=void 0,this.autoScrollEnabled=!1,this.referenceCoordinates=void 0,this.listeners=void 0,this.windowListeners=void 0,this.props=t;const{event:{target:r}}=t;this.props=t,this.listeners=new y7(S8(r)),this.windowListeners=new y7(px(r)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(Cy.Resize,this.handleCancel),this.windowListeners.add(Cy.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(Cy.Keydown,this.handleKeyDown))}handleStart(){const{activeNode:t,onStart:r}=this.props,n=t.node.current;n&&Wcs(n),r(P1)}handleKeyDown(t){if(YEe(t)){const{active:r,context:n,options:a}=this.props,{keyboardCodes:i=Iht,coordinateGetter:l=Xcs,scrollBehavior:o="smooth"}=a,{code:c}=t;if(i.end.includes(c)){this.handleEnd(t);return}if(i.cancel.includes(c)){this.handleCancel(t);return}const{collisionRect:d}=n.current,h=d?{x:d.left,y:d.top}:P1;this.referenceCoordinates||(this.referenceCoordinates=h);const m=l(t,{active:r,context:n.current,currentCoordinates:h});if(m){const p=I9(m,h),x={x:0,y:0},{scrollableAncestors:y}=n.current;for(const _ of y){const b=t.code,{isTop:j,isRight:k,isLeft:T,isBottom:E,maxScroll:A,minScroll:D}=Aht(_),R=Vcs(_),z={x:Math.min(b===hl.Right?R.right-R.width/2:R.right,Math.max(b===hl.Right?R.left:R.left+R.width/2,m.x)),y:Math.min(b===hl.Down?R.bottom-R.height/2:R.bottom,Math.max(b===hl.Down?R.top:R.top+R.height/2,m.y))},O=b===hl.Right&&!k||b===hl.Left&&!T,$=b===hl.Down&&!E||b===hl.Up&&!j;if(O&&z.x!==m.x){const ee=_.scrollLeft+p.x,Z=b===hl.Right&&ee<=A.x||b===hl.Left&&ee>=D.x;if(Z&&!p.y){_.scrollTo({left:ee,behavior:o});return}Z?x.x=_.scrollLeft-ee:x.x=b===hl.Right?_.scrollLeft-A.x:_.scrollLeft-D.x,x.x&&_.scrollBy({left:-x.x,behavior:o});break}else if($&&z.y!==m.y){const ee=_.scrollTop+p.y,Z=b===hl.Down&&ee<=A.y||b===hl.Up&&ee>=D.y;if(Z&&!p.x){_.scrollTo({top:ee,behavior:o});return}Z?x.y=_.scrollTop-ee:x.y=b===hl.Down?_.scrollTop-A.y:_.scrollTop-D.y,x.y&&_.scrollBy({top:-x.y,behavior:o});break}}this.handleMove(t,mP(I9(m,this.referenceCoordinates),x))}}}handleMove(t,r){const{onMove:n}=this.props;t.preventDefault(),n(r)}handleEnd(t){const{onEnd:r}=this.props;t.preventDefault(),this.detach(),r()}handleCancel(t){const{onCancel:r}=this.props;t.preventDefault(),this.detach(),r()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll()}}Lxe.activators=[{eventName:"onKeyDown",handler:(s,t,r)=>{let{keyboardCodes:n=Iht,onActivation:a}=t,{active:i}=r;const{code:l}=s.nativeEvent;if(n.start.includes(l)){const o=i.activatorNode.current;return o&&s.target!==o?!1:(s.preventDefault(),a==null||a({event:s.nativeEvent}),!0)}return!1}}];function i$e(s){return!!(s&&"distance"in s)}function o$e(s){return!!(s&&"delay"in s)}class XEe{constructor(t,r,n){var a;n===void 0&&(n=Ycs(t.event.target)),this.props=void 0,this.events=void 0,this.autoScrollEnabled=!0,this.document=void 0,this.activated=!1,this.initialCoordinates=void 0,this.timeoutId=null,this.listeners=void 0,this.documentListeners=void 0,this.windowListeners=void 0,this.props=t,this.events=r;const{event:i}=t,{target:l}=i;this.props=t,this.events=r,this.document=S8(l),this.documentListeners=new y7(this.document),this.listeners=new y7(n),this.windowListeners=new y7(px(l)),this.initialCoordinates=(a=Vke(i))!=null?a:P1,this.handleStart=this.handleStart.bind(this),this.handleMove=this.handleMove.bind(this),this.handleEnd=this.handleEnd.bind(this),this.handleCancel=this.handleCancel.bind(this),this.handleKeydown=this.handleKeydown.bind(this),this.removeTextSelection=this.removeTextSelection.bind(this),this.attach()}attach(){const{events:t,props:{options:{activationConstraint:r,bypassActivationConstraint:n}}}=this;if(this.listeners.add(t.move.name,this.handleMove,{passive:!1}),this.listeners.add(t.end.name,this.handleEnd),t.cancel&&this.listeners.add(t.cancel.name,this.handleCancel),this.windowListeners.add(Cy.Resize,this.handleCancel),this.windowListeners.add(Cy.DragStart,a$e),this.windowListeners.add(Cy.VisibilityChange,this.handleCancel),this.windowListeners.add(Cy.ContextMenu,a$e),this.documentListeners.add(Cy.Keydown,this.handleKeydown),r){if(n!=null&&n({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(o$e(r)){this.timeoutId=setTimeout(this.handleStart,r.delay),this.handlePending(r);return}if(i$e(r)){this.handlePending(r);return}}this.handleStart()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll(),setTimeout(this.documentListeners.removeAll,50),this.timeoutId!==null&&(clearTimeout(this.timeoutId),this.timeoutId=null)}handlePending(t,r){const{active:n,onPending:a}=this.props;a(n,t,this.initialCoordinates,r)}handleStart(){const{initialCoordinates:t}=this,{onStart:r}=this.props;t&&(this.activated=!0,this.documentListeners.add(Cy.Click,Zcs,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(Cy.SelectionChange,this.removeTextSelection),r(t))}handleMove(t){var r;const{activated:n,initialCoordinates:a,props:i}=this,{onMove:l,options:{activationConstraint:o}}=i;if(!a)return;const c=(r=Vke(t))!=null?r:P1,d=I9(a,c);if(!n&&o){if(i$e(o)){if(o.tolerance!=null&&I_e(d,o.tolerance))return this.handleCancel();if(I_e(d,o.distance))return this.handleStart()}if(o$e(o)&&I_e(d,o.tolerance))return this.handleCancel();this.handlePending(o,d);return}t.cancelable&&t.preventDefault(),l(c)}handleEnd(){const{onAbort:t,onEnd:r}=this.props;this.detach(),this.activated||t(this.props.active),r()}handleCancel(){const{onAbort:t,onCancel:r}=this.props;this.detach(),this.activated||t(this.props.active),r()}handleKeydown(t){t.code===hl.Esc&&this.handleCancel()}removeTextSelection(){var t;(t=this.document.getSelection())==null||t.removeAllRanges()}}const Qcs={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class T8 extends XEe{constructor(t){const{event:r}=t,n=S8(r.target);super(t,Qcs,n)}}T8.activators=[{eventName:"onPointerDown",handler:(s,t)=>{let{nativeEvent:r}=s,{onActivation:n}=t;return!r.isPrimary||r.button!==0?!1:(n==null||n({event:r}),!0)}}];const Jcs={move:{name:"mousemove"},end:{name:"mouseup"}};var Gke;(function(s){s[s.RightClick=2]="RightClick"})(Gke||(Gke={}));class eds extends XEe{constructor(t){super(t,Jcs,S8(t.event.target))}}eds.activators=[{eventName:"onMouseDown",handler:(s,t)=>{let{nativeEvent:r}=s,{onActivation:n}=t;return r.button===Gke.RightClick?!1:(n==null||n({event:r}),!0)}}];const P_e={cancel:{name:"touchcancel"},move:{name:"touchmove"},end:{name:"touchend"}};class tds extends XEe{constructor(t){super(t,P_e)}static setup(){return window.addEventListener(P_e.move.name,t,{capture:!1,passive:!1}),function(){window.removeEventListener(P_e.move.name,t)};function t(){}}}tds.activators=[{eventName:"onTouchStart",handler:(s,t)=>{let{nativeEvent:r}=s,{onActivation:n}=t;const{touches:a}=r;return a.length>1?!1:(n==null||n({event:r}),!0)}}];var v7;(function(s){s[s.Pointer=0]="Pointer",s[s.DraggableRect=1]="DraggableRect"})(v7||(v7={}));var sfe;(function(s){s[s.TreeOrder=0]="TreeOrder",s[s.ReversedTreeOrder=1]="ReversedTreeOrder"})(sfe||(sfe={}));function sds(s){let{acceleration:t,activator:r=v7.Pointer,canScroll:n,draggingRect:a,enabled:i,interval:l=5,order:o=sfe.TreeOrder,pointerCoordinates:c,scrollableAncestors:d,scrollableAncestorRects:h,delta:m,threshold:p}=s;const x=nds({delta:m,disabled:!i}),[y,_]=gcs(),b=S.useRef({x:0,y:0}),j=S.useRef({x:0,y:0}),k=S.useMemo(()=>{switch(r){case v7.Pointer:return c?{top:c.y,bottom:c.y,left:c.x,right:c.x}:null;case v7.DraggableRect:return a}},[r,a,c]),T=S.useRef(null),E=S.useCallback(()=>{const D=T.current;if(!D)return;const R=b.current.x*j.current.x,z=b.current.y*j.current.y;D.scrollBy(R,z)},[]),A=S.useMemo(()=>o===sfe.TreeOrder?[...d].reverse():d,[o,d]);S.useEffect(()=>{if(!i||!d.length||!k){_();return}for(const D of A){if((n==null?void 0:n(D))===!1)continue;const R=d.indexOf(D),z=h[R];if(!z)continue;const{direction:O,speed:$}=qcs(D,z,k,t,p);for(const ee of["x","y"])x[ee][O[ee]]||($[ee]=0,O[ee]=0);if($.x>0||$.y>0){_(),T.current=D,y(E,l),b.current=$,j.current=O;return}}b.current={x:0,y:0},j.current={x:0,y:0},_()},[t,E,n,_,i,l,JSON.stringify(k),JSON.stringify(x),y,d,A,h,JSON.stringify(p)])}const rds={x:{[Ym.Backward]:!1,[Ym.Forward]:!1},y:{[Ym.Backward]:!1,[Ym.Forward]:!1}};function nds(s){let{delta:t,disabled:r}=s;const n=qke(t);return _z(a=>{if(r||!n||!a)return rds;const i={x:Math.sign(t.x-n.x),y:Math.sign(t.y-n.y)};return{x:{[Ym.Backward]:a.x[Ym.Backward]||i.x===-1,[Ym.Forward]:a.x[Ym.Forward]||i.x===1},y:{[Ym.Backward]:a.y[Ym.Backward]||i.y===-1,[Ym.Forward]:a.y[Ym.Forward]||i.y===1}}},[r,t,n])}function ads(s,t){const r=t!=null?s.get(t):void 0,n=r?r.node.current:null;return _z(a=>{var i;return t==null?null:(i=n??a)!=null?i:null},[n,t])}function ids(s,t){return S.useMemo(()=>s.reduce((r,n)=>{const{sensor:a}=n,i=a.activators.map(l=>({eventName:l.eventName,handler:t(l.handler,n)}));return[...r,...i]},[]),[s,t])}var P9;(function(s){s[s.Always=0]="Always",s[s.BeforeDragging=1]="BeforeDragging",s[s.WhileDragging=2]="WhileDragging"})(P9||(P9={}));var Wke;(function(s){s.Optimized="optimized"})(Wke||(Wke={}));const l$e=new Map;function ods(s,t){let{dragging:r,dependencies:n,config:a}=t;const[i,l]=S.useState(null),{frequency:o,measure:c,strategy:d}=a,h=S.useRef(s),m=b(),p=M9(m),x=S.useCallback(function(j){j===void 0&&(j=[]),!p.current&&l(k=>k===null?j:k.concat(j.filter(T=>!k.includes(T))))},[p]),y=S.useRef(null),_=_z(j=>{if(m&&!r)return l$e;if(!j||j===l$e||h.current!==s||i!=null){const k=new Map;for(let T of s){if(!T)continue;if(i&&i.length>0&&!i.includes(T.id)&&T.rect.current){k.set(T.id,T.rect.current);continue}const E=T.node.current,A=E?new ZEe(c(E),E):null;T.rect.current=A,A&&k.set(T.id,A)}return k}return j},[s,i,r,m,c]);return S.useEffect(()=>{h.current=s},[s]),S.useEffect(()=>{m||x()},[r,m]),S.useEffect(()=>{i&&i.length>0&&l(null)},[JSON.stringify(i)]),S.useEffect(()=>{m||typeof o!="number"||y.current!==null||(y.current=setTimeout(()=>{x(),y.current=null},o))},[o,m,x,...n]),{droppableRects:_,measureDroppableContainers:x,measuringScheduled:i!=null};function b(){switch(d){case P9.Always:return!1;case P9.BeforeDragging:return r;default:return!r}}}function Pht(s,t){return _z(r=>s?r||(typeof t=="function"?t(s):s):null,[t,s])}function lds(s,t){return Pht(s,t)}function cds(s){let{callback:t,disabled:r}=s;const n=KEe(t),a=S.useMemo(()=>{if(r||typeof window>"u"||typeof window.MutationObserver>"u")return;const{MutationObserver:i}=window;return new i(n)},[n,r]);return S.useEffect(()=>()=>a==null?void 0:a.disconnect(),[a]),a}function Dxe(s){let{callback:t,disabled:r}=s;const n=KEe(t),a=S.useMemo(()=>{if(r||typeof window>"u"||typeof window.ResizeObserver>"u")return;const{ResizeObserver:i}=window;return new i(n)},[r]);return S.useEffect(()=>()=>a==null?void 0:a.disconnect(),[a]),a}function dds(s){return new ZEe(C8(s),s)}function c$e(s,t,r){t===void 0&&(t=dds);const[n,a]=S.useState(null);function i(){a(c=>{if(!s)return null;if(s.isConnected===!1){var d;return(d=c??r)!=null?d:null}const h=t(s);return JSON.stringify(c)===JSON.stringify(h)?c:h})}const l=cds({callback(c){if(s)for(const d of c){const{type:h,target:m}=d;if(h==="childList"&&m instanceof HTMLElement&&m.contains(s)){i();break}}}}),o=Dxe({callback:i});return D_(()=>{i(),s?(o==null||o.observe(s),l==null||l.observe(document.body,{childList:!0,subtree:!0})):(o==null||o.disconnect(),l==null||l.disconnect())},[s]),n}function uds(s){const t=Pht(s);return kht(s,t)}const d$e=[];function hds(s){const t=S.useRef(s),r=_z(n=>s?n&&n!==d$e&&s&&t.current&&s.parentNode===t.current.parentNode?n:Pxe(s):d$e,[s]);return S.useEffect(()=>{t.current=s},[s]),r}function mds(s){const[t,r]=S.useState(null),n=S.useRef(s),a=S.useCallback(i=>{const l=M_e(i.target);l&&r(o=>o?(o.set(l,Hke(l)),new Map(o)):null)},[]);return S.useEffect(()=>{const i=n.current;if(s!==i){l(i);const o=s.map(c=>{const d=M_e(c);return d?(d.addEventListener("scroll",a,{passive:!0}),[d,Hke(d)]):null}).filter(c=>c!=null);r(o.length?new Map(o):null),n.current=s}return()=>{l(s),l(i)};function l(o){o.forEach(c=>{const d=M_e(c);d==null||d.removeEventListener("scroll",a)})}},[a,s]),S.useMemo(()=>s.length?t?Array.from(t.values()).reduce((i,l)=>mP(i,l),P1):Mht(s):P1,[s,t])}function u$e(s,t){t===void 0&&(t=[]);const r=S.useRef(null);return S.useEffect(()=>{r.current=null},t),S.useEffect(()=>{const n=s!==P1;n&&!r.current&&(r.current=s),!n&&r.current&&(r.current=null)},[s]),r.current?I9(s,r.current):P1}function fds(s){S.useEffect(()=>{if(!Axe)return;const t=s.map(r=>{let{sensor:n}=r;return n.setup==null?void 0:n.setup()});return()=>{for(const r of t)r==null||r()}},s.map(t=>{let{sensor:r}=t;return r}))}function pds(s,t){return S.useMemo(()=>s.reduce((r,n)=>{let{eventName:a,handler:i}=n;return r[a]=l=>{i(l,t)},r},{}),[s,t])}function Lht(s){return S.useMemo(()=>s?Bcs(s):null,[s])}const h$e=[];function gds(s,t){t===void 0&&(t=C8);const[r]=s,n=Lht(r?px(r):null),[a,i]=S.useState(h$e);function l(){i(()=>s.length?s.map(c=>Eht(c)?n:new ZEe(t(c),c)):h$e)}const o=Dxe({callback:l});return D_(()=>{o==null||o.disconnect(),l(),s.forEach(c=>o==null?void 0:o.observe(c))},[s]),a}function xds(s){if(!s)return null;if(s.children.length>1)return s;const t=s.children[0];return bz(t)?t:s}function yds(s){let{measure:t}=s;const[r,n]=S.useState(null),a=S.useCallback(d=>{for(const{target:h}of d)if(bz(h)){n(m=>{const p=t(h);return m?{...m,width:p.width,height:p.height}:p});break}},[t]),i=Dxe({callback:a}),l=S.useCallback(d=>{const h=xds(d);i==null||i.disconnect(),h&&(i==null||i.observe(h)),n(h?t(h):null)},[t,i]),[o,c]=efe(l);return S.useMemo(()=>({nodeRef:o,rect:r,setRef:c}),[r,o,c])}const vds=[{sensor:T8,options:{}},{sensor:Lxe,options:{}}],bds={current:{}},Lue={draggable:{measure:n$e},droppable:{measure:n$e,strategy:P9.WhileDragging,frequency:Wke.Optimized},dragOverlay:{measure:C8}};class b7 extends Map{get(t){var r;return t!=null&&(r=super.get(t))!=null?r:void 0}toArray(){return Array.from(this.values())}getEnabled(){return this.toArray().filter(t=>{let{disabled:r}=t;return!r})}getNodeFor(t){var r,n;return(r=(n=this.get(t))==null?void 0:n.node.current)!=null?r:void 0}}const _ds={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new b7,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:tfe},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:Lue,measureDroppableContainers:tfe,windowRect:null,measuringScheduled:!1},wds={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:tfe,draggableNodes:new Map,over:null,measureDroppableContainers:tfe},Rxe=S.createContext(wds),Dht=S.createContext(_ds);function jds(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new b7}}}function Nds(s,t){switch(t.type){case am.DragStart:return{...s,draggable:{...s.draggable,initialCoordinates:t.initialCoordinates,active:t.active}};case am.DragMove:return s.draggable.active==null?s:{...s,draggable:{...s.draggable,translate:{x:t.coordinates.x-s.draggable.initialCoordinates.x,y:t.coordinates.y-s.draggable.initialCoordinates.y}}};case am.DragEnd:case am.DragCancel:return{...s,draggable:{...s.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case am.RegisterDroppable:{const{element:r}=t,{id:n}=r,a=new b7(s.droppable.containers);return a.set(n,r),{...s,droppable:{...s.droppable,containers:a}}}case am.SetDroppableDisabled:{const{id:r,key:n,disabled:a}=t,i=s.droppable.containers.get(r);if(!i||n!==i.key)return s;const l=new b7(s.droppable.containers);return l.set(r,{...i,disabled:a}),{...s,droppable:{...s.droppable,containers:l}}}case am.UnregisterDroppable:{const{id:r,key:n}=t,a=s.droppable.containers.get(r);if(!a||n!==a.key)return s;const i=new b7(s.droppable.containers);return i.delete(r),{...s,droppable:{...s.droppable,containers:i}}}default:return s}}function kds(s){let{disabled:t}=s;const{active:r,activatorEvent:n,draggableNodes:a}=S.useContext(Rxe),i=qke(n),l=qke(r==null?void 0:r.id);return S.useEffect(()=>{if(!t&&!n&&i&&l!=null){if(!YEe(i)||document.activeElement===i.target)return;const o=a.get(l);if(!o)return;const{activatorNode:c,node:d}=o;if(!c.current&&!d.current)return;requestAnimationFrame(()=>{for(const h of[c.current,d.current]){if(!h)continue;const m=vcs(h);if(m){m.focus();break}}})}},[n,t,a,l,i]),null}function Sds(s,t){let{transform:r,...n}=t;return s!=null&&s.length?s.reduce((a,i)=>i({transform:a,...n}),r):r}function Cds(s){return S.useMemo(()=>({draggable:{...Lue.draggable,...s==null?void 0:s.draggable},droppable:{...Lue.droppable,...s==null?void 0:s.droppable},dragOverlay:{...Lue.dragOverlay,...s==null?void 0:s.dragOverlay}}),[s==null?void 0:s.draggable,s==null?void 0:s.droppable,s==null?void 0:s.dragOverlay])}function Tds(s){let{activeNode:t,measure:r,initialRect:n,config:a=!0}=s;const i=S.useRef(!1),{x:l,y:o}=typeof a=="boolean"?{x:a,y:a}:a;D_(()=>{if(!l&&!o||!t){i.current=!1;return}if(i.current||!n)return;const d=t==null?void 0:t.node.current;if(!d||d.isConnected===!1)return;const h=r(d),m=kht(h,n);if(l||(m.x=0),o||(m.y=0),i.current=!0,Math.abs(m.x)>0||Math.abs(m.y)>0){const p=Sht(d);p&&p.scrollBy({top:m.y,left:m.x})}},[t,l,o,n,r])}const Rht=S.createContext({...P1,scaleX:1,scaleY:1});var WN;(function(s){s[s.Uninitialized=0]="Uninitialized",s[s.Initializing=1]="Initializing",s[s.Initialized=2]="Initialized"})(WN||(WN={}));const Oxe=S.memo(function(t){var r,n,a,i;let{id:l,accessibility:o,autoScroll:c=!0,children:d,sensors:h=vds,collisionDetection:m=Ics,measuring:p,modifiers:x,...y}=t;const _=S.useReducer(Nds,void 0,jds),[b,j]=_,[k,T]=kcs(),[E,A]=S.useState(WN.Uninitialized),D=E===WN.Initialized,{draggable:{active:R,nodes:z,translate:O},droppable:{containers:$}}=b,ee=R!=null?z.get(R):null,Z=S.useRef({initial:null,translated:null}),J=S.useMemo(()=>{var rn;return R!=null?{id:R,data:(rn=ee==null?void 0:ee.data)!=null?rn:bds,rect:Z}:null},[R,ee]),K=S.useRef(null),[re,ie]=S.useState(null),[ce,ne]=S.useState(null),le=M9(y,Object.values(y)),be=wz("DndDescribedBy",l),fe=S.useMemo(()=>$.getEnabled(),[$]),je=Cds(p),{droppableRects:ve,measureDroppableContainers:We,measuringScheduled:Ve}=ods(fe,{dragging:D,dependencies:[O.x,O.y],config:je.droppable}),Le=ads(z,R),Me=S.useMemo(()=>ce?Vke(ce):null,[ce]),ze=Yr(),Pe=lds(Le,je.draggable.measure);Tds({activeNode:R!=null?z.get(R):null,config:ze.layoutShiftCompensation,initialRect:Pe,measure:je.draggable.measure});const Ie=c$e(Le,je.draggable.measure,Pe),De=c$e(Le?Le.parentElement:null),pe=S.useRef({activatorEvent:null,active:null,activeNode:Le,collisionRect:null,collisions:null,droppableRects:ve,draggableNodes:z,draggingNode:null,draggingNodeRect:null,droppableContainers:$,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),tt=$.getNodeFor((r=pe.current.over)==null?void 0:r.id),ge=yds({measure:je.dragOverlay.measure}),ct=(n=ge.nodeRef.current)!=null?n:Le,Ue=D?(a=ge.rect)!=null?a:Ie:null,et=!!(ge.nodeRef.current&&ge.rect),Qe=uds(et?null:Ie),Ne=Lht(ct?px(ct):null),$e=hds(D?tt??Le:null),it=gds($e),Je=Sds(x,{transform:{x:O.x-Qe.x,y:O.y-Qe.y,scaleX:1,scaleY:1},activatorEvent:ce,active:J,activeNodeRect:Ie,containerNodeRect:De,draggingNodeRect:Ue,over:pe.current.over,overlayNodeRect:ge.rect,scrollableAncestors:$e,scrollableAncestorRects:it,windowRect:Ne}),st=Me?mP(Me,O):null,mt=mds($e),wt=u$e(mt),at=u$e(mt,[Ie]),rt=mP(Je,wt),Et=Ue?Dcs(Ue,Je):null,hs=J&&Et?m({active:J,collisionRect:Et,droppableRects:ve,droppableContainers:fe,pointerCoordinates:st}):null,Is=Nht(hs,"id"),[lr,us]=S.useState(null),St=et?Je:mP(Je,at),xs=Pcs(St,(i=lr==null?void 0:lr.rect)!=null?i:null,Ie),kt=S.useRef(null),fs=S.useCallback((rn,sn)=>{let{sensor:Vr,options:$r}=sn;if(K.current==null)return;const hn=z.get(K.current);if(!hn)return;const Zn=rn.nativeEvent,cr=new Vr({active:K.current,activeNode:hn,event:Zn,options:$r,context:pe,onAbort(ds){if(!z.get(ds))return;const{onDragAbort:vn}=le.current,_r={id:ds};vn==null||vn(_r),k({type:"onDragAbort",event:_r})},onPending(ds,Na,vn,_r){if(!z.get(ds))return;const{onDragPending:_a}=le.current,Jt={id:ds,constraint:Na,initialCoordinates:vn,offset:_r};_a==null||_a(Jt),k({type:"onDragPending",event:Jt})},onStart(ds){const Na=K.current;if(Na==null)return;const vn=z.get(Na);if(!vn)return;const{onDragStart:_r}=le.current,Hr={activatorEvent:Zn,active:{id:Na,data:vn.data,rect:Z}};tx.unstable_batchedUpdates(()=>{_r==null||_r(Hr),A(WN.Initializing),j({type:am.DragStart,initialCoordinates:ds,active:Na}),k({type:"onDragStart",event:Hr}),ie(kt.current),ne(Zn)})},onMove(ds){j({type:am.DragMove,coordinates:ds})},onEnd:on(am.DragEnd),onCancel:on(am.DragCancel)});kt.current=cr;function on(ds){return async function(){const{active:vn,collisions:_r,over:Hr,scrollAdjustedTranslate:_a}=pe.current;let Jt=null;if(vn&&_a){const{cancelDrop:Cr}=le.current;Jt={activatorEvent:Zn,active:vn,collisions:_r,delta:_a,over:Hr},ds===am.DragEnd&&typeof Cr=="function"&&await Promise.resolve(Cr(Jt))&&(ds=am.DragCancel)}K.current=null,tx.unstable_batchedUpdates(()=>{j({type:ds}),A(WN.Uninitialized),us(null),ie(null),ne(null),kt.current=null;const Cr=ds===am.DragEnd?"onDragEnd":"onDragCancel";if(Jt){const Gt=le.current[Cr];Gt==null||Gt(Jt),k({type:Cr,event:Jt})}})}}},[z]),Gs=S.useCallback((rn,sn)=>(Vr,$r)=>{const hn=Vr.nativeEvent,Zn=z.get($r);if(K.current!==null||!Zn||hn.dndKit||hn.defaultPrevented)return;const cr={active:Zn};rn(Vr,sn.options,cr)===!0&&(hn.dndKit={capturedBy:sn.sensor},K.current=$r,fs(Vr,sn))},[z,fs]),_s=ids(h,Gs);fds(h),D_(()=>{Ie&&E===WN.Initializing&&A(WN.Initialized)},[Ie,E]),S.useEffect(()=>{const{onDragMove:rn}=le.current,{active:sn,activatorEvent:Vr,collisions:$r,over:hn}=pe.current;if(!sn||!Vr)return;const Zn={active:sn,activatorEvent:Vr,collisions:$r,delta:{x:rt.x,y:rt.y},over:hn};tx.unstable_batchedUpdates(()=>{rn==null||rn(Zn),k({type:"onDragMove",event:Zn})})},[rt.x,rt.y]),S.useEffect(()=>{const{active:rn,activatorEvent:sn,collisions:Vr,droppableContainers:$r,scrollAdjustedTranslate:hn}=pe.current;if(!rn||K.current==null||!sn||!hn)return;const{onDragOver:Zn}=le.current,cr=$r.get(Is),on=cr&&cr.rect.current?{id:cr.id,rect:cr.rect.current,data:cr.data,disabled:cr.disabled}:null,ds={active:rn,activatorEvent:sn,collisions:Vr,delta:{x:hn.x,y:hn.y},over:on};tx.unstable_batchedUpdates(()=>{us(on),Zn==null||Zn(ds),k({type:"onDragOver",event:ds})})},[Is]),D_(()=>{pe.current={activatorEvent:ce,active:J,activeNode:Le,collisionRect:Et,collisions:hs,droppableRects:ve,draggableNodes:z,draggingNode:ct,draggingNodeRect:Ue,droppableContainers:$,over:lr,scrollableAncestors:$e,scrollAdjustedTranslate:rt},Z.current={initial:Ue,translated:Et}},[J,Le,hs,Et,z,ct,Ue,ve,$,lr,$e,rt]),sds({...ze,delta:O,draggingRect:Et,pointerCoordinates:st,scrollableAncestors:$e,scrollableAncestorRects:it});const br=S.useMemo(()=>({active:J,activeNode:Le,activeNodeRect:Ie,activatorEvent:ce,collisions:hs,containerNodeRect:De,dragOverlay:ge,draggableNodes:z,droppableContainers:$,droppableRects:ve,over:lr,measureDroppableContainers:We,scrollableAncestors:$e,scrollableAncestorRects:it,measuringConfiguration:je,measuringScheduled:Ve,windowRect:Ne}),[J,Le,Ie,ce,hs,De,ge,z,$,ve,lr,We,$e,it,je,Ve,Ne]),zr=S.useMemo(()=>({activatorEvent:ce,activators:_s,active:J,activeNodeRect:Ie,ariaDescribedById:{draggable:be},dispatch:j,draggableNodes:z,over:lr,measureDroppableContainers:We}),[ce,_s,J,Ie,j,be,z,lr,We]);return Nt.createElement(_ht.Provider,{value:T},Nt.createElement(Rxe.Provider,{value:zr},Nt.createElement(Dht.Provider,{value:br},Nt.createElement(Rht.Provider,{value:xs},d)),Nt.createElement(kds,{disabled:(o==null?void 0:o.restoreFocus)===!1})),Nt.createElement(Tcs,{...o,hiddenTextDescribedById:be}));function Yr(){const rn=(re==null?void 0:re.autoScrollEnabled)===!1,sn=typeof c=="object"?c.enabled===!1:c===!1,Vr=D&&!rn&&!sn;return typeof c=="object"?{...c,enabled:Vr}:{enabled:Vr}}}),Eds=S.createContext(null),m$e="button",Ads="Draggable";function Mds(s){let{id:t,data:r,disabled:n=!1,attributes:a}=s;const i=wz(Ads),{activators:l,activatorEvent:o,active:c,activeNodeRect:d,ariaDescribedById:h,draggableNodes:m,over:p}=S.useContext(Rxe),{role:x=m$e,roleDescription:y="draggable",tabIndex:_=0}=a??{},b=(c==null?void 0:c.id)===t,j=S.useContext(b?Rht:Eds),[k,T]=efe(),[E,A]=efe(),D=pds(l,t),R=M9(r);D_(()=>(m.set(t,{id:t,key:i,node:k,activatorNode:E,data:R}),()=>{const O=m.get(t);O&&O.key===i&&m.delete(t)}),[m,t]);const z=S.useMemo(()=>({role:x,tabIndex:_,"aria-disabled":n,"aria-pressed":b&&x===m$e?!0:void 0,"aria-roledescription":y,"aria-describedby":h.draggable}),[n,x,_,b,y,h.draggable]);return{active:c,activatorEvent:o,activeNodeRect:d,attributes:z,isDragging:b,listeners:n?void 0:D,node:k,over:p,setNodeRef:T,setActivatorNodeRef:A,transform:j}}function Ids(){return S.useContext(Dht)}const Pds="Droppable",Lds={timeout:25};function Dds(s){let{data:t,disabled:r=!1,id:n,resizeObserverConfig:a}=s;const i=wz(Pds),{active:l,dispatch:o,over:c,measureDroppableContainers:d}=S.useContext(Rxe),h=S.useRef({disabled:r}),m=S.useRef(!1),p=S.useRef(null),x=S.useRef(null),{disabled:y,updateMeasurementsFor:_,timeout:b}={...Lds,...a},j=M9(_??n),k=S.useCallback(()=>{if(!m.current){m.current=!0;return}x.current!=null&&clearTimeout(x.current),x.current=setTimeout(()=>{d(Array.isArray(j.current)?j.current:[j.current]),x.current=null},b)},[b]),T=Dxe({callback:k,disabled:y||!l}),E=S.useCallback((z,O)=>{T&&(O&&(T.unobserve(O),m.current=!1),z&&T.observe(z))},[T]),[A,D]=efe(E),R=M9(t);return S.useEffect(()=>{!T||!A.current||(T.disconnect(),m.current=!1,T.observe(A.current))},[A,T]),S.useEffect(()=>(o({type:am.RegisterDroppable,element:{id:n,key:i,disabled:r,node:A,rect:p,data:R}}),()=>o({type:am.UnregisterDroppable,key:i,id:n})),[n]),S.useEffect(()=>{r!==h.current.disabled&&(o({type:am.SetDroppableDisabled,id:n,key:i,disabled:r}),h.current.disabled=r)},[n,i,r,o]),{active:l,rect:p,isOver:(c==null?void 0:c.id)===n,node:A,over:c,setNodeRef:D}}function Fxe(s,t,r){const n=s.slice();return n.splice(r<0?n.length+r:r,0,n.splice(t,1)[0]),n}function Rds(s,t){return s.reduce((r,n,a)=>{const i=t.get(n);return i&&(r[a]=i),r},Array(s.length))}function Sq(s){return s!==null&&s>=0}function Ods(s,t){if(s===t)return!0;if(s.length!==t.length)return!1;for(let r=0;r{var t;let{rects:r,activeNodeRect:n,activeIndex:a,overIndex:i,index:l}=s;const o=(t=r[a])!=null?t:n;if(!o)return null;const c=Bds(r,l,a);if(l===a){const d=r[i];return d?{x:aa&&l<=i?{x:-o.width-c,y:0,...Cq}:l=i?{x:o.width+c,y:0,...Cq}:{x:0,y:0,...Cq}};function Bds(s,t,r){const n=s[t],a=s[t-1],i=s[t+1];return!n||!a&&!i?0:r{let{rects:t,activeIndex:r,overIndex:n,index:a}=s;const i=Fxe(t,n,r),l=t[a],o=i[a];return!o||!l?null:{x:o.left-l.left,y:o.top-l.top,scaleX:o.width/l.width,scaleY:o.height/l.height}},Tq={scaleX:1,scaleY:1},zds=s=>{var t;let{activeIndex:r,activeNodeRect:n,index:a,rects:i,overIndex:l}=s;const o=(t=i[r])!=null?t:n;if(!o)return null;if(a===r){const d=i[l];return d?{x:0,y:rr&&a<=l?{x:0,y:-o.height-c,...Tq}:a=l?{x:0,y:o.height+c,...Tq}:{x:0,y:0,...Tq}};function $ds(s,t,r){const n=s[t],a=s[t-1],i=s[t+1];return n?rn.map(D=>typeof D=="object"&&"id"in D?D.id:D),[n]),y=l!=null,_=l?x.indexOf(l.id):-1,b=d?x.indexOf(d.id):-1,j=S.useRef(x),k=!Ods(x,j.current),T=b!==-1&&_===-1||k,E=Fds(i);D_(()=>{k&&y&&h(x)},[k,x,y,h]),S.useEffect(()=>{j.current=x},[x]);const A=S.useMemo(()=>({activeIndex:_,containerId:m,disabled:E,disableTransforms:T,items:x,overIndex:b,useDragOverlay:p,sortedRects:Rds(x,c),strategy:a}),[_,m,E.draggable,E.droppable,T,x,b,c,p,a]);return Nt.createElement(Fht.Provider,{value:A},t)}const Uds=s=>{let{id:t,items:r,activeIndex:n,overIndex:a}=s;return Fxe(r,n,a).indexOf(t)},qds=s=>{let{containerId:t,isSorting:r,wasDragging:n,index:a,items:i,newIndex:l,previousItems:o,previousContainerId:c,transition:d}=s;return!d||!n||o!==i&&a===l?!1:r?!0:l!==a&&t===c},Vds={duration:200,easing:"ease"},Bht="transform",Hds=kS.Transition.toString({property:Bht,duration:0,easing:"linear"}),Gds={roleDescription:"sortable"};function Wds(s){let{disabled:t,index:r,node:n,rect:a}=s;const[i,l]=S.useState(null),o=S.useRef(r);return D_(()=>{if(!t&&r!==o.current&&n.current){const c=a.current;if(c){const d=C8(n.current,{ignoreTransform:!0}),h={x:c.left-d.left,y:c.top-d.top,scaleX:c.width/d.width,scaleY:c.height/d.height};(h.x||h.y)&&l(h)}}r!==o.current&&(o.current=r)},[t,r,n,a]),S.useEffect(()=>{i&&l(null)},[i]),i}function zxe(s){let{animateLayoutChanges:t=qds,attributes:r,disabled:n,data:a,getNewIndex:i=Uds,id:l,strategy:o,resizeObserverConfig:c,transition:d=Vds}=s;const{items:h,containerId:m,activeIndex:p,disabled:x,disableTransforms:y,sortedRects:_,overIndex:b,useDragOverlay:j,strategy:k}=S.useContext(Fht),T=Kds(n,x),E=h.indexOf(l),A=S.useMemo(()=>({sortable:{containerId:m,index:E,items:h},...a}),[m,a,E,h]),D=S.useMemo(()=>h.slice(h.indexOf(l)),[h,l]),{rect:R,node:z,isOver:O,setNodeRef:$}=Dds({id:l,data:A,disabled:T.droppable,resizeObserverConfig:{updateMeasurementsFor:D,...c}}),{active:ee,activatorEvent:Z,activeNodeRect:J,attributes:K,setNodeRef:re,listeners:ie,isDragging:ce,over:ne,setActivatorNodeRef:le,transform:be}=Mds({id:l,data:A,attributes:{...Gds,...r},disabled:T.draggable}),fe=pcs($,re),je=!!ee,ve=je&&!y&&Sq(p)&&Sq(b),We=!j&&ce,Ve=We&&ve?be:null,Me=ve?Ve??(o??k)({rects:_,activeNodeRect:J,activeIndex:p,overIndex:b,index:E}):null,ze=Sq(p)&&Sq(b)?i({id:l,items:h,activeIndex:p,overIndex:b}):E,Pe=ee==null?void 0:ee.id,Ie=S.useRef({activeId:Pe,items:h,newIndex:ze,containerId:m}),De=h!==Ie.current.items,pe=t({active:ee,containerId:m,isDragging:ce,isSorting:je,id:l,index:E,items:h,newIndex:Ie.current.newIndex,previousItems:Ie.current.items,previousContainerId:Ie.current.containerId,transition:d,wasDragging:Ie.current.activeId!=null}),tt=Wds({disabled:!pe,index:E,node:z,rect:R});return S.useEffect(()=>{je&&Ie.current.newIndex!==ze&&(Ie.current.newIndex=ze),m!==Ie.current.containerId&&(Ie.current.containerId=m),h!==Ie.current.items&&(Ie.current.items=h)},[je,ze,m,h]),S.useEffect(()=>{if(Pe===Ie.current.activeId)return;if(Pe!=null&&Ie.current.activeId==null){Ie.current.activeId=Pe;return}const ct=setTimeout(()=>{Ie.current.activeId=Pe},50);return()=>clearTimeout(ct)},[Pe]),{active:ee,activeIndex:p,attributes:K,data:A,rect:R,index:E,newIndex:ze,items:h,isOver:O,isSorting:je,isDragging:ce,listeners:ie,node:z,overIndex:b,over:ne,setNodeRef:fe,setActivatorNodeRef:le,setDroppableNodeRef:$,setDraggableNodeRef:re,transform:tt??Me,transition:ge()};function ge(){if(tt||De&&Ie.current.newIndex===E)return Hds;if(!(We&&!YEe(Z)||!d)&&(je||pe))return kS.Transition.toString({...d,property:Bht})}}function Kds(s,t){var r,n;return typeof s=="boolean"?{draggable:s,droppable:!1}:{draggable:(r=s==null?void 0:s.draggable)!=null?r:t.draggable,droppable:(n=s==null?void 0:s.droppable)!=null?n:t.droppable}}function rfe(s){if(!s)return!1;const t=s.data.current;return!!(t&&"sortable"in t&&typeof t.sortable=="object"&&"containerId"in t.sortable&&"items"in t.sortable&&"index"in t.sortable)}const Yds=[hl.Down,hl.Right,hl.Up,hl.Left],zht=(s,t)=>{let{context:{active:r,collisionRect:n,droppableRects:a,droppableContainers:i,over:l,scrollableAncestors:o}}=t;if(Yds.includes(s.code)){if(s.preventDefault(),!r||!n)return;const c=[];i.getEnabled().forEach(m=>{if(!m||m!=null&&m.disabled)return;const p=a.get(m.id);if(p)switch(s.code){case hl.Down:n.topp.top&&c.push(m);break;case hl.Left:n.left>p.left&&c.push(m);break;case hl.Right:n.left1&&(h=d[1].id),h!=null){const m=i.get(r.id),p=i.get(h),x=p?a.get(p.id):null,y=p==null?void 0:p.node.current;if(y&&x&&m&&p){const b=Pxe(y).some((D,R)=>o[R]!==D),j=$ht(m,p),k=Zds(m,p),T=b||!j?{x:0,y:0}:{x:k?n.width-x.width:0,y:k?n.height-x.height:0},E={x:x.left,y:x.top};return T.x&&T.y?E:I9(E,T)}}}};function $ht(s,t){return!rfe(s)||!rfe(t)?!1:s.data.current.sortable.containerId===t.data.current.sortable.containerId}function Zds(s,t){return!rfe(s)||!rfe(t)||!$ht(s,t)?!1:s.data.current.sortable.indext(s),children:e.jsx(ni,{className:"h-3.5 w-3.5"})}),e.jsx(H,{variant:"destructive",size:"icon",className:"h-7 w-7",onClick:()=>r(s),children:e.jsx(Dr,{className:"h-3.5 w-3.5"})})]}),s.post_date&&e.jsx("div",{className:"absolute bottom-2 left-2",children:e.jsxs(Xe,{className:"bg-primary/90 text-primary-foreground text-[10px] gap-1 backdrop-blur-sm px-1.5 py-0.5",children:[e.jsx(Nn,{className:"h-2.5 w-2.5"}),As(new Date(s.post_date+"T00:00:00"),"MMM d")]})})]}),e.jsxs(Oe,{className:"p-3 space-y-2",children:[e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-3",children:s.caption}),e.jsxs(gl,{children:[e.jsx(xl,{asChild:!0,children:e.jsxs(H,{variant:"outline",size:"sm",className:Ft("w-full h-7 text-[11px] gap-1 justify-start font-normal",!s.post_date&&"text-muted-foreground"),children:[e.jsx(Nn,{className:"h-3 w-3"}),s.post_date?As(new Date(s.post_date+"T00:00:00"),"MMM d, yyyy"):"Set post date"]})}),e.jsxs(il,{className:"w-auto p-0",align:"start",children:[e.jsx(g0,{mode:"single",selected:s.post_date?new Date(s.post_date+"T00:00:00"):void 0,onSelect:m=>n(s.id,m?As(m,"yyyy-MM-dd"):null),className:"p-3 pointer-events-auto"}),s.post_date&&e.jsx("div",{className:"p-2 border-t",children:e.jsx(H,{variant:"ghost",size:"sm",className:"w-full text-xs text-muted-foreground",onClick:()=>n(s.id,null),children:"Clear date"})})]})]})]})]})})}const Qds=()=>{const s=ns(),[t,r]=S.useState("all"),[n,a]=S.useState(!1),[i,l]=S.useState(As(new Date,"yyyy-MM")),[o,c]=S.useState([]),[d,h]=S.useState(!1),[m,p]=S.useState(null),[x,y]=S.useState(null),[_,b]=S.useState(""),[j,k]=S.useState(null),[T,E]=S.useState(!1),[A,D]=S.useState(!1),[R,z]=S.useState(As(new Date,"yyyy-MM")),[O,$]=S.useState(null),[ee,Z]=S.useState(""),[J,K]=S.useState(""),[re,ie]=S.useState(""),[ce,ne]=S.useState(!1),le=Mxe(fL(T8,{activationConstraint:{distance:5}}),fL(Lxe,{coordinateGetter:zht})),{data:be=[],isLoading:fe}=yt({queryKey:["admin-social-swag-2"],queryFn:async()=>{const{data:st,error:mt}=await V.from("social_swag_2").select("*").order("month",{ascending:!1}).order("sort_order");if(mt)throw mt;return st}}),{data:je=[]}=yt({queryKey:["admin-social-swag-2-months"],queryFn:async()=>{const{data:st,error:mt}=await V.from("social_swag_2_months").select("*").order("month",{ascending:!1});if(mt)throw mt;return st}}),{data:ve=[]}=yt({queryKey:["admin-social-swag-2-reels"],queryFn:async()=>{const{data:st,error:mt}=await V.from("social_swag_2_reels").select("*").order("month",{ascending:!1});if(mt)throw mt;return st}}),We=[...new Set(be.map(st=>st.month))].sort((st,mt)=>mt.localeCompare(st)),Ve=t==="all"?be:be.filter(st=>st.month===t),Le=st=>{const mt=g5e(st,"yyyy-MM",new Date);return As(mt,"MMMM yyyy")},Me=st=>{y(st),b(st.caption),k(st.post_date)},ze=async()=>{if(x){E(!0);try{const{error:st}=await V.from("social_swag_2").update({caption:_,post_date:j}).eq("id",x.id);if(st)throw st;he.success("Image updated"),y(null),s.invalidateQueries({queryKey:["admin-social-swag-2"]}),s.invalidateQueries({queryKey:["social-swag-2"]})}catch{he.error("Failed to update image")}finally{E(!1)}}},Pe=async st=>{const{active:mt,over:wt}=st;if(!wt||mt.id===wt.id)return;const at=Ve,rt=at.findIndex(Is=>Is.id===mt.id),Et=at.findIndex(Is=>Is.id===wt.id);if(rt===-1||Et===-1)return;const hs=Fxe(at,rt,Et);s.setQueryData(["admin-social-swag-2"],Is=>{if(!Is)return Is;const lr={};return hs.forEach((us,St)=>{lr[us.id]=St}),Is.map(us=>lr[us.id]!==void 0?{...us,sort_order:lr[us.id]}:us).sort((us,St)=>us.month!==St.month?St.month.localeCompare(us.month):us.sort_order-St.sort_order)});try{await Promise.all(hs.map((Is,lr)=>V.from("social_swag_2").update({sort_order:lr}).eq("id",Is.id)))}catch{he.error("Failed to save order"),s.invalidateQueries({queryKey:["admin-social-swag-2"]})}},Ie=st=>{const wt=Array.from(st.target.files||[]).sort((at,rt)=>at.name.localeCompare(rt.name,void 0,{numeric:!0,sensitivity:"base"})).slice(0,16-o.length).map(at=>({file:at,preview:URL.createObjectURL(at),caption:""}));c(at=>[...at,...wt].slice(0,16))},De=st=>{c(mt=>{const wt=[...mt];return URL.revokeObjectURL(wt[st].preview),wt.splice(st,1),wt})},pe=(st,mt)=>{c(wt=>{const at=[...wt];return at[st]={...at[st],caption:mt},at})},tt=async()=>{var mt;if(o.length===0){he.error("Please add at least one image");return}if(o.filter(wt=>!wt.caption.trim()).length>0){he.error("Please add captions to all images");return}h(!0);try{const{data:wt}=await V.from("social_swag_2").select("sort_order").eq("month",i).order("sort_order",{ascending:!1}).limit(1),at=(((mt=wt==null?void 0:wt[0])==null?void 0:mt.sort_order)??-1)+1;for(let rt=0;rt{const mt=st.image_url.split("/social-swag-2/");mt[1]&&await V.storage.from("social-swag-2").remove([mt[1]]);const{error:wt}=await V.from("social_swag_2").delete().eq("id",st.id);if(wt)throw wt},onSuccess:()=>{he.success("Image deleted"),s.invalidateQueries({queryKey:["admin-social-swag-2"]})},onError:()=>he.error("Failed to delete image")}),ct=Pt({mutationFn:async({id:st,postDate:mt})=>{const{error:wt}=await V.from("social_swag_2").update({post_date:mt}).eq("id",st);if(wt)throw wt},onSuccess:()=>{he.success("Post date updated"),s.invalidateQueries({queryKey:["admin-social-swag-2"]}),s.invalidateQueries({queryKey:["social-swag-2"]})},onError:()=>he.error("Failed to update post date")}),Ue=Pt({mutationFn:async({month:st,link:mt})=>{const{error:wt}=await V.from("social_swag_2_months").upsert({month:st,canva_link:mt||null},{onConflict:"month"});if(wt)throw wt},onSuccess:()=>{he.success("Canva link updated"),p(null),s.invalidateQueries({queryKey:["admin-social-swag-2-months"]})},onError:()=>he.error("Failed to update Canva link")}),et=st=>{var mt;return((mt=je.find(wt=>wt.month===st))==null?void 0:mt.canva_link)||""},Qe=st=>ve.find(mt=>mt.month===st)||null,Ne=st=>{var wt;const mt=(wt=st.target.files)==null?void 0:wt[0];mt&&($(mt),Z(URL.createObjectURL(mt)))},$e=()=>{ee&&URL.revokeObjectURL(ee),$(null),Z(""),K(""),ie("")},it=async()=>{if(!O){he.error("Please select an image");return}ne(!0);try{const st=O.name.split(".").pop(),mt=`reels/${R}-${Date.now()}.${st}`,{error:wt}=await V.storage.from("social-swag-2").upload(mt,O);if(wt)throw wt;const{data:{publicUrl:at}}=V.storage.from("social-swag-2").getPublicUrl(mt),{error:rt}=await V.from("social_swag_2_reels").upsert({month:R,image_url:at,canva_link:re||null,caption:J||null},{onConflict:"month"});if(rt)throw rt;he.success("Reel uploaded successfully!"),Uke(`${Le(R)} Reel`,"social-swag-2"),$e(),D(!1),s.invalidateQueries({queryKey:["admin-social-swag-2-reels"]})}catch(st){console.error("Reel upload error:",st),he.error("Failed to upload reel")}finally{ne(!1)}},Je=Pt({mutationFn:async st=>{const mt=st.image_url.split("/social-swag-2/");mt[1]&&await V.storage.from("social-swag-2").remove([mt[1]]);const{error:wt}=await V.from("social_swag_2_reels").delete().eq("id",st.id);if(wt)throw wt},onSuccess:()=>{he.success("Reel deleted"),s.invalidateQueries({queryKey:["admin-social-swag-2-reels"]})},onError:()=>he.error("Failed to delete reel")});return e.jsxs(Ss,{title:"Admin - Social Swag 2.0",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Social Swag 2.0"}),e.jsx("p",{className:"text-muted-foreground",children:"Manage monthly social media images and captions"})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(bs,{open:n,onOpenChange:a,children:[e.jsx(Qi,{asChild:!0,children:e.jsxs(H,{className:"gap-2",children:[e.jsx(Ys,{className:"h-4 w-4"}),"Upload Images"]})}),e.jsxs(vs,{className:"max-w-4xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Cs,{children:e.jsx(Ns,{children:"Upload Social Swag Images"})}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Month"}),e.jsx(Se,{type:"month",value:i,onChange:st=>l(st.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ue,{children:["Images (",o.length,"/16)"]}),e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-6 text-center",children:[e.jsx("input",{type:"file",accept:"image/*",multiple:!0,onChange:Ie,className:"hidden",id:"swag-upload",disabled:o.length>=16}),e.jsxs("label",{htmlFor:"swag-upload",className:"cursor-pointer",children:[e.jsx(Ea,{className:"h-8 w-8 mx-auto text-muted-foreground mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Click to select images (max 16)"})]})]})]}),o.length>0&&e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:o.map((st,mt)=>e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"relative aspect-[4/5] rounded-lg overflow-hidden bg-muted",children:[e.jsx("img",{src:st.preview,alt:`Upload ${mt+1}`,className:"w-full h-full object-cover"}),e.jsx(H,{variant:"destructive",size:"icon",className:"absolute top-1 right-1 h-6 w-6",onClick:()=>De(mt),children:e.jsx(Rr,{className:"h-3 w-3"})})]}),e.jsx(vr,{placeholder:"Caption...",value:st.caption,onChange:wt=>pe(mt,wt.target.value),className:"text-xs h-20"})]},mt))}),e.jsx(H,{onClick:tt,disabled:d||o.length===0,className:"w-full gap-2",children:d?e.jsxs(e.Fragment,{children:[e.jsx(is,{className:"h-4 w-4 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ea,{className:"h-4 w-4"}),"Upload ",o.length," Images"]})})]})]})]}),e.jsxs(bs,{open:A,onOpenChange:st=>{D(st),st||$e()},children:[e.jsx(Qi,{asChild:!0,children:e.jsxs(H,{variant:"outline",className:"gap-2",children:[e.jsx(Qm,{className:"h-4 w-4"}),"Upload Reel"]})}),e.jsxs(vs,{className:"max-w-lg max-h-[85vh] overflow-y-auto",children:[e.jsx(Cs,{children:e.jsx(Ns,{children:"Upload Monthly Reel"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Month"}),e.jsx(Se,{type:"month",value:R,onChange:st=>z(st.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Reel Preview Image"}),ee?e.jsxs("div",{className:"relative aspect-[9/16] max-w-[120px] mx-auto rounded-lg overflow-hidden bg-muted",children:[e.jsx("img",{src:ee,alt:"Reel preview",className:"w-full h-full object-cover"}),e.jsx(H,{variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-6 w-6",onClick:()=>{URL.revokeObjectURL(ee),$(null),Z("")},children:e.jsx(Rr,{className:"h-3 w-3"})})]}):e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-6 text-center",children:[e.jsx("input",{type:"file",accept:"image/*",onChange:Ne,className:"hidden",id:"reel-upload"}),e.jsxs("label",{htmlFor:"reel-upload",className:"cursor-pointer",children:[e.jsx(Qm,{className:"h-8 w-8 mx-auto text-muted-foreground mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Click to select reel preview image"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Canva Download Link"}),e.jsx(Se,{value:re,onChange:st=>ie(st.target.value),placeholder:"https://www.canva.com/..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Caption"}),e.jsx(vr,{value:J,onChange:st=>K(st.target.value),placeholder:"Enter caption for this reel...",className:"h-24"})]}),e.jsx(H,{onClick:it,disabled:ce||!O,className:"w-full gap-2",children:ce?e.jsxs(e.Fragment,{children:[e.jsx(is,{className:"h-4 w-4 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ea,{className:"h-4 w-4"}),"Upload Reel"]})})]})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(ke,{children:e.jsxs(Oe,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:be.length}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Total Images"})]})}),e.jsx(ke,{children:e.jsxs(Oe,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:We.length}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Months"})]})})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(ta,{value:t,onValueChange:r,children:e.jsxs(Qn,{children:[e.jsx(ts,{value:"all",children:"All"}),We.map(st=>e.jsx(ts,{value:st,children:Le(st)},st))]})}),t!=="all"&&e.jsx(ke,{children:e.jsx(Oe,{className:"p-4",children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(Jo,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs(ue,{className:"text-sm text-muted-foreground",children:["Canva Edit Link for ",Le(t)]}),(m==null?void 0:m.month)===t?e.jsxs("div",{className:"flex gap-2 mt-1",children:[e.jsx(Se,{value:m.link,onChange:st=>p({...m,link:st.target.value}),placeholder:"https://www.canva.com/..."}),e.jsx(H,{size:"sm",onClick:()=>Ue.mutate(m),children:"Save"}),e.jsx(H,{size:"sm",variant:"outline",onClick:()=>p(null),children:"Cancel"})]}):e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("span",{className:"text-sm",children:et(t)||"No link set"}),e.jsx(H,{size:"sm",variant:"outline",onClick:()=>p({month:t,link:et(t)}),children:"Edit"})]})]})]})})}),t!=="all"&&e.jsx(ke,{children:e.jsx(Oe,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx(Qm,{className:"h-4 w-4 text-muted-foreground mt-1"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs(ue,{className:"text-sm text-muted-foreground",children:["Reel for ",Le(t)]}),(()=>{const st=Qe(t);return st?e.jsxs("div",{className:"flex items-center gap-4 mt-2",children:[e.jsx("img",{src:st.image_url,alt:"Reel preview",className:"w-16 h-28 object-cover rounded"}),e.jsxs("div",{className:"flex-1 text-sm",children:[e.jsx("p",{className:"line-clamp-2",children:st.caption||"No caption"}),st.canva_link&&e.jsx("a",{href:st.canva_link,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline text-xs",children:"View Canva Link"})]}),e.jsx(H,{variant:"destructive",size:"sm",onClick:()=>Je.mutate(st),children:e.jsx(Dr,{className:"h-4 w-4"})})]}):e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"No reel uploaded for this month"})})()]})]})})})]}),fe?e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading..."}):Ve.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx(wl,{className:"h-12 w-12 mx-auto text-muted-foreground/50 mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:"No images yet. Upload some!"})]}):e.jsx(Oxe,{sensors:le,collisionDetection:Ixe,onDragEnd:Pe,children:e.jsx(Bxe,{items:Ve.map(st=>st.id),strategy:jz,children:e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-4",children:Ve.map(st=>e.jsx(Xds,{item:st,onEdit:Me,onDelete:mt=>ge.mutate(mt),onDateChange:(mt,wt)=>ct.mutate({id:mt,postDate:wt})},st.id))})})})]}),e.jsx(bs,{open:!!x,onOpenChange:st=>{st||y(null)},children:e.jsxs(vs,{className:"max-w-md",children:[e.jsx(Cs,{children:e.jsx(Ns,{children:"Edit Image"})}),x&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"aspect-[4/5] max-h-48 w-full rounded-lg overflow-hidden bg-muted",children:e.jsx("img",{src:x.image_url,alt:"Preview",className:"w-full h-full object-cover"})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Caption"}),e.jsx(vr,{value:_,onChange:st=>b(st.target.value),placeholder:"Enter caption...",className:"h-28"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Post Date"}),e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsxs(gl,{children:[e.jsx(xl,{asChild:!0,children:e.jsxs(H,{variant:"outline",className:Ft("flex-1 justify-start gap-2 font-normal",!j&&"text-muted-foreground"),children:[e.jsx(Nn,{className:"h-4 w-4"}),j?As(new Date(j+"T00:00:00"),"MMM d, yyyy"):"Pick a date"]})}),e.jsx(il,{className:"w-auto p-0",align:"start",children:e.jsx(g0,{mode:"single",selected:j?new Date(j+"T00:00:00"):void 0,onSelect:st=>k(st?As(st,"yyyy-MM-dd"):null),className:"p-3 pointer-events-auto"})})]}),j&&e.jsx(H,{variant:"ghost",size:"icon",onClick:()=>k(null),children:e.jsx(Rr,{className:"h-4 w-4"})})]})]})]}),e.jsxs(wn,{children:[e.jsx(H,{variant:"outline",onClick:()=>y(null),children:"Cancel"}),e.jsx(H,{onClick:ze,disabled:T,className:"gap-2",children:T?e.jsxs(e.Fragment,{children:[e.jsx(is,{className:"h-4 w-4 animate-spin"}),"Saving..."]}):"Save Changes"})]})]})})]})},Jds=()=>{const{toast:s}=li(),t=ns(),[r,n]=S.useState("categories"),[a,i]=S.useState(!1),[l,o]=S.useState(null),[c,d]=S.useState({name:"",description:"",icon:""}),[h,m]=S.useState(!1),[p,x]=S.useState(null),[y,_]=S.useState({name:"",description:"",icon:""}),[b,j]=S.useState(!1),[k,T]=S.useState(null),[E,A]=S.useState(""),{data:D=[],isLoading:R}=yt({queryKey:["admin-community-categories"],queryFn:async()=>{const{data:Pe,error:Ie}=await V.from("community_categories").select("*").order("sort_order");if(Ie)throw Ie;return Pe}}),{data:z=[],isLoading:O}=yt({queryKey:["admin-private-groups"],queryFn:async()=>{const{data:Pe,error:Ie}=await V.from("community_private_groups").select("*").order("sort_order");if(Ie)throw Ie;return Pe}}),{data:$=[]}=yt({queryKey:["admin-group-members",k==null?void 0:k.id],queryFn:async()=>{if(!k)return[];const{data:Pe,error:Ie}=await V.from("community_private_group_members").select("*").eq("group_id",k.id);if(Ie)throw Ie;return Pe},enabled:!!k}),{data:ee=[]}=yt({queryKey:["admin-all-profiles"],queryFn:async()=>{let Ie=[],De=0,pe=!0;for(;pe;){const{data:tt,error:ge}=await V.from("profiles").select("id, name, email, brokerage_id").order("name").range(De,De+1e3-1);if(ge)throw ge;tt&&tt.length>0?(Ie=[...Ie,...tt],De+=1e3,pe=tt.length===1e3):pe=!1}return Ie}}),{data:Z=[]}=yt({queryKey:["admin-all-brokerages"],queryFn:async()=>{const{data:Pe,error:Ie}=await V.from("brokerages").select("*").order("name");if(Ie)throw Ie;return Pe}}),J=Pt({mutationFn:async Pe=>{if(Pe.id){const{error:Ie}=await V.from("community_categories").update({name:Pe.name,description:Pe.description||null,icon:Pe.icon||null}).eq("id",Pe.id);if(Ie)throw Ie}else{const Ie=Math.max(...D.map(pe=>pe.sort_order),0),{error:De}=await V.from("community_categories").insert({name:Pe.name,description:Pe.description||null,icon:Pe.icon||null,sort_order:Ie+1});if(De)throw De}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-community-categories"]}),i(!1),o(null),d({name:"",description:"",icon:""}),s({title:l?"Category updated!":"Category created!"})},onError:Pe=>{s({title:"Error",description:Pe.message,variant:"destructive"})}}),K=Pt({mutationFn:async Pe=>{const{error:Ie}=await V.from("community_categories").delete().eq("id",Pe);if(Ie)throw Ie},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-community-categories"]}),s({title:"Category deleted"})}}),re=Pt({mutationFn:async({id:Pe,direction:Ie})=>{const De=D.findIndex(pe=>pe.id===Pe);if(Ie==="up"&&De>0){const pe=D[De-1],tt=D[De];await V.from("community_categories").update({sort_order:tt.sort_order}).eq("id",pe.id),await V.from("community_categories").update({sort_order:pe.sort_order}).eq("id",tt.id)}else if(Ie==="down"&&Det.invalidateQueries({queryKey:["admin-community-categories"]})}),ie=Pt({mutationFn:async Pe=>{if(Pe.id){const{error:Ie}=await V.from("community_private_groups").update({name:Pe.name,description:Pe.description||null,icon:Pe.icon||null}).eq("id",Pe.id);if(Ie)throw Ie}else{const Ie=Math.max(...z.map(pe=>pe.sort_order),0),{error:De}=await V.from("community_private_groups").insert({name:Pe.name,description:Pe.description||null,icon:Pe.icon||null,sort_order:Ie+1});if(De)throw De}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-private-groups"]}),m(!1),x(null),_({name:"",description:"",icon:""}),s({title:p?"Private group updated!":"Private group created!"})},onError:Pe=>{s({title:"Error",description:Pe.message,variant:"destructive"})}}),ce=Pt({mutationFn:async Pe=>{const{error:Ie}=await V.from("community_private_groups").delete().eq("id",Pe);if(Ie)throw Ie},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-private-groups"]}),s({title:"Private group deleted"})}}),ne=Pt({mutationFn:async({id:Pe,direction:Ie})=>{const De=z.findIndex(pe=>pe.id===Pe);if(Ie==="up"&&De>0){const pe=z[De-1],tt=z[De];await V.from("community_private_groups").update({sort_order:tt.sort_order}).eq("id",pe.id),await V.from("community_private_groups").update({sort_order:pe.sort_order}).eq("id",tt.id)}else if(Ie==="down"&&Det.invalidateQueries({queryKey:["admin-private-groups"]})}),le=Pt({mutationFn:async({groupId:Pe,userId:Ie,isMember:De})=>{if(De){const{error:pe}=await V.from("community_private_group_members").delete().eq("group_id",Pe).eq("user_id",Ie);if(pe)throw pe}else{const{error:pe}=await V.from("community_private_group_members").insert({group_id:Pe,user_id:Ie});if(pe)throw pe}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-group-members",k==null?void 0:k.id]})}}),be=Pt({mutationFn:async({groupId:Pe,brokerageId:Ie,isMember:De})=>{if(De){const{error:pe}=await V.from("community_private_group_members").delete().eq("group_id",Pe).eq("brokerage_id",Ie);if(pe)throw pe}else{const{error:pe}=await V.from("community_private_group_members").insert({group_id:Pe,brokerage_id:Ie});if(pe)throw pe}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-group-members",k==null?void 0:k.id]})}}),fe=Pe=>{o(Pe),d({name:Pe.name,description:Pe.description||"",icon:Pe.icon||""}),i(!0)},je=()=>{o(null),d({name:"",description:"",icon:""}),i(!0)},ve=Pe=>{x(Pe),_({name:Pe.name,description:Pe.description||"",icon:Pe.icon||""}),m(!0)},We=()=>{x(null),_({name:"",description:"",icon:""}),m(!0)},Ve=Pe=>{T(Pe),A(""),j(!0)},Le=Pe=>$.some(Ie=>Ie.user_id===Pe),Me=Pe=>$.some(Ie=>Ie.brokerage_id===Pe),ze=ee.filter(Pe=>Pe.name.toLowerCase().includes(E.toLowerCase())||Pe.email.toLowerCase().includes(E.toLowerCase()));return e.jsx(Ss,{title:"Community Management",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(km,{title:"Community Management",description:"Manage categories and private groups for community discussions"}),e.jsxs(ta,{value:r,onValueChange:n,children:[e.jsxs(Qn,{children:[e.jsx(ts,{value:"categories",children:"Public Categories"}),e.jsxs(ts,{value:"private-groups",children:[e.jsx(Td,{className:"h-4 w-4 mr-1"}),"Private Groups"]})]}),e.jsxs(cs,{value:"categories",className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Categories visible to all community members"}),e.jsxs(H,{onClick:je,children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Add Category"]})]}),e.jsx(ke,{children:e.jsx(Oe,{className:"pt-6",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Vs,{children:[e.jsx(At,{className:"w-[50px]",children:"Order"}),e.jsx(At,{className:"w-[80px]",children:"Icon"}),e.jsx(At,{children:"Name"}),e.jsx(At,{children:"Description"}),e.jsx(At,{className:"w-[100px]",children:"Actions"})]})}),e.jsx(da,{children:R?e.jsx(Vs,{children:e.jsx(gt,{colSpan:5,className:"text-center py-8",children:"Loading..."})}):D.length===0?e.jsx(Vs,{children:e.jsx(gt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No categories yet. Create your first one!"})}):D.map((Pe,Ie)=>e.jsxs(Vs,{children:[e.jsx(gt,{children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx(H,{variant:"ghost",size:"icon",className:"h-6 w-6",disabled:Ie===0,onClick:()=>re.mutate({id:Pe.id,direction:"up"}),children:"↑"}),e.jsx(H,{variant:"ghost",size:"icon",className:"h-6 w-6",disabled:Ie===D.length-1,onClick:()=>re.mutate({id:Pe.id,direction:"down"}),children:"↓"})]})}),e.jsx(gt,{className:"text-2xl",children:Pe.icon||"📁"}),e.jsx(gt,{className:"font-medium",children:Pe.name}),e.jsx(gt,{className:"text-muted-foreground",children:Pe.description||"—"}),e.jsx(gt,{children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx(H,{variant:"ghost",size:"icon",onClick:()=>fe(Pe),children:e.jsx(ni,{className:"h-4 w-4"})}),e.jsx(H,{variant:"ghost",size:"icon",className:"text-destructive",onClick:()=>{confirm("Delete this category? Posts will be uncategorized.")&&K.mutate(Pe.id)},children:e.jsx(Dr,{className:"h-4 w-4"})})]})})]},Pe.id))})]})})})]}),e.jsxs(cs,{value:"private-groups",className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Private groups visible only to assigned members or brokerages"}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Xa,{className:"h-3 w-3"}),"Brokerage groups are created automatically and sync with brokerage names"]})]}),e.jsxs(H,{onClick:We,children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Add Private Group"]})]}),e.jsx(ke,{children:e.jsx(Oe,{className:"pt-6",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Vs,{children:[e.jsx(At,{className:"w-[50px]",children:"Order"}),e.jsx(At,{className:"w-[80px]",children:"Icon"}),e.jsx(At,{children:"Name"}),e.jsx(At,{children:"Description"}),e.jsx(At,{className:"w-[120px]",children:"Members"}),e.jsx(At,{className:"w-[140px]",children:"Actions"})]})}),e.jsx(da,{children:O?e.jsx(Vs,{children:e.jsx(gt,{colSpan:6,className:"text-center py-8",children:"Loading..."})}):z.length===0?e.jsx(Vs,{children:e.jsx(gt,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"No private groups yet. Create your first one!"})}):z.map((Pe,Ie)=>e.jsxs(Vs,{children:[e.jsx(gt,{children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx(H,{variant:"ghost",size:"icon",className:"h-6 w-6",disabled:Ie===0,onClick:()=>ne.mutate({id:Pe.id,direction:"up"}),children:"↑"}),e.jsx(H,{variant:"ghost",size:"icon",className:"h-6 w-6",disabled:Ie===z.length-1,onClick:()=>ne.mutate({id:Pe.id,direction:"down"}),children:"↓"})]})}),e.jsx(gt,{className:"text-2xl",children:Pe.icon||"🔒"}),e.jsx(gt,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2",children:[Pe.name,Pe.brokerage_id?e.jsxs(Xe,{variant:"outline",className:"text-xs bg-blue-50 text-blue-700 border-blue-200",children:[e.jsx(Xa,{className:"h-3 w-3 mr-1"}),"Auto-managed"]}):e.jsxs(Xe,{variant:"secondary",className:"text-xs",children:[e.jsx(Td,{className:"h-3 w-3 mr-1"}),"Private"]})]})}),e.jsx(gt,{className:"text-muted-foreground",children:Pe.description||"—"}),e.jsx(gt,{children:e.jsxs(H,{variant:"outline",size:"sm",onClick:()=>Ve(Pe),children:[e.jsx(Ar,{className:"h-4 w-4 mr-1"}),"Manage"]})}),e.jsx(gt,{children:e.jsxs("div",{className:"flex gap-1",children:[!Pe.brokerage_id&&e.jsx(H,{variant:"ghost",size:"icon",onClick:()=>ve(Pe),children:e.jsx(ni,{className:"h-4 w-4"})}),!Pe.brokerage_id&&e.jsx(H,{variant:"ghost",size:"icon",className:"text-destructive",onClick:()=>{confirm("Delete this private group? All posts in this group will be deleted.")&&ce.mutate(Pe.id)},children:e.jsx(Dr,{className:"h-4 w-4"})}),Pe.brokerage_id&&e.jsx("span",{className:"text-xs text-muted-foreground italic",children:"Managed via brokerage"})]})})]},Pe.id))})]})})})]})]}),e.jsx(bs,{open:a,onOpenChange:i,children:e.jsxs(vs,{children:[e.jsx(Cs,{children:e.jsx(Ns,{children:l?"Edit Category":"Create Category"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Icon (emoji)"}),e.jsx(Se,{value:c.icon,onChange:Pe=>d(Ie=>({...Ie,icon:Pe.target.value})),placeholder:"💬",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Name *"}),e.jsx(Se,{value:c.name,onChange:Pe=>d(Ie=>({...Ie,name:Pe.target.value})),placeholder:"Category name",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Description"}),e.jsx(vr,{value:c.description,onChange:Pe=>d(Ie=>({...Ie,description:Pe.target.value})),placeholder:"Brief description of this category",className:"mt-1"})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(H,{variant:"outline",onClick:()=>i(!1),children:"Cancel"}),e.jsx(H,{onClick:()=>J.mutate({...c,id:l==null?void 0:l.id}),disabled:!c.name.trim(),children:l?"Save Changes":"Create Category"})]})]})]})}),e.jsx(bs,{open:h,onOpenChange:m,children:e.jsxs(vs,{children:[e.jsx(Cs,{children:e.jsx(Ns,{children:p?"Edit Private Group":"Create Private Group"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Icon (emoji)"}),e.jsx(Se,{value:y.icon,onChange:Pe=>_(Ie=>({...Ie,icon:Pe.target.value})),placeholder:"🔒",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Name *"}),e.jsx(Se,{value:y.name,onChange:Pe=>_(Ie=>({...Ie,name:Pe.target.value})),placeholder:"e.g., Pioneers",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Description"}),e.jsx(vr,{value:y.description,onChange:Pe=>_(Ie=>({...Ie,description:Pe.target.value})),placeholder:"Brief description of this private group",className:"mt-1"})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(H,{variant:"outline",onClick:()=>m(!1),children:"Cancel"}),e.jsx(H,{onClick:()=>ie.mutate({...y,id:p==null?void 0:p.id}),disabled:!y.name.trim(),children:p?"Save Changes":"Create Private Group"})]})]})]})}),e.jsx(bs,{open:b,onOpenChange:j,children:e.jsxs(vs,{className:"max-w-2xl",children:[e.jsx(Cs,{children:e.jsxs(Ns,{children:["Manage Members: ",k==null?void 0:k.name]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs(ta,{defaultValue:"brokerages",children:[e.jsxs(Qn,{className:"w-full",children:[e.jsx(ts,{value:"brokerages",className:"flex-1",children:"By Brokerage"}),e.jsx(ts,{value:"users",className:"flex-1",children:"Individual Users"})]}),e.jsxs(cs,{value:"brokerages",className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Select brokerages to grant all their agents access to this private group."}),e.jsx(Ci,{className:"h-[300px] border rounded-md p-4",children:e.jsxs("div",{className:"space-y-2",children:[Z.map(Pe=>e.jsxs("div",{className:"flex items-center justify-between p-2 hover:bg-muted rounded-md",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ao,{checked:Me(Pe.id),onCheckedChange:()=>{k&&be.mutate({groupId:k.id,brokerageId:Pe.id,isMember:Me(Pe.id)})}}),e.jsx("span",{className:"font-medium",children:Pe.name})]}),e.jsxs(Xe,{variant:"secondary",children:[ee.filter(Ie=>Ie.brokerage_id===Pe.id).length," agents"]})]},Pe.id)),Z.length===0&&e.jsx("p",{className:"text-center text-muted-foreground py-4",children:"No brokerages found"})]})})]}),e.jsxs(cs,{value:"users",className:"space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Mn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Se,{placeholder:"Search users...",value:E,onChange:Pe=>A(Pe.target.value),className:"pl-9"})]}),e.jsx(Ci,{className:"h-[300px] border rounded-md p-4",children:e.jsxs("div",{className:"space-y-2",children:[ze.map(Pe=>e.jsx("div",{className:"flex items-center justify-between p-2 hover:bg-muted rounded-md",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ao,{checked:Le(Pe.id),onCheckedChange:()=>{k&&le.mutate({groupId:k.id,userId:Pe.id,isMember:Le(Pe.id)})}}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:Pe.name}),e.jsx("div",{className:"text-sm text-muted-foreground",children:Pe.email})]})]})},Pe.id)),ze.length===0&&e.jsx("p",{className:"text-center text-muted-foreground py-4",children:"No users found"})]})})]})]}),e.jsx("div",{className:"flex justify-end",children:e.jsx(H,{onClick:()=>j(!1),children:"Done"})})]})]})})]})})},f$e=s=>{switch(s){case"academy_video":return e.jsx(El,{className:"h-3 w-3"});case"template":return e.jsx(kn,{className:"h-3 w-3"});case"toolbox":return e.jsx(yc,{className:"h-3 w-3"});case"newsletter":return e.jsx(x_,{className:"h-3 w-3"});case"social_swag":return e.jsx(Lr,{className:"h-3 w-3"});default:return e.jsx(gn,{className:"h-3 w-3"})}},eus=s=>{switch(s){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 s}},tus=s=>{switch(s){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 s}},sus=()=>{const{toast:s}=li(),[t,r]=S.useState([]),[n,a]=S.useState([]),[i,l]=S.useState([]),[o,c]=S.useState(!0),[d,h]=S.useState(""),[m,p]=S.useState(null),[x,y]=S.useState([]),[_,b]=S.useState([]);S.useEffect(()=>{j()},[]);const j=async()=>{try{c(!0);const{data:$,error:ee}=await V.from("activity_logs").select(` id, user_id, app_name, launched_at, profiles ( name, email, brokerages ( name ) ) `).order("launched_at",{ascending:!1}).limit(5e3);if(ee)throw ee;const{data:Z,error:J}=await V.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(J)throw J;const K=[...new Set((Z==null?void 0:Z.map(fe=>fe.user_id))||[])],{data:re}=await V.from("profiles").select(` id, name, email, brokerages ( name ) `).in("id",K),ie=new Map((re==null?void 0:re.map(fe=>[fe.id,fe]))||[]),ce=($==null?void 0:$.map(fe=>{var je,ve,We,Ve;return{id:fe.id,user_id:fe.user_id,app_name:fe.app_name,launched_at:fe.launched_at,user_name:((je=fe.profiles)==null?void 0:je.name)||"Unknown",user_email:((ve=fe.profiles)==null?void 0:ve.email)||"Unknown",brokerage_name:((Ve=(We=fe.profiles)==null?void 0:We.brokerages)==null?void 0:Ve.name)||null}}))||[],ne=(Z==null?void 0:Z.map(fe=>{var ve;const je=ie.get(fe.user_id);return{id:fe.id,user_id:fe.user_id,resource_type:fe.resource_type,resource_id:fe.resource_id,resource_title:fe.resource_title,action_type:fe.action_type,created_at:fe.created_at,user_name:(je==null?void 0:je.name)||"Unknown",user_email:(je==null?void 0:je.email)||"Unknown",brokerage_name:((ve=je==null?void 0:je.brokerages)==null?void 0:ve.name)||null}}))||[];r(ce),a(ne);const le=new Map;ce.forEach(fe=>{if(!le.has(fe.user_id))le.set(fe.user_id,{user_id:fe.user_id,user_name:fe.user_name,user_email:fe.user_email,brokerage_name:fe.brokerage_name,last_activity_type:"app",last_activity_name:fe.app_name,last_activity_at:fe.launched_at,total_app_launches:1,total_content_views:0});else{const je=le.get(fe.user_id);je.total_app_launches++,new Date(fe.launched_at)>new Date(je.last_activity_at)&&(je.last_activity_type="app",je.last_activity_name=fe.app_name,je.last_activity_at=fe.launched_at)}}),ne.forEach(fe=>{if(!le.has(fe.user_id))le.set(fe.user_id,{user_id:fe.user_id,user_name:fe.user_name,user_email:fe.user_email,brokerage_name:fe.brokerage_name,last_activity_type:fe.resource_type,last_activity_name:fe.resource_title,last_activity_at:fe.created_at,total_app_launches:0,total_content_views:1});else{const je=le.get(fe.user_id);je.total_content_views++,new Date(fe.created_at)>new Date(je.last_activity_at)&&(je.last_activity_type=fe.resource_type,je.last_activity_name=fe.resource_title,je.last_activity_at=fe.created_at)}});const be=Array.from(le.values()).sort((fe,je)=>new Date(je.last_activity_at).getTime()-new Date(fe.last_activity_at).getTime());l(be)}catch($){console.error("Error loading activity:",$),s({title:"Error",description:"Failed to load activity logs",variant:"destructive"})}finally{c(!1)}},k=$=>{p({id:$.user_id,name:$.user_name,email:$.user_email});const ee=t.filter(J=>J.user_id===$.user_id),Z=n.filter(J=>J.user_id===$.user_id);y(ee),b(Z)},T=()=>{p(null),y([]),b([])},{sortKey:E,sortDirection:A,handleSort:D,sortData:R}=yz("last_activity_at","desc"),z=i.filter($=>{var Z;if(!d)return!0;const ee=d.toLowerCase();return $.user_name.toLowerCase().includes(ee)||$.user_email.toLowerCase().includes(ee)||((Z=$.brokerage_name)==null?void 0:Z.toLowerCase().includes(ee))}),O=R(z,{user:$=>{var ee;return((ee=$.user_name)==null?void 0:ee.toLowerCase())||""},brokerage:$=>{var ee;return((ee=$.brokerage_name)==null?void 0:ee.toLowerCase())||""},last_activity_at:$=>new Date($.last_activity_at).getTime(),apps:$=>$.total_app_launches,content:$=>$.total_content_views});return o?e.jsx(ke,{children:e.jsx(Oe,{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):e.jsxs(e.Fragment,{children:[e.jsxs(ke,{children:[e.jsxs(Ot,{children:[e.jsx(zt,{children:"User Activity"}),e.jsx(Br,{children:"App launches and content engagement - click to see full history"})]}),e.jsxs(Oe,{children:[e.jsx("div",{className:"mb-4",children:e.jsxs("div",{className:"relative",children:[e.jsx(Mn,{className:"absolute left-3 top-3 h-4 w-4 text-muted-foreground"}),e.jsx(Se,{placeholder:"Search by name, email, or brokerage...",value:d,onChange:$=>h($.target.value),className:"pl-9"})]})}),e.jsx("div",{className:"rounded-md border",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Vs,{children:[e.jsx(pc,{sortKey:"user",currentSortKey:E,currentDirection:A,onSort:D,children:"User"}),e.jsx(pc,{sortKey:"brokerage",currentSortKey:E,currentDirection:A,onSort:D,children:"Brokerage"}),e.jsx(At,{children:"Last Activity"}),e.jsx(pc,{sortKey:"last_activity_at",currentSortKey:E,currentDirection:A,onSort:D,children:"Last Active"}),e.jsx(pc,{sortKey:"apps",currentSortKey:E,currentDirection:A,onSort:D,className:"text-right",children:"Apps"}),e.jsx(pc,{sortKey:"content",currentSortKey:E,currentDirection:A,onSort:D,className:"text-right",children:"Content"})]})}),e.jsx(da,{children:O.length===0?e.jsx(Vs,{children:e.jsx(gt,{colSpan:6,className:"text-center text-muted-foreground",children:"No activity found"})}):O.map($=>e.jsxs(Vs,{className:"cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>k($),children:[e.jsx(gt,{children:e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:$.user_name}),e.jsx("div",{className:"text-sm text-muted-foreground",children:$.user_email})]})}),e.jsx(gt,{children:$.brokerage_name?e.jsx(Xe,{variant:"outline",children:$.brokerage_name}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"-"})}),e.jsx(gt,{children:e.jsx("div",{className:"flex items-center gap-2",children:$.last_activity_type==="app"?e.jsxs(Xe,{variant:"secondary",children:[e.jsx(gn,{className:"h-3 w-3 mr-1"}),$.last_activity_name]}):e.jsxs(Xe,{variant:"outline",className:"flex items-center gap-1",children:[f$e($.last_activity_type),e.jsx("span",{className:"max-w-32 truncate",children:$.last_activity_name})]})})}),e.jsx(gt,{className:"text-sm text-muted-foreground",children:Hl(new Date($.last_activity_at),{addSuffix:!0})}),e.jsx(gt,{className:"text-right",children:e.jsx(Xe,{variant:"outline",children:$.total_app_launches})}),e.jsx(gt,{className:"text-right",children:e.jsx(Xe,{variant:"outline",children:$.total_content_views})})]},$.user_id))})]})})]})]}),e.jsx(bs,{open:!!m,onOpenChange:$=>!$&&T(),children:e.jsxs(vs,{className:"max-w-3xl max-h-[80vh] overflow-hidden flex flex-col",children:[e.jsxs(Cs,{children:[e.jsxs(Ns,{children:[m==null?void 0:m.name,"'s Activity"]}),e.jsx(nn,{children:m==null?void 0:m.email})]}),e.jsxs(ta,{defaultValue:"content",className:"flex-1 overflow-hidden flex flex-col",children:[e.jsxs(Qn,{className:"grid w-full grid-cols-2",children:[e.jsxs(ts,{value:"content",children:["Content (",_.length,")"]}),e.jsxs(ts,{value:"apps",children:["App Launches (",x.length,")"]})]}),e.jsx(cs,{value:"content",className:"flex-1 overflow-auto mt-4",children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Vs,{children:[e.jsx(At,{children:"Type"}),e.jsx(At,{children:"Resource"}),e.jsx(At,{children:"Action"}),e.jsx(At,{children:"Time"})]})}),e.jsx(da,{children:_.length===0?e.jsx(Vs,{children:e.jsx(gt,{colSpan:4,className:"text-center text-muted-foreground",children:"No content engagement"})}):_.map($=>e.jsxs(Vs,{children:[e.jsx(gt,{children:e.jsxs(Xe,{variant:"outline",className:"flex items-center gap-1 w-fit",children:[f$e($.resource_type),eus($.resource_type)]})}),e.jsx(gt,{className:"max-w-48",children:e.jsx("span",{className:"truncate block",children:$.resource_title})}),e.jsx(gt,{children:e.jsx(Xe,{variant:"secondary",children:tus($.action_type)})}),e.jsx(gt,{className:"text-sm text-muted-foreground",children:Hl(new Date($.created_at),{addSuffix:!0})})]},$.id))})]})})}),e.jsx(cs,{value:"apps",className:"flex-1 overflow-auto mt-4",children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Vs,{children:[e.jsx(At,{children:"App"}),e.jsx(At,{children:"Time"})]})}),e.jsx(da,{children:x.length===0?e.jsx(Vs,{children:e.jsx(gt,{colSpan:2,className:"text-center text-muted-foreground",children:"No app launches"})}):x.map($=>e.jsxs(Vs,{children:[e.jsx(gt,{children:e.jsx(Xe,{variant:"secondary",children:$.app_name})}),e.jsx(gt,{className:"text-sm text-muted-foreground",children:Hl(new Date($.launched_at),{addSuffix:!0})})]},$.id))})]})})})]})]})})]})},rus=()=>{const{toast:s}=li(),[t,r]=S.useState({totalUsers:0,activeUsers:0,pendingUsers:0,totalBrokerages:0,totalLaunches:0,launchesThisWeek:0,launchesThisMonth:0,uniqueActiveThisWeek:0}),[n,a]=S.useState(!0);S.useEffect(()=>{i()},[]);const i=async()=>{try{a(!0);const{count:l}=await V.from("profiles").select("*",{count:"exact",head:!0}),{count:o}=await V.from("profiles").select("*",{count:"exact",head:!0}).not("last_login","is",null),c=(l||0)-(o||0),{count:d}=await V.from("brokerages").select("*",{count:"exact",head:!0}),{count:h}=await V.from("activity_logs").select("*",{count:"exact",head:!0}),m=new Date;m.setDate(m.getDate()-7);const{count:p}=await V.from("activity_logs").select("*",{count:"exact",head:!0}).gte("launched_at",m.toISOString()),x=new Date;x.setMonth(x.getMonth()-1);const{count:y}=await V.from("activity_logs").select("*",{count:"exact",head:!0}).gte("launched_at",x.toISOString()),{data:_}=await V.from("activity_logs").select("user_id").gte("launched_at",m.toISOString()),b=new Set(_==null?void 0:_.map(j=>j.user_id)).size;r({totalUsers:l||0,activeUsers:o||0,pendingUsers:c,totalBrokerages:d||0,totalLaunches:h||0,launchesThisWeek:p||0,launchesThisMonth:y||0,uniqueActiveThisWeek:b})}catch(l){console.error("Error loading analytics:",l),s({title:"Error",description:"Failed to load analytics",variant:"destructive"})}finally{a(!1)}};return n?e.jsx(ke,{children:e.jsx(Oe,{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):e.jsxs("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-4",children:[e.jsxs(ke,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(zt,{className:"text-sm font-medium",children:"Total Users"}),e.jsx(Ar,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Oe,{children:[e.jsx("div",{className:"text-2xl font-bold",children:t.totalUsers}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[t.activeUsers," active, ",t.pendingUsers," pending"]})]})]}),e.jsxs(ke,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(zt,{className:"text-sm font-medium",children:"Active Users"}),e.jsx(zi,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Oe,{children:[e.jsx("div",{className:"text-2xl font-bold",children:t.activeUsers}),e.jsx("p",{className:"text-xs text-muted-foreground",children:t.totalUsers>0?`${Math.round(t.activeUsers/t.totalUsers*100)}% of total`:"0% of total"})]})]}),e.jsxs(ke,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(zt,{className:"text-sm font-medium",children:"Pending Invites"}),e.jsx(Pn,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Oe,{children:[e.jsx("div",{className:"text-2xl font-bold",children:t.pendingUsers}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Awaiting setup"})]})]}),e.jsxs(ke,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(zt,{className:"text-sm font-medium",children:"Brokerages"}),e.jsx(Xa,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Oe,{children:[e.jsx("div",{className:"text-2xl font-bold",children:t.totalBrokerages}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Total brokerages"})]})]}),e.jsxs(ke,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(zt,{className:"text-sm font-medium",children:"Total App Launches"}),e.jsx(ef,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Oe,{children:[e.jsx("div",{className:"text-2xl font-bold",children:t.totalLaunches}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"All time"})]})]}),e.jsxs(ke,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(zt,{className:"text-sm font-medium",children:"Launches This Week"}),e.jsx(ef,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Oe,{children:[e.jsx("div",{className:"text-2xl font-bold",children:t.launchesThisWeek}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Last 7 days"})]})]}),e.jsxs(ke,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(zt,{className:"text-sm font-medium",children:"Launches This Month"}),e.jsx(ef,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Oe,{children:[e.jsx("div",{className:"text-2xl font-bold",children:t.launchesThisMonth}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Last 30 days"})]})]}),e.jsxs(ke,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(zt,{className:"text-sm font-medium",children:"Active This Week"}),e.jsx(al,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Oe,{children:[e.jsx("div",{className:"text-2xl font-bold",children:t.uniqueActiveThisWeek}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Unique users"})]})]})]})},p$e={event:"Event",template:"Template",academy_video:"Academy Video",resource_kit:"Resource Kit",newsletter:"Newsletter",social_swag:"Social Swag"},g$e={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 Uht({brokerageOnly:s=!1,brokerageId:t}){const[r,n]=S.useState([]),[a,i]=S.useState(!0),[l,o]=S.useState(""),[c,d]=S.useState("all");S.useEffect(()=>{h()},[t]);const h=async()=>{i(!0);try{let D=[];if(s&&t){const{data:K}=await V.from("profiles").select("id").eq("brokerage_id",t);if(D=(K==null?void 0:K.map(re=>re.id))||[],D.length===0){n([]),i(!1);return}}let R=V.from("resource_shares").select("*").order("created_at",{ascending:!1});s&&D.length>0&&(R=R.or(`sender_id.in.(${D.join(",")}),recipient_id.in.(${D.join(",")})`));const{data:z,error:O}=await R;if(O)throw O;const $=new Set;z==null||z.forEach(K=>{$.add(K.sender_id),$.add(K.recipient_id)});const{data:ee}=await V.from("profiles").select("id, name, email").in("id",Array.from($)),Z=new Map((ee==null?void 0:ee.map(K=>[K.id,K]))||[]),J=(z==null?void 0:z.map(K=>({...K,sender:Z.get(K.sender_id),recipient:Z.get(K.recipient_id)})))||[];n(J)}catch(D){console.error("Error loading shares:",D)}finally{i(!1)}},{sortKey:m,sortDirection:p,handleSort:x,sortData:y}=yz("created_at","desc"),_=r.filter(D=>{var O,$;const R=l===""||D.resource_title.toLowerCase().includes(l.toLowerCase())||((O=D.sender)==null?void 0:O.name.toLowerCase().includes(l.toLowerCase()))||(($=D.recipient)==null?void 0:$.name.toLowerCase().includes(l.toLowerCase())),z=c==="all"||D.resource_type===c;return R&&z}),b=y(_,{resource:D=>{var R;return((R=D.resource_title)==null?void 0:R.toLowerCase())||""},type:D=>D.resource_type,sender:D=>{var R,z;return((z=(R=D.sender)==null?void 0:R.name)==null?void 0:z.toLowerCase())||""},recipient:D=>{var R,z;return((z=(R=D.recipient)==null?void 0:R.name)==null?void 0:z.toLowerCase())||""},status:D=>D.is_read?1:0,created_at:D=>new Date(D.created_at).getTime()}),j=r.length,k=new Set(r.map(D=>D.sender_id)).size,T=new Set(r.map(D=>D.recipient_id)).size,E=r.length>0?Math.round(r.filter(D=>D.is_read).length/r.length*100):0,A=r.reduce((D,R)=>(D[R.resource_type]=(D[R.resource_type]||0)+1,D),{});return a?e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"grid gap-4 md:grid-cols-4",children:[...Array(4)].map((D,R)=>e.jsxs(ke,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsx(Ks,{className:"h-4 w-20"})}),e.jsx(Oe,{children:e.jsx(Ks,{className:"h-8 w-16"})})]},R))}),e.jsx(ke,{children:e.jsx(Oe,{className:"p-6",children:e.jsx(Ks,{className:"h-[300px]"})})})]}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-4",children:[e.jsxs(ke,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(zt,{className:"text-sm font-medium",children:"Total Shares"}),e.jsx(cd,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Oe,{children:e.jsx("div",{className:"text-2xl font-bold",children:j})})]}),e.jsxs(ke,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(zt,{className:"text-sm font-medium",children:"Active Sharers"}),e.jsx(Ar,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Oe,{children:e.jsx("div",{className:"text-2xl font-bold",children:k})})]}),e.jsxs(ke,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(zt,{className:"text-sm font-medium",children:"Recipients Reached"}),e.jsx(al,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Oe,{children:e.jsx("div",{className:"text-2xl font-bold",children:T})})]}),e.jsxs(ke,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(zt,{className:"text-sm font-medium",children:"Read Rate"}),e.jsx(kn,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Oe,{children:e.jsxs("div",{className:"text-2xl font-bold",children:[E,"%"]})})]})]}),e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-sm font-medium",children:"Shares by Resource Type"})}),e.jsx(Oe,{children:e.jsxs("div",{className:"flex flex-wrap gap-2",children:[Object.entries(A).map(([D,R])=>e.jsxs(Xe,{variant:"secondary",className:g$e[D],children:[p$e[D],": ",R]},D)),Object.keys(A).length===0&&e.jsx("span",{className:"text-muted-foreground text-sm",children:"No shares yet"})]})})]}),e.jsxs(ke,{children:[e.jsxs(Ot,{children:[e.jsx(zt,{children:"Share History"}),e.jsxs(Br,{children:["All resource shares ",s?"in your brokerage":"across the platform"]})]}),e.jsxs(Oe,{children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 mb-4",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Mn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Se,{placeholder:"Search by resource, sender, or recipient...",value:l,onChange:D=>o(D.target.value),className:"pl-9"})]}),e.jsxs(Bs,{value:c,onValueChange:d,children:[e.jsx(Os,{className:"w-[180px]",children:e.jsx(Us,{placeholder:"Resource type"})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"all",children:"All Types"}),e.jsx(pt,{value:"event",children:"Events"}),e.jsx(pt,{value:"template",children:"Templates"}),e.jsx(pt,{value:"academy_video",children:"Academy Videos"}),e.jsx(pt,{value:"resource_kit",children:"Resource Kits"}),e.jsx(pt,{value:"newsletter",children:"Newsletters"}),e.jsx(pt,{value:"social_swag",children:"Social Swag"})]})]})]}),e.jsx(Ci,{className:"h-[400px]",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Vs,{children:[e.jsx(pc,{sortKey:"resource",currentSortKey:m,currentDirection:p,onSort:x,children:"Resource"}),e.jsx(pc,{sortKey:"type",currentSortKey:m,currentDirection:p,onSort:x,children:"Type"}),e.jsx(pc,{sortKey:"sender",currentSortKey:m,currentDirection:p,onSort:x,children:"Sender"}),e.jsx(pc,{sortKey:"recipient",currentSortKey:m,currentDirection:p,onSort:x,children:"Recipient"}),e.jsx(pc,{sortKey:"status",currentSortKey:m,currentDirection:p,onSort:x,children:"Status"}),e.jsx(pc,{sortKey:"created_at",currentSortKey:m,currentDirection:p,onSort:x,children:"Date"})]})}),e.jsx(da,{children:b.length===0?e.jsx(Vs,{children:e.jsx(gt,{colSpan:6,className:"text-center text-muted-foreground py-8",children:"No shares found"})}):b.map(D=>{var R,z;return e.jsxs(Vs,{children:[e.jsx(gt,{className:"font-medium max-w-[200px] truncate",children:D.resource_title}),e.jsx(gt,{children:e.jsx(Xe,{variant:"secondary",className:g$e[D.resource_type],children:p$e[D.resource_type]})}),e.jsx(gt,{children:((R=D.sender)==null?void 0:R.name)||"Unknown"}),e.jsx(gt,{children:((z=D.recipient)==null?void 0:z.name)||"Unknown"}),e.jsx(gt,{children:e.jsx(Xe,{variant:D.is_read?"default":"outline",children:D.is_read?"Read":"Unread"})}),e.jsx(gt,{className:"text-muted-foreground",children:As(new Date(D.created_at),"MMM d, yyyy")})]},D.id)})})]})})]})]})]})}const L_e={academy_video:{label:"Academy Videos",icon:xn,color:"bg-purple-100 text-purple-800",actionLabel:"Watched",actionIcon:Bn},template:{label:"Templates",icon:w2,color:"bg-blue-100 text-blue-800",actionLabel:"Accessed",actionIcon:lm},toolbox:{label:"Toolkit",icon:N1,color:"bg-amber-100 text-amber-800",actionLabel:"Downloaded",actionIcon:hi},newsletter:{label:"Newsletters",icon:er,color:"bg-emerald-100 text-emerald-800",actionLabel:"Clicked",actionIcon:lm},social_swag:{label:"Social Swag",icon:pl,color:"bg-pink-100 text-pink-800",actionLabel:"Accessed",actionIcon:lm},event:{label:"Events",icon:Nn,color:"bg-cyan-100 text-cyan-800",actionLabel:"Registered",actionIcon:lm}};function x$e(s){return s.resource_type==="toolbox"?s.total_downloads:s.total_clicks}function nus(s,t){return s==="toolbox"?t.downloads:t.clicks}function aus(){var D;const[s,t]=S.useState([]),[r,n]=S.useState(!0),[a,i]=S.useState(null),l=S.useRef(null),{sortKey:o,sortDirection:c,handleSort:d,sortData:h}=yz("total_views","desc");S.useEffect(()=>{m()},[]);const m=async()=>{try{const{data:R,error:z}=await V.rpc("get_admin_content_engagement");if(z)throw z;t(R||[])}catch(R){console.error("Error loading content engagement:",R)}finally{n(!1)}},p=R=>{i(z=>{const O=z===R?null:R;return requestAnimationFrame(()=>{var $;($=l.current)==null||$.scrollIntoView({behavior:"smooth",block:"start"})}),O})};if(r)return e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"grid gap-3 grid-cols-2 md:grid-cols-4",children:[...Array(4)].map((R,z)=>e.jsxs(ke,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsx(Ks,{className:"h-4 w-20"})}),e.jsx(Oe,{children:e.jsx(Ks,{className:"h-8 w-16"})})]},z))}),e.jsx(ke,{children:e.jsx(Oe,{className:"py-8",children:e.jsx(Ks,{className:"h-64 w-full"})})})]});const x=s.reduce((R,z)=>R+z.total_views,0),y=s.reduce((R,z)=>R+z.total_clicks,0),_=s.reduce((R,z)=>R+z.total_downloads,0),b=s.length,j=s.reduce((R,z)=>(R[z.resource_type]||(R[z.resource_type]={views:0,clicks:0,downloads:0,assets:0,uniqueUsers:0}),R[z.resource_type].views+=z.total_views,R[z.resource_type].clicks+=z.total_clicks,R[z.resource_type].downloads+=z.total_downloads,R[z.resource_type].assets+=1,R[z.resource_type].uniqueUsers+=z.unique_users,R),{}),k=a?s.filter(R=>R.resource_type===a):s,T=h(k,{asset:R=>{var z;return((z=R.resource_title)==null?void 0:z.toLowerCase())||""},type:R=>R.resource_type,views:R=>R.total_views,actions:R=>x$e(R),unique_users:R=>R.unique_users,last_activity:R=>R.last_engaged_at?new Date(R.last_engaged_at).getTime():0}),E=a?L_e[a]||{label:a,icon:Bn,color:"bg-muted text-muted-foreground",actionLabel:"Actions",actionIcon:lm}:null,A=E==null?void 0:E.icon;return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 grid-cols-2 md:grid-cols-5",children:[e.jsxs(ke,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(zt,{className:"text-sm font-medium",children:"Total Views"}),e.jsx(Bn,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Oe,{children:[e.jsx("div",{className:"text-2xl font-bold",children:x.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Across all content"})]})]}),e.jsxs(ke,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(zt,{className:"text-sm font-medium",children:"Total Clicks"}),e.jsx(lm,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Oe,{children:[e.jsx("div",{className:"text-2xl font-bold",children:y.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Link & Canva clicks"})]})]}),e.jsxs(ke,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(zt,{className:"text-sm font-medium",children:"Downloads"}),e.jsx(hi,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Oe,{children:[e.jsx("div",{className:"text-2xl font-bold",children:_.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"PDF downloads"})]})]}),e.jsxs(ke,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(zt,{className:"text-sm font-medium",children:"Assets Tracked"}),e.jsx(al,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Oe,{children:[e.jsx("div",{className:"text-2xl font-bold",children:b}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Unique content items"})]})]}),e.jsxs(ke,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(zt,{className:"text-sm font-medium",children:"Click Rate"}),e.jsx(lm,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Oe,{children:[e.jsxs("div",{className:"text-2xl font-bold",children:[x>0?Math.round((y+_)/x*100):0,"%"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Of views → actions"})]})]})]}),e.jsxs(ke,{children:[e.jsxs(Ot,{children:[e.jsx(zt,{className:"text-sm font-medium",children:"Engagement by Content Type"}),e.jsx(Br,{children:"Click a category to see individual asset performance"})]}),e.jsx(Oe,{children:e.jsx("div",{className:"grid gap-3 grid-cols-2 md:grid-cols-3",children:Object.entries(j).map(([R,z])=>{const O=L_e[R]||{label:R,icon:Bn,color:"bg-muted text-muted-foreground",actionLabel:"Actions",actionIcon:lm},$=O.icon,ee=a===R;return e.jsxs("button",{type:"button",onClick:()=>p(R),className:`flex items-center gap-3 p-3 rounded-lg border text-left transition-colors cursor-pointer ${ee?"ring-2 ring-primary border-primary bg-primary/5":"hover:bg-muted/50"}`,children:[e.jsx("div",{className:`p-2 rounded-md ${O.color}`,children:e.jsx($,{className:"h-4 w-4"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium",children:O.label}),e.jsxs("div",{className:"flex items-center gap-3 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Bn,{className:"h-3 w-3"})," ",z.views]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(O.actionIcon,{className:"h-3 w-3"})," ",nus(R,z)]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ar,{className:"h-3 w-3"})," ",z.uniqueUsers]})]})]}),e.jsxs(Xe,{variant:"secondary",className:"text-[10px]",children:[z.assets," items"]})]},R)})})})]}),e.jsx("div",{ref:l,children:e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(zt,{className:"text-sm font-medium flex items-center gap-2",children:E&&A?e.jsxs(e.Fragment,{children:[e.jsx(A,{className:"h-4 w-4"}),E.label," — Top Performers"]}):"Top Content by Engagement"}),e.jsx(Br,{children:a?`${k.length} ${((D=E==null?void 0:E.label)==null?void 0:D.toLowerCase())||"items"} ranked by total interactions`:"All tracked assets ranked by total interactions"})]}),a&&e.jsxs(H,{variant:"ghost",size:"sm",onClick:()=>i(null),className:"gap-1",children:[e.jsx(za,{className:"h-3.5 w-3.5"}),"Show All"]})]})}),e.jsx(Oe,{children:k.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"No engagement data yet. As users view and click content, stats will appear here."}):e.jsx(Ci,{className:"h-[400px]",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Vs,{children:[e.jsx(At,{className:"w-[40px]",children:"#"}),e.jsx(pc,{sortKey:"asset",currentSortKey:o,currentDirection:c,onSort:d,children:"Asset"}),!a&&e.jsx(pc,{sortKey:"type",currentSortKey:o,currentDirection:c,onSort:d,children:"Type"}),e.jsx(pc,{sortKey:"views",currentSortKey:o,currentDirection:c,onSort:d,className:"text-right",children:"Views"}),e.jsx(pc,{sortKey:"actions",currentSortKey:o,currentDirection:c,onSort:d,className:"text-right",children:E?E.actionLabel:"Actions"}),e.jsx(pc,{sortKey:"unique_users",currentSortKey:o,currentDirection:c,onSort:d,className:"text-right",children:"Unique Users"}),e.jsx(pc,{sortKey:"last_activity",currentSortKey:o,currentDirection:c,onSort:d,children:"Last Activity"})]})}),e.jsx(da,{children:T.map((R,z)=>{const O=L_e[R.resource_type]||{label:R.resource_type,color:"bg-muted text-muted-foreground",actionLabel:"Actions",actionIcon:lm};return e.jsxs(Vs,{children:[e.jsx(gt,{className:"text-muted-foreground text-xs",children:z+1}),e.jsx(gt,{children:e.jsx("p",{className:"font-medium text-sm truncate max-w-[250px]",children:R.resource_title})}),!a&&e.jsx(gt,{children:e.jsx(Xe,{className:`text-[10px] ${O.color}`,children:O.label})}),e.jsx(gt,{className:"text-right font-medium",children:R.total_views}),e.jsx(gt,{className:"text-right font-medium",children:x$e(R)}),e.jsx(gt,{className:"text-right",children:R.unique_users}),e.jsx(gt,{className:"text-xs text-muted-foreground",children:R.last_engaged_at?Hl(new Date(R.last_engaged_at),{addSuffix:!0}):"—"})]},`${R.resource_type}-${R.resource_id}`)})})]})})})]})})]})}var ius=Array.isArray,gx=ius,ous=typeof uh=="object"&&uh&&uh.Object===Object&&uh,qht=ous,lus=qht,cus=typeof self=="object"&&self&&self.Object===Object&&self,dus=lus||cus||Function("return this")(),K_=dus,uus=K_,hus=uus.Symbol,Nz=hus,y$e=Nz,Vht=Object.prototype,mus=Vht.hasOwnProperty,fus=Vht.toString,qR=y$e?y$e.toStringTag:void 0;function pus(s){var t=mus.call(s,qR),r=s[qR];try{s[qR]=void 0;var n=!0}catch{}var a=fus.call(s);return n&&(t?s[qR]=r:delete s[qR]),a}var gus=pus,xus=Object.prototype,yus=xus.toString;function vus(s){return yus.call(s)}var bus=vus,v$e=Nz,_us=gus,wus=bus,jus="[object Null]",Nus="[object Undefined]",b$e=v$e?v$e.toStringTag:void 0;function kus(s){return s==null?s===void 0?Nus:jus:b$e&&b$e in Object(s)?_us(s):wus(s)}var Nj=kus;function Sus(s){return s!=null&&typeof s=="object"}var kj=Sus,Cus=Nj,Tus=kj,Eus="[object Symbol]";function Aus(s){return typeof s=="symbol"||Tus(s)&&Cus(s)==Eus}var E8=Aus,Mus=gx,Ius=E8,Pus=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Lus=/^\w*$/;function Dus(s,t){if(Mus(s))return!1;var r=typeof s;return r=="number"||r=="symbol"||r=="boolean"||s==null||Ius(s)?!0:Lus.test(s)||!Pus.test(s)||t!=null&&s in Object(t)}var QEe=Dus;function Rus(s){var t=typeof s;return s!=null&&(t=="object"||t=="function")}var t4=Rus;const A8=ol(t4);var Ous=Nj,Fus=t4,Bus="[object AsyncFunction]",zus="[object Function]",$us="[object GeneratorFunction]",Uus="[object Proxy]";function qus(s){if(!Fus(s))return!1;var t=Ous(s);return t==zus||t==$us||t==Bus||t==Uus}var JEe=qus;const no=ol(JEe);var Vus=K_,Hus=Vus["__core-js_shared__"],Gus=Hus,D_e=Gus,_$e=function(){var s=/[^.]+$/.exec(D_e&&D_e.keys&&D_e.keys.IE_PROTO||"");return s?"Symbol(src)_1."+s:""}();function Wus(s){return!!_$e&&_$e in s}var Kus=Wus,Yus=Function.prototype,Zus=Yus.toString;function Xus(s){if(s!=null){try{return Zus.call(s)}catch{}try{return s+""}catch{}}return""}var Hht=Xus,Qus=JEe,Jus=Kus,ehs=t4,ths=Hht,shs=/[\\^$.*+?()[\]{}|]/g,rhs=/^\[object .+?Constructor\]$/,nhs=Function.prototype,ahs=Object.prototype,ihs=nhs.toString,ohs=ahs.hasOwnProperty,lhs=RegExp("^"+ihs.call(ohs).replace(shs,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function chs(s){if(!ehs(s)||Jus(s))return!1;var t=Qus(s)?lhs:rhs;return t.test(ths(s))}var dhs=chs;function uhs(s,t){return s==null?void 0:s[t]}var hhs=uhs,mhs=dhs,fhs=hhs;function phs(s,t){var r=fhs(s,t);return mhs(r)?r:void 0}var QA=phs,ghs=QA,xhs=ghs(Object,"create"),$xe=xhs,w$e=$xe;function yhs(){this.__data__=w$e?w$e(null):{},this.size=0}var vhs=yhs;function bhs(s){var t=this.has(s)&&delete this.__data__[s];return this.size-=t?1:0,t}var _hs=bhs,whs=$xe,jhs="__lodash_hash_undefined__",Nhs=Object.prototype,khs=Nhs.hasOwnProperty;function Shs(s){var t=this.__data__;if(whs){var r=t[s];return r===jhs?void 0:r}return khs.call(t,s)?t[s]:void 0}var Chs=Shs,Ths=$xe,Ehs=Object.prototype,Ahs=Ehs.hasOwnProperty;function Mhs(s){var t=this.__data__;return Ths?t[s]!==void 0:Ahs.call(t,s)}var Ihs=Mhs,Phs=$xe,Lhs="__lodash_hash_undefined__";function Dhs(s,t){var r=this.__data__;return this.size+=this.has(s)?0:1,r[s]=Phs&&t===void 0?Lhs:t,this}var Rhs=Dhs,Ohs=vhs,Fhs=_hs,Bhs=Chs,zhs=Ihs,$hs=Rhs;function M8(s){var t=-1,r=s==null?0:s.length;for(this.clear();++t-1}var nms=rms,ams=Uxe;function ims(s,t){var r=this.__data__,n=ams(r,s);return n<0?(++this.size,r.push([s,t])):r[n][1]=t,this}var oms=ims,lms=Vhs,cms=Qhs,dms=tms,ums=nms,hms=oms;function I8(s){var t=-1,r=s==null?0:s.length;for(this.clear();++t0?1:-1},HT=function(t){return kA(t)&&t.indexOf("%")===t.length-1},Kn=function(t){return Lfs(t)&&!kz(t)},Ffs=function(t){return yo(t)},hm=function(t){return Kn(t)||kA(t)},Bfs=0,L8=function(t){var r=++Bfs;return"".concat(t||"").concat(r)},xg=function(t,r){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:0,a=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;if(!Kn(t)&&!kA(t))return n;var i;if(HT(t)){var l=t.indexOf("%");i=r*parseFloat(t.slice(0,l))/100}else i=+t;return kz(i)&&(i=n),a&&i>r&&(i=r),i},ak=function(t){if(!t)return null;var r=Object.keys(t);return r&&r.length?t[r[0]]:null},zfs=function(t){if(!Array.isArray(t))return!1;for(var r=t.length,n={},a=0;a=0)&&Object.prototype.propertyIsEnumerable.call(s,n)&&(r[n]=s[n])}return r}function Wfs(s,t){if(s==null)return{};var r={};for(var n in s)if(Object.prototype.hasOwnProperty.call(s,n)){if(t.indexOf(n)>=0)continue;r[n]=s[n]}return r}function Yke(s){"@babel/helpers - typeof";return Yke=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Yke(s)}var E$e={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"},Z2=function(t){return typeof t=="string"?t:t?t.displayName||t.name||"Component":""},A$e=null,O_e=null,cAe=function s(t){if(t===A$e&&Array.isArray(O_e))return O_e;var r=[];return S.Children.forEach(t,function(n){yo(n)||(Efs.isFragment(n)?r=r.concat(s(n.props.children)):r.push(n))}),O_e=r,A$e=t,r};function v0(s,t){var r=[],n=[];return Array.isArray(t)?n=t.map(function(a){return Z2(a)}):n=[Z2(t)],cAe(s).forEach(function(a){var i=y0(a,"type.displayName")||y0(a,"type.name");n.indexOf(i)!==-1&&r.push(a)}),r}function Xx(s,t){var r=v0(s,t);return r&&r[0]}var M$e=function(t){if(!t||!t.props)return!1;var r=t.props,n=r.width,a=r.height;return!(!Kn(n)||n<=0||!Kn(a)||a<=0)},Kfs=["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"],Yfs=function(t){return t&&t.type&&kA(t.type)&&Kfs.indexOf(t.type)>=0},Zfs=function(t){return t&&Yke(t)==="object"&&"clipDot"in t},Xfs=function(t,r,n,a){var i,l=(i=R_e==null?void 0:R_e[a])!==null&&i!==void 0?i:[];return r.startsWith("data-")||!no(t)&&(a&&l.includes(r)||qfs.includes(r))||n&&lAe.includes(r)},Li=function(t,r,n){if(!t||typeof t=="function"||typeof t=="boolean")return null;var a=t;if(S.isValidElement(t)&&(a=t.props),!A8(a))return null;var i={};return Object.keys(a).forEach(function(l){var o;Xfs((o=a)===null||o===void 0?void 0:o[l],l,r,n)&&(i[l]=a[l])}),i},Zke=function s(t,r){if(t===r)return!0;var n=S.Children.count(t);if(n!==S.Children.count(r))return!1;if(n===0)return!0;if(n===1)return I$e(Array.isArray(t)?t[0]:t,Array.isArray(r)?r[0]:r);for(var a=0;a=0)&&Object.prototype.propertyIsEnumerable.call(s,n)&&(r[n]=s[n])}return r}function sps(s,t){if(s==null)return{};var r={};for(var n in s)if(Object.prototype.hasOwnProperty.call(s,n)){if(t.indexOf(n)>=0)continue;r[n]=s[n]}return r}function Qke(s){var t=s.children,r=s.width,n=s.height,a=s.viewBox,i=s.className,l=s.style,o=s.title,c=s.desc,d=tps(s,eps),h=a||{width:r,height:n,x:0,y:0},m=jo("recharts-surface",i);return Nt.createElement("svg",Xke({},Li(d,!0,"svg"),{className:m,width:r,height:n,style:l,viewBox:"".concat(h.x," ").concat(h.y," ").concat(h.width," ").concat(h.height)}),Nt.createElement("title",null,o),Nt.createElement("desc",null,c),t)}var rps=["children","className"];function Jke(){return Jke=Object.assign?Object.assign.bind():function(s){for(var t=1;t=0)&&Object.prototype.propertyIsEnumerable.call(s,n)&&(r[n]=s[n])}return r}function aps(s,t){if(s==null)return{};var r={};for(var n in s)if(Object.prototype.hasOwnProperty.call(s,n)){if(t.indexOf(n)>=0)continue;r[n]=s[n]}return r}var $l=Nt.forwardRef(function(s,t){var r=s.children,n=s.className,a=nps(s,rps),i=jo("recharts-layer",n);return Nt.createElement("g",Jke({className:i},Li(a,!0),{ref:t}),r)}),S1=function(t,r){for(var n=arguments.length,a=new Array(n>2?n-2:0),i=2;ia?0:a+t),r=r>a?a:r,r<0&&(r+=a),a=t>r?0:r-t>>>0,t>>>=0;for(var i=Array(a);++n=n?s:lps(s,t,r)}var dps=cps,ups="\\ud800-\\udfff",hps="\\u0300-\\u036f",mps="\\ufe20-\\ufe2f",fps="\\u20d0-\\u20ff",pps=hps+mps+fps,gps="\\ufe0e\\ufe0f",xps="\\u200d",yps=RegExp("["+xps+ups+pps+gps+"]");function vps(s){return yps.test(s)}var tmt=vps;function bps(s){return s.split("")}var _ps=bps,smt="\\ud800-\\udfff",wps="\\u0300-\\u036f",jps="\\ufe20-\\ufe2f",Nps="\\u20d0-\\u20ff",kps=wps+jps+Nps,Sps="\\ufe0e\\ufe0f",Cps="["+smt+"]",eSe="["+kps+"]",tSe="\\ud83c[\\udffb-\\udfff]",Tps="(?:"+eSe+"|"+tSe+")",rmt="[^"+smt+"]",nmt="(?:\\ud83c[\\udde6-\\uddff]){2}",amt="[\\ud800-\\udbff][\\udc00-\\udfff]",Eps="\\u200d",imt=Tps+"?",omt="["+Sps+"]?",Aps="(?:"+Eps+"(?:"+[rmt,nmt,amt].join("|")+")"+omt+imt+")*",Mps=omt+imt+Aps,Ips="(?:"+[rmt+eSe+"?",eSe,nmt,amt,Cps].join("|")+")",Pps=RegExp(tSe+"(?="+tSe+")|"+Ips+Mps,"g");function Lps(s){return s.match(Pps)||[]}var Dps=Lps,Rps=_ps,Ops=tmt,Fps=Dps;function Bps(s){return Ops(s)?Fps(s):Rps(s)}var zps=Bps,$ps=dps,Ups=tmt,qps=zps,Vps=Yht;function Hps(s){return function(t){t=Vps(t);var r=Ups(t)?qps(t):void 0,n=r?r[0]:t.charAt(0),a=r?$ps(r,1).join(""):t.slice(1);return n[s]()+a}}var Gps=Hps,Wps=Gps,Kps=Wps("toUpperCase"),Yps=Kps;const s0e=ol(Yps);function td(s){return function(){return s}}const lmt=Math.cos,ife=Math.sin,B1=Math.sqrt,ofe=Math.PI,r0e=2*ofe,sSe=Math.PI,rSe=2*sSe,jT=1e-6,Zps=rSe-jT;function cmt(s){this._+=s[0];for(let t=1,r=s.length;t=0))throw new Error(`invalid digits: ${s}`);if(t>15)return cmt;const r=10**t;return function(n){this._+=n[0];for(let a=1,i=n.length;ajT)if(!(Math.abs(m*c-d*h)>jT)||!i)this._append`L${this._x1=t},${this._y1=r}`;else{let x=n-l,y=a-o,_=c*c+d*d,b=x*x+y*y,j=Math.sqrt(_),k=Math.sqrt(p),T=i*Math.tan((sSe-Math.acos((_+p-b)/(2*j*k)))/2),E=T/k,A=T/j;Math.abs(E-1)>jT&&this._append`L${t+E*h},${r+E*m}`,this._append`A${i},${i},0,0,${+(m*x>h*y)},${this._x1=t+A*c},${this._y1=r+A*d}`}}arc(t,r,n,a,i,l){if(t=+t,r=+r,n=+n,l=!!l,n<0)throw new Error(`negative radius: ${n}`);let o=n*Math.cos(a),c=n*Math.sin(a),d=t+o,h=r+c,m=1^l,p=l?a-i:i-a;this._x1===null?this._append`M${d},${h}`:(Math.abs(this._x1-d)>jT||Math.abs(this._y1-h)>jT)&&this._append`L${d},${h}`,n&&(p<0&&(p=p%rSe+rSe),p>Zps?this._append`A${n},${n},0,1,${m},${t-o},${r-c}A${n},${n},0,1,${m},${this._x1=d},${this._y1=h}`:p>jT&&this._append`A${n},${n},0,${+(p>=sSe)},${m},${this._x1=t+n*Math.cos(i)},${this._y1=r+n*Math.sin(i)}`)}rect(t,r,n,a){this._append`M${this._x0=this._x1=+t},${this._y0=this._y1=+r}h${n=+n}v${+a}h${-n}Z`}toString(){return this._}}function dAe(s){let t=3;return s.digits=function(r){if(!arguments.length)return t;if(r==null)t=null;else{const n=Math.floor(r);if(!(n>=0))throw new RangeError(`invalid digits: ${r}`);t=n}return s},()=>new Qps(t)}function uAe(s){return typeof s=="object"&&"length"in s?s:Array.from(s)}function dmt(s){this._context=s}dmt.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(s,t){switch(s=+s,t=+t,this._point){case 0:this._point=1,this._line?this._context.lineTo(s,t):this._context.moveTo(s,t);break;case 1:this._point=2;default:this._context.lineTo(s,t);break}}};function n0e(s){return new dmt(s)}function umt(s){return s[0]}function hmt(s){return s[1]}function mmt(s,t){var r=td(!0),n=null,a=n0e,i=null,l=dAe(o);s=typeof s=="function"?s:s===void 0?umt:td(s),t=typeof t=="function"?t:t===void 0?hmt:td(t);function o(c){var d,h=(c=uAe(c)).length,m,p=!1,x;for(n==null&&(i=a(x=l())),d=0;d<=h;++d)!(d=x;--y)o.point(T[y],E[y]);o.lineEnd(),o.areaEnd()}j&&(T[p]=+s(b,p,m),E[p]=+t(b,p,m),o.point(n?+n(b,p,m):T[p],r?+r(b,p,m):E[p]))}if(k)return o=null,k+""||null}function h(){return mmt().defined(a).curve(l).context(i)}return d.x=function(m){return arguments.length?(s=typeof m=="function"?m:td(+m),n=null,d):s},d.x0=function(m){return arguments.length?(s=typeof m=="function"?m:td(+m),d):s},d.x1=function(m){return arguments.length?(n=m==null?null:typeof m=="function"?m:td(+m),d):n},d.y=function(m){return arguments.length?(t=typeof m=="function"?m:td(+m),r=null,d):t},d.y0=function(m){return arguments.length?(t=typeof m=="function"?m:td(+m),d):t},d.y1=function(m){return arguments.length?(r=m==null?null:typeof m=="function"?m:td(+m),d):r},d.lineX0=d.lineY0=function(){return h().x(s).y(t)},d.lineY1=function(){return h().x(s).y(r)},d.lineX1=function(){return h().x(n).y(t)},d.defined=function(m){return arguments.length?(a=typeof m=="function"?m:td(!!m),d):a},d.curve=function(m){return arguments.length?(l=m,i!=null&&(o=l(i)),d):l},d.context=function(m){return arguments.length?(m==null?i=o=null:o=l(i=m),d):i},d}class fmt{constructor(t,r){this._context=t,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(t,r){switch(t=+t,r=+r,this._point){case 0:{this._point=1,this._line?this._context.lineTo(t,r):this._context.moveTo(t,r);break}case 1:this._point=2;default:{this._x?this._context.bezierCurveTo(this._x0=(this._x0+t)/2,this._y0,this._x0,r,t,r):this._context.bezierCurveTo(this._x0,this._y0=(this._y0+r)/2,t,this._y0,t,r);break}}this._x0=t,this._y0=r}}function Jps(s){return new fmt(s,!0)}function egs(s){return new fmt(s,!1)}const hAe={draw(s,t){const r=B1(t/ofe);s.moveTo(r,0),s.arc(0,0,r,0,r0e)}},tgs={draw(s,t){const r=B1(t/5)/2;s.moveTo(-3*r,-r),s.lineTo(-r,-r),s.lineTo(-r,-3*r),s.lineTo(r,-3*r),s.lineTo(r,-r),s.lineTo(3*r,-r),s.lineTo(3*r,r),s.lineTo(r,r),s.lineTo(r,3*r),s.lineTo(-r,3*r),s.lineTo(-r,r),s.lineTo(-3*r,r),s.closePath()}},pmt=B1(1/3),sgs=pmt*2,rgs={draw(s,t){const r=B1(t/sgs),n=r*pmt;s.moveTo(0,-r),s.lineTo(n,0),s.lineTo(0,r),s.lineTo(-n,0),s.closePath()}},ngs={draw(s,t){const r=B1(t),n=-r/2;s.rect(n,n,r,r)}},ags=.8908130915292852,gmt=ife(ofe/10)/ife(7*ofe/10),igs=ife(r0e/10)*gmt,ogs=-lmt(r0e/10)*gmt,lgs={draw(s,t){const r=B1(t*ags),n=igs*r,a=ogs*r;s.moveTo(0,-r),s.lineTo(n,a);for(let i=1;i<5;++i){const l=r0e*i/5,o=lmt(l),c=ife(l);s.lineTo(c*r,-o*r),s.lineTo(o*n-c*a,c*n+o*a)}s.closePath()}},F_e=B1(3),cgs={draw(s,t){const r=-B1(t/(F_e*3));s.moveTo(0,r*2),s.lineTo(-F_e*r,-r),s.lineTo(F_e*r,-r),s.closePath()}},my=-.5,fy=B1(3)/2,nSe=1/B1(12),dgs=(nSe/2+1)*3,ugs={draw(s,t){const r=B1(t/dgs),n=r/2,a=r*nSe,i=n,l=r*nSe+r,o=-i,c=l;s.moveTo(n,a),s.lineTo(i,l),s.lineTo(o,c),s.lineTo(my*n-fy*a,fy*n+my*a),s.lineTo(my*i-fy*l,fy*i+my*l),s.lineTo(my*o-fy*c,fy*o+my*c),s.lineTo(my*n+fy*a,my*a-fy*n),s.lineTo(my*i+fy*l,my*l-fy*i),s.lineTo(my*o+fy*c,my*c-fy*o),s.closePath()}};function hgs(s,t){let r=null,n=dAe(a);s=typeof s=="function"?s:td(s||hAe),t=typeof t=="function"?t:td(t===void 0?64:+t);function a(){let i;if(r||(r=i=n()),s.apply(this,arguments).draw(r,+t.apply(this,arguments)),i)return r=null,i+""||null}return a.type=function(i){return arguments.length?(s=typeof i=="function"?i:td(i),a):s},a.size=function(i){return arguments.length?(t=typeof i=="function"?i:td(+i),a):t},a.context=function(i){return arguments.length?(r=i??null,a):r},a}function lfe(){}function cfe(s,t,r){s._context.bezierCurveTo((2*s._x0+s._x1)/3,(2*s._y0+s._y1)/3,(s._x0+2*s._x1)/3,(s._y0+2*s._y1)/3,(s._x0+4*s._x1+t)/6,(s._y0+4*s._y1+r)/6)}function xmt(s){this._context=s}xmt.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:cfe(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(s,t){switch(s=+s,t=+t,this._point){case 0:this._point=1,this._line?this._context.lineTo(s,t):this._context.moveTo(s,t);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:cfe(this,s,t);break}this._x0=this._x1,this._x1=s,this._y0=this._y1,this._y1=t}};function mgs(s){return new xmt(s)}function ymt(s){this._context=s}ymt.prototype={areaStart:lfe,areaEnd:lfe,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(s,t){switch(s=+s,t=+t,this._point){case 0:this._point=1,this._x2=s,this._y2=t;break;case 1:this._point=2,this._x3=s,this._y3=t;break;case 2:this._point=3,this._x4=s,this._y4=t,this._context.moveTo((this._x0+4*this._x1+s)/6,(this._y0+4*this._y1+t)/6);break;default:cfe(this,s,t);break}this._x0=this._x1,this._x1=s,this._y0=this._y1,this._y1=t}};function fgs(s){return new ymt(s)}function vmt(s){this._context=s}vmt.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(s,t){switch(s=+s,t=+t,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+s)/6,n=(this._y0+4*this._y1+t)/6;this._line?this._context.lineTo(r,n):this._context.moveTo(r,n);break;case 3:this._point=4;default:cfe(this,s,t);break}this._x0=this._x1,this._x1=s,this._y0=this._y1,this._y1=t}};function pgs(s){return new vmt(s)}function bmt(s){this._context=s}bmt.prototype={areaStart:lfe,areaEnd:lfe,lineStart:function(){this._point=0},lineEnd:function(){this._point&&this._context.closePath()},point:function(s,t){s=+s,t=+t,this._point?this._context.lineTo(s,t):(this._point=1,this._context.moveTo(s,t))}};function ggs(s){return new bmt(s)}function L$e(s){return s<0?-1:1}function D$e(s,t,r){var n=s._x1-s._x0,a=t-s._x1,i=(s._y1-s._y0)/(n||a<0&&-0),l=(r-s._y1)/(a||n<0&&-0),o=(i*a+l*n)/(n+a);return(L$e(i)+L$e(l))*Math.min(Math.abs(i),Math.abs(l),.5*Math.abs(o))||0}function R$e(s,t){var r=s._x1-s._x0;return r?(3*(s._y1-s._y0)/r-t)/2:t}function B_e(s,t,r){var n=s._x0,a=s._y0,i=s._x1,l=s._y1,o=(i-n)/3;s._context.bezierCurveTo(n+o,a+o*t,i-o,l-o*r,i,l)}function dfe(s){this._context=s}dfe.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:B_e(this,this._t0,R$e(this,this._t0));break}(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(s,t){var r=NaN;if(s=+s,t=+t,!(s===this._x1&&t===this._y1)){switch(this._point){case 0:this._point=1,this._line?this._context.lineTo(s,t):this._context.moveTo(s,t);break;case 1:this._point=2;break;case 2:this._point=3,B_e(this,R$e(this,r=D$e(this,s,t)),r);break;default:B_e(this,this._t0,r=D$e(this,s,t));break}this._x0=this._x1,this._x1=s,this._y0=this._y1,this._y1=t,this._t0=r}}};function _mt(s){this._context=new wmt(s)}(_mt.prototype=Object.create(dfe.prototype)).point=function(s,t){dfe.prototype.point.call(this,t,s)};function wmt(s){this._context=s}wmt.prototype={moveTo:function(s,t){this._context.moveTo(t,s)},closePath:function(){this._context.closePath()},lineTo:function(s,t){this._context.lineTo(t,s)},bezierCurveTo:function(s,t,r,n,a,i){this._context.bezierCurveTo(t,s,n,r,i,a)}};function xgs(s){return new dfe(s)}function ygs(s){return new _mt(s)}function jmt(s){this._context=s}jmt.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x=[],this._y=[]},lineEnd:function(){var s=this._x,t=this._y,r=s.length;if(r)if(this._line?this._context.lineTo(s[0],t[0]):this._context.moveTo(s[0],t[0]),r===2)this._context.lineTo(s[1],t[1]);else for(var n=O$e(s),a=O$e(t),i=0,l=1;l=0;--t)a[t]=(l[t]-a[t+1])/i[t];for(i[r-1]=(s[r]+a[r-1])/2,t=0;t=0&&(this._t=1-this._t,this._line=1-this._line)},point:function(s,t){switch(s=+s,t=+t,this._point){case 0:this._point=1,this._line?this._context.lineTo(s,t):this._context.moveTo(s,t);break;case 1:this._point=2;default:{if(this._t<=0)this._context.lineTo(this._x,t),this._context.lineTo(s,t);else{var r=this._x*(1-this._t)+s*this._t;this._context.lineTo(r,this._y),this._context.lineTo(r,t)}break}}this._x=s,this._y=t}};function bgs(s){return new a0e(s,.5)}function _gs(s){return new a0e(s,0)}function wgs(s){return new a0e(s,1)}function pL(s,t){if((l=s.length)>1)for(var r=1,n,a,i=s[t[0]],l,o=i.length;r=0;)r[t]=t;return r}function jgs(s,t){return s[t]}function Ngs(s){const t=[];return t.key=s,t}function kgs(){var s=td([]),t=aSe,r=pL,n=jgs;function a(i){var l=Array.from(s.apply(this,arguments),Ngs),o,c=l.length,d=-1,h;for(const m of i)for(o=0,++d;o0){for(var r,n,a=0,i=s[0].length,l;a0){for(var r=0,n=s[t[0]],a,i=n.length;r0)||!((i=(a=s[t[0]]).length)>0))){for(var r=0,n=1,a,i,l;n=0)&&Object.prototype.propertyIsEnumerable.call(s,n)&&(r[n]=s[n])}return r}function Lgs(s,t){if(s==null)return{};var r={};for(var n in s)if(Object.prototype.hasOwnProperty.call(s,n)){if(t.indexOf(n)>=0)continue;r[n]=s[n]}return r}var Nmt={symbolCircle:hAe,symbolCross:tgs,symbolDiamond:rgs,symbolSquare:ngs,symbolStar:lgs,symbolTriangle:cgs,symbolWye:ugs},Dgs=Math.PI/180,Rgs=function(t){var r="symbol".concat(s0e(t));return Nmt[r]||hAe},Ogs=function(t,r,n){if(r==="area")return t;switch(n){case"cross":return 5*t*t/9;case"diamond":return .5*t*t/Math.sqrt(3);case"square":return t*t;case"star":{var a=18*Dgs;return 1.25*t*t*(Math.tan(a)-Math.tan(a*2)*Math.pow(Math.tan(a),2))}case"triangle":return Math.sqrt(3)*t*t/4;case"wye":return(21-10*Math.sqrt(3))*t*t/8;default:return Math.PI*t*t/4}},Fgs=function(t,r){Nmt["symbol".concat(s0e(t))]=r},mAe=function(t){var r=t.type,n=r===void 0?"circle":r,a=t.size,i=a===void 0?64:a,l=t.sizeType,o=l===void 0?"area":l,c=Pgs(t,Egs),d=B$e(B$e({},c),{},{type:n,size:i,sizeType:o}),h=function(){var b=Rgs(n),j=hgs().type(b).size(Ogs(i,o,n));return j()},m=d.className,p=d.cx,x=d.cy,y=Li(d,!0);return p===+p&&x===+x&&i===+i?Nt.createElement("path",iSe({},y,{className:jo("recharts-symbols",m),transform:"translate(".concat(p,", ").concat(x,")"),d:h()})):null};mAe.registerSymbol=Fgs;function gL(s){"@babel/helpers - typeof";return gL=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},gL(s)}function oSe(){return oSe=Object.assign?Object.assign.bind():function(s){for(var t=1;t`);var k=x.inactive?d:x.color;return Nt.createElement("li",oSe({className:b,style:m,key:"legend-item-".concat(y)},SA(n.props,x,y)),Nt.createElement(Qke,{width:l,height:l,viewBox:h,style:p},n.renderIcon(x)),Nt.createElement("span",{className:"recharts-legend-item-text",style:{color:k}},_?_(j,x,y):j))})}},{key:"render",value:function(){var n=this.props,a=n.payload,i=n.layout,l=n.align;if(!a||!a.length)return null;var o={padding:0,margin:0,textAlign:i==="horizontal"?l:"left"};return Nt.createElement("ul",{className:"recharts-default-legend",style:o},this.renderItems())}}])}(S.PureComponent);D9(fAe,"displayName","Legend");D9(fAe,"defaultProps",{iconSize:14,layout:"horizontal",align:"center",verticalAlign:"middle",inactiveColor:"#ccc"});var Kgs=qxe;function Ygs(){this.__data__=new Kgs,this.size=0}var Zgs=Ygs;function Xgs(s){var t=this.__data__,r=t.delete(s);return this.size=t.size,r}var Qgs=Xgs;function Jgs(s){return this.__data__.get(s)}var exs=Jgs;function txs(s){return this.__data__.has(s)}var sxs=txs,rxs=qxe,nxs=tAe,axs=sAe,ixs=200;function oxs(s,t){var r=this.__data__;if(r instanceof rxs){var n=r.__data__;if(!nxs||n.lengtho))return!1;var d=i.get(s),h=i.get(t);if(d&&h)return d==t&&h==s;var m=-1,p=!0,x=r&Exs?new kxs:void 0;for(i.set(s,t),i.set(t,s);++m-1&&s%1==0&&s-1&&s%1==0&&s<=P0s}var yAe=L0s,D0s=Nj,R0s=yAe,O0s=kj,F0s="[object Arguments]",B0s="[object Array]",z0s="[object Boolean]",$0s="[object Date]",U0s="[object Error]",q0s="[object Function]",V0s="[object Map]",H0s="[object Number]",G0s="[object Object]",W0s="[object RegExp]",K0s="[object Set]",Y0s="[object String]",Z0s="[object WeakMap]",X0s="[object ArrayBuffer]",Q0s="[object DataView]",J0s="[object Float32Array]",eys="[object Float64Array]",tys="[object Int8Array]",sys="[object Int16Array]",rys="[object Int32Array]",nys="[object Uint8Array]",ays="[object Uint8ClampedArray]",iys="[object Uint16Array]",oys="[object Uint32Array]",wd={};wd[J0s]=wd[eys]=wd[tys]=wd[sys]=wd[rys]=wd[nys]=wd[ays]=wd[iys]=wd[oys]=!0;wd[F0s]=wd[B0s]=wd[X0s]=wd[z0s]=wd[Q0s]=wd[$0s]=wd[U0s]=wd[q0s]=wd[V0s]=wd[H0s]=wd[G0s]=wd[W0s]=wd[K0s]=wd[Y0s]=wd[Z0s]=!1;function lys(s){return O0s(s)&&R0s(s.length)&&!!wd[D0s(s)]}var cys=lys;function dys(s){return function(t){return s(t)}}var Dmt=dys,ffe={exports:{}};ffe.exports;(function(s,t){var r=qht,n=t&&!t.nodeType&&t,a=n&&!0&&s&&!s.nodeType&&s,i=a&&a.exports===n,l=i&&r.process,o=function(){try{var c=a&&a.require&&a.require("util").types;return c||l&&l.binding&&l.binding("util")}catch{}}();s.exports=o})(ffe,ffe.exports);var uys=ffe.exports,hys=cys,mys=Dmt,G$e=uys,W$e=G$e&&G$e.isTypedArray,fys=W$e?mys(W$e):hys,Rmt=fys,pys=y0s,gys=gAe,xys=gx,yys=Lmt,vys=xAe,bys=Rmt,_ys=Object.prototype,wys=_ys.hasOwnProperty;function jys(s,t){var r=xys(s),n=!r&&gys(s),a=!r&&!n&&yys(s),i=!r&&!n&&!a&&bys(s),l=r||n||a||i,o=l?pys(s.length,String):[],c=o.length;for(var d in s)(t||wys.call(s,d))&&!(l&&(d=="length"||a&&(d=="offset"||d=="parent")||i&&(d=="buffer"||d=="byteLength"||d=="byteOffset")||vys(d,c)))&&o.push(d);return o}var Nys=jys,kys=Object.prototype;function Sys(s){var t=s&&s.constructor,r=typeof t=="function"&&t.prototype||kys;return s===r}var Cys=Sys;function Tys(s,t){return function(r){return s(t(r))}}var Omt=Tys,Eys=Omt,Ays=Eys(Object.keys,Object),Mys=Ays,Iys=Cys,Pys=Mys,Lys=Object.prototype,Dys=Lys.hasOwnProperty;function Rys(s){if(!Iys(s))return Pys(s);var t=[];for(var r in Object(s))Dys.call(s,r)&&r!="constructor"&&t.push(r);return t}var Oys=Rys,Fys=JEe,Bys=yAe;function zys(s){return s!=null&&Bys(s.length)&&!Fys(s)}var Sz=zys,$ys=Nys,Uys=Oys,qys=Sz;function Vys(s){return qys(s)?$ys(s):Uys(s)}var i0e=Vys,Hys=i0s,Gys=g0s,Wys=i0e;function Kys(s){return Hys(s,Wys,Gys)}var Yys=Kys,K$e=Yys,Zys=1,Xys=Object.prototype,Qys=Xys.hasOwnProperty;function Jys(s,t,r,n,a,i){var l=r&Zys,o=K$e(s),c=o.length,d=K$e(t),h=d.length;if(c!=h&&!l)return!1;for(var m=c;m--;){var p=o[m];if(!(l?p in t:Qys.call(t,p)))return!1}var x=i.get(s),y=i.get(t);if(x&&y)return x==t&&y==s;var _=!0;i.set(s,t),i.set(t,s);for(var b=l;++m-1}var X1s=Z1s;function Q1s(s,t,r){for(var n=-1,a=s==null?0:s.length;++n=mbs){var d=t?null:ubs(s);if(d)return hbs(d);l=!1,a=dbs,c=new obs}else c=t?[]:o;e:for(;++n=0)&&Object.prototype.propertyIsEnumerable.call(s,n)&&(r[n]=s[n])}return r}function Ebs(s,t){if(s==null)return{};var r={};for(var n in s)if(Object.prototype.hasOwnProperty.call(s,n)){if(t.indexOf(n)>=0)continue;r[n]=s[n]}return r}function Abs(s){return s.value}function Mbs(s,t){if(Nt.isValidElement(s))return Nt.cloneElement(s,t);if(typeof s=="function")return Nt.createElement(s,t);t.ref;var r=Tbs(t,bbs);return Nt.createElement(fAe,r)}var dUe=1,pP=function(s){function t(){var r;_bs(this,t);for(var n=arguments.length,a=new Array(n),i=0;idUe||Math.abs(a.height-this.lastBoundingBox.height)>dUe)&&(this.lastBoundingBox.width=a.width,this.lastBoundingBox.height=a.height,n&&n(a)):(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?n2({},this.lastBoundingBox):{width:0,height:0}}},{key:"getDefaultPosition",value:function(n){var a=this.props,i=a.layout,l=a.align,o=a.verticalAlign,c=a.margin,d=a.chartWidth,h=a.chartHeight,m,p;if(!n||(n.left===void 0||n.left===null)&&(n.right===void 0||n.right===null))if(l==="center"&&i==="vertical"){var x=this.getBBoxSnapshot();m={left:((d||0)-x.width)/2}}else m=l==="right"?{right:c&&c.right||0}:{left:c&&c.left||0};if(!n||(n.top===void 0||n.top===null)&&(n.bottom===void 0||n.bottom===null))if(o==="middle"){var y=this.getBBoxSnapshot();p={top:((h||0)-y.height)/2}}else p=o==="bottom"?{bottom:c&&c.bottom||0}:{top:c&&c.top||0};return n2(n2({},m),p)}},{key:"render",value:function(){var n=this,a=this.props,i=a.content,l=a.width,o=a.height,c=a.wrapperStyle,d=a.payloadUniqBy,h=a.payload,m=n2(n2({position:"absolute",width:l||"auto",height:o||"auto"},this.getDefaultPosition(c)),c);return Nt.createElement("div",{className:"recharts-legend-wrapper",style:m,ref:function(x){n.wrapperNode=x}},Mbs(i,n2(n2({},this.props),{},{payload:Vmt(h,d,Abs)})))}}],[{key:"getWithHeight",value:function(n,a){var i=n2(n2({},this.defaultProps),n.props),l=i.layout;return l==="vertical"&&Kn(n.props.height)?{height:n.props.height}:l==="horizontal"?{width:n.props.width||a}:null}}])}(S.PureComponent);o0e(pP,"displayName","Legend");o0e(pP,"defaultProps",{iconSize:14,layout:"horizontal",align:"center",verticalAlign:"bottom"});var uUe=Nz,Ibs=gAe,Pbs=gx,hUe=uUe?uUe.isConcatSpreadable:void 0;function Lbs(s){return Pbs(s)||Ibs(s)||!!(hUe&&s&&s[hUe])}var Dbs=Lbs,Rbs=Imt,Obs=Dbs;function Wmt(s,t,r,n,a){var i=-1,l=s.length;for(r||(r=Obs),a||(a=[]);++i0&&r(o)?t>1?Wmt(o,t-1,r,n,a):Rbs(a,o):n||(a[a.length]=o)}return a}var Kmt=Wmt;function Fbs(s){return function(t,r,n){for(var a=-1,i=Object(t),l=n(t),o=l.length;o--;){var c=l[s?o:++a];if(r(i[c],c,i)===!1)break}return t}}var Bbs=Fbs,zbs=Bbs,$bs=zbs(),Ubs=$bs,qbs=Ubs,Vbs=i0e;function Hbs(s,t){return s&&qbs(s,t,Vbs)}var Ymt=Hbs,Gbs=Sz;function Wbs(s,t){return function(r,n){if(r==null)return r;if(!Gbs(r))return s(r,n);for(var a=r.length,i=t?a:-1,l=Object(r);(t?i--:++it||i&&l&&c&&!o&&!d||n&&l&&c||!r&&c||!a)return 1;if(!n&&!i&&!d&&s=o)return c;var d=r[n];return c*(d=="desc"?-1:1)}}return s.index-t.index}var o_s=i_s,q_e=nAe,l_s=aAe,c_s=Y_,d_s=Zmt,u_s=s_s,h_s=Dmt,m_s=o_s,f_s=O8,p_s=gx;function g_s(s,t,r){t.length?t=q_e(t,function(i){return p_s(i)?function(l){return l_s(l,i.length===1?i[0]:i)}:i}):t=[f_s];var n=-1;t=q_e(t,h_s(c_s));var a=d_s(s,function(i,l,o){var c=q_e(t,function(d){return d(i)});return{criteria:c,index:++n,value:i}});return u_s(a,function(i,l){return m_s(i,l,r)})}var x_s=g_s;function y_s(s,t,r){switch(r.length){case 0:return s.call(t);case 1:return s.call(t,r[0]);case 2:return s.call(t,r[0],r[1]);case 3:return s.call(t,r[0],r[1],r[2])}return s.apply(t,r)}var v_s=y_s,b_s=v_s,fUe=Math.max;function __s(s,t,r){return t=fUe(t===void 0?s.length-1:t,0),function(){for(var n=arguments,a=-1,i=fUe(n.length-t,0),l=Array(i);++a0){if(++t>=M_s)return arguments[0]}else t=0;return s.apply(void 0,arguments)}}var D_s=L_s,R_s=A_s,O_s=D_s,F_s=O_s(R_s),B_s=F_s,z_s=O8,$_s=w_s,U_s=B_s;function q_s(s,t){return U_s($_s(s,t,z_s),s+"")}var V_s=q_s,H_s=eAe,G_s=Sz,W_s=xAe,K_s=t4;function Y_s(s,t,r){if(!K_s(r))return!1;var n=typeof t;return(n=="number"?G_s(r)&&W_s(t,r.length):n=="string"&&t in r)?H_s(r[t],s):!1}var l0e=Y_s,Z_s=Kmt,X_s=x_s,Q_s=V_s,gUe=l0e,J_s=Q_s(function(s,t){if(s==null)return[];var r=t.length;return r>1&&gUe(s,t[0],t[1])?t=[]:r>2&&gUe(t[0],t[1],t[2])&&(t=[t[0]]),X_s(s,Z_s(t,1),[])}),ews=J_s;const _Ae=ol(ews);function R9(s){"@babel/helpers - typeof";return R9=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},R9(s)}function pSe(){return pSe=Object.assign?Object.assign.bind():function(s){for(var t=1;ts.length)&&(t=s.length);for(var r=0,n=new Array(t);r=t.x),"".concat(VR,"-left"),Kn(r)&&t&&Kn(t.x)&&r=t.y),"".concat(VR,"-top"),Kn(n)&&t&&Kn(t.y)&&n_?Math.max(h,c[n]):Math.max(m,c[n])}function pws(s){var t=s.translateX,r=s.translateY,n=s.useTranslate3d;return{transform:n?"translate3d(".concat(t,"px, ").concat(r,"px, 0)"):"translate(".concat(t,"px, ").concat(r,"px)")}}function gws(s){var t=s.allowEscapeViewBox,r=s.coordinate,n=s.offsetTopLeft,a=s.position,i=s.reverseDirection,l=s.tooltipBox,o=s.useTranslate3d,c=s.viewBox,d,h,m;return l.height>0&&l.width>0&&r?(h=vUe({allowEscapeViewBox:t,coordinate:r,key:"x",offsetTopLeft:n,position:a,reverseDirection:i,tooltipDimension:l.width,viewBox:c,viewBoxDimension:c.width}),m=vUe({allowEscapeViewBox:t,coordinate:r,key:"y",offsetTopLeft:n,position:a,reverseDirection:i,tooltipDimension:l.height,viewBox:c,viewBoxDimension:c.height}),d=pws({translateX:h,translateY:m,useTranslate3d:o})):d=mws,{cssProperties:d,cssClasses:fws({translateX:h,translateY:m,coordinate:r})}}function yL(s){"@babel/helpers - typeof";return yL=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},yL(s)}function bUe(s,t){var r=Object.keys(s);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(s);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(s,a).enumerable})),r.push.apply(r,n)}return r}function _Ue(s){for(var t=1;twUe||Math.abs(n.height-this.state.lastBoundingBox.height)>wUe)&&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,a;this.props.active&&this.updateBBox(),this.state.dismissed&&(((n=this.props.coordinate)===null||n===void 0?void 0:n.x)!==this.state.dismissedAtCoordinate.x||((a=this.props.coordinate)===null||a===void 0?void 0:a.y)!==this.state.dismissedAtCoordinate.y)&&(this.state.dismissed=!1)}},{key:"render",value:function(){var n=this,a=this.props,i=a.active,l=a.allowEscapeViewBox,o=a.animationDuration,c=a.animationEasing,d=a.children,h=a.coordinate,m=a.hasPayload,p=a.isAnimationActive,x=a.offset,y=a.position,_=a.reverseDirection,b=a.useTranslate3d,j=a.viewBox,k=a.wrapperStyle,T=gws({allowEscapeViewBox:l,coordinate:h,offsetTopLeft:x,position:y,reverseDirection:_,tooltipBox:this.state.lastBoundingBox,useTranslate3d:b,viewBox:j}),E=T.cssClasses,A=T.cssProperties,D=_Ue(_Ue({transition:p&&i?"transform ".concat(o,"ms ").concat(c):void 0},A),{},{pointerEvents:"none",visibility:!this.state.dismissed&&i&&m?"visible":"hidden",position:"absolute",top:0,left:0},k);return Nt.createElement("div",{tabIndex:-1,className:E,style:D,ref:function(z){n.wrapperNode=z}},d)}}])}(S.PureComponent),Sws=function(){return!(typeof window<"u"&&window.document&&window.document.createElement&&window.setTimeout)},N_={isSsr:Sws(),get:function(t){return N_[t]},set:function(t,r){if(typeof t=="string")N_[t]=r;else{var n=Object.keys(t);n&&n.length&&n.forEach(function(a){N_[a]=t[a]})}}};function vL(s){"@babel/helpers - typeof";return vL=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},vL(s)}function jUe(s,t){var r=Object.keys(s);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(s);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(s,a).enumerable})),r.push.apply(r,n)}return r}function NUe(s){for(var t=1;t0;return Nt.createElement(kws,{allowEscapeViewBox:l,animationDuration:o,animationEasing:c,isAnimationActive:p,active:i,coordinate:h,hasPayload:D,offset:x,position:b,reverseDirection:j,useTranslate3d:k,viewBox:T,wrapperStyle:E},Rws(d,NUe(NUe({},this.props),{},{payload:A})))}}])}(S.PureComponent);wAe(Zg,"displayName","Tooltip");wAe(Zg,"defaultProps",{accessibilityLayer:!1,allowEscapeViewBox:{x:!1,y:!1},animationDuration:400,animationEasing:"ease",contentStyle:{},coordinate:{x:0,y:0},cursor:!0,cursorStyle:{},filterNull:!0,isAnimationActive:!N_.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 Ows=K_,Fws=function(){return Ows.Date.now()},Bws=Fws,zws=/\s/;function $ws(s){for(var t=s.length;t--&&zws.test(s.charAt(t)););return t}var Uws=$ws,qws=Uws,Vws=/^\s+/;function Hws(s){return s&&s.slice(0,qws(s)+1).replace(Vws,"")}var Gws=Hws,Wws=Gws,kUe=t4,Kws=E8,SUe=NaN,Yws=/^[-+]0x[0-9a-f]+$/i,Zws=/^0b[01]+$/i,Xws=/^0o[0-7]+$/i,Qws=parseInt;function Jws(s){if(typeof s=="number")return s;if(Kws(s))return SUe;if(kUe(s)){var t=typeof s.valueOf=="function"?s.valueOf():s;s=kUe(t)?t+"":t}if(typeof s!="string")return s===0?s:+s;s=Wws(s);var r=Zws.test(s);return r||Xws.test(s)?Qws(s.slice(2),r?2:8):Yws.test(s)?SUe:+s}var sft=Jws,e2s=t4,H_e=Bws,CUe=sft,t2s="Expected a function",s2s=Math.max,r2s=Math.min;function n2s(s,t,r){var n,a,i,l,o,c,d=0,h=!1,m=!1,p=!0;if(typeof s!="function")throw new TypeError(t2s);t=CUe(t)||0,e2s(r)&&(h=!!r.leading,m="maxWait"in r,i=m?s2s(CUe(r.maxWait)||0,t):i,p="trailing"in r?!!r.trailing:p);function x(D){var R=n,z=a;return n=a=void 0,d=D,l=s.apply(z,R),l}function y(D){return d=D,o=setTimeout(j,t),h?x(D):l}function _(D){var R=D-c,z=D-d,O=t-R;return m?r2s(O,i-z):O}function b(D){var R=D-c,z=D-d;return c===void 0||R>=t||R<0||m&&z>=i}function j(){var D=H_e();if(b(D))return k(D);o=setTimeout(j,_(D))}function k(D){return o=void 0,p&&n?x(D):(n=a=void 0,l)}function T(){o!==void 0&&clearTimeout(o),d=0,n=c=a=o=void 0}function E(){return o===void 0?l:k(H_e())}function A(){var D=H_e(),R=b(D);if(n=arguments,a=this,c=D,R){if(o===void 0)return y(c);if(m)return clearTimeout(o),o=setTimeout(j,t),x(c)}return o===void 0&&(o=setTimeout(j,t)),l}return A.cancel=T,A.flush=E,A}var a2s=n2s,i2s=a2s,o2s=t4,l2s="Expected a function";function c2s(s,t,r){var n=!0,a=!0;if(typeof s!="function")throw new TypeError(l2s);return o2s(r)&&(n="leading"in r?!!r.leading:n,a="trailing"in r?!!r.trailing:a),i2s(s,t,{leading:n,maxWait:t,trailing:a})}var d2s=c2s;const rft=ol(d2s);function F9(s){"@babel/helpers - typeof";return F9=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},F9(s)}function TUe(s,t){var r=Object.keys(s);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(s);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(s,a).enumerable})),r.push.apply(r,n)}return r}function Iq(s){for(var t=1;ts.length)&&(t=s.length);for(var r=0,n=new Array(t);r0&&(J=rft(J,_,{trailing:!0,leading:!1}));var K=new ResizeObserver(J),re=A.current.getBoundingClientRect(),ie=re.width,ce=re.height;return ee(ie,ce),K.observe(A.current),function(){K.disconnect()}},[ee,_]);var Z=S.useMemo(function(){var J=O.containerWidth,K=O.containerHeight;if(J<0||K<0)return null;S1(HT(l)||HT(c),`The width(%s) and height(%s) are both fixed numbers, maybe you don't need to use a ResponsiveContainer.`,l,c),S1(!r||r>0,"The aspect(%s) must be greater than zero.",r);var re=HT(l)?J:l,ie=HT(c)?K:c;r&&r>0&&(re?ie=re/r:ie&&(re=ie*r),p&&ie>p&&(ie=p)),S1(re>0||ie>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.`,re,ie,l,c,h,m,r);var ce=!Array.isArray(x)&&Z2(x.type).endsWith("Chart");return Nt.Children.map(x,function(ne){return Nt.isValidElement(ne)?S.cloneElement(ne,Iq({width:re,height:ie},ce?{style:Iq({height:"100%",width:"100%",maxHeight:ie,maxWidth:re},ne.props.style)}:{})):ne})},[r,x,c,p,m,h,O,l]);return Nt.createElement("div",{id:b?"".concat(b):void 0,className:jo("recharts-responsive-container",j),style:Iq(Iq({},E),{},{width:l,height:c,minWidth:h,minHeight:m,maxHeight:p}),ref:A},Z)}),Cz=function(t){return null};Cz.displayName="Cell";function B9(s){"@babel/helpers - typeof";return B9=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},B9(s)}function AUe(s,t){var r=Object.keys(s);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(s);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(s,a).enumerable})),r.push.apply(r,n)}return r}function vSe(s){for(var t=1;t1&&arguments[1]!==void 0?arguments[1]:{};if(t==null||N_.isSsr)return{width:0,height:0};var n=N2s(r),a=JSON.stringify({text:t,copyStyle:n});if(k6.widthCache[a])return k6.widthCache[a];try{var i=document.getElementById(MUe);i||(i=document.createElement("span"),i.setAttribute("id",MUe),i.setAttribute("aria-hidden","true"),document.body.appendChild(i));var l=vSe(vSe({},j2s),n);Object.assign(i.style,l),i.textContent="".concat(t);var o=i.getBoundingClientRect(),c={width:o.width,height:o.height};return k6.widthCache[a]=c,++k6.cacheCount>w2s&&(k6.cacheCount=0,k6.widthCache={}),c}catch{return{width:0,height:0}}},k2s=function(t){return{top:t.top+window.scrollY-document.documentElement.clientTop,left:t.left+window.scrollX-document.documentElement.clientLeft}};function z9(s){"@babel/helpers - typeof";return z9=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},z9(s)}function yfe(s,t){return E2s(s)||T2s(s,t)||C2s(s,t)||S2s()}function S2s(){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 C2s(s,t){if(s){if(typeof s=="string")return IUe(s,t);var r=Object.prototype.toString.call(s).slice(8,-1);if(r==="Object"&&s.constructor&&(r=s.constructor.name),r==="Map"||r==="Set")return Array.from(s);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return IUe(s,t)}}function IUe(s,t){(t==null||t>s.length)&&(t=s.length);for(var r=0,n=new Array(t);r=0)&&Object.prototype.propertyIsEnumerable.call(s,n)&&(r[n]=s[n])}return r}function q2s(s,t){if(s==null)return{};var r={};for(var n in s)if(Object.prototype.hasOwnProperty.call(s,n)){if(t.indexOf(n)>=0)continue;r[n]=s[n]}return r}function FUe(s,t){return W2s(s)||G2s(s,t)||H2s(s,t)||V2s()}function V2s(){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 H2s(s,t){if(s){if(typeof s=="string")return BUe(s,t);var r=Object.prototype.toString.call(s).slice(8,-1);if(r==="Object"&&s.constructor&&(r=s.constructor.name),r==="Map"||r==="Set")return Array.from(s);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return BUe(s,t)}}function BUe(s,t){(t==null||t>s.length)&&(t=s.length);for(var r=0,n=new Array(t);r0&&arguments[0]!==void 0?arguments[0]:[];return re.reduce(function(ie,ce){var ne=ce.word,le=ce.width,be=ie[ie.length-1];if(be&&(a==null||i||be.width+le+nce.width?ie:ce})};if(!h)return x;for(var _="…",b=function(re){var ie=m.slice(0,re),ce=oft({breakAll:d,style:c,children:ie+_}).wordsWithComputedWidth,ne=p(ce),le=ne.length>l||y(ne).width>Number(a);return[le,ne]},j=0,k=m.length-1,T=0,E;j<=k&&T<=m.length-1;){var A=Math.floor((j+k)/2),D=A-1,R=b(D),z=FUe(R,2),O=z[0],$=z[1],ee=b(A),Z=FUe(ee,1),J=Z[0];if(!O&&!J&&(j=A+1),O&&J&&(k=A-1),!O&&J){E=$;break}T++}return E||x},zUe=function(t){var r=yo(t)?[]:t.toString().split(ift);return[{words:r}]},Y2s=function(t){var r=t.width,n=t.scaleToFit,a=t.children,i=t.style,l=t.breakAll,o=t.maxLines;if((r||n)&&!N_.isSsr){var c,d,h=oft({breakAll:l,children:a,style:i});if(h){var m=h.wordsWithComputedWidth,p=h.spaceWidth;c=m,d=p}else return zUe(a);return K2s({breakAll:l,children:a,maxLines:o,style:i},c,d,r,n)}return zUe(a)},$Ue="#808080",CA=function(t){var r=t.x,n=r===void 0?0:r,a=t.y,i=a===void 0?0:a,l=t.lineHeight,o=l===void 0?"1em":l,c=t.capHeight,d=c===void 0?"0.71em":c,h=t.scaleToFit,m=h===void 0?!1:h,p=t.textAnchor,x=p===void 0?"start":p,y=t.verticalAnchor,_=y===void 0?"end":y,b=t.fill,j=b===void 0?$Ue:b,k=OUe(t,$2s),T=S.useMemo(function(){return Y2s({breakAll:k.breakAll,children:k.children,maxLines:k.maxLines,scaleToFit:m,style:k.style,width:k.width})},[k.breakAll,k.children,k.maxLines,m,k.style,k.width]),E=k.dx,A=k.dy,D=k.angle,R=k.className,z=k.breakAll,O=OUe(k,U2s);if(!hm(n)||!hm(i))return null;var $=n+(Kn(E)?E:0),ee=i+(Kn(A)?A:0),Z;switch(_){case"start":Z=G_e("calc(".concat(d,")"));break;case"middle":Z=G_e("calc(".concat((T.length-1)/2," * -").concat(o," + (").concat(d," / 2))"));break;default:Z=G_e("calc(".concat(T.length-1," * -").concat(o,")"));break}var J=[];if(m){var K=T[0].width,re=k.width;J.push("scale(".concat((Kn(re)?re/K:1)/K,")"))}return D&&J.push("rotate(".concat(D,", ").concat($,", ").concat(ee,")")),J.length&&(O.transform=J.join(" ")),Nt.createElement("text",bSe({},Li(O,!0),{x:$,y:ee,className:jo("recharts-text",R),textAnchor:x,fill:j.includes("url")?$Ue:j}),T.map(function(ie,ce){var ne=ie.words.join(z?"":" ");return Nt.createElement("tspan",{x:$,dy:ce===0?Z:o,key:"".concat(ne,"-").concat(ce)},ne)}))};function lS(s,t){return s==null||t==null?NaN:st?1:s>=t?0:NaN}function Z2s(s,t){return s==null||t==null?NaN:ts?1:t>=s?0:NaN}function jAe(s){let t,r,n;s.length!==2?(t=lS,r=(o,c)=>lS(s(o),c),n=(o,c)=>s(o)-c):(t=s===lS||s===Z2s?s:X2s,r=s,n=s);function a(o,c,d=0,h=o.length){if(d>>1;r(o[m],c)<0?d=m+1:h=m}while(d>>1;r(o[m],c)<=0?d=m+1:h=m}while(dd&&n(o[m-1],c)>-n(o[m],c)?m-1:m}return{left:a,center:l,right:i}}function X2s(){return 0}function lft(s){return s===null?NaN:+s}function*Q2s(s,t){for(let r of s)r!=null&&(r=+r)>=r&&(yield r)}const J2s=jAe(lS),Tz=J2s.right;jAe(lft).center;class UUe extends Map{constructor(t,r=sjs){if(super(),Object.defineProperties(this,{_intern:{value:new Map},_key:{value:r}}),t!=null)for(const[n,a]of t)this.set(n,a)}get(t){return super.get(qUe(this,t))}has(t){return super.has(qUe(this,t))}set(t,r){return super.set(ejs(this,t),r)}delete(t){return super.delete(tjs(this,t))}}function qUe({_intern:s,_key:t},r){const n=t(r);return s.has(n)?s.get(n):r}function ejs({_intern:s,_key:t},r){const n=t(r);return s.has(n)?s.get(n):(s.set(n,r),r)}function tjs({_intern:s,_key:t},r){const n=t(r);return s.has(n)&&(r=s.get(n),s.delete(n)),r}function sjs(s){return s!==null&&typeof s=="object"?s.valueOf():s}function rjs(s=lS){if(s===lS)return cft;if(typeof s!="function")throw new TypeError("compare is not a function");return(t,r)=>{const n=s(t,r);return n||n===0?n:(s(r,r)===0)-(s(t,t)===0)}}function cft(s,t){return(s==null||!(s>=s))-(t==null||!(t>=t))||(st?1:0)}const njs=Math.sqrt(50),ajs=Math.sqrt(10),ijs=Math.sqrt(2);function vfe(s,t,r){const n=(t-s)/Math.max(0,r),a=Math.floor(Math.log10(n)),i=n/Math.pow(10,a),l=i>=njs?10:i>=ajs?5:i>=ijs?2:1;let o,c,d;return a<0?(d=Math.pow(10,-a)/l,o=Math.round(s*d),c=Math.round(t*d),o/dt&&--c,d=-d):(d=Math.pow(10,a)*l,o=Math.round(s/d),c=Math.round(t/d),o*dt&&--c),c0))return[];if(s===t)return[s];const n=t=a))return[];const o=i-a+1,c=new Array(o);if(n)if(l<0)for(let d=0;d=n)&&(r=n);return r}function HUe(s,t){let r;for(const n of s)n!=null&&(r>n||r===void 0&&n>=n)&&(r=n);return r}function dft(s,t,r=0,n=1/0,a){if(t=Math.floor(t),r=Math.floor(Math.max(0,r)),n=Math.floor(Math.min(s.length-1,n)),!(r<=t&&t<=n))return s;for(a=a===void 0?cft:rjs(a);n>r;){if(n-r>600){const c=n-r+1,d=t-r+1,h=Math.log(c),m=.5*Math.exp(2*h/3),p=.5*Math.sqrt(h*m*(c-m)/c)*(d-c/2<0?-1:1),x=Math.max(r,Math.floor(t-d*m/c+p)),y=Math.min(n,Math.floor(t+(c-d)*m/c+p));dft(s,t,x,y,a)}const i=s[t];let l=r,o=n;for(HR(s,r,t),a(s[n],i)>0&&HR(s,r,n);l0;)--o}a(s[r],i)===0?HR(s,r,o):(++o,HR(s,o,n)),o<=t&&(r=o+1),t<=o&&(n=o-1)}return s}function HR(s,t,r){const n=s[t];s[t]=s[r],s[r]=n}function ojs(s,t,r){if(s=Float64Array.from(Q2s(s)),!(!(n=s.length)||isNaN(t=+t))){if(t<=0||n<2)return HUe(s);if(t>=1)return VUe(s);var n,a=(n-1)*t,i=Math.floor(a),l=VUe(dft(s,i).subarray(0,i+1)),o=HUe(s.subarray(i+1));return l+(o-l)*(a-i)}}function ljs(s,t,r=lft){if(!(!(n=s.length)||isNaN(t=+t))){if(t<=0||n<2)return+r(s[0],0,s);if(t>=1)return+r(s[n-1],n-1,s);var n,a=(n-1)*t,i=Math.floor(a),l=+r(s[i],i,s),o=+r(s[i+1],i+1,s);return l+(o-l)*(a-i)}}function cjs(s,t,r){s=+s,t=+t,r=(a=arguments.length)<2?(t=s,s=0,1):a<3?1:+r;for(var n=-1,a=Math.max(0,Math.ceil((t-s)/r))|0,i=new Array(a);++n>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):r===8?Lq(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):r===4?Lq(t>>12&15|t>>8&240,t>>8&15|t>>4&240,t>>4&15|t&240,((t&15)<<4|t&15)/255):null):(t=ujs.exec(s))?new rx(t[1],t[2],t[3],1):(t=hjs.exec(s))?new rx(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=mjs.exec(s))?Lq(t[1],t[2],t[3],t[4]):(t=fjs.exec(s))?Lq(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=pjs.exec(s))?QUe(t[1],t[2]/100,t[3]/100,1):(t=gjs.exec(s))?QUe(t[1],t[2]/100,t[3]/100,t[4]):GUe.hasOwnProperty(s)?YUe(GUe[s]):s==="transparent"?new rx(NaN,NaN,NaN,0):null}function YUe(s){return new rx(s>>16&255,s>>8&255,s&255,1)}function Lq(s,t,r,n){return n<=0&&(s=t=r=NaN),new rx(s,t,r,n)}function vjs(s){return s instanceof Ez||(s=V9(s)),s?(s=s.rgb(),new rx(s.r,s.g,s.b,s.opacity)):new rx}function kSe(s,t,r,n){return arguments.length===1?vjs(s):new rx(s,t,r,n??1)}function rx(s,t,r,n){this.r=+s,this.g=+t,this.b=+r,this.opacity=+n}kAe(rx,kSe,hft(Ez,{brighter(s){return s=s==null?bfe:Math.pow(bfe,s),new rx(this.r*s,this.g*s,this.b*s,this.opacity)},darker(s){return s=s==null?U9:Math.pow(U9,s),new rx(this.r*s,this.g*s,this.b*s,this.opacity)},rgb(){return this},clamp(){return new rx(KE(this.r),KE(this.g),KE(this.b),_fe(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:ZUe,formatHex:ZUe,formatHex8:bjs,formatRgb:XUe,toString:XUe}));function ZUe(){return`#${GT(this.r)}${GT(this.g)}${GT(this.b)}`}function bjs(){return`#${GT(this.r)}${GT(this.g)}${GT(this.b)}${GT((isNaN(this.opacity)?1:this.opacity)*255)}`}function XUe(){const s=_fe(this.opacity);return`${s===1?"rgb(":"rgba("}${KE(this.r)}, ${KE(this.g)}, ${KE(this.b)}${s===1?")":`, ${s})`}`}function _fe(s){return isNaN(s)?1:Math.max(0,Math.min(1,s))}function KE(s){return Math.max(0,Math.min(255,Math.round(s)||0))}function GT(s){return s=KE(s),(s<16?"0":"")+s.toString(16)}function QUe(s,t,r,n){return n<=0?s=t=r=NaN:r<=0||r>=1?s=t=NaN:t<=0&&(s=NaN),new d1(s,t,r,n)}function mft(s){if(s instanceof d1)return new d1(s.h,s.s,s.l,s.opacity);if(s instanceof Ez||(s=V9(s)),!s)return new d1;if(s instanceof d1)return s;s=s.rgb();var t=s.r/255,r=s.g/255,n=s.b/255,a=Math.min(t,r,n),i=Math.max(t,r,n),l=NaN,o=i-a,c=(i+a)/2;return o?(t===i?l=(r-n)/o+(r0&&c<1?0:l,new d1(l,o,c,s.opacity)}function _js(s,t,r,n){return arguments.length===1?mft(s):new d1(s,t,r,n??1)}function d1(s,t,r,n){this.h=+s,this.s=+t,this.l=+r,this.opacity=+n}kAe(d1,_js,hft(Ez,{brighter(s){return s=s==null?bfe:Math.pow(bfe,s),new d1(this.h,this.s,this.l*s,this.opacity)},darker(s){return s=s==null?U9:Math.pow(U9,s),new d1(this.h,this.s,this.l*s,this.opacity)},rgb(){var s=this.h%360+(this.h<0)*360,t=isNaN(s)||isNaN(this.s)?0:this.s,r=this.l,n=r+(r<.5?r:1-r)*t,a=2*r-n;return new rx(W_e(s>=240?s-240:s+120,a,n),W_e(s,a,n),W_e(s<120?s+240:s-120,a,n),this.opacity)},clamp(){return new d1(JUe(this.h),Dq(this.s),Dq(this.l),_fe(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 s=_fe(this.opacity);return`${s===1?"hsl(":"hsla("}${JUe(this.h)}, ${Dq(this.s)*100}%, ${Dq(this.l)*100}%${s===1?")":`, ${s})`}`}}));function JUe(s){return s=(s||0)%360,s<0?s+360:s}function Dq(s){return Math.max(0,Math.min(1,s||0))}function W_e(s,t,r){return(s<60?t+(r-t)*s/60:s<180?r:s<240?t+(r-t)*(240-s)/60:t)*255}const SAe=s=>()=>s;function wjs(s,t){return function(r){return s+r*t}}function jjs(s,t,r){return s=Math.pow(s,r),t=Math.pow(t,r)-s,r=1/r,function(n){return Math.pow(s+n*t,r)}}function Njs(s){return(s=+s)==1?fft:function(t,r){return r-t?jjs(t,r,s):SAe(isNaN(t)?r:t)}}function fft(s,t){var r=t-s;return r?wjs(s,r):SAe(isNaN(s)?t:s)}const eqe=function s(t){var r=Njs(t);function n(a,i){var l=r((a=kSe(a)).r,(i=kSe(i)).r),o=r(a.g,i.g),c=r(a.b,i.b),d=fft(a.opacity,i.opacity);return function(h){return a.r=l(h),a.g=o(h),a.b=c(h),a.opacity=d(h),a+""}}return n.gamma=s,n}(1);function kjs(s,t){t||(t=[]);var r=s?Math.min(t.length,s.length):0,n=t.slice(),a;return function(i){for(a=0;ar&&(i=t.slice(r,i),o[l]?o[l]+=i:o[++l]=i),(n=n[0])===(a=a[0])?o[l]?o[l]+=a:o[++l]=a:(o[++l]=null,c.push({i:l,x:wfe(n,a)})),r=K_e.lastIndex;return rt&&(r=s,s=t,t=r),function(n){return Math.max(s,Math.min(t,n))}}function Rjs(s,t,r){var n=s[0],a=s[1],i=t[0],l=t[1];return a2?Ojs:Rjs,c=d=null,m}function m(p){return p==null||isNaN(p=+p)?i:(c||(c=o(s.map(n),t,r)))(n(l(p)))}return m.invert=function(p){return l(a((d||(d=o(t,s.map(n),wfe)))(p)))},m.domain=function(p){return arguments.length?(s=Array.from(p,jfe),h()):s.slice()},m.range=function(p){return arguments.length?(t=Array.from(p),h()):t.slice()},m.rangeRound=function(p){return t=Array.from(p),r=CAe,h()},m.clamp=function(p){return arguments.length?(l=p?!0:yg,h()):l!==yg},m.interpolate=function(p){return arguments.length?(r=p,h()):r},m.unknown=function(p){return arguments.length?(i=p,m):i},function(p,x){return n=p,a=x,h()}}function TAe(){return c0e()(yg,yg)}function Fjs(s){return Math.abs(s=Math.round(s))>=1e21?s.toLocaleString("en").replace(/,/g,""):s.toString(10)}function Nfe(s,t){if((r=(s=t?s.toExponential(t-1):s.toExponential()).indexOf("e"))<0)return null;var r,n=s.slice(0,r);return[n.length>1?n[0]+n.slice(2):n,+s.slice(r+1)]}function bL(s){return s=Nfe(Math.abs(s)),s?s[1]:NaN}function Bjs(s,t){return function(r,n){for(var a=r.length,i=[],l=0,o=s[0],c=0;a>0&&o>0&&(c+o+1>n&&(o=Math.max(1,n-c)),i.push(r.substring(a-=o,a+o)),!((c+=o+1)>n));)o=s[l=(l+1)%s.length];return i.reverse().join(t)}}function zjs(s){return function(t){return t.replace(/[0-9]/g,function(r){return s[+r]})}}var $js=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;function H9(s){if(!(t=$js.exec(s)))throw new Error("invalid format: "+s);var t;return new EAe({fill:t[1],align:t[2],sign:t[3],symbol:t[4],zero:t[5],width:t[6],comma:t[7],precision:t[8]&&t[8].slice(1),trim:t[9],type:t[10]})}H9.prototype=EAe.prototype;function EAe(s){this.fill=s.fill===void 0?" ":s.fill+"",this.align=s.align===void 0?">":s.align+"",this.sign=s.sign===void 0?"-":s.sign+"",this.symbol=s.symbol===void 0?"":s.symbol+"",this.zero=!!s.zero,this.width=s.width===void 0?void 0:+s.width,this.comma=!!s.comma,this.precision=s.precision===void 0?void 0:+s.precision,this.trim=!!s.trim,this.type=s.type===void 0?"":s.type+""}EAe.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 Ujs(s){e:for(var t=s.length,r=1,n=-1,a;r0&&(n=0);break}return n>0?s.slice(0,n)+s.slice(a+1):s}var pft;function qjs(s,t){var r=Nfe(s,t);if(!r)return s+"";var n=r[0],a=r[1],i=a-(pft=Math.max(-8,Math.min(8,Math.floor(a/3)))*3)+1,l=n.length;return i===l?n:i>l?n+new Array(i-l+1).join("0"):i>0?n.slice(0,i)+"."+n.slice(i):"0."+new Array(1-i).join("0")+Nfe(s,Math.max(0,t+i-1))[0]}function sqe(s,t){var r=Nfe(s,t);if(!r)return s+"";var n=r[0],a=r[1];return a<0?"0."+new Array(-a).join("0")+n:n.length>a+1?n.slice(0,a+1)+"."+n.slice(a+1):n+new Array(a-n.length+2).join("0")}const rqe={"%":(s,t)=>(s*100).toFixed(t),b:s=>Math.round(s).toString(2),c:s=>s+"",d:Fjs,e:(s,t)=>s.toExponential(t),f:(s,t)=>s.toFixed(t),g:(s,t)=>s.toPrecision(t),o:s=>Math.round(s).toString(8),p:(s,t)=>sqe(s*100,t),r:sqe,s:qjs,X:s=>Math.round(s).toString(16).toUpperCase(),x:s=>Math.round(s).toString(16)};function nqe(s){return s}var aqe=Array.prototype.map,iqe=["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"];function Vjs(s){var t=s.grouping===void 0||s.thousands===void 0?nqe:Bjs(aqe.call(s.grouping,Number),s.thousands+""),r=s.currency===void 0?"":s.currency[0]+"",n=s.currency===void 0?"":s.currency[1]+"",a=s.decimal===void 0?".":s.decimal+"",i=s.numerals===void 0?nqe:zjs(aqe.call(s.numerals,String)),l=s.percent===void 0?"%":s.percent+"",o=s.minus===void 0?"−":s.minus+"",c=s.nan===void 0?"NaN":s.nan+"";function d(m){m=H9(m);var p=m.fill,x=m.align,y=m.sign,_=m.symbol,b=m.zero,j=m.width,k=m.comma,T=m.precision,E=m.trim,A=m.type;A==="n"?(k=!0,A="g"):rqe[A]||(T===void 0&&(T=12),E=!0,A="g"),(b||p==="0"&&x==="=")&&(b=!0,p="0",x="=");var D=_==="$"?r:_==="#"&&/[boxX]/.test(A)?"0"+A.toLowerCase():"",R=_==="$"?n:/[%p]/.test(A)?l:"",z=rqe[A],O=/[defgprs%]/.test(A);T=T===void 0?6:/[gprs]/.test(A)?Math.max(1,Math.min(21,T)):Math.max(0,Math.min(20,T));function $(ee){var Z=D,J=R,K,re,ie;if(A==="c")J=z(ee)+J,ee="";else{ee=+ee;var ce=ee<0||1/ee<0;if(ee=isNaN(ee)?c:z(Math.abs(ee),T),E&&(ee=Ujs(ee)),ce&&+ee==0&&y!=="+"&&(ce=!1),Z=(ce?y==="("?y:o:y==="-"||y==="("?"":y)+Z,J=(A==="s"?iqe[8+pft/3]:"")+J+(ce&&y==="("?")":""),O){for(K=-1,re=ee.length;++Kie||ie>57){J=(ie===46?a+ee.slice(K+1):ee.slice(K))+J,ee=ee.slice(0,K);break}}}k&&!b&&(ee=t(ee,1/0));var ne=Z.length+ee.length+J.length,le=ne>1)+Z+ee+J+le.slice(ne);break;default:ee=le+Z+ee+J;break}return i(ee)}return $.toString=function(){return m+""},$}function h(m,p){var x=d((m=H9(m),m.type="f",m)),y=Math.max(-8,Math.min(8,Math.floor(bL(p)/3)))*3,_=Math.pow(10,-y),b=iqe[8+y/3];return function(j){return x(_*j)+b}}return{format:d,formatPrefix:h}}var Rq,AAe,gft;Hjs({thousands:",",grouping:[3],currency:["$",""]});function Hjs(s){return Rq=Vjs(s),AAe=Rq.format,gft=Rq.formatPrefix,Rq}function Gjs(s){return Math.max(0,-bL(Math.abs(s)))}function Wjs(s,t){return Math.max(0,Math.max(-8,Math.min(8,Math.floor(bL(t)/3)))*3-bL(Math.abs(s)))}function Kjs(s,t){return s=Math.abs(s),t=Math.abs(t)-s,Math.max(0,bL(t)-bL(s))+1}function xft(s,t,r,n){var a=jSe(s,t,r),i;switch(n=H9(n??",f"),n.type){case"s":{var l=Math.max(Math.abs(s),Math.abs(t));return n.precision==null&&!isNaN(i=Wjs(a,l))&&(n.precision=i),gft(n,l)}case"":case"e":case"g":case"p":case"r":{n.precision==null&&!isNaN(i=Kjs(a,Math.max(Math.abs(s),Math.abs(t))))&&(n.precision=i-(n.type==="e"));break}case"f":case"%":{n.precision==null&&!isNaN(i=Gjs(a))&&(n.precision=i-(n.type==="%")*2);break}}return AAe(n)}function s4(s){var t=s.domain;return s.ticks=function(r){var n=t();return _Se(n[0],n[n.length-1],r??10)},s.tickFormat=function(r,n){var a=t();return xft(a[0],a[a.length-1],r??10,n)},s.nice=function(r){r==null&&(r=10);var n=t(),a=0,i=n.length-1,l=n[a],o=n[i],c,d,h=10;for(o0;){if(d=wSe(l,o,r),d===c)return n[a]=l,n[i]=o,t(n);if(d>0)l=Math.floor(l/d)*d,o=Math.ceil(o/d)*d;else if(d<0)l=Math.ceil(l*d)/d,o=Math.floor(o*d)/d;else break;c=d}return s},s}function kfe(){var s=TAe();return s.copy=function(){return Az(s,kfe())},ov.apply(s,arguments),s4(s)}function yft(s){var t;function r(n){return n==null||isNaN(n=+n)?t:n}return r.invert=r,r.domain=r.range=function(n){return arguments.length?(s=Array.from(n,jfe),r):s.slice()},r.unknown=function(n){return arguments.length?(t=n,r):t},r.copy=function(){return yft(s).unknown(t)},s=arguments.length?Array.from(s,jfe):[0,1],s4(r)}function vft(s,t){s=s.slice();var r=0,n=s.length-1,a=s[r],i=s[n],l;return iMath.pow(s,t)}function Jjs(s){return s===Math.E?Math.log:s===10&&Math.log10||s===2&&Math.log2||(s=Math.log(s),t=>Math.log(t)/s)}function cqe(s){return(t,r)=>-s(-t,r)}function MAe(s){const t=s(oqe,lqe),r=t.domain;let n=10,a,i;function l(){return a=Jjs(n),i=Qjs(n),r()[0]<0?(a=cqe(a),i=cqe(i),s(Yjs,Zjs)):s(oqe,lqe),t}return t.base=function(o){return arguments.length?(n=+o,l()):n},t.domain=function(o){return arguments.length?(r(o),l()):r()},t.ticks=o=>{const c=r();let d=c[0],h=c[c.length-1];const m=h0){for(;p<=x;++p)for(y=1;yh)break;j.push(_)}}else for(;p<=x;++p)for(y=n-1;y>=1;--y)if(_=p>0?y/i(-p):y*i(p),!(_h)break;j.push(_)}j.length*2{if(o==null&&(o=10),c==null&&(c=n===10?"s":","),typeof c!="function"&&(!(n%1)&&(c=H9(c)).precision==null&&(c.trim=!0),c=AAe(c)),o===1/0)return c;const d=Math.max(1,n*o/t.ticks().length);return h=>{let m=h/i(Math.round(a(h)));return m*nr(vft(r(),{floor:o=>i(Math.floor(a(o))),ceil:o=>i(Math.ceil(a(o)))})),t}function bft(){const s=MAe(c0e()).domain([1,10]);return s.copy=()=>Az(s,bft()).base(s.base()),ov.apply(s,arguments),s}function dqe(s){return function(t){return Math.sign(t)*Math.log1p(Math.abs(t/s))}}function uqe(s){return function(t){return Math.sign(t)*Math.expm1(Math.abs(t))*s}}function IAe(s){var t=1,r=s(dqe(t),uqe(t));return r.constant=function(n){return arguments.length?s(dqe(t=+n),uqe(t)):t},s4(r)}function _ft(){var s=IAe(c0e());return s.copy=function(){return Az(s,_ft()).constant(s.constant())},ov.apply(s,arguments)}function hqe(s){return function(t){return t<0?-Math.pow(-t,s):Math.pow(t,s)}}function eNs(s){return s<0?-Math.sqrt(-s):Math.sqrt(s)}function tNs(s){return s<0?-s*s:s*s}function PAe(s){var t=s(yg,yg),r=1;function n(){return r===1?s(yg,yg):r===.5?s(eNs,tNs):s(hqe(r),hqe(1/r))}return t.exponent=function(a){return arguments.length?(r=+a,n()):r},s4(t)}function LAe(){var s=PAe(c0e());return s.copy=function(){return Az(s,LAe()).exponent(s.exponent())},ov.apply(s,arguments),s}function sNs(){return LAe.apply(null,arguments).exponent(.5)}function mqe(s){return Math.sign(s)*s*s}function rNs(s){return Math.sign(s)*Math.sqrt(Math.abs(s))}function wft(){var s=TAe(),t=[0,1],r=!1,n;function a(i){var l=rNs(s(i));return isNaN(l)?n:r?Math.round(l):l}return a.invert=function(i){return s.invert(mqe(i))},a.domain=function(i){return arguments.length?(s.domain(i),a):s.domain()},a.range=function(i){return arguments.length?(s.range((t=Array.from(i,jfe)).map(mqe)),a):t.slice()},a.rangeRound=function(i){return a.range(i).round(!0)},a.round=function(i){return arguments.length?(r=!!i,a):r},a.clamp=function(i){return arguments.length?(s.clamp(i),a):s.clamp()},a.unknown=function(i){return arguments.length?(n=i,a):n},a.copy=function(){return wft(s.domain(),t).round(r).clamp(s.clamp()).unknown(n)},ov.apply(a,arguments),s4(a)}function jft(){var s=[],t=[],r=[],n;function a(){var l=0,o=Math.max(1,t.length);for(r=new Array(o-1);++l0?r[o-1]:s[0],o=r?[n[r-1],t]:[n[d-1],n[d]]},l.unknown=function(c){return arguments.length&&(i=c),l},l.thresholds=function(){return n.slice()},l.copy=function(){return Nft().domain([s,t]).range(a).unknown(i)},ov.apply(s4(l),arguments)}function kft(){var s=[.5],t=[0,1],r,n=1;function a(i){return i!=null&&i<=i?t[Tz(s,i,0,n)]:r}return a.domain=function(i){return arguments.length?(s=Array.from(i),n=Math.min(s.length,t.length-1),a):s.slice()},a.range=function(i){return arguments.length?(t=Array.from(i),n=Math.min(s.length,t.length-1),a):t.slice()},a.invertExtent=function(i){var l=t.indexOf(i);return[s[l-1],s[l]]},a.unknown=function(i){return arguments.length?(r=i,a):r},a.copy=function(){return kft().domain(s).range(t).unknown(r)},ov.apply(a,arguments)}const Y_e=new Date,Z_e=new Date;function Sm(s,t,r,n){function a(i){return s(i=arguments.length===0?new Date:new Date(+i)),i}return a.floor=i=>(s(i=new Date(+i)),i),a.ceil=i=>(s(i=new Date(i-1)),t(i,1),s(i),i),a.round=i=>{const l=a(i),o=a.ceil(i);return i-l(t(i=new Date(+i),l==null?1:Math.floor(l)),i),a.range=(i,l,o)=>{const c=[];if(i=a.ceil(i),o=o==null?1:Math.floor(o),!(i0))return c;let d;do c.push(d=new Date(+i)),t(i,o),s(i);while(dSm(l=>{if(l>=l)for(;s(l),!i(l);)l.setTime(l-1)},(l,o)=>{if(l>=l)if(o<0)for(;++o<=0;)for(;t(l,-1),!i(l););else for(;--o>=0;)for(;t(l,1),!i(l););}),r&&(a.count=(i,l)=>(Y_e.setTime(+i),Z_e.setTime(+l),s(Y_e),s(Z_e),Math.floor(r(Y_e,Z_e))),a.every=i=>(i=Math.floor(i),!isFinite(i)||!(i>0)?null:i>1?a.filter(n?l=>n(l)%i===0:l=>a.count(0,l)%i===0):a)),a}const Sfe=Sm(()=>{},(s,t)=>{s.setTime(+s+t)},(s,t)=>t-s);Sfe.every=s=>(s=Math.floor(s),!isFinite(s)||!(s>0)?null:s>1?Sm(t=>{t.setTime(Math.floor(t/s)*s)},(t,r)=>{t.setTime(+t+r*s)},(t,r)=>(r-t)/s):Sfe);Sfe.range;const L2=1e3,By=L2*60,D2=By*60,lj=D2*24,DAe=lj*7,fqe=lj*30,X_e=lj*365,WT=Sm(s=>{s.setTime(s-s.getMilliseconds())},(s,t)=>{s.setTime(+s+t*L2)},(s,t)=>(t-s)/L2,s=>s.getUTCSeconds());WT.range;const RAe=Sm(s=>{s.setTime(s-s.getMilliseconds()-s.getSeconds()*L2)},(s,t)=>{s.setTime(+s+t*By)},(s,t)=>(t-s)/By,s=>s.getMinutes());RAe.range;const OAe=Sm(s=>{s.setUTCSeconds(0,0)},(s,t)=>{s.setTime(+s+t*By)},(s,t)=>(t-s)/By,s=>s.getUTCMinutes());OAe.range;const FAe=Sm(s=>{s.setTime(s-s.getMilliseconds()-s.getSeconds()*L2-s.getMinutes()*By)},(s,t)=>{s.setTime(+s+t*D2)},(s,t)=>(t-s)/D2,s=>s.getHours());FAe.range;const BAe=Sm(s=>{s.setUTCMinutes(0,0,0)},(s,t)=>{s.setTime(+s+t*D2)},(s,t)=>(t-s)/D2,s=>s.getUTCHours());BAe.range;const Mz=Sm(s=>s.setHours(0,0,0,0),(s,t)=>s.setDate(s.getDate()+t),(s,t)=>(t-s-(t.getTimezoneOffset()-s.getTimezoneOffset())*By)/lj,s=>s.getDate()-1);Mz.range;const d0e=Sm(s=>{s.setUTCHours(0,0,0,0)},(s,t)=>{s.setUTCDate(s.getUTCDate()+t)},(s,t)=>(t-s)/lj,s=>s.getUTCDate()-1);d0e.range;const Sft=Sm(s=>{s.setUTCHours(0,0,0,0)},(s,t)=>{s.setUTCDate(s.getUTCDate()+t)},(s,t)=>(t-s)/lj,s=>Math.floor(s/lj));Sft.range;function JA(s){return Sm(t=>{t.setDate(t.getDate()-(t.getDay()+7-s)%7),t.setHours(0,0,0,0)},(t,r)=>{t.setDate(t.getDate()+r*7)},(t,r)=>(r-t-(r.getTimezoneOffset()-t.getTimezoneOffset())*By)/DAe)}const u0e=JA(0),Cfe=JA(1),nNs=JA(2),aNs=JA(3),_L=JA(4),iNs=JA(5),oNs=JA(6);u0e.range;Cfe.range;nNs.range;aNs.range;_L.range;iNs.range;oNs.range;function eM(s){return Sm(t=>{t.setUTCDate(t.getUTCDate()-(t.getUTCDay()+7-s)%7),t.setUTCHours(0,0,0,0)},(t,r)=>{t.setUTCDate(t.getUTCDate()+r*7)},(t,r)=>(r-t)/DAe)}const h0e=eM(0),Tfe=eM(1),lNs=eM(2),cNs=eM(3),wL=eM(4),dNs=eM(5),uNs=eM(6);h0e.range;Tfe.range;lNs.range;cNs.range;wL.range;dNs.range;uNs.range;const zAe=Sm(s=>{s.setDate(1),s.setHours(0,0,0,0)},(s,t)=>{s.setMonth(s.getMonth()+t)},(s,t)=>t.getMonth()-s.getMonth()+(t.getFullYear()-s.getFullYear())*12,s=>s.getMonth());zAe.range;const $Ae=Sm(s=>{s.setUTCDate(1),s.setUTCHours(0,0,0,0)},(s,t)=>{s.setUTCMonth(s.getUTCMonth()+t)},(s,t)=>t.getUTCMonth()-s.getUTCMonth()+(t.getUTCFullYear()-s.getUTCFullYear())*12,s=>s.getUTCMonth());$Ae.range;const cj=Sm(s=>{s.setMonth(0,1),s.setHours(0,0,0,0)},(s,t)=>{s.setFullYear(s.getFullYear()+t)},(s,t)=>t.getFullYear()-s.getFullYear(),s=>s.getFullYear());cj.every=s=>!isFinite(s=Math.floor(s))||!(s>0)?null:Sm(t=>{t.setFullYear(Math.floor(t.getFullYear()/s)*s),t.setMonth(0,1),t.setHours(0,0,0,0)},(t,r)=>{t.setFullYear(t.getFullYear()+r*s)});cj.range;const dj=Sm(s=>{s.setUTCMonth(0,1),s.setUTCHours(0,0,0,0)},(s,t)=>{s.setUTCFullYear(s.getUTCFullYear()+t)},(s,t)=>t.getUTCFullYear()-s.getUTCFullYear(),s=>s.getUTCFullYear());dj.every=s=>!isFinite(s=Math.floor(s))||!(s>0)?null:Sm(t=>{t.setUTCFullYear(Math.floor(t.getUTCFullYear()/s)*s),t.setUTCMonth(0,1),t.setUTCHours(0,0,0,0)},(t,r)=>{t.setUTCFullYear(t.getUTCFullYear()+r*s)});dj.range;function Cft(s,t,r,n,a,i){const l=[[WT,1,L2],[WT,5,5*L2],[WT,15,15*L2],[WT,30,30*L2],[i,1,By],[i,5,5*By],[i,15,15*By],[i,30,30*By],[a,1,D2],[a,3,3*D2],[a,6,6*D2],[a,12,12*D2],[n,1,lj],[n,2,2*lj],[r,1,DAe],[t,1,fqe],[t,3,3*fqe],[s,1,X_e]];function o(d,h,m){const p=hb).right(l,p);if(x===l.length)return s.every(jSe(d/X_e,h/X_e,m));if(x===0)return Sfe.every(Math.max(jSe(d,h,m),1));const[y,_]=l[p/l[x-1][2]53)return null;"w"in pe||(pe.w=1),"Z"in pe?(ge=J_e(GR(pe.y,0,1)),ct=ge.getUTCDay(),ge=ct>4||ct===0?Tfe.ceil(ge):Tfe(ge),ge=d0e.offset(ge,(pe.V-1)*7),pe.y=ge.getUTCFullYear(),pe.m=ge.getUTCMonth(),pe.d=ge.getUTCDate()+(pe.w+6)%7):(ge=Q_e(GR(pe.y,0,1)),ct=ge.getDay(),ge=ct>4||ct===0?Cfe.ceil(ge):Cfe(ge),ge=Mz.offset(ge,(pe.V-1)*7),pe.y=ge.getFullYear(),pe.m=ge.getMonth(),pe.d=ge.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),ct="Z"in pe?J_e(GR(pe.y,0,1)).getUTCDay():Q_e(GR(pe.y,0,1)).getDay(),pe.m=0,pe.d="W"in pe?(pe.w+6)%7+pe.W*7-(ct+5)%7:pe.w+pe.U*7-(ct+6)%7);return"Z"in pe?(pe.H+=pe.Z/100|0,pe.M+=pe.Z%100,J_e(pe)):Q_e(pe)}}function z(Pe,Ie,De,pe){for(var tt=0,ge=Ie.length,ct=De.length,Ue,et;tt=ct)return-1;if(Ue=Ie.charCodeAt(tt++),Ue===37){if(Ue=Ie.charAt(tt++),et=A[Ue in pqe?Ie.charAt(tt++):Ue],!et||(pe=et(Pe,De,pe))<0)return-1}else if(Ue!=De.charCodeAt(pe++))return-1}return pe}function O(Pe,Ie,De){var pe=d.exec(Ie.slice(De));return pe?(Pe.p=h.get(pe[0].toLowerCase()),De+pe[0].length):-1}function $(Pe,Ie,De){var pe=x.exec(Ie.slice(De));return pe?(Pe.w=y.get(pe[0].toLowerCase()),De+pe[0].length):-1}function ee(Pe,Ie,De){var pe=m.exec(Ie.slice(De));return pe?(Pe.w=p.get(pe[0].toLowerCase()),De+pe[0].length):-1}function Z(Pe,Ie,De){var pe=j.exec(Ie.slice(De));return pe?(Pe.m=k.get(pe[0].toLowerCase()),De+pe[0].length):-1}function J(Pe,Ie,De){var pe=_.exec(Ie.slice(De));return pe?(Pe.m=b.get(pe[0].toLowerCase()),De+pe[0].length):-1}function K(Pe,Ie,De){return z(Pe,t,Ie,De)}function re(Pe,Ie,De){return z(Pe,r,Ie,De)}function ie(Pe,Ie,De){return z(Pe,n,Ie,De)}function ce(Pe){return l[Pe.getDay()]}function ne(Pe){return i[Pe.getDay()]}function le(Pe){return c[Pe.getMonth()]}function be(Pe){return o[Pe.getMonth()]}function fe(Pe){return a[+(Pe.getHours()>=12)]}function je(Pe){return 1+~~(Pe.getMonth()/3)}function ve(Pe){return l[Pe.getUTCDay()]}function We(Pe){return i[Pe.getUTCDay()]}function Ve(Pe){return c[Pe.getUTCMonth()]}function Le(Pe){return o[Pe.getUTCMonth()]}function Me(Pe){return a[+(Pe.getUTCHours()>=12)]}function ze(Pe){return 1+~~(Pe.getUTCMonth()/3)}return{format:function(Pe){var Ie=D(Pe+="",T);return Ie.toString=function(){return Pe},Ie},parse:function(Pe){var Ie=R(Pe+="",!1);return Ie.toString=function(){return Pe},Ie},utcFormat:function(Pe){var Ie=D(Pe+="",E);return Ie.toString=function(){return Pe},Ie},utcParse:function(Pe){var Ie=R(Pe+="",!0);return Ie.toString=function(){return Pe},Ie}}}var pqe={"-":"",_:" ",0:"0"},lf=/^\s*\d+/,xNs=/^%/,yNs=/[\\^$*+?|[\]().{}]/g;function Gl(s,t,r){var n=s<0?"-":"",a=(n?-s:s)+"",i=a.length;return n+(i[t.toLowerCase(),r]))}function bNs(s,t,r){var n=lf.exec(t.slice(r,r+1));return n?(s.w=+n[0],r+n[0].length):-1}function _Ns(s,t,r){var n=lf.exec(t.slice(r,r+1));return n?(s.u=+n[0],r+n[0].length):-1}function wNs(s,t,r){var n=lf.exec(t.slice(r,r+2));return n?(s.U=+n[0],r+n[0].length):-1}function jNs(s,t,r){var n=lf.exec(t.slice(r,r+2));return n?(s.V=+n[0],r+n[0].length):-1}function NNs(s,t,r){var n=lf.exec(t.slice(r,r+2));return n?(s.W=+n[0],r+n[0].length):-1}function gqe(s,t,r){var n=lf.exec(t.slice(r,r+4));return n?(s.y=+n[0],r+n[0].length):-1}function xqe(s,t,r){var n=lf.exec(t.slice(r,r+2));return n?(s.y=+n[0]+(+n[0]>68?1900:2e3),r+n[0].length):-1}function kNs(s,t,r){var n=/^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(t.slice(r,r+6));return n?(s.Z=n[1]?0:-(n[2]+(n[3]||"00")),r+n[0].length):-1}function SNs(s,t,r){var n=lf.exec(t.slice(r,r+1));return n?(s.q=n[0]*3-3,r+n[0].length):-1}function CNs(s,t,r){var n=lf.exec(t.slice(r,r+2));return n?(s.m=n[0]-1,r+n[0].length):-1}function yqe(s,t,r){var n=lf.exec(t.slice(r,r+2));return n?(s.d=+n[0],r+n[0].length):-1}function TNs(s,t,r){var n=lf.exec(t.slice(r,r+3));return n?(s.m=0,s.d=+n[0],r+n[0].length):-1}function vqe(s,t,r){var n=lf.exec(t.slice(r,r+2));return n?(s.H=+n[0],r+n[0].length):-1}function ENs(s,t,r){var n=lf.exec(t.slice(r,r+2));return n?(s.M=+n[0],r+n[0].length):-1}function ANs(s,t,r){var n=lf.exec(t.slice(r,r+2));return n?(s.S=+n[0],r+n[0].length):-1}function MNs(s,t,r){var n=lf.exec(t.slice(r,r+3));return n?(s.L=+n[0],r+n[0].length):-1}function INs(s,t,r){var n=lf.exec(t.slice(r,r+6));return n?(s.L=Math.floor(n[0]/1e3),r+n[0].length):-1}function PNs(s,t,r){var n=xNs.exec(t.slice(r,r+1));return n?r+n[0].length:-1}function LNs(s,t,r){var n=lf.exec(t.slice(r));return n?(s.Q=+n[0],r+n[0].length):-1}function DNs(s,t,r){var n=lf.exec(t.slice(r));return n?(s.s=+n[0],r+n[0].length):-1}function bqe(s,t){return Gl(s.getDate(),t,2)}function RNs(s,t){return Gl(s.getHours(),t,2)}function ONs(s,t){return Gl(s.getHours()%12||12,t,2)}function FNs(s,t){return Gl(1+Mz.count(cj(s),s),t,3)}function Tft(s,t){return Gl(s.getMilliseconds(),t,3)}function BNs(s,t){return Tft(s,t)+"000"}function zNs(s,t){return Gl(s.getMonth()+1,t,2)}function $Ns(s,t){return Gl(s.getMinutes(),t,2)}function UNs(s,t){return Gl(s.getSeconds(),t,2)}function qNs(s){var t=s.getDay();return t===0?7:t}function VNs(s,t){return Gl(u0e.count(cj(s)-1,s),t,2)}function Eft(s){var t=s.getDay();return t>=4||t===0?_L(s):_L.ceil(s)}function HNs(s,t){return s=Eft(s),Gl(_L.count(cj(s),s)+(cj(s).getDay()===4),t,2)}function GNs(s){return s.getDay()}function WNs(s,t){return Gl(Cfe.count(cj(s)-1,s),t,2)}function KNs(s,t){return Gl(s.getFullYear()%100,t,2)}function YNs(s,t){return s=Eft(s),Gl(s.getFullYear()%100,t,2)}function ZNs(s,t){return Gl(s.getFullYear()%1e4,t,4)}function XNs(s,t){var r=s.getDay();return s=r>=4||r===0?_L(s):_L.ceil(s),Gl(s.getFullYear()%1e4,t,4)}function QNs(s){var t=s.getTimezoneOffset();return(t>0?"-":(t*=-1,"+"))+Gl(t/60|0,"0",2)+Gl(t%60,"0",2)}function _qe(s,t){return Gl(s.getUTCDate(),t,2)}function JNs(s,t){return Gl(s.getUTCHours(),t,2)}function eks(s,t){return Gl(s.getUTCHours()%12||12,t,2)}function tks(s,t){return Gl(1+d0e.count(dj(s),s),t,3)}function Aft(s,t){return Gl(s.getUTCMilliseconds(),t,3)}function sks(s,t){return Aft(s,t)+"000"}function rks(s,t){return Gl(s.getUTCMonth()+1,t,2)}function nks(s,t){return Gl(s.getUTCMinutes(),t,2)}function aks(s,t){return Gl(s.getUTCSeconds(),t,2)}function iks(s){var t=s.getUTCDay();return t===0?7:t}function oks(s,t){return Gl(h0e.count(dj(s)-1,s),t,2)}function Mft(s){var t=s.getUTCDay();return t>=4||t===0?wL(s):wL.ceil(s)}function lks(s,t){return s=Mft(s),Gl(wL.count(dj(s),s)+(dj(s).getUTCDay()===4),t,2)}function cks(s){return s.getUTCDay()}function dks(s,t){return Gl(Tfe.count(dj(s)-1,s),t,2)}function uks(s,t){return Gl(s.getUTCFullYear()%100,t,2)}function hks(s,t){return s=Mft(s),Gl(s.getUTCFullYear()%100,t,2)}function mks(s,t){return Gl(s.getUTCFullYear()%1e4,t,4)}function fks(s,t){var r=s.getUTCDay();return s=r>=4||r===0?wL(s):wL.ceil(s),Gl(s.getUTCFullYear()%1e4,t,4)}function pks(){return"+0000"}function wqe(){return"%"}function jqe(s){return+s}function Nqe(s){return Math.floor(+s/1e3)}var S6,Ift,Pft;gks({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 gks(s){return S6=gNs(s),Ift=S6.format,S6.parse,Pft=S6.utcFormat,S6.utcParse,S6}function xks(s){return new Date(s)}function yks(s){return s instanceof Date?+s:+new Date(+s)}function UAe(s,t,r,n,a,i,l,o,c,d){var h=TAe(),m=h.invert,p=h.domain,x=d(".%L"),y=d(":%S"),_=d("%I:%M"),b=d("%I %p"),j=d("%a %d"),k=d("%b %d"),T=d("%B"),E=d("%Y");function A(D){return(c(D)t(a/(s.length-1)))},r.quantiles=function(n){return Array.from({length:n+1},(a,i)=>ojs(s,i/n))},r.copy=function(){return Oft(t).domain(s)},Sj.apply(r,arguments)}function f0e(){var s=0,t=.5,r=1,n=1,a,i,l,o,c,d=yg,h,m=!1,p;function x(_){return isNaN(_=+_)?p:(_=.5+((_=+h(_))-i)*(n*_t}var $ft=kks,Sks=p0e,Cks=$ft,Tks=O8;function Eks(s){return s&&s.length?Sks(s,Tks,Cks):void 0}var Aks=Eks;const g0e=ol(Aks);function Mks(s,t){return ss.e^i.s<0?1:-1;for(n=i.d.length,a=s.d.length,t=0,r=ns.d[t]^i.s<0?1:-1;return n===a?0:n>a^i.s<0?1:-1};Wa.decimalPlaces=Wa.dp=function(){var s=this,t=s.d.length-1,r=(t-s.e)*Nd;if(t=s.d[t],t)for(;t%10==0;t/=10)r--;return r<0?0:r};Wa.dividedBy=Wa.div=function(s){return X2(this,new this.constructor(s))};Wa.dividedToIntegerBy=Wa.idiv=function(s){var t=this,r=t.constructor;return $c(X2(t,new r(s),0,1),r.precision)};Wa.equals=Wa.eq=function(s){return!this.cmp(s)};Wa.exponent=function(){return Bh(this)};Wa.greaterThan=Wa.gt=function(s){return this.cmp(s)>0};Wa.greaterThanOrEqualTo=Wa.gte=function(s){return this.cmp(s)>=0};Wa.isInteger=Wa.isint=function(){return this.e>this.d.length-2};Wa.isNegative=Wa.isneg=function(){return this.s<0};Wa.isPositive=Wa.ispos=function(){return this.s>0};Wa.isZero=function(){return this.s===0};Wa.lessThan=Wa.lt=function(s){return this.cmp(s)<0};Wa.lessThanOrEqualTo=Wa.lte=function(s){return this.cmp(s)<1};Wa.logarithm=Wa.log=function(s){var t,r=this,n=r.constructor,a=n.precision,i=a+5;if(s===void 0)s=new n(10);else if(s=new n(s),s.s<1||s.eq(i0))throw Error(ev+"NaN");if(r.s<1)throw Error(ev+(r.s?"NaN":"-Infinity"));return r.eq(i0)?new n(0):(Yd=!1,t=X2(G9(r,i),G9(s,i),i),Yd=!0,$c(t,a))};Wa.minus=Wa.sub=function(s){var t=this;return s=new t.constructor(s),t.s==s.s?Gft(t,s):Vft(t,(s.s=-s.s,s))};Wa.modulo=Wa.mod=function(s){var t,r=this,n=r.constructor,a=n.precision;if(s=new n(s),!s.s)throw Error(ev+"NaN");return r.s?(Yd=!1,t=X2(r,s,0,1).times(s),Yd=!0,r.minus(t)):$c(new n(r),a)};Wa.naturalExponential=Wa.exp=function(){return Hft(this)};Wa.naturalLogarithm=Wa.ln=function(){return G9(this)};Wa.negated=Wa.neg=function(){var s=new this.constructor(this);return s.s=-s.s||0,s};Wa.plus=Wa.add=function(s){var t=this;return s=new t.constructor(s),t.s==s.s?Vft(t,s):Gft(t,(s.s=-s.s,s))};Wa.precision=Wa.sd=function(s){var t,r,n,a=this;if(s!==void 0&&s!==!!s&&s!==1&&s!==0)throw Error(YE+s);if(t=Bh(a)+1,n=a.d.length-1,r=n*Nd+1,n=a.d[n],n){for(;n%10==0;n/=10)r--;for(n=a.d[0];n>=10;n/=10)r++}return s&&t>r?t:r};Wa.squareRoot=Wa.sqrt=function(){var s,t,r,n,a,i,l,o=this,c=o.constructor;if(o.s<1){if(!o.s)return new c(0);throw Error(ev+"NaN")}for(s=Bh(o),Yd=!1,a=Math.sqrt(+o),a==0||a==1/0?(t=n_(o.d),(t.length+s)%2==0&&(t+="0"),a=Math.sqrt(t),s=z8((s+1)/2)-(s<0||s%2),a==1/0?t="5e"+s:(t=a.toExponential(),t=t.slice(0,t.indexOf("e")+1)+s),n=new c(t)):n=new c(a.toString()),r=c.precision,a=l=r+3;;)if(i=n,n=i.plus(X2(o,i,l+2)).times(.5),n_(i.d).slice(0,l)===(t=n_(n.d)).slice(0,l)){if(t=t.slice(l-3,l+1),a==l&&t=="4999"){if($c(i,r+1,0),i.times(i).eq(o)){n=i;break}}else if(t!="9999")break;l+=4}return Yd=!0,$c(n,r)};Wa.times=Wa.mul=function(s){var t,r,n,a,i,l,o,c,d,h=this,m=h.constructor,p=h.d,x=(s=new m(s)).d;if(!h.s||!s.s)return new m(0);for(s.s*=h.s,r=h.e+s.e,c=p.length,d=x.length,c=0;){for(t=0,a=c+n;a>n;)o=i[a]+x[n]*p[a-n-1]+t,i[a--]=o%Wm|0,t=o/Wm|0;i[a]=(i[a]+t)%Wm|0}for(;!i[--l];)i.pop();return t?++r:i.shift(),s.d=i,s.e=r,Yd?$c(s,m.precision):s};Wa.toDecimalPlaces=Wa.todp=function(s,t){var r=this,n=r.constructor;return r=new n(r),s===void 0?r:(R_(s,0,B8),t===void 0?t=n.rounding:R_(t,0,8),$c(r,s+Bh(r)+1,t))};Wa.toExponential=function(s,t){var r,n=this,a=n.constructor;return s===void 0?r=TA(n,!0):(R_(s,0,B8),t===void 0?t=a.rounding:R_(t,0,8),n=$c(new a(n),s+1,t),r=TA(n,!0,s+1)),r};Wa.toFixed=function(s,t){var r,n,a=this,i=a.constructor;return s===void 0?TA(a):(R_(s,0,B8),t===void 0?t=i.rounding:R_(t,0,8),n=$c(new i(a),s+Bh(a)+1,t),r=TA(n.abs(),!1,s+Bh(n)+1),a.isneg()&&!a.isZero()?"-"+r:r)};Wa.toInteger=Wa.toint=function(){var s=this,t=s.constructor;return $c(new t(s),Bh(s)+1,t.rounding)};Wa.toNumber=function(){return+this};Wa.toPower=Wa.pow=function(s){var t,r,n,a,i,l,o=this,c=o.constructor,d=12,h=+(s=new c(s));if(!s.s)return new c(i0);if(o=new c(o),!o.s){if(s.s<1)throw Error(ev+"Infinity");return o}if(o.eq(i0))return o;if(n=c.precision,s.eq(i0))return $c(o,n);if(t=s.e,r=s.d.length-1,l=t>=r,i=o.s,l){if((r=h<0?-h:h)<=qft){for(a=new c(i0),t=Math.ceil(n/Nd+4),Yd=!1;r%2&&(a=a.times(o),Cqe(a.d,t)),r=z8(r/2),r!==0;)o=o.times(o),Cqe(o.d,t);return Yd=!0,s.s<0?new c(i0).div(a):$c(a,n)}}else if(i<0)throw Error(ev+"NaN");return i=i<0&&s.d[Math.max(t,r)]&1?-1:1,o.s=1,Yd=!1,a=s.times(G9(o,n+d)),Yd=!0,a=Hft(a),a.s=i,a};Wa.toPrecision=function(s,t){var r,n,a=this,i=a.constructor;return s===void 0?(r=Bh(a),n=TA(a,r<=i.toExpNeg||r>=i.toExpPos)):(R_(s,1,B8),t===void 0?t=i.rounding:R_(t,0,8),a=$c(new i(a),s,t),r=Bh(a),n=TA(a,s<=r||r<=i.toExpNeg,s)),n};Wa.toSignificantDigits=Wa.tosd=function(s,t){var r=this,n=r.constructor;return s===void 0?(s=n.precision,t=n.rounding):(R_(s,1,B8),t===void 0?t=n.rounding:R_(t,0,8)),$c(new n(r),s,t)};Wa.toString=Wa.valueOf=Wa.val=Wa.toJSON=Wa[Symbol.for("nodejs.util.inspect.custom")]=function(){var s=this,t=Bh(s),r=s.constructor;return TA(s,t<=r.toExpNeg||t>=r.toExpPos)};function Vft(s,t){var r,n,a,i,l,o,c,d,h=s.constructor,m=h.precision;if(!s.s||!t.s)return t.s||(t=new h(s)),Yd?$c(t,m):t;if(c=s.d,d=t.d,l=s.e,a=t.e,c=c.slice(),i=l-a,i){for(i<0?(n=c,i=-i,o=d.length):(n=d,a=l,o=c.length),l=Math.ceil(m/Nd),o=l>o?l+1:o+1,i>o&&(i=o,n.length=1),n.reverse();i--;)n.push(0);n.reverse()}for(o=c.length,i=d.length,o-i<0&&(i=o,n=d,d=c,c=n),r=0;i;)r=(c[--i]=c[i]+d[i]+r)/Wm|0,c[i]%=Wm;for(r&&(c.unshift(r),++a),o=c.length;c[--o]==0;)c.pop();return t.d=c,t.e=a,Yd?$c(t,m):t}function R_(s,t,r){if(s!==~~s||sr)throw Error(YE+s)}function n_(s){var t,r,n,a=s.length-1,i="",l=s[0];if(a>0){for(i+=l,t=1;tl?1:-1;else for(o=c=0;oa[o]?1:-1;break}return c}function r(n,a,i){for(var l=0;i--;)n[i]-=l,l=n[i]1;)n.shift()}return function(n,a,i,l){var o,c,d,h,m,p,x,y,_,b,j,k,T,E,A,D,R,z,O=n.constructor,$=n.s==a.s?1:-1,ee=n.d,Z=a.d;if(!n.s)return new O(n);if(!a.s)throw Error(ev+"Division by zero");for(c=n.e-a.e,R=Z.length,A=ee.length,x=new O($),y=x.d=[],d=0;Z[d]==(ee[d]||0);)++d;if(Z[d]>(ee[d]||0)&&--c,i==null?k=i=O.precision:l?k=i+(Bh(n)-Bh(a))+1:k=i,k<0)return new O(0);if(k=k/Nd+2|0,d=0,R==1)for(h=0,Z=Z[0],k++;(d1&&(Z=s(Z,h),ee=s(ee,h),R=Z.length,A=ee.length),E=R,_=ee.slice(0,R),b=_.length;b=Wm/2&&++D;do h=0,o=t(Z,_,R,b),o<0?(j=_[0],R!=b&&(j=j*Wm+(_[1]||0)),h=j/D|0,h>1?(h>=Wm&&(h=Wm-1),m=s(Z,h),p=m.length,b=_.length,o=t(m,_,p,b),o==1&&(h--,r(m,R16)throw Error(HAe+Bh(s));if(!s.s)return new h(i0);for(t==null?(Yd=!1,o=m):o=t,l=new h(.03125);s.abs().gte(.1);)s=s.times(l),d+=5;for(n=Math.log(kT(2,d))/Math.LN10*2+5|0,o+=n,r=a=i=new h(i0),h.precision=o;;){if(a=$c(a.times(s),o),r=r.times(++c),l=i.plus(X2(a,r,o)),n_(l.d).slice(0,o)===n_(i.d).slice(0,o)){for(;d--;)i=$c(i.times(i),o);return h.precision=m,t==null?(Yd=!0,$c(i,m)):i}i=l}}function Bh(s){for(var t=s.e*Nd,r=s.d[0];r>=10;r/=10)t++;return t}function ewe(s,t,r){if(t>s.LN10.sd())throw Yd=!0,r&&(s.precision=r),Error(ev+"LN10 precision limit exceeded");return $c(new s(s.LN10),t)}function KN(s){for(var t="";s--;)t+="0";return t}function G9(s,t){var r,n,a,i,l,o,c,d,h,m=1,p=10,x=s,y=x.d,_=x.constructor,b=_.precision;if(x.s<1)throw Error(ev+(x.s?"NaN":"-Infinity"));if(x.eq(i0))return new _(0);if(t==null?(Yd=!1,d=b):d=t,x.eq(10))return t==null&&(Yd=!0),ewe(_,d);if(d+=p,_.precision=d,r=n_(y),n=r.charAt(0),i=Bh(x),Math.abs(i)<15e14){for(;n<7&&n!=1||n==1&&r.charAt(1)>3;)x=x.times(s),r=n_(x.d),n=r.charAt(0),m++;i=Bh(x),n>1?(x=new _("0."+r),i++):x=new _(n+"."+r.slice(1))}else return c=ewe(_,d+2,b).times(i+""),x=G9(new _(n+"."+r.slice(1)),d-p).plus(c),_.precision=b,t==null?(Yd=!0,$c(x,b)):x;for(o=l=x=X2(x.minus(i0),x.plus(i0),d),h=$c(x.times(x),d),a=3;;){if(l=$c(l.times(h),d),c=o.plus(X2(l,new _(a),d)),n_(c.d).slice(0,d)===n_(o.d).slice(0,d))return o=o.times(2),i!==0&&(o=o.plus(ewe(_,d+2,b).times(i+""))),o=X2(o,new _(m),d),_.precision=b,t==null?(Yd=!0,$c(o,b)):o;o=c,a+=2}}function Sqe(s,t){var r,n,a;for((r=t.indexOf("."))>-1&&(t=t.replace(".","")),(n=t.search(/e/i))>0?(r<0&&(r=n),r+=+t.slice(n+1),t=t.substring(0,n)):r<0&&(r=t.length),n=0;t.charCodeAt(n)===48;)++n;for(a=t.length;t.charCodeAt(a-1)===48;)--a;if(t=t.slice(n,a),t){if(a-=n,r=r-n-1,s.e=z8(r/Nd),s.d=[],n=(r+1)%Nd,r<0&&(n+=Nd),nEfe||s.e<-Efe))throw Error(HAe+r)}else s.s=0,s.e=0,s.d=[0];return s}function $c(s,t,r){var n,a,i,l,o,c,d,h,m=s.d;for(l=1,i=m[0];i>=10;i/=10)l++;if(n=t-l,n<0)n+=Nd,a=t,d=m[h=0];else{if(h=Math.ceil((n+1)/Nd),i=m.length,h>=i)return s;for(d=i=m[h],l=1;i>=10;i/=10)l++;n%=Nd,a=n-Nd+l}if(r!==void 0&&(i=kT(10,l-a-1),o=d/i%10|0,c=t<0||m[h+1]!==void 0||d%i,c=r<4?(o||c)&&(r==0||r==(s.s<0?3:2)):o>5||o==5&&(r==4||c||r==6&&(n>0?a>0?d/kT(10,l-a):0:m[h-1])%10&1||r==(s.s<0?8:7))),t<1||!m[0])return c?(i=Bh(s),m.length=1,t=t-i-1,m[0]=kT(10,(Nd-t%Nd)%Nd),s.e=z8(-t/Nd)||0):(m.length=1,m[0]=s.e=s.s=0),s;if(n==0?(m.length=h,i=1,h--):(m.length=h+1,i=kT(10,Nd-n),m[h]=a>0?(d/kT(10,l-a)%kT(10,a)|0)*i:0),c)for(;;)if(h==0){(m[0]+=i)==Wm&&(m[0]=1,++s.e);break}else{if(m[h]+=i,m[h]!=Wm)break;m[h--]=0,i=1}for(n=m.length;m[--n]===0;)m.pop();if(Yd&&(s.e>Efe||s.e<-Efe))throw Error(HAe+Bh(s));return s}function Gft(s,t){var r,n,a,i,l,o,c,d,h,m,p=s.constructor,x=p.precision;if(!s.s||!t.s)return t.s?t.s=-t.s:t=new p(s),Yd?$c(t,x):t;if(c=s.d,m=t.d,n=t.e,d=s.e,c=c.slice(),l=d-n,l){for(h=l<0,h?(r=c,l=-l,o=m.length):(r=m,n=d,o=c.length),a=Math.max(Math.ceil(x/Nd),o)+2,l>a&&(l=a,r.length=1),r.reverse(),a=l;a--;)r.push(0);r.reverse()}else{for(a=c.length,o=m.length,h=a0;--a)c[o++]=0;for(a=m.length;a>l;){if(c[--a]0?i=i.charAt(0)+"."+i.slice(1)+KN(n):l>1&&(i=i.charAt(0)+"."+i.slice(1)),i=i+(a<0?"e":"e+")+a):a<0?(i="0."+KN(-a-1)+i,r&&(n=r-l)>0&&(i+=KN(n))):a>=l?(i+=KN(a+1-l),r&&(n=r-a-1)>0&&(i=i+"."+KN(n))):((n=a+1)0&&(a+1===l&&(i+="."),i+=KN(n))),s.s<0?"-"+i:i}function Cqe(s,t){if(s.length>t)return s.length=t,!0}function Wft(s){var t,r,n;function a(i){var l=this;if(!(l instanceof a))return new a(i);if(l.constructor=a,i instanceof a){l.s=i.s,l.e=i.e,l.d=(i=i.d)?i.slice():i;return}if(typeof i=="number"){if(i*0!==0)throw Error(YE+i);if(i>0)l.s=1;else if(i<0)i=-i,l.s=-1;else{l.s=0,l.e=0,l.d=[0];return}if(i===~~i&&i<1e7){l.e=0,l.d=[i];return}return Sqe(l,i.toString())}else if(typeof i!="string")throw Error(YE+i);if(i.charCodeAt(0)===45?(i=i.slice(1),l.s=-1):l.s=1,Qks.test(i))Sqe(l,i);else throw Error(YE+i)}if(a.prototype=Wa,a.ROUND_UP=0,a.ROUND_DOWN=1,a.ROUND_CEIL=2,a.ROUND_FLOOR=3,a.ROUND_HALF_UP=4,a.ROUND_HALF_DOWN=5,a.ROUND_HALF_EVEN=6,a.ROUND_HALF_CEIL=7,a.ROUND_HALF_FLOOR=8,a.clone=Wft,a.config=a.set=Jks,s===void 0&&(s={}),s)for(n=["precision","rounding","toExpNeg","toExpPos","LN10"],t=0;t=a[t+1]&&n<=a[t+2])this[r]=n;else throw Error(YE+r+": "+n);if((n=s[r="LN10"])!==void 0)if(n==Math.LN10)this[r]=new this(n);else throw Error(YE+r+": "+n);return this}var GAe=Wft(Xks);i0=new GAe(1);const kc=GAe;function eSs(s){return nSs(s)||rSs(s)||sSs(s)||tSs()}function tSs(){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 sSs(s,t){if(s){if(typeof s=="string")return TSe(s,t);var r=Object.prototype.toString.call(s).slice(8,-1);if(r==="Object"&&s.constructor&&(r=s.constructor.name),r==="Map"||r==="Set")return Array.from(s);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return TSe(s,t)}}function rSs(s){if(typeof Symbol<"u"&&Symbol.iterator in Object(s))return Array.from(s)}function nSs(s){if(Array.isArray(s))return TSe(s)}function TSe(s,t){(t==null||t>s.length)&&(t=s.length);for(var r=0,n=new Array(t);r=t?r.apply(void 0,a):s(t-l,Tqe(function(){for(var o=arguments.length,c=new Array(o),d=0;ds.length)&&(t=s.length);for(var r=0,n=new Array(t);r"u"||!(Symbol.iterator in Object(s)))){var r=[],n=!0,a=!1,i=void 0;try{for(var l=s[Symbol.iterator](),o;!(n=(o=l.next()).done)&&(r.push(o.value),!(t&&r.length===t));n=!0);}catch(c){a=!0,i=c}finally{try{!n&&l.return!=null&&l.return()}finally{if(a)throw i}}return r}}function vSs(s){if(Array.isArray(s))return s}function Qft(s){var t=W9(s,2),r=t[0],n=t[1],a=r,i=n;return r>n&&(a=n,i=r),[a,i]}function Jft(s,t,r){if(s.lte(0))return new kc(0);var n=v0e.getDigitCount(s.toNumber()),a=new kc(10).pow(n),i=s.div(a),l=n!==1?.05:.1,o=new kc(Math.ceil(i.div(l).toNumber())).add(r).mul(l),c=o.mul(a);return t?c:new kc(Math.ceil(c))}function bSs(s,t,r){var n=1,a=new kc(s);if(!a.isint()&&r){var i=Math.abs(s);i<1?(n=new kc(10).pow(v0e.getDigitCount(s)-1),a=new kc(Math.floor(a.div(n).toNumber())).mul(n)):i>1&&(a=new kc(Math.floor(s)))}else s===0?a=new kc(Math.floor((t-1)/2)):r||(a=new kc(Math.floor(s)));var l=Math.floor((t-1)/2),o=lSs(oSs(function(c){return a.add(new kc(c-l).mul(n)).toNumber()}),ESe);return o(0,t)}function ept(s,t,r,n){var a=arguments.length>4&&arguments[4]!==void 0?arguments[4]:0;if(!Number.isFinite((t-s)/(r-1)))return{step:new kc(0),tickMin:new kc(0),tickMax:new kc(0)};var i=Jft(new kc(t).sub(s).div(r-1),n,a),l;s<=0&&t>=0?l=new kc(0):(l=new kc(s).add(t).div(2),l=l.sub(new kc(l).mod(i)));var o=Math.ceil(l.sub(s).div(i).toNumber()),c=Math.ceil(new kc(t).sub(l).div(i).toNumber()),d=o+c+1;return d>r?ept(s,t,r,n,a+1):(d0?c+(r-d):c,o=t>0?o:o+(r-d)),{step:i,tickMin:l.sub(new kc(o).mul(i)),tickMax:l.add(new kc(c).mul(i))})}function _Ss(s){var t=W9(s,2),r=t[0],n=t[1],a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:6,i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,l=Math.max(a,2),o=Qft([r,n]),c=W9(o,2),d=c[0],h=c[1];if(d===-1/0||h===1/0){var m=h===1/0?[d].concat(MSe(ESe(0,a-1).map(function(){return 1/0}))):[].concat(MSe(ESe(0,a-1).map(function(){return-1/0})),[h]);return r>n?ASe(m):m}if(d===h)return bSs(d,a,i);var p=ept(d,h,l,i),x=p.step,y=p.tickMin,_=p.tickMax,b=v0e.rangeStep(y,_.add(new kc(.1).mul(x)),x);return r>n?ASe(b):b}function wSs(s,t){var r=W9(s,2),n=r[0],a=r[1],i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,l=Qft([n,a]),o=W9(l,2),c=o[0],d=o[1];if(c===-1/0||d===1/0)return[n,a];if(c===d)return[c];var h=Math.max(t,2),m=Jft(new kc(d).sub(c).div(h-1),i,0),p=[].concat(MSe(v0e.rangeStep(new kc(c),new kc(d).sub(new kc(.99).mul(m)),m)),[d]);return n>a?ASe(p):p}var jSs=Zft(_Ss),NSs=Zft(wSs),kSs="Invariant failed";function EA(s,t){throw new Error(kSs)}var SSs=["offset","layout","width","dataKey","data","dataPointFormatter","xAxis","yAxis"];function jL(s){"@babel/helpers - typeof";return jL=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},jL(s)}function Afe(){return Afe=Object.assign?Object.assign.bind():function(s){for(var t=1;ts.length)&&(t=s.length);for(var r=0,n=new Array(t);r=0)&&Object.prototype.propertyIsEnumerable.call(s,n)&&(r[n]=s[n])}return r}function PSs(s,t){if(s==null)return{};var r={};for(var n in s)if(Object.prototype.hasOwnProperty.call(s,n)){if(t.indexOf(n)>=0)continue;r[n]=s[n]}return r}function LSs(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function DSs(s,t){for(var r=0;rs.length)&&(t=s.length);for(var r=0,n=new Array(t);r1&&arguments[1]!==void 0?arguments[1]:[],a=arguments.length>2?arguments[2]:void 0,i=arguments.length>3?arguments[3]:void 0,l=-1,o=(r=n==null?void 0:n.length)!==null&&r!==void 0?r:0;if(o<=1)return 0;if(i&&i.axisType==="angleAxis"&&Math.abs(Math.abs(i.range[1]-i.range[0])-360)<=1e-6)for(var c=i.range,d=0;d0?a[d-1].coordinate:a[o-1].coordinate,m=a[d].coordinate,p=d>=o-1?a[0].coordinate:a[d+1].coordinate,x=void 0;if(gg(m-h)!==gg(p-m)){var y=[];if(gg(p-m)===gg(c[1]-c[0])){x=p;var _=m+c[1]-c[0];y[0]=Math.min(_,(_+h)/2),y[1]=Math.max(_,(_+h)/2)}else{x=h;var b=p+c[1]-c[0];y[0]=Math.min(m,(b+m)/2),y[1]=Math.max(m,(b+m)/2)}var j=[Math.min(m,(x+m)/2),Math.max(m,(x+m)/2)];if(t>j[0]&&t<=j[1]||t>=y[0]&&t<=y[1]){l=a[d].index;break}}else{var k=Math.min(h,p),T=Math.max(h,p);if(t>(k+m)/2&&t<=(T+m)/2){l=a[d].index;break}}}else for(var E=0;E0&&E(n[E].coordinate+n[E-1].coordinate)/2&&t<=(n[E].coordinate+n[E+1].coordinate)/2||E===o-1&&t>(n[E].coordinate+n[E-1].coordinate)/2){l=n[E].index;break}return l},WAe=function(t){var r,n=t,a=n.type.displayName,i=(r=t.type)!==null&&r!==void 0&&r.defaultProps?Fu(Fu({},t.type.defaultProps),t.props):t.props,l=i.stroke,o=i.fill,c;switch(a){case"Line":c=l;break;case"Area":case"Radar":c=l&&l!=="none"?l:o;break;default:c=o;break}return c},QSs=function(t){var r=t.barSize,n=t.totalSize,a=t.stackGroups,i=a===void 0?{}:a;if(!i)return{};for(var l={},o=Object.keys(i),c=0,d=o.length;c=0});if(j&&j.length){var k=j[0].type.defaultProps,T=k!==void 0?Fu(Fu({},k),j[0].props):j[0].props,E=T.barSize,A=T[b];l[A]||(l[A]=[]);var D=yo(E)?r:E;l[A].push({item:j[0],stackList:j.slice(1),barSize:yo(D)?void 0:xg(D,n,0)})}}return l},JSs=function(t){var r=t.barGap,n=t.barCategoryGap,a=t.bandSize,i=t.sizeList,l=i===void 0?[]:i,o=t.maxBarSize,c=l.length;if(c<1)return null;var d=xg(r,a,0,!0),h,m=[];if(l[0].barSize===+l[0].barSize){var p=!1,x=a/c,y=l.reduce(function(E,A){return E+A.barSize||0},0);y+=(c-1)*d,y>=a&&(y-=(c-1)*d,d=0),y>=a&&x>0&&(p=!0,x*=.9,y=c*x);var _=(a-y)/2>>0,b={offset:_-d,size:0};h=l.reduce(function(E,A){var D={item:A.item,position:{offset:b.offset+b.size+d,size:p?x:A.barSize}},R=[].concat(Mqe(E),[D]);return b=R[R.length-1].position,A.stackList&&A.stackList.length&&A.stackList.forEach(function(z){R.push({item:z,position:b})}),R},m)}else{var j=xg(n,a,0,!0);a-2*j-(c-1)*d<=0&&(d=0);var k=(a-2*j-(c-1)*d)/c;k>1&&(k>>=0);var T=o===+o?Math.min(k,o):k;h=l.reduce(function(E,A,D){var R=[].concat(Mqe(E),[{item:A.item,position:{offset:j+(k+d)*D+(k-T)/2,size:T}}]);return A.stackList&&A.stackList.length&&A.stackList.forEach(function(z){R.push({item:z,position:R[R.length-1].position})}),R},m)}return h},e4s=function(t,r,n,a){var i=n.children,l=n.width,o=n.margin,c=l-(o.left||0)-(o.right||0),d=npt({children:i,legendWidth:c});if(d){var h=a||{},m=h.width,p=h.height,x=d.align,y=d.verticalAlign,_=d.layout;if((_==="vertical"||_==="horizontal"&&y==="middle")&&x!=="center"&&Kn(t[x]))return Fu(Fu({},t),{},yP({},x,t[x]+(m||0)));if((_==="horizontal"||_==="vertical"&&x==="center")&&y!=="middle"&&Kn(t[y]))return Fu(Fu({},t),{},yP({},y,t[y]+(p||0)))}return t},t4s=function(t,r,n){return yo(r)?!0:t==="horizontal"?r==="yAxis":t==="vertical"||n==="x"?r==="xAxis":n==="y"?r==="yAxis":!0},apt=function(t,r,n,a,i){var l=r.props.children,o=v0(l,Pz).filter(function(d){return t4s(a,i,d.props.direction)});if(o&&o.length){var c=o.map(function(d){return d.props.dataKey});return t.reduce(function(d,h){var m=dm(h,n);if(yo(m))return d;var p=Array.isArray(m)?[x0e(m),g0e(m)]:[m,m],x=c.reduce(function(y,_){var b=dm(h,_,0),j=p[0]-Math.abs(Array.isArray(b)?b[0]:b),k=p[1]+Math.abs(Array.isArray(b)?b[1]:b);return[Math.min(j,y[0]),Math.max(k,y[1])]},[1/0,-1/0]);return[Math.min(x[0],d[0]),Math.max(x[1],d[1])]},[1/0,-1/0])}return null},s4s=function(t,r,n,a,i){var l=r.map(function(o){return apt(t,o,n,i,a)}).filter(function(o){return!yo(o)});return l&&l.length?l.reduce(function(o,c){return[Math.min(o[0],c[0]),Math.max(o[1],c[1])]},[1/0,-1/0]):null},ipt=function(t,r,n,a,i){var l=r.map(function(c){var d=c.props.dataKey;return n==="number"&&d&&apt(t,c,d,a)||j7(t,d,n,i)});if(n==="number")return l.reduce(function(c,d){return[Math.min(c[0],d[0]),Math.max(c[1],d[1])]},[1/0,-1/0]);var o={};return l.reduce(function(c,d){for(var h=0,m=d.length;h=2?gg(o[0]-o[1])*2*d:d,r&&(t.ticks||t.niceTicks)){var h=(t.ticks||t.niceTicks).map(function(m){var p=i?i.indexOf(m):m;return{coordinate:a(p)+d,value:m,offset:d}});return h.filter(function(m){return!kz(m.coordinate)})}return t.isCategorical&&t.categoricalDomain?t.categoricalDomain.map(function(m,p){return{coordinate:a(m)+d,value:m,index:p,offset:d}}):a.ticks&&!n?a.ticks(t.tickCount).map(function(m){return{coordinate:a(m)+d,value:m,offset:d}}):a.domain().map(function(m,p){return{coordinate:a(m)+d,value:i?i[m]:m,index:p,offset:d}})},twe=new WeakMap,Oq=function(t,r){if(typeof r!="function")return t;twe.has(t)||twe.set(t,new WeakMap);var n=twe.get(t);if(n.has(r))return n.get(r);var a=function(){t.apply(void 0,arguments),r.apply(void 0,arguments)};return n.set(r,a),a},cpt=function(t,r,n){var a=t.scale,i=t.type,l=t.layout,o=t.axisType;if(a==="auto")return l==="radial"&&o==="radiusAxis"?{scale:$9(),realScaleType:"band"}:l==="radial"&&o==="angleAxis"?{scale:kfe(),realScaleType:"linear"}:i==="category"&&r&&(r.indexOf("LineChart")>=0||r.indexOf("AreaChart")>=0||r.indexOf("ComposedChart")>=0&&!n)?{scale:w7(),realScaleType:"point"}:i==="category"?{scale:$9(),realScaleType:"band"}:{scale:kfe(),realScaleType:"linear"};if(kA(a)){var c="scale".concat(s0e(a));return{scale:(kqe[c]||w7)(),realScaleType:kqe[c]?c:"point"}}return no(a)?{scale:a}:{scale:w7(),realScaleType:"point"}},Pqe=1e-4,dpt=function(t){var r=t.domain();if(!(!r||r.length<=2)){var n=r.length,a=t.range(),i=Math.min(a[0],a[1])-Pqe,l=Math.max(a[0],a[1])+Pqe,o=t(r[0]),c=t(r[n-1]);(ol||cl)&&t.domain([r[0],r[n-1]])}},r4s=function(t,r){if(!t)return null;for(var n=0,a=t.length;na)&&(i[1]=a),i[0]>a&&(i[0]=a),i[1]=0?(t[o][n][0]=i,t[o][n][1]=i+c,i=t[o][n][1]):(t[o][n][0]=l,t[o][n][1]=l+c,l=t[o][n][1])}},i4s=function(t){var r=t.length;if(!(r<=0))for(var n=0,a=t[0].length;n=0?(t[l][n][0]=i,t[l][n][1]=i+o,i=t[l][n][1]):(t[l][n][0]=0,t[l][n][1]=0)}},o4s={sign:a4s,expand:Sgs,none:pL,silhouette:Cgs,wiggle:Tgs,positive:i4s},l4s=function(t,r,n){var a=r.map(function(o){return o.props.dataKey}),i=o4s[n],l=kgs().keys(a).value(function(o,c){return+dm(o,c,0)}).order(aSe).offset(i);return l(t)},c4s=function(t,r,n,a,i,l){if(!t)return null;var o=l?r.reverse():r,c={},d=o.reduce(function(m,p){var x,y=(x=p.type)!==null&&x!==void 0&&x.defaultProps?Fu(Fu({},p.type.defaultProps),p.props):p.props,_=y.stackId,b=y.hide;if(b)return m;var j=y[n],k=m[j]||{hasStack:!1,stackGroups:{}};if(hm(_)){var T=k.stackGroups[_]||{numericAxisId:n,cateAxisId:a,items:[]};T.items.push(p),k.hasStack=!0,k.stackGroups[_]=T}else k.stackGroups[L8("_stackId_")]={numericAxisId:n,cateAxisId:a,items:[p]};return Fu(Fu({},m),{},yP({},j,k))},c),h={};return Object.keys(d).reduce(function(m,p){var x=d[p];if(x.hasStack){var y={};x.stackGroups=Object.keys(x.stackGroups).reduce(function(_,b){var j=x.stackGroups[b];return Fu(Fu({},_),{},yP({},b,{numericAxisId:n,cateAxisId:a,items:j.items,stackedData:l4s(t,j.items,i)}))},y)}return Fu(Fu({},m),{},yP({},p,x))},h)},upt=function(t,r){var n=r.realScaleType,a=r.type,i=r.tickCount,l=r.originalDomain,o=r.allowDecimals,c=n||r.scale;if(c!=="auto"&&c!=="linear")return null;if(i&&a==="number"&&l&&(l[0]==="auto"||l[1]==="auto")){var d=t.domain();if(!d.length)return null;var h=jSs(d,i,o);return t.domain([x0e(h),g0e(h)]),{niceTicks:h}}if(i&&a==="number"){var m=t.domain(),p=NSs(m,i,o);return{niceTicks:p}}return null};function Lqe(s){var t=s.axis,r=s.ticks,n=s.bandSize,a=s.entry,i=s.index,l=s.dataKey;if(t.type==="category"){if(!t.allowDuplicatedCategory&&t.dataKey&&!yo(a[t.dataKey])){var o=nfe(r,"value",a[t.dataKey]);if(o)return o.coordinate+n/2}return r[i]?r[i].coordinate+n/2:null}var c=dm(a,yo(l)?t.dataKey:l);return yo(c)?null:t.scale(c)}var Dqe=function(t){var r=t.axis,n=t.ticks,a=t.offset,i=t.bandSize,l=t.entry,o=t.index;if(r.type==="category")return n[o]?n[o].coordinate+a:null;var c=dm(l,r.dataKey,r.domain[o]);return yo(c)?null:r.scale(c)-i/2+a},d4s=function(t){var r=t.numericAxis,n=r.scale.domain();if(r.type==="number"){var a=Math.min(n[0],n[1]),i=Math.max(n[0],n[1]);return a<=0&&i>=0?0:i<0?i:a}return n[0]},u4s=function(t,r){var n,a=(n=t.type)!==null&&n!==void 0&&n.defaultProps?Fu(Fu({},t.type.defaultProps),t.props):t.props,i=a.stackId;if(hm(i)){var l=r[i];if(l){var o=l.items.indexOf(t);return o>=0?l.stackedData[o]:null}}return null},h4s=function(t){return t.reduce(function(r,n){return[x0e(n.concat([r[0]]).filter(Kn)),g0e(n.concat([r[1]]).filter(Kn))]},[1/0,-1/0])},hpt=function(t,r,n){return Object.keys(t).reduce(function(a,i){var l=t[i],o=l.stackedData,c=o.reduce(function(d,h){var m=h4s(h.slice(r,n+1));return[Math.min(d[0],m[0]),Math.max(d[1],m[1])]},[1/0,-1/0]);return[Math.min(c[0],a[0]),Math.max(c[1],a[1])]},[1/0,-1/0]).map(function(a){return a===1/0||a===-1/0?0:a})},Rqe=/^dataMin[\s]*-[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,Oqe=/^dataMax[\s]*\+[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,DSe=function(t,r,n){if(no(t))return t(r,n);if(!Array.isArray(t))return r;var a=[];if(Kn(t[0]))a[0]=n?t[0]:Math.min(t[0],r[0]);else if(Rqe.test(t[0])){var i=+Rqe.exec(t[0])[1];a[0]=r[0]-i}else no(t[0])?a[0]=t[0](r[0]):a[0]=r[0];if(Kn(t[1]))a[1]=n?t[1]:Math.max(t[1],r[1]);else if(Oqe.test(t[1])){var l=+Oqe.exec(t[1])[1];a[1]=r[1]+l}else no(t[1])?a[1]=t[1](r[1]):a[1]=r[1];return a},Ife=function(t,r,n){if(t&&t.scale&&t.scale.bandwidth){var a=t.scale.bandwidth();if(!n||a>0)return a}if(t&&r&&r.length>=2){for(var i=_Ae(r,function(m){return m.coordinate}),l=1/0,o=1,c=i.length;os.length)&&(t=s.length);for(var r=0,n=new Array(t);r2&&arguments[2]!==void 0?arguments[2]:{top:0,right:0,bottom:0,left:0};return Math.min(Math.abs(t-(n.left||0)-(n.right||0)),Math.abs(r-(n.top||0)-(n.bottom||0)))/2},_4s=function(t,r,n,a,i){var l=t.width,o=t.height,c=t.startAngle,d=t.endAngle,h=xg(t.cx,l,l/2),m=xg(t.cy,o,o/2),p=ppt(l,o,n),x=xg(t.innerRadius,p,0),y=xg(t.outerRadius,p,p*.8),_=Object.keys(r);return _.reduce(function(b,j){var k=r[j],T=k.domain,E=k.reversed,A;if(yo(k.range))a==="angleAxis"?A=[c,d]:a==="radiusAxis"&&(A=[x,y]),E&&(A=[A[1],A[0]]);else{A=k.range;var D=A,R=p4s(D,2);c=R[0],d=R[1]}var z=cpt(k,i),O=z.realScaleType,$=z.scale;$.domain(T).range(A),dpt($);var ee=upt($,p2(p2({},k),{},{realScaleType:O})),Z=p2(p2(p2({},k),ee),{},{range:A,radius:y,realScaleType:O,scale:$,cx:h,cy:m,innerRadius:x,outerRadius:y,startAngle:c,endAngle:d});return p2(p2({},b),{},fpt({},j,Z))},{})},w4s=function(t,r){var n=t.x,a=t.y,i=r.x,l=r.y;return Math.sqrt(Math.pow(n-i,2)+Math.pow(a-l,2))},j4s=function(t,r){var n=t.x,a=t.y,i=r.cx,l=r.cy,o=w4s({x:n,y:a},{x:i,y:l});if(o<=0)return{radius:o};var c=(n-i)/o,d=Math.acos(c);return a>l&&(d=2*Math.PI-d),{radius:o,angle:b4s(d),angleInRadian:d}},N4s=function(t){var r=t.startAngle,n=t.endAngle,a=Math.floor(r/360),i=Math.floor(n/360),l=Math.min(a,i);return{startAngle:r-l*360,endAngle:n-l*360}},k4s=function(t,r){var n=r.startAngle,a=r.endAngle,i=Math.floor(n/360),l=Math.floor(a/360),o=Math.min(i,l);return t+o*360},$qe=function(t,r){var n=t.x,a=t.y,i=j4s({x:n,y:a},r),l=i.radius,o=i.angle,c=r.innerRadius,d=r.outerRadius;if(ld)return!1;if(l===0)return!0;var h=N4s(r),m=h.startAngle,p=h.endAngle,x=o,y;if(m<=p){for(;x>p;)x-=360;for(;x=m&&x<=p}else{for(;x>m;)x-=360;for(;x=p&&x<=m}return y?p2(p2({},r),{},{radius:l,angle:k4s(x,r)}):null},gpt=function(t){return!S.isValidElement(t)&&!no(t)&&typeof t!="boolean"?t.className:""};function X9(s){"@babel/helpers - typeof";return X9=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},X9(s)}var S4s=["offset"];function C4s(s){return M4s(s)||A4s(s)||E4s(s)||T4s()}function T4s(){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 E4s(s,t){if(s){if(typeof s=="string")return RSe(s,t);var r=Object.prototype.toString.call(s).slice(8,-1);if(r==="Object"&&s.constructor&&(r=s.constructor.name),r==="Map"||r==="Set")return Array.from(s);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return RSe(s,t)}}function A4s(s){if(typeof Symbol<"u"&&s[Symbol.iterator]!=null||s["@@iterator"]!=null)return Array.from(s)}function M4s(s){if(Array.isArray(s))return RSe(s)}function RSe(s,t){(t==null||t>s.length)&&(t=s.length);for(var r=0,n=new Array(t);r=0)&&Object.prototype.propertyIsEnumerable.call(s,n)&&(r[n]=s[n])}return r}function P4s(s,t){if(s==null)return{};var r={};for(var n in s)if(Object.prototype.hasOwnProperty.call(s,n)){if(t.indexOf(n)>=0)continue;r[n]=s[n]}return r}function Uqe(s,t){var r=Object.keys(s);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(s);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(s,a).enumerable})),r.push.apply(r,n)}return r}function em(s){for(var t=1;t=0?1:-1,T,E;a==="insideStart"?(T=x+k*l,E=_):a==="insideEnd"?(T=y-k*l,E=!_):a==="end"&&(T=y+k*l,E=_),E=j<=0?E:!E;var A=id(d,h,b,T),D=id(d,h,b,T+(E?1:-1)*359),R="M".concat(A.x,",").concat(A.y,` A`).concat(b,",").concat(b,",0,1,").concat(E?0:1,`, `).concat(D.x,",").concat(D.y),z=yo(t.id)?L8("recharts-radial-line-"):t.id;return Nt.createElement("text",Q9({},n,{dominantBaseline:"central",className:jo("recharts-radial-bar-label",o)}),Nt.createElement("defs",null,Nt.createElement("path",{id:z,d:R})),Nt.createElement("textPath",{xlinkHref:"#".concat(z)},r))},z4s=function(t){var r=t.viewBox,n=t.offset,a=t.position,i=r,l=i.cx,o=i.cy,c=i.innerRadius,d=i.outerRadius,h=i.startAngle,m=i.endAngle,p=(h+m)/2;if(a==="outside"){var x=id(l,o,d+n,p),y=x.x,_=x.y;return{x:y,y:_,textAnchor:y>=l?"start":"end",verticalAnchor:"middle"}}if(a==="center")return{x:l,y:o,textAnchor:"middle",verticalAnchor:"middle"};if(a==="centerTop")return{x:l,y:o,textAnchor:"middle",verticalAnchor:"start"};if(a==="centerBottom")return{x:l,y:o,textAnchor:"middle",verticalAnchor:"end"};var b=(c+d)/2,j=id(l,o,b,p),k=j.x,T=j.y;return{x:k,y:T,textAnchor:"middle",verticalAnchor:"middle"}},$4s=function(t){var r=t.viewBox,n=t.parentViewBox,a=t.offset,i=t.position,l=r,o=l.x,c=l.y,d=l.width,h=l.height,m=h>=0?1:-1,p=m*a,x=m>0?"end":"start",y=m>0?"start":"end",_=d>=0?1:-1,b=_*a,j=_>0?"end":"start",k=_>0?"start":"end";if(i==="top"){var T={x:o+d/2,y:c-m*a,textAnchor:"middle",verticalAnchor:x};return em(em({},T),n?{height:Math.max(c-n.y,0),width:d}:{})}if(i==="bottom"){var E={x:o+d/2,y:c+h+p,textAnchor:"middle",verticalAnchor:y};return em(em({},E),n?{height:Math.max(n.y+n.height-(c+h),0),width:d}:{})}if(i==="left"){var A={x:o-b,y:c+h/2,textAnchor:j,verticalAnchor:"middle"};return em(em({},A),n?{width:Math.max(A.x-n.x,0),height:h}:{})}if(i==="right"){var D={x:o+d+b,y:c+h/2,textAnchor:k,verticalAnchor:"middle"};return em(em({},D),n?{width:Math.max(n.x+n.width-D.x,0),height:h}:{})}var R=n?{width:d,height:h}:{};return i==="insideLeft"?em({x:o+b,y:c+h/2,textAnchor:k,verticalAnchor:"middle"},R):i==="insideRight"?em({x:o+d-b,y:c+h/2,textAnchor:j,verticalAnchor:"middle"},R):i==="insideTop"?em({x:o+d/2,y:c+p,textAnchor:"middle",verticalAnchor:y},R):i==="insideBottom"?em({x:o+d/2,y:c+h-p,textAnchor:"middle",verticalAnchor:x},R):i==="insideTopLeft"?em({x:o+b,y:c+p,textAnchor:k,verticalAnchor:y},R):i==="insideTopRight"?em({x:o+d-b,y:c+p,textAnchor:j,verticalAnchor:y},R):i==="insideBottomLeft"?em({x:o+b,y:c+h-p,textAnchor:k,verticalAnchor:x},R):i==="insideBottomRight"?em({x:o+d-b,y:c+h-p,textAnchor:j,verticalAnchor:x},R):A8(i)&&(Kn(i.x)||HT(i.x))&&(Kn(i.y)||HT(i.y))?em({x:o+xg(i.x,d),y:c+xg(i.y,h),textAnchor:"end",verticalAnchor:"end"},R):em({x:o+d/2,y:c+h/2,textAnchor:"middle",verticalAnchor:"middle"},R)},U4s=function(t){return"cx"in t&&Kn(t.cx)};function Xm(s){var t=s.offset,r=t===void 0?5:t,n=I4s(s,S4s),a=em({offset:r},n),i=a.viewBox,l=a.position,o=a.value,c=a.children,d=a.content,h=a.className,m=h===void 0?"":h,p=a.textBreakAll;if(!i||yo(o)&&yo(c)&&!S.isValidElement(d)&&!no(d))return null;if(S.isValidElement(d))return S.cloneElement(d,a);var x;if(no(d)){if(x=S.createElement(d,a),S.isValidElement(x))return x}else x=O4s(a);var y=U4s(i),_=Li(a,!0);if(y&&(l==="insideStart"||l==="insideEnd"||l==="end"))return B4s(a,x,_);var b=y?z4s(a):$4s(a);return Nt.createElement(CA,Q9({className:jo("recharts-label",m)},_,b,{breakAll:p}),x)}Xm.displayName="Label";var xpt=function(t){var r=t.cx,n=t.cy,a=t.angle,i=t.startAngle,l=t.endAngle,o=t.r,c=t.radius,d=t.innerRadius,h=t.outerRadius,m=t.x,p=t.y,x=t.top,y=t.left,_=t.width,b=t.height,j=t.clockWise,k=t.labelViewBox;if(k)return k;if(Kn(_)&&Kn(b)){if(Kn(m)&&Kn(p))return{x:m,y:p,width:_,height:b};if(Kn(x)&&Kn(y))return{x,y,width:_,height:b}}return Kn(m)&&Kn(p)?{x:m,y:p,width:0,height:0}:Kn(r)&&Kn(n)?{cx:r,cy:n,startAngle:i||a||0,endAngle:l||a||0,innerRadius:d||0,outerRadius:h||c||o||0,clockWise:j}:t.viewBox?t.viewBox:{}},q4s=function(t,r){return t?t===!0?Nt.createElement(Xm,{key:"label-implicit",viewBox:r}):hm(t)?Nt.createElement(Xm,{key:"label-implicit",viewBox:r,value:t}):S.isValidElement(t)?t.type===Xm?S.cloneElement(t,{key:"label-implicit",viewBox:r}):Nt.createElement(Xm,{key:"label-implicit",content:t,viewBox:r}):no(t)?Nt.createElement(Xm,{key:"label-implicit",content:t,viewBox:r}):A8(t)?Nt.createElement(Xm,Q9({viewBox:r},t,{key:"label-implicit"})):null:null},V4s=function(t,r){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;if(!t||!t.children&&n&&!t.label)return null;var a=t.children,i=xpt(t),l=v0(a,Xm).map(function(c,d){return S.cloneElement(c,{viewBox:r||i,key:"label-".concat(d)})});if(!n)return l;var o=q4s(t.label,r||i);return[o].concat(C4s(l))};Xm.parseViewBox=xpt;Xm.renderCallByParent=V4s;function H4s(s){var t=s==null?0:s.length;return t?s[t-1]:void 0}var G4s=H4s;const W4s=ol(G4s);function J9(s){"@babel/helpers - typeof";return J9=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},J9(s)}var K4s=["valueAccessor"],Y4s=["data","dataKey","clockWise","id","textBreakAll"];function Z4s(s){return eCs(s)||J4s(s)||Q4s(s)||X4s()}function X4s(){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 Q4s(s,t){if(s){if(typeof s=="string")return OSe(s,t);var r=Object.prototype.toString.call(s).slice(8,-1);if(r==="Object"&&s.constructor&&(r=s.constructor.name),r==="Map"||r==="Set")return Array.from(s);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return OSe(s,t)}}function J4s(s){if(typeof Symbol<"u"&&s[Symbol.iterator]!=null||s["@@iterator"]!=null)return Array.from(s)}function eCs(s){if(Array.isArray(s))return OSe(s)}function OSe(s,t){(t==null||t>s.length)&&(t=s.length);for(var r=0,n=new Array(t);r=0)&&Object.prototype.propertyIsEnumerable.call(s,n)&&(r[n]=s[n])}return r}function nCs(s,t){if(s==null)return{};var r={};for(var n in s)if(Object.prototype.hasOwnProperty.call(s,n)){if(t.indexOf(n)>=0)continue;r[n]=s[n]}return r}var aCs=function(t){return Array.isArray(t.value)?W4s(t.value):t.value};function Q2(s){var t=s.valueAccessor,r=t===void 0?aCs:t,n=Hqe(s,K4s),a=n.data,i=n.dataKey,l=n.clockWise,o=n.id,c=n.textBreakAll,d=Hqe(n,Y4s);return!a||!a.length?null:Nt.createElement($l,{className:"recharts-label-list"},a.map(function(h,m){var p=yo(i)?r(h,m):dm(h&&h.payload,i),x=yo(o)?{}:{id:"".concat(o,"-").concat(m)};return Nt.createElement(Xm,Lfe({},Li(h,!0),d,x,{parentViewBox:h.parentViewBox,value:p,textBreakAll:c,viewBox:Xm.parseViewBox(yo(l)?h:Vqe(Vqe({},h),{},{clockWise:l})),key:"label-".concat(m),index:m}))}))}Q2.displayName="LabelList";function iCs(s,t){return s?s===!0?Nt.createElement(Q2,{key:"labelList-implicit",data:t}):Nt.isValidElement(s)||no(s)?Nt.createElement(Q2,{key:"labelList-implicit",data:t,content:s}):A8(s)?Nt.createElement(Q2,Lfe({data:t},s,{key:"labelList-implicit"})):null:null}function oCs(s,t){var r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;if(!s||!s.children&&r&&!s.label)return null;var n=s.children,a=v0(n,Q2).map(function(l,o){return S.cloneElement(l,{data:t,key:"labelList-".concat(o)})});if(!r)return a;var i=iCs(s.label,t);return[i].concat(Z4s(a))}Q2.renderCallByParent=oCs;function eB(s){"@babel/helpers - typeof";return eB=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},eB(s)}function FSe(){return FSe=Object.assign?Object.assign.bind():function(s){for(var t=1;t180),",").concat(+(l>d),`, `).concat(m.x,",").concat(m.y,` `);if(a>0){var x=id(r,n,a,l),y=id(r,n,a,d);p+="L ".concat(y.x,",").concat(y.y,` A `).concat(a,",").concat(a,`,0, `).concat(+(Math.abs(c)>180),",").concat(+(l<=d),`, `).concat(x.x,",").concat(x.y," Z")}else p+="L ".concat(r,",").concat(n," Z");return p},hCs=function(t){var r=t.cx,n=t.cy,a=t.innerRadius,i=t.outerRadius,l=t.cornerRadius,o=t.forceCornerRadius,c=t.cornerIsExternal,d=t.startAngle,h=t.endAngle,m=gg(h-d),p=Fq({cx:r,cy:n,radius:i,angle:d,sign:m,cornerRadius:l,cornerIsExternal:c}),x=p.circleTangency,y=p.lineTangency,_=p.theta,b=Fq({cx:r,cy:n,radius:i,angle:h,sign:-m,cornerRadius:l,cornerIsExternal:c}),j=b.circleTangency,k=b.lineTangency,T=b.theta,E=c?Math.abs(d-h):Math.abs(d-h)-_-T;if(E<0)return o?"M ".concat(y.x,",").concat(y.y,` a`).concat(l,",").concat(l,",0,0,1,").concat(l*2,`,0 a`).concat(l,",").concat(l,",0,0,1,").concat(-l*2,`,0 `):ypt({cx:r,cy:n,innerRadius:a,outerRadius:i,startAngle:d,endAngle:h});var A="M ".concat(y.x,",").concat(y.y,` A`).concat(l,",").concat(l,",0,0,").concat(+(m<0),",").concat(x.x,",").concat(x.y,` A`).concat(i,",").concat(i,",0,").concat(+(E>180),",").concat(+(m<0),",").concat(j.x,",").concat(j.y,` A`).concat(l,",").concat(l,",0,0,").concat(+(m<0),",").concat(k.x,",").concat(k.y,` `);if(a>0){var D=Fq({cx:r,cy:n,radius:a,angle:d,sign:m,isExternal:!0,cornerRadius:l,cornerIsExternal:c}),R=D.circleTangency,z=D.lineTangency,O=D.theta,$=Fq({cx:r,cy:n,radius:a,angle:h,sign:-m,isExternal:!0,cornerRadius:l,cornerIsExternal:c}),ee=$.circleTangency,Z=$.lineTangency,J=$.theta,K=c?Math.abs(d-h):Math.abs(d-h)-O-J;if(K<0&&l===0)return"".concat(A,"L").concat(r,",").concat(n,"Z");A+="L".concat(Z.x,",").concat(Z.y,` A`).concat(l,",").concat(l,",0,0,").concat(+(m<0),",").concat(ee.x,",").concat(ee.y,` A`).concat(a,",").concat(a,",0,").concat(+(K>180),",").concat(+(m>0),",").concat(R.x,",").concat(R.y,` A`).concat(l,",").concat(l,",0,0,").concat(+(m<0),",").concat(z.x,",").concat(z.y,"Z")}else A+="L".concat(r,",").concat(n,"Z");return A},mCs={cx:0,cy:0,innerRadius:0,outerRadius:0,startAngle:0,endAngle:0,cornerRadius:0,forceCornerRadius:!1,cornerIsExternal:!1},vpt=function(t){var r=Wqe(Wqe({},mCs),t),n=r.cx,a=r.cy,i=r.innerRadius,l=r.outerRadius,o=r.cornerRadius,c=r.forceCornerRadius,d=r.cornerIsExternal,h=r.startAngle,m=r.endAngle,p=r.className;if(l0&&Math.abs(h-m)<360?b=hCs({cx:n,cy:a,innerRadius:i,outerRadius:l,cornerRadius:Math.min(_,y/2),forceCornerRadius:c,cornerIsExternal:d,startAngle:h,endAngle:m}):b=ypt({cx:n,cy:a,innerRadius:i,outerRadius:l,startAngle:h,endAngle:m}),Nt.createElement("path",FSe({},Li(r,!0),{className:x,d:b,role:"img"}))};function tB(s){"@babel/helpers - typeof";return tB=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},tB(s)}function BSe(){return BSe=Object.assign?Object.assign.bind():function(s){for(var t=1;t0;)if(!r.equals(s[n],t[n],n,n,s,t,r))return!1;return!0}function TCs(s,t){return $8(s.getTime(),t.getTime())}function tVe(s,t,r){if(s.size!==t.size)return!1;for(var n={},a=s.entries(),i=0,l,o;(l=a.next())&&!l.done;){for(var c=t.entries(),d=!1,h=0;(o=c.next())&&!o.done;){var m=l.value,p=m[0],x=m[1],y=o.value,_=y[0],b=y[1];!d&&!n[h]&&(d=r.equals(p,_,i,h,s,t,r)&&r.equals(x,b,p,_,s,t,r))&&(n[h]=!0),h++}if(!d)return!1;i++}return!0}function ECs(s,t,r){var n=eVe(s),a=n.length;if(eVe(t).length!==a)return!1;for(var i;a-- >0;)if(i=n[a],i===Npt&&(s.$$typeof||t.$$typeof)&&s.$$typeof!==t.$$typeof||!jpt(t,i)||!r.equals(s[i],t[i],i,i,s,t,r))return!1;return!0}function XR(s,t,r){var n=Qqe(s),a=n.length;if(Qqe(t).length!==a)return!1;for(var i,l,o;a-- >0;)if(i=n[a],i===Npt&&(s.$$typeof||t.$$typeof)&&s.$$typeof!==t.$$typeof||!jpt(t,i)||!r.equals(s[i],t[i],i,i,s,t,r)||(l=Jqe(s,i),o=Jqe(t,i),(l||o)&&(!l||!o||l.configurable!==o.configurable||l.enumerable!==o.enumerable||l.writable!==o.writable)))return!1;return!0}function ACs(s,t){return $8(s.valueOf(),t.valueOf())}function MCs(s,t){return s.source===t.source&&s.flags===t.flags}function sVe(s,t,r){if(s.size!==t.size)return!1;for(var n={},a=s.values(),i,l;(i=a.next())&&!i.done;){for(var o=t.values(),c=!1,d=0;(l=o.next())&&!l.done;)!c&&!n[d]&&(c=r.equals(i.value,l.value,i.value,l.value,s,t,r))&&(n[d]=!0),d++;if(!c)return!1}return!0}function ICs(s,t){var r=s.length;if(t.length!==r)return!1;for(;r-- >0;)if(s[r]!==t[r])return!1;return!0}var PCs="[object Arguments]",LCs="[object Boolean]",DCs="[object Date]",RCs="[object Map]",OCs="[object Number]",FCs="[object Object]",BCs="[object RegExp]",zCs="[object Set]",$Cs="[object String]",UCs=Array.isArray,rVe=typeof ArrayBuffer=="function"&&ArrayBuffer.isView?ArrayBuffer.isView:null,nVe=Object.assign,qCs=Object.prototype.toString.call.bind(Object.prototype.toString);function VCs(s){var t=s.areArraysEqual,r=s.areDatesEqual,n=s.areMapsEqual,a=s.areObjectsEqual,i=s.arePrimitiveWrappersEqual,l=s.areRegExpsEqual,o=s.areSetsEqual,c=s.areTypedArraysEqual;return function(h,m,p){if(h===m)return!0;if(h==null||m==null||typeof h!="object"||typeof m!="object")return h!==h&&m!==m;var x=h.constructor;if(x!==m.constructor)return!1;if(x===Object)return a(h,m,p);if(UCs(h))return t(h,m,p);if(rVe!=null&&rVe(h))return c(h,m,p);if(x===Date)return r(h,m,p);if(x===RegExp)return l(h,m,p);if(x===Map)return n(h,m,p);if(x===Set)return o(h,m,p);var y=qCs(h);return y===DCs?r(h,m,p):y===BCs?l(h,m,p):y===RCs?n(h,m,p):y===zCs?o(h,m,p):y===FCs?typeof h.then!="function"&&typeof m.then!="function"&&a(h,m,p):y===PCs?a(h,m,p):y===LCs||y===OCs||y===$Cs?i(h,m,p):!1}}function HCs(s){var t=s.circular,r=s.createCustomConfig,n=s.strict,a={areArraysEqual:n?XR:CCs,areDatesEqual:TCs,areMapsEqual:n?Xqe(tVe,XR):tVe,areObjectsEqual:n?XR:ECs,arePrimitiveWrappersEqual:ACs,areRegExpsEqual:MCs,areSetsEqual:n?Xqe(sVe,XR):sVe,areTypedArraysEqual:n?XR:ICs};if(r&&(a=nVe({},a,r(a))),t){var i=zq(a.areArraysEqual),l=zq(a.areMapsEqual),o=zq(a.areObjectsEqual),c=zq(a.areSetsEqual);a=nVe({},a,{areArraysEqual:i,areMapsEqual:l,areObjectsEqual:o,areSetsEqual:c})}return a}function GCs(s){return function(t,r,n,a,i,l,o){return s(t,r,o)}}function WCs(s){var t=s.circular,r=s.comparator,n=s.createState,a=s.equals,i=s.strict;if(n)return function(c,d){var h=n(),m=h.cache,p=m===void 0?t?new WeakMap:void 0:m,x=h.meta;return r(c,d,{cache:p,equals:a,meta:x,strict:i})};if(t)return function(c,d){return r(c,d,{cache:new WeakMap,equals:a,meta:void 0,strict:i})};var l={cache:void 0,equals:a,meta:void 0,strict:i};return function(c,d){return r(c,d,l)}}var KCs=n4();n4({strict:!0});n4({circular:!0});n4({circular:!0,strict:!0});n4({createInternalComparator:function(){return $8}});n4({strict:!0,createInternalComparator:function(){return $8}});n4({circular:!0,createInternalComparator:function(){return $8}});n4({circular:!0,createInternalComparator:function(){return $8},strict:!0});function n4(s){s===void 0&&(s={});var t=s.circular,r=t===void 0?!1:t,n=s.createInternalComparator,a=s.createState,i=s.strict,l=i===void 0?!1:i,o=HCs(s),c=VCs(o),d=n?n(c):GCs(c);return WCs({circular:r,comparator:c,createState:a,equals:d,strict:l})}function YCs(s){typeof requestAnimationFrame<"u"&&requestAnimationFrame(s)}function aVe(s){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,r=-1,n=function a(i){r<0&&(r=i),i-r>t?(s(i),r=-1):YCs(a)};requestAnimationFrame(n)}function zSe(s){"@babel/helpers - typeof";return zSe=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},zSe(s)}function ZCs(s){return e3s(s)||JCs(s)||QCs(s)||XCs()}function XCs(){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 QCs(s,t){if(s){if(typeof s=="string")return iVe(s,t);var r=Object.prototype.toString.call(s).slice(8,-1);if(r==="Object"&&s.constructor&&(r=s.constructor.name),r==="Map"||r==="Set")return Array.from(s);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return iVe(s,t)}}function iVe(s,t){(t==null||t>s.length)&&(t=s.length);for(var r=0,n=new Array(t);rs.length)&&(t=s.length);for(var r=0,n=new Array(t);r1?1:j<0?0:j},_=function(j){for(var k=j>1?1:j,T=k,E=0;E<8;++E){var A=m(T)-k,D=x(T);if(Math.abs(A-k)0&&arguments[0]!==void 0?arguments[0]:{},r=t.stiff,n=r===void 0?100:r,a=t.damping,i=a===void 0?8:a,l=t.dt,o=l===void 0?17:l,c=function(h,m,p){var x=-(h-m)*n,y=p*i,_=p+(x-y)*o/1e3,b=p*o/1e3+h;return Math.abs(b-m)s.length)&&(t=s.length);for(var r=0,n=new Array(t);r=0)&&Object.prototype.propertyIsEnumerable.call(s,n)&&(r[n]=s[n])}return r}function M3s(s,t){if(s==null)return{};var r={},n=Object.keys(s),a,i;for(i=0;i=0)&&(r[a]=s[a]);return r}function swe(s){return D3s(s)||L3s(s)||P3s(s)||I3s()}function I3s(){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 P3s(s,t){if(s){if(typeof s=="string")return HSe(s,t);var r=Object.prototype.toString.call(s).slice(8,-1);if(r==="Object"&&s.constructor&&(r=s.constructor.name),r==="Map"||r==="Set")return Array.from(s);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return HSe(s,t)}}function L3s(s){if(typeof Symbol<"u"&&s[Symbol.iterator]!=null||s["@@iterator"]!=null)return Array.from(s)}function D3s(s){if(Array.isArray(s))return HSe(s)}function HSe(s,t){(t==null||t>s.length)&&(t=s.length);for(var r=0,n=new Array(t);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 Ffe(s){return Ffe=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},Ffe(s)}var O_=function(s){z3s(r,s);var t=$3s(r);function r(n,a){var i;R3s(this,r),i=t.call(this,n,a);var l=i.props,o=l.isActive,c=l.attributeName,d=l.from,h=l.to,m=l.steps,p=l.children,x=l.duration;if(i.handleStyleChange=i.handleStyleChange.bind(KSe(i)),i.changeStyle=i.changeStyle.bind(KSe(i)),!o||x<=0)return i.state={style:{}},typeof p=="function"&&(i.state={style:h}),WSe(i);if(m&&m.length)i.state={style:m[0].style};else if(d){if(typeof p=="function")return i.state={style:d},WSe(i);i.state={style:c?EO({},c,d):d}}else i.state={style:{}};return i}return F3s(r,[{key:"componentDidMount",value:function(){var a=this.props,i=a.isActive,l=a.canBegin;this.mounted=!0,!(!i||!l)&&this.runAnimation(this.props)}},{key:"componentDidUpdate",value:function(a){var i=this.props,l=i.isActive,o=i.canBegin,c=i.attributeName,d=i.shouldReAnimate,h=i.to,m=i.from,p=this.state.style;if(o){if(!l){var x={style:c?EO({},c,h):h};this.state&&p&&(c&&p[c]!==h||!c&&p!==h)&&this.setState(x);return}if(!(KCs(a.to,h)&&a.canBegin&&a.isActive)){var y=!a.canBegin||!a.isActive;this.manager&&this.manager.stop(),this.stopJSAnimation&&this.stopJSAnimation();var _=y||d?m:a.to;if(this.state&&p){var b={style:c?EO({},c,_):_};(c&&p[c]!==_||!c&&p!==_)&&this.setState(b)}this.runAnimation(Hv(Hv({},this.props),{},{from:_,begin:0}))}}}},{key:"componentWillUnmount",value:function(){this.mounted=!1;var a=this.props.onAnimationEnd;this.unSubscribe&&this.unSubscribe(),this.manager&&(this.manager.stop(),this.manager=null),this.stopJSAnimation&&this.stopJSAnimation(),a&&a()}},{key:"handleStyleChange",value:function(a){this.changeStyle(a)}},{key:"changeStyle",value:function(a){this.mounted&&this.setState({style:a})}},{key:"runJSAnimation",value:function(a){var i=this,l=a.from,o=a.to,c=a.duration,d=a.easing,h=a.begin,m=a.onAnimationEnd,p=a.onAnimationStart,x=T3s(l,o,x3s(d),c,this.changeStyle),y=function(){i.stopJSAnimation=x()};this.manager.start([p,h,y,c,m])}},{key:"runStepAnimation",value:function(a){var i=this,l=a.steps,o=a.begin,c=a.onAnimationStart,d=l[0],h=d.style,m=d.duration,p=m===void 0?0:m,x=function(_,b,j){if(j===0)return _;var k=b.duration,T=b.easing,E=T===void 0?"ease":T,A=b.style,D=b.properties,R=b.onAnimationEnd,z=j>0?l[j-1]:b,O=D||Object.keys(A);if(typeof E=="function"||E==="spring")return[].concat(swe(_),[i.runJSAnimation.bind(i,{from:z.style,to:A,duration:k,easing:E}),k]);var $=cVe(O,k,E),ee=Hv(Hv(Hv({},z.style),A),{},{transition:$});return[].concat(swe(_),[ee,k,R]).filter(a3s)};return this.manager.start([c].concat(swe(l.reduce(x,[h,Math.max(p,o)])),[a.onAnimationEnd]))}},{key:"runAnimation",value:function(a){this.manager||(this.manager=t3s());var i=a.begin,l=a.duration,o=a.attributeName,c=a.to,d=a.easing,h=a.onAnimationStart,m=a.onAnimationEnd,p=a.steps,x=a.children,y=this.manager;if(this.unSubscribe=y.subscribe(this.handleStyleChange),typeof d=="function"||typeof x=="function"||d==="spring"){this.runJSAnimation(a);return}if(p.length>1){this.runStepAnimation(a);return}var _=o?EO({},o,c):c,b=cVe(Object.keys(_),l,d);y.start([h,i,Hv(Hv({},_),{},{transition:b}),l,m])}},{key:"render",value:function(){var a=this.props,i=a.children;a.begin;var l=a.duration;a.attributeName,a.easing;var o=a.isActive;a.steps,a.from,a.to,a.canBegin,a.onAnimationEnd,a.shouldReAnimate,a.onAnimationReStart;var c=A3s(a,E3s),d=S.Children.count(i),h=this.state.style;if(typeof i=="function")return i(h);if(!o||d===0||l<=0)return i;var m=function(x){var y=x.props,_=y.style,b=_===void 0?{}:_,j=y.className,k=S.cloneElement(x,Hv(Hv({},c),{},{style:Hv(Hv({},b),h),className:j}));return k};return d===1?m(S.Children.only(i)):Nt.createElement("div",null,S.Children.map(i,function(p){return m(p)}))}}]),r}(S.PureComponent);O_.displayName="Animate";O_.defaultProps={begin:0,duration:1e3,from:"",to:"",attributeName:"",easing:"ease",isActive:!0,canBegin:!0,steps:[],onAnimationEnd:function(){},onAnimationStart:function(){}};O_.propTypes={from:ac.oneOfType([ac.object,ac.string]),to:ac.oneOfType([ac.object,ac.string]),attributeName:ac.string,duration:ac.number,begin:ac.number,easing:ac.oneOfType([ac.string,ac.func]),steps:ac.arrayOf(ac.shape({duration:ac.number.isRequired,style:ac.object.isRequired,easing:ac.oneOfType([ac.oneOf(["ease","ease-in","ease-out","ease-in-out","linear"]),ac.func]),properties:ac.arrayOf("string"),onAnimationEnd:ac.func})),children:ac.oneOfType([ac.node,ac.func]),isActive:ac.bool,canBegin:ac.bool,onAnimationEnd:ac.func,shouldReAnimate:ac.bool,onAnimationStart:ac.func,onAnimationReStart:ac.func};function nB(s){"@babel/helpers - typeof";return nB=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},nB(s)}function Bfe(){return Bfe=Object.assign?Object.assign.bind():function(s){for(var t=1;ts.length)&&(t=s.length);for(var r=0,n=new Array(t);r=0?1:-1,c=n>=0?1:-1,d=a>=0&&n>=0||a<0&&n<0?1:0,h;if(l>0&&i instanceof Array){for(var m=[0,0,0,0],p=0,x=4;pl?l:i[p];h="M".concat(t,",").concat(r+o*m[0]),m[0]>0&&(h+="A ".concat(m[0],",").concat(m[0],",0,0,").concat(d,",").concat(t+c*m[0],",").concat(r)),h+="L ".concat(t+n-c*m[1],",").concat(r),m[1]>0&&(h+="A ".concat(m[1],",").concat(m[1],",0,0,").concat(d,`, `).concat(t+n,",").concat(r+o*m[1])),h+="L ".concat(t+n,",").concat(r+a-o*m[2]),m[2]>0&&(h+="A ".concat(m[2],",").concat(m[2],",0,0,").concat(d,`, `).concat(t+n-c*m[2],",").concat(r+a)),h+="L ".concat(t+c*m[3],",").concat(r+a),m[3]>0&&(h+="A ".concat(m[3],",").concat(m[3],",0,0,").concat(d,`, `).concat(t,",").concat(r+a-o*m[3])),h+="Z"}else if(l>0&&i===+i&&i>0){var y=Math.min(l,i);h="M ".concat(t,",").concat(r+o*y,` A `).concat(y,",").concat(y,",0,0,").concat(d,",").concat(t+c*y,",").concat(r,` L `).concat(t+n-c*y,",").concat(r,` A `).concat(y,",").concat(y,",0,0,").concat(d,",").concat(t+n,",").concat(r+o*y,` L `).concat(t+n,",").concat(r+a-o*y,` A `).concat(y,",").concat(y,",0,0,").concat(d,",").concat(t+n-c*y,",").concat(r+a,` L `).concat(t+c*y,",").concat(r+a,` A `).concat(y,",").concat(y,",0,0,").concat(d,",").concat(t,",").concat(r+a-o*y," Z")}else h="M ".concat(t,",").concat(r," h ").concat(n," v ").concat(a," h ").concat(-n," Z");return h},X3s=function(t,r){if(!t||!r)return!1;var n=t.x,a=t.y,i=r.x,l=r.y,o=r.width,c=r.height;if(Math.abs(o)>0&&Math.abs(c)>0){var d=Math.min(i,i+o),h=Math.max(i,i+o),m=Math.min(l,l+c),p=Math.max(l,l+c);return n>=d&&n<=h&&a>=m&&a<=p}return!1},Q3s={x:0,y:0,width:0,height:0,radius:0,isAnimationActive:!1,isUpdateAnimationActive:!1,animationBegin:0,animationDuration:1500,animationEasing:"ease"},KAe=function(t){var r=xVe(xVe({},Q3s),t),n=S.useRef(),a=S.useState(-1),i=q3s(a,2),l=i[0],o=i[1];S.useEffect(function(){if(n.current&&n.current.getTotalLength)try{var E=n.current.getTotalLength();E&&o(E)}catch{}},[]);var c=r.x,d=r.y,h=r.width,m=r.height,p=r.radius,x=r.className,y=r.animationEasing,_=r.animationDuration,b=r.animationBegin,j=r.isAnimationActive,k=r.isUpdateAnimationActive;if(c!==+c||d!==+d||h!==+h||m!==+m||h===0||m===0)return null;var T=jo("recharts-rectangle",x);return k?Nt.createElement(O_,{canBegin:l>0,from:{width:h,height:m,x:c,y:d},to:{width:h,height:m,x:c,y:d},duration:_,animationEasing:y,isActive:k},function(E){var A=E.width,D=E.height,R=E.x,z=E.y;return Nt.createElement(O_,{canBegin:l>0,from:"0px ".concat(l===-1?1:l,"px"),to:"".concat(l,"px 0px"),attributeName:"strokeDasharray",begin:b,duration:_,isActive:j,easing:y},Nt.createElement("path",Bfe({},Li(r,!0),{className:T,d:yVe(R,z,A,D,p),ref:n})))}):Nt.createElement("path",Bfe({},Li(r,!0),{className:T,d:yVe(c,d,h,m,p)}))},J3s=["points","className","baseLinePoints","connectNulls"];function gI(){return gI=Object.assign?Object.assign.bind():function(s){for(var t=1;t=0)&&Object.prototype.propertyIsEnumerable.call(s,n)&&(r[n]=s[n])}return r}function t5s(s,t){if(s==null)return{};var r={};for(var n in s)if(Object.prototype.hasOwnProperty.call(s,n)){if(t.indexOf(n)>=0)continue;r[n]=s[n]}return r}function vVe(s){return a5s(s)||n5s(s)||r5s(s)||s5s()}function s5s(){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 r5s(s,t){if(s){if(typeof s=="string")return YSe(s,t);var r=Object.prototype.toString.call(s).slice(8,-1);if(r==="Object"&&s.constructor&&(r=s.constructor.name),r==="Map"||r==="Set")return Array.from(s);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return YSe(s,t)}}function n5s(s){if(typeof Symbol<"u"&&s[Symbol.iterator]!=null||s["@@iterator"]!=null)return Array.from(s)}function a5s(s){if(Array.isArray(s))return YSe(s)}function YSe(s,t){(t==null||t>s.length)&&(t=s.length);for(var r=0,n=new Array(t);r0&&arguments[0]!==void 0?arguments[0]:[],r=[[]];return t.forEach(function(n){bVe(n)?r[r.length-1].push(n):r[r.length-1].length>0&&r.push([])}),bVe(t[0])&&r[r.length-1].push(t[0]),r[r.length-1].length<=0&&(r=r.slice(0,-1)),r},k7=function(t,r){var n=i5s(t);r&&(n=[n.reduce(function(i,l){return[].concat(vVe(i),vVe(l))},[])]);var a=n.map(function(i){return i.reduce(function(l,o,c){return"".concat(l).concat(c===0?"M":"L").concat(o.x,",").concat(o.y)},"")}).join("");return n.length===1?"".concat(a,"Z"):a},o5s=function(t,r,n){var a=k7(t,n);return"".concat(a.slice(-1)==="Z"?a.slice(0,-1):a,"L").concat(k7(r.reverse(),n).slice(1))},l5s=function(t){var r=t.points,n=t.className,a=t.baseLinePoints,i=t.connectNulls,l=e5s(t,J3s);if(!r||!r.length)return null;var o=jo("recharts-polygon",n);if(a&&a.length){var c=l.stroke&&l.stroke!=="none",d=o5s(r,a,i);return Nt.createElement("g",{className:o},Nt.createElement("path",gI({},Li(l,!0),{fill:d.slice(-1)==="Z"?l.fill:"none",stroke:"none",d})),c?Nt.createElement("path",gI({},Li(l,!0),{fill:"none",d:k7(r,i)})):null,c?Nt.createElement("path",gI({},Li(l,!0),{fill:"none",d:k7(a,i)})):null)}var h=k7(r,i);return Nt.createElement("path",gI({},Li(l,!0),{fill:h.slice(-1)==="Z"?l.fill:"none",className:o,d:h}))};function ZSe(){return ZSe=Object.assign?Object.assign.bind():function(s){for(var t=1;t=0)&&Object.prototype.propertyIsEnumerable.call(s,n)&&(r[n]=s[n])}return r}function p5s(s,t){if(s==null)return{};var r={};for(var n in s)if(Object.prototype.hasOwnProperty.call(s,n)){if(t.indexOf(n)>=0)continue;r[n]=s[n]}return r}var g5s=function(t,r,n,a,i,l){return"M".concat(t,",").concat(i,"v").concat(a,"M").concat(l,",").concat(r,"h").concat(n)},x5s=function(t){var r=t.x,n=r===void 0?0:r,a=t.y,i=a===void 0?0:a,l=t.top,o=l===void 0?0:l,c=t.left,d=c===void 0?0:c,h=t.width,m=h===void 0?0:h,p=t.height,x=p===void 0?0:p,y=t.className,_=f5s(t,c5s),b=d5s({x:n,y:i,top:o,left:d,width:m,height:x},_);return!Kn(n)||!Kn(i)||!Kn(m)||!Kn(x)||!Kn(o)||!Kn(d)?null:Nt.createElement("path",XSe({},Li(b,!0),{className:jo("recharts-cross",y),d:g5s(n,i,m,x,o,d)}))},y5s=p0e,v5s=$ft,b5s=Y_;function _5s(s,t){return s&&s.length?y5s(s,b5s(t),v5s):void 0}var w5s=_5s;const j5s=ol(w5s);var N5s=p0e,k5s=Y_,S5s=Uft;function C5s(s,t){return s&&s.length?N5s(s,k5s(t),S5s):void 0}var T5s=C5s;const E5s=ol(T5s);var A5s=["cx","cy","angle","ticks","axisLine"],M5s=["ticks","tick","angle","tickFormatter","stroke"];function kL(s){"@babel/helpers - typeof";return kL=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},kL(s)}function S7(){return S7=Object.assign?Object.assign.bind():function(s){for(var t=1;t=0)&&Object.prototype.propertyIsEnumerable.call(s,n)&&(r[n]=s[n])}return r}function I5s(s,t){if(s==null)return{};var r={};for(var n in s)if(Object.prototype.hasOwnProperty.call(s,n)){if(t.indexOf(n)>=0)continue;r[n]=s[n]}return r}function P5s(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function NVe(s,t){for(var r=0;rCVe?l=a==="outer"?"start":"end":i<-CVe?l=a==="outer"?"end":"start":l="middle",l}},{key:"renderAxisLine",value:function(){var n=this.props,a=n.cx,i=n.cy,l=n.radius,o=n.axisLine,c=n.axisLineType,d=aC(aC({},Li(this.props,!1)),{},{fill:"none"},Li(o,!1));if(c==="circle")return Nt.createElement(b0e,MT({className:"recharts-polar-angle-axis-line"},d,{cx:a,cy:i,r:l}));var h=this.props.ticks,m=h.map(function(p){return id(a,i,l,p.coordinate)});return Nt.createElement(l5s,MT({className:"recharts-polar-angle-axis-line"},d,{points:m}))}},{key:"renderTicks",value:function(){var n=this,a=this.props,i=a.ticks,l=a.tick,o=a.tickLine,c=a.tickFormatter,d=a.stroke,h=Li(this.props,!1),m=Li(l,!1),p=aC(aC({},h),{},{fill:"none"},Li(o,!1)),x=i.map(function(y,_){var b=n.getTickLineCoord(y),j=n.getTickTextAnchor(y),k=aC(aC(aC({textAnchor:j},h),{},{stroke:"none",fill:d},m),{},{index:_,payload:y,x:b.x2,y:b.y2});return Nt.createElement($l,MT({className:jo("recharts-polar-angle-axis-tick",gpt(l)),key:"tick-".concat(y.coordinate)},SA(n.props,y,_)),o&&Nt.createElement("line",MT({className:"recharts-polar-angle-axis-tick-line"},p,b)),l&&t.renderTickItem(l,k,c?c(y.value,_):y.value))});return Nt.createElement($l,{className:"recharts-polar-angle-axis-ticks"},x)}},{key:"render",value:function(){var n=this.props,a=n.ticks,i=n.radius,l=n.axisLine;return i<=0||!a||!a.length?null:Nt.createElement($l,{className:jo("recharts-polar-angle-axis",this.props.className)},l&&this.renderAxisLine(),this.renderTicks())}}],[{key:"renderTickItem",value:function(n,a,i){var l;return Nt.isValidElement(n)?l=Nt.cloneElement(n,a):no(n)?l=n(a):l=Nt.createElement(CA,MT({},a,{className:"recharts-polar-angle-axis-tick-value"}),i),l}}])}(S.PureComponent);j0e(N0e,"displayName","PolarAngleAxis");j0e(N0e,"axisType","angleAxis");j0e(N0e,"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 K5s=Omt,Y5s=K5s(Object.getPrototypeOf,Object),Z5s=Y5s,X5s=Nj,Q5s=Z5s,J5s=kj,eTs="[object Object]",tTs=Function.prototype,sTs=Object.prototype,Dpt=tTs.toString,rTs=sTs.hasOwnProperty,nTs=Dpt.call(Object);function aTs(s){if(!J5s(s)||X5s(s)!=eTs)return!1;var t=Q5s(s);if(t===null)return!0;var r=rTs.call(t,"constructor")&&t.constructor;return typeof r=="function"&&r instanceof r&&Dpt.call(r)==nTs}var iTs=aTs;const oTs=ol(iTs);var lTs=Nj,cTs=kj,dTs="[object Boolean]";function uTs(s){return s===!0||s===!1||cTs(s)&&lTs(s)==dTs}var hTs=uTs;const mTs=ol(hTs);function iB(s){"@babel/helpers - typeof";return iB=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},iB(s)}function Ufe(){return Ufe=Object.assign?Object.assign.bind():function(s){for(var t=1;ts.length)&&(t=s.length);for(var r=0,n=new Array(t);r0,from:{upperWidth:0,lowerWidth:0,height:p,x:c,y:d},to:{upperWidth:h,lowerWidth:m,height:p,x:c,y:d},duration:_,animationEasing:y,isActive:j},function(T){var E=T.upperWidth,A=T.lowerWidth,D=T.height,R=T.x,z=T.y;return Nt.createElement(O_,{canBegin:l>0,from:"0px ".concat(l===-1?1:l,"px"),to:"".concat(l,"px 0px"),attributeName:"strokeDasharray",begin:b,duration:_,easing:y},Nt.createElement("path",Ufe({},Li(r,!0),{className:k,d:MVe(R,z,E,A,D),ref:n})))}):Nt.createElement("g",null,Nt.createElement("path",Ufe({},Li(r,!0),{className:k,d:MVe(c,d,h,m,p)})))},NTs=["option","shapeType","propTransformer","activeClassName","isActive"];function oB(s){"@babel/helpers - typeof";return oB=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},oB(s)}function kTs(s,t){if(s==null)return{};var r=STs(s,t),n,a;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(s);for(a=0;a=0)&&Object.prototype.propertyIsEnumerable.call(s,n)&&(r[n]=s[n])}return r}function STs(s,t){if(s==null)return{};var r={};for(var n in s)if(Object.prototype.hasOwnProperty.call(s,n)){if(t.indexOf(n)>=0)continue;r[n]=s[n]}return r}function IVe(s,t){var r=Object.keys(s);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(s);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(s,a).enumerable})),r.push.apply(r,n)}return r}function qfe(s){for(var t=1;t0?y0(T,"paddingAngle",0):0;if(A){var R=t0(A.endAngle-A.startAngle,T.endAngle-T.startAngle),z=ed(ed({},T),{},{startAngle:k+D,endAngle:k+R(_)+D});b.push(z),k=z.endAngle}else{var O=T.endAngle,$=T.startAngle,ee=t0(0,O-$),Z=ee(_),J=ed(ed({},T),{},{startAngle:k+D,endAngle:k+Z+D});b.push(J),k=J.endAngle}}),Nt.createElement($l,null,n.renderSectorsStatically(b))})}},{key:"attachKeyboardHandlers",value:function(n){var a=this;n.onkeydown=function(i){if(!i.altKey)switch(i.key){case"ArrowLeft":{var l=++a.state.sectorToFocus%a.sectorRefs.length;a.sectorRefs[l].focus(),a.setState({sectorToFocus:l});break}case"ArrowRight":{var o=--a.state.sectorToFocus<0?a.sectorRefs.length-1:a.state.sectorToFocus%a.sectorRefs.length;a.sectorRefs[o].focus(),a.setState({sectorToFocus:o});break}case"Escape":{a.sectorRefs[a.state.sectorToFocus].blur(),a.setState({sectorToFocus:0});break}}}}},{key:"renderSectors",value:function(){var n=this.props,a=n.sectors,i=n.isAnimationActive,l=this.state.prevSectors;return i&&a&&a.length&&(!l||!Iz(l,a))?this.renderSectorsWithAnimation():this.renderSectorsStatically(a)}},{key:"componentDidMount",value:function(){this.pieRef&&this.attachKeyboardHandlers(this.pieRef)}},{key:"render",value:function(){var n=this,a=this.props,i=a.hide,l=a.sectors,o=a.className,c=a.label,d=a.cx,h=a.cy,m=a.innerRadius,p=a.outerRadius,x=a.isAnimationActive,y=this.state.isAnimationFinished;if(i||!l||!l.length||!Kn(d)||!Kn(h)||!Kn(m)||!Kn(p))return null;var _=jo("recharts-pie",o);return Nt.createElement($l,{tabIndex:this.props.rootTabIndex,className:_,ref:function(j){n.pieRef=j}},this.renderSectors(),c&&this.renderLabels(l),Xm.renderCallByParent(this.props,null,!1),(!x||y)&&Q2.renderCallByParent(this.props,l,!1))}}],[{key:"getDerivedStateFromProps",value:function(n,a){return a.prevIsAnimationActive!==n.isAnimationActive?{prevIsAnimationActive:n.isAnimationActive,prevAnimationId:n.animationId,curSectors:n.sectors,prevSectors:[],isAnimationFinished:!0}:n.isAnimationActive&&n.animationId!==a.prevAnimationId?{prevAnimationId:n.animationId,curSectors:n.sectors,prevSectors:a.curSectors,isAnimationFinished:!0}:n.sectors!==a.curSectors?{curSectors:n.sectors,isAnimationFinished:!0}:null}},{key:"getTextAnchor",value:function(n,a){return n>a?"start":n=360?k:k-1)*c,E=b-k*x-T,A=a.reduce(function(z,O){var $=dm(O,j,0);return z+(Kn($)?$:0)},0),D;if(A>0){var R;D=a.map(function(z,O){var $=dm(z,j,0),ee=dm(z,h,O),Z=(Kn($)?$:0)/A,J;O?J=R.endAngle+gg(_)*c*($!==0?1:0):J=l;var K=J+gg(_)*(($!==0?x:0)+Z*E),re=(J+K)/2,ie=(y.innerRadius+y.outerRadius)/2,ce=[{name:ee,value:$,payload:z,dataKey:j,type:p}],ne=id(y.cx,y.cy,ie,re);return R=ed(ed(ed({percent:Z,cornerRadius:i,name:ee,tooltipPayload:ce,midAngle:re,middleRadius:ie,tooltipPosition:ne},z),y),{},{value:dm(z,j),startAngle:J,endAngle:K,payload:z,paddingAngle:gg(_)*c}),R})}return ed(ed({},y),{},{sectors:D,data:a})});var WTs=Math.ceil,KTs=Math.max;function YTs(s,t,r,n){for(var a=-1,i=KTs(WTs((t-s)/(r||1)),0),l=Array(i);i--;)l[n?i:++a]=s,s+=r;return l}var ZTs=YTs,XTs=sft,RVe=1/0,QTs=17976931348623157e292;function JTs(s){if(!s)return s===0?s:0;if(s=XTs(s),s===RVe||s===-RVe){var t=s<0?-1:1;return t*QTs}return s===s?s:0}var Bpt=JTs,eEs=ZTs,tEs=l0e,rwe=Bpt;function sEs(s){return function(t,r,n){return n&&typeof n!="number"&&tEs(t,r,n)&&(r=n=void 0),t=rwe(t),r===void 0?(r=t,t=0):r=rwe(r),n=n===void 0?t0&&n.handleDrag(a.changedTouches[0])}),Wx(n,"handleDragEnd",function(){n.setState({isTravellerMoving:!1,isSlideMoving:!1},function(){var a=n.props,i=a.endIndex,l=a.onDragEnd,o=a.startIndex;l==null||l({endIndex:i,startIndex:o})}),n.detachDragEndListener()}),Wx(n,"handleLeaveWrapper",function(){(n.state.isTravellerMoving||n.state.isSlideMoving)&&(n.leaveTimer=window.setTimeout(n.handleDragEnd,n.props.leaveTimeOut))}),Wx(n,"handleEnterSlideOrTraveller",function(){n.setState({isTextActive:!0})}),Wx(n,"handleLeaveSlideOrTraveller",function(){n.setState({isTextActive:!1})}),Wx(n,"handleSlideDragStart",function(a){var i=$Ve(a)?a.changedTouches[0]:a;n.setState({isTravellerMoving:!1,isSlideMoving:!0,slideMoveStartX:i.pageX}),n.attachDragEndListener()}),n.travellerDragStartHandlers={startX:n.handleTravellerDragStart.bind(n,"startX"),endX:n.handleTravellerDragStart.bind(n,"endX")},n.state={},n}return gEs(t,s),hEs(t,[{key:"componentWillUnmount",value:function(){this.leaveTimer&&(clearTimeout(this.leaveTimer),this.leaveTimer=null),this.detachDragEndListener()}},{key:"getIndex",value:function(n){var a=n.startX,i=n.endX,l=this.state.scaleValues,o=this.props,c=o.gap,d=o.data,h=d.length-1,m=Math.min(a,i),p=Math.max(a,i),x=t.getIndexInRange(l,m),y=t.getIndexInRange(l,p);return{startIndex:x-x%c,endIndex:y===h?h:y-y%c}}},{key:"getTextOfTick",value:function(n){var a=this.props,i=a.data,l=a.tickFormatter,o=a.dataKey,c=dm(i[n],o,n);return no(l)?l(c,n):c}},{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 a=this.state,i=a.slideMoveStartX,l=a.startX,o=a.endX,c=this.props,d=c.x,h=c.width,m=c.travellerWidth,p=c.startIndex,x=c.endIndex,y=c.onChange,_=n.pageX-i;_>0?_=Math.min(_,d+h-m-o,d+h-m-l):_<0&&(_=Math.max(_,d-l,d-o));var b=this.getIndex({startX:l+_,endX:o+_});(b.startIndex!==p||b.endIndex!==x)&&y&&y(b),this.setState({startX:l+_,endX:o+_,slideMoveStartX:n.pageX})}},{key:"handleTravellerDragStart",value:function(n,a){var i=$Ve(a)?a.changedTouches[0]:a;this.setState({isSlideMoving:!1,isTravellerMoving:!0,movingTravellerId:n,brushMoveStartX:i.pageX}),this.attachDragEndListener()}},{key:"handleTravellerMove",value:function(n){var a=this.state,i=a.brushMoveStartX,l=a.movingTravellerId,o=a.endX,c=a.startX,d=this.state[l],h=this.props,m=h.x,p=h.width,x=h.travellerWidth,y=h.onChange,_=h.gap,b=h.data,j={startX:this.state.startX,endX:this.state.endX},k=n.pageX-i;k>0?k=Math.min(k,m+p-x-d):k<0&&(k=Math.max(k,m-d)),j[l]=d+k;var T=this.getIndex(j),E=T.startIndex,A=T.endIndex,D=function(){var z=b.length-1;return l==="startX"&&(o>c?E%_===0:A%_===0)||oc?A%_===0:E%_===0)||o>c&&A===z};this.setState(Wx(Wx({},l,d+k),"brushMoveStartX",n.pageX),function(){y&&D()&&y(T)})}},{key:"handleTravellerMoveKeyboard",value:function(n,a){var i=this,l=this.state,o=l.scaleValues,c=l.startX,d=l.endX,h=this.state[a],m=o.indexOf(h);if(m!==-1){var p=m+n;if(!(p===-1||p>=o.length)){var x=o[p];a==="startX"&&x>=d||a==="endX"&&x<=c||this.setState(Wx({},a,x),function(){i.props.onChange(i.getIndex({startX:i.state.startX,endX:i.state.endX}))})}}}},{key:"renderBackground",value:function(){var n=this.props,a=n.x,i=n.y,l=n.width,o=n.height,c=n.fill,d=n.stroke;return Nt.createElement("rect",{stroke:d,fill:c,x:a,y:i,width:l,height:o})}},{key:"renderPanorama",value:function(){var n=this.props,a=n.x,i=n.y,l=n.width,o=n.height,c=n.data,d=n.children,h=n.padding,m=S.Children.only(d);return m?Nt.cloneElement(m,{x:a,y:i,width:l,height:o,margin:h,compact:!0,data:c}):null}},{key:"renderTravellerLayer",value:function(n,a){var i,l,o=this,c=this.props,d=c.y,h=c.travellerWidth,m=c.height,p=c.traveller,x=c.ariaLabel,y=c.data,_=c.startIndex,b=c.endIndex,j=Math.max(n,this.props.x),k=nwe(nwe({},Li(this.props,!1)),{},{x:j,y:d,width:h,height:m}),T=x||"Min value: ".concat((i=y[_])===null||i===void 0?void 0:i.name,", Max value: ").concat((l=y[b])===null||l===void 0?void 0:l.name);return Nt.createElement($l,{tabIndex:0,role:"slider","aria-label":T,"aria-valuenow":n,className:"recharts-brush-traveller",onMouseEnter:this.handleEnterSlideOrTraveller,onMouseLeave:this.handleLeaveSlideOrTraveller,onMouseDown:this.travellerDragStartHandlers[a],onTouchStart:this.travellerDragStartHandlers[a],onKeyDown:function(A){["ArrowLeft","ArrowRight"].includes(A.key)&&(A.preventDefault(),A.stopPropagation(),o.handleTravellerMoveKeyboard(A.key==="ArrowRight"?1:-1,a))},onFocus:function(){o.setState({isTravellerFocused:!0})},onBlur:function(){o.setState({isTravellerFocused:!1})},style:{cursor:"col-resize"}},t.renderTraveller(p,k))}},{key:"renderSlide",value:function(n,a){var i=this.props,l=i.y,o=i.height,c=i.stroke,d=i.travellerWidth,h=Math.min(n,a)+d,m=Math.max(Math.abs(a-n)-d,0);return Nt.createElement("rect",{className:"recharts-brush-slide",onMouseEnter:this.handleEnterSlideOrTraveller,onMouseLeave:this.handleLeaveSlideOrTraveller,onMouseDown:this.handleSlideDragStart,onTouchStart:this.handleSlideDragStart,style:{cursor:"move"},stroke:"none",fill:c,fillOpacity:.2,x:h,y:l,width:m,height:o})}},{key:"renderText",value:function(){var n=this.props,a=n.startIndex,i=n.endIndex,l=n.y,o=n.height,c=n.travellerWidth,d=n.stroke,h=this.state,m=h.startX,p=h.endX,x=5,y={pointerEvents:"none",fill:d};return Nt.createElement($l,{className:"recharts-brush-texts"},Nt.createElement(CA,Gfe({textAnchor:"end",verticalAnchor:"middle",x:Math.min(m,p)-x,y:l+o/2},y),this.getTextOfTick(a)),Nt.createElement(CA,Gfe({textAnchor:"start",verticalAnchor:"middle",x:Math.max(m,p)+c+x,y:l+o/2},y),this.getTextOfTick(i)))}},{key:"render",value:function(){var n=this.props,a=n.data,i=n.className,l=n.children,o=n.x,c=n.y,d=n.width,h=n.height,m=n.alwaysShowText,p=this.state,x=p.startX,y=p.endX,_=p.isTextActive,b=p.isSlideMoving,j=p.isTravellerMoving,k=p.isTravellerFocused;if(!a||!a.length||!Kn(o)||!Kn(c)||!Kn(d)||!Kn(h)||d<=0||h<=0)return null;var T=jo("recharts-brush",i),E=Nt.Children.count(l)===1,A=dEs("userSelect","none");return Nt.createElement($l,{className:T,onMouseLeave:this.handleLeaveWrapper,onTouchMove:this.handleTouchMove,style:A},this.renderBackground(),E&&this.renderPanorama(),this.renderSlide(x,y),this.renderTravellerLayer(x,"startX"),this.renderTravellerLayer(y,"endX"),(_||b||j||k||m)&&this.renderText())}}],[{key:"renderDefaultTraveller",value:function(n){var a=n.x,i=n.y,l=n.width,o=n.height,c=n.stroke,d=Math.floor(i+o/2)-1;return Nt.createElement(Nt.Fragment,null,Nt.createElement("rect",{x:a,y:i,width:l,height:o,fill:c,stroke:"none"}),Nt.createElement("line",{x1:a+1,y1:d,x2:a+l-1,y2:d,fill:"none",stroke:"#fff"}),Nt.createElement("line",{x1:a+1,y1:d+2,x2:a+l-1,y2:d+2,fill:"none",stroke:"#fff"}))}},{key:"renderTraveller",value:function(n,a){var i;return Nt.isValidElement(n)?i=Nt.cloneElement(n,a):no(n)?i=n(a):i=t.renderDefaultTraveller(a),i}},{key:"getDerivedStateFromProps",value:function(n,a){var i=n.data,l=n.width,o=n.x,c=n.travellerWidth,d=n.updateId,h=n.startIndex,m=n.endIndex;if(i!==a.prevData||d!==a.prevUpdateId)return nwe({prevData:i,prevTravellerWidth:c,prevUpdateId:d,prevX:o,prevWidth:l},i&&i.length?yEs({data:i,width:l,x:o,travellerWidth:c,startIndex:h,endIndex:m}):{scale:null,scaleValues:null});if(a.scale&&(l!==a.prevWidth||o!==a.prevX||c!==a.prevTravellerWidth)){a.scale.range([o,o+l-c]);var p=a.scale.domain().map(function(x){return a.scale(x)});return{prevData:i,prevTravellerWidth:c,prevUpdateId:d,prevX:o,prevWidth:l,startX:a.scale(n.startIndex),endX:a.scale(n.endIndex),scaleValues:p}}return null}},{key:"getIndexInRange",value:function(n,a){for(var i=n.length,l=0,o=i-1;o-l>1;){var c=Math.floor((l+o)/2);n[c]>a?o=c:l=c}return a>=n[o]?o:l}}])}(S.PureComponent);Wx(EL,"displayName","Brush");Wx(EL,"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 vEs=bAe;function bEs(s,t){var r;return vEs(s,function(n,a,i){return r=t(n,a,i),!r}),!!r}var _Es=bEs,wEs=Emt,jEs=Y_,NEs=_Es,kEs=gx,SEs=l0e;function CEs(s,t,r){var n=kEs(s)?wEs:NEs;return r&&SEs(s,t,r)&&(t=void 0),n(s,jEs(t))}var TEs=CEs;const EEs=ol(TEs);var S_=function(t,r){var n=t.alwaysShow,a=t.ifOverflow;return n&&(a="extendDomain"),a===r},UVe=Xmt;function AEs(s,t,r){t=="__proto__"&&UVe?UVe(s,t,{configurable:!0,enumerable:!0,value:r,writable:!0}):s[t]=r}var MEs=AEs,IEs=MEs,PEs=Ymt,LEs=Y_;function DEs(s,t){var r={};return t=LEs(t),PEs(s,function(n,a,i){IEs(r,a,t(n,a,i))}),r}var REs=DEs;const OEs=ol(REs);function FEs(s,t){for(var r=-1,n=s==null?0:s.length;++r=0)&&Object.prototype.propertyIsEnumerable.call(s,n)&&(r[n]=s[n])}return r}function tAs(s,t){if(s==null)return{};var r={};for(var n in s)if(Object.prototype.hasOwnProperty.call(s,n)){if(t.indexOf(n)>=0)continue;r[n]=s[n]}return r}function sAs(s,t){var r=s.x,n=s.y,a=eAs(s,ZEs),i="".concat(r),l=parseInt(i,10),o="".concat(n),c=parseInt(o,10),d="".concat(t.height||a.height),h=parseInt(d,10),m="".concat(t.width||a.width),p=parseInt(m,10);return QR(QR(QR(QR(QR({},t),a),l?{x:l}:{}),c?{y:c}:{}),{},{height:h,width:p,name:t.name,radius:t.radius})}function VVe(s){return Nt.createElement(Rpt,s4e({shapeType:"rectangle",propTransformer:sAs,activeClassName:"recharts-active-bar"},s))}var rAs=function(t){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;return function(n,a){if(typeof t=="number")return t;var i=Kn(n)||Ffs(n);return i?t(n,a):(i||EA(),r)}},nAs=["value","background"],Vpt;function AL(s){"@babel/helpers - typeof";return AL=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},AL(s)}function aAs(s,t){if(s==null)return{};var r=iAs(s,t),n,a;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(s);for(a=0;a=0)&&Object.prototype.propertyIsEnumerable.call(s,n)&&(r[n]=s[n])}return r}function iAs(s,t){if(s==null)return{};var r={};for(var n in s)if(Object.prototype.hasOwnProperty.call(s,n)){if(t.indexOf(n)>=0)continue;r[n]=s[n]}return r}function Kfe(){return Kfe=Object.assign?Object.assign.bind():function(s){for(var t=1;t0&&Math.abs(re)0&&Math.abs(K)0&&(J=Math.min((We||0)-(K[Ve-1]||0),J))}),Number.isFinite(J)){var re=J/Z,ie=_.layout==="vertical"?n.height:n.width;if(_.padding==="gap"&&(R=re*ie/2),_.padding==="no-gap"){var ce=xg(t.barCategoryGap,re*ie),ne=re*ie/2;R=ne-ce-(ne-ce)/ie*ce}}}a==="xAxis"?z=[n.left+(T.left||0)+(R||0),n.left+n.width-(T.right||0)-(R||0)]:a==="yAxis"?z=c==="horizontal"?[n.top+n.height-(T.bottom||0),n.top+(T.top||0)]:[n.top+(T.top||0)+(R||0),n.top+n.height-(T.bottom||0)-(R||0)]:z=_.range,A&&(z=[z[1],z[0]]);var le=cpt(_,i,p),be=le.scale,fe=le.realScaleType;be.domain(j).range(z),dpt(be);var je=upt(be,r1(r1({},_),{},{realScaleType:fe}));a==="xAxis"?(ee=b==="top"&&!E||b==="bottom"&&E,O=n.left,$=m[D]-ee*_.height):a==="yAxis"&&(ee=b==="left"&&!E||b==="right"&&E,O=m[D]-ee*_.width,$=n.top);var ve=r1(r1(r1({},_),je),{},{realScaleType:fe,x:O,y:$,scale:be,width:a==="xAxis"?n.width:_.width,height:a==="yAxis"?n.height:_.height});return ve.bandSize=Ife(ve,je),!_.hide&&a==="xAxis"?m[D]+=(ee?-1:1)*ve.height:_.hide||(m[D]+=(ee?-1:1)*ve.width),r1(r1({},x),{},C0e({},y,ve))},{})},Ypt=function(t,r){var n=t.x,a=t.y,i=r.x,l=r.y;return{x:Math.min(n,i),y:Math.min(a,l),width:Math.abs(i-n),height:Math.abs(l-a)}},xAs=function(t){var r=t.x1,n=t.y1,a=t.x2,i=t.y2;return Ypt({x:r,y:n},{x:a,y:i})},Zpt=function(){function s(t){fAs(this,s),this.scale=t}return pAs(s,[{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]:{},a=n.bandAware,i=n.position;if(r!==void 0){if(i)switch(i){case"start":return this.scale(r);case"middle":{var l=this.bandwidth?this.bandwidth()/2:0;return this.scale(r)+l}case"end":{var o=this.bandwidth?this.bandwidth():0;return this.scale(r)+o}default:return this.scale(r)}if(a){var c=this.bandwidth?this.bandwidth()/2:0;return this.scale(r)+c}return this.scale(r)}}},{key:"isInRange",value:function(r){var n=this.range(),a=n[0],i=n[n.length-1];return a<=i?r>=a&&r<=i:r>=i&&r<=a}}],[{key:"create",value:function(r){return new s(r)}}])}();C0e(Zpt,"EPS",1e-4);var YAe=function(t){var r=Object.keys(t).reduce(function(n,a){return r1(r1({},n),{},C0e({},a,Zpt.create(t[a])))},{});return r1(r1({},r),{},{apply:function(a){var i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},l=i.bandAware,o=i.position;return OEs(a,function(c,d){return r[d].apply(c,{bandAware:l,position:o})})},isInRange:function(a){return qpt(a,function(i,l){return r[l].isInRange(i)})}})};function yAs(s){return(s%180+180)%180}var vAs=function(t){var r=t.width,n=t.height,a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,i=yAs(a),l=i*Math.PI/180,o=Math.atan(n/r),c=l>o&&l-1?a[i?t[l]:l]:void 0}}var NAs=jAs,kAs=Bpt;function SAs(s){var t=kAs(s),r=t%1;return t===t?r?t-r:t:0}var CAs=SAs,TAs=qmt,EAs=Y_,AAs=CAs,MAs=Math.max;function IAs(s,t,r){var n=s==null?0:s.length;if(!n)return-1;var a=r==null?0:AAs(r);return a<0&&(a=MAs(n+a,0)),TAs(s,EAs(t),a)}var PAs=IAs,LAs=NAs,DAs=PAs,RAs=LAs(DAs),OAs=RAs;const FAs=ol(OAs);var BAs=Ums(function(s){return{x:s.left,y:s.top,width:s.width,height:s.height}},function(s){return["l",s.left,"t",s.top,"w",s.width,"h",s.height].join("")}),ZAe=S.createContext(void 0),XAe=S.createContext(void 0),Xpt=S.createContext(void 0),Qpt=S.createContext({}),Jpt=S.createContext(void 0),egt=S.createContext(0),tgt=S.createContext(0),YVe=function(t){var r=t.state,n=r.xAxisMap,a=r.yAxisMap,i=r.offset,l=t.clipPathId,o=t.children,c=t.width,d=t.height,h=BAs(i);return Nt.createElement(ZAe.Provider,{value:n},Nt.createElement(XAe.Provider,{value:a},Nt.createElement(Qpt.Provider,{value:i},Nt.createElement(Xpt.Provider,{value:h},Nt.createElement(Jpt.Provider,{value:l},Nt.createElement(egt.Provider,{value:d},Nt.createElement(tgt.Provider,{value:c},o)))))))},zAs=function(){return S.useContext(Jpt)},sgt=function(t){var r=S.useContext(ZAe);r==null&&EA();var n=r[t];return n==null&&EA(),n},$As=function(){var t=S.useContext(ZAe);return ak(t)},UAs=function(){var t=S.useContext(XAe),r=FAs(t,function(n){return qpt(n.domain,Number.isFinite)});return r||ak(t)},rgt=function(t){var r=S.useContext(XAe);r==null&&EA();var n=r[t];return n==null&&EA(),n},qAs=function(){var t=S.useContext(Xpt);return t},VAs=function(){return S.useContext(Qpt)},QAe=function(){return S.useContext(tgt)},JAe=function(){return S.useContext(egt)};function ML(s){"@babel/helpers - typeof";return ML=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},ML(s)}function HAs(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function GAs(s,t){for(var r=0;rs.length)&&(t=s.length);for(var r=0,n=new Array(t);rs*a)return!1;var i=r();return s*(t-s*i/2-n)>=0&&s*(t+s*i/2-a)<=0}function CMs(s,t){return dgt(s,t+1)}function TMs(s,t,r,n,a){for(var i=(n||[]).slice(),l=t.start,o=t.end,c=0,d=1,h=l,m=function(){var y=n==null?void 0:n[c];if(y===void 0)return{v:dgt(n,d)};var _=c,b,j=function(){return b===void 0&&(b=r(y,_)),b},k=y.coordinate,T=c===0||Jfe(s,k,j,h,o);T||(c=0,h=l,d+=1),T&&(h=k+s*(j()/2+a),c+=d)},p;d<=i.length;)if(p=m(),p)return p.v;return[]}function hB(s){"@babel/helpers - typeof";return hB=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},hB(s)}function rHe(s,t){var r=Object.keys(s);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(s);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(s,a).enumerable})),r.push.apply(r,n)}return r}function pp(s){for(var t=1;t0?x.coordinate-b*s:x.coordinate})}else i[p]=x=pp(pp({},x),{},{tickCoord:x.coordinate});var j=Jfe(s,x.tickCoord,_,o,c);j&&(c=x.tickCoord-s*(_()/2+a),i[p]=pp(pp({},x),{},{isShow:!0}))},h=l-1;h>=0;h--)d(h);return i}function PMs(s,t,r,n,a,i){var l=(n||[]).slice(),o=l.length,c=t.start,d=t.end;if(i){var h=n[o-1],m=r(h,o-1),p=s*(h.coordinate+s*m/2-d);l[o-1]=h=pp(pp({},h),{},{tickCoord:p>0?h.coordinate-p*s:h.coordinate});var x=Jfe(s,h.tickCoord,function(){return m},c,d);x&&(d=h.tickCoord-s*(m/2+a),l[o-1]=pp(pp({},h),{},{isShow:!0}))}for(var y=i?o-1:o,_=function(k){var T=l[k],E,A=function(){return E===void 0&&(E=r(T,k)),E};if(k===0){var D=s*(T.coordinate-s*A()/2-c);l[k]=T=pp(pp({},T),{},{tickCoord:D<0?T.coordinate-D*s:T.coordinate})}else l[k]=T=pp(pp({},T),{},{tickCoord:T.coordinate});var R=Jfe(s,T.tickCoord,A,c,d);R&&(c=T.tickCoord+s*(A()/2+a),l[k]=pp(pp({},T),{},{isShow:!0}))},b=0;b=2?gg(a[1].coordinate-a[0].coordinate):1,j=SMs(i,b,x);return c==="equidistantPreserveStart"?TMs(b,j,_,a,l):(c==="preserveStart"||c==="preserveStartEnd"?p=PMs(b,j,_,a,l,c==="preserveStartEnd"):p=IMs(b,j,_,a,l),p.filter(function(k){return k.isShow}))}var LMs=["viewBox"],DMs=["viewBox"],RMs=["ticks"];function LL(s){"@babel/helpers - typeof";return LL=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},LL(s)}function yI(){return yI=Object.assign?Object.assign.bind():function(s){for(var t=1;t=0)&&Object.prototype.propertyIsEnumerable.call(s,n)&&(r[n]=s[n])}return r}function OMs(s,t){if(s==null)return{};var r={};for(var n in s)if(Object.prototype.hasOwnProperty.call(s,n)){if(t.indexOf(n)>=0)continue;r[n]=s[n]}return r}function FMs(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function aHe(s,t){for(var r=0;r0?c(this.props):c(x)),l<=0||o<=0||!y||!y.length?null:Nt.createElement($l,{className:jo("recharts-cartesian-axis",d),ref:function(b){n.layerReference=b}},i&&this.renderAxisLine(),this.renderTicks(y,this.state.fontSize,this.state.letterSpacing),Xm.renderCallByParent(this.props))}}],[{key:"renderTickItem",value:function(n,a,i){var l,o=jo(a.className,"recharts-cartesian-axis-tick-value");return Nt.isValidElement(n)?l=Nt.cloneElement(n,Jh(Jh({},a),{},{className:o})):no(n)?l=n(Jh(Jh({},a),{},{className:o})):l=Nt.createElement(CA,yI({},a,{className:"recharts-cartesian-axis-tick-value"}),i),l}}])}(S.Component);rMe(U8,"displayName","CartesianAxis");rMe(U8,"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 HMs=["x1","y1","x2","y2","key"],GMs=["offset"];function AA(s){"@babel/helpers - typeof";return AA=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},AA(s)}function iHe(s,t){var r=Object.keys(s);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(s);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(s,a).enumerable})),r.push.apply(r,n)}return r}function yp(s){for(var t=1;t=0)&&Object.prototype.propertyIsEnumerable.call(s,n)&&(r[n]=s[n])}return r}function ZMs(s,t){if(s==null)return{};var r={};for(var n in s)if(Object.prototype.hasOwnProperty.call(s,n)){if(t.indexOf(n)>=0)continue;r[n]=s[n]}return r}var XMs=function(t){var r=t.fill;if(!r||r==="none")return null;var n=t.fillOpacity,a=t.x,i=t.y,l=t.width,o=t.height,c=t.ry;return Nt.createElement("rect",{x:a,y:i,ry:c,width:l,height:o,stroke:"none",fill:r,fillOpacity:n,className:"recharts-cartesian-grid-bg"})};function mgt(s,t){var r;if(Nt.isValidElement(s))r=Nt.cloneElement(s,t);else if(no(s))r=s(t);else{var n=t.x1,a=t.y1,i=t.x2,l=t.y2,o=t.key,c=oHe(t,HMs),d=Li(c,!1);d.offset;var h=oHe(d,GMs);r=Nt.createElement("line",KT({},h,{x1:n,y1:a,x2:i,y2:l,fill:"none",key:o}))}return r}function QMs(s){var t=s.x,r=s.width,n=s.horizontal,a=n===void 0?!0:n,i=s.horizontalPoints;if(!a||!i||!i.length)return null;var l=i.map(function(o,c){var d=yp(yp({},s),{},{x1:t,y1:o,x2:t+r,y2:o,key:"line-".concat(c),index:c});return mgt(a,d)});return Nt.createElement("g",{className:"recharts-cartesian-grid-horizontal"},l)}function JMs(s){var t=s.y,r=s.height,n=s.vertical,a=n===void 0?!0:n,i=s.verticalPoints;if(!a||!i||!i.length)return null;var l=i.map(function(o,c){var d=yp(yp({},s),{},{x1:o,y1:t,x2:o,y2:t+r,key:"line-".concat(c),index:c});return mgt(a,d)});return Nt.createElement("g",{className:"recharts-cartesian-grid-vertical"},l)}function e6s(s){var t=s.horizontalFill,r=s.fillOpacity,n=s.x,a=s.y,i=s.width,l=s.height,o=s.horizontalPoints,c=s.horizontal,d=c===void 0?!0:c;if(!d||!t||!t.length)return null;var h=o.map(function(p){return Math.round(p+a-a)}).sort(function(p,x){return p-x});a!==h[0]&&h.unshift(0);var m=h.map(function(p,x){var y=!h[x+1],_=y?a+l-p:h[x+1]-p;if(_<=0)return null;var b=x%t.length;return Nt.createElement("rect",{key:"react-".concat(x),y:p,x:n,height:_,width:i,stroke:"none",fill:t[b],fillOpacity:r,className:"recharts-cartesian-grid-bg"})});return Nt.createElement("g",{className:"recharts-cartesian-gridstripes-horizontal"},m)}function t6s(s){var t=s.vertical,r=t===void 0?!0:t,n=s.verticalFill,a=s.fillOpacity,i=s.x,l=s.y,o=s.width,c=s.height,d=s.verticalPoints;if(!r||!n||!n.length)return null;var h=d.map(function(p){return Math.round(p+i-i)}).sort(function(p,x){return p-x});i!==h[0]&&h.unshift(0);var m=h.map(function(p,x){var y=!h[x+1],_=y?i+o-p:h[x+1]-p;if(_<=0)return null;var b=x%n.length;return Nt.createElement("rect",{key:"react-".concat(x),x:p,y:l,width:_,height:c,stroke:"none",fill:n[b],fillOpacity:a,className:"recharts-cartesian-grid-bg"})});return Nt.createElement("g",{className:"recharts-cartesian-gridstripes-vertical"},m)}var s6s=function(t,r){var n=t.xAxis,a=t.width,i=t.height,l=t.offset;return lpt(sMe(yp(yp(yp({},U8.defaultProps),n),{},{ticks:R2(n,!0),viewBox:{x:0,y:0,width:a,height:i}})),l.left,l.left+l.width,r)},r6s=function(t,r){var n=t.yAxis,a=t.width,i=t.height,l=t.offset;return lpt(sMe(yp(yp(yp({},U8.defaultProps),n),{},{ticks:R2(n,!0),viewBox:{x:0,y:0,width:a,height:i}})),l.top,l.top+l.height,r)},C6={horizontal:!0,vertical:!0,horizontalPoints:[],verticalPoints:[],stroke:"#ccc",fill:"none",verticalFill:[],horizontalFill:[]};function fgt(s){var t,r,n,a,i,l,o=QAe(),c=JAe(),d=VAs(),h=yp(yp({},s),{},{stroke:(t=s.stroke)!==null&&t!==void 0?t:C6.stroke,fill:(r=s.fill)!==null&&r!==void 0?r:C6.fill,horizontal:(n=s.horizontal)!==null&&n!==void 0?n:C6.horizontal,horizontalFill:(a=s.horizontalFill)!==null&&a!==void 0?a:C6.horizontalFill,vertical:(i=s.vertical)!==null&&i!==void 0?i:C6.vertical,verticalFill:(l=s.verticalFill)!==null&&l!==void 0?l:C6.verticalFill,x:Kn(s.x)?s.x:d.left,y:Kn(s.y)?s.y:d.top,width:Kn(s.width)?s.width:d.width,height:Kn(s.height)?s.height:d.height}),m=h.x,p=h.y,x=h.width,y=h.height,_=h.syncWithTicks,b=h.horizontalValues,j=h.verticalValues,k=$As(),T=UAs();if(!Kn(x)||x<=0||!Kn(y)||y<=0||!Kn(m)||m!==+m||!Kn(p)||p!==+p)return null;var E=h.verticalCoordinatesGenerator||s6s,A=h.horizontalCoordinatesGenerator||r6s,D=h.horizontalPoints,R=h.verticalPoints;if((!D||!D.length)&&no(A)){var z=b&&b.length,O=A({yAxis:T?yp(yp({},T),{},{ticks:z?b:T.ticks}):void 0,width:o,height:c,offset:d},z?!0:_);S1(Array.isArray(O),"horizontalCoordinatesGenerator should return Array but instead it returned [".concat(AA(O),"]")),Array.isArray(O)&&(D=O)}if((!R||!R.length)&&no(E)){var $=j&&j.length,ee=E({xAxis:k?yp(yp({},k),{},{ticks:$?j:k.ticks}):void 0,width:o,height:c,offset:d},$?!0:_);S1(Array.isArray(ee),"verticalCoordinatesGenerator should return Array but instead it returned [".concat(AA(ee),"]")),Array.isArray(ee)&&(R=ee)}return Nt.createElement("g",{className:"recharts-cartesian-grid"},Nt.createElement(XMs,{fill:h.fill,fillOpacity:h.fillOpacity,x:h.x,y:h.y,width:h.width,height:h.height,ry:h.ry}),Nt.createElement(QMs,KT({},h,{offset:d,horizontalPoints:D,xAxis:k,yAxis:T})),Nt.createElement(JMs,KT({},h,{offset:d,verticalPoints:R,xAxis:k,yAxis:T})),Nt.createElement(e6s,KT({},h,{horizontalPoints:D})),Nt.createElement(t6s,KT({},h,{verticalPoints:R})))}fgt.displayName="CartesianGrid";var n6s=["type","layout","connectNulls","ref"],a6s=["key"];function DL(s){"@babel/helpers - typeof";return DL=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},DL(s)}function lHe(s,t){if(s==null)return{};var r=i6s(s,t),n,a;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(s);for(a=0;a=0)&&Object.prototype.propertyIsEnumerable.call(s,n)&&(r[n]=s[n])}return r}function i6s(s,t){if(s==null)return{};var r={};for(var n in s)if(Object.prototype.hasOwnProperty.call(s,n)){if(t.indexOf(n)>=0)continue;r[n]=s[n]}return r}function C7(){return C7=Object.assign?Object.assign.bind():function(s){for(var t=1;ts.length)&&(t=s.length);for(var r=0,n=new Array(t);rm){x=[].concat(T6(c.slice(0,y)),[m-_]);break}var b=x.length%2===0?[0,p]:[p];return[].concat(T6(t.repeat(c,h)),T6(x),b).map(function(j){return"".concat(j,"px")}).join(", ")}),n1(r,"id",L8("recharts-line-")),n1(r,"pathRef",function(l){r.mainCurve=l}),n1(r,"handleAnimationEnd",function(){r.setState({isAnimationFinished:!0}),r.props.onAnimationEnd&&r.props.onAnimationEnd()}),n1(r,"handleAnimationStart",function(){r.setState({isAnimationFinished:!1}),r.props.onAnimationStart&&r.props.onAnimationStart()}),r}return g6s(t,s),h6s(t,[{key:"componentDidMount",value:function(){if(this.props.isAnimationActive){var n=this.getTotalLength();this.setState({totalLength:n})}}},{key:"componentDidUpdate",value:function(){if(this.props.isAnimationActive){var n=this.getTotalLength();n!==this.state.totalLength&&this.setState({totalLength:n})}}},{key:"getTotalLength",value:function(){var n=this.mainCurve;try{return n&&n.getTotalLength&&n.getTotalLength()||0}catch{return 0}}},{key:"renderErrorBar",value:function(n,a){if(this.props.isAnimationActive&&!this.state.isAnimationFinished)return null;var i=this.props,l=i.points,o=i.xAxis,c=i.yAxis,d=i.layout,h=i.children,m=v0(h,Pz);if(!m)return null;var p=function(_,b){return{x:_.x,y:_.y,value:_.value,errorVal:dm(_.payload,b)}},x={clipPath:n?"url(#clipPath-".concat(a,")"):null};return Nt.createElement($l,x,m.map(function(y){return Nt.cloneElement(y,{key:"bar-".concat(y.props.dataKey),data:l,xAxis:o,yAxis:c,layout:d,dataPointFormatter:p})}))}},{key:"renderDots",value:function(n,a,i){var l=this.props.isAnimationActive;if(l&&!this.state.isAnimationFinished)return null;var o=this.props,c=o.dot,d=o.points,h=o.dataKey,m=Li(this.props,!1),p=Li(c,!0),x=d.map(function(_,b){var j=Vx(Vx(Vx({key:"dot-".concat(b),r:3},m),p),{},{index:b,cx:_.x,cy:_.y,value:_.value,dataKey:h,payload:_.payload,points:d});return t.renderDotItem(c,j)}),y={clipPath:n?"url(#clipPath-".concat(a?"":"dots-").concat(i,")"):null};return Nt.createElement($l,C7({className:"recharts-line-dots",key:"dots"},y),x)}},{key:"renderCurveStatically",value:function(n,a,i,l){var o=this.props,c=o.type,d=o.layout,h=o.connectNulls;o.ref;var m=lHe(o,n6s),p=Vx(Vx(Vx({},Li(m,!0)),{},{fill:"none",className:"recharts-line-curve",clipPath:a?"url(#clipPath-".concat(i,")"):null,points:n},l),{},{type:c,layout:d,connectNulls:h});return Nt.createElement(Dfe,C7({},p,{pathRef:this.pathRef}))}},{key:"renderCurveWithAnimation",value:function(n,a){var i=this,l=this.props,o=l.points,c=l.strokeDasharray,d=l.isAnimationActive,h=l.animationBegin,m=l.animationDuration,p=l.animationEasing,x=l.animationId,y=l.animateNewValues,_=l.width,b=l.height,j=this.state,k=j.prevPoints,T=j.totalLength;return Nt.createElement(O_,{begin:h,duration:m,isActive:d,easing:p,from:{t:0},to:{t:1},key:"line-".concat(x),onAnimationEnd:this.handleAnimationEnd,onAnimationStart:this.handleAnimationStart},function(E){var A=E.t;if(k){var D=k.length/o.length,R=o.map(function(Z,J){var K=Math.floor(J*D);if(k[K]){var re=k[K],ie=t0(re.x,Z.x),ce=t0(re.y,Z.y);return Vx(Vx({},Z),{},{x:ie(A),y:ce(A)})}if(y){var ne=t0(_*2,Z.x),le=t0(b/2,Z.y);return Vx(Vx({},Z),{},{x:ne(A),y:le(A)})}return Vx(Vx({},Z),{},{x:Z.x,y:Z.y})});return i.renderCurveStatically(R,n,a)}var z=t0(0,T),O=z(A),$;if(c){var ee="".concat(c).split(/[,\s]+/gim).map(function(Z){return parseFloat(Z)});$=i.getStrokeDasharray(O,T,ee)}else $=i.generateSimpleStrokeDasharray(T,O);return i.renderCurveStatically(o,n,a,{strokeDasharray:$})})}},{key:"renderCurve",value:function(n,a){var i=this.props,l=i.points,o=i.isAnimationActive,c=this.state,d=c.prevPoints,h=c.totalLength;return o&&l&&l.length&&(!d&&h>0||!Iz(d,l))?this.renderCurveWithAnimation(n,a):this.renderCurveStatically(l,n,a)}},{key:"render",value:function(){var n,a=this.props,i=a.hide,l=a.dot,o=a.points,c=a.className,d=a.xAxis,h=a.yAxis,m=a.top,p=a.left,x=a.width,y=a.height,_=a.isAnimationActive,b=a.id;if(i||!o||!o.length)return null;var j=this.state.isAnimationFinished,k=o.length===1,T=jo("recharts-line",c),E=d&&d.allowDataOverflow,A=h&&h.allowDataOverflow,D=E||A,R=yo(b)?this.id:b,z=(n=Li(l,!1))!==null&&n!==void 0?n:{r:3,strokeWidth:2},O=z.r,$=O===void 0?3:O,ee=z.strokeWidth,Z=ee===void 0?2:ee,J=Zfs(l)?l:{},K=J.clipDot,re=K===void 0?!0:K,ie=$*2+Z;return Nt.createElement($l,{className:T},E||A?Nt.createElement("defs",null,Nt.createElement("clipPath",{id:"clipPath-".concat(R)},Nt.createElement("rect",{x:E?p:p-x/2,y:A?m:m-y/2,width:E?x:x*2,height:A?y:y*2})),!re&&Nt.createElement("clipPath",{id:"clipPath-dots-".concat(R)},Nt.createElement("rect",{x:p-ie/2,y:m-ie/2,width:x+ie,height:y+ie}))):null,!k&&this.renderCurve(D,R),this.renderErrorBar(D,R),(k||l)&&this.renderDots(D,re,R),(!_||j)&&Q2.renderCallByParent(this.props,o))}}],[{key:"getDerivedStateFromProps",value:function(n,a){return n.animationId!==a.prevAnimationId?{prevAnimationId:n.animationId,curPoints:n.points,prevPoints:a.curPoints}:n.points!==a.curPoints?{curPoints:n.points}:null}},{key:"repeat",value:function(n,a){for(var i=n.length%2!==0?[].concat(T6(n),[0]):n,l=[],o=0;os.length)&&(t=s.length);for(var r=0,n=new Array(t);r=0)&&Object.prototype.propertyIsEnumerable.call(s,n)&&(r[n]=s[n])}return r}function aIs(s,t){if(s==null)return{};var r={};for(var n in s)if(Object.prototype.hasOwnProperty.call(s,n)){if(t.indexOf(n)>=0)continue;r[n]=s[n]}return r}function iIs(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function oIs(s,t){for(var r=0;rs.length)&&(t=s.length);for(var r=0,n=new Array(t);r0?l:t&&t.length&&Kn(a)&&Kn(i)?t.slice(a,i+1):[]};function Agt(s){return s==="number"?[0,"auto"]:void 0}var _4e=function(t,r,n,a){var i=t.graphicalItems,l=t.tooltipAxis,o=I0e(r,t);return n<0||!i||!i.length||n>=o.length?null:i.reduce(function(c,d){var h,m=(h=d.props.data)!==null&&h!==void 0?h:r;m&&t.dataStartIndex+t.dataEndIndex!==0&&t.dataEndIndex-t.dataStartIndex>=n&&(m=m.slice(t.dataStartIndex,t.dataEndIndex+1));var p;if(l.dataKey&&!l.allowDuplicatedCategory){var x=m===void 0?o:m;p=nfe(x,l.dataKey,a)}else p=m&&m[n]||o[n];return p?[].concat(BL(c),[mpt(d,p)]):c},[])},gHe=function(t,r,n,a){var i=a||{x:t.chartX,y:t.chartY},l=vIs(i,n),o=t.orderedTooltipTicks,c=t.tooltipAxis,d=t.tooltipTicks,h=XSs(l,o,d,c);if(h>=0&&d){var m=d[h]&&d[h].value,p=_4e(t,r,h,m),x=bIs(n,o,h,i);return{activeTooltipIndex:h,activeLabel:m,activePayload:p,activeCoordinate:x}}return null},_Is=function(t,r){var n=r.axes,a=r.graphicalItems,i=r.axisType,l=r.axisIdKey,o=r.stackGroups,c=r.dataStartIndex,d=r.dataEndIndex,h=t.layout,m=t.children,p=t.stackOffset,x=opt(h,i);return n.reduce(function(y,_){var b,j=_.type.defaultProps!==void 0?Xr(Xr({},_.type.defaultProps),_.props):_.props,k=j.type,T=j.dataKey,E=j.allowDataOverflow,A=j.allowDuplicatedCategory,D=j.scale,R=j.ticks,z=j.includeHidden,O=j[l];if(y[O])return y;var $=I0e(t.data,{graphicalItems:a.filter(function(je){var ve,We=l in je.props?je.props[l]:(ve=je.type.defaultProps)===null||ve===void 0?void 0:ve[l];return We===O}),dataStartIndex:c,dataEndIndex:d}),ee=$.length,Z,J,K;W6s(j.domain,E,k)&&(Z=DSe(j.domain,null,E),x&&(k==="number"||D!=="auto")&&(K=j7($,T,"category")));var re=Agt(k);if(!Z||Z.length===0){var ie,ce=(ie=j.domain)!==null&&ie!==void 0?ie:re;if(T){if(Z=j7($,T,k),k==="category"&&x){var ne=zfs(Z);A&&ne?(J=Z,Z=Hfe(0,ee)):A||(Z=Fqe(ce,Z,_).reduce(function(je,ve){return je.indexOf(ve)>=0?je:[].concat(BL(je),[ve])},[]))}else if(k==="category")A?Z=Z.filter(function(je){return je!==""&&!yo(je)}):Z=Fqe(ce,Z,_).reduce(function(je,ve){return je.indexOf(ve)>=0||ve===""||yo(ve)?je:[].concat(BL(je),[ve])},[]);else if(k==="number"){var le=s4s($,a.filter(function(je){var ve,We,Ve=l in je.props?je.props[l]:(ve=je.type.defaultProps)===null||ve===void 0?void 0:ve[l],Le="hide"in je.props?je.props.hide:(We=je.type.defaultProps)===null||We===void 0?void 0:We.hide;return Ve===O&&(z||!Le)}),T,i,h);le&&(Z=le)}x&&(k==="number"||D!=="auto")&&(K=j7($,T,"category"))}else x?Z=Hfe(0,ee):o&&o[O]&&o[O].hasStack&&k==="number"?Z=p==="expand"?[0,1]:hpt(o[O].stackGroups,c,d):Z=ipt($,a.filter(function(je){var ve=l in je.props?je.props[l]:je.type.defaultProps[l],We="hide"in je.props?je.props.hide:je.type.defaultProps.hide;return ve===O&&(z||!We)}),k,h,!0);if(k==="number")Z=y4e(m,Z,O,i,R),ce&&(Z=DSe(ce,Z,E));else if(k==="category"&&ce){var be=ce,fe=Z.every(function(je){return be.indexOf(je)>=0});fe&&(Z=be)}}return Xr(Xr({},y),{},Ui({},O,Xr(Xr({},j),{},{axisType:i,domain:Z,categoricalDomain:K,duplicateDomain:J,originalDomain:(b=j.domain)!==null&&b!==void 0?b:re,isCategorical:x,layout:h})))},{})},wIs=function(t,r){var n=r.graphicalItems,a=r.Axis,i=r.axisType,l=r.axisIdKey,o=r.stackGroups,c=r.dataStartIndex,d=r.dataEndIndex,h=t.layout,m=t.children,p=I0e(t.data,{graphicalItems:n,dataStartIndex:c,dataEndIndex:d}),x=p.length,y=opt(h,i),_=-1;return n.reduce(function(b,j){var k=j.type.defaultProps!==void 0?Xr(Xr({},j.type.defaultProps),j.props):j.props,T=k[l],E=Agt("number");if(!b[T]){_++;var A;return y?A=Hfe(0,x):o&&o[T]&&o[T].hasStack?(A=hpt(o[T].stackGroups,c,d),A=y4e(m,A,T,i)):(A=DSe(E,ipt(p,n.filter(function(D){var R,z,O=l in D.props?D.props[l]:(R=D.type.defaultProps)===null||R===void 0?void 0:R[l],$="hide"in D.props?D.props.hide:(z=D.type.defaultProps)===null||z===void 0?void 0:z.hide;return O===T&&!$}),"number",h),a.defaultProps.allowDataOverflow),A=y4e(m,A,T,i)),Xr(Xr({},b),{},Ui({},T,Xr(Xr({axisType:i},a.defaultProps),{},{hide:!0,orientation:y0(xIs,"".concat(i,".").concat(_%2),null),domain:A,originalDomain:E,isCategorical:y,layout:h})))}return b},{})},jIs=function(t,r){var n=r.axisType,a=n===void 0?"xAxis":n,i=r.AxisComp,l=r.graphicalItems,o=r.stackGroups,c=r.dataStartIndex,d=r.dataEndIndex,h=t.children,m="".concat(a,"Id"),p=v0(h,i),x={};return p&&p.length?x=_Is(t,{axes:p,graphicalItems:l,axisType:a,axisIdKey:m,stackGroups:o,dataStartIndex:c,dataEndIndex:d}):l&&l.length&&(x=wIs(t,{Axis:i,graphicalItems:l,axisType:a,axisIdKey:m,stackGroups:o,dataStartIndex:c,dataEndIndex:d})),x},NIs=function(t){var r=ak(t),n=R2(r,!1,!0);return{tooltipTicks:n,orderedTooltipTicks:_Ae(n,function(a){return a.coordinate}),tooltipAxis:r,tooltipAxisBandSize:Ife(r,n)}},xHe=function(t){var r=t.children,n=t.defaultShowTooltip,a=Xx(r,EL),i=0,l=0;return t.data&&t.data.length!==0&&(l=t.data.length-1),a&&a.props&&(a.props.startIndex>=0&&(i=a.props.startIndex),a.props.endIndex>=0&&(l=a.props.endIndex)),{chartX:0,chartY:0,dataStartIndex:i,dataEndIndex:l,activeTooltipIndex:-1,isTooltipActive:!!n}},kIs=function(t){return!t||!t.length?!1:t.some(function(r){var n=Z2(r&&r.type);return n&&n.indexOf("Bar")>=0})},yHe=function(t){return t==="horizontal"?{numericAxisName:"yAxis",cateAxisName:"xAxis"}:t==="vertical"?{numericAxisName:"xAxis",cateAxisName:"yAxis"}:t==="centric"?{numericAxisName:"radiusAxis",cateAxisName:"angleAxis"}:{numericAxisName:"angleAxis",cateAxisName:"radiusAxis"}},SIs=function(t,r){var n=t.props,a=t.graphicalItems,i=t.xAxisMap,l=i===void 0?{}:i,o=t.yAxisMap,c=o===void 0?{}:o,d=n.width,h=n.height,m=n.children,p=n.margin||{},x=Xx(m,EL),y=Xx(m,pP),_=Object.keys(c).reduce(function(A,D){var R=c[D],z=R.orientation;return!R.mirror&&!R.hide?Xr(Xr({},A),{},Ui({},z,A[z]+R.width)):A},{left:p.left||0,right:p.right||0}),b=Object.keys(l).reduce(function(A,D){var R=l[D],z=R.orientation;return!R.mirror&&!R.hide?Xr(Xr({},A),{},Ui({},z,y0(A,"".concat(z))+R.height)):A},{top:p.top||0,bottom:p.bottom||0}),j=Xr(Xr({},b),_),k=j.bottom;x&&(j.bottom+=x.props.height||EL.defaultProps.height),y&&r&&(j=e4s(j,a,n,r));var T=d-j.left-j.right,E=h-j.top-j.bottom;return Xr(Xr({brushBottom:k},j),{},{width:Math.max(T,0),height:Math.max(E,0)})},CIs=function(t,r){if(r==="xAxis")return t[r].width;if(r==="yAxis")return t[r].height},nMe=function(t){var r=t.chartName,n=t.GraphicalChild,a=t.defaultTooltipEventType,i=a===void 0?"axis":a,l=t.validateTooltipEventTypes,o=l===void 0?["axis"]:l,c=t.axisComponents,d=t.legendContent,h=t.formatAxisMap,m=t.defaultProps,p=function(j,k){var T=k.graphicalItems,E=k.stackGroups,A=k.offset,D=k.updateId,R=k.dataStartIndex,z=k.dataEndIndex,O=j.barSize,$=j.layout,ee=j.barGap,Z=j.barCategoryGap,J=j.maxBarSize,K=yHe($),re=K.numericAxisName,ie=K.cateAxisName,ce=kIs(T),ne=[];return T.forEach(function(le,be){var fe=I0e(j.data,{graphicalItems:[le],dataStartIndex:R,dataEndIndex:z}),je=le.type.defaultProps!==void 0?Xr(Xr({},le.type.defaultProps),le.props):le.props,ve=je.dataKey,We=je.maxBarSize,Ve=je["".concat(re,"Id")],Le=je["".concat(ie,"Id")],Me={},ze=c.reduce(function(it,Je){var st=k["".concat(Je.axisType,"Map")],mt=je["".concat(Je.axisType,"Id")];st&&st[mt]||Je.axisType==="zAxis"||EA();var wt=st[mt];return Xr(Xr({},it),{},Ui(Ui({},Je.axisType,wt),"".concat(Je.axisType,"Ticks"),R2(wt)))},Me),Pe=ze[ie],Ie=ze["".concat(ie,"Ticks")],De=E&&E[Ve]&&E[Ve].hasStack&&u4s(le,E[Ve].stackGroups),pe=Z2(le.type).indexOf("Bar")>=0,tt=Ife(Pe,Ie),ge=[],ct=ce&&QSs({barSize:O,stackGroups:E,totalSize:CIs(ze,ie)});if(pe){var Ue,et,Qe=yo(We)?J:We,Ne=(Ue=(et=Ife(Pe,Ie,!0))!==null&&et!==void 0?et:Qe)!==null&&Ue!==void 0?Ue:0;ge=JSs({barGap:ee,barCategoryGap:Z,bandSize:Ne!==tt?Ne:tt,sizeList:ct[Le],maxBarSize:Qe}),Ne!==tt&&(ge=ge.map(function(it){return Xr(Xr({},it),{},{position:Xr(Xr({},it.position),{},{offset:it.position.offset-Ne/2})})}))}var $e=le&&le.type&&le.type.getComposedData;$e&&ne.push({props:Xr(Xr({},$e(Xr(Xr({},ze),{},{displayedData:fe,props:j,dataKey:ve,item:le,bandSize:tt,barPosition:ge,offset:A,stackedData:De,layout:$,dataStartIndex:R,dataEndIndex:z}))),{},Ui(Ui(Ui({key:le.key||"item-".concat(be)},re,ze[re]),ie,ze[ie]),"animationId",D)),childIndex:Jfs(le,j.children),item:le})}),ne},x=function(j,k){var T=j.props,E=j.dataStartIndex,A=j.dataEndIndex,D=j.updateId;if(!M$e({props:T}))return null;var R=T.children,z=T.layout,O=T.stackOffset,$=T.data,ee=T.reverseStackOrder,Z=yHe(z),J=Z.numericAxisName,K=Z.cateAxisName,re=v0(R,n),ie=c4s($,re,"".concat(J,"Id"),"".concat(K,"Id"),O,ee),ce=c.reduce(function(je,ve){var We="".concat(ve.axisType,"Map");return Xr(Xr({},je),{},Ui({},We,jIs(T,Xr(Xr({},ve),{},{graphicalItems:re,stackGroups:ve.axisType===J&&ie,dataStartIndex:E,dataEndIndex:A}))))},{}),ne=SIs(Xr(Xr({},ce),{},{props:T,graphicalItems:re}),k==null?void 0:k.legendBBox);Object.keys(ce).forEach(function(je){ce[je]=h(T,ce[je],ne,je.replace("Map",""),r)});var le=ce["".concat(K,"Map")],be=NIs(le),fe=p(T,Xr(Xr({},ce),{},{dataStartIndex:E,dataEndIndex:A,updateId:D,graphicalItems:re,stackGroups:ie,offset:ne}));return Xr(Xr({formattedGraphicalItems:fe,graphicalItems:re,offset:ne,stackGroups:ie},be),ce)},y=function(b){function j(k){var T,E,A;return iIs(this,j),A=cIs(this,j,[k]),Ui(A,"eventEmitterSymbol",Symbol("rechartsEventEmitter")),Ui(A,"accessibilityManager",new G6s),Ui(A,"handleLegendBBoxUpdate",function(D){if(D){var R=A.state,z=R.dataStartIndex,O=R.dataEndIndex,$=R.updateId;A.setState(Xr({legendBBox:D},x({props:A.props,dataStartIndex:z,dataEndIndex:O,updateId:$},Xr(Xr({},A.state),{},{legendBBox:D}))))}}),Ui(A,"handleReceiveSyncEvent",function(D,R,z){if(A.props.syncId===D){if(z===A.eventEmitterSymbol&&typeof A.props.syncMethod!="function")return;A.applySyncEvent(R)}}),Ui(A,"handleBrushChange",function(D){var R=D.startIndex,z=D.endIndex;if(R!==A.state.dataStartIndex||z!==A.state.dataEndIndex){var O=A.state.updateId;A.setState(function(){return Xr({dataStartIndex:R,dataEndIndex:z},x({props:A.props,dataStartIndex:R,dataEndIndex:z,updateId:O},A.state))}),A.triggerSyncEvent({dataStartIndex:R,dataEndIndex:z})}}),Ui(A,"handleMouseEnter",function(D){var R=A.getMouseInfo(D);if(R){var z=Xr(Xr({},R),{},{isTooltipActive:!0});A.setState(z),A.triggerSyncEvent(z);var O=A.props.onMouseEnter;no(O)&&O(z,D)}}),Ui(A,"triggeredAfterMouseMove",function(D){var R=A.getMouseInfo(D),z=R?Xr(Xr({},R),{},{isTooltipActive:!0}):{isTooltipActive:!1};A.setState(z),A.triggerSyncEvent(z);var O=A.props.onMouseMove;no(O)&&O(z,D)}),Ui(A,"handleItemMouseEnter",function(D){A.setState(function(){return{isTooltipActive:!0,activeItem:D,activePayload:D.tooltipPayload,activeCoordinate:D.tooltipPosition||{x:D.cx,y:D.cy}}})}),Ui(A,"handleItemMouseLeave",function(){A.setState(function(){return{isTooltipActive:!1}})}),Ui(A,"handleMouseMove",function(D){D.persist(),A.throttleTriggeredAfterMouseMove(D)}),Ui(A,"handleMouseLeave",function(D){A.throttleTriggeredAfterMouseMove.cancel();var R={isTooltipActive:!1};A.setState(R),A.triggerSyncEvent(R);var z=A.props.onMouseLeave;no(z)&&z(R,D)}),Ui(A,"handleOuterEvent",function(D){var R=Qfs(D),z=y0(A.props,"".concat(R));if(R&&no(z)){var O,$;/.*touch.*/i.test(R)?$=A.getMouseInfo(D.changedTouches[0]):$=A.getMouseInfo(D),z((O=$)!==null&&O!==void 0?O:{},D)}}),Ui(A,"handleClick",function(D){var R=A.getMouseInfo(D);if(R){var z=Xr(Xr({},R),{},{isTooltipActive:!0});A.setState(z),A.triggerSyncEvent(z);var O=A.props.onClick;no(O)&&O(z,D)}}),Ui(A,"handleMouseDown",function(D){var R=A.props.onMouseDown;if(no(R)){var z=A.getMouseInfo(D);R(z,D)}}),Ui(A,"handleMouseUp",function(D){var R=A.props.onMouseUp;if(no(R)){var z=A.getMouseInfo(D);R(z,D)}}),Ui(A,"handleTouchMove",function(D){D.changedTouches!=null&&D.changedTouches.length>0&&A.throttleTriggeredAfterMouseMove(D.changedTouches[0])}),Ui(A,"handleTouchStart",function(D){D.changedTouches!=null&&D.changedTouches.length>0&&A.handleMouseDown(D.changedTouches[0])}),Ui(A,"handleTouchEnd",function(D){D.changedTouches!=null&&D.changedTouches.length>0&&A.handleMouseUp(D.changedTouches[0])}),Ui(A,"handleDoubleClick",function(D){var R=A.props.onDoubleClick;if(no(R)){var z=A.getMouseInfo(D);R(z,D)}}),Ui(A,"handleContextMenu",function(D){var R=A.props.onContextMenu;if(no(R)){var z=A.getMouseInfo(D);R(z,D)}}),Ui(A,"triggerSyncEvent",function(D){A.props.syncId!==void 0&&iwe.emit(owe,A.props.syncId,D,A.eventEmitterSymbol)}),Ui(A,"applySyncEvent",function(D){var R=A.props,z=R.layout,O=R.syncMethod,$=A.state.updateId,ee=D.dataStartIndex,Z=D.dataEndIndex;if(D.dataStartIndex!==void 0||D.dataEndIndex!==void 0)A.setState(Xr({dataStartIndex:ee,dataEndIndex:Z},x({props:A.props,dataStartIndex:ee,dataEndIndex:Z,updateId:$},A.state)));else if(D.activeTooltipIndex!==void 0){var J=D.chartX,K=D.chartY,re=D.activeTooltipIndex,ie=A.state,ce=ie.offset,ne=ie.tooltipTicks;if(!ce)return;if(typeof O=="function")re=O(ne,D);else if(O==="value"){re=-1;for(var le=0;le=0){var De,pe;if(J.dataKey&&!J.allowDuplicatedCategory){var tt=typeof J.dataKey=="function"?Ie:"payload.".concat(J.dataKey.toString());De=nfe(le,tt,re),pe=be&&fe&&nfe(fe,tt,re)}else De=le==null?void 0:le[K],pe=be&&fe&&fe[K];if(Le||Ve){var ge=D.props.activeIndex!==void 0?D.props.activeIndex:K;return[S.cloneElement(D,Xr(Xr(Xr({},O.props),ze),{},{activeIndex:ge})),null,null]}if(!yo(De))return[Pe].concat(BL(A.renderActivePoints({item:O,activePoint:De,basePoint:pe,childIndex:K,isRange:be})))}else{var ct,Ue=(ct=A.getItemByXY(A.state.activeCoordinate))!==null&&ct!==void 0?ct:{graphicalItem:Pe},et=Ue.graphicalItem,Qe=et.item,Ne=Qe===void 0?D:Qe,$e=et.childIndex,it=Xr(Xr(Xr({},O.props),ze),{},{activeIndex:$e});return[S.cloneElement(Ne,it),null,null]}return be?[Pe,null,null]:[Pe,null]}),Ui(A,"renderCustomized",function(D,R,z){return S.cloneElement(D,Xr(Xr({key:"recharts-customized-".concat(z)},A.props),A.state))}),Ui(A,"renderMap",{CartesianGrid:{handler:Uq,once:!0},ReferenceArea:{handler:A.renderReferenceElement},ReferenceLine:{handler:Uq},ReferenceDot:{handler:A.renderReferenceElement},XAxis:{handler:Uq},YAxis:{handler:Uq},Brush:{handler:A.renderBrush,once:!0},Bar:{handler:A.renderGraphicChild},Line:{handler:A.renderGraphicChild},Area:{handler:A.renderGraphicChild},Radar:{handler:A.renderGraphicChild},RadialBar:{handler:A.renderGraphicChild},Scatter:{handler:A.renderGraphicChild},Pie:{handler:A.renderGraphicChild},Funnel:{handler:A.renderGraphicChild},Tooltip:{handler:A.renderCursor,once:!0},PolarGrid:{handler:A.renderPolarGrid,once:!0},PolarAngleAxis:{handler:A.renderPolarAxis},PolarRadiusAxis:{handler:A.renderPolarAxis},Customized:{handler:A.renderCustomized}}),A.clipPathId="".concat((T=k.id)!==null&&T!==void 0?T:L8("recharts"),"-clip"),A.throttleTriggeredAfterMouseMove=rft(A.triggeredAfterMouseMove,(E=k.throttleDelay)!==null&&E!==void 0?E:1e3/60),A.state={},A}return hIs(j,b),lIs(j,[{key:"componentDidMount",value:function(){var T,E;this.addListener(),this.accessibilityManager.setDetails({container:this.container,offset:{left:(T=this.props.margin.left)!==null&&T!==void 0?T:0,top:(E=this.props.margin.top)!==null&&E!==void 0?E:0},coordinateList:this.state.tooltipTicks,mouseHandlerCallback:this.triggeredAfterMouseMove,layout:this.props.layout}),this.displayDefaultTooltip()}},{key:"displayDefaultTooltip",value:function(){var T=this.props,E=T.children,A=T.data,D=T.height,R=T.layout,z=Xx(E,Zg);if(z){var O=z.props.defaultIndex;if(!(typeof O!="number"||O<0||O>this.state.tooltipTicks.length-1)){var $=this.state.tooltipTicks[O]&&this.state.tooltipTicks[O].value,ee=_4e(this.state,A,O,$),Z=this.state.tooltipTicks[O].coordinate,J=(this.state.offset.top+D)/2,K=R==="horizontal",re=K?{x:Z,y:J}:{y:Z,x:J},ie=this.state.formattedGraphicalItems.find(function(ne){var le=ne.item;return le.type.name==="Scatter"});ie&&(re=Xr(Xr({},re),ie.props.points[O].tooltipPosition),ee=ie.props.points[O].tooltipPayload);var ce={activeTooltipIndex:O,isTooltipActive:!0,activeLabel:$,activePayload:ee,activeCoordinate:re};this.setState(ce),this.renderCursor(z),this.accessibilityManager.setIndex(O)}}}},{key:"getSnapshotBeforeUpdate",value:function(T,E){if(!this.props.accessibilityLayer)return null;if(this.state.tooltipTicks!==E.tooltipTicks&&this.accessibilityManager.setDetails({coordinateList:this.state.tooltipTicks}),this.props.layout!==T.layout&&this.accessibilityManager.setDetails({layout:this.props.layout}),this.props.margin!==T.margin){var A,D;this.accessibilityManager.setDetails({offset:{left:(A=this.props.margin.left)!==null&&A!==void 0?A:0,top:(D=this.props.margin.top)!==null&&D!==void 0?D:0}})}return null}},{key:"componentDidUpdate",value:function(T){Zke([Xx(T.children,Zg)],[Xx(this.props.children,Zg)])||this.displayDefaultTooltip()}},{key:"componentWillUnmount",value:function(){this.removeListener(),this.throttleTriggeredAfterMouseMove.cancel()}},{key:"getTooltipEventType",value:function(){var T=Xx(this.props.children,Zg);if(T&&typeof T.props.shared=="boolean"){var E=T.props.shared?"axis":"item";return o.indexOf(E)>=0?E:i}return i}},{key:"getMouseInfo",value:function(T){if(!this.container)return null;var E=this.container,A=E.getBoundingClientRect(),D=k2s(A),R={chartX:Math.round(T.pageX-D.left),chartY:Math.round(T.pageY-D.top)},z=A.width/E.offsetWidth||1,O=this.inRange(R.chartX,R.chartY,z);if(!O)return null;var $=this.state,ee=$.xAxisMap,Z=$.yAxisMap,J=this.getTooltipEventType(),K=gHe(this.state,this.props.data,this.props.layout,O);if(J!=="axis"&&ee&&Z){var re=ak(ee).scale,ie=ak(Z).scale,ce=re&&re.invert?re.invert(R.chartX):null,ne=ie&&ie.invert?ie.invert(R.chartY):null;return Xr(Xr({},R),{},{xValue:ce,yValue:ne},K)}return K?Xr(Xr({},R),K):null}},{key:"inRange",value:function(T,E){var A=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1,D=this.props.layout,R=T/A,z=E/A;if(D==="horizontal"||D==="vertical"){var O=this.state.offset,$=R>=O.left&&R<=O.left+O.width&&z>=O.top&&z<=O.top+O.height;return $?{x:R,y:z}:null}var ee=this.state,Z=ee.angleAxisMap,J=ee.radiusAxisMap;if(Z&&J){var K=ak(Z);return $qe({x:R,y:z},K)}return null}},{key:"parseEventsOfWrapper",value:function(){var T=this.props.children,E=this.getTooltipEventType(),A=Xx(T,Zg),D={};A&&E==="axis"&&(A.props.trigger==="click"?D={onClick:this.handleClick}:D={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 R=afe(this.props,this.handleOuterEvent);return Xr(Xr({},R),D)}},{key:"addListener",value:function(){iwe.on(owe,this.handleReceiveSyncEvent)}},{key:"removeListener",value:function(){iwe.removeListener(owe,this.handleReceiveSyncEvent)}},{key:"filterFormatItem",value:function(T,E,A){for(var D=this.state.formattedGraphicalItems,R=0,z=D.length;R{const{data:k,error:T}=await V.from("email_campaigns").select("*").eq("status","sent").order("sent_at",{ascending:!0});if(T)throw T;return k}}),{data:n}=yt({queryKey:["campaign-agent-profiles"],queryFn:async()=>{const{data:k,error:T}=await V.from("profiles").select("id, name, email");if(T)throw T;return k}});if(r)return e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading analytics..."});const a=t||[],i=new Map((n||[]).map(k=>[k.id,k])),l=a.reduce((k,T)=>k+(T.sent_count||0),0),o=a.reduce((k,T)=>k+(T.open_count||0),0),c=a.reduce((k,T)=>k+(T.click_count||0),0),d=a.reduce((k,T)=>k+(T.bounce_count||0),0),h=a.reduce((k,T)=>k+(T.complaint_count||0),0),m=l>0?(o/l*100).toFixed(1):"0.0",p=l>0?(c/l*100).toFixed(1):"0.0",x=[{label:"Campaigns Sent",value:a.length,icon:yn,color:"text-foreground"},{label:"Total Emails Sent",value:l,icon:Ar,color:"text-green-600"},{label:"Avg Open Rate",value:`${m}%`,icon:Bn,color:"text-blue-600"},{label:"Avg Click Rate",value:`${p}%`,icon:lm,color:"text-purple-600"},{label:"Total Bounces",value:d,icon:uu,color:"text-orange-600"},{label:"Complaints",value:h,icon:al,color:"text-destructive"}],y=new Map;a.forEach(k=>{var A,D;const T=k.user_id,E=y.get(T)||{name:((A=i.get(T))==null?void 0:A.name)||((D=i.get(T))==null?void 0:D.email)||"Unknown",campaigns:0,sent:0,opens:0,clicks:0};E.campaigns++,E.sent+=k.sent_count||0,E.opens+=k.open_count||0,E.clicks+=k.click_count||0,y.set(T,E)});const _=[...y.entries()].map(([k,T])=>({id:k,...T,openRate:T.sent>0?+(T.opens/T.sent*100).toFixed(1):0})).sort((k,T)=>T.sent-k.sent),b=_.slice(0,6).map(k=>({name:k.name,value:k.sent})),j=a.map(k=>{var T;return{name:k.name.length>20?k.name.slice(0,20)+"…":k.name,agent:((T=i.get(k.user_id))==null?void 0:T.name)||"Unknown",openRate:k.sent_count>0?+(k.open_count/k.sent_count*100).toFixed(1):0,clickRate:k.sent_count>0?+(k.click_count/k.sent_count*100).toFixed(1):0,sent:k.sent_count,date:k.sent_at?As(new Date(k.sent_at),"MMM d"):""}});return e.jsx("div",{className:"space-y-6",children:a.length===0?e.jsx(ke,{children:e.jsxs(Oe,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(yn,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold mb-1",children:"No campaigns sent yet"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Campaign analytics will appear here after the first send."})]})}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-3",children:x.map(k=>e.jsx(ke,{children:e.jsxs(Oe,{className:"p-4 text-center",children:[e.jsx(k.icon,{className:`h-5 w-5 mx-auto mb-1 ${k.color}`}),e.jsx("p",{className:"text-2xl font-bold",children:k.value}),e.jsx("p",{className:"text-xs text-muted-foreground",children:k.label})]})},k.label))}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-base",children:"Open & Click Rates by Campaign"})}),e.jsx(Oe,{children:e.jsx("div",{className:"h-[280px]",children:e.jsx(gP,{width:"100%",height:"100%",children:e.jsxs(Mgt,{data:j,children:[e.jsx(MA,{dataKey:"date",fontSize:11}),e.jsx(IA,{fontSize:11,unit:"%"}),e.jsx(Zg,{formatter:k=>`${k}%`}),e.jsx(uj,{dataKey:"openRate",fill:"hsl(220, 70%, 50%)",name:"Open Rate",radius:[2,2,0,0]}),e.jsx(uj,{dataKey:"clickRate",fill:"hsl(270, 70%, 50%)",name:"Click Rate",radius:[2,2,0,0]})]})})})})]}),e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-base",children:"Send Volume by Agent"})}),e.jsx(Oe,{children:e.jsx("div",{className:"h-[280px]",children:e.jsx(gP,{width:"100%",height:"100%",children:e.jsxs(Igt,{children:[e.jsx(Z_,{data:b,dataKey:"value",nameKey:"name",cx:"50%",cy:"50%",outerRadius:100,label:({name:k,percent:T})=>`${k} (${(T*100).toFixed(0)}%)`,fontSize:11,children:b.map((k,T)=>e.jsx(Cz,{fill:vHe[T%vHe.length]},T))}),e.jsx(Zg,{})]})})})})]})]}),e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-base",children:"Send Volume Trend"})}),e.jsx(Oe,{children:e.jsx("div",{className:"h-[240px]",children:e.jsx(gP,{width:"100%",height:"100%",children:e.jsxs(TIs,{data:j,children:[e.jsx(MA,{dataKey:"date",fontSize:11}),e.jsx(IA,{fontSize:11}),e.jsx(Zg,{}),e.jsx(Lz,{type:"monotone",dataKey:"sent",stroke:"hsl(142, 71%, 45%)",strokeWidth:2,name:"Emails Sent",dot:{r:4}})]})})})})]}),e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-base",children:"Agent Performance"})}),e.jsx(Oe,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b text-left text-muted-foreground",children:[e.jsx("th",{className:"pb-2 font-medium",children:"Agent"}),e.jsx("th",{className:"pb-2 font-medium text-center",children:"Campaigns"}),e.jsx("th",{className:"pb-2 font-medium text-center",children:"Sent"}),e.jsx("th",{className:"pb-2 font-medium text-center",children:"Opens"}),e.jsx("th",{className:"pb-2 font-medium text-center",children:"Clicks"}),e.jsx("th",{className:"pb-2 font-medium text-center",children:"Open Rate"})]})}),e.jsx("tbody",{children:_.map(k=>e.jsxs("tr",{className:"border-b last:border-0 hover:bg-muted/30",children:[e.jsx("td",{className:"py-2.5 font-medium",children:k.name}),e.jsx("td",{className:"py-2.5 text-center",children:k.campaigns}),e.jsx("td",{className:"py-2.5 text-center",children:k.sent}),e.jsx("td",{className:"py-2.5 text-center",children:k.opens}),e.jsx("td",{className:"py-2.5 text-center",children:k.clicks}),e.jsx("td",{className:"py-2.5 text-center",children:e.jsxs(Xe,{variant:"outline",children:[k.openRate,"%"]})})]},k.id))})]})})})]}),e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-base",children:"Campaign Leaderboard"})}),e.jsx(Oe,{children:e.jsx("div",{className:"space-y-2",children:[...a].sort((k,T)=>{const E=k.sent_count>0?k.open_count/k.sent_count:0;return(T.sent_count>0?T.open_count/T.sent_count:0)-E}).slice(0,10).map((k,T)=>{const E=k.sent_count>0?(k.open_count/k.sent_count*100).toFixed(1):"0.0",A=k.sent_count>0?(k.click_count/k.sent_count*100).toFixed(1):"0.0",D=i.get(k.user_id);return e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg hover:bg-muted/30 cursor-pointer",onClick:()=>s(`/admin/email-campaigns/${k.id}`),children:[e.jsxs("span",{className:"text-lg font-bold text-muted-foreground w-6",children:["#",T+1]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:k.name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(D==null?void 0:D.name)||"Unknown"," · ",k.sent_at?As(new Date(k.sent_at),"MMM d, yyyy"):""," · ",k.sent_count," sent"]})]}),e.jsxs("div",{className:"flex gap-3 text-xs",children:[e.jsxs(Xe,{variant:"outline",className:"gap-1",children:[e.jsx(Bn,{className:"h-3 w-3"})," ",E,"%"]}),e.jsxs(Xe,{variant:"outline",className:"gap-1",children:[e.jsx(lm,{className:"h-3 w-3"})," ",A,"%"]})]})]},k.id)})})})]})]})})}const AIs=()=>{const{toast:s}=li(),[t,r]=S.useState(!0),[n,a]=S.useState([]),[i,l]=S.useState([]),[o,c]=S.useState({installs:0,activeAgents:0,impressions30d:0,leads30d:0});S.useEffect(()=>{d()},[]);const d=async()=>{try{r(!0);const h=new Date;h.setDate(h.getDate()-30);const m=h.toISOString(),{data:p}=await V.from("website_apps").select("slug, name").order("sort_order"),x=[];let y=0;for(;;){const{data:A,error:D}=await V.from("agent_website_app_installs").select("user_id, app_slug, enabled").range(y,y+999);if(D)throw D;if(x.push(...A||[]),!A||A.length<1e3)break;y+=1e3}const _=[];for(y=0;;){const{data:A,error:D}=await V.from("widget_events").select("user_id, app_slug, event_type, created_at").gte("created_at",m).order("created_at",{ascending:!1}).range(y,y+999);if(D)throw D;if(_.push(...A||[]),!A||A.length<1e3||(y+=1e3,y>2e4))break}const b=new Map;for(const A of p||[])b.set(A.slug,{app_slug:A.slug,app_name:A.name,installs:0,enabled:0,impressions:0,expands:0,cta_clicks:0,lead_captures:0});for(const A of x){const D=b.get(A.app_slug);D&&(D.installs+=1,A.enabled&&(D.enabled+=1))}for(const A of _){const D=b.get(A.app_slug);D&&(A.event_type==="impression"?D.impressions+=1:A.event_type==="expand"?D.expands+=1:A.event_type==="cta_click"?D.cta_clicks+=1:A.event_type==="lead_capture"&&(D.lead_captures+=1))}const j=new Map;for(const A of x){if(!A.enabled)continue;const D=j.get(A.user_id)||{user_id:A.user_id,name:null,email:null,apps_enabled:[],events_30d:0,leads_30d:0};D.apps_enabled.includes(A.app_slug)||D.apps_enabled.push(A.app_slug),j.set(A.user_id,D)}for(const A of _){const D=j.get(A.user_id);D&&(D.events_30d+=1,A.event_type==="lead_capture"&&(D.leads_30d+=1))}const k=Array.from(j.keys());if(k.length>0){const{data:A}=await V.from("profiles").select("id, name, email").in("id",k);for(const D of A||[]){const R=j.get(D.id);R&&(R.name=D.name,R.email=D.email)}}const T=Array.from(b.values()),E=Array.from(j.values()).sort((A,D)=>D.events_30d-A.events_30d);a(T),l(E),c({installs:T.reduce((A,D)=>A+D.enabled,0),activeAgents:E.length,impressions30d:T.reduce((A,D)=>A+D.impressions,0),leads30d:T.reduce((A,D)=>A+D.lead_captures,0)})}catch(h){console.error(h),s({title:"Error",description:h.message||"Failed to load website app analytics",variant:"destructive"})}finally{r(!1)}};return t?e.jsx(ke,{children:e.jsx(Oe,{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-4",children:[e.jsxs(ke,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(zt,{className:"text-sm font-medium",children:"Active Installs"}),e.jsx(ld,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Oe,{children:[e.jsx("div",{className:"text-2xl font-bold",children:o.installs}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Apps turned on across all agents"})]})]}),e.jsxs(ke,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(zt,{className:"text-sm font-medium",children:"Agents Using Apps"}),e.jsx(Ar,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Oe,{children:[e.jsx("div",{className:"text-2xl font-bold",children:o.activeAgents}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"At least one app enabled"})]})]}),e.jsxs(ke,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(zt,{className:"text-sm font-medium",children:"Impressions (30d)"}),e.jsx(Bn,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Oe,{children:[e.jsx("div",{className:"text-2xl font-bold",children:o.impressions30d}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Widget views on lead sites"})]})]}),e.jsxs(ke,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(zt,{className:"text-sm font-medium",children:"Leads Captured (30d)"}),e.jsx(er,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Oe,{children:[e.jsx("div",{className:"text-2xl font-bold",children:o.leads30d}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Total submissions"})]})]})]}),e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsx(zt,{children:"App Performance (last 30 days)"})}),e.jsx(Oe,{children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Vs,{children:[e.jsx(At,{children:"App"}),e.jsx(At,{className:"text-right",children:"Installs"}),e.jsx(At,{className:"text-right",children:"Enabled"}),e.jsx(At,{className:"text-right",children:"Impressions"}),e.jsx(At,{className:"text-right",children:"Expands"}),e.jsx(At,{className:"text-right",children:"CTA Clicks"}),e.jsx(At,{className:"text-right",children:"Leads"}),e.jsx(At,{className:"text-right",children:"Conv. Rate"})]})}),e.jsxs(da,{children:[n.map(h=>{const m=h.impressions>0?(h.lead_captures/h.impressions*100).toFixed(1):"—";return e.jsxs(Vs,{children:[e.jsx(gt,{className:"font-medium",children:h.app_name}),e.jsx(gt,{className:"text-right",children:h.installs}),e.jsx(gt,{className:"text-right",children:h.enabled}),e.jsx(gt,{className:"text-right",children:h.impressions}),e.jsx(gt,{className:"text-right",children:h.expands}),e.jsx(gt,{className:"text-right",children:h.cta_clicks}),e.jsx(gt,{className:"text-right font-semibold",children:h.lead_captures}),e.jsx(gt,{className:"text-right text-muted-foreground",children:m==="—"?"—":`${m}%`})]},h.app_slug)}),n.length===0&&e.jsx(Vs,{children:e.jsx(gt,{colSpan:8,className:"text-center text-muted-foreground py-6",children:"No data yet"})})]})]})})]}),e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsx(zt,{children:"Agent Usage (last 30 days)"})}),e.jsxs(Oe,{children:[e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Vs,{children:[e.jsx(At,{children:"Agent"}),e.jsx(At,{children:"Email"}),e.jsx(At,{children:"Apps Enabled"}),e.jsx(At,{className:"text-right",children:"Events (30d)"}),e.jsx(At,{className:"text-right",children:"Leads (30d)"})]})}),e.jsxs(da,{children:[i.slice(0,100).map(h=>e.jsxs(Vs,{children:[e.jsx(gt,{className:"font-medium",children:h.name||"—"}),e.jsx(gt,{className:"text-muted-foreground",children:h.email||"—"}),e.jsx(gt,{children:e.jsx("div",{className:"flex flex-wrap gap-1",children:h.apps_enabled.map(m=>e.jsx(Xe,{variant:"secondary",className:"text-xs",children:m},m))})}),e.jsx(gt,{className:"text-right",children:h.events_30d}),e.jsx(gt,{className:"text-right font-semibold",children:h.leads_30d})]},h.user_id)),i.length===0&&e.jsx(Vs,{children:e.jsx(gt,{colSpan:5,className:"text-center text-muted-foreground py-6",children:"No agents have enabled website apps yet"})})]})]}),i.length>100&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:["Showing top 100 of ",i.length," agents."]})]})]})]})},MIs=()=>{const[s,t]=S.useState([]),[r,n]=S.useState([]),[a,i]=S.useState({}),[l,o]=S.useState(!0);S.useEffect(()=>{c()},[]);const c=async()=>{o(!0);try{const[{data:m},{data:p}]=await Promise.all([V.rpc("get_extension_usage_summary"),V.from("extension_usage_events").select("id, user_id, action, metadata, created_at").order("created_at",{ascending:!1}).limit(50)]),x=m||[],y=p||[];t(x),n(y);const _=Array.from(new Set(y.map(b=>b.user_id)));if(_.length){const{data:b}=await V.from("profiles").select("id, name, email").in("id",_),j={};(b||[]).forEach(k=>{j[k.id]={name:k.name,email:k.email}}),i(j)}}finally{o(!1)}},d=s.reduce((m,p)=>({users:m.users+1,contacts:m.contacts+Number(p.contacts_saved||0),listings:m.listings+Number(p.listings_imported||0),activities:m.activities+Number(p.activities_logged||0),events:m.events+Number(p.total_events||0)}),{users:0,contacts:0,listings:0,activities:0,events:0});if(l)return e.jsx(ke,{children:e.jsx(Oe,{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})});const h=m=>{switch(m){case"contact_saved":return"Contact saved";case"listing_imported":return"Listing imported";case"activity_logged":return"Activity logged";case"template_used":return"Template used";case"paired":return"Extension paired";default:return m}};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-5",children:[e.jsxs(ke,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(zt,{className:"text-sm font-medium",children:"Active Users"}),e.jsx(Ar,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Oe,{children:[e.jsx("div",{className:"text-2xl font-bold",children:d.users}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Using extension"})]})]}),e.jsxs(ke,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(zt,{className:"text-sm font-medium",children:"Total Actions"}),e.jsx(fE,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Oe,{children:[e.jsx("div",{className:"text-2xl font-bold",children:d.events}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"All events"})]})]}),e.jsxs(ke,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(zt,{className:"text-sm font-medium",children:"Contacts Saved"}),e.jsx(Vl,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Oe,{children:e.jsx("div",{className:"text-2xl font-bold",children:d.contacts})})]}),e.jsxs(ke,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(zt,{className:"text-sm font-medium",children:"Listings Imported"}),e.jsx(Fn,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Oe,{children:e.jsx("div",{className:"text-2xl font-bold",children:d.listings})})]}),e.jsxs(ke,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(zt,{className:"text-sm font-medium",children:"Activities Logged"}),e.jsx(Gi,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Oe,{children:e.jsx("div",{className:"text-2xl font-bold",children:d.activities})})]})]}),e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsx(zt,{children:"Users by Extension Activity"})}),e.jsx(Oe,{children:s.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-8 text-center",children:"No extension usage yet. Once agents install and use the Chrome Extension, their activity will appear here."}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Vs,{children:[e.jsx(At,{children:"User"}),e.jsx(At,{className:"text-right",children:"Total"}),e.jsx(At,{className:"text-right",children:"Contacts"}),e.jsx(At,{className:"text-right",children:"Listings"}),e.jsx(At,{className:"text-right",children:"Activities"}),e.jsx(At,{children:"First Used"}),e.jsx(At,{children:"Last Used"})]})}),e.jsx(da,{children:s.map(m=>e.jsxs(Vs,{children:[e.jsxs(gt,{children:[e.jsx("div",{className:"font-medium",children:m.name||"—"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:m.email})]}),e.jsx(gt,{className:"text-right font-medium",children:m.total_events}),e.jsx(gt,{className:"text-right",children:m.contacts_saved}),e.jsx(gt,{className:"text-right",children:m.listings_imported}),e.jsx(gt,{className:"text-right",children:m.activities_logged}),e.jsx(gt,{className:"text-xs text-muted-foreground",children:m.first_event_at?As(new Date(m.first_event_at),"MMM d, yyyy"):"—"}),e.jsx(gt,{className:"text-xs text-muted-foreground",children:m.last_event_at?As(new Date(m.last_event_at),"MMM d, h:mm a"):"—"})]},m.user_id))})]})})})]}),e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsx(zt,{children:"Recent Activity"})}),e.jsx(Oe,{children:r.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No recent events."}):e.jsx("div",{className:"space-y-2",children:r.map(m=>{const p=a[m.user_id];return e.jsxs("div",{className:"flex items-center justify-between border-b pb-2 last:border-0",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Xe,{variant:"secondary",children:h(m.action)}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:(p==null?void 0:p.name)||(p==null?void 0:p.email)||m.user_id.slice(0,8)}),m.metadata&&Object.keys(m.metadata).length>0&&e.jsx("div",{className:"text-xs text-muted-foreground truncate max-w-md",children:JSON.stringify(m.metadata)})]})]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:As(new Date(m.created_at),"MMM d, h:mm a")})]},m.id)})})})]})]})},IIs=()=>e.jsx(Ss,{title:"Analytics",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Analytics & Activity"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Platform-wide usage statistics and user activity"})]}),e.jsxs(ta,{defaultValue:"analytics",className:"space-y-4",children:[e.jsxs(Qn,{children:[e.jsx(ts,{value:"analytics",children:"Analytics"}),e.jsx(ts,{value:"website-apps",children:"Website Apps"}),e.jsx(ts,{value:"extension",children:"Chrome Extension"}),e.jsx(ts,{value:"content",children:"Content"}),e.jsx(ts,{value:"email-campaigns",children:"Email Campaigns"}),e.jsx(ts,{value:"activity",children:"Activity"}),e.jsx(ts,{value:"shares",children:"Shares"})]}),e.jsx(cs,{value:"analytics",className:"space-y-4",children:e.jsx(rus,{})}),e.jsx(cs,{value:"website-apps",className:"space-y-4",children:e.jsx(AIs,{})}),e.jsx(cs,{value:"extension",className:"space-y-4",children:e.jsx(MIs,{})}),e.jsx(cs,{value:"content",className:"space-y-4",children:e.jsx(aus,{})}),e.jsx(cs,{value:"email-campaigns",className:"space-y-4",children:e.jsx(EIs,{})}),e.jsx(cs,{value:"activity",className:"space-y-4",children:e.jsx(sus,{})}),e.jsx(cs,{value:"shares",className:"space-y-4",children:e.jsx(Uht,{})})]})]})});function PIs(){const s=ns(),[t,r]=S.useState(!1),[n,a]=S.useState(null),[i,l]=S.useState({title:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1,category_id:""}),[o,c]=S.useState(null),[d,h]=S.useState(""),[m,p]=S.useState([]),[x,y]=S.useState([]),[_,b]=S.useState([]),[j,k]=S.useState(!1),[T,E]=S.useState(null),[A,D]=S.useState(""),{data:R,isLoading:z}=yt({queryKey:["brokerage-resources"],queryFn:async()=>{const{data:pe,error:tt}=await V.from("brokerage_resources").select("*").order("publish_date",{ascending:!1});if(tt)throw tt;return pe}}),{data:O}=yt({queryKey:["brokerage-resource-pdfs"],queryFn:async()=>{const{data:pe,error:tt}=await V.from("brokerage_resource_pdfs").select("*").order("sort_order",{ascending:!0});if(tt)throw tt;return pe}}),{data:$}=yt({queryKey:["brokerage-resource-videos"],queryFn:async()=>{const{data:pe,error:tt}=await V.from("brokerage_resource_videos").select("*").order("sort_order",{ascending:!0});if(tt)throw tt;return pe}}),{data:ee}=yt({queryKey:["brokerage-resource-links"],queryFn:async()=>{const{data:pe,error:tt}=await V.from("brokerage_resource_links").select("*").order("sort_order",{ascending:!0});if(tt)throw tt;return pe}}),{data:Z,isLoading:J}=yt({queryKey:["brokerage-resource-categories"],queryFn:async()=>{const{data:pe,error:tt}=await V.from("brokerage_resource_categories").select("*").order("sort_order",{ascending:!0});if(tt)throw tt;return pe}}),K=()=>{l({title:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1,category_id:""}),c(null),h(""),p([]),y([]),b([]),a(null),D("")},re=pe=>{a(pe),l({title:pe.title,description:pe.description||"",publish_date:pe.publish_date.split("T")[0],is_published:pe.is_published,category_id:pe.category_id||""}),h(pe.preview_image_url||""),D("");const tt=(O==null?void 0:O.filter(Ue=>Ue.resource_id===pe.id))||[];p(tt.map(Ue=>({id:Ue.id,name:Ue.name,file_url:Ue.file_url,file_size:Ue.file_size,sort_order:Ue.sort_order})));const ge=($==null?void 0:$.filter(Ue=>Ue.resource_id===pe.id))||[];y(ge.map(Ue=>({id:Ue.id,title:Ue.title,video_url:Ue.video_url,sort_order:Ue.sort_order})));const ct=(ee==null?void 0:ee.filter(Ue=>Ue.resource_id===pe.id))||[];b(ct.map(Ue=>({id:Ue.id,title:Ue.title,canva_share_link:Ue.canva_share_link,sort_order:Ue.sort_order}))),r(!0)},ie=pe=>{var ge;const tt=(ge=pe.target.files)==null?void 0:ge[0];tt&&(c(tt),h(URL.createObjectURL(tt)))},ce=()=>{p([...m,{name:"",file_url:"",sort_order:m.length}])},ne=pe=>{p(m.filter((tt,ge)=>ge!==pe))},le=(pe,tt,ge)=>{const ct=[...m];if(tt==="file"&&ge instanceof File){const Ue=ge.name.replace(/\.[^/.]+$/,"");ct[pe]={...ct[pe],file:ge,file_size:ge.size,name:ct[pe].name||Ue}}else ct[pe]={...ct[pe],[tt]:ge};p(ct)},be=()=>{y([...x,{title:"",video_url:"",sort_order:x.length}])},fe=pe=>{y(x.filter((tt,ge)=>ge!==pe))},je=(pe,tt,ge)=>{const ct=[...x];tt==="file"&&ge instanceof File?ct[pe]={...ct[pe],file:ge}:ct[pe]={...ct[pe],[tt]:ge},y(ct)},ve=()=>{b([..._,{title:"",canva_share_link:"",sort_order:_.length}])},We=pe=>{b(_.filter((tt,ge)=>ge!==pe))},Ve=(pe,tt,ge)=>{const ct=[..._];ct[pe]={...ct[pe],[tt]:ge},b(ct)},Le=async(pe,tt)=>{try{const ge=await V.functions.invoke("bunny-upload",{body:{action:"create",title:pe.name}});if(ge.error)throw ge.error;const{videoId:ct,uploadUrl:Ue,libraryId:et}=ge.data,Qe=await V.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:ct,libraryId:et}});if(Qe.error)throw Qe.error;const{uploadUrl:Ne,apiKey:$e}=Qe.data,it=new XMLHttpRequest;return it.open("PUT",Ne,!0),it.setRequestHeader("AccessKey",$e),it.upload.onprogress=Je=>{if(Je.lengthComputable){const st=Math.round(Je.loaded/Je.total*100),mt=[...x];mt[tt]={...mt[tt],uploadProgress:st},y(mt)}},await new Promise((Je,st)=>{it.onload=()=>it.status>=200&&it.status<300?Je():st(new Error("Upload failed")),it.onerror=()=>st(new Error("Upload failed")),it.send(pe)}),`https://iframe.mediadelivery.net/embed/${et}/${ct}`}catch(ge){throw console.error("Bunny upload error:",ge),ge}},Me=Pt({mutationFn:async pe=>{const{data:tt,error:ge}=await V.from("brokerage_resource_categories").insert({name:pe,sort_order:(Z==null?void 0:Z.length)||0}).select().single();if(ge)throw ge;return tt},onSuccess:pe=>{s.invalidateQueries({queryKey:["brokerage-resource-categories"]}),l({...i,category_id:pe.id}),D(""),he.success("Category created")},onError:pe=>{he.error("Failed to create category: "+pe.message)}}),ze=Pt({mutationFn:async()=>{k(!0);let pe=(n==null?void 0:n.preview_image_url)||null;if(o){const ct=o.name.split(".").pop(),Ue=`${Date.now()}.${ct}`,{error:et}=await V.storage.from("brokerage-resources").upload(`previews/${Ue}`,o);if(et)throw et;const{data:Qe}=V.storage.from("brokerage-resources").getPublicUrl(`previews/${Ue}`);pe=Qe.publicUrl}const tt={title:i.title,description:i.description||null,preview_image_url:pe,publish_date:i.publish_date,is_published:i.is_published,category_id:i.category_id||null};let ge;if(n){const{error:ct}=await V.from("brokerage_resources").update(tt).eq("id",n.id);if(ct)throw ct;ge=n.id;const Ue=(O==null?void 0:O.filter(wt=>wt.resource_id===n.id).map(wt=>wt.id))||[],et=m.filter(wt=>wt.id).map(wt=>wt.id),Qe=Ue.filter(wt=>!et.includes(wt));Qe.length>0&&await V.from("brokerage_resource_pdfs").delete().in("id",Qe);const Ne=($==null?void 0:$.filter(wt=>wt.resource_id===n.id).map(wt=>wt.id))||[],$e=x.filter(wt=>wt.id).map(wt=>wt.id),it=Ne.filter(wt=>!$e.includes(wt));it.length>0&&await V.from("brokerage_resource_videos").delete().in("id",it);const Je=(ee==null?void 0:ee.filter(wt=>wt.resource_id===n.id).map(wt=>wt.id))||[],st=_.filter(wt=>wt.id).map(wt=>wt.id),mt=Je.filter(wt=>!st.includes(wt));mt.length>0&&await V.from("brokerage_resource_links").delete().in("id",mt)}else{const{data:ct,error:Ue}=await V.from("brokerage_resources").insert(tt).select().single();if(Ue)throw Ue;ge=ct.id}for(let ct=0;ct{s.invalidateQueries({queryKey:["brokerage-resources"]}),s.invalidateQueries({queryKey:["brokerage-resource-pdfs"]}),s.invalidateQueries({queryKey:["brokerage-resource-videos"]}),s.invalidateQueries({queryKey:["brokerage-resource-links"]}),he.success(n?"Resource updated":"Resource created"),r(!1),K(),k(!1)},onError:pe=>{he.error("Failed to save resource: "+pe.message),k(!1)}}),Pe=Pt({mutationFn:async pe=>{const{error:tt}=await V.from("brokerage_resources").delete().eq("id",pe);if(tt)throw tt},onSuccess:()=>{s.invalidateQueries({queryKey:["brokerage-resources"]}),s.invalidateQueries({queryKey:["brokerage-resource-pdfs"]}),s.invalidateQueries({queryKey:["brokerage-resource-videos"]}),s.invalidateQueries({queryKey:["brokerage-resource-links"]}),he.success("Resource deleted")},onError:pe=>{he.error("Failed to delete: "+pe.message)}}),Ie=pe=>{if(pe.preventDefault(),!i.title){he.error("Please enter a title");return}ze.mutate()},De=pe=>{const tt=(O==null?void 0:O.filter(Ue=>Ue.resource_id===pe).length)||0,ge=($==null?void 0:$.filter(Ue=>Ue.resource_id===pe).length)||0,ct=(ee==null?void 0:ee.filter(Ue=>Ue.resource_id===pe).length)||0;return{pdfCount:tt,videoCount:ge,linkCount:ct}};return e.jsx(Ss,{title:"Brokerage Resources Management",description:"Create and manage resources for brokerage managers",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs(ke,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsx(zt,{className:"text-sm font-medium text-muted-foreground",children:"Total Resources"})}),e.jsx(Oe,{children:e.jsx("div",{className:"text-2xl font-bold",children:(R==null?void 0:R.length)||0})})]}),e.jsxs(ke,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsx(zt,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Oe,{children:e.jsx("div",{className:"text-2xl font-bold",children:(R==null?void 0:R.filter(pe=>pe.is_published).length)||0})})]})]}),e.jsxs(H,{onClick:()=>{K(),r(!0)},children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Add Resource"]})]}),e.jsx(ke,{children:e.jsx(Oe,{className:"p-0",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Vs,{children:[e.jsx(At,{children:"Title"}),e.jsx(At,{children:"Category"}),e.jsx(At,{children:"Content"}),e.jsx(At,{children:"Publish Date"}),e.jsx(At,{children:"Status"}),e.jsx(At,{className:"text-right",children:"Actions"})]})}),e.jsx(da,{children:z?e.jsx(Vs,{children:e.jsx(gt,{colSpan:6,className:"text-center py-8",children:"Loading..."})}):(R==null?void 0:R.length)===0?e.jsx(Vs,{children:e.jsx(gt,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"No brokerage resources yet. Create your first one!"})}):R==null?void 0:R.map(pe=>{const{pdfCount:tt,videoCount:ge,linkCount:ct}=De(pe.id),Ue=Z==null?void 0:Z.find(et=>et.id===pe.category_id);return e.jsxs(Vs,{children:[e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[pe.preview_image_url?e.jsx("img",{src:pe.preview_image_url,alt:pe.title,className:"w-10 h-10 rounded object-cover"}):e.jsx("div",{className:"w-10 h-10 rounded bg-muted flex items-center justify-center",children:e.jsx(pm,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:pe.title}),pe.description&&e.jsx("div",{className:"text-sm text-muted-foreground line-clamp-1",children:pe.description})]})]})}),e.jsx(gt,{children:Ue?e.jsx("span",{className:"inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-muted",children:Ue.name}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-3 text-sm text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(kn,{className:"h-3.5 w-3.5"}),tt]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(xn,{className:"h-3.5 w-3.5"}),ge]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Jo,{className:"h-3.5 w-3.5"}),ct]})]})}),e.jsx(gt,{children:As(new Date(pe.publish_date),"MMM d, yyyy")}),e.jsx(gt,{children:e.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"})}),e.jsx(gt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(H,{variant:"ghost",size:"icon",onClick:()=>{const et=(O==null?void 0:O.filter($e=>$e.resource_id===pe.id))||[],Qe=($==null?void 0:$.filter($e=>$e.resource_id===pe.id))||[],Ne=(ee==null?void 0:ee.filter($e=>$e.resource_id===pe.id))||[];E({...pe,pdfs:et,videos:Qe,links:Ne})},children:e.jsx(Bn,{className:"h-4 w-4"})}),e.jsx(H,{variant:"ghost",size:"icon",onClick:()=>re(pe),children:e.jsx(ni,{className:"h-4 w-4"})}),e.jsx(H,{variant:"ghost",size:"icon",onClick:()=>{confirm("Delete this resource?")&&Pe.mutate(pe.id)},children:e.jsx(Dr,{className:"h-4 w-4 text-destructive"})})]})})]},pe.id)})})]})})}),e.jsx(bs,{open:t,onOpenChange:r,children:e.jsxs(vs,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Cs,{children:e.jsx(Ns,{children:n?"Edit Brokerage Resource":"Add Brokerage Resource"})}),e.jsxs("form",{onSubmit:Ie,className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Preview Image"}),e.jsxs("div",{className:"flex items-center gap-4",children:[d?e.jsx("img",{src:d,alt:"Preview",className:"w-24 h-24 rounded object-cover"}):e.jsx("div",{className:"w-24 h-24 rounded bg-muted flex items-center justify-center",children:e.jsx(pm,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx(Se,{type:"file",accept:"image/*",onChange:ie})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"title",children:"Title *"}),e.jsx(Se,{id:"title",value:i.title,onChange:pe=>l({...i,title:pe.target.value}),placeholder:"Resource Title"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ue,{className:"flex items-center gap-2",children:[e.jsx(xm,{className:"h-4 w-4"}),"Category"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Bs,{value:i.category_id,onValueChange:pe=>l({...i,category_id:pe}),children:[e.jsx(Os,{className:"flex-1",children:e.jsx(Us,{placeholder:"Select a category"})}),e.jsx(Fs,{children:Z==null?void 0:Z.map(pe=>e.jsx(pt,{value:pe.id,children:pe.name},pe.id))})]}),i.category_id&&e.jsx(H,{type:"button",variant:"ghost",size:"icon",onClick:()=>l({...i,category_id:""}),children:e.jsx(Rr,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Se,{placeholder:"Or create new category...",value:A,onChange:pe=>D(pe.target.value),className:"flex-1"}),e.jsxs(H,{type:"button",variant:"outline",size:"sm",disabled:!A.trim()||Me.isPending,onClick:()=>Me.mutate(A.trim()),children:[e.jsx(Ys,{className:"h-4 w-4 mr-1"}),"Add"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Description"}),e.jsx(R1,{content:i.description,onChange:pe=>l({...i,description:pe}),placeholder:"Brief description of this resource",minHeight:"120px"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(Se,{id:"publish_date",type:"date",value:i.publish_date,onChange:pe=>l({...i,publish_date:pe.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Published"}),e.jsxs("div",{className:"flex items-center space-x-2 pt-2",children:[e.jsx(Or,{checked:i.is_published,onCheckedChange:pe=>l({...i,is_published:pe})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:i.is_published?"Visible to brokerage managers":"Hidden from brokerage managers"})]})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(ue,{className:"flex items-center gap-2",children:[e.jsx(kn,{className:"h-4 w-4"}),"PDF Documents (",m.length,")"]}),e.jsxs(H,{type:"button",variant:"outline",size:"sm",onClick:ce,children:[e.jsx(Ys,{className:"h-4 w-4 mr-1"}),"Add PDF"]})]}),m.map((pe,tt)=>e.jsxs("div",{className:"flex items-center gap-2 p-3 border rounded-lg bg-muted/50",children:[e.jsx(Se,{placeholder:"PDF Name",value:pe.name,onChange:ge=>le(tt,"name",ge.target.value),className:"flex-1"}),e.jsx(Se,{type:"file",accept:".pdf",onChange:ge=>{var Ue;const ct=(Ue=ge.target.files)==null?void 0:Ue[0];ct&&le(tt,"file",ct)},className:"flex-1"}),pe.file_url&&!pe.file&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"Uploaded"}),e.jsx(H,{type:"button",variant:"ghost",size:"icon",onClick:()=>ne(tt),children:e.jsx(Rr,{className:"h-4 w-4"})})]},tt))]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(ue,{className:"flex items-center gap-2",children:[e.jsx(xn,{className:"h-4 w-4"}),"Videos (",x.length,")"]}),e.jsxs(H,{type:"button",variant:"outline",size:"sm",onClick:be,children:[e.jsx(Ys,{className:"h-4 w-4 mr-1"}),"Add Video"]})]}),x.map((pe,tt)=>e.jsxs("div",{className:"space-y-2 p-3 border rounded-lg bg-muted/50",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Se,{placeholder:"Video Title",value:pe.title,onChange:ge=>je(tt,"title",ge.target.value),className:"flex-1"}),e.jsx(H,{type:"button",variant:"ghost",size:"icon",onClick:()=>fe(tt),children:e.jsx(Rr,{className:"h-4 w-4"})})]}),e.jsx(Se,{type:"file",accept:"video/*",onChange:ge=>{var Ue;const ct=(Ue=ge.target.files)==null?void 0:Ue[0];ct&&je(tt,"file",ct)}}),pe.uploadProgress!==void 0&&pe.uploadProgress>0&&e.jsx("div",{className:"w-full bg-muted rounded-full h-2",children:e.jsx("div",{className:"bg-primary h-2 rounded-full transition-all",style:{width:`${pe.uploadProgress}%`}})}),pe.video_url&&!pe.file&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"Video uploaded"})]},tt))]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(ue,{className:"flex items-center gap-2",children:[e.jsx(Jo,{className:"h-4 w-4"}),"Canva Links (",_.length,")"]}),e.jsxs(H,{type:"button",variant:"outline",size:"sm",onClick:ve,children:[e.jsx(Ys,{className:"h-4 w-4 mr-1"}),"Add Link"]})]}),_.map((pe,tt)=>e.jsxs("div",{className:"flex items-center gap-2 p-3 border rounded-lg bg-muted/50",children:[e.jsx(Se,{placeholder:"Link Title",value:pe.title,onChange:ge=>Ve(tt,"title",ge.target.value),className:"flex-1"}),e.jsx(Se,{placeholder:"Canva Share Link",value:pe.canva_share_link,onChange:ge=>Ve(tt,"canva_share_link",ge.target.value),className:"flex-1"}),e.jsx(H,{type:"button",variant:"ghost",size:"icon",onClick:()=>We(tt),children:e.jsx(Rr,{className:"h-4 w-4"})})]},tt))]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(H,{type:"button",variant:"outline",onClick:()=>r(!1),children:"Cancel"}),e.jsx(H,{type:"submit",disabled:ze.isPending||j,children:ze.isPending||j?"Saving...":n?"Update":"Create"})]})]})]})}),e.jsx(bs,{open:!!T,onOpenChange:()=>E(null),children:e.jsxs(vs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Cs,{children:e.jsx(Ns,{children:T==null?void 0:T.title})}),T&&e.jsxs("div",{className:"space-y-4",children:[T.preview_image_url&&e.jsx("img",{src:T.preview_image_url,alt:T.title,className:"w-full h-48 object-cover rounded-lg"}),T.description&&e.jsx("p",{className:"text-muted-foreground",children:T.description}),T.pdfs&&T.pdfs.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"font-medium mb-2 flex items-center gap-2",children:[e.jsx(kn,{className:"h-4 w-4"}),"PDF Documents (",T.pdfs.length,")"]}),e.jsx("div",{className:"space-y-1",children:T.pdfs.map(pe=>e.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))})]}),T.videos&&T.videos.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"font-medium mb-2 flex items-center gap-2",children:[e.jsx(xn,{className:"h-4 w-4"}),"Videos (",T.videos.length,")"]}),e.jsx("div",{className:"space-y-2",children:T.videos.map(pe=>e.jsx("div",{className:"p-2 border rounded",children:e.jsx("p",{className:"font-medium text-sm",children:pe.title})},pe.id))})]}),T.links&&T.links.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"font-medium mb-2 flex items-center gap-2",children:[e.jsx(Jo,{className:"h-4 w-4"}),"Canva Links (",T.links.length,")"]}),e.jsx("div",{className:"space-y-1",children:T.links.map(pe=>e.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 Pgt=[{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 LIs(){const[s,t]=S.useState([]),[r,n]=S.useState(!0),[a,i]=S.useState(!1),[l,o]=S.useState(!1),[c,d]=S.useState(null),[h,m]=S.useState(!1),[p,x]=S.useState(!1),[y,_]=S.useState(""),[b,j]=S.useState(""),[k,T]=S.useState(""),[E,A]=S.useState(""),[D,R]=S.useState("Learn More"),[z,O]=S.useState("top"),[$,ee]=S.useState(""),[Z,J]=S.useState(!0),[K,re]=S.useState(""),[ie,ce]=S.useState("");S.useEffect(()=>{ne()},[]);const ne=async()=>{try{const{data:Me,error:ze}=await V.from("dashboard_banners").select("*").order("placement").order("sort_order");if(ze)throw ze;t(Me||[])}catch(Me){he.error("Failed to load banners: "+Me.message)}finally{n(!1)}},le=()=>{_(""),j(""),T(""),A(""),R("Learn More"),O("top"),ee(""),J(!0),re(""),ce(""),d(null)},be=Me=>{d(Me),_(Me.title),j(Me.description||""),T(Me.image_url),A(Me.link_url||""),R(Me.link_text||"Learn More"),O(Me.placement),ee(Me.section_after||""),J(Me.is_active),re(Me.start_date?As(new Date(Me.start_date),"yyyy-MM-dd'T'HH:mm"):""),ce(Me.end_date?As(new Date(Me.end_date),"yyyy-MM-dd'T'HH:mm"):""),i(!0)},fe=async Me=>{var Pe;const ze=(Pe=Me.target.files)==null?void 0:Pe[0];if(ze){m(!0);try{const Ie=ze.name.split(".").pop(),De=`${Date.now()}.${Ie}`,{error:pe}=await V.storage.from("banner-images").upload(De,ze);if(pe)throw pe;const{data:{publicUrl:tt}}=V.storage.from("banner-images").getPublicUrl(De);T(tt),he.success("Image uploaded successfully")}catch(Ie){he.error("Failed to upload image: "+Ie.message)}finally{m(!1)}}},je=async()=>{if(!y.trim()||!k){he.error("Please fill in required fields (title and image)");return}x(!0);try{const Me={title:y.trim(),description:b.trim()||null,image_url:k,link_url:E.trim()||null,link_text:D.trim()||"Learn More",placement:z,section_after:z==="between"?$:null,is_active:Z,start_date:K?new Date(K).toISOString():null,end_date:ie?new Date(ie).toISOString():null};if(c){const{error:ze}=await V.from("dashboard_banners").update(Me).eq("id",c.id);if(ze)throw ze;he.success("Banner updated successfully")}else{const ze=s.filter(Ie=>Ie.placement===z).length,{error:Pe}=await V.from("dashboard_banners").insert({...Me,sort_order:ze});if(Pe)throw Pe;he.success("Banner created successfully")}i(!1),le(),ne()}catch(Me){he.error("Failed to save banner: "+Me.message)}finally{x(!1)}},ve=async()=>{if(c)try{const{error:Me}=await V.from("dashboard_banners").delete().eq("id",c.id);if(Me)throw Me;he.success("Banner deleted successfully"),o(!1),d(null),ne()}catch(Me){he.error("Failed to delete banner: "+Me.message)}},We=async Me=>{try{const{error:ze}=await V.from("dashboard_banners").update({is_active:!Me.is_active}).eq("id",Me.id);if(ze)throw ze;he.success(Me.is_active?"Banner deactivated":"Banner activated"),ne()}catch(ze){he.error("Failed to update banner: "+ze.message)}},Ve=s.filter(Me=>Me.placement==="top"),Le=s.filter(Me=>Me.placement==="between");return r?e.jsx(Ss,{title:"Dashboard Management",children:e.jsx("div",{className:"flex items-center justify-center h-64",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary"})})}):e.jsxs(Ss,{title:"Dashboard Management",description:"Configure dashboard modules and banners",children:[e.jsxs("div",{className:"space-y-8",children:[e.jsxs(ke,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(wl,{className:"h-5 w-5"}),"Hero Banners (Top of Dashboard)"]}),e.jsx(Br,{children:"These banners appear in a rotating carousel at the top of the dashboard"})]}),e.jsxs(bs,{open:a&&z==="top",onOpenChange:Me=>{Me||le(),i(Me),Me&&O("top")},children:[e.jsx(Qi,{asChild:!0,children:e.jsxs(H,{onClick:()=>{le(),O("top")},children:[e.jsx(Ys,{className:"mr-2 h-4 w-4"}),"Add Hero Banner"]})}),e.jsxs(vs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Cs,{children:[e.jsxs(Ns,{children:[c?"Edit":"Create"," Banner"]}),e.jsx(nn,{children:"Configure the banner's content and display settings"})]}),e.jsx(bHe,{title:y,setTitle:_,description:b,setDescription:j,imageUrl:k,linkUrl:E,setLinkUrl:A,linkText:D,setLinkText:R,placement:z,setPlacement:O,sectionAfter:$,setSectionAfter:ee,isActive:Z,setIsActive:J,startDate:K,setStartDate:re,endDate:ie,setEndDate:ce,handleImageUpload:fe,uploading:h,showPlacementOptions:!1}),e.jsxs(wn,{children:[e.jsx(H,{variant:"outline",onClick:()=>{i(!1),le()},children:"Cancel"}),e.jsx(H,{onClick:je,disabled:p,children:p?"Saving...":c?"Update Banner":"Create Banner"})]})]})]})]}),e.jsx(Oe,{children:Ve.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-8",children:"No hero banners yet. Add your first banner above."}):e.jsx("div",{className:"space-y-3",children:Ve.map(Me=>e.jsx(_He,{banner:Me,onEdit:()=>be(Me),onDelete:()=>{d(Me),o(!0)},onToggleActive:()=>We(Me)},Me.id))})})]}),e.jsxs(ke,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(wl,{className:"h-5 w-5"}),"Section Banners"]}),e.jsx(Br,{children:"These banners appear between dashboard content sections"})]}),e.jsxs(bs,{open:a&&z==="between",onOpenChange:Me=>{Me||le(),i(Me),Me&&O("between")},children:[e.jsx(Qi,{asChild:!0,children:e.jsxs(H,{onClick:()=>{le(),O("between")},children:[e.jsx(Ys,{className:"mr-2 h-4 w-4"}),"Add Section Banner"]})}),e.jsxs(vs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Cs,{children:[e.jsxs(Ns,{children:[c?"Edit":"Create"," Section Banner"]}),e.jsx(nn,{children:"Configure where this banner appears between sections"})]}),e.jsx(bHe,{title:y,setTitle:_,description:b,setDescription:j,imageUrl:k,linkUrl:E,setLinkUrl:A,linkText:D,setLinkText:R,placement:z,setPlacement:O,sectionAfter:$,setSectionAfter:ee,isActive:Z,setIsActive:J,startDate:K,setStartDate:re,endDate:ie,setEndDate:ce,handleImageUpload:fe,uploading:h,showPlacementOptions:!0}),e.jsxs(wn,{children:[e.jsx(H,{variant:"outline",onClick:()=>{i(!1),le()},children:"Cancel"}),e.jsx(H,{onClick:je,disabled:p,children:p?"Saving...":c?"Update Banner":"Create Banner"})]})]})]})]}),e.jsx(Oe,{children:Le.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-8",children:"No section banners yet. Add your first banner above."}):e.jsx("div",{className:"space-y-3",children:Le.map(Me=>e.jsx(_He,{banner:Me,onEdit:()=>be(Me),onDelete:()=>{d(Me),o(!0)},onToggleActive:()=>We(Me),showSection:!0},Me.id))})})]})]}),e.jsx(bs,{open:l,onOpenChange:o,children:e.jsxs(vs,{children:[e.jsxs(Cs,{children:[e.jsx(Ns,{children:"Delete Banner"}),e.jsxs(nn,{children:['Are you sure you want to delete "',c==null?void 0:c.title,'"? This action cannot be undone.']})]}),e.jsxs(wn,{children:[e.jsx(H,{variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsx(H,{variant:"destructive",onClick:ve,children:"Delete"})]})]})})]})}function bHe({title:s,setTitle:t,description:r,setDescription:n,imageUrl:a,linkUrl:i,setLinkUrl:l,linkText:o,setLinkText:c,placement:d,setPlacement:h,sectionAfter:m,setSectionAfter:p,isActive:x,setIsActive:y,startDate:_,setStartDate:b,endDate:j,setEndDate:k,handleImageUpload:T,uploading:E,showPlacementOptions:A}){return e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"title",children:"Title *"}),e.jsx(Se,{id:"title",placeholder:"Banner headline...",value:s,onChange:D=>t(D.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"description",children:"Description"}),e.jsx(vr,{id:"description",placeholder:"Optional banner description...",value:r,onChange:D=>n(D.target.value),rows:2})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Banner Image *"}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(Se,{type:"file",accept:"image/*",onChange:T,disabled:E,className:"flex-1"}),E&&e.jsx("span",{className:"text-sm text-muted-foreground",children:"Uploading..."})]}),a&&e.jsx("div",{className:"mt-2 relative rounded-lg overflow-hidden border",children:e.jsx("img",{src:a,alt:"Preview",className:"w-full h-40 object-cover"})})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"linkUrl",children:"Link URL (optional)"}),e.jsx(Se,{id:"linkUrl",placeholder:"https://...",value:i,onChange:D=>l(D.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"linkText",children:"Button Text"}),e.jsx(Se,{id:"linkText",placeholder:"Learn More",value:o,onChange:D=>c(D.target.value)})]})]}),A&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Placement"}),e.jsxs(Bs,{value:m,onValueChange:p,children:[e.jsx(Os,{children:e.jsx(Us,{placeholder:"Select section placement..."})}),e.jsx(Fs,{children:Pgt.map(D=>e.jsx(pt,{value:D.value,children:D.label},D.value))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ue,{htmlFor:"startDate",className:"flex items-center gap-2",children:[e.jsx(Nn,{className:"h-4 w-4"}),"Start Date (optional)"]}),e.jsx(Se,{id:"startDate",type:"datetime-local",value:_,onChange:D=>b(D.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ue,{htmlFor:"endDate",className:"flex items-center gap-2",children:[e.jsx(Nn,{className:"h-4 w-4"}),"End Date (optional)"]}),e.jsx(Se,{id:"endDate",type:"datetime-local",value:j,onChange:D=>k(D.target.value)})]})]}),e.jsx("div",{className:"flex items-center justify-between pt-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Or,{id:"isActive",checked:x,onCheckedChange:y}),e.jsx(ue,{htmlFor:"isActive",children:"Active"})]})})]})}function _He({banner:s,onEdit:t,onDelete:r,onToggleActive:n,showSection:a=!1}){var c;const i=(c=Pgt.find(d=>d.value===s.section_after))==null?void 0:c.label,[l,o]=S.useState(null);return S.useEffect(()=>{(async()=>{const{count:h}=await V.from("content_engagement_logs").select("*",{count:"exact",head:!0}).eq("resource_id",s.id).eq("action_type","click_link");o(h??0)})()},[s.id]),e.jsxs("div",{className:"flex items-center gap-4 p-3 border rounded-lg bg-card hover:bg-accent/50 transition-colors",children:[e.jsx(Oh,{className:"h-5 w-5 text-muted-foreground cursor-grab"}),e.jsx("img",{src:s.image_url,alt:s.title,className:"w-24 h-14 object-cover rounded"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h4",{className:"font-medium truncate",children:s.title}),!s.is_active&&e.jsx(Xe,{variant:"secondary",children:"Inactive"}),s.start_date&&new Date(s.start_date)>new Date&&e.jsx(Xe,{variant:"outline",children:"Scheduled"})]}),s.description&&e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:s.description}),a&&i&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:i})]}),l!==null&&e.jsxs("div",{className:"flex items-center gap-1 text-destructive",title:"Button clicks",children:[e.jsx(Kd,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm font-semibold",children:l})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[s.link_url&&e.jsx("a",{href:s.link_url,target:"_blank",rel:"noopener noreferrer",children:e.jsx(H,{variant:"ghost",size:"icon",children:e.jsx(gn,{className:"h-4 w-4"})})}),e.jsx(H,{variant:"ghost",size:"icon",onClick:n,children:s.is_active?e.jsx(Bn,{className:"h-4 w-4"}):e.jsx($f,{className:"h-4 w-4"})}),e.jsx(H,{variant:"ghost",size:"icon",onClick:t,children:e.jsx(ni,{className:"h-4 w-4"})}),e.jsx(H,{variant:"ghost",size:"icon",onClick:r,children:e.jsx(Dr,{className:"h-4 w-4 text-destructive"})})]})]})}const qq={open:{label:"Open",icon:Pn,color:"bg-yellow-500"},in_progress:{label:"In Progress",icon:qc,color:"bg-blue-500"},resolved:{label:"Resolved",icon:zi,color:"bg-green-500"},closed:{label:"Closed",icon:kd,color:"bg-muted-foreground"}},wHe={general:"General Support",technology:"Technology Support",crm:"CRM Support",marketing:"Marketing Support"};function DIs(){var z,O;const{user:s}=Ms(),t=ns(),[r,n]=S.useState(null),[a,i]=S.useState(""),[l,o]=S.useState([]),[c,d]=S.useState("all"),[h,m]=S.useState("all"),[p,x]=S.useState(!1),{data:y=[],isLoading:_}=yt({queryKey:["admin-support-tickets",c,h],queryFn:async()=>{let $=V.from("support_tickets").select("*, profiles!support_tickets_user_id_fkey(name, email)").order("created_at",{ascending:!1});c!=="all"&&($=$.eq("status",c)),h!=="all"&&($=$.eq("category",h));const{data:ee,error:Z}=await $;if(Z)throw Z;return ee}}),{data:b=[]}=yt({queryKey:["admin-users-notifications"],queryFn:async()=>{const{data:$,error:ee}=await V.from("user_roles").select("user_id").eq("role","admin");if(ee)throw ee;const Z=$.map(ne=>ne.user_id),{data:J,error:K}=await V.from("profiles").select("id, name, email").in("id",Z);if(K)throw K;const{data:re,error:ie}=await V.from("support_notification_settings").select("user_id, receive_notifications");if(ie)throw ie;const ce=new Map((re==null?void 0:re.map(ne=>[ne.user_id,ne.receive_notifications]))||[]);return J.map(ne=>({...ne,receives_notifications:ce.get(ne.id)||!1}))}}),{data:j=[]}=yt({queryKey:["admin-ticket-replies",r==null?void 0:r.id],queryFn:async()=>{if(!r)return[];const{data:$,error:ee}=await V.from("support_ticket_replies").select("*, profiles(name)").eq("ticket_id",r.id).order("created_at",{ascending:!0});if(ee)throw ee;return $},enabled:!!r}),k=Pt({mutationFn:async({userId:$,enabled:ee})=>{const{data:Z}=await V.from("support_notification_settings").select("id").eq("user_id",$).maybeSingle();if(Z){const{error:J}=await V.from("support_notification_settings").update({receive_notifications:ee}).eq("user_id",$);if(J)throw J}else{const{error:J}=await V.from("support_notification_settings").insert({user_id:$,receive_notifications:ee});if(J)throw J}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-users-notifications"]}),he.success("Notification settings updated")},onError:()=>{he.error("Failed to update settings")}}),T=Pt({mutationFn:async({ticketId:$,status:ee})=>{const{error:Z}=await V.from("support_tickets").update({status:ee}).eq("id",$);if(Z)throw Z},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-support-tickets"]}),r&&n({...r,status:r.status}),he.success("Status updated")},onError:()=>{he.error("Failed to update status")}}),E=Pt({mutationFn:async({ticketId:$,assignedTo:ee})=>{const{error:Z}=await V.from("support_tickets").update({assigned_to:ee}).eq("id",$);if(Z)throw Z},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-support-tickets"]}),he.success("Ticket assigned")},onError:()=>{he.error("Failed to assign ticket")}}),A=Pt({mutationFn:async({content:$,attachments:ee})=>{var J,K;if(!r||!s)throw new Error("Missing data");const{error:Z}=await V.from("support_ticket_replies").insert({ticket_id:r.id,user_id:s.id,content:$,is_admin_reply:!0,attachments:ee});if(Z)throw Z;try{await V.functions.invoke("support-reply-notify",{body:{ticketId:r.id,ticketSubject:r.subject,replyContent:$,userEmail:(J=r.profiles)==null?void 0:J.email,userName:(K=r.profiles)==null?void 0:K.name}})}catch(re){console.error("Failed to send reply notification:",re)}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-ticket-replies",r==null?void 0:r.id]}),i(""),o([]),he.success("Reply sent!")},onError:()=>{he.error("Failed to send reply")}}),D=()=>{!a.trim()&&l.length===0||A.mutate({content:a,attachments:l})};S.useEffect(()=>{const $=V.channel("admin-tickets").on("postgres_changes",{event:"*",schema:"public",table:"support_tickets"},()=>{t.invalidateQueries({queryKey:["admin-support-tickets"]})}).subscribe();return()=>{V.removeChannel($)}},[t]);const R=y.filter($=>$.status==="open").length;return r?(qq[r.status].icon,e.jsx(Ss,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(H,{variant:"ghost",size:"icon",onClick:()=>n(null),children:e.jsx(za,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h1",{className:"text-2xl font-bold",children:r.subject}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(Xe,{variant:"secondary",children:wHe[r.category]}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:["from ",((z=r.profiles)==null?void 0:z.name)||"Unknown"," (",(O=r.profiles)==null?void 0:O.email,")"]})]})]})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs(ke,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsx(zt,{className:"text-sm",children:"Status"})}),e.jsx(Oe,{children:e.jsxs(Bs,{value:r.status,onValueChange:$=>{T.mutate({ticketId:r.id,status:$}),n({...r,status:$})},children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"open",children:"Open"}),e.jsx(pt,{value:"in_progress",children:"In Progress"}),e.jsx(pt,{value:"resolved",children:"Resolved"}),e.jsx(pt,{value:"closed",children:"Closed"})]})]})})]}),e.jsxs(ke,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsx(zt,{className:"text-sm",children:"Assigned To"})}),e.jsx(Oe,{children:e.jsxs(Bs,{value:r.assigned_to||"unassigned",onValueChange:$=>{const ee=$==="unassigned"?null:$;E.mutate({ticketId:r.id,assignedTo:ee}),n({...r,assigned_to:ee})},children:[e.jsx(Os,{children:e.jsx(Us,{placeholder:"Unassigned"})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"unassigned",children:"Unassigned"}),b.map($=>e.jsx(pt,{value:$.id,children:$.name},$.id))]})]})})]})]}),e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsxs(Br,{children:["Created on ",As(new Date(r.created_at),"MMM d, yyyy 'at' h:mm a")]})}),e.jsx(Oe,{children:e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:r.description})})]}),e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-lg",children:"Conversation"})}),e.jsxs(Oe,{children:[e.jsx(Ci,{className:"h-[300px] pr-4",children:j.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-8",children:"No replies yet"}):e.jsx("div",{className:"space-y-4",children:j.map($=>{var ee,Z;return e.jsxs("div",{className:`p-4 rounded-lg ${$.is_admin_reply?"bg-primary/10 ml-4":"bg-muted mr-4"}`,children:[e.jsxs("div",{className:"flex justify-between items-start mb-2",children:[e.jsx("span",{className:"font-medium text-sm",children:$.is_admin_reply?`${((ee=$.profiles)==null?void 0:ee.name)||"Admin"} (Support)`:((Z=$.profiles)==null?void 0:Z.name)||"User"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:As(new Date($.created_at),"MMM d, h:mm a")})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:$.content}),$.attachments&&$.attachments.length>0&&e.jsx(dht,{attachments:$.attachments})]},$.id)})})}),e.jsx(Qo,{className:"my-4"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(vr,{placeholder:"Type your reply...",value:a,onChange:$=>i($.target.value),className:"min-h-[80px]"}),e.jsx(H,{onClick:D,disabled:!a.trim()&&l.length===0||A.isPending,className:"self-end",children:e.jsx(yn,{className:"h-4 w-4"})})]}),e.jsx(cht,{value:l,onChange:o,disabled:A.isPending})]})]})]})]})})):e.jsx(Ss,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Support Tickets"}),e.jsxs("p",{className:"text-muted-foreground",children:["Manage support requests from agents",R>0&&e.jsxs(Xe,{variant:"destructive",className:"ml-2",children:[R," open"]})]})]}),e.jsxs(bs,{open:p,onOpenChange:x,children:[e.jsx(Qi,{asChild:!0,children:e.jsxs(H,{variant:"outline",children:[e.jsx(Go,{className:"h-4 w-4 mr-2"}),"Notification Settings"]})}),e.jsxs(vs,{children:[e.jsxs(Cs,{children:[e.jsx(Ns,{children:"Email Notification Settings"}),e.jsx(nn,{children:"Choose which admins receive email notifications for new support tickets."})]}),e.jsx("div",{className:"space-y-4 mt-4",children:b.map($=>e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(io,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:$.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:$.email})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[$.receives_notifications?e.jsx(wp,{className:"h-4 w-4 text-primary"}):e.jsx(u_,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(Or,{checked:$.receives_notifications,onCheckedChange:ee=>k.mutate({userId:$.id,enabled:ee})})]})]},$.id))})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-4 items-center",children:[e.jsx(ta,{value:c,onValueChange:d,className:"w-auto",children:e.jsxs(Qn,{children:[e.jsx(ts,{value:"all",children:"All"}),e.jsx(ts,{value:"open",children:"Open"}),e.jsx(ts,{value:"in_progress",children:"In Progress"}),e.jsx(ts,{value:"resolved",children:"Resolved"}),e.jsx(ts,{value:"closed",children:"Closed"})]})}),e.jsxs(Bs,{value:h,onValueChange:m,children:[e.jsx(Os,{className:"w-[180px]",children:e.jsx(Us,{placeholder:"All Categories"})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"all",children:"All Categories"}),e.jsx(pt,{value:"general",children:"General Support"}),e.jsx(pt,{value:"technology",children:"Technology Support"}),e.jsx(pt,{value:"crm",children:"CRM Support"}),e.jsx(pt,{value:"marketing",children:"Marketing Support"})]})]})]}),e.jsx("div",{className:"mt-4",children:_?e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading tickets..."}):y.length===0?e.jsx(ke,{children:e.jsxs(Oe,{className:"text-center py-12",children:[e.jsx(qc,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-medium mb-2",children:"No tickets found"}),e.jsx("p",{className:"text-muted-foreground",children:"No support tickets match the current filters."})]})}):e.jsx("div",{className:"space-y-3",children:y.map($=>{var Z,J;const ee=qq[$.status].icon;return e.jsx(ke,{className:"cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>n($),children:e.jsx(Oe,{className:"p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-medium truncate",children:$.subject}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 flex-wrap",children:[e.jsx(Xe,{variant:"outline",className:"text-xs",children:wHe[$.category]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[(Z=$.profiles)==null?void 0:Z.name," • ",As(new Date($.created_at),"MMM d, yyyy")]}),$.assigned_to&&e.jsxs(Xe,{variant:"secondary",className:"text-xs gap-1",children:[e.jsx(io,{className:"h-3 w-3"}),((J=b.find(K=>K.id===$.assigned_to))==null?void 0:J.name)||"Assigned"]})]})]}),e.jsxs(Xe,{className:qq[$.status].color,children:[e.jsx(ee,{className:"h-3 w-3 mr-1"}),qq[$.status].label]})]})})},$.id)})})})]})]})})}const Lgt=Kf.create({name:"color",addOptions(){return{types:["textStyle"]}},addGlobalAttributes(){return[{types:this.options.types,attributes:{color:{default:null,parseHTML:s=>{var t;return(t=s.style.color)===null||t===void 0?void 0:t.replace(/['"]+/g,"")},renderHTML:s=>s.color?{style:`color: ${s.color}`}:{}}}}]},addCommands(){return{setColor:s=>({chain:t})=>t().setMark("textStyle",{color:s}).run(),unsetColor:()=>({chain:s})=>s().setMark("textStyle",{color:null}).removeEmptyTextStyle().run()}}});function RIs({content:s,onChange:t,variables:r}){const n=XTe({extensions:[JTe,cEe.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline"}}),dEe.configure({types:["heading","paragraph"]}),uEe,Lgt],content:s,onUpdate:({editor:l})=>{t(l.getHTML())}});S.useEffect(()=>{n&&s!==n.getHTML()&&n.commands.setContent(s)},[s,n]);const a=l=>{n&&n.chain().focus().insertContent(`{{${l.key}}}`).run()},i=()=>{if(!n)return;const l=n.getAttributes("link").href,o=window.prompt("URL",l);if(o!==null){if(o===""){n.chain().focus().extendMarkRange("link").unsetLink().run();return}n.chain().focus().extendMarkRange("link").setLink({href:o}).run()}};return n?e.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-1 p-2 border-b bg-muted/30",children:[e.jsx(H,{type:"button",variant:"ghost",size:"sm",onClick:()=>n.chain().focus().toggleBold().run(),className:n.isActive("bold")?"bg-muted":"",children:e.jsx(Ok,{className:"h-4 w-4"})}),e.jsx(H,{type:"button",variant:"ghost",size:"sm",onClick:()=>n.chain().focus().toggleItalic().run(),className:n.isActive("italic")?"bg-muted":"",children:e.jsx(qk,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(H,{type:"button",variant:"ghost",size:"sm",onClick:()=>n.chain().focus().toggleBulletList().run(),className:n.isActive("bulletList")?"bg-muted":"",children:e.jsx(Vf,{className:"h-4 w-4"})}),e.jsx(H,{type:"button",variant:"ghost",size:"sm",onClick:()=>n.chain().focus().toggleOrderedList().run(),className:n.isActive("orderedList")?"bg-muted":"",children:e.jsx(b1,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(H,{type:"button",variant:"ghost",size:"sm",onClick:()=>n.chain().focus().setTextAlign("left").run(),className:n.isActive({textAlign:"left"})?"bg-muted":"",children:e.jsx(uE,{className:"h-4 w-4"})}),e.jsx(H,{type:"button",variant:"ghost",size:"sm",onClick:()=>n.chain().focus().setTextAlign("center").run(),className:n.isActive({textAlign:"center"})?"bg-muted":"",children:e.jsx(dE,{className:"h-4 w-4"})}),e.jsx(H,{type:"button",variant:"ghost",size:"sm",onClick:()=>n.chain().focus().setTextAlign("right").run(),className:n.isActive({textAlign:"right"})?"bg-muted":"",children:e.jsx(hE,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(H,{type:"button",variant:"ghost",size:"sm",onClick:i,className:n.isActive("link")?"bg-muted":"",children:e.jsx(Jo,{className:"h-4 w-4"})}),e.jsx(H,{type:"button",variant:"ghost",size:"sm",onClick:()=>n.chain().focus().toggleCodeBlock().run(),className:n.isActive("codeBlock")?"bg-muted":"",children:e.jsx(pE,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(H,{type:"button",variant:"ghost",size:"sm",onClick:()=>n.chain().focus().undo().run(),disabled:!n.can().undo(),children:e.jsx(Xk,{className:"h-4 w-4"})}),e.jsx(H,{type:"button",variant:"ghost",size:"sm",onClick:()=>n.chain().focus().redo().run(),disabled:!n.can().redo(),children:e.jsx(Yk,{className:"h-4 w-4"})}),e.jsx("div",{className:"flex-1"}),r.length>0&&e.jsxs(Xu,{children:[e.jsx(Qu,{asChild:!0,children:e.jsxs(H,{type:"button",variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(QI,{className:"h-4 w-4"}),"Insert Variable"]})}),e.jsx(wu,{align:"end",className:"w-64",children:r.map(l=>e.jsxs(di,{onClick:()=>a(l),className:"flex flex-col items-start",children:[e.jsx("span",{className:"font-medium",children:l.label}),e.jsx("span",{className:"text-xs text-muted-foreground font-mono",children:`{{${l.key}}}`}),l.description&&e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:l.description})]},l.key))})]})]}),e.jsx(YTe,{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&&e.jsxs("div",{className:"border-t p-3 bg-muted/20",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Available variables (click to copy):"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:r.map(l=>e.jsx(Xe,{variant:"secondary",className:"cursor-pointer hover:bg-secondary/80 font-mono text-xs",onClick:()=>{navigator.clipboard.writeText(`{{${l.key}}}`)},children:`{{${l.key}}}`},l.key))})]})]}):null}function OIs(){const s=ns(),[t,r]=S.useState(null),[n,a]=S.useState(null),[i,l]=S.useState(""),[o,c]=S.useState(""),[d,h]=S.useState(""),[m,p]=S.useState(!0),[x,y]=S.useState("visual"),{data:_,isLoading:b}=yt({queryKey:["email-templates"],queryFn:async()=>{const{data:A,error:D}=await V.from("email_templates").select("*").order("name");if(D)throw D;return A.map(R=>({...R,available_variables:R.available_variables||[]}))}}),j=Pt({mutationFn:async A=>{const{error:D}=await V.from("email_templates").update({subject:A.subject,body_html:A.body_html,description:A.description,is_active:A.is_active}).eq("id",A.id);if(D)throw D},onSuccess:()=>{s.invalidateQueries({queryKey:["email-templates"]}),he.success("Email template updated successfully"),r(null)},onError:A=>{he.error("Failed to update template: "+A.message)}}),k=A=>{r(A),l(A.subject),c(A.body_html),h(A.description||""),p(A.is_active),y("visual")},T=()=>{t&&j.mutate({id:t.id,subject:i,body_html:o,description:d,is_active:m})},E=(A,D)=>{let R=A;return D.forEach(z=>{const O=`{{${z.key}}}`,$=`[${z.label}]`;R=R.replace(new RegExp(O.replace(/[{}]/g,"\\$&"),"g"),$)}),R};return t?e.jsxs(Ss,{title:"Edit Email Template",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs(H,{variant:"ghost",onClick:()=>r(null),children:[e.jsx(za,{className:"h-4 w-4 mr-2"}),"Back to Templates"]}),e.jsx("div",{className:"flex-1"}),e.jsxs(H,{variant:"outline",onClick:()=>a(t),children:[e.jsx(Bn,{className:"h-4 w-4 mr-2"}),"Preview"]}),e.jsxs(H,{onClick:T,disabled:j.isPending,children:[e.jsx(vc,{className:"h-4 w-4 mr-2"}),j.isPending?"Saving...":"Save Changes"]})]}),e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(er,{className:"h-5 w-5"}),t.name]}),e.jsxs(Br,{className:"mt-1",children:["Template slug: ",e.jsx("code",{className:"bg-muted px-1 rounded",children:t.slug})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ue,{htmlFor:"active-toggle",children:"Active"}),e.jsx(Or,{id:"active-toggle",checked:m,onCheckedChange:p})]})]})}),e.jsxs(Oe,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"description",children:"Description"}),e.jsx(vr,{id:"description",value:d,onChange:A=>h(A.target.value),placeholder:"Brief description of when this email is sent",rows:2})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"subject",children:"Email Subject"}),e.jsx(Se,{id:"subject",value:i,onChange:A=>l(A.target.value),placeholder:"Email subject line"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["You can use variables like ","{{name}}"," in the subject"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ue,{children:"Email Body"}),e.jsx(ta,{value:x,onValueChange:A=>y(A),children:e.jsxs(Qn,{className:"h-8",children:[e.jsxs(ts,{value:"visual",className:"text-xs px-3 h-6",children:[e.jsx(Vk,{className:"h-3 w-3 mr-1"}),"Visual"]}),e.jsxs(ts,{value:"html",className:"text-xs px-3 h-6",children:[e.jsx(pE,{className:"h-3 w-3 mr-1"}),"HTML"]})]})})]}),x==="visual"?e.jsx(RIs,{content:o,onChange:c,variables:t.available_variables}):e.jsx(vr,{value:o,onChange:A=>c(A.target.value),className:"font-mono text-sm min-h-[400px]",placeholder:"HTML email body"})]})]})]})]}),e.jsx(bs,{open:!!n,onOpenChange:()=>a(null),children:e.jsxs(vs,{className:"max-w-3xl max-h-[90vh] overflow-auto",children:[e.jsxs(Cs,{children:[e.jsx(Ns,{children:"Email Preview"}),e.jsxs(nn,{children:["Subject: ",i.replace(/\{\{(\w+)\}\}/g,"[$1]")]})]}),e.jsx("div",{className:"border rounded-lg p-4 bg-white",children:e.jsx("div",{dangerouslySetInnerHTML:{__html:E(o,t.available_variables)}})})]})})]}):e.jsx(Ss,{title:"Email Templates",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Email Templates"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Manage and customize system email templates"})]}),b?e.jsx("div",{className:"grid gap-4",children:[...Array(4)].map((A,D)=>e.jsx(ke,{children:e.jsxs(Ot,{children:[e.jsx(Ks,{className:"h-5 w-48"}),e.jsx(Ks,{className:"h-4 w-96"})]})},D))}):e.jsx("div",{className:"grid gap-4",children:_==null?void 0:_.map(A=>e.jsxs(ke,{className:"hover:shadow-md transition-shadow",children:[e.jsx(Ot,{children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs(zt,{className:"flex items-center gap-2 text-lg",children:[e.jsx(er,{className:"h-5 w-5 text-muted-foreground"}),A.name,!A.is_active&&e.jsx(Xe,{variant:"secondary",children:"Inactive"})]}),e.jsx(Br,{children:A.description})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(H,{variant:"outline",size:"sm",onClick:()=>a(A),children:[e.jsx(Bn,{className:"h-4 w-4 mr-2"}),"Preview"]}),e.jsxs(H,{size:"sm",onClick:()=>k(A),children:[e.jsx(ou,{className:"h-4 w-4 mr-2"}),"Edit"]})]})]})}),e.jsx(Oe,{children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Subject:"}),e.jsx("code",{className:"bg-muted px-2 py-0.5 rounded text-sm",children:A.subject})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Variables:"}),e.jsx("div",{className:"flex flex-wrap gap-1",children:A.available_variables.map(D=>e.jsx(Xe,{variant:"outline",className:"font-mono text-xs",children:`{{${D.key}}}`},D.key))})]})]})})]},A.id))}),e.jsx(bs,{open:!!n&&!t,onOpenChange:()=>a(null),children:e.jsxs(vs,{className:"max-w-3xl max-h-[90vh] overflow-auto",children:[e.jsxs(Cs,{children:[e.jsxs(Ns,{children:["Email Preview: ",n==null?void 0:n.name]}),e.jsxs(nn,{children:["Subject: ",n==null?void 0:n.subject.replace(/\{\{(\w+)\}\}/g,"[$1]")]})]}),n&&e.jsx("div",{className:"border rounded-lg p-4 bg-white",children:e.jsx("div",{dangerouslySetInnerHTML:{__html:E(n.body_html,n.available_variables)}})})]})})]})})}function FIs(){const s=ns(),[t,r]=S.useState("templates"),[n,a]=S.useState(null),[i,l]=S.useState(null),[o,c]=S.useState(!1),[d,h]=S.useState(!1),[m,p]=S.useState({title:"",subject:"",body:"",description:"",tone:"",category_id:"",is_active:!0}),[x,y]=S.useState({name:"",description:"",icon:"📧"}),{data:_=[]}=yt({queryKey:["agent-email-template-categories"],queryFn:async()=>{const{data:$,error:ee}=await V.from("email_template_categories").select("*").order("sort_order");if(ee)throw ee;return $}}),{data:b=[],isLoading:j}=yt({queryKey:["agent-email-templates-admin"],queryFn:async()=>{const{data:$,error:ee}=await V.from("agent_email_templates").select("*, category:email_template_categories(*)").order("sort_order");if(ee)throw ee;return $}}),k=Pt({mutationFn:async $=>{const ee={title:$.title,subject:$.subject,body:$.body,description:$.description||null,tone:$.tone||null,category_id:$.category_id||null,is_active:$.is_active};if($.id){const{error:Z}=await V.from("agent_email_templates").update(ee).eq("id",$.id);if(Z)throw Z}else{const{error:Z}=await V.from("agent_email_templates").insert(ee);if(Z)throw Z}},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-email-templates-admin"]}),c(!1),he.success(n?"Template updated":"Template created")},onError:()=>he.error("Failed to save template")}),T=Pt({mutationFn:async $=>{const{error:ee}=await V.from("agent_email_templates").delete().eq("id",$);if(ee)throw ee},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-email-templates-admin"]}),he.success("Template deleted")}}),E=Pt({mutationFn:async $=>{const ee={name:$.name,description:$.description||null,icon:$.icon};if($.id){const{error:Z}=await V.from("email_template_categories").update(ee).eq("id",$.id);if(Z)throw Z}else{const Z=_.length>0?Math.max(..._.map(K=>K.sort_order))+1:0,{error:J}=await V.from("email_template_categories").insert({...ee,sort_order:Z});if(J)throw J}},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-email-template-categories"]}),h(!1),he.success(i?"Category updated":"Category created")},onError:()=>he.error("Failed to save category")}),A=Pt({mutationFn:async $=>{const{error:ee}=await V.from("email_template_categories").delete().eq("id",$);if(ee)throw ee},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-email-template-categories"]}),he.success("Category deleted")}}),D=()=>{a(null),p({title:"",subject:"",body:"",description:"",tone:"",category_id:"",is_active:!0}),c(!0)},R=$=>{a($),p({title:$.title,subject:$.subject,body:$.body,description:$.description||"",tone:$.tone||"",category_id:$.category_id||"",is_active:$.is_active}),c(!0)},z=()=>{l(null),y({name:"",description:"",icon:"📧"}),h(!0)},O=$=>{l($),y({name:$.name,description:$.description||"",icon:$.icon}),h(!0)};return e.jsx(Ss,{children:e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsx(km,{title:"Agent Email Templates",description:"Manage email templates that agents use when composing emails from Mission Control."}),e.jsxs(ta,{value:t,onValueChange:r,children:[e.jsxs(Qn,{children:[e.jsxs(ts,{value:"templates",className:"gap-2",children:[e.jsx(er,{className:"h-4 w-4"})," Templates"]}),e.jsxs(ts,{value:"categories",className:"gap-2",children:[e.jsx(Uf,{className:"h-4 w-4"})," Categories"]})]}),e.jsxs(cs,{value:"templates",className:"space-y-4",children:[e.jsx("div",{className:"flex justify-end",children:e.jsxs(H,{onClick:D,className:"gap-2",children:[e.jsx(Ys,{className:"h-4 w-4"})," Add Template"]})}),e.jsx(ke,{children:e.jsx(Oe,{className:"p-0",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Vs,{children:[e.jsx(At,{children:"Template"}),e.jsx(At,{className:"hidden md:table-cell",children:"Category"}),e.jsx(At,{className:"hidden md:table-cell",children:"Tone"}),e.jsx(At,{children:"Status"}),e.jsx(At,{className:"text-right",children:"Actions"})]})}),e.jsx(da,{children:j?e.jsx(Vs,{children:e.jsx(gt,{colSpan:5,className:"text-center py-8",children:e.jsx(is,{className:"h-6 w-6 animate-spin mx-auto"})})}):b.length===0?e.jsx(Vs,{children:e.jsx(gt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No templates yet. Create your first one!"})}):b.map($=>e.jsxs(Vs,{children:[e.jsx(gt,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:$.title}),e.jsx("p",{className:"text-xs text-muted-foreground truncate max-w-[300px]",children:$.subject})]})}),e.jsx(gt,{className:"hidden md:table-cell",children:$.category?e.jsxs(Xe,{variant:"outline",className:"gap-1",children:[$.category.icon," ",$.category.name]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsx(gt,{className:"hidden md:table-cell",children:$.tone?e.jsx(Xe,{variant:"secondary",children:$.tone}):"—"}),e.jsx(gt,{children:e.jsx(Xe,{variant:$.is_active?"default":"secondary",children:$.is_active?"Active":"Inactive"})}),e.jsx(gt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-1",children:[e.jsx(H,{variant:"ghost",size:"icon",onClick:()=>R($),children:e.jsx(ni,{className:"h-4 w-4"})}),e.jsx(H,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",onClick:()=>{confirm("Delete this template?")&&T.mutate($.id)},children:e.jsx(Dr,{className:"h-4 w-4"})})]})})]},$.id))})]})})})]}),e.jsxs(cs,{value:"categories",className:"space-y-4",children:[e.jsx("div",{className:"flex justify-end",children:e.jsxs(H,{onClick:z,className:"gap-2",children:[e.jsx(Ys,{className:"h-4 w-4"})," Add Category"]})}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-3",children:_.map($=>e.jsxs(ke,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(zt,{className:"text-base flex items-center gap-2",children:[e.jsx("span",{className:"text-lg",children:$.icon})," ",$.name]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(H,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>O($),children:e.jsx(ni,{className:"h-3.5 w-3.5"})}),e.jsx(H,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive",onClick:()=>{confirm("Delete this category?")&&A.mutate($.id)},children:e.jsx(Dr,{className:"h-3.5 w-3.5"})})]})]})}),e.jsxs(Oe,{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:$.description||"No description"}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:[b.filter(ee=>ee.category_id===$.id).length," templates"]})]})]},$.id))})]})]}),e.jsx(bs,{open:o,onOpenChange:c,children:e.jsxs(vs,{className:"sm:max-w-[700px] max-h-[90vh] overflow-y-auto",children:[e.jsx(Cs,{children:e.jsx(Ns,{children:n?"Edit Template":"New Template"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{children:"Title"}),e.jsx(Se,{value:m.title,onChange:$=>p(ee=>({...ee,title:$.target.value})),placeholder:"e.g. Quick Check-in"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{children:"Category"}),e.jsxs(Bs,{value:m.category_id,onValueChange:$=>p(ee=>({...ee,category_id:$})),children:[e.jsx(Os,{children:e.jsx(Us,{placeholder:"Select category"})}),e.jsx(Fs,{children:_.map($=>e.jsxs(pt,{value:$.id,children:[$.icon," ",$.name]},$.id))})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{children:"Subject Line"}),e.jsx(Se,{value:m.subject,onChange:$=>p(ee=>({...ee,subject:$.target.value})),placeholder:"e.g. Hey {{first_name}}, just checking in!"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Use ","{{first_name}}",", ","{{last_name}}",", ","{{full_name}}"," for merge variables"]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{children:"Email Body"}),e.jsx(vr,{value:m.body,onChange:$=>p(ee=>({...ee,body:$.target.value})),rows:12,placeholder:"Write your email template...",className:"resize-y"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{children:"Description (internal)"}),e.jsx(Se,{value:m.description,onChange:$=>p(ee=>({...ee,description:$.target.value})),placeholder:"Short description for admin reference"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{children:"Tone"}),e.jsx(Se,{value:m.tone,onChange:$=>p(ee=>({...ee,tone:$.target.value})),placeholder:"e.g. Warm & Casual"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Or,{checked:m.is_active,onCheckedChange:$=>p(ee=>({...ee,is_active:$}))}),e.jsx(ue,{children:"Active"})]})]}),e.jsxs(wn,{children:[e.jsx(H,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsxs(H,{onClick:()=>k.mutate({...m,id:n==null?void 0:n.id}),disabled:k.isPending||!m.title||!m.subject||!m.body,children:[k.isPending&&e.jsx(is,{className:"h-4 w-4 mr-2 animate-spin"}),n?"Save Changes":"Create Template"]})]})]})}),e.jsx(bs,{open:d,onOpenChange:h,children:e.jsxs(vs,{className:"sm:max-w-[450px]",children:[e.jsx(Cs,{children:e.jsx(Ns,{children:i?"Edit Category":"New Category"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-[60px_1fr] gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{children:"Icon"}),e.jsx(Se,{value:x.icon,onChange:$=>y(ee=>({...ee,icon:$.target.value})),className:"text-center text-lg"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{children:"Name"}),e.jsx(Se,{value:x.name,onChange:$=>y(ee=>({...ee,name:$.target.value})),placeholder:"e.g. Check-in & Stay in Touch"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{children:"Description"}),e.jsx(Se,{value:x.description,onChange:$=>y(ee=>({...ee,description:$.target.value})),placeholder:"Brief description of this category"})]})]}),e.jsxs(wn,{children:[e.jsx(H,{variant:"outline",onClick:()=>h(!1),children:"Cancel"}),e.jsxs(H,{onClick:()=>E.mutate({...x,id:i==null?void 0:i.id}),disabled:E.isPending||!x.name,children:[E.isPending&&e.jsx(is,{className:"h-4 w-4 mr-2 animate-spin"}),i?"Save Changes":"Create Category"]})]})]})})]})})}const BIs=({brokerageId:s})=>{var Cr,Gt;const{toast:t}=li(),r=Fr(),[n,a]=S.useState([]),[i,l]=S.useState(!0),[o,c]=S.useState(""),[d,h]=S.useState("all"),[m,p]=S.useState(new Set),[x,y]=S.useState(!1),[_,b]=S.useState({}),[j,k]=S.useState(!1),[T,E]=S.useState(!1),[A,D]=S.useState({email:"",name:"",password:"",phone:""}),[R,z]=S.useState(!1),[O,$]=S.useState(null),[ee,Z]=S.useState(!1),[J,K]=S.useState(!1),[re,ie]=S.useState(!1),[ce,ne]=S.useState(""),[le,be]=S.useState(!1),[fe,je]=S.useState([]),[ve,We]=S.useState(!1),[Ve,Le]=S.useState(!1),[Me,ze]=S.useState(null),[Pe,Ie]=S.useState({name:"",phone:"",email:""}),[De,pe]=S.useState(!1),[tt,ge]=S.useState(!1),[ct,Ue]=S.useState(null),[et,Qe]=S.useState("asc"),[Ne,$e]=S.useState(!1),[it,Je]=S.useState(null),[st,mt]=S.useState(!1),[wt,at]=S.useState(null),[rt,Et]=S.useState(""),[hs,Is]=S.useState(!1),[lr,us]=S.useState(null);S.useEffect(()=>{xs(),St()},[s]);const St=async()=>{try{const{data:Ee,error:He}=await V.from("brokerage_manager_assignments").select("user_id").eq("brokerage_id",s);if(He)throw He;je((Ee==null?void 0:Ee.map(ot=>ot.user_id))||[])}catch(Ee){console.error("Error loading brokerage managers:",Ee)}},xs=async()=>{try{l(!0);const{data:Ee,error:He}=await V.functions.invoke("get-brokerage-agents",{body:{brokerageId:s}});if(He)throw He;const ot=Ee.agents||[];if(a(ot),ot.length>0){const jt=ot.map(qt=>qt.id),{data:Dt}=await V.from("agent_assistant_assignments").select("agent_id, assistant_id").in("agent_id",jt);if(Dt&&Dt.length>0){const qt=Dt.map(ls=>ls.assistant_id),{data:ss}=await V.from("profiles").select("id, name, email").in("id",qt),Yt={};for(const ls of Dt){const Xs=ss==null?void 0:ss.find(Rs=>Rs.id===ls.assistant_id);Xs&&(Yt[ls.agent_id]={name:Xs.name||"",email:Xs.email||""})}b(Yt)}else b({})}}catch(Ee){console.error("Error loading agents:",Ee),t({title:"Error",description:"Failed to load agents",variant:"destructive"})}finally{l(!1)}},kt=async()=>{if(!A.email||!A.name||!A.password){t({title:"Error",description:"Please fill in all fields",variant:"destructive"});return}E(!0);try{const{data:{session:Ee}}=await V.auth.getSession(),He=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/create-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Ee==null?void 0:Ee.access_token}`},body:JSON.stringify({...A,brokerageId:s})}),ot=await He.json();if(!He.ok)throw new Error(ot.error||"Failed to create agent");t({title:"Success",description:`Agent ${A.email} created successfully`}),D({email:"",name:"",password:"",phone:""}),k(!1),xs()}catch(Ee){console.error("Error creating agent:",Ee),t({title:"Error",description:Ee.message||"Failed to create agent",variant:"destructive"})}finally{E(!1)}},fs=async Ee=>{try{const{data:{session:He}}=await V.auth.getSession(),ot=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/resend-welcome-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${He==null?void 0:He.access_token}`},body:JSON.stringify({userId:Ee})}),jt=await ot.json();if(!ot.ok)throw new Error(jt.error||"Failed to resend welcome email");t({title:"Success",description:"Welcome email sent successfully"})}catch(He){console.error("Error resending welcome email:",He),t({title:"Error",description:He.message||"Failed to resend welcome email",variant:"destructive"})}},Gs=async(Ee,He)=>{try{const{error:ot}=await V.functions.invoke("send-password-reset",{body:{email:Ee,redirectTo:window.location.origin}});if(ot)throw ot;t({title:"Password Reset Sent",description:`Password reset email sent to ${He}`})}catch(ot){console.error("Error sending password reset:",ot),t({title:"Error",description:ot.message||"Failed to send password reset email",variant:"destructive"})}},_s=Ee=>{$(Ee),z(!0)},br=Ee=>{ze(Ee),Ie({name:Ee.name,phone:Ee.phone||"",email:Ee.email}),Le(!0)},zr=async()=>{if(!Me)return;if(!Pe.name.trim()){t({title:"Error",description:"Name is required",variant:"destructive"});return}const Ee=Pe.email.trim().toLowerCase()!==Me.email.toLowerCase();pe(!0);try{if(Ee){if(!Pe.email.trim())throw new Error("Email is required");ge(!0);const{data:{session:ot}}=await V.auth.getSession(),jt=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/update-agent-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${ot==null?void 0:ot.access_token}`},body:JSON.stringify({agentId:Me.id,newEmail:Pe.email.trim(),brokerageId:s})}),Dt=await jt.json();if(ge(!1),!jt.ok)throw new Error(Dt.error||"Failed to update email")}const{error:He}=await V.from("profiles").update({name:Pe.name.trim(),phone:Pe.phone.trim()||null}).eq("id",Me.id);if(He)throw He;t({title:"Success",description:"Agent profile updated successfully"}),Le(!1),ze(null),xs()}catch(He){console.error("Error updating agent:",He),t({title:"Error",description:He.message||"Failed to update agent",variant:"destructive"})}finally{pe(!1),ge(!1)}},Yr=async()=>{if(!ce){t({title:"Error",description:"Please select an agent to promote",variant:"destructive"});return}be(!0);try{const{data:{session:Ee}}=await V.auth.getSession(),He=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Ee==null?void 0:Ee.access_token}`},body:JSON.stringify({userId:ce,role:"brokerage_manager",action:"add",brokerageId:s})}),ot=await He.json();if(!He.ok)throw new Error(ot.error||"Failed to add brokerage manager");t({title:"Success",description:"Brokerage manager added successfully"}),ie(!1),ne(""),St()}catch(Ee){console.error("Error adding brokerage manager:",Ee),t({title:"Error",description:Ee.message||"Failed to add brokerage manager",variant:"destructive"})}finally{be(!1)}},rn=async Ee=>{try{const{data:{session:He}}=await V.auth.getSession(),ot=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${He==null?void 0:He.access_token}`},body:JSON.stringify({userId:Ee,role:"brokerage_manager",action:"remove",brokerageId:s})}),jt=await ot.json();if(!ot.ok)throw new Error(jt.error||"Failed to remove brokerage manager");t({title:"Success",description:"Brokerage manager role removed"}),St()}catch(He){console.error("Error removing brokerage manager:",He),t({title:"Error",description:He.message||"Failed to remove brokerage manager",variant:"destructive"})}},sn=Ee=>fe.includes(Ee),Vr=Ee=>{at(Ee),Et(""),mt(!0)},$r=async()=>{if(!(!wt||!rt)){if(rt.length<6){t({title:"Error",description:"Password must be at least 6 characters",variant:"destructive"});return}Is(!0);try{const{data:{session:Ee}}=await V.auth.getSession(),He=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/update-agent-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Ee==null?void 0:Ee.access_token}`},body:JSON.stringify({agentId:wt.id,brokerageId:s,action:"set_password",newPassword:rt})}),ot=await He.json();if(!He.ok)throw new Error(ot.error||"Failed to set password");t({title:"Success",description:`Password set for ${wt.name}`}),mt(!1),at(null),Et("")}catch(Ee){console.error("Error setting password:",Ee),t({title:"Error",description:Ee.message||"Failed to set password",variant:"destructive"})}finally{Is(!1)}}},hn=async Ee=>{us(Ee.id);try{const{data:{session:He}}=await V.auth.getSession(),ot=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/update-agent-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${He==null?void 0:He.access_token}`},body:JSON.stringify({agentId:Ee.id,brokerageId:s,action:"claim_account"})}),jt=await ot.json();if(!ot.ok)throw new Error(jt.error||"Failed to claim account");t({title:"Success",description:`Account claimed for ${Ee.name}`}),xs()}catch(He){console.error("Error claiming account:",He),t({title:"Error",description:He.message||"Failed to claim account",variant:"destructive"})}finally{us(null)}},Zn=async()=>{if(O){Z(!0);try{const{data:{session:Ee}}=await V.auth.getSession(),He=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/remove-agent",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Ee==null?void 0:Ee.access_token}`},body:JSON.stringify({userId:O.id,brokerageId:s})}),ot=await He.json();if(!He.ok)throw new Error(ot.error||"Failed to remove agent");t({title:"Success",description:`${O.name} has been removed from your brokerage`}),z(!1),$(null),xs()}catch(Ee){console.error("Error removing agent:",Ee),t({title:"Error",description:Ee.message||"Failed to remove agent",variant:"destructive"})}finally{Z(!1)}}},cr=Ee=>{const He=Ee.trim().split(" ");return He.length>1?He[He.length-1].toLowerCase():Ee.toLowerCase()},on=Ee=>{ct===Ee?Qe(et==="asc"?"desc":"asc"):(Ue(Ee),Qe("asc"))},ds=Ee=>ct!==Ee?e.jsx(qu,{className:"ml-1 h-4 w-4"}):et==="asc"?e.jsx(Hu,{className:"ml-1 h-4 w-4"}):e.jsx(fm,{className:"ml-1 h-4 w-4"}),Na=n.filter(Ee=>{if(d==="active"&&!Ee.claimed||d==="pending"&&Ee.claimed)return!1;if(!o)return!0;const He=o.toLowerCase();return Ee.name.toLowerCase().includes(He)||Ee.email.toLowerCase().includes(He)}),vn=[...Na].sort((Ee,He)=>{if(!ct)return 0;let ot=0;return ct==="name"?ot=cr(Ee.name).localeCompare(cr(He.name)):ct==="status"&&(ot=Ee.claimed===He.claimed?0:Ee.claimed?-1:1),et==="asc"?ot:-ot});Na.filter(Ee=>Ee.claimed&&!sn(Ee.id));const _r=Ee=>{p(He=>{const ot=new Set(He);return ot.has(Ee)?ot.delete(Ee):ot.add(Ee),ot})},Hr=()=>{m.size===vn.length?p(new Set):p(new Set(vn.map(Ee=>Ee.id)))},_a=()=>{p(new Set)},Jt=async()=>{const Ee=Array.from(m);if(Ee.length===0)return;y(!0);let He=0,ot=0;try{const{data:{session:jt}}=await V.auth.getSession();for(const Dt of Ee)try{(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/resend-welcome-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${jt==null?void 0:jt.access_token}`},body:JSON.stringify({userId:Dt})})).ok?He++:ot++}catch{ot++}He>0?t({title:"Success",description:`Welcome emails sent to ${He} agent${He>1?"s":""}${ot>0?` (${ot} failed)`:""}`}):t({title:"Error",description:"Failed to send welcome emails",variant:"destructive"}),_a()}catch(jt){console.error("Error bulk sending welcome emails:",jt),t({title:"Error",description:jt.message||"Failed to send welcome emails",variant:"destructive"})}finally{y(!1)}};return i?e.jsx(ke,{children:e.jsx(Oe,{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):e.jsxs(e.Fragment,{children:[e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(zt,{children:"Agents"}),e.jsx(Br,{children:"Manage your brokerage's agents"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(H,{variant:"outline",onClick:()=>ie(!0),children:[e.jsx(Fh,{className:"mr-2 h-4 w-4"}),"Add Brokerage Manager"]}),e.jsxs(H,{variant:"outline",onClick:()=>K(!0),children:[e.jsx($2,{className:"mr-2 h-4 w-4"}),"Import CSV"]}),e.jsxs(H,{onClick:()=>k(!0),children:[e.jsx(Vl,{className:"mr-2 h-4 w-4"}),"Add Agent"]})]})]})}),e.jsxs(Oe,{children:[e.jsxs("div",{className:"mb-4 flex flex-col gap-4 sm:flex-row sm:items-center",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Mn,{className:"absolute left-3 top-3 h-4 w-4 text-muted-foreground"}),e.jsx(Se,{placeholder:"Search agents...",value:o,onChange:Ee=>c(Ee.target.value),className:"pl-9"})]}),e.jsxs(Bs,{value:d,onValueChange:Ee=>h(Ee),children:[e.jsx(Os,{className:"w-[160px]",children:e.jsx(Us,{placeholder:"Filter by status"})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"all",children:"All Agents"}),e.jsx(pt,{value:"active",children:"Active"}),e.jsx(pt,{value:"pending",children:"Pending"})]})]})]}),m.size>0&&e.jsxs("div",{className:"mb-4 flex items-center gap-3 rounded-lg border bg-muted/50 p-3",children:[e.jsxs("span",{className:"text-sm font-medium",children:[m.size," agent",m.size>1?"s":""," selected"]}),e.jsx("div",{className:"flex-1"}),e.jsxs(H,{size:"sm",variant:"outline",onClick:()=>{const He=n.filter(ot=>m.has(ot.id)&&ot.email).map(ot=>({email:ot.email,name:ot.name}));sessionStorage.setItem("campaign_direct_recipients",JSON.stringify(He)),r("/admin/email-campaigns/new?directMode=1",{state:{directRecipients:He}})},disabled:x,children:[e.jsx(ph,{className:"mr-2 h-4 w-4"}),"Email Agents (",m.size,")"]}),e.jsxs(H,{size:"sm",variant:"outline",onClick:Jt,disabled:x,children:[e.jsx(er,{className:"mr-2 h-4 w-4"}),x?"Sending...":"Resend Welcome Email"]}),e.jsx(H,{size:"sm",variant:"ghost",onClick:_a,children:"Clear"})]}),e.jsx("div",{className:"rounded-md border",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Vs,{children:[e.jsx(At,{className:"w-[40px]",children:e.jsx(ao,{checked:vn.length>0&&m.size===vn.length,onCheckedChange:Hr,"aria-label":"Select all"})}),e.jsx(At,{children:e.jsxs(H,{variant:"ghost",size:"sm",className:"-ml-3 h-8 hover:bg-transparent",onClick:()=>on("name"),children:["Name (Last)",ds("name")]})}),e.jsx(At,{children:"Email"}),e.jsx(At,{children:e.jsxs(H,{variant:"ghost",size:"sm",className:"-ml-3 h-8 hover:bg-transparent",onClick:()=>on("status"),children:["Status",ds("status")]})}),e.jsx(At,{children:"Actions"})]})}),e.jsx(da,{children:vn.length===0?e.jsx(Vs,{children:e.jsx(gt,{colSpan:5,className:"text-center text-muted-foreground",children:"No agents found"})}):vn.map(Ee=>e.jsxs(Vs,{children:[e.jsx(gt,{children:e.jsx(ao,{checked:m.has(Ee.id),onCheckedChange:()=>_r(Ee.id),"aria-label":`Select ${Ee.name}`})}),e.jsx(gt,{className:"font-medium",children:Ee.name}),e.jsx(gt,{children:Ee.email}),e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[Ee.claimed?e.jsx(Xe,{variant:"default",children:"Active"}):e.jsx(Xe,{variant:"secondary",children:"Pending"}),sn(Ee.id)&&e.jsxs(Xe,{variant:"outline",className:"border-primary text-primary",children:[e.jsx(w1,{className:"mr-1 h-3 w-3"}),"Manager"]}),_[Ee.id]&&e.jsxs(Xe,{variant:"outline",className:"text-xs",children:[e.jsx(Ar,{className:"mr-1 h-3 w-3"}),"Asst: ",_[Ee.id].name||_[Ee.id].email]})]})}),e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-1 flex-wrap",children:[e.jsx(H,{size:"sm",variant:"ghost",onClick:()=>{Je(Ee),$e(!0)},title:"Send celebration",className:"text-yellow-500 hover:text-yellow-600 hover:bg-yellow-50",children:e.jsx(gh,{className:"h-4 w-4"})}),e.jsx(H,{size:"sm",variant:"ghost",onClick:()=>br(Ee),title:"Edit agent",children:e.jsx(ni,{className:"h-4 w-4"})}),!Ee.claimed&&e.jsxs(e.Fragment,{children:[e.jsx(H,{size:"sm",variant:"ghost",onClick:()=>fs(Ee.id),title:"Resend welcome email",children:e.jsx(er,{className:"h-4 w-4"})}),e.jsx(H,{size:"sm",variant:"ghost",onClick:()=>hn(Ee),title:"Claim account for agent",disabled:lr===Ee.id,className:"text-green-600 hover:text-green-700 hover:bg-green-50",children:e.jsx(j1,{className:"h-4 w-4"})})]}),e.jsx(H,{size:"sm",variant:"ghost",onClick:()=>Vr(Ee),title:"Set password",className:"text-blue-600 hover:text-blue-700 hover:bg-blue-50",children:e.jsx(Td,{className:"h-4 w-4"})}),e.jsx(H,{size:"sm",variant:"ghost",onClick:()=>Gs(Ee.email,Ee.name),title:"Send password reset email",children:e.jsx(_E,{className:"h-4 w-4"})}),sn(Ee.id)&&e.jsx(H,{size:"sm",variant:"ghost",onClick:()=>rn(Ee.id),title:"Remove manager role",className:"text-orange-500 hover:text-orange-600",children:e.jsx(Fh,{className:"h-4 w-4"})}),e.jsx(H,{size:"sm",variant:"ghost",onClick:()=>_s(Ee),className:"text-destructive hover:text-destructive",title:"Remove agent",children:e.jsx(Dr,{className:"h-4 w-4"})})]})})]},Ee.id))})]})})]})]}),e.jsx(bs,{open:j,onOpenChange:k,children:e.jsxs(vs,{children:[e.jsxs(Cs,{children:[e.jsx(Ns,{children:"Add New Agent"}),e.jsx(nn,{children:"Create a new agent account. They'll receive an email to set up their account."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"name",children:"Name"}),e.jsx(Se,{id:"name",value:A.name,onChange:Ee=>D({...A,name:Ee.target.value}),placeholder:"John Doe"})]}),e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"email",children:"Email"}),e.jsx(Se,{id:"email",type:"email",value:A.email,onChange:Ee=>D({...A,email:Ee.target.value}),placeholder:"john@example.com"})]}),e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"phone",children:"Phone (optional)"}),e.jsx(Se,{id:"phone",type:"tel",value:A.phone,onChange:Ee=>D({...A,phone:Ee.target.value}),placeholder:"555-123-4567"})]}),e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"password",children:"Temporary Password"}),e.jsx(Se,{id:"password",type:"password",value:A.password,onChange:Ee=>D({...A,password:Ee.target.value}),placeholder:"Temporary password"})]})]}),e.jsxs(wn,{children:[e.jsx(H,{variant:"outline",onClick:()=>k(!1),children:"Cancel"}),e.jsx(H,{onClick:kt,disabled:T,children:T?"Creating...":"Create Agent"})]})]})}),e.jsx(bs,{open:R,onOpenChange:z,children:e.jsxs(vs,{children:[e.jsxs(Cs,{children:[e.jsx(Ns,{children:"Remove Agent"}),e.jsxs(nn,{children:["Are you sure you want to remove ",e.jsx("strong",{children:O==null?void 0:O.name})," from your brokerage? This will revoke their access to the dashboard."]})]}),e.jsxs(wn,{children:[e.jsx(H,{variant:"outline",onClick:()=>z(!1),children:"Cancel"}),e.jsx(H,{variant:"destructive",onClick:Zn,disabled:ee,children:ee?"Removing...":"Remove Agent"})]})]})}),e.jsx(uht,{open:J,onOpenChange:K,fixedBrokerageId:s,onSuccess:xs}),e.jsx(bs,{open:re,onOpenChange:ie,children:e.jsxs(vs,{children:[e.jsxs(Cs,{children:[e.jsx(Ns,{children:"Add Brokerage Manager"}),e.jsx(nn,{children:"Promote an existing active agent to brokerage manager. They will be able to manage agents and view analytics."})]}),e.jsx("div",{className:"space-y-4",children:e.jsxs("div",{children:[e.jsx(ue,{children:"Select Agent"}),e.jsxs(gl,{open:ve,onOpenChange:We,children:[e.jsx(xl,{asChild:!0,children:e.jsxs(H,{variant:"outline",role:"combobox","aria-expanded":ve,className:"w-full justify-between",children:[ce?((Cr=n.find(Ee=>Ee.id===ce))==null?void 0:Cr.name)+" ("+((Gt=n.find(Ee=>Ee.id===ce))==null?void 0:Gt.email)+")":"Select an agent to promote...",e.jsx(d0,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(il,{className:"w-full p-0",align:"start",children:e.jsxs(k0,{children:[e.jsx(S0,{placeholder:"Search by name or email..."}),e.jsxs(C0,{className:"max-h-[200px]",children:[e.jsx(T0,{children:"No eligible agents found."}),e.jsx(E0,{children:n.filter(Ee=>!sn(Ee.id)).map(Ee=>e.jsxs(fg,{value:`${Ee.name} ${Ee.email}`,onSelect:()=>{ne(Ee.id),We(!1)},children:[e.jsx(va,{className:`mr-2 h-4 w-4 ${ce===Ee.id?"opacity-100":"opacity-0"}`}),Ee.name," (",Ee.email,")"]},Ee.id))})]})]})})]}),n.filter(Ee=>!sn(Ee.id)).length===0&&e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"All agents are already brokerage managers."})]})}),e.jsxs(wn,{children:[e.jsx(H,{variant:"outline",onClick:()=>ie(!1),children:"Cancel"}),e.jsx(H,{onClick:Yr,disabled:le||!ce,children:le?"Adding...":"Add as Manager"})]})]})}),e.jsx(bs,{open:Ve,onOpenChange:Le,children:e.jsxs(vs,{children:[e.jsxs(Cs,{children:[e.jsx(Ns,{children:"Edit Agent"}),e.jsxs(nn,{children:["Update profile information for ",Me==null?void 0:Me.name]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"edit-name",children:"Name"}),e.jsx(Se,{id:"edit-name",value:Pe.name,onChange:Ee=>Ie({...Pe,name:Ee.target.value}),placeholder:"Agent name"})]}),e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"edit-email",children:"Email"}),e.jsx(Se,{id:"edit-email",type:"email",value:Pe.email,onChange:Ee=>Ie({...Pe,email:Ee.target.value}),placeholder:"agent@example.com"}),Pe.email.trim().toLowerCase()!==(Me==null?void 0:Me.email.toLowerCase())&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Changing email will update their login credentials"})]}),e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"edit-phone",children:"Phone"}),e.jsx(Se,{id:"edit-phone",type:"tel",value:Pe.phone,onChange:Ee=>Ie({...Pe,phone:Ee.target.value}),placeholder:"555-123-4567"})]})]}),e.jsxs(wn,{children:[e.jsx(H,{variant:"outline",onClick:()=>Le(!1),children:"Cancel"}),e.jsx(H,{onClick:zr,disabled:De||tt,children:tt?"Updating email...":De?"Saving...":"Save Changes"})]})]})}),it&&e.jsx(hht,{open:Ne,onOpenChange:Ee=>{$e(Ee),Ee||Je(null)},userId:it.id,userName:it.name}),e.jsx(bs,{open:st,onOpenChange:mt,children:e.jsxs(vs,{children:[e.jsxs(Cs,{children:[e.jsx(Ns,{children:"Set Password"}),e.jsxs(nn,{children:["Set a new password for ",wt==null?void 0:wt.name,". They will be able to log in with this password immediately."]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"new-password",children:"New Password"}),e.jsx(Se,{id:"new-password",type:"password",value:rt,onChange:Ee=>Et(Ee.target.value),placeholder:"Enter new password (min 6 characters)"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Make sure to communicate this password to the agent through a secure channel."})]}),e.jsxs(wn,{children:[e.jsx(H,{variant:"outline",onClick:()=>mt(!1),children:"Cancel"}),e.jsx(H,{onClick:$r,disabled:hs||!rt||rt.length<6,children:hs?"Setting...":"Set Password"})]})]})})]})},zIs={academy_video:"Academy Video",template:"Template",toolbox:"Toolbox Resource",newsletter:"Newsletter",social_swag:"Social Swag",event:"Event"},$Is={view:"Viewed",click_canva:"Opened Canva",click_pdf:"Downloaded PDF",click_video:"Watched Video",click_link:"Clicked Link",register:"Registered"},UIs=s=>{switch(s){case"academy_video":return e.jsx(xn,{className:"h-4 w-4"});case"template":return e.jsx(kn,{className:"h-4 w-4"});case"toolbox":return e.jsx(kn,{className:"h-4 w-4"});case"newsletter":return e.jsx(x_,{className:"h-4 w-4"});case"social_swag":return e.jsx(Lr,{className:"h-4 w-4"});case"event":return e.jsx(Nn,{className:"h-4 w-4"});default:return e.jsx(gn,{className:"h-4 w-4"})}},qIs=({brokerageId:s})=>{const{toast:t}=li(),[r,n]=S.useState([]),[a,i]=S.useState([]),[l,o]=S.useState([]),[c,d]=S.useState(!0),[h,m]=S.useState(null);S.useEffect(()=>{p()},[s]);const p=async()=>{try{d(!0);const{data:_,error:b}=await V.from("profiles").select("id, name, email").eq("brokerage_id",s);if(b)throw b;const j=_.map(ee=>ee.id),k=new Map(_.map(ee=>[ee.id,ee]));if(j.length===0){n([]),i([]),o([]);return}const{data:T,error:E}=await V.from("activity_logs").select("*").in("user_id",j).order("launched_at",{ascending:!1});if(E)throw E;const A=T.map(ee=>{var Z,J;return{id:ee.id,user_id:ee.user_id,app_name:ee.app_name,launched_at:ee.launched_at,user_name:((Z=k.get(ee.user_id))==null?void 0:Z.name)||"Unknown",user_email:((J=k.get(ee.user_id))==null?void 0:J.email)||"Unknown"}});n(A);const{data:D,error:R}=await V.from("content_engagement_logs").select("*").in("user_id",j).order("created_at",{ascending:!1});if(R)throw R;const z=(D||[]).map(ee=>{var Z,J;return{id:ee.id,user_id:ee.user_id,resource_type:ee.resource_type,resource_id:ee.resource_id,resource_title:ee.resource_title,action_type:ee.action_type,created_at:ee.created_at,user_name:((Z=k.get(ee.user_id))==null?void 0:Z.name)||"Unknown",user_email:((J=k.get(ee.user_id))==null?void 0:J.email)||"Unknown"}});i(z);const O=new Map;_.forEach(ee=>{O.set(ee.id,{user_id:ee.id,user_name:ee.name,user_email:ee.email,app_launches:0,content_views:0,last_activity:""})}),A.forEach(ee=>{const Z=O.get(ee.user_id);Z&&(Z.app_launches++,(!Z.last_activity||new Date(ee.launched_at)>new Date(Z.last_activity))&&(Z.last_activity=ee.launched_at))}),z.forEach(ee=>{const Z=O.get(ee.user_id);Z&&(Z.content_views++,(!Z.last_activity||new Date(ee.created_at)>new Date(Z.last_activity))&&(Z.last_activity=ee.created_at))});const $=Array.from(O.values()).filter(ee=>ee.app_launches>0||ee.content_views>0).sort((ee,Z)=>new Date(Z.last_activity).getTime()-new Date(ee.last_activity).getTime());o($)}catch(_){console.error("Error loading activity:",_),t({title:"Error",description:"Failed to load activity logs",variant:"destructive"})}finally{d(!1)}},x=_=>r.filter(b=>b.user_id===_),y=_=>a.filter(b=>b.user_id===_);return c?e.jsx(ke,{children:e.jsx(Oe,{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):e.jsxs(e.Fragment,{children:[e.jsxs(ke,{children:[e.jsxs(Ot,{children:[e.jsx(zt,{children:"Agent Activity"}),e.jsx(Br,{children:"Track app usage and content engagement - click an agent for details"})]}),e.jsx(Oe,{children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Vs,{children:[e.jsx(At,{children:"Agent"}),e.jsx(At,{className:"text-center",children:"App Launches"}),e.jsx(At,{className:"text-center",children:"Content Views"}),e.jsx(At,{children:"Last Active"})]})}),e.jsx(da,{children:l.length===0?e.jsx(Vs,{children:e.jsx(gt,{colSpan:4,className:"text-center text-muted-foreground",children:"No activity yet"})}):l.map(_=>e.jsxs(Vs,{className:"cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>m({id:_.user_id,name:_.user_name,email:_.user_email}),children:[e.jsx(gt,{children:e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:_.user_name}),e.jsx("div",{className:"text-sm text-muted-foreground",children:_.user_email})]})}),e.jsx(gt,{className:"text-center",children:e.jsxs(Xe,{variant:"outline",className:"gap-1",children:[e.jsx(El,{className:"h-3 w-3"}),_.app_launches]})}),e.jsx(gt,{className:"text-center",children:e.jsxs(Xe,{variant:"secondary",className:"gap-1",children:[e.jsx(kn,{className:"h-3 w-3"}),_.content_views]})}),e.jsx(gt,{className:"text-sm text-muted-foreground",children:_.last_activity&&Hl(new Date(_.last_activity),{addSuffix:!0})})]},_.user_id))})]})})})]}),e.jsx(bs,{open:!!h,onOpenChange:_=>!_&&m(null),children:e.jsxs(vs,{className:"max-w-3xl max-h-[80vh] overflow-hidden flex flex-col",children:[e.jsxs(Cs,{children:[e.jsxs(Ns,{children:[h==null?void 0:h.name,"'s Activity"]}),e.jsx(nn,{children:h==null?void 0:h.email})]}),e.jsxs(ta,{defaultValue:"content",className:"flex-1 overflow-hidden flex flex-col",children:[e.jsxs(Qn,{className:"grid w-full grid-cols-2",children:[e.jsx(ts,{value:"content",children:"Content Engagement"}),e.jsx(ts,{value:"apps",children:"App Launches"})]}),e.jsx(cs,{value:"content",className:"flex-1 overflow-auto",children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Vs,{children:[e.jsx(At,{children:"Resource"}),e.jsx(At,{children:"Type"}),e.jsx(At,{children:"Action"}),e.jsx(At,{children:"Time"})]})}),e.jsx(da,{children:h&&y(h.id).length===0?e.jsx(Vs,{children:e.jsx(gt,{colSpan:4,className:"text-center text-muted-foreground",children:"No content engagement yet"})}):h&&y(h.id).map(_=>e.jsxs(Vs,{children:[e.jsx(gt,{className:"max-w-[200px] truncate font-medium",children:_.resource_title}),e.jsx(gt,{children:e.jsxs(Xe,{variant:"outline",className:"gap-1",children:[UIs(_.resource_type),zIs[_.resource_type]||_.resource_type]})}),e.jsx(gt,{children:e.jsx("span",{className:"text-sm text-muted-foreground",children:$Is[_.action_type]||_.action_type})}),e.jsx(gt,{className:"text-sm text-muted-foreground",children:Hl(new Date(_.created_at),{addSuffix:!0})})]},_.id))})]})})}),e.jsx(cs,{value:"apps",className:"flex-1 overflow-auto",children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Vs,{children:[e.jsx(At,{children:"App"}),e.jsx(At,{children:"Time"})]})}),e.jsx(da,{children:h&&x(h.id).length===0?e.jsx(Vs,{children:e.jsx(gt,{colSpan:2,className:"text-center text-muted-foreground",children:"No app launches yet"})}):h&&x(h.id).map(_=>e.jsxs(Vs,{children:[e.jsx(gt,{children:e.jsx(Xe,{variant:"outline",children:_.app_name})}),e.jsx(gt,{className:"text-sm text-muted-foreground",children:Hl(new Date(_.launched_at),{addSuffix:!0})})]},_.id))})]})})})]})]})})]})},VIs=({brokerageId:s})=>{const{toast:t}=li(),[r,n]=S.useState({totalAgents:0,activeAgents:0,pendingAgents:0,totalLaunches:0,launchesThisWeek:0,launchesThisMonth:0}),[a,i]=S.useState(!0);S.useEffect(()=>{l()},[s]);const l=async()=>{try{i(!0);const{data:o,error:c}=await V.from("profiles").select("id").eq("brokerage_id",s);if(c)throw c;const d=o.map(A=>A.id),h=d.length;if(d.length===0){i(!1);return}const{data:m,error:p}=await V.from("profiles").select("id, email").in("id",d);if(p)throw p;const{count:x}=await V.from("profiles").select("*",{count:"exact",head:!0}).eq("brokerage_id",s).not("last_login","is",null),y=x||0,_=h-y,{count:b}=await V.from("activity_logs").select("*",{count:"exact",head:!0}).in("user_id",d),j=new Date;j.setDate(j.getDate()-7);const{count:k}=await V.from("activity_logs").select("*",{count:"exact",head:!0}).in("user_id",d).gte("launched_at",j.toISOString()),T=new Date;T.setMonth(T.getMonth()-1);const{count:E}=await V.from("activity_logs").select("*",{count:"exact",head:!0}).in("user_id",d).gte("launched_at",T.toISOString());n({totalAgents:h,activeAgents:y,pendingAgents:_,totalLaunches:b||0,launchesThisWeek:k||0,launchesThisMonth:E||0})}catch(o){console.error("Error loading analytics:",o),t({title:"Error",description:"Failed to load analytics",variant:"destructive"})}finally{i(!1)}};return a?e.jsx(ke,{children:e.jsx(Oe,{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):e.jsxs("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:[e.jsxs(ke,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(zt,{className:"text-sm font-medium",children:"Total Agents"}),e.jsx(Ar,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Oe,{children:[e.jsx("div",{className:"text-2xl font-bold",children:r.totalAgents}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[r.activeAgents," active, ",r.pendingAgents," pending"]})]})]}),e.jsxs(ke,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(zt,{className:"text-sm font-medium",children:"Active Agents"}),e.jsx(zi,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Oe,{children:[e.jsx("div",{className:"text-2xl font-bold",children:r.activeAgents}),e.jsx("p",{className:"text-xs text-muted-foreground",children:r.totalAgents>0?`${Math.round(r.activeAgents/r.totalAgents*100)}% of total`:"0% of total"})]})]}),e.jsxs(ke,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(zt,{className:"text-sm font-medium",children:"Pending Invites"}),e.jsx(Pn,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Oe,{children:[e.jsx("div",{className:"text-2xl font-bold",children:r.pendingAgents}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Awaiting setup"})]})]}),e.jsxs(ke,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(zt,{className:"text-sm font-medium",children:"Total App Launches"}),e.jsx(ef,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Oe,{children:[e.jsx("div",{className:"text-2xl font-bold",children:r.totalLaunches}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"All time"})]})]}),e.jsxs(ke,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(zt,{className:"text-sm font-medium",children:"This Week"}),e.jsx(ef,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Oe,{children:[e.jsx("div",{className:"text-2xl font-bold",children:r.launchesThisWeek}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Last 7 days"})]})]}),e.jsxs(ke,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(zt,{className:"text-sm font-medium",children:"This Month"}),e.jsx(ef,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Oe,{children:[e.jsx("div",{className:"text-2xl font-bold",children:r.launchesThisMonth}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Last 30 days"})]})]})]})},HIs=({brokerageId:s})=>{const[t,r]=S.useState([]),[n,a]=S.useState(!0),[i,l]=S.useState(!1),[o,c]=S.useState(!1),[d,h]=S.useState({description:"",maxUses:""});S.useEffect(()=>{m()},[s]);const m=async()=>{try{const{data:j,error:k}=await V.from("invite_codes").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1});if(k)throw k;r(j||[])}catch(j){console.error("Error loading invite codes:",j),he.error("Failed to load invite links")}finally{a(!1)}},p=()=>Math.random().toString(36).substring(2,8).toUpperCase(),x=async()=>{l(!0);try{const j=p(),{error:k}=await V.from("invite_codes").insert({code:j,description:d.description||null,max_uses:d.maxUses?parseInt(d.maxUses):null,brokerage_id:s,is_active:!0});if(k)throw k;he.success("Invite link created!"),c(!1),h({description:"",maxUses:""}),m()}catch(j){console.error("Error creating invite code:",j),he.error("Failed to create invite link")}finally{l(!1)}},y=async j=>{try{const{error:k}=await V.from("invite_codes").delete().eq("id",j);if(k)throw k;he.success("Invite link deleted"),r(t.filter(T=>T.id!==j))}catch(k){console.error("Error deleting invite code:",k),he.error("Failed to delete invite link")}},_=async(j,k)=>{try{const{error:T}=await V.from("invite_codes").update({is_active:!k}).eq("id",j);if(T)throw T;r(t.map(E=>E.id===j?{...E,is_active:!k}:E)),he.success(`Invite link ${k?"deactivated":"activated"}`)}catch(T){console.error("Error toggling invite code:",T),he.error("Failed to update invite link")}},b=j=>{const k=`${window.location.origin}/join?code=${j}`;navigator.clipboard.writeText(k),he.success("Link copied to clipboard!")};return n?e.jsx(ke,{children:e.jsx(Oe,{className:"flex items-center justify-center py-8",children:e.jsx(is,{className:"h-6 w-6 animate-spin text-muted-foreground"})})}):e.jsxs(ke,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(Jo,{className:"h-5 w-5"}),"Agent Invite Links"]}),e.jsx(Br,{children:"Create shareable links for agents to join your brokerage"})]}),e.jsxs(bs,{open:o,onOpenChange:c,children:[e.jsx(Qi,{asChild:!0,children:e.jsxs(H,{size:"sm",children:[e.jsx(Ys,{className:"mr-2 h-4 w-4"}),"Create Link"]})}),e.jsxs(vs,{children:[e.jsxs(Cs,{children:[e.jsx(Ns,{children:"Create Invite Link"}),e.jsx(nn,{children:"Create a new invite link for agents to join your brokerage"})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"description",children:"Description (optional)"}),e.jsx(Se,{id:"description",placeholder:"e.g., New agent recruiting campaign",value:d.description,onChange:j=>h({...d,description:j.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"maxUses",children:"Max Uses (optional)"}),e.jsx(Se,{id:"maxUses",type:"number",placeholder:"Leave empty for unlimited",value:d.maxUses,onChange:j=>h({...d,maxUses:j.target.value})})]}),e.jsx(H,{onClick:x,disabled:i,className:"w-full",children:i?e.jsxs(e.Fragment,{children:[e.jsx(is,{className:"mr-2 h-4 w-4 animate-spin"}),"Creating..."]}):"Create Invite Link"})]})]})]})]}),e.jsx(Oe,{children:t.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Jo,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No invite links yet"}),e.jsx("p",{className:"text-sm",children:"Create one to start inviting agents"})]}):e.jsx("div",{className:"space-y-3",children:t.map(j=>e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border bg-card",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("code",{className:"text-sm font-mono bg-muted px-2 py-0.5 rounded",children:j.code}),e.jsx(Xe,{variant:j.is_active?"default":"secondary",children:j.is_active?"Active":"Inactive"})]}),j.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1 truncate",children:j.description}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[j.uses_count," uses",j.max_uses&&` / ${j.max_uses} max`]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(H,{variant:"ghost",size:"sm",onClick:()=>b(j.code),title:"Copy link",children:e.jsx(ui,{className:"h-4 w-4"})}),e.jsx(H,{variant:"ghost",size:"sm",onClick:()=>_(j.id,j.is_active),title:j.is_active?"Deactivate":"Activate",children:j.is_active?"Disable":"Enable"}),e.jsx(H,{variant:"ghost",size:"sm",onClick:()=>y(j.id),className:"text-destructive hover:text-destructive",title:"Delete",children:e.jsx(Dr,{className:"h-4 w-4"})})]})]},j.id))})})]})},GIs=({open:s,onOpenChange:t,referralCode:r,brokerageId:n,senderName:a,brokerageName:i,onInvitesSent:l})=>{const[o,c]=S.useState(""),[d,h]=S.useState([]),[m,p]=S.useState(""),[x,y]=S.useState(!1),_=E=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(E),b=()=>{const E=o.trim().toLowerCase();if(E&&_(E)&&!d.includes(E)){if(d.length>=10){he.error("Maximum 10 emails per invite");return}h([...d,E]),c("")}else E&&!_(E)?he.error("Please enter a valid email address"):d.includes(E)&&he.error("Email already added")},j=E=>{h(d.filter(A=>A!==E))},k=E=>{(E.key==="Enter"||E.key===",")&&(E.preventDefault(),b())},T=async()=>{if(d.length===0){he.error("Please add at least one email address");return}y(!0);try{const{data:E,error:A}=await V.functions.invoke("send-referral-invite",{body:{emails:d,personalMessage:m.trim()||void 0,referralCode:r,brokerageId:n,senderName:a,brokerageName:i}});if(A)throw A;E.successCount===E.totalCount?he.success(`${E.successCount} invite${E.successCount>1?"s":""} sent successfully!`):he.warning(`${E.successCount} of ${E.totalCount} invites sent. Some failed.`),h([]),p(""),t(!1),l==null||l()}catch(E){console.error("Error sending invites:",E),he.error("Failed to send invites. Please try again.")}finally{y(!1)}};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"sm:max-w-[550px]",children:[e.jsxs(Cs,{children:[e.jsxs(Ns,{className:"flex items-center gap-2",children:[e.jsx(er,{className:"h-5 w-5 text-primary"}),"Invite Broker Friends"]}),e.jsx(nn,{children:"Send a personalized email invitation to broker owners you know. They'll receive a beautiful email highlighting LevelUp's features."})]}),e.jsxs("div",{className:"bg-gradient-to-r from-primary/10 to-primary/5 border border-primary/20 rounded-lg p-4 flex items-center gap-3",children:[e.jsx("div",{className:"bg-primary/20 rounded-full p-2",children:e.jsx(Di,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-sm",children:"Earn $25/month for each referral!"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"When they sign up and stay for 30 days, you save on your membership forever."})]})]}),e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"email",children:"Email Addresses (up to 10)"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Se,{id:"email",type:"email",placeholder:"Enter email and press Enter",value:o,onChange:E=>c(E.target.value),onKeyDown:k,onBlur:b}),e.jsx(H,{type:"button",variant:"secondary",onClick:b,children:"Add"})]}),d.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:d.map(E=>e.jsxs(Xe,{variant:"secondary",className:"flex items-center gap-1 pr-1",children:[E,e.jsx("button",{type:"button",onClick:()=>j(E),className:"ml-1 rounded-full p-0.5 hover:bg-muted",children:e.jsx(Rr,{className:"h-3 w-3"})})]},E))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"message",children:"Personal Message (optional)"}),e.jsx(vr,{id:"message",placeholder:"Add a personal note that will appear at the top of the email...",value:m,onChange:E=>p(E.target.value),rows:3,maxLength:500}),e.jsxs("p",{className:"text-xs text-muted-foreground text-right",children:[m.length,"/500 characters"]})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-4 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium",children:[e.jsx(Lr,{className:"h-4 w-4 text-primary"}),"What they'll receive:"]}),e.jsxs("ul",{className:"text-xs text-muted-foreground space-y-1",children:[e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-1 h-1 rounded-full bg-primary"}),"Beautiful branded email from you"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-1 h-1 rounded-full bg-primary"}),"Your personal message (if added)"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-1 h-1 rounded-full bg-primary"}),"Key LevelUp features for brokerages"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-1 h-1 rounded-full bg-primary"}),"Direct signup link with your referral code"]})]})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(H,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(H,{onClick:T,disabled:d.length===0||x,children:x?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent mr-2"}),"Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(yn,{className:"h-4 w-4 mr-2"}),"Send ",d.length>0&&`(${d.length})`," Invite",d.length!==1?"s":""]})})]})]})})},WIs=({brokerageId:s,refreshTrigger:t})=>{const[r,n]=S.useState([]),[a,i]=S.useState(!0);S.useEffect(()=>{l()},[s,t]);const l=async()=>{try{const{data:c,error:d}=await V.from("referral_invites").select("*").eq("referrer_brokerage_id",s).order("sent_at",{ascending:!1}).limit(20);if(d)throw d;n(c||[])}catch(c){console.error("Error fetching invites:",c)}finally{i(!1)}},o=c=>{switch(c){case"signed_up":return e.jsxs(Xe,{className:"bg-green-100 text-green-800 gap-1",children:[e.jsx(zi,{className:"h-3 w-3"}),"Signed Up"]});case"expired":return e.jsxs(Xe,{variant:"outline",className:"text-muted-foreground gap-1",children:[e.jsx(kd,{className:"h-3 w-3"}),"Expired"]});default:return e.jsxs(Xe,{variant:"secondary",className:"gap-1",children:[e.jsx(Pn,{className:"h-3 w-3"}),"Pending"]})}};return a?e.jsx("div",{className:"flex justify-center py-4",children:e.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-primary border-t-transparent"})}):r.length===0?e.jsxs("div",{className:"text-center py-6 text-muted-foreground",children:[e.jsx(er,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No invites sent yet"}),e.jsx("p",{className:"text-xs",children:"Start inviting broker friends to earn rewards!"})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium mb-3",children:"Recent Invites"}),r.map(c=>e.jsxs("div",{className:"flex items-center justify-between p-2.5 bg-muted/30 rounded-lg",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:c.recipient_email}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Sent ",As(new Date(c.sent_at),"MMM d, yyyy")]})]}),o(c.status)]},c.id))]})},KIs=()=>{const{brokerageId:s,user:t}=Ms(),[r,n]=S.useState(null),[a,i]=S.useState(""),[l,o]=S.useState(""),[c,d]=S.useState([]),[h,m]=S.useState(!0),[p,x]=S.useState(!1),[y,_]=S.useState(0);S.useEffect(()=>{s&&b()},[s]);const b=async()=>{try{const[D,R]=await Promise.all([V.from("brokerages").select("name").eq("id",s).single(),t?V.from("profiles").select("name").eq("id",t.id).single():Promise.resolve({data:null})]);D.data&&i(D.data.name),R.data&&o(R.data.name||"A LevelUp Member");const{data:z}=await V.from("referral_codes").select("code").eq("brokerage_id",s).single();if(z)n(z.code);else{const $=`REF${s==null?void 0:s.slice(0,8).toUpperCase()}`;await V.from("referral_codes").insert({brokerage_id:s,code:$}),n($)}const{data:O}=await V.from("referrals").select(` *, referred_user:profiles!referred_user_id(name, email), referred_brokerage:brokerages!referred_brokerage_id(name) `).eq("referrer_brokerage_id",s).order("created_at",{ascending:!1});d(O||[])}catch(D){console.error("Error fetching referral data:",D)}finally{m(!1)}},j=()=>{const D=`https://dashboard.relevelup.com/?ref=${r}`;navigator.clipboard.writeText(D),he.success("Referral link copied to clipboard!")},k=c.filter(D=>D.status==="qualified").length,T=c.filter(D=>D.status==="pending").length,E=k*25,A=Math.max(0,Math.ceil((299-E)/25));return h?null:e.jsxs(e.Fragment,{children:[e.jsxs(ke,{className:"overflow-hidden",children:[e.jsx("div",{className:"bg-gradient-to-r from-primary/10 via-primary/5 to-background border-b",children:e.jsxs("div",{className:"px-6 py-6",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("div",{className:"bg-primary/20 rounded-full p-2",children:e.jsx(Di,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-bold",children:"Referral Rewards Program"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Earn $25/month off your membership for every broker you refer"})]})]}),e.jsx("div",{className:"mt-4 bg-background/80 rounded-lg p-4 border",children:e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-4",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"text-center",children:[e.jsxs("p",{className:"text-3xl font-bold text-primary",children:["$",E]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Monthly Savings"})]}),E>0&&e.jsxs("div",{className:"flex items-center gap-1 text-green-600",children:[e.jsx(zi,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm font-medium",children:"Active"})]})]}),A>0&&E<299&&e.jsxs("div",{className:"text-right",children:[e.jsxs("p",{className:"text-sm font-medium",children:["Refer ",A," more = ",e.jsx("span",{className:"text-primary",children:"FREE membership!"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Your membership could cost $0/month"})]}),E>=299&&e.jsxs("div",{className:"flex items-center gap-2 text-primary",children:[e.jsx(Lr,{className:"h-5 w-5"}),e.jsx("span",{className:"font-bold",children:"FREE Membership Unlocked!"})]})]})})]})}),e.jsxs(Oe,{className:"pt-6 space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsxs(H,{onClick:()=>x(!0),className:"w-full",size:"lg",children:[e.jsx(er,{className:"h-4 w-4 mr-2"}),"Invite Broker Friends"]}),e.jsxs(H,{onClick:j,variant:"outline",className:"w-full",size:"lg",children:[e.jsx(ui,{className:"h-4 w-4 mr-2"}),"Copy Referral Link"]})]}),e.jsxs("div",{className:"p-4 bg-muted/50 rounded-lg",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Your Referral Link"}),e.jsxs("code",{className:"block px-3 py-2 bg-background rounded border text-sm break-all",children:["https://dashboard.relevelup.com/?ref=",r]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{className:"text-center p-4 bg-green-50 dark:bg-green-950/20 rounded-lg border border-green-200 dark:border-green-900",children:[e.jsx(oc,{className:"h-5 w-5 mx-auto text-green-600 mb-1"}),e.jsxs("p",{className:"text-2xl font-bold text-green-700 dark:text-green-400",children:["$",E]}),e.jsx("p",{className:"text-xs text-green-600 dark:text-green-500",children:"Monthly Savings"})]}),e.jsxs("div",{className:"text-center p-4 bg-primary/5 rounded-lg border border-primary/20",children:[e.jsx(Ar,{className:"h-5 w-5 mx-auto text-primary mb-1"}),e.jsx("p",{className:"text-2xl font-bold",children:k}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Qualified Referrals"})]}),e.jsxs("div",{className:"text-center p-4 bg-amber-50 dark:bg-amber-950/20 rounded-lg border border-amber-200 dark:border-amber-900",children:[e.jsx(Pn,{className:"h-5 w-5 mx-auto text-amber-600 mb-1"}),e.jsx("p",{className:"text-2xl font-bold text-amber-700 dark:text-amber-400",children:T}),e.jsx("p",{className:"text-xs text-amber-600 dark:text-amber-500",children:"Pending (30 days)"})]})]}),e.jsxs("div",{className:"bg-muted/30 rounded-lg p-4",children:[e.jsx("h4",{className:"font-semibold text-sm mb-3",children:"How It Works"}),e.jsxs("div",{className:"space-y-2 text-sm text-muted-foreground",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"bg-primary text-primary-foreground rounded-full w-5 h-5 flex items-center justify-center text-xs shrink-0",children:"1"}),e.jsx("p",{children:"Share your referral link or send an invite email to broker friends"})]}),e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"bg-primary text-primary-foreground rounded-full w-5 h-5 flex items-center justify-center text-xs shrink-0",children:"2"}),e.jsx("p",{children:"They sign up and subscribe to LevelUp"})]}),e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"bg-primary text-primary-foreground rounded-full w-5 h-5 flex items-center justify-center text-xs shrink-0",children:"3"}),e.jsx("p",{children:"After 30 days, you get $25/month off your membership - forever!"})]})]})]}),e.jsx(WIs,{brokerageId:s,refreshTrigger:y}),c.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium",children:"Your Referrals"}),c.slice(0,5).map(D=>{var R,z;return e.jsxs("div",{className:"flex items-center justify-between p-2.5 bg-muted/30 rounded-lg",children:[e.jsx("span",{className:"text-sm truncate",children:((R=D.referred_brokerage)==null?void 0:R.name)||((z=D.referred_user)==null?void 0:z.email)||"Pending setup"}),e.jsxs(Xe,{variant:D.status==="qualified"?"default":D.status==="pending"?"secondary":"destructive",className:D.status==="qualified"?"bg-green-600":"",children:[D.status==="qualified"&&e.jsx(zi,{className:"h-3 w-3 mr-1"}),D.status]})]},D.id)})]})]})]}),e.jsx(GIs,{open:p,onOpenChange:x,referralCode:r||"",brokerageId:s||"",senderName:l||"A LevelUp Member",brokerageName:a,onInvitesSent:()=>_(D=>D+1)})]})},YIs=({brokerageId:s})=>{const t=Fr(),{teams:r,isLoading:n}=XA(s),{data:a,isLoading:i}=yt({queryKey:["team-aggregate-stats",s,r.map(h=>h.id)],queryFn:async()=>{if(r.length===0)return[];const h=r.map(D=>D.id),{data:m}=await V.from("team_members").select("team_id, user_id, role").in("team_id",h);if(!m||m.length===0)return r.map(D=>({team_id:D.id,team_name:D.name,member_count:0,leader_name:null,leader_avatar:null,total_contacts:0,total_deals:0,total_videos:0}));const p=m.map(D=>D.user_id),x=m.filter(D=>D.role==="team_leader").map(D=>D.user_id),{data:y}=await V.from("profiles").select("id, name, avatar_url").in("id",x),_=new Map((y||[]).map(D=>[D.id,D])),{data:b}=await V.from("innercircle_contacts").select("owner_user_id").in("owner_user_id",p),{data:j}=await V.from("deal_pipeline").select("owner_user_id").in("owner_user_id",p),{data:k}=await V.from("agent_videos").select("owner_user_id").in("owner_user_id",p).eq("is_deleted",!1),T=new Map;(b||[]).forEach(D=>{T.set(D.owner_user_id,(T.get(D.owner_user_id)||0)+1)});const E=new Map;(j||[]).forEach(D=>{E.set(D.owner_user_id,(E.get(D.owner_user_id)||0)+1)});const A=new Map;return(k||[]).forEach(D=>{A.set(D.owner_user_id,(A.get(D.owner_user_id)||0)+1)}),r.map(D=>{const R=m.filter(K=>K.team_id===D.id),z=R.find(K=>K.role==="team_leader"),O=z?_.get(z.user_id):null,$=R.map(K=>K.user_id),ee=$.reduce((K,re)=>K+(T.get(re)||0),0),Z=$.reduce((K,re)=>K+(E.get(re)||0),0),J=$.reduce((K,re)=>K+(A.get(re)||0),0);return{team_id:D.id,team_name:D.name,member_count:R.length,leader_name:(O==null?void 0:O.name)||null,leader_avatar:(O==null?void 0:O.avatar_url)||null,total_contacts:ee,total_deals:Z,total_videos:J}})},enabled:r.length>0});if(n||i)return e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:[1,2,3].map(h=>e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsx(Ks,{className:"h-5 w-32"})}),e.jsx(Oe,{children:e.jsx(Ks,{className:"h-24 w-full"})})]},h))});if(r.length===0)return e.jsx(ke,{children:e.jsxs(Oe,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Ar,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold mb-2",children:"No Teams Yet"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"Create teams to organize your agents and track their performance."}),e.jsx(H,{onClick:()=>t("/brokerage/teams"),children:"Manage Teams"})]})});const o=(a||[]).reduce((h,m)=>h+m.member_count,0),c=(a||[]).reduce((h,m)=>h+m.total_contacts,0),d=(a||[]).reduce((h,m)=>h+m.total_deals,0);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid gap-4 grid-cols-2 md:grid-cols-4",children:[e.jsx(ke,{children:e.jsxs(Oe,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground mb-1",children:[e.jsx(Ar,{className:"h-4 w-4"})," Teams"]}),e.jsx("p",{className:"text-2xl font-bold",children:r.length})]})}),e.jsx(ke,{children:e.jsxs(Oe,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground mb-1",children:[e.jsx(Ar,{className:"h-4 w-4"})," Total Members"]}),e.jsx("p",{className:"text-2xl font-bold",children:o})]})}),e.jsx(ke,{children:e.jsxs(Oe,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground mb-1",children:[e.jsx(xE,{className:"h-4 w-4"})," Total Contacts"]}),e.jsx("p",{className:"text-2xl font-bold",children:c.toLocaleString()})]})}),e.jsx(ke,{children:e.jsxs(Oe,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground mb-1",children:[e.jsx(pm,{className:"h-4 w-4"})," Total Deals"]}),e.jsx("p",{className:"text-2xl font-bold",children:d.toLocaleString()})]})})]}),e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:(a||[]).map(h=>e.jsxs(ke,{className:"hover:shadow-md transition-shadow",children:[e.jsxs(Ot,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(zt,{className:"text-lg",children:h.team_name}),e.jsxs(Xe,{variant:"secondary",children:[h.member_count," members"]})]}),h.leader_name&&e.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[e.jsxs(Un,{className:"h-6 w-6",children:[e.jsx(Ka,{src:h.leader_avatar||""}),e.jsx(qn,{className:"text-xs",children:h.leader_name.charAt(0).toUpperCase()})]}),e.jsxs("span",{className:"text-sm text-muted-foreground flex items-center gap-1",children:[e.jsx(zf,{className:"h-3 w-3 text-amber-500"}),h.leader_name]})]})]}),e.jsx(Oe,{children:e.jsxs("div",{className:"grid grid-cols-3 gap-3 text-center",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-semibold",children:h.total_contacts.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Contacts"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-semibold",children:h.total_deals.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Deals"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-semibold",children:h.total_videos.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Videos"})]})]})})]},h.team_id))}),e.jsx("div",{className:"flex justify-end",children:e.jsx(H,{variant:"outline",onClick:()=>t("/brokerage/teams"),children:"Manage Teams →"})})]})},ZIs=()=>{const{user:s,isBrokerageManager:t,brokerageId:r,isAdmin:n,managedBrokerages:a,selectedBrokerageId:i,setSelectedBrokerageId:l}=Ms(),o=Fr(),{toast:c}=li(),[d,h]=S.useState(""),[m,p]=S.useState(!0),x=i||(a.length>0?a[0].id:r);S.useEffect(()=>{if(!s||!t&&!n){o("/dashboard");return}!i&&a.length>0&&l(a[0].id),x?y():a.length===0&&!r&&p(!1)},[s,t,n,x,o,a,i]);const y=async()=>{if(!x){p(!1);return}try{const{data:_,error:b}=await V.from("brokerages").select("name").eq("id",x).single();if(b)throw b;h(_.name)}catch(_){console.error("Error loading brokerage info:",_),c({title:"Error",description:"Failed to load brokerage information",variant:"destructive"})}finally{p(!1)}};return m?e.jsx(Ss,{title:"Manage Brokerages",description:"Loading brokerage information...",children:e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):x?e.jsx(Ss,{title:d||"Manage Brokerages",description:"Brokerage Management Dashboard",children:e.jsxs("div",{className:"space-y-6",children:[a.length>1&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Managing:"}),e.jsxs(Bs,{value:i||"",onValueChange:l,children:[e.jsxs(Os,{className:"w-[280px]",children:[e.jsx(Xa,{className:"mr-2 h-4 w-4"}),e.jsx(Us,{placeholder:"Select brokerage"})]}),e.jsx(Fs,{children:a.map(_=>e.jsx(pt,{value:_.id,children:_.name},_.id))})]})]}),e.jsxs(ta,{defaultValue:"agents",className:"space-y-4",children:[e.jsxs(Qn,{className:"grid w-full grid-cols-4 md:grid-cols-8",children:[e.jsx(ts,{value:"agents",children:"Agents"}),e.jsx(ts,{value:"teams",children:"Teams"}),e.jsx(ts,{value:"invite",children:"Invite Links"}),e.jsx(ts,{value:"referrals",children:"Referrals"}),e.jsx(ts,{value:"leaderboard",children:"Leaderboard"}),e.jsx(ts,{value:"activity",children:"Activity"}),e.jsx(ts,{value:"analytics",children:"Analytics"}),e.jsx(ts,{value:"shares",children:"Shares"})]}),e.jsx(cs,{value:"agents",className:"space-y-4",children:e.jsx(BIs,{brokerageId:x})}),e.jsx(cs,{value:"teams",className:"space-y-4",children:e.jsx(YIs,{brokerageId:x})}),e.jsx(cs,{value:"invite",className:"space-y-4",children:e.jsx(HIs,{brokerageId:x})}),e.jsx(cs,{value:"referrals",className:"space-y-4",children:e.jsx(KIs,{})}),e.jsx(cs,{value:"leaderboard",className:"space-y-4",children:e.jsx(ydt,{brokerageId:x,title:`${d} Event Leaderboard`,showUserStats:!1})}),e.jsx(cs,{value:"activity",className:"space-y-4",children:e.jsx(qIs,{brokerageId:x})}),e.jsx(cs,{value:"analytics",className:"space-y-4",children:e.jsx(VIs,{brokerageId:x})}),e.jsx(cs,{value:"shares",className:"space-y-4",children:e.jsx(Uht,{brokerageOnly:!0,brokerageId:x})})]})]})}):e.jsx(Ss,{title:"Manage Brokerages",description:"Brokerage Management",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Xa,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h2",{className:"text-xl font-semibold mb-2",children:"No Brokerage Assigned"}),e.jsx("p",{className:"text-muted-foreground",children:"You don't have any brokerages to manage."})]})})};function XIs({brokerageId:s,canManage:t}){const{user:r}=Ms(),[n,a]=S.useState([]),[i,l]=S.useState(!0),[o,c]=S.useState(!1),[d,h]=S.useState(null),[m,p]=S.useState(null),[x,y]=S.useState(!1),[_,b]=S.useState(""),[j,k]=S.useState(""),[T,E]=S.useState(!1),A=async()=>{try{const{data:$,error:ee}=await V.from("brokerage_announcements").select("*").eq("brokerage_id",s).order("is_pinned",{ascending:!1}).order("pinned_at",{ascending:!1,nullsFirst:!1}).order("created_at",{ascending:!1});if(ee)throw ee;const Z=$;if(Z&&Z.length>0){const J=[...new Set(Z.map(ce=>ce.created_by))],{data:K}=await V.from("profiles").select("id, name, avatar_url").in("id",J),re=new Map((K==null?void 0:K.map(ce=>[ce.id,ce]))||[]),ie=Z.map(ce=>({...ce,author:re.get(ce.created_by)||{name:"Unknown",avatar_url:null}}));a(ie)}else a([])}catch($){console.error("Error fetching announcements:",$)}finally{l(!1)}};S.useEffect(()=>{A()},[s]);const D=()=>{b(""),k(""),E(!1),h(null)},R=$=>{$?(h($),b($.title),k($.content),E($.is_pinned)):D(),c(!0)},z=async()=>{if(!_.trim()||!j.trim()){he.error("Please fill in all fields");return}y(!0);try{if(d){const{error:$}=await V.from("brokerage_announcements").update({title:_.trim(),content:j.trim(),is_pinned:T,pinned_at:T?new Date().toISOString():null}).eq("id",d.id);if($)throw $;he.success("Announcement updated")}else{const{error:$}=await V.from("brokerage_announcements").insert({brokerage_id:s,created_by:r==null?void 0:r.id,title:_.trim(),content:j.trim(),is_pinned:T,pinned_at:T?new Date().toISOString():null});if($)throw $;he.success("Announcement created")}c(!1),D(),A()}catch($){console.error("Error saving announcement:",$),he.error("Failed to save announcement")}finally{y(!1)}},O=async()=>{if(m)try{const{error:$}=await V.from("brokerage_announcements").delete().eq("id",m);if($)throw $;he.success("Announcement deleted"),A()}catch($){console.error("Error deleting announcement:",$),he.error("Failed to delete announcement")}finally{p(null)}};return i?e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(ph,{className:"h-5 w-5"}),"Announcements"]})}),e.jsx(Oe,{children:e.jsx("div",{className:"animate-pulse space-y-3",children:e.jsx("div",{className:"h-20 bg-muted rounded"})})})]}):e.jsxs(e.Fragment,{children:[e.jsxs(ke,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-4",children:[e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(ph,{className:"h-5 w-5 text-primary"}),"Announcements"]}),t&&e.jsxs(H,{size:"sm",onClick:()=>R(),className:"gap-1",children:[e.jsx(Ys,{className:"h-4 w-4"}),"New"]})]}),e.jsx(Oe,{children:n.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No announcements yet"}):e.jsx("div",{className:"space-y-4",children:n.map($=>{var ee,Z,J,K;return e.jsx("div",{className:`p-4 rounded-lg border ${$.is_pinned?"bg-primary/5 border-primary/20":"bg-muted/30"}`,children:e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[$.is_pinned&&e.jsx(Wk,{className:"h-3.5 w-3.5 text-primary shrink-0"}),e.jsx("h4",{className:"font-semibold truncate",children:$.title})]}),e.jsx("p",{className:"text-sm text-muted-foreground whitespace-pre-wrap",children:$.content}),e.jsxs("div",{className:"flex items-center gap-2 mt-3 text-xs text-muted-foreground",children:[e.jsxs(Un,{className:"h-5 w-5",children:[e.jsx(Ka,{src:((ee=$.author)==null?void 0:ee.avatar_url)||void 0}),e.jsx(qn,{className:"text-[10px]",children:((J=(Z=$.author)==null?void 0:Z.name)==null?void 0:J.charAt(0))||"?"})]}),e.jsx("span",{children:(K=$.author)==null?void 0:K.name}),e.jsx("span",{children:"•"}),e.jsx("span",{children:As(new Date($.created_at),"MMM d, yyyy")})]})]}),t&&e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[e.jsx(H,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>R($),children:e.jsx(ni,{className:"h-4 w-4"})}),e.jsx(H,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:text-destructive",onClick:()=>p($.id),children:e.jsx(Dr,{className:"h-4 w-4"})})]})]})},$.id)})})})]}),e.jsx(bs,{open:o,onOpenChange:c,children:e.jsxs(vs,{children:[e.jsx(Cs,{children:e.jsx(Ns,{children:d?"Edit Announcement":"New Announcement"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"title",children:"Title"}),e.jsx(Se,{id:"title",value:_,onChange:$=>b($.target.value),placeholder:"Announcement title..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"content",children:"Content"}),e.jsx(vr,{id:"content",value:j,onChange:$=>k($.target.value),placeholder:"Write your announcement...",rows:4})]}),e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Or,{id:"pinned",checked:T,onCheckedChange:E}),e.jsxs(ue,{htmlFor:"pinned",className:"flex items-center gap-1 cursor-pointer",children:[e.jsx(Wk,{className:"h-4 w-4"}),"Pin to top"]})]})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(H,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsx(H,{onClick:z,disabled:x,children:x?"Saving...":d?"Update":"Create"})]})]})]})}),e.jsx(Rl,{open:!!m,onOpenChange:()=>p(null),children:e.jsxs(jl,{children:[e.jsxs(Nl,{children:[e.jsx(Sl,{children:"Delete Announcement"}),e.jsx(Cl,{children:"Are you sure you want to delete this announcement? This action cannot be undone."})]}),e.jsxs(kl,{children:[e.jsx(Tl,{children:"Cancel"}),e.jsx(ml,{onClick:O,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})})]})}function QIs({brokerageId:s,canManage:t=!1}){const{startImpersonation:r,isLoading:n}=age(),{user:a}=Ms(),[i,l]=S.useState([]),[o,c]=S.useState(!0),[d,h]=S.useState(""),[m,p]=S.useState(new Set);S.useEffect(()=>{(async()=>{try{const{data:_,error:b}=await V.from("profiles").select("id, name, email, phone, avatar_url, title, bio, areas_served, years_experience, instagram_url, facebook_url, linkedin_url").eq("brokerage_id",s).order("name");if(b)throw b;if(l(_||[]),_&&_.length>0){const j=_.map(T=>T.id),{data:k}=await V.from("agent_assistant_assignments").select("agent_id").in("agent_id",j);k&&p(new Set(k.map(T=>T.agent_id)))}}catch(_){console.error("Error fetching agents:",_)}finally{c(!1)}})()},[s]);const x=i.filter(y=>{var _,b;return y.name.toLowerCase().includes(d.toLowerCase())||y.email.toLowerCase().includes(d.toLowerCase())||((_=y.title)==null?void 0:_.toLowerCase().includes(d.toLowerCase()))||((b=y.areas_served)==null?void 0:b.toLowerCase().includes(d.toLowerCase()))});return o?e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(Ar,{className:"h-5 w-5"}),"Agent Roster"]})}),e.jsx(Oe,{children:e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4",children:[1,2,3,4].map(y=>e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-48 bg-muted rounded-lg"})},y))})})]}):e.jsxs(ke,{children:[e.jsxs(Ot,{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 space-y-0",children:[e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(Ar,{className:"h-5 w-5 text-primary"}),"Agent Roster",e.jsxs("span",{className:"text-sm font-normal text-muted-foreground",children:["(",i.length,")"]})]}),e.jsxs("div",{className:"relative w-full sm:w-64",children:[e.jsx(Mn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Se,{placeholder:"Search agents...",value:d,onChange:y=>h(y.target.value),className:"pl-9"})]})]}),e.jsx(Oe,{children:x.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:d?"No agents match your search":"No agents in this brokerage yet"}):e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4",children:x.map(y=>e.jsx(JIs,{agent:y,hasAssistant:m.has(y.id),canImpersonate:t&&y.id!==(a==null?void 0:a.id),onImpersonate:()=>r(y.id,"/my-brokerage"),impersonationLoading:n},y.id))})})]})}function JIs({agent:s,hasAssistant:t,canImpersonate:r,onImpersonate:n,impersonationLoading:a}){const i=s.name.split(" ").map(l=>l[0]).join("").toUpperCase().slice(0,2);return e.jsxs("div",{className:"group relative bg-card border rounded-xl p-4 hover:shadow-md transition-shadow",children:[e.jsxs("div",{className:"flex flex-col items-center text-center mb-3",children:[e.jsxs(Un,{className:"h-20 w-20 mb-3 ring-2 ring-background shadow-md",children:[e.jsx(Ka,{src:s.avatar_url||void 0,alt:s.name}),e.jsx(qn,{className:"text-lg bg-primary/10 text-primary",children:i})]}),e.jsx("h3",{className:"font-semibold text-sm leading-tight",children:s.name}),s.title&&e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:s.title}),t&&e.jsx(Xe,{variant:"outline",className:"text-[10px] mt-1",children:"Has Assistant"})]}),s.bio&&e.jsx("p",{className:"text-xs text-muted-foreground text-center line-clamp-2 mb-3",children:s.bio}),e.jsxs("div",{className:"space-y-1.5 mb-3",children:[s.areas_served&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(Qa,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate",children:s.areas_served})]}),s.years_experience&&e.jsxs("p",{className:"text-xs text-muted-foreground text-center",children:[s.years_experience," ",s.years_experience===1?"year":"years"," experience"]})]}),e.jsxs("div",{className:"flex items-center justify-center gap-2",children:[r&&e.jsxs(rd,{children:[e.jsx(nd,{asChild:!0,children:e.jsx(H,{variant:"outline",size:"icon",className:"h-8 w-8 text-blue-600 hover:text-blue-700 hover:bg-blue-50",onClick:n,disabled:a,children:e.jsx(kE,{className:"h-4 w-4"})})}),e.jsxs(Rc,{children:["Login as ",s.name]})]}),s.phone&&e.jsx(H,{variant:"outline",size:"icon",className:"h-8 w-8",asChild:!0,children:e.jsx("a",{href:`tel:${s.phone}`,title:`Call ${s.name}`,children:e.jsx(Yn,{className:"h-4 w-4"})})}),e.jsx(H,{variant:"outline",size:"icon",className:"h-8 w-8",asChild:!0,children:e.jsx("a",{href:`mailto:${s.email}`,title:`Email ${s.name}`,children:e.jsx(er,{className:"h-4 w-4"})})}),s.linkedin_url&&e.jsx(H,{variant:"outline",size:"icon",className:"h-8 w-8",asChild:!0,children:e.jsx("a",{href:s.linkedin_url,target:"_blank",rel:"noopener noreferrer",title:"LinkedIn",children:e.jsx(qf,{className:"h-4 w-4"})})}),s.instagram_url&&e.jsx(H,{variant:"outline",size:"icon",className:"h-8 w-8",asChild:!0,children:e.jsx("a",{href:s.instagram_url,target:"_blank",rel:"noopener noreferrer",title:"Instagram",children:e.jsx(yu,{className:"h-4 w-4"})})})]})]})}function ePs({brokerageId:s}){const[t,r]=S.useState([]),[n,a]=S.useState(!0);if(S.useEffect(()=>{(async()=>{try{const{data:c,error:d}=await V.from("profiles").select("id, name, avatar_url").eq("brokerage_id",s);if(d)throw d;if(!c||c.length===0){r([]),a(!1);return}const h=c.map(_=>_.id),{data:m,error:p}=await V.from("agent_attendance_stats").select("user_id, total_points").in("user_id",h).order("total_points",{ascending:!1});if(p)throw p;const x=new Map(c.map(_=>[_.id,_])),y=(m||[]).filter(_=>_.total_points>0).map(_=>{const b=x.get(_.user_id);return{user_id:_.user_id,total_points:_.total_points,name:(b==null?void 0:b.name)||"Unknown",avatar_url:(b==null?void 0:b.avatar_url)||null}});r(y)}catch(c){console.error("Error fetching leaderboard:",c)}finally{a(!1)}})()},[s]),n)return e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(To,{className:"h-5 w-5"}),"Team Leaderboard"]})}),e.jsx(Oe,{children:e.jsx("div",{className:"animate-pulse space-y-3",children:[1,2,3].map(o=>e.jsx("div",{className:"h-12 bg-muted rounded"},o))})})]});const i=o=>o===1?"text-yellow-500":o===2?"text-gray-400":o===3?"text-amber-600":"text-muted-foreground",l=o=>o<=3?e.jsx(H2,{className:Ft("h-5 w-5",i(o))}):e.jsx("span",{className:"w-5 text-center text-sm text-muted-foreground",children:o});return e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(To,{className:"h-5 w-5 text-primary"}),"Team Leaderboard"]})}),e.jsx(Oe,{children:t.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No points earned yet. Attend events to earn points!"}):e.jsx("div",{className:"space-y-2",children:t.slice(0,10).map((o,c)=>{const d=o.name.split(" ").map(m=>m[0]).join("").toUpperCase().slice(0,2),h=c+1;return e.jsxs("div",{className:Ft("flex items-center gap-3 p-2 rounded-lg",h<=3&&"bg-muted/50"),children:[e.jsx("div",{className:"w-6 flex justify-center",children:l(h)}),e.jsxs(Un,{className:"h-8 w-8",children:[e.jsx(Ka,{src:o.avatar_url||void 0}),e.jsx(qn,{className:"text-xs",children:d})]}),e.jsx("span",{className:"flex-1 text-sm font-medium truncate",children:o.name}),e.jsxs("span",{className:"text-sm font-semibold text-primary",children:[o.total_points.toLocaleString()," pts"]})]},o.user_id)})})})]})}function tPs({brokerageId:s}){const t=Fr(),[r,n]=S.useState([]),[a,i]=S.useState(!0);S.useEffect(()=>{(async()=>{try{const{data:c,error:d}=await V.from("profiles").select("id, name, avatar_url").eq("brokerage_id",s);if(d)throw d;if(!c||c.length===0){n([]),i(!1);return}const h=c.map(_=>_.id),m=new Map(c.map(_=>[_.id,_])),{data:p,error:x}=await V.from("listings").select(` id, slug, property_address, city, price, property_type, agent_id, listing_photos(photo_url) `).in("agent_id",h).eq("status","active").order("created_at",{ascending:!1}).limit(6);if(x)throw x;const y=(p||[]).map(_=>({id:_.id,slug:_.slug,property_address:_.property_address,city:_.city,price:_.price,property_type:_.property_type,agent_id:_.agent_id,agent:m.get(_.agent_id)||null,photos:_.listing_photos||[]}));n(y)}catch(c){console.error("Error fetching listings:",c)}finally{i(!1)}})()},[s]);const l=o=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(o);return a?e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(Fn,{className:"h-5 w-5"}),"Brokerage Listings"]})}),e.jsx(Oe,{children:e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[1,2].map(o=>e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-32 bg-muted rounded-lg"})},o))})})]}):e.jsxs(ke,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-4",children:[e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(Fn,{className:"h-5 w-5 text-primary"}),"Brokerage Listings"]}),e.jsxs(H,{size:"sm",variant:"outline",onClick:()=>t("/mission-control/listings"),className:"gap-1",children:[e.jsx(Ys,{className:"h-4 w-4"}),"Add Listing"]})]}),e.jsxs(Oe,{children:[r.length===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx(Fn,{className:"h-10 w-10 text-muted-foreground mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-3",children:"No active listings from your brokerage yet"}),e.jsxs(H,{size:"sm",onClick:()=>t("/mission-control/listings/new"),className:"gap-1",children:[e.jsx(Ys,{className:"h-4 w-4"}),"Add Your First Listing"]})]}):e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:r.map(o=>e.jsxs("div",{onClick:()=>window.open(`https://listings.relevelup.com/${o.slug||o.id}`,"_blank"),className:"group cursor-pointer border rounded-lg overflow-hidden hover:shadow-md transition-shadow",children:[e.jsxs("div",{className:"relative h-24 bg-muted",children:[o.photos&&o.photos.length>0?e.jsx("img",{src:o.photos[0].photo_url,alt:o.property_address||"Listing",className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(Fn,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx("div",{className:"absolute top-2 left-2",children:e.jsx("span",{className:"text-[10px] font-medium bg-primary text-primary-foreground px-1.5 py-0.5 rounded uppercase",children:o.property_type.replace("_"," ")})})]}),e.jsxs("div",{className:"p-2.5",children:[e.jsx("p",{className:"font-semibold text-sm text-primary",children:l(o.price)}),e.jsx("p",{className:"text-xs text-muted-foreground truncate mt-0.5",children:o.property_address||"Address not available"}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:o.city}),o.agent&&e.jsxs("p",{className:"text-[10px] text-muted-foreground mt-1.5 truncate",children:["Listed by ",o.agent.name]})]})]},o.id))}),r.length>0&&e.jsxs(H,{variant:"ghost",size:"sm",className:"w-full mt-3",onClick:()=>t("/mission-control/listings"),children:["View All Listings",e.jsx(gn,{className:"h-3 w-3 ml-1"})]})]})]})}function sPs(){const{user:s,isAdmin:t,isBrokerageManager:r}=Ms(),n=Fr(),[a,i]=S.useState(!0),[l,o]=S.useState(null),[c,d]=S.useState(""),[h,m]=S.useState(0),[p,x]=S.useState(!1),[y,_]=S.useState(!1);return S.useEffect(()=>{(async()=>{if(s)try{const{data:j}=await V.from("profiles").select("brokerage_id").eq("id",s.id).maybeSingle();if(!(j!=null&&j.brokerage_id)){i(!1);return}o(j.brokerage_id);const{data:k}=await V.from("brokerages").select("name").eq("id",j.brokerage_id).maybeSingle();k&&d(k.name);const{count:T}=await V.from("profiles").select("id",{count:"exact",head:!0}).eq("brokerage_id",j.brokerage_id);if(m(T||0),t)x(!0),_(!0);else if(r){const{data:E}=await V.from("brokerage_manager_assignments").select("id").eq("user_id",s.id).eq("brokerage_id",j.brokerage_id).maybeSingle();x(!!E),_(!!E)}}catch(j){console.error("Error fetching brokerage info:",j)}finally{i(!1)}})()},[s,t,r]),a?e.jsx(Ss,{title:"My Brokerage",description:"Loading...",children:e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):l?e.jsx(Ss,{title:c||"My Brokerage",description:"Team Hub",children:e.jsxs("div",{className:"space-y-8",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2 bg-muted/50 rounded-lg px-4 py-2",children:[e.jsx(Ar,{className:"h-5 w-5 text-primary"}),e.jsxs("span",{className:"font-medium",children:[h," ",h===1?"Agent":"Agents"]})]}),y&&e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(H,{variant:"outline",onClick:()=>n("/brokerage-content"),children:[e.jsx(tf,{className:"h-4 w-4 mr-2"}),"Brokerage Content"]}),e.jsxs(H,{onClick:()=>n(`/mission-control/listings/new?brokerage=${l}`),children:[e.jsx(Fn,{className:"h-4 w-4 mr-2"}),"Add Listing"]})]})]}),e.jsx(XIs,{brokerageId:l,canManage:p}),e.jsx(QIs,{brokerageId:l,canManage:p}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[e.jsx(ePs,{brokerageId:l}),e.jsx(tPs,{brokerageId:l})]})]})}):e.jsx(Ss,{title:"My Brokerage",description:"Team Hub",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Xa,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h2",{className:"text-xl font-semibold mb-2",children:"No Brokerage Assigned"}),e.jsx("p",{className:"text-muted-foreground",children:"You're not currently part of a brokerage team."})]})})}function rPs(s){if(!s)return null;try{const t=new URL(s),r=t.hostname.replace("www.","");let n=null;if(r==="youtube.com"||r==="m.youtube.com"?n=t.searchParams.get("v"):r==="youtu.be"&&(n=t.pathname.slice(1)),n)return`https://img.youtube.com/vi/${n}/hqdefault.jpg`}catch{}return null}function nPs(s){if(!s)return!1;try{const t=new URL(s).hostname.replace("www.","");return["youtube.com","youtu.be","m.youtube.com"].includes(t)}catch{return!1}}const jHe={video:{icon:El,label:"Video",color:"bg-red-500/10 text-red-600 dark:text-red-400"},pdf:{icon:kn,label:"Document",color:"bg-blue-500/10 text-blue-600 dark:text-blue-400"},link:{icon:ql,label:"Link",color:"bg-green-500/10 text-green-600 dark:text-green-400"},event:{icon:Nn,label:"Event",color:"bg-purple-500/10 text-purple-600 dark:text-purple-400"},graphic:{icon:pl,label:"Graphic",color:"bg-amber-500/10 text-amber-600 dark:text-amber-400"}};function aPs({item:s,canManage:t}){const[r,n]=S.useState(!1),[a,i]=S.useState(null),l=mHt(),o=Fr(),c=jHe[s.content_type]||jHe.link,d=c.icon,h=S.useMemo(()=>s.thumbnail_url?s.thumbnail_url:s.content_type==="graphic"&&s.file_url?s.file_url:s.content_type==="video"?rPs(s.url):null,[s]);S.useEffect(()=>{h||!s.url||s.content_type!=="video"||!nPs(s.url)||fetch(`https://www.youtube.com/oembed?url=${encodeURIComponent(s.url)}&format=json`).then(y=>y.ok?y.json():null).then(y=>{y!=null&&y.thumbnail_url&&i(y.thumbnail_url)}).catch(()=>{})},[s.url,s.content_type,h]);const m=h||a,p=()=>{o(`/brokerage-content/${s.id}`)},x=async()=>{try{await l.mutateAsync(s.id),he.success("Content deleted")}catch{he.error("Failed to delete")}n(!1)};return e.jsxs(e.Fragment,{children:[e.jsxs(ke,{className:"group overflow-hidden transition-all duration-200 hover:shadow-lg hover:border-primary/30 cursor-pointer",onClick:p,children:[m?e.jsx("div",{className:"aspect-video bg-muted/50 overflow-hidden",children:e.jsx("img",{src:m,alt:s.title,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300",referrerPolicy:"no-referrer"})}):e.jsx("div",{className:"aspect-video bg-muted/30 flex items-center justify-center",children:e.jsx(d,{className:"h-12 w-12 text-muted-foreground/30"})}),e.jsx(Oe,{className:"p-4",children:e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsxs(Xe,{variant:"secondary",className:`text-[10px] px-1.5 py-0 ${c.color}`,children:[e.jsx(d,{className:"h-3 w-3 mr-1"}),c.label]}),s.category&&e.jsxs(Xe,{variant:"outline",className:"text-[10px] px-1.5 py-0",children:[s.category.icon," ",s.category.name]})]}),e.jsx("h3",{className:"font-semibold text-sm text-foreground group-hover:text-primary transition-colors truncate",children:s.title}),s.description&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1 line-clamp-2",children:s.description}),s.content_type==="event"&&s.event_date&&e.jsxs("p",{className:"text-xs text-primary mt-2 font-medium",children:["📅 ",As(new Date(s.event_date),"MMM d, yyyy · h:mm a")]}),e.jsxs("p",{className:"text-[10px] text-muted-foreground mt-2",children:["Added ",As(new Date(s.created_at),"MMM d, yyyy")]})]}),t&&e.jsxs(Xu,{children:[e.jsx(Qu,{asChild:!0,onClick:y=>y.stopPropagation(),children:e.jsx(H,{variant:"ghost",size:"icon",className:"h-7 w-7 shrink-0",children:e.jsx(Ay,{className:"h-4 w-4"})})}),e.jsx(wu,{align:"end",children:e.jsxs(di,{onClick:y=>{y.stopPropagation(),n(!0)},className:"text-destructive",children:[e.jsx(Dr,{className:"h-4 w-4 mr-2"}),"Delete"]})})]})]})})]}),e.jsx(Rl,{open:r,onOpenChange:n,children:e.jsxs(jl,{children:[e.jsxs(Nl,{children:[e.jsx(Sl,{children:"Delete Content"}),e.jsxs(Cl,{children:['Are you sure you want to delete "',s.title,'"? This cannot be undone.']})]}),e.jsxs(kl,{children:[e.jsx(Tl,{children:"Cancel"}),e.jsx(ml,{onClick:x,className:"bg-destructive text-destructive-foreground",children:"Delete"})]})]})})]})}function iPs(s){try{const t=new URL(s),r=t.hostname.replace("www.","");let n=null;if(r==="youtube.com"||r==="m.youtube.com"?n=t.searchParams.get("v"):r==="youtu.be"&&(n=t.pathname.slice(1)),n)return`https://img.youtube.com/vi/${n}/hqdefault.jpg`}catch{}return null}const NHe=[{value:"video",label:"🎥 Video",hint:"YouTube, Vimeo, or video URL"},{value:"pdf",label:"📄 Document / PDF",hint:"Upload a PDF or document"},{value:"link",label:"🔗 Link / Resource",hint:"External URL"},{value:"event",label:"📅 Event",hint:"Brokerage event with date"},{value:"graphic",label:"🎨 Graphic / Canva",hint:"Image, Canva share link, or social post"}];function oPs({brokerageId:s,categories:t}){var je;const{user:r}=Ms(),[n,a]=S.useState(!1),[i,l]=S.useState(!1),[o,c]=S.useState(""),[d,h]=S.useState("📁"),[m,p]=S.useState(!1);S.useRef(null);const[x,y]=S.useState("video"),[_,b]=S.useState(""),[j,k]=S.useState(""),[T,E]=S.useState(""),[A,D]=S.useState(""),[R,z]=S.useState(""),[O,$]=S.useState(""),[ee,Z]=S.useState(""),J=hHt(),K=fHt(s),re=pHt(),ie=gHt(s),ce=()=>{y("video"),b(""),k(""),E(""),D(""),z(""),$(""),Z("")},ne=async(ve,We)=>{var Le;const Ve=(Le=ve.target.files)==null?void 0:Le[0];if(Ve){p(!0);try{const Me=Ve.name.split(".").pop(),ze=`${s}/${Date.now()}-${Math.random().toString(36).slice(2)}.${Me}`,{error:Pe}=await V.storage.from("brokerage-content").upload(ze,Ve);if(Pe)throw Pe;const{data:{publicUrl:Ie}}=V.storage.from("brokerage-content").getPublicUrl(ze);We==="file"?(D(Ie),x==="graphic"&&!R&&z(Ie)):z(Ie),he.success("File uploaded")}catch(Me){he.error(Me.message||"Upload failed")}finally{p(!1)}}},le=async()=>{if(!_.trim()){he.error("Title is required");return}if(r)try{await J.mutateAsync({brokerage_id:s,category_id:ee||null,content_type:x,title:_.trim(),description:j.trim()||null,url:T.trim()||null,file_url:A.trim()||null,thumbnail_url:R.trim()||null,event_date:O?new Date(O).toISOString():null,created_by:r.id}),he.success("Content added!"),ce(),a(!1)}catch(ve){he.error(ve.message||"Failed to add content")}},be=async()=>{if(o.trim())try{await K.mutateAsync({name:o.trim(),icon:d,sort_order:t.length}),c(""),h("📁"),he.success("Category created")}catch(ve){he.error(ve.message||"Failed to create category")}},fe=async()=>{try{await ie.mutateAsync(),he.success("Default categories created")}catch{he.error("Failed to create defaults")}};return e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs(bs,{open:n,onOpenChange:a,children:[e.jsx(Qi,{asChild:!0,children:e.jsxs(H,{children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Add Content"]})}),e.jsxs(vs,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(Cs,{children:e.jsx(Ns,{children:"Add Brokerage Content"})}),e.jsxs("div",{className:"space-y-4 mt-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{children:"Content Type"}),e.jsxs(Bs,{value:x,onValueChange:y,children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsx(Fs,{children:NHe.map(ve=>e.jsx(pt,{value:ve.value,children:ve.label},ve.value))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(je=NHe.find(ve=>ve.value===x))==null?void 0:je.hint})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{children:"Category"}),e.jsxs(Bs,{value:ee,onValueChange:Z,children:[e.jsx(Os,{children:e.jsx(Us,{placeholder:"Select category (optional)"})}),e.jsx(Fs,{children:t.map(ve=>e.jsxs(pt,{value:ve.id,children:[ve.icon," ",ve.name]},ve.id))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{children:"Title *"}),e.jsx(Se,{value:_,onChange:ve=>b(ve.target.value),placeholder:"Content title"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{children:"Description"}),e.jsx(vr,{value:j,onChange:ve=>k(ve.target.value),placeholder:"Brief description...",rows:2})]}),["video","link","graphic","event"].includes(x)&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{children:x==="video"?"Video URL":x==="graphic"?"Canva / Image URL":x==="event"?"Event Link (Zoom, etc.)":"URL"}),e.jsx(Se,{value:T,onChange:ve=>{const We=ve.target.value;if(E(We),x==="video"&&!R){const Ve=iPs(We);Ve&&z(Ve)}},placeholder:"https://..."})]}),["pdf","graphic"].includes(x)&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{children:x==="pdf"?"Upload PDF":"Upload Image"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Se,{type:"file",accept:x==="pdf"?".pdf,.doc,.docx":"image/*",onChange:ve=>ne(ve,"file"),disabled:m}),m&&e.jsx(is,{className:"h-4 w-4 animate-spin"})]}),A&&e.jsx("p",{className:"text-xs text-green-600",children:"✓ File uploaded"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{children:"Thumbnail Image (optional)"}),e.jsx(Se,{type:"file",accept:"image/*",onChange:ve=>ne(ve,"thumbnail"),disabled:m}),R&&e.jsxs("div",{className:"relative w-20 h-20 rounded overflow-hidden",children:[e.jsx("img",{src:R,className:"w-full h-full object-cover",alt:"thumb"}),e.jsx("button",{onClick:()=>z(""),className:"absolute top-0 right-0 bg-background/80 rounded-bl p-0.5",children:e.jsx(Rr,{className:"h-3 w-3"})})]})]}),x==="event"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{children:"Event Date & Time"}),e.jsx(Se,{type:"datetime-local",value:O,onChange:ve=>$(ve.target.value)})]}),e.jsxs(H,{onClick:le,disabled:J.isPending||!_.trim(),className:"w-full",children:[J.isPending?e.jsx(is,{className:"h-4 w-4 animate-spin mr-2"}):e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Add Content"]})]})]})]}),e.jsxs(bs,{open:i,onOpenChange:l,children:[e.jsx(Qi,{asChild:!0,children:e.jsxs(H,{variant:"outline",size:"sm",children:[e.jsx(Go,{className:"h-4 w-4 mr-2"}),"Categories"]})}),e.jsxs(vs,{className:"max-w-md",children:[e.jsx(Cs,{children:e.jsx(Ns,{children:"Manage Categories"})}),e.jsxs("div",{className:"space-y-4 mt-2",children:[t.length===0&&e.jsxs("div",{className:"text-center py-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-3",children:"No categories yet"}),e.jsxs(H,{variant:"outline",size:"sm",onClick:fe,disabled:ie.isPending,children:[ie.isPending?e.jsx(is,{className:"h-4 w-4 animate-spin mr-2"}):null,"Create Default Categories"]})]}),t.map(ve=>e.jsxs("div",{className:"flex items-center justify-between p-2 rounded-lg border",children:[e.jsxs("span",{className:"text-sm",children:[ve.icon," ",ve.name]}),!ve.is_default&&e.jsx(H,{variant:"ghost",size:"icon",className:"h-7 w-7 text-destructive",onClick:async()=>{await re.mutateAsync(ve.id),he.success("Category deleted")},children:e.jsx(Rr,{className:"h-4 w-4"})})]},ve.id)),e.jsxs("div",{className:"flex gap-2 pt-2 border-t",children:[e.jsx(Se,{value:d,onChange:ve=>h(ve.target.value),className:"w-14 text-center",maxLength:2}),e.jsx(Se,{value:o,onChange:ve=>c(ve.target.value),placeholder:"New category name",className:"flex-1",onKeyDown:ve=>ve.key==="Enter"&&be()}),e.jsx(H,{size:"sm",onClick:be,disabled:!o.trim(),children:"Add"})]})]})]})]})]})}function lPs(){const{user:s,isAdmin:t,isBrokerageManager:r}=Ms(),[n,a]=S.useState(!0),[i,l]=S.useState(null),[o,c]=S.useState(""),[d,h]=S.useState(!1),[m,p]=S.useState(null),[x,y]=S.useState("");S.useEffect(()=>{(async()=>{if(s)try{const{data:E}=await V.from("profiles").select("brokerage_id").eq("id",s.id).maybeSingle();if(!(E!=null&&E.brokerage_id)){a(!1);return}l(E.brokerage_id);const{data:A}=await V.from("brokerages").select("name").eq("id",E.brokerage_id).maybeSingle();if(A&&c(A.name),t)h(!0);else if(r){const{data:D}=await V.from("brokerage_manager_assignments").select("id").eq("user_id",s.id).eq("brokerage_id",E.brokerage_id).maybeSingle();h(!!D)}}catch(E){console.error("Error fetching brokerage info:",E)}finally{a(!1)}})()},[s,t,r]);const{data:_=[]}=cHt(i),{data:b=[],isLoading:j}=dHt(i,m),k=S.useMemo(()=>{if(!x.trim())return b;const T=x.toLowerCase();return b.filter(E=>{var A;return E.title.toLowerCase().includes(T)||((A=E.description)==null?void 0:A.toLowerCase().includes(T))||E.content_type.toLowerCase().includes(T)})},[b,x]);return n?e.jsx(Ss,{title:"Brokerage Content",description:"Loading...",children:e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):i?e.jsx(Ss,{title:`${o} Content`,description:"Brokerage Content Hub",children:e.jsxs("div",{className:"space-y-6",children:[d&&i&&e.jsx(oPs,{brokerageId:i,categories:_}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"relative max-w-sm",children:[e.jsx(Mn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Se,{placeholder:"Search content...",value:x,onChange:T=>y(T.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(H,{variant:m===null?"default":"outline",size:"sm",onClick:()=>p(null),children:"All"}),_.map(T=>e.jsxs(H,{variant:m===T.id?"default":"outline",size:"sm",onClick:()=>p(T.id),children:[e.jsx("span",{className:"mr-1",children:T.icon}),T.name]},T.id))]})]}),j?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):k.length===0?e.jsx(ke,{className:"bg-muted/30 border-dashed",children:e.jsxs(Oe,{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(Uf,{className:"h-12 w-12 text-muted-foreground/50 mb-3"}),e.jsx("p",{className:"text-muted-foreground font-medium",children:x.trim()?"No matching content found":"No content yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:x.trim()?"Try a different search term or category.":d?"Add your first piece of content above.":"Your brokerage hasn't added content yet."})]})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:k.map(T=>e.jsx(aPs,{item:T,canManage:d},T.id))})]})}):e.jsx(Ss,{title:"Brokerage Content",description:"Content Hub",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Xa,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h2",{className:"text-xl font-semibold mb-2",children:"No Brokerage Assigned"}),e.jsx("p",{className:"text-muted-foreground",children:"You're not currently part of a brokerage team."})]})})}const kHe={video:{icon:El,label:"Video",color:"bg-red-500/10 text-red-600 dark:text-red-400"},pdf:{icon:kn,label:"Document",color:"bg-blue-500/10 text-blue-600 dark:text-blue-400"},link:{icon:ql,label:"Link",color:"bg-green-500/10 text-green-600 dark:text-green-400"},event:{icon:Nn,label:"Event",color:"bg-purple-500/10 text-purple-600 dark:text-purple-400"},graphic:{icon:pl,label:"Graphic",color:"bg-amber-500/10 text-amber-600 dark:text-amber-400"}};function cPs(s){try{const t=new URL(s),r=t.hostname.replace("www.","");if(t.pathname==="/playlist"){const n=t.searchParams.get("list");if(n)return`https://www.youtube.com/embed/videoseries?list=${n}`}if(r==="youtube.com"||r==="m.youtube.com"){const n=t.searchParams.get("v");if(n){const a=t.searchParams.get("list");let i=`https://www.youtube.com/embed/${n}`;return a&&(i+=`?list=${a}`),i}}if(r==="youtu.be"){const n=t.pathname.slice(1);if(n){const a=t.searchParams.get("list");let i=`https://www.youtube.com/embed/${n}`;return a&&(i+=`?list=${a}`),i}}if(r==="youtube.com"&&t.pathname.startsWith("/embed/"))return s}catch{}return null}function dPs(s){try{const t=new URL(s).hostname.replace("www.","");return["youtube.com","youtu.be","m.youtube.com"].includes(t)}catch{return!1}}function uPs(s){try{return new URL(s).hostname.includes("vimeo.com")}catch{return!1}}function hPs(s){try{const t=s.match(/vimeo\.com\/(\d+)/);if(t)return`https://player.vimeo.com/video/${t[1]}`}catch{}return null}function mPs(){const{contentId:s}=Po(),{data:t,isLoading:r}=yt({queryKey:["brokerage-content-detail",s],queryFn:async()=>{const{data:d,error:h}=await V.from("brokerage_content").select(` *, category:brokerage_content_categories(*) `).eq("id",s).single();if(h)throw h;return d},enabled:!!s});if(r)return e.jsx(Ss,{title:"Brokerage Content",children:e.jsx("div",{className:"flex justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})});if(!t)return e.jsx(Ss,{title:"Brokerage Content",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Xa,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold",children:"Content not found"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"This content may have been removed."}),e.jsx(H,{asChild:!0,className:"mt-4",children:e.jsx(Xn,{to:"/brokerage-content",children:"Back to Content"})})]})});const n=kHe[t.content_type]||kHe.link,a=n.icon,i=t.url||t.file_url,l=i&&dPs(i)?cPs(i):null,o=i&&uPs(i)?hPs(i):null,c=l||o;return e.jsx(Ss,{title:t.title,children:e.jsxs("div",{className:"space-y-6 max-w-4xl mx-auto",children:[e.jsx(H,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(Xn,{to:"/brokerage-content",children:[e.jsx(za,{className:"h-4 w-4"}),"Back to Content"]})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Xe,{variant:"secondary",className:`text-xs px-2 py-0.5 ${n.color}`,children:[e.jsx(a,{className:"h-3 w-3 mr-1"}),n.label]}),t.category&&e.jsxs(Xe,{variant:"outline",className:"text-xs px-2 py-0.5",children:[t.category.icon," ",t.category.name]}),e.jsxs("span",{className:"text-xs text-muted-foreground ml-auto",children:["Added ",As(new Date(t.created_at),"MMMM d, yyyy")]})]}),e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:t.title}),c&&e.jsx(ke,{className:"overflow-hidden",children:e.jsx("div",{className:"relative w-full bg-black",style:{paddingTop:"56.25%"},children:e.jsx("iframe",{src:c,className:"absolute top-0 left-0 w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,title:t.title})})}),t.content_type==="graphic"&&t.file_url&&!c&&e.jsx(ke,{className:"overflow-hidden",children:e.jsx("img",{src:t.file_url,alt:t.title,className:"w-full max-h-[600px] object-contain bg-muted"})}),!c&&t.content_type!=="graphic"&&t.thumbnail_url&&e.jsx(ke,{className:"overflow-hidden",children:e.jsx("img",{src:t.thumbnail_url,alt:t.title,className:"w-full max-h-[400px] object-cover"})}),t.description&&e.jsx(ke,{children:e.jsx(Oe,{className:"pt-6",children:e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:t.description})})}),t.content_type==="event"&&t.event_date&&e.jsx(ke,{children:e.jsxs(Oe,{className:"pt-6 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 rounded-md bg-primary/10",children:e.jsx(Nn,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-foreground",children:"Event Date"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:As(new Date(t.event_date),"EEEE, MMMM d, yyyy · h:mm a")})]})]})}),e.jsxs("div",{className:"flex flex-wrap gap-3",children:[t.file_url&&e.jsx(H,{asChild:!0,size:"lg",children:e.jsxs("a",{href:t.file_url,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(hi,{className:"h-4 w-4 mr-2"}),t.content_type==="pdf"?"Download Document":"Download File"]})}),t.url&&e.jsx(H,{variant:t.file_url?"outline":"default",asChild:!0,size:"lg",children:e.jsxs("a",{href:t.url,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(gn,{className:"h-4 w-4 mr-2"}),c?"Open on YouTube":t.content_type==="event"?"Join Event":t.content_type==="graphic"?"Open in Canva":"Open Link"]})})]})]})})}const ape={open_house:{label:"Open House Coverage",emoji:"🏡",description:"Need someone to host an open house"},showing_coverage:{label:"Showing Coverage",emoji:"🔑",description:"Cover a buyer showing"},floor_time:{label:"Floor Time",emoji:"📞",description:"Cover phone / floor duty"},general:{label:"General Help",emoji:"🤝",description:"Sign install, errand, anything else"}};function fPs(s="open"){const{user:t}=Ms();return yt({queryKey:["brokerage-help-requests",s,t==null?void 0:t.id],queryFn:async()=>{if(!t)return[];let r=V.from("brokerage_help_requests").select("*, requester:profiles!brokerage_help_requests_requester_user_id_fkey(name, email, avatar_url)").order("created_at",{ascending:!1});if(s==="open")r=r.eq("status","open");else if(s==="mine")r=r.eq("requester_user_id",t.id);else if(s==="filled")r=r.in("status",["filled","completed"]);else if(s==="my_claims"){const{data:i}=await V.from("brokerage_help_claims").select("request_id").eq("claimant_user_id",t.id),l=(i||[]).map(o=>o.request_id);if(l.length===0)return[];r=r.in("id",l)}const{data:n,error:a}=await r;if(a)throw a;return n},enabled:!!t})}function pPs(s){return yt({queryKey:["brokerage-help-request",s],queryFn:async()=>{if(!s)return null;const{data:t,error:r}=await V.from("brokerage_help_requests").select("*, requester:profiles!brokerage_help_requests_requester_user_id_fkey(name, email, phone, avatar_url)").eq("id",s).single();if(r)throw r;return t},enabled:!!s})}function gPs(s){return yt({queryKey:["brokerage-help-claims",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await V.from("brokerage_help_claims").select("*, claimant:profiles!brokerage_help_claims_claimant_user_id_fkey(name, email, phone, avatar_url)").eq("request_id",s).order("created_at",{ascending:!0});if(r)throw r;return t},enabled:!!s})}function xPs(){const s=ns(),{user:t,brokerageId:r}=Ms();return Pt({mutationFn:async n=>{if(!t||!r)throw new Error("You must be in a brokerage to post.");const{data:a,error:i}=await V.from("brokerage_help_requests").insert({...n,brokerage_id:r,requester_user_id:t.id}).select().single();if(i)throw i;try{await V.functions.invoke("brokerage-help-notify",{body:{request_id:a.id}})}catch(l){console.warn("notify failed (non-blocking):",l)}return a},onSuccess:()=>{s.invalidateQueries({queryKey:["brokerage-help-requests"]})}})}function yPs(){const s=ns(),{user:t}=Ms();return Pt({mutationFn:async({request_id:r,note:n})=>{if(!t)throw new Error("Not signed in");const{data:a,error:i}=await V.from("brokerage_help_claims").insert({request_id:r,claimant_user_id:t.id,note:n}).select().single();if(i)throw i;return a},onSuccess:(r,n)=>{s.invalidateQueries({queryKey:["brokerage-help-claims",n.request_id]}),s.invalidateQueries({queryKey:["brokerage-help-requests"]})}})}function vPs(){const s=ns();return Pt({mutationFn:async({claim_id:t,request_id:r,claimant_user_id:n})=>{const{error:a}=await V.from("brokerage_help_claims").update({status:"accepted",responded_at:new Date().toISOString()}).eq("id",t);if(a)throw a;const{error:i}=await V.from("brokerage_help_requests").update({status:"filled",assigned_user_id:n}).eq("id",r);if(i)throw i;try{await V.functions.invoke("brokerage-help-claim-decision",{body:{claim_id:t}})}catch(l){console.warn("claim decision notify failed:",l)}},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["brokerage-help-claims",r.request_id]}),s.invalidateQueries({queryKey:["brokerage-help-request",r.request_id]}),s.invalidateQueries({queryKey:["brokerage-help-requests"]})}})}function bPs(){const s=ns();return Pt({mutationFn:async({claim_id:t})=>{const{error:r}=await V.from("brokerage_help_claims").update({status:"declined",responded_at:new Date().toISOString()}).eq("id",t);if(r)throw r},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["brokerage-help-claims",r.request_id]})}})}function _Ps(){const s=ns();return Pt({mutationFn:async t=>{const{error:r}=await V.from("brokerage_help_requests").update({status:"cancelled"}).eq("id",t);if(r)throw r},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["brokerage-help-requests"]}),s.invalidateQueries({queryKey:["brokerage-help-request",r]})}})}function wPs(){const s=ns();return Pt({mutationFn:async t=>{const{error:r}=await V.from("brokerage_help_requests").update({status:"completed"}).eq("id",t);if(r)throw r},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["brokerage-help-requests"]}),s.invalidateQueries({queryKey:["brokerage-help-request",r]})}})}function jPs(){const{user:s,brokerageId:t}=Ms(),r=ns(),n=yt({queryKey:["brokerage-help-prefs",s==null?void 0:s.id,t],queryFn:async()=>{if(!s||!t)return null;const{data:i,error:l}=await V.from("brokerage_help_notification_prefs").select("*").eq("user_id",s.id).eq("brokerage_id",t).maybeSingle();if(l)throw l;return i},enabled:!!s&&!!t}),a=Pt({mutationFn:async i=>{if(!s||!t)throw new Error("No user/brokerage");const{error:l}=await V.from("brokerage_help_notification_prefs").upsert({user_id:s.id,brokerage_id:t,email_enabled:i},{onConflict:"user_id,brokerage_id"});if(l)throw l},onSuccess:()=>{r.invalidateQueries({queryKey:["brokerage-help-prefs"]})}});return{...n,setEmailEnabled:a.mutate,isSaving:a.isPending}}function NPs(s,t){if(!s)return null;const r=(a,i)=>new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",...i}).format(new Date(a)),n=r(s,{weekday:"short",month:"short",day:"numeric",hour:"numeric",minute:"2-digit"});if(t){const a=r(t,{hour:"numeric",minute:"2-digit"});return`${n} – ${a} ET`}return`${n} ET`}function kPs(s){switch(s.compensation_type){case"flat_fee":return s.compensation_amount?`$${Number(s.compensation_amount).toFixed(0)}`:"Flat fee";case"referral_percent":return s.compensation_amount?`${Number(s.compensation_amount)}% referral`:"Referral";case"goodwill":return"Goodwill"}}function SPs({req:s,onClick:t}){var i;const r=ape[s.request_type],n=NPs(s.event_start_at,s.event_end_at),a=[s.address,s.city,s.state].filter(Boolean).join(", ");return e.jsx(ke,{className:"cursor-pointer hover:shadow-md transition group",onClick:t,children:e.jsxs(Oe,{className:"p-5",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 mb-3",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs(Xe,{variant:"secondary",className:"text-xs",children:[r.emoji," ",r.label]}),s.status!=="open"&&e.jsx(Xe,{variant:"outline",className:"text-xs capitalize",children:s.status})]}),e.jsx($a,{className:"h-4 w-4 text-muted-foreground group-hover:translate-x-0.5 transition"})]}),e.jsx("h3",{className:"font-semibold text-base mb-2 line-clamp-2",children:s.title}),e.jsxs("div",{className:"space-y-1.5 text-sm text-muted-foreground",children:[n&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Pn,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{children:n})]}),a&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Qa,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{className:"line-clamp-1",children:a})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(oc,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{children:kPs(s)})]})]}),e.jsxs("div",{className:"mt-3 pt-3 border-t flex items-center justify-between text-xs text-muted-foreground",children:[e.jsxs("span",{children:["Posted by ",((i=s.requester)==null?void 0:i.name)||"Teammate"]}),e.jsx("span",{children:new Date(s.created_at).toLocaleDateString()})]})]})})}function CPs(){var c;const s=Fr(),{brokerageId:t}=Ms(),[r,n]=S.useState("open"),{data:a=[],isLoading:i}=fPs(r),l=jPs(),o=((c=l.data)==null?void 0:c.email_enabled)??!0;return t?e.jsx(Ss,{title:"Help Board",description:"Ask a teammate to cover an open house, showing, or shift.",children:e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsx(ta,{value:r,onValueChange:d=>n(d),children:e.jsxs(Qn,{children:[e.jsx(ts,{value:"open",children:"Open"}),e.jsx(ts,{value:"mine",children:"My Posts"}),e.jsx(ts,{value:"my_claims",children:"My Claims"}),e.jsx(ts,{value:"filled",children:"Filled"})]})}),e.jsxs(H,{onClick:()=>s("/brokerage/help-board/new"),className:"gap-2",children:[e.jsx(Ys,{className:"h-4 w-4"})," Post Request"]})]}),e.jsx(ke,{className:"bg-muted/30 border-dashed",children:e.jsxs(Oe,{className:"flex items-center justify-between py-3 px-5",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[o?e.jsx(wp,{className:"h-4 w-4 text-primary"}):e.jsx(u_,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"email-notif",className:"text-sm font-medium cursor-pointer",children:"Email me when teammates post new help requests"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"You can still browse the board either way."})]})]}),e.jsx(Or,{id:"email-notif",checked:o,disabled:l.isLoading||l.isSaving,onCheckedChange:d=>l.setEmailEnabled(d)})]})}),i?e.jsx("div",{className:"flex items-center justify-center py-16",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):a.length===0?e.jsx(ke,{className:"bg-muted/30 border-dashed",children:e.jsxs(Oe,{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(i1,{className:"h-12 w-12 text-muted-foreground/50 mb-3"}),e.jsx("p",{className:"font-medium",children:"Nothing here yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:r==="open"?"No open requests right now — be the first to post one!":"Check back later."})]})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:a.map(d=>e.jsx(SPs,{req:d,onClick:()=>s(`/brokerage/help-board/${d.id}`)},d.id))})]})}):e.jsx(Ss,{title:"Help Board",description:"Brokerage Help Board",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx(i1,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h2",{className:"text-xl font-semibold mb-2",children:"No Brokerage Assigned"}),e.jsx("p",{className:"text-muted-foreground",children:"Join a brokerage to post and claim help requests."})]})})}function TPs(){const s=Fr(),{toast:t}=li(),r=xPs(),[n,a]=S.useState("open_house"),[i,l]=S.useState(""),[o,c]=S.useState(""),[d,h]=S.useState(""),[m,p]=S.useState(""),[x,y]=S.useState(""),[_,b]=S.useState(""),[j,k]=S.useState(""),[T,E]=S.useState(""),[A,D]=S.useState(""),[R,z]=S.useState(""),[O,$]=S.useState("goodwill"),[ee,Z]=S.useState(""),[J,K]=S.useState(""),re=n==="open_house"||n==="showing_coverage",ie=n!=="general",ce=(le,be)=>!le||!be?null:`${le}T${be}:00`,ne=async le=>{if(le.preventDefault(),!i.trim()){t({title:"Add a title",description:"Tell teammates what you need help with.",variant:"destructive"});return}try{const be=ce(d,m),fe=ce(d,x);await r.mutateAsync({request_type:n,title:i.trim(),description:o.trim()||null,event_start_at:be,event_end_at:fe,address:re&&_.trim()||null,city:re&&j.trim()||null,state:re&&T.trim()||null,zip:re&&A.trim()||null,mls_number:R.trim()||null,compensation_type:O,compensation_amount:ee?Number(ee):null,compensation_notes:J.trim()||null}),t({title:"Posted!",description:"Your teammates have been notified."}),s("/brokerage/help-board")}catch(be){t({title:"Could not post",description:(be==null?void 0:be.message)??"Something went wrong.",variant:"destructive"})}};return e.jsx(Ss,{title:"Post a Help Request",description:"Ask a teammate to cover for you",children:e.jsxs("div",{className:"max-w-2xl mx-auto",children:[e.jsxs(H,{variant:"ghost",size:"sm",onClick:()=>s("/brokerage/help-board"),className:"mb-4 gap-2",children:[e.jsx(za,{className:"h-4 w-4"})," Back to board"]}),e.jsx("form",{onSubmit:ne,children:e.jsx(ke,{children:e.jsxs(Oe,{className:"p-6 space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"What do you need help with?"}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:Object.keys(ape).map(le=>{const be=ape[le],fe=le===n;return e.jsxs("button",{type:"button",onClick:()=>a(le),className:`text-left p-3 rounded-lg border-2 transition ${fe?"border-primary bg-primary/5":"border-border hover:border-primary/40"}`,children:[e.jsx("div",{className:"text-lg",children:be.emoji}),e.jsx("div",{className:"font-medium text-sm mt-1",children:be.label}),e.jsx("div",{className:"text-xs text-muted-foreground line-clamp-1",children:be.description})]},le)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"title",children:"Title *"}),e.jsx(Se,{id:"title",value:i,onChange:le=>l(le.target.value),placeholder:n==="open_house"?"Open house at 123 Oak St — Sat 1-3pm":"Quick description",maxLength:120,required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"description",children:"Details"}),e.jsx(vr,{id:"description",value:o,onChange:le=>c(le.target.value),placeholder:"Any context — lockbox code instructions later, what to expect, etc.",rows:3,maxLength:1e3})]}),ie&&e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"date",children:"Date"}),e.jsx(Se,{id:"date",type:"date",value:d,onChange:le=>h(le.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"start",children:"Start"}),e.jsx(Se,{id:"start",type:"time",value:m,onChange:le=>p(le.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"end",children:"End"}),e.jsx(Se,{id:"end",type:"time",value:x,onChange:le=>y(le.target.value)})]})]}),re&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"address",children:"Address"}),e.jsx(Se,{id:"address",value:_,onChange:le=>b(le.target.value),placeholder:"123 Oak St"})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-2 col-span-2",children:[e.jsx(ue,{htmlFor:"city",children:"City"}),e.jsx(Se,{id:"city",value:j,onChange:le=>k(le.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"state",children:"State"}),e.jsx(Se,{id:"state",value:T,onChange:le=>E(le.target.value.toUpperCase()),maxLength:2})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"zip",children:"Zip"}),e.jsx(Se,{id:"zip",value:A,onChange:le=>D(le.target.value),maxLength:10})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"mls",children:"MLS # (optional)"}),e.jsx(Se,{id:"mls",value:R,onChange:le=>z(le.target.value)})]})]})]}),e.jsxs("div",{className:"space-y-3 pt-2 border-t",children:[e.jsx(ue,{children:"Compensation"}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-2",children:[{val:"goodwill",label:"Goodwill",sub:"Pay it forward"},{val:"flat_fee",label:"Flat Fee",sub:"Dollar amount"},{val:"referral_percent",label:"Referral %",sub:"On the deal"}].map(le=>{const be=O===le.val;return e.jsxs("button",{type:"button",onClick:()=>$(le.val),className:`text-left p-3 rounded-lg border-2 transition ${be?"border-primary bg-primary/5":"border-border hover:border-primary/40"}`,children:[e.jsx("div",{className:"font-medium text-sm",children:le.label}),e.jsx("div",{className:"text-xs text-muted-foreground",children:le.sub})]},le.val)})}),O!=="goodwill"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"amount",children:O==="flat_fee"?"Amount ($)":"Percent (%)"}),e.jsx(Se,{id:"amount",type:"number",min:"0",step:O==="referral_percent"?"1":"5",value:ee,onChange:le=>Z(le.target.value),placeholder:O==="flat_fee"?"100":"25"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"comp-notes",children:"Compensation notes"}),e.jsx(Se,{id:"comp-notes",value:J,onChange:le=>K(le.target.value),placeholder:"e.g. Venmo same day, or split any leads",maxLength:200})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(H,{type:"button",variant:"ghost",onClick:()=>s("/brokerage/help-board"),children:"Cancel"}),e.jsxs(H,{type:"submit",disabled:r.isPending,className:"gap-2",children:[r.isPending&&e.jsx(is,{className:"h-4 w-4 animate-spin"}),"Post & Notify Brokerage"]})]})]})})})]})})}function EPs(s,t){if(!s)return null;const r=(a,i)=>new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",...i}).format(new Date(a)),n=r(s,{weekday:"long",month:"long",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"});return t?`${n} – ${r(t,{hour:"numeric",minute:"2-digit"})} ET`:`${n} ET`}function cwe(s){return s?s.split(" ").map(t=>t[0]).slice(0,2).join("").toUpperCase():"?"}function APs(){var R,z,O,$,ee,Z,J,K;const{id:s}=Po(),t=Fr(),{user:r}=Ms(),{toast:n}=li(),{data:a,isLoading:i}=pPs(s),{data:l=[]}=gPs(s),o=yPs(),c=vPs(),d=bPs(),h=_Ps(),m=wPs(),[p,x]=S.useState("");if(i)return e.jsx(Ss,{title:"Loading...",description:"",children:e.jsx("div",{className:"flex items-center justify-center py-16",children:e.jsx(is,{className:"h-8 w-8 animate-spin text-primary"})})});if(!a)return e.jsxs(Ss,{title:"Not Found",description:"",children:[e.jsxs(H,{variant:"ghost",onClick:()=>t("/brokerage/help-board"),className:"gap-2",children:[e.jsx(za,{className:"h-4 w-4"})," Back to board"]}),e.jsx("p",{className:"mt-4 text-muted-foreground",children:"Request not found or you don't have access."})]});const y=ape[a.request_type],_=EPs(a.event_start_at,a.event_end_at),b=[a.address,a.city,a.state,a.zip].filter(Boolean).join(", "),j=(r==null?void 0:r.id)===a.requester_user_id,k=l.find(re=>re.claimant_user_id===(r==null?void 0:r.id)),T=l.find(re=>re.status==="accepted"),E=a.status==="open",A=a.compensation_type==="flat_fee"?a.compensation_amount?`$${Number(a.compensation_amount).toFixed(0)} flat fee`:"Flat fee":a.compensation_type==="referral_percent"?a.compensation_amount?`${a.compensation_amount}% referral`:"Referral percentage":"Goodwill (paying it forward)",D=async()=>{if(!p.trim()){n({title:"Add a quick note",description:"Let the requester know you're available."});return}try{await o.mutateAsync({request_id:a.id,note:p.trim()}),n({title:"You're in!",description:"The requester will review and pick someone."}),x("")}catch(re){n({title:"Could not submit",description:re==null?void 0:re.message,variant:"destructive"})}};return e.jsx(Ss,{title:a.title,description:`${y.emoji} ${y.label}`,children:e.jsxs("div",{className:"max-w-3xl mx-auto space-y-4",children:[e.jsxs(H,{variant:"ghost",size:"sm",onClick:()=>t("/brokerage/help-board"),className:"gap-2",children:[e.jsx(za,{className:"h-4 w-4"})," Back to board"]}),e.jsx(ke,{children:e.jsxs(Oe,{className:"p-6 space-y-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs(Xe,{variant:"secondary",children:[y.emoji," ",y.label]}),e.jsx(Xe,{variant:E?"default":"outline",className:"capitalize",children:a.status})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsxs(Un,{className:"h-7 w-7",children:[e.jsx(Ka,{src:((R=a.requester)==null?void 0:R.avatar_url)||void 0}),e.jsx(qn,{children:cwe((z=a.requester)==null?void 0:z.name)})]}),e.jsx("span",{children:((O=a.requester)==null?void 0:O.name)||"Teammate"})]})]}),e.jsx("h1",{className:"text-2xl font-bold",children:a.title}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3 pt-2",children:[_&&e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[e.jsx(Pn,{className:"h-4 w-4 text-primary mt-0.5"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"When"}),e.jsx("div",{children:_})]})]}),b&&e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[e.jsx(Qa,{className:"h-4 w-4 text-primary mt-0.5"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Where"}),e.jsx("div",{children:b})]})]}),e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[e.jsx(oc,{className:"h-4 w-4 text-primary mt-0.5"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Compensation"}),e.jsx("div",{children:A})]})]}),a.mls_number&&e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[e.jsx($k,{className:"h-4 w-4 text-primary mt-0.5"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"MLS"}),e.jsx("div",{children:a.mls_number})]})]})]}),a.description&&e.jsxs("div",{className:"pt-3 border-t",children:[e.jsx("h3",{className:"text-xs uppercase tracking-wide font-semibold text-muted-foreground mb-2",children:"Notes"}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:a.description})]}),a.compensation_notes&&e.jsxs("p",{className:"text-sm text-muted-foreground italic",children:["💰 ",a.compensation_notes]})]})}),!j&&E&&!k&&e.jsx(ke,{children:e.jsxs(Oe,{className:"p-6 space-y-3",children:[e.jsx("h3",{className:"font-semibold",children:"Offer to cover this"}),e.jsx(vr,{placeholder:"Quick note — e.g. 'I'm 10 min away and free that day'",value:p,onChange:re=>x(re.target.value),rows:3,maxLength:400}),e.jsxs(H,{onClick:D,disabled:o.isPending,className:"gap-2",children:[o.isPending&&e.jsx(is,{className:"h-4 w-4 animate-spin"}),"I can cover this"]})]})}),!j&&k&&e.jsx(ke,{className:"border-primary/30 bg-primary/5",children:e.jsxs(Oe,{className:"p-4 flex items-center gap-3",children:[e.jsx(va,{className:"h-5 w-5 text-primary"}),e.jsxs("div",{className:"text-sm",children:[e.jsxs("div",{className:"font-medium capitalize",children:["Your offer: ",k.status]}),e.jsxs("div",{className:"text-muted-foreground",children:[k.status==="pending"&&"Waiting for the requester to pick.",k.status==="accepted"&&"You're confirmed — see contact info below.",k.status==="declined"&&"They went with someone else this time."]})]})]})}),T&&(j||T.claimant_user_id===(r==null?void 0:r.id))&&e.jsx(ke,{className:"border-primary/30",children:e.jsxs(Oe,{className:"p-6",children:[e.jsx("h3",{className:"font-semibold mb-3",children:"Confirmed coverage"}),e.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[e.jsxs(Un,{className:"h-10 w-10",children:[e.jsx(Ka,{src:(($=T.claimant)==null?void 0:$.avatar_url)||void 0}),e.jsx(qn,{children:cwe((ee=T.claimant)==null?void 0:ee.name)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:(Z=T.claimant)==null?void 0:Z.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Covering this request"})]})]}),e.jsxs("div",{className:"space-y-1.5 text-sm",children:[((J=T.claimant)==null?void 0:J.email)&&e.jsxs("a",{href:`mailto:${T.claimant.email}`,className:"flex items-center gap-2 text-primary hover:underline",children:[e.jsx(er,{className:"h-4 w-4"})," ",T.claimant.email]}),((K=T.claimant)==null?void 0:K.phone)&&e.jsxs("a",{href:`tel:${T.claimant.phone}`,className:"flex items-center gap-2 text-primary hover:underline",children:[e.jsx(Yn,{className:"h-4 w-4"})," ",T.claimant.phone]})]})]})}),j&&e.jsx(ke,{children:e.jsxs(Oe,{className:"p-6 space-y-3",children:[e.jsxs("h3",{className:"font-semibold",children:["Interested agents (",l.length,")"]}),l.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No claims yet. Hang tight — your teammates were just notified."}),l.map(re=>{var ie,ce,ne,le,be;return e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg border",children:[e.jsxs(Un,{className:"h-10 w-10",children:[e.jsx(Ka,{src:((ie=re.claimant)==null?void 0:ie.avatar_url)||void 0}),e.jsx(qn,{children:cwe((ce=re.claimant)==null?void 0:ce.name)})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap",children:[e.jsx("div",{className:"font-medium",children:((ne=re.claimant)==null?void 0:ne.name)||"Teammate"}),e.jsx(Xe,{variant:"outline",className:"capitalize text-xs",children:re.status})]}),re.note&&e.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:['"',re.note,'"']}),re.status==="pending"&&E&&e.jsxs("div",{className:"flex gap-2 mt-2",children:[e.jsxs(H,{size:"sm",onClick:()=>c.mutate({claim_id:re.id,request_id:a.id,claimant_user_id:re.claimant_user_id}),disabled:c.isPending,className:"gap-1",children:[e.jsx(va,{className:"h-3.5 w-3.5"})," Pick ",((be=(le=re.claimant)==null?void 0:le.name)==null?void 0:be.split(" ")[0])||"them"]}),e.jsxs(H,{size:"sm",variant:"ghost",onClick:()=>d.mutate({claim_id:re.id,request_id:a.id}),disabled:d.isPending,className:"gap-1",children:[e.jsx(Rr,{className:"h-3.5 w-3.5"})," Pass"]})]})]})]},re.id)}),j&&E&&e.jsx("div",{className:"pt-3 border-t flex justify-end",children:e.jsx(H,{variant:"ghost",size:"sm",onClick:()=>h.mutate(a.id),disabled:h.isPending,children:"Cancel request"})}),j&&a.status==="filled"&&e.jsx("div",{className:"pt-3 border-t flex justify-end",children:e.jsx(H,{size:"sm",onClick:()=>m.mutate(a.id),disabled:m.isPending,children:"Mark complete"})})]})})]})})}const MPs=[{key:"search",label:"Search for Properties",icon:Mn,defaultText:"Search for Properties",placeholder:"https://your-website.com/search",helper:"Link to your home search page"},{key:"call",label:"Call Agent",icon:Yn,defaultText:"Call Me",hrefPrefix:"tel:",placeholder:"+15555551234",helper:"Your phone number"},{key:"email",label:"Email Agent",icon:er,defaultText:"Email Me",hrefPrefix:"mailto:",placeholder:"you@email.com",helper:"Your email address"},{key:"schedule",label:"Schedule a Call",icon:Nn,defaultText:"Schedule a Call",placeholder:"https://calendly.com/you",helper:"Link to your booking page"},{key:"listings",label:"View My Listings",icon:Fn,defaultText:"View My Listings",placeholder:"https://your-website.com/listings",helper:"Link to your listings page"},{key:"valuation",label:"Get Home Value",icon:oc,defaultText:"Get My Home Value",placeholder:"https://your-website.com/home-value",helper:"Link to your home valuation page"},{key:"openhouse",label:"See Open Houses",icon:Qa,defaultText:"See Open Houses",placeholder:"https://your-website.com/open-houses",helper:"Link to your open houses page"},{key:"forward",label:"Forward to a Friend",icon:cd,defaultText:"Forward to a Friend",isForward:!0,placeholder:"Optional landing page (or leave blank)",helper:"Opens recipient's email pre-filled — leave blank to default"},{key:"custom",label:"Custom Button",icon:Kd,defaultText:"Learn More",placeholder:"https://...",helper:"Any link you want"}];function SHe(s){const t=s.match(/(?:youtube\.com\/(?:watch\?v=|embed\/|v\/)|youtu\.be\/)([A-Za-z0-9_-]{11})/);return t?t[1]:null}function IPs(s){const t=s.match(/vimeo\.com\/(?:video\/)?(\d+)/);return t?t[1]:null}function Dgt({html:s,onChange:t}){const{user:r}=Ms(),n=S.useRef(null),a=S.useRef(""),i=S.useRef(t);i.current=t;const[l,o]=S.useState("desktop"),c=S.useRef(null),[d,h]=S.useState(!1),[m,p]=S.useState(""),[x,y]=S.useState(""),_=S.useRef(null),b=()=>{var kt;const St=(kt=n.current)==null?void 0:kt.contentDocument,xs=St==null?void 0:St.getSelection();xs&&xs.rangeCount>0&&(St!=null&&St.body.contains(xs.anchorNode))&&(_.current=xs.getRangeAt(0).cloneRange())},j=()=>{var _s;const St=c.current,xs=(_s=n.current)==null?void 0:_s.contentDocument;if(!St||!xs)return;let kt=m.trim();kt&&!/^(https?:|mailto:|tel:|#|\/)/i.test(kt)&&(kt="https://"+kt),St.setAttribute("href",kt),St.setAttribute("target","_blank");const fs=x.trim();fs&&fs!==(St.textContent||"").trim()&&(St.textContent=fs);const Gs=` `+xs.documentElement.outerHTML;a.current=Gs,i.current(Gs),h(!1)};S.useEffect(()=>{var kt,fs;const St=n.current;if(!St||a.current===s)return;const xs=()=>{const Gs=St.contentDocument;if(!Gs)return;Gs.open(),Gs.write(s||""),Gs.close(),a.current=s;const _s=Gs.body;if(!_s)return;_s.setAttribute("contenteditable","true"),_s.style.outline="none",_s.style.minHeight="400px",_s.style.cursor="text";const br=()=>{const Yr=` `+Gs.documentElement.outerHTML;a.current=Yr,i.current(Yr)};_s.addEventListener("input",br),_s.addEventListener("blur",br),_s.addEventListener("mouseup",b),_s.addEventListener("keyup",b),Gs.addEventListener("selectionchange",b);const zr=Yr=>{var Zn;const rn=Yr.target,sn=rn==null?void 0:rn.closest("a");if(sn){if(Yr.metaKey||Yr.ctrlKey||Yr.shiftKey)return;Yr.preventDefault(),Yr.stopPropagation(),c.current=sn,p(sn.getAttribute("href")||""),y((sn.textContent||"").trim()),h(!0);return}const Vr=Gs.getSelection();if(!Vr)return;const $r=(Zn=Gs.caretRangeFromPoint)==null?void 0:Zn.call(Gs,Yr.clientX,Yr.clientY),hn=$r==null?void 0:$r.startContainer;if(hn&&hn.nodeType===Node.TEXT_NODE){const cr=hn.textContent||"",on=$r.startOffset,ds=cr.lastIndexOf("[",on),Na=cr.indexOf("]",on);if(ds!==-1&&Na!==-1&&Na>ds){const vn=Gs.createRange();vn.setStart(hn,ds),vn.setEnd(hn,Na+1),Vr.removeAllRanges(),Vr.addRange(vn),_.current=vn.cloneRange()}}};_s.addEventListener("click",zr,!0)};((kt=St.contentDocument)==null?void 0:kt.readyState)==="complete"||(fs=St.contentDocument)!=null&&fs.body?xs():St.addEventListener("load",xs,{once:!0})},[s]);const k=(St,xs)=>{var Gs;const kt=(Gs=n.current)==null?void 0:Gs.contentDocument;if(!kt)return;kt.body.focus(),kt.execCommand(St,!1,xs);const fs=` `+kt.documentElement.outerHTML;a.current=fs,i.current(fs)},T=()=>{const St=window.prompt("Enter URL (https://...)");St&&k("createLink",St)},E=(St,xs)=>{var Gs;const kt=(Gs=n.current)==null?void 0:Gs.contentDocument;if(!kt)return;if(kt.body.focus(),xs==="cursor"&&_.current&&kt.body.contains(_.current.startContainer)){const _s=kt.getSelection();if(_s){_s.removeAllRanges(),_s.addRange(_.current),kt.execCommand("insertHTML",!1,St);const br=` `+kt.documentElement.outerHTML;a.current=br,i.current(br);return}}xs==="top"?kt.body.insertAdjacentHTML("afterbegin",St):kt.body.insertAdjacentHTML("beforeend",St);const fs=` `+kt.documentElement.outerHTML;a.current=fs,i.current(fs)},[A,D]=S.useState(!1),[R,z]=S.useState(null),[O,$]=S.useState(""),[ee,Z]=S.useState(""),[J,K]=S.useState("#406E71"),[re,ie]=S.useState("cursor"),ce=St=>{z(St),$(St.defaultText),Z(""),D(!0)},ne=()=>{if(!R)return;const St=ee.trim();if(!R.isForward&&!St)return;let xs=St;if(R.isForward){const _s=St||"",br=encodeURIComponent("You should see this newsletter"),zr=encodeURIComponent(_s?`I thought you'd like this — take a look: ${_s} `:`I thought you'd like this newsletter — take a look! `);xs=`mailto:?subject=${br}&body=${zr}`}else R.hrefPrefix==="tel:"?xs="tel:"+St.replace(/[^0-9+]/g,""):R.hrefPrefix==="mailto:"?xs="mailto:"+St:/^https?:\/\//i.test(St)||(xs="https://"+St);const kt=(O||R.defaultText).replace(/[<>]/g,""),fs=J||"#406E71",Gs=`
${kt}

 

`;E(Gs,re),D(!1)},[le,be]=S.useState(!1),[fe,je]=S.useState(""),[ve,We]=S.useState(""),[Ve,Le]=S.useState(""),[Me,ze]=S.useState("cursor"),Pe=(()=>{if(ve.trim())return ve.trim();const St=SHe(fe);return St?`https://i.ytimg.com/vi/${St}/hqdefault.jpg`:""})(),Ie=()=>{je(""),We(""),Le(""),be(!0)},De=()=>{const St=fe.trim();if(!St)return;let xs=St;/^https?:\/\//i.test(xs)||(xs="https://"+xs);const kt=SHe(xs),fs=kt?null:IPs(xs);let Gs=ve.trim();!Gs&&kt&&(Gs=`https://i.ytimg.com/vi/${kt}/hqdefault.jpg`),!Gs&&fs&&(Gs=`https://vumbnail.com/${fs}.jpg`),Gs||(Gs="https://placehold.co/600x340/406E71/ffffff?text=Watch+Video");const _s=(Ve||"Watch the video").replace(/[<>]/g,""),br=`
${_s}
▶ ${_s}

 

`.trim();E(br,Me),be(!1)},[pe,tt]=S.useState(!1),[ge,ct]=S.useState(""),[Ue,et]=S.useState(""),[Qe,Ne]=S.useState("full"),[$e,it]=S.useState("cursor"),[Je,st]=S.useState(!1),mt=S.useRef(null),wt=()=>{ct(""),et(""),Ne("full"),tt(!0)},at=async St=>{var xs;if(!r){he.error("You must be signed in to upload images");return}if(St.size>10*1024*1024){he.error("Image must be under 10MB");return}st(!0);try{const kt=((xs=St.name.split(".").pop())==null?void 0:xs.toLowerCase())||"png",fs=`${r.id}/newsletters/${Date.now()}-${Math.random().toString(36).slice(2,8)}.${kt}`,{error:Gs}=await V.storage.from("email-assets").upload(fs,St,{cacheControl:"3600",upsert:!1,contentType:St.type});if(Gs)throw Gs;const{data:_s}=V.storage.from("email-assets").getPublicUrl(fs);ct(_s.publicUrl),he.success("Image uploaded")}catch(kt){he.error(kt.message||"Upload failed")}finally{st(!1)}},rt=()=>{if(!ge.trim())return;const St=(Ue||"").replace(/[<>"]/g,""),xs=Qe==="half"?280:560,kt=`
${St}

 

`.trim();E(kt,$e),tt(!1)},{data:Et,isLoading:hs}=yt({queryKey:["newsletter-editor-videos",r==null?void 0:r.id],enabled:!!(r!=null&&r.id)&&le,queryFn:async()=>{const{data:St,error:xs}=await V.from("agent_videos").select("id, title, thumbnail_url, share_token, duration_seconds, created_at").eq("owner_user_id",r.id).eq("is_deleted",!1).eq("status","ready").not("share_token","is",null).order("created_at",{ascending:!1}).limit(50);if(xs)throw xs;return St||[]}}),Is=St=>{St.share_token&&(je(`https://video.relevelup.com/share/video/${St.share_token}`),We(`https://video.relevelup.com/thumb/${St.share_token}`),Le(St.title||"Watch the video"))},lr=l==="mobile"?390:"100%",us=l==="mobile"?390:void 0;return e.jsxs("div",{className:"rounded-md border overflow-hidden bg-background",children:[e.jsxs("div",{className:"flex items-center gap-1 border-b bg-muted/40 px-2 py-1.5 flex-wrap",children:[e.jsx(H,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>k("bold"),title:"Bold",children:e.jsx(Ok,{className:"h-3.5 w-3.5"})}),e.jsx(H,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>k("italic"),title:"Italic",children:e.jsx(qk,{className:"h-3.5 w-3.5"})}),e.jsx(H,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>k("underline"),title:"Underline",children:e.jsx(XI,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:"w-px h-5 bg-border mx-1"}),e.jsx(H,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>k("insertUnorderedList"),title:"Bullet list",children:e.jsx(Vf,{className:"h-3.5 w-3.5"})}),e.jsx(H,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>k("insertOrderedList"),title:"Numbered list",children:e.jsx(b1,{className:"h-3.5 w-3.5"})}),e.jsx(H,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:T,title:"Insert link",children:e.jsx(Jo,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:"w-px h-5 bg-border mx-1"}),e.jsx(H,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>k("undo"),title:"Undo",children:e.jsx(Xk,{className:"h-3.5 w-3.5"})}),e.jsx(H,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>k("redo"),title:"Redo",children:e.jsx(Yk,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:"w-px h-5 bg-border mx-1"}),e.jsxs(Xu,{children:[e.jsx(Qu,{asChild:!0,children:e.jsxs(H,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 gap-1.5",title:"Insert CTA Button",children:[e.jsx(Kd,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"text-xs font-medium",children:"CTA Button"})]})}),e.jsxs(wu,{align:"start",className:"w-56 bg-popover z-50",children:[e.jsx(l9,{children:"Insert a call-to-action"}),e.jsx(A_,{}),MPs.map(St=>{const xs=St.icon;return e.jsxs(di,{onClick:()=>ce(St),children:[e.jsx(xs,{className:"h-4 w-4 mr-2"}),St.label]},St.key)})]})]}),e.jsxs(H,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 gap-1.5",title:"Insert image",onClick:wt,children:[e.jsx(wl,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"text-xs font-medium",children:"Image"})]}),e.jsxs(H,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 gap-1.5",title:"Insert video block",onClick:Ie,children:[e.jsx(xn,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"text-xs font-medium",children:"Video"})]}),e.jsx("div",{className:"ml-auto flex items-center gap-2",children:e.jsxs(hP,{type:"single",value:l,onValueChange:St=>St&&o(St),size:"sm",className:"h-7",children:[e.jsx(WE,{value:"desktop",className:"h-7 px-2",title:"Desktop preview",children:e.jsx(Vk,{className:"h-3.5 w-3.5"})}),e.jsx(WE,{value:"mobile",className:"h-7 px-2",title:"Mobile preview",children:e.jsx(Vy,{className:"h-3.5 w-3.5"})})]})})]}),e.jsxs("div",{className:"px-3 py-1.5 bg-primary/5 border-b text-xs text-muted-foreground flex items-center gap-1.5",children:[e.jsx(Kd,{className:"h-3 w-3"}),e.jsxs("span",{children:["Tip: click where you want to add an image, video, or button — or click a ",e.jsx("em",{children:"[ bracketed placeholder ]"})," to replace it. Click any button/link to edit where it goes."]})]}),e.jsx("div",{className:"bg-muted/20 flex justify-center overflow-auto",style:{padding:l==="mobile"?16:0},children:e.jsx("iframe",{ref:n,title:"Newsletter visual editor",className:"bg-white",style:{width:lr,maxWidth:us,height:480,border:l==="mobile"?"1px solid hsl(var(--border))":"none",borderRadius:l==="mobile"?12:0,boxShadow:l==="mobile"?"0 4px 12px rgba(0,0,0,0.08)":"none"}})}),e.jsx(bs,{open:d,onOpenChange:h,children:e.jsxs(vs,{className:"sm:max-w-md",children:[e.jsx(Cs,{children:e.jsx(Ns,{children:"Edit link"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"link-edit-text",children:"Button / link text"}),e.jsx(Se,{id:"link-edit-text",value:x,onChange:St=>y(St.target.value),placeholder:"Click here"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"link-edit-href",children:"Where should this link go?"}),e.jsx(Se,{id:"link-edit-href",value:m,onChange:St=>p(St.target.value),placeholder:"https://your-website.com/...",autoFocus:!0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Use https://… for a web page, mailto:you@email.com for email, or tel:+15555551234 for a phone number."})]})]}),e.jsxs(wn,{children:[e.jsx(H,{type:"button",variant:"outline",onClick:()=>h(!1),children:"Cancel"}),e.jsx(H,{type:"button",onClick:j,disabled:!m.trim(),children:"Save link"})]})]})}),e.jsx(bs,{open:A,onOpenChange:D,children:e.jsxs(vs,{className:"sm:max-w-md",children:[e.jsx(Cs,{children:e.jsxs(Ns,{children:["Insert ",(R==null?void 0:R.label)||"CTA Button"]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"cta-text",children:"Button text"}),e.jsx(Se,{id:"cta-text",value:O,onChange:St=>$(St.target.value),placeholder:R==null?void 0:R.defaultText})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"cta-value",children:R==null?void 0:R.helper}),e.jsx(Se,{id:"cta-value",value:ee,onChange:St=>Z(St.target.value),placeholder:R==null?void 0:R.placeholder,autoFocus:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"cta-color",children:"Button color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Se,{id:"cta-color",type:"color",value:J,onChange:St=>K(St.target.value),className:"h-9 w-16 p-1 cursor-pointer"}),e.jsx(Se,{value:J,onChange:St=>K(St.target.value),className:"flex-1"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Position"}),e.jsxs(I2,{value:re,onValueChange:St=>ie(St),className:"flex gap-4 flex-wrap",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(ih,{value:"cursor",id:"cta-cursor"}),e.jsxs(ue,{htmlFor:"cta-cursor",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(Kd,{className:"h-3.5 w-3.5"}),"At cursor"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(ih,{value:"top",id:"cta-top"}),e.jsxs(ue,{htmlFor:"cta-top",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(Hu,{className:"h-3.5 w-3.5"}),"Top of newsletter"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(ih,{value:"bottom",id:"cta-bottom"}),e.jsxs(ue,{htmlFor:"cta-bottom",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(fm,{className:"h-3.5 w-3.5"}),"Bottom of newsletter"]})]})]})]}),e.jsx("div",{className:"rounded-md border bg-muted/30 p-4 flex justify-center",children:e.jsx("div",{style:{backgroundColor:J,color:"#ffffff",borderRadius:6,padding:"14px 28px",fontFamily:"Arial, sans-serif",fontWeight:600,fontSize:16},children:O||(R==null?void 0:R.defaultText)})})]}),e.jsxs(wn,{children:[e.jsx(H,{type:"button",variant:"outline",onClick:()=>D(!1),children:"Cancel"}),e.jsx(H,{type:"button",onClick:ne,disabled:!(R!=null&&R.isForward)&&!ee.trim(),children:"Insert Button"})]})]})}),e.jsx(bs,{open:le,onOpenChange:be,children:e.jsxs(vs,{className:"sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(Cs,{children:e.jsx(Ns,{children:"Insert Video Block"})}),e.jsxs(ta,{defaultValue:"library",className:"space-y-3",children:[e.jsxs(Qn,{className:"grid w-full grid-cols-3",children:[e.jsx(ts,{value:"library",children:"My Library"}),e.jsx(ts,{value:"url",children:"From URL"}),e.jsx(ts,{value:"record",children:"Record New"})]}),e.jsxs(cs,{value:"library",className:"space-y-3 mt-2",children:[hs?e.jsxs("div",{className:"text-center py-8 text-sm text-muted-foreground",children:[e.jsx(is,{className:"h-5 w-5 animate-spin mx-auto mb-2"}),"Loading your videos..."]}):!Et||Et.length===0?e.jsxs("div",{className:"text-center py-8 text-sm text-muted-foreground border rounded-md",children:[e.jsx(xn,{className:"h-8 w-8 mx-auto mb-2 opacity-40"}),e.jsx("p",{children:"No videos in your library yet."}),e.jsx("p",{className:"text-xs mt-1",children:'Record one in the "Record New" tab.'})]}):e.jsx("div",{className:"grid grid-cols-2 gap-2 max-h-72 overflow-y-auto pr-1",children:Et.map(St=>{const xs=fe.includes(St.share_token||"___"),kt=St.share_token?`https://video.relevelup.com/thumb/${St.share_token}`:St.thumbnail_url||"";return e.jsxs("button",{type:"button",onClick:()=>Is(St),className:`group text-left rounded-md border-2 overflow-hidden transition-all ${xs?"border-primary ring-2 ring-primary/30":"border-transparent hover:border-primary/40"}`,children:[e.jsxs("div",{className:"aspect-video bg-muted relative",children:[kt?e.jsx("img",{src:kt,alt:St.title||"Video",className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground",children:e.jsx(xn,{className:"h-6 w-6"})}),e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx("div",{className:"rounded-full bg-black/60 w-9 h-9 flex items-center justify-center",children:e.jsx(El,{className:"h-4 w-4 text-white fill-white"})})})]}),e.jsx("div",{className:"p-1.5",children:e.jsx("p",{className:"text-xs font-medium line-clamp-1",children:St.title||"Untitled"})})]},St.id)})}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{htmlFor:"vid-title-lib",className:"text-xs",children:"Caption (optional)"}),e.jsx(Se,{id:"vid-title-lib",value:Ve,onChange:St=>Le(St.target.value),placeholder:"Watch the video"})]})]}),e.jsxs(cs,{value:"url",className:"space-y-3 mt-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{htmlFor:"vid-url",children:"Video URL"}),e.jsx(Se,{id:"vid-url",value:fe,onChange:St=>je(St.target.value),placeholder:"https://youtube.com/watch?v=... or Vimeo link"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"YouTube & Vimeo thumbnails are detected automatically."})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{htmlFor:"vid-title",children:"Caption (optional)"}),e.jsx(Se,{id:"vid-title",value:Ve,onChange:St=>Le(St.target.value),placeholder:"Watch the video"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{htmlFor:"vid-thumb",children:"Custom thumbnail URL (optional)"}),e.jsx(Se,{id:"vid-thumb",value:ve,onChange:St=>We(St.target.value),placeholder:"https://... (only if not YouTube/Vimeo)"})]})]}),e.jsx(cs,{value:"record",className:"mt-2",children:e.jsxs("div",{className:"rounded-md border bg-muted/30 p-5 text-center space-y-3",children:[e.jsx(xn,{className:"h-10 w-10 mx-auto text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Record a quick video"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:`Record a personal intro, market update, or property tour. When you're done, it'll show up in "My Library" and you can pick it from there.`})]}),e.jsx(H,{type:"button",onClick:()=>{window.open("/mission-control/video/record","_blank")},children:"Open Video Recorder"}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Opens in a new tab — come back here when you're done."})]})})]}),e.jsxs("div",{className:"space-y-2 pt-2 border-t",children:[e.jsx(ue,{children:"Position"}),e.jsxs(I2,{value:Me,onValueChange:St=>ze(St),className:"flex gap-4 flex-wrap",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(ih,{value:"cursor",id:"vid-cursor"}),e.jsxs(ue,{htmlFor:"vid-cursor",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(Kd,{className:"h-3.5 w-3.5"}),"At cursor"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(ih,{value:"top",id:"vid-top"}),e.jsxs(ue,{htmlFor:"vid-top",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(Hu,{className:"h-3.5 w-3.5"}),"Top"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(ih,{value:"bottom",id:"vid-bottom"}),e.jsxs(ue,{htmlFor:"vid-bottom",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(fm,{className:"h-3.5 w-3.5"}),"Bottom"]})]})]})]}),Pe&&e.jsxs("div",{className:"rounded-md border bg-muted/30 p-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Preview"}),e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:Pe,alt:"thumbnail",className:"w-full rounded-md",style:{maxHeight:180,objectFit:"cover"},onError:St=>{St.target.style.opacity="0.3"}}),e.jsx("div",{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 rounded-full bg-black/65 text-white flex items-center justify-center",style:{width:56,height:56,fontSize:24},children:"▶"})]})]}),e.jsxs(wn,{children:[e.jsx(H,{type:"button",variant:"outline",onClick:()=>be(!1),children:"Cancel"}),e.jsx(H,{type:"button",onClick:De,disabled:!fe.trim(),children:"Insert Video"})]})]})}),e.jsx(bs,{open:pe,onOpenChange:tt,children:e.jsxs(vs,{className:"sm:max-w-md max-h-[90vh] overflow-y-auto",children:[e.jsx(Cs,{children:e.jsx(Ns,{children:"Insert Image"})}),e.jsxs(ta,{defaultValue:"upload",className:"space-y-3",children:[e.jsxs(Qn,{className:"grid w-full grid-cols-2",children:[e.jsx(ts,{value:"upload",children:"Upload"}),e.jsx(ts,{value:"url",children:"From URL"})]}),e.jsxs(cs,{value:"upload",className:"space-y-3 mt-2",children:[e.jsx("input",{ref:mt,type:"file",accept:"image/png,image/jpeg,image/webp,image/gif",className:"hidden",onChange:St=>{var kt;const xs=(kt=St.target.files)==null?void 0:kt[0];xs&&at(xs),St.target.value=""}}),ge?e.jsxs("div",{className:"rounded-md border overflow-hidden bg-muted/30",children:[e.jsx("img",{src:ge,alt:"Preview",className:"w-full max-h-48 object-contain"}),e.jsxs("div",{className:"flex justify-between items-center p-2 text-xs",children:[e.jsx("span",{className:"text-muted-foreground truncate",children:"Uploaded ✓"}),e.jsx(H,{type:"button",variant:"ghost",size:"sm",onClick:()=>ct(""),children:"Replace"})]})]}):e.jsx("button",{type:"button",onClick:()=>{var St;return(St=mt.current)==null?void 0:St.click()},disabled:Je,className:"w-full rounded-md border-2 border-dashed border-border hover:border-primary/50 hover:bg-muted/40 transition-colors py-10 text-center disabled:opacity-60",children:Je?e.jsxs(e.Fragment,{children:[e.jsx(is,{className:"h-8 w-8 mx-auto mb-2 animate-spin text-primary"}),e.jsx("p",{className:"text-sm",children:"Uploading..."})]}):e.jsxs(e.Fragment,{children:[e.jsx(Ea,{className:"h-8 w-8 mx-auto mb-2 text-muted-foreground"}),e.jsx("p",{className:"text-sm font-medium",children:"Click to upload an image"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"PNG, JPG, WEBP, GIF · up to 10MB"})]})})]}),e.jsxs(cs,{value:"url",className:"space-y-3 mt-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{htmlFor:"img-url",children:"Image URL"}),e.jsx(Se,{id:"img-url",value:ge,onChange:St=>ct(St.target.value),placeholder:"https://..."})]}),ge&&/^https?:\/\//i.test(ge)&&e.jsx("div",{className:"rounded-md border overflow-hidden bg-muted/30",children:e.jsx("img",{src:ge,alt:"Preview",className:"w-full max-h-48 object-contain",onError:St=>{St.target.style.opacity="0.3"}})})]})]}),e.jsxs("div",{className:"space-y-3 pt-2 border-t",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{htmlFor:"img-alt",children:"Alt text (for accessibility)"}),e.jsx(Se,{id:"img-alt",value:Ue,onChange:St=>et(St.target.value),placeholder:"Describe the image"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{children:"Size"}),e.jsxs(I2,{value:Qe,onValueChange:St=>Ne(St),className:"flex gap-4",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(ih,{value:"full",id:"img-full"}),e.jsx(ue,{htmlFor:"img-full",className:"cursor-pointer font-normal",children:"Full width"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(ih,{value:"half",id:"img-half"}),e.jsx(ue,{htmlFor:"img-half",className:"cursor-pointer font-normal",children:"Half width"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{children:"Position"}),e.jsxs(I2,{value:$e,onValueChange:St=>it(St),className:"flex gap-4 flex-wrap",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(ih,{value:"cursor",id:"img-cursor"}),e.jsxs(ue,{htmlFor:"img-cursor",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(Kd,{className:"h-3.5 w-3.5"}),"At cursor"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(ih,{value:"top",id:"img-top"}),e.jsxs(ue,{htmlFor:"img-top",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(Hu,{className:"h-3.5 w-3.5"}),"Top"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(ih,{value:"bottom",id:"img-bottom"}),e.jsxs(ue,{htmlFor:"img-bottom",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(fm,{className:"h-3.5 w-3.5"}),"Bottom"]})]})]})]})]}),e.jsxs(wn,{children:[e.jsx(H,{type:"button",variant:"outline",onClick:()=>tt(!1),children:"Cancel"}),e.jsx(H,{type:"button",onClick:rt,disabled:!ge.trim()||Je,children:"Insert Image"})]})]})})]})}function PPs({open:s,onOpenChange:t,initial:r,onSaved:n}){const{user:a,isAdmin:i,isBrokerageManager:l,brokerageId:o}=Ms(),[c,d]=S.useState(""),[h,m]=S.useState(""),[p,x]=S.useState(""),[y,_]=S.useState(!1),[b,j]=S.useState("private"),[k,T]=S.useState(!1),{data:E}=yt({queryKey:["my-team-leader-info",a==null?void 0:a.id],enabled:!!(a!=null&&a.id)&&s,queryFn:async()=>{const{data:z}=await V.from("team_members").select("team_id, role").eq("user_id",a.id).maybeSingle();return z}}),A=(E==null?void 0:E.role)==="team_leader",D=(E==null?void 0:E.team_id)??null;S.useEffect(()=>{s&&(d((r==null?void 0:r.title)??""),m((r==null?void 0:r.description)??""),x((r==null?void 0:r.html_content)??LPs()),_((r==null?void 0:r.is_template)??!1),j((r==null?void 0:r.share_scope)??"private"))},[s,r]);const R=async()=>{if(a){if(!c.trim()){he.error("Please enter a title");return}if(!p.trim()){he.error("Newsletter content is empty");return}T(!0);try{const z={user_id:a.id,title:c.trim(),description:h.trim()||null,html_content:p,is_template:y,share_scope:b,shared_team_id:b==="team"?D:null,shared_brokerage_id:b==="brokerage"?o:null};if(b==="team"&&!D){he.error("You must be a team leader to share with a team"),T(!1);return}if(b==="brokerage"&&!l){he.error("Only brokerage managers can share to a brokerage"),T(!1);return}if(b==="global"&&!i){he.error("Only admins can publish global starter templates"),T(!1);return}let O;if(r!=null&&r.id?{error:O}=await V.from("agent_custom_newsletters").update(z).eq("id",r.id):{error:O}=await V.from("agent_custom_newsletters").insert(z),O)throw O;he.success(r!=null&&r.id?"Saved":"Newsletter created"),n==null||n(),t(!1)}catch(z){he.error(z.message||"Failed to save")}finally{T(!1)}}};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-6xl h-[92vh] flex flex-col p-0",children:[e.jsx(Cs,{className:"px-6 pt-6 pb-3 border-b",children:e.jsx(Ns,{children:r!=null&&r.id?"Edit Newsletter":"Create Newsletter"})}),e.jsxs("div",{className:"flex-1 overflow-y-auto px-6 py-4 space-y-4",children:[e.jsxs("div",{className:"grid sm:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"acn-title",children:"Title *"}),e.jsx(Se,{id:"acn-title",value:c,onChange:z=>d(z.target.value),placeholder:"e.g. June Market Update"})]}),e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"acn-desc",children:"Description (optional)"}),e.jsx(Se,{id:"acn-desc",value:h,onChange:z=>m(z.target.value),placeholder:"Short summary"})]})]}),e.jsxs("div",{className:"flex items-center gap-3 rounded-lg border bg-muted/30 px-4 py-3",children:[e.jsx(Or,{id:"acn-template",checked:y,onCheckedChange:_}),e.jsx(ue,{htmlFor:"acn-template",className:"cursor-pointer",children:"Save as reusable template"}),e.jsx("span",{className:"text-xs text-muted-foreground ml-auto",children:"Templates can be duplicated and reused for future newsletters"})]}),(A||l||i)&&e.jsxs("div",{className:"rounded-lg border p-4 space-y-3",children:[e.jsx(ue,{className:"text-sm font-semibold",children:"Sharing"}),e.jsxs(I2,{value:b,onValueChange:z=>j(z),className:"space-y-2",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(ih,{value:"private",id:"s-private",className:"mt-0.5"}),e.jsxs(ue,{htmlFor:"s-private",className:"cursor-pointer font-normal",children:[e.jsx("span",{className:"font-medium",children:"Private"}),e.jsx("span",{className:"block text-xs text-muted-foreground",children:"Only you can see this"})]})]}),A&&e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(ih,{value:"team",id:"s-team",className:"mt-0.5"}),e.jsxs(ue,{htmlFor:"s-team",className:"cursor-pointer font-normal",children:[e.jsx("span",{className:"font-medium",children:"Share with my team"}),e.jsx("span",{className:"block text-xs text-muted-foreground",children:"All members of your team can use this"})]})]}),l&&e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(ih,{value:"brokerage",id:"s-brokerage",className:"mt-0.5"}),e.jsxs(ue,{htmlFor:"s-brokerage",className:"cursor-pointer font-normal",children:[e.jsx("span",{className:"font-medium",children:"Share with my brokerage"}),e.jsx("span",{className:"block text-xs text-muted-foreground",children:"All agents in your brokerage can use this"})]})]}),i&&e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(ih,{value:"global",id:"s-global",className:"mt-0.5"}),e.jsxs(ue,{htmlFor:"s-global",className:"cursor-pointer font-normal",children:[e.jsx("span",{className:"font-medium",children:"Global starter template"}),e.jsx("span",{className:"block text-xs text-muted-foreground",children:"Visible to all users as a starter"})]})]})]})]}),e.jsxs("div",{children:[e.jsx(ue,{className:"mb-2 block",children:"Content"}),e.jsx(Dgt,{html:p,onChange:x})]})]}),e.jsxs(wn,{className:"px-6 py-3 border-t",children:[e.jsx(H,{variant:"outline",onClick:()=>t(!1),disabled:k,children:"Cancel"}),e.jsxs(H,{onClick:R,disabled:k,children:[k?e.jsx(is,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(vc,{className:"h-4 w-4 mr-2"}),r!=null&&r.id?"Save Changes":"Create"]})]})]})})}function LPs(){return`

Your Newsletter Title

A note from {{agent_name}}

Hi {{first_name}},

Start writing here. Tell your story, share market insights, or invite your contacts to an upcoming event.

Talk soon,
{{agent_name}}

`}function cf(){const{data:s,isLoading:t}=yt({queryKey:["gmail-integration"],queryFn:async()=>{const{data:a,error:i}=await V.from("gmail_integrations").select("*").maybeSingle();if(i)throw i;return a}}),r=!!(s!=null&&s.is_active),n=(s==null?void 0:s.gmail_email)||null;return{isGmailConnected:r,gmailEmail:n,isLoading:t}}function Dz(){var a;const{user:s}=Ms(),{data:t,isLoading:r}=yt({queryKey:["mass-email-settings",s==null?void 0:s.id],enabled:!!s,staleTime:60*1e3,queryFn:async()=>{var d,h,m,p;const[i,l]=await Promise.all([V.from("mass_email_settings").select("reply_to_email, display_name").eq("user_id",s.id).maybeSingle(),V.from("profiles").select("email, name").eq("id",s.id).maybeSingle()]),o=i.data,c=l.data;return{reply_to_email:((d=o==null?void 0:o.reply_to_email)==null?void 0:d.trim())||((h=c==null?void 0:c.email)==null?void 0:h.trim())||s.email||null,display_name:((m=o==null?void 0:o.display_name)==null?void 0:m.trim())||((p=c==null?void 0:c.name)==null?void 0:p.trim())||null}}});return{isReady:!!((a=t==null?void 0:t.reply_to_email)!=null&&a.trim()),isLoading:r,settings:t}}function q8(){const s=ba();return yt({queryKey:["custom-tags",s],queryFn:async()=>{const{data:t,error:r}=await V.from("contact_custom_tags").select("*").eq("owner_user_id",s).order("name");if(r)throw r;return t},enabled:!!s})}function DPs(s){return yt({queryKey:["contact-custom-tags",s],queryFn:async()=>{const{data:t,error:r}=await V.from("contact_custom_tag_assignments").select("*, tag:contact_custom_tags(*)").eq("contact_id",s);if(r)throw r;return t},enabled:!!s})}function aMe(){const s=ns(),t=ba();return Pt({mutationFn:async({name:r,color:n})=>{const{data:a,error:i}=await V.from("contact_custom_tags").insert({owner_user_id:t,name:r.trim(),color:n||"#6366F1"}).select().single();if(i)throw i;return a},onSuccess:()=>{s.invalidateQueries({queryKey:["custom-tags"]})}})}function RPs(){const s=ns();return Pt({mutationFn:async t=>{const{error:r}=await V.from("contact_custom_tags").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["custom-tags"]}),s.invalidateQueries({queryKey:["contact-custom-tags"]}),s.invalidateQueries({queryKey:["all-contact-custom-tags"]})}})}function OPs(){const s=ns();return Pt({mutationFn:async({id:t,name:r,color:n})=>{const a={};r!==void 0&&(a.name=r.trim()),n!==void 0&&(a.color=n);const{error:i}=await V.from("contact_custom_tags").update(a).eq("id",t);if(i)throw i},onSuccess:()=>{s.invalidateQueries({queryKey:["custom-tags"]}),s.invalidateQueries({queryKey:["contact-custom-tags"]}),s.invalidateQueries({queryKey:["all-contact-custom-tags"]})}})}function Rgt(){const s=ns();return Pt({mutationFn:async({contactId:t,tagId:r})=>{const{error:n}=await V.from("contact_custom_tag_assignments").insert({contact_id:t,tag_id:r});if(n)throw n},onSuccess:(t,{contactId:r})=>{s.invalidateQueries({queryKey:["contact-custom-tags",r]}),s.invalidateQueries({queryKey:["all-contact-custom-tags"]})}})}function FPs(){const s=ns();return Pt({mutationFn:async({contactId:t,tagId:r})=>{const{error:n}=await V.from("contact_custom_tag_assignments").delete().eq("contact_id",t).eq("tag_id",r);if(n)throw n},onSuccess:(t,{contactId:r})=>{s.invalidateQueries({queryKey:["contact-custom-tags",r]}),s.invalidateQueries({queryKey:["all-contact-custom-tags"]})}})}function iMe(){const s=ba();return yt({queryKey:["all-contact-custom-tags",s],queryFn:async()=>{const{data:t,error:r}=await V.from("contact_custom_tag_assignments").select("contact_id, tag_id, tag:contact_custom_tags(id, name, color)");if(r)throw r;return t},enabled:!!s})}function Ogt(){const{user:s}=Ms();return yt({queryKey:["contact-smart-lists",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:r}=await V.from("contact_smart_lists").select("*").order("created_at",{ascending:!1});if(r)throw r;return t},enabled:!!s})}function BPs(){const s=ns(),{user:t}=Ms();return Pt({mutationFn:async({name:r,filters:n,sort_by:a})=>{const{data:i,error:l}=await V.from("contact_smart_lists").insert({owner_user_id:t.id,name:r,filters:n,sort_by:a}).select().single();if(l)throw l;return i},onSuccess:()=>{s.invalidateQueries({queryKey:["contact-smart-lists"]}),En({title:"Smart filter saved"})},onError:r=>{En({title:"Error saving smart filter",description:r.message,variant:"destructive"})}})}function zPs(){const s=ns();return Pt({mutationFn:async t=>{const{error:r}=await V.from("contact_smart_lists").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["contact-smart-lists"]}),En({title:"Smart filter deleted"})}})}const CHe=s=>s.replace(/&/g,"&").replace(//g,">").replace(/"/g,""");function THe(s,t,r,n){const a=t.name||`${t.first_name||""} ${t.last_name||""}`.trim()||"there",i=new Date,l=new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"long",day:"numeric",year:"numeric"}).format(i),o=new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",year:"numeric"}).format(i),c={first_name:t.first_name||"there",last_name:t.last_name||"",name:a,full_name:a,email:t.email||"",phone:t.phone||"",address:t.address||"",city:t.city||"",state:t.state||"",zip:t.zip||t.zip_code||"",agent_name:(r==null?void 0:r.name)||"",agent_email:(r==null?void 0:r.email)||"",agent_phone:(r==null?void 0:r.phone)||"",agent_title:(r==null?void 0:r.title)||"",brokerage:n||"",current_date:l,current_year:o};return s.replace(/\{\{\s*(\w+)\s*\}\}/g,(d,h)=>c[h]??`{{${h}}}`)}function $Ps(s,t,r,n){const a=t.trim()?`
${CHe(t).replace(/\n/g,"
")}
`:"",i=r.trim()?`
${CHe(r).replace(/\n/g,"
")}
`:"",l=n?`
${n}
`:"";return`${a} ${s} ${i} ${l}`}function UPs(s,t,r){const n=(s==null?void 0:s.name)||"Your Agent",a=(s==null?void 0:s.email)||"",i=(t==null?void 0:t.name)||"",l=[t==null?void 0:t.city,t==null?void 0:t.state].filter(Boolean).join(", "),o=a?`mailto:${encodeURIComponent(a)}?subject=${encodeURIComponent("Unsubscribe")}&body=${encodeURIComponent(`Please remove ${r} from your newsletter list.`)}`:"#";return`
${n}${i?" • "+i:""}
${l?`
${l}
`:""}
You're receiving this because ${n} thought you'd find it useful. Unsubscribe
`}const qPs=["free","act now","click here","limited time","urgent","$$$","100% free","guarantee","no obligation","risk-free","winner","cash bonus","make money","earn extra","amazing"];function VPs(s,t){const r=[],n=s.trim();if(n.length>0){n.length<10&&r.push("Subject line is very short — most opened subjects are 30-60 characters."),n.length>90&&r.push("Subject line is very long — many inboxes truncate after 60-70 characters.");const l=n.replace(/[^A-Za-z]/g,""),o=n.replace(/[^A-Z]/g,"");l.length>6&&o.length/l.length>.6&&r.push("Subject is mostly uppercase — this often triggers spam filters."),(n.match(/!/g)||[]).length>=3&&r.push("Too many exclamation marks in the subject.");const d=n.toLowerCase(),h=qPs.filter(m=>d.includes(m));h.length>0&&r.push(`Subject contains spam-trigger words: ${h.slice(0,3).join(", ")}.`)}const a=t.replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim();return a.length<40&&r.push("Email body is very short — add more text so it doesn't look like a spam blast."),(t.match(/0&&a.length<80&&r.push("Email is mostly images with little text — many spam filters block these."),r}function oMe({open:s,onOpenChange:t,newsletterId:r,newsletterTitle:n,htmlCode:a}){const{user:i}=Ms();cf();const{isReady:l,settings:o}=Dz(),c=ba(),{data:d}=yt({queryKey:["agent-profile-for-newsletter-send",i==null?void 0:i.id],enabled:!!i&&s,staleTime:5*60*1e3,queryFn:async()=>{if(!i)return null;const{data:cr}=await V.from("profiles").select("name, email, phone, avatar_url, title, email_signature, use_email_signature").eq("id",i.id).maybeSingle();return cr}}),[h,m]=S.useState("visual"),[p,x]=S.useState("all"),[y,_]=S.useState(""),[b,j]=S.useState(""),[k,T]=S.useState(""),[E,A]=S.useState(""),[D,R]=S.useState(!0),[z,O]=S.useState([]),[$,ee]=S.useState(null),[Z,J]=S.useState(new Set),[K,re]=S.useState(""),[ie,ce]=S.useState(!1),[ne,le]=S.useState(!1),[be,fe]=S.useState(!1),[je,ve]=S.useState({sent:0,failed:0,total:0,currentName:""}),[We,Ve]=S.useState(!0),[Le,Me]=S.useState(!1),[ze,Pe]=S.useState([]),[Ie,De]=S.useState(!1),[pe,tt]=S.useState(new Set),[ge,ct]=S.useState("now"),[Ue,et]=S.useState(""),{data:Qe=[]}=q8(),{data:Ne=[]}=iMe(),{data:$e=[]}=Ogt(),{data:it=[],isLoading:Je}=yt({queryKey:["newsletter-send-contacts",c],enabled:!!c&&s,queryFn:async()=>{const cr=[];let on=0;const ds=1e3;for(;;){const{data:Na,error:vn}=await V.from("innercircle_contacts").select("id, first_name, last_name, email, phone, address, city, state, zip, zip_code").eq("owner_user_id",c).not("email","is",null).neq("email","").order("first_name").range(on,on+ds-1);if(vn)throw vn;if(!Na||Na.length===0||(cr.push(...Na),Na.length{const{data:cr}=await V.from("ses_suppressed_emails").select("email");return(cr||[]).map(on=>on.email.toLowerCase())}}),{data:mt}=yt({queryKey:["newsletter-brokerage-info",i==null?void 0:i.id],enabled:!!i&&s,staleTime:10*60*1e3,queryFn:async()=>{if(!i)return null;const{data:cr}=await V.from("profiles").select("brokerage_id").eq("id",i.id).maybeSingle();if(!(cr!=null&&cr.brokerage_id))return null;const{data:on}=await V.from("brokerages").select("name, city, state").eq("id",cr.brokerage_id).maybeSingle();return on}}),{data:wt}=yt({queryKey:["newsletter-active-lead-site",c],enabled:!!c&&s,staleTime:5*60*1e3,queryFn:async()=>{if(!c)return null;const{data:cr}=await V.from("lead_sites").select("id, subdomain_slug, mls_provider_id, mls_agent_id, mls_agent_key, is_active").eq("agent_id",c).eq("is_active",!0).not("mls_provider_id","is",null).order("created_at",{ascending:!0}).limit(1).maybeSingle();return cr}}),at=!!(wt!=null&&wt.mls_provider_id),rt=(wt==null?void 0:wt.mls_agent_id)||(wt==null?void 0:wt.mls_agent_key)||null,{data:Et=[],isLoading:hs}=yt({queryKey:["newsletter-agent-listings",c,rt],enabled:!!c&&!!rt&&Ie,staleTime:60*1e3,queryFn:async()=>{if(!rt)return[];const{data:cr}=await V.from("mlsgrid_listings").select("listing_key, address, city, state, list_price, bedrooms, bathrooms_total, living_area, photos, standard_status, modification_timestamp").eq("list_agent_mls_id",rt).eq("standard_status","Active").order("modification_timestamp",{ascending:!1}).limit(30);return cr||[]}}),Is=S.useMemo(()=>{const cr=new Set(st);return it.filter(on=>on.email&&on.email.includes("@")&&!cr.has(on.email.toLowerCase()))},[it,st]),lr=S.useMemo(()=>{if(z.length===0)return null;const cr=new Set;for(const on of Ne)z.includes(on.tag_id)&&cr.add(on.contact_id);return cr},[Ne,z]),us=S.useMemo(()=>$e.find(cr=>cr.id===$)||null,[$e,$]),St=S.useMemo(()=>{var cr;if(p==="all")return Is;if(p==="tags")return lr?Is.filter(on=>lr.has(on.id)):[];if(p==="smartlists"){if(!us)return[];const on=(((cr=us.filters)==null?void 0:cr.search)||"").toLowerCase().trim();return on?Is.filter(ds=>`${ds.first_name||""} ${ds.last_name||""}`.toLowerCase().includes(on)||(ds.email||"").toLowerCase().includes(on)):Is}return Is.filter(on=>Z.has(on.id))},[p,Is,lr,us,Z]),xs=S.useMemo(()=>{if(!K.trim())return Is;const cr=K.toLowerCase();return Is.filter(on=>`${on.first_name||""} ${on.last_name||""}`.toLowerCase().includes(cr))},[Is,K]);S.useEffect(()=>{s&&(_(""),j(`Hi {{first_name}}, Sharing this month's update — hope you find something useful!`),T(`As always, reach out anytime if I can help. Talk soon!`),A(a||""),m("light"),x("all"),O([]),ee(null),J(new Set),re(""),ce(!1),R(!0),Ve(!0),Pe([]),ct("now"),et(""),ve({sent:0,failed:0,total:0,currentName:""}))},[s,n,a]);const kt=l,fs=!!(y.trim()&&kt&&St.length>0&&!ne),Gs=cr=>{const on=h==="advanced"||h==="visual"?E:a,ds=D&&(d!=null&&d.email_signature)?d.email_signature:null;let Na;return h==="light"?Na=$Ps(on,b,k,ds):Na=ds?`${on}
${ds}
`:on,We&&(Na+=UPs(d??null,mt??null,cr.email)),THe(Na,cr,d??null,(mt==null?void 0:mt.name)??null)},_s=S.useMemo(()=>Gs({first_name:"Friend",last_name:"",email:"preview@example.com",phone:"",address:"",city:"",state:"",zip:""}),[h,b,k,E,a,D,d,We,mt]),br=S.useMemo(()=>VPs(y,h==="advanced"||h==="visual"?E:a),[y,h,E,a]),zr=async()=>{Me(!0),Pe([]);try{const cr=h==="advanced"||h==="visual"?E:a,{data:on,error:ds}=await V.functions.invoke("generate-newsletter-subjects",{body:{newsletterTitle:n,bodyHtml:cr,currentSubject:y}});if(ds)throw ds;const Na=on==null?void 0:on.subjects;if(!Array.isArray(Na)||Na.length===0)throw new Error("No subjects returned");Pe(Na)}catch(cr){const on=(cr==null?void 0:cr.message)||"Failed to generate subjects";on.includes("credits exhausted")||on.includes("402")?he.error("AI credits exhausted. Please add credits to your workspace."):on.includes("Rate limit")||on.includes("429")?he.error("Rate limit hit — try again in a moment."):he.error(on)}finally{Me(!1)}},Yr=cr=>cr?"$"+Number(cr).toLocaleString("en-US"):"",rn=()=>{if(pe.size===0){he.error("Pick at least one listing first.");return}const cr=Et.filter(_r=>pe.has(_r.listing_key)),on=(wt==null?void 0:wt.subdomain_slug)||"",ds=on?`https://${on}.relevelup.com`:"https://relevelup.com",vn=`

Featured Listings

${cr.map(_r=>{var ot,jt;const Hr=Array.isArray(_r.photos)&&_r.photos.length>0?typeof _r.photos[0]=="string"?_r.photos[0]:((ot=_r.photos[0])==null?void 0:ot.MediaURL)||((jt=_r.photos[0])==null?void 0:jt.url)||"":"",_a=`${ds}/listings/${_r.listing_key}`,Jt=_r.bedrooms?`${_r.bedrooms} bd`:"",Cr=_r.bathrooms_total?`${_r.bathrooms_total} ba`:"",Gt=_r.living_area?`${Number(_r.living_area).toLocaleString()} sqft`:"",Ee=[Jt,Cr,Gt].filter(Boolean).join(" • "),He=`${_r.address||""}${_r.city?", "+_r.city:""}`;return`
${Hr?`${He}`:""}
${Yr(_r.list_price)}
${He}
${Ee}
`.trim()}).join(` `)}
`.trim();A(_r=>(_r||a||"")+` `+vn),m("visual"),tt(new Set),De(!1),he.success(`Added ${cr.length} listing${cr.length===1?"":"s"} to your newsletter.`)},sn=()=>Gs({first_name:"__FN__",last_name:"__LN__",email:"__EM__",name:"__NAME__",phone:"__PHONE__",address:"__ADDR__",city:"__CITY__",state:"__STATE__",zip:"__ZIP__"}).replace(/__FN__/g,"{{first_name}}").replace(/__LN__/g,"{{last_name}}").replace(/__EM__/g,"{{email}}").replace(/__NAME__/g,"{{name}}").replace(/__PHONE__/g,"{{phone}}").replace(/__ADDR__/g,"{{address}}").replace(/__CITY__/g,"{{city}}").replace(/__STATE__/g,"{{state}}").replace(/__ZIP__/g,"{{zip}}"),Vr=()=>THe(y,{first_name:"__FN__",last_name:"__LN__",email:"__EM__",name:"__NAME__",phone:"__PHONE__",address:"__ADDR__",city:"__CITY__",state:"__STATE__",zip:"__ZIP__"},d??null,(mt==null?void 0:mt.name)??null).replace(/__FN__/g,"{{first_name}}").replace(/__LN__/g,"{{last_name}}").replace(/__EM__/g,"{{email}}").replace(/__NAME__/g,"{{name}}").replace(/__PHONE__/g,"{{phone}}").replace(/__ADDR__/g,"{{address}}").replace(/__CITY__/g,"{{city}}").replace(/__STATE__/g,"{{state}}").replace(/__ZIP__/g,"{{zip}}"),$r=()=>{if(fs){if(ge==="later"){if(!Ue){he.error("Pick a date and time to schedule.");return}const cr=new Date(Ue).getTime();if(Number.isNaN(cr)||cr{if(!(!fs||!i)){fe(!1),le(!0),ve({sent:0,failed:0,total:St.length,currentName:"Preparing campaign…"});try{const on=`${((o==null?void 0:o.display_name)||"ReLevelUp").toLowerCase().replace(/[^a-z]/g,".")}@send.relevelup.com`,ds=sn(),Na=Vr(),vn=ge==="later",{data:_r,error:Hr}=await V.from("email_campaigns").insert({user_id:c||i.id,name:`Newsletter: ${n}`,subject:Na,body_html:ds,from_email:on,reply_to_email:(o==null?void 0:o.reply_to_email)||null,total_recipients:St.length,status:vn?"scheduled":"draft",scheduled_at:vn?new Date(Ue).toISOString():null}).select("id").single();if(Hr)throw Hr;ve(Jt=>({...Jt,currentName:"Adding recipients…"}));const _a=St.map(Jt=>({campaign_id:_r.id,contact_id:Jt.id,email:Jt.email,name:[Jt.first_name,Jt.last_name].filter(Boolean).join(" ")||null,status:"pending"}));for(let Jt=0;Jt<_a.length;Jt+=500){const Cr=_a.slice(Jt,Jt+500),{error:Gt}=await V.from("email_campaign_recipients").insert(Cr);if(Gt)throw Gt;ve(Ee=>({...Ee,sent:Math.min(Jt+Cr.length,_a.length)}))}if(vn){const{error:Jt}=await V.functions.invoke("ses-schedule-campaign",{body:{action:"schedule",campaign_id:_r.id}});if(Jt)throw Jt;he.success(`Newsletter scheduled for ${new Date(Ue).toLocaleString()}.`)}else{const{error:Jt}=await V.functions.invoke("ses-send-campaign",{body:{action:"send_campaign",campaign_id:_r.id}});if(Jt)throw Jt;he.success(`Sending to ${St.length} contact${St.length===1?"":"s"}! Open & click tracking will appear in Sent Emails.`)}t(!1)}catch(cr){console.error("Newsletter send failed:",cr),he.error(`Failed to send: ${cr.message||"Unknown error"}`)}finally{le(!1)}}},Zn=cr=>{J(on=>{const ds=new Set(on);return ds.has(cr)?ds.delete(cr):ds.add(cr),ds})};return e.jsxs(bs,{open:s,onOpenChange:cr=>!ne&&t(cr),children:[e.jsxs(vs,{className:"max-w-5xl max-h-[92vh] overflow-y-auto",children:[e.jsx(Cs,{children:e.jsxs(Ns,{className:"flex items-center gap-2",children:[e.jsx(yn,{className:"h-5 w-5"})," Send Newsletter"]})}),!kt&&e.jsxs("div",{className:"flex items-start gap-3 rounded-lg border-2 border-destructive/40 bg-destructive/10 p-4 text-sm",children:[e.jsx(wo,{className:"h-5 w-5 text-destructive shrink-0 mt-0.5"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-semibold text-destructive",children:"Set up Mass Email first"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"You need to verify your sender email before you can send newsletters. It only takes a minute — we'll send a verification email to confirm you own the address."}),e.jsx(H,{size:"sm",className:"mt-3",onClick:()=>{window.open("/mission-control/integrations#mass-email","_blank")},children:"Set up Mass Email →"})]})]}),e.jsxs("div",{className:"grid lg:grid-cols-2 gap-6",children:[e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ue,{children:"Subject"}),e.jsxs(H,{type:"button",variant:"ghost",size:"sm",className:"h-7 gap-1 text-xs",onClick:zr,disabled:Le,title:"Generate subject lines with AI",children:[Le?e.jsx(is,{className:"h-3 w-3 animate-spin"}):e.jsx(Lr,{className:"h-3 w-3"}),"AI Suggestions"]})]}),e.jsx(Se,{value:y,onChange:cr=>_(cr.target.value),placeholder:"Newsletter subject"}),ze.length>0&&e.jsxs("div",{className:"rounded-md border bg-primary/5 p-2 space-y-1",children:[e.jsx("p",{className:"text-[11px] font-medium text-muted-foreground px-1",children:"Click to use:"}),ze.map((cr,on)=>e.jsxs("button",{type:"button",onClick:()=>{_(cr),Pe([])},className:"w-full text-left text-sm px-2 py-1.5 rounded hover:bg-primary/10 transition-colors",children:[e.jsx(Lr,{className:"h-3 w-3 inline-block mr-1.5 text-primary"}),cr]},on))]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Merge tags work here too: ",e.jsx("code",{children:"{{first_name}}"}),", ",e.jsx("code",{children:"{{agent_name}}"})]})]}),br.length>0&&e.jsxs("div",{className:"rounded-lg border border-amber-300/50 bg-amber-50 dark:bg-amber-950/20 p-3 text-xs space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-1.5 font-medium text-amber-900 dark:text-amber-200",children:[e.jsx(PF,{className:"h-3.5 w-3.5"}),"Deliverability tips"]}),e.jsx("ul",{className:"list-disc list-inside text-amber-800 dark:text-amber-300 space-y-0.5",children:br.map((cr,on)=>e.jsx("li",{children:cr},on))})]}),at&&e.jsxs("div",{className:"rounded-lg border border-primary/30 bg-primary/5 p-3 flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"text-xs",children:[e.jsxs("div",{className:"font-medium flex items-center gap-1.5",children:[e.jsx(Fn,{className:"h-3.5 w-3.5 text-primary"}),"Insert your active listings"]}),e.jsx("p",{className:"text-muted-foreground mt-0.5",children:"Pick from your live MLS listings and drop them into the email."})]}),e.jsx(H,{type:"button",size:"sm",variant:"outline",onClick:()=>De(!0),children:"Choose listings"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Editing"}),e.jsxs(ta,{value:h,onValueChange:cr=>m(cr),children:[e.jsxs(Qn,{className:"grid grid-cols-3 w-full",children:[e.jsxs(ts,{value:"visual",children:[e.jsx(My,{className:"h-3 w-3 mr-1"}),"Visual"]}),e.jsxs(ts,{value:"light",children:[e.jsx(kn,{className:"h-3 w-3 mr-1"}),"Quick edit"]}),e.jsxs(ts,{value:"advanced",children:[e.jsx(b2,{className:"h-3 w-3 mr-1"}),"HTML"]})]}),e.jsx(cs,{value:"visual",className:"mt-3",children:e.jsx(Dgt,{html:E,onChange:A})}),e.jsxs(cs,{value:"light",className:"space-y-3 mt-3",children:[e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs text-muted-foreground",children:"Personal intro (above newsletter)"}),e.jsx(vr,{value:b,onChange:cr=>j(cr.target.value),rows:4,placeholder:"Hi {{first_name}}, ..."})]}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs text-muted-foreground",children:"Personal outro (below newsletter)"}),e.jsx(vr,{value:k,onChange:cr=>T(cr.target.value),rows:3,placeholder:"Talk soon!"})]})]}),e.jsxs(cs,{value:"advanced",className:"mt-3",children:[e.jsx(ue,{className:"text-xs text-muted-foreground",children:"Edit full HTML"}),e.jsx(vr,{value:E,onChange:cr=>A(cr.target.value),rows:14,className:"font-mono text-xs"})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:"Append my email signature"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:d!=null&&d.email_signature?"Will append the signature from your profile.":"No signature set. Add one in Profile → Email Signature."})]}),e.jsx(Or,{checked:D&&!!(d!=null&&d.email_signature),disabled:!(d!=null&&d.email_signature),onCheckedChange:R})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:"Include unsubscribe footer"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Adds your brokerage info and a one-click unsubscribe link. Strongly recommended for deliverability."})]}),e.jsx(Or,{checked:We,onCheckedChange:Ve})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Recipients"}),e.jsxs(ta,{value:p,onValueChange:cr=>x(cr),children:[e.jsxs(Qn,{className:"grid grid-cols-4 w-full",children:[e.jsxs(ts,{value:"all",children:[e.jsx(Ar,{className:"h-3 w-3 mr-1"}),"All"]}),e.jsxs(ts,{value:"tags",children:[e.jsx(xm,{className:"h-3 w-3 mr-1"}),"Tags"]}),e.jsxs(ts,{value:"smartlists",children:[e.jsx(gF,{className:"h-3 w-3 mr-1"}),"Lists"]}),e.jsxs(ts,{value:"individual",children:[e.jsx(io,{className:"h-3 w-3 mr-1"}),"Pick"]})]}),e.jsx(cs,{value:"all",className:"mt-3",children:e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-4 text-sm",children:["Send to ",e.jsx("strong",{children:Is.length})," contact",Is.length===1?"":"s"," with a valid, non-suppressed email."]})}),e.jsxs(cs,{value:"tags",className:"mt-3 space-y-2",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Select one or more tags"}),e.jsx(Ci,{className:"h-40 rounded-lg border p-2",children:Qe.length===0?e.jsx("p",{className:"text-xs text-muted-foreground p-2",children:"No tags yet. Add tags to contacts to use this option."}):Qe.map(cr=>e.jsxs("label",{className:"flex items-center gap-2 p-1.5 hover:bg-muted rounded cursor-pointer",children:[e.jsx(ao,{checked:z.includes(cr.id),onCheckedChange:on=>O(ds=>on?[...ds,cr.id]:ds.filter(Na=>Na!==cr.id))}),e.jsx("span",{className:"inline-block h-2 w-2 rounded-full",style:{background:cr.color||"#406E71"}}),e.jsx("span",{className:"text-sm",children:cr.name})]},cr.id))})]}),e.jsxs(cs,{value:"smartlists",className:"mt-3 space-y-2",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Pick a saved smart list"}),e.jsx(Ci,{className:"h-40 rounded-lg border p-2",children:$e.length===0?e.jsx("p",{className:"text-xs text-muted-foreground p-2",children:"No smart lists yet. Save one from the contacts page."}):$e.map(cr=>e.jsxs("label",{className:"flex items-center gap-2 p-1.5 hover:bg-muted rounded cursor-pointer",children:[e.jsx("input",{type:"radio",name:"smartlist",checked:$===cr.id,onChange:()=>ee(cr.id)}),e.jsx("span",{className:"text-sm",children:cr.name})]},cr.id))})]}),e.jsxs(cs,{value:"individual",className:"mt-3 space-y-2",children:[e.jsx(Se,{placeholder:"Search contacts...",value:K,onChange:cr=>re(cr.target.value)}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground",children:[e.jsxs("span",{children:[Z.size," selected"]}),e.jsx("button",{type:"button",className:"underline",onClick:()=>J(new Set),children:"Clear"})]}),e.jsxs(Ci,{className:"h-48 rounded-lg border p-2",children:[Je&&e.jsx("p",{className:"text-xs text-muted-foreground p-2",children:"Loading contacts…"}),!Je&&xs.length===0&&e.jsx("p",{className:"text-xs text-muted-foreground p-2",children:"No matching contacts."}),xs.slice(0,200).map(cr=>e.jsxs("label",{className:"flex items-center gap-2 p-1.5 hover:bg-muted rounded cursor-pointer",children:[e.jsx(ao,{checked:Z.has(cr.id),onCheckedChange:()=>Zn(cr.id)}),e.jsxs("div",{className:"text-sm flex-1 min-w-0",children:[e.jsxs("div",{className:"truncate",children:[cr.first_name," ",cr.last_name||""]}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:cr.email})]})]},cr.id)),xs.length>200&&e.jsx("p",{className:"text-xs text-muted-foreground p-2",children:"Showing first 200 — refine search to see more."})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[e.jsxs(Xe,{variant:"secondary",className:"gap-1",children:[e.jsx(ea,{className:"h-3 w-3"})," ",St.length," recipient",St.length===1?"":"s"]}),kt&&e.jsxs(Xe,{variant:"outline",className:"gap-1 text-xs",children:["via Mass Email",o!=null&&o.reply_to_email?` (${o.reply_to_email})`:""]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ue,{children:"Preview"}),e.jsx(H,{variant:"ghost",size:"sm",onClick:()=>ce(cr=>!cr),children:ie?e.jsxs(e.Fragment,{children:[e.jsx($f,{className:"h-3 w-3 mr-1"}),"Hide"]}):e.jsxs(e.Fragment,{children:[e.jsx(Bn,{className:"h-3 w-3 mr-1"}),"Show"]})})]}),ie?e.jsx("div",{className:"rounded-lg border overflow-hidden bg-white",children:e.jsx("iframe",{title:"newsletter-preview",srcDoc:_s,className:"w-full h-[560px] bg-white",sandbox:""})}):e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-6 text-center text-sm text-muted-foreground",children:["Click ",e.jsx("strong",{children:"Show"})," to preview how the email looks. Merge tags use sample data (Friend)."]})]})]}),ne&&e.jsxs("div",{className:"space-y-2 rounded-lg border p-3 bg-muted/30",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(is,{className:"h-4 w-4 animate-spin"}),"Sending to ",je.currentName||"..."]}),e.jsxs("span",{className:"text-muted-foreground",children:[je.sent+je.failed," / ",je.total]})]}),e.jsx(Mi,{value:je.total?(je.sent+je.failed)/je.total*100:0}),je.failed>0&&e.jsxs("p",{className:"text-xs text-destructive",children:[je.failed," failed"]})]}),e.jsxs("div",{className:"space-y-3 pt-2 border-t",children:[e.jsxs("div",{className:"rounded-lg border bg-muted/20 p-3 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium",children:[e.jsx(Pn,{className:"h-4 w-4"})," When to send"]}),e.jsxs(I2,{value:ge,onValueChange:cr=>ct(cr),className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx(ih,{value:"now",id:"send-now"}),e.jsx("span",{className:"text-sm",children:"Send now"})]}),e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx(ih,{value:"later",id:"send-later"}),e.jsxs("span",{className:"text-sm flex items-center gap-1",children:[e.jsx(h_,{className:"h-3.5 w-3.5"})," Schedule for later"]})]}),ge==="later"&&e.jsx(Se,{type:"datetime-local",value:Ue,onChange:cr=>et(cr.target.value),className:"sm:ml-2 w-full sm:w-auto",min:new Date(Date.now()+5*6e4).toISOString().slice(0,16)})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Suppressed/unsubscribed contacts are skipped automatically. Open & click tracking is included."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(H,{variant:"outline",onClick:()=>t(!1),disabled:ne,children:"Cancel"}),e.jsx(H,{onClick:$r,disabled:!fs,children:ne?e.jsxs(e.Fragment,{children:[e.jsx(is,{className:"h-4 w-4 mr-1 animate-spin"}),"Working…"]}):ge==="later"?e.jsxs(e.Fragment,{children:[e.jsx(h_,{className:"h-4 w-4 mr-1"}),"Schedule for ",St.length]}):e.jsxs(e.Fragment,{children:[e.jsx(yn,{className:"h-4 w-4 mr-1"}),"Send to ",St.length]})})]})]})]})]}),e.jsx(Rl,{open:be,onOpenChange:fe,children:e.jsxs(jl,{children:[e.jsxs(Nl,{children:[e.jsx(Sl,{children:ge==="later"?"Schedule newsletter?":"Send newsletter?"}),e.jsxs(Cl,{children:[ge==="later"?"Schedule ":"Send ",e.jsxs("span",{className:"font-medium text-foreground",children:['"',y,'"']})," to"," ",e.jsxs("span",{className:"font-medium text-foreground",children:[St.length," contact",St.length===1?"":"s"]}),ge==="later"&&Ue?` for ${new Date(Ue).toLocaleString()}`:"","? Suppressed and unsubscribed contacts are skipped automatically."]})]}),e.jsxs(kl,{children:[e.jsx(Tl,{children:"Cancel"}),e.jsx(ml,{onClick:hn,children:ge==="later"?e.jsxs(e.Fragment,{children:[e.jsx(h_,{className:"h-4 w-4 mr-1"}),"Schedule"]}):e.jsxs(e.Fragment,{children:[e.jsx(yn,{className:"h-4 w-4 mr-1"}),"Send to ",St.length]})})]})]})}),e.jsx(bs,{open:Ie,onOpenChange:De,children:e.jsxs(vs,{className:"max-w-2xl max-h-[85vh] overflow-y-auto",children:[e.jsx(Cs,{children:e.jsxs(Ns,{className:"flex items-center gap-2",children:[e.jsx(Fn,{className:"h-5 w-5"})," Choose listings to insert"]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Pick up to 6 of your active listings. They'll be added as an email-safe grid linking to your lead site."}),hs&&e.jsxs("div",{className:"text-sm text-muted-foreground p-6 text-center",children:[e.jsx(is,{className:"h-4 w-4 animate-spin inline-block mr-2"}),"Loading your listings…"]}),!hs&&Et.length===0&&e.jsx("div",{className:"rounded-lg border bg-muted/30 p-6 text-center text-sm text-muted-foreground",children:"No active listings found in your MLS feed."}),e.jsx("div",{className:"grid grid-cols-2 gap-3",children:Et.map(cr=>{var Na,vn;const on=pe.has(cr.listing_key),ds=Array.isArray(cr.photos)&&cr.photos.length>0?typeof cr.photos[0]=="string"?cr.photos[0]:((Na=cr.photos[0])==null?void 0:Na.MediaURL)||((vn=cr.photos[0])==null?void 0:vn.url)||"":"";return e.jsxs("button",{type:"button",onClick:()=>{tt(_r=>{const Hr=new Set(_r);return Hr.has(cr.listing_key)?Hr.delete(cr.listing_key):Hr.size<6?Hr.add(cr.listing_key):he.error("Max 6 listings per newsletter"),Hr})},className:`relative rounded-lg border-2 overflow-hidden text-left transition-all ${on?"border-primary ring-2 ring-primary/30":"border-border hover:border-primary/50"}`,children:[ds&&e.jsx("img",{src:ds,alt:"",className:"w-full h-32 object-cover"}),e.jsxs("div",{className:"p-2",children:[e.jsx("div",{className:"text-sm font-semibold text-primary",children:cr.list_price?`$${Number(cr.list_price).toLocaleString()}`:""}),e.jsx("div",{className:"text-xs truncate",children:cr.address}),e.jsxs("div",{className:"text-[11px] text-muted-foreground truncate",children:[cr.city,cr.state?`, ${cr.state}`:""]})]}),on&&e.jsx("div",{className:"absolute top-1 right-1 bg-primary text-primary-foreground rounded-full p-0.5",children:e.jsx(ea,{className:"h-4 w-4"})})]},cr.listing_key)})})]}),e.jsxs(wn,{children:[e.jsx(H,{variant:"outline",onClick:()=>De(!1),children:"Cancel"}),e.jsxs(H,{onClick:rn,disabled:pe.size===0,children:["Insert ",pe.size>0?pe.size:""," listing",pe.size===1?"":"s"]})]})]})})]})}function HPs(){const{user:s}=Ms(),t=ns(),[r,n]=S.useState("starters"),[a,i]=S.useState(!1),[l,o]=S.useState(null),[c,d]=S.useState(null),[h,m]=S.useState(null),{data:p,isLoading:x}=yt({queryKey:["agent-custom-newsletters",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),queryFn:async()=>{const{data:R,error:z}=await V.from("agent_custom_newsletters").select("*").order("updated_at",{ascending:!1});if(z)throw z;return R||[]}}),y=()=>t.invalidateQueries({queryKey:["agent-custom-newsletters"]}),_=(p==null?void 0:p.filter(R=>R.user_id===(s==null?void 0:s.id)&&!R.is_template))??[],b=(p==null?void 0:p.filter(R=>R.user_id===(s==null?void 0:s.id)&&R.is_template))??[],j=(p==null?void 0:p.filter(R=>R.user_id!==(s==null?void 0:s.id)&&R.is_template&&(R.share_scope==="team"||R.share_scope==="brokerage"||R.share_scope==="global")))??[],k=(p==null?void 0:p.filter(R=>R.share_scope==="global"&&R.is_template))??[],T=r==="starters"?k:r==="mine"?_:r==="templates"?b:j.filter(R=>R.share_scope!=="global"),E=async R=>{if(!s)return;const{error:z}=await V.from("agent_custom_newsletters").insert({user_id:s.id,title:`${R.title} (Copy)`,description:R.description,html_content:R.html_content,is_template:!1,share_scope:"private"});if(z){he.error(z.message);return}he.success('Duplicated to "My Newsletters"'),y(),n("mine")},A=async R=>{const{error:z}=await V.from("agent_custom_newsletters").delete().eq("id",R);if(z){he.error(z.message);return}he.success("Deleted"),m(null),y()},D=R=>R.share_scope==="global"?e.jsxs(Xe,{variant:"secondary",className:"gap-1",children:[e.jsx(Lr,{className:"h-3 w-3"}),"Starter"]}):R.share_scope==="brokerage"?e.jsxs(Xe,{variant:"secondary",className:"gap-1",children:[e.jsx(Xa,{className:"h-3 w-3"}),"Brokerage"]}):R.share_scope==="team"?e.jsxs(Xe,{variant:"secondary",className:"gap-1",children:[e.jsx(Ar,{className:"h-3 w-3"}),"Team"]}):e.jsxs(Xe,{variant:"outline",className:"gap-1 text-muted-foreground",children:[e.jsx(Td,{className:"h-3 w-3"}),"Private"]});return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs(H,{variant:r==="starters"?"default":"outline",size:"sm",onClick:()=>n("starters"),className:"gap-1.5",children:[e.jsx(Lr,{className:"h-3.5 w-3.5"}),"Starter Templates (",k.length,")"]}),e.jsxs(H,{variant:r==="mine"?"default":"outline",size:"sm",onClick:()=>n("mine"),children:["My Newsletters (",_.length,")"]}),e.jsxs(H,{variant:r==="templates"?"default":"outline",size:"sm",onClick:()=>n("templates"),children:["My Templates (",b.length,")"]}),e.jsxs(H,{variant:r==="shared"?"default":"outline",size:"sm",onClick:()=>n("shared"),children:["Shared with Me (",j.filter(R=>R.share_scope!=="global").length,")"]})]}),e.jsxs(H,{onClick:()=>{o(null),i(!0)},children:[e.jsx(Ys,{className:"h-4 w-4 mr-1.5"})," Create Newsletter"]})]}),x&&e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:[...Array(3)].map((R,z)=>e.jsx(Ks,{className:"h-48 w-full"},z))}),r==="starters"&&!x&&e.jsxs("div",{className:"rounded-lg border border-primary/20 bg-primary/5 px-4 py-3 text-sm flex items-start gap-2",children:[e.jsx(Lr,{className:"h-4 w-4 text-primary mt-0.5 shrink-0"}),e.jsxs("span",{children:["Click ",e.jsx("strong",{children:"Use"}),' on any starter to copy it into your "My Newsletters" — then edit, send, or save as your own template.']})]}),!x&&T.length===0&&e.jsx(ke,{children:e.jsxs(Oe,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(kn,{className:"h-10 w-10 mx-auto mb-3 opacity-50"}),r==="starters"&&e.jsx("p",{children:"No starter templates available yet."}),r==="mine"&&e.jsx("p",{children:`You haven't created any newsletters yet. Try a Starter Template or click "Create Newsletter"!`}),r==="templates"&&e.jsx("p",{children:`You haven't saved any templates yet. Toggle "Save as reusable template" when creating a newsletter.`}),r==="shared"&&e.jsx("p",{children:"No team or brokerage templates have been shared with you yet."})]})}),!x&&T.length>0&&e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:T.map(R=>{const z=R.user_id===(s==null?void 0:s.id);return e.jsxs(ke,{className:"overflow-hidden hover:shadow-md transition-shadow",children:[e.jsxs("div",{className:"aspect-[3/2] bg-muted relative overflow-hidden",children:[R.thumbnail_url?e.jsx("img",{src:R.thumbnail_url,alt:R.title,className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full p-3 overflow-hidden pointer-events-none",dangerouslySetInnerHTML:{__html:`
${R.html_content}
`}}),e.jsxs("div",{className:"absolute top-2 right-2 flex gap-1",children:[R.is_template&&e.jsx(Xe,{className:"bg-primary/90",children:"Template"}),D(R)]})]}),e.jsxs(Oe,{className:"p-3 space-y-2",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold line-clamp-1",children:R.title}),R.description&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-1",children:R.description}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:["Updated ",As(new Date(R.updated_at||R.created_at),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex gap-1.5 flex-wrap",children:[e.jsxs(H,{size:"sm",onClick:()=>d(R),className:"flex-1 min-w-[80px]",children:[e.jsx(yn,{className:"h-3.5 w-3.5 mr-1"})," Send"]}),z?e.jsxs(e.Fragment,{children:[e.jsx(H,{size:"sm",variant:"outline",onClick:()=>{o(R),i(!0)},children:e.jsx(ni,{className:"h-3.5 w-3.5"})}),e.jsx(H,{size:"sm",variant:"outline",onClick:()=>E(R),children:e.jsx(ui,{className:"h-3.5 w-3.5"})}),e.jsx(H,{size:"sm",variant:"outline",onClick:()=>m(R.id),children:e.jsx(Dr,{className:"h-3.5 w-3.5"})})]}):e.jsxs(H,{size:"sm",variant:"outline",onClick:()=>E(R),children:[e.jsx(ui,{className:"h-3.5 w-3.5 mr-1"})," Use"]})]})]})]},R.id)})}),e.jsx(PPs,{open:a,onOpenChange:i,initial:l,onSaved:y}),c&&e.jsx(oMe,{open:!!c,onOpenChange:R=>!R&&d(null),newsletterId:c.id,newsletterTitle:c.title,htmlCode:c.html_content}),e.jsx(Rl,{open:!!h,onOpenChange:R=>!R&&m(null),children:e.jsxs(jl,{children:[e.jsxs(Nl,{children:[e.jsx(Sl,{children:"Delete this newsletter?"}),e.jsx(Cl,{children:"This cannot be undone."})]}),e.jsxs(kl,{children:[e.jsx(Tl,{children:"Cancel"}),e.jsx(ml,{onClick:()=>h&&A(h),children:"Delete"})]})]})})]})}function GPs(){const s=Fr(),[t,r]=S.useState(""),[n,a]=S.useState("grid"),[i,l]=S.useState(null),{data:o,isLoading:c}=yt({queryKey:["newsletters"],queryFn:async()=>{const{data:A,error:D}=await V.from("newsletter_content").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(D)throw D;return A}}),{data:d}=yt({queryKey:["newsletter-likes-all"],queryFn:async()=>{const{data:A}=await V.from("newsletter_likes").select("newsletter_id");return A||[]}}),{data:h}=yt({queryKey:["newsletter-comments-all"],queryFn:async()=>{const{data:A}=await V.from("newsletter_comments").select("newsletter_id");return A||[]}}),{data:m}=yt({queryKey:["newsletter-resource-counts"],queryFn:async()=>{const[A,D,R,z]=await Promise.all([V.from("newsletter_canva_links").select("newsletter_id"),V.from("newsletter_pdfs").select("newsletter_id"),V.from("newsletter_videos").select("newsletter_id"),V.from("newsletter_drive_links").select("newsletter_id")]);return{canva:A.data||[],pdfs:D.data||[],videos:R.data||[],drives:z.data||[]}}}),p=A=>(d==null?void 0:d.filter(D=>D.newsletter_id===A).length)||0,x=A=>(h==null?void 0:h.filter(D=>D.newsletter_id===A).length)||0,y=A=>{var D;return((D=m==null?void 0:m.canva)==null?void 0:D.filter(R=>R.newsletter_id===A).length)||0},_=A=>{var D;return((D=m==null?void 0:m.pdfs)==null?void 0:D.filter(R=>R.newsletter_id===A).length)||0},b=A=>{var D;return((D=m==null?void 0:m.videos)==null?void 0:D.filter(R=>R.newsletter_id===A).length)||0},j=A=>{var D;return((D=m==null?void 0:m.drives)==null?void 0:D.filter(R=>R.newsletter_id===A).length)||0},k=A=>y(A)+_(A)+b(A)+j(A),T=o==null?void 0:o.filter(A=>{var D;return A.title.toLowerCase().includes(t.toLowerCase())||((D=A.description)==null?void 0:D.toLowerCase().includes(t.toLowerCase()))}),E=A=>{s(`/newsletters/${A}`)};return e.jsx(Ss,{title:"Newsletter Content",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"font-bold text-foreground text-5xl",children:"Newsletter Content"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Monthly templates, plus newsletters you build yourself"})]}),e.jsxs(ta,{defaultValue:"custom",className:"space-y-4",children:[e.jsxs(Qn,{children:[e.jsx(ts,{value:"custom",children:"Build & Send"}),e.jsx(ts,{value:"curated",children:"Curated Monthly"})]}),e.jsx(cs,{value:"custom",className:"mt-2",children:e.jsx(HPs,{})}),e.jsxs(cs,{value:"curated",className:"space-y-6 mt-2",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1 max-w-sm",children:[e.jsx(Mn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Se,{placeholder:"Search newsletters...",value:t,onChange:A=>r(A.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"flex gap-2",children:[t&&e.jsx(H,{variant:"outline",size:"sm",onClick:()=>r(""),children:"Clear"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(H,{variant:n==="grid"?"secondary":"outline",size:"icon",onClick:()=>a("grid"),className:"rounded-full",children:e.jsx(_g,{className:"h-4 w-4"})}),e.jsx(H,{variant:n==="list"?"secondary":"outline",size:"icon",onClick:()=>a("list"),className:"rounded-full",children:e.jsx(Vf,{className:"h-4 w-4"})})]})]})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[(T==null?void 0:T.length)||0," item",(T==null?void 0:T.length)!==1?"s":""," found"]}),c&&e.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((A,D)=>e.jsx(ke,{children:e.jsxs(Oe,{className:"p-0",children:[e.jsx(Ks,{className:"aspect-[3/2] w-full"}),e.jsxs("div",{className:"p-4 space-y-2",children:[e.jsx(Ks,{className:"h-5 w-3/4"}),e.jsx(Ks,{className:"h-4 w-full"})]})]})},D))}),!c&&(T==null?void 0:T.length)===0&&e.jsxs("div",{className:"text-center py-12",children:[e.jsx(kn,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("div",{className:"text-muted-foreground mb-4",children:t?"No newsletters match your search":"No newsletters available yet"}),t&&e.jsx(H,{variant:"outline",onClick:()=>r(""),children:"Clear Search"})]}),!c&&T&&T.length>0&&e.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-3",children:T.map(A=>{const D=k(A.id),R=y(A.id),z=_(A.id),O=b(A.id);return n==="grid"?e.jsxs(ke,{className:"group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer border-border/50",onClick:()=>E(A.id),children:[e.jsx("div",{className:"relative overflow-hidden bg-muted aspect-[3/2]",children:A.preview_image_url?e.jsx("img",{src:A.preview_image_url,alt:A.title,className:"w-full h-full object-contain group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground",children:e.jsx(kn,{className:"h-16 w-16"})})}),e.jsxs(Oe,{className:"p-4 space-y-3",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1",children:A.title}),e.jsxs("div",{className:"flex items-center gap-1.5 mt-1 text-xs text-muted-foreground",children:[e.jsx(Nn,{className:"h-3 w-3"}),As(new Date(A.publish_date),"MMM d, yyyy")]})]}),A.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2",children:A.description.replace(/<[^>]*>/g,"")}),D>0&&e.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[R>0&&e.jsxs(Xe,{variant:"secondary",className:"text-xs gap-1 font-normal",children:[e.jsx(pl,{className:"h-3 w-3"})," ",R," Template",R>1?"s":""]}),z>0&&e.jsxs(Xe,{variant:"secondary",className:"text-xs gap-1 font-normal",children:[e.jsx(hi,{className:"h-3 w-3"})," ",z," PDF",z>1?"s":""]}),O>0&&e.jsxs(Xe,{variant:"secondary",className:"text-xs gap-1 font-normal",children:[e.jsx(El,{className:"h-3 w-3"})," ",O," Video",O>1?"s":""]})]}),e.jsxs("div",{className:"flex items-center gap-4 text-xs text-muted-foreground pt-1 border-t border-border/50",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(sf,{className:"h-3 w-3"})," ",p(A.id)]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(qc,{className:"h-3 w-3"})," ",x(A.id)]})]}),A.html_code&&e.jsxs(H,{size:"sm",className:"w-full bg-gradient-to-r from-[#2a4c64] to-[#406E71] text-white hover:opacity-90",onClick:$=>{$.stopPropagation(),l(A)},children:[e.jsx(yn,{className:"h-4 w-4 mr-1.5"}),"Send Newsletter"]})]})]},A.id):e.jsx(ke,{className:"group overflow-hidden hover:shadow-md transition-all duration-200 cursor-pointer border-border/50",onClick:()=>E(A.id),children:e.jsxs("div",{className:"flex flex-row",children:[e.jsx("div",{className:"relative overflow-hidden bg-muted w-40 sm:w-48 shrink-0",children:A.preview_image_url?e.jsx("img",{src:A.preview_image_url,alt:A.title,className:"w-full h-full object-contain group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground min-h-[100px]",children:e.jsx(kn,{className:"h-10 w-10"})})}),e.jsxs(Oe,{className:"p-4 flex-1 flex flex-col justify-center gap-2",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1",children:A.title}),e.jsxs("div",{className:"flex items-center gap-1.5 mt-0.5 text-xs text-muted-foreground",children:[e.jsx(Nn,{className:"h-3 w-3"}),As(new Date(A.publish_date),"MMM d, yyyy")]})]}),A.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-1",children:A.description.replace(/<[^>]*>/g,"")}),e.jsxs("div",{className:"flex items-center gap-4 text-xs text-muted-foreground",children:[D>0&&e.jsxs("span",{children:[D," resource",D>1?"s":""]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(sf,{className:"h-3 w-3"})," ",p(A.id)]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(qc,{className:"h-3 w-3"})," ",x(A.id)]})]})]}),A.html_code&&e.jsx("div",{className:"p-3 flex items-center shrink-0",children:e.jsxs(H,{size:"sm",className:"bg-gradient-to-r from-[#2a4c64] to-[#406E71] text-white hover:opacity-90",onClick:$=>{$.stopPropagation(),l(A)},children:[e.jsx(yn,{className:"h-4 w-4 mr-1.5"}),"Send"]})})]})},A.id)})})]})]}),(i==null?void 0:i.html_code)&&e.jsx(oMe,{open:!!i,onOpenChange:A=>!A&&l(null),newsletterId:i.id,newsletterTitle:i.title,htmlCode:i.html_code})]})})}function WPs({rows:s}){if(!s||s.length===0)return null;const t=s.filter(r=>r.columns.some(n=>n.title||n.description||n.image_url));return t.length===0?null:e.jsx("div",{className:"space-y-6",children:t.map((r,n)=>{const a=r.columns.filter(i=>i.title||i.description||i.image_url);return a.length===0?null:e.jsx("div",{className:"grid gap-4",style:{gridTemplateColumns:`repeat(${a.length}, minmax(0, 1fr))`},children:a.map((i,l)=>e.jsxs(ke,{className:"overflow-hidden border-border/50",children:[i.image_url&&e.jsx("img",{src:i.image_url,alt:i.title||"",className:"w-full h-40 object-cover"}),e.jsxs(Oe,{className:"p-4 space-y-2",children:[i.title&&e.jsx("h4",{className:"font-semibold text-foreground",children:i.title}),i.description&&e.jsx("p",{className:"text-sm text-muted-foreground",children:i.description})]})]},l))},n)})})}function KPs(){const{id:s}=Po(),t=Fr(),{user:r}=Ms(),{toast:n}=li(),a=ns(),{trackEngagement:i}=y8(),[l,o]=S.useState(""),[c,d]=S.useState(!1),{data:h,isLoading:m}=yt({queryKey:["newsletter",s],queryFn:async()=>{const{data:R,error:z}=await V.from("newsletter_content").select("*").eq("id",s).single();if(z)throw z;return R},enabled:!!s});S.useEffect(()=>{h&&i("newsletter",h.id,h.title,"view")},[h==null?void 0:h.id]);const{data:p}=yt({queryKey:["newsletter-drives",s],queryFn:async()=>{const{data:R}=await V.from("newsletter_drive_links").select("*").eq("newsletter_id",s).order("sort_order");return R||[]},enabled:!!s}),{data:x}=yt({queryKey:["newsletter-pdfs",s],queryFn:async()=>{const{data:R}=await V.from("newsletter_pdfs").select("*").eq("newsletter_id",s).order("sort_order");return R||[]},enabled:!!s}),{data:y}=yt({queryKey:["newsletter-videos",s],queryFn:async()=>{const{data:R}=await V.from("newsletter_videos").select("*").eq("newsletter_id",s).order("sort_order");return R||[]},enabled:!!s}),{data:_}=yt({queryKey:["newsletter-canva-links",s],queryFn:async()=>{const{data:R}=await V.from("newsletter_canva_links").select("*").eq("newsletter_id",s).order("sort_order");return R||[]},enabled:!!s}),{data:b}=yt({queryKey:["newsletter-likes",s],queryFn:async()=>{const{data:R}=await V.from("newsletter_likes").select("*").eq("newsletter_id",s);return R||[]},enabled:!!s}),{data:j}=yt({queryKey:["newsletter-comments",s],queryFn:async()=>{const{data:R}=await V.from("newsletter_comments").select("*, profiles:user_id(name)").eq("newsletter_id",s).order("created_at",{ascending:!1});return R||[]},enabled:!!s}),k=b==null?void 0:b.some(R=>R.user_id===(r==null?void 0:r.id)),T=Pt({mutationFn:async()=>{k?await V.from("newsletter_likes").delete().eq("newsletter_id",s).eq("user_id",r==null?void 0:r.id):await V.from("newsletter_likes").insert({newsletter_id:s,user_id:r==null?void 0:r.id})},onSuccess:()=>{a.invalidateQueries({queryKey:["newsletter-likes",s]})}}),E=Pt({mutationFn:async R=>{const{error:z}=await V.from("newsletter_comments").insert({newsletter_id:s,user_id:r==null?void 0:r.id,content:R});if(z)throw z},onSuccess:()=>{a.invalidateQueries({queryKey:["newsletter-comments",s]}),o(""),n({title:"Comment added"})}}),A=Pt({mutationFn:async R=>{const{error:z}=await V.from("newsletter_comments").delete().eq("id",R);if(z)throw z},onSuccess:()=>{a.invalidateQueries({queryKey:["newsletter-comments",s]}),n({title:"Comment deleted"})}}),D=R=>{if(R.includes("player.mediadelivery.net")||R.includes("iframe.mediadelivery.net")){const z=R.match(/embed\/(\d+)\/([a-f0-9-]+)/);if(z)return e.jsx("div",{className:"relative w-full pt-[56.25%]",children:e.jsx("iframe",{src:`https://iframe.mediadelivery.net/embed/${z[1]}/${z[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(R.includes("youtube.com")||R.includes("youtu.be")){const z=R.match(/(?:youtube\.com\/(?:watch\?v=|embed\/)|youtu\.be\/)([^&\s]+)/);if(z)return e.jsx("div",{className:"relative w-full pt-[56.25%]",children:e.jsx("iframe",{src:`https://www.youtube.com/embed/${z[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 e.jsxs("a",{href:R,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-2 text-primary hover:underline",children:[e.jsx(El,{className:"h-4 w-4"})," Watch Video"]})};return m?e.jsx(Ss,{title:"",description:"",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Ks,{className:"h-8 w-32"}),e.jsx(Ks,{className:"h-64 w-full"}),e.jsx(Ks,{className:"h-32 w-full"})]})}):h?e.jsx(Ss,{title:"",description:"",children:e.jsxs("div",{className:"max-w-4xl mx-auto space-y-6",children:[e.jsxs(H,{variant:"ghost",onClick:()=>t("/newsletters"),className:"mb-4",children:[e.jsx(za,{className:"mr-2 h-4 w-4"})," Back to Newsletters"]}),h.preview_image_url&&e.jsx("img",{src:h.preview_image_url,alt:h.title,className:"w-full h-64 md:h-80 object-cover rounded-lg"}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-3xl font-bold",children:h.title}),e.jsx("p",{className:"text-muted-foreground mt-1",children:As(new Date(h.publish_date),"MMMM d, yyyy")})]}),h.description&&e.jsx("div",{className:"text-lg text-muted-foreground prose prose-sm max-w-none dark:prose-invert [&_p]:mb-4 [&_p:last-child]:mb-0 whitespace-pre-line",dangerouslySetInnerHTML:{__html:h.description}}),e.jsx(WPs,{rows:h.content_blocks||[]}),e.jsxs("div",{className:"flex items-center gap-4 flex-wrap",children:[e.jsx(w8,{resourceType:"newsletter",resourceId:h.id,resourceTitle:h.title}),e.jsxs(H,{variant:k?"default":"outline",size:"sm",onClick:()=>T.mutate(),children:[e.jsx(Bi,{className:`h-4 w-4 mr-1 ${k?"fill-current":""}`}),(b==null?void 0:b.length)||0," ",(b==null?void 0:b.length)===1?"Like":"Likes"]}),h.html_code&&e.jsxs(H,{size:"sm",className:"bg-gradient-to-r from-[#2a4c64] to-[#406E71] text-white hover:opacity-90",onClick:()=>d(!0),children:[e.jsx(yn,{className:"h-4 w-4 mr-1"}),"Send Newsletter"]})]}),h.html_code&&e.jsx(oMe,{open:c,onOpenChange:d,newsletterId:h.id,newsletterTitle:h.title,htmlCode:h.html_code}),_&&_.length>0&&e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-lg",children:"Canva Templates"})}),e.jsx(Oe,{className:"space-y-2",children:_.map(R=>e.jsxs("a",{href:R.canva_share_link,target:"_blank",rel:"noopener noreferrer",onClick:()=>i("newsletter",h.id,h.title,"click_canva"),className:"flex items-center gap-3 p-3 rounded-lg hover:bg-muted transition-colors",children:[e.jsx(pl,{className:"h-5 w-5 text-purple-500"}),e.jsx("span",{className:"font-medium",children:R.title}),e.jsx(gn,{className:"h-4 w-4 text-muted-foreground ml-auto"})]},R.id))})]}),p&&p.length>0&&e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-lg",children:"Google Drive Files"})}),e.jsx(Oe,{className:"space-y-2",children:p.map(R=>e.jsxs("a",{href:R.drive_url,target:"_blank",rel:"noopener noreferrer",onClick:()=>i("newsletter",h.id,h.title,"click_link"),className:"flex items-center gap-3 p-3 rounded-lg hover:bg-muted transition-colors",children:[e.jsx(gn,{className:"h-5 w-5 text-primary"}),e.jsx("span",{className:"font-medium",children:R.title})]},R.id))})]}),x&&x.length>0&&e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-lg",children:"PDF Downloads"})}),e.jsx(Oe,{className:"space-y-2",children:x.map(R=>e.jsxs("a",{href:R.file_url,target:"_blank",rel:"noopener noreferrer",onClick:()=>i("newsletter",h.id,h.title,"click_pdf"),className:"flex items-center gap-3 p-3 rounded-lg hover:bg-muted transition-colors",children:[e.jsx(kn,{className:"h-5 w-5 text-red-500"}),e.jsx("span",{className:"font-medium flex-1",children:R.name}),e.jsx(hi,{className:"h-4 w-4 text-muted-foreground"})]},R.id))})]}),y&&y.length>0&&e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-lg",children:"Videos"})}),e.jsx(Oe,{className:"space-y-6",children:y.map(R=>e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium",children:R.title}),D(R.video_url)]},R.id))})]}),e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsxs(zt,{className:"text-lg",children:["Comments (",(j==null?void 0:j.length)||0,")"]})}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsxs("div",{className:"flex gap-3",children:[e.jsx(vr,{placeholder:"Write a comment...",value:l,onChange:R=>o(R.target.value),className:"flex-1"}),e.jsx(H,{onClick:()=>l.trim()&&E.mutate(l),disabled:!l.trim()||E.isPending,children:e.jsx(yn,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"space-y-4",children:j==null?void 0:j.map(R=>{var z,O,$;return e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Un,{className:"h-8 w-8",children:e.jsx(qn,{children:((O=(z=R.profiles)==null?void 0:z.name)==null?void 0:O[0])||"U"})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"font-medium text-sm",children:(($=R.profiles)==null?void 0:$.name)||"User"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:As(new Date(R.created_at),"MMM d, yyyy")}),R.user_id===(r==null?void 0:r.id)&&e.jsx(H,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>A.mutate(R.id),children:e.jsx(Dr,{className:"h-3 w-3"})})]})]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:R.content})]})]},R.id)})})]})]})]})}):e.jsx(Ss,{title:"Not Found",description:"",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx("p",{className:"text-muted-foreground",children:"Newsletter not found"}),e.jsx(H,{variant:"link",onClick:()=>t("/newsletters"),children:"Back to Newsletters"})]})})}function YPs({rows:s,onChange:t}){const[r,n]=S.useState(null),a=()=>{t([...s,{columns:[{title:"",description:""},{title:"",description:""},{title:"",description:""}]}])},i=d=>{t(s.filter((h,m)=>m!==d))},l=(d,h,m,p)=>{const x=[...s];x[d]={...x[d],columns:x[d].columns.map((y,_)=>_===h?{...y,[m]:p}:y)},t(x)},o=async(d,h,m)=>{var y;const p=(y=m.target.files)==null?void 0:y[0];if(!p)return;const x=`${d}-${h}`;n(x);try{const _=`content-blocks/${Date.now()}-${p.name}`,{error:b}=await V.storage.from("newsletter-content").upload(_,p);if(!b){const{data:j}=V.storage.from("newsletter-content").getPublicUrl(_);l(d,h,"image_url",j.publicUrl)}}finally{n(null)}},c=(d,h)=>{l(d,h,"image_url","")};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ue,{className:"text-base font-medium",children:"Content Blocks (3-Column Rows)"}),e.jsxs(H,{type:"button",variant:"outline",size:"sm",onClick:a,children:[e.jsx(Ys,{className:"mr-1 h-3 w-3"})," Add Row"]})]}),s.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No content block rows yet. Add a row to create a 3-column layout."}),s.map((d,h)=>e.jsxs(ke,{className:"relative",children:[e.jsx(H,{type:"button",variant:"ghost",size:"icon",className:"absolute top-2 right-2 h-6 w-6 text-muted-foreground hover:text-destructive",onClick:()=>i(h),children:e.jsx(Rr,{className:"h-4 w-4"})}),e.jsxs(Oe,{className:"p-4 pt-3",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(Oh,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:["Row ",h+1]})]}),e.jsx("div",{className:"grid grid-cols-3 gap-3",children:d.columns.map((m,p)=>{const x=`${h}-${p}`;return e.jsxs("div",{className:"space-y-2 border border-border/50 rounded-md p-3 bg-muted/20",children:[e.jsxs("span",{className:"text-xs text-muted-foreground font-medium",children:["Column ",p+1]}),m.image_url?e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:m.image_url,alt:"",className:"w-full h-20 object-cover rounded"}),e.jsx(H,{type:"button",variant:"destructive",size:"icon",className:"absolute top-1 right-1 h-5 w-5 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>c(h,p),children:e.jsx(Rr,{className:"h-3 w-3"})})]}):e.jsxs("div",{children:[e.jsx(Se,{type:"file",accept:"image/*",className:"hidden",id:`block-img-${x}`,onChange:y=>o(h,p,y)}),e.jsx(H,{type:"button",variant:"outline",size:"sm",className:"w-full text-xs h-8",disabled:r===x,asChild:!0,children:e.jsx("label",{htmlFor:`block-img-${x}`,className:"cursor-pointer",children:r===x?"Uploading...":e.jsxs(e.Fragment,{children:[e.jsx(wl,{className:"h-3 w-3 mr-1"})," Image"]})})})]}),e.jsx(Se,{placeholder:"Title",value:m.title,onChange:y=>l(h,p,"title",y.target.value),className:"h-8 text-sm"}),e.jsx(vr,{placeholder:"Description",value:m.description,onChange:y=>l(h,p,"description",y.target.value),className:"text-sm min-h-[60px] resize-none"})]},p)})})]})]},h))]})}function ZPs(){const{toast:s}=li(),t=ns(),[r,n]=S.useState(!1),[a,i]=S.useState(null),[l,o]=S.useState({title:"",description:"",publish_date:As(new Date,"yyyy-MM-dd'T'HH:mm"),is_published:!1}),[c,d]=S.useState(null),[h,m]=S.useState(null),[p,x]=S.useState([]),[y,_]=S.useState([]),[b,j]=S.useState([]),[k,T]=S.useState([]),[E,A]=S.useState([]),[D,R]=S.useState(""),[z,O]=S.useState([]),[$,ee]=S.useState(!1),{data:Z,isLoading:J}=yt({queryKey:["admin-newsletters"],queryFn:async()=>{const{data:Me,error:ze}=await V.from("newsletter_content").select("*").order("publish_date",{ascending:!1});if(ze)throw ze;return Me}}),K=Pt({mutationFn:async Me=>{const{data:ze,error:Pe}=await V.from("newsletter_content").insert({title:Me.title,description:Me.description||null,preview_image_url:Me.preview_image_url,publish_date:Me.publish_date,is_published:Me.is_published,content_blocks:Me.content_blocks,html_code:Me.html_code}).select().single();if(Pe)throw Pe;return ze},onSuccess:async Me=>{await ce(Me.id),t.invalidateQueries({queryKey:["admin-newsletters"]}),s({title:"Newsletter created successfully"}),Me.is_published&&ocs(Me.title,Me.id),be()},onError:Me=>{s({title:"Error creating newsletter",description:Me.message,variant:"destructive"})}}),re=Pt({mutationFn:async Me=>{const{error:ze}=await V.from("newsletter_content").update({title:Me.title,description:Me.description||null,preview_image_url:Me.preview_image_url,publish_date:Me.publish_date,is_published:Me.is_published,content_blocks:Me.content_blocks,html_code:Me.html_code}).eq("id",Me.id);if(ze)throw ze;return Me.id},onSuccess:async Me=>{await ce(Me),t.invalidateQueries({queryKey:["admin-newsletters"]}),s({title:"Newsletter updated successfully"}),be()},onError:Me=>{s({title:"Error updating newsletter",description:Me.message,variant:"destructive"})}}),ie=Pt({mutationFn:async Me=>{const{error:ze}=await V.from("newsletter_content").delete().eq("id",Me);if(ze)throw ze},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-newsletters"]}),s({title:"Newsletter deleted successfully"})},onError:Me=>{s({title:"Error deleting newsletter",description:Me.message,variant:"destructive"})}}),ce=async Me=>{await V.from("newsletter_drive_links").delete().eq("newsletter_id",Me),await V.from("newsletter_pdfs").delete().eq("newsletter_id",Me),await V.from("newsletter_videos").delete().eq("newsletter_id",Me),await V.from("newsletter_canva_links").delete().eq("newsletter_id",Me);for(const ze of z){const Pe=`${Me}/${Date.now()}-${ze.file.name}`,{error:Ie}=await V.storage.from("newsletter-content").upload(Pe,ze.file);if(!Ie){const{data:De}=V.storage.from("newsletter-content").getPublicUrl(Pe);y.push({name:ze.name,file_url:De.publicUrl,file_size:ze.file.size,sort_order:y.length})}}p.length>0&&await V.from("newsletter_drive_links").insert(p.map((ze,Pe)=>({newsletter_id:Me,title:ze.title,drive_url:ze.drive_url,sort_order:Pe}))),y.length>0&&await V.from("newsletter_pdfs").insert(y.map((ze,Pe)=>({newsletter_id:Me,name:ze.name,file_url:ze.file_url,file_size:ze.file_size||null,sort_order:Pe}))),b.length>0&&await V.from("newsletter_videos").insert(b.map((ze,Pe)=>({newsletter_id:Me,title:ze.title,video_url:ze.video_url,sort_order:Pe}))),k.length>0&&await V.from("newsletter_canva_links").insert(k.map((ze,Pe)=>({newsletter_id:Me,title:ze.title,canva_share_link:ze.canva_share_link,sort_order:Pe})))},ne=async Me=>{i(Me),o({title:Me.title,description:Me.description||"",publish_date:As(new Date(Me.publish_date),"yyyy-MM-dd'T'HH:mm"),is_published:Me.is_published}),m(Me.preview_image_url),A(Me.content_blocks||[]),R(Me.html_code||"");const[ze,Pe,Ie,De]=await Promise.all([V.from("newsletter_drive_links").select("*").eq("newsletter_id",Me.id).order("sort_order"),V.from("newsletter_pdfs").select("*").eq("newsletter_id",Me.id).order("sort_order"),V.from("newsletter_videos").select("*").eq("newsletter_id",Me.id).order("sort_order"),V.from("newsletter_canva_links").select("*").eq("newsletter_id",Me.id).order("sort_order")]);x(ze.data||[]),_(Pe.data||[]),j(Ie.data||[]),T(De.data||[]),O([]),n(!0)},le=async Me=>{const[ze,Pe,Ie,De]=await Promise.all([V.from("newsletter_drive_links").select("*").eq("newsletter_id",Me.id).order("sort_order"),V.from("newsletter_pdfs").select("*").eq("newsletter_id",Me.id).order("sort_order"),V.from("newsletter_videos").select("*").eq("newsletter_id",Me.id).order("sort_order"),V.from("newsletter_canva_links").select("*").eq("newsletter_id",Me.id).order("sort_order")]);i(null),o({title:`${Me.title} (Copy)`,description:Me.description||"",publish_date:As(new Date,"yyyy-MM-dd'T'HH:mm"),is_published:!1}),m(Me.preview_image_url),A(Me.content_blocks||[]),R(Me.html_code||""),x((ze.data||[]).map(({id:pe,...tt})=>tt)),_((Pe.data||[]).map(({id:pe,...tt})=>tt)),j((Ie.data||[]).map(({id:pe,...tt})=>tt)),T((De.data||[]).map(({id:pe,...tt})=>tt)),O([]),n(!0)},be=()=>{n(!1),i(null),o({title:"",description:"",publish_date:As(new Date,"yyyy-MM-dd'T'HH:mm"),is_published:!1}),d(null),m(null),x([]),_([]),j([]),T([]),A([]),R(""),O([])},fe=async Me=>{var Pe;const ze=(Pe=Me.target.files)==null?void 0:Pe[0];ze&&(d(ze),m(URL.createObjectURL(ze)))},je=async()=>{if(!l.title){s({title:"Title is required",variant:"destructive"});return}ee(!0);let Me=h;if(c){const ze=`previews/${Date.now()}-${c.name}`,{error:Pe}=await V.storage.from("newsletter-content").upload(ze,c);if(!Pe){const{data:Ie}=V.storage.from("newsletter-content").getPublicUrl(ze);Me=Ie.publicUrl}}a?re.mutate({id:a.id,...l,preview_image_url:Me,content_blocks:E,html_code:D||null}):K.mutate({...l,preview_image_url:Me,content_blocks:E,html_code:D||null}),ee(!1)},ve=()=>x([...p,{title:"",drive_url:"",sort_order:p.length}]),We=()=>j([...b,{title:"",video_url:"",sort_order:b.length}]),Ve=()=>T([...k,{title:"",canva_share_link:"",sort_order:k.length}]),Le=Me=>{const ze=Me.target.files;if(!ze)return;const Pe=Array.from(ze).map(Ie=>({file:Ie,name:Ie.name.replace(/\.[^/.]+$/,"")}));O([...z,...Pe])};return e.jsx(Ss,{title:"Newsletter Content",description:"Manage monthly newsletter templates and resources",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(km,{title:"Newsletter Content",description:"Manage monthly newsletter templates and resources"}),e.jsxs("div",{className:"flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs(ke,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsx(zt,{className:"text-sm font-medium text-muted-foreground",children:"Total"})}),e.jsx(Oe,{children:e.jsx("div",{className:"text-2xl font-bold",children:(Z==null?void 0:Z.length)||0})})]}),e.jsxs(ke,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsx(zt,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Oe,{children:e.jsx("div",{className:"text-2xl font-bold",children:(Z==null?void 0:Z.filter(Me=>Me.is_published).length)||0})})]})]}),e.jsxs(bs,{open:r,onOpenChange:Me=>!Me&&be(),children:[e.jsx(Qi,{asChild:!0,children:e.jsxs(H,{onClick:()=>n(!0),children:[e.jsx(Ys,{className:"mr-2 h-4 w-4"})," Add Newsletter"]})}),e.jsxs(vs,{className:"max-w-4xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Cs,{children:e.jsx(Ns,{children:a?"Edit Newsletter":"Add Newsletter"})}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Title *"}),e.jsx(Se,{value:l.title,onChange:Me=>o({...l,title:Me.target.value}),placeholder:"Newsletter title"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Publish Date"}),e.jsx(Se,{type:"datetime-local",value:l.publish_date,onChange:Me=>o({...l,publish_date:Me.target.value})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Description"}),e.jsx(R1,{content:l.description,onChange:Me=>o({...l,description:Me}),placeholder:"Newsletter description",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Preview Image"}),e.jsxs("div",{className:"flex items-center gap-4",children:[h&&e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:h,alt:"Preview",className:"h-20 w-32 object-cover rounded-md"}),e.jsx(H,{type:"button",variant:"destructive",size:"icon",className:"absolute -top-2 -right-2 h-5 w-5 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>{d(null),m(null)},children:e.jsx(Rr,{className:"h-3 w-3"})})]}),e.jsxs("div",{children:[e.jsx(Se,{type:"file",accept:"image/*",onChange:fe,className:"hidden",id:"preview-upload"}),e.jsx(H,{variant:"outline",asChild:!0,children:e.jsxs("label",{htmlFor:"preview-upload",className:"cursor-pointer",children:[e.jsx(Ea,{className:"mr-2 h-4 w-4"})," Upload Image"]})})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Or,{checked:l.is_published,onCheckedChange:Me=>o({...l,is_published:Me})}),e.jsx(ue,{children:"Published"})]}),e.jsx(YPs,{rows:E,onChange:A}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ue,{className:"text-base font-medium",children:"HTML Code (for agent send)"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:'When provided, agents see a "Send Newsletter" button on this newsletter.'})]}),e.jsx("textarea",{value:D,onChange:Me=>R(Me.target.value),rows:10,placeholder:"...",className:"w-full font-mono text-xs rounded-md border border-input bg-background px-3 py-2 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Supports merge tags: ",e.jsx("code",{children:"{{first_name}}"}),", ",e.jsx("code",{children:"{{last_name}}"}),", ",e.jsx("code",{children:"{{full_name}}"}),", ",e.jsx("code",{children:"{{agent_name}}"}),", ",e.jsx("code",{children:"{{agent_email}}"}),", ",e.jsx("code",{children:"{{agent_phone}}"}),"."]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ue,{className:"text-base font-medium",children:"Canva Links"}),e.jsxs(H,{type:"button",variant:"outline",size:"sm",onClick:Ve,children:[e.jsx(Ys,{className:"mr-1 h-3 w-3"})," Add Canva Link"]})]}),k.map((Me,ze)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx(Se,{placeholder:"Link title",value:Me.title,onChange:Pe=>{const Ie=[...k];Ie[ze].title=Pe.target.value,T(Ie)},className:"w-1/3"}),e.jsx(Se,{placeholder:"Canva share link",value:Me.canva_share_link,onChange:Pe=>{const Ie=[...k];Ie[ze].canva_share_link=Pe.target.value,T(Ie)},className:"flex-1"}),e.jsx(H,{type:"button",variant:"ghost",size:"icon",onClick:()=>T(k.filter((Pe,Ie)=>Ie!==ze)),children:e.jsx(Rr,{className:"h-4 w-4"})})]},ze))]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ue,{className:"text-base font-medium",children:"Google Drive Links"}),e.jsxs(H,{type:"button",variant:"outline",size:"sm",onClick:ve,children:[e.jsx(Ys,{className:"mr-1 h-3 w-3"})," Add Link"]})]}),p.map((Me,ze)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx(Se,{placeholder:"Link title",value:Me.title,onChange:Pe=>{const Ie=[...p];Ie[ze].title=Pe.target.value,x(Ie)},className:"w-1/3"}),e.jsx(Se,{placeholder:"Google Drive URL",value:Me.drive_url,onChange:Pe=>{const Ie=[...p];Ie[ze].drive_url=Pe.target.value,x(Ie)},className:"flex-1"}),e.jsx(H,{type:"button",variant:"ghost",size:"icon",onClick:()=>x(p.filter((Pe,Ie)=>Ie!==ze)),children:e.jsx(Rr,{className:"h-4 w-4"})})]},ze))]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ue,{className:"text-base font-medium",children:"PDF Files"}),e.jsxs("div",{children:[e.jsx(Se,{type:"file",accept:".pdf",multiple:!0,onChange:Le,className:"hidden",id:"pdf-upload"}),e.jsx(H,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("label",{htmlFor:"pdf-upload",className:"cursor-pointer",children:[e.jsx(Ea,{className:"mr-1 h-3 w-3"})," Upload PDF"]})})]})]}),y.map((Me,ze)=>e.jsxs("div",{className:"flex gap-2 items-center bg-muted/50 p-2 rounded",children:[e.jsx(kn,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"flex-1 text-sm",children:Me.name}),e.jsx(H,{type:"button",variant:"ghost",size:"icon",onClick:()=>_(y.filter((Pe,Ie)=>Ie!==ze)),children:e.jsx(Rr,{className:"h-4 w-4"})})]},`existing-${ze}`)),z.map((Me,ze)=>e.jsxs("div",{className:"flex gap-2 items-center bg-muted/50 p-2 rounded",children:[e.jsx(kn,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(Se,{value:Me.name,onChange:Pe=>{const Ie=[...z];Ie[ze].name=Pe.target.value,O(Ie)},className:"flex-1 h-8",placeholder:"PDF name"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"(new)"}),e.jsx(H,{type:"button",variant:"ghost",size:"icon",onClick:()=>O(z.filter((Pe,Ie)=>Ie!==ze)),children:e.jsx(Rr,{className:"h-4 w-4"})})]},`pending-${ze}`))]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ue,{className:"text-base font-medium",children:"Video Links"}),e.jsxs(H,{type:"button",variant:"outline",size:"sm",onClick:We,children:[e.jsx(Ys,{className:"mr-1 h-3 w-3"})," Add Video"]})]}),b.map((Me,ze)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx(Se,{placeholder:"Video title",value:Me.title,onChange:Pe=>{const Ie=[...b];Ie[ze].title=Pe.target.value,j(Ie)},className:"w-1/3"}),e.jsx(Se,{placeholder:"Video URL",value:Me.video_url,onChange:Pe=>{const Ie=[...b];Ie[ze].video_url=Pe.target.value,j(Ie)},className:"flex-1"}),e.jsx(H,{type:"button",variant:"ghost",size:"icon",onClick:()=>j(b.filter((Pe,Ie)=>Ie!==ze)),children:e.jsx(Rr,{className:"h-4 w-4"})})]},ze))]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4 border-t",children:[e.jsx(H,{variant:"outline",onClick:be,children:"Cancel"}),e.jsx(H,{onClick:je,disabled:$||K.isPending||re.isPending,children:$?"Uploading...":a?"Update":"Create"})]})]})]})]})]}),e.jsx(ke,{children:e.jsx(Oe,{className:"p-0",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Vs,{children:[e.jsx(At,{children:"Name"}),e.jsx(At,{children:"Publish Date"}),e.jsx(At,{children:"Status"}),e.jsx(At,{className:"text-right",children:"Actions"})]})}),e.jsx(da,{children:J?e.jsx(Vs,{children:e.jsx(gt,{colSpan:4,className:"text-center py-8",children:"Loading..."})}):(Z==null?void 0:Z.length)===0?e.jsx(Vs,{children:e.jsx(gt,{colSpan:4,className:"text-center py-8 text-muted-foreground",children:"No newsletters yet. Create your first one!"})}):Z==null?void 0:Z.map(Me=>e.jsxs(Vs,{children:[e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[Me.preview_image_url?e.jsx("img",{src:Me.preview_image_url,alt:Me.title,className:"w-10 h-10 rounded object-cover"}):e.jsx("div",{className:"w-10 h-10 rounded bg-muted flex items-center justify-center",children:e.jsx(kn,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:Me.title}),Me.description&&e.jsx("div",{className:"text-sm text-muted-foreground line-clamp-1",children:Me.description.replace(/<[^>]*>/g,"")})]})]})}),e.jsx(gt,{children:As(new Date(Me.publish_date),"MMM d, yyyy")}),e.jsx(gt,{children:e.jsx("span",{className:`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${Me.is_published?"bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400":"bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-400"}`,children:Me.is_published?"Published":"Draft"})}),e.jsx(gt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-1",children:[e.jsx(H,{variant:"ghost",size:"icon",onClick:()=>ne(Me),title:"Edit",children:e.jsx(ni,{className:"h-4 w-4"})}),e.jsx(H,{variant:"ghost",size:"icon",onClick:()=>le(Me),title:"Duplicate",children:e.jsx(ui,{className:"h-4 w-4"})}),e.jsx(H,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",title:"Delete",onClick:()=>{confirm("Are you sure you want to delete this newsletter?")&&ie.mutate(Me.id)},children:e.jsx(Dr,{className:"h-4 w-4"})})]})})]},Me.id))})]})})})]})})}const EHe={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 XPs(){const{user:s}=Ms(),{toast:t}=li(),r=Fr(),n=ns(),[a,i]=S.useState(""),[l,o]=S.useState("popular"),[c,d]=S.useState(!1),[h,m]=S.useState(""),[p,x]=S.useState(""),[y,_]=S.useState(!1),{data:b=[],isLoading:j}=yt({queryKey:["wishlist-items",l,y],queryFn:async()=>{let D=V.from("wishlist_items").select("*");y&&s&&(D=D.eq("user_id",s.id)),l==="latest"?D=D.order("created_at",{ascending:!1}):l==="popular"?D=D.order("vote_count",{ascending:!1}):l==="trending"&&(D=D.order("vote_count",{ascending:!1}));const{data:R,error:z}=await D;if(z)throw z;const O=[...new Set((R==null?void 0:R.map(ie=>ie.user_id))||[])],{data:$}=await V.from("profiles").select("id, name").in("id",O),ee=new Map(($==null?void 0:$.map(ie=>[ie.id,ie]))||[]);let Z=[];if(s){const{data:ie}=await V.from("wishlist_votes").select("item_id").eq("user_id",s.id);Z=(ie==null?void 0:ie.map(ce=>ce.item_id))||[]}const J=(R==null?void 0:R.map(ie=>ie.id))||[],{data:K}=await V.from("wishlist_comments").select("item_id").in("item_id",J),re=new Map;return K==null||K.forEach(ie=>{re.set(ie.item_id,(re.get(ie.item_id)||0)+1)}),R==null?void 0:R.map(ie=>{const ce=ee.get(ie.user_id),ne=(ce==null?void 0:ce.name)||"Unknown";return{...ie,user_name:ne,user_initials:ne.split(" ").map(le=>le[0]).join("").toUpperCase().slice(0,2),has_voted:Z.includes(ie.id),comment_count:re.get(ie.id)||0}})}}),k=Pt({mutationFn:async({title:D,description:R})=>{const{error:z}=await V.from("wishlist_items").insert({user_id:s.id,title:D,description:R});if(z)throw z},onSuccess:()=>{n.invalidateQueries({queryKey:["wishlist-items"]}),d(!1),m(""),x(""),t({title:"Idea submitted!",description:"Your idea has been added to the wishlist."})},onError:D=>{t({title:"Error",description:D.message,variant:"destructive"})}}),T=Pt({mutationFn:async({itemId:D,hasVoted:R})=>{if(R){const{error:z}=await V.from("wishlist_votes").delete().eq("item_id",D).eq("user_id",s.id);if(z)throw z;return{itemId:D,wasAdded:!1}}else{const{error:z}=await V.from("wishlist_votes").insert({item_id:D,user_id:s.id});if(z)throw z;return{itemId:D,wasAdded:!0}}},onSuccess:async D=>{if(n.invalidateQueries({queryKey:["wishlist-items"]}),D!=null&&D.wasAdded){const R=b.find(O=>O.id===D.itemId),z=((R==null?void 0:R.vote_count)||0)+1;V.functions.invoke("wishlist-notify",{body:{itemId:D.itemId,voteCount:z}}).catch(console.error)}},onError:D=>{t({title:"Error",description:D.message,variant:"destructive"})}}),E=b.filter(D=>D.title.toLowerCase().includes(a.toLowerCase())||D.description.toLowerCase().includes(a.toLowerCase())),A=()=>{if(!h.trim()||!p.trim()){t({title:"Error",description:"Please fill in both title and description.",variant:"destructive"});return}k.mutate({title:h.trim(),description:p.trim()})};return e.jsx(Ss,{title:"Wishlist",children:e.jsxs("div",{className:"max-w-4xl mx-auto",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(q2,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-5xl font-bold",children:"Wishlist"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Share ideas and vote on what we build next"})]})]}),e.jsxs(bs,{open:c,onOpenChange:d,children:[e.jsx(Qi,{asChild:!0,children:e.jsxs(H,{className:"gap-2",children:[e.jsx(Ys,{className:"h-4 w-4"}),"Add Idea"]})}),e.jsxs(vs,{children:[e.jsx(Cs,{children:e.jsx(Ns,{children:"Submit a New Idea"})}),e.jsxs("div",{className:"space-y-4 pt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"title",children:"Title"}),e.jsx(Se,{id:"title",placeholder:"Give your idea a clear title...",value:h,onChange:D=>m(D.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"description",children:"Description"}),e.jsx(vr,{id:"description",placeholder:"Describe your idea in detail. What problem does it solve? How would it help agents?",value:p,onChange:D=>x(D.target.value),rows:4})]}),e.jsx(H,{onClick:A,className:"w-full",disabled:k.isPending,children:k.isPending?e.jsxs(e.Fragment,{children:[e.jsx(is,{className:"h-4 w-4 mr-2 animate-spin"}),"Submitting..."]}):"Submit Idea"})]})]})]})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 mb-6",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Mn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Se,{placeholder:"Search ideas...",value:a,onChange:D=>i(D.target.value),className:"pl-10"})]}),e.jsx("div",{className:"flex gap-2",children:e.jsx(ta,{value:l,onValueChange:D=>o(D),children:e.jsxs(Qn,{children:[e.jsx(ts,{value:"popular",children:"Most Popular"}),e.jsx(ts,{value:"latest",children:"Latest"}),e.jsx(ts,{value:"trending",children:"Trending"})]})})})]}),e.jsx("div",{className:"flex items-center gap-2 mb-4",children:e.jsx(H,{variant:y?"default":"outline",size:"sm",onClick:()=>_(!y),children:y?"Show All Ideas":"My Ideas"})}),j?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(is,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):E.length===0?e.jsxs("div",{className:"text-center py-12 bg-muted/30 rounded-lg",children:[e.jsx(q2,{className:"h-12 w-12 text-muted-foreground mx-auto mb-4"}),e.jsx("h3",{className:"text-lg font-medium mb-2",children:"No ideas yet"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"Be the first to submit an idea!"}),e.jsxs(H,{onClick:()=>d(!0),children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Add Idea"]})]}):e.jsx("div",{className:"space-y-3",children:E.map(D=>e.jsx("div",{className:"bg-card border rounded-lg p-4 hover:shadow-md transition-shadow cursor-pointer",onClick:()=>r(`/wishlist/${D.id}`),children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsxs("button",{onClick:R=>{R.stopPropagation(),T.mutate({itemId:D.id,hasVoted:D.has_voted||!1})},className:Ft("flex flex-col items-center justify-center min-w-[50px] py-2 px-3 rounded-lg border transition-colors",D.has_voted?"bg-primary/10 border-primary text-primary":"bg-muted/50 border-border hover:bg-muted"),children:[e.jsx(Hu,{className:Ft("h-4 w-4",D.has_voted&&"fill-current")}),e.jsx("span",{className:"text-sm font-semibold",children:D.vote_count})]}),e.jsx(Un,{className:"h-10 w-10 bg-primary/20",children:e.jsx(qn,{className:"bg-primary/20 text-primary text-sm font-medium",children:D.user_initials})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("h3",{className:"font-semibold text-foreground",children:D.title}),e.jsx(Xe,{className:Ft("text-xs",EHe[D.status].color),children:EHe[D.status].label})]}),e.jsx("p",{className:"text-muted-foreground text-sm line-clamp-2",children:D.description}),e.jsxs("div",{className:"flex items-center gap-3 mt-2 text-xs text-muted-foreground",children:[e.jsx("span",{children:D.user_name}),e.jsx("span",{children:"•"}),e.jsx("span",{children:new Date(D.created_at).toLocaleDateString()})]})]}),e.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground",children:[e.jsx(Gi,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm",children:D.comment_count})]})]})},D.id))})]})})}const AHe={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 QPs(){const{itemId:s}=Po(),t=Fr(),{user:r}=Ms(),{toast:n}=li(),a=ns(),[i,l]=S.useState(""),{data:o=!1}=yt({queryKey:["user-is-admin",r==null?void 0:r.id],queryFn:async()=>{if(!r)return!1;const{data:b,error:j}=await V.from("user_roles").select("role").eq("user_id",r.id).eq("role","admin").maybeSingle();return!j&&!!b},enabled:!!r}),{data:c,isLoading:d}=yt({queryKey:["wishlist-item",s],queryFn:async()=>{const{data:b,error:j}=await V.from("wishlist_items").select("*").eq("id",s).single();if(j)throw j;const{data:k}=await V.from("profiles").select("name").eq("id",b.user_id).single();let T=!1;if(r){const{data:E}=await V.from("wishlist_votes").select("id").eq("item_id",s).eq("user_id",r.id).maybeSingle();T=!!E}return{...b,user_name:(k==null?void 0:k.name)||"Unknown",user_initials:((k==null?void 0:k.name)||"U").split(" ").map(E=>E[0]).join("").toUpperCase().slice(0,2),has_voted:T}}}),{data:h=[],isLoading:m}=yt({queryKey:["wishlist-comments",s],queryFn:async()=>{const{data:b,error:j}=await V.from("wishlist_comments").select("*").eq("item_id",s).order("created_at",{ascending:!0});if(j)throw j;const k=[...new Set((b==null?void 0:b.map(A=>A.user_id))||[])],{data:T}=await V.from("profiles").select("id, name").in("id",k),E=new Map((T==null?void 0:T.map(A=>[A.id,A]))||[]);return b==null?void 0:b.map(A=>{const D=E.get(A.user_id),R=(D==null?void 0:D.name)||"Unknown";return{...A,user_name:R,user_initials:R.split(" ").map(z=>z[0]).join("").toUpperCase().slice(0,2)}})}}),p=Pt({mutationFn:async b=>{if(b){const{error:j}=await V.from("wishlist_votes").delete().eq("item_id",s).eq("user_id",r.id);if(j)throw j;return{wasAdded:!1}}else{const{error:j}=await V.from("wishlist_votes").insert({item_id:s,user_id:r.id});if(j)throw j;return{wasAdded:!0}}},onSuccess:async b=>{if(a.invalidateQueries({queryKey:["wishlist-item",s]}),a.invalidateQueries({queryKey:["wishlist-items"]}),b!=null&&b.wasAdded&&c){const j=(c.vote_count||0)+1;V.functions.invoke("wishlist-notify",{body:{itemId:s,voteCount:j}}).catch(console.error)}},onError:b=>{n({title:"Error",description:b.message,variant:"destructive"})}}),x=Pt({mutationFn:async b=>{const{error:j}=await V.from("wishlist_comments").insert({item_id:s,user_id:r.id,content:b});if(j)throw j},onSuccess:()=>{a.invalidateQueries({queryKey:["wishlist-comments",s]}),l(""),n({title:"Comment added!"})},onError:b=>{n({title:"Error",description:b.message,variant:"destructive"})}}),y=Pt({mutationFn:async b=>{const{error:j}=await V.from("wishlist_comments").delete().eq("id",b);if(j)throw j},onSuccess:()=>{a.invalidateQueries({queryKey:["wishlist-comments",s]}),n({title:"Comment deleted"})},onError:b=>{n({title:"Error",description:b.message,variant:"destructive"})}}),_=()=>{i.trim()&&x.mutate(i.trim())};return d?e.jsx(Ss,{title:"Wishlist",children:e.jsxs("div",{className:"max-w-3xl mx-auto",children:[e.jsx(Ks,{className:"h-8 w-32 mb-6"}),e.jsx(Ks,{className:"h-48 w-full mb-6"}),e.jsx(Ks,{className:"h-32 w-full"})]})}):c?e.jsx(Ss,{title:"Wishlist",children:e.jsxs("div",{className:"max-w-3xl mx-auto",children:[e.jsxs(H,{variant:"ghost",size:"sm",onClick:()=>t("/wishlist"),className:"mb-4",children:[e.jsx(za,{className:"h-4 w-4 mr-2"}),"Back to Wishlist"]}),e.jsx("div",{className:"bg-card border rounded-lg p-6 mb-6",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsxs("button",{onClick:()=>p.mutate(c.has_voted),className:Ft("flex flex-col items-center justify-center min-w-[60px] py-3 px-4 rounded-lg border transition-colors",c.has_voted?"bg-primary/10 border-primary text-primary":"bg-muted/50 border-border hover:bg-muted"),children:[e.jsx(Hu,{className:Ft("h-5 w-5",c.has_voted&&"fill-current")}),e.jsx("span",{className:"text-lg font-bold",children:c.vote_count}),e.jsx("span",{className:"text-xs",children:"votes"})]}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("h1",{className:"text-xl font-bold",children:c.title}),e.jsx(Xe,{className:Ft("text-xs",AHe[c.status].color),children:AHe[c.status].label})]}),e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap mb-4",children:c.description}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Un,{className:"h-6 w-6",children:e.jsx(qn,{className:"bg-primary/20 text-primary text-xs",children:c.user_initials})}),e.jsx("span",{children:c.user_name}),e.jsx("span",{children:"•"}),e.jsx("span",{children:new Date(c.created_at).toLocaleDateString()})]})]})]})}),e.jsxs("div",{className:"bg-card border rounded-lg p-6",children:[e.jsxs("h2",{className:"text-lg font-semibold mb-4",children:["Comments (",h.length,")"]}),e.jsxs("div",{className:"flex gap-3 mb-6",children:[e.jsx(Jme,{placeholder:o?"Share your thoughts... Use # to link templates":"Share your thoughts on this idea...",value:i,onChange:l,minHeight:"60px",mentionFormat:"encoded",enableTemplateMentions:o}),e.jsx(H,{onClick:_,disabled:!i.trim()||x.isPending,size:"icon",className:"h-auto",children:x.isPending?e.jsx(is,{className:"h-4 w-4 animate-spin"}):e.jsx(yn,{className:"h-4 w-4"})})]}),m?e.jsx("div",{className:"space-y-4",children:[1,2].map(b=>e.jsx(Ks,{className:"h-20 w-full"},b))}):h.length===0?e.jsx("p",{className:"text-center text-muted-foreground py-8",children:"No comments yet. Be the first to share your thoughts!"}):e.jsx("div",{className:"space-y-4",children:h.map(b=>e.jsxs("div",{className:"flex gap-3 p-3 bg-muted/30 rounded-lg",children:[e.jsx(Un,{className:"h-8 w-8",children:e.jsx(qn,{className:"bg-primary/20 text-primary text-xs",children:b.user_initials})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"font-medium text-sm",children:b.user_name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:new Date(b.created_at).toLocaleDateString()})]}),e.jsx(qEe,{content:b.content,className:"text-sm text-foreground"})]}),(r==null?void 0:r.id)===b.user_id&&e.jsx(H,{variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground hover:text-destructive",onClick:()=>y.mutate(b.id),children:e.jsx(Dr,{className:"h-4 w-4"})})]},b.id))})]})]})}):e.jsx(Ss,{title:"Wishlist",children:e.jsxs("div",{className:"max-w-3xl mx-auto text-center py-12",children:[e.jsx("p",{className:"text-muted-foreground",children:"Item not found"}),e.jsx(H,{variant:"link",onClick:()=>t("/wishlist"),children:"Go back to Wishlist"})]})})}const MHe={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"}},IHe=["open","under_review","planned","in_progress","launched","declined"];function JPs(){const{toast:s}=li(),t=Fr(),r=ns(),[n,a]=S.useState(""),[i,l]=S.useState("all"),[o,c]=S.useState(!1),[d,h]=S.useState(null),{data:m=[],isLoading:p}=yt({queryKey:["admin-wishlist-items"],queryFn:async()=>{const{data:j,error:k}=await V.from("wishlist_items").select("*").order("vote_count",{ascending:!1});if(k)throw k;const T=[...new Set((j==null?void 0:j.map(O=>O.user_id))||[])],{data:E}=await V.from("profiles").select("id, name, email").in("id",T),A=new Map((E==null?void 0:E.map(O=>[O.id,O]))||[]),D=(j==null?void 0:j.map(O=>O.id))||[],{data:R}=await V.from("wishlist_comments").select("item_id").in("item_id",D),z=new Map;return R==null||R.forEach(O=>{z.set(O.item_id,(z.get(O.item_id)||0)+1)}),j==null?void 0:j.map(O=>{const $=A.get(O.user_id);return{...O,user_name:($==null?void 0:$.name)||"Unknown",user_email:($==null?void 0:$.email)||"",comment_count:z.get(O.id)||0}})}}),x=Pt({mutationFn:async({itemId:j,status:k})=>{const{error:T}=await V.from("wishlist_items").update({status:k}).eq("id",j);if(T)throw T},onSuccess:()=>{r.invalidateQueries({queryKey:["admin-wishlist-items"]}),s({title:"Status updated!"})},onError:j=>{s({title:"Error",description:j.message,variant:"destructive"})}}),y=Pt({mutationFn:async j=>{const{error:k}=await V.from("wishlist_items").delete().eq("id",j);if(k)throw k},onSuccess:()=>{r.invalidateQueries({queryKey:["admin-wishlist-items"]}),c(!1),h(null),s({title:"Item deleted!"})},onError:j=>{s({title:"Error",description:j.message,variant:"destructive"})}}),_=m.filter(j=>{const k=j.title.toLowerCase().includes(n.toLowerCase())||j.description.toLowerCase().includes(n.toLowerCase())||j.user_name.toLowerCase().includes(n.toLowerCase()),T=i==="all"||j.status===i;return k&&T}),b={total:m.length,open:m.filter(j=>j.status==="open").length,inProgress:m.filter(j=>j.status==="in_progress").length,launched:m.filter(j=>j.status==="launched").length,highVotes:m.filter(j=>j.vote_count>=10).length};return e.jsx(Ss,{title:"Admin - Wishlist",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(H,{variant:"ghost",size:"icon",onClick:()=>t("/admin"),children:e.jsx(za,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Wishlist Management"}),e.jsx("p",{className:"text-muted-foreground",children:"Review and manage community ideas"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-4",children:[e.jsxs("div",{className:"bg-card border rounded-lg p-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Total Ideas"}),e.jsx("p",{className:"text-2xl font-bold",children:b.total})]}),e.jsxs("div",{className:"bg-card border rounded-lg p-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Open"}),e.jsx("p",{className:"text-2xl font-bold text-blue-600",children:b.open})]}),e.jsxs("div",{className:"bg-card border rounded-lg p-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"In Progress"}),e.jsx("p",{className:"text-2xl font-bold text-orange-600",children:b.inProgress})]}),e.jsxs("div",{className:"bg-card border rounded-lg p-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Launched"}),e.jsx("p",{className:"text-2xl font-bold text-green-600",children:b.launched})]}),e.jsxs("div",{className:"bg-card border rounded-lg p-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"10+ Votes"}),e.jsx("p",{className:"text-2xl font-bold text-primary",children:b.highVotes})]})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Mn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Se,{placeholder:"Search ideas, users...",value:n,onChange:j=>a(j.target.value),className:"pl-10"})]}),e.jsxs(Bs,{value:i,onValueChange:j=>l(j),children:[e.jsx(Os,{className:"w-[180px]",children:e.jsx(Us,{placeholder:"Filter by status"})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"all",children:"All Statuses"}),IHe.map(j=>e.jsx(pt,{value:j,children:MHe[j].label},j))]})]})]}),p?e.jsx("div",{className:"space-y-2",children:[1,2,3,4,5].map(j=>e.jsx(Ks,{className:"h-16 w-full"},j))}):e.jsx("div",{className:"bg-card border rounded-lg overflow-hidden",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Vs,{children:[e.jsx(At,{className:"w-[60px]",children:"Votes"}),e.jsx(At,{children:"Title"}),e.jsx(At,{className:"hidden md:table-cell",children:"Submitted By"}),e.jsx(At,{className:"hidden sm:table-cell",children:"Comments"}),e.jsx(At,{children:"Status"}),e.jsx(At,{className:"w-[100px]",children:"Actions"})]})}),e.jsx(da,{children:_.length===0?e.jsx(Vs,{children:e.jsx(gt,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"No items found"})}):_.map(j=>e.jsxs(Vs,{className:Ft(j.vote_count>=10&&"bg-primary/5"),children:[e.jsx(gt,{children:e.jsx(Xe,{variant:j.vote_count>=10?"default":"secondary",children:j.vote_count})}),e.jsx(gt,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium line-clamp-1",children:j.title}),e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-1",children:j.description})]})}),e.jsx(gt,{className:"hidden md:table-cell",children:e.jsxs("div",{children:[e.jsx("p",{className:"text-sm",children:j.user_name}),e.jsx("p",{className:"text-xs text-muted-foreground",children:j.user_email})]})}),e.jsx(gt,{className:"hidden sm:table-cell",children:j.comment_count}),e.jsx(gt,{children:e.jsxs(Bs,{value:j.status,onValueChange:k=>x.mutate({itemId:j.id,status:k}),children:[e.jsx(Os,{className:"w-[140px] h-8",children:e.jsx(Us,{})}),e.jsx(Fs,{children:IHe.map(k=>e.jsx(pt,{value:k,children:MHe[k].label},k))})]})}),e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(H,{variant:"ghost",size:"icon",onClick:()=>window.open(`/wishlist/${j.id}`,"_blank"),children:e.jsx(gn,{className:"h-4 w-4"})}),e.jsx(H,{variant:"ghost",size:"icon",className:"text-destructive",onClick:()=>{h(j.id),c(!0)},children:e.jsx(Dr,{className:"h-4 w-4"})})]})})]},j.id))})]})}),e.jsx(bs,{open:o,onOpenChange:c,children:e.jsxs(vs,{children:[e.jsx(Cs,{children:e.jsx(Ns,{children:"Delete Wishlist Item"})}),e.jsx("p",{className:"text-muted-foreground",children:"Are you sure you want to delete this idea? This will also delete all votes and comments."}),e.jsxs("div",{className:"flex justify-end gap-2 mt-4",children:[e.jsx(H,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsx(H,{variant:"destructive",onClick:()=>d&&y.mutate(d),disabled:y.isPending,children:y.isPending?e.jsxs(e.Fragment,{children:[e.jsx(is,{className:"h-4 w-4 mr-2 animate-spin"}),"Deleting..."]}):"Delete"})]})]})})]})})}function eLs(){const{user:s}=Ms(),[t,r]=S.useState([]),[n,a]=S.useState(!0),[i,l]=S.useState(!1),[o,c]=S.useState(null),[d,h]=S.useState(!1),[m,p]=S.useState(null),[x,y]=S.useState(""),[_,b]=S.useState(""),[j,k]=S.useState(""),[T,E]=S.useState(""),[A,D]=S.useState(""),[R,z]=S.useState(!1),[O,$]=S.useState(""),[ee,Z]=S.useState("once"),[J,K]=S.useState([]),[re,ie]=S.useState([]),[ce,ne]=S.useState(!1),[le,be]=S.useState(!1),[fe,je]=S.useState([]),[ve,We]=S.useState({total:0,dismissed:0});S.useEffect(()=>{Ve()},[]);const Ve=async()=>{const{data:st,error:mt}=await V.from("levelup_briefs").select("*").order("created_at",{ascending:!1});mt?(he.error("Failed to fetch briefs"),console.error(mt)):r(st||[]),a(!1)},Le=()=>{y(""),b(""),k(""),E(""),D(""),z(!1),$(new Date().toISOString().slice(0,16)),Z("once"),K([]),ie([]),c(null)},Me=()=>{Le(),l(!0)},ze=async st=>{c(st),y(st.title),b(st.description||""),k(st.video_url||""),E(st.graphic_url||""),D(st.graphic_link_url||""),z(st.is_published),$(st.publish_date.slice(0,16)),Z(st.show_frequency);const{data:mt}=await V.from("levelup_brief_links").select("*").eq("brief_id",st.id).order("sort_order");K((mt==null?void 0:mt.map(at=>({title:at.title,url:at.url})))||[]);const{data:wt}=await V.from("levelup_brief_polls").select("*").eq("brief_id",st.id).order("sort_order");if(wt){const at=[];for(const rt of wt){const{data:Et}=await V.from("levelup_brief_poll_options").select("*").eq("poll_id",rt.id).order("sort_order");at.push({question:rt.question,poll_type:rt.poll_type,options:(Et==null?void 0:Et.map(hs=>hs.option_text))||[]})}ie(at)}l(!0)},Pe=async st=>{var wt;const mt=(wt=st.target.files)==null?void 0:wt[0];if(mt){ne(!0);try{const at=await V.functions.invoke("bunny-upload",{body:{action:"create",title:mt.name.replace(/\.[^/.]+$/,"")}});if(at.error)throw at.error;const{videoId:rt,libraryId:Et}=at.data,hs=await V.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:rt}});if(hs.error)throw hs.error;const{uploadUrl:Is,apiKey:lr}=hs.data,us=new XMLHttpRequest;await new Promise((xs,kt)=>{us.upload.addEventListener("progress",fs=>{if(fs.lengthComputable){const Gs=Math.round(fs.loaded/fs.total*100);console.log("Upload progress:",Gs)}}),us.addEventListener("load",()=>{us.status>=200&&us.status<300?xs():kt(new Error(`Upload failed with status ${us.status}`))}),us.addEventListener("error",()=>kt(new Error("Upload failed"))),us.open("PUT",Is),us.setRequestHeader("AccessKey",lr),us.send(mt)});const St=`https://player.mediadelivery.net/embed/${Et}/${rt}`;k(St),he.success("Video uploaded successfully! It may take a few minutes to process.")}catch(at){console.error("Upload error:",at),he.error("Failed to upload video")}finally{ne(!1)}}},Ie=async()=>{if(!x.trim()){he.error("Title is required");return}try{let st;if(o){const{error:mt}=await V.from("levelup_briefs").update({title:x,description:_||null,video_url:j||null,graphic_url:T||null,graphic_link_url:A||null,is_published:R,publish_date:O,show_frequency:ee}).eq("id",o.id);if(mt)throw mt;st=o.id,await V.from("levelup_brief_links").delete().eq("brief_id",st);const{data:wt}=await V.from("levelup_brief_polls").select("id").eq("brief_id",st);if(wt)for(const at of wt)await V.from("levelup_brief_poll_options").delete().eq("poll_id",at.id);await V.from("levelup_brief_polls").delete().eq("brief_id",st)}else{const{data:mt,error:wt}=await V.from("levelup_briefs").insert({title:x,description:_||null,video_url:j||null,graphic_url:T||null,graphic_link_url:A||null,is_published:R,publish_date:O,show_frequency:ee,created_by:s==null?void 0:s.id}).select().single();if(wt)throw wt;st=mt.id}if(J.length>0){const mt=J.map((wt,at)=>({brief_id:st,title:wt.title,url:wt.url,sort_order:at}));await V.from("levelup_brief_links").insert(mt)}for(let mt=0;mt0){const Et=wt.options.map((hs,Is)=>({poll_id:at.id,option_text:hs,sort_order:Is}));await V.from("levelup_brief_poll_options").insert(Et)}}he.success(o?"Brief updated":"Brief created"),l(!1),Le(),Ve()}catch(st){console.error("Error saving brief:",st),he.error("Failed to save brief")}},De=async st=>{if(confirm("Are you sure you want to delete this brief?"))try{const{error:mt}=await V.from("levelup_briefs").delete().eq("id",st);if(mt)throw mt;he.success("Brief deleted"),Ve()}catch(mt){console.error("Error deleting brief:",mt),he.error("Failed to delete brief")}},pe=async st=>{p(st);const{count:mt}=await V.from("levelup_brief_views").select("*",{count:"exact",head:!0}).eq("brief_id",st.id),{count:wt}=await V.from("levelup_brief_views").select("*",{count:"exact",head:!0}).eq("brief_id",st.id).not("dismissed_at","is",null);We({total:mt||0,dismissed:wt||0});const{data:at}=await V.from("levelup_brief_polls").select("*").eq("brief_id",st.id).order("sort_order");if(at){const rt=[];for(const Et of at){const{data:hs}=await V.from("levelup_brief_poll_options").select("*").eq("poll_id",Et.id).order("sort_order"),{data:Is}=await V.from("levelup_brief_poll_responses").select("option_id, user_id").eq("poll_id",Et.id),lr=[...new Set((Is==null?void 0:Is.map(fs=>fs.user_id))||[])];let us={};if(lr.length>0){const{data:fs}=await V.from("profiles").select("id, name, email").in("id",lr);fs&&fs.forEach(Gs=>{us[Gs.id]=Gs.name||Gs.email||"Unknown"})}const St=(Is||[]).map(fs=>({optionId:fs.option_id,userName:us[fs.user_id]||"Unknown",userId:fs.user_id})),xs={};let kt=0;hs&&hs.forEach(fs=>{const Gs=(Is==null?void 0:Is.filter(_s=>_s.option_id===fs.id).length)||0;xs[fs.id]=Gs,kt+=Gs}),rt.push({...Et,options:hs||[],results:xs,respondents:St,totalResponses:Et.poll_type==="single"?new Set(Is==null?void 0:Is.map(fs=>fs.user_id)).size:kt})}je(rt)}h(!0)},tt=()=>{K([...J,{title:"",url:""}])},ge=(st,mt,wt)=>{const at=[...J];at[st][mt]=wt,K(at)},ct=st=>{K(J.filter((mt,wt)=>wt!==st))},Ue=()=>{ie([...re,{question:"",poll_type:"single",options:["",""]}])},et=(st,mt)=>{const wt=[...re];wt[st].question=mt,ie(wt)},Qe=(st,mt)=>{const wt=[...re];wt[st].poll_type=mt,ie(wt)},Ne=st=>{const mt=[...re];mt[st].options.push(""),ie(mt)},$e=(st,mt,wt)=>{const at=[...re];at[st].options[mt]=wt,ie(at)},it=(st,mt)=>{const wt=[...re];wt[st].options=wt[st].options.filter((at,rt)=>rt!==mt),ie(wt)},Je=st=>{ie(re.filter((mt,wt)=>wt!==st))};return e.jsxs(Ss,{title:"The LevelUp Brief",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsx(km,{title:"The LevelUp Brief",description:"Create engaging popup briefs for your agents",children:e.jsxs(H,{onClick:Me,children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Create Brief"]})}),e.jsx(ke,{children:e.jsx(Oe,{className:"p-0",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Vs,{children:[e.jsx(At,{children:"Title"}),e.jsx(At,{children:"Status"}),e.jsx(At,{children:"Frequency"}),e.jsx(At,{children:"Publish Date"}),e.jsx(At,{className:"text-right",children:"Actions"})]})}),e.jsx(da,{children:n?e.jsx(Vs,{children:e.jsx(gt,{colSpan:5,className:"text-center py-8",children:"Loading..."})}):t.length===0?e.jsx(Vs,{children:e.jsx(gt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No briefs created yet"})}):t.map(st=>e.jsxs(Vs,{children:[e.jsx(gt,{className:"font-medium",children:st.title}),e.jsx(gt,{children:e.jsx(Xe,{variant:st.is_published?"default":"secondary",children:st.is_published?"Published":"Draft"})}),e.jsx(gt,{className:"capitalize",children:st.show_frequency.replace("_"," ")}),e.jsx(gt,{children:As(new Date(st.publish_date),"MMM d, yyyy h:mm a")}),e.jsx(gt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(H,{variant:"ghost",size:"icon",onClick:()=>pe(st),children:e.jsx(Bo,{className:"h-4 w-4"})}),e.jsx(H,{variant:"ghost",size:"icon",onClick:()=>ze(st),children:e.jsx(ou,{className:"h-4 w-4"})}),e.jsx(H,{variant:"ghost",size:"icon",onClick:()=>De(st.id),children:e.jsx(Dr,{className:"h-4 w-4 text-destructive"})})]})})]},st.id))})]})})})]}),e.jsx(bs,{open:i,onOpenChange:l,children:e.jsxs(vs,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Cs,{children:e.jsx(Ns,{children:o?"Edit Brief":"Create New Brief"})}),e.jsxs(ta,{defaultValue:"content",className:"w-full",children:[e.jsxs(Qn,{className:"grid w-full grid-cols-4",children:[e.jsx(ts,{value:"content",children:"Content"}),e.jsx(ts,{value:"media",children:"Media"}),e.jsx(ts,{value:"links",children:"Links"}),e.jsx(ts,{value:"polls",children:"Polls"})]}),e.jsxs(cs,{value:"content",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Title *"}),e.jsx(Se,{value:x,onChange:st=>y(st.target.value),placeholder:"What's happening at LevelUp..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Description"}),e.jsx(R1,{content:_,onChange:st=>b(st),placeholder:"Brief overview for agents...",minHeight:"120px"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Publish Date"}),e.jsx(Se,{type:"datetime-local",value:O,onChange:st=>$(st.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Show Frequency"}),e.jsxs(Bs,{value:ee,onValueChange:Z,children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"once",children:"Once (until dismissed)"}),e.jsx(pt,{value:"every_login",children:"Every login"}),e.jsx(pt,{value:"daily",children:"Daily"})]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Or,{checked:R,onCheckedChange:z}),e.jsx(ue,{children:"Publish immediately"})]})]}),e.jsxs(cs,{value:"media",className:"space-y-6 mt-4",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx("h4",{className:"font-semibold text-sm text-foreground",children:"Video (optional)"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Upload Video to Bunny.net"}),e.jsx("div",{className:"flex gap-2",children:e.jsx(Se,{type:"file",accept:"video/*",onChange:Pe,disabled:ce})}),ce&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Uploading..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Or paste embed URL"}),e.jsx(Se,{value:j,onChange:st=>k(st.target.value),placeholder:"https://iframe.mediadelivery.net/embed/..."})]}),j&&e.jsx("div",{className:"aspect-video rounded-lg overflow-hidden bg-muted",children:e.jsx("iframe",{src:j,className:"w-full h-full",allow:"autoplay; fullscreen",allowFullScreen:!0})})]}),e.jsxs("div",{className:"border-t pt-4 space-y-4",children:[e.jsx("h4",{className:"font-semibold text-sm text-foreground",children:"Graphic / Image (optional)"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Upload Image"}),e.jsx("div",{className:"flex gap-2",children:e.jsx(Se,{type:"file",accept:"image/*",onChange:async st=>{var wt;const mt=(wt=st.target.files)==null?void 0:wt[0];if(mt){be(!0);try{const at=mt.name.split(".").pop(),rt=`brief-graphics/${Date.now()}.${at}`,{error:Et}=await V.storage.from("banner-images").upload(rt,mt,{upsert:!0});if(Et)throw Et;const{data:hs}=V.storage.from("banner-images").getPublicUrl(rt);E(hs.publicUrl),he.success("Image uploaded!")}catch(at){console.error(at),he.error("Failed to upload image")}finally{be(!1)}}},disabled:le})}),le&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Uploading..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Or paste Image URL"}),e.jsx(Se,{value:T,onChange:st=>E(st.target.value),placeholder:"https://example.com/image.png"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Click-through Link (optional)"}),e.jsx(Se,{value:A,onChange:st=>D(st.target.value),placeholder:"https://example.com/landing-page"})]}),T&&e.jsx("div",{className:"rounded-lg overflow-hidden bg-muted border",children:e.jsx("img",{src:T,alt:"Brief graphic preview",className:"w-full object-contain max-h-64"})})]})]}),e.jsxs(cs,{value:"links",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(ue,{children:"Quick Links"}),e.jsxs(H,{variant:"outline",size:"sm",onClick:tt,children:[e.jsx(Ys,{className:"h-4 w-4 mr-1"}),"Add Link"]})]}),J.map((st,mt)=>e.jsxs("div",{className:"flex gap-2 items-start",children:[e.jsx(Se,{value:st.title,onChange:wt=>ge(mt,"title",wt.target.value),placeholder:"Link title",className:"flex-1"}),e.jsx(Se,{value:st.url,onChange:wt=>ge(mt,"url",wt.target.value),placeholder:"https://...",className:"flex-[2]"}),e.jsx(H,{variant:"ghost",size:"icon",onClick:()=>ct(mt),children:e.jsx(Dr,{className:"h-4 w-4 text-destructive"})})]},mt)),J.length===0&&e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No links added yet"})]}),e.jsxs(cs,{value:"polls",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(ue,{children:"Polls"}),e.jsxs(H,{variant:"outline",size:"sm",onClick:Ue,children:[e.jsx(Ys,{className:"h-4 w-4 mr-1"}),"Add Poll"]})]}),re.map((st,mt)=>e.jsx(ke,{className:"p-4",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(Se,{value:st.question,onChange:wt=>et(mt,wt.target.value),placeholder:"Poll question...",className:"flex-1 mr-2"}),e.jsxs(Bs,{value:st.poll_type,onValueChange:wt=>Qe(mt,wt),children:[e.jsx(Os,{className:"w-32",children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"single",children:"Single"}),e.jsx(pt,{value:"multi",children:"Multi-select"})]})]}),e.jsx(H,{variant:"ghost",size:"icon",onClick:()=>Je(mt),children:e.jsx(Dr,{className:"h-4 w-4 text-destructive"})})]}),e.jsxs("div",{className:"space-y-2 pl-4",children:[st.options.map((wt,at)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Se,{value:wt,onChange:rt=>$e(mt,at,rt.target.value),placeholder:`Option ${at+1}`}),st.options.length>2&&e.jsx(H,{variant:"ghost",size:"icon",onClick:()=>it(mt,at),children:e.jsx(Dr,{className:"h-4 w-4 text-muted-foreground"})})]},at)),e.jsxs(H,{variant:"ghost",size:"sm",onClick:()=>Ne(mt),children:[e.jsx(Ys,{className:"h-4 w-4 mr-1"}),"Add Option"]})]})]})},mt)),re.length===0&&e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No polls added yet"})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 mt-4",children:[e.jsx(H,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx(H,{onClick:Ie,children:o?"Update Brief":"Create Brief"})]})]})}),e.jsx(bs,{open:d,onOpenChange:h,children:e.jsxs(vs,{className:"max-w-2xl",children:[e.jsx(Cs,{children:e.jsxs(Ns,{children:["Results: ",m==null?void 0:m.title]})}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs(ke,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsx(zt,{className:"text-sm font-medium text-muted-foreground",children:"Total Views"})}),e.jsx(Oe,{children:e.jsx("p",{className:"text-2xl font-bold",children:ve.total})})]}),e.jsxs(ke,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsx(zt,{className:"text-sm font-medium text-muted-foreground",children:"Dismissed"})}),e.jsx(Oe,{children:e.jsx("p",{className:"text-2xl font-bold",children:ve.dismissed})})]})]}),fe.length>0?e.jsxs("div",{className:"space-y-4",children:[e.jsx("h3",{className:"font-semibold",children:"Poll Results"}),fe.map(st=>e.jsxs(ke,{className:"p-4",children:[e.jsx("h4",{className:"font-medium mb-3",children:st.question}),e.jsx("div",{className:"space-y-2",children:st.options.map(mt=>{const wt=st.results[mt.id]||0,at=st.totalResponses>0?Math.round(wt/st.totalResponses*100):0;return e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{children:mt.option_text}),e.jsxs("span",{className:"text-muted-foreground",children:[wt," (",at,"%)"]})]}),e.jsx("div",{className:"h-2 bg-muted rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-primary transition-all",style:{width:`${at}%`}})}),wt>0&&e.jsx("div",{className:"flex flex-wrap gap-1 pt-1",children:(st.respondents||[]).filter(rt=>rt.optionId===mt.id).map((rt,Et)=>e.jsx(Xe,{variant:"secondary",className:"text-xs font-normal",children:rt.userName},Et))})]},mt.id)})})]},st.id))]}):e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No polls in this brief"})]})]})})]})}const tLs=()=>{const{user:s}=Ms(),{toast:t}=li(),r=ns(),[n,a]=S.useState(!1),[i,l]=S.useState(null),[o,c]=S.useState({name:"",description:"",signup_link_url:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),[d,h]=S.useState(null),[m,p]=S.useState(""),{data:x=[],isLoading:y}=yt({queryKey:["additional-services-admin"],queryFn:async()=>{const{data:A,error:D}=await V.from("additional_services").select("*").order("publish_date",{ascending:!1});if(D)throw D;return A}}),_=Pt({mutationFn:async A=>{let D=A.existingImageUrl;if(A.image){const z=A.image.name.split(".").pop(),O=`${Date.now()}-${Math.random().toString(36).substring(7)}.${z}`,{error:$}=await V.storage.from("service-images").upload(O,A.image);if($)throw $;const{data:ee}=V.storage.from("service-images").getPublicUrl(O);D=ee.publicUrl}const R={name:A.item.name,description:A.item.description||null,preview_image_url:D,signup_link_url:A.item.signup_link_url,publish_date:A.item.publish_date?new Date(A.item.publish_date).toISOString():new Date().toISOString(),is_published:A.item.is_published,created_by:s==null?void 0:s.id};if(A.itemId){const{error:z}=await V.from("additional_services").update(R).eq("id",A.itemId);if(z)throw z}else{const{error:z}=await V.from("additional_services").insert(R);if(z)throw z}},onSuccess:()=>{r.invalidateQueries({queryKey:["additional-services-admin"]}),r.invalidateQueries({queryKey:["additional-services"]}),t({title:i?"Service updated":"Service created"}),a(!1),j()},onError:A=>{t({title:"Error saving service",description:A.message,variant:"destructive"})}}),b=Pt({mutationFn:async A=>{const{error:D}=await V.from("additional_services").delete().eq("id",A);if(D)throw D},onSuccess:()=>{r.invalidateQueries({queryKey:["additional-services-admin"]}),r.invalidateQueries({queryKey:["additional-services"]}),t({title:"Service deleted"})},onError:A=>{t({title:"Error deleting service",description:A.message,variant:"destructive"})}}),j=()=>{c({name:"",description:"",signup_link_url:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),h(null),p(""),l(null)},k=A=>{l(A),c({name:A.name,description:A.description||"",signup_link_url:A.signup_link_url,publish_date:A.publish_date?new Date(A.publish_date).toISOString().split("T")[0]:new Date().toISOString().split("T")[0],is_published:A.is_published}),p(A.preview_image_url||""),a(!0)},T=A=>{var R;const D=(R=A.target.files)==null?void 0:R[0];D&&(h(D),p(URL.createObjectURL(D)))},E=A=>{if(A.preventDefault(),!o.name.trim()){t({title:"Name is required",variant:"destructive"});return}if(!o.signup_link_url.trim()){t({title:"Signup link URL is required",variant:"destructive"});return}_.mutate({item:o,image:d,existingImageUrl:(i==null?void 0:i.preview_image_url)||null,itemId:i==null?void 0:i.id})};return e.jsx(Ss,{title:"Manage Additional Services",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs(ke,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsx(zt,{className:"text-sm font-medium text-muted-foreground",children:"Total Services"})}),e.jsx(Oe,{children:e.jsx("div",{className:"text-2xl font-bold",children:x.length})})]}),e.jsxs(ke,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsx(zt,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Oe,{children:e.jsx("div",{className:"text-2xl font-bold",children:x.filter(A=>A.is_published).length})})]})]}),e.jsxs(bs,{open:n,onOpenChange:A=>{a(A),A||j()},children:[e.jsx(Qi,{asChild:!0,children:e.jsxs(H,{className:"gap-2",children:[e.jsx(Ys,{className:"h-4 w-4"}),"Add Service"]})}),e.jsxs(vs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Cs,{children:e.jsx(Ns,{children:i?"Edit Service":"Add New Service"})}),e.jsxs("form",{onSubmit:E,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"name",children:"Name *"}),e.jsx(Se,{id:"name",value:o.name,onChange:A=>c({...o,name:A.target.value}),placeholder:"Enter service name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Description"}),e.jsx(R1,{content:o.description,onChange:A=>c({...o,description:A}),placeholder:"Enter description",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"signup_link_url",children:"Signup Link URL *"}),e.jsx(Se,{id:"signup_link_url",type:"url",value:o.signup_link_url,onChange:A=>c({...o,signup_link_url:A.target.value}),placeholder:"https://example.com/signup"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(Se,{id:"publish_date",type:"date",value:o.publish_date,onChange:A=>c({...o,publish_date:A.target.value})})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Or,{id:"is_published",checked:o.is_published,onCheckedChange:A=>c({...o,is_published:A})}),e.jsx(ue,{htmlFor:"is_published",children:"Published"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Preview Image"}),m?e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:m,alt:"Preview",className:"w-full max-h-48 object-contain rounded-lg border"}),e.jsx(H,{type:"button",variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-6 w-6",onClick:()=>{h(null),p("")},children:e.jsx(Rr,{className:"h-3 w-3"})})]}):e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-4 text-center",children:[e.jsx(wl,{className:"h-8 w-8 mx-auto text-muted-foreground mb-2"}),e.jsx(Se,{type:"file",accept:"image/*",onChange:T,className:"cursor-pointer"})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(H,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(H,{type:"submit",disabled:_.isPending,children:_.isPending?"Saving...":i?"Update":"Create"})]})]})]})]})]}),e.jsx(ke,{children:e.jsx(Oe,{className:"p-0",children:y?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):x.length===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:'No services yet. Click "Add Service" to create your first one.'}):e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Vs,{children:[e.jsx(At,{className:"w-16",children:"Preview"}),e.jsx(At,{children:"Name"}),e.jsx(At,{children:"Signup Link"}),e.jsx(At,{children:"Publish Date"}),e.jsx(At,{children:"Status"}),e.jsx(At,{className:"text-right",children:"Actions"})]})}),e.jsx(da,{children:x.map(A=>e.jsxs(Vs,{children:[e.jsx(gt,{children:A.preview_image_url?e.jsx("img",{src:A.preview_image_url,alt:"",className:"w-12 h-12 object-cover rounded"}):e.jsx("div",{className:"w-12 h-12 bg-muted rounded flex items-center justify-center",children:e.jsx(wl,{className:"h-5 w-5 text-muted-foreground"})})}),e.jsx(gt,{className:"font-medium",children:A.name}),e.jsx(gt,{children:e.jsxs("a",{href:A.signup_link_url,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline flex items-center gap-1",children:[e.jsx(gn,{className:"h-3 w-3"}),"Link"]})}),e.jsx(gt,{children:new Date(A.publish_date).toLocaleDateString()}),e.jsx(gt,{children:e.jsx(Xe,{variant:A.is_published?"default":"secondary",children:A.is_published?"Published":"Draft"})}),e.jsx(gt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(H,{variant:"ghost",size:"icon",onClick:()=>k(A),children:e.jsx(ni,{className:"h-4 w-4"})}),e.jsx(H,{variant:"ghost",size:"icon",onClick:()=>{confirm("Are you sure you want to delete this service?")&&b.mutate(A.id)},children:e.jsx(Dr,{className:"h-4 w-4 text-destructive"})})]})})]},A.id))})]})})})]})})};function sLs(){const{toast:s}=li(),[t,r]=S.useState([]),[n,a]=S.useState(!0),[i,l]=S.useState(!1),[o,c]=S.useState(!1),[d,h]=S.useState({name:"",promotionCode:"",discountType:"percent",percentOff:"",amountOff:"",duration:"once",durationInMonths:""});S.useEffect(()=>{m()},[]);const m=async()=>{try{const{data:b,error:j}=await V.functions.invoke("stripe-manage-coupons",{body:{action:"list"}});if(j)throw j;r(b.coupons||[])}catch(b){console.error("Error fetching coupons:",b),s({title:"Error",description:"Failed to load coupons",variant:"destructive"})}finally{a(!1)}},p=async()=>{if(!d.name){s({title:"Error",description:"Please enter a coupon name",variant:"destructive"});return}if(d.discountType==="percent"&&!d.percentOff){s({title:"Error",description:"Please enter a percent off value",variant:"destructive"});return}if(d.discountType==="amount"&&!d.amountOff){s({title:"Error",description:"Please enter an amount off value",variant:"destructive"});return}if(d.duration==="repeating"&&!d.durationInMonths){s({title:"Error",description:"Please enter duration in months",variant:"destructive"});return}l(!0);try{const b={action:"create",name:d.name,duration:d.duration,promotion_code:d.promotionCode.trim()||void 0};d.discountType==="percent"?b.percent_off=parseFloat(d.percentOff):(b.amount_off=Math.round(parseFloat(d.amountOff)*100),b.currency="usd"),d.duration==="repeating"&&(b.duration_in_months=parseInt(d.durationInMonths));const{data:j,error:k}=await V.functions.invoke("stripe-manage-coupons",{body:b});if(k)throw k;s({title:"Success",description:"Coupon created successfully"}),c(!1),h({name:"",promotionCode:"",discountType:"percent",percentOff:"",amountOff:"",duration:"once",durationInMonths:""}),m()}catch(b){console.error("Error creating coupon:",b),s({title:"Error",description:b.message||"Failed to create coupon",variant:"destructive"})}finally{l(!1)}},x=async b=>{if(confirm("Are you sure you want to delete this coupon?"))try{const{error:j}=await V.functions.invoke("stripe-manage-coupons",{body:{action:"delete",couponId:b}});if(j)throw j;s({title:"Success",description:"Coupon deleted successfully"}),m()}catch(j){console.error("Error deleting coupon:",j),s({title:"Error",description:j.message||"Failed to delete coupon",variant:"destructive"})}},y=b=>b.percent_off?`${b.percent_off}% off`:b.amount_off?`$${(b.amount_off/100).toFixed(2)} off`:"N/A",_=b=>{switch(b.duration){case"once":return"Once";case"forever":return"Forever";case"repeating":return`${b.duration_in_months} months`;default:return b.duration}};return e.jsx(Ss,{title:"Subscription Discounts",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(km,{title:"Subscription Discounts",description:"Create and manage discount coupons for subscriptions",children:e.jsxs(bs,{open:o,onOpenChange:c,children:[e.jsx(Qi,{asChild:!0,children:e.jsxs(H,{children:[e.jsx(Ys,{className:"mr-2 h-4 w-4"}),"Create Coupon"]})}),e.jsxs(vs,{children:[e.jsxs(Cs,{children:[e.jsx(Ns,{children:"Create New Coupon"}),e.jsx(nn,{children:"Create a discount coupon that can be applied to subscriptions"})]}),e.jsxs("div",{className:"space-y-4 pt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Promotion Code (what users will type)"}),e.jsx(Se,{placeholder:"e.g., BROKERAGE50",value:d.promotionCode,onChange:b=>h({...d,promotionCode:b.target.value.toUpperCase().replace(/[^A-Z0-9]/g,"")}),className:"font-mono uppercase"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Letters and numbers only. This is the code users enter at checkout."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Coupon Name (internal label)"}),e.jsx(Se,{placeholder:"e.g., 50% Off Brokerage Launch",value:d.name,onChange:b=>h({...d,name:b.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Discount Type"}),e.jsxs(Bs,{value:d.discountType,onValueChange:b=>{const j=b==="amount"&&d.duration==="forever"?"once":d.duration;h({...d,discountType:b,duration:j})},children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"percent",children:e.jsxs("span",{className:"flex items-center",children:[e.jsx(ME,{className:"mr-2 h-4 w-4"}),"Percentage Off"]})}),e.jsx(pt,{value:"amount",children:e.jsxs("span",{className:"flex items-center",children:[e.jsx(oc,{className:"mr-2 h-4 w-4"}),"Fixed Amount Off"]})})]})]})]}),d.discountType==="percent"?e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Percent Off"}),e.jsxs("div",{className:"relative",children:[e.jsx(Se,{type:"number",min:"1",max:"100",placeholder:"20",value:d.percentOff,onChange:b=>h({...d,percentOff:b.target.value})}),e.jsx("span",{className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground",children:"%"})]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Amount Off (USD)"}),e.jsxs("div",{className:"relative",children:[e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground",children:"$"}),e.jsx(Se,{type:"number",min:"1",placeholder:"10.00",className:"pl-7",value:d.amountOff,onChange:b=>h({...d,amountOff:b.target.value})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Duration"}),e.jsxs(Bs,{value:d.duration,onValueChange:b=>h({...d,duration:b}),children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"once",children:"Once (first payment only)"}),e.jsx(pt,{value:"repeating",children:"Multiple months"}),e.jsxs(pt,{value:"forever",disabled:d.discountType==="amount",children:["Forever ",d.discountType==="amount"&&"(% discounts only)"]})]})]}),d.discountType==="amount"&&e.jsx("p",{className:"text-xs text-muted-foreground",children:'Note: "Forever" duration is only available for percentage-based discounts.'})]}),d.duration==="repeating"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Number of Months"}),e.jsx(Se,{type:"number",min:"1",placeholder:"3",value:d.durationInMonths,onChange:b=>h({...d,durationInMonths:b.target.value})})]}),e.jsx(H,{onClick:p,disabled:i,className:"w-full",children:i?e.jsxs(e.Fragment,{children:[e.jsx(is,{className:"mr-2 h-4 w-4 animate-spin"}),"Creating..."]}):"Create Coupon"})]})]})]})}),e.jsxs(ke,{children:[e.jsxs(Ot,{children:[e.jsx(zt,{children:"Active Coupons"}),e.jsx(Br,{children:"Share coupon codes with users to give them discounts on subscriptions"})]}),e.jsx(Oe,{children:n?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(is,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):t.length===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No coupons created yet. Create your first coupon to get started."}):e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Vs,{children:[e.jsx(At,{children:"Promo Code"}),e.jsx(At,{children:"Name"}),e.jsx(At,{children:"Discount"}),e.jsx(At,{children:"Duration"}),e.jsx(At,{children:"Redemptions"}),e.jsx(At,{children:"Status"}),e.jsx(At,{className:"text-right",children:"Actions"})]})}),e.jsx(da,{children:t.map(b=>{var j;return e.jsxs(Vs,{children:[e.jsx(gt,{className:"font-mono font-medium",children:((j=b.promotion_codes)==null?void 0:j.length)>0?b.promotion_codes.join(", "):e.jsx("span",{className:"text-muted-foreground text-xs",children:"No promo code"})}),e.jsx(gt,{children:b.name||"-"}),e.jsx(gt,{children:y(b)}),e.jsx(gt,{children:_(b)}),e.jsx(gt,{children:b.times_redeemed}),e.jsx(gt,{children:e.jsx(Xe,{variant:b.valid?"default":"secondary",children:b.valid?"Active":"Inactive"})}),e.jsx(gt,{className:"text-right",children:e.jsx(H,{variant:"ghost",size:"sm",onClick:()=>x(b.id),children:e.jsx(Dr,{className:"h-4 w-4 text-destructive"})})})]},b.id)})})]})})]}),e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsx(zt,{children:"How to Use Coupons"})}),e.jsxs(Oe,{className:"text-sm text-muted-foreground space-y-2",children:[e.jsx("p",{children:"1. Create a coupon above with your desired discount."}),e.jsx("p",{children:'2. Share the coupon code (shown in the "Code" column) with users.'}),e.jsx("p",{children:"3. Users can enter the code during checkout to receive the discount."}),e.jsx("p",{children:"4. Alternatively, you can create a promotion code in Stripe dashboard for public-facing promotions."})]})]})]})})}const dwe={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 rLs(){const[s,t]=S.useState(""),[r,n]=S.useState("all"),[a,i]=S.useState("all"),[l,o]=S.useState(null),{data:c,isLoading:d,refetch:h}=yt({queryKey:["admin-subscriptions"],queryFn:async()=>{const{data:j,error:k}=await V.from("profiles").select(` *, brokerages:brokerage_id (id, name) `).order("created_at",{ascending:!1});if(k)throw k;return j}}),{data:m}=yt({queryKey:["admin-brokerages-subscriptions"],queryFn:async()=>{const{data:j,error:k}=await V.from("brokerages").select("*").order("name");if(k)throw k;return await Promise.all((j||[]).map(async E=>{const{data:A}=await V.from("profiles").select("id, name, email, subscription_status, subscription_product_id").eq("brokerage_id",E.id),{data:D}=await V.from("user_roles").select("user_id").eq("role","brokerage_manager"),R=(D==null?void 0:D.map($=>$.user_id))||[],z=(A==null?void 0:A.filter($=>R.includes($.id)))||[],O=(A==null?void 0:A.length)||0;return{...E,managers:z,agentCount:O}}))}}),{data:p}=yt({queryKey:["admin-website-subscriptions"],queryFn:async()=>{const{data:j,error:k}=await V.from("local_move_subscriptions").select("*").order("created_at",{ascending:!1});if(k)throw k;return j}}),x=j=>{if(j.is_grandfathered)return{status:"Grandfathered",badge:"Legacy",variant:"secondary"};if(j.brokerage_id&&!j.subscription_product_id)return{status:"Brokerage",badge:"Team Member",variant:"outline"};if(j.is_trial&&j.trial_expires_at)return new Date(j.trial_expires_at)>new Date?{status:"Trial",badge:"Active Trial",variant:"default"}:{status:"Trial Expired",badge:"Expired",variant:"destructive"};if(j.subscription_status==="active"||j.subscription_status==="trialing"){const k=dwe[j.subscription_product_id];return{status:(k==null?void 0:k.name)||"Active",badge:j.subscription_status==="trialing"?"Trial":"Active",variant:"default"}}return j.subscription_status==="canceled"||j.subscription_status==="past_due"?{status:"Canceled",badge:"Inactive",variant:"destructive"}:{status:"None",badge:"No Subscription",variant:"outline"}},y=c==null?void 0:c.filter(j=>{var T,E;if(!(((T=j.name)==null?void 0:T.toLowerCase().includes(s.toLowerCase()))||((E=j.email)==null?void 0:E.toLowerCase().includes(s.toLowerCase()))))return!1;if(a!=="all"){const A=j.subscription_source||"platform";if(a==="platform"&&A==="local_move_website"||a==="local_move_website"&&A!=="local_move_website")return!1}switch(x(j),r){case"active":return j.subscription_status==="active";case"trialing":return j.subscription_status==="trialing"||j.is_trial&&new Date(j.trial_expires_at)>new Date;case"grandfathered":return j.is_grandfathered;case"brokerage":return j.brokerage_id&&!j.subscription_product_id&&!j.is_grandfathered;case"expired":return j.subscription_status==="canceled"||j.subscription_status==="past_due"||j.is_trial&&new Date(j.trial_expires_at)<=new Date;case"none":return!j.subscription_status||j.subscription_status==="none";default:return!0}}),_={totalUsers:(c==null?void 0:c.length)||0,activeSubscriptions:(c==null?void 0:c.filter(j=>j.subscription_status==="active").length)||0,trials:(c==null?void 0:c.filter(j=>j.subscription_status==="trialing"||j.is_trial&&new Date(j.trial_expires_at)>new Date).length)||0,grandfathered:(c==null?void 0:c.filter(j=>j.is_grandfathered).length)||0,brokerageMembers:(c==null?void 0:c.filter(j=>j.brokerage_id&&!j.subscription_product_id&&!j.is_grandfathered).length)||0,individualSubscribers:(c==null?void 0:c.filter(j=>j.subscription_status==="active"&&j.subscription_product_id==="prod_Tc07cYplXUGNkm").length)||0,brokerageSubscribers:(c==null?void 0:c.filter(j=>j.subscription_status==="active"&&(j.subscription_product_id==="prod_Tc08MupgoVySDG"||j.subscription_product_id==="prod_Tc09N1tJ4RrAFn")).length)||0},b=j=>{window.open(`https://dashboard.stripe.com/customers/${j}`,"_blank")};return e.jsx(Ss,{title:"Subscription Management",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(km,{title:"Subscription Management",description:"Track and manage all subscriptions",children:e.jsxs(H,{onClick:()=>h(),variant:"outline",size:"sm",children:[e.jsx(po,{className:"h-4 w-4 mr-2"}),"Refresh"]})}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-7 gap-4",children:[e.jsx(ke,{children:e.jsxs(Oe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ar,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Total Users"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:_.totalUsers})]})}),e.jsx(ke,{className:"border-green-500/50",children:e.jsxs(Oe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(u0,{className:"h-4 w-4 text-green-500"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Active Paid"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1 text-green-600",children:_.activeSubscriptions})]})}),e.jsx(ke,{className:"border-blue-500/50",children:e.jsxs(Oe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Pn,{className:"h-4 w-4 text-blue-500"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Trials"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1 text-blue-600",children:_.trials})]})}),e.jsx(ke,{className:"border-purple-500/50",children:e.jsxs(Oe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(zf,{className:"h-4 w-4 text-purple-500"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Grandfathered"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1 text-purple-600",children:_.grandfathered})]})}),e.jsx(ke,{className:"border-orange-500/50",children:e.jsxs(Oe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Xa,{className:"h-4 w-4 text-orange-500"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Brokerage Members"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1 text-orange-600",children:_.brokerageMembers})]})}),e.jsx(ke,{children:e.jsxs(Oe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(j1,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Individual"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:_.individualSubscribers})]})}),e.jsx(ke,{children:e.jsxs(Oe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Xa,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Brokerage Subs"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:_.brokerageSubscribers})]})})]}),e.jsxs(ta,{defaultValue:"users",className:"space-y-4",children:[e.jsxs(Qn,{children:[e.jsx(ts,{value:"users",children:"All Users"}),e.jsx(ts,{value:"brokerages",children:"Brokerages"}),e.jsxs(ts,{value:"websites",className:"gap-2",children:[e.jsx(ld,{className:"h-4 w-4"}),"Website Subscriptions",p&&p.length>0&&e.jsx(Xe,{variant:"secondary",className:"ml-1",children:p.length})]})]}),e.jsxs(cs,{value:"users",className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Mn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Se,{placeholder:"Search by name or email...",value:s,onChange:j=>t(j.target.value),className:"pl-9"})]}),e.jsxs(Bs,{value:a,onValueChange:j=>i(j),children:[e.jsx(Os,{className:"w-[200px]",children:e.jsx(Us,{placeholder:"Source"})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"all",children:"All Sources"}),e.jsx(pt,{value:"platform",children:"Platform"}),e.jsx(pt,{value:"local_move_website",children:"Local Move Website"})]})]}),e.jsxs(Bs,{value:r,onValueChange:j=>n(j),children:[e.jsx(Os,{className:"w-[200px]",children:e.jsx(Us,{placeholder:"Filter by status"})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"all",children:"All Statuses"}),e.jsx(pt,{value:"active",children:"Active Subscriptions"}),e.jsx(pt,{value:"trialing",children:"Trials"}),e.jsx(pt,{value:"grandfathered",children:"Grandfathered"}),e.jsx(pt,{value:"brokerage",children:"Brokerage Members"}),e.jsx(pt,{value:"expired",children:"Expired/Canceled"}),e.jsx(pt,{value:"none",children:"No Subscription"})]})]})]}),e.jsx(ke,{children:e.jsx(Oe,{className:"p-0",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Vs,{children:[e.jsx(At,{children:"User"}),e.jsx(At,{children:"Status"}),e.jsx(At,{children:"Plan"}),e.jsx(At,{children:"Brokerage"}),e.jsx(At,{children:"End Date"}),e.jsx(At,{className:"text-right",children:"Actions"})]})}),e.jsx(da,{children:d?e.jsx(Vs,{children:e.jsx(gt,{colSpan:6,className:"text-center py-8",children:"Loading subscriptions..."})}):(y==null?void 0:y.length)===0?e.jsx(Vs,{children:e.jsx(gt,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"No users found"})}):y==null?void 0:y.map(j=>{var E,A;const k=x(j),T=dwe[j.subscription_product_id];return e.jsxs(Vs,{children:[e.jsx(gt,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:j.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:j.email})]})}),e.jsx(gt,{children:e.jsx(Xe,{variant:k.variant,children:k.badge})}),e.jsx(gt,{children:e.jsx("span",{className:"text-sm",children:j.is_grandfathered?"Legacy Access":j.brokerage_id&&!j.subscription_product_id?"Brokerage Subscription":(T==null?void 0:T.name)||k.status})}),e.jsx(gt,{children:(E=j.brokerages)!=null&&E.name?e.jsx("span",{className:"text-sm",children:j.brokerages.name}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"—"})}),e.jsx(gt,{children:j.subscription_end_date?e.jsx("span",{className:"text-sm",children:As(new Date(j.subscription_end_date),"MMM d, yyyy")}):j.trial_expires_at?e.jsxs("span",{className:"text-sm text-blue-600",children:["Trial: ",As(new Date(j.trial_expires_at),"MMM d, yyyy")]}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"—"})}),e.jsx(gt,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[j.stripe_customer_id&&e.jsx(H,{variant:"ghost",size:"sm",onClick:()=>b(j.stripe_customer_id),children:e.jsx(gn,{className:"h-4 w-4"})}),e.jsxs(bs,{children:[e.jsx(Qi,{asChild:!0,children:e.jsx(H,{variant:"outline",size:"sm",onClick:()=>o(j),children:"Details"})}),e.jsxs(vs,{children:[e.jsxs(Cs,{children:[e.jsx(Ns,{children:"Subscription Details"}),e.jsxs(nn,{children:[j.name," (",j.email,")"]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Status"}),e.jsx(Xe,{variant:k.variant,className:"mt-1",children:k.badge})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Plan"}),e.jsx("p",{className:"font-medium",children:j.is_grandfathered?"Grandfathered (Legacy)":j.brokerage_id&&!j.subscription_product_id?"Brokerage Subscription":(T==null?void 0:T.name)||"None"})]}),j.brokerage_id&&e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Brokerage"}),e.jsx("p",{className:"font-medium",children:((A=j.brokerages)==null?void 0:A.name)||"Unknown"})]}),j.subscription_end_date&&e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Current Period End"}),e.jsx("p",{className:"font-medium",children:As(new Date(j.subscription_end_date),"MMMM d, yyyy")})]}),j.trial_expires_at&&e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Trial Expires"}),e.jsx("p",{className:"font-medium",children:As(new Date(j.trial_expires_at),"MMMM d, yyyy")})]}),j.stripe_customer_id&&e.jsxs("div",{className:"col-span-2",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Stripe Customer ID"}),e.jsx("p",{className:"font-mono text-sm",children:j.stripe_customer_id})]})]}),j.stripe_customer_id&&e.jsxs(H,{className:"w-full",onClick:()=>b(j.stripe_customer_id),children:[e.jsx(gn,{className:"h-4 w-4 mr-2"}),"View in Stripe Dashboard"]})]})]})]})]})})]},j.id)})})]})})})]}),e.jsx(cs,{value:"brokerages",className:"space-y-4",children:e.jsx("div",{className:"grid gap-4",children:m==null?void 0:m.map(j=>{var T,E;const k=(T=j.managers)==null?void 0:T.some(A=>A.subscription_status==="active"&&(A.subscription_product_id==="prod_Tc08MupgoVySDG"||A.subscription_product_id==="prod_Tc09N1tJ4RrAFn"));return e.jsxs(ke,{children:[e.jsx(Ot,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-primary/10 flex items-center justify-center",children:e.jsx(Xa,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(zt,{className:"text-lg",children:j.name}),e.jsxs(Br,{children:[j.agentCount," agents"]})]})]}),e.jsx(Xe,{variant:k?"default":"outline",children:k?"Active Subscription":"No Active Subscription"})]})}),e.jsx(Oe,{children:((E=j.managers)==null?void 0:E.length)>0?e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium text-muted-foreground",children:"Managers:"}),j.managers.map(A=>{const D=dwe[A.subscription_product_id];return e.jsxs("div",{className:"flex items-center justify-between p-2 rounded-lg bg-muted/50",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:A.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:A.email})]}),e.jsx("div",{className:"text-right",children:D?e.jsxs("div",{children:[e.jsx(Xe,{variant:"default",children:D.name}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:D.price})]}):e.jsx(Xe,{variant:"outline",children:"No Subscription"})})]},A.id)})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"No managers assigned"})})]},j.id)})})}),e.jsx(cs,{value:"websites",className:"space-y-4",children:e.jsxs(ke,{children:[e.jsxs(Ot,{children:[e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(ld,{className:"h-5 w-5 text-primary"}),"Local Move Website Subscriptions"]}),e.jsx(Br,{children:"$249 setup fee + $99/mo subscriptions from TheLocalMove.com agent websites"})]}),e.jsx(Oe,{className:"p-0",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Vs,{children:[e.jsx(At,{children:"Agent"}),e.jsx(At,{children:"Status"}),e.jsx(At,{children:"Setup Fee"}),e.jsx(At,{children:"Monthly"}),e.jsx(At,{children:"Next Renewal"}),e.jsx(At,{children:"Started"}),e.jsx(At,{className:"text-right",children:"Actions"})]})}),e.jsx(da,{children:p?p.length===0?e.jsx(Vs,{children:e.jsx(gt,{colSpan:7,className:"text-center py-8 text-muted-foreground",children:"No website subscriptions yet"})}):p.map(j=>e.jsxs(Vs,{children:[e.jsx(gt,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:j.agent_name||"—"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:j.agent_email})]})}),e.jsx(gt,{children:e.jsx(Xe,{variant:j.status==="active"?"default":j.status==="canceled"?"destructive":"outline",children:j.status})}),e.jsx(gt,{children:j.setup_fee_paid?e.jsxs(Xe,{variant:"secondary",children:["Paid · $",(j.setup_fee_amount_cents/100).toFixed(0)]}):e.jsx(Xe,{variant:"outline",children:"Unpaid"})}),e.jsxs(gt,{className:"font-medium",children:["$",(j.monthly_amount_cents/100).toFixed(0),"/mo"]}),e.jsx(gt,{children:j.current_period_end?e.jsx("span",{className:"text-sm",children:As(new Date(j.current_period_end),"MMM d, yyyy")}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"—"})}),e.jsx(gt,{children:e.jsx("span",{className:"text-sm",children:As(new Date(j.created_at),"MMM d, yyyy")})}),e.jsx(gt,{className:"text-right",children:j.stripe_customer_id&&e.jsx(H,{variant:"ghost",size:"sm",onClick:()=>b(j.stripe_customer_id),children:e.jsx(gn,{className:"h-4 w-4"})})})]},j.id)):e.jsx(Vs,{children:e.jsx(gt,{colSpan:7,className:"text-center py-8",children:"Loading…"})})})]})})]})})]})]})})}function nLs(){const[s,t]=S.useState([]),[r,n]=S.useState(!0),[a,i]=S.useState(""),[l,o]=S.useState("all"),[c,d]=S.useState({total:0,qualified:0,pending:0,cancelled:0,totalDiscounts:0});S.useEffect(()=>{h()},[]);const h=async()=>{try{const{data:y,error:_}=await V.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(_)throw _;t(y||[]);const b=(y==null?void 0:y.filter(T=>T.status==="qualified").length)||0,j=(y==null?void 0:y.filter(T=>T.status==="pending").length)||0,k=(y==null?void 0:y.filter(T=>T.status==="cancelled").length)||0;d({total:(y==null?void 0:y.length)||0,qualified:b,pending:j,cancelled:k,totalDiscounts:b*25})}catch(y){console.error("Error fetching referrals:",y),he.error("Failed to load referrals")}finally{n(!1)}},m=async()=>{try{he.loading("Processing qualifications...");const{error:y}=await V.functions.invoke("process-referral-qualifications");if(y)throw y;he.dismiss(),he.success("Qualifications processed successfully"),h()}catch(y){he.dismiss(),console.error("Error processing qualifications:",y),he.error("Failed to process qualifications")}},p=s.filter(y=>{var j,k,T,E,A,D;const _=((k=(j=y.referrer_brokerage)==null?void 0:j.name)==null?void 0:k.toLowerCase().includes(a.toLowerCase()))||((E=(T=y.referred_brokerage)==null?void 0:T.name)==null?void 0:E.toLowerCase().includes(a.toLowerCase()))||((D=(A=y.referred_user)==null?void 0:A.email)==null?void 0:D.toLowerCase().includes(a.toLowerCase())),b=l==="all"||y.status===l;return _&&b}),x=y=>{switch(y){case"qualified":return e.jsxs(Xe,{className:"bg-green-100 text-green-800",children:[e.jsx(zi,{className:"h-3 w-3 mr-1"}),"Qualified"]});case"pending":return e.jsxs(Xe,{variant:"secondary",children:[e.jsx(Pn,{className:"h-3 w-3 mr-1"}),"Pending"]});case"cancelled":return e.jsxs(Xe,{variant:"destructive",children:[e.jsx(kd,{className:"h-3 w-3 mr-1"}),"Cancelled"]});default:return e.jsx(Xe,{children:y})}};return e.jsx(Ss,{title:"Referral Program",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(km,{title:"Referral Program",description:"Track and manage brokerage referrals",children:e.jsxs(H,{onClick:m,variant:"outline",children:[e.jsx(po,{className:"h-4 w-4 mr-2"}),"Process Qualifications"]})}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-5 gap-4",children:[e.jsx(ke,{children:e.jsx(Oe,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ar,{className:"h-5 w-5 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:c.total}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Total Referrals"})]})]})})}),e.jsx(ke,{children:e.jsx(Oe,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(zi,{className:"h-5 w-5 text-green-600"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:c.qualified}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Qualified"})]})]})})}),e.jsx(ke,{children:e.jsx(Oe,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Pn,{className:"h-5 w-5 text-amber-600"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:c.pending}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Pending"})]})]})})}),e.jsx(ke,{children:e.jsx(Oe,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(kd,{className:"h-5 w-5 text-red-600"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:c.cancelled}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Cancelled"})]})]})})}),e.jsx(ke,{children:e.jsx(Oe,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(oc,{className:"h-5 w-5 text-green-600"}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-2xl font-bold",children:["$",c.totalDiscounts]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Monthly Discounts"})]})]})})})]}),e.jsxs(ke,{children:[e.jsxs(Ot,{children:[e.jsx(zt,{children:"All Referrals"}),e.jsx(Br,{children:"View and manage all referral relationships"})]}),e.jsxs(Oe,{children:[e.jsxs("div",{className:"flex gap-4 mb-4",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Mn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Se,{placeholder:"Search by brokerage or email...",value:a,onChange:y=>i(y.target.value),className:"pl-10"})]}),e.jsxs(Bs,{value:l,onValueChange:o,children:[e.jsx(Os,{className:"w-[180px]",children:e.jsx(Us,{placeholder:"Filter by status"})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"all",children:"All Statuses"}),e.jsx(pt,{value:"pending",children:"Pending"}),e.jsx(pt,{value:"qualified",children:"Qualified"}),e.jsx(pt,{value:"cancelled",children:"Cancelled"})]})]})]}),r?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Vs,{children:[e.jsx(At,{children:"Referrer"}),e.jsx(At,{children:"Referred"}),e.jsx(At,{children:"Signup Date"}),e.jsx(At,{children:"Status"}),e.jsx(At,{children:"Qualified Date"}),e.jsx(At,{children:"Discount"})]})}),e.jsx(da,{children:p.length===0?e.jsx(Vs,{children:e.jsx(gt,{colSpan:6,className:"text-center text-muted-foreground py-8",children:"No referrals found"})}):p.map(y=>{var _,b,j,k;return e.jsxs(Vs,{children:[e.jsx(gt,{className:"font-medium",children:((_=y.referrer_brokerage)==null?void 0:_.name)||"Unknown"}),e.jsx(gt,{children:e.jsxs("div",{children:[e.jsx("p",{children:((b=y.referred_brokerage)==null?void 0:b.name)||((j=y.referred_user)==null?void 0:j.name)||"Pending setup"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(k=y.referred_user)==null?void 0:k.email})]})}),e.jsx(gt,{children:As(new Date(y.signup_date),"MMM d, yyyy")}),e.jsx(gt,{children:x(y.status)}),e.jsx(gt,{children:y.qualified_date?As(new Date(y.qualified_date),"MMM d, yyyy"):"-"}),e.jsx(gt,{children:y.discount_applied?e.jsx(Xe,{variant:"outline",className:"text-green-600",children:"$25/mo applied"}):e.jsx("span",{className:"text-muted-foreground",children:"-"})})]},y.id)})})]})]})]})]})})}const uwe=[{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"},{value:"add_contact",label:"Add Contact"},{value:"add_plan",label:"Add Touchpoint Plan"},{value:"create_video",label:"Create Video"},{value:"complete_touch",label:"Complete Touch"},{value:"add_transaction",label:"Add Transaction"},{value:"add_listing",label:"Add Listing"},{value:"schedule_popby",label:"Schedule Pop-by"}],aLs=[{value:"brokerage_manager",label:"Brokerage Manager"},{value:"agent",label:"Agent"}];function iLs(){const[s,t]=S.useState([]),[r,n]=S.useState(!0),[a,i]=S.useState(!1),[l,o]=S.useState(null),[c,d]=S.useState({title:"",description:"",action_type:"view_template",target_role:"agent",is_active:!0});S.useEffect(()=>{h()},[]);const h=async()=>{try{const{data:k,error:T}=await V.from("onboarding_checklist_items").select("*").order("target_role").order("sort_order");if(T)throw T;t(k||[])}catch(k){console.error("Error fetching checklist items:",k),he.error("Failed to load checklist items")}finally{n(!1)}},m=()=>{o(null),d({title:"",description:"",action_type:"view_template",target_role:"agent",is_active:!0}),i(!0)},p=k=>{o(k),d({title:k.title,description:k.description||"",action_type:k.action_type,target_role:k.target_role,is_active:k.is_active}),i(!0)},x=async()=>{if(!c.title.trim()){he.error("Title is required");return}try{if(l){const{error:k}=await V.from("onboarding_checklist_items").update({title:c.title,description:c.description||null,action_type:c.action_type,target_role:c.target_role,is_active:c.is_active}).eq("id",l.id);if(k)throw k;he.success("Checklist item updated")}else{const k=s.filter(E=>E.target_role===c.target_role).reduce((E,A)=>Math.max(E,A.sort_order),-1),{error:T}=await V.from("onboarding_checklist_items").insert({title:c.title,description:c.description||null,action_type:c.action_type,target_role:c.target_role,is_active:c.is_active,sort_order:k+1});if(T)throw T;he.success("Checklist item created")}i(!1),h()}catch(k){console.error("Error saving checklist item:",k),he.error("Failed to save checklist item")}},y=async k=>{if(confirm("Are you sure you want to delete this checklist item?"))try{const{error:T}=await V.from("onboarding_checklist_items").delete().eq("id",k);if(T)throw T;he.success("Checklist item deleted"),h()}catch(T){console.error("Error deleting checklist item:",T),he.error("Failed to delete checklist item")}},_=async k=>{try{const{error:T}=await V.from("onboarding_checklist_items").update({is_active:!k.is_active}).eq("id",k.id);if(T)throw T;he.success(k.is_active?"Item deactivated":"Item activated"),h()}catch(T){console.error("Error toggling item:",T),he.error("Failed to update item")}},b=s.filter(k=>k.target_role==="brokerage_manager"),j=s.filter(k=>k.target_role==="agent");return e.jsxs(Ss,{title:"Onboarding Checklist",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold",children:"Onboarding Checklist"}),e.jsx("p",{className:"text-muted-foreground",children:"Manage checklist items shown to new users on their dashboard"})]}),e.jsxs(H,{onClick:m,className:"gap-2",children:[e.jsx(Ys,{className:"h-4 w-4"}),"Add Item"]})]}),e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(Xe,{variant:"secondary",children:"Brokerage Manager"}),"Checklist Items"]})}),e.jsx(Oe,{children:b.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No checklist items for brokerage managers"}):e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Vs,{children:[e.jsx(At,{className:"w-12",children:"#"}),e.jsx(At,{children:"Title"}),e.jsx(At,{children:"Action Type"}),e.jsx(At,{children:"Status"}),e.jsx(At,{className:"text-right",children:"Actions"})]})}),e.jsx(da,{children:b.map((k,T)=>{var E;return e.jsxs(Vs,{children:[e.jsx(gt,{className:"text-muted-foreground",children:T+1}),e.jsx(gt,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:k.title}),k.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-1",children:k.description})]})}),e.jsx(gt,{children:e.jsx(Xe,{variant:"outline",children:((E=uwe.find(A=>A.value===k.action_type))==null?void 0:E.label)||k.action_type})}),e.jsx(gt,{children:e.jsx(Or,{checked:k.is_active,onCheckedChange:()=>_(k)})}),e.jsx(gt,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx(H,{variant:"ghost",size:"icon",onClick:()=>p(k),children:e.jsx(ni,{className:"h-4 w-4"})}),e.jsx(H,{variant:"ghost",size:"icon",onClick:()=>y(k.id),children:e.jsx(Dr,{className:"h-4 w-4 text-destructive"})})]})})]},k.id)})})]})})]}),e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(Xe,{variant:"secondary",children:"Agent"}),"Checklist Items"]})}),e.jsx(Oe,{children:j.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No checklist items for agents"}):e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Vs,{children:[e.jsx(At,{className:"w-12",children:"#"}),e.jsx(At,{children:"Title"}),e.jsx(At,{children:"Action Type"}),e.jsx(At,{children:"Status"}),e.jsx(At,{className:"text-right",children:"Actions"})]})}),e.jsx(da,{children:j.map((k,T)=>{var E;return e.jsxs(Vs,{children:[e.jsx(gt,{className:"text-muted-foreground",children:T+1}),e.jsx(gt,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:k.title}),k.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-1",children:k.description})]})}),e.jsx(gt,{children:e.jsx(Xe,{variant:"outline",children:((E=uwe.find(A=>A.value===k.action_type))==null?void 0:E.label)||k.action_type})}),e.jsx(gt,{children:e.jsx(Or,{checked:k.is_active,onCheckedChange:()=>_(k)})}),e.jsx(gt,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx(H,{variant:"ghost",size:"icon",onClick:()=>p(k),children:e.jsx(ni,{className:"h-4 w-4"})}),e.jsx(H,{variant:"ghost",size:"icon",onClick:()=>y(k.id),children:e.jsx(Dr,{className:"h-4 w-4 text-destructive"})})]})})]},k.id)})})]})})]})]}),e.jsx(bs,{open:a,onOpenChange:i,children:e.jsxs(vs,{children:[e.jsx(Cs,{children:e.jsx(Ns,{children:l?"Edit Checklist Item":"Add Checklist Item"})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"title",children:"Title *"}),e.jsx(Se,{id:"title",value:c.title,onChange:k=>d({...c,title:k.target.value}),placeholder:"e.g., Watch your first academy video"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"description",children:"Description"}),e.jsx(vr,{id:"description",value:c.description,onChange:k=>d({...c,description:k.target.value}),placeholder:"Optional description for the checklist item",rows:2})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Target Role"}),e.jsxs(Bs,{value:c.target_role,onValueChange:k=>d({...c,target_role:k}),children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsx(Fs,{children:aLs.map(k=>e.jsx(pt,{value:k.value,children:k.label},k.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Action Type"}),e.jsxs(Bs,{value:c.action_type,onValueChange:k=>d({...c,action_type:k}),children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsx(Fs,{children:uwe.map(k=>e.jsx(pt,{value:k.value,children:k.label},k.value))})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Or,{id:"is_active",checked:c.is_active,onCheckedChange:k=>d({...c,is_active:k})}),e.jsx(ue,{htmlFor:"is_active",children:"Active"})]})]}),e.jsxs(wn,{children:[e.jsx(H,{variant:"outline",onClick:()=>i(!1),children:"Cancel"}),e.jsx(H,{onClick:x,children:l?"Save Changes":"Create Item"})]})]})})]})}function oLs(){const[s,t]=S.useState(""),[r,n]=S.useState("all"),[a,i]=S.useState("name"),[l,o]=S.useState("asc"),[c,d]=S.useState(""),[h,m]=S.useState(""),[p,x]=S.useState(""),[y,_]=S.useState(""),{data:b}=yt({queryKey:["admin-brokerages"],queryFn:async()=>{const{data:$,error:ee}=await V.from("brokerages").select("id, name").order("name");if(ee)throw ee;return $}}),j=async $=>{let Z=[],J=0,K=!0;for(;K;){const{data:re,error:ie}=await $(J,J+1e3-1);if(ie)throw ie;re&&re.length>0?(Z=[...Z,...re],J+=1e3,K=re.length===1e3):K=!1}return Z},{data:k,isLoading:T}=yt({queryKey:["admin-agent-os-user-stats"],queryFn:async()=>{const $=await j((ze,Pe)=>V.from("profiles").select("id, name, email, brokerage_id, created_at").range(ze,Pe)),{data:ee}=await V.from("brokerages").select("id, name"),Z=new Map((ee==null?void 0:ee.map(ze=>[ze.id,ze.name]))||[]),[{data:J},{data:K},{data:re},{data:ie},{data:ce},{data:ne},{data:le}]=await Promise.all([V.rpc("get_admin_contact_counts"),V.rpc("get_admin_video_counts"),V.rpc("get_admin_popby_counts"),V.rpc("get_admin_listing_counts"),V.rpc("get_admin_deal_counts"),V.rpc("get_admin_portal_counts"),V.rpc("get_admin_sendable_card_counts")]),be=new Map;J==null||J.forEach(ze=>be.set(ze.owner_user_id,ze.contact_count));const fe=new Map;K==null||K.forEach(ze=>fe.set(ze.owner_user_id,ze.video_count));const je=new Map;re==null||re.forEach(ze=>je.set(ze.owner_user_id,ze.popby_count));const ve=new Map;ie==null||ie.forEach(ze=>ve.set(ze.agent_id,ze.listing_count));const We=new Map;ce==null||ce.forEach(ze=>We.set(ze.owner_user_id,ze.deal_count));const Ve=new Map;ne==null||ne.forEach(ze=>Ve.set(ze.owner_user_id,{total:ze.portal_count,active:ze.active_portal_count}));const Le=new Map;return le==null||le.forEach(ze=>Le.set(ze.owner_user_id,{total:ze.card_count,sent:ze.sent_card_count,views:ze.total_card_views})),$.map(ze=>{const Pe=Ve.get(ze.id),Ie=Le.get(ze.id);return{id:ze.id,name:ze.name||"Unknown",email:ze.email||"",brokerage_id:ze.brokerage_id,brokerage_name:ze.brokerage_id&&Z.get(ze.brokerage_id)||null,contact_count:be.get(ze.id)||0,video_count:fe.get(ze.id)||0,popby_count:je.get(ze.id)||0,listing_count:ve.get(ze.id)||0,deal_count:We.get(ze.id)||0,portal_count:(Pe==null?void 0:Pe.total)||0,active_portal_count:(Pe==null?void 0:Pe.active)||0,card_count:(Ie==null?void 0:Ie.total)||0,sent_card_count:(Ie==null?void 0:Ie.sent)||0,total_card_views:(Ie==null?void 0:Ie.views)||0,created_at:ze.created_at}})}}),E=S.useMemo(()=>{if(!k)return[];let $=k.filter(ee=>{const Z=s.toLowerCase(),J=!s||ee.name.toLowerCase().includes(Z)||ee.email.toLowerCase().includes(Z),K=r==="all"||r==="none"&&!ee.brokerage_id||ee.brokerage_id===r,re=parseInt(c)||0,ie=parseInt(h)||0,ce=parseInt(p)||0,ne=parseInt(y)||0,le=ee.contact_count>=re&&ee.video_count>=ie&&ee.popby_count>=ce&&ee.listing_count>=ne;return J&&K&&le});return $.sort((ee,Z)=>{let J=0;return a==="name"?J=ee.name.localeCompare(Z.name):J=ee[a]-Z[a],l==="asc"?J:-J}),$},[k,s,r,a,l,c,h,p,y]),A=$=>{a===$?o(l==="asc"?"desc":"asc"):(i($),o("desc"))},D=()=>{const $=["Name","Email","Brokerage","Contacts","Videos","Popbys","Listings","Deals","Portals (Active)","Cards Created","Cards Sent","Card Views"],ee=E.map(ie=>[ie.name,ie.email,ie.brokerage_name||"None",ie.contact_count,ie.video_count,ie.popby_count,ie.listing_count,ie.deal_count,`${ie.portal_count} (${ie.active_portal_count})`,ie.card_count,ie.sent_card_count,ie.total_card_views]),Z=[$.join(","),...ee.map(ie=>ie.map(ce=>`"${ce}"`).join(","))].join(` `),J=new Blob([Z],{type:"text/csv"}),K=URL.createObjectURL(J),re=document.createElement("a");re.href=K,re.download=`agent-os-user-stats-${new Date().toISOString().split("T")[0]}.csv`,re.click(),URL.revokeObjectURL(K)},R=S.useMemo(()=>E.length?E.reduce(($,ee)=>({contacts:$.contacts+ee.contact_count,videos:$.videos+ee.video_count,popbys:$.popbys+ee.popby_count,listings:$.listings+ee.listing_count,deals:$.deals+ee.deal_count,portals:$.portals+ee.portal_count,activePortals:$.activePortals+ee.active_portal_count,cards:$.cards+ee.card_count,sentCards:$.sentCards+ee.sent_card_count,cardViews:$.cardViews+ee.total_card_views}),{contacts:0,videos:0,popbys:0,listings:0,deals:0,portals:0,activePortals:0,cards:0,sentCards:0,cardViews:0}):{contacts:0,videos:0,popbys:0,listings:0,deals:0,portals:0,activePortals:0,cards:0,sentCards:0,cardViews:0},[E]),z=S.useMemo(()=>E.length?{portals:E.filter($=>$.portal_count>0).length,cards:E.filter($=>$.card_count>0).length}:{portals:0,cards:0},[E]),O=({field:$,children:ee})=>e.jsx(At,{className:"cursor-pointer hover:bg-muted/50 select-none",onClick:()=>A($),children:e.jsxs("div",{className:"flex items-center gap-1",children:[ee,e.jsx(qu,{className:`h-3 w-3 ${a===$?"text-primary":"text-muted-foreground"}`})]})});return e.jsx(xj,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs(ke,{className:"border-blue-500/20 bg-gradient-to-br from-blue-500/5 to-transparent",children:[e.jsx(Ot,{className:"pb-2",children:e.jsxs(zt,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(m_,{className:"h-4 w-4 text-blue-500"}),"Client Portals"]})}),e.jsx(Oe,{children:e.jsxs("div",{className:"grid grid-cols-3 gap-4 text-center",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold",children:z.portals}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Agents Using"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold",children:R.portals}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Total Portals"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold text-emerald-600",children:R.activePortals}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Active Portals"})]})]})})]}),e.jsxs(ke,{className:"border-violet-500/20 bg-gradient-to-br from-violet-500/5 to-transparent",children:[e.jsx(Ot,{className:"pb-2",children:e.jsxs(zt,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(er,{className:"h-4 w-4 text-violet-500"}),"Card Studio"]})}),e.jsx(Oe,{children:e.jsxs("div",{className:"grid grid-cols-4 gap-3 text-center",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold",children:z.cards}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Agents Using"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold",children:R.cards}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Cards Created"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold text-emerald-600",children:R.sentCards}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Cards Sent"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold text-blue-600",children:R.cardViews}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Total Views"})]})]})})]})]}),e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(Ar,{className:"h-5 w-5"}),"User Activity Analytics"]}),e.jsx(Br,{children:"View all users and their Agent OS usage metrics"})]}),e.jsxs(H,{variant:"outline",size:"sm",onClick:D,children:[e.jsx(hi,{className:"h-4 w-4 mr-2"}),"Export CSV"]})]})}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-6",children:[e.jsx("div",{className:"md:col-span-2",children:e.jsxs("div",{className:"relative",children:[e.jsx(Mn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Se,{placeholder:"Search by name or email...",value:s,onChange:$=>t($.target.value),className:"pl-9"})]})}),e.jsx("div",{children:e.jsxs(Bs,{value:r,onValueChange:n,children:[e.jsxs(Os,{children:[e.jsx(Xa,{className:"h-4 w-4 mr-2 text-muted-foreground"}),e.jsx(Us,{placeholder:"Brokerage"})]}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"all",children:"All Brokerages"}),e.jsx(pt,{value:"none",children:"No Brokerage"}),b==null?void 0:b.map($=>e.jsx(pt,{value:$.id,children:$.name},$.id))]})]})}),e.jsx("div",{children:e.jsx(Se,{type:"number",placeholder:"Min contacts",value:c,onChange:$=>d($.target.value),min:"0"})}),e.jsx("div",{children:e.jsx(Se,{type:"number",placeholder:"Min videos",value:h,onChange:$=>m($.target.value),min:"0"})}),e.jsx("div",{children:e.jsx(Se,{type:"number",placeholder:"Min popbys",value:p,onChange:$=>x($.target.value),min:"0"})})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-8 text-sm",children:[e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:E.length}),e.jsx("div",{className:"text-muted-foreground",children:"Users"})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:R.contacts.toLocaleString()}),e.jsx("div",{className:"text-muted-foreground",children:"Contacts"})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:R.videos.toLocaleString()}),e.jsx("div",{className:"text-muted-foreground",children:"Videos"})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:R.popbys.toLocaleString()}),e.jsx("div",{className:"text-muted-foreground",children:"Popbys"})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:R.listings.toLocaleString()}),e.jsx("div",{className:"text-muted-foreground",children:"Listings"})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:R.deals.toLocaleString()}),e.jsx("div",{className:"text-muted-foreground",children:"Deals"})]}),e.jsxs("div",{className:"bg-blue-500/10 rounded-lg p-3 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:R.portals.toLocaleString()}),e.jsx("div",{className:"text-muted-foreground",children:"Portals"})]}),e.jsxs("div",{className:"bg-violet-500/10 rounded-lg p-3 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:R.cards.toLocaleString()}),e.jsx("div",{className:"text-muted-foreground",children:"Cards"})]})]}),T?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(is,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsx("div",{className:"rounded-md border overflow-x-auto",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Vs,{children:[e.jsx(O,{field:"name",children:"Name"}),e.jsx(At,{children:"Email"}),e.jsx(At,{children:"Brokerage"}),e.jsx(O,{field:"contact_count",children:"Contacts"}),e.jsx(O,{field:"video_count",children:"Videos"}),e.jsx(O,{field:"popby_count",children:"Popbys"}),e.jsx(O,{field:"listing_count",children:"Listings"}),e.jsx(O,{field:"deal_count",children:"Deals"}),e.jsx(O,{field:"portal_count",children:e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(m_,{className:"h-3 w-3 text-blue-500"}),"Portals"]})}),e.jsx(O,{field:"card_count",children:e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(er,{className:"h-3 w-3 text-violet-500"}),"Cards"]})})]})}),e.jsx(da,{children:E.length===0?e.jsx(Vs,{children:e.jsx(gt,{colSpan:10,className:"text-center py-8 text-muted-foreground",children:"No users found matching your filters"})}):E.map($=>e.jsxs(Vs,{children:[e.jsx(gt,{className:"font-medium",children:$.name}),e.jsx(gt,{className:"text-muted-foreground",children:$.email}),e.jsx(gt,{children:$.brokerage_name?e.jsx(Xe,{variant:"secondary",children:$.brokerage_name}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(gt,{children:e.jsx(Xe,{variant:$.contact_count>0?"default":"outline",children:$.contact_count})}),e.jsx(gt,{children:e.jsx(Xe,{variant:$.video_count>0?"default":"outline",children:$.video_count})}),e.jsx(gt,{children:e.jsx(Xe,{variant:$.popby_count>0?"default":"outline",children:$.popby_count})}),e.jsx(gt,{children:e.jsx(Xe,{variant:$.listing_count>0?"default":"outline",children:$.listing_count})}),e.jsx(gt,{children:e.jsx(Xe,{variant:$.deal_count>0?"default":"outline",children:$.deal_count})}),e.jsx(gt,{children:$.portal_count>0?e.jsxs(rd,{children:[e.jsx(nd,{children:e.jsxs(Xe,{variant:"default",className:"bg-blue-600 hover:bg-blue-700",children:[$.portal_count,$.active_portal_count>0&&e.jsxs("span",{className:"ml-1 opacity-75",children:["(",$.active_portal_count," active)"]})]})}),e.jsxs(Rc,{children:[e.jsxs("p",{children:[$.portal_count," total portals"]}),e.jsxs("p",{children:[$.active_portal_count," currently active"]})]})]}):e.jsx(Xe,{variant:"outline",children:"0"})}),e.jsx(gt,{children:$.card_count>0?e.jsxs(rd,{children:[e.jsx(nd,{children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Xe,{variant:"default",className:"bg-violet-600 hover:bg-violet-700",children:$.card_count}),$.sent_card_count>0&&e.jsxs("span",{className:"flex items-center gap-0.5 text-xs text-emerald-600",children:[e.jsx(yn,{className:"h-3 w-3"}),$.sent_card_count]}),$.total_card_views>0&&e.jsxs("span",{className:"flex items-center gap-0.5 text-xs text-muted-foreground",children:[e.jsx(Bn,{className:"h-3 w-3"}),$.total_card_views]})]})}),e.jsxs(Rc,{children:[e.jsxs("p",{children:[$.card_count," cards created"]}),e.jsxs("p",{children:[$.sent_card_count," sent"]}),e.jsxs("p",{children:[$.total_card_views," total views"]})]})]}):e.jsx(Xe,{variant:"outline",children:"0"})})]},$.id))})]})})]})]})]})})}function lLs(){li(),ns();const[s,t]=S.useState("user-analytics"),{data:r}=yt({queryKey:["admin-feature-flags"],queryFn:async()=>{const{data:x,error:y}=await V.from("feature_flags").select("*").order("key");if(y)throw y;return x}}),{data:n,isLoading:a}=yt({queryKey:["admin-relationship-types"],queryFn:async()=>{const{data:x,error:y}=await V.from("relationship_types").select("*").order("sort_order");if(y)throw y;return x}}),{data:i,isLoading:l}=yt({queryKey:["admin-action-types"],queryFn:async()=>{const{data:x,error:y}=await V.from("action_types").select("*").order("sort_order");if(y)throw y;return x}}),{data:o,isLoading:c}=yt({queryKey:["admin-action-scripts"],queryFn:async()=>{const{data:x,error:y}=await V.from("action_scripts").select("*, action_type:action_types(*)");if(y)throw y;return x}}),{data:d,isLoading:h}=yt({queryKey:["admin-touchpoint-plans"],queryFn:async()=>{const{data:x,error:y}=await V.from("touchpoint_plans").select("*").order("name");if(y)throw y;return x}}),{data:m,isLoading:p}=yt({queryKey:["admin-popby-items"],queryFn:async()=>{const{data:x,error:y}=await V.from("popby_items").select("*").is("owner_user_id",null).order("name");if(y)throw y;return x}});return e.jsx(Ss,{title:"Agent OS Control Center",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(km,{title:"Agent OS Control Center",description:"Manage InnerCircle settings, scripts, and touchpoint plans"}),e.jsxs(ta,{value:s,onValueChange:t,children:[e.jsxs(Qn,{className:"grid w-full grid-cols-9",children:[e.jsxs(ts,{value:"user-analytics",className:"gap-2",children:[e.jsx(Bo,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Users"})]}),e.jsxs(ts,{value:"relationship-types",className:"gap-2",children:[e.jsx(Ar,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Relationships"})]}),e.jsxs(ts,{value:"action-types",className:"gap-2",children:[e.jsx(Yn,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Actions"})]}),e.jsxs(ts,{value:"scripts",className:"gap-2",children:[e.jsx(kn,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Scripts"})]}),e.jsxs(ts,{value:"video-scripts",className:"gap-2",children:[e.jsx(Qm,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Video Scripts"})]}),e.jsxs(ts,{value:"plans",className:"gap-2",children:[e.jsx(Nn,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Plans"})]}),e.jsxs(ts,{value:"popbys",className:"gap-2",children:[e.jsx(Di,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Popbys"})]}),e.jsxs(ts,{value:"settings",className:"gap-2",children:[e.jsx(Go,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Settings"})]}),e.jsxs(ts,{value:"feature-flags",className:"gap-2",children:[e.jsx(U2,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Flags"})]})]}),e.jsx(cs,{value:"user-analytics",className:"mt-6",children:e.jsx(oLs,{})}),e.jsx(cs,{value:"relationship-types",className:"mt-6",children:e.jsx(cLs,{types:n||[],isLoading:a})}),e.jsx(cs,{value:"action-types",className:"mt-6",children:e.jsx(dLs,{types:i||[],isLoading:l})}),e.jsx(cs,{value:"scripts",className:"mt-6",children:e.jsx(uLs,{scripts:o||[],actionTypes:i||[],isLoading:c})}),e.jsx(cs,{value:"video-scripts",className:"mt-6",children:e.jsx(pLs,{})}),e.jsx(cs,{value:"plans",className:"mt-6",children:e.jsx(hLs,{plans:d||[],actionTypes:i||[],scripts:o||[],isLoading:h})}),e.jsx(cs,{value:"popbys",className:"mt-6",children:e.jsx(fLs,{items:m||[],isLoading:p})}),e.jsx(cs,{value:"settings",className:"mt-6",children:e.jsx(gLs,{})}),e.jsx(cs,{value:"feature-flags",className:"mt-6",children:e.jsx(mLs,{flags:r||[]})})]})]})})}function cLs({types:s,isLoading:t}){const{toast:r}=li(),n=ns(),[a,i]=S.useState(null),[l,o]=S.useState(!1),c=Pt({mutationFn:async h=>{if(h.id){const{error:m}=await V.from("relationship_types").update({name:h.name,description:h.description,icon:h.icon}).eq("id",h.id);if(m)throw m}else{const{error:m}=await V.from("relationship_types").insert([{name:h.name,description:h.description,icon:h.icon,sort_order:s.length}]);if(m)throw m}},onSuccess:()=>{n.invalidateQueries({queryKey:["admin-relationship-types"]}),o(!1),i(null),r({title:"Saved successfully"})},onError:h=>{r({title:"Error",description:h.message,variant:"destructive"})}}),d=async h=>{await V.from("relationship_types").update({active:!h.active}).eq("id",h.id),n.invalidateQueries({queryKey:["admin-relationship-types"]})};return e.jsxs(ke,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(zt,{children:"Relationship Types"}),e.jsx(Br,{children:"Define the relationship categories for InnerCircle contacts"})]}),e.jsxs(H,{onClick:()=>{i(null),o(!0)},children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Add Type"]})]}),e.jsx(Oe,{children:t?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(is,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Vs,{children:[e.jsx(At,{className:"w-12"}),e.jsx(At,{children:"Name"}),e.jsx(At,{children:"Description"}),e.jsx(At,{children:"Status"}),e.jsx(At,{className:"w-24",children:"Actions"})]})}),e.jsx(da,{children:s.map(h=>e.jsxs(Vs,{children:[e.jsx(gt,{children:e.jsx(Oh,{className:"h-4 w-4 text-muted-foreground cursor-grab"})}),e.jsx(gt,{className:"font-medium",children:h.name}),e.jsx(gt,{className:"text-muted-foreground",children:h.description}),e.jsx(gt,{children:e.jsx(Or,{checked:h.active,onCheckedChange:()=>d(h)})}),e.jsx(gt,{children:e.jsx(H,{variant:"ghost",size:"icon",onClick:()=>{i(h),o(!0)},children:e.jsx(ni,{className:"h-4 w-4"})})})]},h.id))})]})}),e.jsx(bs,{open:l,onOpenChange:o,children:e.jsxs(vs,{children:[e.jsx(Cs,{children:e.jsxs(Ns,{children:[a?"Edit":"Add"," Relationship Type"]})}),e.jsxs("form",{onSubmit:h=>{h.preventDefault();const m=new FormData(h.currentTarget);c.mutate({id:a==null?void 0:a.id,name:m.get("name"),description:m.get("description"),icon:m.get("icon")})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"name",children:"Name"}),e.jsx(Se,{id:"name",name:"name",defaultValue:a==null?void 0:a.name,required:!0})]}),e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"description",children:"Description"}),e.jsx(vr,{id:"description",name:"description",defaultValue:(a==null?void 0:a.description)||""})]}),e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"icon",children:"Icon"}),e.jsx(Se,{id:"icon",name:"icon",defaultValue:(a==null?void 0:a.icon)||"",placeholder:"e.g., star, heart, user"})]})]}),e.jsxs(wn,{className:"mt-4",children:[e.jsx(H,{type:"button",variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsxs(H,{type:"submit",disabled:c.isPending,children:[c.isPending&&e.jsx(is,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function dLs({types:s,isLoading:t}){const{toast:r}=li(),n=ns(),[a,i]=S.useState(null),[l,o]=S.useState(!1),c=Pt({mutationFn:async h=>{if(h.id){const{error:m}=await V.from("action_types").update({name:h.name,description:h.description,icon:h.icon,color:h.color}).eq("id",h.id);if(m)throw m}else{const{error:m}=await V.from("action_types").insert([{name:h.name,description:h.description,icon:h.icon,color:h.color,sort_order:s.length}]);if(m)throw m}},onSuccess:()=>{n.invalidateQueries({queryKey:["admin-action-types"]}),o(!1),i(null),r({title:"Saved successfully"})},onError:h=>{r({title:"Error",description:h.message,variant:"destructive"})}}),d=async h=>{await V.from("action_types").update({active:!h.active}).eq("id",h.id),n.invalidateQueries({queryKey:["admin-action-types"]})};return e.jsxs(ke,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(zt,{children:"Action Types"}),e.jsx(Br,{children:"Define the types of touchpoint actions agents can take"})]}),e.jsxs(H,{onClick:()=>{i(null),o(!0)},children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Add Action"]})]}),e.jsx(Oe,{children:t?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(is,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Vs,{children:[e.jsx(At,{children:"Name"}),e.jsx(At,{children:"Description"}),e.jsx(At,{children:"Color"}),e.jsx(At,{children:"Status"}),e.jsx(At,{className:"w-24",children:"Actions"})]})}),e.jsx(da,{children:s.map(h=>e.jsxs(Vs,{children:[e.jsx(gt,{className:"font-medium",children:h.name}),e.jsx(gt,{className:"text-muted-foreground",children:h.description}),e.jsx(gt,{children:h.color&&e.jsx("div",{className:"w-6 h-6 rounded",style:{backgroundColor:h.color}})}),e.jsx(gt,{children:e.jsx(Or,{checked:h.active,onCheckedChange:()=>d(h)})}),e.jsx(gt,{children:e.jsx(H,{variant:"ghost",size:"icon",onClick:()=>{i(h),o(!0)},children:e.jsx(ni,{className:"h-4 w-4"})})})]},h.id))})]})}),e.jsx(bs,{open:l,onOpenChange:o,children:e.jsxs(vs,{children:[e.jsx(Cs,{children:e.jsxs(Ns,{children:[a?"Edit":"Add"," Action Type"]})}),e.jsxs("form",{onSubmit:h=>{h.preventDefault();const m=new FormData(h.currentTarget);c.mutate({id:a==null?void 0:a.id,name:m.get("name"),description:m.get("description"),icon:m.get("icon"),color:m.get("color")})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"name",children:"Name"}),e.jsx(Se,{id:"name",name:"name",defaultValue:a==null?void 0:a.name,required:!0})]}),e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"description",children:"Description"}),e.jsx(vr,{id:"description",name:"description",defaultValue:(a==null?void 0:a.description)||""})]}),e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"icon",children:"Icon"}),e.jsx(Se,{id:"icon",name:"icon",defaultValue:(a==null?void 0:a.icon)||"",placeholder:"e.g., phone, message"})]}),e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"color",children:"Color"}),e.jsx(Se,{id:"color",name:"color",type:"color",defaultValue:(a==null?void 0:a.color)||"#6366f1"})]})]}),e.jsxs(wn,{className:"mt-4",children:[e.jsx(H,{type:"button",variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsxs(H,{type:"submit",disabled:c.isPending,children:[c.isPending&&e.jsx(is,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function uLs({scripts:s,actionTypes:t,isLoading:r}){const{toast:n}=li(),a=ns(),[i,l]=S.useState(null),[o,c]=S.useState(!1),d=Pt({mutationFn:async m=>{if(m.id){const{error:p}=await V.from("action_scripts").update({title:m.title,action_type_id:m.action_type_id,tone:m.tone,script_body:m.script_body,active:m.active}).eq("id",m.id);if(p)throw p}else{const{error:p}=await V.from("action_scripts").insert([{title:m.title,action_type_id:m.action_type_id,tone:m.tone,script_body:m.script_body,active:!0}]);if(p)throw p}},onSuccess:()=>{a.invalidateQueries({queryKey:["admin-action-scripts"]}),c(!1),l(null),n({title:"Saved successfully"})},onError:m=>{n({title:"Error",description:m.message,variant:"destructive"})}}),h=Pt({mutationFn:async m=>{const{error:p}=await V.from("action_scripts").delete().eq("id",m);if(p)throw p},onSuccess:()=>{a.invalidateQueries({queryKey:["admin-action-scripts"]}),n({title:"Deleted successfully"})}});return e.jsxs(ke,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(zt,{children:"Script Library"}),e.jsx(Br,{children:"Create and manage scripts for each action type"})]}),e.jsxs(H,{onClick:()=>{l(null),c(!0)},children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Add Script"]})]}),e.jsx(Oe,{children:r?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(is,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Vs,{children:[e.jsx(At,{children:"Title"}),e.jsx(At,{children:"Action Type"}),e.jsx(At,{children:"Tone"}),e.jsx(At,{children:"Status"}),e.jsx(At,{className:"w-24",children:"Actions"})]})}),e.jsx(da,{children:s.map(m=>{var p;return e.jsxs(Vs,{children:[e.jsx(gt,{className:"font-medium",children:m.title}),e.jsx(gt,{children:e.jsx(Xe,{variant:"outline",children:((p=m.action_type)==null?void 0:p.name)||"Unknown"})}),e.jsx(gt,{className:"text-muted-foreground",children:m.tone}),e.jsx(gt,{children:e.jsx(Xe,{variant:m.active?"default":"secondary",children:m.active?"Active":"Inactive"})}),e.jsxs(gt,{className:"flex gap-1",children:[e.jsx(H,{variant:"ghost",size:"icon",onClick:()=>{l(m),c(!0)},children:e.jsx(ni,{className:"h-4 w-4"})}),e.jsx(H,{variant:"ghost",size:"icon",onClick:()=>h.mutate(m.id),children:e.jsx(Dr,{className:"h-4 w-4 text-destructive"})})]})]},m.id)})})]})}),e.jsx(bs,{open:o,onOpenChange:c,children:e.jsxs(vs,{className:"max-w-2xl",children:[e.jsx(Cs,{children:e.jsxs(Ns,{children:[i?"Edit":"Add"," Script"]})}),e.jsxs("form",{onSubmit:m=>{m.preventDefault();const p=new FormData(m.currentTarget);d.mutate({id:i==null?void 0:i.id,title:p.get("title"),action_type_id:p.get("action_type_id"),tone:p.get("tone"),script_body:p.get("script_body"),active:!0})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"title",children:"Title"}),e.jsx(Se,{id:"title",name:"title",defaultValue:i==null?void 0:i.title,required:!0})]}),e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"action_type_id",children:"Action Type"}),e.jsxs(Bs,{name:"action_type_id",defaultValue:i==null?void 0:i.action_type_id,children:[e.jsx(Os,{children:e.jsx(Us,{placeholder:"Select action type"})}),e.jsx(Fs,{children:t.map(m=>e.jsx(pt,{value:m.id,children:m.name},m.id))})]})]})]}),e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"tone",children:"Tone (optional)"}),e.jsx(Se,{id:"tone",name:"tone",defaultValue:(i==null?void 0:i.tone)||"",placeholder:"e.g., Friendly, Professional, Casual"})]}),e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"script_body",children:"Script Body"}),e.jsx(vr,{id:"script_body",name:"script_body",defaultValue:i==null?void 0:i.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...`})]})]}),e.jsxs(wn,{className:"mt-4",children:[e.jsx(H,{type:"button",variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsxs(H,{type:"submit",disabled:d.isPending,children:[d.isPending&&e.jsx(is,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function hLs({plans:s,actionTypes:t,scripts:r,isLoading:n}){const{toast:a}=li(),i=ns(),[l,o]=S.useState(null),[c,d]=S.useState(!1),[h,m]=S.useState(null),[p,x]=S.useState(!1),[y,_]=S.useState(null),[b,j]=S.useState(null),{data:k}=yt({queryKey:["plan-items",h],queryFn:async()=>{if(!h)return[];const{data:O,error:$}=await V.from("touchpoint_plan_items").select("*").eq("plan_id",h).order("month_number");if($)throw $;return O},enabled:!!h}),T=Pt({mutationFn:async O=>{if(O.id){const{error:$}=await V.from("touchpoint_plans").update({name:O.name,description:O.description,active:O.active}).eq("id",O.id);if($)throw $}else{const{error:$}=await V.from("touchpoint_plans").insert([{name:O.name,description:O.description,active:!0}]);if($)throw $}},onSuccess:()=>{i.invalidateQueries({queryKey:["admin-touchpoint-plans"]}),d(!1),o(null),a({title:"Saved successfully"})},onError:O=>{a({title:"Error",description:O.message,variant:"destructive"})}}),E=Pt({mutationFn:async O=>{if(O.id){const{error:$}=await V.from("touchpoint_plan_items").update({action_type_id:O.action_type_id,default_script_id:O.default_script_id,notes:O.notes}).eq("id",O.id);if($)throw $}else{const{error:$}=await V.from("touchpoint_plan_items").insert([{plan_id:O.plan_id,month_number:O.month_number,action_type_id:O.action_type_id,default_script_id:O.default_script_id,notes:O.notes}]);if($)throw $}},onSuccess:()=>{i.invalidateQueries({queryKey:["plan-items",h]}),a({title:"Item saved"})}}),A=Pt({mutationFn:async O=>{const{error:$}=await V.from("touchpoint_plan_items").delete().eq("id",O);if($)throw $},onSuccess:()=>{i.invalidateQueries({queryKey:["plan-items",h]})}}),D=Pt({mutationFn:async O=>{const{data:$,error:ee}=await V.from("action_scripts").insert([{...O,active:!0}]).select().single();if(ee)throw ee;return $},onSuccess:async O=>{i.invalidateQueries({queryKey:["admin-action-scripts"]}),y&&await E.mutateAsync({id:y.itemId,plan_id:h,month_number:y.month,action_type_id:y.actionTypeId,default_script_id:O.id}),x(!1),_(null),a({title:"Script created and assigned"})},onError:O=>{a({title:"Error",description:O.message,variant:"destructive"})}}),R=(O,$,ee)=>{_({month:O,actionTypeId:$,itemId:ee}),x(!0)},z=O=>r.find($=>$.id===O);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(ke,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(zt,{children:"Touchpoint Plans"}),e.jsx(Br,{children:"Create annual touchpoint plans that agents can apply to their contacts"})]}),e.jsxs(H,{onClick:()=>{o(null),d(!0)},children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Add Plan"]})]}),e.jsx(Oe,{children:n?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(is,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:s.map(O=>e.jsxs(ke,{className:`cursor-pointer transition-colors ${h===O.id?"border-primary":""}`,onClick:()=>m(O.id),children:[e.jsx(Ot,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(zt,{className:"text-base",children:O.name}),e.jsx(H,{variant:"ghost",size:"icon",onClick:$=>{$.stopPropagation(),o(O),d(!0)},children:e.jsx(ni,{className:"h-4 w-4"})})]})}),e.jsxs(Oe,{children:[e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2",children:O.description}),e.jsx(Xe,{variant:O.active?"default":"secondary",className:"mt-2",children:O.active?"Active":"Inactive"})]})]},O.id))})})]}),h&&e.jsxs(ke,{children:[e.jsxs(Ot,{children:[e.jsx(zt,{children:"Plan Schedule"}),e.jsx(Br,{children:"Configure the monthly touchpoint schedule. Select an action type for each month, then assign or create a script."})]}),e.jsx(Oe,{children:e.jsx("div",{className:"grid gap-3",children:Array.from({length:12},(O,$)=>$+1).map(O=>{const $=k==null?void 0:k.find(J=>J.month_number===O),ee=$!=null&&$.default_script_id?z($.default_script_id):null,Z=r.filter(J=>J.action_type_id===($==null?void 0:$.action_type_id)&&J.active);return e.jsxs("div",{className:"p-4 border rounded-lg space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"w-20 font-medium text-sm",children:["Month ",O]}),e.jsxs(Bs,{value:($==null?void 0:$.action_type_id)||"none",onValueChange:J=>{J==="none"&&$?A.mutate($.id):J!=="none"&&E.mutate({id:$==null?void 0:$.id,plan_id:h,month_number:O,action_type_id:J,default_script_id:null})},children:[e.jsx(Os,{className:"w-40",children:e.jsx(Us,{placeholder:"No action"})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"none",children:"No action"}),t.filter(J=>J.active).map(J=>e.jsx(pt,{value:J.id,children:e.jsxs("span",{className:"flex items-center gap-2",children:[J.color&&e.jsx("span",{className:"w-3 h-3 rounded-full",style:{backgroundColor:J.color}}),J.name]})},J.id))]})]}),$&&e.jsxs(e.Fragment,{children:[e.jsxs(Bs,{value:$.default_script_id||"none",onValueChange:J=>{j(null),E.mutate({id:$.id,default_script_id:J==="none"?null:J})},children:[e.jsx(Os,{className:"w-56",children:e.jsx(Us,{placeholder:"Select script"})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"none",children:"No default script"}),Z.map(J=>e.jsxs(pt,{value:J.id,children:[J.title," ",J.tone&&`(${J.tone})`]},J.id))]})]}),e.jsxs(H,{variant:"outline",size:"sm",onClick:()=>R(O,$.action_type_id,$.id),children:[e.jsx(Ys,{className:"h-3 w-3 mr-1"}),"New Script"]}),ee&&e.jsx(H,{variant:"ghost",size:"sm",onClick:()=>j((b==null?void 0:b.id)===ee.id?null:ee),children:(b==null?void 0:b.id)===ee.id?"Hide":"Preview"})]})]}),b&&($==null?void 0:$.default_script_id)===b.id&&e.jsxs("div",{className:"ml-24 p-3 bg-muted rounded-lg text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Xe,{variant:"outline",children:b.title}),b.tone&&e.jsx(Xe,{variant:"secondary",children:b.tone})]}),e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:b.script_body})]})]},O)})})})]}),e.jsx(bs,{open:c,onOpenChange:d,children:e.jsxs(vs,{children:[e.jsx(Cs,{children:e.jsxs(Ns,{children:[l?"Edit":"Add"," Touchpoint Plan"]})}),e.jsxs("form",{onSubmit:O=>{O.preventDefault();const $=new FormData(O.currentTarget);T.mutate({id:l==null?void 0:l.id,name:$.get("name"),description:$.get("description"),active:!0})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"name",children:"Name"}),e.jsx(Se,{id:"name",name:"name",defaultValue:l==null?void 0:l.name,required:!0})]}),e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"description",children:"Description"}),e.jsx(vr,{id:"description",name:"description",defaultValue:(l==null?void 0:l.description)||"",rows:3})]})]}),e.jsxs(wn,{className:"mt-4",children:[e.jsx(H,{type:"button",variant:"outline",onClick:()=>d(!1),children:"Cancel"}),e.jsxs(H,{type:"submit",disabled:T.isPending,children:[T.isPending&&e.jsx(is,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})}),e.jsx(bs,{open:p,onOpenChange:x,children:e.jsxs(vs,{className:"max-w-2xl",children:[e.jsxs(Cs,{children:[e.jsx(Ns,{children:"Create New Script"}),e.jsxs(nn,{children:["Create a script for Month ",y==null?void 0:y.month,". Use ","{{FirstName}}",", ","{{LastName}}",", and ","{{AgentName}}"," as placeholders."]})]}),e.jsxs("form",{onSubmit:O=>{O.preventDefault();const $=new FormData(O.currentTarget);D.mutate({title:$.get("title"),action_type_id:y.actionTypeId,tone:$.get("tone"),script_body:$.get("script_body")})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"script_title",children:"Title"}),e.jsx(Se,{id:"script_title",name:"title",placeholder:"e.g., Warm Check-In",required:!0})]}),e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"script_tone",children:"Tone"}),e.jsx(Se,{id:"script_tone",name:"tone",placeholder:"e.g., Friendly, Professional"})]})]}),e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"script_body",children:"Script Body"}),e.jsx(vr,{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..."})]})]}),e.jsxs(wn,{className:"mt-4",children:[e.jsx(H,{type:"button",variant:"outline",onClick:()=>x(!1),children:"Cancel"}),e.jsxs(H,{type:"submit",disabled:D.isPending,children:[D.isPending&&e.jsx(is,{className:"h-4 w-4 mr-2 animate-spin"}),"Create & Assign"]})]})]})]})})]})}function mLs({flags:s}){const{toast:t}=li(),r=ns(),n=async(a,i)=>{const{error:l}=await V.from("feature_flags").update({...i,updated_at:new Date().toISOString()}).eq("id",a.id);l?t({title:"Error",description:l.message,variant:"destructive"}):(r.invalidateQueries({queryKey:["admin-feature-flags"]}),t({title:"Flag updated"}))};return e.jsxs(ke,{children:[e.jsxs(Ot,{children:[e.jsx(zt,{children:"Feature Flags"}),e.jsx(Br,{children:"Control which features are enabled for members"})]}),e.jsx(Oe,{children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Vs,{children:[e.jsx(At,{children:"Flag"}),e.jsx(At,{children:"Status"}),e.jsx(At,{children:"Notes"}),e.jsx(At,{children:"Last Updated"})]})}),e.jsx(da,{children:s.map(a=>e.jsxs(Vs,{children:[e.jsx(gt,{className:"font-mono text-sm",children:a.key}),e.jsx(gt,{children:e.jsx(Or,{checked:a.enabled,onCheckedChange:i=>n(a,{enabled:i})})}),e.jsx(gt,{children:e.jsx(Se,{defaultValue:a.notes||"",placeholder:"Add notes...",className:"max-w-xs",onBlur:i=>{i.target.value!==a.notes&&n(a,{notes:i.target.value})}})}),e.jsx(gt,{className:"text-muted-foreground text-sm",children:new Date(a.updated_at).toLocaleDateString()})]},a.id))})]})})]})}function fLs({items:s,isLoading:t}){const{toast:r}=li(),n=ns(),[a,i]=S.useState(null),[l,o]=S.useState(!1),c=Pt({mutationFn:async m=>{if(m.id){const{error:p}=await V.from("popby_items").update({name:m.name,description:m.description}).eq("id",m.id);if(p)throw p}else{const{error:p}=await V.from("popby_items").insert([{name:m.name,description:m.description,owner_user_id:null}]);if(p)throw p}},onSuccess:()=>{n.invalidateQueries({queryKey:["admin-popby-items"]}),n.invalidateQueries({queryKey:["popby-items"]}),o(!1),i(null),r({title:"Saved successfully"})},onError:m=>{r({title:"Error",description:m.message,variant:"destructive"})}}),d=async m=>{await V.from("popby_items").update({is_active:!m.is_active}).eq("id",m.id),n.invalidateQueries({queryKey:["admin-popby-items"]}),n.invalidateQueries({queryKey:["popby-items"]})},h=async m=>{await V.from("popby_items").delete().eq("id",m),n.invalidateQueries({queryKey:["admin-popby-items"]}),n.invalidateQueries({queryKey:["popby-items"]}),r({title:"Deleted successfully"})};return e.jsxs(ke,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(zt,{children:"Popby Ideas"}),e.jsx(Br,{children:"Manage global popby ideas that all agents can see"})]}),e.jsxs(H,{onClick:()=>{i(null),o(!0)},children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Add Popby Idea"]})]}),e.jsx(Oe,{children:t?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(is,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):s.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Di,{className:"h-12 w-12 mx-auto mb-2 opacity-50"}),e.jsx("p",{children:"No popby ideas yet. Add your first one!"})]}):e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Vs,{children:[e.jsx(At,{children:"Name"}),e.jsx(At,{children:"Description"}),e.jsx(At,{children:"Status"}),e.jsx(At,{className:"w-24",children:"Actions"})]})}),e.jsx(da,{children:s.map(m=>e.jsxs(Vs,{children:[e.jsx(gt,{className:"font-medium",children:m.name}),e.jsx(gt,{className:"text-muted-foreground",children:m.description}),e.jsx(gt,{children:e.jsx(Or,{checked:m.is_active,onCheckedChange:()=>d(m)})}),e.jsx(gt,{children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx(H,{variant:"ghost",size:"icon",onClick:()=>{i(m),o(!0)},children:e.jsx(ni,{className:"h-4 w-4"})}),e.jsx(H,{variant:"ghost",size:"icon",onClick:()=>h(m.id),children:e.jsx(Dr,{className:"h-4 w-4 text-destructive"})})]})})]},m.id))})]})}),e.jsx(bs,{open:l,onOpenChange:o,children:e.jsxs(vs,{children:[e.jsx(Cs,{children:e.jsxs(Ns,{children:[a?"Edit":"Add"," Popby Idea"]})}),e.jsxs("form",{onSubmit:m=>{m.preventDefault();const p=new FormData(m.currentTarget);c.mutate({id:a==null?void 0:a.id,name:p.get("name"),description:p.get("description")})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"name",children:"Name"}),e.jsx(Se,{id:"name",name:"name",defaultValue:a==null?void 0:a.name,required:!0,placeholder:"e.g., Homemade Cookies"})]}),e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"description",children:"Description"}),e.jsx(vr,{id:"description",name:"description",defaultValue:(a==null?void 0:a.description)||"",placeholder:"Brief description of the popby idea..."})]})]}),e.jsxs(wn,{className:"mt-4",children:[e.jsx(H,{type:"button",variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsxs(H,{type:"submit",disabled:c.isPending,children:[c.isPending&&e.jsx(is,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function pLs(){var x;const{toast:s}=li(),t=ns(),[r,n]=S.useState(null),[a,i]=S.useState(!1),{data:l,isLoading:o}=yt({queryKey:["admin-video-script-categories"],queryFn:async()=>{const{data:y,error:_}=await V.from("video_script_categories").select("*").order("sort_order");if(_)throw _;return y}}),{data:c,isLoading:d}=yt({queryKey:["admin-video-scripts"],queryFn:async()=>{const{data:y,error:_}=await V.from("video_scripts").select("*, category:video_script_categories(*)").order("title");if(_)throw _;return y}}),h=Pt({mutationFn:async y=>{var _,b;if(y.id){const{error:j}=await V.from("video_scripts").update({title:y.title,script_text:y.script_text,category_id:y.category_id,tags:((_=y.tags)==null?void 0:_.split(",").map(k=>k.trim()).filter(Boolean))||[]}).eq("id",y.id);if(j)throw j}else{const{error:j}=await V.from("video_scripts").insert([{title:y.title,script_text:y.script_text,category_id:y.category_id||null,tags:((b=y.tags)==null?void 0:b.split(",").map(k=>k.trim()).filter(Boolean))||[]}]);if(j)throw j}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-video-scripts"]}),i(!1),n(null),s({title:"Video script saved!"})},onError:y=>s({title:"Error",description:y.message,variant:"destructive"})}),m=async y=>{await V.from("video_scripts").update({is_active:!y.is_active}).eq("id",y.id),t.invalidateQueries({queryKey:["admin-video-scripts"]})},p=async y=>{confirm("Delete this video script?")&&(await V.from("video_scripts").delete().eq("id",y),t.invalidateQueries({queryKey:["admin-video-scripts"]}),s({title:"Script deleted"}))};return e.jsxs(ke,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(zt,{children:"Video Scripts"}),e.jsx(Br,{children:"Manage teleprompter scripts for Quick Video Touch"})]}),e.jsxs(H,{onClick:()=>{n(null),i(!0)},children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Add Script"]})]}),e.jsx(Oe,{children:d?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(is,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Vs,{children:[e.jsx(At,{children:"Title"}),e.jsx(At,{children:"Category"}),e.jsx(At,{children:"Status"}),e.jsx(At,{className:"w-24",children:"Actions"})]})}),e.jsx(da,{children:c==null?void 0:c.map(y=>{var _;return e.jsxs(Vs,{children:[e.jsx(gt,{className:"font-medium",children:y.title}),e.jsx(gt,{className:"text-muted-foreground",children:((_=y.category)==null?void 0:_.name)||"Uncategorized"}),e.jsx(gt,{children:e.jsx(Or,{checked:y.is_active,onCheckedChange:()=>m(y)})}),e.jsxs(gt,{className:"flex gap-1",children:[e.jsx(H,{variant:"ghost",size:"icon",onClick:()=>{n(y),i(!0)},children:e.jsx(ni,{className:"h-4 w-4"})}),e.jsx(H,{variant:"ghost",size:"icon",onClick:()=>p(y.id),children:e.jsx(Dr,{className:"h-4 w-4"})})]})]},y.id)})})]})}),e.jsx(bs,{open:a,onOpenChange:i,children:e.jsxs(vs,{className:"max-w-2xl",children:[e.jsx(Cs,{children:e.jsxs(Ns,{children:[r?"Edit":"Add"," Video Script"]})}),e.jsxs("form",{onSubmit:y=>{y.preventDefault();const _=new FormData(y.currentTarget);h.mutate({id:r==null?void 0:r.id,title:_.get("title"),script_text:_.get("script_text"),category_id:_.get("category_id")||null,tags:_.get("tags")})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"title",children:"Title"}),e.jsx(Se,{id:"title",name:"title",defaultValue:r==null?void 0:r.title,required:!0})]}),e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"category_id",children:"Category"}),e.jsxs(Bs,{name:"category_id",defaultValue:(r==null?void 0:r.category_id)||"",children:[e.jsx(Os,{children:e.jsx(Us,{placeholder:"Select category"})}),e.jsx(Fs,{children:l==null?void 0:l.map(y=>e.jsx(pt,{value:y.id,children:y.name},y.id))})]})]}),e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"script_text",children:"Script Text"}),e.jsx(vr,{id:"script_text",name:"script_text",defaultValue:r==null?void 0:r.script_text,rows:6,required:!0,placeholder:"Enter the teleprompter script..."})]}),e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"tags",children:"Tags (comma-separated)"}),e.jsx(Se,{id:"tags",name:"tags",defaultValue:((x=r==null?void 0:r.tags)==null?void 0:x.join(", "))||"",placeholder:"birthday, follow-up, thank-you"})]})]}),e.jsxs(wn,{className:"mt-4",children:[e.jsx(H,{type:"button",variant:"outline",onClick:()=>i(!1),children:"Cancel"}),e.jsxs(H,{type:"submit",disabled:h.isPending,children:[h.isPending&&e.jsx(is,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function gLs(){const{toast:s}=li(),[t,r]=S.useState(""),[n,a]=S.useState(!0),[i,l]=S.useState(!1);S.useEffect(()=>{(async()=>{a(!0);try{const{data:d}=await V.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();d!=null&&d.value&&r(d.value)}catch(d){console.error("Error fetching settings:",d)}a(!1)})()},[]);const o=async()=>{l(!0);try{await V.from("settings").upsert({key:"mapbox_public_token",value:t.trim()}),s({title:"Mapbox token saved!"})}catch{s({title:"Error saving token",variant:"destructive"})}l(!1)};return n?e.jsx(ke,{children:e.jsx(Oe,{className:"flex justify-center py-8",children:e.jsx(is,{className:"h-8 w-8 animate-spin text-muted-foreground"})})}):e.jsx("div",{className:"space-y-6",children:e.jsxs(ke,{children:[e.jsxs(Ot,{children:[e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(Qa,{className:"h-5 w-5"}),"Popby Map Settings"]}),e.jsx(Br,{children:"Configure the map feature for popbys"})]}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"mapbox-token",children:"Mapbox Public Token"}),e.jsx(Se,{id:"mapbox-token",placeholder:"pk.eyJ1I...",value:t,onChange:c=>r(c.target.value)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Get your token at"," ",e.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."]})]}),e.jsxs(H,{onClick:o,disabled:i,children:[i&&e.jsx(is,{className:"h-4 w-4 mr-2 animate-spin"}),"Save Token"]}),t&&e.jsx(Xe,{variant:"secondary",className:"ml-2",children:"Token configured"})]})]})})}const xLs=()=>{const[s,t]=S.useState(""),[r,n]=S.useState("grid"),a=Fr(),{data:i=[],isLoading:l}=yt({queryKey:["additional-services"],queryFn:async()=>{const{data:c,error:d}=await V.from("additional_services").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(d)throw d;return c}}),o=i.filter(c=>{var h;return c.name.toLowerCase().includes(s.toLowerCase())||((h=c.description)==null?void 0:h.toLowerCase().includes(s.toLowerCase()))});return e.jsx(Ss,{title:"Additional Services",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Additional Services"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Explore our additional services and offerings"})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1 max-w-sm",children:[e.jsx(Mn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Se,{placeholder:"Search services...",value:s,onChange:c=>t(c.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"flex gap-2",children:[s&&e.jsx(H,{variant:"outline",size:"sm",onClick:()=>t(""),children:"Clear"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(H,{variant:r==="grid"?"secondary":"outline",size:"icon",onClick:()=>n("grid"),className:"rounded-full",children:e.jsx(_g,{className:"h-4 w-4"})}),e.jsx(H,{variant:r==="list"?"secondary":"outline",size:"icon",onClick:()=>n("list"),className:"rounded-full",children:e.jsx(Vf,{className:"h-4 w-4"})})]})]})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[o.length," service",o.length!==1?"s":""," found"]}),l&&e.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((c,d)=>e.jsx(ke,{children:e.jsxs(Oe,{className:"p-4",children:[e.jsx(Ks,{className:"aspect-[3/2] w-full rounded-lg mb-4"}),e.jsx(Ks,{className:"h-5 w-3/4 mb-2"}),e.jsx(Ks,{className:"h-4 w-full mb-4"})]})},d))}),!l&&o.length===0&&e.jsxs("div",{className:"text-center py-12",children:[e.jsx("div",{className:"text-muted-foreground mb-4",children:s?"No services match your search":"No additional services available yet"}),s&&e.jsx(H,{variant:"outline",onClick:()=>t(""),children:"Clear Search"})]}),!l&&o.length>0&&e.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:o.map(c=>e.jsxs(ke,{className:`group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer ${r==="list"?"flex flex-row":""}`,onClick:()=>a(`/additional-services/${c.id}`),children:[e.jsx("div",{className:`relative overflow-hidden bg-muted ${r==="list"?"w-48 shrink-0":"aspect-[3/2]"}`,children:c.preview_image_url?e.jsx("img",{src:c.preview_image_url,alt:c.name,className:"w-full h-full object-contain group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground",children:e.jsx(Lr,{className:"h-8 w-8"})})}),e.jsxs(Oe,{className:`p-4 flex flex-col ${r==="list"?"flex-1":""}`,children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1 mb-1",children:c.name}),c.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 flex-1",children:Q7(c.description)})]})]},c.id))})]})})},yLs=()=>{const{serviceId:s}=Po(),t=Fr(),{data:r,isLoading:n}=yt({queryKey:["additional-service",s],queryFn:async()=>{const{data:a,error:i}=await V.from("additional_services").select("*").eq("id",s).eq("is_published",!0).single();if(i)throw i;return a},enabled:!!s});return n?e.jsx(Ss,{title:"Loading...",children:e.jsxs("div",{className:"max-w-4xl mx-auto space-y-6",children:[e.jsx(Ks,{className:"h-8 w-48"}),e.jsx(Ks,{className:"h-64 w-full rounded-lg"}),e.jsx(Ks,{className:"h-24 w-full"})]})}):r?e.jsx(Ss,{title:r.name,children:e.jsxs("div",{className:"max-w-4xl mx-auto space-y-6",children:[e.jsxs(H,{variant:"ghost",onClick:()=>t("/additional-services"),className:"gap-2",children:[e.jsx(za,{className:"h-4 w-4"}),"Back to Services"]}),e.jsx(ke,{className:"overflow-hidden",children:e.jsx("div",{className:"relative bg-muted",children:r.preview_image_url?e.jsx("img",{src:r.preview_image_url,alt:r.name,className:"w-full h-auto max-h-[500px] object-contain mx-auto"}):e.jsx("div",{className:"w-full h-64 flex items-center justify-center text-muted-foreground",children:e.jsx(Lr,{className:"h-16 w-16"})})})}),e.jsx(ke,{children:e.jsxs(Oe,{className:"p-6 space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground mb-2",children:r.name}),e.jsxs("div",{className:"flex items-center text-sm text-muted-foreground",children:[e.jsx(Nn,{className:"h-4 w-4 mr-1"}),"Published ",As(new Date(r.publish_date),"MMMM d, yyyy")]})]}),r.description&&e.jsx("div",{className:"prose prose-sm max-w-none text-muted-foreground [&_a]:text-primary [&_a]:underline",dangerouslySetInnerHTML:{__html:r.description}}),e.jsx("div",{className:"pt-4 border-t",children:e.jsxs(H,{size:"lg",className:"gap-2",onClick:()=>window.open(r.signup_link_url,"_blank"),children:[e.jsx(gn,{className:"h-5 w-5"}),"Sign Up Now"]})})]})})]})}):e.jsx(Ss,{title:"Not Found",children:e.jsxs("div",{className:"max-w-4xl mx-auto text-center py-12",children:[e.jsx("h2",{className:"text-2xl font-bold text-foreground mb-4",children:"Service Not Found"}),e.jsx("p",{className:"text-muted-foreground mb-6",children:"The service you're looking for doesn't exist or has been removed."}),e.jsxs(H,{onClick:()=>t("/additional-services"),children:[e.jsx(za,{className:"h-4 w-4 mr-2"}),"Back to Services"]})]})})},JR=[{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 vLs(){const[s,t]=S.useState(JR[0].id),r=JR.find(n=>n.id===s)||JR[0];return e.jsx(Ss,{title:"AI Toolkit",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(MI,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"AI Toolkit"}),e.jsx("p",{className:"text-muted-foreground",children:"Powerful AI tools to boost your real estate business"})]})]}),e.jsx("div",{className:"md:hidden",children:e.jsxs(Bs,{value:s,onValueChange:t,children:[e.jsx(Os,{className:"w-full",children:e.jsx(Us,{placeholder:"Select a tool"})}),e.jsx(Fs,{children:JR.map(n=>e.jsx(pt,{value:n.id,children:n.name},n.id))})]})}),e.jsx("div",{className:"hidden md:block",children:e.jsx(ta,{value:s,onValueChange:t,className:"w-full",children:e.jsx(Qn,{className:"w-full flex-wrap h-auto gap-1 bg-muted p-1",children:JR.map(n=>e.jsx(ts,{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))})})}),e.jsx("div",{className:"flex justify-center",children:e.jsx("div",{className:"w-full max-w-[700px]",dangerouslySetInnerHTML:{__html:r.iframe}})})]})})}const PHe="agent-os-onboarding-completed",Vq=[{icon:v_,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:ym,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:Ar,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:xu,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:Di,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:Bo,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"]}],bLs=()=>{const[s,t]=S.useState(!1),[r,n]=S.useState(0),[a,i]=S.useState(!1);S.useEffect(()=>{if(!localStorage.getItem(PHe)){const y=setTimeout(()=>t(!0),500);return()=>clearTimeout(y)}},[]);const l=()=>{r{n(r+1),i(!1)},150)):c()},o=()=>{c()},c=()=>{localStorage.setItem(PHe,"true"),t(!1)},d=Vq[r],h=d.icon,m=r===Vq.length-1,p=x=>{x||c(),t(x)};return e.jsx(bs,{open:s,onOpenChange:p,children:e.jsxs(vs,{className:"sm:max-w-lg overflow-hidden p-0 gap-0",children:[e.jsxs("div",{className:`relative bg-gradient-to-br ${d.bgGradient} p-8 pb-12 transition-all duration-500`,children:[e.jsxs("div",{className:"absolute inset-0 overflow-hidden",children:[e.jsx("div",{className:"absolute -top-4 -right-4 w-32 h-32 bg-white/10 rounded-full blur-2xl animate-pulse"}),e.jsx("div",{className:"absolute -bottom-8 -left-8 w-40 h-40 bg-white/10 rounded-full blur-3xl animate-pulse",style:{animationDelay:"1s"}}),e.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"})]}),e.jsxs("div",{className:`relative mx-auto flex h-20 w-20 items-center justify-center transition-all duration-300 ${a?"scale-75 opacity-0":"scale-100 opacity-100"}`,children:[e.jsx("div",{className:"absolute inset-0 bg-white/20 rounded-2xl blur-xl"}),e.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:e.jsx(h,{className:`h-10 w-10 ${d.iconColor} drop-shadow-lg`})})]}),r===0&&e.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:[e.jsx(Lr,{className:"h-3 w-3"}),"Beta"]})]}),e.jsxs("div",{className:"p-6 pt-4",children:[e.jsxs(Cs,{className:"text-center sm:text-center pb-2",children:[e.jsx(Ns,{className:`text-2xl font-bold transition-all duration-300 ${a?"translate-y-2 opacity-0":"translate-y-0 opacity-100"}`,children:d.title}),e.jsx(nn,{className:`text-base pt-2 transition-all duration-300 delay-75 ${a?"translate-y-2 opacity-0":"translate-y-0 opacity-100"}`,children:d.description})]}),d.highlights&&e.jsx("div",{className:`space-y-2.5 py-4 transition-all duration-300 delay-100 ${a?"translate-y-2 opacity-0":"translate-y-0 opacity-100"}`,children:d.highlights.map((x,y)=>e.jsxs("div",{className:"flex items-center gap-3 group",style:{transitionDelay:`${150+y*50}ms`},children:[e.jsx("div",{className:`flex h-6 w-6 shrink-0 items-center justify-center rounded-full bg-gradient-to-br ${d.bgGradient} shadow-sm`,children:e.jsx(va,{className:"h-3.5 w-3.5 text-white"})}),e.jsx("span",{className:"text-sm text-muted-foreground group-hover:text-foreground transition-colors",children:x})]},y))}),e.jsx("div",{className:"flex justify-center gap-2 py-4",children:Vq.map((x,y)=>e.jsx("button",{onClick:()=>{y!==r&&(i(!0),setTimeout(()=>{n(y),i(!1)},150))},className:`h-2 rounded-full transition-all duration-300 ${y===r?"w-8 bg-gradient-to-r "+d.bgGradient:y{const{user:s}=Ms();return yt({queryKey:["contact-snoozes",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:r}=await V.from("contact_snoozes").select("*").gte("snoozed_until",new Date().toISOString());if(r)throw r;return t},enabled:!!s})},wLs=()=>{const s=ns(),{user:t}=Ms();return Pt({mutationFn:async({contactId:r,days:n})=>{if(!(t!=null&&t.id))throw new Error("Not authenticated");const a=Lc(new Date,n);await V.from("contact_snoozes").delete().eq("contact_id",r);const{error:i}=await V.from("contact_snoozes").insert({contact_id:r,owner_user_id:t.id,snoozed_until:a.toISOString()});if(i)throw i},onSuccess:()=>{s.invalidateQueries({queryKey:["contact-snoozes"]}),s.invalidateQueries({queryKey:["today-actions"]}),s.invalidateQueries({queryKey:["popby-logs"]}),En({title:"Touch snoozed!",description:"Contact has been snoozed."})},onError:r=>{En({title:"Error snoozing contact",description:r.message,variant:"destructive"})}})},jLs=()=>{const s=ns();return Pt({mutationFn:async t=>{const{error:r}=await V.from("contact_snoozes").delete().eq("contact_id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["contact-snoozes"]}),En({title:"Snooze cancelled"})},onError:t=>{En({title:"Error cancelling snooze",description:t.message,variant:"destructive"})}})},NLs=[{label:"1 week",days:7},{label:"2 weeks",days:14},{label:"1 month",days:30}];function P0e({open:s,onOpenChange:t,contactId:r,contactName:n}){const[a,i]=S.useState(null),l=wLs(),o=async()=>{a&&(await l.mutateAsync({contactId:r,days:a}),i(null),t(!1))},c=d=>As(Lc(new Date,d),"MMM d, yyyy");return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"sm:max-w-md",children:[e.jsxs(Cs,{children:[e.jsxs(Ns,{className:"flex items-center gap-2",children:[e.jsx(Pn,{className:"h-5 w-5"}),"Snooze Touch"]}),e.jsxs(nn,{children:["Postpone the next scheduled touch for ",n,". Select how long to snooze."]})]}),e.jsx("div",{className:"space-y-3 py-4",children:NLs.map(d=>e.jsxs("button",{type:"button",onClick:()=>i(d.days),className:Ft("w-full flex items-center justify-between p-3 rounded-lg border transition-colors",a===d.days?"border-primary bg-primary/5":"border-border hover:border-primary/50 hover:bg-accent/50"),children:[e.jsx("span",{className:"font-medium",children:d.label}),e.jsxs("span",{className:"text-sm text-muted-foreground flex items-center gap-1",children:[e.jsx(Nn,{className:"h-3.5 w-3.5"}),"Until ",c(d.days)]})]},d.days))}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(H,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(H,{onClick:o,disabled:!a||l.isPending,children:l.isPending?"Snoozing...":"Snooze Touch"})]})]})})}const kLs={Crown:zf,FileText:kn,Users:Ar,Globe:ld,Star:ya,Phone:Yn,MessageSquare:Gi,PenTool:Gk,Video:xn,Gift:Di};function SLs({actions:s,onMarkComplete:t,onViewScript:r,isLoading:n,buildSmsLink:a,buildEmailLink:i,onGmailCompose:l}){const o=Fr(),[c,d]=S.useState("name"),[h,m]=S.useState("asc"),[p,x]=S.useState(null),[y,_]=S.useState(""),b=A=>{c===A?m(D=>D==="asc"?"desc":"asc"):(d(A),m("asc"))},j=S.useMemo(()=>[...s].sort((A,D)=>{var z,O;let R=0;switch(c){case"name":{const $=`${A.contact.first_name} ${A.contact.last_name||""}`.toLowerCase(),ee=`${D.contact.first_name} ${D.contact.last_name||""}`.toLowerCase();R=$.localeCompare(ee);break}case"relationship_type":R=(A.relationshipTypeName||"").localeCompare(D.relationshipTypeName||"");break;case"action_type":R=(((z=A.actionType)==null?void 0:z.name)||"").localeCompare(((O=D.actionType)==null?void 0:O.name)||"");break;case"last_touch":R=(A.monthNumber||0)-(D.monthNumber||0);break}return h==="asc"?R:-R}),[s,c,h]),k=A=>kLs[A||"Phone"]||Yn,T=({field:A,children:D})=>e.jsxs(H,{variant:"ghost",size:"sm",className:"h-8 -ml-3 font-medium",onClick:()=>b(A),children:[D,c===A?h==="asc"?e.jsx(Hu,{className:"ml-2 h-4 w-4"}):e.jsx(fm,{className:"ml-2 h-4 w-4"}):e.jsx(qu,{className:"ml-2 h-4 w-4 opacity-50"})]}),E=(A,D,R)=>{x(A),_(`${D} ${R||""}`.trim())};return s.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx("p",{children:"No actions scheduled for today."}),e.jsx("p",{className:"text-sm mt-1",children:"Add contacts and enable touchpoint plans to get started."})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"border rounded-lg overflow-hidden",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Vs,{className:"bg-muted/50",children:[e.jsx(At,{className:"w-[180px]",children:e.jsx(T,{field:"name",children:"Contact"})}),e.jsx(At,{className:"w-[130px]",children:e.jsx(T,{field:"relationship_type",children:"Type"})}),e.jsx(At,{className:"w-[120px]",children:e.jsx(T,{field:"action_type",children:"Action"})}),e.jsx(At,{className:"w-[130px]",children:"Phone"}),e.jsx(At,{className:"w-[200px]",children:"Quick Actions"})]})}),e.jsx(da,{children:j.map((A,D)=>{var Z,J,K,re,ie,ce;const R=A.isSpecialDate,z=A.specialDateType,O=R?z==="birthday"?gm:Fn:k(((Z=A.actionType)==null?void 0:Z.icon)||null),$=A.contact.phone,ee=A.contact.email;return e.jsxs(Vs,{className:Ft("hover:bg-muted/50 transition-colors",R&&z==="birthday"&&"bg-pink-50/50 dark:bg-pink-950/20",R&&z==="anniversary"&&"bg-purple-50/50 dark:bg-purple-950/20"),children:[e.jsx(gt,{className:"font-medium",children:e.jsx("div",{children:e.jsxs("button",{onClick:()=>o(`/mission-control/contacts/${A.contact.id}`),className:"truncate max-w-[160px] text-left hover:text-primary hover:underline transition-colors",children:[A.contact.first_name," ",A.contact.last_name]})})}),e.jsx(gt,{children:A.relationshipTypeName?e.jsx(Xe,{variant:"secondary",className:"text-xs",children:A.relationshipTypeName}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsx(gt,{children:e.jsx("div",{className:"flex items-center gap-1.5",children:R?e.jsx(Xe,{className:Ft("gap-1",z==="birthday"&&"bg-pink-500 hover:bg-pink-600",z==="anniversary"&&"bg-purple-500 hover:bg-purple-600"),children:z==="birthday"?e.jsxs(e.Fragment,{children:[e.jsx(gm,{className:"h-3 w-3"})," Birthday"]}):e.jsxs(e.Fragment,{children:[e.jsx(Fn,{className:"h-3 w-3"})," Anniversary"]})}):e.jsxs(Xe,{variant:"outline",className:"gap-1",children:[e.jsx(O,{className:"h-3 w-3"}),(J=A.actionType)==null?void 0:J.name]})})}),e.jsx(gt,{children:$?e.jsx("span",{className:"text-sm font-mono",children:A.contact.phone}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[$&&e.jsx("a",{href:`tel:${A.contact.phone}`,className:"p-1.5 rounded bg-primary/10 hover:bg-primary/20 text-primary transition-colors",title:"Call",children:e.jsx(Yn,{className:"h-3.5 w-3.5"})}),$&&e.jsx("a",{href:a(A.contact.phone,(K=A.script)==null?void 0:K.script_body,A.contact),className:"p-1.5 rounded bg-emerald-500/10 hover:bg-emerald-500/20 text-emerald-600 dark:text-emerald-400 transition-colors",title:"Text",children:e.jsx(Gi,{className:"h-3.5 w-3.5"})}),ee&&(l?e.jsx("button",{onClick:()=>l({id:A.contact.id,first_name:A.contact.first_name,last_name:A.contact.last_name,email:A.contact.email}),className:"p-1.5 rounded bg-sky-500/10 hover:bg-sky-500/20 text-sky-600 dark:text-sky-400 transition-colors",title:"Compose Email",children:e.jsx(er,{className:"h-3.5 w-3.5"})}):e.jsx("a",{href:i(A.contact.email,(re=A.script)==null?void 0:re.script_body,(ie=A.script)==null?void 0:ie.email_subject,(ce=A.actionType)==null?void 0:ce.name,A.contact),className:"p-1.5 rounded bg-sky-500/10 hover:bg-sky-500/20 text-sky-600 dark:text-sky-400 transition-colors",title:"Email",children:e.jsx(er,{className:"h-3.5 w-3.5"})})),R&&e.jsxs("button",{onClick:()=>{const ne=`${A.contact.first_name}${A.contact.last_name?" "+A.contact.last_name:""}`,le=z==="birthday"?"birthday":"home_anniversary",be=new URLSearchParams({cardType:le,contactId:A.contact.id,name:ne,...A.contact.address?{address:A.contact.address}:{},...z==="anniversary"&&A.contact.home_anniversary?{date:A.contact.home_anniversary}:{}});o(`/mission-control/card-studio?${be.toString()}`)},className:Ft("h-7 px-2 rounded text-xs font-semibold flex items-center gap-1 transition-colors",z==="birthday"?"bg-pink-500/15 hover:bg-pink-500/25 text-pink-600 dark:text-pink-400":"bg-purple-500/15 hover:bg-purple-500/25 text-purple-600 dark:text-purple-400"),title:`Send ${z==="birthday"?"Birthday":"Anniversary"} Card`,children:[e.jsx(er,{className:"h-3.5 w-3.5"}),"Send Card"]}),e.jsx(H,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-foreground",onClick:()=>E(A.contact.id,A.contact.first_name,A.contact.last_name),title:"Snooze",children:e.jsx(Hf,{className:"h-3.5 w-3.5"})}),e.jsxs(H,{variant:"default",size:"sm",className:"h-7 px-2 text-xs ml-1",onClick:()=>{var ne;return t(A.contact.id,A.actionType.id,(ne=A.script)==null?void 0:ne.id)},disabled:n,children:[e.jsx(ea,{className:"h-3.5 w-3.5 mr-1"}),"Done"]})]})})]},`${A.contact.id}-${D}`)})})]})}),e.jsx(P0e,{open:!!p,onOpenChange:A=>!A&&x(null),contactId:p||"",contactName:y})]})}function CLs({onSelect:s}){const[t,r]=S.useState(null),{data:n=[],isLoading:a}=yt({queryKey:["agent-email-template-categories"],queryFn:async()=>{const{data:c,error:d}=await V.from("email_template_categories").select("*").order("sort_order");if(d)throw d;return c}}),{data:i=[],isLoading:l}=yt({queryKey:["agent-email-templates",t],queryFn:async()=>{let c=V.from("agent_email_templates").select("*").eq("is_active",!0).order("sort_order");t&&(c=c.eq("category_id",t));const{data:d,error:h}=await c;if(h)throw h;return d}}),o=n.find(c=>c.id===t);return a?e.jsx("div",{className:"flex items-center justify-center py-6",children:e.jsx(is,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):t?e.jsxs("div",{className:"space-y-2",children:[e.jsxs("button",{onClick:()=>r(null),className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(fl,{className:"h-3.5 w-3.5"}),"Back to categories"]}),e.jsxs("p",{className:"text-xs font-medium flex items-center gap-1.5",children:[e.jsx("span",{children:o==null?void 0:o.icon})," ",o==null?void 0:o.name]}),l?e.jsx("div",{className:"flex items-center justify-center py-6",children:e.jsx(is,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):i.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No templates in this category"}):e.jsx(Ci,{className:"max-h-[280px]",children:e.jsx("div",{className:"space-y-1",children:i.map(c=>e.jsxs("button",{onClick:()=>s(c),className:"w-full p-2.5 rounded-lg border hover:bg-accent transition-colors text-left",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"font-medium text-sm",children:c.title}),c.tone&&e.jsx(Xe,{variant:"secondary",className:"text-[10px] shrink-0",children:c.tone})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-1",children:c.subject})]},c.id))})})]}):e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground px-1 mb-2",children:"Select a category"}),e.jsx("div",{className:"max-h-[200px] overflow-y-auto space-y-1 pr-1",children:n.map(c=>e.jsxs("button",{onClick:()=>r(c.id),className:"w-full flex items-center justify-between p-2.5 rounded-lg border hover:bg-accent transition-colors text-left",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("span",{className:"text-lg",children:c.icon}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:c.name}),c.description&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-1",children:c.description})]})]}),e.jsx($a,{className:"h-4 w-4 text-muted-foreground shrink-0"})]},c.id))})]})}function L0e(){const{user:s}=Ms(),t=ns(),{data:r,isLoading:n}=yt({queryKey:["contact-intake-page",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return null;const{data:d,error:h}=await V.from("contact_intake_pages").select("*").eq("user_id",s.id).maybeSingle();if(h)throw h;return d},enabled:!!(s!=null&&s.id)}),a=Pt({mutationFn:async d=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{data:h,error:m}=await V.from("contact_intake_pages").insert({user_id:s.id,slug:d.toLowerCase().replace(/[^a-z0-9-]/g,"-")}).select().single();if(m)throw m;return h},onSuccess:()=>{t.invalidateQueries({queryKey:["contact-intake-page"]}),he.success("Connect page created!")},onError:d=>{var h;(h=d.message)!=null&&h.includes("duplicate")?he.error("That slug is already taken. Try another."):he.error("Failed to create page")}}),i=Pt({mutationFn:async d=>{if(!(r!=null&&r.id))throw new Error("No intake page");const{error:h}=await V.from("contact_intake_pages").update({...d,updated_at:new Date().toISOString()}).eq("id",r.id);if(h)throw h},onSuccess:()=>{t.invalidateQueries({queryKey:["contact-intake-page"]}),he.success("Page updated!")},onError:()=>he.error("Failed to update page")}),{data:l=[],isLoading:o}=yt({queryKey:["contact-intake-submissions",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return[];const{data:d,error:h}=await V.from("contact_intake_submissions").select("*").eq("agent_user_id",s.id).order("created_at",{ascending:!1}).limit(100);if(h)throw h;return d},enabled:!!(s!=null&&s.id)}),c=Pt({mutationFn:async d=>{if(!(r!=null&&r.id))throw new Error("No intake page. Create your Connect page first.");const{data:h,error:m}=await V.from("contact_intake_tokens").insert({contact_id:d,intake_page_id:r.id}).select("token").single();if(m)throw m;return`${window.location.origin}/connect/${r.slug}?t=${h.token}`}});return{intakePage:r,isLoading:n,createPage:a,updatePage:i,submissions:l,loadingSubmissions:o,generateUpdateLink:c}}function TLs({value:s,onChange:t,userId:r,placeholder:n}){const[a,i]=S.useState(!1),[l,o]=S.useState([]),[c,d]=S.useState(!1),[h,m]=S.useState(0),p=S.useRef(null),x=S.useRef(null);S.useEffect(()=>{const _=b=>{p.current&&!p.current.contains(b.target)&&i(!1)};return document.addEventListener("mousedown",_),()=>document.removeEventListener("mousedown",_)},[]),S.useEffect(()=>{x.current&&clearTimeout(x.current);const _=s.trim();if(!r||_.length<1||_.includes("@")&&_.indexOf("@")>0&&/\S+@\S+\.\S+/.test(_)){o([]);return}return x.current=setTimeout(async()=>{d(!0);const b=`%${_}%`,j=V,{data:k,error:T}=await j.from("innercircle_contacts").select("id, first_name, last_name, email").eq("owner_user_id",r).not("email","is",null).or(`first_name.ilike.${b},last_name.ilike.${b},email.ilike.${b}`).order("first_name",{ascending:!0}).limit(8);d(!1),!T&&k&&(o(k),m(0),i(k.length>0))},180),()=>{x.current&&clearTimeout(x.current)}},[s,r]);const y=_=>{_.email&&(t(_.email),i(!1))};return e.jsxs("div",{ref:p,className:"relative",children:[e.jsx(Se,{id:"gmail-to",value:s,onChange:_=>t(_.target.value),onFocus:()=>l.length>0&&i(!0),onKeyDown:_=>{!a||l.length===0||(_.key==="ArrowDown"?(_.preventDefault(),m(b=>Math.min(b+1,l.length-1))):_.key==="ArrowUp"?(_.preventDefault(),m(b=>Math.max(b-1,0))):_.key==="Enter"?(_.preventDefault(),y(l[h])):_.key==="Escape"&&i(!1))},placeholder:n||"Start typing a name or email...",autoComplete:"off"}),a&&e.jsx("div",{className:"absolute z-50 mt-1 w-full rounded-md border bg-popover shadow-lg max-h-72 overflow-y-auto",children:c&&l.length===0?e.jsxs("div",{className:"px-3 py-2 text-sm text-muted-foreground flex items-center gap-2",children:[e.jsx(is,{className:"h-3 w-3 animate-spin"})," Searching..."]}):l.map((_,b)=>{const j=[_.first_name,_.last_name].filter(Boolean).join(" ")||"(No name)";return e.jsxs("button",{type:"button",onMouseEnter:()=>m(b),onClick:()=>y(_),className:`w-full flex items-center gap-2 px-3 py-2 text-left text-sm border-b last:border-b-0 ${b===h?"bg-accent":"bg-popover"}`,children:[e.jsx(io,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"font-medium truncate",children:j}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:_.email})]})]},_.id)})})]})}const ELs=5*1024*1024,a2=50,ALs=["application/pdf","image/jpeg","image/png","image/gif","image/webp","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","text/csv"];function MLs(s){return s<1024?s+" B":s<1024*1024?(s/1024).toFixed(1)+" KB":(s/(1024*1024)).toFixed(1)+" MB"}function ILs(s){return new Promise((t,r)=>{const n=new FileReader;n.onload=()=>{const a=n.result;t(a.split(",")[1])},n.onerror=r,n.readAsDataURL(s)})}function wN(s,t){let r=s.replace(/\{\{first_name\}\}/gi,t.first_name).replace(/\{\{last_name\}\}/gi,t.last_name||"").replace(/\{\{full_name\}\}/gi,`${t.first_name} ${t.last_name||""}`.trim());return t.updateLink&&(r=r.replace(/\{\{update_link\}\}/gi,t.updateLink)),r}function X_({open:s,onOpenChange:t,contact:r,bulkContacts:n,defaultSubject:a="",defaultBody:i="",gmailEmail:l,onSendComplete:o}){const{user:c}=Ms(),d=ns(),{isReady:h,settings:m}=Dz(),{intakePage:p}=L0e(),x=p?`https://contacts.relevelup.com/${p.slug}`:null,y=!!n&&n.length>0,_=h&&(y||!l),b=y?n:r?[r]:[],j=b[0],k=y?Math.ceil(b.length/a2):1,T=y&&b.length>a2,[E,A]=S.useState((j==null?void 0:j.email)||""),[D,R]=S.useState(a),[z,O]=S.useState(i),[$,ee]=S.useState(!1),[Z,J]=S.useState(!1),[K,re]=S.useState([]),[ie,ce]=S.useState(a),[ne,le]=S.useState(i),[be,fe]=S.useState("composing"),[je,ve]=S.useState(0),[We,Ve]=S.useState(0),[Le,Me]=S.useState(0),[ze,Pe]=S.useState(0),Ie=S.useRef(!1),[De,pe]=S.useState(null);S.useEffect(()=>{s&&(A((j==null?void 0:j.email)||""),ce(a),le(i),R(wN(a,j||{first_name:""})),O(wN(i,j||{first_name:""})),J(!a&&!i),re([]),fe("composing"),ve(0),Ve(0),Me(0),Pe(0),Ie.current=!1,pe(null))},[s,j,a,i]);const tt=async at=>{const rt=at.target.files;if(!rt)return;const Et=K.reduce((Is,lr)=>Is+lr.size,0),hs=[];for(const Is of Array.from(rt)){if(!ALs.includes(Is.type)){he.error(`${Is.name}: Unsupported file type`);continue}if(Et+Is.size>ELs){he.error("Total attachments exceed 5MB limit");break}try{const lr=await ILs(Is);hs.push({name:Is.name,type:Is.type,size:Is.size,data:lr})}catch{he.error(`Failed to read ${Is.name}`)}}re(Is=>[...Is,...hs]),at.target.value=""},ge=at=>{re(rt=>rt.filter((Et,hs)=>hs!==at))},ct=at=>{ce(at.subject),le(at.body),R(wN(at.subject,j||{first_name:""})),O(wN(at.body,j||{first_name:""})),J(!1)},Ue=at=>at.split(/\n\n+/).map(rt=>`

${rt.replace(/\n/g,"
")}

`).join(""),et=async at=>{if(!(at!=null&&at.email))return he.error("Please enter a recipient email"),!1;const rt=at||{first_name:""},Et=wN(ie,rt),hs=wN(ne,rt),Is=Ue(hs);try{if(_){const lr=(m==null?void 0:m.display_name)||"ReLevelUp",us=`${lr.toLowerCase().replace(/[^a-z]/g,".")}@send.relevelup.com`,St=`${lr} <${us}>`,{data:xs,error:kt}=await V.functions.invoke("ses-send-campaign",{body:{action:"test_send",to:at.email,from_email:St,subject:Et,body_html:Is,reply_to:(m==null?void 0:m.reply_to_email)||void 0}});if(kt)throw kt;if(!(xs!=null&&xs.success))throw new Error((xs==null?void 0:xs.error)||"Failed to send")}else{const{data:lr,error:us}=await V.functions.invoke("gmail-send",{body:{to:at.email,subject:Et,body:Is,contactId:at.id||void 0,attachments:K.map(({name:St,type:xs,data:kt})=>({name:St,type:xs,data:kt}))}});if(us)throw us;if(!(lr!=null&&lr.success))throw new Error((lr==null?void 0:lr.error)||"Failed to send")}return c&&at.id&&await V.from("bulk_email_sends").insert({user_id:c.id,contact_id:at.id,contact_email:at.email,subject:Et,source:_?"ses_bulk":"sphere_gaps"}),!0}catch(lr){return console.error("Send error:",lr),he.error("Failed to send to "+at.first_name+": "+(lr instanceof Error?lr.message:"Unknown error")),!1}},Qe=()=>{const at=je*a2;return b.slice(at,at+a2)},Ne=async()=>{if(!D||!z){he.error("Please fill in subject and message");return}const at=Qe();ee(!0),fe("sending");let rt=0,Et=0;for(let Is=0;IssetTimeout(us,150));Ve(Is=>Is+rt),Me(Is=>Is+Et),ee(!1),d.invalidateQueries({queryKey:["bulk-email-sends"]}),je>=k-1||Ie.current?fe("all_done"):fe("batch_complete")},$e=async()=>{if(!D||!z){he.error("Please fill in subject and message");return}if(!y){const at=j||{id:"",first_name:"",last_name:"",email:E.trim()};if(!at.email){he.error("Please enter a recipient email");return}ee(!0);try{await et(at)&&(d.invalidateQueries({queryKey:["bulk-email-sends"]}),he.success("Email sent successfully!"),t(!1),o==null||o())}finally{ee(!1)}return}await Ne()},it=async()=>{ve(at=>at+1),Pe(0),await new Promise(at=>setTimeout(at,50)),await Ne()};S.useEffect(()=>{},[je]);const Je=()=>{if($){Ie.current=!0;return}t(!1),o==null||o()},st=je*a2,mt=Math.min(st+a2,b.length),wt=y&&b.length>0?Math.round((We+Le)/b.length*100):0;return e.jsx(bs,{open:s,onOpenChange:Je,children:e.jsxs(vs,{className:"sm:max-w-[600px] max-h-[90vh] overflow-y-auto",children:[e.jsxs(Cs,{children:[e.jsxs(Ns,{className:"flex items-center gap-2",children:[e.jsx(er,{className:`h-5 w-5 ${_?"text-orange-500":"text-red-500"}`}),y?`Send to ${b.length} Contacts`:"Compose Email"]}),_?e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Sending via ",e.jsx("span",{className:"font-medium",children:"Mass Email"})," (reply-to: ",m==null?void 0:m.reply_to_email,")"]}):l?e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Sending from ",e.jsx("span",{className:"font-medium",children:l})]}):null,y&&be==="composing"&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Composing email for ",e.jsxs("span",{className:"font-medium",children:[b.length," contacts"]}),". You'll review each personalized email before sending."]})]}),be==="sending"&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx(is,{className:"h-8 w-8 animate-spin mx-auto text-primary"}),e.jsxs("p",{className:"font-medium",children:["Sending batch ",je+1," of ",k,"..."]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[ze," of ",Qe().length," in this batch"]})]}),e.jsx(Mi,{value:ze/Qe().length*100,className:"h-2"}),e.jsxs("div",{className:"flex justify-between text-xs text-muted-foreground",children:[e.jsxs("span",{children:["Overall: ",We+Le," / ",b.length]}),e.jsxs("span",{children:[We," sent • ",Le," failed"]})]}),e.jsx(H,{variant:"outline",size:"sm",className:"w-full",onClick:()=>{Ie.current=!0},children:"Stop Sending"})]}),be==="batch_complete"&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx(ea,{className:"h-8 w-8 text-emerald-500 mx-auto"}),e.jsxs("p",{className:"font-medium",children:["Batch ",je+1," Complete!"]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[We," sent, ",Le," failed so far"]})]}),e.jsx(Mi,{value:wt,className:"h-2"}),e.jsxs("p",{className:"text-xs text-center text-muted-foreground",children:[b.length-We-Le," contacts remaining (",k-je-1," batches left)"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(H,{variant:"outline",className:"flex-1",onClick:Je,children:"Done for Now"}),e.jsxs(H,{className:"flex-1 gap-2",onClick:it,children:[e.jsx(yn,{className:"h-4 w-4"}),"Send Next ",Math.min(a2,b.length-mt)," Contacts"]})]})]}),be==="all_done"&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx(ea,{className:"h-10 w-10 text-emerald-500 mx-auto"}),e.jsx("p",{className:"font-semibold text-lg",children:"All Done!"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[We," emails sent successfully",Le>0&&e.jsxs("span",{className:"text-destructive",children:[" • ",Le," failed"]})]})]}),e.jsx(H,{className:"w-full",onClick:Je,children:"Close"})]}),be==="composing"&&e.jsxs("div",{className:"space-y-4",children:[Z?e.jsxs("div",{className:"border rounded-lg p-3 bg-muted/30 max-h-[50vh] overflow-y-auto",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("p",{className:"text-sm font-medium flex items-center gap-1.5",children:[e.jsx(kn,{className:"h-4 w-4"})," Choose a Template"]}),e.jsxs(H,{variant:"ghost",size:"sm",onClick:()=>J(!1),className:"h-7 px-2 text-xs",children:[e.jsx(Rr,{className:"h-3 w-3 mr-1"})," Write from scratch"]})]}),e.jsx(CLs,{onSelect:ct})]}):e.jsxs(H,{variant:"outline",size:"sm",className:"gap-2",onClick:()=>J(!0),children:[e.jsx(kn,{className:"h-4 w-4"}),"Browse Templates"]}),e.jsx(Qo,{}),!y&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{htmlFor:"gmail-to",children:"To"}),e.jsx(TLs,{value:E,onChange:A,userId:c==null?void 0:c.id})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{htmlFor:"gmail-subject",children:"Subject"}),e.jsx(Se,{id:"gmail-subject",value:D,onChange:at=>{R(at.target.value),ce(at.target.value)},placeholder:"Enter subject..."})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ue,{htmlFor:"gmail-body",children:"Message"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(Xe,{variant:"outline",className:"text-[10px] cursor-pointer hover:bg-accent",onClick:()=>{O(at=>at+"{{first_name}}"),le(at=>at+"{{first_name}}")},children:"{{first_name}}"}),e.jsx(Xe,{variant:"outline",className:"text-[10px] cursor-pointer hover:bg-accent",onClick:()=>{O(at=>at+"{{last_name}}"),le(at=>at+"{{last_name}}")},children:"{{last_name}}"}),x&&e.jsx(Xe,{variant:"outline",className:"text-[10px] cursor-pointer hover:bg-primary/10 border-primary/40 text-primary",onClick:()=>{const at=` When you get a sec, can you share your latest contact info with me? It only takes about a minute: ${x} `;O(rt=>rt+at),le(rt=>rt+at)},title:"Insert your Connect Page link",children:"+ Connect Page"})]})]}),e.jsx(vr,{id:"gmail-body",value:z,onChange:at=>{O(at.target.value),le(at.target.value)},placeholder:"Write your message...",rows:10,className:"resize-y"}),y&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Use ","{{first_name}}",", ","{{last_name}}"," to personalize. You'll preview each recipient's email in the next step."]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(H,{type:"button",variant:"outline",size:"sm",className:"gap-2",onClick:()=>{var at;return(at=document.getElementById("gmail-attachments"))==null?void 0:at.click()},disabled:$,children:[e.jsx(Hk,{className:"h-4 w-4"}),"Attach Files"]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"PDF, images, Word, Excel (max 5MB total)"}),e.jsx("input",{id:"gmail-attachments",type:"file",multiple:!0,accept:".pdf,.jpg,.jpeg,.png,.gif,.webp,.doc,.docx,.xls,.xlsx,.csv",className:"hidden",onChange:tt})]}),K.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2",children:K.map((at,rt)=>e.jsxs(Xe,{variant:"secondary",className:"gap-1.5 pl-2 pr-1 py-1",children:[e.jsx(Hk,{className:"h-3 w-3"}),e.jsx("span",{className:"max-w-[140px] truncate text-xs",children:at.name}),e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["(",MLs(at.size),")"]}),e.jsx("button",{type:"button",onClick:()=>ge(rt),className:"ml-0.5 rounded-full p-0.5 hover:bg-muted",children:e.jsx(Rr,{className:"h-3 w-3"})})]},rt))})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(H,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),y?e.jsxs(H,{onClick:()=>{pe(b[0]||null),fe("reviewing")},disabled:!D||!z,className:"gap-2",children:["Review Emails",e.jsx(bi,{className:"h-4 w-4"})]}):e.jsxs(H,{onClick:$e,disabled:$||!D||!z||!E.trim(),className:"gap-2",children:[$?e.jsx(is,{className:"h-4 w-4 animate-spin"}):e.jsx(yn,{className:"h-4 w-4"}),$?"Sending...":"Send Email"]})]})]}),be==="reviewing"&&y&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("p",{className:"text-xs text-primary bg-primary/10 rounded-md px-2.5 py-1.5",children:["✉️ Click any recipient below to preview the ",e.jsx("span",{className:"font-semibold",children:"exact personalized email"})," they will receive."]}),T&&e.jsxs("p",{className:"text-xs text-amber-600 bg-amber-500/10 rounded-md px-2.5 py-1.5",children:["📦 ",b.length," contacts will be sent in ",k," batches of up to ",a2,". You'll confirm before each batch."]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(ue,{children:["Recipients (",b.length,")"]}),e.jsx("div",{className:"bg-muted p-1.5 rounded-md space-y-0.5 max-h-32 overflow-y-auto",children:b.map(at=>e.jsxs("div",{className:`text-sm px-2 py-1 rounded cursor-pointer transition-colors ${(De==null?void 0:De.id)===at.id?"bg-primary/10 text-primary font-medium":"text-muted-foreground hover:bg-accent hover:text-foreground"}`,onClick:()=>pe(at),children:[at.first_name," ",at.last_name," — ",at.email]},at.id))})]}),De&&e.jsxs("div",{className:"border rounded-lg p-3 bg-muted/30 space-y-2 animate-in fade-in slide-in-from-top-1",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("p",{className:"text-xs font-semibold text-primary flex items-center gap-1.5",children:[e.jsx(er,{className:"h-3.5 w-3.5"}),"Preview for ",De.first_name," ",De.last_name]})}),e.jsxs("div",{className:"space-y-1 text-sm",children:[e.jsxs("p",{children:[e.jsx("span",{className:"text-muted-foreground text-xs",children:"To:"})," ",De.email]}),e.jsxs("p",{children:[e.jsx("span",{className:"text-muted-foreground text-xs",children:"Subject:"})," ",wN(ie,De)]})]}),e.jsx(Qo,{}),e.jsx("div",{className:"text-sm whitespace-pre-wrap bg-background rounded p-2.5 max-h-40 overflow-y-auto border",children:wN(ne,De)})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsxs(H,{variant:"outline",onClick:()=>{fe("composing"),pe(null)},children:[e.jsx(za,{className:"h-4 w-4 mr-1"}),"Back to Edit"]}),e.jsxs(H,{onClick:$e,disabled:$,className:"gap-2",children:[$?e.jsx(is,{className:"h-4 w-4 animate-spin"}):e.jsx(yn,{className:"h-4 w-4"}),T?`Send First ${a2}`:`Send to ${b.length}`]})]})]})]})})}function PLs(){const s=Fr(),{data:t}=Cp(),{data:r}=oz(),n=Jge(),{isGmailConnected:a,gmailEmail:i}=cf(),[l,o]=S.useState(null),[c,d]=S.useState(!1),[h,m]=S.useState(new Set),p=jg(new Date),x=Lc(p,30),y=E=>{if(!E)return null;const A=E.split(/[-/T]/);if(A.length<3)return null;const D=parseInt(A[1],10)-1,R=parseInt(A[2],10);return isNaN(D)||isNaN(R)?null:new Date(p.getFullYear(),D,R)},_=S.useMemo(()=>{if(!t)return[];const E=[];for(const A of t){if(A.birthday){const D=y(A.birthday);D&&(Cc(D,p)||mA(D,p)&&fA(D,x))&&E.push({contact:A,type:"birthday",date:D,daysUntil:l0(D,p),dateStr:A.birthday})}if(A.home_anniversary){const D=y(A.home_anniversary);D&&(Cc(D,p)||mA(D,p)&&fA(D,x))&&E.push({contact:A,type:"anniversary",date:D,daysUntil:l0(D,p),dateStr:A.home_anniversary})}}return E.sort((A,D)=>A.daysUntil-D.daysUntil),E},[t]),b=async E=>{const A=(r==null?void 0:r.find(D=>D.name==="Call"))||(r==null?void 0:r[0]);if(A)try{await n.mutateAsync({contactId:E.contact.id,actionTypeId:A.id,notes:`${E.type==="birthday"?"Birthday":"Home Anniversary"} outreach`}),m(D=>new Set(D).add(`${E.contact.id}-${E.type}`)),En({title:"Touch logged!",description:`Logged outreach for ${E.contact.first_name}`})}catch{En({title:"Error",description:"Failed to log touch",variant:"destructive"})}},j=E=>{const A=`${E.contact.first_name}${E.contact.last_name?" "+E.contact.last_name:""}`,D=E.type==="birthday"?"birthday":"home_anniversary",R=new URLSearchParams({cardType:D,contactId:E.contact.id,name:A,...E.contact.address?{address:E.contact.address}:{},...E.type==="anniversary"&&E.dateStr?{date:E.dateStr}:{}});s(`/mission-control/card-studio?${R.toString()}`)},k=E=>E===0?"Today!":E===1?"Tomorrow":`${E} days`,T=E=>E===0?"bg-red-500/15 text-red-600 dark:text-red-400 border-red-500/30":E<=3?"bg-amber-500/15 text-amber-600 dark:text-amber-400 border-amber-500/30":E<=7?"bg-blue-500/15 text-blue-600 dark:text-blue-400 border-blue-500/30":"bg-muted text-muted-foreground border-border";return e.jsxs(e.Fragment,{children:[e.jsxs(ke,{children:[e.jsx(Ot,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(zt,{className:"text-lg flex items-center gap-2",children:[e.jsx(xu,{className:"h-5 w-5 text-primary"}),"Upcoming Milestones",e.jsx(Xe,{variant:"secondary",className:"text-xs font-normal",children:"Next 30 days"})]}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:[_.length," event",_.length!==1?"s":""]})]})}),e.jsxs(Oe,{className:"space-y-2",children:[_.length===0&&e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(gm,{className:"h-8 w-8 mx-auto mb-2 opacity-40"}),e.jsx("p",{className:"text-sm",children:"No birthdays or anniversaries in the next 30 days."}),e.jsx("p",{className:"text-xs mt-1",children:"Add dates to your contacts to see upcoming milestones here."})]}),_.map((E,A)=>{var O,$;const D=`${E.contact.id}-${E.type}`,R=h.has(D),z=`${((O=E.contact.first_name)==null?void 0:O[0])||""}${(($=E.contact.last_name)==null?void 0:$[0])||""}`.toUpperCase();return e.jsxs("div",{className:Ft("p-3 rounded-lg border transition-colors",E.daysUntil===0&&E.type==="birthday"?"bg-pink-500/10 border-pink-500/30 dark:bg-pink-900/20 dark:border-pink-800/40":E.daysUntil===0&&E.type==="anniversary"?"bg-blue-500/10 border-blue-500/30 dark:bg-blue-900/20 dark:border-blue-800/40":E.type==="birthday"?"bg-pink-50/60 border-pink-200/60 hover:bg-pink-100/60 dark:bg-pink-950/20 dark:border-pink-900/30 dark:hover:bg-pink-950/30":"bg-blue-50/60 border-blue-200/60 hover:bg-blue-100/60 dark:bg-blue-950/20 dark:border-blue-900/30 dark:hover:bg-blue-950/30"),children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"relative shrink-0",children:[e.jsx(Un,{className:Ft("h-10 w-10",E.type==="birthday"?"ring-2 ring-pink-300/50 dark:ring-pink-700/50":"ring-2 ring-blue-300/50 dark:ring-blue-700/50"),children:e.jsx(qn,{className:Ft("text-xs font-medium",E.type==="birthday"?"bg-pink-100 text-pink-700 dark:bg-pink-900/40 dark:text-pink-300":"bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-300"),children:z})}),e.jsx("span",{className:"absolute -bottom-1.5 -right-1.5 text-base leading-none drop-shadow-sm",children:E.type==="birthday"?"🎂":"🏠"})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"font-medium text-sm truncate",children:[E.contact.first_name," ",E.contact.last_name||""]}),e.jsx(Xe,{variant:"outline",className:Ft("text-[10px] shrink-0 whitespace-nowrap",T(E.daysUntil)),children:k(E.daysUntil)})]}),e.jsxs("div",{className:Ft("text-xs flex items-center gap-1.5 mt-0.5",E.type==="birthday"?"text-pink-600/80 dark:text-pink-400/80":"text-blue-600/80 dark:text-blue-400/80"),children:[E.type==="birthday"?e.jsxs(e.Fragment,{children:[e.jsx(gm,{className:"h-3 w-3"})," Birthday"]}):e.jsxs(e.Fragment,{children:[e.jsx(Fn,{className:"h-3 w-3"})," Home Anniversary"]}),e.jsx("span",{children:"·"}),e.jsx("span",{children:As(E.date,"MMM d")})]})]})]}),e.jsxs("div",{className:"flex items-center gap-1 mt-2 pl-[52px]",children:[E.contact.phone&&e.jsx(H,{variant:"ghost",size:"icon",className:"h-7 w-7",title:"Call",asChild:!0,children:e.jsx("a",{href:`tel:${E.contact.phone}`,children:e.jsx(Yn,{className:"h-3.5 w-3.5"})})}),E.contact.phone&&e.jsx(H,{variant:"ghost",size:"icon",className:"h-7 w-7",title:"Text",asChild:!0,children:e.jsx("a",{href:`sms:${E.contact.phone}`,children:e.jsx(Gi,{className:"h-3.5 w-3.5"})})}),E.contact.email&&e.jsx(H,{variant:"ghost",size:"icon",className:"h-7 w-7",title:"Email",onClick:()=>{a?(o({id:E.contact.id,first_name:E.contact.first_name,last_name:E.contact.last_name,email:E.contact.email}),d(!0)):window.location.href=`mailto:${E.contact.email}`},children:e.jsx(er,{className:"h-3.5 w-3.5"})}),e.jsx(H,{variant:"ghost",size:"icon",className:"h-7 w-7",title:"Record video",onClick:()=>s(`/mission-control/video/record?contactId=${E.contact.id}`),children:e.jsx(xn,{className:"h-3.5 w-3.5"})}),e.jsxs(H,{variant:"ghost",size:"sm",className:Ft("h-7 px-2 gap-1 text-xs",E.type==="birthday"?"text-pink-600 hover:text-pink-700 dark:text-pink-400":"text-blue-600 hover:text-blue-700 dark:text-blue-400"),title:`Send ${E.type==="birthday"?"birthday":"anniversary"} card`,onClick:()=>j(E),children:[e.jsx(Lr,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Card"})]}),e.jsx(H,{variant:"ghost",size:"icon",className:Ft("h-7 w-7",R&&"text-green-600"),title:"Log a touch",disabled:R||n.isPending,onClick:()=>b(E),children:e.jsx(ea,{className:"h-3.5 w-3.5"})}),e.jsx(H,{variant:"ghost",size:"icon",className:"h-7 w-7",title:"View contact",onClick:()=>s(`/mission-control/contacts/${E.contact.id}`),children:e.jsx(Bn,{className:"h-3.5 w-3.5"})})]})]},`${D}-${A}`)})]})]}),a&&l&&e.jsx(X_,{open:c,onOpenChange:d,contact:l,gmailEmail:i})]})}function LLs(s){const[t,r]=S.useState([]),[n,a]=S.useState(!1),{data:i,isLoading:l}=yt({queryKey:["active-visitors",s],queryFn:async()=>{if(!s)return[];try{await V.rpc("cleanup_stale_visitors")}catch{}const{data:h}=await V.from("lead_site_active_visitors").select("*").eq("lead_site_id",s).gte("last_seen_at",new Date(Date.now()-2*60*1e3).toISOString()).order("last_seen_at",{ascending:!1});if(!h)return[];const m=h.map(y=>y.contact_id).filter(Boolean);let p={};if(m.length>0){const{data:y}=await V.from("innercircle_contacts").select("id, first_name, last_name, email, phone").in("id",m);(y||[]).forEach(_=>{p[_.id]=_})}const x=h.map(y=>y.auth_user_id).filter(Boolean);if(x.length>0){const{data:y}=await V.from("lead_site_consumer_profiles").select("user_id, name, phone, contact_id").eq("lead_site_id",s).in("user_id",x);(y||[]).forEach(_=>{const b=h.find(j=>j.auth_user_id===_.user_id);b&&!b.contact_id&&_.contact_id&&(b.contact_id=_.contact_id),b&&!p[b.contact_id||""]&&_.name&&(p[b.contact_id||b.auth_user_id||""]={first_name:_.name.split(" ")[0],last_name:_.name.split(" ").slice(1).join(" ")||null,email:null,phone:_.phone})})}return h.map(y=>{var _,b;return{...y,contact_name:p[y.contact_id||y.auth_user_id||""]?`${p[y.contact_id||y.auth_user_id||""].first_name} ${p[y.contact_id||y.auth_user_id||""].last_name||""}`.trim():null,contact_email:((_=p[y.contact_id||y.auth_user_id||""])==null?void 0:_.email)||null,contact_phone:((b=p[y.contact_id||y.auth_user_id||""])==null?void 0:b.phone)||null}})},enabled:!!s,refetchInterval:6e4});S.useEffect(()=>{if(!s)return;const h=V.channel(`active-visitors-${s}`).on("postgres_changes",{event:"*",schema:"public",table:"lead_site_active_visitors",filter:`lead_site_id=eq.${s}`},m=>{m.eventType==="INSERT"?r(p=>p.find(y=>y.id===m.new.id)?p:[m.new,...p]):m.eventType==="UPDATE"?r(p=>p.map(x=>x.id===m.new.id?{...x,...m.new}:x)):m.eventType==="DELETE"&&r(p=>p.filter(x=>x.id!==m.old.id))}).subscribe(m=>{m==="SUBSCRIBED"&&a(!0)});return()=>{V.removeChannel(h)}},[s]);const o=n&&t.length>0?DLs([...t,...i||[]]):i||[],c=Date.now(),d=o.filter(h=>c-new Date(h.last_seen_at).getTime()<2*60*1e3);return{activeVisitors:d,isLoading:l,count:d.length}}function DLs(s){const t=new Set;return s.filter(r=>t.has(r.id)?!1:(t.add(r.id),!0))}const RLs={property_view:{label:"Viewed",icon:Bn,color:"text-blue-500",bgColor:"bg-blue-500/10"},new_lead:{label:"New Lead",icon:Vl,color:"text-emerald-500",bgColor:"bg-emerald-500/10"},saved_listing:{label:"Saved",icon:Bi,color:"text-rose-500",bgColor:"bg-rose-500/10"}};function OLs(){const{user:s}=Ms(),t=Fr(),{isGmailConnected:r,gmailEmail:n}=cf(),{leadSite:a}=av(),{count:i}=LLs(a==null?void 0:a.id),[l,o]=S.useState(!1),[c,d]=S.useState(null),{data:h,isLoading:m}=yt({queryKey:["lead-site-activity",s==null?void 0:s.id],queryFn:async()=>{const{data:j,error:k}=await V.rpc("get_lead_site_activity",{_user_id:s.id});if(k)throw k;return j},enabled:!!s,refetchInterval:6e4});if(m||!(h!=null&&h.has_site))return null;const p=(h.activities||[]).filter(j=>j.visitor_name&&j.visitor_name!=="Site Visitor"),x=p.filter(j=>j.activity_type==="new_lead"),y=(h.activities||[]).filter(j=>j.activity_type==="property_view").length,_=(h.activities||[]).filter(j=>j.activity_type==="saved_listing").length,b=j=>{if(j.visitor_email)if(r){const k=(j.visitor_name||"").split(" ");d({id:j.contact_id||"",first_name:k[0]||"",last_name:k.slice(1).join(" ")||null,email:j.visitor_email}),o(!0)}else window.location.href=`mailto:${j.visitor_email}`};return e.jsxs("section",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"p-1.5 bg-primary/10 rounded-lg",children:e.jsx(ld,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Website Activity"}),i>0&&e.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 text-[11px] font-semibold",children:[e.jsxs("span",{className:"relative flex h-1.5 w-1.5",children:[e.jsx("span",{className:"animate-ping absolute inline-flex h-full w-full rounded-full bg-emerald-400 opacity-75"}),e.jsx("span",{className:"relative inline-flex rounded-full h-1.5 w-1.5 bg-emerald-500"})]}),i," Live"]})]})]}),e.jsxs(H,{variant:"ghost",size:"sm",className:"text-primary gap-1",onClick:()=>t("/mission-control/website-activity"),children:["View All",e.jsx(bi,{className:"h-4 w-4"})]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2 p-3 rounded-lg bg-emerald-500/5 border border-emerald-200 dark:border-emerald-800",children:[e.jsx(Vl,{className:"h-4 w-4 text-emerald-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-bold text-emerald-600 dark:text-emerald-400",children:x.length}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"New Leads"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 p-3 rounded-lg bg-blue-500/5 border border-blue-200 dark:border-blue-800",children:[e.jsx(Bn,{className:"h-4 w-4 text-blue-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-bold text-blue-600 dark:text-blue-400",children:y}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Views"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 p-3 rounded-lg bg-rose-500/5 border border-rose-200 dark:border-rose-800",children:[e.jsx(Bi,{className:"h-4 w-4 text-rose-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-bold text-rose-600 dark:text-rose-400",children:_}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Saved"})]})]})]}),p.length>0?e.jsxs("div",{className:"space-y-2",children:[p.slice(0,5).map((j,k)=>{const T=RLs[j.activity_type],E=T.icon,A=Hl(new Date(j.occurred_at),{addSuffix:!0});return e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg border bg-card hover:shadow-sm transition-shadow",children:[e.jsx("div",{className:`p-1.5 rounded-md ${T.bgColor}`,children:e.jsx(E,{className:`h-3.5 w-3.5 ${T.color}`})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("button",{className:"font-medium text-sm text-primary hover:underline text-left truncate block",onClick:()=>{j.contact_id&&t(`/mission-control/contacts/${j.contact_id}`)},children:j.visitor_name}),e.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-muted-foreground",children:[e.jsx("span",{children:T.label}),j.mls_number&&e.jsxs("span",{children:["· MLS# ",j.mls_number]}),j.lead_type&&e.jsxs("span",{children:["· ",j.lead_type]}),e.jsxs("span",{children:["· ",A]})]})]}),e.jsxs("div",{className:"flex items-center gap-0.5 shrink-0",children:[j.visitor_email&&e.jsx(H,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-primary",onClick:()=>b(j),children:e.jsx(er,{className:"h-3.5 w-3.5"})}),j.visitor_phone&&e.jsxs(e.Fragment,{children:[e.jsx(H,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-primary",onClick:()=>window.location.href=`tel:${j.visitor_phone}`,children:e.jsx(Yn,{className:"h-3.5 w-3.5"})}),e.jsx(H,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-primary",onClick:()=>window.location.href=`sms:${j.visitor_phone}`,children:e.jsx(Gi,{className:"h-3.5 w-3.5"})})]}),j.contact_id&&e.jsx(H,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>t(`/mission-control/contacts/${j.contact_id}`),children:e.jsx($a,{className:"h-3.5 w-3.5"})})]})]},`${j.activity_type}-${j.occurred_at}-${k}`)}),p.length>5&&e.jsxs(H,{variant:"outline",className:"w-full text-xs",onClick:()=>t("/mission-control/website-activity"),children:["View ",p.length-5," more activities",e.jsx(bi,{className:"h-3.5 w-3.5 ml-1"})]})]}):e.jsx(ke,{children:e.jsxs(Oe,{className:"p-6 text-center",children:[e.jsx(ef,{className:"h-8 w-8 text-muted-foreground/30 mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No actionable website activity yet."}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:y>0?`${y} anonymous listing views recorded.`:"Lead engagement will appear here as visitors interact with your site."}),e.jsxs(H,{variant:"outline",size:"sm",className:"mt-3",onClick:()=>t("/mission-control/website-activity"),children:["View Full Activity",e.jsx(bi,{className:"h-3.5 w-3.5 ml-1"})]})]})}),r&&c&&e.jsx(X_,{open:l,onOpenChange:o,contact:c,gmailEmail:n})]})}const LHe={Crown:zf,FileText:kn,Users:Ar,Globe:ld,Star:ya,Phone:Yn,MessageSquare:Gi,PenTool:Gk,Video:xn,Gift:Di},FLs={"Top 25":"bg-primary text-primary-foreground","Past Client":"bg-sky-500 text-white","Referral Partner":"bg-orange-500 text-white",Sphere:"bg-emerald-500 text-white",VIP:"bg-amber-500 text-white"};function BLs(){var $e,it,Je,st,mt,wt;const s=Fr(),{user:t}=Ms(),{data:r}=R0(),{data:n}=uot(),{data:a}=Cp(),{data:i}=oz(),{data:l}=got(),o=oHt(),c=bTe(),d=aHt(90),h=Jge(),[m,p]=S.useState(null),[x,y]=S.useState(null),[_,b]=S.useState(!1),[j,k]=S.useState(""),[T,E]=S.useState(!1),[A,D]=S.useState(""),[R,z]=S.useState(rme()),[O,$]=S.useState("cards"),[ee,Z]=S.useState(!1),[J,K]=S.useState(null),[re,ie]=S.useState(null),[ce,ne]=S.useState(""),{isGmailConnected:le,gmailEmail:be}=cf(),fe=()=>{const at=parseInt(A,10);if(isNaN(at)||at<1){En({title:"Invalid goal",description:"Please enter a number greater than 0",variant:"destructive"});return}z(at),pot(at),E(!1),En({title:"Goal updated",description:`Weekly touch goal set to ${at}`})},je=()=>{D(R.toString()),E(!0)};S.useEffect(()=>{(async()=>{if(!(t!=null&&t.id))return;const{data:rt}=await V.from("profiles").select("name").eq("id",t.id).single();rt!=null&&rt.name&&k(rt.name.split(" ")[0])})()},[t==null?void 0:t.id]),S.useEffect(()=>{o.mutate()},[]);const ve=jg(new Date),We=Lc(ve,7),Ve=at=>{if(!at)return null;const rt=at.split(/[-/T]/);if(rt.length<3)return null;const Et=parseInt(rt[1],10)-1,hs=parseInt(rt[2],10);return isNaN(Et)||isNaN(hs)?null:new Date(ve.getFullYear(),Et,hs)},Le=(a==null?void 0:a.filter(at=>{const rt=Ve(at.birthday),Et=Ve(at.home_anniversary);return rt&&Cc(rt,ve)||Et&&Cc(Et,ve)}))||[];a!=null&&a.filter(at=>{if(!at.birthday&&!at.home_anniversary)return!1;const rt=Et=>{if(!Et)return!1;const hs=Ve(Et);return hs?mA(hs,ve)&&fA(hs,We):!1};return rt(at.birthday)||rt(at.home_anniversary)}).slice(0,5);const Me=[],ze=(i==null?void 0:i.find(at=>at.name==="Call"))||(i==null?void 0:i[0]);for(const at of Le){const rt=Ve(at.birthday),Et=Ve(at.home_anniversary),hs=rt&&Cc(rt,ve),Is=Et&&Cc(Et,ve);hs&&Me.push({contact:at,actionType:ze||{id:"special-date-birthday",name:"Birthday Call",icon:"Cake",color:"#EC4899",description:"Wish them happy birthday!",active:!0,sort_order:0,created_at:"",updated_at:""},planName:"🎂 Birthday Today!",relationshipTypeName:((Je=(it=($e=at.tags)==null?void 0:$e[0])==null?void 0:it.relationship_type)==null?void 0:Je.name)||"",monthNumber:0,isSpecialDate:!0,specialDateType:"birthday"}),Is&&Me.push({contact:at,actionType:ze||{id:"special-date-anniversary",name:"Anniversary Call",icon:"Home",color:"#8B5CF6",description:"Celebrate their home anniversary!",active:!0,sort_order:0,created_at:"",updated_at:""},planName:"🏠 Home Anniversary!",relationshipTypeName:((wt=(mt=(st=at.tags)==null?void 0:st[0])==null?void 0:mt.relationship_type)==null?void 0:wt.name)||"",monthNumber:0,isSpecialDate:!0,specialDateType:"anniversary"})}const Ie=l!==void 0?l||[]:(a==null?void 0:a.slice(0,5).map((at,rt)=>{var hs,Is,lr;const Et=i==null?void 0:i[rt%((i==null?void 0:i.length)||1)];return Et?{contact:at,actionType:Et,planName:"Quick Touch",relationshipTypeName:((lr=(Is=(hs=at.tags)==null?void 0:hs[0])==null?void 0:Is.relationship_type)==null?void 0:lr.name)||"",monthNumber:0}:null}).filter(Boolean))||[],De=[...Me,...Ie],pe=async(at,rt,Et)=>{await h.mutateAsync({contactId:at,actionTypeId:rt,scriptUsedId:Et}),b(!1),y(null)},tt=at=>{at.script?(y(at),b(!0)):pe(at.contact.id,at.actionType.id)},ge=at=>LHe[at||"Phone"]||Yn,ct=at=>LHe[at||"Users"]||Ar,Ue=(at,rt)=>at.replace(/\{\{FirstName\}\}/g,rt.first_name).replace(/\{\{LastName\}\}/g,rt.last_name||"").replace(/\{\{AgentName\}\}/g,j||"there"),et=(at,rt)=>({Call:`Thinking of you, ${rt}!`,Text:`Quick hello, ${rt}`,Email:`Checking in, ${rt}`,"Handwritten Note":`A note for ${rt}`,Video:`Video message for ${rt}`,Gift:`Something special for you, ${rt}`})[at]||`Hello ${rt}!`,Qe=(at,rt,Et)=>{const hs=`sms:${at}`;if(rt&&Et){const Is=Ue(rt,Et);return`${hs}?body=${encodeURIComponent(Is)}`}return hs},Ne=(at,rt,Et,hs,Is)=>{const lr=`mailto:${at}`,us=[];if(Is){const St=Et||et(hs||"Email",Is.first_name);if(us.push(`subject=${encodeURIComponent(St)}`),rt){const xs=Ue(rt,Is);us.push(`body=${encodeURIComponent(xs)}`)}}return us.length>0?`${lr}?${us.join("&")}`:lr};return e.jsxs(e.Fragment,{children:[e.jsxs(Ss,{title:"Mission Control",description:"Your relationship-first contact system",children:[e.jsxs("div",{className:"space-y-6 overflow-x-hidden",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Mission Control"}),e.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"})]}),e.jsx(OLs,{}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold mb-4",children:"Your Sphere"}),e.jsx("div",{className:"flex flex-wrap gap-3",children:r==null?void 0:r.filter(at=>at.active).map(at=>{const rt=ct(at.icon),Et=(n==null?void 0:n[at.id])||0,hs=m===at.id,Is=FLs[at.name]||"bg-secondary text-secondary-foreground";return e.jsxs("button",{onClick:()=>{hs?(p(null),s("/mission-control/contacts")):(p(at.id),s(`/mission-control/contacts?type=${at.id}`))},className:` flex items-center gap-2 px-4 py-3 rounded-lg border transition-all ${hs?Is:"bg-card hover:bg-accent"} `,children:[e.jsx(rt,{className:"h-5 w-5"}),e.jsxs("div",{className:"text-left",children:[e.jsx("div",{className:"font-medium",children:at.name}),e.jsxs("div",{className:`text-sm ${hs?"opacity-90":"text-muted-foreground"}`,children:[Et," Contacts"]})]})]},at.id)})})]}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3",children:[e.jsxs(H,{onClick:()=>s("/mission-control/video/record"),className:"w-full bg-gradient-to-r from-primary to-primary/80",children:[e.jsx(Qm,{className:"h-4 w-4 mr-1"}),"Quick Video"]}),e.jsxs(H,{onClick:()=>s("/mission-control/contacts"),className:"w-full",variant:"outline",children:["View Contacts",e.jsx($a,{className:"h-4 w-4 ml-1"})]}),e.jsx(H,{variant:"outline",onClick:()=>s("/mission-control/video-library"),className:"w-full",children:"Video Library"}),e.jsx(H,{variant:"outline",onClick:()=>s("/mission-control/plans"),className:"w-full",children:"Manage Plans"})]}),e.jsxs("section",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx("h2",{className:"text-xl font-semibold",children:"Today in Your InnerCircle"}),l!==void 0&&e.jsxs(Xe,{variant:"outline",className:"gap-1",children:[e.jsx(Lr,{className:"h-3 w-3"}),"Plan-based"]}),e.jsxs("div",{className:"ml-auto flex items-center gap-1 border rounded-lg p-0.5",children:[e.jsx(H,{variant:O==="cards"?"secondary":"ghost",size:"sm",className:"h-7 px-2",onClick:()=>$("cards"),title:"Card view",children:e.jsx(_g,{className:"h-4 w-4"})}),e.jsx(H,{variant:O==="table"?"secondary":"ghost",size:"sm",className:"h-7 px-2",onClick:()=>$("table"),title:"Table view",children:e.jsx(Vf,{className:"h-4 w-4"})})]})]}),e.jsx(ke,{children:e.jsx(Oe,{className:"p-4",children:De.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx("p",{children:"No actions scheduled for today."}),e.jsx("p",{className:"text-sm mt-1",children:"Add contacts and enable touchpoint plans to get started."}),e.jsx(H,{variant:"outline",className:"mt-4",onClick:()=>s("/mission-control/plans"),children:"Manage Plans"})]}):O==="table"?e.jsx(SLs,{actions:De,onMarkComplete:pe,onViewScript:tt,isLoading:h.isPending,buildSmsLink:Qe,buildEmailLink:Ne,onGmailCompose:le?at=>{K(at),Z(!0)}:void 0}):e.jsxs("div",{className:"flex gap-3 overflow-x-auto pb-2",children:[De.map((at,rt)=>{var kt,fs,Gs,_s,br,zr,Yr;const Et=at.isSpecialDate,hs=at.specialDateType,Is=Et?hs==="birthday"?gm:Fn:ge(((kt=at.actionType)==null?void 0:kt.icon)||null),lr=at.contact.phone,us=at.contact.email,St=Et?hs==="birthday"?"#EC4899":"#8B5CF6":((fs=at.actionType)==null?void 0:fs.color)||"#3B82F6",xs=Et?hs==="birthday"?"🎂 Birthday Today!":"🏠 Home Anniversary!":(Gs=at.actionType)==null?void 0:Gs.name;return e.jsxs("div",{className:`flex-shrink-0 w-[260px] border rounded-lg overflow-hidden ${Et?"ring-2 ring-offset-2":""}`,style:Et?{"--tw-ring-color":St}:void 0,children:[e.jsxs("div",{className:"p-3 text-white flex items-center gap-2",style:{backgroundColor:St},children:[e.jsx(Is,{className:"h-4 w-4"}),e.jsx("span",{className:"font-medium text-sm",children:xs})]}),e.jsxs("div",{className:"p-3 space-y-2",children:[e.jsxs("button",{onClick:()=>s(`/mission-control/contacts/${at.contact.id}`),className:"font-medium text-sm hover:text-primary hover:underline transition-colors text-left",children:[at.contact.first_name," ",at.contact.last_name]}),e.jsxs("div",{className:"flex gap-1.5",children:[lr&&e.jsxs(e.Fragment,{children:[e.jsxs("a",{href:`tel:${at.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:[e.jsx(Yn,{className:"h-3 w-3"}),"Call"]}),e.jsxs("a",{href:Qe(at.contact.phone,(_s=at.script)==null?void 0:_s.script_body,at.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:[e.jsx(Gi,{className:"h-3 w-3"}),"Text"]})]}),us&&(le?e.jsxs("button",{onClick:()=>{K({id:at.contact.id,first_name:at.contact.first_name,last_name:at.contact.last_name,email:at.contact.email}),Z(!0)},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:"Compose Email",children:[e.jsx(er,{className:"h-3 w-3"}),"Email"]}):e.jsxs("a",{href:Ne(at.contact.email,(br=at.script)==null?void 0:br.script_body,(zr=at.script)==null?void 0:zr.email_subject,(Yr=at.actionType)==null?void 0:Yr.name,at.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:[e.jsx(er,{className:"h-3 w-3"}),"Email"]}))]}),Et&&e.jsxs("button",{onClick:()=>{const rn=`${at.contact.first_name}${at.contact.last_name?" "+at.contact.last_name:""}`,sn=hs==="birthday"?"birthday":"home_anniversary",Vr=new URLSearchParams({cardType:sn,contactId:at.contact.id,name:rn,...at.contact.address?{address:at.contact.address}:{},...hs==="anniversary"&&at.contact.home_anniversary?{date:at.contact.home_anniversary}:{}});s(`/mission-control/card-studio?${Vr.toString()}`)},className:"w-full flex items-center justify-center gap-1.5 px-2 py-1.5 rounded text-xs font-semibold bg-gradient-to-r from-pink-500/15 to-violet-500/15 hover:from-pink-500/25 hover:to-violet-500/25 text-pink-600 dark:text-pink-400 transition-colors",children:[e.jsx(er,{className:"h-3 w-3"}),"Send ",hs==="birthday"?"Birthday":"Anniversary"," Card"]}),!lr&&!us&&e.jsx("p",{className:"text-xs text-muted-foreground italic",children:"No contact info"}),e.jsxs("div",{className:"flex gap-1 flex-wrap",children:[at.relationshipTypeName&&e.jsx(Xe,{variant:"secondary",className:"text-xs",children:at.relationshipTypeName}),at.monthNumber>0&&e.jsxs(Xe,{variant:"outline",className:"text-xs",children:["Month ",at.monthNumber]})]}),at.script&&e.jsx(H,{size:"sm",variant:"outline",className:"w-full",onClick:()=>tt(at),children:"View Script"}),e.jsxs("div",{className:"flex gap-1.5",children:[e.jsxs(H,{size:"sm",variant:"outline",className:"flex-1 gap-1",onClick:()=>{ie(at.contact.id),ne(`${at.contact.first_name} ${at.contact.last_name||""}`.trim())},children:[e.jsx(Hf,{className:"h-3.5 w-3.5"}),"Snooze"]}),e.jsx(H,{size:"sm",className:"flex-1",onClick:()=>{var rn;return pe(at.contact.id,at.actionType.id,(rn=at.script)==null?void 0:rn.id)},disabled:h.isPending,children:"Mark Complete"})]})]})]},at.contact.id+rt)}),e.jsx("div",{className:"flex-shrink-0 w-[100px] border rounded-lg flex items-center justify-center",children:e.jsxs(Xu,{children:[e.jsx(Qu,{asChild:!0,children:e.jsxs(H,{variant:"ghost",className:"h-full w-full",children:[e.jsx(Jx,{className:"h-5 w-5 mr-2"}),"More"]})}),e.jsx(wu,{children:e.jsx(di,{onClick:()=>s("/mission-control/contacts"),children:"View all contacts"})})]})})]})})})]}),e.jsxs(ke,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(zt,{className:"text-lg",children:"Momentum"}),e.jsxs(bs,{open:T,onOpenChange:E,children:[e.jsx(Qi,{asChild:!0,children:e.jsx("button",{onClick:je,className:"p-0.5 rounded hover:bg-muted transition-colors","aria-label":"Edit weekly goal",children:e.jsx(Go,{className:"h-4 w-4 text-muted-foreground hover:text-primary"})})}),e.jsxs(vs,{className:"sm:max-w-[360px]",children:[e.jsxs(Cs,{children:[e.jsx(Ns,{children:"Set Weekly Goal"}),e.jsx(nn,{children:"How many touches do you want to complete each week?"})]}),e.jsxs("div",{className:"space-y-4 pt-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"weekly-goal-ic",children:"Weekly touch goal"}),e.jsx(Se,{id:"weekly-goal-ic",type:"number",min:"1",value:A,onChange:at=>D(at.target.value),placeholder:"20",onKeyDown:at=>{at.key==="Enter"&&fe()}})]}),e.jsx(H,{onClick:fe,className:"w-full",children:"Save Goal"})]})]})]})]})}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsx(Mi,{value:Math.min(c.actionsThisWeek/R*100,100),className:"h-3 w-full max-w-full"}),e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(od,{className:"h-5 w-5 text-orange-500"}),e.jsxs("span",{className:"font-medium",children:[c.actionsThisWeek," / ",R]}),e.jsx("span",{className:"text-muted-foreground",children:"Actions Completed This Week"})]}),c.streak>0&&e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx("span",{className:"text-lg",children:"🔥"}),e.jsx("span",{className:"font-medium",children:"Great Job!"}),e.jsxs("span",{className:"text-muted-foreground",children:["Keep Your Streak Going! (",c.streak," days)"]})]}),d.count>0&&e.jsxs("button",{onClick:()=>s("/mission-control/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:[e.jsx(Pn,{className:"h-4 w-4 text-orange-500 mt-0.5"}),e.jsxs("div",{children:[e.jsxs("span",{className:"font-medium text-orange-600 dark:text-orange-400",children:[d.count," Contact",d.count!==1?"s":""]}),e.jsx("span",{className:"text-muted-foreground",children:" Not Reached in 90+ Days"})]}),e.jsx($a,{className:"h-4 w-4 text-muted-foreground ml-auto mt-0.5"})]})]})]}),e.jsxs("div",{className:"grid md:grid-cols-2 gap-6",children:[e.jsx(Aot,{}),e.jsx(PLs,{})]})]}),e.jsx(bs,{open:_,onOpenChange:b,children:e.jsxs(vs,{className:"max-w-md",children:[e.jsx(Cs,{children:e.jsx(Ns,{className:"flex items-center gap-2",children:x&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-3 h-3 rounded-full",style:{backgroundColor:x.actionType.color||"#3B82F6"}}),x.actionType.name," Script"]})})}),x&&x.script&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:["For: ",e.jsxs("span",{className:"font-medium text-foreground",children:[x.contact.first_name," ",x.contact.last_name]})]}),e.jsx("div",{className:"bg-muted p-4 rounded-lg",children:e.jsx("p",{className:"whitespace-pre-wrap",children:Ue(x.script.script_body,x.contact)})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(H,{variant:"outline",className:"flex-1",onClick:()=>b(!1),children:"Close"}),e.jsx(H,{className:"flex-1",onClick:()=>{var at;return pe(x.contact.id,x.actionType.id,(at=x.script)==null?void 0:at.id)},disabled:h.isPending,children:"Mark Complete"})]})]})]})}),e.jsx(bLs,{})]}),le&&J&&e.jsx(X_,{open:ee,onOpenChange:Z,contact:J,gmailEmail:be}),e.jsx(P0e,{open:!!re,onOpenChange:at=>!at&&ie(null),contactId:re||"",contactName:ce})]})}const zLs=[{value:"bidirectional",label:"Two-Way",icon:qu,tooltip:"Sync contacts in both directions"},{value:"push_only",label:"Push Only",icon:Hu,tooltip:"Only push Agent OS → BoldTrail"},{value:"pull_only",label:"Pull Only",icon:fm,tooltip:"Only pull BoldTrail → Agent OS"}];function w4e({value:s,onChange:t,size:r="default"}){const n=r==="sm"?"text-xs":"text-sm";return e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("p",{className:`font-medium ${n} text-muted-foreground`,children:"Sync Direction"}),e.jsx(hP,{type:"single",value:s,onValueChange:a=>{a&&t(a)},className:"justify-start",children:zLs.map(a=>e.jsxs(rd,{children:[e.jsx(nd,{asChild:!0,children:e.jsxs(WE,{value:a.value,"aria-label":a.tooltip,className:`gap-1.5 ${n} border border-transparent data-[state=on]:!bg-primary data-[state=on]:!text-primary-foreground data-[state=on]:!border-primary data-[state=on]:shadow-sm`,children:[e.jsx(a.icon,{className:r==="sm"?"h-3 w-3":"h-4 w-4"}),a.label]})}),e.jsx(Rc,{children:a.tooltip})]},a.value))})]})}function DHe(){const s=ns(),[t,r]=S.useState(!1),[n,a]=S.useState(null),[i,l]=S.useState(!1),[o,c]=S.useState(!1),[d,h]=S.useState(null),[m,p]=S.useState(null),[x,y]=S.useState(0),_=S.useRef(!1),{data:b}=yt({queryKey:["boldtrail-status"],queryFn:async()=>{const{data:O,error:$}=await V.functions.invoke("boldtrail-sync",{body:{action:"status"}});if($)throw $;return O}}),j=(b==null?void 0:b.sync_direction)||"bidirectional",k=d??j,T=Pt({mutationFn:async()=>{const{data:O,error:$}=await V.functions.invoke("boldtrail-sync",{body:{action:"sync_preview"}});if($)throw $;if(O!=null&&O.error)throw new Error(O.error);return O},onSuccess:O=>{h(null),a(O),r(!0)},onError:O=>{he.error(O.message||"Failed to generate sync preview")}}),E=Pt({mutationFn:async()=>{_.current=!1,p("Initializing sync..."),y(5);const{data:O,error:$}=await V.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:"init",sync_direction:k}});if($)throw $;if(O!=null&&O.error)throw new Error(O.error);const ee=O;let Z=ee.sync_log_id,J=ee.next_phase,K=ee.next_offset,re=ee.push_total||0,ie=ee.pull_total||0,ce=ee.update_total||0,ne=0,le=0,be=0;for(;J!=="finalize"&&!_.current;){const ve=re+ie+ce;J==="fetch_bt"?p("Fetching BoldTrail contacts..."):J==="analyze"?(p("Analyzing contacts..."),y(15)):J==="push"?(p(`Pushing contacts to BoldTrail... (${ne}/${re})`),y(ve>0?ne/ve*90:0)):J==="pull"?(p(`Pulling contacts from BoldTrail... (${le}/${ie})`),y(ve>0?(re+le)/ve*90:0)):J==="update"&&(p(`Updating existing contacts... (${be}/${ce})`),y(ve>0?(re+ie+be)/ve*90:0));const{data:We,error:Ve}=await V.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:J,offset:K,sync_log_id:Z,sync_direction:k}});if(Ve)throw Ve;if(We!=null&&We.error)throw new Error(We.error);const Le=We;ne+=Le.chunk_pushed||0,le+=Le.chunk_pulled||0,be+=Le.chunk_updated||0,Le.push_total!==void 0&&(re=Le.push_total||0),Le.pull_total!==void 0&&(ie=Le.pull_total||0),Le.update_total!==void 0&&(ce=Le.update_total||0),Le.progress&&p(Le.progress),J=Le.next_phase,K=Le.next_offset}p("Finalizing sync..."),y(95);const{data:fe,error:je}=await V.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:"finalize",sync_log_id:Z,sync_direction:k}});if(je)throw je;return y(100),fe},onSuccess:O=>{p(null),y(0),r(!1),s.invalidateQueries({queryKey:["boldtrail-status"]}),s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact-counts"]}),s.invalidateQueries({queryKey:["contacts-last-touch"]});const $=[`Pushed ${O.contacts_pushed||0}`,`pulled ${O.contacts_pulled||0}`,`updated ${O.contacts_updated||0}`,`skipped ${O.contacts_skipped||0} duplicates`];he.success(`Sync complete! ${$.join(", ")}.`)},onError:O=>{p(null),y(0),he.error(O.message||"Sync failed")}});if(!(b!=null&&b.connected))return null;const A=k==="pull_only"?0:(n==null?void 0:n.to_push)??0,D=k==="push_only"?0:(n==null?void 0:n.to_pull)??0,R=(n==null?void 0:n.to_update)??0,z=A>0||D>0||R>0;return e.jsxs(e.Fragment,{children:[e.jsxs(rd,{children:[e.jsx(nd,{asChild:!0,children:e.jsx(H,{variant:"outline",size:"icon",onClick:()=>T.mutate(),disabled:T.isPending,className:"shrink-0",children:T.isPending?e.jsx(po,{className:"h-4 w-4 animate-spin"}):e.jsx(qu,{className:"h-4 w-4 text-emerald-600"})})}),e.jsx(Rc,{children:"Sync with BoldTrail"})]}),e.jsx(bs,{open:t,onOpenChange:O=>{E.isPending||r(O)},children:e.jsxs(vs,{className:"sm:max-w-lg",children:[e.jsxs(Cs,{children:[e.jsxs(Ns,{className:"flex items-center gap-2",children:[e.jsx(qu,{className:"h-5 w-5 text-emerald-600"}),"Sync Preview"]}),e.jsx(nn,{children:"Review what will happen when you sync your contacts."})]}),n&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(w4e,{value:k,onChange:h,size:"sm"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:`rounded-lg border p-3 text-center ${k==="pull_only"?"opacity-40":""}`,children:[e.jsx("p",{className:"text-2xl font-bold text-emerald-600",children:A}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(Hu,{className:"h-3 w-3"})," Push to BoldTrail"]})]}),e.jsxs("div",{className:`rounded-lg border p-3 text-center ${k==="push_only"?"opacity-40":""}`,children:[e.jsx("p",{className:"text-2xl font-bold text-blue-600",children:D}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(fm,{className:"h-3 w-3"})," Pull to Agent OS"]})]}),e.jsxs("div",{className:"rounded-lg border p-3 text-center",children:[e.jsx("p",{className:"text-2xl font-bold text-amber-600",children:R}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(KI,{className:"h-3 w-3"})," To update"]})]}),e.jsxs("div",{className:"rounded-lg border p-3 text-center",children:[e.jsx("p",{className:"text-2xl font-bold text-muted-foreground",children:n.already_synced}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(Ar,{className:"h-3 w-3"})," Already synced"]})]})]}),e.jsxs("div",{className:"text-xs text-muted-foreground text-center",children:["Agent OS: ",n.agent_os_total," contacts · BoldTrail: ",n.boldtrail_total," contacts"]}),R>0&&e.jsxs("div",{className:"text-xs text-muted-foreground text-center bg-amber-50 dark:bg-amber-950/30 rounded-md p-2",children:[e.jsx(KI,{className:"h-3 w-3 inline mr-1"}),R," contacts have missing fields that will be filled from the other system"]}),A>0&&e.jsxs(m0,{open:i,onOpenChange:l,children:[e.jsx(f0,{asChild:!0,children:e.jsxs(H,{variant:"ghost",size:"sm",className:"w-full justify-between text-xs",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Hu,{className:"h-3 w-3 text-emerald-600"}),A," contacts to push to BoldTrail"]}),e.jsx(Io,{className:`h-3 w-3 transition-transform ${i?"rotate-180":""}`})]})}),e.jsx(p0,{children:e.jsxs("div",{className:"rounded border divide-y max-h-40 overflow-y-auto",children:[n.push_preview.map((O,$)=>e.jsxs("div",{className:"px-3 py-1.5 text-xs flex justify-between",children:[e.jsx("span",{className:"font-medium",children:O.name||"No name"}),e.jsx("span",{className:"text-muted-foreground",children:O.email})]},$)),n.to_push>20&&e.jsxs("div",{className:"px-3 py-1.5 text-xs text-muted-foreground text-center",children:["...and ",n.to_push-20," more"]})]})})]}),D>0&&e.jsxs(m0,{open:o,onOpenChange:c,children:[e.jsx(f0,{asChild:!0,children:e.jsxs(H,{variant:"ghost",size:"sm",className:"w-full justify-between text-xs",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(fm,{className:"h-3 w-3 text-blue-600"}),D," contacts to pull from BoldTrail"]}),e.jsx(Io,{className:`h-3 w-3 transition-transform ${o?"rotate-180":""}`})]})}),e.jsx(p0,{children:e.jsxs("div",{className:"rounded border divide-y max-h-40 overflow-y-auto",children:[n.pull_preview.map((O,$)=>e.jsxs("div",{className:"px-3 py-1.5 text-xs flex justify-between",children:[e.jsx("span",{className:"font-medium",children:O.name||"No name"}),e.jsx("span",{className:"text-muted-foreground",children:O.email})]},$)),n.to_pull>20&&e.jsxs("div",{className:"px-3 py-1.5 text-xs text-muted-foreground text-center",children:["...and ",n.to_pull-20," more"]})]})})]}),!z&&!E.isPending&&e.jsx("div",{className:"text-center py-4 text-sm text-muted-foreground",children:"✅ Everything is already in sync! No contacts to transfer or update."}),E.isPending&&e.jsxs("div",{className:"space-y-2 py-2",children:[e.jsx(Mi,{value:x||10,className:"h-2"}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:m||"Sync in progress..."})]}),e.jsxs("div",{className:"flex gap-2 justify-end pt-2",children:[e.jsx(H,{variant:"outline",onClick:()=>r(!1),disabled:E.isPending,children:"Cancel"}),e.jsxs(H,{onClick:()=>E.mutate(),disabled:E.isPending||!z,className:"gap-2",children:[E.isPending?e.jsx(po,{className:"h-4 w-4 animate-spin"}):e.jsx(qu,{className:"h-4 w-4"}),E.isPending?"Syncing...":"Sync Now"]})]})]})]})})]})}const $Ls=()=>{const{user:s}=Ms();return yt({queryKey:["popby-items",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:r}=await V.from("popby_items").select("*").or(`owner_user_id.is.null,owner_user_id.eq.${s==null?void 0:s.id}`).eq("is_active",!0).order("name");if(r)throw r;return t},enabled:!!s})},D0e=s=>{const{user:t}=Ms();return yt({queryKey:["popby-logs",t==null?void 0:t.id,s],queryFn:async()=>{let r=V.from("popby_logs").select("*").order("completed_at",{ascending:!1});if(s){const i=new Date;i.setDate(i.getDate()-s),r=r.gte("completed_at",i.toISOString())}const{data:n,error:a}=await r;if(a)throw a;return n},enabled:!!t})},lMe=()=>{const{user:s}=Ms();return yt({queryKey:["relationship-type-popby-defaults",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:r}=await V.from("relationship_type_popby_defaults").select("*");if(r)throw r;return t},enabled:!!s})},Fgt=()=>{const{user:s}=Ms();return yt({queryKey:["contact-popby-settings",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:r}=await V.from("contact_popby_settings").select("*");if(r)throw r;return t},enabled:!!s})},ULs=()=>{const{data:s}=Cp();R0();const{data:t}=D0e(),{data:r}=Fgt(),{data:n}=lMe(),a=new Map;t==null||t.forEach(d=>{const h=a.get(d.contact_id);(!h||new Date(d.completed_at)>new Date(h))&&a.set(d.contact_id,d.completed_at)});const i=new Map;n==null||n.forEach(d=>i.set(d.relationship_type_id,d.frequency_days));const l=new Map;r==null||r.filter(d=>d.is_active).forEach(d=>{l.set(d.contact_id,d.frequency_days)});const o=jg(new Date);return(s||[]).map(d=>{let h=90;if(l.has(d.id))h=l.get(d.id);else if(d.tags&&d.tags.length>0){const _=d.tags.map(b=>i.get(b.relationship_type_id)).filter(b=>b!==void 0);_.length>0&&(h=Math.min(..._))}const m=a.get(d.id)||null,p=m?Jy(o,jg(new Date(m))):null,x=p===null||p>=h,y=x&&p!==null?p-h:0;return{...d,lastPopby:m,daysSinceLastPopby:p,frequencyDays:h,isDue:x,daysOverdue:y}}).sort((d,h)=>h.daysOverdue-d.daysOverdue)},Bgt=()=>ULs().filter(t=>t.isDue),qLs=()=>{const s=ns(),{user:t}=Ms();return Pt({mutationFn:async r=>{const{error:n}=await V.from("popby_items").insert({...r,owner_user_id:t==null?void 0:t.id});if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["popby-items"]}),En({title:"Popby item created!"})},onError:r=>{En({title:"Error creating popby item",description:r.message,variant:"destructive"})}})},VLs=()=>{const s=ns(),{user:t}=Ms();return Pt({mutationFn:async r=>{const n=new Date().toISOString(),{error:a}=await V.from("popby_logs").insert({...r,owner_user_id:t==null?void 0:t.id,completed_at:n});if(a)throw a;try{const{data:i}=await V.from("action_types").select("id").ilike("name","Pop-By").eq("active",!0).maybeSingle();i!=null&&i.id&&await V.from("contact_touch_logs").insert({owner_user_id:t==null?void 0:t.id,contact_id:r.contact_id,action_type_id:i.id,notes:r.notes??"Pop-by logged",completed_at:n})}catch(i){console.error("Failed to log corresponding touch for popby",i)}},onSuccess:()=>{s.invalidateQueries({queryKey:["popby-logs"]}),s.invalidateQueries({queryKey:["contact-touch-logs"]}),s.invalidateQueries({queryKey:["contacts-last-touch"]}),En({title:"Popby logged!"})},onError:r=>{En({title:"Error logging popby",description:r.message,variant:"destructive"})}})},HLs=()=>{const s=ns(),{user:t}=Ms();return Pt({mutationFn:async r=>{const{error:n}=await V.from("relationship_type_popby_defaults").upsert({...r,owner_user_id:t==null?void 0:t.id},{onConflict:"relationship_type_id,owner_user_id"});if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["relationship-type-popby-defaults"]}),En({title:"Frequency updated!"})},onError:r=>{En({title:"Error updating frequency",description:r.message,variant:"destructive"})}})},GLs=()=>{const{data:s}=D0e(30),t=Bgt(),r=new Date;r.setDate(r.getDate()-7);const n=(s==null?void 0:s.filter(i=>new Date(i.completed_at)>=r).length)||0,a=(s==null?void 0:s.length)||0;return{thisWeekCount:n,thisMonthCount:a,dueCount:t.length}};function WLs(){const{user:s}=Ms();return yt({queryKey:["contact-touch-logs",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:r}=await V.from("contact_touch_logs").select("*").order("completed_at",{ascending:!1});if(r)throw r;return t},enabled:!!s})}function zgt(s){const{data:t}=WLs(),{data:r}=Fgt(),{data:n}=lMe(),{data:a}=_Ls();return S.useMemo(()=>{const i=a==null?void 0:a.find(b=>b.contact_id===s.id),l=i?new Date(i.snoozed_until):null,o=jg(new Date);if(l&&!fA(l,o))return{nextTouchDate:l,daysUntil:Jy(l,o),status:"snoozed",frequencyDays:90,lastTouchDate:null,snoozedUntil:l};const d=((t==null?void 0:t.filter(b=>b.contact_id===s.id))||[]).sort((b,j)=>new Date(j.completed_at).getTime()-new Date(b.completed_at).getTime())[0],h=d?new Date(d.completed_at):null;let m=90;const p=r==null?void 0:r.find(b=>b.contact_id===s.id&&b.is_active);if(p)m=p.frequency_days;else if(s.tags&&s.tags.length>0){const b=s.tags.map(j=>{const k=n==null?void 0:n.find(T=>T.relationship_type_id===j.relationship_type_id);return k==null?void 0:k.frequency_days}).filter(j=>j!==void 0);b.length>0&&(m=Math.min(...b))}if(!h)return{nextTouchDate:null,daysUntil:null,status:"never-touched",frequencyDays:m,lastTouchDate:null,snoozedUntil:null};const x=Lc(jg(h),m),y=Jy(x,o);let _;return y<0?_="overdue":y<=7?_="due-soon":_="on-track",{nextTouchDate:x,daysUntil:y,status:_,frequencyDays:m,lastTouchDate:h,snoozedUntil:null}},[s,t,r,n,a])}function j4e({contact:s}){const t=zgt(s),n=(()=>{switch(t.status){case"overdue":return{variant:"destructive",icon:wo,text:`${Math.abs(t.daysUntil)} days overdue`,className:""};case"due-soon":return{variant:"secondary",icon:Pn,text:t.daysUntil===0?"Due today":`Due in ${t.daysUntil} days`,className:"bg-amber-100 text-amber-800 dark:bg-amber-900/30 dark:text-amber-400"};case"on-track":return{variant:"secondary",icon:ea,text:`Next touch in ${t.daysUntil} days`,className:"bg-emerald-100 text-emerald-800 dark:bg-emerald-900/30 dark:text-emerald-400"};case"snoozed":return{variant:"secondary",icon:Hf,text:`Snoozed until ${As(t.snoozedUntil,"MMM d")}`,className:"bg-slate-100 text-slate-700 dark:bg-slate-800 dark:text-slate-300"};case"never-touched":return{variant:"outline",icon:Nn,text:"Never touched",className:"border-dashed"}}})(),a=n.icon;return e.jsxs(Xe,{variant:n.variant,className:Ft("gap-1",n.className),children:[e.jsx(a,{className:"h-3 w-3"}),n.text]})}function KLs({contact:s,onLogTouch:t,onSnooze:r}){const n=zgt(s),a=jLs(),[i,l]=S.useState(!1),o=()=>{switch(n.status){case"overdue":return"text-destructive";case"due-soon":return"text-amber-600 dark:text-amber-400";case"on-track":return"text-emerald-600 dark:text-emerald-400";case"snoozed":return"text-slate-600 dark:text-slate-400";case"never-touched":return"text-muted-foreground"}},c=()=>{switch(n.status){case"overdue":return e.jsx(wo,{className:"h-5 w-5 text-destructive"});case"due-soon":return e.jsx(Pn,{className:"h-5 w-5 text-amber-600 dark:text-amber-400"});case"on-track":return e.jsx(ea,{className:"h-5 w-5 text-emerald-600 dark:text-emerald-400"});case"snoozed":return e.jsx(Hf,{className:"h-5 w-5 text-slate-600 dark:text-slate-400"});case"never-touched":return e.jsx(Nn,{className:"h-5 w-5 text-muted-foreground"})}},d=()=>{switch(n.status){case"overdue":return`${Math.abs(n.daysUntil)} days overdue`;case"due-soon":return n.daysUntil===0?"Due today!":`Due in ${n.daysUntil} days`;case"on-track":return`On track - ${n.daysUntil} days remaining`;case"snoozed":return`Snoozed for ${n.daysUntil} more days`;case"never-touched":return"No touches logged yet"}},h=async()=>{await a.mutateAsync(s.id)};return e.jsxs(e.Fragment,{children:[e.jsxs(ke,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsxs(zt,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Nn,{className:"h-4 w-4"}),"Next Touch"]})}),e.jsxs(Oe,{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[c(),e.jsx("span",{className:Ft("font-medium",o()),children:d()})]}),n.status==="snoozed"&&n.snoozedUntil&&e.jsxs("div",{className:"text-sm text-muted-foreground",children:[e.jsx("span",{className:"font-medium",children:"Snoozed until:"})," ",As(n.snoozedUntil,"MMMM d, yyyy")]}),n.status!=="snoozed"&&n.nextTouchDate&&e.jsxs("div",{className:"text-sm text-muted-foreground",children:[e.jsx("span",{className:"font-medium",children:"Scheduled:"})," ",As(n.nextTouchDate,"MMMM d, yyyy")]}),n.lastTouchDate&&e.jsxs("div",{className:"text-sm text-muted-foreground",children:[e.jsx("span",{className:"font-medium",children:"Last touch:"})," ",As(n.lastTouchDate,"MMM d, yyyy")]}),n.status!=="snoozed"&&e.jsxs("div",{className:"text-xs text-muted-foreground border-t pt-2",children:["Touch frequency: Every ",n.frequencyDays," days"]}),n.status==="snoozed"&&e.jsxs("div",{className:"flex gap-2 pt-1",children:[e.jsxs(H,{size:"sm",variant:"outline",className:"flex-1",onClick:h,disabled:a.isPending,children:[e.jsx(Rr,{className:"h-4 w-4 mr-1"}),"Cancel Snooze"]}),t&&e.jsx(H,{size:"sm",className:"flex-1",onClick:t,children:"Log Touch"})]}),n.status!=="snoozed"&&e.jsxs("div",{className:"flex gap-2 pt-1",children:[e.jsxs(H,{size:"sm",variant:"outline",className:"flex-1",onClick:()=>l(!0),children:[e.jsx(Hf,{className:"h-4 w-4 mr-1"}),"Snooze"]}),(n.status==="overdue"||n.status==="due-soon"||n.status==="never-touched")&&t&&e.jsx(H,{size:"sm",className:"flex-1",variant:n.status==="overdue"?"default":"outline",onClick:t,children:"Log Touch"})]})]})]}),e.jsx(P0e,{open:i,onOpenChange:l,contactId:s.id,contactName:`${s.first_name} ${s.last_name||""}`.trim()})]})}const hwe=768;function V8(){const[s,t]=S.useState(void 0);return S.useEffect(()=>{const r=window.matchMedia(`(max-width: ${hwe-1}px)`),n=()=>{t(window.innerWidthr.removeEventListener("change",n)},[]),!!s}function YLs(){const{user:s}=Ms(),{hasLeadSite:t,leadSite:r}=av(),{data:n,isLoading:a}=yt({queryKey:["website-active-contacts",s==null?void 0:s.id,r==null?void 0:r.id],queryFn:async()=>{if(!r)return new Set;const{data:i}=await V.from("lead_site_visitors").select("contact_id").eq("lead_site_id",r.id).not("contact_id","is",null),{data:l}=await V.from("lead_site_consumer_profiles").select("contact_id").eq("lead_site_id",r.id).not("contact_id","is",null),o=new Set;return(i||[]).forEach(c=>{c.contact_id&&o.add(c.contact_id)}),(l||[]).forEach(c=>{c.contact_id&&o.add(c.contact_id)}),o},enabled:!!s&&t,staleTime:5*60*1e3});return{activeContactIds:n??new Set,hasLeadSite:t,isLoading:a}}const ZLs={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"}},XLs={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 T7({score:s,showScore:t=!1,showTooltip:r=!0,size:n="sm",className:a}){const i=ZLs[s.status],l=XLs[n],o=e.jsxs("div",{className:Ft("inline-flex items-center rounded-full font-medium",i.bgLightClass,i.textClass,l.badge,l.text,a),children:[e.jsx("span",{className:Ft("rounded-full",i.bgClass,l.dot)}),t?e.jsx("span",{children:s.score}):e.jsx("span",{children:i.label})]});return r?e.jsx(xj,{children:e.jsxs(rd,{children:[e.jsx(nd,{asChild:!0,children:o}),e.jsx(Rc,{side:"top",className:"w-64 p-3",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"font-semibold",children:"Relationship Score"}),e.jsxs("span",{className:Ft("font-bold",i.textClass),children:[s.score,"/100"]})]}),e.jsx(Mi,{value:s.score,className:"h-2"}),e.jsxs("div",{className:"space-y-1.5 text-xs",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Recency"}),e.jsxs("span",{children:[s.breakdown.recency,"/40"]})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Touchpoints (12mo)"}),e.jsxs("span",{children:[s.breakdown.touchpoints,"/30"]})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Transactions"}),e.jsxs("span",{children:[s.breakdown.transactions,"/20"]})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Referrals"}),e.jsxs("span",{children:[s.breakdown.referrals,"/10"]})]})]}),s.daysSinceTouch!==null&&e.jsxs("p",{className:"text-xs text-muted-foreground pt-1 border-t",children:["Last contact: ",s.daysSinceTouch===0?"Today":`${s.daysSinceTouch} days ago`]}),s.daysSinceTouch===null&&e.jsx("p",{className:"text-xs text-muted-foreground pt-1 border-t italic",children:"Never contacted"})]})})]})}):o}const QLs=[{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:"spouse_email",label:"Spouse Email",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}],Hq=s=>{if(!s||!s.trim())return null;const t=s.trim();if(/^\d{4}-\d{2}-\d{2}$/.test(t))return t;const r=t.match(/^(\d{1,2})[\/\-](\d{1,2})(?:[\/\-](\d{2,4}))?$/);if(r){const a=r[1].padStart(2,"0"),i=r[2].padStart(2,"0");let l="2000";r[3]&&(l=r[3].length===2?(parseInt(r[3])>50?"19":"20")+r[3]:r[3]);const o=parseInt(a),c=parseInt(i);if(o>=1&&o<=12&&c>=1&&c<=31)return`${l}-${a}-${i}`}const n=new Date(t);return isNaN(n.getTime())?null:n.toISOString().split("T")[0]},JLs=({open:s,onOpenChange:t,relationshipTypes:r,onSuccess:n})=>{const{user:a}=Ms(),{toast:i}=li(),l=S.useRef(null),[o,c]=S.useState("upload"),[d,h]=S.useState([]),[m,p]=S.useState([]),[x,y]=S.useState({}),[_,b]=S.useState([]),[j,k]=S.useState([]),[T,E]=S.useState([]),[A,D]=S.useState(""),[R,z]=S.useState(!1),[O,$]=S.useState([]),[ee,Z]=S.useState(!1),[J,K]=S.useState(null);S.useEffect(()=>{!s||!(a!=null&&a.id)||(async()=>{const{data:Ie}=await V.from("contact_custom_tags").select("id, name, color").eq("owner_user_id",a.id).order("name");k(Ie||[])})()},[s,a==null?void 0:a.id]);const re=Ie=>{E(De=>De.includes(Ie)?De.filter(pe=>pe!==Ie):[...De,Ie])},ie=async()=>{const Ie=A.trim();if(!(!Ie||!(a!=null&&a.id))){z(!0);try{const{data:De,error:pe}=await V.from("contact_custom_tags").insert({owner_user_id:a.id,name:Ie}).select("id, name, color").single();if(pe)throw pe;De&&(k(tt=>[...tt,De].sort((ge,ct)=>ge.name.localeCompare(ct.name))),E(tt=>[...tt,De.id]),D(""))}catch(De){i({title:"Could not create tag",description:De.message||"Try a different name.",variant:"destructive"})}finally{z(!1)}}},ce=()=>{c("upload"),h([]),p([]),y({}),b([]),E([]),D(""),$([]),K(null),l.current&&(l.current.value="")},ne=()=>{ce(),t(!1)},le=Ie=>{const De=Ie.split(` `).map(et=>et.trim()).filter(et=>et);if(De.length===0)return{headers:[],data:[]};const pe=et=>{const Qe=[];let Ne="",$e=!1;for(let it=0;it0&&(tt[0]=tt[0].replace(/^\uFEFF/,""));const ge=new Map,ct=tt.map((et,Qe)=>{let Ne=(et||"").trim();Ne||(Ne=`Column ${Qe+1}`);const $e=ge.get(Ne)||0;return ge.set(Ne,$e+1),$e===0?Ne:`${Ne} (${$e+1})`}),Ue=De.slice(1).map(pe);return{headers:ct,data:Ue}},be=Ie=>{var tt;const De=(tt=Ie.target.files)==null?void 0:tt[0];if(!De)return;const pe=new FileReader;pe.onload=ge=>{var Ne;const ct=(Ne=ge.target)==null?void 0:Ne.result,{headers:Ue,data:et}=le(ct);if(Ue.length===0){i({title:"No data found",description:"The CSV file appears to be empty.",variant:"destructive"});return}h(Ue),p(et);const Qe={};Ue.forEach($e=>{const it=$e.toLowerCase().replace(/[_\s-]/g,"");it.includes("firstname")||it==="first"?Qe.first_name=$e:it.includes("lastname")||it==="last"?Qe.last_name=$e:it.includes("spouse")&&it.includes("email")?Qe.spouse_email=$e:it.includes("spouse")||it.includes("partner")?Qe.spouse_name=$e:it.includes("email")?Qe.email=$e:it.includes("phone")||it.includes("mobile")||it.includes("cell")?Qe.phone=$e:it.includes("address")||it.includes("street")?Qe.address=$e:it==="city"?Qe.city=$e:it==="state"||it==="province"?Qe.state=$e:it==="zip"||it==="zipcode"||it==="postalcode"?Qe.zip=$e:it.includes("company")||it.includes("organization")||it.includes("business")?Qe.company_name=$e:it.includes("jobtitle")||it.includes("title")&&!it.includes("spouse")?Qe.job_title=$e:it.includes("birthday")||it.includes("dob")||it.includes("birthdate")?Qe.birthday=$e:it.includes("anniversary")||it.includes("homeanniversary")?Qe.home_anniversary=$e:(it.includes("notes")||it.includes("comment"))&&(Qe.notes=$e)}),y(Qe),c("mapping")},pe.readAsText(De)},fe=(Ie,De)=>{y(pe=>{if(De==="none"){const{[Ie]:tt,...ge}=pe;return ge}return{...pe,[Ie]:De}})},je=Ie=>{b(De=>De.includes(Ie)?De.filter(pe=>pe!==Ie):[...De,Ie])},ve=async()=>{if(!(a!=null&&a.id))return;const{data:Ie}=await V.from("innercircle_contacts").select("id, email, phone").eq("owner_user_id",a.id),De=new Set((Ie||[]).filter(ge=>ge.email).map(ge=>ge.email.toLowerCase())),pe=new Set((Ie||[]).filter(ge=>ge.phone).map(ge=>ge.phone.replace(/[^0-9]/g,""))),tt=m.map(ge=>{const ct=it=>{const Je=x[it];if(!Je)return"";const st=d.indexOf(Je);return st>=0?(ge[st]||"").trim():""},Ue=ct("first_name"),et=ct("email"),Qe=ct("phone"),Ne=Ue.length>0,$e=!!(et&&De.has(et.toLowerCase())||Qe&&pe.has(Qe.replace(/[^0-9]/g,"")));return{first_name:Ue,last_name:ct("last_name"),email:et,phone:Qe,address:ct("address"),city:ct("city"),state:ct("state"),zip:ct("zip"),spouse_name:ct("spouse_name"),spouse_email:ct("spouse_email"),company_name:ct("company_name"),job_title:ct("job_title"),birthday:ct("birthday"),home_anniversary:ct("home_anniversary"),notes:ct("notes"),isValid:Ne,isDuplicate:$e,error:Ne?void 0:"First name is required"}});$(tt),c("preview")},We=Ie=>{const De=Ie.trim().split(/\s+/);return{first_name:De[0],last_name:De.length>1?De.slice(1).join(" "):null}},Ve=async()=>{if(!(a!=null&&a.id))return;const Ie=O.filter(ge=>ge.isValid);if(Ie.length===0){i({title:"No valid contacts",description:"There are no valid contacts to import.",variant:"destructive"});return}Z(!0);let De=0,pe=0,tt=0;try{for(const ge of Ie)try{let ct=null;if(ge.email){const{data:Qe}=await V.from("innercircle_contacts").select("id").eq("owner_user_id",a.id).eq("email",ge.email).maybeSingle();ct=Qe}if(!ct&&ge.phone){const Qe=ge.phone.replace(/[^0-9]/g,""),{data:Ne}=await V.from("innercircle_contacts").select("id, phone").eq("owner_user_id",a.id).not("phone","is",null);if(Ne){const $e=Ne.find(it=>it.phone&&it.phone.replace(/[^0-9]/g,"")===Qe);$e&&(ct={id:$e.id})}}const Ue={owner_user_id:a.id,first_name:ge.first_name,last_name:ge.last_name||null,email:ge.email||null,phone:ge.phone||null,address:ge.address||null,city:ge.city||null,state:ge.state||null,zip:ge.zip||null,spouse_name:ge.spouse_name||null,spouse_email:ge.spouse_email||null,company_name:ge.company_name||null,job_title:ge.job_title||null,birthday:Hq(ge.birthday),home_anniversary:Hq(ge.home_anniversary),notes:ge.notes||null};let et=null;if(ct){const{data:Qe}=await V.from("innercircle_contacts").select("*").eq("id",ct.id).single();if(Qe){const Ne={},$e=["last_name","email","phone","address","city","state","zip","spouse_name","spouse_email","company_name","job_title","birthday","home_anniversary","notes"];for(const it of $e){const Je=Qe[it],st=Ue[it];(!Je||Je==="")&&st&&(Ne[it]=st)}Object.keys(Ne).length>0&&await V.from("innercircle_contacts").update(Ne).eq("id",ct.id)}et=ct.id,pe++}else{const{data:Qe,error:Ne}=await V.from("innercircle_contacts").insert(Ue).select("id").single();Ne?(console.error("Insert error for contact:",ge.first_name,Ne),tt++):Qe?(et=Qe.id,_.length>0&&await V.from("innercircle_contact_tags").insert(_.map($e=>({contact_id:Qe.id,relationship_type_id:$e}))),De++):tt++}if(et&&T.length>0&&await V.from("contact_custom_tag_assignments").upsert(T.map(Qe=>({contact_id:et,tag_id:Qe})),{onConflict:"contact_id,tag_id",ignoreDuplicates:!0}),et&&ge.spouse_name){const Qe=We(ge.spouse_name);let Ne=null;if(ge.spouse_email){const{data:it}=await V.from("innercircle_contacts").select("id").eq("owner_user_id",a.id).eq("email",ge.spouse_email).maybeSingle();Ne=it}if(!Ne){const{data:it}=await V.from("innercircle_contacts").select("id").eq("owner_user_id",a.id).eq("first_name",Qe.first_name).eq("last_name",Qe.last_name||ge.last_name||"").maybeSingle();Ne=it}let $e=null;if(Ne){$e=Ne.id;const it=Hq(ge.home_anniversary);it&&await V.from("innercircle_contacts").update({home_anniversary:it}).eq("id",Ne.id).is("home_anniversary",null)}else{const{data:it}=await V.from("innercircle_contacts").insert({owner_user_id:a.id,first_name:Qe.first_name,last_name:Qe.last_name||ge.last_name||null,email:ge.spouse_email||null,address:ge.address||null,city:ge.city||null,state:ge.state||null,zip:ge.zip||null,home_anniversary:Hq(ge.home_anniversary),spouse_name:`${ge.first_name}${ge.last_name?" "+ge.last_name:""}`,spouse_email:ge.email||null,notes:`Spouse of ${ge.first_name} ${ge.last_name||""} (imported via CSV)`.trim()}).select("id").single();it&&($e=it.id,De++)}$e&&(await V.from("innercircle_contacts").update({spouse_contact_id:$e}).eq("id",et),await V.from("innercircle_contacts").update({spouse_contact_id:et}).eq("id",$e))}}catch(ct){console.error("Error importing contact:",ct),tt++}K({created:De,updated:pe,failed:tt}),c("result"),(De>0||pe>0)&&n(),i({title:"Import Complete",description:`${De} created, ${pe} updated${tt>0?`, ${tt} failed`:""}.`})}catch(ge){console.error("Import error:",ge),i({title:"Import Failed",description:ge.message||"Failed to import contacts",variant:"destructive"})}finally{Z(!1)}},Le=O.filter(Ie=>Ie.isValid).length,Me=O.filter(Ie=>!Ie.isValid).length,ze=O.filter(Ie=>Ie.isValid&&Ie.isDuplicate).length,Pe=Le-ze;return e.jsx(bs,{open:s,onOpenChange:ne,children:e.jsxs(vs,{className:"max-w-3xl max-h-[85vh] overflow-hidden flex flex-col",children:[e.jsxs(Cs,{children:[e.jsxs(Ns,{className:"flex items-center gap-2",children:[e.jsx($2,{className:"h-5 w-5"}),"Import Contacts from CSV"]}),e.jsx(nn,{children:"Upload a CSV file with your contacts. You can map columns and select relationship types."})]}),o==="upload"&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-8 text-center",children:[e.jsx("input",{type:"file",accept:".csv,.txt",ref:l,onChange:be,className:"hidden"}),e.jsx(Ea,{className:"h-10 w-10 mx-auto text-muted-foreground mb-4"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Click to upload or drag and drop a CSV file"}),e.jsx(H,{onClick:()=>{var Ie;return(Ie=l.current)==null?void 0:Ie.click()},children:"Select CSV File"})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-4 text-sm",children:[e.jsx("p",{className:"font-medium mb-2",children:"Supported Fields:"}),e.jsx("p",{className:"text-muted-foreground text-xs mb-3",children:"First Name, Last Name, Email, Phone, Street Address, City, State, Zip, Spouse Name, Spouse Email, Company, Job Title, Birthday, Home Anniversary, Notes"}),e.jsxs(H,{variant:"outline",size:"sm",onClick:()=>{const Ie=`First Name,Last Name,Email,Phone,Street Address,City,State,Zip,Spouse Name,Spouse Email,Company,Job Title,Birthday,Home Anniversary,Notes John,Doe,john@example.com,555-123-4567,123 Main St,Austin,TX,78701,Jane Doe,jane@example.com,ABC Realty,Real Estate Agent,1985-06-15,2020-03-22,Met at open house`,De=new Blob([Ie],{type:"text/csv"}),pe=URL.createObjectURL(De),tt=document.createElement("a");tt.href=pe,tt.download="contact_import_template.csv",tt.click(),URL.revokeObjectURL(pe)},children:[e.jsx(hi,{className:"h-4 w-4 mr-2"}),"Download Template"]})]})]}),o==="mapping"&&e.jsxs("div",{className:"flex-1 overflow-auto space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(ue,{className:"text-base font-medium",children:"Map CSV Columns to Contact Fields"}),e.jsx("div",{className:"grid gap-3",children:QLs.map(Ie=>e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs(ue,{className:"w-40 text-sm",children:[Ie.label,Ie.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsxs(Bs,{value:x[Ie.key]||"none",onValueChange:De=>fe(Ie.key,De),children:[e.jsx(Os,{className:"w-48",children:e.jsx(Us,{placeholder:"Select column..."})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"none",children:"-- Not mapped --"}),d.map(De=>e.jsx(pt,{value:De,children:De},De))]})]})]},Ie.key))})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(ue,{className:"text-base font-medium",children:"Apply Relationship Types (optional)"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:r.map(Ie=>e.jsx(Xe,{variant:_.includes(Ie.id)?"default":"outline",className:"cursor-pointer",onClick:()=>je(Ie.id),children:Ie.name},Ie.id))})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(ue,{className:"text-base font-medium",children:"Apply Tags to All Imported Contacts (optional)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Every contact in this CSV — both newly created and merged duplicates — will receive the selected tags."}),j.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2",children:j.map(Ie=>{const De=T.includes(Ie.id);return e.jsxs(Xe,{variant:De?"default":"outline",className:"cursor-pointer gap-1",style:De&&Ie.color?{backgroundColor:Ie.color,borderColor:Ie.color}:void 0,onClick:()=>re(Ie.id),children:[Ie.name,De&&e.jsx(Rr,{className:"h-3 w-3"})]},Ie.id)})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Se,{placeholder:"Create a new tag (e.g. Open House Oct 2026)",value:A,onChange:Ie=>D(Ie.target.value),onKeyDown:Ie=>{Ie.key==="Enter"&&(Ie.preventDefault(),ie())},className:"max-w-xs"}),e.jsxs(H,{type:"button",variant:"outline",size:"sm",onClick:ie,disabled:!A.trim()||R,children:[R?e.jsx(is,{className:"h-4 w-4 animate-spin"}):e.jsx(Ys,{className:"h-4 w-4 mr-1"}),"Add Tag"]})]})]}),e.jsx("div",{className:"bg-muted/50 rounded-lg p-3 text-sm",children:e.jsxs("p",{className:"text-muted-foreground",children:["Preview: ",m.length," row(s) found in CSV"]})})]}),o==="preview"&&e.jsxs("div",{className:"flex-1 overflow-hidden flex flex-col space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-4 text-sm flex-wrap",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ea,{className:"h-4 w-4 text-primary"}),e.jsxs("span",{children:[Pe," new"]})]}),ze>0&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(wo,{className:"h-4 w-4"}),e.jsxs("span",{children:[ze," existing (will merge gaps)"]})]}),Me>0&&e.jsxs("div",{className:"flex items-center gap-2 text-destructive",children:[e.jsx(wo,{className:"h-4 w-4"}),e.jsxs("span",{children:[Me," invalid"]})]})]}),ze>0&&e.jsx("div",{className:"bg-muted/50 rounded-lg p-3 text-xs text-muted-foreground",children:"Duplicates matched by email or phone will only fill in missing fields — your existing data won't be overwritten."}),e.jsxs("div",{className:"flex-1 overflow-auto border rounded-lg",children:[e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Vs,{className:"bg-muted/30",children:[e.jsx(At,{children:"First Name"}),e.jsx(At,{children:"Last Name"}),e.jsx(At,{children:"Email"}),e.jsx(At,{children:"Phone"}),e.jsx(At,{children:"Status"})]})}),e.jsx(da,{children:O.slice(0,100).map((Ie,De)=>e.jsxs(Vs,{children:[e.jsx(gt,{children:Ie.first_name}),e.jsx(gt,{children:Ie.last_name}),e.jsx(gt,{children:Ie.email}),e.jsx(gt,{children:Ie.phone}),e.jsx(gt,{children:Ie.isValid?Ie.isDuplicate?e.jsx(Xe,{variant:"outline",className:"bg-accent text-accent-foreground",children:"Merge"}):e.jsx(Xe,{variant:"secondary",className:"bg-primary/10 text-primary",children:"New"}):e.jsx(Xe,{variant:"destructive",children:Ie.error||"Invalid"})})]},De))})]}),O.length>100&&e.jsxs("p",{className:"text-sm text-muted-foreground text-center py-2",children:["Showing first 100 of ",O.length," contacts"]})]})]}),o==="result"&&J&&e.jsxs("div",{className:"space-y-4 py-4 text-center",children:[e.jsx(ea,{className:"h-12 w-12 mx-auto text-primary"}),e.jsx("h3",{className:"text-lg font-semibold",children:"Import Complete"}),e.jsxs("p",{className:"text-muted-foreground",children:[J.created," created, ",J.updated," merged"]}),J.failed>0&&e.jsxs("p",{className:"text-destructive",children:[J.failed," failed to import"]})]}),e.jsxs(wn,{children:[o==="upload"&&e.jsx(H,{variant:"outline",onClick:ne,children:"Cancel"}),o==="mapping"&&e.jsxs(e.Fragment,{children:[e.jsx(H,{variant:"outline",onClick:ce,children:"Back"}),e.jsx(H,{onClick:ve,disabled:!x.first_name,children:"Continue"})]}),o==="preview"&&e.jsxs(e.Fragment,{children:[e.jsx(H,{variant:"outline",onClick:()=>c("mapping"),children:"Back"}),e.jsx(H,{onClick:Ve,disabled:ee||Le===0,children:ee?e.jsxs(e.Fragment,{children:[e.jsx(is,{className:"mr-2 h-4 w-4 animate-spin"}),"Importing..."]}):`Import ${Le} Contact${Le!==1?"s":""}`})]}),o==="result"&&e.jsx(H,{onClick:ne,children:"Done"})]})]})})};function e8s(){return"contacts"in navigator&&"ContactsManager"in window}function t8s(s){const t=[],r=s.split("BEGIN:VCARD").filter(n=>n.trim());for(const n of r){const a=n.split(/\r?\n/);let i="",l="",o="",c="",d="";for(const h of a){const m=h.replace(/^\s+/,"");if(m.startsWith("N:")||m.startsWith("N;")){const x=m.substring(m.indexOf(":")+1).split(";");l=(x[0]||"").trim(),i=(x[1]||"").trim()}if((m.startsWith("FN:")||m.startsWith("FN;"))&&!i){const x=m.substring(m.indexOf(":")+1).trim().split(" ");i=x[0]||"",l=x.slice(1).join(" ")}(m.startsWith("EMAIL")||m.match(/^item\d+\.EMAIL/i))&&!o&&(o=m.substring(m.indexOf(":")+1).trim()),(m.startsWith("TEL")||m.match(/^item\d+\.TEL/i))&&!c&&(c=m.substring(m.indexOf(":")+1).trim()),(m.startsWith("ADR")||m.match(/^item\d+\.ADR/i))&&!d&&(d=m.substring(m.indexOf(":")+1).split(";").map(y=>y.trim()).filter(Boolean).join(", "))}(i||l)&&t.push({first_name:i,last_name:l,email:o,phone:c,address:d})}return t}function s8s({open:s,onOpenChange:t,onComplete:r}){Ms();const{data:n}=Cp(),a=Qge(),i=S.useRef(null),[l,o]=S.useState("choose"),[c,d]=S.useState([]),[h,m]=S.useState(new Set),[p,x]=S.useState(0),[y,_]=S.useState(0),b=e8s(),j=S.useCallback($=>{if(!n)return $;const ee=new Set(n.filter(J=>J.email).map(J=>J.email.toLowerCase())),Z=new Set(n.filter(J=>J.phone).map(J=>J.phone.replace(/\D/g,"")));return $.map(J=>{var ie,ce;const K=(ie=J.email)==null?void 0:ie.toLowerCase(),re=(ce=J.phone)==null?void 0:ce.replace(/\D/g,"");return K&&ee.has(K)?{...J,isDuplicate:!0,duplicateField:"email"}:re&&re.length>=7&&Z.has(re)?{...J,isDuplicate:!0,duplicateField:"phone"}:J})},[n]),k=async()=>{try{const $=["name","email","tel","address"],ee=await navigator.contacts.select($,{multiple:!0});if(!ee||ee.length===0)return;const Z=ee.map(re=>{var ne,le,be,fe;const ce=(((ne=re.name)==null?void 0:ne[0])||"").split(" ");return{first_name:ce[0]||"",last_name:ce.slice(1).join(" "),email:((le=re.email)==null?void 0:le[0])||"",phone:((be=re.tel)==null?void 0:be[0])||"",address:(fe=re.address)!=null&&fe[0]?[re.address[0].streetAddress,re.address[0].city,re.address[0].region,re.address[0].postalCode].filter(Boolean).join(", "):""}}),J=j(Z);d(J);const K=new Set;J.forEach((re,ie)=>{re.isDuplicate||K.add(ie)}),m(K),o("preview")}catch($){console.error("Contact Picker error:",$),En({title:"Could not access contacts",description:"Please try the file upload option instead.",variant:"destructive"})}},T=$=>{var J;const ee=(J=$.target.files)==null?void 0:J[0];if(!ee)return;const Z=new FileReader;Z.onload=K=>{var le;const re=(le=K.target)==null?void 0:le.result,ie=t8s(re);if(ie.length===0){En({title:"No contacts found",description:"The file didn't contain any valid contacts.",variant:"destructive"});return}const ce=j(ie);d(ce);const ne=new Set;ce.forEach((be,fe)=>{be.isDuplicate||ne.add(fe)}),m(ne),o("preview")},Z.readAsText(ee),i.current&&(i.current.value="")},E=async()=>{const $=c.filter((Z,J)=>h.has(J));if($.length===0)return;o("importing");let ee=0;for(const Z of $)try{await a.mutateAsync({first_name:Z.first_name,last_name:Z.last_name||void 0,email:Z.email||void 0,phone:Z.phone||void 0,address:Z.address||void 0}),ee++,_(Math.round(ee/$.length*100))}catch(J){console.error(`Failed to import ${Z.first_name} ${Z.last_name}:`,J)}x(ee),o("done")},A=$=>{m(ee=>{const Z=new Set(ee);return Z.has($)?Z.delete($):Z.add($),Z})},D=()=>{h.size===c.length?m(new Set):m(new Set(c.map(($,ee)=>ee)))},R=$=>{$||(o("choose"),d([]),m(new Set),x(0),_(0),l==="done"&&r()),t($)},z=c.filter($=>$.isDuplicate).length,O=h.size;return e.jsx(bs,{open:s,onOpenChange:R,children:e.jsxs(vs,{className:"sm:max-w-lg max-h-[90vh]",children:[e.jsxs(Cs,{children:[e.jsxs(Ns,{className:"flex items-center gap-2",children:[e.jsx(Vy,{className:"h-5 w-5 text-primary"}),l==="choose"&&"Import Phone Contacts",l==="preview"&&"Select Contacts to Import",l==="importing"&&"Importing Contacts...",l==="done"&&"Import Complete"]}),l==="choose"&&e.jsx(nn,{children:"Add contacts from your phone directly into Agent OS."})]}),l==="choose"&&e.jsxs("div",{className:"space-y-4 pt-2",children:[b&&e.jsxs(H,{onClick:k,className:"w-full h-auto py-4 flex flex-col items-center gap-2",children:[e.jsx(Vy,{className:"h-6 w-6"}),e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"font-semibold",children:"Select from Phone"}),e.jsx("div",{className:"text-xs opacity-80",children:"Pick contacts directly from your device"})]})]}),e.jsxs("div",{className:"relative",children:[b&&e.jsx("div",{className:"absolute inset-0 flex items-center",children:e.jsx("span",{className:"w-full border-t"})}),b&&e.jsx("div",{className:"relative flex justify-center text-xs uppercase",children:e.jsx("span",{className:"bg-background px-2 text-muted-foreground",children:"or"})})]}),e.jsxs(H,{variant:b?"outline":"default",onClick:()=>{var $;return($=i.current)==null?void 0:$.click()},className:"w-full h-auto py-4 flex flex-col items-center gap-2",children:[e.jsx(Ea,{className:"h-6 w-6"}),e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"font-semibold",children:"Upload Contact File"}),e.jsx("div",{className:"text-xs opacity-80",children:b?"Import a .vcf file exported from your Contacts app":"Export contacts from your phone as a .vcf file, then upload here"})]})]}),e.jsx("input",{ref:i,type:"file",accept:".vcf,.vcard",onChange:T,className:"hidden"}),!b&&e.jsxs("div",{className:"rounded-lg bg-muted p-3 text-sm text-muted-foreground space-y-2",children:[e.jsx("p",{className:"font-medium",children:"How to export contacts:"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-xs",children:"iPhone:"}),e.jsx("p",{className:"text-xs",children:'Open Contacts → select contacts → Share → choose "Export vCard"'})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-xs",children:"Android:"}),e.jsx("p",{className:"text-xs",children:"Open Contacts → Menu → Export → save as .vcf file"})]})]})]}),l==="preview"&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("span",{children:[c.length," contact",c.length!==1?"s":""," found",z>0&&e.jsxs("span",{className:"text-amber-600 ml-1",children:["(",z," already exist)"]})]}),e.jsx(H,{variant:"ghost",size:"sm",onClick:D,children:h.size===c.length?"Deselect All":"Select All"})]}),e.jsx(Ci,{className:"h-[350px] rounded-md border",children:e.jsx("div",{className:"divide-y",children:c.map(($,ee)=>e.jsxs("div",{className:`flex items-start gap-3 p-3 cursor-pointer hover:bg-accent/50 transition-colors ${$.isDuplicate?"opacity-60":""}`,onClick:()=>A(ee),children:[e.jsx(ao,{checked:h.has(ee),onCheckedChange:()=>A(ee),className:"mt-0.5"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"font-medium text-sm truncate",children:[$.first_name," ",$.last_name]}),$.isDuplicate&&e.jsxs(Xe,{variant:"secondary",className:"text-[10px] px-1.5 py-0 bg-amber-500/10 text-amber-600 border-amber-200",children:["Exists (",$.duplicateField,")"]})]}),e.jsxs("div",{className:"text-xs text-muted-foreground space-y-0.5 mt-0.5",children:[$.phone&&e.jsx("div",{children:$.phone}),$.email&&e.jsx("div",{className:"truncate",children:$.email})]})]})]},ee))})}),e.jsxs("div",{className:"flex items-center justify-between pt-2",children:[e.jsx(H,{variant:"ghost",size:"sm",onClick:()=>o("choose"),children:"Back"}),e.jsxs(H,{onClick:E,disabled:O===0,children:["Import ",O," Contact",O!==1?"s":""]})]})]}),l==="importing"&&e.jsxs("div",{className:"flex flex-col items-center gap-4 py-8",children:[e.jsx(is,{className:"h-8 w-8 animate-spin text-primary"}),e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"font-medium",children:"Importing contacts..."}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[y,"% complete"]})]}),e.jsx("div",{className:"w-full bg-muted rounded-full h-2",children:e.jsx("div",{className:"bg-primary h-2 rounded-full transition-all",style:{width:`${y}%`}})})]}),l==="done"&&e.jsxs("div",{className:"flex flex-col items-center gap-4 py-8",children:[e.jsx("div",{className:"h-12 w-12 rounded-full bg-emerald-500/10 flex items-center justify-center",children:e.jsx(va,{className:"h-6 w-6 text-emerald-600"})}),e.jsxs("div",{className:"text-center",children:[e.jsxs("p",{className:"font-semibold text-lg",children:[p," contact",p!==1?"s":""," imported!"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Your contacts are now in Agent OS and ready for touchpoint plans."})]}),e.jsx(H,{onClick:()=>R(!1),className:"mt-2",children:"Done"})]})]})})}function r8s(s){return yt({queryKey:["video-share-recipients",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await V.from("video_share_recipients").select("*").eq("video_id",s).order("sent_at",{ascending:!1});if(r)throw r;return t},enabled:!!s})}function n8s(){const{user:s}=Ms();return yt({queryKey:["video-share-stats",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return null;const{data:t,error:r}=await V.from("video_share_recipients").select("*").eq("owner_user_id",s.id);if(r)throw r;const n=t;return{totalSent:n.length,totalOpened:n.filter(a=>a.opened_at).length,totalClicked:n.filter(a=>a.clicked_at).length,totalWatched:n.filter(a=>a.watched_at).length,openRate:n.length>0?Math.round(n.filter(a=>a.opened_at).length/n.length*100):0,clickRate:n.length>0?Math.round(n.filter(a=>a.clicked_at).length/n.length*100):0,watchRate:n.length>0?Math.round(n.filter(a=>a.watched_at).length/n.length*100):0}},enabled:!!(s!=null&&s.id)})}function a8s(){const{user:s}=Ms();return yt({queryKey:["video-share-history",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return[];const{data:t,error:r}=await V.from("video_share_recipients").select(` *, agent_videos!inner(id, title, thumbnail_url, share_token, duration_seconds) `).eq("owner_user_id",s.id).order("sent_at",{ascending:!1}).limit(200);if(r)throw r;return t},enabled:!!(s!=null&&s.id)})}function $gt(){const{user:s}=Ms(),t=ns();return Pt({mutationFn:async r=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{data:n,error:a}=await V.from("video_share_recipients").insert([{video_id:r.video_id,owner_user_id:s.id,recipient_email:r.recipient_email,recipient_name:r.recipient_name||null,contact_id:r.contact_id||null,sent_via:r.sent_via||"gmail",share_token:"placeholder"}]).select().single();if(a)throw a;return n},onSuccess:r=>{t.invalidateQueries({queryKey:["video-share-recipients",r.video_id]}),t.invalidateQueries({queryKey:["video-share-stats"]}),t.invalidateQueries({queryKey:["video-share-history"]})}})}function Ugt(s){return`https://relzejiswnotikjgvjhz.supabase.co/functions/v1/track-video-share?t=${s}&e=open`}function qgt(s){return`https://relzejiswnotikjgvjhz.supabase.co/functions/v1/track-video-share?t=${s}&e=click`}const i8s=100;function o8s({open:s,onOpenChange:t,contacts:r,isGmailConnected:n,isMassEmailReady:a,onSendComplete:i}){const l=Fr(),o=ba(),c=$gt(),[d,h]=S.useState([]),[m,p]=S.useState(!1),[x,y]=S.useState(""),[_,b]=S.useState(null),[j,k]=S.useState(""),[T,E]=S.useState(""),[A,D]=S.useState(!1),[R,z]=S.useState({done:0,total:0,failed:0}),O=r.filter(ce=>!!ce.email),$=r.length-O.length,ee=O.length>i8s;S.useEffect(()=>{s&&(b(null),y(""),z({done:0,total:0,failed:0}))},[s]),S.useEffect(()=>{!s||!o||(p(!0),V.from("agent_videos").select("id, title, share_token, thumbnail_url, playback_url, duration_seconds, created_at").eq("owner_user_id",o).eq("is_deleted",!1).eq("status","ready").order("created_at",{ascending:!1}).limit(50).then(({data:ce})=>{h(ce||[]),p(!1)}))},[s,o]),S.useEffect(()=>{if(!_)return;const ce=_.title||"a quick video";k(`I recorded a video for you — ${ce}`),E("Hey {{first_name}}! I recorded a quick video just for you. Click below to watch it:")},[_]);const Z=d.filter(ce=>!x||(ce.title||"").toLowerCase().includes(x.toLowerCase())),J=(ce,ne)=>{if(!_)return"";const le=_.share_token?`https://video.relevelup.com/share/video/${_.share_token}`:"",be=_.share_token?`https://video.relevelup.com/thumb/${_.share_token}`:_.thumbnail_url||"",fe=_.title||"Video Message",ve=T.replace(/\{\{first_name\}\}/gi,ce).split(/\n\n+/).map(Le=>`

${Le.replace(/\n/g,"
")}

`).join(""),We=ne?qgt(ne):le,Ve=ne?``:"";return`
${ve}

▶ Watch Video

${Ve}
`},K=async()=>{if(!_)return;D(!0),z({done:0,total:O.length,failed:0});let ce=0,ne=0;for(const le of O)try{let be;try{be=(await c.mutateAsync({video_id:_.id,recipient_email:le.email,recipient_name:`${le.first_name} ${le.last_name||""}`.trim(),contact_id:le.id,sent_via:"gmail"})).share_token}catch(Ve){console.warn("Tracking record failed for",le.email,Ve)}const fe=J(le.first_name,be),je=j.replace(/\{\{first_name\}\}/gi,le.first_name),{data:ve,error:We}=await V.functions.invoke("gmail-send",{body:{to:le.email,subject:je,body:fe,contactId:le.id}});if(We||!(ve!=null&&ve.success))throw new Error((ve==null?void 0:ve.error)||(We==null?void 0:We.message)||"Send failed");ce+=1}catch(be){console.error("Failed to send to",le.email,be),ne+=1}finally{z({done:ce+ne,total:O.length,failed:ne}),await new Promise(be=>setTimeout(be,250))}D(!1),ne===0?he.success(`Video sent to ${ce} ${ce===1?"contact":"contacts"}!`):he.warning(`Sent to ${ce}, ${ne} failed. Check console for details.`),t(!1),i==null||i()},re=()=>{if(!_)return;const ce=J("there",void 0);l("/admin/email-campaigns/new",{state:{directRecipients:O.map(ne=>({email:ne.email,name:`${ne.first_name} ${ne.last_name||""}`.trim()})),initialSubject:j,initialBodyHtml:ce}}),t(!1)},ie=!!_&&!!j.trim()&&O.length>0&&(ee?a:n);return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"sm:max-w-[640px] max-h-[90vh] overflow-y-auto",children:[e.jsxs(Cs,{children:[e.jsxs(Ns,{className:"flex items-center gap-2",children:[e.jsx(xn,{className:"h-5 w-5 text-primary"}),"Send Video to ",O.length," ",O.length===1?"Contact":"Contacts"]}),e.jsxs(nn,{children:[ee?e.jsxs("span",{className:"flex items-center gap-1.5 text-amber-600",children:[e.jsx(ph,{className:"h-3.5 w-3.5"}),O.length," recipients — will be sent as a Mass Email campaign"]}):e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(er,{className:"h-3.5 w-3.5"}),"Sent individually via your connected Gmail"]}),$>0&&e.jsxs("span",{className:"ml-2 text-xs text-muted-foreground",children:["(",$," skipped — no email)"]})]})]}),e.jsxs("div",{className:"space-y-4",children:[ee&&!a&&e.jsxs("div",{className:"flex items-start gap-2 p-3 rounded-md bg-destructive/10 text-destructive text-sm",children:[e.jsx(wo,{className:"h-4 w-4 mt-0.5 shrink-0"}),e.jsxs("div",{children:["Mass Email is not set up yet. Verify a sender address in Integrations → Mass Email before sending to ",O.length," recipients."]})]}),!ee&&!n&&e.jsxs("div",{className:"flex items-start gap-2 p-3 rounded-md bg-destructive/10 text-destructive text-sm",children:[e.jsx(wo,{className:"h-4 w-4 mt-0.5 shrink-0"}),e.jsx("div",{children:"Gmail isn't connected. Connect Gmail in Integrations to send videos."})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ue,{children:"Choose a video"}),e.jsxs(H,{type:"button",variant:"ghost",size:"sm",className:"gap-1",onClick:()=>l("/innercircle/videos/record"),children:[e.jsx(Ys,{className:"h-3.5 w-3.5"})," Record new"]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(Mn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Se,{placeholder:"Search your video library...",value:x,onChange:ce=>y(ce.target.value),className:"pl-10"})]}),e.jsx("div",{className:"max-h-[220px] overflow-y-auto space-y-2 border rounded-md p-2",children:m?e.jsxs(e.Fragment,{children:[e.jsx(Ks,{className:"h-14 w-full"}),e.jsx(Ks,{className:"h-14 w-full"})]}):Z.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:d.length===0?"No videos yet. Record one to get started.":"No videos match your search."}):Z.map(ce=>{const ne=(_==null?void 0:_.id)===ce.id;return e.jsxs("button",{type:"button",onClick:()=>b(ce),className:`w-full flex items-center gap-3 p-2 rounded-md border text-left transition-colors ${ne?"border-primary bg-primary/5":"border-border hover:border-primary/50 hover:bg-accent/50"}`,children:[e.jsxs("div",{className:"w-16 h-10 rounded bg-muted flex items-center justify-center shrink-0 overflow-hidden relative",children:[ce.thumbnail_url?e.jsx("img",{src:ce.thumbnail_url,alt:"",className:"w-full h-full object-cover",referrerPolicy:"no-referrer"}):e.jsx(Qm,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/20",children:e.jsx(El,{className:"h-4 w-4 text-white"})})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:ce.title||"Untitled Video"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[ce.duration_seconds?`${Math.round(ce.duration_seconds)}s`:"",ce.created_at?` · ${new Date(ce.created_at).toLocaleDateString()}`:""]})]})]},ce.id)})})]}),e.jsx(Qo,{}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{htmlFor:"bulk-video-subject",children:"Subject"}),e.jsx(Se,{id:"bulk-video-subject",value:j,onChange:ce=>k(ce.target.value),placeholder:"I recorded a video for you"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(ue,{htmlFor:"bulk-video-message",children:["Personal message ",e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(use ","{{first_name}}"," to personalize)"]})]}),e.jsx(vr,{id:"bulk-video-message",value:T,onChange:ce=>E(ce.target.value),rows:4,className:"resize-y"})]}),A&&R.total>0&&e.jsxs("div",{className:"p-3 rounded-md bg-muted text-sm",children:["Sending… ",R.done," / ",R.total,R.failed>0&&e.jsxs("span",{className:"text-destructive ml-2",children:["(",R.failed," failed)"]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(H,{variant:"outline",onClick:()=>t(!1),disabled:A,children:"Cancel"}),ee?e.jsxs(H,{onClick:re,disabled:!ie,className:"gap-2",children:[e.jsx(ph,{className:"h-4 w-4"}),"Continue in Mass Email"]}):e.jsxs(H,{onClick:K,disabled:!ie||A,className:"gap-2",children:[A?e.jsx(is,{className:"h-4 w-4 animate-spin"}):e.jsx(yn,{className:"h-4 w-4"}),A?"Sending…":`Send to ${O.length}`]})]})]})]})})}function cMe(){const s=ba();return yt({queryKey:["drip-campaigns",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await V.from("drip_campaigns").select("*").or(`owner_user_id.eq.${s},is_starter.eq.true`).order("is_starter",{ascending:!1}).order("sort_order",{ascending:!0});if(r)throw r;return t},enabled:!!s})}function l8s(s){return yt({queryKey:["drip-campaign",s],queryFn:async()=>{if(!s)return null;const{data:t,error:r}=await V.from("drip_campaigns").select("*").eq("id",s).maybeSingle();if(r)throw r;return t},enabled:!!s})}function c8s(){const s=ba(),t=ns();return Pt({mutationFn:async r=>{if(!s)throw new Error("Not authenticated");const{data:n,error:a}=await V.from("drip_campaigns").insert({owner_user_id:s,name:r.name,description:r.description??null,category:r.category??"nurture",icon:r.icon??"🌱",cover_color:r.cover_color??"from-emerald-500 to-teal-600",goal:r.goal??null,is_active:!1}).select().single();if(a)throw a;return n},onSuccess:()=>t.invalidateQueries({queryKey:["drip-campaigns"]})})}function Vgt(){const s=ns();return Pt({mutationFn:async({id:t,...r})=>{const{data:n,error:a}=await V.from("drip_campaigns").update(r).eq("id",t).select().single();if(a)throw a;return n},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["drip-campaigns"]}),s.invalidateQueries({queryKey:["drip-campaign",r.id]})}})}function d8s(){const s=ns();return Pt({mutationFn:async t=>{const{error:r}=await V.from("drip_campaigns").delete().eq("id",t);if(r)throw r},onSuccess:()=>s.invalidateQueries({queryKey:["drip-campaigns"]})})}function u8s(){const s=ba(),t=ns();return Pt({mutationFn:async r=>{if(!s)throw new Error("Not authenticated");const[{data:n,error:a},{data:i,error:l}]=await Promise.all([V.from("drip_campaigns").select("*").eq("id",r).single(),V.from("drip_campaign_steps").select("*").eq("campaign_id",r).order("step_order")]);if(a)throw a;if(l)throw l;const{data:o,error:c}=await V.from("drip_campaigns").insert({owner_user_id:s,name:n.name,description:n.description,category:n.category,icon:n.icon,cover_color:n.cover_color,goal:n.goal,is_active:!1,is_starter:!1}).select().single();if(c)throw c;if(i&&i.length>0){const d=i.map(m=>({campaign_id:o.id,step_order:m.step_order,channel:m.channel,subject:m.subject,body:m.body,video_url:m.video_url,delay_type:m.delay_type,delay_days:m.delay_days,delay_hours:m.delay_hours,anchor_field:m.anchor_field,anchor_offset_days:m.anchor_offset_days,send_window_start:m.send_window_start,send_window_end:m.send_window_end})),{error:h}=await V.from("drip_campaign_steps").insert(d);if(h)throw h}return o},onSuccess:()=>t.invalidateQueries({queryKey:["drip-campaigns"]})})}function Hgt(s){return yt({queryKey:["drip-campaign-steps",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await V.from("drip_campaign_steps").select("*").eq("campaign_id",s).order("step_order",{ascending:!0});if(r)throw r;return t},enabled:!!s})}function h8s(){const s=ns();return Pt({mutationFn:async t=>{const{data:r,error:n}=await V.from("drip_campaign_steps").insert({campaign_id:t.campaign_id,step_order:t.step_order,channel:t.channel??"email",subject:t.subject??"",body:t.body??"",video_url:t.video_url??null,delay_type:t.delay_type??"relative",delay_days:t.delay_days??0,delay_hours:t.delay_hours??0,anchor_field:t.anchor_field??null,anchor_offset_days:t.anchor_offset_days??0}).select().single();if(n)throw n;return r},onSuccess:(t,r)=>s.invalidateQueries({queryKey:["drip-campaign-steps",r.campaign_id]})})}function m8s(){const s=ns();return Pt({mutationFn:async({id:t,campaign_id:r,...n})=>{const{data:a,error:i}=await V.from("drip_campaign_steps").update(n).eq("id",t).select().single();if(i)throw i;return{data:a,campaign_id:r}},onSuccess:t=>s.invalidateQueries({queryKey:["drip-campaign-steps",t.campaign_id]})})}function f8s(){const s=ns();return Pt({mutationFn:async({id:t,campaign_id:r})=>{const{error:n}=await V.from("drip_campaign_steps").delete().eq("id",t);if(n)throw n;return r},onSuccess:t=>s.invalidateQueries({queryKey:["drip-campaign-steps",t]})})}function p8s(s){return yt({queryKey:["campaign-enrollments",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await V.from("drip_campaign_enrollments").select("*, contact:innercircle_contacts(id, first_name, last_name, email)").eq("campaign_id",s).order("enrolled_at",{ascending:!1});if(r)throw r;return t},enabled:!!s})}function g8s(s){return yt({queryKey:["campaign-enrollment-count",s],queryFn:async()=>{if(!s)return 0;const{count:t,error:r}=await V.from("drip_campaign_enrollments").select("id",{count:"exact",head:!0}).eq("campaign_id",s).eq("status","active");if(r)throw r;return t??0},enabled:!!s,staleTime:3e4})}function Ggt(){const s=ns();return Pt({mutationFn:async({campaignId:t,contactIds:r})=>{const{data:n,error:a}=await V.functions.invoke("enroll-contacts-in-campaign",{body:{campaign_id:t,contact_ids:r}});if(a)throw a;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["campaign-enrollments"]}),s.invalidateQueries({queryKey:["contact-campaigns"]})}})}function x8s(){const s=ns();return Pt({mutationFn:async({id:t,status:r})=>{const n={status:r};r==="paused"&&(n.paused_at=new Date().toISOString()),r==="exited"&&(n.exited_at=new Date().toISOString(),n.exit_reason="manual");const{data:a,error:i}=await V.from("drip_campaign_enrollments").update(n).eq("id",t).select().single();if(i)throw i;return a},onSuccess:()=>{s.invalidateQueries({queryKey:["campaign-enrollments"]}),s.invalidateQueries({queryKey:["contact-campaigns"]})}})}const y8s=[{key:"{{client_first_name}}",label:"Client First Name"},{key:"{{client_last_name}}",label:"Client Last Name"},{key:"{{agent_name}}",label:"Your Name"},{key:"{{agent_first_name}}",label:"Your First Name"},{key:"{{agent_phone}}",label:"Your Phone"},{key:"{{review_link}}",label:"Review Link"},{key:"{{lead_site_url}}",label:"Your Website"},{key:"{{lead_site_search_url}}",label:"Your Website — Search"},{key:"{{lead_site_valuation_url}}",label:"Your Website — Home Value"},{key:"{{lead_site_blog_url}}",label:"Your Website — Blog"}],R0e={nurture:"New Lead Nurture",sphere:"Sphere of Influence",buyer:"Buyer",seller:"Seller",fsbo:"FSBO",past_client:"Past Client",birthday:"Birthday",anniversary:"Home Anniversary",custom:"Custom"},v8s={nurture:"from-emerald-500 to-teal-600",sphere:"from-rose-500 to-pink-600",buyer:"from-cyan-500 to-blue-600",seller:"from-indigo-500 to-purple-600",fsbo:"from-red-500 to-orange-600",past_client:"from-purple-500 to-violet-600",birthday:"from-amber-500 to-orange-600",anniversary:"from-blue-500 to-indigo-600",custom:"from-slate-500 to-gray-600"};function H8({userId:s,onSelect:t,onSelectVideo:r,triggerLabel:n="Library",triggerSize:a="sm",triggerVariant:i="outline",triggerClassName:l}){const[o,c]=S.useState(!1),[d,h]=S.useState([]),[m,p]=S.useState(!1),[x,y]=S.useState("");S.useEffect(()=>{!o||!s||(p(!0),V.from("agent_videos").select("id, title, recipient_name, playback_url, thumbnail_url, created_at, duration_seconds").eq("owner_user_id",s).eq("is_deleted",!1).eq("status","ready").order("created_at",{ascending:!1}).limit(50).then(({data:b})=>{h(b||[]),p(!1)}))},[o,s]);const _=d.filter(b=>!x||(b.title||b.recipient_name||"").toLowerCase().includes(x.toLowerCase()));return e.jsxs(bs,{open:o,onOpenChange:c,children:[e.jsx(Qi,{asChild:!0,children:e.jsxs(H,{variant:i,size:a,className:l||"gap-1.5 shrink-0",children:[e.jsx(Qm,{className:"h-3.5 w-3.5"}),n]})}),e.jsxs(vs,{className:"max-w-lg max-h-[70vh] flex flex-col",children:[e.jsxs(Cs,{children:[e.jsx(Ns,{children:"Select from Video Library"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Choose a video from your library"})]}),e.jsxs("div",{className:"relative mb-3",children:[e.jsx(Mn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Se,{placeholder:"Search videos...",value:x,onChange:b=>y(b.target.value),className:"pl-10"})]}),e.jsx("div",{className:"flex-1 overflow-y-auto space-y-2 min-h-0",children:m?e.jsxs(e.Fragment,{children:[e.jsx(Ks,{className:"h-16 w-full"}),e.jsx(Ks,{className:"h-16 w-full"})]}):_.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:d.length===0?"No videos in your library yet":"No videos match your search"}):_.map(b=>e.jsxs("button",{onClick:()=>{t(b.playback_url||""),r==null||r(b),c(!1)},className:"w-full flex items-center gap-3 p-3 rounded-lg border border-border hover:border-primary/50 hover:bg-accent/50 transition-colors text-left",children:[e.jsx("div",{className:"w-16 h-10 rounded bg-muted flex items-center justify-center shrink-0 overflow-hidden",children:b.thumbnail_url?e.jsx("img",{src:b.thumbnail_url,alt:"",className:"w-full h-full object-cover",referrerPolicy:"no-referrer",onError:j=>{const k=j.currentTarget.parentElement;if(k){j.currentTarget.remove();const T=document.createElement("span");T.innerHTML="🎬",T.className="text-lg",k.appendChild(T)}}}):e.jsx(xn,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:b.title||b.recipient_name||"Untitled Video"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[b.duration_seconds?`${Math.round(b.duration_seconds)}s`:"",b.created_at?` · ${new Date(b.created_at).toLocaleDateString()}`:""]})]})]},b.id))})]})]})}function b8s(){return yt({queryKey:["video-script-categories"],queryFn:async()=>{const{data:s,error:t}=await V.from("video_script_categories").select("*").order("sort_order");if(t)throw t;return s}})}function _8s(s){return yt({queryKey:["video-scripts",s],queryFn:async()=>{let t=V.from("video_scripts").select("*, category:video_script_categories(*)").eq("is_active",!0).order("title");const{data:r,error:n}=await t;if(n)throw n;return r}})}function w8s(){const{user:s}=Ms();return yt({queryKey:["user-video-scripts",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return[];const{data:t,error:r}=await V.from("user_video_scripts").select("*, category:video_script_categories(*)").eq("owner_user_id",s.id).order("title");if(r)throw r;return t},enabled:!!(s!=null&&s.id)})}function j8s(){const{user:s}=Ms(),t=ns();return Pt({mutationFn:async r=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{data:n,error:a}=await V.from("user_video_scripts").insert([{owner_user_id:s.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(a)throw a;return n},onSuccess:()=>{t.invalidateQueries({queryKey:["user-video-scripts"]})}})}function N8s(s){const{user:t}=Ms();return yt({queryKey:["agent-videos",t==null?void 0:t.id,s],queryFn:async()=>{if(!(t!=null&&t.id))return[];let r=V.from("agent_videos").select("*, contact:innercircle_contacts(id, first_name, last_name)").eq("owner_user_id",t.id).order("created_at",{ascending:!1});r=r.eq("is_deleted",!1);const{data:n,error:a}=await r;if(a)throw a;return n},enabled:!!(t!=null&&t.id)})}function k8s(s){return yt({queryKey:["agent-video",s],queryFn:async()=>{const{data:t,error:r}=await V.from("agent_videos").select("*, contact:innercircle_contacts(id, first_name, last_name)").eq("id",s).single();if(r)throw r;return t},enabled:!!s})}function Cj(){const{user:s}=Ms(),t=ns();return Pt({mutationFn:async r=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{data:n,error:a}=await V.from("agent_videos").insert([{owner_user_id:s.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",page_template:"default",category:r.category||"general"}]).select("*, share_token").single();if(a)throw a;return n},onSuccess:()=>{t.invalidateQueries({queryKey:["agent-videos"]}),t.invalidateQueries({queryKey:["storage-usage"]})}})}function S8s(){const s=ns();return Pt({mutationFn:async({id:t,...r})=>{const{data:n,error:a}=await V.from("agent_videos").update(r).eq("id",t).select().single();if(a)throw a;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["agent-videos"]}),s.invalidateQueries({queryKey:["agent-video",t.id]})}})}function C8s(){const s=ns();return Pt({mutationFn:async({id:t,bunnyVideoId:r,hardDelete:n=!1})=>{if(console.log("Deleting video:",{id:t,bunnyVideoId:r,hardDelete:n}),r){console.log("Calling bunny-upload delete for videoId:",r);const{data:a,error:i}=await V.functions.invoke("bunny-upload",{body:{action:"delete",videoId:r,isAgentVideo:!0}});i?console.error("Failed to delete from Bunny:",i):console.log("Bunny delete response:",a)}else console.warn("No bunnyVideoId provided, skipping Bunny.net deletion");if(n){console.log("Hard deleting from database:",t);const{error:a}=await V.from("agent_videos").delete().eq("id",t);if(a)throw a}else{console.log("Soft deleting from database:",t);const{error:a}=await V.from("agent_videos").update({is_deleted:!0}).eq("id",t);if(a)throw a}console.log("Video deletion complete")},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-videos"]}),s.invalidateQueries({queryKey:["storage-usage"]})}})}function O0e(){const{user:s}=Ms();return yt({queryKey:["storage-usage",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return null;const{data:t,error:r}=await V.from("agent_storage_usage").select("*").eq("user_id",s.id).maybeSingle();if(r)throw r;return t||{user_id:s.id,total_storage_mb:0,storage_tier:"basic",max_storage_mb:1024}},enabled:!!(s!=null&&s.id)})}function Wgt(){const{data:s,isLoading:t}=O0e(),r=s?s.total_storage_mb0?s.total_storage_mb/s.max_storage_mb*100:0,i=a>=80;return{canRecord:r,remainingMb:n,usagePercent:a,isNearLimit:i,storage:s,isLoading:t}}async function tM(s){const{data:t,error:r}=await V.functions.invoke("bunny-upload",{body:{action:"create",title:s,isAgentVideo:!0}});if(r)throw r;return t}async function sM(s){const{data:t,error:r}=await V.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:s,isAgentVideo:!0}});if(r)throw r;return t}async function F_(s){const{data:t,error:r}=await V.functions.invoke("bunny-upload",{body:{action:"status",videoId:s,isAgentVideo:!0}});if(r)throw r;return t}function T8s(){const{user:s}=Ms(),t=ns();return Pt({mutationFn:async({contactId:r,videoId:n,notes:a})=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{data:i}=await V.from("action_types").select("id").eq("name","Video").single();if(!i)throw new Error("Video action type not found");const{data:l,error:o}=await V.from("contact_touch_logs").insert([{owner_user_id:s.id,contact_id:r,action_type_id:i.id,notes:a||`Quick Video Touch - Video ID: ${n}`}]).select().single();if(o)throw o;return l},onSuccess:()=>{t.invalidateQueries({queryKey:["contact-touch-logs"]}),t.invalidateQueries({queryKey:["contacts"]})}})}function Kgt({open:s,onOpenChange:t,onUploadComplete:r}){const{data:n}=Cp(),{data:a}=O0e(),i=Cj(),l=S.useRef(null),[o,c]=S.useState(null),[d,h]=S.useState(""),[m,p]=S.useState(""),[x,y]=S.useState(""),[_,b]=S.useState(!1),[j,k]=S.useState(0),[T,E]=S.useState("idle"),A=(a==null?void 0:a.total_storage_mb)||0,R=((a==null?void 0:a.max_storage_mb)||1024)-A,z=Z=>{var re;const J=(re=Z.target.files)==null?void 0:re[0];if(!J)return;if(!J.type.startsWith("video/")){he.error("Please select a video file");return}const K=J.size/(1024*1024);if(K>500){he.error("Video file must be less than 500MB");return}if(K>R){he.error(`Not enough storage. You have ${R.toFixed(1)} MB remaining.`);return}c(J),d||h(J.name.replace(/\.[^/.]+$/,""))},O=async()=>{if(!o){he.error("Please select a video file");return}b(!0),k(0),E("creating");try{const{data:Z,error:J}=await V.functions.invoke("bunny-upload",{body:{action:"create",title:d||o.name,isAgentVideo:!0}});if(J)throw new Error(J.message);const{videoId:K,libraryId:re}=Z;E("uploading");const{data:ie,error:ce}=await V.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:K,isAgentVideo:!0}});if(ce)throw new Error(ce.message);await new Promise((be,fe)=>{const je=new XMLHttpRequest;je.upload.addEventListener("progress",ve=>{if(ve.lengthComputable){const We=Math.round(ve.loaded/ve.total*100);k(We)}}),je.addEventListener("load",()=>{je.status>=200&&je.status<300?be():fe(new Error(`Upload failed with status ${je.status}`))}),je.addEventListener("error",()=>fe(new Error("Upload failed"))),je.open("PUT",ie.uploadUrl),je.setRequestHeader("AccessKey",ie.apiKey),je.send(o)}),E("processing");const ne=o.size/(1024*1024),le=`https://iframe.mediadelivery.net/embed/${re}/${K}`;await i.mutateAsync({bunny_video_id:K,playback_url:le,file_size_mb:ne,title:d||o.name,notes:m||void 0,contact_id:x||void 0,status:"processing",touch_type:"video_upload"}),he.success("Video uploaded successfully! Processing may take a few minutes."),r==null||r(le),$()}catch(Z){console.error("Upload error:",Z),he.error(Z instanceof Error?Z.message:"Failed to upload video")}finally{b(!1),E("idle")}},$=()=>{_||(c(null),h(""),p(""),y(""),k(0),E("idle"),t(!1))},ee=()=>{switch(T){case"creating":return"Preparing upload...";case"uploading":return`Uploading... ${j}%`;case"processing":return"Saving video...";default:return""}};return e.jsx(bs,{open:s,onOpenChange:$,children:e.jsxs(vs,{className:"sm:max-w-md",children:[e.jsxs(Cs,{children:[e.jsx(Ns,{children:"Upload Video"}),e.jsx(nn,{children:"Upload a video file from your device to your video library."})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Video File"}),o?e.jsxs("div",{className:"flex items-center gap-3 p-3 bg-muted rounded-lg",children:[e.jsx(xn,{className:"h-8 w-8 text-primary flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:o.name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(o.size/(1024*1024)).toFixed(1)," MB"]})]}),!_&&e.jsx(H,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:Z=>{Z.stopPropagation(),c(null)},children:e.jsx(Rr,{className:"h-4 w-4"})})]}):e.jsxs("div",{className:"border-2 border-dashed border-muted-foreground/25 rounded-lg p-8 text-center cursor-pointer hover:border-primary/50 transition-colors",onClick:()=>{var Z;return(Z=l.current)==null?void 0:Z.click()},children:[e.jsx(Ea,{className:"h-8 w-8 mx-auto text-muted-foreground mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Click to select a video file"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"MP4, MOV, WebM (max 500MB)"})]}),e.jsx("input",{ref:l,type:"file",accept:"video/*",className:"hidden",onChange:z,disabled:_})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"title",children:"Title"}),e.jsx(Se,{id:"title",value:d,onChange:Z=>h(Z.target.value),placeholder:"Enter video title",disabled:_})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Associate with Contact (optional)"}),e.jsxs(Bs,{value:x||"__none__",onValueChange:Z=>y(Z==="__none__"?"":Z),disabled:_,children:[e.jsx(Os,{children:e.jsx(Us,{placeholder:"Select a contact"})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"__none__",children:"No contact"}),n==null?void 0:n.map(Z=>e.jsxs(pt,{value:Z.id,children:[Z.first_name," ",Z.last_name||""]},Z.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"notes",children:"Notes (optional)"}),e.jsx(vr,{id:"notes",value:m,onChange:Z=>p(Z.target.value),placeholder:"Add any notes about this video",rows:2,disabled:_})]}),_&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(is,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{children:ee()})]}),e.jsx(Mi,{value:T==="uploading"?j:T==="processing"?100:10})]})]}),e.jsxs(wn,{children:[e.jsx(H,{variant:"outline",onClick:$,disabled:_,children:"Cancel"}),e.jsx(H,{onClick:O,disabled:!o||_,children:_?e.jsxs(e.Fragment,{children:[e.jsx(is,{className:"h-4 w-4 mr-2 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ea,{className:"h-4 w-4 mr-2"}),"Upload Video"]})})]})]})})}const E8s=["🌱","💎","🏠","🔑","📧","💌","🎂","🥂","🤝","⭐","🎉","📞"];function Ygt({open:s,onOpenChange:t,campaignId:r}){const[n,a]=S.useState(r??null),[i,l]=S.useState("details");S.useEffect(()=>{a(r??null),l("details")},[r,s]);const o=n,c=!!o,{data:d}=l8s(o||void 0),{data:h,isLoading:m}=Hgt(o||void 0),p=c8s(),x=Vgt(),y=h8s(),[_,b]=S.useState(""),[j,k]=S.useState(""),[T,E]=S.useState("nurture"),[A,D]=S.useState("🌱"),[R,z]=S.useState("");S.useEffect(()=>{d?(b(d.name),k(d.description||""),E(d.category),D(d.icon),z(d.goal||"")):c||(b(""),k(""),E("nurture"),D("🌱"),z(""))},[d,c,s]);const O=v8s[T],$=async()=>{if(!_.trim()){he.error("Give your campaign a name");return}try{if(c&&o)await x.mutateAsync({id:o,name:_,description:j,category:T,icon:A,goal:R,cover_color:O}),he.success("Campaign updated");else{const Z=await p.mutateAsync({name:_,description:j,category:T,icon:A,goal:R,cover_color:O});return he.success("Campaign created — now add your first step!"),a(Z.id),l("steps"),Z}}catch(Z){he.error(Z.message||"Failed to save")}},ee=async()=>{if(!o){he.error("Save the campaign first, then add steps");return}const Z=((h==null?void 0:h.length)||0)+1;try{await y.mutateAsync({campaign_id:o,step_order:Z,channel:"email",subject:"",body:"",delay_type:"relative",delay_days:Z===1?0:2,delay_hours:0})}catch{he.error("Failed to add step")}};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-3xl max-h-[90vh] flex flex-col p-0 overflow-hidden",children:[e.jsx("div",{className:`bg-gradient-to-br ${O} p-5 text-white shrink-0`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("span",{className:"text-4xl drop-shadow-sm",children:A}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(Ns,{className:"text-lg font-bold text-white",children:c?"Edit Campaign":"Create New Campaign"}),e.jsx(nn,{className:"text-white/85 text-xs mt-0.5",children:"Design a multi-step nurture sequence. Steps are sent in order with your chosen delays."})]})]})}),e.jsxs(ta,{value:i,onValueChange:Z=>l(Z),className:"flex-1 flex flex-col overflow-hidden min-h-0",children:[e.jsxs(Qn,{className:"mx-5 mt-4 grid grid-cols-2 w-fit",children:[e.jsx(ts,{value:"details",children:"Details"}),e.jsxs(ts,{value:"steps",disabled:!c,children:["Steps ",h&&h.length>0&&e.jsx(Xe,{variant:"secondary",className:"ml-1.5 text-[10px]",children:h.length})]})]}),e.jsx(cs,{value:"details",className:"flex-1 overflow-hidden mt-0 min-h-0",children:e.jsx(Ci,{className:"h-full",children:e.jsxs("div",{className:"p-5 space-y-4",children:[e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs",children:"Campaign Name *"}),e.jsx(Se,{value:_,onChange:Z=>b(Z.target.value),placeholder:"e.g. New Buyer Lead — 7 Touch Nurture",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs",children:"Description"}),e.jsx(vr,{value:j,onChange:Z=>k(Z.target.value),placeholder:"What's this campaign for? When should you use it?",rows:2,className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs",children:"Goal (optional)"}),e.jsx(Se,{value:R,onChange:Z=>z(Z.target.value),placeholder:"e.g. Book a buyer consultation within 14 days",className:"mt-1"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs",children:"Category"}),e.jsxs(Bs,{value:T,onValueChange:Z=>E(Z),children:[e.jsx(Os,{className:"mt-1",children:e.jsx(Us,{})}),e.jsx(Fs,{children:Object.entries(R0e).map(([Z,J])=>e.jsx(pt,{value:Z,children:J},Z))})]})]}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs",children:"Icon"}),e.jsx("div",{className:"flex gap-1.5 flex-wrap mt-1",children:E8s.map(Z=>e.jsx("button",{type:"button",onClick:()=>D(Z),className:`h-8 w-8 rounded-md text-lg flex items-center justify-center transition-all ${A===Z?"bg-primary/15 ring-2 ring-primary":"hover:bg-muted"}`,children:Z},Z))})]})]}),e.jsx("div",{className:"border-t pt-4",children:e.jsx("p",{className:"text-xs text-muted-foreground",children:c?"Save changes, then jump to the Steps tab to manage your sequence.":"Save to create the campaign, then you can add steps to it."})})]})})}),e.jsx(cs,{value:"steps",className:"flex-1 overflow-hidden mt-0 min-h-0",children:e.jsx(Ci,{className:"h-full",children:e.jsx("div",{className:"p-5 space-y-3",children:m?e.jsx("div",{className:"text-center text-sm text-muted-foreground py-8",children:"Loading steps…"}):!h||h.length===0?e.jsxs("div",{className:"text-center py-10 border border-dashed rounded-xl",children:[e.jsx(Lr,{className:"h-8 w-8 text-muted-foreground/40 mx-auto mb-2"}),e.jsx("p",{className:"text-sm font-medium mb-1",children:"No steps yet"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-3",children:"Build your sequence — each step waits for its delay, then sends."}),e.jsxs(H,{size:"sm",onClick:ee,disabled:y.isPending,children:[e.jsx(Ys,{className:"h-3.5 w-3.5 mr-1.5"})," Add first step"]})]}):e.jsxs(e.Fragment,{children:[h.map((Z,J)=>e.jsx(A8s,{step:Z,index:J,totalSteps:h.length},Z.id)),e.jsxs(H,{variant:"outline",size:"sm",onClick:ee,disabled:y.isPending,className:"w-full",children:[y.isPending?e.jsx(is,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(Ys,{className:"h-3.5 w-3.5 mr-1.5"}),"Add another step"]})]})})})})]}),e.jsxs(wn,{className:"border-t p-4 shrink-0",children:[e.jsx(H,{variant:"outline",onClick:()=>t(!1),children:c?"Done":"Cancel"}),e.jsxs(H,{onClick:$,disabled:p.isPending||x.isPending,children:[(p.isPending||x.isPending)&&e.jsx(is,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),c?"Save Changes":"Create Campaign"]})]})]})})}function A8s({step:s,index:t,totalSteps:r}){const n=m8s(),a=f8s(),i=ba(),[l,o]=S.useState(!1),[c,d]=S.useState(s),[h,m]=S.useState(!1),[p,x]=S.useState(!1),[y,_]=S.useState(""),[b,j]=S.useState(!1);S.useEffect(()=>d(s),[s]);const k=JSON.stringify(c)!==JSON.stringify(s),T=async()=>{m(!0);try{await n.mutateAsync({id:s.id,campaign_id:s.campaign_id,channel:c.channel,subject:c.subject,body:c.body,video_url:c.video_url,delay_type:c.delay_type,delay_days:c.delay_days,delay_hours:c.delay_hours,anchor_field:c.anchor_field,anchor_offset_days:c.anchor_offset_days}),he.success(`Step ${t+1} saved`)}catch{he.error("Failed to save step")}finally{m(!1)}},E=async()=>{if(confirm(`Delete step ${t+1}?`))try{await a.mutateAsync({id:s.id,campaign_id:s.campaign_id}),he.success("Step deleted")}catch{he.error("Failed to delete")}},A=R=>{d({...c,body:c.body+R})},D=()=>{if(c.delay_type==="calendar_anchor"){const z=c.anchor_field==="birthday"?"birthday":"home anniversary",O=c.anchor_offset_days||0;return O===0?`On their ${z}`:O<0?`${Math.abs(O)}d before ${z}`:`${O}d after ${z}`}if(t===0&&!c.delay_days&&!c.delay_hours)return"Sends immediately";const R=[];return c.delay_days&&R.push(`${c.delay_days}d`),c.delay_hours&&R.push(`${c.delay_hours}h`),t===0?`After ${R.join(" ")||"0"}`:`+${R.join(" ")||"0"}`};return e.jsxs("div",{className:"border rounded-lg bg-card overflow-hidden",children:[e.jsxs("div",{className:"flex items-center gap-2 p-3 hover:bg-muted/30 cursor-pointer",onClick:()=>o(!l),children:[e.jsx("div",{className:"h-7 w-7 shrink-0 rounded-full bg-primary/10 text-primary flex items-center justify-center text-xs font-semibold",children:t+1}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[c.delay_type==="calendar_anchor"?e.jsx(Nn,{className:"h-3 w-3"}):e.jsx(Pn,{className:"h-3 w-3"}),e.jsx("span",{children:D()}),e.jsx("span",{children:"·"}),c.channel==="email"?e.jsx(er,{className:"h-3 w-3"}):e.jsx(Gi,{className:"h-3 w-3"}),e.jsx("span",{className:"capitalize",children:c.channel})]}),e.jsx("p",{className:"text-sm font-medium truncate mt-0.5",children:c.subject||e.jsx("span",{className:"text-muted-foreground italic",children:"No subject"})})]}),l?e.jsx(cx,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(Io,{className:"h-4 w-4 text-muted-foreground"})]}),l&&e.jsxs("div",{className:"border-t p-4 space-y-3 bg-muted/10",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs",children:"Channel"}),e.jsxs(Bs,{value:c.channel,onValueChange:R=>d({...c,channel:R}),children:[e.jsx(Os,{className:"mt-1 h-9",children:e.jsx(Us,{})}),e.jsx(Fs,{children:e.jsx(pt,{value:"email",children:"📧 Email"})})]})]}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs",children:"Timing Type"}),e.jsxs(Bs,{value:c.delay_type,onValueChange:R=>d({...c,delay_type:R}),children:[e.jsx(Os,{className:"mt-1 h-9",children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"relative",children:"⏱ Relative delay"}),e.jsx(pt,{value:"calendar_anchor",children:"📅 Calendar date"})]})]})]})]}),c.delay_type==="relative"?e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs",children:"Days delay"}),e.jsx(Se,{type:"number",min:0,value:c.delay_days,onChange:R=>d({...c,delay_days:parseInt(R.target.value)||0}),className:"mt-1 h-9"})]}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs",children:"Hours delay"}),e.jsx(Se,{type:"number",min:0,max:23,value:c.delay_hours,onChange:R=>d({...c,delay_hours:parseInt(R.target.value)||0}),className:"mt-1 h-9"})]})]}):e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs",children:"Anchor"}),e.jsxs(Bs,{value:c.anchor_field||"birthday",onValueChange:R=>d({...c,anchor_field:R}),children:[e.jsx(Os,{className:"mt-1 h-9",children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"birthday",children:"🎂 Birthday"}),e.jsx(pt,{value:"home_anniversary",children:"🏠 Home Anniversary"})]})]})]}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs",children:"Offset (days, negative = before)"}),e.jsx(Se,{type:"number",value:c.anchor_offset_days||0,onChange:R=>d({...c,anchor_offset_days:parseInt(R.target.value)||0}),className:"mt-1 h-9",placeholder:"0 = on the day, -7 = week before"})]})]}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs",children:"Subject Line"}),e.jsx(Se,{value:c.subject,onChange:R=>d({...c,subject:R.target.value}),placeholder:"e.g. Quick question about your home search, {{client_first_name}}",className:"mt-1 h-9"})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx(ue,{className:"text-xs",children:"Email Body"}),e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[c.body.length," chars"]})]}),e.jsx(vr,{value:c.body,onChange:R=>d({...c,body:R.target.value}),placeholder:`Hi {{client_first_name}}, I wanted to reach out and...`,rows:6,className:"mt-1 font-mono text-xs"}),e.jsxs("div",{className:"flex flex-wrap gap-1 mt-2",children:[e.jsx("span",{className:"text-[10px] text-muted-foreground mr-1",children:"Insert:"}),y8s.map(R=>e.jsx("button",{type:"button",onClick:()=>A(R.key),className:"text-[10px] px-1.5 py-0.5 rounded bg-primary/10 text-primary hover:bg-primary/20",children:R.label},R.key))]})]}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs",children:"Video (optional)"}),c.video_url?e.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[e.jsxs("div",{className:"flex-1 text-xs text-muted-foreground truncate bg-muted/50 rounded px-2 py-1.5 border border-input",children:[e.jsx(xn,{className:"h-3 w-3 inline mr-1 text-primary"}),c.video_url.length>50?c.video_url.slice(0,50)+"...":c.video_url]}),e.jsx(H,{variant:"ghost",size:"sm",className:"h-7 text-xs text-destructive",onClick:()=>d({...c,video_url:null}),children:"Remove"})]}):e.jsxs("div",{className:"mt-1 flex items-center gap-1.5 flex-wrap",children:[e.jsx(H8,{userId:i||void 0,onSelect:R=>d({...c,video_url:R}),triggerSize:"sm",triggerClassName:"gap-1.5 flex-1 min-w-[120px]"}),e.jsxs(H,{variant:"outline",size:"sm",className:"gap-1 text-xs flex-1 min-w-[120px]",onClick:()=>j(!0),children:[e.jsx(Ea,{className:"h-3 w-3"})," Upload"]}),e.jsxs(H,{variant:"ghost",size:"sm",className:"gap-1 text-xs text-muted-foreground flex-1 min-w-[120px]",onClick:()=>{_(""),x(!0)},children:[e.jsx(Jo,{className:"h-3 w-3"})," Paste URL"]}),e.jsx(Kgt,{open:b,onOpenChange:j,onUploadComplete:R=>d({...c,video_url:R})}),e.jsx(bs,{open:p,onOpenChange:x,children:e.jsxs(vs,{className:"sm:max-w-md",children:[e.jsxs(Cs,{children:[e.jsx(Ns,{children:"Add video URL"}),e.jsx(nn,{children:"Paste a YouTube, Loom, or direct video URL."})]}),e.jsx(Se,{value:y,onChange:R=>_(R.target.value),placeholder:"https://...",autoFocus:!0,onKeyDown:R=>{R.key==="Enter"&&y.trim()&&(d({...c,video_url:y.trim()}),x(!1))}}),e.jsxs(wn,{children:[e.jsx(H,{variant:"ghost",onClick:()=>x(!1),children:"Cancel"}),e.jsx(H,{disabled:!y.trim(),onClick:()=>{d({...c,video_url:y.trim()}),x(!1)},children:"Add video"})]})]})})]})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t",children:[e.jsxs(H,{variant:"ghost",size:"sm",onClick:E,className:"text-destructive hover:text-destructive",children:[e.jsx(Dr,{className:"h-3.5 w-3.5 mr-1"})," Delete step"]}),e.jsxs(H,{size:"sm",onClick:T,disabled:!k||h,children:[h&&e.jsx(is,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),"Save step"]})]})]})]})}function M8s({open:s,onOpenChange:t,contactIds:r,onSuccess:n}){const{data:a,isLoading:i}=cMe(),l=Ggt(),[o,c]=S.useState(""),[d,h]=S.useState(null),[m,p]=S.useState(!1),x=(a||[]).filter(b=>!b.is_starter),y=x.filter(b=>b.name.toLowerCase().includes(o.toLowerCase())||(b.description||"").toLowerCase().includes(o.toLowerCase())),_=async()=>{if(d)try{const b=await l.mutateAsync({campaignId:d,contactIds:r}),j=[`${b.enrolled} enrolled`];b.skipped>0&&j.push(`${b.skipped} skipped`),b.errors>0&&j.push(`${b.errors} errors`),he.success(j.join(" · ")),t(!1),h(null),n==null||n()}catch(b){he.error(b.message||"Failed to enroll contacts")}};return e.jsxs(bs,{open:s,onOpenChange:t,children:[e.jsxs(vs,{className:"max-w-md",children:[e.jsxs(Cs,{children:[e.jsxs(Ns,{className:"flex items-center gap-2",children:[e.jsx(Lr,{className:"h-4 w-4 text-primary"}),"Enroll in Drip Campaign"]}),e.jsxs(nn,{children:[r.length," contact",r.length!==1?"s":""," will be added to the selected campaign. Already-enrolled contacts will be skipped."]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Mn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(Se,{placeholder:"Search campaigns...",value:o,onChange:b=>c(b.target.value),className:"pl-9 h-9"})]}),e.jsx(Ci,{className:"h-[320px] -mx-1 px-1",children:i?e.jsx("div",{className:"text-center py-8 text-sm text-muted-foreground",children:"Loading..."}):y.length===0?e.jsx("div",{className:"text-center py-8",children:x.length===0?e.jsxs(e.Fragment,{children:[e.jsx(Lr,{className:"h-8 w-8 text-muted-foreground/40 mx-auto mb-2"}),e.jsx("p",{className:"text-sm font-medium mb-1",children:"No campaigns yet"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-3",children:"Build a custom drip campaign to nurture these contacts on autopilot."}),e.jsxs(H,{size:"sm",onClick:()=>p(!0),children:[e.jsx(Ys,{className:"h-3.5 w-3.5 mr-1.5"})," Create campaign"]})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"No campaigns match your search."})}):e.jsx("div",{className:"space-y-1.5",children:y.map(b=>e.jsxs("button",{onClick:()=>h(b.id),className:`w-full flex items-start gap-3 p-3 rounded-lg border text-left transition-all ${d===b.id?"border-primary bg-primary/5 ring-1 ring-primary":"border-border hover:border-primary/40 hover:bg-muted/30"}`,children:[e.jsx("div",{className:`shrink-0 h-9 w-9 rounded-lg bg-gradient-to-br ${b.cover_color} flex items-center justify-center text-lg`,children:b.icon}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:b.name}),b.is_active&&e.jsx(Xe,{variant:"outline",className:"text-[9px] bg-emerald-500/10 text-emerald-600 border-emerald-200 px-1 py-0",children:"Active"})]}),b.description&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 mt-0.5",children:b.description})]}),d===b.id&&e.jsx(va,{className:"h-4 w-4 text-primary shrink-0 mt-1"})]},b.id))})})]}),e.jsxs(wn,{className:"gap-2 sm:gap-2",children:[x.length>0&&e.jsxs(H,{variant:"ghost",size:"sm",onClick:()=>p(!0),className:"mr-auto text-xs",children:[e.jsx(Ys,{className:"h-3.5 w-3.5 mr-1"})," New campaign"]}),e.jsx(H,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(H,{onClick:_,disabled:!d||l.isPending,children:[l.isPending&&e.jsx(is,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),"Enroll ",r.length," contact",r.length!==1?"s":""]})]})]}),e.jsx(Ygt,{open:m,onOpenChange:p})]})}function I8s({selectedIds:s,contacts:t,onClearSelection:r,onSendToLeadPond:n,showLeadPondAction:a,onTransfer:i,showTransferAction:l}){const o=Fr(),{data:c}=R0(),d=vTe(),h=ns(),{isGmailConnected:m}=cf(),{isReady:p}=Dz(),{data:x}=q8(),y=aMe(),_=Rgt(),[b,j]=S.useState(!1),[k,T]=S.useState(!1),[E,A]=S.useState(!1),[D,R]=S.useState(!1),[z,O]=S.useState(!1),[$,ee]=S.useState(""),Z=s.size;if(Z===0)return null;const J=async be=>{j(!0);try{const je=Array.from(s).map(We=>({contact_id:We,relationship_type_id:be})),{error:ve}=await V.from("innercircle_contact_tags").upsert(je,{onConflict:"contact_id,relationship_type_id",ignoreDuplicates:!0});if(ve)throw ve;h.invalidateQueries({queryKey:["innercircle-contacts"]}),h.invalidateQueries({queryKey:["innercircle-contact-counts"]}),En({title:`Assigned type to ${Z} contacts`}),r()}catch(fe){En({title:"Error assigning type",description:fe.message,variant:"destructive"})}finally{j(!1)}},K=async be=>{j(!0);try{const fe=Array.from(s);for(const je of fe)try{await _.mutateAsync({contactId:je,tagId:be})}catch{}h.invalidateQueries({queryKey:["all-contact-custom-tags"]}),En({title:`Tagged ${Z} contacts`}),O(!1),ee("")}catch(fe){En({title:"Error adding tags",description:fe.message,variant:"destructive"})}finally{j(!1)}},re=async()=>{if($.trim()){j(!0);try{const be=await y.mutateAsync({name:$.trim()});await K(be.id)}catch(be){En({title:"Error creating tag",description:be.message,variant:"destructive"}),j(!1)}}},ie=(x==null?void 0:x.filter(be=>be.name.toLowerCase().includes($.toLowerCase())))||[],ce=x==null?void 0:x.find(be=>be.name.toLowerCase()===$.trim().toLowerCase()),ne=()=>{const be=t.filter(Me=>s.has(Me.id)),fe=["First Name","Last Name","Email","Phone","Address","Birthday","Home Anniversary","Notes","Relationship Types"],je=be.map(Me=>{var ze;return[Me.first_name,Me.last_name||"",Me.email||"",Me.phone||"",Me.address||"",Me.birthday||"",Me.home_anniversary||"",Me.notes||"",((ze=Me.tags)==null?void 0:ze.map(Pe=>{var Ie;return(Ie=Pe.relationship_type)==null?void 0:Ie.name}).join("; "))||""]}),ve=[fe.join(","),...je.map(Me=>Me.map(ze=>`"${(ze||"").replace(/"/g,'""')}"`).join(","))].join(` `),We=new Blob([ve],{type:"text/csv"}),Ve=URL.createObjectURL(We),Le=document.createElement("a");Le.href=Ve,Le.download=`contacts-export-${new Date().toISOString().slice(0,10)}.csv`,Le.click(),URL.revokeObjectURL(Ve),En({title:`Exported ${Z} contacts`})},le=async()=>{if(confirm(`Are you sure you want to delete ${Z} contacts? This cannot be undone.`)){j(!0);try{const be=Array.from(s);for(const fe of be)await d.mutateAsync(fe);r()}catch(be){En({title:"Error deleting contacts",description:be.message,variant:"destructive"})}finally{j(!1)}}};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-3 p-3 bg-primary/5 border border-primary/20 rounded-lg",children:[e.jsxs(Xe,{variant:"secondary",className:"font-semibold",children:[Z," selected"]}),e.jsxs(Bs,{onValueChange:J,disabled:b,children:[e.jsx(Os,{className:"w-[180px] h-8",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(xm,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"text-sm",children:"Assign Type"})]})}),e.jsx(Fs,{children:c==null?void 0:c.filter(be=>be.active).map(be=>e.jsx(pt,{value:be.id,children:be.name},be.id))})]}),e.jsxs(gl,{open:z,onOpenChange:O,children:[e.jsx(xl,{asChild:!0,children:e.jsxs(H,{variant:"outline",size:"sm",disabled:b,children:[e.jsx(Ys,{className:"h-3.5 w-3.5 mr-1"}),"Add Tag"]})}),e.jsxs(il,{className:"w-56 p-2",align:"start",children:[e.jsx(Se,{placeholder:"Search or create tag...",value:$,onChange:be=>ee(be.target.value),onKeyDown:be=>{be.key==="Enter"&&$.trim()&&!ce?(be.preventDefault(),re()):be.key==="Enter"&&ce&&(be.preventDefault(),K(ce.id))},className:"h-8 text-sm mb-2"}),e.jsxs("div",{className:"max-h-[200px] overflow-y-auto space-y-0.5",children:[ie.map(be=>e.jsxs("button",{onClick:()=>K(be.id),className:"flex items-center gap-2 w-full px-2 py-1.5 rounded-md text-sm hover:bg-accent transition-colors",children:[e.jsx("div",{className:"h-3 w-3 rounded-full shrink-0",style:{backgroundColor:be.color}}),e.jsx("span",{className:"flex-1 text-left truncate",children:be.name})]},be.id)),$.trim()&&!ce&&e.jsxs("button",{onClick:re,className:"flex items-center gap-2 w-full px-2 py-1.5 rounded-md text-sm hover:bg-accent transition-colors text-primary",children:[e.jsx(Ys,{className:"h-3.5 w-3.5"}),'Create "',$.trim(),'"']}),ie.length===0&&!$.trim()&&e.jsx("p",{className:"text-xs text-muted-foreground text-center py-2",children:"Type to create a tag"})]})]})]}),m&&e.jsxs(H,{variant:"outline",size:"sm",onClick:()=>T(!0),disabled:b,children:[e.jsx(er,{className:"h-3.5 w-3.5 mr-1"}),"Email"]}),p&&e.jsxs(H,{variant:"outline",size:"sm",onClick:()=>{const be=Array.from(s).join(",");o(`/admin/email-campaigns/new?contactIds=${be}`)},disabled:b,children:[e.jsx(ph,{className:"h-3.5 w-3.5 mr-1"}),"Mass Email"]}),e.jsxs(H,{variant:"outline",size:"sm",onClick:()=>A(!0),disabled:b,children:[e.jsx(xn,{className:"h-3.5 w-3.5 mr-1"}),"Send Video"]}),e.jsxs(H,{variant:"outline",size:"sm",onClick:()=>R(!0),disabled:b,children:[e.jsx(Lr,{className:"h-3.5 w-3.5 mr-1"}),"Enroll in Campaign"]}),a&&n&&e.jsxs(H,{variant:"outline",size:"sm",onClick:()=>n(Array.from(s)),disabled:b,children:[e.jsx(y1,{className:"h-3.5 w-3.5 mr-1"}),"Send to Lead Pond"]}),l&&i&&e.jsxs(H,{variant:"outline",size:"sm",onClick:()=>i(Array.from(s)),disabled:b,children:[e.jsx(F2,{className:"h-3.5 w-3.5 mr-1"}),"Transfer"]}),e.jsxs(H,{variant:"outline",size:"sm",onClick:ne,disabled:b,children:[e.jsx(hi,{className:"h-3.5 w-3.5 mr-1"}),"Export"]}),e.jsxs(H,{variant:"outline",size:"sm",onClick:le,disabled:b,className:"text-destructive hover:text-destructive",children:[e.jsx(Dr,{className:"h-3.5 w-3.5 mr-1"}),"Delete"]}),e.jsxs(H,{variant:"ghost",size:"sm",onClick:r,className:"ml-auto",children:[e.jsx(Rr,{className:"h-3.5 w-3.5 mr-1"}),"Clear"]})]}),e.jsx(M8s,{open:D,onOpenChange:R,contactIds:Array.from(s),onSuccess:r}),e.jsx(X_,{open:k,onOpenChange:T,bulkContacts:Array.from(s).map(be=>{const fe=t.find(je=>je.id===be);return fe?{id:fe.id,first_name:fe.first_name,last_name:fe.last_name,email:fe.email||""}:null}).filter(be=>be!==null&&be.email!==""),onSendComplete:()=>{T(!1),r()}}),e.jsx(o8s,{open:E,onOpenChange:A,contacts:Array.from(s).map(be=>t.find(fe=>fe.id===be)).filter(be=>!!be).map(be=>({id:be.id,first_name:be.first_name,last_name:be.last_name,email:be.email})),isGmailConnected:!!m,isMassEmailReady:!!p,onSendComplete:()=>{A(!1),r()}})]})}function RHe({contact:s,onEdit:t,onDelete:r,onSnooze:n,onSendToLeadPond:a,showLeadPondAction:i,onTransfer:l,showTransferAction:o}){const c=Fr(),{isReady:d}=Dz(),h=`${s.first_name} ${s.last_name||""}`.trim();return e.jsxs(Xu,{children:[e.jsx(Qu,{asChild:!0,children:e.jsx(H,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:m=>m.stopPropagation(),children:e.jsx(Jx,{className:"h-4 w-4"})})}),e.jsxs(wu,{align:"end",onClick:m=>m.stopPropagation(),children:[e.jsxs(di,{onClick:()=>c(`/mission-control/contacts/${s.id}?tab=activity&action=log`),children:[e.jsx(Yn,{className:"h-4 w-4 mr-2"}),"Log Touch"]}),e.jsxs(di,{onClick:()=>c(`/mission-control/video?contactId=${s.id}`),children:[e.jsx(xn,{className:"h-4 w-4 mr-2"}),"Send Video"]}),e.jsxs(di,{onClick:()=>c(`/mission-control/popbys?contactId=${s.id}`),children:[e.jsx(Qa,{className:"h-4 w-4 mr-2"}),"Schedule Pop-by"]}),d&&s.email&&e.jsxs(di,{onClick:()=>c(`/admin/email-campaigns/new?contactIds=${s.id}`),children:[e.jsx(er,{className:"h-4 w-4 mr-2"}),"Mass Email"]}),e.jsxs(di,{onClick:()=>n(s.id,h),children:[e.jsx(Hf,{className:"h-4 w-4 mr-2"}),"Snooze"]}),i&&a&&e.jsxs(di,{onClick:()=>a(s.id),children:[e.jsx(y1,{className:"h-4 w-4 mr-2"}),"Send to Lead Pond"]}),o&&l&&e.jsxs(di,{onClick:()=>l(s.id),children:[e.jsx(F2,{className:"h-4 w-4 mr-2"}),"Transfer to Team Member"]}),e.jsxs(di,{onClick:()=>t(s),children:[e.jsx(ni,{className:"h-4 w-4 mr-2"}),"Edit"]}),e.jsxs(di,{onClick:()=>r(s.id),className:"text-destructive focus:text-destructive",children:[e.jsx(Dr,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})}function P8s({currentFilters:s,currentSortBy:t,onApplySmartList:r}){const{data:n}=Ogt(),a=BPs(),i=zPs(),[l,o]=S.useState(!1),[c,d]=S.useState(""),h=s.search||s.type&&s.type!=="all"||s.status&&s.status!=="all",m=async()=>{c.trim()&&(await a.mutateAsync({name:c.trim(),filters:s,sort_by:t}),d(""),o(!1))};return e.jsxs(e.Fragment,{children:[e.jsxs(Xu,{children:[e.jsx(Qu,{asChild:!0,children:e.jsxs(H,{variant:"outline",size:"sm",className:"gap-1.5",children:[e.jsx(v1,{className:"h-3.5 w-3.5"}),"Smart Filters",n&&n.length>0&&e.jsx(Xe,{variant:"secondary",className:"h-5 px-1.5 text-[10px]",children:n.length}),e.jsx(Io,{className:"h-3.5 w-3.5"})]})}),e.jsxs(wu,{align:"start",className:"w-56",children:[n&&n.length>0?e.jsxs(e.Fragment,{children:[n.map(p=>e.jsxs(di,{className:"flex items-center justify-between group",children:[e.jsx("span",{className:"flex-1 cursor-pointer",onClick:()=>r(p.filters,p.sort_by),children:p.name}),e.jsx(H,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:x=>{x.stopPropagation(),i.mutate(p.id)},children:e.jsx(Dr,{className:"h-3 w-3 text-destructive"})})]},p.id)),e.jsx(A_,{})]}):e.jsx(di,{disabled:!0,className:"text-muted-foreground text-xs",children:"No saved filters yet"}),h&&e.jsxs(di,{onClick:()=>o(!0),children:[e.jsx(JO,{className:"h-4 w-4 mr-2"}),"Save Current Filter"]})]})]}),e.jsx(bs,{open:l,onOpenChange:o,children:e.jsxs(vs,{className:"max-w-sm",children:[e.jsx(Cs,{children:e.jsx(Ns,{children:"Save Smart Filter"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(Se,{placeholder:"e.g. Buyers in 40205",value:c,onChange:p=>d(p.target.value),onKeyDown:p=>p.key==="Enter"&&m(),autoFocus:!0}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(H,{variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsx(H,{onClick:m,disabled:!c.trim()||a.isPending,children:"Save"})]})]})]})})]})}function OHe(s){if(!s)return null;const t=Tc(s);if(!t)return null;const r=new Date;r.setHours(0,0,0,0);const n=new Date(r.getFullYear(),t.getMonth(),t.getDate());return ns.relationshipScore.status==="at-risk"},{key:"never-contacted",title:"Never Contacted",subtitle:"No outreach yet",icon:Vl,gradient:"from-violet-500/15 via-purple-500/10 to-transparent",iconBg:"bg-violet-500/15",iconColor:"text-violet-600 dark:text-violet-400",match:s=>s.relationshipScore.daysSinceTouch===null},{key:"stale-90",title:"Stale 90+ Days",subtitle:"Time to reconnect",icon:Pn,gradient:"from-amber-500/15 via-yellow-500/10 to-transparent",iconBg:"bg-amber-500/15",iconColor:"text-amber-600 dark:text-amber-400",match:s=>{const t=s.relationshipScore.daysSinceTouch;return t!==null&&t>90}},{key:"cooling",title:"Cooling Off",subtitle:"Engagement dropping",icon:h1,gradient:"from-cyan-500/15 via-sky-500/10 to-transparent",iconBg:"bg-cyan-500/15",iconColor:"text-cyan-600 dark:text-cyan-400",match:s=>s.relationshipScore.status==="cooling"},{key:"birthdays-soon",title:"Birthdays Soon",subtitle:"Next 30 days",icon:gm,gradient:"from-pink-500/15 via-fuchsia-500/10 to-transparent",iconBg:"bg-pink-500/15",iconColor:"text-pink-600 dark:text-pink-400",match:(s,t)=>t.daysToBirthday!==null&&t.daysToBirthday<=30},{key:"anniversary-soon",title:"Home Anniversary",subtitle:"Next 30 days",icon:Fn,gradient:"from-emerald-500/15 via-green-500/10 to-transparent",iconBg:"bg-emerald-500/15",iconColor:"text-emerald-600 dark:text-emerald-400",match:(s,t)=>t.daysToAnniv!==null&&t.daysToAnniv<=30},{key:"has-deal",title:"Active Deal",subtitle:"In your pipeline",icon:pm,gradient:"from-teal-500/15 via-[#406E71]/10 to-transparent",iconBg:"bg-teal-500/15",iconColor:"text-teal-700 dark:text-teal-400",match:(s,t)=>t.hasDeal},{key:"website-active",title:"Active on Site",subtitle:"Browsing right now",icon:ld,gradient:"from-indigo-500/15 via-blue-500/10 to-transparent",iconBg:"bg-indigo-500/15",iconColor:"text-indigo-600 dark:text-indigo-400",match:()=>!1},{key:"vips",title:"VIPs",subtitle:"Top relationships",icon:Lr,gradient:"from-amber-400/20 via-yellow-300/10 to-transparent",iconBg:"bg-amber-400/20",iconColor:"text-amber-600 dark:text-amber-300",match:s=>s.relationshipScore.score>=80},{key:"missing-info",title:"Missing Info",subtitle:"No email or phone",icon:uu,gradient:"from-slate-500/15 via-zinc-500/10 to-transparent",iconBg:"bg-slate-500/15",iconColor:"text-slate-600 dark:text-slate-400",match:s=>{var t,r;return!((t=s.email)!=null&&t.trim())&&!((r=s.phone)!=null&&r.trim())}}];function L8s({contacts:s,contactDealsMap:t,websiteActiveIds:r,activeKey:n,onSelect:a}){const i=S.useRef(null),l=S.useMemo(()=>{const c={"needs-attention":0,cooling:0,"never-contacted":0,"stale-90":0,"birthdays-soon":0,"anniversary-soon":0,"has-deal":0,"website-active":r.size,"missing-info":0,vips:0};if(!s)return c;for(const d of s){const h={hasDeal:!!(t&&t[d.id]),daysToBirthday:OHe(d.birthday),daysToAnniv:OHe(d.home_anniversary)};for(const m of FHe)m.key!=="website-active"&&m.match(d,h)&&c[m.key]++}return c},[s,t,r]),o=c=>{var d;(d=i.current)==null||d.scrollBy({left:c,behavior:"smooth"})};return e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2 px-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Lr,{className:"h-4 w-4 text-[#406E71]"}),e.jsx("h3",{className:"text-sm font-semibold text-foreground",children:"Smart Segments"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Auto-organized for you"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[n&&e.jsxs("button",{onClick:()=>a(null),className:"flex items-center gap-1 px-2 py-1 rounded-md text-xs font-medium text-muted-foreground hover:text-foreground hover:bg-muted transition-colors",children:[e.jsx(Rr,{className:"h-3 w-3"}),"Clear"]}),e.jsx("button",{onClick:()=>o(-320),className:"hidden md:flex h-7 w-7 rounded-full items-center justify-center bg-muted/60 hover:bg-muted transition-colors","aria-label":"Scroll left",children:e.jsx(fl,{className:"h-4 w-4"})}),e.jsx("button",{onClick:()=>o(320),className:"hidden md:flex h-7 w-7 rounded-full items-center justify-center bg-muted/60 hover:bg-muted transition-colors","aria-label":"Scroll right",children:e.jsx($a,{className:"h-4 w-4"})})]})]}),e.jsx("div",{ref:i,style:{touchAction:"pan-x",WebkitOverflowScrolling:"touch"},className:"flex gap-3 overflow-x-auto overflow-y-hidden overscroll-x-contain pb-2 px-1 -mx-1 snap-x snap-mandatory scroll-smooth [&::-webkit-scrollbar]:hidden [-ms-overflow-style:none] [scrollbar-width:none]",children:FHe.map(c=>{const d=c.icon,h=l[c.key],m=n===c.key,p=h===0;return e.jsxs("button",{onClick:()=>a(m?null:c.key),disabled:p&&!m,className:`group relative shrink-0 snap-start w-[180px] text-left rounded-xl border transition-all duration-200 overflow-hidden ${m?"border-[#406E71] ring-2 ring-[#406E71]/30 shadow-lg scale-[1.02] bg-card":p?"border-border/40 bg-card/50 opacity-50 cursor-not-allowed":"border-border hover:border-[#406E71]/50 hover:shadow-md hover:-translate-y-0.5 bg-card cursor-pointer"}`,children:[e.jsx("div",{className:`absolute inset-0 bg-gradient-to-br ${c.gradient} pointer-events-none`}),e.jsxs("div",{className:"relative p-3.5",children:[e.jsxs("div",{className:"flex items-start justify-between mb-2.5",children:[e.jsx("div",{className:`h-9 w-9 rounded-lg ${c.iconBg} flex items-center justify-center`,children:e.jsx(d,{className:`h-4.5 w-4.5 ${c.iconColor}`,strokeWidth:2.25})}),e.jsx("div",{className:"text-right",children:e.jsx("div",{className:"text-2xl font-bold leading-none text-foreground tabular-nums",children:h.toLocaleString()})})]}),e.jsx("div",{className:"text-sm font-semibold text-foreground leading-tight",children:c.title}),e.jsx("div",{className:"text-[11px] text-muted-foreground mt-0.5 leading-tight",children:c.subtitle})]})]},c.key)})})]})}const Zgt="innercircle_geocode_cache_v1";function D8s(){try{return JSON.parse(localStorage.getItem(Zgt)||"{}")}catch{return{}}}function R8s(s){try{localStorage.setItem(Zgt,JSON.stringify(s))}catch{}}function O8s(s){const t=[s.address,s.city,s.state,s.zip||s.zip_code].filter(Boolean);return t.length<2&&!s.address||t.length===0?null:t.join(", ")}function F8s({open:s,onOpenChange:t,contacts:r,onCitySelect:n}){const a=S.useRef(null),i=S.useRef(null),[l,o]=S.useState(""),[c,d]=S.useState(!0),[h,m]=S.useState([]),[p,x]=S.useState({done:0,total:0}),[y,_]=S.useState(!1),[b,j]=S.useState("heat");S.useEffect(()=>{if(!s)return;let T=!1;return(async()=>{d(!0);const{data:E}=await V.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();T||(o((E==null?void 0:E.value)||""),d(!1))})(),()=>{T=!0}},[s]),S.useEffect(()=>{if(!s||!l)return;let T=!1;return(async()=>{const A=D8s(),D=r.map(K=>({c:K,addr:O8s(K)})).filter(K=>K.addr),R=[],z=[];for(const{c:K,addr:re}of D){const ie=A[re];ie!==null&&(ie?R.push({id:K.id,name:`${K.first_name||""} ${K.last_name||""}`.trim(),city:K.city||null,state:K.state||null,zip:K.zip||K.zip_code||null,lat:ie.lat,lng:ie.lng}):z.push({c:K,addr:re}))}if(T||m(R),x({done:R.length,total:D.length}),z.length===0)return;_(!0);const O=6;let $=0;const ee={...A},Z=[...R],J=async()=>{var K;for(;${T=!0}},[s,l,r]);const k=S.useMemo(()=>{const T=new Map;for(const E of r){const A=(E.city||"").trim();if(!A)continue;const D=(E.state||"").trim()||null,R=`${A.toLowerCase()}|${D||""}`,z=T.get(R);z?z.count++:T.set(R,{city:A,state:D,count:1})}return Array.from(T.values()).sort((E,A)=>A.count-E.count)},[r]);return S.useEffect(()=>{if(!(!s||!l||!a.current||i.current))return fc.accessToken=l,i.current=new fc.Map({container:a.current,style:"mapbox://styles/mapbox/light-v11",center:[-98.5795,39.8283],zoom:3.5}),i.current.addControl(new fc.NavigationControl,"top-right"),()=>{var T;(T=i.current)==null||T.remove(),i.current=null}},[s,l]),S.useEffect(()=>{const T=i.current;if(!T||h.length===0)return;const E=()=>{const D={type:"FeatureCollection",features:h.map(z=>({type:"Feature",properties:{id:z.id,name:z.name},geometry:{type:"Point",coordinates:[z.lng,z.lat]}}))},R=T.getSource("contacts-src");if(R?R.setData(D):(T.addSource("contacts-src",{type:"geojson",data:D}),T.addLayer({id:"contacts-heat",type:"heatmap",source:"contacts-src",maxzoom:15,paint:{"heatmap-weight":1,"heatmap-intensity":["interpolate",["linear"],["zoom"],0,1,15,3],"heatmap-color":["interpolate",["linear"],["heatmap-density"],0,"rgba(64,110,113,0)",.2,"rgba(64,110,113,0.4)",.4,"rgba(56,189,248,0.6)",.6,"rgba(250,204,21,0.7)",.8,"rgba(249,115,22,0.85)",1,"rgba(220,38,38,1)"],"heatmap-radius":["interpolate",["linear"],["zoom"],0,12,9,30,15,60],"heatmap-opacity":["interpolate",["linear"],["zoom"],13,1,15,.6]}}),T.addLayer({id:"contacts-points",type:"circle",source:"contacts-src",paint:{"circle-radius":["interpolate",["linear"],["zoom"],0,4,8,5,16,9],"circle-color":"#406E71","circle-stroke-color":"#ffffff","circle-stroke-width":1.5,"circle-opacity":.9}}),T.on("click","contacts-points",z=>{var ee;const O=(ee=z.features)==null?void 0:ee[0];if(!O)return;const $=O.geometry.coordinates.slice();new fc.Popup({offset:12}).setLngLat($).setHTML(`
${O.properties.name||"Contact"}
`).addTo(T)}),T.on("mouseenter","contacts-points",()=>{T.getCanvas().style.cursor="pointer"}),T.on("mouseleave","contacts-points",()=>{T.getCanvas().style.cursor=""})),T.getLayer("contacts-heat")&&T.setLayoutProperty("contacts-heat","visibility",b==="heat"?"visible":"none"),T.getLayer("contacts-points")&&(T.setPaintProperty("contacts-points","circle-opacity",b==="points"?.9:0),T.setLayoutProperty("contacts-points","visibility","visible")),h.length>0&&!T._fitDone){const z=new fc.LngLatBounds;h.forEach(O=>z.extend([O.lng,O.lat]));try{T.fitBounds(z,{padding:60,maxZoom:11,duration:600}),T._fitDone=!0}catch{}}};T.isStyleLoaded()?E():T.once("load",E)},[h,b]),e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-6xl w-[95vw] h-[90vh] p-0 flex flex-col",children:[e.jsx(Cs,{className:"p-4 pb-2 border-b",children:e.jsxs(Ns,{className:"flex items-center gap-2",children:[e.jsx(od,{className:"h-5 w-5 text-orange-500"}),"Geographic Heat Map",e.jsxs(Xe,{variant:"secondary",className:"ml-2",children:[h.length," mapped · ",k.length," cities"]})]})}),e.jsxs("div",{className:"flex-1 flex flex-col md:flex-row min-h-0",children:[e.jsx("div",{className:"flex-1 relative min-h-[300px]",children:c?e.jsx("div",{className:"h-full flex items-center justify-center",children:e.jsx(is,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):l?e.jsxs(e.Fragment,{children:[e.jsx("div",{ref:a,className:"absolute inset-0"}),e.jsxs("div",{className:"absolute top-3 left-3 flex flex-col gap-2 z-10",children:[e.jsxs("div",{className:"bg-background/95 backdrop-blur rounded-md shadow-md border p-1 flex",children:[e.jsxs(H,{size:"sm",variant:b==="heat"?"default":"ghost",onClick:()=>j("heat"),className:"h-8",children:[e.jsx(od,{className:"h-3.5 w-3.5 mr-1"})," Heat"]}),e.jsxs(H,{size:"sm",variant:b==="points"?"default":"ghost",onClick:()=>j("points"),className:"h-8",children:[e.jsx(pF,{className:"h-3.5 w-3.5 mr-1"})," Pins"]})]}),y&&e.jsxs("div",{className:"bg-background/95 backdrop-blur rounded-md shadow-md border px-2.5 py-1.5 text-xs flex items-center gap-2",children:[e.jsx(is,{className:"h-3 w-3 animate-spin"}),"Mapping ",p.done," / ",p.total]})]})]}):e.jsxs("div",{className:"h-full flex flex-col items-center justify-center gap-3 p-6 text-center",children:[e.jsx(wo,{className:"h-10 w-10 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold",children:"Map Not Configured"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Mapbox token is not set. Contact your administrator."})]})]})}),e.jsxs("div",{className:"w-full md:w-72 border-t md:border-t-0 md:border-l flex flex-col bg-muted/30 min-h-[200px]",children:[e.jsxs("div",{className:"p-3 border-b bg-background",children:[e.jsxs("h3",{className:"text-sm font-semibold flex items-center gap-1.5",children:[e.jsx(Qa,{className:"h-4 w-4 text-primary"}),"Top Cities"]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:"Tap a city to filter your contacts"})]}),e.jsx(Ci,{className:"flex-1",children:e.jsxs("div",{className:"p-2 space-y-1.5",children:[k.length===0&&e.jsx("p",{className:"text-xs text-muted-foreground p-3 text-center",children:"No city data on your contacts yet. Add city/state to contacts to populate the map."}),k.slice(0,50).map((T,E)=>{var R;const A=((R=k[0])==null?void 0:R.count)||1,D=T.count/A*100;return e.jsx(ke,{className:"cursor-pointer hover:border-primary transition-colors overflow-hidden",onClick:()=>{n==null||n(T.city,T.state),t(!1)},children:e.jsxs(Oe,{className:"p-2.5 relative",children:[e.jsx("div",{className:"absolute inset-y-0 left-0 bg-primary/10",style:{width:`${D}%`}}),e.jsxs("div",{className:"relative flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"text-sm font-medium truncate",children:[T.city,T.state?`, ${T.state}`:""]}),e.jsx("div",{className:"text-[10px] text-muted-foreground",children:E===0?"🔥 Hottest market":`Rank #${E+1}`})]}),e.jsx(Xe,{variant:"secondary",className:"shrink-0",children:T.count})]})]})},`${T.city}-${T.state}-${E}`)})]})})]})]})]})})}function ST(s){if(!s)return null;try{const t=s.split(/[-/T]/);if(t.length<3)return null;const r=parseInt(t[1],10)-1,n=parseInt(t[2],10);if(isNaN(r)||isNaN(n))return null;const a=new Date;a.setHours(0,0,0,0);let i=new Date(a.getFullYear(),r,n);return i.setHours(0,0,0,0),ir)return null;const a=t==="birthday"?"🎂":"🏡",i=n===0?t==="birthday"?"Birthday today!":"Anniversary today!":n===1?t==="birthday"?"Birthday tomorrow":"Anniversary tomorrow":`${a} in ${n}d`;return{emoji:a,label:i,daysUntil:n}}function zHe({birthday:s,homeAnniversary:t,className:r,contactId:n,contactName:a,contactAddress:i}){const l=Fr(),o=BHe(s,"birthday",7),c=BHe(t,"anniversary",7);if(!o&&!c)return null;const d=(h,m)=>{m.stopPropagation();const p=new URLSearchParams;n&&p.set("contactId",n),a&&p.set("name",a),i&&p.set("address",i),h==="home_anniversary"&&t&&p.set("date",t),p.set("cardType",h),l(`/mission-control/card-studio?${p.toString()}`)};return e.jsxs("div",{className:Ft("flex flex-wrap gap-1",r),children:[o&&e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsx(Xe,{variant:"secondary",className:Ft("text-[10px] gap-0.5 font-medium",o.daysUntil===0?"bg-pink-100 text-pink-700 dark:bg-pink-900/30 dark:text-pink-400 animate-pulse":"bg-pink-50 text-pink-600 dark:bg-pink-900/20 dark:text-pink-400"),children:o.label}),n&&e.jsxs("button",{onClick:h=>d("birthday",h),className:"inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded-full text-[9px] font-semibold bg-pink-500/15 text-pink-600 dark:text-pink-400 hover:bg-pink-500/25 transition-colors",title:"Send a birthday card",children:[e.jsx(er,{className:"h-2.5 w-2.5"}),"Send Card"]})]}),c&&e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsx(Xe,{variant:"secondary",className:Ft("text-[10px] gap-0.5 font-medium",c.daysUntil===0?"bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400 animate-pulse":"bg-blue-50 text-blue-600 dark:bg-blue-900/20 dark:text-blue-400"),children:c.label}),n&&e.jsxs("button",{onClick:h=>d("home_anniversary",h),className:"inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded-full text-[9px] font-semibold bg-blue-500/15 text-blue-600 dark:text-blue-400 hover:bg-blue-500/25 transition-colors",title:"Send an anniversary card",children:[e.jsx(er,{className:"h-2.5 w-2.5"}),"Send Card"]})]})]})}function $He({deal:s}){if(!s||!s.stage)return null;const{stage:t}=s;return e.jsxs(Xe,{variant:"outline",className:"text-[10px] gap-1 font-medium whitespace-nowrap",style:{borderColor:t.color,color:t.color,backgroundColor:`${t.color}10`},children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full inline-block",style:{backgroundColor:t.color}}),t.name]})}function UHe({count:s,className:t}){return!s||s<=0?null:e.jsxs(Xe,{variant:"outline",className:Ft("text-[10px] gap-1 border-emerald-300 bg-emerald-500/10 text-emerald-700 dark:text-emerald-400 px-1.5 py-0 h-5",t),title:`Enrolled in ${s} active drip campaign${s===1?"":"s"}`,children:[e.jsx(FE,{className:"h-2.5 w-2.5"}),s===1?"In drip":`${s} drips`]})}function B8s(){const s=ba();return yt({queryKey:["contacts-campaign-counts",s],queryFn:async()=>{if(!s)return{};const{data:t,error:r}=await V.from("drip_campaign_enrollments").select("contact_id, status").eq("owner_user_id",s).eq("status","active");if(r)throw r;const n={};return(t||[]).forEach(a=>{a.contact_id&&(n[a.contact_id]=(n[a.contact_id]||0)+1)}),n},enabled:!!s,staleTime:6e4})}function z8s(){const s=ba();return yt({queryKey:["contact-deals-map",s],queryFn:async()=>{const{data:t,error:r}=await V.from("deal_pipeline").select(` id, deal_name, contact_id, stage:deal_pipeline_stages(id, name, color, icon, is_won_stage, is_lost_stage) `).not("contact_id","is",null);if(r)throw r;const n={};return(t||[]).forEach(a=>{a.contact_id&&!n[a.contact_id]&&(n[a.contact_id]=a)}),n},enabled:!!s})}function $8s({contactId:s,compact:t=!1}){const{data:r}=q8(),{data:n}=DPs(s),a=aMe(),i=Rgt(),l=FPs(),[o,c]=S.useState(!1),[d,h]=S.useState(""),m=S.useRef(null),p=new Set((n==null?void 0:n.map(j=>j.tag_id))||[]),x=(r==null?void 0:r.filter(j=>j.name.toLowerCase().includes(d.toLowerCase())))||[],y=r==null?void 0:r.find(j=>j.name.toLowerCase()===d.trim().toLowerCase()),_=async j=>{p.has(j.id)?await l.mutateAsync({contactId:s,tagId:j.id}):await i.mutateAsync({contactId:s,tagId:j.id})},b=async()=>{if(!(!d.trim()||y))try{const j=await a.mutateAsync({name:d.trim()});await i.mutateAsync({contactId:s,tagId:j.id}),h("")}catch{}};return e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[n==null?void 0:n.map(j=>{var k,T,E;return e.jsxs(Xe,{variant:"outline",className:"text-xs gap-1 pr-1",style:{borderColor:((k=j.tag)==null?void 0:k.color)||"#6366F1",color:((T=j.tag)==null?void 0:T.color)||"#6366F1"},children:[e.jsx(xm,{className:"h-2.5 w-2.5"}),(E=j.tag)==null?void 0:E.name,e.jsx("button",{onClick:A=>{A.stopPropagation(),l.mutate({contactId:s,tagId:j.tag_id})},className:"ml-0.5 rounded-full hover:bg-accent p-0.5",children:e.jsx(Rr,{className:"h-2.5 w-2.5"})})]},j.id)}),e.jsxs(gl,{open:o,onOpenChange:c,children:[e.jsx(xl,{asChild:!0,children:e.jsxs(H,{variant:"ghost",size:"sm",className:t?"h-6 w-6 p-0":"h-6 px-2 text-xs",onClick:j=>j.stopPropagation(),children:[e.jsx(Ys,{className:"h-3 w-3"}),!t&&e.jsx("span",{className:"ml-1",children:"Tag"})]})}),e.jsxs(il,{className:"w-56 p-2",align:"start",onClick:j=>j.stopPropagation(),children:[e.jsx(Se,{ref:m,placeholder:"Search or create tag...",value:d,onChange:j=>h(j.target.value),onKeyDown:j=>{j.key==="Enter"&&d.trim()&&!y?(j.preventDefault(),b()):j.key==="Enter"&&y&&!p.has(y.id)&&(j.preventDefault(),_(y))},className:"h-8 text-sm mb-2"}),e.jsxs("div",{className:"max-h-[200px] overflow-y-auto space-y-0.5",children:[x.map(j=>e.jsxs("button",{onClick:()=>_(j),className:"flex items-center gap-2 w-full px-2 py-1.5 rounded-md text-sm hover:bg-accent transition-colors",children:[e.jsx("div",{className:"h-3 w-3 rounded-full shrink-0",style:{backgroundColor:j.color}}),e.jsx("span",{className:"flex-1 text-left truncate",children:j.name}),p.has(j.id)&&e.jsx(va,{className:"h-3.5 w-3.5 text-primary shrink-0"})]},j.id)),d.trim()&&!y&&e.jsxs("button",{onClick:b,className:"flex items-center gap-2 w-full px-2 py-1.5 rounded-md text-sm hover:bg-accent transition-colors text-primary",children:[e.jsx(Ys,{className:"h-3.5 w-3.5"}),'Create "',d.trim(),'"']}),x.length===0&&!d.trim()&&e.jsx("p",{className:"text-xs text-muted-foreground text-center py-2",children:"Type to create your first tag"})]})]})]})]})}function qHe({contactId:s,tags:t}){return!t||t.length===0?null:e.jsx(e.Fragment,{children:t.map(r=>{var n,a,i;return e.jsx(Xe,{variant:"outline",className:"text-[10px] gap-0.5",style:{borderColor:((n=r.tag)==null?void 0:n.color)||"#6366F1",color:((a=r.tag)==null?void 0:a.color)||"#6366F1"},children:(i=r.tag)==null?void 0:i.name},r.tag_id)})})}const Gq=["#6366F1","#8B5CF6","#EC4899","#EF4444","#F97316","#F59E0B","#10B981","#14B8A6","#06B6D4","#3B82F6","#6B7280","#1F2937"];function U8s({open:s,onOpenChange:t}){const{data:r,isLoading:n}=q8(),a=aMe(),i=OPs(),l=RPs(),[o,c]=S.useState(""),[d,h]=S.useState(Gq[0]),[m,p]=S.useState(null),[x,y]=S.useState(""),[_,b]=S.useState(""),j=async()=>{if(o.trim())try{await a.mutateAsync({name:o.trim(),color:d}),c(""),h(Gq[0]),En({title:"Tag created"})}catch(A){En({title:"Error",description:A.message,variant:"destructive"})}},k=async A=>{if(x.trim())try{await i.mutateAsync({id:A,name:x.trim(),color:_}),p(null),En({title:"Tag updated"})}catch(D){En({title:"Error",description:D.message,variant:"destructive"})}},T=async(A,D)=>{if(confirm(`Delete tag "${D}"? It will be removed from all contacts.`))try{await l.mutateAsync(A),En({title:"Tag deleted"})}catch(R){En({title:"Error",description:R.message,variant:"destructive"})}},E=A=>{p(A.id),y(A.name),b(A.color)};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-md",children:[e.jsx(Cs,{children:e.jsx(Ns,{children:"Manage Tags"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Se,{placeholder:"New tag name...",value:o,onChange:A=>c(A.target.value),onKeyDown:A=>A.key==="Enter"&&j(),className:"flex-1 h-9"}),e.jsxs(H,{size:"sm",onClick:j,disabled:!o.trim()||a.isPending,className:"h-9",children:[e.jsx(Ys,{className:"h-4 w-4 mr-1"}),"Add"]})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:Gq.map(A=>e.jsx("button",{onClick:()=>h(A),className:`h-6 w-6 rounded-full border-2 transition-transform ${d===A?"border-foreground scale-110":"border-transparent hover:scale-105"}`,style:{backgroundColor:A}},A))})]}),e.jsxs("div",{className:"mt-2 space-y-1 max-h-[320px] overflow-y-auto",children:[n&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"Loading..."}),(r==null?void 0:r.length)===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No tags yet. Create one above!"}),r==null?void 0:r.map(A=>e.jsx("div",{className:"flex items-center gap-2 p-2 rounded-lg hover:bg-accent/50 group",children:m===A.id?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex flex-wrap gap-1",children:Gq.map(D=>e.jsx("button",{onClick:()=>b(D),className:`h-5 w-5 rounded-full border-2 ${_===D?"border-foreground":"border-transparent"}`,style:{backgroundColor:D}},D))}),e.jsx(Se,{value:x,onChange:D=>y(D.target.value),onKeyDown:D=>D.key==="Enter"&&k(A.id),className:"flex-1 h-8 text-sm",autoFocus:!0}),e.jsx(H,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>k(A.id),children:e.jsx(va,{className:"h-4 w-4 text-primary"})}),e.jsx(H,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>p(null),children:e.jsx(Rr,{className:"h-4 w-4"})})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"h-3.5 w-3.5 rounded-full shrink-0",style:{backgroundColor:A.color}}),e.jsx("span",{className:"flex-1 text-sm",children:A.name}),e.jsx(H,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>E(A),children:e.jsx(ni,{className:"h-3.5 w-3.5"})}),e.jsx(H,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 opacity-0 group-hover:opacity-100 transition-opacity text-destructive hover:text-destructive",onClick:()=>T(A.id,A.name),children:e.jsx(Dr,{className:"h-3.5 w-3.5"})})]})},A.id))]})]})})}function q8s({open:s,onOpenChange:t}){const{data:r,isLoading:n}=v8(),a=wTe(),i=qHt(),l=VHt(),[o,c]=S.useState(""),[d,h]=S.useState(null),[m,p]=S.useState(""),x=async()=>{if(o.trim())try{await a.mutateAsync(o.trim()),c("")}catch(j){he.error(j.message||"Failed to add lead source")}},y=async j=>{if(m.trim())try{await i.mutateAsync({id:j,name:m.trim()}),h(null)}catch(k){he.error(k.message||"Failed to update")}},_=async(j,k)=>{if(confirm(`Remove lead source "${k}"? Contacts using it will keep the label but it won't appear in new dropdowns.`))try{await l.mutateAsync(j)}catch(T){he.error(T.message||"Failed to remove")}},b=j=>{h(j.id),p(j.name)};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-md",children:[e.jsx(Cs,{children:e.jsx(Ns,{children:"Manage Lead Sources"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Se,{placeholder:"New lead source name...",value:o,onChange:j=>c(j.target.value),onKeyDown:j=>j.key==="Enter"&&x(),className:"flex-1 h-9"}),e.jsxs(H,{size:"sm",onClick:x,disabled:!o.trim()||a.isPending,className:"h-9",children:[e.jsx(Ys,{className:"h-4 w-4 mr-1"}),"Add"]})]}),e.jsxs("div",{className:"mt-2 space-y-1 max-h-[360px] overflow-y-auto",children:[n&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"Loading..."}),(r==null?void 0:r.length)===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No lead sources yet. Create one above!"}),r==null?void 0:r.map(j=>e.jsx("div",{className:"flex items-center gap-2 p-2 rounded-lg hover:bg-accent/50 group",children:d===j.id?e.jsxs(e.Fragment,{children:[e.jsx(Se,{value:m,onChange:k=>p(k.target.value),onKeyDown:k=>k.key==="Enter"&&y(j.id),className:"flex-1 h-8 text-sm",autoFocus:!0}),e.jsx(H,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>y(j.id),children:e.jsx(va,{className:"h-4 w-4 text-primary"})}),e.jsx(H,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>h(null),children:e.jsx(Rr,{className:"h-4 w-4"})})]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"flex-1 text-sm",children:j.name}),j.owner_user_id&&e.jsxs(e.Fragment,{children:[e.jsx(H,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>b(j),children:e.jsx(ni,{className:"h-3.5 w-3.5"})}),e.jsx(H,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 opacity-0 group-hover:opacity-100 transition-opacity text-destructive hover:text-destructive",onClick:()=>_(j.id,j.name),children:e.jsx(Dr,{className:"h-3.5 w-3.5"})})]}),!j.owner_user_id&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"Default"})]})},j.id))]})]})})}function Xgt({value:s,onChange:t,label:r="Lead Source"}){const{data:n}=v8(),a=wTe(),[i,l]=S.useState(!1),[o,c]=S.useState(""),d=async()=>{if(o.trim())try{const h=await a.mutateAsync(o.trim());h&&(t(h.id),c(""),l(!1))}catch{}};return e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:r}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Bs,{value:s||"_none",onValueChange:h=>t(h==="_none"?"":h),children:[e.jsx(Os,{className:"flex-1",children:e.jsx(Us,{placeholder:"Select lead source"})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"_none",children:"No source"}),n==null?void 0:n.map(h=>e.jsx(pt,{value:h.id,children:h.name},h.id))]})]}),e.jsx(H,{type:"button",variant:"outline",size:"icon",className:"shrink-0",onClick:()=>l(!i),children:i?e.jsx(Rr,{className:"h-4 w-4"}):e.jsx(Ys,{className:"h-4 w-4"})})]}),i&&e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Se,{placeholder:"New lead source name...",value:o,onChange:h=>c(h.target.value),onKeyDown:h=>{h.key==="Enter"&&(h.preventDefault(),d())},className:"flex-1"}),e.jsx(H,{type:"button",size:"sm",onClick:d,disabled:!o.trim()||a.isPending,children:"Add"})]})]})}function N4e({contactId:s,currentSpouseContactId:t,currentSpouseName:r,currentSpouseEmail:n,onLink:a,onUnlink:i,isEditing:l}){const o=Fr(),[c,d]=S.useState(!1),[h,m]=S.useState(""),{data:p}=yt({queryKey:["innercircle-contact-spouse",t],queryFn:async()=>{const{data:y,error:_}=await V.from("innercircle_contacts").select("id, first_name, last_name, email, phone, birthday").eq("id",t).maybeSingle();if(_)throw _;return y},enabled:!!t}),{data:x}=yt({queryKey:["spouse-search",h],queryFn:async()=>{let y=V.from("innercircle_contacts").select("id, first_name, last_name, email, phone").neq("id",s).order("first_name").limit(20);h.trim()&&(y=y.or(`first_name.ilike.%${h}%,last_name.ilike.%${h}%,email.ilike.%${h}%,phone.ilike.%${h}%`));const{data:_,error:b}=await y;if(b)throw b;return _},enabled:c});if(t&&p){const y=`${p.first_name} ${p.last_name||""}`.trim();return e.jsxs("div",{className:"space-y-1",children:[e.jsx(ue,{className:"text-sm font-medium",children:"Spouse / Partner"}),e.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-border bg-muted/30 px-3 py-2",children:[e.jsx(io,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("button",{onClick:()=>o(`/mission-control/contacts/${p.id}`),className:"text-sm font-medium text-primary hover:underline truncate block",children:y}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:[p.phone,p.email].filter(Boolean).join(" · ")||"No contact info"})]}),l&&e.jsxs(H,{variant:"ghost",size:"sm",onClick:i,className:"shrink-0 h-7 px-2",children:[e.jsx(BE,{className:"h-3.5 w-3.5 mr-1"}),"Unlink"]}),!l&&e.jsx(H,{variant:"ghost",size:"sm",onClick:()=>o(`/mission-control/contacts/${p.id}`),className:"shrink-0 h-7 px-2",children:e.jsx(bi,{className:"h-3.5 w-3.5"})})]})]})}return!t&&(r||n)?e.jsxs("div",{className:"space-y-1",children:[e.jsx(ue,{className:"text-sm font-medium",children:"Spouse / Partner"}),e.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-border bg-muted/30 px-3 py-2",children:[e.jsx(io,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("span",{className:"text-sm",children:r}),n&&e.jsx("span",{className:"text-xs text-muted-foreground block truncate",children:n})]}),l&&e.jsxs(gl,{open:c,onOpenChange:d,children:[e.jsx(xl,{asChild:!0,children:e.jsxs(H,{variant:"outline",size:"sm",className:"shrink-0 h-7 px-2",children:[e.jsx(ql,{className:"h-3.5 w-3.5 mr-1"}),"Link Contact"]})}),e.jsx(il,{className:"w-72 p-2",align:"end",children:e.jsx(VHe,{search:h,setSearch:m,results:x,onSelect:y=>{a(y),d(!1),m("")}})})]})]})]}):l?e.jsxs("div",{className:"space-y-1",children:[e.jsx(ue,{className:"text-sm font-medium",children:"Spouse / Partner"}),e.jsxs(gl,{open:c,onOpenChange:d,children:[e.jsx(xl,{asChild:!0,children:e.jsxs(H,{variant:"outline",className:"w-full justify-start text-muted-foreground font-normal h-10",children:[e.jsx(ql,{className:"h-4 w-4 mr-2"}),"Link an existing contact as spouse..."]})}),e.jsx(il,{className:"w-72 p-2",align:"start",children:e.jsx(VHe,{search:h,setSearch:m,results:x,onSelect:y=>{a(y),d(!1),m("")}})})]})]}):null}function VHe({search:s,setSearch:t,results:r,onSelect:n}){return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Mn,{className:"absolute left-2 top-2.5 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(Se,{value:s,onChange:a=>t(a.target.value),placeholder:"Search contacts...",className:"pl-7 h-8 text-sm",autoFocus:!0})]}),e.jsx(Ci,{className:"max-h-48",children:r&&r.length>0?e.jsx("div",{className:"space-y-0.5",children:r.map(a=>e.jsxs("button",{onClick:()=>n(a.id),className:"w-full text-left px-2 py-1.5 rounded hover:bg-accent transition-colors",children:[e.jsxs("div",{className:"text-sm font-medium truncate",children:[a.first_name," ",a.last_name]}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:[a.phone,a.email].filter(Boolean).join(" · ")||"No contact info"})]},a.id))}):e.jsx("p",{className:"text-xs text-muted-foreground text-center py-3",children:s?"No contacts found":"Type to search contacts"})})]})}function V8s(){var _a;const s=Fr(),[t,r]=Ed(),{user:n}=Ms(),a=V8(),i=ns(),l=t.get("type"),o=t.get("filter")??t.get("status"),c=t.get("new")==="true",{contactsWithScores:d,isLoading:h}=sxe(),{activeContactIds:m,hasLeadSite:p}=YLs(),{data:x}=B8s(),{data:y}=R0(),{data:_}=z8s(),{data:b}=q8(),{data:j}=iMe(),[k,T]=S.useState(new Set),[E,A]=S.useState("any"),D=Qge(),R=yTe(),z=vTe(),O=hot(),[$,ee]=S.useState(""),[Z,J]=S.useState(!1),[K,re]=S.useState(l||"all"),[ie,ce]=S.useState(o||"all"),[ne,le]=S.useState("date-added"),[be,fe]=S.useState(c),[je,ve]=S.useState(null),[We,Ve]=S.useState(!1),[Le,Me]=S.useState(!1),[ze,Pe]=S.useState(null),[Ie,De]=S.useState(""),[pe,tt]=S.useState(new Set),[ge,ct]=S.useState(!1),Ue=Math.max(1,parseInt(t.get("page")||"1",10)||1),[et,Qe]=S.useState(Ue),Ne=S.useCallback(Jt=>{Qe(Cr=>{const Gt=typeof Jt=="function"?Jt(Cr):Jt;return r(Ee=>{const He=new URLSearchParams(Ee);return Gt<=1?He.delete("page"):He.set("page",String(Gt)),He},{replace:!0}),Gt})},[]),[$e,it]=S.useState(50),[Je,st]=S.useState("my"),[mt,wt]=S.useState(!1),[at,rt]=S.useState(!1),{data:Et}=sv(),{addToLeadPond:hs}=mht(Et==null?void 0:Et.teamId),Is=!!((_a=Et==null?void 0:Et.team)!=null&&_a.lead_pond_enabled&&(Et!=null&&Et.teamId)),lr=!!(Et!=null&&Et.teamId),[us,St]=S.useState([]),[xs,kt]=S.useState(!1),fs=Jt=>{St([Jt]),kt(!0)},Gs=Jt=>{St(Jt),kt(!0)},_s=Jt=>{Et!=null&&Et.teamId&&hs.mutate({contact_id:Jt,team_id:Et.teamId})},br=Jt=>{Et!=null&&Et.teamId&&Jt.forEach(Cr=>{hs.mutate({contact_id:Cr,team_id:Et.teamId})})},zr=S.useCallback(Jt=>{ct(!1),tt(Cr=>{const Gt=new Set(Cr);return Gt.has(Jt)?Gt.delete(Jt):Gt.add(Jt),Gt})},[]);S.useEffect(()=>{if(!(n!=null&&n.id))return;const Jt=V.channel(`innercircle_contacts_inserts_${n.id}`).on("postgres_changes",{event:"INSERT",schema:"public",table:"innercircle_contacts",filter:`owner_user_id=eq.${n.id}`},()=>{i.invalidateQueries({queryKey:["innercircle-contacts"]}),i.invalidateQueries({queryKey:["innercircle-contact-counts"]})}).subscribe();return()=>{V.removeChannel(Jt)}},[i,n==null?void 0:n.id]),S.useEffect(()=>{o&&ce(o)},[o]);const[Yr,rn]=S.useState({first_name:"",last_name:"",email:"",phone:"",address:"",city:"",state:"",zip_code:"",birthday:"",home_anniversary:"",spouse_name:"",spouse_email:"",lead_source_id:"",notes:"",tagIds:[]});S.useEffect(()=>{c&&fe(!0)},[c]),S.useEffect(()=>{var Jt;je&&rn({first_name:je.first_name||"",last_name:je.last_name||"",email:je.email||"",phone:je.phone||"",address:je.address||"",city:je.city||"",state:je.state||"",zip_code:je.zip_code||"",birthday:je.birthday||"",home_anniversary:je.home_anniversary||"",spouse_name:je.spouse_name||"",spouse_email:je.spouse_email||"",lead_source_id:je.lead_source_id||"",notes:je.notes||"",tagIds:((Jt=je.tags)==null?void 0:Jt.map(Cr=>Cr.relationship_type_id))||[]})},[je]);const sn=S.useMemo(()=>{if(!d)return[];let Jt=d.filter(Cr=>{var ot,jt,Dt,qt,ss;const Gt=$===""||`${Cr.first_name} ${Cr.last_name}`.toLowerCase().includes($.toLowerCase())||((ot=Cr.email)==null?void 0:ot.toLowerCase().includes($.toLowerCase()))||((jt=Cr.phone)==null?void 0:jt.includes($))||((Dt=Cr.city)==null?void 0:Dt.toLowerCase().includes($.toLowerCase()))||((qt=Cr.state)==null?void 0:qt.toLowerCase().includes($.toLowerCase())),Ee=K==="all"||((ss=Cr.tags)==null?void 0:ss.some(Yt=>Yt.relationship_type_id===K)),He=k.size===0||(()=>{const Yt=(j==null?void 0:j.filter(ls=>ls.contact_id===Cr.id).map(ls=>ls.tag_id))||[];return E==="any"?Yt.some(ls=>k.has(ls)):Array.from(k).every(ls=>Yt.includes(ls))})();return Gt&&Ee&&He});return ie==="not-touched-90"?Jt=Jt.filter(Cr=>{const Gt=Cr.relationshipScore.daysSinceTouch;return Gt===null||Gt>90}):ie==="at-risk"?Jt=Jt.filter(Cr=>Cr.relationshipScore.status==="at-risk"):ie==="cooling"?Jt=Jt.filter(Cr=>Cr.relationshipScore.status==="cooling"):ie==="warm"?Jt=Jt.filter(Cr=>Cr.relationshipScore.status==="warm"):ie==="has-deal"?Jt=Jt.filter(Cr=>_&&_[Cr.id]):ie==="no-deal"?Jt=Jt.filter(Cr=>!_||!_[Cr.id]):ie==="open-house"?Jt=Jt.filter(Cr=>{var Ee;return(((Ee=Cr.lead_source_ref)==null?void 0:Ee.name)||Cr.lead_source)==="Open House"}):ie==="website-active"?Jt=Jt.filter(Cr=>m.has(Cr.id)):ie==="never-contacted"?Jt=Jt.filter(Cr=>Cr.relationshipScore.daysSinceTouch===null):ie==="vips"?Jt=Jt.filter(Cr=>Cr.relationshipScore.score>=80):ie==="missing-info"?Jt=Jt.filter(Cr=>{var Gt,Ee;return!((Gt=Cr.email)!=null&&Gt.trim())&&!((Ee=Cr.phone)!=null&&Ee.trim())}):ie==="birthdays-soon"?Jt=Jt.filter(Cr=>{const Gt=ST(Cr.birthday);return Gt!==null&&Gt<=30}):ie==="anniversary-soon"?Jt=Jt.filter(Cr=>{const Gt=ST(Cr.home_anniversary);return Gt!==null&&Gt<=30}):ie==="in-drip"?Jt=Jt.filter(Cr=>((x==null?void 0:x[Cr.id])??0)>0):ie==="not-in-drip"&&(Jt=Jt.filter(Cr=>((x==null?void 0:x[Cr.id])??0)===0)),Jt=[...Jt].sort((Cr,Gt)=>{switch(ne){case"important-dates":{const Ee=ST(Cr.birthday),He=ST(Gt.birthday),ot=ST(Cr.home_anniversary),jt=ST(Gt.home_anniversary),Dt=[Ee,ot].filter(ss=>ss!==null).sort((ss,Yt)=>(ss??1/0)-(Yt??1/0))[0]??1/0,qt=[He,jt].filter(ss=>ss!==null).sort((ss,Yt)=>(ss??1/0)-(Yt??1/0))[0]??1/0;return Dt-qt}case"last-touched":{const Ee=Cr.relationshipScore.lastTouchDate,He=Gt.relationshipScore.lastTouchDate;return!Ee&&!He?0:Ee?He?new Date(Ee).getTime()-new Date(He).getTime():1:-1}case"next-touch":{const Ee=Cr.relationshipScore.daysSinceTouch,He=Gt.relationshipScore.daysSinceTouch;return Ee===null&&He===null?0:Ee===null?-1:He===null?1:He-Ee}case"score":return Cr.relationshipScore.score-Gt.relationshipScore.score;case"date-added":{const Ee=Cr.created_at,He=Gt.created_at;return!Ee&&!He?0:Ee?He?new Date(He).getTime()-new Date(Ee).getTime():-1:1}case"name":default:{const Ee=`${Cr.first_name||""} ${Cr.last_name||""}`.toLowerCase(),He=`${Gt.first_name||""} ${Gt.last_name||""}`.toLowerCase();return Ee.localeCompare(He)}}}),Jt},[d,$,K,k,E,ie,ne,_,j,m,x]),Vr=sn.length,$r=Math.max(1,Math.ceil(Vr/$e)),hn=Math.min(et,$r),Zn=S.useMemo(()=>{const Jt=(hn-1)*$e;return sn.slice(Jt,Jt+$e)},[sn,hn,$e]),cr=S.useRef(!1);S.useEffect(()=>{if(!cr.current){cr.current=!0;return}Ne(1)},[$,K,k,E,ie,ne]);const on=S.useCallback(()=>{ct(!1),tt(Jt=>Jt.size>0?new Set:new Set(Zn.map(Cr=>Cr.id)))},[Zn]),ds=S.useCallback(()=>{ct(!0),tt(new Set(sn.map(Jt=>Jt.id)))},[sn]),Na=S.useCallback((Jt,Cr)=>{ee(Jt.search||""),re(Jt.type||"all"),ce(Jt.status||"all"),le(Cr||"name")},[]),vn=()=>{rn({first_name:"",last_name:"",email:"",phone:"",address:"",city:"",state:"",zip_code:"",birthday:"",home_anniversary:"",spouse_name:"",spouse_email:"",lead_source_id:"",notes:"",tagIds:[]})},_r=async Jt=>{Jt.preventDefault();const Cr={...Yr,lead_source_id:Yr.lead_source_id||null};je?(await R.mutateAsync({id:je.id,...Cr}),ve(null)):(await D.mutateAsync(Cr),fe(!1)),vn()},Hr=async Jt=>{confirm("Are you sure you want to delete this contact?")&&await z.mutateAsync(Jt)};return e.jsx(Ss,{title:"Contacts",description:"Manage your InnerCircle contacts",children:e.jsxs("div",{className:"space-y-6 overflow-x-hidden",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Contacts"}),e.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"})]}),Et&&e.jsxs("div",{className:"flex bg-muted rounded-lg p-1 gap-0.5",children:[e.jsx("button",{onClick:()=>st("my"),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors ${Je==="my"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:"My Contacts"}),(Et.team.contact_visibility==="full_team"||Et.team.contact_visibility==="leader_only"&&Et.role==="team_leader")&&e.jsxs("button",{onClick:()=>st("team"),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors flex items-center gap-1.5 ${Je==="team"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[e.jsx(Ar,{className:"h-3.5 w-3.5"}),"Team"]}),Et.team.lead_pond_enabled&&e.jsxs("button",{onClick:()=>st("lead-pond"),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors flex items-center gap-1.5 ${Je==="lead-pond"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[e.jsx(y1,{className:"h-3.5 w-3.5"}),"Lead Pond"]})]})]}),e.jsx("div",{className:"flex items-center gap-4",children:e.jsxs(H,{variant:"ghost",size:"sm",onClick:()=>s("/mission-control"),children:[e.jsx(fl,{className:"h-4 w-4 mr-1"}),"Back"]})}),Je==="team"?e.jsx(VEe,{}):Je==="lead-pond"&&Et?e.jsx(HEe,{teamId:Et.teamId}):e.jsxs(e.Fragment,{children:[e.jsx(L8s,{contacts:d,contactDealsMap:_,websiteActiveIds:m,activeKey:{"at-risk":"needs-attention",cooling:"cooling","not-touched-90":"stale-90","never-contacted":"never-contacted","birthdays-soon":"birthdays-soon","anniversary-soon":"anniversary-soon","has-deal":"has-deal","website-active":"website-active",vips:"vips","missing-info":"missing-info"}[ie]??null,onSelect:Jt=>{const Gt=Jt?{"needs-attention":"at-risk",cooling:"cooling","stale-90":"not-touched-90","never-contacted":"never-contacted","birthdays-soon":"birthdays-soon","anniversary-soon":"anniversary-soon","has-deal":"has-deal","website-active":"website-active",vips:"vips","missing-info":"missing-info"}[Jt]:"all";ce(Gt),Ne(1)}}),e.jsx(ke,{children:e.jsx(Oe,{className:"p-3",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Mn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Se,{placeholder:"Search by name, email, or phone...",value:$,onChange:Jt=>ee(Jt.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"space-y-2 sm:space-y-0",children:[e.jsxs(H,{onClick:()=>J(!0),className:"sm:hidden w-full h-11 bg-gradient-to-r from-orange-500 to-red-500 hover:from-orange-600 hover:to-red-600 text-white border-0 shadow-sm",children:[e.jsx(od,{className:"h-4 w-4 mr-2"}),"View Geographic Heat Map"]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 sm:hidden",children:[e.jsxs(H,{onClick:()=>fe(!0),className:"h-10 w-full justify-center",children:[e.jsx(Ys,{className:"h-4 w-4 mr-1.5"}),e.jsx("span",{className:"truncate",children:"Add Contact"})]}),e.jsxs(H,{variant:"outline",onClick:()=>Ve(!0),className:"h-10 w-full justify-center",children:[e.jsx(Ea,{className:"h-4 w-4 mr-1.5"}),e.jsx("span",{className:"truncate",children:"Import CSV"})]}),e.jsxs(H,{variant:"outline",onClick:()=>Me(!0),className:"h-10 w-full justify-center",children:[e.jsx(Vy,{className:"h-4 w-4 mr-1.5"}),e.jsx("span",{className:"truncate",children:"From Phone"})]}),e.jsx("div",{className:"w-full [&>*]:w-full [&_button]:w-full [&_button]:h-10 [&_button]:justify-center",children:e.jsx(DHe,{})})]}),e.jsxs("div",{className:"hidden sm:flex items-center gap-2 flex-wrap",children:[e.jsxs(H,{onClick:()=>fe(!0),className:"shrink-0",children:[e.jsx(Ys,{className:"h-4 w-4 mr-1"}),"Add Contact"]}),e.jsxs(H,{variant:"outline",onClick:()=>Ve(!0),className:"shrink-0",children:[e.jsx(Ea,{className:"h-4 w-4 mr-1"}),"Import CSV"]}),e.jsxs(H,{variant:"outline",onClick:()=>Me(!0),className:"shrink-0",children:[e.jsx(Vy,{className:"h-4 w-4 mr-1"}),"Import from Phone"]}),e.jsx(DHe,{}),e.jsxs(H,{variant:"outline",onClick:()=>J(!0),className:"shrink-0 border-orange-200 text-orange-700 hover:bg-orange-50 hover:text-orange-800 dark:border-orange-900 dark:text-orange-400",children:[e.jsx(od,{className:"h-4 w-4 mr-1"}),"Heat Map"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs(Bs,{value:K,onValueChange:re,children:[e.jsx(Os,{className:"w-[145px] h-9 text-sm",children:e.jsx(Us,{placeholder:"Filter by type"})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"all",children:"All Types"}),y==null?void 0:y.filter(Jt=>Jt.active).map(Jt=>e.jsx(pt,{value:Jt.id,children:Jt.name},Jt.id))]})]}),b&&b.length>0&&e.jsxs(gl,{children:[e.jsx(xl,{asChild:!0,children:e.jsxs(H,{variant:"outline",className:"h-9 justify-start text-sm",children:[e.jsx(xm,{className:"h-3.5 w-3.5 mr-1.5 shrink-0 text-muted-foreground"}),k.size===0?"Filter by Tags":`${k.size} tag${k.size>1?"s":""}`]})}),e.jsx(il,{className:"w-60 p-3",align:"start",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm font-medium",children:"Tags"}),e.jsxs("div",{className:"flex items-center gap-1 bg-muted rounded-md p-0.5",children:[e.jsx("button",{onClick:()=>A("any"),className:`px-2 py-0.5 rounded text-xs font-medium transition-colors ${E==="any"?"bg-background text-foreground shadow-sm":"text-muted-foreground"}`,children:"Any"}),e.jsx("button",{onClick:()=>A("all"),className:`px-2 py-0.5 rounded text-xs font-medium transition-colors ${E==="all"?"bg-background text-foreground shadow-sm":"text-muted-foreground"}`,children:"All"})]})]}),e.jsx("div",{className:"max-h-[200px] overflow-y-auto space-y-0.5",children:b.map(Jt=>{const Cr=k.has(Jt.id);return e.jsxs("button",{onClick:()=>{T(Gt=>{const Ee=new Set(Gt);return Ee.has(Jt.id)?Ee.delete(Jt.id):Ee.add(Jt.id),Ee})},className:"flex items-center gap-2 w-full px-2 py-1.5 rounded-md text-sm hover:bg-accent transition-colors",children:[e.jsx(ao,{checked:Cr,className:"pointer-events-none"}),e.jsx("div",{className:"h-2.5 w-2.5 rounded-full shrink-0",style:{backgroundColor:Jt.color}}),e.jsx("span",{className:"flex-1 text-left truncate",children:Jt.name})]},Jt.id)})}),k.size>0&&e.jsx(H,{variant:"ghost",size:"sm",className:"w-full text-xs",onClick:()=>T(new Set),children:"Clear tags"})]})})]}),e.jsxs(Xu,{children:[e.jsx(Qu,{asChild:!0,children:e.jsx(H,{variant:"ghost",size:"icon",className:"h-9 w-9 shrink-0",title:"Settings",children:e.jsx(Go,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsxs(wu,{align:"end",children:[e.jsxs(di,{onClick:()=>wt(!0),children:[e.jsx(xm,{className:"h-4 w-4 mr-2"}),"Manage Tags"]}),e.jsxs(di,{onClick:()=>rt(!0),children:[e.jsx(y1,{className:"h-4 w-4 mr-2"}),"Manage Lead Sources"]})]})]}),e.jsxs(Bs,{value:ie,onValueChange:ce,children:[e.jsx(Os,{className:"w-[145px] h-9 text-sm",children:e.jsx(Us,{placeholder:"Filter by status"})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"all",children:"All Status"}),e.jsx(pt,{value:"warm",children:"🟢 Warm"}),e.jsx(pt,{value:"cooling",children:"🟡 Cooling Off"}),e.jsx(pt,{value:"at-risk",children:"🔴 At Risk"}),e.jsx(pt,{value:"has-deal",children:"📋 Has Deal"}),e.jsx(pt,{value:"no-deal",children:"📭 No Deal"}),e.jsx(pt,{value:"open-house",children:"🏠 Open House"}),p&&e.jsx(pt,{value:"website-active",children:"🌐 Website Active"}),e.jsx(pt,{value:"in-drip",children:"🌱 In Drip Campaign"}),e.jsx(pt,{value:"not-in-drip",children:"🚫 Not In Drip"})]})]}),e.jsxs(Bs,{value:ne,onValueChange:le,children:[e.jsx(Os,{className:"w-[165px] h-9 text-sm",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(qu,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx(Us,{placeholder:"Sort by"})]})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"name",children:"Name (A-Z)"}),e.jsx(pt,{value:"important-dates",children:"Important Dates"}),e.jsx(pt,{value:"last-touched",children:"Last Touched"}),e.jsx(pt,{value:"next-touch",children:"Next Touch Due"}),e.jsx(pt,{value:"score",children:"Relationship Score"}),e.jsx(pt,{value:"date-added",children:"Date Added"})]})]}),e.jsx(P8s,{currentFilters:{search:$,type:K,status:ie},currentSortBy:ne,onApplySmartList:Na})]})]})})}),e.jsx(I8s,{selectedIds:pe,contacts:sn,onClearSelection:()=>{tt(new Set),ct(!1)},showLeadPondAction:Is,onSendToLeadPond:br,showTransferAction:lr,onTransfer:Gs}),pe.size>0&&pe.size===Zn.length&&!ge&&Vr>$e&&e.jsxs("div",{className:"flex items-center justify-center gap-2 p-2 bg-primary/5 border border-primary/20 rounded-lg text-sm",children:[e.jsxs("span",{children:["All ",Zn.length," contacts on this page are selected."]}),e.jsxs(H,{variant:"link",size:"sm",className:"h-auto p-0 font-semibold",onClick:ds,children:["Select all ",Vr.toLocaleString()," matching contacts"]})]}),ge&&e.jsxs("div",{className:"flex items-center justify-center gap-2 p-2 bg-primary/10 border border-primary/30 rounded-lg text-sm font-medium",children:["All ",Vr.toLocaleString()," matching contacts are selected.",e.jsx(H,{variant:"link",size:"sm",className:"h-auto p-0",onClick:()=>{tt(new Set),ct(!1)},children:"Clear selection"})]}),Vr>$e&&e.jsxs("div",{className:"flex flex-col sm:flex-row items-center justify-between gap-2 py-1",children:[e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Showing ",(hn-1)*$e+1,"–",Math.min(hn*$e,Vr)," of ",Vr.toLocaleString()," contacts"]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(H,{variant:"outline",size:"sm",disabled:hn<=1,onClick:()=>Ne(1),children:"First"}),e.jsx(H,{variant:"outline",size:"sm",disabled:hn<=1,onClick:()=>Ne(Jt=>Jt-1),children:e.jsx(fl,{className:"h-4 w-4"})}),e.jsxs("span",{className:"px-3 text-sm font-medium",children:["Page ",hn," of ",$r]}),e.jsx(H,{variant:"outline",size:"sm",disabled:hn>=$r,onClick:()=>Ne(Jt=>Jt+1),children:e.jsx($a,{className:"h-4 w-4"})}),e.jsx(H,{variant:"outline",size:"sm",disabled:hn>=$r,onClick:()=>Ne($r),children:"Last"})]})]}),a?e.jsx("div",{className:"space-y-3",children:h?e.jsx(ke,{className:"p-6 text-center text-muted-foreground",children:"Loading contacts..."}):sn.length===0?e.jsx(ke,{className:"p-6 text-center text-muted-foreground",children:$||K!=="all"||ie!=="all"?"No contacts match your search":"No contacts yet. Add your first contact!"}):Zn.map(Jt=>{var Gt,Ee,He;const{relationshipScore:Cr}=Jt;return e.jsx(ke,{className:"cursor-pointer hover:bg-accent/50 transition-colors",onClick:()=>{const ot=new URLSearchParams;$&&ot.set("search",$),K!=="all"&&ot.set("type",K),ie!=="all"&&ot.set("filter",ie);const jt=ot.toString();s(`/mission-control/contacts/${Jt.id}${jt?`?${jt}`:""}`)},children:e.jsx(Oe,{className:"p-4",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2 flex-wrap",children:[e.jsxs("h3",{className:"font-semibold text-base truncate",children:[Jt.first_name," ",Jt.last_name]}),e.jsx(UHe,{count:(x==null?void 0:x[Jt.id])??0}),e.jsx($a,{className:"h-4 w-4 text-muted-foreground shrink-0 ml-auto"})]}),e.jsxs("div",{className:"space-y-1 text-sm mb-3",children:[Jt.email&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(er,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{className:"truncate",children:Jt.email})]}),Jt.phone&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(Yn,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{children:Jt.phone})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1 mb-2",children:[e.jsx(T7,{score:Cr,size:"sm"}),e.jsx(j4e,{contact:Jt}),(((Gt=Jt.lead_source_ref)==null?void 0:Gt.name)||Jt.lead_source)&&e.jsx(Xe,{variant:"outline",className:"text-xs gap-1 border-primary/30 text-primary",children:((Ee=Jt.lead_source_ref)==null?void 0:Ee.name)||Jt.lead_source}),(He=Jt.tags)==null?void 0:He.map(ot=>{var jt;return e.jsx(Xe,{variant:"secondary",className:"text-xs",children:(jt=ot.relationship_type)==null?void 0:jt.name},ot.id)}),e.jsx(qHe,{contactId:Jt.id,tags:j==null?void 0:j.filter(ot=>ot.contact_id===Jt.id)}),e.jsx($He,{deal:_==null?void 0:_[Jt.id]})]}),e.jsx(zHe,{birthday:Jt.birthday,homeAnniversary:Jt.home_anniversary,className:"mb-2",contactId:Jt.id,contactName:`${Jt.first_name}${Jt.last_name?" "+Jt.last_name:""}`,contactAddress:[Jt.address,Jt.city,Jt.state].filter(Boolean).join(", ")}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-xs text-muted-foreground",children:[Cr.lastTouchDate?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Pn,{className:"h-3 w-3"}),As(new Date(Cr.lastTouchDate),"MMM d")]}):e.jsx("span",{className:"italic",children:"Never contacted"}),Jt.birthday&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Nn,{className:"h-3 w-3"}),As(Tc(Jt.birthday),"MMM d")]}),Jt.home_anniversary&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Fn,{className:"h-3 w-3"}),As(Tc(Jt.home_anniversary),"MMM d")]}),Jt.created_at&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Ys,{className:"h-3 w-3"}),"Added ",As(new Date(Jt.created_at),"MMM d, yyyy")]})]})]}),e.jsx("div",{className:"ml-2",onClick:ot=>ot.stopPropagation(),children:e.jsx(RHe,{contact:Jt,onEdit:ve,onDelete:Hr,onSnooze:(ot,jt)=>{Pe(ot),De(jt)},showLeadPondAction:Is,onSendToLeadPond:_s,showTransferAction:lr,onTransfer:fs})})]})})},Jt.id)})}):e.jsx(ke,{children:e.jsx(Oe,{className:"p-0 overflow-x-auto",children:e.jsxs(la,{className:"min-w-[800px]",children:[e.jsx(ca,{children:e.jsxs(Vs,{children:[e.jsx(At,{className:"w-[40px]",children:e.jsx(ao,{checked:Zn.length>0&&Zn.every(Jt=>pe.has(Jt.id)),onCheckedChange:()=>on()})}),e.jsx(At,{children:"Name"}),e.jsx(At,{children:"Status"}),e.jsx(At,{children:"Score"}),e.jsx(At,{children:"Contact Info"}),e.jsx(At,{children:"Types / Pipeline"}),e.jsx(At,{children:"Last Contact"}),e.jsx(At,{className:"cursor-pointer select-none",onClick:()=>le(ne==="date-added"?"name":"date-added"),children:e.jsxs("div",{className:"flex items-center gap-1",children:["Date Added",ne==="date-added"&&e.jsx(qu,{className:"h-3 w-3"})]})}),e.jsx(At,{children:"Important Dates"}),e.jsx(At,{className:"w-[50px]",children:"Actions"})]})}),e.jsx(da,{children:h?e.jsx(Vs,{children:e.jsx(gt,{colSpan:10,className:"text-center py-8",children:"Loading contacts..."})}):sn.length===0?e.jsx(Vs,{children:e.jsx(gt,{colSpan:10,className:"text-center py-8 text-muted-foreground",children:$||K!=="all"||ie!=="all"?"No contacts match your search":"No contacts yet. Add your first contact!"})}):Zn.map(Jt=>{var Ee,He,ot;const{relationshipScore:Cr}=Jt,Gt=_==null?void 0:_[Jt.id];return e.jsxs(Vs,{className:`cursor-pointer hover:bg-accent/50 ${pe.has(Jt.id)?"bg-accent/30":""}`,onClick:()=>{const jt=new URLSearchParams;$&&jt.set("search",$),K!=="all"&&jt.set("type",K),ie!=="all"&&jt.set("status",ie);const Dt=jt.toString();s(`/mission-control/contacts/${Jt.id}${Dt?`?${Dt}`:""}`)},children:[e.jsx(gt,{onClick:jt=>jt.stopPropagation(),children:e.jsx(ao,{checked:pe.has(Jt.id),onCheckedChange:()=>zr(Jt.id)})}),e.jsx(gt,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs("span",{children:[Jt.first_name," ",Jt.last_name]}),e.jsx(UHe,{count:(x==null?void 0:x[Jt.id])??0})]})}),e.jsx(gt,{children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx(T7,{score:Cr,size:"sm"}),e.jsx(j4e,{contact:Jt})]})}),e.jsx(gt,{children:e.jsx(T7,{score:Cr,size:"sm",showScore:!0})}),e.jsx(gt,{children:e.jsxs("div",{className:"space-y-1 text-sm",children:[Jt.email&&e.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground",children:[e.jsx(er,{className:"h-3 w-3"}),Jt.email]}),Jt.phone&&e.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground",children:[e.jsx(Yn,{className:"h-3 w-3"}),Jt.phone]})]})}),e.jsx(gt,{children:e.jsxs("div",{className:"flex flex-wrap gap-1",children:[(((Ee=Jt.lead_source_ref)==null?void 0:Ee.name)||Jt.lead_source)&&e.jsx(Xe,{variant:"outline",className:"text-xs border-primary/30 text-primary",children:((He=Jt.lead_source_ref)==null?void 0:He.name)||Jt.lead_source}),(ot=Jt.tags)==null?void 0:ot.map(jt=>{var Dt;return e.jsx(Xe,{variant:"secondary",className:"text-xs",children:(Dt=jt.relationship_type)==null?void 0:Dt.name},jt.id)}),e.jsx(qHe,{contactId:Jt.id,tags:j==null?void 0:j.filter(jt=>jt.contact_id===Jt.id)}),e.jsx($He,{deal:Gt})]})}),e.jsx(gt,{children:e.jsx("div",{className:"text-sm",children:Cr.lastTouchDate?e.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground",children:[e.jsx(Pn,{className:"h-3 w-3"}),As(new Date(Cr.lastTouchDate),"MMM d, yyyy")]}):e.jsx("span",{className:"text-muted-foreground text-xs italic",children:"Never contacted"})})}),e.jsx(gt,{children:e.jsx("span",{className:"text-sm text-muted-foreground",children:Jt.created_at?As(new Date(Jt.created_at),"MMM d, yyyy"):"—"})}),e.jsx(gt,{children:e.jsxs("div",{className:"space-y-1",children:[e.jsx(zHe,{birthday:Jt.birthday,homeAnniversary:Jt.home_anniversary,contactId:Jt.id,contactName:`${Jt.first_name}${Jt.last_name?" "+Jt.last_name:""}`,contactAddress:[Jt.address,Jt.city,Jt.state].filter(Boolean).join(", ")}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[Jt.birthday&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Nn,{className:"h-3 w-3"}),As(Tc(Jt.birthday),"MMM d")]}),Jt.home_anniversary&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Fn,{className:"h-3 w-3"}),As(Tc(Jt.home_anniversary),"MMM d")]})]})]})}),e.jsx(gt,{children:e.jsx(RHe,{contact:Jt,onEdit:ve,onDelete:Hr,onSnooze:(jt,Dt)=>{Pe(jt),De(Dt)},showLeadPondAction:Is,onSendToLeadPond:_s,showTransferAction:lr,onTransfer:fs})})]},Jt.id)})})]})})}),Vr>0&&e.jsxs("div",{className:"flex flex-col sm:flex-row items-center justify-between gap-4 py-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsxs("span",{children:["Showing ",(hn-1)*$e+1,"–",Math.min(hn*$e,Vr)," of ",Vr.toLocaleString()," contacts"]}),e.jsxs(Bs,{value:String($e),onValueChange:Jt=>{it(Number(Jt)),Ne(1)},children:[e.jsx(Os,{className:"w-[80px] h-8",children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"50",children:"50"}),e.jsx(pt,{value:"100",children:"100"}),e.jsx(pt,{value:"250",children:"250"})]})]}),e.jsx("span",{className:"text-xs",children:"per page"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(H,{variant:"outline",size:"sm",disabled:hn<=1,onClick:()=>Ne(1),children:"First"}),e.jsx(H,{variant:"outline",size:"sm",disabled:hn<=1,onClick:()=>Ne(Jt=>Jt-1),children:e.jsx(fl,{className:"h-4 w-4"})}),e.jsxs("span",{className:"px-3 text-sm font-medium",children:["Page ",hn," of ",$r]}),e.jsx(H,{variant:"outline",size:"sm",disabled:hn>=$r,onClick:()=>Ne(Jt=>Jt+1),children:e.jsx($a,{className:"h-4 w-4"})}),e.jsx(H,{variant:"outline",size:"sm",disabled:hn>=$r,onClick:()=>Ne($r),children:"Last"})]})]}),e.jsx(bs,{open:be||!!je,onOpenChange:Jt=>{Jt||(fe(!1),ve(null),vn())},children:e.jsxs(vs,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(Cs,{children:e.jsx(Ns,{children:je?"Edit Contact":"Add Contact"})}),e.jsxs("form",{onSubmit:_r,className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"first_name",children:"First Name *"}),e.jsx(Se,{id:"first_name",value:Yr.first_name,onChange:Jt=>rn({...Yr,first_name:Jt.target.value}),required:!0})]}),e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"last_name",children:"Last Name"}),e.jsx(Se,{id:"last_name",value:Yr.last_name,onChange:Jt=>rn({...Yr,last_name:Jt.target.value})})]})]}),e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"email",children:"Email"}),e.jsx(Se,{id:"email",type:"email",value:Yr.email,onChange:Jt=>rn({...Yr,email:Jt.target.value})})]}),e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"phone",children:"Phone"}),e.jsx(Se,{id:"phone",value:Yr.phone,onChange:Jt=>rn({...Yr,phone:Jt.target.value})})]}),e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"address",children:"Address"}),e.jsx(Se,{id:"address",value:Yr.address,onChange:Jt=>rn({...Yr,address:Jt.target.value}),placeholder:"Street address"})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"city",children:"City"}),e.jsx(Se,{id:"city",value:Yr.city,onChange:Jt=>rn({...Yr,city:Jt.target.value})})]}),e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"state",children:"State"}),e.jsx(Se,{id:"state",value:Yr.state,onChange:Jt=>rn({...Yr,state:Jt.target.value})})]}),e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"zip_code",children:"Zip"}),e.jsx(Se,{id:"zip_code",value:Yr.zip_code,onChange:Jt=>rn({...Yr,zip_code:Jt.target.value})})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"birthday",children:"Birthday"}),e.jsx(Se,{id:"birthday",type:"date",value:Yr.birthday,onChange:Jt=>rn({...Yr,birthday:Jt.target.value})})]}),e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"home_anniversary",children:"Home Anniversary"}),e.jsx(Se,{id:"home_anniversary",type:"date",value:Yr.home_anniversary,onChange:Jt=>rn({...Yr,home_anniversary:Jt.target.value})})]})]}),je&&e.jsx(N4e,{contactId:je.id,currentSpouseContactId:(je==null?void 0:je.spouse_contact_id)||null,currentSpouseName:(je==null?void 0:je.spouse_name)||null,currentSpouseEmail:(je==null?void 0:je.spouse_email)||null,onLink:Jt=>O.mutate({contactId:je.id,spouseContactId:Jt}),onUnlink:()=>O.mutate({contactId:je.id,spouseContactId:null}),isEditing:!0}),e.jsx(Xgt,{value:Yr.lead_source_id,onChange:Jt=>rn({...Yr,lead_source_id:Jt})}),e.jsxs("div",{children:[e.jsx(ue,{children:"Relationship Types"}),e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:y==null?void 0:y.filter(Jt=>Jt.active).map(Jt=>e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx(ao,{checked:Yr.tagIds.includes(Jt.id),onCheckedChange:Cr=>{rn(Cr?{...Yr,tagIds:[...Yr.tagIds,Jt.id]}:{...Yr,tagIds:Yr.tagIds.filter(Gt=>Gt!==Jt.id)})}}),e.jsx("span",{className:"text-sm",children:Jt.name})]},Jt.id))})]}),e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"notes",children:"Notes"}),e.jsx(vr,{id:"notes",value:Yr.notes,onChange:Jt=>rn({...Yr,notes:Jt.target.value}),rows:3})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(H,{type:"button",variant:"outline",onClick:()=>{fe(!1),ve(null),vn()},children:"Cancel"}),e.jsxs(H,{type:"submit",disabled:D.isPending||R.isPending,children:[je?"Update":"Create"," Contact"]})]})]})]})}),e.jsx(JLs,{open:We,onOpenChange:Ve,relationshipTypes:(y==null?void 0:y.filter(Jt=>Jt.active))||[],onSuccess:()=>{Ve(!1)}}),e.jsx(s8s,{open:Le,onOpenChange:Me,onComplete:()=>Me(!1)}),e.jsx(P0e,{open:!!ze,onOpenChange:Jt=>{Jt||Pe(null)},contactId:ze||"",contactName:Ie}),e.jsx(U8s,{open:mt,onOpenChange:wt}),e.jsx(q8s,{open:at,onOpenChange:rt}),e.jsx(F8s,{open:Z,onOpenChange:J,contacts:d||[],onCitySelect:Jt=>{ee(Jt),Ne(1)}}),e.jsx(fht,{open:xs,onOpenChange:kt,contactIds:us,contactNames:us.map(Jt=>{const Cr=sn.find(Gt=>Gt.id===Jt);return Cr?`${Cr.first_name} ${Cr.last_name||""}`.trim():""}),onComplete:()=>{St([]),tt(new Set),ct(!1)}})]})]})})}const H8s="9a88a47c-cb2a-4401-a2b5-111a76b19f9d";function G8s({open:s,onOpenChange:t,contact:r}){var Z;const{user:n}=Ms(),a=Fr(),i=ns(),{intakePage:l,isLoading:o}=L0e(),{isGmailConnected:c,gmailEmail:d}=cf(),h=Jge(),{data:m}=yt({queryKey:["profile-for-invite",n==null?void 0:n.id],enabled:!!(n!=null&&n.id)&&s,queryFn:async()=>{const{data:J}=await V.from("profiles").select("name, email, avatar_url").eq("id",n.id).maybeSingle();return J}}),p=(m==null?void 0:m.name)||((Z=n==null?void 0:n.email)==null?void 0:Z.split("@")[0])||"Your Agent",x=p.split(" ")[0],y=l?`https://contacts.relevelup.com/${l.slug}`:"",_=S.useMemo(()=>`Hi ${r.first_name}, I'm updating my contact list and want to make sure I have your latest info — the best phone, email, address, and a couple of dates I love to remember (like your birthday and home anniversary). It only takes about a minute, and it helps me stay in touch the right way. Thanks so much!`,[r.first_name]),[b,j]=S.useState("gmail"),[k,T]=S.useState(""),[E,A]=S.useState(""),[D,R]=S.useState(!1);S.useEffect(()=>{s&&(T(`Quick favor, ${r.first_name} — can you update your info?`),A(_),j(c?"gmail":"system"))},[s,_,r.first_name,c]);const z=S.useMemo(()=>E.split(/\n\n+/).map(J=>`

${J.replace(/&/g,"&").replace(//g,">").replace(/\n/g,"
")}

`).join(""),[E]),O=()=>`
${m!=null&&m.avatar_url?`${p}`:`
${x.charAt(0)}
`}

A note from ${p}

${z}

Update Your Info

Takes about a minute — promise

Share My Info →

${y}

Sent with care by ${p}

Powered by ReLevelUp

`,$=async()=>{if(!l){he.error("Set up your Connect Page first",{action:{label:"Set Up",onClick:()=>a("/mission-control/connect-page")}});return}if(!k.trim()||!E.trim()){he.error("Subject and message are required");return}R(!0);const J=O();try{if(b==="gmail"&&c){const{data:K,error:re}=await V.functions.invoke("gmail-send",{body:{to:r.email,subject:k,body:J,contactId:r.id}});if(re)throw re;if(!(K!=null&&K.success))throw new Error((K==null?void 0:K.error)||"Failed to send")}else{const{data:K,error:re}=await V.functions.invoke("send-connect-invite",{body:{contactEmail:r.email,subject:k,htmlBody:J,replyToEmail:(m==null?void 0:m.email)||(n==null?void 0:n.email),agentName:p}});if(re)throw re;if(!(K!=null&&K.success))throw new Error((K==null?void 0:K.error)||"Failed to send")}try{await h.mutateAsync({contactId:r.id,actionTypeId:H8s,notes:`Sent Connect Page invite — Subject: "${k}"`})}catch(K){console.warn("Failed to log activity:",K)}i.invalidateQueries({queryKey:["contact-touch-logs"]}),he.success("Connect Page invite sent!"),t(!1)}catch(K){console.error("Send error:",K),he.error(K instanceof Error?K.message:"Failed to send invite")}finally{R(!1)}},ee=O();return e.jsx(bs,{open:s,onOpenChange:J=>!D&&t(J),children:e.jsxs(vs,{className:"sm:max-w-[720px] max-h-[92vh] overflow-y-auto",children:[e.jsxs(Cs,{children:[e.jsxs(Ns,{className:"flex items-center gap-2",children:[e.jsx(Lr,{className:"h-5 w-5 text-primary"}),"Send Connect Page Invite"]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Ask ",e.jsxs("span",{className:"font-medium",children:[r.first_name," ",r.last_name||""]})," to share their latest contact info — takes them about a minute."]})]}),o?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(is,{className:"h-6 w-6 animate-spin text-primary"})}):l?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Send From"}),e.jsx(ta,{value:b,onValueChange:J=>j(J),className:"mt-1.5",children:e.jsxs(Qn,{className:"grid w-full grid-cols-2",children:[e.jsxs(ts,{value:"gmail",disabled:!c,children:[e.jsx(er,{className:"h-3.5 w-3.5 mr-1.5"}),c?`Gmail (${d})`:"Gmail (not connected)"]}),e.jsxs(ts,{value:"system",children:[e.jsx(Lr,{className:"h-3.5 w-3.5 mr-1.5"}),"System Email"]})]})}),e.jsx("p",{className:"text-[11px] text-muted-foreground mt-1.5",children:b==="gmail"?"Replies go directly to your Gmail inbox.":`Sent from notifications@dashboard.relevelup.com — replies go to ${(m==null?void 0:m.email)||(n==null?void 0:n.email)||"your account email"}.`})]}),e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"invite-subject",children:"Subject"}),e.jsx(Se,{id:"invite-subject",value:k,onChange:J=>T(J.target.value),className:"mt-1.5"})]}),e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"invite-message",children:"Personal Message"}),e.jsx(vr,{id:"invite-message",value:E,onChange:J=>A(J.target.value),rows:6,className:"mt-1.5 resize-none"}),e.jsx("p",{className:"text-[11px] text-muted-foreground mt-1",children:"The Connect Page button is added below your message automatically."})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[e.jsx(ue,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Preview"}),e.jsxs("a",{href:y,target:"_blank",rel:"noopener noreferrer",className:"text-xs text-primary hover:underline flex items-center gap-1",children:["Open Connect Page ",e.jsx(gn,{className:"h-3 w-3"})]})]}),e.jsx("div",{className:"rounded-lg border overflow-hidden bg-muted/30",children:e.jsx("iframe",{srcDoc:ee,title:"Email preview",sandbox:"",className:"w-full h-[420px] bg-background"})})]}),e.jsxs("div",{className:"flex items-center justify-end gap-2 pt-2",children:[e.jsx(H,{variant:"outline",onClick:()=>t(!1),disabled:D,children:"Cancel"}),e.jsx(H,{onClick:$,disabled:D,children:D?e.jsxs(e.Fragment,{children:[e.jsx(is,{className:"h-4 w-4 mr-1.5 animate-spin"})," Sending…"]}):e.jsxs(e.Fragment,{children:[e.jsx(yn,{className:"h-4 w-4 mr-1.5"})," Send Invite"]})})]})]}):e.jsxs("div",{className:"space-y-4 py-6 text-center",children:[e.jsx(wo,{className:"h-10 w-10 text-amber-500 mx-auto"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"You haven't set up a Connect Page yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Create yours in one click — it only takes a moment."})]}),e.jsxs(H,{onClick:()=>a("/mission-control/connect-page"),children:[e.jsx(ql,{className:"h-4 w-4 mr-1"})," Set Up Connect Page"]})]})]})})}function W8s(s){return yt({queryKey:["contact-video-replies",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await V.from("video_replies").select(` *, video:agent_videos(id, title, thumbnail_url, playback_url) `).eq("contact_id",s).order("created_at",{ascending:!1});if(r)throw r;return t},enabled:!!s})}function K8s(s){return yt({queryKey:["client-portal",s],queryFn:async()=>{if(!s)return null;const{data:t,error:r}=await V.from("client_portals").select("*").eq("deal_id",s).maybeSingle();if(r)throw r;return t},enabled:!!s})}function dMe(){const s=ba(),t=ns();return Pt({mutationFn:async r=>{if(!s)throw new Error("Not authenticated");const{data:n,error:a}=await V.from("client_portals").insert({deal_id:r.deal_id,owner_user_id:s,slug:"",is_enabled:r.is_enabled??!0,visibility:r.visibility||"private",require_onboarding:r.require_onboarding??!0,allow_spouse:r.allow_spouse??!1,client_name:r.client_name||null,client_email:r.client_email||null,client_phone:r.client_phone||null,invite_method:r.invite_method||"email"}).select().single();if(a)throw a;return n},onSuccess:(r,n)=>{t.invalidateQueries({queryKey:["client-portal",n.deal_id]})}})}function G8(){const s=ns();return Pt({mutationFn:async({id:t,...r})=>{const{data:n,error:a}=await V.from("client_portals").update(r).eq("id",t).select().single();if(a)throw a;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["client-portal",t.deal_id]}),s.invalidateQueries({queryKey:["all-client-portals"]})}})}function Qgt(){const s=ns();return Pt({mutationFn:async t=>{const{data:r,error:n}=await V.from("client_portals").update({archived_at:new Date().toISOString(),is_enabled:!1}).eq("id",t).select().single();if(n)throw n;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["client-portal",t.deal_id]}),s.invalidateQueries({queryKey:["all-client-portals"]})}})}function Jgt(){const s=ns();return Pt({mutationFn:async t=>{const{data:r,error:n}=await V.from("client_portals").update({archived_at:null}).eq("id",t).select().single();if(n)throw n;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["client-portal",t.deal_id]}),s.invalidateQueries({queryKey:["all-client-portals"]})}})}function ext(){const s=ns();return Pt({mutationFn:async({id:t,dealId:r})=>{await V.from("portal_updates").delete().eq("portal_id",t);const{error:n}=await V.from("client_portals").delete().eq("id",t);if(n)throw n;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["client-portal",t]}),s.invalidateQueries({queryKey:["all-client-portals"]})}})}function Y8s(s){return yt({queryKey:["portal-updates",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await V.from("portal_updates").select("*").eq("portal_id",s).order("created_at",{ascending:!1});if(r)throw r;return t},enabled:!!s})}function txt(){const s=ns();return Pt({mutationFn:async t=>{const{data:r,error:n}=await V.from("portal_updates").insert({portal_id:t.portal_id,title:t.title,content:t.content||null,video_url:t.video_url||null,is_stage_change:t.is_stage_change||!1}).select().single();if(n)throw n;return r},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["portal-updates",r.portal_id]})}})}function Z8s(){const s=ba();return yt({queryKey:["portal-custom-questions",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await V.from("portal_custom_questions").select("*").eq("owner_user_id",s).eq("is_active",!0).order("sort_order",{ascending:!0});if(r)throw r;return t},enabled:!!s})}function X8s(){const s=ba(),t=ns();return Pt({mutationFn:async r=>{if(!s)throw new Error("Not authenticated");const{data:n,error:a}=await V.from("portal_custom_questions").insert({owner_user_id:s,question_text:r.question_text,field_type:r.field_type,options:r.options||[],is_required:r.is_required||!1,sort_order:r.sort_order||0}).select().single();if(a)throw a;return n},onSuccess:()=>{t.invalidateQueries({queryKey:["portal-custom-questions"]})}})}function Q8s(){const s=ns();return Pt({mutationFn:async({id:t,...r})=>{const{data:n,error:a}=await V.from("portal_custom_questions").update(r).eq("id",t).select().single();if(a)throw a;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["portal-custom-questions"]})}})}function J8s(){const s=ns();return Pt({mutationFn:async t=>{const{error:r}=await V.from("portal_custom_questions").update({is_active:!1}).eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["portal-custom-questions"]})}})}function C_(s){const t=window.location.hostname;return t==="localhost"||t.includes("lovable.app")?`${window.location.origin}/portal/${s}`:`https://clients.relevelup.com/${s}`}function eDs({contactId:s}){const t=Fr(),r=ns(),[n,a]=S.useState(null),[i,l]=S.useState(!1),[o,c]=S.useState(!1),[d,h]=S.useState(""),[m,p]=S.useState(""),[x,y]=S.useState(null),_=G8(),b=txt(),{data:j,isLoading:k}=yt({queryKey:["contact-portals",s],queryFn:async()=>{const{data:z,error:O}=await V.from("deal_pipeline").select("id, deal_name, deal_type").eq("contact_id",s);if(O)throw O;if(!z||z.length===0)return[];const $=z.map(J=>J.id),{data:ee,error:Z}=await V.from("client_portals").select("*").in("deal_id",$).is("archived_at",null);if(Z)throw Z;return(ee||[]).map(J=>({...J,deal:z.find(K=>K.id===J.deal_id)}))},enabled:!!s}),T=(j==null?void 0:j.map(z=>z.id))||[],{data:E}=yt({queryKey:["contact-portal-updates",T],queryFn:async()=>{if(T.length===0)return{};const{data:z,error:O}=await V.from("portal_updates").select("*").in("portal_id",T).order("created_at",{ascending:!1});if(O)throw O;const $={};return(z||[]).forEach(ee=>{$[ee.portal_id]||($[ee.portal_id]=ee)}),$},enabled:T.length>0}),A=z=>{navigator.clipboard.writeText(C_(z)),a(z),he.success("Portal link copied!"),setTimeout(()=>a(null),2e3)},D=async z=>{d.trim()&&(await b.mutateAsync({portal_id:z,title:d,content:m||void 0}),c(!1),h(""),p(""),r.invalidateQueries({queryKey:["contact-portal-updates"]}),he.success("Portal update posted!"))},R=async()=>{x&&(await _.mutateAsync({id:x.id,welcome_message:x.welcome_message,next_step_text:x.next_step_text,is_enabled:x.is_enabled,show_post_close_tips:x.show_post_close_tips,review_url:x.review_url}),l(!1),y(null),r.invalidateQueries({queryKey:["contact-portals",s]}),he.success("Portal settings updated!"))};return k||!j||j.length===0?null:e.jsxs(ke,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsxs(zt,{className:"text-base flex items-center gap-2",children:[e.jsx(ld,{className:"h-4 w-4"}),"Client Portal"]})}),e.jsx(Oe,{className:"space-y-3",children:j.map(z=>{var Z,J,K;const O=((Z=z.stage_mapping)==null?void 0:Z.length)>0?z.stage_mapping:Bge(((J=z.deal)==null?void 0:J.deal_type)||"buyer"),$=O==null?void 0:O[z.current_stage_index??0],ee=E==null?void 0:E[z.id];return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:((K=z.deal)==null?void 0:K.deal_name)||"Portal"}),$&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Stage: ",$.label||$.name]})]}),e.jsx(Xe,{variant:z.is_enabled?"default":"secondary",className:"text-[10px] flex-shrink-0",children:z.is_enabled?"Active":"Disabled"})]}),ee&&e.jsxs("div",{className:"bg-muted/50 rounded-md p-2",children:[e.jsx("p",{className:"text-xs font-medium truncate",children:ee.title}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:As(new Date(ee.created_at),"MMM d, yyyy")})]}),e.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[e.jsxs(H,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>A(z.slug),children:[n===z.slug?e.jsx(va,{className:"h-3 w-3 mr-1"}):e.jsx(ui,{className:"h-3 w-3 mr-1"}),"Copy Link"]}),e.jsxs(H,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>window.open(C_(z.slug),"_blank"),children:[e.jsx(gn,{className:"h-3 w-3 mr-1"}),"View"]}),e.jsxs(bs,{open:o,onOpenChange:c,children:[e.jsx(Qi,{asChild:!0,children:e.jsxs(H,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>c(!0),children:[e.jsx(Gi,{className:"h-3 w-3 mr-1"}),"Post Update"]})}),e.jsxs(vs,{children:[e.jsx(Cs,{children:e.jsx(Ns,{children:"Post Portal Update"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ue,{children:"Title"}),e.jsx(Se,{value:d,onChange:re=>h(re.target.value),placeholder:"e.g. Inspection completed!"})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Details (optional)"}),e.jsx(vr,{value:m,onChange:re=>p(re.target.value),placeholder:"Add more details...",rows:3})]}),e.jsxs(H,{onClick:()=>D(z.id),disabled:!d.trim()||b.isPending,className:"w-full",children:[e.jsx(yn,{className:"h-4 w-4 mr-1"}),"Post Update"]})]})]})]}),e.jsxs(bs,{open:i,onOpenChange:l,children:[e.jsx(Qi,{asChild:!0,children:e.jsxs(H,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>{y({...z}),l(!0)},children:[e.jsx(Go,{className:"h-3 w-3 mr-1"}),"Settings"]})}),e.jsxs(vs,{children:[e.jsx(Cs,{children:e.jsx(Ns,{children:"Portal Settings"})}),x&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ue,{children:"Portal Enabled"}),e.jsx(Or,{checked:x.is_enabled,onCheckedChange:re=>y({...x,is_enabled:re})})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Welcome Message"}),e.jsx(vr,{value:x.welcome_message||"",onChange:re=>y({...x,welcome_message:re.target.value}),placeholder:"Welcome to your home journey!",rows:2})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Next Step"}),e.jsx(Se,{value:x.next_step_text||"",onChange:re=>y({...x,next_step_text:re.target.value}),placeholder:"What your client should do next..."})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Review URL"}),e.jsx(Se,{value:x.review_url||"",onChange:re=>y({...x,review_url:re.target.value}),placeholder:"https://..."})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ue,{children:"Show Post-Close Tips"}),e.jsx(Or,{checked:x.show_post_close_tips,onCheckedChange:re=>y({...x,show_post_close_tips:re})})]}),e.jsx(Qo,{}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(H,{onClick:R,disabled:_.isPending,className:"flex-1",children:"Save Settings"}),e.jsxs(H,{variant:"outline",onClick:()=>t(`/mission-control/pipeline?deal=${z.deal_id}`),children:[e.jsx(bi,{className:"h-4 w-4 mr-1"}),"Full Settings"]})]})]})]})]})]}),j.length>1&&e.jsx(Qo,{})]},z.id)})})]})}function tDs({contactId:s}){const{data:t}=yt({queryKey:["agent-lead-sites-slugs"],queryFn:async()=>{const{data:l,error:o}=await V.from("lead_sites").select("id, subdomain_slug").eq("is_active",!0);if(o)throw o;return new Map((l||[]).map(c=>[c.id,c.subdomain_slug]))},staleTime:6e5}),r=t&&t.size>0,{data:n,isLoading:a}=yt({queryKey:["contact-property-views",s],queryFn:async()=>{const{data:l,error:o}=await V.rpc("get_contact_property_views",{p_contact_id:s});if(o)throw o;return l||[]},enabled:!!s&&!!r});if(!r||a||!n||n.length===0)return null;const i=l=>{const o=t==null?void 0:t.get(l.lead_site_id);return o?`https://${o}.thelocalmove.com/listing/${l.mls_number}`:null};return e.jsxs(ke,{className:"overflow-hidden",children:[e.jsx(Ot,{className:"pb-2",children:e.jsxs(zt,{className:"text-base flex items-center gap-2",children:[e.jsx("div",{className:"h-7 w-7 rounded-lg bg-primary/10 flex items-center justify-center",children:e.jsx(Bn,{className:"h-4 w-4 text-primary"})}),"Property Activity",e.jsxs(Xe,{variant:"secondary",className:"text-xs ml-auto",children:[n.length," ",n.length===1?"property":"properties"]})]})}),e.jsx(Oe,{className:"pt-0",children:e.jsx("div",{className:"space-y-1",children:n.map(l=>{const o=i(l),c=l.property_address||`MLS# ${l.mls_number}`;return e.jsxs("a",{href:o||"#",target:"_blank",rel:"noopener noreferrer",onClick:d=>{o||d.preventDefault()},className:"group flex items-center gap-3 p-2.5 rounded-lg hover:bg-muted/60 transition-colors",children:[l.photo_url?e.jsx("div",{className:"h-10 w-10 rounded-lg overflow-hidden flex-shrink-0 bg-muted",children:e.jsx("img",{src:l.photo_url,alt:c,className:"w-full h-full object-cover"})}):e.jsx("div",{className:"h-9 w-9 rounded-lg bg-gradient-to-br from-primary/15 to-primary/5 flex items-center justify-center flex-shrink-0",children:e.jsx(Fn,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"flex items-center gap-1.5",children:e.jsx("span",{className:"font-medium text-sm truncate",children:c})}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(Pn,{className:"h-3 w-3"}),e.jsx("span",{title:As(new Date(l.viewed_at),"PPp"),children:Hl(new Date(l.viewed_at),{addSuffix:!0})})]})]}),o&&e.jsx(gn,{className:"h-3.5 w-3.5 text-muted-foreground opacity-0 group-hover:opacity-100 transition-opacity"})]},l.mls_number)})})})]})}const sDs=["Single Family","Condo","Townhouse","Multi-Family","Land","Commercial"];function HHe({value:s,onChange:t,onAdd:r,suggestions:n,placeholder:a,icon:i}){const[l,o]=S.useState(!1),c=S.useRef(null),d=S.useRef(null);S.useEffect(()=>{const m=p=>{d.current&&!d.current.contains(p.target)&&c.current&&!c.current.contains(p.target)&&o(!1)};return document.addEventListener("mousedown",m),()=>document.removeEventListener("mousedown",m)},[]);const h=n.filter(m=>m.toLowerCase().includes(s.toLowerCase()));return e.jsxs("div",{className:"relative flex-1",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Se,{ref:c,value:s,onChange:m=>{t(m.target.value),o(!0)},onFocus:()=>o(!0),placeholder:a,onKeyDown:m=>{m.key==="Enter"&&(m.preventDefault(),h.length>0?r(h[0]):r(s))}}),n.length>0&&e.jsx(Io,{className:"absolute right-3 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground pointer-events-none"})]}),e.jsx(H,{type:"button",variant:"outline",size:"sm",onClick:()=>r(s),children:e.jsx(Ys,{className:"h-4 w-4"})})]}),l&&h.length>0&&e.jsx("div",{ref:d,className:"absolute z-50 mt-1 w-full max-h-60 overflow-y-auto rounded-md border bg-popover shadow-md",children:h.map(m=>e.jsxs("button",{type:"button",className:"w-full text-left px-3 py-2 text-sm hover:bg-accent hover:text-accent-foreground transition-colors flex items-center gap-2",onClick:()=>{r(m),o(!1)},children:[i||e.jsx(Qa,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"}),m]},m))})]})}function rDs({contactId:s,contactName:t}){var O,$,ee;const{user:r}=Ms(),n=ba(),{hasLeadSite:a}=av(),i=ns(),[l,o]=S.useState(!1),[c,d]=S.useState(""),[h,m]=S.useState(""),{data:p}=yt({queryKey:["agent-lead-site-config",n],queryFn:async()=>{const{data:Z,error:J}=await V.from("lead_sites").select("theme_config, mls_market_area").eq("agent_id",n).eq("is_active",!0).order("created_at",{ascending:!0}).limit(1).maybeSingle();if(J||!Z)return{cities:[],zipCodes:[]};const K=Z.theme_config||{},re=Array.isArray(K.searchCities)?K.searchCities:[];Z.mls_market_area&&!re.includes(Z.mls_market_area)&&re.unshift(Z.mls_market_area);const ie=Array.isArray(K.searchZipCodes)?K.searchZipCodes:[];return{cities:re,zipCodes:ie}},enabled:!!n}),{data:x,isLoading:y}=yt({queryKey:["contact-property-alert",s],queryFn:async()=>{const{data:Z,error:J}=await V.from("contact_property_alerts").select("*").eq("contact_id",s).maybeSingle();if(J)throw J;return Z},enabled:!!s&&!!r}),[_,b]=S.useState({}),j=()=>{b({is_active:(x==null?void 0:x.is_active)??!0,min_price:(x==null?void 0:x.min_price)??null,max_price:(x==null?void 0:x.max_price)??null,min_beds:(x==null?void 0:x.min_beds)??null,min_baths:(x==null?void 0:x.min_baths)??null,min_sqft:(x==null?void 0:x.min_sqft)??null,max_sqft:(x==null?void 0:x.max_sqft)??null,cities:(x==null?void 0:x.cities)??[],zip_codes:(x==null?void 0:x.zip_codes)??[],property_types:(x==null?void 0:x.property_types)??[],frequency:(x==null?void 0:x.frequency)??"daily"}),o(!0)},k=Pt({mutationFn:async()=>{const Z={contact_id:s,owner_user_id:n,is_active:_.is_active??!0,min_price:_.min_price||null,max_price:_.max_price||null,min_beds:_.min_beds||null,min_baths:_.min_baths||null,min_sqft:_.min_sqft||null,max_sqft:_.max_sqft||null,cities:_.cities||[],zip_codes:_.zip_codes||[],property_types:_.property_types||[],frequency:_.frequency||"daily"};if(x!=null&&x.id){const{error:J}=await V.from("contact_property_alerts").update(Z).eq("id",x.id);if(J)throw J}else{const{error:J}=await V.from("contact_property_alerts").insert(Z);if(J)throw J}},onSuccess:()=>{i.invalidateQueries({queryKey:["contact-property-alert",s]}),o(!1),he.success("Property alert saved!")},onError:Z=>{he.error(Z.message||"Failed to save alert")}}),T=Pt({mutationFn:async()=>{if(!(x!=null&&x.id))return;const{error:Z}=await V.from("contact_property_alerts").delete().eq("id",x.id);if(Z)throw Z},onSuccess:()=>{i.invalidateQueries({queryKey:["contact-property-alert",s]}),o(!1),he.success("Property alert removed")}}),E=Z=>{var K;const J=Z.trim();J&&!((K=_.cities)!=null&&K.includes(J))&&b(re=>({...re,cities:[...re.cities||[],J]})),d("")},A=Z=>{var K;const J=Z.trim();J&&!((K=_.zip_codes)!=null&&K.includes(J))&&b(re=>({...re,zip_codes:[...re.zip_codes||[],J]})),m("")},D=Z=>{b(J=>{const K=J.property_types||[];return{...J,property_types:K.includes(Z)?K.filter(re=>re!==Z):[...K,Z]}})};if(!a||y)return null;if(x&&!l)return e.jsxs(ke,{className:"overflow-hidden",children:[e.jsx(Ot,{className:"pb-2",children:e.jsxs(zt,{className:"text-base flex items-center gap-2",children:[e.jsx("div",{className:`h-7 w-7 rounded-lg flex items-center justify-center ${x.is_active?"bg-green-500/10":"bg-muted"}`,children:x.is_active?e.jsx(wp,{className:"h-4 w-4 text-green-600"}):e.jsx(u_,{className:"h-4 w-4 text-muted-foreground"})}),"Property Alerts",e.jsxs(Xe,{variant:x.is_active?"default":"secondary",className:"text-xs ml-auto",children:[x.is_active?"Active":"Paused"," · ",x.frequency]})]})}),e.jsxs(Oe,{className:"pt-0 space-y-2",children:[e.jsxs("div",{className:"flex flex-wrap gap-1.5 text-xs",children:[x.min_price||x.max_price?e.jsxs(Xe,{variant:"outline",className:"gap-1",children:[e.jsx(oc,{className:"h-3 w-3"}),x.min_price?`$${(x.min_price/1e3).toFixed(0)}k`:"$0"," - ",x.max_price?`$${(x.max_price/1e3).toFixed(0)}k`:"Any"]}):null,x.min_beds?e.jsxs(Xe,{variant:"outline",className:"gap-1",children:[e.jsx(B2,{className:"h-3 w-3"}),x.min_beds,"+ beds"]}):null,x.min_baths?e.jsxs(Xe,{variant:"outline",className:"gap-1",children:[e.jsx(_p,{className:"h-3 w-3"}),x.min_baths,"+ baths"]}):null,(O=x.cities)==null?void 0:O.map(Z=>e.jsxs(Xe,{variant:"outline",className:"gap-1",children:[e.jsx(Qa,{className:"h-3 w-3"}),Z]},Z)),($=x.zip_codes)==null?void 0:$.map(Z=>e.jsx(Xe,{variant:"outline",children:Z},Z)),(ee=x.property_types)==null?void 0:ee.map(Z=>e.jsx(Xe,{variant:"outline",children:Z},Z))]}),x.last_sent_at&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Last sent: ",new Date(x.last_sent_at).toLocaleDateString()]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(H,{variant:"outline",size:"sm",onClick:j,className:"flex-1",children:"Manage Alert"}),e.jsxs(H,{variant:"destructive",size:"sm",onClick:()=>T.mutate(),disabled:T.isPending,className:"flex-1",children:[T.isPending?e.jsx(is,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Rr,{className:"h-4 w-4 mr-1"}),"Remove Alert"]})]})]})]});const R=((p==null?void 0:p.cities)||[]).filter(Z=>{var J;return!((J=_.cities)!=null&&J.includes(Z))}),z=((p==null?void 0:p.zipCodes)||[]).filter(Z=>{var J;return!((J=_.zip_codes)!=null&&J.includes(Z))});return l?e.jsxs(ke,{children:[e.jsx(Ot,{className:"pb-3",children:e.jsxs(zt,{className:"text-base flex items-center gap-2",children:[e.jsx(wp,{className:"h-4 w-4 text-primary"}),x?"Edit":"Setup"," Property Alert for ",t]})}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ue,{children:"Alert Active"}),e.jsx(Or,{checked:_.is_active??!0,onCheckedChange:Z=>b(J=>({...J,is_active:Z}))})]}),e.jsxs("div",{children:[e.jsxs(ue,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(oc,{className:"h-3.5 w-3.5"})," Price Range"]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(Se,{type:"number",placeholder:"Min price",value:_.min_price??"",onChange:Z=>b(J=>({...J,min_price:Z.target.value?Number(Z.target.value):null}))}),e.jsx(Se,{type:"number",placeholder:"Max price",value:_.max_price??"",onChange:Z=>b(J=>({...J,max_price:Z.target.value?Number(Z.target.value):null}))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs(ue,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(B2,{className:"h-3.5 w-3.5"})," Min Beds"]}),e.jsxs(Bs,{value:_.min_beds?String(_.min_beds):"any",onValueChange:Z=>b(J=>({...J,min_beds:Z==="any"?null:Number(Z)})),children:[e.jsx(Os,{children:e.jsx(Us,{placeholder:"Any"})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"any",children:"Any"}),[1,2,3,4,5].map(Z=>e.jsxs(pt,{value:String(Z),children:[Z,"+"]},Z))]})]})]}),e.jsxs("div",{children:[e.jsxs(ue,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(_p,{className:"h-3.5 w-3.5"})," Min Baths"]}),e.jsxs(Bs,{value:_.min_baths?String(_.min_baths):"any",onValueChange:Z=>b(J=>({...J,min_baths:Z==="any"?null:Number(Z)})),children:[e.jsx(Os,{children:e.jsx(Us,{placeholder:"Any"})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"any",children:"Any"}),[1,1.5,2,2.5,3,4].map(Z=>e.jsxs(pt,{value:String(Z),children:[Z,"+"]},Z))]})]})]})]}),e.jsxs("div",{children:[e.jsxs(ue,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(LE,{className:"h-3.5 w-3.5"})," Square Feet"]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(Se,{type:"number",placeholder:"Min sqft",value:_.min_sqft??"",onChange:Z=>b(J=>({...J,min_sqft:Z.target.value?Number(Z.target.value):null}))}),e.jsx(Se,{type:"number",placeholder:"Max sqft",value:_.max_sqft??"",onChange:Z=>b(J=>({...J,max_sqft:Z.target.value?Number(Z.target.value):null}))})]})]}),e.jsxs("div",{children:[e.jsxs(ue,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(Qa,{className:"h-3.5 w-3.5"})," Cities"]}),e.jsx(HHe,{value:c,onChange:d,onAdd:E,suggestions:R,placeholder:"Type to search cities..."}),_.cities&&_.cities.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1 mt-2",children:_.cities.map(Z=>e.jsxs(Xe,{variant:"secondary",className:"gap-1",children:[Z,e.jsx("button",{onClick:()=>b(J=>{var K;return{...J,cities:(K=J.cities)==null?void 0:K.filter(re=>re!==Z)}}),children:e.jsx(Rr,{className:"h-3 w-3"})})]},Z))})]}),e.jsxs("div",{children:[e.jsx(ue,{className:"mb-1.5",children:"Zip Codes"}),e.jsx(HHe,{value:h,onChange:m,onAdd:A,suggestions:z,placeholder:"Type to search zip codes...",icon:e.jsx("span",{className:"text-xs text-muted-foreground font-mono",children:"#"})}),_.zip_codes&&_.zip_codes.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1 mt-2",children:_.zip_codes.map(Z=>e.jsxs(Xe,{variant:"secondary",className:"gap-1",children:[Z,e.jsx("button",{onClick:()=>b(J=>{var K;return{...J,zip_codes:(K=J.zip_codes)==null?void 0:K.filter(re=>re!==Z)}}),children:e.jsx(Rr,{className:"h-3 w-3"})})]},Z))})]}),e.jsxs("div",{children:[e.jsxs(ue,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(Fn,{className:"h-3.5 w-3.5"})," Property Types"]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:sDs.map(Z=>{var J;return e.jsx(Xe,{variant:(J=_.property_types)!=null&&J.includes(Z)?"default":"outline",className:"cursor-pointer",onClick:()=>D(Z),children:Z},Z)})})]}),e.jsxs("div",{children:[e.jsx(ue,{className:"mb-1.5",children:"Frequency"}),e.jsxs(Bs,{value:_.frequency||"daily",onValueChange:Z=>b(J=>({...J,frequency:Z})),children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"daily",children:"Daily"}),e.jsx(pt,{value:"weekly",children:"Weekly"})]})]})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsxs(H,{onClick:()=>k.mutate(),disabled:k.isPending,className:"flex-1",children:[k.isPending?e.jsx(is,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(vc,{className:"h-4 w-4 mr-1"}),"Save Alert"]}),e.jsx(H,{variant:"outline",onClick:()=>o(!1),children:"Cancel"}),x&&e.jsx(H,{variant:"destructive",size:"icon",onClick:()=>T.mutate(),disabled:T.isPending,children:e.jsx(Rr,{className:"h-4 w-4"})})]})]})]}):e.jsx(ke,{className:"overflow-hidden",children:e.jsx(Oe,{className:"p-4",children:e.jsxs("button",{onClick:j,className:"w-full flex items-center gap-3 p-3 rounded-lg border border-dashed border-primary/30 hover:bg-primary/5 transition-colors",children:[e.jsx("div",{className:"h-9 w-9 rounded-lg bg-primary/10 flex items-center justify-center flex-shrink-0",children:e.jsx(wp,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"font-medium text-sm",children:"Set Up Property Alerts"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Automatically email ",t," new listings matching their criteria"]})]})]})})})}function nDs({contactId:s,contactName:t}){var ie;const{user:r}=Ms(),n=ba(),{hasLeadSite:a}=av(),i=ns(),[l,o]=S.useState(!1),[c,d]=S.useState(""),[h,m]=S.useState([]),[p,x]=S.useState(!1),[y,_]=S.useState(!1),[b,j]=S.useState(!1),[k,T]=S.useState(""),E=S.useRef(null),A=S.useRef(null),{data:D}=yt({queryKey:["agent-lead-site-cities",n],queryFn:async()=>{const{data:ce,error:ne}=await V.from("lead_sites").select("theme_config, mls_market_area").eq("agent_id",n).eq("is_active",!0).order("created_at",{ascending:!0}).limit(1).maybeSingle();if(ne||!ce)return[];const le=ce.theme_config||{},be=Array.isArray(le.searchCities)?le.searchCities:[];return ce.mls_market_area&&!be.includes(ce.mls_market_area)&&be.unshift(ce.mls_market_area),be},enabled:!!n}),{data:R,isLoading:z}=yt({queryKey:["contact-market-report",s],queryFn:async()=>{const{data:ce,error:ne}=await V.from("innercircle_contacts").select("market_report_enabled, market_report_cities").eq("id",s).single();if(ne)throw ne;return ce},enabled:!!s&&!!r});S.useEffect(()=>{const ce=ne=>{A.current&&!A.current.contains(ne.target)&&E.current&&!E.current.contains(ne.target)&&_(!1)};return document.addEventListener("mousedown",ce),()=>document.removeEventListener("mousedown",ce)},[]);const O=()=>{x((R==null?void 0:R.market_report_enabled)??!1),m((R==null?void 0:R.market_report_cities)??[]),o(!0)},$=ce=>{const ne=(ce||c).trim();ne&&!h.includes(ne)&&m([...h,ne]),d(""),_(!1)},ee=(D||[]).filter(ce=>!h.includes(ce)&&ce.toLowerCase().includes(c.toLowerCase())),Z=Pt({mutationFn:async()=>{const{data:ce,error:ne}=await V.functions.invoke("send-market-report",{body:{action:"preview",agentId:n,cities:(R==null?void 0:R.market_report_cities)??[]}});if(ne)throw new Error(ne.message||"Failed to generate preview");if(ce&&!ce.ok&&ce.error)throw new Error(ce.error);return ce},onSuccess:ce=>{T(ce.html),j(!0)},onError:ce=>{he.error(ce.message||"Failed to generate preview")}}),J=Pt({mutationFn:async()=>{const{data:ce,error:ne}=await V.functions.invoke("send-market-report",{body:{action:"send",agentId:n,cities:(R==null?void 0:R.market_report_cities)??[],contactIds:[s]}});if(ne)throw new Error(ne.message||"Failed to send report");if(ce&&!ce.ok&&ce.error)throw new Error(ce.error);return ce},onSuccess:()=>{he.success(`Market report sent to ${t}!`)},onError:ce=>{he.error(ce.message||"Failed to send report")}}),K=Pt({mutationFn:async()=>{const{error:ce}=await V.from("innercircle_contacts").update({market_report_enabled:p,market_report_cities:h}).eq("id",s);if(ce)throw ce},onSuccess:()=>{i.invalidateQueries({queryKey:["contact-market-report",s]}),o(!1),he.success(p?"Monthly market report enabled!":"Market report disabled")},onError:ce=>{he.error(ce.message||"Failed to save")}}),re=Pt({mutationFn:async()=>{const{error:ce}=await V.from("innercircle_contacts").update({market_report_enabled:!1,market_report_cities:[]}).eq("id",s);if(ce)throw ce},onSuccess:()=>{i.invalidateQueries({queryKey:["contact-market-report",s]}),o(!1),x(!1),m([]),he.success("Market report removed")},onError:ce=>{he.error(ce.message||"Failed to remove market report")}});return!a||z?null:R!=null&&R.market_report_enabled&&!l?e.jsxs(ke,{className:"overflow-hidden",children:[e.jsx(Ot,{className:"pb-2",children:e.jsxs(zt,{className:"text-base flex items-center gap-2",children:[e.jsx("div",{className:"h-7 w-7 rounded-lg flex items-center justify-center bg-primary/10",children:e.jsx(Bo,{className:"h-4 w-4 text-primary"})}),"Monthly Market Report",e.jsx(Xe,{variant:"default",className:"text-xs ml-auto",children:"Active"})]})}),e.jsxs(Oe,{className:"pt-0 space-y-2",children:[e.jsx("div",{className:"flex flex-wrap gap-1.5 text-xs",children:((ie=R.market_report_cities)==null?void 0:ie.length)>0?R.market_report_cities.map(ce=>e.jsxs(Xe,{variant:"outline",className:"gap-1",children:[e.jsx(Qa,{className:"h-3 w-3"}),ce]},ce)):e.jsx("span",{className:"text-muted-foreground",children:"Using default market area"})}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[t," receives a branded market report on the 1st of each month."]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(H,{variant:"outline",size:"sm",onClick:()=>Z.mutate(),disabled:Z.isPending,className:"flex-1",children:[Z.isPending?e.jsx(is,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Bn,{className:"h-4 w-4 mr-1"}),"Preview"]}),e.jsxs(H,{variant:"default",size:"sm",onClick:()=>J.mutate(),disabled:J.isPending,className:"flex-1",children:[J.isPending?e.jsx(is,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(yn,{className:"h-4 w-4 mr-1"}),"Send Now"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(H,{variant:"outline",size:"sm",onClick:O,className:"flex-1",children:"Manage"}),e.jsxs(H,{variant:"destructive",size:"sm",onClick:()=>re.mutate(),disabled:re.isPending,className:"flex-1",children:[re.isPending?e.jsx(is,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Rr,{className:"h-4 w-4 mr-1"}),"Remove"]})]}),e.jsx(bs,{open:b,onOpenChange:j,children:e.jsxs(vs,{className:"max-w-3xl max-h-[85vh] overflow-hidden flex flex-col",children:[e.jsx(Cs,{children:e.jsxs(Ns,{className:"flex items-center gap-2",children:[e.jsx(Bo,{className:"h-5 w-5 text-primary"}),"Market Report Preview"]})}),e.jsx("div",{className:"flex-1 overflow-y-auto -mx-6 px-6",children:e.jsx("div",{className:"border rounded-lg overflow-hidden",dangerouslySetInnerHTML:{__html:k}})}),e.jsxs("div",{className:"flex gap-2 pt-4 border-t",children:[e.jsxs(H,{onClick:()=>{j(!1),J.mutate()},disabled:J.isPending,className:"flex-1",children:[J.isPending?e.jsx(is,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(yn,{className:"h-4 w-4 mr-1"}),"Send to ",t]}),e.jsx(H,{variant:"outline",onClick:()=>j(!1),children:"Close"})]})]})})]})]}):l?e.jsxs(ke,{children:[e.jsx(Ot,{className:"pb-3",children:e.jsxs(zt,{className:"text-base flex items-center gap-2",children:[e.jsx(Bo,{className:"h-4 w-4 text-primary"}),"Market Report for ",t]})}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ue,{children:"Send Monthly Report"}),e.jsx(Or,{checked:p,onCheckedChange:x})]}),p&&e.jsxs("div",{children:[e.jsxs(ue,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(Qa,{className:"h-3.5 w-3.5"})," Report Cities"]}),e.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Select cities from your website's configured areas."}),e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Se,{ref:E,value:c,onChange:ce=>{d(ce.target.value),_(!0)},onFocus:()=>_(!0),placeholder:"Type to search cities...",onKeyDown:ce=>{ce.key==="Enter"&&(ce.preventDefault(),ee.length>0?$(ee[0]):$())}}),e.jsx(Io,{className:"absolute right-3 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground pointer-events-none"})]}),e.jsx(H,{type:"button",variant:"outline",size:"sm",onClick:()=>$(),children:e.jsx(Ys,{className:"h-4 w-4"})})]}),y&&ee.length>0&&e.jsx("div",{ref:A,className:"absolute z-50 mt-1 w-full max-h-60 overflow-y-auto rounded-md border bg-popover shadow-md",children:ee.map(ce=>e.jsxs("button",{type:"button",className:"w-full text-left px-3 py-2 text-sm hover:bg-accent hover:text-accent-foreground transition-colors flex items-center gap-2",onClick:()=>$(ce),children:[e.jsx(Qa,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"}),ce]},ce))})]}),h.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1 mt-2",children:h.map(ce=>e.jsxs(Xe,{variant:"secondary",className:"gap-1",children:[ce,e.jsx("button",{onClick:()=>m(h.filter(ne=>ne!==ce)),children:e.jsx(Rr,{className:"h-3 w-3"})})]},ce))})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsxs(H,{onClick:()=>K.mutate(),disabled:K.isPending,className:"flex-1",children:[K.isPending?e.jsx(is,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(vc,{className:"h-4 w-4 mr-1"}),"Save"]}),e.jsx(H,{variant:"outline",onClick:()=>o(!1),children:"Cancel"})]})]})]}):e.jsx(ke,{className:"overflow-hidden",children:e.jsx(Oe,{className:"p-4",children:e.jsxs("button",{onClick:O,className:"w-full flex items-center gap-3 p-3 rounded-lg border border-dashed border-primary/30 hover:bg-primary/5 transition-colors",children:[e.jsx("div",{className:"h-9 w-9 rounded-lg bg-primary/10 flex items-center justify-center flex-shrink-0",children:e.jsx(Bo,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"font-medium text-sm",children:"Enable Monthly Market Report"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Auto-send ",t," a branded market report with real MLS data every month"]})]})]})})})}function aDs(s){return yt({queryKey:["contact-drip-activity",s],queryFn:async()=>{if(!s)return{enrollments:[],stepLogs:[]};const{data:t,error:r}=await V.from("drip_campaign_enrollments").select("id, campaign_id, current_step, status, next_send_at, enrolled_at, completed_at, exited_at, exit_reason").eq("contact_id",s).order("enrolled_at",{ascending:!1});if(r)throw console.error("[ContactDripActivity] enrollments error",r),r;const n=(t||[]).map(c=>c.id),a=Array.from(new Set((t||[]).map(c=>c.campaign_id)));let i=new Map;if(a.length>0){const{data:c}=await V.from("drip_campaigns").select("id, name, description, is_active").in("id",a);(c||[]).forEach(d=>i.set(d.id,d))}const l=(t||[]).map(c=>({...c,campaign:i.get(c.campaign_id)||null}));let o=[];if(n.length>0){const{data:c,error:d}=await V.from("drip_campaign_step_log").select("id, enrollment_id, campaign_id, step_order, channel, recipient_email, subject, status, error_message, sent_at").in("enrollment_id",n).order("sent_at",{ascending:!1});d?console.error("[ContactDripActivity] step log error",d):o=(c||[]).map(h=>{var m;return{...h,campaign:{name:((m=i.get(h.campaign_id))==null?void 0:m.name)??""}}})}return{enrollments:l,stepLogs:o}},enabled:!!s})}function iDs(s){switch(s){case"active":return e.jsx(Xe,{variant:"secondary",className:"bg-emerald-500/10 text-emerald-600 border-emerald-500/20",children:"Active"});case"paused":return e.jsx(Xe,{variant:"secondary",className:"bg-amber-500/10 text-amber-600 border-amber-500/20",children:"Paused"});case"completed":return e.jsx(Xe,{variant:"secondary",className:"bg-sky-500/10 text-sky-600 border-sky-500/20",children:"Completed"});case"exited":return e.jsx(Xe,{variant:"outline",children:"Exited"});default:return e.jsx(Xe,{variant:"outline",children:s})}}function GHe(s){return s==="sent"?e.jsx(ea,{className:"h-4 w-4 text-emerald-500"}):s==="failed"?e.jsx(uu,{className:"h-4 w-4 text-destructive"}):s==="skipped"?e.jsx(Hf,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(Pn,{className:"h-4 w-4 text-muted-foreground"})}function oDs({contactId:s}){const t=Fr(),{data:r,isLoading:n}=aDs(s),[a,i]=S.useState(null);if(n)return null;const l=(r==null?void 0:r.enrollments)||[],o=(r==null?void 0:r.stepLogs)||[];return l.length===0&&o.length===0?null:e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsxs(zt,{className:"flex items-center gap-2 text-base",children:[e.jsx(FE,{className:"h-5 w-5 text-emerald-500"}),"Drip Campaign Activity"]})}),e.jsxs(Oe,{className:"space-y-4",children:[l.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Enrollments"}),l.map(c=>{var d;return e.jsxs("button",{onClick:()=>t("/mission-control/smart-drips"),className:"w-full text-left flex items-start gap-3 p-3 rounded-lg border hover:bg-muted/50 transition-colors",children:[e.jsx("div",{className:"h-8 w-8 rounded-full bg-emerald-500/10 flex items-center justify-center text-emerald-600 flex-shrink-0",children:e.jsx(FE,{className:"h-4 w-4"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:((d=c.campaign)==null?void 0:d.name)||"Untitled campaign"}),iDs(c.status)]}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:["Step ",c.current_step+1,c.next_send_at&&c.status==="active"&&e.jsxs(e.Fragment,{children:[" · Next: ",Hl(new Date(c.next_send_at),{addSuffix:!0})]}),c.completed_at&&e.jsxs(e.Fragment,{children:[" · Completed ",Hl(new Date(c.completed_at),{addSuffix:!0})]}),c.exited_at&&!c.completed_at&&e.jsxs(e.Fragment,{children:[" · ",c.exit_reason||"Exited"," ",Hl(new Date(c.exited_at),{addSuffix:!0})]})]})]}),e.jsx($a,{className:"h-4 w-4 text-muted-foreground mt-1 flex-shrink-0"})]},c.id)})]}),o.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:["Send History (",o.length,")"]}),e.jsxs("div",{className:"space-y-1",children:[o.slice(0,8).map(c=>{var d,h;return e.jsxs(bs,{open:(a==null?void 0:a.id)===c.id,onOpenChange:m=>!m&&i(null),children:[e.jsx(Qi,{asChild:!0,children:e.jsxs("button",{onClick:()=>i(c),className:"w-full text-left flex items-start gap-3 p-2.5 rounded-lg border hover:bg-muted/50 transition-colors",children:[e.jsx("div",{className:"mt-0.5 flex-shrink-0",children:GHe(c.status)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[c.channel==="sms"?e.jsx(Gi,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"}):e.jsx(er,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"}),e.jsx("p",{className:"text-sm truncate",children:c.subject||`${c.channel.toUpperCase()} step ${c.step_order+1}`})]}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5 truncate",children:[((d=c.campaign)==null?void 0:d.name)||"Campaign"," · ",As(new Date(c.sent_at),"MMM d, h:mm a")]}),c.status==="failed"&&c.error_message&&e.jsx("p",{className:"text-xs text-destructive mt-0.5 truncate",children:c.error_message})]})]})}),e.jsxs(vs,{className:"max-w-lg",children:[e.jsx(Cs,{children:e.jsxs(Ns,{className:"flex items-center gap-2",children:[GHe(c.status),c.subject||"Drip step"]})}),e.jsxs("div",{className:"space-y-2 text-sm",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Campaign"}),e.jsx("span",{className:"font-medium",children:((h=c.campaign)==null?void 0:h.name)||"—"})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Channel"}),e.jsx("span",{className:"font-medium uppercase",children:c.channel})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Step"}),e.jsxs("span",{className:"font-medium",children:["#",c.step_order+1]})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Recipient"}),e.jsx("span",{className:"font-medium",children:c.recipient_email||"—"})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Status"}),e.jsx("span",{className:"font-medium capitalize",children:c.status})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Sent"}),e.jsx("span",{className:"font-medium",children:As(new Date(c.sent_at),"MMM d, yyyy h:mm a")})]}),c.error_message&&e.jsx("div",{className:"rounded-md border border-destructive/30 bg-destructive/5 p-2 text-destructive text-xs",children:c.error_message})]})]})]},c.id)}),o.length>8&&e.jsx(H,{variant:"ghost",size:"sm",className:"w-full text-xs",onClick:()=>t("/mission-control/smart-drips"),children:"View all in Smart Drips"})]})]})]})]})}function sxt({contactId:s}={}){const{user:t}=Ms();return yt({queryKey:["sent-emails",t==null?void 0:t.id,s??"all"],enabled:!!t,queryFn:async()=>{const r=t.id;let n=V.from("gmail_sent_emails").select("id, contact_id, to_email, subject, sent_at, source").eq("user_id",r).or("source.is.null,source.neq.drip_campaign").order("sent_at",{ascending:!1}).limit(1e3);s&&(n=n.eq("contact_id",s));let a=V.from("bulk_email_sends").select("id, contact_id, contact_email, subject, sent_at, source").eq("user_id",r).order("sent_at",{ascending:!1}).limit(1e3);s&&(a=a.eq("contact_id",s));const i=await V.from("email_campaigns").select("id, subject").eq("user_id",r),l=(i.data||[]).map(_=>_.id),o=new Map((i.data||[]).map(_=>[_.id,_.subject]));let c=[];if(l.length>0){let _=V.from("email_campaign_recipients").select("id, contact_id, email, sent_at, campaign_id, opened_at, clicked_at").in("campaign_id",l).eq("status","sent").not("sent_at","is",null).order("sent_at",{ascending:!1}).limit(1e3);s&&(_=_.eq("contact_id",s)),c=(await _).data||[]}const[d,h]=await Promise.all([n,a]),m=(d.data||[]).map(_=>({id:`g-${_.id}`,channel:_.source==="portal_invite"?"Client Portal Invite":"Gmail",subject:_.subject,to_email:_.to_email,contact_id:_.contact_id,sent_at:_.sent_at,source:_.source})),p=(h.data||[]).map(_=>({id:`b-${_.id}`,channel:"Mass Email",subject:_.subject,to_email:_.contact_email,contact_id:_.contact_id,sent_at:_.sent_at,source:_.source})),x=c.map(_=>({id:`c-${_.id}`,channel:"Campaign",subject:o.get(_.campaign_id)||"(campaign)",to_email:_.email,contact_id:_.contact_id,sent_at:_.sent_at,source:null,campaign_id:_.campaign_id,opened_at:_.opened_at,clicked_at:_.clicked_at})),y=[...m,...p,...x];return y.sort((_,b)=>_.sent_at0&&e.jsx(Xe,{variant:"secondary",className:"ml-1",children:t.length})]})}),e.jsx(Oe,{children:r?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading..."}):t.length===0?e.jsxs("div",{className:"text-center py-6 text-sm text-muted-foreground",children:[e.jsx(er,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),"No emails sent to this contact yet."]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"space-y-2",children:i.map(l=>e.jsx("div",{className:"flex items-start justify-between gap-3 p-3 rounded-lg border hover:bg-muted/30",children:e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(Xe,{variant:"outline",className:`text-xs ${lDs[l.channel]}`,children:l.channel}),e.jsx("span",{className:"text-xs text-muted-foreground",children:As(new Date(l.sent_at),"MMM d, yyyy h:mm a")})]}),e.jsx("p",{className:"text-sm font-medium truncate",children:l.subject}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:["to ",l.to_email]})]})},l.id))}),t.length>5&&e.jsx(H,{variant:"ghost",size:"sm",className:"w-full mt-3",onClick:()=>a(!n),children:n?"Show less":`Show all ${t.length}`}),e.jsx("div",{className:"mt-3 pt-3 border-t",children:e.jsx(Xn,{to:"/mission-control/sent-emails",className:"text-xs text-primary hover:underline",children:"View all sent emails →"})})]})})]})}function dDs({videoId:s}){var l;const{data:t,isLoading:r,error:n}=k8s(s);if(r)return e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ks,{className:"w-full aspect-video rounded-lg"}),e.jsx(Ks,{className:"h-4 w-1/3"})]});if(n||!t||t.is_deleted)return e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx(uu,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"font-medium",children:"Video Unavailable"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"This video has been deleted or is no longer available."})]});const a=o=>{let c=o;return c.includes("iframe.mediadelivery.net/play/")&&(c=c.replace("/play/","/embed/"),c+=(c.includes("?")?"&":"?")+"autoplay=true&responsive=true"),c},i=(l=t.playback_url)==null?void 0:l.includes("iframe.mediadelivery.net");return e.jsxs("div",{className:"space-y-4",children:[t.playback_url?e.jsx("div",{className:"relative w-full aspect-video bg-black rounded-lg overflow-hidden",children:i?e.jsx("iframe",{src:a(t.playback_url),title:t.title||"Video preview",className:"absolute top-0 left-0 w-full h-full",style:{border:0},allow:"accelerometer; gyroscope; autoplay; encrypted-media; picture-in-picture",allowFullScreen:!0}):e.jsx("video",{src:t.playback_url,controls:!0,autoPlay:!0,className:"absolute top-0 left-0 w-full h-full object-contain"})}):e.jsx("div",{className:"w-full aspect-video bg-muted rounded-lg flex items-center justify-center",children:e.jsx("p",{className:"text-muted-foreground",children:"Video is still processing..."})}),t.title&&e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium",children:t.title}),t.notes&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:t.notes})]})]})}function uDs({contactId:s}){const t=Fr(),[r,n]=S.useState(!1),{data:a,isLoading:i}=yt({queryKey:["deal-tasks","contact",s],queryFn:async()=>{const{data:m,error:p}=await V.from("deal_tasks").select(` id, title, priority, status, due_date, completed_at, deal:deal_pipeline(id, deal_name) `).eq("contact_id",s).order("status").order("due_date",{ascending:!0,nullsFirst:!1});if(p)throw p;return m},enabled:!!s}),l=async(m,p)=>{const x=p==="done"?"todo":"done";await V.from("deal_tasks").update({status:x,completed_at:x==="done"?new Date().toISOString():null}).eq("id",m),window.dispatchEvent(new CustomEvent("refetch-contact-tasks"))},{refetch:o}=yt({queryKey:["deal-tasks","contact",s],queryFn:async()=>{const{data:m,error:p}=await V.from("deal_tasks").select(` id, title, priority, status, due_date, completed_at, deal:deal_pipeline(id, deal_name) `).eq("contact_id",s).order("status").order("due_date",{ascending:!0,nullsFirst:!1});if(p)throw p;return m},enabled:!!s}),c={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"},d=(a==null?void 0:a.filter(m=>m.status!=="done"))||[],h=(a==null?void 0:a.filter(m=>m.status==="done"))||[];return e.jsxs(ke,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(zt,{className:"text-base flex items-center gap-2",children:[e.jsx(va,{className:"h-4 w-4"}),"Tasks",d.length>0&&e.jsx(Xe,{variant:"secondary",className:"text-xs",children:d.length})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(H,{variant:"ghost",size:"sm",onClick:()=>t("/mission-control/tasks"),children:"View All"}),e.jsx(H,{variant:"outline",size:"sm",onClick:()=>n(!0),children:e.jsx(Ys,{className:"h-3.5 w-3.5"})})]})]})}),e.jsx(Oe,{className:"space-y-1",children:i?e.jsx(Ks,{className:"h-8 w-full"}):d.length===0&&h.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No tasks yet"}):e.jsxs(e.Fragment,{children:[d.map(m=>e.jsxs("button",{onClick:async()=>{await l(m.id,m.status),o()},className:"w-full text-left flex items-center gap-2 px-2 py-1.5 rounded hover:bg-muted/50 transition-colors group",children:[e.jsx("div",{className:"h-4 w-4 rounded-full border-2 border-muted-foreground/30 shrink-0 group-hover:border-primary"}),e.jsxs("span",{className:"text-sm flex-1 truncate",children:[c[m.priority]," ",m.title]}),m.due_date&&e.jsx("span",{className:"text-[10px] text-muted-foreground",children:As(new Date(m.due_date),"MMM d")})]},m.id)),h.length>0&&e.jsx("div",{className:"pt-1 border-t mt-1",children:e.jsxs("p",{className:"text-[10px] text-muted-foreground px-2 py-1",children:[h.length," completed"]})})]})}),r&&e.jsx(hDs,{contactId:s,open:r,onOpenChange:m=>{n(m),m||o()}})]})}function hDs({contactId:s,open:t,onOpenChange:r}){const[n,a]=S.useState(""),[i,l]=S.useState("medium"),[o,c]=S.useState(),{data:d}=yt({queryKey:["session"],queryFn:async()=>{const{data:m}=await V.auth.getSession();return m.session}}),h=async()=>{var p;if(!n.trim()||!((p=d==null?void 0:d.user)!=null&&p.id))return;const{error:m}=await V.from("deal_tasks").insert([{owner_user_id:d.user.id,contact_id:s,title:n.trim(),priority:i,status:"todo",due_date:o?As(o,"yyyy-MM-dd"):null}]);if(m){console.error("Task create error:",m);return}r(!1)};return e.jsx(bs,{open:t,onOpenChange:r,children:e.jsxs(vs,{className:"sm:max-w-[400px]",children:[e.jsx(Cs,{children:e.jsx(Ns,{children:"Add Task"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ue,{children:"Title"}),e.jsx(Se,{value:n,onChange:m=>a(m.target.value),placeholder:"Task title...",onKeyDown:m=>m.key==="Enter"&&h()})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ue,{children:"Priority"}),e.jsxs("select",{value:i,onChange:m=>l(m.target.value),className:"w-full h-10 rounded-md border border-input bg-background px-3 text-sm",children:[e.jsx("option",{value:"low",children:"🟢 Low"}),e.jsx("option",{value:"medium",children:"🟡 Medium"}),e.jsx("option",{value:"high",children:"🟠 High"}),e.jsx("option",{value:"urgent",children:"🔴 Urgent"})]})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Due Date"}),e.jsx(Se,{type:"date",value:o?As(o,"yyyy-MM-dd"):"",onChange:m=>c(m.target.value?new Date(m.target.value+"T00:00:00"):void 0)})]})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(H,{variant:"outline",onClick:()=>r(!1),children:"Cancel"}),e.jsx(H,{onClick:h,disabled:!n.trim(),children:"Create Task"})]})]})]})})}function mDs({contactId:s}){const t=Fr(),{data:r,isLoading:n}=yt({queryKey:["contact-linked-deals",s],queryFn:async()=>{const{data:a,error:i}=await V.from("deal_pipeline").select(` id, deal_name, deal_type, expected_price, property_address, stage:deal_pipeline_stages(id, name, color, icon, is_won_stage, is_lost_stage) `).eq("contact_id",s).order("updated_at",{ascending:!1});if(i)throw i;return a},enabled:!!s});return n||!r||r.length===0?null:e.jsxs(ke,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsxs(zt,{className:"text-base flex items-center gap-2",children:[e.jsx(pm,{className:"h-4 w-4"}),"Linked Deals"]})}),e.jsx(Oe,{className:"space-y-2",children:r.map(a=>{const i=a.stage;return e.jsx("button",{onClick:()=>t(`/mission-control/pipeline?deal=${a.id}`),className:"w-full text-left p-3 rounded-lg border hover:bg-accent transition-colors group",children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:a.deal_name}),a.property_address&&e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:a.property_address}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(Xe,{variant:"outline",className:"text-[10px] capitalize",children:a.deal_type}),i&&e.jsxs(Xe,{variant:"outline",className:"text-[10px] gap-1",style:{borderColor:i.color,color:i.color,backgroundColor:`${i.color}10`},children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full inline-block",style:{backgroundColor:i.color}}),i.name]})]})]}),e.jsx(bi,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors flex-shrink-0"})]})},a.id)})})]})}function fDs(){var Je,st,mt,wt,at;const{contactId:s}=Po(),t=Fr(),[r]=Ed(),n=r.get("search")||"",a=r.get("type")||"all",i=r.get("status")||"all",{data:l,isLoading:o}=KVt(s||""),{data:c}=R0(),{data:d}=oz(),{data:h}=lz(3650),{data:m}=D0e(365),{data:p}=W8s(s),{contactsWithScores:x}=sxe(),y=yTe(),_=vTe(),b=Jge(),j=hot(),[k,T]=S.useState(!1),[E,A]=S.useState({}),[D,R]=S.useState(!1),[z,O]=S.useState(null),[$,ee]=S.useState(""),[Z,J]=S.useState(void 0),[K,re]=S.useState(""),[ie,ce]=S.useState(null),[ne,le]=S.useState(!1),[be,fe]=S.useState(null),[je,ve]=S.useState(!1),{isGmailConnected:We,gmailEmail:Ve}=cf(),{data:Le}=yt({queryKey:["gmail-sent-emails",s],queryFn:async()=>{const{data:rt,error:Et}=await V.from("gmail_sent_emails").select("*").eq("contact_id",s).order("sent_at",{ascending:!1});if(Et)throw Et;return rt},enabled:!!s}),Me=rt=>{if(!rt)return null;const Et=rt.match(/Video ID:\s*([a-f0-9-]+)/i);return Et?Et[1]:null},ze=S.useMemo(()=>{if(!x)return[];let rt=x.filter(Et=>{var lr,us,St;const hs=n===""||`${Et.first_name} ${Et.last_name}`.toLowerCase().includes(n.toLowerCase())||((lr=Et.email)==null?void 0:lr.toLowerCase().includes(n.toLowerCase()))||((us=Et.phone)==null?void 0:us.includes(n)),Is=a==="all"||((St=Et.tags)==null?void 0:St.some(xs=>xs.relationship_type_id===a));return hs&&Is});return i==="not-touched-90"?rt=rt.filter(Et=>{const hs=Et.relationshipScore.daysSinceTouch;return hs===null||hs>90}):i==="at-risk"?rt=rt.filter(Et=>Et.relationshipScore.status==="at-risk"):i==="cooling"?rt=rt.filter(Et=>Et.relationshipScore.status==="cooling"):i==="warm"&&(rt=rt.filter(Et=>Et.relationshipScore.status==="warm")),rt.map(Et=>Et.id)},[x,n,a,i]),Pe=ze.indexOf(s||""),Ie=Pe>0?ze[Pe-1]:null,De=Pe1&&Pe!==-1,tt=rt=>{const Et=new URLSearchParams;n&&Et.set("search",n),a!=="all"&&Et.set("type",a),i!=="all"&&Et.set("status",i);const hs=Et.toString();return`/mission-control/contacts/${rt}${hs?`?${hs}`:""}`},ge=S.useMemo(()=>{const rt=((h==null?void 0:h.filter(hs=>hs.contact_id===s))||[]).map(hs=>{var St,xs,kt;const Is=Me(hs.notes);let lr=((St=hs.action_type)==null?void 0:St.name)||"Touch",us=hs.notes;if(lr==="Other"&&((xs=hs.notes)!=null&&xs.startsWith("["))){const fs=hs.notes.indexOf("]");fs>0&&(lr=hs.notes.substring(1,fs),us=hs.notes.substring(fs+1).replace(/^\s*—\s*/,"").trim()||null)}return{id:hs.id,type:"touch",completed_at:hs.completed_at,name:lr,color:((kt=hs.action_type)==null?void 0:kt.color)||"#3B82F6",notes:us,videoId:Is}}),Et=((m==null?void 0:m.filter(hs=>hs.contact_id===s))||[]).map(hs=>({id:hs.id,type:"popby",completed_at:hs.completed_at,name:"Pop-by",color:"#F97316",notes:hs.notes,videoId:null}));return[...rt,...Et].sort((hs,Is)=>new Date(Is.completed_at).getTime()-new Date(hs.completed_at).getTime())},[h,m,s]),ct=()=>{var rt;l&&(A({first_name:l.first_name||"",last_name:l.last_name||"",email:l.email||"",phone:l.phone||"",address:l.address||"",city:l.city||"",state:l.state||"",zip_code:l.zip_code||"",birthday:l.birthday||"",home_anniversary:l.home_anniversary||"",spouse_name:l.spouse_name||"",spouse_email:l.spouse_email||"",company_name:l.company_name||"",job_title:l.job_title||"",lead_source_id:l.lead_source_id||"",notes:l.notes||"",tagIds:((rt=l.tags)==null?void 0:rt.map(Et=>Et.relationship_type_id))||[]}),T(!0))},Ue=async()=>{await y.mutateAsync({id:s,...E,lead_source_id:E.lead_source_id||null}),T(!1)},et=async()=>{confirm("Are you sure you want to delete this contact?")&&(await _.mutateAsync(s),t("/mission-control/contacts"))},Ne=((Je=d==null?void 0:d.find(rt=>rt.id===z))==null?void 0:Je.name)==="Other",$e=async()=>{if(!z||Ne&&!K.trim())return;const rt=Z?new Date(Z.getFullYear(),Z.getMonth(),Z.getDate(),12,0,0).toISOString():void 0,Et=Ne?`[${K.trim()}]${$?" — "+$:""}`:$;await b.mutateAsync({contactId:s,actionTypeId:z,notes:Et,completedAt:rt}),R(!1),O(null),ee(""),J(void 0),re("")},it=(rt,Et)=>{We&&l?(fe({email:rt,name:Et||`${l.first_name} ${l.last_name||""}`.trim()}),le(!0)):window.location.href=`mailto:${rt}`};return o?e.jsx(Ss,{title:"Contact Details",children:e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full"})})}):l?e.jsxs(e.Fragment,{children:[e.jsx(Ss,{title:`${l.first_name} ${l.last_name||""}`,description:"Contact details and activity",children:e.jsxs("div",{className:"space-y-6 overflow-x-hidden",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(H,{variant:"ghost",size:"sm",onClick:()=>{window.history.length>1?t(-1):t("/mission-control/contacts")},children:[e.jsx(fl,{className:"h-4 w-4 mr-1"}),"Back to Contacts"]}),pe&&e.jsxs("div",{className:"flex items-center gap-1 ml-2 border-l pl-2",children:[e.jsxs(H,{variant:"ghost",size:"sm",onClick:()=>Ie&&t(tt(Ie)),disabled:!Ie,className:"px-2",children:[e.jsx(fl,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only sm:not-sr-only sm:ml-1",children:"Prev"})]}),e.jsxs("span",{className:"text-xs text-muted-foreground whitespace-nowrap",children:[Pe+1," of ",ze.length]}),e.jsxs(H,{variant:"ghost",size:"sm",onClick:()=>De&&t(tt(De)),disabled:!De,className:"px-2",children:[e.jsx("span",{className:"sr-only sm:not-sr-only sm:mr-1",children:"Next"}),e.jsx($a,{className:"h-4 w-4"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 w-full sm:w-auto justify-end flex-wrap",children:[l.email&&e.jsxs(H,{variant:"outline",onClick:()=>it(l.email,`${l.first_name} ${l.last_name||""}`.trim()),children:[e.jsx(er,{className:"h-4 w-4 mr-1"}),"Email"]}),l.email&&e.jsxs(H,{variant:"outline",onClick:()=>ve(!0),className:"border-primary/40 text-primary hover:bg-primary/10",children:[e.jsx(Lr,{className:"h-4 w-4 mr-1"}),"Send Connect Page"]}),e.jsxs(H,{variant:"default",onClick:()=>t(`/mission-control/video/record?contact_id=${s}`),className:"bg-gradient-to-r from-primary to-primary/80",children:[e.jsx(xn,{className:"h-4 w-4 mr-1"}),"Quick Video Touch"]}),e.jsxs(bs,{open:D,onOpenChange:R,children:[e.jsx(Qi,{asChild:!0,children:e.jsxs(H,{variant:"outline",children:[e.jsx(Ys,{className:"h-4 w-4 mr-1"}),"Log Action"]})}),e.jsxs(vs,{className:"max-h-[85vh] overflow-y-auto",children:[e.jsx(Cs,{children:e.jsx(Ns,{children:"Log an Action"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ue,{children:"Action Type"}),e.jsx("div",{className:"grid grid-cols-2 gap-2 mt-2",children:d==null?void 0:d.filter(rt=>rt.active).map(rt=>e.jsxs("button",{onClick:()=>O(rt.id),className:` p-3 rounded-lg border text-left transition-all ${z===rt.id?"border-primary bg-primary/10":"hover:bg-accent"} `,children:[e.jsx("div",{className:"font-medium",children:rt.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:rt.description})]},rt.id))}),Ne&&e.jsxs("div",{className:"mt-3",children:[e.jsx(ue,{htmlFor:"custom-action-name",children:"What did you do?"}),e.jsx(Se,{id:"custom-action-name",value:K,onChange:rt=>re(rt.target.value),placeholder:"e.g. Met a client for lunch, Dropped off a gift...",className:"mt-1"})]})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Date (optional — backdate if needed)"}),e.jsxs(gl,{children:[e.jsx(xl,{asChild:!0,children:e.jsxs(H,{variant:"outline",className:Ft("w-full justify-start text-left font-normal mt-2",!Z&&"text-muted-foreground"),children:[e.jsx(Nn,{className:"h-4 w-4 mr-2"}),Z?As(Z,"PPP"):"Today (default)"]})}),e.jsx(il,{className:"w-auto p-0",align:"start",children:e.jsx(g0,{mode:"single",selected:Z,onSelect:J,disabled:rt=>rt>new Date,initialFocus:!0,className:Ft("p-3 pointer-events-auto")})})]})]}),e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"action-notes",children:"Notes (optional)"}),e.jsx(vr,{id:"action-notes",value:$,onChange:rt=>ee(rt.target.value),placeholder:"Add any notes about this interaction...",rows:3})]}),e.jsxs(H,{onClick:$e,disabled:!z||Ne&&!K.trim()||b.isPending,className:"w-full",children:[e.jsx(va,{className:"h-4 w-4 mr-1"}),"Complete Action"]})]})]})]}),e.jsxs(H,{variant:"outline",onClick:ct,children:[e.jsx(ou,{className:"h-4 w-4 mr-1"}),"Edit"]}),e.jsx(H,{variant:"destructive",size:"icon",onClick:et,children:e.jsx(Dr,{className:"h-4 w-4"})})]})]}),e.jsx("div",{className:"bg-card border rounded-lg p-4 sm:p-6",children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center gap-4",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs("h1",{className:"text-2xl sm:text-3xl font-bold",children:[l.first_name," ",l.last_name||""]}),(((st=l.lead_source_ref)==null?void 0:st.name)||l.lead_source)&&e.jsx(Xe,{variant:"outline",className:"text-xs border-primary/30 text-primary",children:((mt=l.lead_source_ref)==null?void 0:mt.name)||l.lead_source})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 mt-2 text-muted-foreground",children:[l.email&&e.jsxs("button",{onClick:()=>it(l.email),className:"flex items-center gap-1 hover:text-primary transition-colors",children:[e.jsx(er,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm",children:l.email})]}),l.phone&&e.jsxs("a",{href:`tel:${l.phone}`,className:"flex items-center gap-1 hover:text-primary transition-colors",children:[e.jsx(Yn,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm",children:l.phone})]})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(j4e,{contact:l}),(wt=l.tags)==null?void 0:wt.map(rt=>{const Et=c==null?void 0:c.find(hs=>hs.id===rt.relationship_type_id);return Et?e.jsx(Xe,{variant:"secondary",className:"text-xs",children:Et.name},rt.id):null})]}),e.jsx("div",{className:"mt-2",children:e.jsx($8s,{contactId:s})})]})}),e.jsxs("div",{className:"grid md:grid-cols-3 gap-6",children:[e.jsxs(ke,{className:"md:col-span-2",children:[e.jsx(Ot,{children:e.jsx(zt,{children:"Contact Information"})}),e.jsx(Oe,{children:k?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"first_name",children:"First Name"}),e.jsx(Se,{id:"first_name",value:E.first_name,onChange:rt=>A({...E,first_name:rt.target.value})})]}),e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"last_name",children:"Last Name"}),e.jsx(Se,{id:"last_name",value:E.last_name,onChange:rt=>A({...E,last_name:rt.target.value})})]})]}),e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"email",children:"Email"}),e.jsx(Se,{id:"email",type:"email",value:E.email,onChange:rt=>A({...E,email:rt.target.value})})]}),e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"phone",children:"Phone"}),e.jsx(Se,{id:"phone",value:E.phone,onChange:rt=>A({...E,phone:rt.target.value})})]}),e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"address",children:"Street Address"}),e.jsx(Se,{id:"address",value:E.address,onChange:rt=>A({...E,address:rt.target.value}),placeholder:"123 Main St"})]}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-4",children:[e.jsxs("div",{className:"col-span-2",children:[e.jsx(ue,{htmlFor:"city",children:"City"}),e.jsx(Se,{id:"city",value:E.city,onChange:rt=>A({...E,city:rt.target.value}),placeholder:"City"})]}),e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"state",children:"State"}),e.jsx(Se,{id:"state",value:E.state,onChange:rt=>A({...E,state:rt.target.value}),placeholder:"TX",maxLength:2})]}),e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"zip_code",children:"Zip Code"}),e.jsx(Se,{id:"zip_code",value:E.zip_code,onChange:rt=>A({...E,zip_code:rt.target.value}),placeholder:"12345"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"birthday",children:"Birthday"}),e.jsx(Se,{id:"birthday",type:"date",value:E.birthday,onChange:rt=>A({...E,birthday:rt.target.value})})]}),e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"home_anniversary",children:"Home Anniversary"}),e.jsx(Se,{id:"home_anniversary",type:"date",value:E.home_anniversary,onChange:rt=>A({...E,home_anniversary:rt.target.value})})]})]}),e.jsx(Qo,{}),e.jsx(N4e,{contactId:s,currentSpouseContactId:(l==null?void 0:l.spouse_contact_id)||null,currentSpouseName:(l==null?void 0:l.spouse_name)||null,currentSpouseEmail:(l==null?void 0:l.spouse_email)||null,onLink:rt=>j.mutate({contactId:s,spouseContactId:rt}),onUnlink:()=>j.mutate({contactId:s,spouseContactId:null}),isEditing:!0}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"company_name",children:"Company"}),e.jsx(Se,{id:"company_name",value:E.company_name,onChange:rt=>A({...E,company_name:rt.target.value}),placeholder:"Enter company name"})]}),e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"job_title",children:"Job Title"}),e.jsx(Se,{id:"job_title",value:E.job_title,onChange:rt=>A({...E,job_title:rt.target.value}),placeholder:"Enter job title"})]})]}),e.jsx(Xgt,{value:E.lead_source_id||"",onChange:rt=>A({...E,lead_source_id:rt})}),e.jsxs("div",{children:[e.jsx(ue,{children:"Relationship Types"}),e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:c==null?void 0:c.filter(rt=>rt.active).map(rt=>{var Et;return e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx(ao,{checked:(Et=E.tagIds)==null?void 0:Et.includes(rt.id),onCheckedChange:hs=>{var Is;A(hs?{...E,tagIds:[...E.tagIds||[],rt.id]}:{...E,tagIds:(Is=E.tagIds)==null?void 0:Is.filter(lr=>lr!==rt.id)})}}),e.jsx("span",{className:"text-sm",children:rt.name})]},rt.id)})})]}),e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"notes",children:"Notes"}),e.jsx(vr,{id:"notes",value:E.notes,onChange:rt=>A({...E,notes:rt.target.value}),rows:4})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(H,{onClick:Ue,disabled:y.isPending,children:"Save Changes"}),e.jsx(H,{variant:"outline",onClick:()=>T(!1),children:"Cancel"})]})]}):e.jsxs("div",{className:"space-y-4",children:[ge.length>0&&e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3 flex items-center gap-2",children:[e.jsx(Nn,{className:"h-4 w-4 text-primary"}),e.jsxs("span",{className:"text-sm",children:[e.jsx("span",{className:"font-medium",children:"Last Contacted:"})," ",As(new Date(ge[0].completed_at),"MMM d, yyyy")," ","(",ge[0].name,")"]})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:gap-6 gap-2",children:[l.email&&e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(er,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}),e.jsx("button",{onClick:()=>it(l.email),className:"text-primary hover:underline truncate text-left",children:l.email})]}),l.phone&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Yn,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}),e.jsx("a",{href:`tel:${l.phone}`,className:"text-primary hover:underline",children:l.phone})]})]}),(l.address||l.city||l.state||l.zip_code)&&e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Qa,{className:"h-4 w-4 text-muted-foreground mt-0.5"}),e.jsxs("div",{className:"flex flex-col",children:[l.address&&e.jsx("span",{children:l.address}),(l.city||l.state||l.zip_code)&&e.jsxs("span",{className:"text-muted-foreground",children:[[l.city,l.state].filter(Boolean).join(", "),l.zip_code&&` ${l.zip_code}`]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[l.birthday&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Nn,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:["Birthday: ",As(Tc(l.birthday),"MMMM d")]})]}),l.home_anniversary&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Fn,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:["Home Anniversary: ",As(Tc(l.home_anniversary),"MMMM d")]})]}),l.created_at&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ys,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:["Date Added: ",As(new Date(l.created_at),"MMMM d, yyyy")]})]})]}),e.jsx(Qo,{}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsx(N4e,{contactId:s,currentSpouseContactId:(l==null?void 0:l.spouse_contact_id)||null,currentSpouseName:l.spouse_name||null,currentSpouseEmail:l.spouse_email||null,onLink:rt=>j.mutate({contactId:s,spouseContactId:rt}),onUnlink:()=>j.mutate({contactId:s,spouseContactId:null}),isEditing:!1}),(l.company_name||l.job_title)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Xa,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:l.job_title&&l.company_name?`${l.job_title} at ${l.company_name}`:l.job_title||l.company_name})]})]}),e.jsx(Qo,{}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium mb-2",children:"Relationship Types"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:(at=l.tags)!=null&&at.length?l.tags.map(rt=>{var Et;return e.jsx(Xe,{variant:"secondary",children:(Et=rt.relationship_type)==null?void 0:Et.name},rt.id)}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"No relationship types assigned"})})]}),l.notes&&e.jsxs(e.Fragment,{children:[e.jsx(Qo,{}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium mb-2",children:"Notes"}),e.jsx("p",{className:"text-sm text-muted-foreground whitespace-pre-wrap",children:l.notes})]})]})]})})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsx(KLs,{contact:l,onLogTouch:()=>R(!0)}),e.jsx(mDs,{contactId:s}),e.jsx(eDs,{contactId:s}),e.jsx(tDs,{contactId:s}),e.jsx(rDs,{contactId:s,contactName:l.first_name}),e.jsx(nDs,{contactId:s,contactName:l.first_name}),e.jsx(uDs,{contactId:s}),e.jsx(oDs,{contactId:s}),e.jsx(cDs,{contactId:s}),e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsx(zt,{children:"Activity Log"})}),e.jsx(Oe,{children:ge.length>0?e.jsx("div",{className:"space-y-4",children:ge.map(rt=>{var Et;return e.jsxs("div",{className:"flex items-start gap-3 pb-3 border-b last:border-0",children:[e.jsx("div",{className:"h-8 w-8 rounded-full flex items-center justify-center text-white text-xs",style:{backgroundColor:rt.color},children:rt.type==="popby"?e.jsx(Di,{className:"h-4 w-4"}):(Et=rt.name)==null?void 0:Et.charAt(0)}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium text-sm",children:rt.name}),rt.videoId&&e.jsxs(H,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:()=>ce(rt.videoId),children:[e.jsx(El,{className:"h-3 w-3 mr-1"}),"Preview"]})]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:As(new Date(rt.completed_at),"MMM d, yyyy h:mm a")}),rt.notes&&!rt.videoId&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:rt.notes})]})]},rt.id)})}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No activity logged yet"})})]}),p&&p.length>0&&e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(Gi,{className:"h-5 w-5 text-primary"}),"Video Replies"]})}),e.jsx(Oe,{children:e.jsx("div",{className:"space-y-4",children:p.map(rt=>{var Et,hs;return e.jsxs("div",{className:"flex items-start gap-3 pb-3 border-b last:border-0",children:[(Et=rt.video)!=null&&Et.thumbnail_url?e.jsx("img",{src:rt.video.thumbnail_url,alt:rt.video.title||"Video",className:"h-12 w-16 object-cover rounded cursor-pointer hover:opacity-80 transition-opacity",onClick:()=>ce(rt.video_id)}):e.jsx("div",{className:"h-12 w-16 bg-muted rounded flex items-center justify-center cursor-pointer hover:bg-muted/80 transition-colors",onClick:()=>ce(rt.video_id),children:e.jsx(xn,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"font-medium text-sm truncate",children:["Replied to: ",((hs=rt.video)==null?void 0:hs.title)||"Untitled Video"]}),e.jsxs(H,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs flex-shrink-0",onClick:()=>ce(rt.video_id),children:[e.jsx(El,{className:"h-3 w-3 mr-1"}),"Watch"]})]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:As(new Date(rt.created_at),"MMM d, yyyy h:mm a")}),rt.message&&e.jsxs("p",{className:"text-sm text-muted-foreground mt-1 line-clamp-2",children:['"',rt.message,'"']})]})]},rt.id)})})})]}),Le&&Le.length>0&&e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(yn,{className:"h-5 w-5 text-sky-500"}),"Sent Emails"]})}),e.jsx(Oe,{children:e.jsx("div",{className:"space-y-3",children:Le.map(rt=>e.jsxs(bs,{children:[e.jsx(Qi,{asChild:!0,children:e.jsxs("button",{className:"w-full text-left flex items-start gap-3 p-3 rounded-lg border hover:bg-muted/50 transition-colors cursor-pointer",children:[e.jsx("div",{className:"h-8 w-8 rounded-full bg-sky-500/10 flex items-center justify-center text-sky-600 flex-shrink-0",children:e.jsx(er,{className:"h-4 w-4"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:rt.subject}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["To: ",rt.to_email," · ",As(new Date(rt.sent_at),"MMM d, yyyy h:mm a")]})]}),e.jsx($a,{className:"h-4 w-4 text-muted-foreground mt-1 flex-shrink-0"})]})}),e.jsxs(vs,{className:"max-w-2xl max-h-[85vh] flex flex-col",children:[e.jsxs(Cs,{children:[e.jsxs(Ns,{className:"flex items-center gap-2",children:[e.jsx(er,{className:"h-5 w-5 text-sky-500"}),rt.subject]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["To: ",rt.to_email," · ",As(new Date(rt.sent_at),"MMM d, yyyy h:mm a")]})]}),e.jsx("div",{className:"flex-1 min-h-0 overflow-hidden rounded-lg border bg-white",children:e.jsx("iframe",{srcDoc:rt.body,className:"w-full h-[400px] border-0",sandbox:"",title:`Email: ${rt.subject}`})})]})]},rt.id))})})]})]}),e.jsx(bs,{open:!!ie,onOpenChange:rt=>!rt&&ce(null),children:e.jsxs(vs,{className:"max-w-2xl",children:[e.jsx(Cs,{children:e.jsx(Ns,{children:"Video Preview"})}),ie&&e.jsx(dDs,{videoId:ie})]})})]})]})}),We&&l&&be&&e.jsx(X_,{open:ne,onOpenChange:le,contact:{id:l.id,first_name:l.first_name,last_name:l.last_name,email:be.email},gmailEmail:Ve}),l&&l.email&&e.jsx(G8s,{open:je,onOpenChange:ve,contact:{id:l.id,first_name:l.first_name,last_name:l.last_name,email:l.email}})]}):e.jsx(Ss,{title:"Contact Not Found",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx("p",{className:"text-muted-foreground mb-4",children:"This contact was not found."}),e.jsx(H,{onClick:()=>t("/mission-control/contacts"),children:"Back to Contacts"})]})})}function pDs({rangeDays:s}){const{user:t}=Ms(),r=ns(),[n,a]=S.useState(null),[i,l]=S.useState(null),[o,c]=S.useState(!1),{data:d=[],isLoading:h}=yt({queryKey:["newsletter-campaigns",t==null?void 0:t.id,s],enabled:!!t,queryFn:async()=>{let x=V.from("email_campaigns").select("id, name, subject, status, sent_at, scheduled_at, created_at, total_recipients, sent_count, open_count, click_count, bounce_count").eq("user_id",t.id).like("name","Newsletter:%").order("created_at",{ascending:!1}).limit(50);if(s){const b=new Date(Date.now()-s*864e5).toISOString();x=x.gte("created_at",b)}const{data:y,error:_}=await x;if(_)throw _;return y||[]}}),{data:m}=yt({queryKey:["newsletter-campaign-recipients",n],enabled:!!n,queryFn:async()=>{const{data:x,error:y}=await V.from("email_campaign_recipients").select("id, email, name, status, sent_at, opened_at, clicked_at, error_message").eq("campaign_id",n).order("sent_at",{ascending:!1}).limit(2e3);if(y)throw y;return x||[]}}),p=async()=>{if(!(!i||!t)){c(!0);try{const{data:x,error:y}=await V.from("email_campaign_recipients").select("email, name, contact_id").eq("campaign_id",i.id).eq("status","sent").is("opened_at",null).limit(5e3);if(y)throw y;if(!x||x.length===0){he.info("All recipients opened — nothing to resend!"),l(null),c(!1);return}const{data:_}=await V.from("email_campaigns").select("subject, body_html, from_email, reply_to_email").eq("id",i.id).single();if(!_)throw new Error("Original campaign not found");const{data:b,error:j}=await V.from("email_campaigns").insert({user_id:t.id,name:`${i.name} (Resend to non-openers)`,subject:_.subject,body_html:_.body_html,from_email:_.from_email,reply_to_email:_.reply_to_email,total_recipients:x.length,status:"draft"}).select("id").single();if(j)throw j;const k=x.map(E=>({campaign_id:b.id,contact_id:E.contact_id,email:E.email,name:E.name,status:"pending"}));for(let E=0;E{const y=x.sent_count||0,_=y>0?x.open_count/y*100:0,b=y>0?x.click_count/y*100:0,j=x.sent_at?Jy(new Date,new Date(x.sent_at)):0,k=x.status==="sent"&&j>=3&&y>0&&x.open_counta(x.id),children:[e.jsx(Bn,{className:"h-3.5 w-3.5 mr-1"})," Details"]}),k&&e.jsxs(H,{variant:"outline",size:"sm",onClick:()=>l(x),children:[e.jsx(PE,{className:"h-3.5 w-3.5 mr-1"})," Resend"]})]})]}),x.status==="sent"&&y>0&&e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3 mt-3",children:[e.jsx(Wq,{icon:e.jsx(yn,{className:"h-3.5 w-3.5"}),label:"Sent",value:y,sub:`of ${x.total_recipients}`}),e.jsx(Wq,{icon:e.jsx(Bn,{className:"h-3.5 w-3.5 text-blue-600"}),label:"Opens",value:x.open_count,sub:`${_.toFixed(1)}%`,children:e.jsx(Mi,{value:_,className:"h-1 mt-1"})}),e.jsx(Wq,{icon:e.jsx(Kd,{className:"h-3.5 w-3.5 text-purple-600"}),label:"Clicks",value:x.click_count,sub:`${b.toFixed(1)}%`,children:e.jsx(Mi,{value:b,className:"h-1 mt-1"})}),e.jsx(Wq,{icon:e.jsx(qI,{className:"h-3.5 w-3.5 text-orange-600"}),label:"Bounces",value:x.bounce_count,sub:x.bounce_count>0?"review":"none"})]})]},x.id)})})]})}),e.jsx($S,{open:!!n,onOpenChange:x=>!x&&a(null),children:e.jsxs(vj,{className:"w-full sm:max-w-2xl overflow-y-auto",children:[e.jsx(US,{children:e.jsx(qS,{children:"Recipient Activity"})}),e.jsx("div",{className:"mt-4 space-y-1",children:m?m.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No recipients yet."}):e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"text-xs uppercase text-muted-foreground border-b",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left py-2",children:"Recipient"}),e.jsx("th",{className:"text-left py-2",children:"Opened"}),e.jsx("th",{className:"text-left py-2",children:"Clicked"}),e.jsx("th",{className:"text-left py-2",children:"Status"})]})}),e.jsx("tbody",{children:m.map(x=>e.jsxs("tr",{className:"border-b last:border-0",children:[e.jsxs("td",{className:"py-2",children:[e.jsx("div",{className:"font-medium truncate max-w-[180px]",children:x.name||"—"}),e.jsx("div",{className:"text-xs text-muted-foreground truncate max-w-[180px]",children:x.email})]}),e.jsx("td",{className:"py-2 text-xs",children:x.opened_at?e.jsx(Xe,{variant:"default",className:"text-xs",children:As(new Date(x.opened_at),"MMM d")}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx("td",{className:"py-2 text-xs",children:x.clicked_at?e.jsx(Xe,{variant:"default",className:"text-xs bg-purple-600",children:As(new Date(x.clicked_at),"MMM d")}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsxs("td",{className:"py-2 text-xs",children:[x.status==="sent"&&e.jsx(Xe,{variant:"outline",className:"text-xs",children:"sent"}),x.status==="pending"&&e.jsx(Xe,{variant:"secondary",className:"text-xs",children:"queued"}),x.status==="failed"&&e.jsx(Xe,{variant:"destructive",className:"text-xs",title:x.error_message||"",children:"failed"}),x.status==="suppressed"&&e.jsx(Xe,{variant:"outline",className:"text-xs",children:"suppressed"})]})]},x.id))})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading…"})})]})}),e.jsx(Rl,{open:!!i,onOpenChange:x=>!x&&l(null),children:e.jsxs(jl,{children:[e.jsxs(Nl,{children:[e.jsx(Sl,{children:"Resend to non-openers?"}),e.jsxs(Cl,{children:["This will send ",e.jsxs("span",{className:"font-medium text-foreground",children:['"',i==null?void 0:i.subject,'"']})," again only to contacts who didn't open the original. Consider tweaking the subject next time — but a clean resend is a great way to recover lost opens."]})]}),e.jsxs(kl,{children:[e.jsx(Tl,{disabled:o,children:"Cancel"}),e.jsx(ml,{onClick:p,disabled:o,children:o?e.jsxs(e.Fragment,{children:[e.jsx(is,{className:"h-4 w-4 mr-1 animate-spin"}),"Resending…"]}):e.jsxs(e.Fragment,{children:[e.jsx(PE,{className:"h-4 w-4 mr-1"}),"Resend"]})})]})]})})]})}function Wq({icon:s,label:t,value:r,sub:n,children:a}){return e.jsxs("div",{className:"rounded-lg border bg-muted/20 p-2.5",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[s,t]}),e.jsxs("div",{className:"flex items-baseline gap-1.5 mt-0.5",children:[e.jsx("span",{className:"text-lg font-bold",children:r.toLocaleString()}),n&&e.jsx("span",{className:"text-xs text-muted-foreground",children:n})]}),a]})}const WHe=["Gmail","Mass Email","Campaign","Client Portal Invite"],gDs={Gmail:"bg-red-100 text-red-700 border-red-200","Mass Email":"bg-blue-100 text-blue-700 border-blue-200",Campaign:"bg-purple-100 text-purple-700 border-purple-200","Client Portal Invite":"bg-emerald-100 text-emerald-700 border-emerald-200"};function xDs(){const{user:s}=Ms(),{data:t=[],isLoading:r}=sxt(),[n,a]=S.useState(""),[i,l]=S.useState("all"),[o,c]=S.useState("30"),[d,h]=S.useState(!1),{gmailEmail:m}=cf(),p=S.useMemo(()=>Array.from(new Set(t.map(b=>b.contact_id).filter(Boolean))),[t]),{data:x}=yt({queryKey:["sent-emails-contact-names",s==null?void 0:s.id,p.length],enabled:p.length>0,queryFn:async()=>{const{data:b}=await V.from("innercircle_contacts").select("id, first_name, last_name").in("id",p),j=new Map;return(b||[]).forEach(k=>{j.set(k.id,[k.first_name,k.last_name].filter(Boolean).join(" ")||"Contact")}),j}}),y=S.useMemo(()=>{const b=o==="all"?null:Date.now()-parseInt(o)*864e5,j=n.trim().toLowerCase();return t.filter(k=>{if(i!=="all"&&k.channel!==i||b&&new Date(k.sent_at).getTime(){const b={};return y.forEach(j=>{b[j.channel]=(b[j.channel]||0)+1}),b},[y]);return e.jsx(Ss,{children:e.jsxs("div",{className:"space-y-6 p-4 md:p-8",children:[e.jsxs("div",{className:"flex flex-col md:flex-row md:items-start md:justify-between gap-4",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-2xl font-bold flex items-center gap-2",children:[e.jsx(yn,{className:"h-6 w-6"})," Sent Emails"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"All emails you've sent through LevelUp — Gmail, mass emails, campaigns, and client portal invites."})]}),e.jsxs(H,{onClick:()=>h(!0),children:[e.jsx(er,{className:"h-4 w-4 mr-2"})," Send Email"]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3",children:[e.jsx(ke,{children:e.jsxs(Oe,{className:"py-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground uppercase",children:"Total"}),e.jsx("p",{className:"text-2xl font-bold",children:y.length})]})}),WHe.map(b=>e.jsx(ke,{children:e.jsxs(Oe,{className:"py-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground uppercase truncate",children:b}),e.jsx("p",{className:"text-2xl font-bold",children:_[b]||0})]})},b))]}),e.jsxs("div",{className:"flex flex-col md:flex-row gap-2",children:[e.jsxs("div",{className:"relative flex-1 max-w-md",children:[e.jsx(Mn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Se,{placeholder:"Search subject, recipient, contact...",value:n,onChange:b=>a(b.target.value),className:"pl-9"})]}),e.jsxs(Bs,{value:i,onValueChange:l,children:[e.jsx(Os,{className:"w-[200px]",children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"all",children:"All Channels"}),WHe.map(b=>e.jsx(pt,{value:b,children:b},b))]})]}),e.jsxs(Bs,{value:o,onValueChange:c,children:[e.jsx(Os,{className:"w-[160px]",children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"7",children:"Last 7 days"}),e.jsx(pt,{value:"30",children:"Last 30 days"}),e.jsx(pt,{value:"90",children:"Last 90 days"}),e.jsx(pt,{value:"365",children:"Last year"}),e.jsx(pt,{value:"all",children:"All time"})]})]})]}),e.jsx(pDs,{rangeDays:o==="all"?null:parseInt(o)}),r?e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading..."}):y.length===0?e.jsx(ke,{children:e.jsxs(Oe,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(er,{className:"h-12 w-12 text-muted-foreground mb-3"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No sent emails match your filters."})]})}):e.jsx(ke,{children:e.jsx(Oe,{className:"p-0",children:e.jsxs("div",{className:"overflow-x-auto",children:[e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-muted/50 text-xs uppercase text-muted-foreground",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left py-3 px-4 font-medium",children:"Sent"}),e.jsx("th",{className:"text-left py-3 px-4 font-medium",children:"Channel"}),e.jsx("th",{className:"text-left py-3 px-4 font-medium",children:"Subject"}),e.jsx("th",{className:"text-left py-3 px-4 font-medium",children:"Recipient"}),e.jsx("th",{className:"text-left py-3 px-4 font-medium",children:"Contact"})]})}),e.jsx("tbody",{children:y.slice(0,500).map(b=>{const j=b.contact_id?x==null?void 0:x.get(b.contact_id):null;return e.jsxs("tr",{className:"border-t hover:bg-muted/30",children:[e.jsx("td",{className:"py-3 px-4 whitespace-nowrap text-muted-foreground",children:As(new Date(b.sent_at),"MMM d, yyyy h:mm a")}),e.jsx("td",{className:"py-3 px-4",children:e.jsx(Xe,{variant:"outline",className:gDs[b.channel],children:b.channel})}),e.jsx("td",{className:"py-3 px-4 max-w-xs truncate font-medium",children:b.subject}),e.jsx("td",{className:"py-3 px-4 text-muted-foreground",children:b.to_email}),e.jsx("td",{className:"py-3 px-4",children:b.contact_id&&j?e.jsx(Xn,{to:`/mission-control/contacts/${b.contact_id}`,className:"text-primary hover:underline",children:j}):e.jsx("span",{className:"text-muted-foreground",children:"—"})})]},b.id)})})]}),y.length>500&&e.jsxs("p",{className:"text-xs text-muted-foreground text-center py-3 border-t",children:["Showing first 500 of ",y.length," — narrow your filters to see more."]})]})})}),e.jsx(X_,{open:d,onOpenChange:h,gmailEmail:m})]})})}const KHe={Crown:zf,FileText:kn,Users:Ar,Globe:ld,Star:ya,Phone:Yn,MessageSquare:Gi,PenTool:Gk,Video:xn,Gift:Di},mwe=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function yDs(){var mt,wt;const s=Fr(),{user:t}=Ms(),{data:r}=R0(),{data:n}=ZVt(),{data:a}=rHt(),{data:i}=uot(),{data:l}=oz(),{data:o}=YVt(),c=nHt(),d=XVt(),h=JVt(),m=eHt(),p=tHt(),x=sHt(),y=QVt(),[_,b]=S.useState(null),[j,k]=S.useState(!1),[T,E]=S.useState(null),[A,D]=S.useState(""),[R,z]=S.useState(""),[O,$]=S.useState([]),[ee,Z]=S.useState(null),[J,K]=S.useState(null),[re,ie]=S.useState(!1),[ce,ne]=S.useState(""),[le,be]=S.useState(""),[fe,je]=S.useState(""),[ve,We]=S.useState(""),Ve=(at,rt)=>a==null?void 0:a.some(Et=>Et.plan_id===at&&Et.relationship_type_id===rt&&Et.active),Le=at=>a==null?void 0:a.find(rt=>rt.relationship_type_id===at&&rt.active),Me=async(at,rt)=>{const Et=Ve(at,rt);await c.mutateAsync({planId:at,relationshipTypeId:rt,active:!Et})},ze=(n==null?void 0:n.filter(at=>at.active&&!at.owner_user_id))||[],Pe=(n==null?void 0:n.filter(at=>at.owner_user_id===(t==null?void 0:t.id)))||[],Ie=r==null?void 0:r.find(at=>at.id===_),De=_?Le(_):null,pe=n==null?void 0:n.find(at=>at.id===(De==null?void 0:De.plan_id)),tt=async()=>{if(!A.trim())return;const at=await d.mutateAsync({name:A,description:R});at&&O.length>0&&await p.mutateAsync({planId:at.id,items:O}),Ue()},ge=async()=>{!A.trim()||!T||(await h.mutateAsync({id:T,name:A,description:R}),await p.mutateAsync({planId:T,items:O}),Ue())},ct=at=>{var rt;E(at.id),D(at.name),z(at.description||""),$(((rt=at.items)==null?void 0:rt.map(Et=>({month_number:Et.month_number,action_type_id:Et.action_type_id,default_script_id:Et.default_script_id||void 0,notes:Et.notes||void 0})))||[]),k(!0)},Ue=()=>{k(!1),E(null),D(""),z(""),$([])},et=(at,rt)=>{K(rt)},Qe=(at,rt,Et)=>{$(hs=>[...hs.filter(lr=>lr.month_number!==at),{month_number:at,action_type_id:rt,default_script_id:Et}]),Z(null),K(null)},Ne=at=>{$(rt=>rt.filter(Et=>Et.month_number!==at))},$e=async()=>{if(!ce.trim()||!le.trim()||!J)return;const at=await x.mutateAsync({actionTypeId:J,title:ce,scriptBody:le,emailSubject:fe||void 0,tone:ve||void 0});at&&ee!==null&&Qe(ee,J,at.id),ie(!1),ne(""),be(""),je(""),We("")},it=J?o==null?void 0:o.filter(at=>at.action_type_id===J&&at.active):[],Je=at=>KHe[at||"Phone"]||Yn,st=at=>KHe[at||"Users"]||Ar;return e.jsxs(Ss,{title:"Touchpoint Plans",description:"Assign plans to your contact groups",children:[e.jsxs("div",{className:"space-y-6 overflow-x-hidden",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Touchpoint Plans"}),e.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"})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3",children:[e.jsxs(H,{variant:"ghost",size:"sm",onClick:()=>s("/mission-control"),children:[e.jsx(fl,{className:"h-4 w-4 mr-1"}),"Back"]}),e.jsxs(H,{onClick:()=>k(!0),className:"w-full sm:w-auto",children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Create Custom Plan"]})]}),e.jsxs("div",{className:"grid lg:grid-cols-3 gap-6",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx("h3",{className:"font-semibold text-lg",children:"Your Contact Groups"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Select a group to assign a touchpoint plan"}),r==null?void 0:r.filter(at=>at.active).map(at=>{const rt=st(at.icon),Et=(i==null?void 0:i[at.id])||0,hs=Le(at.id),Is=n==null?void 0:n.find(us=>us.id===(hs==null?void 0:hs.plan_id)),lr=_===at.id;return e.jsxs("button",{onClick:()=>b(at.id),className:` w-full flex items-center gap-3 p-4 rounded-lg border text-left transition-all ${lr?"border-primary bg-primary/5 ring-2 ring-primary":"hover:bg-accent"} `,children:[e.jsx(rt,{className:"h-5 w-5 text-muted-foreground"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-medium",children:at.name}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[Et," contacts"]})]}),Is?e.jsxs(Xe,{variant:"secondary",className:"text-xs",children:[e.jsx(zi,{className:"h-3 w-3 mr-1"}),Is.name.split(" ")[0]]}):e.jsx(Xe,{variant:"outline",className:"text-xs text-muted-foreground",children:"No plan"})]},at.id)})]}),e.jsx("div",{className:"lg:col-span-2",children:_&&Ie?e.jsxs(ke,{children:[e.jsxs(Ot,{children:[e.jsxs(zt,{className:"flex items-center gap-2",children:[(()=>{const at=st(Ie.icon);return e.jsx(at,{className:"h-5 w-5"})})(),Ie.name," Touchpoint Plan"]}),e.jsxs(Br,{children:["Choose a plan for your ",Ie.name," contacts"]})]}),e.jsxs(Oe,{className:"space-y-6",children:[pe&&e.jsxs("div",{className:"p-4 bg-primary/5 rounded-lg border border-primary/20",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"font-medium flex items-center gap-2",children:[e.jsx(zi,{className:"h-4 w-4 text-green-500"}),"Currently using: ",pe.name]}),pe.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:pe.description})]}),e.jsx(H,{variant:"outline",size:"sm",onClick:()=>Me(pe.id,_),children:"Disable"})]}),pe.items&&pe.items.length>0&&e.jsxs("div",{className:"mt-4",children:[e.jsxs("div",{className:"text-sm font-medium mb-2 flex items-center gap-2",children:[e.jsx(Nn,{className:"h-4 w-4"}),"12-Month Schedule"]}),e.jsx("div",{className:"grid grid-cols-4 sm:grid-cols-6 gap-2",children:mwe.map((at,rt)=>{var lr,us;const Et=((lr=pe.items)==null?void 0:lr.filter(St=>St.month_number===rt+1))||[],hs=(us=Et[0])==null?void 0:us.action_type,Is=hs?Je(hs.icon):null;return e.jsxs("div",{className:` p-2 rounded border text-center ${Et.length>0?"bg-primary/10 border-primary":"bg-muted"} `,children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:at}),Is&&e.jsx(Is,{className:"h-4 w-4 mx-auto mt-1",style:{color:(hs==null?void 0:hs.color)||"#3B82F6"}})]},rt)})})]})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium mb-3",children:pe?"Switch to a Different Plan":"Choose a Plan"}),ze.length>0&&e.jsxs("div",{className:"space-y-2 mb-4",children:[e.jsx("div",{className:"text-sm text-muted-foreground",children:"Pre-built Templates"}),ze.map(at=>{var Et;const rt=(pe==null?void 0:pe.id)===at.id;return e.jsxs("div",{className:` flex items-center justify-between p-3 rounded-lg border ${rt?"opacity-50":"hover:bg-accent"} `,children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:at.name}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[((Et=at.items)==null?void 0:Et.length)||0," touchpoints/year"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(H,{size:"sm",variant:"ghost",title:"Duplicate as my own plan",disabled:y.isPending,onClick:()=>{const hs=`${at.name} (Copy)`;y.mutate({sourcePlanId:at.id,newName:hs})},children:e.jsx(ui,{className:"h-4 w-4"})}),e.jsx(H,{size:"sm",variant:rt?"outline":"default",disabled:rt||c.isPending,onClick:()=>Me(at.id,_),children:rt?"Active":"Use This"})]})]},at.id)})]}),Pe.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-sm text-muted-foreground",children:"My Custom Plans"}),Pe.map(at=>{var Et;const rt=(pe==null?void 0:pe.id)===at.id;return e.jsxs("div",{className:` flex items-center justify-between p-3 rounded-lg border ${rt?"opacity-50":"hover:bg-accent"} `,children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:at.name}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[((Et=at.items)==null?void 0:Et.length)||0," touchpoints/year"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(H,{size:"sm",variant:"ghost",title:"Edit plan",onClick:()=>ct(at),children:e.jsx(Wb,{className:"h-4 w-4"})}),e.jsx(H,{size:"sm",variant:"ghost",title:"Delete plan",onClick:()=>m.mutate(at.id),children:e.jsx(Dr,{className:"h-4 w-4 text-destructive"})}),e.jsx(H,{size:"sm",variant:rt?"outline":"default",disabled:rt||c.isPending,onClick:()=>Me(at.id,_),children:rt?"Active":"Use This"})]})]},at.id)})]}),ze.length===0&&Pe.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No plans available. Create a custom plan to get started."})]})]})]}):e.jsx(ke,{children:e.jsxs(Oe,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(Nn,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"Select a contact group to view and assign plans"})]})})})]}),e.jsx(ke,{className:"bg-muted/50",children:e.jsx(Oe,{className:"py-4",children:e.jsxs("p",{className:"text-sm text-muted-foreground",children:[e.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."]})})})]}),e.jsx(bs,{open:j,onOpenChange:at=>{at?k(!0):Ue()},children:e.jsxs(vs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Cs,{children:e.jsx(Ns,{children:T?"Edit Touchpoint Plan":"Create Custom Touchpoint Plan"})}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"plan-name",children:"Plan Name"}),e.jsx(Se,{id:"plan-name",value:A,onChange:at=>D(at.target.value),placeholder:"e.g., My VIP Plan"})]}),e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"plan-description",children:"Description (optional)"}),e.jsx(vr,{id:"plan-description",value:R,onChange:at=>z(at.target.value),placeholder:"Describe your plan...",rows:2})]})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"12-Month Schedule"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-3",children:"Click on a month to add a touchpoint"}),e.jsx("div",{className:"grid grid-cols-6 gap-2",children:mwe.map((at,rt)=>{const Et=rt+1,hs=O.find(us=>us.month_number===Et),Is=hs?l==null?void 0:l.find(us=>us.id===hs.action_type_id):null,lr=Is?Je(Is.icon):null;return e.jsxs("div",{className:"relative",children:[e.jsxs("button",{type:"button",onClick:()=>Z(ee===Et?null:Et),className:` w-full p-3 rounded-lg border text-center transition-all ${hs?"bg-primary/10 border-primary":"bg-muted hover:bg-accent"} ${ee===Et?"ring-2 ring-primary":""} `,children:[e.jsx("div",{className:"text-xs text-muted-foreground font-medium",children:at}),lr?e.jsx(lr,{className:"h-5 w-5 mx-auto mt-1",style:{color:(Is==null?void 0:Is.color)||"#3B82F6"}}):e.jsx(Ys,{className:"h-5 w-5 mx-auto mt-1 text-muted-foreground/50"})]}),hs&&e.jsx("button",{type:"button",onClick:us=>{us.stopPropagation(),Ne(Et)},className:"absolute -top-1 -right-1 p-1 bg-destructive text-destructive-foreground rounded-full",children:e.jsx(Rr,{className:"h-3 w-3"})})]},rt)})}),ee!==null&&!J&&e.jsxs("div",{className:"mt-4 p-3 bg-muted rounded-lg",children:[e.jsxs("div",{className:"text-sm font-medium mb-2",children:["Step 1: Select action for ",mwe[ee-1],":"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:l==null?void 0:l.filter(at=>at.active).map(at=>{const rt=Je(at.icon);return e.jsxs("button",{type:"button",onClick:()=>et(ee,at.id),className:"flex items-center gap-2 px-3 py-2 rounded-lg border bg-background hover:bg-accent transition-colors",children:[e.jsx(rt,{className:"h-4 w-4",style:{color:at.color||"#3B82F6"}}),e.jsx("span",{className:"text-sm",children:at.name})]},at.id)})})]}),ee!==null&&J&&e.jsxs("div",{className:"mt-4 p-3 bg-muted rounded-lg space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"text-sm font-medium",children:"Step 2: Select a script (optional)"}),e.jsxs(H,{variant:"ghost",size:"sm",onClick:()=>K(null),children:[e.jsx(fl,{className:"h-4 w-4 mr-1"})," Back"]})]}),e.jsxs("div",{className:"space-y-2 max-h-[300px] overflow-y-auto pr-1",children:[e.jsx("button",{type:"button",onClick:()=>Qe(ee,J),className:"w-full flex items-center gap-3 p-3 rounded-lg border bg-background hover:bg-accent transition-colors text-left",children:e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-medium text-sm",children:"No Script"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Use without a predefined script"})]})}),it==null?void 0:it.map(at=>e.jsx("button",{type:"button",onClick:()=>Qe(ee,J,at.id),className:"w-full flex items-center gap-3 p-3 rounded-lg border bg-background hover:bg-accent transition-colors text-left",children:e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-medium text-sm",children:at.title}),at.tone&&e.jsx(Xe,{variant:"secondary",className:"text-xs mt-1",children:at.tone}),e.jsxs("div",{className:"text-xs text-muted-foreground mt-1 line-clamp-2",children:[at.script_body.substring(0,100),"..."]})]})},at.id)),e.jsxs("button",{type:"button",onClick:()=>ie(!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:[e.jsx(Ys,{className:"h-5 w-5 text-muted-foreground"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-medium text-sm",children:"Create Custom Script"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Write your own script for this action"})]})]})]})]})]}),O.length>0&&e.jsxs("div",{className:"text-sm text-muted-foreground",children:[O.length," touchpoint",O.length!==1?"s":""," per year"]})]}),e.jsxs(wn,{children:[e.jsx(H,{variant:"outline",onClick:Ue,children:"Cancel"}),e.jsxs(H,{onClick:T?ge:tt,disabled:!A.trim()||d.isPending||h.isPending,children:[e.jsx(vc,{className:"h-4 w-4 mr-2"}),T?"Save Changes":"Create Plan"]})]})]})}),e.jsx(bs,{open:re,onOpenChange:ie,children:e.jsxs(vs,{className:"max-w-lg",children:[e.jsx(Cs,{children:e.jsx(Ns,{children:"Create Custom Script"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"script-title",children:"Script Title"}),e.jsx(Se,{id:"script-title",value:ce,onChange:at=>ne(at.target.value),placeholder:"e.g., Friendly Check-in Call"})]}),e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"script-tone",children:"Tone (optional)"}),e.jsxs(Bs,{value:ve,onValueChange:We,children:[e.jsx(Os,{children:e.jsx(Us,{placeholder:"Select tone..."})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"friendly",children:"Friendly"}),e.jsx(pt,{value:"professional",children:"Professional"}),e.jsx(pt,{value:"casual",children:"Casual"}),e.jsx(pt,{value:"formal",children:"Formal"})]})]})]}),((wt=(mt=l==null?void 0:l.find(at=>at.id===J))==null?void 0:mt.name)==null?void 0:wt.toLowerCase().includes("email"))&&e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"script-email-subject",children:"Email Subject"}),e.jsx(Se,{id:"script-email-subject",value:fe,onChange:at=>je(at.target.value),placeholder:"e.g., Quick Hello!"})]}),e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"script-body",children:"Script Content"}),e.jsx(vr,{id:"script-body",value:le,onChange:at=>be(at.target.value),placeholder:"Write your script here... You can use {{FirstName}} and {{LastName}} as placeholders.",rows:6}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Tip: Use ","{{FirstName}}"," and ","{{LastName}}"," as placeholders"]})]})]}),e.jsxs(wn,{children:[e.jsx(H,{variant:"outline",onClick:()=>ie(!1),children:"Cancel"}),e.jsxs(H,{onClick:$e,disabled:!ce.trim()||!le.trim()||x.isPending,children:[e.jsx(vc,{className:"h-4 w-4 mr-2"}),"Create & Use Script"]})]})]})})]})}function vDs(s,t,r,n){const a=d=>d*Math.PI/180,l=a(r-s),o=a(n-t),c=Math.sin(l/2)**2+Math.cos(a(s))*Math.cos(a(r))*Math.sin(o/2)**2;return 2*3958.8*Math.asin(Math.sqrt(c))}const rxt="popby_geocode_cache_v1";function bDs(){try{return JSON.parse(localStorage.getItem(rxt)||"{}")}catch{return{}}}function _Ds(s){try{localStorage.setItem(rxt,JSON.stringify(s))}catch{}}function wDs({contacts:s,onLogPopby:t}){const[r,n]=S.useState(null),[a,i]=S.useState("idle"),[l,o]=S.useState(5),[c,d]=S.useState(""),[h,m]=S.useState(new Map),[p,x]=S.useState(!1);S.useEffect(()=>{(async()=>{const{data:k}=await V.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();k!=null&&k.value&&d(k.value)})()},[]);const y=S.useMemo(()=>s.filter(k=>k.isDue&&(k.address||k.city&&k.state||k.zip)),[s]),_=()=>{if(!("geolocation"in navigator)){i("unavailable");return}i("loading"),navigator.geolocation.getCurrentPosition(k=>{n({lat:k.coords.latitude,lng:k.coords.longitude}),i("ok")},()=>{i("denied")},{enableHighAccuracy:!0,timeout:1e4,maximumAge:6e4})};S.useEffect(()=>{if(!c||!r||y.length===0)return;let k=!1;const T=bDs(),E=new Map;y.forEach(D=>{const R=[D.address,D.city,D.state,D.zip].filter(Boolean).join("|").toLowerCase();T[R]&&E.set(D.id,T[R])}),m(new Map(E));const A=y.filter(D=>!([D.address,D.city,D.state,D.zip].filter(Boolean).join("|").toLowerCase()in T));if(A.length!==0)return x(!0),(async()=>{const D=[...A],R=async()=>{var z,O;for(;D.length&&!k;){const $=D.shift(),ee=[$.address,$.city,$.state,$.zip].filter(Boolean),Z=ee.join("|").toLowerCase(),J=ee.join(", ");try{const re=await(await fetch(`https://api.mapbox.com/geocoding/v5/mapbox.places/${encodeURIComponent(J)}.json?limit=1&access_token=${c}`)).json();if((O=(z=re==null?void 0:re.features)==null?void 0:z[0])!=null&&O.center){const[ie,ce]=re.features[0].center;T[Z]={lat:ce,lng:ie},E.set($.id,{lat:ce,lng:ie})}else T[Z]=null}catch{}}};await Promise.all([R(),R(),R(),R()]),k||(_Ds(T),m(new Map(E)),x(!1))})(),()=>{k=!0}},[c,r,y]);const b=S.useMemo(()=>{if(!r)return[];const k=[];return y.forEach(T=>{const E=h.get(T.id);if(!E)return;const A=vDs(r.lat,r.lng,E.lat,E.lng);A<=l&&k.push({...T,distanceMiles:A,lat:E.lat,lng:E.lng})}),k.sort((T,E)=>T.distanceMiles-E.distanceMiles)},[r,y,h,l]),j=k=>{const E=/iPad|iPhone|iPod/.test(navigator.userAgent)?`https://maps.apple.com/?daddr=${k.lat},${k.lng}`:`https://www.google.com/maps/dir/?api=1&destination=${k.lat},${k.lng}`;window.open(E,"_blank","noopener")};return e.jsxs(ke,{className:"border-primary/30 bg-gradient-to-br from-primary/5 to-transparent",children:[e.jsx(Ot,{className:"pb-3",children:e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{children:[e.jsxs(zt,{className:"flex items-center gap-2 text-lg",children:[e.jsx($I,{className:"h-5 w-5 text-primary"}),"Nearby Now"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Due contacts within driving distance — perfect for errand-day pop-bys."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Bs,{value:String(l),onValueChange:k=>o(Number(k)),children:[e.jsx(Os,{className:"w-[110px] h-9",children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"2",children:"2 miles"}),e.jsx(pt,{value:"5",children:"5 miles"}),e.jsx(pt,{value:"10",children:"10 miles"}),e.jsx(pt,{value:"25",children:"25 miles"})]})]}),e.jsxs(H,{size:"sm",variant:a==="ok"?"outline":"default",onClick:_,disabled:a==="loading",children:[a==="loading"?e.jsx(po,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx($I,{className:"h-4 w-4 mr-1"}),a==="ok"?"Refresh":"Use my location"]})]})]})}),e.jsxs(Oe,{className:"space-y-3",children:[a==="idle"&&e.jsxs("div",{className:"text-center py-6 text-sm text-muted-foreground",children:[e.jsx(Qa,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),"Tap ",e.jsx("span",{className:"font-medium text-foreground",children:'"Use my location"'})," to see who's close by right now."]}),a==="denied"&&e.jsxs("div",{className:"text-center py-6 text-sm text-destructive flex flex-col items-center gap-2",children:[e.jsx(wo,{className:"h-6 w-6"}),"Location access was blocked. Enable it in your browser to use Nearby Now."]}),a==="unavailable"&&e.jsx("div",{className:"text-center py-6 text-sm text-muted-foreground",children:"Geolocation isn't available on this device."}),a==="ok"&&!c&&e.jsx("div",{className:"text-center py-6 text-sm text-muted-foreground",children:"Mapping isn't configured yet — ask an admin to add the Mapbox token."}),a==="ok"&&c&&y.length===0&&e.jsx("div",{className:"text-center py-6 text-sm text-muted-foreground",children:"No due contacts have addresses yet. Add street addresses to your sphere to power this."}),a==="ok"&&c&&y.length>0&&p&&b.length===0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ks,{className:"h-14 w-full"}),e.jsx(Ks,{className:"h-14 w-full"}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:"Locating contacts…"})]}),a==="ok"&&c&&!p&&b.length===0&&y.length>0&&e.jsxs("div",{className:"text-center py-6 text-sm text-muted-foreground",children:["No due contacts within ",l," miles. Try widening the radius."]}),b.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Xe,{variant:"secondary",className:"font-medium",children:[b.length," nearby"]}),p&&e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(po,{className:"h-3 w-3 animate-spin"})," still locating…"]})]}),e.jsx("div",{className:"space-y-2",children:b.map(k=>e.jsxs("div",{className:"flex items-center justify-between gap-3 p-3 rounded-lg bg-card border hover:border-primary/40 transition-colors",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs("span",{className:"font-medium truncate",children:[k.first_name," ",k.last_name]}),e.jsx(Xe,{variant:"outline",className:"text-xs",children:k.distanceMiles<1?`${(k.distanceMiles*5280).toFixed(0)} ft`:`${k.distanceMiles.toFixed(1)} mi`}),k.daysOverdue>0&&e.jsxs(Xe,{variant:"destructive",className:"text-xs",children:[k.daysOverdue,"d overdue"]})]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate mt-0.5",children:[k.address,k.city,k.state].filter(Boolean).join(", ")})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[k.phone&&e.jsx(H,{size:"icon",variant:"ghost",asChild:!0,className:"h-9 w-9",title:"Call",children:e.jsx("a",{href:`tel:${k.phone}`,children:e.jsx(Yn,{className:"h-4 w-4"})})}),e.jsx(H,{size:"icon",variant:"ghost",onClick:()=>j(k),className:"h-9 w-9",title:"Directions",children:e.jsx(wF,{className:"h-4 w-4"})}),e.jsxs(H,{size:"sm",onClick:()=>t(k),children:[e.jsx(Di,{className:"h-4 w-4 mr-1"}),"Log"]})]})]},k.id))})]})]})]})}const jDs="0dde5abb-0005-4c8c-a471-30d0cbc9e280",NDs=[{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 kDs(){const s=Fr(),t=Bgt(),{data:r}=$Ls(),{data:n}=R0(),{data:a}=lMe(),{data:i}=D0e(90),{data:l}=Cp(),o=GLs(),c=VLs(),d=qLs(),h=HLs(),{data:m=[],isLoading:p}=yt({queryKey:["popby-templates"],queryFn:async()=>{const{data:re,error:ie}=await V.from("canva_templates").select(` *, category:template_categories(id, name), type:template_types(id, name) `).eq("category_id",jDs).order("publish_date",{ascending:!1});if(ie)throw ie;const{data:ce}=await V.from("template_likes").select("template_id"),{data:ne}=await V.from("template_comments").select("template_id"),le=new Map;ce==null||ce.forEach(fe=>{le.set(fe.template_id,(le.get(fe.template_id)||0)+1)});const be=new Map;return ne==null||ne.forEach(fe=>{be.set(fe.template_id,(be.get(fe.template_id)||0)+1)}),(re||[]).map(fe=>({...fe,likesCount:le.get(fe.id)||0,commentsCount:be.get(fe.id)||0}))}}),x=re=>{const ie=l==null?void 0:l.find(ce=>ce.id===re);return ie?`${ie.first_name} ${ie.last_name||""}`.trim():"Unknown"},y=re=>{if(!re)return null;const ie=r==null?void 0:r.find(ce=>ce.id===re);return(ie==null?void 0:ie.name)||null},[_,b]=S.useState(null),[j,k]=S.useState(!1),[T,E]=S.useState(!1),[A,D]=S.useState(!1),[R,z]=S.useState({popby_item_id:"",notes:""}),[O,$]=S.useState({name:"",description:""}),ee=async()=>{_&&(await c.mutateAsync({contact_id:_.id,popby_item_id:R.popby_item_id||void 0,notes:R.notes||void 0}),k(!1),b(null),z({popby_item_id:"",notes:""}))},Z=async()=>{O.name.trim()&&(await d.mutateAsync({name:O.name.trim(),description:O.description.trim()||void 0}),D(!1),$({name:"",description:""}))},J=async(re,ie)=>{await h.mutateAsync({relationship_type_id:re,frequency_days:parseInt(ie)})},K=re=>{var ce;const ie=a==null?void 0:a.find(ne=>ne.relationship_type_id===re);return((ce=ie==null?void 0:ie.frequency_days)==null?void 0:ce.toString())||"90"};return e.jsx(Ss,{title:"Popbys",description:"Drop off gifts to stay top of mind",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Popbys"}),e.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"})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsx(ke,{children:e.jsxs(Oe,{className:"p-4 text-center",children:[e.jsx("div",{className:"text-3xl font-bold text-primary",children:o.thisWeekCount}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"This Week"})]})}),e.jsx(ke,{children:e.jsxs(Oe,{className:"p-4 text-center",children:[e.jsx("div",{className:"text-3xl font-bold text-emerald-500",children:o.thisMonthCount}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"This Month"})]})}),e.jsx(ke,{children:e.jsxs(Oe,{className:"p-4 text-center",children:[e.jsx("div",{className:"text-3xl font-bold text-amber-500",children:o.dueCount}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Due Now"})]})})]}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs(H,{onClick:()=>s("/mission-control/popbys/map"),children:[e.jsx(Qa,{className:"h-4 w-4 mr-2"}),"View Map"]}),e.jsxs(H,{variant:"outline",onClick:()=>E(!0),children:[e.jsx(Go,{className:"h-4 w-4 mr-2"}),"Frequency Settings"]}),e.jsxs(H,{variant:"outline",onClick:()=>D(!0),children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Add Popby Idea"]})]}),e.jsxs(ta,{defaultValue:"due",children:[e.jsxs(Qn,{children:[e.jsx(ts,{value:"due",children:"Due for Popby"}),e.jsx(ts,{value:"activity",children:"Recent Activity"}),e.jsx(ts,{value:"library",children:"Popby Library"}),e.jsx(ts,{value:"templates",children:"Popby Templates"})]}),e.jsxs(cs,{value:"due",className:"space-y-4 mt-4",children:[e.jsx(wDs,{contacts:t||[],onLogPopby:re=>{b(re),k(!0)}}),!t||t.length===0?e.jsx(ke,{children:e.jsxs(Oe,{className:"p-8 text-center text-muted-foreground",children:[e.jsx(Di,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No contacts due for a popby right now!"}),e.jsx("p",{className:"text-sm mt-1",children:"Great job staying connected."})]})}):e.jsx("div",{className:"space-y-3",children:t.map(re=>e.jsx(ke,{className:"hover:shadow-md transition-shadow",children:e.jsx(Oe,{className:"p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"font-medium",children:[re.first_name," ",re.last_name]}),re.daysOverdue>0&&e.jsxs(Xe,{variant:"destructive",className:"text-xs",children:[re.daysOverdue,"+ days overdue"]}),re.daysSinceLastPopby===null&&e.jsx(Xe,{variant:"outline",className:"text-xs",children:"Never visited"})]}),e.jsxs("div",{className:"flex items-center gap-4 mt-1 text-sm text-muted-foreground",children:[re.address&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Qa,{className:"h-3 w-3"}),re.city||re.address]}),re.tags&&re.tags.length>0&&e.jsx("span",{children:re.tags.map(ie=>{var ce;return(ce=ie.relationship_type)==null?void 0:ce.name}).join(", ")})]}),re.lastPopby&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Last popby: ",As(new Date(re.lastPopby),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[re.phone&&e.jsx(H,{size:"sm",variant:"ghost",asChild:!0,children:e.jsx("a",{href:`tel:${re.phone}`,children:e.jsx(Yn,{className:"h-4 w-4"})})}),e.jsxs(H,{size:"sm",onClick:()=>{b(re),k(!0)},children:[e.jsx(zi,{className:"h-4 w-4 mr-1"}),"Log Popby"]})]})]})})},re.id))})]}),e.jsx(cs,{value:"activity",className:"space-y-4 mt-4",children:!i||i.length===0?e.jsx(ke,{children:e.jsxs(Oe,{className:"p-8 text-center text-muted-foreground",children:[e.jsx(Pn,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No popby activity yet!"}),e.jsx("p",{className:"text-sm mt-1",children:"Start logging popbys to see your history here."})]})}):e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-lg",children:"Recent Popby Log"})}),e.jsx(Oe,{className:"space-y-3",children:i.map(re=>e.jsxs("div",{className:"flex items-start gap-3 pb-3 border-b last:border-0 last:pb-0",children:[e.jsx("div",{className:"h-10 w-10 rounded-full bg-orange-500/10 flex items-center justify-center",children:e.jsx(Di,{className:"h-5 w-5 text-orange-500"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"font-medium",children:x(re.contact_id)}),y(re.popby_item_id)&&e.jsx(Xe,{variant:"secondary",className:"text-xs",children:y(re.popby_item_id)})]}),e.jsx("div",{className:"text-sm text-muted-foreground",children:As(new Date(re.completed_at),"MMM d, yyyy h:mm a")}),re.notes&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1 line-clamp-2",children:re.notes})]})]},re.id))})]})}),e.jsx(cs,{value:"library",className:"space-y-4 mt-4",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[r==null?void 0:r.map(re=>e.jsx(ke,{children:e.jsx(Oe,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(Di,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"font-medium",children:re.name}),re.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:re.description}),!re.owner_user_id&&e.jsx(Xe,{variant:"secondary",className:"mt-2 text-xs",children:"Shared"})]})]})})},re.id)),e.jsx(ke,{className:"border-dashed cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>D(!0),children:e.jsx(Oe,{className:"p-4 flex items-center justify-center h-full min-h-[100px]",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(Ys,{className:"h-8 w-8 mx-auto mb-2"}),e.jsx("p",{children:"Add New Popby Idea"})]})})})]})}),e.jsxs(cs,{value:"templates",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:[m.length," template",m.length!==1?"s":""," found"]}),p&&e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6",children:[...Array(4)].map((re,ie)=>e.jsx(ke,{children:e.jsxs(Oe,{className:"p-4",children:[e.jsx(Ks,{className:"aspect-[3/2] w-full rounded-lg mb-4"}),e.jsx(Ks,{className:"h-5 w-3/4 mb-2"}),e.jsx(Ks,{className:"h-4 w-full mb-4"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ks,{className:"h-5 w-16"}),e.jsx(Ks,{className:"h-5 w-20"})]})]})},ie))}),!p&&m.length===0&&e.jsx(ke,{children:e.jsxs(Oe,{className:"p-8 text-center text-muted-foreground",children:[e.jsx(yc,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No popby templates available yet!"}),e.jsx("p",{className:"text-sm mt-1",children:"Check back soon for new templates."})]})}),!p&&m.length>0&&e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6",children:m.map(re=>e.jsxs(ke,{className:"group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer",onClick:()=>s(`/templates/${re.id}`),children:[e.jsx("div",{className:"relative overflow-hidden bg-muted aspect-[3/2]",children:re.preview_image_url?e.jsx("img",{src:re.preview_image_url,alt:re.name,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground",children:"No Preview"})}),e.jsxs(Oe,{className:"p-4 flex flex-col",children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1 mb-1",children:re.name}),re.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-3 flex-1",children:Q7(re.description)}),e.jsx("div",{className:"flex flex-wrap gap-2 mb-3",children:e.jsx(Xe,{variant:"secondary",className:"text-xs",children:"PopBys"})}),e.jsxs("div",{className:"flex items-center gap-4 text-sm text-muted-foreground mb-3",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(sf,{className:"h-3.5 w-3.5"}),re.likesCount]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(qc,{className:"h-3.5 w-3.5"}),re.commentsCount]})]}),e.jsxs(H,{size:"sm",className:"w-full gap-2",onClick:ie=>{ie.stopPropagation(),s(`/templates/${re.id}`)},children:[e.jsx(gn,{className:"h-4 w-4"}),"View Template"]})]})]},re.id))})]})]}),e.jsx(bs,{open:j,onOpenChange:k,children:e.jsxs(vs,{children:[e.jsx(Cs,{children:e.jsxs(Ns,{children:["Log Popby for ",_==null?void 0:_.first_name," ",_==null?void 0:_.last_name]})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Popby Item (optional)"}),e.jsxs(Bs,{value:R.popby_item_id,onValueChange:re=>z(ie=>({...ie,popby_item_id:re})),children:[e.jsx(Os,{children:e.jsx(Us,{placeholder:"Select a popby item..."})}),e.jsx(Fs,{children:r==null?void 0:r.map(re=>e.jsx(pt,{value:re.id,children:re.name},re.id))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Notes (optional)"}),e.jsx(vr,{placeholder:"Any notes about this popby...",value:R.notes,onChange:re=>z(ie=>({...ie,notes:re.target.value}))})]})]}),e.jsxs(wn,{children:[e.jsx(H,{variant:"outline",onClick:()=>k(!1),children:"Cancel"}),e.jsx(H,{onClick:ee,disabled:c.isPending,children:"Log Popby"})]})]})}),e.jsx(bs,{open:T,onOpenChange:E,children:e.jsxs(vs,{className:"max-w-md",children:[e.jsx(Cs,{children:e.jsx(Ns,{children:"Popby Frequency Settings"})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.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(re=>e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsx(ue,{className:"font-medium",children:re.name}),e.jsxs(Bs,{value:K(re.id),onValueChange:ie=>J(re.id,ie),children:[e.jsx(Os,{className:"w-[180px]",children:e.jsx(Us,{})}),e.jsx(Fs,{children:NDs.map(ie=>e.jsx(pt,{value:ie.value,children:ie.label},ie.value))})]})]},re.id))]}),e.jsx(wn,{children:e.jsx(H,{onClick:()=>E(!1),children:"Done"})})]})}),e.jsx(bs,{open:A,onOpenChange:D,children:e.jsxs(vs,{children:[e.jsx(Cs,{children:e.jsx(Ns,{children:"Add Popby Idea"})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Name *"}),e.jsx(Se,{placeholder:"e.g., Homemade cookies",value:O.name,onChange:re=>$(ie=>({...ie,name:re.target.value}))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Description"}),e.jsx(vr,{placeholder:"Optional description...",value:O.description,onChange:re=>$(ie=>({...ie,description:re.target.value}))})]})]}),e.jsxs(wn,{children:[e.jsx(H,{variant:"outline",onClick:()=>D(!1),children:"Cancel"}),e.jsx(H,{onClick:Z,disabled:!O.name.trim()||d.isPending,children:"Add Item"})]})]})})]})})}const SDs=yj({property_address:Ho().min(1,"Property address is required"),city:Ho().optional(),state:Ho().optional(),zip:Ho().optional(),transaction_type:krt(["buyer","seller"]),close_date:Ho().min(1,"Close date is required"),sale_price:ZF().min(0,"Sale price must be positive"),commission_amount:ZF().optional(),lead_source_id:Ho().optional(),client_type_id:Ho().optional(),contact_id:Ho().optional(),notes:Ho().optional(),is_win:rOt()});function nxt({open:s,onOpenChange:t,transaction:r}){const[n,a]=S.useState(!1),[i,l]=S.useState(""),[o,c]=S.useState(!1),[d,h]=S.useState(""),m=exe(),p=HHt(),{data:x}=v8(),{data:y}=R0(),{data:_}=Cp(),b=Qge(),j=wTe(),{data:k}=txe(),T=(k==null?void 0:k.show_commission)??!0,E=qge({resolver:Vge(SDs),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}});S.useEffect(()=>{r?E.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}):E.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,E]);const A=async O=>{const $={property_address:O.property_address,transaction_type:O.transaction_type,close_date:O.close_date,sale_price:O.sale_price,is_win:O.is_win,commission_amount:O.commission_amount||null,lead_source_id:O.lead_source_id||null,client_type_id:O.client_type_id||null,contact_id:O.contact_id||null,city:O.city||null,state:O.state||null,zip:O.zip||null,notes:O.notes||null};r?await p.mutateAsync({id:r.id,...$}):await m.mutateAsync($),t(!1)},D=async()=>{if(!i.trim())return;const[O,...$]=i.trim().split(" "),ee=$.join(" ")||null,Z=await b.mutateAsync({first_name:O,last_name:ee,tagIds:[]});Z&&(E.setValue("contact_id",Z.id),l(""),c(!1),a(!1))},R=async()=>{if(!d.trim())return;const O=await j.mutateAsync(d.trim());O&&(E.setValue("lead_source_id",O.id),h(""))},z=_==null?void 0:_.find(O=>O.id===E.watch("contact_id"));return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-lg max-h-[90vh]",children:[e.jsx(Cs,{children:e.jsx(Ns,{children:r?"Edit Transaction":"Add Transaction"})}),e.jsx(Ci,{className:"max-h-[70vh] pr-4",children:e.jsx(Hge,{...E,children:e.jsxs("form",{onSubmit:E.handleSubmit(A),className:"space-y-4",children:[e.jsx(iu,{control:E.control,name:"property_address",render:({field:O})=>e.jsxs(Ud,{children:[e.jsx(qd,{children:"Property Address *"}),e.jsx(Vd,{children:e.jsx(Se,{placeholder:"123 Main St",...O})}),e.jsx(mg,{})]})}),e.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[e.jsx(iu,{control:E.control,name:"city",render:({field:O})=>e.jsxs(Ud,{children:[e.jsx(qd,{children:"City"}),e.jsx(Vd,{children:e.jsx(Se,{placeholder:"City",...O})})]})}),e.jsx(iu,{control:E.control,name:"state",render:({field:O})=>e.jsxs(Ud,{children:[e.jsx(qd,{children:"State"}),e.jsx(Vd,{children:e.jsx(Se,{placeholder:"TX",...O})})]})}),e.jsx(iu,{control:E.control,name:"zip",render:({field:O})=>e.jsxs(Ud,{children:[e.jsx(qd,{children:"Zip"}),e.jsx(Vd,{children:e.jsx(Se,{placeholder:"75001",...O})})]})})]}),e.jsx(iu,{control:E.control,name:"transaction_type",render:({field:O})=>e.jsxs(Ud,{children:[e.jsx(qd,{children:"Transaction Type *"}),e.jsxs(Bs,{onValueChange:O.onChange,value:O.value,children:[e.jsx(Vd,{children:e.jsx(Os,{children:e.jsx(Us,{placeholder:"Select type"})})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"buyer",children:"Buyer"}),e.jsx(pt,{value:"seller",children:"Seller"})]})]}),e.jsx(mg,{})]})}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsx(iu,{control:E.control,name:"close_date",render:({field:O})=>e.jsxs(Ud,{children:[e.jsx(qd,{children:"Close Date *"}),e.jsx(Vd,{children:e.jsx(Se,{type:"date",...O})}),e.jsx(mg,{})]})}),e.jsx(iu,{control:E.control,name:"sale_price",render:({field:O})=>e.jsxs(Ud,{children:[e.jsx(qd,{children:"Sale Price *"}),e.jsx(Vd,{children:e.jsx(Se,{type:"number",placeholder:"0",...O,onChange:$=>O.onChange(Number($.target.value))})}),e.jsx(mg,{})]})})]}),T&&e.jsx(iu,{control:E.control,name:"commission_amount",render:({field:O})=>e.jsxs(Ud,{children:[e.jsx(qd,{children:"Commission"}),e.jsx(Vd,{children:e.jsx(Se,{type:"number",placeholder:"0",...O,value:O.value??"",onChange:$=>O.onChange($.target.value?Number($.target.value):void 0)})})]})}),e.jsx(iu,{control:E.control,name:"lead_source_id",render:({field:O})=>e.jsxs(Ud,{children:[e.jsx(qd,{children:"Lead Source"}),e.jsxs(Bs,{onValueChange:O.onChange,value:O.value||"",children:[e.jsx(Vd,{children:e.jsx(Os,{children:e.jsx(Us,{placeholder:"Select source"})})}),e.jsx(Fs,{children:x==null?void 0:x.map($=>e.jsx(pt,{value:$.id,children:$.name},$.id))})]})]})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Se,{placeholder:"Add custom source...",value:d,onChange:O=>h(O.target.value),className:"flex-1"}),e.jsx(H,{type:"button",variant:"outline",size:"icon",onClick:R,disabled:!d.trim(),children:e.jsx(Ys,{className:"h-4 w-4"})})]}),e.jsx(iu,{control:E.control,name:"client_type_id",render:({field:O})=>e.jsxs(Ud,{children:[e.jsx(qd,{children:"Client Type"}),e.jsxs(Bs,{onValueChange:O.onChange,value:O.value||"",children:[e.jsx(Vd,{children:e.jsx(Os,{children:e.jsx(Us,{placeholder:"Select client type"})})}),e.jsx(Fs,{children:y==null?void 0:y.map($=>e.jsx(pt,{value:$.id,children:$.name},$.id))})]})]})}),e.jsx(iu,{control:E.control,name:"contact_id",render:({field:O})=>e.jsxs(Ud,{children:[e.jsx(qd,{children:"Client Contact"}),e.jsxs(gl,{open:n,onOpenChange:a,children:[e.jsx(xl,{asChild:!0,children:e.jsx(Vd,{children:e.jsxs(H,{variant:"outline",role:"combobox",className:Ft("w-full justify-between",!O.value&&"text-muted-foreground"),children:[z?`${z.first_name} ${z.last_name||""}`.trim():"Select contact",e.jsx(d0,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})})}),e.jsxs(il,{className:"w-full p-0",align:"start",children:[e.jsxs(k0,{children:[e.jsx(S0,{placeholder:"Search contacts..."}),e.jsxs(C0,{children:[e.jsx(T0,{children:e.jsxs("div",{className:"p-2 space-y-2",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"No contact found."}),!o&&e.jsxs(H,{variant:"outline",size:"sm",className:"w-full",onClick:()=>c(!0),children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Add New Contact"]})]})}),e.jsx(E0,{children:_==null?void 0:_.map($=>e.jsxs(fg,{value:`${$.first_name} ${$.last_name||""}`,onSelect:()=>{O.onChange($.id),a(!1)},children:[e.jsx(va,{className:Ft("mr-2 h-4 w-4",$.id===O.value?"opacity-100":"opacity-0")}),$.first_name," ",$.last_name||""]},$.id))})]})]}),o&&e.jsxs("div",{className:"p-2 border-t space-y-2",children:[e.jsx(Se,{placeholder:"Enter contact name...",value:i,onChange:$=>l($.target.value)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(H,{size:"sm",onClick:D,disabled:!i.trim()||b.isPending,children:"Add Contact"}),e.jsx(H,{size:"sm",variant:"outline",onClick:()=>{c(!1),l("")},children:"Cancel"})]})]})]})]})]})}),e.jsx(iu,{control:E.control,name:"notes",render:({field:O})=>e.jsxs(Ud,{children:[e.jsx(qd,{children:"Notes"}),e.jsx(Vd,{children:e.jsx(vr,{placeholder:"Any notes about this transaction...",...O})})]})}),e.jsx(iu,{control:E.control,name:"is_win",render:({field:O})=>e.jsxs(Ud,{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(qd,{children:"Mark as Win 🏆"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Highlight this as a notable success"})]}),e.jsx(Vd,{children:e.jsx(Or,{checked:O.value,onCheckedChange:O.onChange})})]})}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(H,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(H,{type:"submit",disabled:m.isPending||p.isPending,children:[r?"Update":"Add"," Transaction"]})]})]})})})]})})}function uMe({transactions:s,showCommission:t,isLoading:r,agentNameMap:n,readOnly:a}){const[i,l]=S.useState(null),[o,c]=S.useState(null),[d,h]=S.useState(""),[m,p]=S.useState("all"),[x,y]=S.useState("all"),[_,b]=S.useState("all"),[j,k]=S.useState(!1),T=GHt(),E=exe(),{data:A}=v8();R0();const D=V8(),R=$=>{const{id:ee,created_at:Z,updated_at:J,lead_source:K,client_type:re,contact:ie,...ce}=$;E.mutate(ce)},z=()=>{o&&(T.mutate(o),c(null))},O=s.filter($=>{var ie,ce,ne,le;const ee=d===""||$.property_address.toLowerCase().includes(d.toLowerCase())||((ce=(ie=$.contact)==null?void 0:ie.first_name)==null?void 0:ce.toLowerCase().includes(d.toLowerCase()))||((le=(ne=$.contact)==null?void 0:ne.last_name)==null?void 0:le.toLowerCase().includes(d.toLowerCase())),Z=m==="all"||$.transaction_type===m,J=x==="all"||$.lead_source_id===x,K=_==="all"||$.client_type_id===_,re=!j||$.is_win;return ee&&Z&&J&&K&&re});return r?e.jsx(ke,{children:e.jsx(Oe,{className:"p-6 space-y-4",children:[1,2,3].map($=>e.jsx(Ks,{className:"h-16 w-full"},$))})}):e.jsxs(e.Fragment,{children:[e.jsxs(ke,{children:[e.jsx(Ot,{className:"pb-3",children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4",children:[e.jsxs(zt,{children:["Transactions (",O.length,")"]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Mn,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(Se,{placeholder:"Search...",value:d,onChange:$=>h($.target.value),className:"pl-8 w-[150px]"})]}),e.jsxs(Bs,{value:m,onValueChange:p,children:[e.jsx(Os,{className:"w-[100px]",children:e.jsx(Us,{placeholder:"Type"})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"all",children:"All Types"}),e.jsx(pt,{value:"buyer",children:"Buyer"}),e.jsx(pt,{value:"seller",children:"Seller"})]})]}),e.jsxs(Bs,{value:x,onValueChange:y,children:[e.jsx(Os,{className:"w-[130px]",children:e.jsx(Us,{placeholder:"Lead Source"})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"all",children:"All Sources"}),A==null?void 0:A.map($=>e.jsx(pt,{value:$.id,children:$.name},$.id))]})]}),e.jsxs(H,{variant:j?"default":"outline",size:"sm",onClick:()=>k(!j),children:[e.jsx(Bc,{className:"h-4 w-4 mr-1"}),"Wins"]})]})]})}),e.jsx(Oe,{children:O.length===0?e.jsx("p",{className:"text-center text-muted-foreground py-8",children:"No transactions found"}):D?e.jsx("div",{className:"space-y-3",children:O.map($=>e.jsxs(ke,{className:"p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"font-medium truncate",children:$.property_address}),$.is_win&&e.jsx(Bc,{className:"h-4 w-4 text-yellow-500 flex-shrink-0"})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[$.city,$.state?`, ${$.state}`:""]})]}),e.jsx(Xe,{variant:$.transaction_type==="buyer"?"default":"secondary",children:$.transaction_type})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 mt-3 text-sm",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Close Date: "}),MRe($.close_date)]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Price: "}),sd($.sale_price)]}),t&&$.commission_amount&&e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Commission: "}),sd($.commission_amount)]}),$.lead_source&&e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Source: "}),$.lead_source.name]}),$.contact&&e.jsxs("div",{className:"col-span-2",children:[e.jsx("span",{className:"text-muted-foreground",children:"Client: "}),$.contact.first_name," ",$.contact.last_name]}),n&&e.jsxs("div",{className:"col-span-2",children:[e.jsx("span",{className:"text-muted-foreground",children:"Agent: "}),n[$.owner_user_id]||"Unknown"]})]}),!a&&e.jsxs("div",{className:"flex justify-end gap-2 mt-3 pt-3 border-t",children:[e.jsx(H,{variant:"ghost",size:"sm",onClick:()=>l($),children:e.jsx(ou,{className:"h-4 w-4"})}),e.jsx(H,{variant:"ghost",size:"sm",onClick:()=>R($),children:e.jsx(ui,{className:"h-4 w-4"})}),e.jsx(H,{variant:"ghost",size:"sm",onClick:()=>c($.id),children:e.jsx(Dr,{className:"h-4 w-4 text-destructive"})})]})]},$.id))}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Vs,{children:[n&&e.jsx(At,{children:"Agent"}),e.jsx(At,{children:"Property"}),e.jsx(At,{children:"Type"}),e.jsx(At,{children:"Close Date"}),e.jsx(At,{children:"Sale Price"}),t&&e.jsx(At,{children:"Commission"}),e.jsx(At,{children:"Lead Source"}),e.jsx(At,{children:"Client"}),!a&&e.jsx(At,{className:"w-[50px]"})]})}),e.jsx(da,{children:O.map($=>{var ee;return e.jsxs(Vs,{children:[n&&e.jsx(gt,{className:"font-medium text-sm",children:n[$.owner_user_id]||"Unknown"}),e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[$.is_win&&e.jsx(Bc,{className:"h-4 w-4 text-yellow-500"}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:$.property_address}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[$.city,$.state?`, ${$.state}`:""]})]})]})}),e.jsx(gt,{children:e.jsx(Xe,{variant:$.transaction_type==="buyer"?"default":"secondary",children:$.transaction_type})}),e.jsx(gt,{children:MRe($.close_date)}),e.jsx(gt,{children:sd($.sale_price)}),t&&e.jsx(gt,{children:$.commission_amount?sd($.commission_amount):"-"}),e.jsx(gt,{children:((ee=$.lead_source)==null?void 0:ee.name)||"-"}),e.jsx(gt,{children:$.contact?`${$.contact.first_name} ${$.contact.last_name||""}`.trim():"-"}),!a&&e.jsx(gt,{children:e.jsxs(Xu,{children:[e.jsx(Qu,{asChild:!0,children:e.jsx(H,{variant:"ghost",size:"icon",children:e.jsx(Ay,{className:"h-4 w-4"})})}),e.jsxs(wu,{align:"end",children:[e.jsxs(di,{onClick:()=>l($),children:[e.jsx(ou,{className:"h-4 w-4 mr-2"}),"Edit"]}),e.jsxs(di,{onClick:()=>R($),children:[e.jsx(ui,{className:"h-4 w-4 mr-2"}),"Duplicate"]}),e.jsxs(di,{onClick:()=>c($.id),className:"text-destructive",children:[e.jsx(Dr,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})})]},$.id)})})]})})})]}),e.jsx(nxt,{open:!!i,onOpenChange:$=>!$&&l(null),transaction:i||void 0}),e.jsx(Rl,{open:!!o,onOpenChange:$=>!$&&c(null),children:e.jsxs(jl,{children:[e.jsxs(Nl,{children:[e.jsx(Sl,{children:"Delete Transaction?"}),e.jsx(Cl,{children:"This action cannot be undone. This will permanently delete this transaction."})]}),e.jsxs(kl,{children:[e.jsx(Tl,{children:"Cancel"}),e.jsx(ml,{onClick:z,className:"bg-destructive text-destructive-foreground",children:"Delete"})]})]})})]})}function axt({goals:s,stats:t,year:r,showCommission:n}){const a=new Date().getMonth()+1,i=new Date().getFullYear()===r?a:12,l=12-i,o=(p,x)=>{if(!x||x===0)return null;const y=Math.min(p/x*100,100),_=Math.max(x-p,0),b=l>0?_/l:0,j=i/12*100,k=y>=j?"ahead":y>=j*.8?"on-track":"behind";return{percent:y,remaining:_,pace:b,status:k}},c=o(t.totalTransactions,s.transactions_goal),d=o(t.totalVolume,s.volume_goal),h=n?o(t.totalCommission,s.gci_goal):null,m=p=>{switch(p){case"ahead":return e.jsxs(Xe,{className:"bg-green-500 text-white",children:[e.jsx(al,{className:"h-3 w-3 mr-1"}),"Ahead"]});case"on-track":return e.jsxs(Xe,{variant:"secondary",children:[e.jsx(g_,{className:"h-3 w-3 mr-1"}),"On Track"]});case"behind":return e.jsxs(Xe,{variant:"destructive",children:[e.jsx(K2,{className:"h-3 w-3 mr-1"}),"Behind"]});default:return null}};return!s.transactions_goal&&!s.volume_goal&&!s.gci_goal?null:e.jsxs(ke,{children:[e.jsx(Ot,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Wu,{className:"h-5 w-5 text-primary"}),e.jsxs(zt,{children:[r," Goals Progress"]})]})}),e.jsx(Oe,{children:e.jsxs("div",{className:"grid md:grid-cols-3 gap-6",children:[s.transactions_goal&&c&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm font-medium",children:"Transactions"}),m(c.status)]}),e.jsx(Mi,{value:c.percent,className:"h-2"}),e.jsxs("div",{className:"flex justify-between text-sm text-muted-foreground",children:[e.jsxs("span",{children:[t.totalTransactions," of ",s.transactions_goal]}),e.jsxs("span",{children:[Math.round(c.percent),"%"]})]}),c.remaining>0&&l>0&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Need ",Math.ceil(c.pace),"/month to hit goal"]})]}),s.volume_goal&&d&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm font-medium",children:"Volume"}),m(d.status)]}),e.jsx(Mi,{value:d.percent,className:"h-2"}),e.jsxs("div",{className:"flex justify-between text-sm text-muted-foreground",children:[e.jsxs("span",{children:[sd(t.totalVolume,!0)," of ",sd(s.volume_goal,!0)]}),e.jsxs("span",{children:[Math.round(d.percent),"%"]})]}),d.remaining>0&&l>0&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Need ",sd(d.pace,!0),"/month"]})]}),n&&s.gci_goal&&h&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm font-medium",children:"GCI"}),m(h.status)]}),e.jsx(Mi,{value:h.percent,className:"h-2"}),e.jsxs("div",{className:"flex justify-between text-sm text-muted-foreground",children:[e.jsxs("span",{children:[sd(t.totalCommission,!0)," of ",sd(s.gci_goal,!0)]}),e.jsxs("span",{children:[Math.round(h.percent),"%"]})]}),h.remaining>0&&l>0&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Need ",sd(h.pace,!0),"/month"]})]})]})})]})}const CDs={light:"",dark:".dark"},ixt=S.createContext(null);function oxt(){const s=S.useContext(ixt);if(!s)throw new Error("useChart must be used within a ");return s}const lxt=S.forwardRef(({id:s,className:t,children:r,config:n,...a},i)=>{const l=S.useId(),o=`chart-${s||l.replace(/:/g,"")}`;return e.jsx(ixt.Provider,{value:{config:n},children:e.jsxs("div",{"data-chart":o,ref:i,className:Ft("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",t),...a,children:[e.jsx(TDs,{id:o,config:n}),e.jsx(gP,{children:r})]})})});lxt.displayName="Chart";const TDs=({id:s,config:t})=>{const r=Object.entries(t).filter(([n,a])=>a.theme||a.color);return r.length?e.jsx("style",{dangerouslySetInnerHTML:{__html:Object.entries(CDs).map(([n,a])=>` ${a} [data-chart=${s}] { ${r.map(([i,l])=>{var c;const o=((c=l.theme)==null?void 0:c[n])||l.color;return o?` --color-${i}: ${o};`:null}).join(` `)} } `).join(` `)}}):null},cxt=S.forwardRef(({active:s,payload:t,className:r,indicator:n="dot",hideLabel:a=!1,hideIndicator:i=!1,label:l,labelFormatter:o,labelClassName:c,formatter:d,color:h,nameKey:m,labelKey:p},x)=>{const{config:y}=oxt(),_=S.useMemo(()=>{var A;if(a||!(t!=null&&t.length))return null;const[j]=t,k=`${p||j.dataKey||j.name||"value"}`,T=k4e(y,j,k),E=!p&&typeof l=="string"?((A=y[l])==null?void 0:A.label)||l:T==null?void 0:T.label;return o?e.jsx("div",{className:Ft("font-medium",c),children:o(E,t)}):E?e.jsx("div",{className:Ft("font-medium",c),children:E}):null},[l,o,t,a,c,y,p]);if(!s||!(t!=null&&t.length))return null;const b=t.length===1&&n!=="dot";return e.jsxs("div",{ref:x,className:Ft("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:[b?null:_,e.jsx("div",{className:"grid gap-1.5",children:t.map((j,k)=>{const T=`${m||j.name||j.dataKey||"value"}`,E=k4e(y,j,T),A=h||j.payload.fill||j.color;return e.jsx("div",{className:Ft("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:d&&(j==null?void 0:j.value)!==void 0&&j.name?d(j.value,j.name,j,k,j.payload):e.jsxs(e.Fragment,{children:[E!=null&&E.icon?e.jsx(E.icon,{}):!i&&e.jsx("div",{className:Ft("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":b&&n==="dashed"}),style:{"--color-bg":A,"--color-border":A}}),e.jsxs("div",{className:Ft("flex flex-1 justify-between leading-none",b?"items-end":"items-center"),children:[e.jsxs("div",{className:"grid gap-1.5",children:[b?_:null,e.jsx("span",{className:"text-muted-foreground",children:(E==null?void 0:E.label)||j.name})]}),j.value&&e.jsx("span",{className:"font-mono font-medium tabular-nums text-foreground",children:j.value.toLocaleString()})]})]})},j.dataKey)})})]})});cxt.displayName="ChartTooltip";const EDs=S.forwardRef(({className:s,hideIcon:t=!1,payload:r,verticalAlign:n="bottom",nameKey:a},i)=>{const{config:l}=oxt();return r!=null&&r.length?e.jsx("div",{ref:i,className:Ft("flex items-center justify-center gap-4",n==="top"?"pb-3":"pt-3",s),children:r.map(o=>{const c=`${a||o.dataKey||"value"}`,d=k4e(l,o,c);return e.jsxs("div",{className:Ft("flex items-center gap-1.5 [&>svg]:h-3 [&>svg]:w-3 [&>svg]:text-muted-foreground"),children:[d!=null&&d.icon&&!t?e.jsx(d.icon,{}):e.jsx("div",{className:"h-2 w-2 shrink-0 rounded-[2px]",style:{backgroundColor:o.color}}),d==null?void 0:d.label]},o.value)})}):null});EDs.displayName="ChartLegend";function k4e(s,t,r){if(typeof t!="object"||t===null)return;const n="payload"in t&&typeof t.payload=="object"&&t.payload!==null?t.payload:void 0;let a=r;return r in t&&typeof t[r]=="string"?a=t[r]:n&&r in n&&typeof n[r]=="string"&&(a=n[r]),a in s?s[a]:s[r]}const Kq=["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 hMe({stats:s,year:t}){const r=s.transactionsByMonth.some(a=>a.count>0),n=s.leadSourceBreakdown.length>0;return!r&&!n?e.jsx(ke,{children:e.jsx(Oe,{className:"py-12 text-center text-muted-foreground",children:"Add transactions to see your performance charts"})}):e.jsxs("div",{className:"grid gap-6",children:[r&&e.jsxs(ke,{className:"overflow-hidden",children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-base",children:"Transactions by Month"})}),e.jsx(Oe,{className:"overflow-hidden",children:e.jsx(lxt,{config:{count:{label:"Transactions",color:"hsl(var(--primary))"}},className:"h-[250px]",children:e.jsx(gP,{width:"100%",height:"100%",children:e.jsxs(Mgt,{data:s.transactionsByMonth,margin:{top:5,right:10,left:0,bottom:5},children:[e.jsx(fgt,{strokeDasharray:"3 3",className:"stroke-muted"}),e.jsx(MA,{dataKey:"month",tick:{fontSize:11},className:"fill-muted-foreground",interval:0}),e.jsx(IA,{allowDecimals:!1,tick:{fontSize:12},className:"fill-muted-foreground",width:30}),e.jsx(Zg,{content:e.jsx(cxt,{})}),e.jsx(uj,{dataKey:"count",fill:"hsl(var(--primary))",radius:[4,4,0,0],name:"Transactions"})]})})})})]}),n&&e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-base",children:"Lead Sources"})}),e.jsxs(Oe,{children:[e.jsx("div",{className:"h-[250px]",children:e.jsx(gP,{width:"100%",height:"100%",children:e.jsxs(Igt,{children:[e.jsx(Z_,{data:s.leadSourceBreakdown,dataKey:"count",nameKey:"name",cx:"50%",cy:"50%",outerRadius:80,label:({name:a,percent:i})=>i>.05?`${a} (${(i*100).toFixed(0)}%)`:"",labelLine:!1,children:s.leadSourceBreakdown.map((a,i)=>e.jsx(Cz,{fill:Kq[i%Kq.length]},`cell-${i}`))}),e.jsx(Zg,{formatter:(a,i)=>[`${a} deals`,i]})]})})}),e.jsx("div",{className:"flex flex-wrap gap-2 mt-2 justify-center",children:s.leadSourceBreakdown.slice(0,6).map((a,i)=>e.jsxs("div",{className:"flex items-center gap-1 text-xs",children:[e.jsx("div",{className:"w-3 h-3 rounded-sm",style:{backgroundColor:Kq[i%Kq.length]}}),e.jsx("span",{className:"text-muted-foreground",children:a.name})]},a.name))})]})]})]})}function ADs(s){if(!s||!s.trim())return null;const t=s.trim(),r=["yyyy-MM-dd","M/d/yyyy","MM/dd/yyyy","M-d-yyyy","MM-dd-yyyy","MM/dd/yy","M/d/yy"];for(const n of r)try{const a=g5e(t,n,new Date);if(eNe(a))return As(a,"yyyy-MM-dd")}catch{}try{const n=new Date(t);if(eNe(n))return As(n,"yyyy-MM-dd")}catch{}return null}const MDs=["property_address","city","state","zip","transaction_type","close_date","sale_price","commission_amount","lead_source","client_type","is_win","notes"];function IDs({open:s,onOpenChange:t}){const[r,n]=S.useState([]),[a,i]=S.useState(!1),[l,o]=S.useState(0),{data:c}=v8(),{data:d}=R0(),h=exe(),m=()=>{const j=MDs.join(","),k=["123 Main St","Dallas","TX","75001","buyer","2024-06-15","450000","13500","Referral","Past Client","yes","Great transaction!"].join(","),T=`${j} ${k}`,E=new Blob([T],{type:"text/csv"}),A=URL.createObjectURL(E),D=document.createElement("a");D.href=A,D.download="transaction-import-template.csv",D.click(),URL.revokeObjectURL(A)},p=j=>{const k=j.split(` `).filter(E=>E.trim());if(k.length<2)return[];const T=k[0].split(",").map(E=>E.trim().toLowerCase().replace(/['"]/g,""));return k.slice(1).map((E,A)=>{var ce,ne,le,be;const D=[];let R="",z=!1;for(const fe of E)fe==='"'?z=!z:fe===","&&!z?(D.push(R.trim()),R=""):R+=fe;D.push(R.trim());const O=fe=>{var ve;const je=T.indexOf(fe);return je>=0?(ve=D[je])==null?void 0:ve.replace(/^["']|["']$/g,"").trim():""},$=(ce=O("transaction_type"))==null?void 0:ce.toLowerCase(),ee=(ne=O("sale_price"))==null?void 0:ne.replace(/[$,]/g,""),Z=(le=O("commission_amount"))==null?void 0:le.replace(/[$,]/g,""),J=(be=O("is_win"))==null?void 0:be.toLowerCase(),K=O("close_date"),re=ADs(K);let ie;return O("property_address")?["buyer","seller"].includes($)?re?(!ee||isNaN(Number(ee)))&&(ie="Invalid sale price"):ie=`Invalid date format: "${K}" - use MM/DD/YYYY or YYYY-MM-DD`:ie='Transaction type must be "buyer" or "seller"':ie="Missing property address",{property_address:O("property_address"),city:O("city"),state:O("state"),zip:O("zip"),transaction_type:$==="seller"?"seller":"buyer",close_date:re||"",sale_price:Number(ee)||0,commission_amount:Z?Number(Z):null,lead_source_name:O("lead_source"),client_type_name:O("client_type"),is_win:["yes","true","1"].includes(J),notes:O("notes"),error:ie}})},x=j=>{var E;const k=(E=j.target.files)==null?void 0:E[0];if(!k)return;const T=new FileReader;T.onload=A=>{var z;const D=(z=A.target)==null?void 0:z.result,R=p(D);n(R)},T.readAsText(k)},y=async()=>{const j=r.filter(E=>!E.error);if(j.length===0){he.error("No valid transactions to import");return}i(!0),o(0);let k=0,T=0;for(let E=0;Ez.name.toLowerCase()===A.lead_source_name.toLowerCase()),R=d==null?void 0:d.find(z=>z.name.toLowerCase()===A.client_type_name.toLowerCase());await h.mutateAsync({property_address:A.property_address,city:A.city||null,state:A.state||null,zip:A.zip||null,transaction_type:A.transaction_type,close_date:A.close_date,sale_price:A.sale_price,commission_amount:A.commission_amount,lead_source_id:(D==null?void 0:D.id)||null,client_type_id:(R==null?void 0:R.id)||null,contact_id:null,notes:A.notes||null,is_win:A.is_win}),k++}catch(D){T++,console.error("Failed to import transaction:",D)}o(Math.round((E+1)/j.length*100))}i(!1),k>0&&he.success(`Imported ${k} transaction${k>1?"s":""}`),T>0&&he.error(`Failed to import ${T} transaction${T>1?"s":""}`),n([]),t(!1)},_=r.filter(j=>!j.error).length,b=r.filter(j=>j.error).length;return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-2xl max-h-[90vh]",children:[e.jsxs(Cs,{children:[e.jsx(Ns,{children:"Import Transactions"}),e.jsx(nn,{children:"Upload a CSV file with your past transactions"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between p-3 border rounded-lg bg-muted/50",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Download Template"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Get a CSV template with the correct format"})]}),e.jsxs(H,{variant:"outline",onClick:m,children:[e.jsx(hi,{className:"h-4 w-4 mr-2"}),"Template"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"csv-file",children:"Upload CSV File"}),e.jsx(Se,{id:"csv-file",type:"file",accept:".csv",onChange:x})]}),r.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Xe,{variant:"outline",children:[r.length," rows found"]}),_>0&&e.jsxs(Xe,{className:"bg-green-500 text-white",children:[e.jsx(va,{className:"h-3 w-3 mr-1"}),_," valid"]}),b>0&&e.jsxs(Xe,{variant:"destructive",children:[e.jsx(wo,{className:"h-3 w-3 mr-1"}),b," errors"]})]}),e.jsx(Ci,{className:"h-[200px] border rounded-lg",children:e.jsxs("div",{className:"p-2 space-y-2",children:[r.slice(0,10).map((j,k)=>e.jsxs("div",{className:`p-2 rounded text-sm ${j.error?"bg-destructive/10":"bg-muted/50"}`,children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"font-medium",children:j.property_address||"(no address)"}),e.jsx(Xe,{variant:j.transaction_type==="buyer"?"default":"secondary",children:j.transaction_type})]}),e.jsxs("div",{className:"text-muted-foreground",children:[j.close_date," • $",j.sale_price.toLocaleString()]}),j.error&&e.jsx(jEe,{variant:"destructive",className:"mt-1 py-1",children:e.jsx(NEe,{className:"text-xs",children:j.error})})]},k)),r.length>10&&e.jsxs("p",{className:"text-center text-sm text-muted-foreground",children:["...and ",r.length-10," more"]})]})}),a&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"w-full bg-muted rounded-full h-2",children:e.jsx("div",{className:"bg-primary h-2 rounded-full transition-all",style:{width:`${l}%`}})}),e.jsxs("p",{className:"text-sm text-center text-muted-foreground",children:["Importing... ",l,"%"]})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(H,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(H,{onClick:y,disabled:_===0||a,children:[e.jsx(Ea,{className:"h-4 w-4 mr-2"}),"Import ",_," Transaction",_!==1?"s":""]})]})]})]})})}const PDs=yj({transactions_goal:ZF().min(0).optional(),volume_goal:ZF().min(0).optional(),gci_goal:ZF().min(0).optional()});function LDs({open:s,onOpenChange:t,year:r,existingGoals:n}){const a=WHt(),{data:i}=txe(),l=(i==null?void 0:i.show_commission)??!0,o=qge({resolver:Vge(PDs),defaultValues:{transactions_goal:void 0,volume_goal:void 0,gci_goal:void 0}});S.useEffect(()=>{n?o.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}):o.reset({transactions_goal:void 0,volume_goal:void 0,gci_goal:void 0})},[n,o,s]);const c=async d=>{await a.mutateAsync({year:r,transactions_goal:d.transactions_goal??null,volume_goal:d.volume_goal??null,gci_goal:l?d.gci_goal??null:null}),t(!1)};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-md",children:[e.jsxs(Cs,{children:[e.jsxs(Ns,{children:[r," Goals"]}),e.jsx(nn,{children:"Set your annual targets to track your progress throughout the year."})]}),e.jsx(Hge,{...o,children:e.jsxs("form",{onSubmit:o.handleSubmit(c),className:"space-y-4",children:[e.jsx(iu,{control:o.control,name:"transactions_goal",render:({field:d})=>e.jsxs(Ud,{children:[e.jsx(qd,{children:"Transactions Goal"}),e.jsx(Vd,{children:e.jsx(Se,{type:"number",placeholder:"e.g., 24",...d,value:d.value??"",onChange:h=>d.onChange(h.target.value?Number(h.target.value):void 0)})}),e.jsx(jue,{children:"Total number of deals you want to close"}),e.jsx(mg,{})]})}),e.jsx(iu,{control:o.control,name:"volume_goal",render:({field:d})=>e.jsxs(Ud,{children:[e.jsx(qd,{children:"Volume Goal ($)"}),e.jsx(Vd,{children:e.jsx(Se,{type:"number",placeholder:"e.g., 5000000",...d,value:d.value??"",onChange:h=>d.onChange(h.target.value?Number(h.target.value):void 0)})}),e.jsx(jue,{children:"Total sales volume you want to achieve"}),e.jsx(mg,{})]})}),l&&e.jsx(iu,{control:o.control,name:"gci_goal",render:({field:d})=>e.jsxs(Ud,{children:[e.jsx(qd,{children:"GCI Goal ($)"}),e.jsx(Vd,{children:e.jsx(Se,{type:"number",placeholder:"e.g., 150000",...d,value:d.value??"",onChange:h=>d.onChange(h.target.value?Number(h.target.value):void 0)})}),e.jsx(jue,{children:"Gross commission income target"}),e.jsx(mg,{})]})}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(H,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(H,{type:"submit",disabled:a.isPending,children:"Save Goals"})]})]})})]})})}function mMe({transactions:s,isLoading:t}){const r=S.useRef(null),n=S.useRef(null),a=S.useRef([]),i=S.useRef(null),{isAdmin:l}=Ms(),[o,c]=S.useState(""),[d,h]=S.useState(!0),[m,p]=S.useState(0),[x,y]=S.useState(!1),_=s.filter(j=>j.latitude!=null&&j.longitude!=null),b=s.filter(j=>j.latitude==null||j.longitude==null);return S.useEffect(()=>{(async()=>{h(!0);try{const{data:k}=await V.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();k!=null&&k.value&&c(k.value)}catch(k){console.error("Error fetching mapbox token:",k)}h(!1)})()},[]),S.useEffect(()=>{if(!o||b.length===0||x)return;(async()=>{var T;y(!0);let k=0;for(const E of b){const A=[E.property_address,E.city,E.state,E.zip].filter(Boolean).join(", ");if(A)try{const R=await(await fetch(`https://api.mapbox.com/geocoding/v5/mapbox.places/${encodeURIComponent(A)}.json?access_token=${o}&limit=1`)).json();if((T=R.features)!=null&&T[0]){const[z,O]=R.features[0].center;await V.from("scorecard_transactions").update({latitude:O,longitude:z}).eq("id",E.id),E.latitude=O,E.longitude=z,k++}}catch(D){console.error("Geocode error:",D)}}p(k),y(!1)})()},[o,s]),S.useEffect(()=>{if(!r.current||!o||n.current)return;fc.accessToken=o;const j=s.filter(E=>E.latitude!=null&&E.longitude!=null);let k=[-98.5795,39.8283],T=4;if(j.length>0){const E=j.reduce((D,R)=>D+R.longitude,0)/j.length,A=j.reduce((D,R)=>D+R.latitude,0)/j.length;k=[E,A],T=j.length===1?12:10}return n.current=new fc.Map({container:r.current,style:"mapbox://styles/mapbox/light-v11",zoom:T,center:k}),n.current.addControl(new fc.NavigationControl,"top-right"),()=>{var E;(E=n.current)==null||E.remove(),n.current=null}},[o]),S.useEffect(()=>{var k;if(!n.current||!o)return;a.current.forEach(T=>T.remove()),a.current=[],(k=i.current)==null||k.remove();const j=s.filter(T=>T.latitude!=null&&T.longitude!=null);if(j.forEach(T=>{var O;const E=T.transaction_type==="buyer",A=E?"#3B82F6":"#10B981",D=document.createElement("div");D.className="cursor-pointer",D.innerHTML=`
${E?'':''}
`;const R=new fc.Popup({offset:25,closeButton:!0}).setHTML(`
${T.property_address}
${T.city?`
${T.city}${T.state?", "+T.state:""} ${T.zip||""}
`:""}
${E?"Buyer":"Seller"} $${Number(T.sale_price).toLocaleString()}
Closed: ${Tc(T.close_date).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})} ${(O=T.lead_source)!=null&&O.name?" · "+T.lead_source.name:""}
${T.contact?`
Client: ${T.contact.first_name} ${T.contact.last_name||""}
`:""}
`),z=new fc.Marker(D).setLngLat([T.longitude,T.latitude]).setPopup(R).addTo(n.current);a.current.push(z)}),j.length>1){const T=new fc.LngLatBounds;j.forEach(E=>T.extend([E.longitude,E.latitude])),n.current.fitBounds(T,{padding:60,maxZoom:13})}else j.length===1&&n.current.flyTo({center:[j[0].longitude,j[0].latitude],zoom:12})},[s,o,x]),d||t?e.jsx(ke,{children:e.jsx(Oe,{className:"flex items-center justify-center h-[50vh]",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary"})})}):o?s.length===0?e.jsx(ke,{children:e.jsxs(Oe,{className:"flex flex-col items-center justify-center h-[50vh] text-center gap-3",children:[e.jsx(Qa,{className:"h-12 w-12 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold",children:"No Transactions Yet"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Add transactions to see them plotted on the map."})]})]})}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-4 text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-4 h-4 rounded-full border-2 border-white shadow",style:{background:"#3B82F6"}}),e.jsx("span",{children:"Buyer"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-4 h-4 rounded-full border-2 border-white shadow",style:{background:"#10B981"}}),e.jsx("span",{children:"Seller"})]}),e.jsxs("span",{className:"text-muted-foreground ml-auto text-xs",children:[_.length," of ",s.length," mapped",x&&" · Geocoding..."]})]}),e.jsx("div",{ref:r,className:"w-full h-[55vh] rounded-lg shadow-lg border"})]}):e.jsx(ke,{children:e.jsxs(Oe,{className:"flex flex-col items-center justify-center h-[50vh] text-center gap-3",children:[e.jsx(wo,{className:"h-12 w-12 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold",children:"Map Not Configured"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:l?"Set up your Mapbox token in the Popby Map to enable maps across the platform.":"The map feature has not been configured yet. Please contact your administrator."})]})]})})}const dxt=()=>{const{data:s}=sv();return yt({queryKey:["team-scorecard-members",s==null?void 0:s.teamId],queryFn:async()=>{const{data:t,error:r}=await V.from("team_members").select("user_id").eq("team_id",s.teamId);if(r)throw r;const n=t.map(l=>l.user_id),{data:a,error:i}=await V.from("profiles").select("id, name, email, avatar_url").in("id",n);if(i)throw i;return a||[]},enabled:!!(s!=null&&s.teamId)&&(s==null?void 0:s.role)==="team_leader"})},DDs=s=>{const{data:t}=sv(),{data:r}=dxt();return yt({queryKey:["team-scorecard-transactions",t==null?void 0:t.teamId,s],queryFn:async()=>{const n=r.map(l=>l.id),{data:a,error:i}=await V.from("scorecard_transactions").select(` *, lead_source:lead_sources(id, name), client_type:relationship_types(id, name), contact:innercircle_contacts(id, first_name, last_name) `).in("owner_user_id",n).gte("close_date",`${s}-01-01`).lte("close_date",`${s}-12-31`).order("close_date",{ascending:!1});if(i)throw i;return a},enabled:!!r&&r.length>0})};function RDs(s,t){const r=t.filter(i=>i.owner_user_id===s.id),n=r.reduce((i,l)=>i+Number(l.sale_price),0),a=r.reduce((i,l)=>i+(Number(l.commission_amount)||0),0);return{member:s,totalTransactions:r.length,buyerCount:r.filter(i=>i.transaction_type==="buyer").length,sellerCount:r.filter(i=>i.transaction_type==="seller").length,totalVolume:n,averagePrice:r.length>0?n/r.length:0,totalGCI:a}}function ODs(s,t){return s?s.split(" ").map(r=>r[0]).join("").toUpperCase().slice(0,2):t[0].toUpperCase()}function FDs({year:s}){var p;const{data:t,isLoading:r}=dxt(),{data:n,isLoading:a}=DDs(s),i=Fr(),l=r||a,{aggregate:o,memberStats:c,topPerformer:d,agentNameMap:h,teamChartStats:m}=S.useMemo(()=>{if(!t||!n)return{aggregate:null,memberStats:[],topPerformer:null,agentNameMap:{},teamChartStats:null};const x=t.map($=>RDs($,n));x.sort(($,ee)=>ee.totalVolume-$.totalVolume);const y={};t.forEach($=>{y[$.id]=$.name||$.email});const _=n.length,b=n.reduce(($,ee)=>$+Number(ee.sale_price),0),j=n.reduce(($,ee)=>$+(Number(ee.commission_amount)||0),0),k=n.filter($=>$.transaction_type==="buyer").length,T=n.filter($=>$.transaction_type==="seller").length,E={};n.forEach($=>{var Z;const ee=((Z=$.lead_source)==null?void 0:Z.name)||"Unknown";E[ee]=(E[ee]||0)+1});const A=Object.entries(E).sort(($,ee)=>ee[1]-$[1])[0],D={};n.forEach($=>{const ee=Tc($.close_date).toLocaleString("default",{month:"short"});D[ee]=(D[ee]||0)+1});const z=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"].map($=>({month:$,count:D[$]||0})),O=Object.entries(E).map(([$,ee])=>({name:$,count:ee})).sort(($,ee)=>ee.count-$.count);return{aggregate:{totalTxns:_,buyerCount:k,sellerCount:T,totalVolume:b,avgPrice:_>0?b/_:0,totalGCI:j,topSource:A?{name:A[0],count:A[1]}:null,memberCount:t.length},memberStats:x,topPerformer:x[0]||null,agentNameMap:y,teamChartStats:{transactionsByMonth:z,leadSourceBreakdown:O}}},[t,n]);return l?e.jsxs("div",{className:"space-y-6",children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[1,2,3,4].map(x=>e.jsx(Ks,{className:"h-24"},x))}),e.jsx(Ks,{className:"h-64"})]}):!o||c.length===0?e.jsx(ke,{className:"py-12",children:e.jsxs(Oe,{className:"text-center space-y-2",children:[e.jsx(Ar,{className:"h-10 w-10 mx-auto text-muted-foreground"}),e.jsx("h3",{className:"text-lg font-semibold",children:"No Team Data"}),e.jsxs("p",{className:"text-muted-foreground",children:["No scorecard transactions found for your team members in ",s,"."]})]})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-4",children:[e.jsx(ke,{children:e.jsxs(Oe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Ar,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Members"})]}),e.jsx("p",{className:"text-2xl font-bold",children:o.memberCount})]})}),e.jsx(ke,{children:e.jsxs(Oe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Fn,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Team Transactions"})]}),e.jsx("p",{className:"text-2xl font-bold",children:o.totalTxns}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[o.buyerCount,"B / ",o.sellerCount,"S"]})]})}),e.jsx(ke,{children:e.jsxs(Oe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(oc,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Team Volume"})]}),e.jsx("p",{className:"text-2xl font-bold",children:sd(o.totalVolume,!0)})]})}),e.jsx(ke,{children:e.jsxs(Oe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(al,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Avg Price"})]}),e.jsx("p",{className:"text-2xl font-bold",children:sd(o.avgPrice,!0)})]})}),e.jsx(ke,{children:e.jsxs(Oe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(oc,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Team GCI"})]}),e.jsx("p",{className:"text-2xl font-bold",children:sd(o.totalGCI,!0)})]})}),e.jsx(ke,{children:e.jsxs(Oe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Bc,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Top Source"})]}),e.jsx("p",{className:"text-lg font-bold truncate",children:((p=o.topSource)==null?void 0:p.name)||"-"}),o.topSource&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[o.topSource.count," deals"]})]})})]}),d&&d.totalTransactions>0&&e.jsx(ke,{className:"border-primary/30 bg-primary/5",children:e.jsxs(Oe,{className:"pt-4 flex items-center gap-4",children:[e.jsx("div",{className:"flex items-center justify-center h-10 w-10 rounded-full bg-primary/10",children:e.jsx(To,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("p",{className:"text-sm font-medium text-muted-foreground",children:["Top Performer — ",s]}),e.jsx("p",{className:"text-lg font-bold",children:d.member.name||d.member.email})]}),e.jsxs("div",{className:"text-right",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:[d.totalTransactions," deals"]}),e.jsx("p",{className:"font-semibold",children:sd(d.totalVolume,!0)})]})]})}),e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-lg",children:"Member Performance"})}),e.jsx(Oe,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Vs,{children:[e.jsx(At,{children:"Agent"}),e.jsx(At,{className:"text-center",children:"Transactions"}),e.jsx(At,{className:"text-center",children:"B / S"}),e.jsx(At,{className:"text-right",children:"Volume"}),e.jsx(At,{className:"text-right",children:"Avg Price"}),e.jsx(At,{className:"text-right",children:"GCI"}),e.jsx(At,{className:"text-right"})]})}),e.jsx(da,{children:c.map((x,y)=>e.jsxs(Vs,{children:[e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"relative",children:[y===0&&x.totalTransactions>0&&e.jsx(To,{className:"absolute -top-2 -right-2 h-3.5 w-3.5 text-amber-500"}),e.jsxs(Un,{className:"h-8 w-8",children:[e.jsx(Ka,{src:x.member.avatar_url||void 0}),e.jsx(qn,{className:"text-xs",children:ODs(x.member.name,x.member.email)})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:x.member.name||x.member.email}),x.member.name&&e.jsx("p",{className:"text-xs text-muted-foreground",children:x.member.email})]})]})}),e.jsx(gt,{className:"text-center font-semibold",children:x.totalTransactions}),e.jsxs(gt,{className:"text-center text-sm",children:[x.buyerCount," / ",x.sellerCount]}),e.jsx(gt,{className:"text-right font-medium",children:sd(x.totalVolume,!0)}),e.jsx(gt,{className:"text-right text-sm",children:sd(x.averagePrice,!0)}),e.jsx(gt,{className:"text-right font-medium",children:sd(x.totalGCI,!0)}),e.jsx(gt,{className:"text-right",children:e.jsx(H,{variant:"ghost",size:"sm",onClick:()=>i(`/mission-control/scorecard/${x.member.id}`),children:e.jsx(Bn,{className:"h-4 w-4"})})})]},x.member.id))})]})})})]}),e.jsxs(ta,{defaultValue:"transactions",className:"space-y-4",children:[e.jsxs(Qn,{children:[e.jsxs(ts,{value:"transactions",children:[e.jsx(Vf,{className:"h-4 w-4 mr-1"}),"All Transactions"]}),e.jsxs(ts,{value:"charts",children:[e.jsx(Bo,{className:"h-4 w-4 mr-1"}),"Charts"]}),e.jsxs(ts,{value:"map",children:[e.jsx(Qa,{className:"h-4 w-4 mr-1"}),"Map"]})]}),e.jsx(cs,{value:"transactions",children:e.jsx(uMe,{transactions:n||[],showCommission:!0,isLoading:a,agentNameMap:h,readOnly:!0})}),e.jsx(cs,{value:"charts",children:m&&e.jsx(hMe,{stats:m,year:s})}),e.jsx(cs,{value:"map",children:e.jsx(mMe,{transactions:n||[],isLoading:a})})]})]})}const uxt=new Date().getFullYear(),YHe=Array.from({length:10},(s,t)=>uxt-t);function BDs(){var $;const[s,t]=S.useState(uxt),[r,n]=S.useState(!1),[a,i]=S.useState(!1),[l,o]=S.useState(!1),[c,d]=S.useState(!1),[h,m]=S.useState("my"),{data:p}=sv(),x=(p==null?void 0:p.role)==="team_leader",{data:y,isLoading:_}=jTe(s),{yearStats:b,lifetimeStats:j,isLoading:k,showCommission:T}=Eot(s),{data:E,isLoading:A}=Tot(s),{data:D}=txe(),R=KHt(),z=()=>{if(!y||y.length===0)return;const ee=["Property Address","City","State","Zip","Transaction Type","Close Date","Sale Price",...T?["Commission"]:[],"Lead Source","Client Type","Contact Name","Is Win","Notes"],Z=y.map(ce=>{var ne,le;return[ce.property_address,ce.city||"",ce.state||"",ce.zip||"",ce.transaction_type,ce.close_date,ce.sale_price,...T?[ce.commission_amount||""]:[],((ne=ce.lead_source)==null?void 0:ne.name)||"",((le=ce.client_type)==null?void 0:le.name)||"",ce.contact?`${ce.contact.first_name} ${ce.contact.last_name||""}`.trim():"",ce.is_win?"Yes":"No",ce.notes||""]}),J=[ee,...Z].map(ce=>ce.map(ne=>`"${String(ne).replace(/"/g,'""')}"`).join(",")).join(` `),K=new Blob([J],{type:"text/csv"}),re=URL.createObjectURL(K),ie=document.createElement("a");ie.href=re,ie.download=`transactions-${s}.csv`,ie.click(),URL.revokeObjectURL(re)},O=!y||y.length===0;return e.jsxs(Ss,{title:"Scorecard",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Scorecard"}),e.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide px-1.5 py-0.5 rounded border border-amber-500/50 text-amber-600 dark:text-amber-400 bg-amber-500/10",children:"Beta"})]}),x&&e.jsxs("div",{className:"flex items-center gap-1 bg-muted rounded-lg p-1 w-fit",children:[e.jsx(H,{variant:h==="my"?"default":"ghost",size:"sm",onClick:()=>m("my"),className:"h-8",children:"My Scorecard"}),e.jsxs(H,{variant:h==="team"?"default":"ghost",size:"sm",onClick:()=>m("team"),className:"h-8",children:[e.jsx(Ar,{className:"h-4 w-4 mr-1.5"}),"Team"]})]}),h==="team"&&x?e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground",children:"Team Performance"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Aggregate stats and member comparison"})]}),e.jsxs(Bs,{value:String(s),onValueChange:ee=>t(Number(ee)),children:[e.jsx(Os,{className:"w-[120px]",children:e.jsx(Us,{})}),e.jsx(Fs,{children:YHe.map(ee=>e.jsx(pt,{value:String(ee),children:ee},ee))})]})]}),e.jsx(FDs,{year:s})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Business Scorecard"}),e.jsx("p",{className:"text-muted-foreground",children:"Track your transactions, goals, and performance"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(Bs,{value:String(s),onValueChange:ee=>t(Number(ee)),children:[e.jsx(Os,{className:"w-[120px]",children:e.jsx(Us,{})}),e.jsx(Fs,{children:YHe.map(ee=>e.jsx(pt,{value:String(ee),children:ee},ee))})]}),e.jsx(H,{variant:"outline",size:"icon",onClick:()=>d(!c),children:e.jsx(Go,{className:"h-4 w-4"})})]})]}),c&&e.jsxs(ke,{children:[e.jsx(Ot,{className:"pb-3",children:e.jsx(zt,{className:"text-lg",children:"Settings"})}),e.jsx(Oe,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(ue,{children:"Show Commission"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Display commission fields and include in stats"})]}),e.jsx(Or,{checked:(D==null?void 0:D.show_commission)??!0,onCheckedChange:ee=>R.mutate({show_commission:ee})})]})})]}),O&&!_?e.jsx(ke,{className:"py-12",children:e.jsxs(Oe,{className:"text-center space-y-4",children:[e.jsx("div",{className:"w-16 h-16 mx-auto rounded-full bg-primary/10 flex items-center justify-center",children:e.jsx(Bo,{className:"h-8 w-8 text-primary"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold",children:"Start Tracking Your Success"}),e.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."})]}),e.jsxs("div",{className:"flex flex-wrap justify-center gap-2 pt-2",children:[e.jsxs(H,{onClick:()=>n(!0),children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Add Your First Transaction"]}),e.jsxs(H,{variant:"outline",onClick:()=>i(!0),children:[e.jsx(Ea,{className:"h-4 w-4 mr-2"}),"Import CSV"]})]}),e.jsxs("div",{className:"pt-4 border-t mt-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:"Need help formatting your data?"}),e.jsx(H,{variant:"link",className:"h-auto p-0",asChild:!0,children:e.jsxs("a",{href:"/templates/transaction-import-template.csv",download:!0,children:[e.jsx(hi,{className:"h-4 w-4 mr-2"}),"Download CSV Template"]})})]})]})}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(H,{onClick:()=>n(!0),children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Add Transaction"]}),e.jsxs(H,{variant:"outline",onClick:()=>o(!0),children:[e.jsx(Wu,{className:"h-4 w-4 mr-2"}),"Set Goals"]}),e.jsxs(H,{variant:"outline",onClick:()=>i(!0),children:[e.jsx(Ea,{className:"h-4 w-4 mr-2"}),"Import"]}),e.jsxs(H,{variant:"outline",onClick:z,disabled:O,children:[e.jsx(hi,{className:"h-4 w-4 mr-2"}),"Export"]}),e.jsx(H,{variant:"ghost",size:"sm",asChild:!0,children:e.jsxs("a",{href:"/templates/transaction-import-template.csv",download:!0,children:[e.jsx(hi,{className:"h-4 w-4 mr-2"}),"CSV Template"]})})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-7 gap-4",children:[e.jsx(ke,{children:e.jsxs(Oe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Fn,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Transactions"})]}),e.jsx("p",{className:"text-2xl font-bold",children:b.totalTransactions}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[j.totalTransactions," lifetime"]})]})}),e.jsx(ke,{children:e.jsxs(Oe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Ar,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Buyer/Seller"})]}),e.jsxs("p",{className:"text-2xl font-bold",children:[b.buyerCount,"/",b.sellerCount]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"B/S split"})]})}),e.jsx(ke,{children:e.jsxs(Oe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(oc,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Volume"})]}),e.jsx("p",{className:"text-2xl font-bold",children:sd(b.totalVolume,!0)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[sd(j.totalVolume,!0)," lifetime"]})]})}),e.jsx(ke,{children:e.jsxs(Oe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(al,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Avg Price"})]}),e.jsx("p",{className:"text-2xl font-bold",children:sd(b.averagePrice,!0)})]})}),e.jsx(ke,{children:e.jsxs(Oe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Bc,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Top Source"})]}),e.jsx("p",{className:"text-lg font-bold truncate",children:(($=b.topLeadSource)==null?void 0:$.name)||"-"}),b.topLeadSource&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[b.topLeadSource.count," deals"]})]})}),T&&e.jsx(ke,{children:e.jsxs(Oe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(oc,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"GCI"})]}),e.jsx("p",{className:"text-2xl font-bold",children:sd(b.totalCommission,!0)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[sd(j.totalCommission,!0)," lifetime"]})]})}),T&&b.totalNetToAgent>0&&b.totalNetToAgent!==b.totalCommission&&e.jsx(ke,{children:e.jsxs(Oe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-teal-600 dark:text-teal-400 mb-1",children:[e.jsx(oc,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Net to Agent"})]}),e.jsx("p",{className:"text-2xl font-bold text-teal-600 dark:text-teal-400",children:sd(b.totalNetToAgent,!0)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[sd(j.totalNetToAgent,!0)," lifetime"]})]})})]}),E&&e.jsx(axt,{goals:E,stats:b,year:s,showCommission:T}),e.jsxs(ta,{defaultValue:"transactions",className:"space-y-4",children:[e.jsxs(Qn,{children:[e.jsx(ts,{value:"transactions",children:"Transactions"}),e.jsx(ts,{value:"charts",children:"Charts"}),e.jsxs(ts,{value:"map",children:[e.jsx(Qa,{className:"h-4 w-4 mr-1"}),"Map"]})]}),e.jsx(cs,{value:"transactions",children:e.jsx(uMe,{transactions:y||[],showCommission:T,isLoading:_})}),e.jsx(cs,{value:"charts",children:e.jsx(hMe,{stats:b,year:s})}),e.jsx(cs,{value:"map",children:e.jsx(mMe,{transactions:y||[],isLoading:_})})]})]})]})]}),e.jsx(nxt,{open:r,onOpenChange:n}),e.jsx(IDs,{open:a,onOpenChange:i}),e.jsx(LDs,{open:l,onOpenChange:o,year:s,existingGoals:E})]})}function hxt({open:s,onOpenChange:t,listingId:r,listingSlug:n,listingTitle:a}){const{user:i}=Ms(),[l,o]=S.useState(null),[c,d]=S.useState(!1),[h,m]=S.useState(!1);S.useEffect(()=>{(async()=>{if(!(!s||!i)){d(!0);try{const{data:b,error:j}=await V.from("listing_shares").select("id, share_token, click_count, lead_count").eq("listing_id",r).eq("sharing_agent_id",i.id).order("created_at",{ascending:!1}).limit(1).maybeSingle();if(j)throw j;if(b&&b.share_token)o(b);else if(b&&!b.share_token){const{data:k,error:T}=await V.from("listing_shares").update({share_type:"referral_link"}).eq("id",b.id).select("id, share_token, click_count, lead_count").single();if(T)throw T;o(k)}else{const{data:k,error:T}=await V.from("listing_shares").insert({listing_id:r,sharing_agent_id:i.id,share_type:"referral_link"}).select("id, share_token, click_count, lead_count").single();if(T)throw T;o(k)}}catch(b){console.error("Error creating share link:",b),he.error("Failed to generate share link")}finally{d(!1)}}})()},[s,i,r]);const p=l!=null&&l.share_token?`https://listings.relevelup.com/${n||r}?ref=${l.share_token}`:"",x=async()=>{try{await navigator.clipboard.writeText(p),m(!0),he.success("Link copied to clipboard!"),setTimeout(()=>m(!1),2e3)}catch{he.error("Failed to copy link")}},y=_=>{const b=encodeURIComponent(p),j=encodeURIComponent(`Check out this listing: ${a}`);switch(_){case"email":window.open(`mailto:?subject=${j}&body=${b}`);break;case"text":window.open(`sms:?body=${j}%20${b}`);break;case"facebook":window.open(`https://www.facebook.com/sharer/sharer.php?u=${b}`,"_blank");break}};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"sm:max-w-md",children:[e.jsxs(Cs,{children:[e.jsxs(Ns,{className:"flex items-center gap-2",children:[e.jsx(Lr,{className:"h-5 w-5 text-amber-500"}),"Share & Earn Leads"]}),e.jsx(nn,{children:"Share this listing with your network. When someone submits a lead through your link, they'll become your contact!"})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsx("div",{className:"bg-amber-50 dark:bg-amber-950/30 border border-amber-200 dark:border-amber-800 rounded-lg p-3",children:e.jsxs("p",{className:"text-sm text-amber-800 dark:text-amber-200",children:[e.jsx("strong",{children:"How it works:"})," The listing still shows the original agent's info, but any leads from your unique link go directly to you!"]})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Your Referral Link"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Se,{value:c?"Generating...":p,readOnly:!0,className:"font-mono text-sm"}),e.jsx(H,{onClick:x,disabled:c||!p,variant:h?"default":"outline",children:h?e.jsx(va,{className:"h-4 w-4"}):e.jsx(ui,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Share via"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(H,{variant:"outline",className:"flex-1",onClick:()=>y("email"),disabled:c,children:[e.jsx(er,{className:"h-4 w-4 mr-2"}),"Email"]}),e.jsxs(H,{variant:"outline",className:"flex-1",onClick:()=>y("text"),disabled:c,children:[e.jsx(Gi,{className:"h-4 w-4 mr-2"}),"Text"]}),e.jsxs(H,{variant:"outline",className:"flex-1",onClick:()=>y("facebook"),disabled:c,children:[e.jsx(fh,{className:"h-4 w-4 mr-2"}),"Facebook"]})]})]}),l&&(l.click_count>0||l.lead_count>0)&&e.jsxs("div",{className:"pt-4 border-t",children:[e.jsx(ue,{className:"mb-2 block",children:"Your Share Performance"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"bg-muted rounded-lg p-3 text-center",children:[e.jsxs("div",{className:"flex items-center justify-center gap-1 text-muted-foreground mb-1",children:[e.jsx(Bn,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs",children:"Clicks"})]}),e.jsx("p",{className:"text-2xl font-bold",children:l.click_count})]}),e.jsxs("div",{className:"bg-primary/10 rounded-lg p-3 text-center",children:[e.jsxs("div",{className:"flex items-center justify-center gap-1 text-primary mb-1",children:[e.jsx(Ar,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs",children:"Leads"})]}),e.jsx("p",{className:"text-2xl font-bold text-primary",children:l.lead_count})]})]})]})]})]})})}const zDs={active:"bg-emerald-500",coming_soon:"bg-sky-500",office_exclusive:"bg-indigo-500",pre_market:"bg-cyan-500",price_improvement:"bg-orange-500",under_contract:"bg-purple-500",sold:"bg-gray-500"},$Ds={active:"Active",coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"},UDs={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"};function Yq({listing:s,onClick:t,onEdit:r,onDelete:n,onCreateMusicVideo:a,showActions:i}){var b,j;const{user:l}=Ms(),{data:o}=wot(s.id),c=_ot(),[d,h]=S.useState(!1),m=k=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(k),p=((b=s.photos)==null?void 0:b.find(k=>k.is_primary))||((j=s.photos)==null?void 0:j[0]),x=(l==null?void 0:l.id)===s.agent_id,y=async k=>{k.stopPropagation();try{const T=await c.mutateAsync(s.id);he.success(T.saved?"Listing saved!":"Listing removed from saved")}catch{he.error("Failed to save listing")}},_=k=>{if(k.stopPropagation(),l)h(!0);else{const T=`https://listings.relevelup.com/${s.slug||s.id}`;navigator.clipboard.writeText(T),he.success("Link copied to clipboard!")}};return e.jsxs(ke,{className:"overflow-hidden hover:shadow-lg transition-shadow cursor-pointer group",onClick:t,children:[e.jsxs("div",{className:"relative aspect-[4/3] bg-muted",children:[p?e.jsx("img",{src:p.photo_url,alt:s.property_address||s.city,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground",children:e.jsx(Hy,{className:"h-12 w-12"})}),e.jsx(Xe,{className:`absolute top-2 left-2 ${zDs[s.status]} text-white border-0`,children:$Ds[s.status]}),s.is_featured&&e.jsx("div",{className:"absolute top-2 right-2 p-1.5 bg-amber-500 rounded-full",children:e.jsx(ya,{className:"h-4 w-4 text-white fill-white"})}),e.jsxs("div",{className:"absolute bottom-2 right-2 flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity",children:[e.jsx(H,{size:"icon",variant:"secondary",className:"h-8 w-8",onClick:y,children:e.jsx(Bi,{className:`h-4 w-4 ${o?"fill-pink-500 text-pink-500":""}`})}),e.jsx(H,{size:"icon",variant:"secondary",className:"h-8 w-8",onClick:_,title:x?"Copy link":"Share & earn leads",children:x?e.jsx(cd,{className:"h-4 w-4"}):e.jsx(Lr,{className:"h-4 w-4 text-amber-500"})})]})]}),e.jsx(hxt,{open:d,onOpenChange:h,listingId:s.id,listingSlug:s.slug||null,listingTitle:s.property_address||`${s.city}, ${s.state}`}),e.jsxs(Oe,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-xl font-bold text-primary",children:m(s.price)}),s.open_to_referrals&&e.jsxs(Xe,{variant:"outline",className:"text-xs",children:[e.jsx(Ar,{className:"h-3 w-3 mr-1"}),"Referrals"]})]}),e.jsxs("div",{children:[s.property_address&&e.jsx("p",{className:"font-medium truncate",children:s.property_address}),e.jsxs("p",{className:"text-sm text-muted-foreground flex items-center gap-1",children:[e.jsx(Qa,{className:"h-3 w-3"}),s.city,", ",s.state,s.neighborhood&&` • ${s.neighborhood}`]})]}),e.jsxs("div",{className:"flex items-center gap-4 text-sm text-muted-foreground",children:[s.bedrooms&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(x1,{className:"h-4 w-4"}),s.bedrooms," bd"]}),s.bathrooms&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(_p,{className:"h-4 w-4"}),s.bathrooms," ba"]}),s.square_footage&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Hy,{className:"h-4 w-4"}),s.square_footage.toLocaleString()," sqft"]})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t",children:[e.jsx(Xe,{variant:"secondary",className:"text-xs",children:UDs[s.property_type]}),s.agent&&e.jsx("p",{className:"text-xs text-muted-foreground truncate max-w-[120px]",children:s.agent.name})]}),e.jsxs("div",{className:"flex items-center gap-3 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Bn,{className:"h-3 w-3"}),s.view_count]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(cd,{className:"h-3 w-3"}),s.share_count]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Bi,{className:"h-3 w-3"}),s.save_count]})]}),i&&(r||n||a)&&e.jsxs("div",{className:"flex flex-wrap gap-2",children:[a&&e.jsxs(H,{variant:"outline",size:"sm",className:"flex-1 min-w-[140px] gap-1.5 border-violet-500/60 text-violet-600 hover:bg-violet-50",onClick:k=>{k.stopPropagation(),a()},children:[e.jsx(GI,{className:"h-4 w-4"}),"Music Video"]}),r&&e.jsxs(H,{variant:"outline",size:"sm",className:"flex-1",onClick:k=>{k.stopPropagation(),r()},children:[e.jsx(ou,{className:"h-4 w-4 mr-2"}),"Edit"]}),n&&e.jsx(H,{variant:"destructive",size:"sm",onClick:k=>{k.stopPropagation(),n()},children:e.jsx(Dr,{className:"h-4 w-4"})})]})]})]})}const qDs=[{value:"active",label:"Active"},{value:"coming_soon",label:"Coming Soon"},{value:"office_exclusive",label:"Office Exclusive"},{value:"pre_market",label:"Pre-Market"},{value:"price_improvement",label:"Price Improvement"},{value:"under_contract",label:"Under Contract"},{value:"sold",label:"Sold"}],VDs=[{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 HDs({filters:s,onFiltersChange:t,onClose:r}){const n=()=>{t({sortBy:"newest"})};return e.jsxs(ke,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between pb-3",children:[e.jsx(zt,{className:"text-lg",children:"Filters"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(H,{variant:"ghost",size:"sm",onClick:n,children:"Clear All"}),e.jsx(H,{variant:"ghost",size:"icon",onClick:r,children:e.jsx(Rr,{className:"h-4 w-4"})})]})]}),e.jsxs(Oe,{children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Status"}),e.jsxs(Bs,{value:s.status||"all",onValueChange:a=>t({...s,status:a==="all"?void 0:a}),children:[e.jsx(Os,{children:e.jsx(Us,{placeholder:"All statuses"})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"all",children:"All Statuses"}),qDs.map(a=>e.jsx(pt,{value:a.value,children:a.label},a.value))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Property Type"}),e.jsxs(Bs,{value:s.propertyType||"all",onValueChange:a=>t({...s,propertyType:a==="all"?void 0:a}),children:[e.jsx(Os,{children:e.jsx(Us,{placeholder:"All types"})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"all",children:"All Types"}),VDs.map(a=>e.jsx(pt,{value:a.value,children:a.label},a.value))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Min Price"}),e.jsx(Se,{type:"number",placeholder:"No minimum",value:s.minPrice||"",onChange:a=>t({...s,minPrice:a.target.value?Number(a.target.value):void 0})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Max Price"}),e.jsx(Se,{type:"number",placeholder:"No maximum",value:s.maxPrice||"",onChange:a=>t({...s,maxPrice:a.target.value?Number(a.target.value):void 0})})]})]}),e.jsxs("div",{className:"flex items-center justify-between mt-4 pt-4 border-t",children:[e.jsxs("div",{children:[e.jsx(ue,{children:"Open to Referrals Only"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Show only listings accepting buyer referrals"})]}),e.jsx(Or,{checked:s.openToReferrals||!1,onCheckedChange:a=>t({...s,openToReferrals:a||void 0})})]})]})]})}function GDs({leaderboard:s}){const t=n=>{switch(n){case 0:return e.jsx(To,{className:"h-5 w-5 text-amber-500"});case 1:return e.jsx(H2,{className:"h-5 w-5 text-gray-400"});case 2:return e.jsx(Bc,{className:"h-5 w-5 text-amber-700"});default:return e.jsx("span",{className:"text-sm font-medium text-muted-foreground w-5 text-center",children:n+1})}},r=(n,a)=>!n||n.length===0?e.jsx("div",{className:"py-8 text-center text-muted-foreground",children:"No data yet. Start sharing to climb the leaderboard!"}):e.jsx("div",{className:"space-y-2",children:n.map((i,l)=>e.jsxs("div",{className:`flex items-center gap-4 p-3 rounded-lg ${l===0?"bg-gradient-to-r from-amber-500/10 to-amber-500/5 border border-amber-500/20":"bg-muted/50"}`,children:[e.jsx("div",{className:"flex items-center justify-center w-8",children:t(l)}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx("p",{className:"font-medium truncate",children:i.name})}),e.jsxs(Xe,{variant:l===0?"default":"secondary",children:[i.count," ",a]})]},i.agentId))});return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(To,{className:"h-5 w-5 text-amber-500"}),"Community Badges"]})}),e.jsx(Oe,{children:e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.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:[e.jsx("div",{className:"w-12 h-12 mx-auto mb-2 rounded-full bg-emerald-500/20 flex items-center justify-center",children:e.jsx(cd,{className:"h-6 w-6 text-emerald-500"})}),e.jsx("p",{className:"font-medium text-sm",children:"Listing Amplifier"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Share 10+ listings"})]}),e.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:[e.jsx("div",{className:"w-12 h-12 mx-auto mb-2 rounded-full bg-sky-500/20 flex items-center justify-center",children:e.jsx(Fn,{className:"h-6 w-6 text-sky-500"})}),e.jsx("p",{className:"font-medium text-sm",children:"Top Contributor"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Add 5+ listings"})]}),e.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:[e.jsx("div",{className:"w-12 h-12 mx-auto mb-2 rounded-full bg-purple-500/20 flex items-center justify-center",children:e.jsx(H2,{className:"h-6 w-6 text-purple-500"})}),e.jsx("p",{className:"font-medium text-sm",children:"Referral Connector"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Send 3+ referrals"})]}),e.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:[e.jsx("div",{className:"w-12 h-12 mx-auto mb-2 rounded-full bg-amber-500/20 flex items-center justify-center",children:e.jsx(To,{className:"h-6 w-6 text-amber-500"})}),e.jsx("p",{className:"font-medium text-sm",children:"Community MVP"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Top performer"})]})]})})]}),e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsx(zt,{children:"Community Leaderboard"})}),e.jsx(Oe,{children:e.jsxs(ta,{defaultValue:"sharers",children:[e.jsxs(Qn,{className:"w-full",children:[e.jsxs(ts,{value:"sharers",className:"flex-1",children:[e.jsx(cd,{className:"h-4 w-4 mr-2"}),"Top Sharers"]}),e.jsxs(ts,{value:"listers",className:"flex-1",children:[e.jsx(Fn,{className:"h-4 w-4 mr-2"}),"Top Contributors"]})]}),e.jsx(cs,{value:"sharers",className:"mt-4",children:r(s==null?void 0:s.topSharers,"shares")}),e.jsx(cs,{value:"listers",className:"mt-4",children:r(s==null?void 0:s.topListers,"listings")})]})})]})]})}const ZHe={coming_soon:"#F59E0B",office_exclusive:"#6366F1",pre_market:"#06B6D4",active:"#10B981",price_improvement:"#8B5CF6",under_contract:"#3B82F6",sold:"#A855F7"},XHe={coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",active:"Active",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"};function WDs(s){return s>=1e6?`$${(s/1e6).toFixed(1)}M`:`$${(s/1e3).toFixed(0)}K`}function KDs({listings:s,isLoading:t}){const r=Fr(),n=S.useRef(null),a=S.useRef(null),i=S.useRef([]),{isAdmin:l}=Ms(),[o,c]=S.useState(""),[d,h]=S.useState(!0),[m,p]=S.useState(!1),x=s.filter(_=>_.latitude!=null&&_.longitude!=null),y=s.filter(_=>(_.latitude==null||_.longitude==null)&&(_.property_address||_.city));return S.useEffect(()=>{(async()=>{h(!0);try{const{data:b}=await V.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();b!=null&&b.value&&c(b.value)}catch(b){console.error("Error fetching mapbox token:",b)}h(!1)})()},[]),S.useEffect(()=>{if(!o||y.length===0||m)return;(async()=>{var b;p(!0);for(const j of y){const k=[j.property_address,j.city,j.state].filter(Boolean).join(", ");if(k)try{const E=await(await fetch(`https://api.mapbox.com/geocoding/v5/mapbox.places/${encodeURIComponent(k)}.json?access_token=${o}&limit=1`)).json();if((b=E.features)!=null&&b[0]){const[A,D]=E.features[0].center;await V.from("listings").update({latitude:D,longitude:A}).eq("id",j.id),j.latitude=D,j.longitude=A}}catch(T){console.error("Geocode error:",T)}}p(!1)})()},[o,s]),S.useEffect(()=>{if(!n.current||!o||a.current)return;fc.accessToken=o;const _=s.filter(k=>k.latitude!=null&&k.longitude!=null);let b=[-98.5795,39.8283],j=4;if(_.length>0){const k=_.reduce((E,A)=>E+A.longitude,0)/_.length,T=_.reduce((E,A)=>E+A.latitude,0)/_.length;b=[k,T],j=_.length===1?12:10}return a.current=new fc.Map({container:n.current,style:"mapbox://styles/mapbox/light-v11",zoom:j,center:b}),a.current.addControl(new fc.NavigationControl,"top-right"),()=>{var k;(k=a.current)==null||k.remove(),a.current=null}},[o]),S.useEffect(()=>{if(!a.current||!o)return;i.current.forEach(b=>b.remove()),i.current=[];const _=s.filter(b=>b.latitude!=null&&b.longitude!=null);if(_.forEach(b=>{var D,R,z;const j=ZHe[b.status]||"#10B981",k=((D=b.photos)==null?void 0:D.find(O=>O.is_primary))||((R=b.photos)==null?void 0:R[0]),T=document.createElement("div");T.className="cursor-pointer",T.innerHTML=`
`;const E=new fc.Popup({offset:25,closeButton:!0,maxWidth:"280px"}).setHTML(`
${k!=null&&k.photo_url?``:""}
${WDs(b.price)}
${b.property_address||""}
${b.city}, ${b.state}
${XHe[b.status]||b.status} ${b.bedrooms?`${b.bedrooms} bed`:""} ${b.bathrooms?`${b.bathrooms} bath`:""}
${(z=b.agent)!=null&&z.name?`
Listed by ${b.agent.name}
`:""}
Click to view details →
`),A=new fc.Marker(T).setLngLat([b.longitude,b.latitude]).setPopup(E).addTo(a.current);i.current.push(A)}),_.length>1){const b=new fc.LngLatBounds;_.forEach(j=>b.extend([j.longitude,j.latitude])),a.current.fitBounds(b,{padding:60,maxZoom:13})}else _.length===1&&a.current.flyTo({center:[_[0].longitude,_[0].latitude],zoom:12})},[s,o,m]),S.useEffect(()=>(window.__navigateToListing__=_=>{r(`/mission-control/listings/${_}`)},()=>{delete window.__navigateToListing__}),[r]),d||t?e.jsx(ke,{children:e.jsx(Oe,{className:"flex items-center justify-center h-[60vh]",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary"})})}):o?s.length===0?e.jsx(ke,{children:e.jsxs(Oe,{className:"flex flex-col items-center justify-center h-[60vh] text-center gap-3",children:[e.jsx(Qa,{className:"h-12 w-12 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold",children:"No Listings Yet"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Add listings to see them on the map."})]})]})}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-sm",children:[Object.entries(ZHe).map(([_,b])=>e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:"w-3 h-3 rounded-full border-2 border-white shadow",style:{background:b}}),e.jsx("span",{className:"text-xs",children:XHe[_]})]},_)),e.jsxs("span",{className:"text-muted-foreground ml-auto text-xs",children:[x.length," of ",s.length," mapped",m&&" · Geocoding..."]})]}),e.jsx("div",{ref:n,className:"w-full h-[60vh] rounded-lg shadow-lg border"})]}):e.jsx(ke,{children:e.jsxs(Oe,{className:"flex flex-col items-center justify-center h-[60vh] text-center gap-3",children:[e.jsx(wo,{className:"h-12 w-12 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold",children:"Map Not Configured"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:l?"Set up your Mapbox token in Settings to enable maps.":"The map feature has not been configured yet. Please contact your administrator."})]})]})})}const S4e="homereel_mv_prefill",C4e="homereel_mv_badge_default";function mxt(s){try{sessionStorage.setItem(S4e,JSON.stringify(s)),s.badge&&s.badge.type!=="none"&&sessionStorage.setItem(C4e,JSON.stringify(s.badge))}catch{}}function dXs(){try{const s=sessionStorage.getItem(S4e);return s?(sessionStorage.removeItem(S4e),JSON.parse(s)):null}catch{return null}}function uXs(){try{const s=sessionStorage.getItem(C4e);return s?(sessionStorage.removeItem(C4e),JSON.parse(s)):null}catch{return null}}function fxt(s,t){switch(s){case"coming_soon":case"pre_market":return{type:"coming_soon"};case"price_improvement":return{type:"price_improvement",newPrice:t?String(t):""};case"active":return{type:"just_listed"};default:return{type:"none"}}}function YDs(){var O,$,ee,Z,J,K,re,ie;const s=Fr(),{brokerageId:t}=Ms(),{data:r,isLoading:n}=xot(),[a,i]=S.useState("feed"),[l,o]=S.useState(!1),[c,d]=S.useState(""),[h,m]=S.useState({sortBy:"newest"}),{data:p,isLoading:x}=yot({...h,city:c||h.city}),{data:y,isLoading:_}=AHt(),{data:b,isLoading:j}=vot(),{data:k,isLoading:T}=LHt(),{data:E,isLoading:A}=OHt(),{data:D}=RHt(),R=bot(),z=async ce=>{if(confirm("Are you sure you want to delete this listing? This action cannot be undone."))try{await R.mutateAsync(ce),he.success("Listing deleted successfully")}catch{he.error("Failed to delete listing")}};return n?e.jsx(Ss,{title:"Listing Exchange",description:"Community-powered listing collaboration",children:e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full"})})}):r?e.jsx(Ss,{title:"Listing Exchange",description:"Community-powered listing collaboration",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Listing Exchange"}),e.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"})]}),e.jsxs(H,{onClick:()=>s("/mission-control/listings/new"),children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Add Listing"]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(ke,{children:e.jsxs(Oe,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(Fn,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:(p==null?void 0:p.length)||0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Active Listings"})]})]})}),e.jsx(ke,{children:e.jsxs(Oe,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-pink-500/10 rounded-lg",children:e.jsx(Bi,{className:"h-5 w-5 text-pink-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:(y==null?void 0:y.length)||0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Saved"})]})]})}),e.jsx(ke,{children:e.jsxs(Oe,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-emerald-500/10 rounded-lg",children:e.jsx(mE,{className:"h-5 w-5 text-emerald-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:(b==null?void 0:b.length)||0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"My Listings"})]})]})}),e.jsx(ke,{children:e.jsxs(Oe,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-sky-500/10 rounded-lg",children:e.jsx(Ar,{className:"h-5 w-5 text-sky-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:(((O=k==null?void 0:k.sent)==null?void 0:O.length)||0)+((($=k==null?void 0:k.received)==null?void 0:$.length)||0)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Referrals"})]})]})})]}),e.jsxs(ta,{value:a,onValueChange:i,children:[e.jsxs(Qn,{className:"w-full justify-start overflow-x-auto",children:[e.jsx(ts,{value:"feed",children:"Community Feed"}),t&&e.jsx(ts,{value:"brokerage",children:"Brokerage"}),e.jsx(ts,{value:"my-listings",children:"My Listings"}),e.jsx(ts,{value:"saved",children:"Saved"}),e.jsx(ts,{value:"referrals",children:"Referrals"}),e.jsx(ts,{value:"map",children:"Map"}),e.jsx(ts,{value:"leaderboard",children:"Leaderboard"})]}),e.jsxs(cs,{value:"feed",className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Mn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Se,{placeholder:"Search by city or neighborhood...",value:c,onChange:ce=>d(ce.target.value),className:"pl-9"})]}),e.jsxs(Bs,{value:h.sortBy,onValueChange:ce=>m({...h,sortBy:ce}),children:[e.jsx(Os,{className:"w-[180px]",children:e.jsx(Us,{placeholder:"Sort by"})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"newest",children:"Newest First"}),e.jsx(pt,{value:"updated",children:"Recently Updated"}),e.jsx(pt,{value:"price_asc",children:"Price: Low to High"}),e.jsx(pt,{value:"price_desc",children:"Price: High to Low"})]})]}),e.jsxs(H,{variant:"outline",onClick:()=>o(!l),children:[e.jsx(v1,{className:"h-4 w-4 mr-2"}),"Filters"]})]}),l&&e.jsx(HDs,{filters:h,onFiltersChange:m,onClose:()=>o(!1)}),x?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[...Array(6)].map((ce,ne)=>e.jsxs(ke,{children:[e.jsx(Ks,{className:"h-48 w-full"}),e.jsxs(Oe,{className:"p-4 space-y-2",children:[e.jsx(Ks,{className:"h-5 w-3/4"}),e.jsx(Ks,{className:"h-4 w-1/2"}),e.jsx(Ks,{className:"h-4 w-1/4"})]})]},ne))}):(p==null?void 0:p.length)===0?e.jsx(ke,{children:e.jsxs(Oe,{className:"py-12 text-center",children:[e.jsx(Fn,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-medium mb-2",children:"No listings found"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"Be the first to share a listing with the community!"}),e.jsxs(H,{onClick:()=>s("/mission-control/listings/new"),children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Add Listing"]})]})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:p==null?void 0:p.map(ce=>e.jsx(Yq,{listing:ce,onClick:()=>s(`/mission-control/listings/${ce.id}`)},ce.id))})]}),e.jsx(cs,{value:"my-listings",className:"space-y-4",children:j?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[...Array(3)].map((ce,ne)=>e.jsxs(ke,{children:[e.jsx(Ks,{className:"h-48 w-full"}),e.jsxs(Oe,{className:"p-4 space-y-2",children:[e.jsx(Ks,{className:"h-5 w-3/4"}),e.jsx(Ks,{className:"h-4 w-1/2"})]})]},ne))}):(b==null?void 0:b.length)===0?e.jsx(ke,{children:e.jsxs(Oe,{className:"py-12 text-center",children:[e.jsx(mE,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-medium mb-2",children:"No listings yet"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"Share your listings with the LevelUp community!"}),e.jsxs(H,{onClick:()=>s("/mission-control/listings/new"),children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Add Your First Listing"]})]})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:b==null?void 0:b.map(ce=>e.jsx(Yq,{listing:ce,showActions:!0,onClick:()=>s(`/mission-control/listings/${ce.id}`),onEdit:()=>s(`/mission-control/listings/${ce.id}/edit`),onDelete:()=>z(ce.id),onCreateMusicVideo:()=>{const ne=(ce.photos??[]).slice().sort((le,be)=>(be.is_primary?1:0)-(le.is_primary?1:0)||(le.sort_order??0)-(be.sort_order??0)).map(le=>le.photo_url).filter(Boolean);if(ne.length===0){he.error("Add photos to this listing first.");return}mxt({photos:ne,details:{address:ce.property_address||`${ce.city??""} ${ce.state??""}`.trim(),beds:ce.bedrooms?String(ce.bedrooms):"",baths:ce.bathrooms?String(ce.bathrooms):"",sqft:ce.square_footage?String(ce.square_footage):"",price:ce.price?String(ce.price):"",highlights:ce.description||""},sourceLabel:"My Listings",badge:fxt(ce.status,ce.price)}),s("/admin/beta/homereel?tab=music-video")}},ce.id))})}),e.jsx(cs,{value:"saved",className:"space-y-4",children:_?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[...Array(3)].map((ce,ne)=>e.jsxs(ke,{children:[e.jsx(Ks,{className:"h-48 w-full"}),e.jsxs(Oe,{className:"p-4 space-y-2",children:[e.jsx(Ks,{className:"h-5 w-3/4"}),e.jsx(Ks,{className:"h-4 w-1/2"})]})]},ne))}):(y==null?void 0:y.length)===0?e.jsx(ke,{children:e.jsxs(Oe,{className:"py-12 text-center",children:[e.jsx(Bi,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-medium mb-2",children:"No saved listings"}),e.jsx("p",{className:"text-muted-foreground",children:"Save listings to quickly access them later"})]})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:y==null?void 0:y.map(ce=>e.jsx(Yq,{listing:ce.listing,onClick:()=>s(`/mission-control/listings/${ce.listing.id}`)},ce.id))})}),e.jsx(cs,{value:"referrals",className:"space-y-6",children:e.jsxs("div",{className:"grid md:grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsxs("h3",{className:"font-semibold mb-3 flex items-center gap-2",children:[e.jsx(cd,{className:"h-4 w-4"}),"Referrals Sent (",((ee=k==null?void 0:k.sent)==null?void 0:ee.length)||0,")"]}),((Z=k==null?void 0:k.sent)==null?void 0:Z.length)===0?e.jsx(ke,{children:e.jsx(Oe,{className:"py-8 text-center text-muted-foreground",children:"No referrals sent yet"})}):e.jsx("div",{className:"space-y-3",children:(J=k==null?void 0:k.sent)==null?void 0:J.map(ce=>{var ne,le;return e.jsx(ke,{children:e.jsx(Oe,{className:"p-4",children:e.jsxs("div",{className:"flex justify-between items-start mb-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:ce.buyer_name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:((ne=ce.listing)==null?void 0:ne.property_address)||((le=ce.listing)==null?void 0:le.city)})]}),e.jsx(Xe,{variant:ce.status==="closed"?"default":"secondary",children:ce.status.replace("_"," ")})]})})},ce.id)})})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"font-semibold mb-3 flex items-center gap-2",children:[e.jsx(Ar,{className:"h-4 w-4"}),"Referrals Received (",((K=k==null?void 0:k.received)==null?void 0:K.length)||0,")"]}),((re=k==null?void 0:k.received)==null?void 0:re.length)===0?e.jsx(ke,{children:e.jsx(Oe,{className:"py-8 text-center text-muted-foreground",children:"No referrals received yet"})}):e.jsx("div",{className:"space-y-3",children:(ie=k==null?void 0:k.received)==null?void 0:ie.map(ce=>{var ne;return e.jsx(ke,{children:e.jsxs(Oe,{className:"p-4",children:[e.jsxs("div",{className:"flex justify-between items-start mb-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:ce.buyer_name}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["From: ",(ne=ce.sender)==null?void 0:ne.name]})]}),e.jsx(Xe,{variant:ce.status==="closed"?"default":"secondary",children:ce.status.replace("_"," ")})]}),e.jsx(H,{size:"sm",variant:"outline",className:"w-full mt-2",onClick:()=>s(`/mission-control/listings/${ce.listing_id}`),children:"View Listing"})]})},ce.id)})})]})]})}),t&&e.jsx(cs,{value:"brokerage",className:"space-y-4",children:A?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[...Array(3)].map((ce,ne)=>e.jsxs(ke,{children:[e.jsx(Ks,{className:"h-48 w-full"}),e.jsxs(Oe,{className:"p-4 space-y-2",children:[e.jsx(Ks,{className:"h-5 w-3/4"}),e.jsx(Ks,{className:"h-4 w-1/2"})]})]},ne))}):(E==null?void 0:E.length)===0?e.jsx(ke,{children:e.jsxs(Oe,{className:"py-12 text-center",children:[e.jsx(mE,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-medium mb-2",children:"No brokerage listings yet"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"No agents in your brokerage have added listings yet."}),e.jsxs(H,{onClick:()=>s("/mission-control/listings/new"),children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Add a Listing"]})]})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:E==null?void 0:E.map(ce=>e.jsx(Yq,{listing:ce,onClick:()=>s(`/mission-control/listings/${ce.id}`)},ce.id))})}),e.jsx(cs,{value:"map",children:e.jsx(KDs,{listings:p||[],isLoading:x})}),e.jsx(cs,{value:"leaderboard",children:e.jsx(GDs,{leaderboard:D})})]})]})}):e.jsx(Ss,{title:"Listing Exchange",description:"Community-powered listing collaboration",children:e.jsx(ke,{children:e.jsxs(Oe,{className:"py-12 text-center",children:[e.jsx(Fn,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h2",{className:"text-xl font-semibold mb-2",children:"Coming Soon"}),e.jsx("p",{className:"text-muted-foreground",children:"Listing Exchange is currently in development. Check back soon!"})]})})})}function pxt(s){return yt({queryKey:["listing-documents",s],queryFn:async()=>{const{data:t,error:r}=await V.from("listing_documents").select("*").eq("listing_id",s).order("sort_order",{ascending:!0}).order("created_at",{ascending:!0});if(r)throw r;return t},enabled:!!s})}function ZDs(){const{user:s}=Ms(),t=ns();return Pt({mutationFn:async({listingId:r,file:n})=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const a=n.name.split(".").pop(),i=`${s.id}/${r}/${crypto.randomUUID()}.${a}`,{error:l}=await V.storage.from("listing-documents").upload(i,n,{contentType:n.type||void 0});if(l)throw l;const{data:o,error:c}=await V.from("listing_documents").insert({listing_id:r,owner_user_id:s.id,file_name:n.name,file_size:n.size,file_type:n.type||null,storage_path:i}).select().single();if(c)throw c;return o},onSuccess:(r,n)=>{t.invalidateQueries({queryKey:["listing-documents",n.listingId]})}})}function XDs(){const s=ns();return Pt({mutationFn:async({id:t,storage_path:r,listingId:n})=>{await V.storage.from("listing-documents").remove([r]);const{error:a}=await V.from("listing_documents").delete().eq("id",t);if(a)throw a;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["listing-documents",t]})}})}function QDs(){const s=ns();return Pt({mutationFn:async({id:t,visible:r,listingId:n})=>{const{error:a}=await V.from("listing_documents").update({visible_on_exchange:r}).eq("id",t);if(a)throw a;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["listing-documents",t]})}})}async function gxt(s){const{data:t,error:r}=await V.storage.from("listing-documents").createSignedUrl(s,3600);if(r)throw r;return t.signedUrl}const JDs=s=>s<1024?`${s} B`:s<1024*1024?`${(s/1024).toFixed(0)} KB`:`${(s/(1024*1024)).toFixed(1)} MB`;function eRs({listingId:s,ownerOnly:t=!1}){const{data:r=[]}=pxt(s),n=t?r:r.filter(i=>i.visible_on_exchange);if(n.length===0)return null;const a=async i=>{try{const l=await gxt(i);window.open(l,"_blank")}catch{he.error("Failed to open document")}};return e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsxs(zt,{className:"text-lg flex items-center gap-2",children:[e.jsx(kn,{className:"h-5 w-5"}),"Documents & Disclosures (",n.length,")"]})}),e.jsx(Oe,{children:e.jsx("div",{className:"space-y-2",children:n.map(i=>e.jsxs("button",{onClick:()=>a(i.storage_path),className:"w-full flex items-center gap-3 p-3 rounded-lg border hover:bg-muted transition-colors text-left group",children:[e.jsx("div",{className:"p-2 rounded-md bg-primary/10 flex-shrink-0",children:e.jsx(kn,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-sm font-medium truncate",children:i.file_name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:JDs(i.file_size)})]}),e.jsx(hi,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary"})]},i.id))})})]})}const tRs=s=>{if(!s)return"";const t=s.replace(/\D/g,""),r=t.length===11&&t.startsWith("1")?t.slice(1):t;return r.length!==10?s:`${r.slice(0,3)}-${r.slice(3,6)}-${r.slice(6)}`},QHe=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s),iC="#D4AF37",JHe="#0F172A",eGe=async s=>new Promise((t,r)=>{const n=new Image;n.crossOrigin="anonymous",n.referrerPolicy="no-referrer",n.onload=()=>t(n),n.onerror=r,n.src=s}),tGe=(s,t,r,n,a,i)=>{const l=Math.max(a/t.naturalWidth,i/t.naturalHeight),o=a/l,c=i/l,d=(t.naturalWidth-o)/2,h=(t.naturalHeight-c)/2;s.drawImage(t,d,h,o,c,r,n,a,i)},AO=(s,t,r)=>{if(s.measureText(t).width<=r)return t;let n=t;for(;n.length>3&&s.measureText(`${n}…`).width>r;)n=n.slice(0,-1);return`${n.trim()}…`},sRs=(s,t,r,n)=>{const a=t.split(/\s+/).filter(Boolean),i=[];let l="";for(const o of a){const c=l?`${l} ${o}`:o;if(s.measureText(c).width<=r||!l)l=c;else if(i.push(l),l=o,i.length===n)break}return l&&i.length{let i=r;for(const l of t)s.fillText(l,i,n),i+=s.measureText(l).width+a},nRs=s=>s instanceof DOMException||s instanceof Error?s.name:null;function xxt({listingId:s,open:t,onOpenChange:r}){var A,D;const{data:n}=_Te(s||""),[a,i]=S.useState(null),[l,o]=S.useState(!1),[c,d]=S.useState(null),[h,m]=S.useState(null),p=((n==null?void 0:n.photos)||[]).slice().sort((R,z)=>R.is_primary&&!z.is_primary?-1:!R.is_primary&&z.is_primary?1:(R.sort_order??0)-(z.sort_order??0));S.useEffect(()=>{var z;if(!t)return;const R=((z=p[0])==null?void 0:z.photo_url)||null;m(O=>O||R)},[t,n==null?void 0:n.id,p.length]),S.useEffect(()=>{let R=!1;if(!(!t||!(n!=null&&n.agent_id)))return(async()=>{var ee,Z,J,K;const{data:z}=await V.from("profiles").select("name, phone, phone_e164, avatar_url, brokerage:brokerages!profiles_brokerage_id_fkey(name)").eq("id",n.agent_id).maybeSingle();if(R)return;const O=z,$=((ee=O==null?void 0:O.brokerage)==null?void 0:ee.name)||((J=(Z=n.agent)==null?void 0:Z.brokerage)==null?void 0:J.name)||null;i({name:(O==null?void 0:O.name)||((K=n.agent)==null?void 0:K.name)||"Agent",phone:(O==null?void 0:O.phone)||(O==null?void 0:O.phone_e164)||null,avatar_url:(O==null?void 0:O.avatar_url)||null,brokerage:$})})(),()=>{R=!0}},[t,n==null?void 0:n.agent_id]),S.useEffect(()=>{if(!t){d(null),m(null);return}if(!n||!a)return;const R=setTimeout(()=>{x()},350);return()=>clearTimeout(R)},[t,n==null?void 0:n.id,a==null?void 0:a.name,h]);const x=async()=>{if(!(!n||!a)){o(!0);try{const R=document.createElement("canvas");R.width=1080,R.height=1080;const z=R.getContext("2d");if(!z)throw new Error("Canvas unavailable");if(z.fillStyle=JHe,z.fillRect(0,0,1080,1080),k){const K=await eGe(k);tGe(z,K,0,0,1080,1080)}const O=z.createLinearGradient(0,0,0,1080);O.addColorStop(0,"rgba(15,23,42,0.58)"),O.addColorStop(.34,"rgba(15,23,42,0.16)"),O.addColorStop(.62,"rgba(15,23,42,0.48)"),O.addColorStop(1,"rgba(15,23,42,0.98)"),z.fillStyle=O,z.fillRect(0,0,1080,1080),z.fillStyle=iC,z.fillRect(56,62,72,2),z.font="600 22px Arial, sans-serif",rRs(z,"JUST LISTED",146,72,8),z.save(),z.shadowColor="rgba(0,0,0,0.55)",z.shadowBlur=24,z.shadowOffsetY=4,z.fillStyle="#F8FAFC",z.font="600 64px Georgia, serif",z.textBaseline="top";const $=sRs(z,n.property_address||`${n.city||""}, ${n.state||""}`.trim(),952,2);let ee=$.length>1?590:654;$.forEach(K=>{z.fillText(K,64,ee),ee+=70}),z.restore();const Z=[n.city,n.state].filter(Boolean).join(", ")+(n.neighborhood?` · ${n.neighborhood}`:"");z.fillStyle="rgba(248,250,252,0.9)",z.font="600 26px Arial, sans-serif",z.fillText(AO(z,Z.toUpperCase(),952),64,ee+8),z.fillStyle=iC,z.font="700 56px Arial, sans-serif",z.fillText(QHe(n.price),64,ee+58),E.length>0&&(z.fillStyle="rgba(248,250,252,0.86)",z.font="600 22px Arial, sans-serif",z.fillText(AO(z,E.join(" · "),430),360,ee+78));const J=z.createLinearGradient(0,880,0,1080);if(J.addColorStop(0,"rgba(15,23,42,0.96)"),J.addColorStop(1,"#0B1322"),z.fillStyle=J,z.fillRect(0,880,1080,200),z.fillStyle=iC,z.fillRect(0,880,1080,2),z.save(),z.beginPath(),z.arc(124,980,60,0,Math.PI*2),z.closePath(),z.fillStyle="#1E293B",z.fill(),z.lineWidth=6,z.strokeStyle=iC,z.stroke(),z.clip(),a.avatar_url)try{const K=await eGe(a.avatar_url);tGe(z,K,64,920,120,120)}catch{z.fillStyle=iC,z.font="700 48px Arial, sans-serif",z.textAlign="center",z.textBaseline="middle",z.fillText(a.name.charAt(0).toUpperCase(),124,982)}else z.fillStyle=iC,z.font="700 48px Arial, sans-serif",z.textAlign="center",z.textBaseline="middle",z.fillText(a.name.charAt(0).toUpperCase(),124,982);z.restore(),z.textAlign="left",z.textBaseline="alphabetic",z.fillStyle="#F8FAFC",z.font="600 38px Georgia, serif",z.fillText(AO(z,a.name,T?430:820),212,970),a.brokerage&&(z.fillStyle=iC,z.font="600 20px Arial, sans-serif",z.fillText(AO(z,a.brokerage.toUpperCase(),T?430:820),212,1008)),T&&(z.textAlign="right",z.fillStyle="rgba(212,175,55,0.86)",z.font="600 16px Arial, sans-serif",z.fillText("CALL · TEXT",1016,958),z.fillStyle="#F8FAFC",z.font="600 38px Arial, sans-serif",z.fillText(T,1016,1008)),d(R.toDataURL("image/png"))}catch(R){console.error("Generate graphic error",R),he.error("Could not generate graphic")}finally{o(!1)}}},y=async R=>(await fetch(R)).blob(),_=async()=>{if(!c)return;const R=document.createElement("a");R.href=c,R.download=`just-listed-${(n==null?void 0:n.slug)||(n==null?void 0:n.id)||"graphic"}.png`,R.click(),he.success("Downloaded!")},b=async()=>{if(c)try{const R=await y(c);await navigator.clipboard.write([new ClipboardItem({"image/png":R})]),he.success("Copied to clipboard")}catch{he.error("Copy not supported in this browser")}},j=async()=>{if(c)try{const R=await y(c),z=new File([R],"just-listed.png",{type:"image/png"});navigator.canShare&&navigator.canShare({files:[z]})?await navigator.share({files:[z],title:"Just Listed"}):_()}catch(R){nRs(R)!=="AbortError"&&he.error("Share failed")}},k=h||((A=p[0])==null?void 0:A.photo_url)||null,T=tRs(a==null?void 0:a.phone),E=[n!=null&&n.bedrooms?`${n.bedrooms} BD`:null,n!=null&&n.bathrooms?`${n.bathrooms} BA`:null,n!=null&&n.square_footage?`${n.square_footage.toLocaleString()} SF`:null].filter(Boolean);return e.jsx(bs,{open:t,onOpenChange:r,children:e.jsx(vs,{className:"!max-w-[480px] !w-[calc(100vw-2rem)] !p-0 !gap-0 !block overflow-hidden",style:{maxHeight:"calc(100vh - 2rem)"},children:e.jsxs("div",{className:"flex flex-col",style:{maxHeight:"calc(100vh - 2rem)"},children:[e.jsxs(Cs,{className:"px-5 pt-5 pb-3 shrink-0",children:[e.jsxs(Ns,{className:"flex items-center gap-2 pr-8",children:[e.jsx(Lr,{className:"h-5 w-5 text-amber-500 shrink-0"}),e.jsx("span",{className:"truncate",children:"Your Just Listed Graphic"})]}),e.jsx(nn,{className:"text-xs",children:"Square 1080×1080 — perfect for Instagram, Facebook, LinkedIn."})]}),e.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-5 pb-3",children:[e.jsxs("div",{className:"relative mx-auto flex items-center justify-center rounded-lg overflow-hidden",style:{width:"280px",maxWidth:"100%",height:"280px",background:JHe},children:[k&&e.jsx("img",{src:k,alt:"Selected property",className:"absolute inset-0 h-full w-full object-cover"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-b from-slate-950/65 via-slate-950/25 to-slate-950"}),e.jsxs("div",{className:"absolute left-4 right-4 top-4 flex items-center gap-2",children:[e.jsx("span",{className:"h-px w-6 bg-amber-400"}),e.jsx("span",{className:"text-[9px] font-semibold uppercase tracking-[0.28em] text-amber-300",children:"Just Listed"})]}),e.jsxs("div",{className:"absolute left-4 right-4 bottom-[64px] text-white",children:[e.jsx("div",{className:"line-clamp-2 font-serif text-[18px] font-semibold leading-[1.05] drop-shadow-lg",children:(n==null?void 0:n.property_address)||`${(n==null?void 0:n.city)||""}, ${(n==null?void 0:n.state)||""}`}),e.jsxs("div",{className:"mt-1 truncate text-[9px] font-semibold uppercase tracking-[0.18em] text-white/85",children:[[n==null?void 0:n.city,n==null?void 0:n.state].filter(Boolean).join(", "),n!=null&&n.neighborhood?` · ${n.neighborhood}`:""]}),e.jsxs("div",{className:"mt-1.5 flex items-center gap-2",children:[e.jsx("span",{className:"text-[16px] font-bold text-amber-300",children:n?QHe(n.price):""}),E.length>0&&e.jsx("span",{className:"truncate text-[8px] font-semibold uppercase tracking-[0.14em] text-white/80",children:E.join(" · ")})]})]}),e.jsxs("div",{className:"absolute inset-x-0 bottom-0 flex h-[52px] items-center border-t border-amber-400 bg-slate-950/95 px-4",children:[e.jsx("div",{className:"flex h-9 w-9 shrink-0 items-center justify-center overflow-hidden rounded-full border-2 border-amber-400 bg-slate-800 text-xs font-bold text-amber-300",children:a!=null&&a.avatar_url?e.jsx("img",{src:a.avatar_url,alt:"",className:"h-full w-full object-cover"}):(D=a==null?void 0:a.name)==null?void 0:D.charAt(0).toUpperCase()}),e.jsxs("div",{className:"ml-2 min-w-0 flex-1",children:[e.jsx("div",{className:"truncate font-serif text-xs font-semibold text-white",children:a==null?void 0:a.name}),(a==null?void 0:a.brokerage)&&e.jsx("div",{className:"truncate text-[7px] font-semibold uppercase tracking-[0.18em] text-amber-300",children:a.brokerage})]}),T&&e.jsx("div",{className:"ml-2 shrink-0 text-[9px] font-semibold text-white",children:T})]}),l&&e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center gap-2 bg-slate-950/80 text-white/85",children:[e.jsx(is,{className:"h-7 w-7 animate-spin"}),e.jsx("p",{className:"text-xs",children:"Crafting your graphic…"})]})]}),p.length>1&&e.jsxs("div",{className:"mt-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Choose photo"}),e.jsx("div",{className:"flex gap-2 pb-2",style:{overflowX:"auto",overflowY:"hidden",WebkitOverflowScrolling:"touch"},children:p.map(R=>{const z=h===R.photo_url;return e.jsx("button",{type:"button",onClick:()=>m(R.photo_url),className:`relative shrink-0 h-14 w-14 rounded-md overflow-hidden border-2 transition ${z?"border-amber-500 ring-2 ring-amber-500/30":"border-transparent hover:border-muted-foreground/40"}`,children:e.jsx("img",{src:R.photo_url,alt:"",className:"w-full h-full object-cover"})},R.id)})})]})]}),e.jsxs("div",{className:"px-5 pb-5 pt-2 shrink-0 border-t bg-background flex flex-wrap justify-end gap-2",children:[e.jsx(H,{variant:"outline",size:"sm",onClick:()=>void x(),disabled:l||!n||!a,children:"Regenerate"}),e.jsxs(H,{variant:"outline",size:"sm",onClick:b,disabled:!c,className:"gap-1.5",children:[e.jsx(ui,{className:"h-3.5 w-3.5"})," Copy"]}),e.jsxs(H,{variant:"outline",size:"sm",onClick:j,disabled:!c,className:"gap-1.5",children:[e.jsx(cd,{className:"h-3.5 w-3.5"})," Share"]}),e.jsxs(H,{size:"sm",onClick:_,disabled:!c,className:"gap-1.5",children:[e.jsx(hi,{className:"h-3.5 w-3.5"})," Download"]})]})]})})})}function aRs(s){return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s)}const iRs={single_family:"Single Family Home",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury Home",commercial:"Commercial",other:"Property"};function oRs({open:s,onOpenChange:t,listing:r}){const{user:n}=Ms(),{data:a=[],isLoading:i}=Cp(),{data:l=[]}=R0(),[o,c]=S.useState(""),[d,h]=S.useState("all"),[m,p]=S.useState(new Set),[x,y]=S.useState(!1),[_,b]=S.useState(null);S.useEffect(()=>{s||(c(""),h("all"),p(new Set),y(!1))},[s]),S.useEffect(()=>{!s||!n||(async()=>{const{data:z}=await V.from("gmail_integrations").select("gmail_email").eq("user_id",n.id).maybeSingle();b((z==null?void 0:z.gmail_email)||null)})()},[s,n]);const j=S.useMemo(()=>a.filter(z=>z.email),[a]),k=S.useMemo(()=>{let z=j;if(d!=="all"&&(z=z.filter(O=>{var $;return($=O.tags)==null?void 0:$.some(ee=>ee.relationship_type_id===d)})),o.trim()){const O=o.toLowerCase();z=z.filter($=>`${$.first_name||""} ${$.last_name||""}`.toLowerCase().includes(O)||($.email||"").toLowerCase().includes(O))}return z},[j,o,d]),T=()=>{m.size===k.length?p(new Set):p(new Set(k.map(z=>z.id)))},E=z=>{const O=new Set(m);O.has(z)?O.delete(z):O.add(z),p(O)},A=S.useMemo(()=>j.filter(z=>m.has(z.id)).map(z=>({id:z.id,first_name:z.first_name||"there",last_name:z.last_name,email:z.email})),[j,m]),{defaultSubject:D,defaultBody:R}=S.useMemo(()=>{var fe,je,ve,We;const z=r.property_address||`${r.city}, ${r.state}`,O=aRs(r.price),$=iRs[r.property_type]||"home",ee=r.bedrooms?`${r.bedrooms} bed`:"",Z=r.bathrooms?`${r.bathrooms} bath`:"",J=r.square_footage?`${r.square_footage.toLocaleString()} sqft`:"",K=[ee,Z,J].filter(Boolean).join(" • "),re=`https://listings.relevelup.com/${r.slug||r.id}`,ie=((je=(fe=r.photos)==null?void 0:fe.find(Ve=>Ve.is_primary))==null?void 0:je.photo_url)||((We=(ve=r.photos)==null?void 0:ve[0])==null?void 0:We.photo_url)||"",ne={active:"Just Listed",coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"}[r.status]||"New Listing",le=`${ne}: ${z} — ${O}`,be=`

Hi {{first_name}},

I wanted to share a property I think you might love. Take a look:

${ie?` ${z} `:""}
${ne}

${O}

${z}

${r.city}, ${r.state}

${K?`

${K} • ${$}

`:""} View Photos & Details →

If this catches your eye — or you know someone who'd love it — just hit reply. I'd be happy to set up a private showing.

Talk soon,

`;return{defaultSubject:le,defaultBody:be}},[r]);return x?e.jsx(X_,{open:x,onOpenChange:z=>{y(z),z||t(!1)},bulkContacts:A,defaultSubject:D,defaultBody:R,gmailEmail:_}):e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"sm:max-w-[640px] max-h-[90vh] flex flex-col",children:[e.jsxs(Cs,{children:[e.jsxs(Ns,{className:"flex items-center gap-2",children:[e.jsx(Lr,{className:"h-5 w-5 text-amber-500"}),"Email this listing to your sphere"]}),e.jsx(nn,{children:"Pick which contacts should hear about this property. We'll personalize each email with their name."})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Mn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Se,{placeholder:"Search contacts...",value:o,onChange:z=>c(z.target.value),className:"pl-9"})]}),e.jsxs(Bs,{value:d,onValueChange:h,children:[e.jsx(Os,{className:"sm:w-[180px]",children:e.jsx(Us,{placeholder:"Filter by tag"})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"all",children:"All contacts"}),l.map(z=>e.jsx(pt,{value:z.id,children:z.name},z.id))]})]})]}),e.jsxs("div",{className:"flex items-center justify-between text-sm border-y py-2",children:[e.jsxs("button",{type:"button",onClick:T,className:"flex items-center gap-2 text-primary hover:underline",children:[e.jsx(ao,{checked:k.length>0&&m.size===k.length,className:"pointer-events-none"}),e.jsx("span",{children:m.size===k.length&&k.length>0?"Deselect all":`Select all (${k.length})`})]}),e.jsxs(Xe,{variant:"secondary",className:"gap-1",children:[e.jsx(Ar,{className:"h-3 w-3"}),m.size," selected"]})]}),e.jsx(Ci,{className:"flex-1 -mx-6 px-6",children:i?e.jsxs("div",{className:"flex items-center justify-center py-12 text-muted-foreground",children:[e.jsx(is,{className:"h-5 w-5 animate-spin mr-2"}),"Loading your contacts..."]}):k.length===0?e.jsx("div",{className:"text-center py-12 text-muted-foreground text-sm",children:j.length===0?"No contacts with email addresses yet.":"No contacts match your search."}):e.jsx("div",{className:"space-y-1 py-2",children:k.map(z=>e.jsxs("label",{className:"flex items-center gap-3 p-2 rounded-md hover:bg-muted/50 cursor-pointer",children:[e.jsx(ao,{checked:m.has(z.id),onCheckedChange:()=>E(z.id)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("p",{className:"text-sm font-medium truncate",children:[z.first_name," ",z.last_name]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:z.email})]}),z.tags&&z.tags.length>0&&e.jsx("div",{className:"flex gap-1 flex-wrap justify-end max-w-[40%]",children:z.tags.slice(0,2).map(O=>{var $;return e.jsx(Xe,{variant:"outline",className:"text-[10px] px-1.5 py-0",children:($=O.relationship_type)==null?void 0:$.name},O.id)})})]},z.id))})}),e.jsx(Qo,{}),e.jsxs("div",{className:"flex justify-between items-center gap-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:_?`Sending from ${_}`:"Connect Gmail in Settings to send"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(H,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(H,{onClick:()=>y(!0),disabled:m.size===0,className:"gap-2",children:[e.jsx(er,{className:"h-4 w-4"}),"Compose Email (",m.size,")"]})]})]})]})})}function Ry(s){const t=s.expected_commission;if(!t)return null;if((s.commission_calc_method||"standard")==="referral_first"){let a=t;s.referral_fee_pct&&(a-=t*(s.referral_fee_pct/100));let i=a;return s.brokerage_split_pct&&(i-=a*(s.brokerage_split_pct/100)),s.team_split_pct&&(i-=t*(s.team_split_pct/100)),s.franchise_fee_pct&&(i-=t*(s.franchise_fee_pct/100)),s.transaction_fee&&(i-=s.transaction_fee),Math.max(0,i)}let n=t;return s.brokerage_split_pct&&(n-=t*(s.brokerage_split_pct/100)),s.team_split_pct&&(n-=t*(s.team_split_pct/100)),s.franchise_fee_pct&&(n-=t*(s.franchise_fee_pct/100)),s.referral_fee_pct&&(n-=t*(s.referral_fee_pct/100)),s.transaction_fee&&(n-=s.transaction_fee),Math.max(0,n)}function F0e(){const s=ba();return yt({queryKey:["deal-pipeline-stages",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await V.from("deal_pipeline_stages").select("*").eq("owner_user_id",s).order("sort_order",{ascending:!0});if(r)throw r;return t},enabled:!!s})}function yxt(){const s=ba(),t=ns();return Pt({mutationFn:async()=>{if(!s)throw new Error("Not authenticated");const{error:r}=await V.rpc("initialize_deal_pipeline_stages",{p_user_id:s});if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-pipeline-stages"]})}})}function B0e(){const s=ba();return yt({queryKey:["deal-pipeline-deals",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await V.from("deal_pipeline").select(` *, contact:innercircle_contacts(id, first_name, last_name, email, phone), listing:listings(id, property_address, city, state, price, status, created_at) `).eq("owner_user_id",s).order("updated_at",{ascending:!1});if(r)throw r;return t},enabled:!!s})}function vxt(){const s=ba(),t=ns();return Pt({mutationFn:async r=>{if(!s)throw new Error("Not authenticated");const{data:n,error:a}=await V.from("deal_pipeline").insert({deal_name:r.deal_name,deal_type:r.deal_type,stage_id:r.stage_id||null,contact_id:r.contact_id||null,listing_id:r.listing_id||null,property_address:r.property_address||null,city:r.city||null,state:r.state||null,zip_code:r.zip_code||null,expected_price:r.expected_price||null,expected_commission:r.expected_commission||null,commission_percentage:r.commission_percentage||3,target_close_date:r.target_close_date||null,contract_date:r.contract_date||null,listing_date:r.listing_date||null,priority:r.priority||"medium",probability:r.probability||50,notes:r.notes||null,owner_user_id:s}).select().single();if(a)throw a;return await V.from("deal_activities").insert([{deal_id:n.id,activity_type:"system",title:"Deal created",description:`Deal "${r.deal_name}" was created`}]),n},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-pipeline-deals"]}),t.invalidateQueries({queryKey:["deal-pipeline-stats"]})}})}function bxt(){const s=ns();return Pt({mutationFn:async({id:t,...r})=>{const{data:n,error:a}=await V.from("deal_pipeline").update(r).eq("id",t).select().single();if(a)throw a;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-pipeline-deals"]}),s.invalidateQueries({queryKey:["deal-pipeline-stats"]})}})}function lRs(){const s=ns();return Pt({mutationFn:async({dealId:t,stageId:r,stageName:n})=>{const{data:a,error:i}=await V.from("deal_pipeline").update({stage_id:r}).eq("id",t).select().single();if(i)throw i;return await V.from("deal_activities").insert({deal_id:t,activity_type:"stage_change",title:`Moved to ${n}`,metadata:{new_stage_id:r,new_stage_name:n}}),a},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-pipeline-deals"]}),s.invalidateQueries({queryKey:["deal-activities"]})}})}function cRs(){const s=ns();return Pt({mutationFn:async t=>{const{error:r}=await V.from("deal_pipeline").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-pipeline-deals"]}),s.invalidateQueries({queryKey:["deal-pipeline-stats"]})}})}function dRs(s){return yt({queryKey:["deal-activities",s],queryFn:async()=>{const{data:t,error:r}=await V.from("deal_activities").select("*").eq("deal_id",s).order("created_at",{ascending:!1});if(r)throw r;return t},enabled:!!s})}function uRs(){const s=ns();return Pt({mutationFn:async t=>{const{data:r,error:n}=await V.from("deal_activities").insert([{deal_id:t.deal_id,activity_type:t.activity_type,title:t.title,description:t.description||null}]).select().single();if(n)throw n;return r},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["deal-activities",r.deal_id]})}})}function hRs(s){return yt({queryKey:["deal-checklist",s],queryFn:async()=>{const{data:t,error:r}=await V.from("deal_checklist_items").select("*").eq("deal_id",s).order("sort_order",{ascending:!0});if(r)throw r;return t},enabled:!!s})}function mRs(){const s=ns();return Pt({mutationFn:async({id:t,is_completed:r,deal_id:n})=>{const{data:a,error:i}=await V.from("deal_checklist_items").update({is_completed:r,completed_at:r?new Date().toISOString():null}).eq("id",t).select().single();if(i)throw i;return a},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["deal-checklist",r.deal_id]})}})}function fRs(){const s=ns();return Pt({mutationFn:async t=>{const{data:r,error:n}=await V.from("deal_checklist_items").insert([{deal_id:t.deal_id,title:t.title,description:t.description||null,due_date:t.due_date||null,sort_order:t.sort_order||0}]).select().single();if(n)throw n;return r},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["deal-checklist",r.deal_id]})}})}function pRs(){const s=ba();return yt({queryKey:["deal-pipeline-stats",s],queryFn:async()=>{if(!s)return null;const{data:t,error:r}=await V.from("deal_pipeline").select("*, deal_pipeline_stages(name, is_won_stage, is_lost_stage)").eq("owner_user_id",s);if(r)throw r;const n=(t==null?void 0:t.filter(o=>{var c,d,h;return!((c=o.deal_pipeline_stages)!=null&&c.is_won_stage)&&!((d=o.deal_pipeline_stages)!=null&&d.is_lost_stage)&&((h=o.deal_pipeline_stages)==null?void 0:h.name)!=="Cancelled"}))||[],a=(t==null?void 0:t.filter(o=>{var c;return(c=o.deal_pipeline_stages)==null?void 0:c.is_won_stage}))||[],i=new Date().getFullYear(),l=a.filter(o=>{const c=o.actual_close_date;return c?new Date(c).getFullYear()===i:!0});return{totalDeals:(t==null?void 0:t.length)||0,activeDeals:n.length,wonDeals:a.length,pipelineValue:n.reduce((o,c)=>o+(c.expected_price||0),0),expectedCommission:n.reduce((o,c)=>o+(c.expected_commission||0),0),expectedNetToAgent:n.reduce((o,c)=>o+(Ry(c)||0),0),wonValue:a.reduce((o,c)=>o+(c.expected_price||0),0),weightedGCI:n.reduce((o,c)=>{const d=(c.probability??50)/100;return o+(c.expected_commission||0)*d},0),weightedNet:n.reduce((o,c)=>{const d=(c.probability??50)/100;return o+(Ry(c)||0)*d},0),ytdWonDeals:l.length,ytdWonGCI:l.reduce((o,c)=>o+(c.expected_commission||0),0),ytdWonNet:l.reduce((o,c)=>o+(Ry(c)||0),0),projectedAnnualNet:l.reduce((o,c)=>o+(Ry(c)||0),0)+n.reduce((o,c)=>{const d=(c.probability??50)/100;return o+(Ry(c)||0)*d},0)}},enabled:!!s})}function gRs(s){const t=ba();return yt({queryKey:["deal-by-listing",s,t],queryFn:async()=>{if(!t||!s)return null;const{data:r,error:n}=await V.from("deal_pipeline").select(` *, deal_pipeline_stages(id, name, color) `).eq("owner_user_id",t).eq("listing_id",s).maybeSingle();if(n)throw n;return r},enabled:!!t&&!!s})}function xRs(){const s=ns();return Pt({mutationFn:async({dealId:t,listingId:r})=>{const{data:n,error:a}=await V.from("deal_pipeline").update({listing_id:r}).eq("id",t).select().single();if(a)throw a;return await V.from("deal_activities").insert({deal_id:t,activity_type:"system",title:"Linked to Listing Exchange",description:"This deal is now synced with Listing Exchange",metadata:{listing_id:r}}),n},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["deal-pipeline-deals"]}),s.invalidateQueries({queryKey:["deal-by-listing",r.listingId]})}})}function yRs(){const s=ns();return Pt({mutationFn:async({dealId:t,listingId:r})=>{const{data:n,error:a}=await V.from("deal_pipeline").update({listing_id:null}).eq("id",t).select().single();if(a)throw a;return{data:n,listingId:r}},onSuccess:t=>{s.invalidateQueries({queryKey:["deal-pipeline-deals"]}),s.invalidateQueries({queryKey:["deal-by-listing",t.listingId]})}})}function vRs({listing:s}){const t=Fr(),[r,n]=S.useState(""),[a,i]=S.useState(!1),{data:l,isLoading:o}=gRs(s.id),{data:c,isLoading:d}=F0e(),{data:h,isLoading:m}=B0e(),p=yxt(),x=xRs(),y=yRs(),_=vxt(),b=(h==null?void 0:h.filter(A=>!A.listing_id))||[],j=A=>{if(!(c!=null&&c.length))return null;switch(A){case"coming_soon":case"active":case"price_improvement":return c.find(D=>D.name==="Active");case"under_contract":return c.find(D=>D.name==="Under Contract");case"sold":return c.find(D=>D.is_won_stage);default:return c.find(D=>D.name==="Active")}},k=async()=>{i(!0);try{c!=null&&c.length||await p.mutateAsync();const A=j(s.status);await _.mutateAsync({deal_name:s.property_address?`${s.property_address}, ${s.city}`:`${s.city}, ${s.state}`,deal_type:"seller",stage_id:(A==null?void 0:A.id)||null,listing_id:s.id,property_address:s.property_address,city:s.city,state:s.state,expected_price:s.price,expected_commission:s.price*.03,commission_percentage:3,priority:"medium",probability:50}),he.success("Deal created and linked to listing!")}catch(A){console.error("Failed to create deal:",A),he.error("Failed to create deal")}finally{i(!1)}},T=async()=>{if(!r){he.error("Please select a deal");return}try{await x.mutateAsync({dealId:r,listingId:s.id}),he.success("Listing linked to deal!"),n("")}catch{he.error("Failed to link listing")}},E=async()=>{if(l)try{await y.mutateAsync({dealId:l.id,listingId:s.id}),he.success("Listing unlinked from deal")}catch{he.error("Failed to unlink listing")}};return o||d?e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsxs(zt,{className:"flex items-center gap-2 text-base",children:[e.jsx(p_,{className:"h-4 w-4"}),"Deal Pipeline"]})}),e.jsx(Oe,{children:e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(is,{className:"h-5 w-5 animate-spin text-muted-foreground"})})})]}):l?e.jsxs(ke,{className:"border-primary/20 bg-primary/5",children:[e.jsx(Ot,{className:"pb-2",children:e.jsxs(zt,{className:"flex items-center gap-2 text-base",children:[e.jsx(ql,{className:"h-4 w-4 text-primary"}),"Linked to Pipeline"]})}),e.jsxs(Oe,{className:"space-y-3",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:l.deal_name}),e.jsx("div",{className:"flex items-center gap-2 mt-1",children:l.deal_pipeline_stages&&e.jsx(Xe,{variant:"secondary",className:"text-xs",style:{backgroundColor:`${l.deal_pipeline_stages.color}20`,color:l.deal_pipeline_stages.color},children:l.deal_pipeline_stages.name})})]})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Status changes sync automatically between the listing and pipeline."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(H,{variant:"outline",size:"sm",className:"flex-1",onClick:()=>t("/mission-control/pipeline"),children:["View Pipeline",e.jsx(bi,{className:"h-3 w-3 ml-1"})]}),e.jsx(H,{variant:"ghost",size:"sm",onClick:E,disabled:y.isPending,children:y.isPending?e.jsx(is,{className:"h-4 w-4 animate-spin"}):e.jsx(BE,{className:"h-4 w-4"})})]})]})]}):e.jsxs(ke,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsxs(zt,{className:"flex items-center gap-2 text-base",children:[e.jsx(p_,{className:"h-4 w-4"}),"Deal Pipeline"]})}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Link this listing to your pipeline to track the deal and sync status changes."}),e.jsxs(H,{onClick:k,disabled:a||_.isPending,className:"w-full",size:"sm",children:[a||_.isPending?e.jsx(is,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Create New Deal"]}),b.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute inset-0 flex items-center",children:e.jsx("span",{className:"w-full border-t"})}),e.jsx("div",{className:"relative flex justify-center text-xs uppercase",children:e.jsx("span",{className:"bg-card px-2 text-muted-foreground",children:"or"})})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Bs,{value:r,onValueChange:n,children:[e.jsx(Os,{className:"flex-1 text-sm",children:e.jsx(Us,{placeholder:"Link to existing deal..."})}),e.jsx(Fs,{children:b.map(A=>e.jsx(pt,{value:A.id,children:A.deal_name},A.id))})]}),e.jsx(H,{variant:"secondary",size:"icon",onClick:T,disabled:!r||x.isPending,children:x.isPending?e.jsx(is,{className:"h-4 w-4 animate-spin"}):e.jsx(ql,{className:"h-4 w-4"})})]})]})]})]})}const bRs={active:"bg-emerald-500",coming_soon:"bg-sky-500",office_exclusive:"bg-indigo-500",pre_market:"bg-cyan-500",price_improvement:"bg-orange-500",under_contract:"bg-purple-500",sold:"bg-gray-500"},_Rs={active:"Active",coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"},sGe={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"};function wRs(){var ce,ne,le,be,fe,je,ve,We,Ve;const{listingId:s}=Po(),t=Fr(),{user:r}=Ms(),{data:n,isLoading:a}=_Te(s||""),{data:i}=wot(s||""),{data:l}=IHt(s||""),o=_ot(),c=MHt(),d=PHt(),h=bot(),m=DHt(),[p,x]=S.useState(!1),[y,_]=S.useState(!1),[b,j]=S.useState(!1),[k,T]=S.useState(!1),[E,A]=S.useState(!1),[D,R]=S.useState(null),[z,O]=S.useState({buyerName:"",buyerType:"",notes:""}),$=(r==null?void 0:r.id)===(n==null?void 0:n.agent_id),ee=Le=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(Le),Z=async Le=>{const Me=`https://listings.relevelup.com/${(n==null?void 0:n.slug)||(n==null?void 0:n.id)}`,ze=`Check out this listing: ${(n==null?void 0:n.property_address)||(n==null?void 0:n.city)}`;d.mutate({listingId:n.id,shareType:Le});try{switch(Le){case"facebook":window.open(`https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(Me)}`,"_blank");break;case"copy":await navigator.clipboard.writeText(Me),he.success("Link copied to clipboard!");break;case"text":window.open(`sms:?body=${encodeURIComponent(`${ze} ${Me}`)}`);break;case"email":window.open(`mailto:?subject=${encodeURIComponent(ze)}&body=${encodeURIComponent(`Check out this listing: ${Me}`)}`);break}}catch(Pe){console.error("Share error:",Pe),he.error("Failed to share")}},J=async()=>{try{await h.mutateAsync(n.id),he.success("Listing deleted"),t("/mission-control/listings")}catch{he.error("Failed to delete listing")}},K=async()=>{if(!z.buyerName.trim()){he.error("Please enter buyer name");return}try{await m.mutateAsync({listingId:n.id,listingAgentId:n.agent_id,buyerName:z.buyerName,buyerType:z.buyerType||void 0,notes:z.notes||void 0}),he.success("Referral sent successfully!"),_(!1),O({buyerName:"",buyerType:"",notes:""})}catch{he.error("Failed to send referral")}},re=Le=>{var tt,ge;const Me=(n==null?void 0:n.property_address)||`${n==null?void 0:n.city}, ${n==null?void 0:n.state}`,ze=ee((n==null?void 0:n.price)||0),Pe=n!=null&&n.bedrooms?`${n.bedrooms}BD`:"",Ie=n!=null&&n.bathrooms?`${n.bathrooms}BA`:"",De=n!=null&&n.square_footage?`${n.square_footage.toLocaleString()}SF`:"",pe=[Pe,Ie,De].filter(Boolean).join(" | ");switch(Le){case"just_listed":return`🏡 JUST LISTED! ${Me} ${ze} ${pe} ${(n==null?void 0:n.description)||"Schedule your showing today!"} #JustListed #RealEstate #HomeForSale #${(tt=n==null?void 0:n.city)==null?void 0:tt.replace(/\s/g,"")}`;case"price_improvement":return`📣 PRICE IMPROVEMENT! ${Me} Now ${ze}! ${pe} Don't miss this opportunity! #PriceReduced #RealEstate #HomeForSale`;case"teaser":return`Looking for a ${sGe[(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! ${pe} DM me for details! 📩 #ComingSoon #RealEstate #${(ge=n==null?void 0:n.city)==null?void 0:ge.replace(/\s/g,"")}`;default:return""}};if(a)return e.jsx(Ss,{title:"Listing",description:"",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Ks,{className:"h-10 w-32"}),e.jsx(Ks,{className:"h-[400px] w-full"}),e.jsxs("div",{className:"grid md:grid-cols-3 gap-6",children:[e.jsx(Ks,{className:"h-48"}),e.jsx(Ks,{className:"h-48"}),e.jsx(Ks,{className:"h-48"})]})]})});if(!n)return e.jsx(Ss,{title:"Listing Not Found",description:"",children:e.jsx(ke,{children:e.jsxs(Oe,{className:"py-12 text-center",children:[e.jsx("p",{className:"text-muted-foreground mb-4",children:"This listing could not be found."}),e.jsx(H,{onClick:()=>t("/mission-control/listings"),children:"Back to Listings"})]})})});const ie=((ce=n.photos)==null?void 0:ce.find(Le=>Le.is_primary))||((ne=n.photos)==null?void 0:ne[0]);return e.jsxs(Ss,{title:"",description:"",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs(H,{variant:"ghost",onClick:()=>t("/mission-control/listings"),children:[e.jsx(za,{className:"h-4 w-4 mr-2"}),"Back to Listings"]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsx("div",{className:"md:col-span-2",children:e.jsx("div",{className:"aspect-[16/10] rounded-lg overflow-hidden bg-muted cursor-pointer",onClick:()=>ie&&R(ie.photo_url),children:ie?e.jsx("img",{src:ie.photo_url,alt:"Primary",className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground",children:"No photos"})})}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:(le=n.photos)==null?void 0:le.slice(1,5).map((Le,Me)=>e.jsx("div",{className:"aspect-square rounded-lg overflow-hidden bg-muted cursor-pointer",onClick:()=>R(Le.photo_url),children:e.jsx("img",{src:Le.photo_url,alt:`Photo ${Me+2}`,className:"w-full h-full object-cover"})},Le.id))})]}),e.jsxs("div",{className:"grid md:grid-cols-3 gap-6",children:[e.jsxs("div",{className:"md:col-span-2 space-y-6",children:[e.jsx(ke,{children:e.jsxs(Oe,{className:"p-6",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-4 mb-6",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Xe,{className:`${bRs[n.status]} text-white border-0`,children:_Rs[n.status]}),n.is_featured&&e.jsxs(Xe,{variant:"outline",className:"border-amber-500 text-amber-500",children:[e.jsx(ya,{className:"h-3 w-3 mr-1 fill-amber-500"}),"Featured"]}),n.open_to_referrals&&e.jsxs(Xe,{variant:"outline",children:[e.jsx(Ar,{className:"h-3 w-3 mr-1"}),"Open to Referrals"]})]}),e.jsx("h1",{className:"text-3xl font-bold text-primary mb-2",children:ee(n.price)}),n.property_address&&e.jsx("p",{className:"text-xl font-medium",children:n.property_address}),e.jsxs("p",{className:"text-muted-foreground flex items-center gap-1",children:[e.jsx(Qa,{className:"h-4 w-4"}),n.city,", ",n.state,n.neighborhood&&` • ${n.neighborhood}`]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(H,{variant:"outline",size:"icon",onClick:()=>o.mutate(n.id),children:e.jsx(Bi,{className:`h-4 w-4 ${i?"fill-pink-500 text-pink-500":""}`})}),e.jsx(H,{variant:"outline",size:"icon",onClick:()=>c.mutate(n.id),children:l?e.jsx(u_,{className:"h-4 w-4"}):e.jsx(wp,{className:"h-4 w-4"})}),!$&&e.jsxs(H,{variant:"outline",className:"border-amber-500 text-amber-600 hover:bg-amber-50",onClick:()=>j(!0),children:[e.jsx(Lr,{className:"h-4 w-4 mr-2"}),"Share & Earn Leads"]}),e.jsxs(Xu,{children:[e.jsx(Qu,{asChild:!0,children:e.jsxs(H,{variant:"outline",children:[e.jsx(cd,{className:"h-4 w-4 mr-2"}),"Share"]})}),e.jsxs(wu,{children:[e.jsxs(di,{onClick:()=>Z("copy"),children:[e.jsx(ui,{className:"h-4 w-4 mr-2"}),"Copy Link"]}),e.jsxs(di,{onClick:()=>Z("facebook"),children:[e.jsx(fh,{className:"h-4 w-4 mr-2"}),"Facebook"]}),e.jsxs(di,{onClick:()=>Z("text"),children:[e.jsx(Gi,{className:"h-4 w-4 mr-2"}),"Text"]}),e.jsxs(di,{onClick:()=>Z("email"),children:[e.jsx(er,{className:"h-4 w-4 mr-2"}),"Email"]})]})]}),$&&e.jsxs(e.Fragment,{children:[e.jsxs(H,{variant:"outline",onClick:()=>{const Le=(n.photos??[]).slice().sort((Me,ze)=>(ze.is_primary?1:0)-(Me.is_primary?1:0)||(Me.sort_order??0)-(ze.sort_order??0)).map(Me=>Me.photo_url).filter(Boolean);if(Le.length===0){he.error("Add photos to this listing first.");return}mxt({photos:Le,details:{address:n.property_address||`${n.city??""} ${n.state??""}`.trim(),beds:n.bedrooms?String(n.bedrooms):"",baths:n.bathrooms?String(n.bathrooms):"",sqft:n.square_footage?String(n.square_footage):"",price:n.price?String(n.price):"",highlights:n.description||""},sourceLabel:"Listing Exchange",badge:fxt(n.status,n.price)}),t("/admin/beta/homereel?tab=music-video")},className:"gap-2 border-violet-500/60 text-violet-600 hover:bg-violet-50",children:[e.jsx(GI,{className:"h-4 w-4"}),"Create Music Video"]}),e.jsxs(H,{variant:"outline",onClick:()=>A(!0),className:"gap-2 border-amber-500/60 text-amber-600 hover:bg-amber-50",children:[e.jsx(Lr,{className:"h-4 w-4"}),"Just Listed Graphic"]}),e.jsxs(H,{variant:"outline",onClick:()=>T(!0),className:"gap-2",children:[e.jsx(er,{className:"h-4 w-4"}),"Email My Sphere"]}),e.jsxs(H,{variant:"outline",onClick:()=>t(`/mission-control/listings/${n.id}/edit`),children:[e.jsx(ou,{className:"h-4 w-4 mr-2"}),"Edit"]}),e.jsx(H,{variant:"destructive",size:"icon",onClick:()=>x(!0),children:e.jsx(Dr,{className:"h-4 w-4"})})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-4 py-4 border-y",children:[n.bedrooms&&e.jsxs("div",{className:"text-center",children:[e.jsx(x1,{className:"h-5 w-5 mx-auto mb-1 text-muted-foreground"}),e.jsx("p",{className:"font-semibold",children:n.bedrooms}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Beds"})]}),n.bathrooms&&e.jsxs("div",{className:"text-center",children:[e.jsx(_p,{className:"h-5 w-5 mx-auto mb-1 text-muted-foreground"}),e.jsx("p",{className:"font-semibold",children:n.bathrooms}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Baths"})]}),n.square_footage&&e.jsxs("div",{className:"text-center",children:[e.jsx(Hy,{className:"h-5 w-5 mx-auto mb-1 text-muted-foreground"}),e.jsx("p",{className:"font-semibold",children:n.square_footage.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Sq Ft"})]}),n.year_built&&e.jsxs("div",{className:"text-center",children:[e.jsx(Nn,{className:"h-5 w-5 mx-auto mb-1 text-muted-foreground"}),e.jsx("p",{className:"font-semibold",children:n.year_built}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Built"})]})]}),e.jsxs("div",{className:"pt-4 space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(Xe,{variant:"secondary",children:[e.jsx(Xa,{className:"h-3 w-3 mr-1"}),sGe[n.property_type]]}),n.lot_size&&e.jsxs(Xe,{variant:"secondary",children:["Lot: ",n.lot_size]}),n.has_hoa&&e.jsx(Xe,{variant:"secondary",children:"HOA"})]}),n.description&&e.jsxs("div",{children:[e.jsx("h3",{className:"font-medium mb-2",children:"Description"}),e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:n.description})]}),n.agent_notes&&n.agent_notes_public&&e.jsxs("div",{children:[e.jsx("h3",{className:"font-medium mb-2",children:"Agent Notes"}),e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:n.agent_notes})]}),n.mls_link&&e.jsx(H,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:n.mls_link,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(gn,{className:"h-4 w-4 mr-2"}),"View on MLS"]})})]}),e.jsxs("div",{className:"flex items-center gap-4 pt-4 mt-4 border-t text-sm text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Bn,{className:"h-4 w-4"}),n.view_count," views"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(cd,{className:"h-4 w-4"}),n.share_count," shares"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Bi,{className:"h-4 w-4"}),n.save_count," saves"]})]})]})}),n.allow_sharing&&e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-lg",children:"Share Content"})}),e.jsx(Oe,{className:"space-y-4",children:["just_listed","price_improvement","teaser"].map(Le=>e.jsxs("div",{className:"p-3 bg-muted rounded-lg",children:[e.jsxs("div",{className:"flex justify-between items-start mb-2",children:[e.jsxs("p",{className:"font-medium text-sm capitalize",children:[Le.replace("_"," ")," Caption"]}),e.jsx(H,{size:"sm",variant:"ghost",onClick:()=>{navigator.clipboard.writeText(re(Le)),he.success("Caption copied!")},children:e.jsx(ui,{className:"h-3 w-3"})})]}),e.jsx("p",{className:"text-xs text-muted-foreground whitespace-pre-wrap",children:re(Le)})]},Le))})]}),e.jsx(eRs,{listingId:n.id,ownerOnly:$})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-lg",children:"Listing Agent"})}),e.jsxs(Oe,{children:[e.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[e.jsx("div",{className:"w-12 h-12 rounded-full bg-primary/10 flex items-center justify-center",children:e.jsx("span",{className:"text-lg font-semibold text-primary",children:((fe=(be=n.agent)==null?void 0:be.name)==null?void 0:fe.charAt(0))||"?"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((je=n.agent)==null?void 0:je.name)||"Unknown"}),((We=(ve=n.agent)==null?void 0:ve.brokerage)==null?void 0:We.name)&&e.jsx("p",{className:"text-sm text-muted-foreground",children:n.agent.brokerage.name})]})]}),!$&&e.jsx("div",{className:"space-y-2",children:((Ve=n.agent)==null?void 0:Ve.email)&&e.jsx(H,{variant:"outline",className:"w-full",asChild:!0,children:e.jsxs("a",{href:`mailto:${n.agent.email}`,children:[e.jsx(er,{className:"h-4 w-4 mr-2"}),"Email Agent"]})})})]})]}),$&&e.jsx(vRs,{listing:n}),!$&&n.open_to_referrals&&e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsxs(zt,{className:"text-lg flex items-center gap-2",children:[e.jsx(Ar,{className:"h-5 w-5"}),"Send a Buyer"]})}),e.jsxs(Oe,{children:[e.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."}),e.jsx(H,{className:"w-full",onClick:()=>_(!0),children:"Send Referral"})]})]})]})]})]}),e.jsx(bs,{open:!!D,onOpenChange:()=>R(null),children:e.jsx(vs,{className:"max-w-4xl",children:e.jsx("img",{src:D||"",alt:"Full size",className:"w-full h-auto"})})}),e.jsx(bs,{open:p,onOpenChange:x,children:e.jsxs(vs,{children:[e.jsxs(Cs,{children:[e.jsx(Ns,{children:"Delete Listing"}),e.jsx(nn,{children:"Are you sure you want to delete this listing? This action cannot be undone."})]}),e.jsxs(wn,{children:[e.jsx(H,{variant:"outline",onClick:()=>x(!1),children:"Cancel"}),e.jsx(H,{variant:"destructive",onClick:J,disabled:h.isPending,children:h.isPending?"Deleting...":"Delete"})]})]})}),e.jsx(bs,{open:y,onOpenChange:_,children:e.jsxs(vs,{children:[e.jsxs(Cs,{children:[e.jsx(Ns,{children:"Send Buyer Referral"}),e.jsx(nn,{children:"Submit buyer information to the listing agent"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Buyer Name *"}),e.jsx(Se,{value:z.buyerName,onChange:Le=>O({...z,buyerName:Le.target.value}),placeholder:"Enter buyer's name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Buyer Type"}),e.jsxs(Bs,{value:z.buyerType,onValueChange:Le=>O({...z,buyerType:Le}),children:[e.jsx(Os,{children:e.jsx(Us,{placeholder:"Select type"})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"first_time",children:"First-Time Buyer"}),e.jsx(pt,{value:"investor",children:"Investor"}),e.jsx(pt,{value:"relocating",children:"Relocating"}),e.jsx(pt,{value:"upgrade",children:"Upgrading"}),e.jsx(pt,{value:"downsize",children:"Downsizing"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Notes"}),e.jsx(vr,{value:z.notes,onChange:Le=>O({...z,notes:Le.target.value}),placeholder:"Any additional information..."})]})]}),e.jsxs(wn,{children:[e.jsx(H,{variant:"outline",onClick:()=>_(!1),children:"Cancel"}),e.jsx(H,{onClick:K,disabled:m.isPending,children:m.isPending?"Sending...":"Send Referral"})]})]})}),e.jsx(hxt,{open:b,onOpenChange:j,listingId:(n==null?void 0:n.id)||"",listingSlug:(n==null?void 0:n.slug)||null,listingTitle:(n==null?void 0:n.property_address)||`${n==null?void 0:n.city}, ${n==null?void 0:n.state}`}),n&&e.jsx(oRs,{open:k,onOpenChange:T,listing:n}),e.jsx(xxt,{listingId:(n==null?void 0:n.id)||null,open:E,onOpenChange:A})]})}function jRs({onImport:s}){const[t,r]=S.useState(""),[n,a]=S.useState([]),[i,l]=S.useState(!1),[o,c]=S.useState(!1),[d,h]=S.useState(null),m=S.useRef(),p=S.useRef(null);S.useEffect(()=>{const k=T=>{p.current&&!p.current.contains(T.target)&&c(!1)};return document.addEventListener("mousedown",k),()=>document.removeEventListener("mousedown",k)},[]);const x=async k=>{if(k.trim().length<3){a([]),c(!1);return}l(!0);try{const{data:T,error:E}=await V.functions.invoke("mls-listing-search",{body:{query:k}});if(E)throw E;a((T==null?void 0:T.listings)||[]),c(!0)}catch(T){console.error("MLS search error:",T),a([])}finally{l(!1)}},y=k=>{r(k),m.current&&clearTimeout(m.current),m.current=setTimeout(()=>x(k),400)},_=k=>{h(k.mlsNumber),s(k),c(!1),r(`${k.address}, ${k.city}`),he.success(`Imported: ${k.address}`,{description:"Property details and photos have been auto-filled."}),h(null)},b=k=>k?`$${k.toLocaleString()}`:"",j=k=>{const T=(k||"").toLowerCase();return T.includes("single")||T.includes("detached")?"Single Family":T.includes("condo")?"Condo":T.includes("town")?"Townhouse":T.includes("land")||T.includes("lot")?"Land":T.includes("multi")?"Multi-Family":T.includes("commercial")?"Commercial":k||"Other"};return e.jsxs(ke,{className:"border-primary/30 bg-primary/5",children:[e.jsxs(Ot,{className:"pb-3",children:[e.jsxs(zt,{className:"text-base flex items-center gap-2",children:[e.jsx(hi,{className:"h-4 w-4 text-primary"}),"Import from MLS"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Search by address to auto-fill property details and photos from MLS"})]}),e.jsx(Oe,{children:e.jsxs("div",{ref:p,className:"relative",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Mn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Se,{value:t,onChange:k=>y(k.target.value),onFocus:()=>n.length>0&&c(!0),placeholder:"Start typing a property address...",className:"pl-9 pr-9"}),i&&e.jsx(is,{className:"absolute right-3 top-1/2 -translate-y-1/2 h-4 w-4 animate-spin text-muted-foreground"}),t&&!i&&e.jsx("button",{type:"button",onClick:()=>{r(""),a([]),c(!1)},className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground",children:e.jsx(Rr,{className:"h-4 w-4"})})]}),o&&e.jsx("div",{className:"absolute z-50 w-full mt-1 bg-popover border rounded-lg shadow-lg max-h-[400px] overflow-y-auto",children:n.length===0&&!i?e.jsx("div",{className:"p-4 text-center text-sm text-muted-foreground",children:"No properties found. Try a different address."}):n.map(k=>e.jsxs("button",{type:"button",onClick:()=>_(k),disabled:d===k.mlsNumber,className:"w-full text-left p-3 hover:bg-accent/50 transition-colors border-b last:border-0 flex items-start gap-3",children:[k.photos[0]?e.jsx("img",{src:k.photos[0],alt:"",className:"w-16 h-12 rounded object-cover flex-shrink-0"}):e.jsx("div",{className:"w-16 h-12 rounded bg-muted flex items-center justify-center flex-shrink-0",children:e.jsx(Qa,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:k.address}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[k.city,", ",k.state," ",k.zip]}),e.jsxs("div",{className:"flex items-center gap-3 mt-1 text-xs text-muted-foreground",children:[e.jsx("span",{className:"font-semibold text-foreground",children:b(k.price)}),k.bedrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(x1,{className:"h-3 w-3"})," ",k.bedrooms]}),k.bathrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(_p,{className:"h-3 w-3"})," ",k.bathrooms]}),k.sqft>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(LE,{className:"h-3 w-3"})," ",k.sqft.toLocaleString()]})]})]}),e.jsxs("div",{className:"flex-shrink-0 flex flex-col items-end gap-1",children:[e.jsx(Xe,{variant:"outline",className:"text-[10px]",children:j(k.propertyType)}),k.photos.length>0&&e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[k.photos.length," photos"]})]})]},k.mlsNumber))})]})})]})}function NRs({photo:s,onRemove:t,onSetPrimary:r}){const{attributes:n,listeners:a,setNodeRef:i,transform:l,transition:o,isDragging:c}=zxe({id:s.id}),d={transform:kS.Transform.toString(l),transition:o};return e.jsxs("div",{ref:i,style:d,className:Ft("relative aspect-square rounded-lg overflow-hidden bg-muted group",c&&"opacity-50 ring-2 ring-primary z-50"),children:[e.jsx("img",{src:s.photo_url,alt:"",className:"w-full h-full object-cover"}),e.jsx("button",{type:"button",...n,...a,className:"absolute top-1 left-1 p-1 bg-black/60 text-white rounded cursor-grab active:cursor-grabbing opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx(Oh,{className:"h-3.5 w-3.5"})}),e.jsx("button",{type:"button",onClick:()=>t(s.id),className:"absolute top-1 right-1 p-1 bg-destructive text-destructive-foreground rounded-full hover:bg-destructive/90 opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx(Rr,{className:"h-3 w-3"})}),s.is_primary?e.jsxs("span",{className:"absolute bottom-1 left-1 text-[10px] bg-primary text-primary-foreground px-1.5 py-0.5 rounded flex items-center gap-0.5",children:[e.jsx(ya,{className:"h-2.5 w-2.5 fill-current"})," Primary"]}):e.jsx("button",{type:"button",onClick:()=>r(s.id),className:"absolute bottom-1 left-1 text-[10px] bg-black/60 text-white px-1.5 py-0.5 rounded opacity-0 group-hover:opacity-100 transition-opacity hover:bg-black/80",children:"Set as Primary"})]})}function kRs({photos:s,uploading:t,onUpload:r,onRemove:n,onReorder:a,onSetPrimary:i}){const l=Mxe(fL(T8,{activationConstraint:{distance:5}})),o=[...s].sort((d,h)=>(d.sort_order??0)-(h.sort_order??0)),c=d=>{const{active:h,over:m}=d;if(!m||h.id===m.id)return;const p=o.findIndex(j=>j.id===h.id),x=o.findIndex(j=>j.id===m.id),y=[...o],[_]=y.splice(p,1);y.splice(x,0,_);const b=y.map((j,k)=>({...j,sort_order:k}));a(b)};return e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Drag photos to reorder. Hover to set primary."}),e.jsx(Oxe,{sensors:l,collisionDetection:Ixe,onDragEnd:c,children:e.jsx(Bxe,{items:o.map(d=>d.id),strategy:jz,children:e.jsxs("div",{className:"grid grid-cols-3 sm:grid-cols-4 gap-4",children:[o.map(d=>e.jsx(NRs,{photo:d,onRemove:n,onSetPrimary:i},d.id)),e.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:[t?e.jsx(is,{className:"h-8 w-8 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(Ea,{className:"h-8 w-8"}),e.jsx("span",{className:"text-xs",children:"Upload"})]}),e.jsx("input",{type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:d=>r(d.target.files),disabled:t})]})]})})})]})}function SRs({selectedVideoId:s,onVideoSelect:t,listingId:r}){const n=Fr(),{user:a}=Ms(),[i,l]=S.useState(!1),[o,c]=S.useState([]),[d,h]=S.useState(!1),[m,p]=S.useState(null),[x,y]=S.useState({});S.useEffect(()=>{s&&a?_():p(null)},[s,a]);const _=async()=>{if(!s)return;const{data:O,error:$}=await V.from("agent_videos").select("id, bunny_video_id, title, thumbnail_url, preview_url, playback_url, duration_seconds, status, created_at").eq("id",s).eq("is_deleted",!1).single();!$&&O&&(p(O),b(O))},b=async O=>{try{const{data:$,error:ee}=await V.functions.invoke("bunny-upload",{body:{action:"asset-urls",videoId:O.bunny_video_id,isAgentVideo:!0}});!ee&&($!=null&&$.thumbnailUrl)&&y(Z=>({...Z,[O.id]:{thumbnailUrl:$.thumbnailUrl}}))}catch($){console.warn("Failed to get signed URL",$)}},j=async()=>{if(a){h(!0);try{const{data:O,error:$}=await V.from("agent_videos").select("id, bunny_video_id, title, thumbnail_url, preview_url, playback_url, duration_seconds, status, created_at").eq("owner_user_id",a.id).eq("is_deleted",!1).eq("status","ready").order("created_at",{ascending:!1});if($)throw $;c(O||[]),O!=null&&O.length&&k(O)}catch(O){console.error("Error fetching videos:",O),he.error("Failed to load videos")}finally{h(!1)}}},k=async O=>{var $;try{const ee=O.map(ie=>ie.bunny_video_id),{data:Z,error:J}=await V.functions.invoke("bunny-upload",{body:{action:"bulk-asset-urls",videoIds:ee,isAgentVideo:!0}});if(J)throw J;const K=(Z==null?void 0:Z.assets)||{},re={};for(const ie of O)($=K[ie.bunny_video_id])!=null&&$.thumbnailUrl&&(re[ie.id]={thumbnailUrl:K[ie.bunny_video_id].thumbnailUrl});y(ie=>({...ie,...re}))}catch(ee){console.warn("Failed to bulk-fetch signed URLs",ee)}},T=()=>{l(!0),j()},E=O=>{t(O.id),p(O),l(!1),he.success("Video selected")},A=()=>{t(null),p(null)},D=()=>{const O=r?`/mission-control/listings/${r}/edit`:"/mission-control/listings/new";n(`/mission-control/video?returnUrl=${encodeURIComponent(O)}`)},R=O=>{if(!O)return"0:00";const $=Math.floor(O/60),ee=O%60;return`${$}:${ee.toString().padStart(2,"0")}`},z=O=>{var $;return(($=x[O.id])==null?void 0:$.thumbnailUrl)||O.thumbnail_url};return e.jsxs("div",{className:"space-y-3",children:[m?e.jsx(ke,{className:"overflow-hidden",children:e.jsx(Oe,{className:"p-0",children:e.jsxs("div",{className:"flex items-start gap-4 p-4",children:[e.jsxs("div",{className:"relative w-32 h-20 bg-muted rounded-lg overflow-hidden flex-shrink-0",children:[z(m)?e.jsx("img",{src:z(m),alt:m.title||"Video thumbnail",className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(xn,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx("div",{className:"absolute inset-0 bg-black/30 flex items-center justify-center",children:e.jsx(El,{className:"h-6 w-6 text-white fill-white"})}),m.duration_seconds&&e.jsx("div",{className:"absolute bottom-1 right-1 bg-black/70 text-white text-[10px] px-1.5 py-0.5 rounded",children:R(m.duration_seconds)})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:m.title||"Untitled Video"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Property Video Tour"})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(H,{type:"button",variant:"outline",size:"sm",onClick:T,children:"Change"}),e.jsx(H,{type:"button",variant:"ghost",size:"sm",onClick:A,className:"text-destructive hover:text-destructive",children:e.jsx(Rr,{className:"h-4 w-4"})})]})]})})}):e.jsx(ke,{className:"border-dashed",children:e.jsx(Oe,{className:"p-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx(xn,{className:"h-10 w-10 mx-auto text-muted-foreground mb-3"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Add a video walkthrough to showcase this property"}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2 justify-center",children:[e.jsxs(H,{type:"button",variant:"outline",onClick:T,className:"gap-2",children:[e.jsx(NE,{className:"h-4 w-4"}),"Select from Library"]}),e.jsxs(H,{type:"button",variant:"outline",onClick:D,className:"gap-2",children:[e.jsx(lx,{className:"h-4 w-4"}),"Record New Video"]})]})]})})}),e.jsx(bs,{open:i,onOpenChange:l,children:e.jsxs(vs,{className:"max-w-2xl max-h-[80vh] overflow-hidden flex flex-col",children:[e.jsx(Cs,{children:e.jsxs(Ns,{className:"flex items-center gap-2",children:[e.jsx(NE,{className:"h-5 w-5"}),"Select a Video"]})}),e.jsx("div",{className:"flex-1 overflow-y-auto",children:d?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(is,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):o.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx(xn,{className:"h-12 w-12 mx-auto text-muted-foreground mb-3"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"No videos in your library yet"}),e.jsxs(H,{onClick:D,className:"gap-2",children:[e.jsx(lx,{className:"h-4 w-4"}),"Record Your First Video"]})]}):e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-3 p-1",children:o.map(O=>e.jsxs("button",{type:"button",onClick:()=>E(O),className:`group relative rounded-lg overflow-hidden border-2 transition-all text-left ${s===O.id?"border-primary ring-2 ring-primary/20":"border-transparent hover:border-muted-foreground/30"}`,children:[e.jsxs("div",{className:"aspect-video bg-muted relative",children:[z(O)?e.jsx("img",{src:z(O),alt:O.title||"Video",className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(xn,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx("div",{className:"absolute inset-0 bg-black/0 group-hover:bg-black/30 transition-colors flex items-center justify-center",children:e.jsx(El,{className:"h-8 w-8 text-white opacity-0 group-hover:opacity-100 transition-opacity"})}),O.duration_seconds&&e.jsx("div",{className:"absolute bottom-1 right-1 bg-black/70 text-white text-[10px] px-1.5 py-0.5 rounded",children:R(O.duration_seconds)})]}),e.jsx("div",{className:"p-2 bg-card",children:e.jsx("p",{className:"text-xs font-medium truncate",children:O.title||"Untitled Video"})})]},O.id))})}),e.jsxs("div",{className:"flex justify-between items-center pt-4 border-t",children:[e.jsxs(H,{type:"button",variant:"ghost",onClick:D,className:"gap-2",children:[e.jsx(lx,{className:"h-4 w-4"}),"Record New Video"]}),e.jsx(H,{type:"button",variant:"outline",onClick:()=>l(!1),children:"Cancel"})]})]})})]})}const CRs=s=>s<1024?`${s} B`:s<1024*1024?`${(s/1024).toFixed(0)} KB`:`${(s/(1024*1024)).toFixed(1)} MB`;function TRs({listingId:s}){const t=S.useRef(null),{data:r=[],isLoading:n}=pxt(s),a=ZDs(),i=XDs(),l=QDs(),o=async d=>{if(!(!d||d.length===0)){for(const h of Array.from(d)){if(h.size>25*1024*1024){he.error(`${h.name} exceeds 25MB limit`);continue}try{await a.mutateAsync({listingId:s,file:h})}catch(m){he.error(`Failed to upload ${h.name}: ${m.message}`)}}t.current&&(t.current.value=""),he.success("Documents uploaded")}},c=async d=>{try{const h=await gxt(d);window.open(h,"_blank")}catch{he.error("Failed to open document")}};return e.jsxs("div",{className:"space-y-3",children:[e.jsx("input",{ref:t,type:"file",multiple:!0,accept:".pdf,application/pdf",className:"hidden",onChange:d=>o(d.target.files)}),e.jsxs(H,{type:"button",variant:"outline",onClick:()=>{var d;return(d=t.current)==null?void 0:d.click()},disabled:a.isPending,className:"w-full",children:[a.isPending?e.jsx(is,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Ea,{className:"h-4 w-4 mr-2"}),"Upload PDFs (disclosures, etc.)"]}),n?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading..."}):r.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No documents yet. Upload PDFs that other agents can download from your listing."}):e.jsx("div",{className:"space-y-2",children:r.map(d=>e.jsxs(ke,{className:"p-3 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 rounded-md bg-primary/10",children:e.jsx(kn,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-sm font-medium truncate",children:d.file_name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:CRs(d.file_size)})]}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[d.visible_on_exchange?e.jsx(Bn,{className:"h-3 w-3"}):e.jsx($f,{className:"h-3 w-3"}),e.jsx("span",{className:"hidden sm:inline",children:d.visible_on_exchange?"Visible":"Hidden"}),e.jsx(Or,{checked:d.visible_on_exchange,onCheckedChange:h=>l.mutate({id:d.id,visible:h,listingId:s}),className:"ml-1"})]}),e.jsx(H,{type:"button",variant:"ghost",size:"icon",onClick:()=>c(d.storage_path),children:e.jsx(hi,{className:"h-4 w-4"})}),e.jsx(H,{type:"button",variant:"ghost",size:"icon",onClick:()=>{confirm(`Delete ${d.file_name}?`)&&i.mutate({id:d.id,storage_path:d.storage_path,listingId:s})},children:e.jsx(Rr,{className:"h-4 w-4 text-destructive"})})]},d.id))})]})}const ERs=[{value:"active",label:"Active"},{value:"coming_soon",label:"Coming Soon"},{value:"office_exclusive",label:"Office Exclusive"},{value:"pre_market",label:"Pre-Market"},{value:"price_improvement",label:"Price Improvement"},{value:"under_contract",label:"Under Contract"},{value:"sold",label:"Sold"}],ARs=[{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 MRs({id:s,url:t,index:r,onRemove:n}){const{attributes:a,listeners:i,setNodeRef:l,transform:o,transition:c,isDragging:d}=zxe({id:s}),h={transform:kS.Transform.toString(o),transition:c};return e.jsxs("div",{ref:l,style:h,className:`relative aspect-square rounded-lg overflow-hidden bg-muted group ${d?"opacity-50 ring-2 ring-primary z-50":""}`,children:[e.jsx("img",{src:t,alt:"",className:"w-full h-full object-cover"}),e.jsx("button",{type:"button",...a,...i,className:"absolute top-1 left-1 p-1 bg-black/60 text-white rounded cursor-grab active:cursor-grabbing opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx(Oh,{className:"h-3.5 w-3.5"})}),e.jsx("button",{type:"button",onClick:()=>n(r),className:"absolute top-1 right-1 p-1 bg-destructive text-destructive-foreground rounded-full hover:bg-destructive/90 opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx(Rr,{className:"h-3 w-3"})}),r===0&&e.jsxs("span",{className:"absolute bottom-1 left-1 text-[10px] bg-primary text-primary-foreground px-1.5 py-0.5 rounded flex items-center gap-0.5",children:[e.jsx(ya,{className:"h-2.5 w-2.5 fill-current"})," Primary"]})]})}function IRs({photoUrls:s,pendingPhotos:t,onRemove:r,onReorder:n,uploading:a,onUpload:i}){const l=Mxe(fL(T8,{activationConstraint:{distance:5}})),o=s.map((d,h)=>`pending-${h}`),c=d=>{const{active:h,over:m}=d;if(!m||h.id===m.id)return;const p=o.indexOf(h.id),x=o.indexOf(m.id),y=[...s],_=[...t],[b]=y.splice(p,1),[j]=_.splice(p,1);y.splice(x,0,b),_.splice(x,0,j),n(y,_)};return e.jsxs("div",{className:"space-y-2",children:[s.length>1&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Drag photos to reorder. First photo will be primary."}),e.jsx(Oxe,{sensors:l,collisionDetection:Ixe,onDragEnd:c,children:e.jsx(Bxe,{items:o,strategy:jz,children:e.jsxs("div",{className:"grid grid-cols-3 sm:grid-cols-4 gap-4",children:[s.map((d,h)=>e.jsx(MRs,{id:o[h],url:d,index:h,onRemove:r},o[h])),e.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:[a?e.jsx(is,{className:"h-8 w-8 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(Ea,{className:"h-8 w-8"}),e.jsx("span",{className:"text-xs",children:"Upload"})]}),e.jsx("input",{type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:d=>i(d.target.files),disabled:a})]})]})})}),t.length>0&&e.jsxs("p",{className:"text-sm text-muted-foreground mt-4",children:[t.length," photo",t.length!==1?"s":""," will be uploaded when you save."]})]})}function rGe(){const{listingId:s}=Po(),[t]=Ed(),r=t.get("brokerage"),n=Fr(),{user:a}=Ms(),{hasLeadSite:i}=av(),l=!!s&&s!=="new",o=!!r&&!l,[c,d]=S.useState([]),[h,m]=S.useState({open:!1,listingId:null,nextPath:"/mission-control/listings"}),{data:p,isLoading:x}=_Te(l?s:""),y=jHt(),_=NHt(),b=kHt(),j=SHt(),k=CHt(),T=THt(),E=EHt(),{data:A=[]}=yt({queryKey:["brokerage-agents",r],queryFn:async()=>{if(!r)return[];const{data:ve,error:We}=await V.from("profiles").select("id, name, email").eq("brokerage_id",r).order("name");if(We)throw We;return ve||[]},enabled:o}),[D,R]=S.useState(""),[z,O]=S.useState(!1),[$,ee]=S.useState([]),[Z,J]=S.useState([]),[K,re]=S.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:"",video_id:null,allow_sharing:!0,open_to_referrals:!0,open_to_social_promotion:!0,share_with_brokerage:!1,is_public:!0});S.useEffect(()=>{var ve,We,Ve,Le,Me;p&&l&&re({property_address:p.property_address||"",city:p.city||"",state:p.state||"",neighborhood:p.neighborhood||"",price:((ve=p.price)==null?void 0:ve.toString())||"",property_type:p.property_type,status:p.status,bedrooms:((We=p.bedrooms)==null?void 0:We.toString())||"",bathrooms:((Ve=p.bathrooms)==null?void 0:Ve.toString())||"",square_footage:((Le=p.square_footage)==null?void 0:Le.toString())||"",lot_size:p.lot_size||"",year_built:((Me=p.year_built)==null?void 0:Me.toString())||"",has_hoa:p.has_hoa,description:p.description||"",agent_notes:p.agent_notes||"",agent_notes_public:p.agent_notes_public,mls_link:p.mls_link||"",video_link:p.video_link||"",video_id:p.video_id||null,allow_sharing:p.allow_sharing,open_to_referrals:p.open_to_referrals,open_to_social_promotion:p.open_to_social_promotion,share_with_brokerage:p.share_with_brokerage??!1,is_public:p.is_public})},[p,l]);const ie=ve=>{var Me,ze;const We={"single family":"single_family",detached:"single_family",residential:"single_family",condo:"condo",condominium:"condo",apartment:"condo",townhouse:"townhouse",townhome:"townhouse",land:"land",lot:"land","lots and land":"land","multi-family":"multi_family","multi family":"multi_family",duplex:"multi_family",commercial:"commercial"},Ve=(ve.propertyType||"").toLowerCase(),Le=((Me=Object.entries(We).find(([Pe])=>Ve.includes(Pe)))==null?void 0:Me[1])||"other";re(Pe=>({...Pe,property_address:ve.address||Pe.property_address,city:ve.city||Pe.city,state:ve.state||Pe.state,price:ve.price?String(ve.price):Pe.price,property_type:Le,bedrooms:ve.bedrooms?String(ve.bedrooms):Pe.bedrooms,bathrooms:ve.bathrooms?String(ve.bathrooms):Pe.bathrooms,square_footage:ve.sqft?String(ve.sqft):Pe.square_footage,lot_size:ve.lotSize?String(ve.lotSize):Pe.lot_size,year_built:ve.yearBuilt?String(ve.yearBuilt):Pe.year_built,description:ve.description||Pe.description})),((ze=ve.photos)==null?void 0:ze.length)>0&&(d(ve.photos),Z.forEach(Pe=>URL.revokeObjectURL(Pe)),ee([]),J([]))},ce=ve=>{if(!ve)return;const We=Array.from(ve);ee(Le=>[...Le,...We]);const Ve=We.map(Le=>URL.createObjectURL(Le));J(Le=>[...Le,...Ve])},ne=ve=>{URL.revokeObjectURL(Z[ve]),ee(We=>We.filter((Ve,Le)=>Le!==ve)),J(We=>We.filter((Ve,Le)=>Le!==ve))},le=async ve=>{var We;if(!(!ve||!p)){O(!0);try{for(const Ve of Array.from(ve)){const Le=Ve.name.split(".").pop(),Me=`${a==null?void 0:a.id}/${p.id}/${Date.now()}.${Le}`,{error:ze}=await V.storage.from("listing-photos").upload(Me,Ve);if(ze)throw ze;const{data:{publicUrl:Pe}}=V.storage.from("listing-photos").getPublicUrl(Me);await j.mutateAsync({listingId:p.id,photoUrl:Pe,isPrimary:!((We=p.photos)!=null&&We.length)})}he.success("Photos uploaded!")}catch(Ve){console.error("Upload error:",Ve),he.error("Failed to upload photos")}finally{O(!1)}}},be=async ve=>{for(let We=0;We<$.length;We++){const Ve=$[We],Le=Ve.name.split(".").pop(),Me=`${a==null?void 0:a.id}/${ve}/${Date.now()}-${We}.${Le}`,{error:ze}=await V.storage.from("listing-photos").upload(Me,Ve);if(ze)throw ze;const{data:{publicUrl:Pe}}=V.storage.from("listing-photos").getPublicUrl(Me);await j.mutateAsync({listingId:ve,photoUrl:Pe,isPrimary:We===0})}},fe=async ve=>{if(p)try{await k.mutateAsync({photoId:ve,listingId:p.id}),he.success("Photo removed")}catch{he.error("Failed to remove photo")}},je=async ve=>{if(ve.preventDefault(),!K.city.trim()||!K.state.trim()||!K.price){he.error("Please fill in required fields (City, State, Price)");return}if(o&&!D){he.error("Please select an agent to assign this listing to");return}try{const We={property_address:K.property_address||null,city:K.city,state:K.state,neighborhood:K.neighborhood||null,price:Number(K.price),property_type:K.property_type,status:K.status,bedrooms:K.bedrooms?Number(K.bedrooms):null,bathrooms:K.bathrooms?Number(K.bathrooms):null,square_footage:K.square_footage?Number(K.square_footage):null,lot_size:K.lot_size||null,year_built:K.year_built?Number(K.year_built):null,has_hoa:K.has_hoa,description:K.description||null,agent_notes:K.agent_notes||null,agent_notes_public:K.agent_notes_public,mls_link:K.mls_link||null,video_link:K.video_link||null,video_id:K.video_id||null,allow_sharing:K.allow_sharing,open_to_referrals:K.open_to_referrals,open_to_social_promotion:K.open_to_social_promotion,share_with_brokerage:K.share_with_brokerage,is_public:K.is_public};if(l)await b.mutateAsync({id:s,...We}),he.success("Listing updated!"),n(`/mission-control/listings/${s}`);else{O(!0);let Ve;if(o&&D?Ve=await _.mutateAsync({agentId:D,...We}):Ve=await y.mutateAsync(We),$.length>0)try{await be(Ve.id),Z.forEach(Me=>URL.revokeObjectURL(Me)),ee([]),J([])}catch(Me){console.error("Photo upload error:",Me),he.error("Listing created but some photos failed to upload")}if(c.length>0)try{for(let Me=0;Men(o?"/my-brokerage":"/mission-control/listings"),children:[e.jsx(za,{className:"h-4 w-4 mr-2"}),o?"Back to Brokerage":"Back to Listings"]}),e.jsxs("div",{className:"grid md:grid-cols-3 gap-6",children:[e.jsxs("div",{className:"md:col-span-2 space-y-6",children:[o&&e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsx(zt,{children:"Assign to Agent *"})}),e.jsxs(Oe,{children:[e.jsxs(Bs,{value:D,onValueChange:R,children:[e.jsx(Os,{children:e.jsx(Us,{placeholder:"Select an agent..."})}),e.jsx(Fs,{children:A.map(ve=>e.jsx(pt,{value:ve.id,children:ve.name||ve.email},ve.id))})]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:"This listing will appear on the selected agent's Listing Exchange."})]})]}),!l&&i&&!o&&e.jsx(jRs,{onImport:ie}),c.length>0&&e.jsxs(ke,{className:"border-primary/30 bg-primary/5",children:[e.jsxs(Ot,{className:"pb-3",children:[e.jsxs(zt,{className:"text-base flex items-center gap-2",children:[e.jsx(hi,{className:"h-4 w-4 text-primary"}),"MLS Photos (",c.length,")"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"These photos will be imported when you save the listing."})]}),e.jsxs(Oe,{children:[e.jsxs("div",{className:"grid grid-cols-4 sm:grid-cols-6 gap-2",children:[c.slice(0,12).map((ve,We)=>e.jsx("div",{className:"aspect-square rounded overflow-hidden bg-muted",children:e.jsx("img",{src:ve,alt:"",className:"w-full h-full object-cover"})},We)),c.length>12&&e.jsxs("div",{className:"aspect-square rounded bg-muted flex items-center justify-center text-sm text-muted-foreground font-medium",children:["+",c.length-12]})]}),e.jsxs(H,{type:"button",variant:"ghost",size:"sm",className:"mt-2 text-destructive",onClick:()=>d([]),children:[e.jsx(Rr,{className:"h-3 w-3 mr-1"})," Clear MLS photos"]})]})]}),e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsx(zt,{children:"Property Details"})}),e.jsx(Oe,{className:"space-y-4",children:e.jsxs("div",{className:"grid sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"sm:col-span-2 space-y-2",children:[e.jsx(ue,{children:"Property Address"}),e.jsx(Se,{value:K.property_address,onChange:ve=>re({...K,property_address:ve.target.value}),placeholder:"123 Main St"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"City *"}),e.jsx(Se,{value:K.city,onChange:ve=>re({...K,city:ve.target.value}),placeholder:"City",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"State *"}),e.jsx(Se,{value:K.state,onChange:ve=>re({...K,state:ve.target.value}),placeholder:"State",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Neighborhood"}),e.jsx(Se,{value:K.neighborhood,onChange:ve=>re({...K,neighborhood:ve.target.value}),placeholder:"Neighborhood"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Price *"}),e.jsx(Se,{type:"number",value:K.price,onChange:ve=>re({...K,price:ve.target.value}),placeholder:"500000",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Property Type"}),e.jsxs(Bs,{value:K.property_type,onValueChange:ve=>re({...K,property_type:ve}),children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsx(Fs,{children:ARs.map(ve=>e.jsx(pt,{value:ve.value,children:ve.label},ve.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Status"}),e.jsxs(Bs,{value:K.status,onValueChange:ve=>re({...K,status:ve}),children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsx(Fs,{children:ERs.map(ve=>e.jsx(pt,{value:ve.value,children:ve.label},ve.value))})]})]})]})})]}),e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsx(zt,{children:"Property Specs (Optional)"})}),e.jsx(Oe,{children:e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Bedrooms"}),e.jsx(Se,{type:"number",value:K.bedrooms,onChange:ve=>re({...K,bedrooms:ve.target.value}),placeholder:"3"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Bathrooms"}),e.jsx(Se,{type:"number",step:"0.5",value:K.bathrooms,onChange:ve=>re({...K,bathrooms:ve.target.value}),placeholder:"2"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Sq Ft"}),e.jsx(Se,{type:"number",value:K.square_footage,onChange:ve=>re({...K,square_footage:ve.target.value}),placeholder:"2000"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Lot Size"}),e.jsx(Se,{value:K.lot_size,onChange:ve=>re({...K,lot_size:ve.target.value}),placeholder:"0.25 acres"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Year Built"}),e.jsx(Se,{type:"number",value:K.year_built,onChange:ve=>re({...K,year_built:ve.target.value}),placeholder:"2005"})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-6",children:[e.jsx(Or,{checked:K.has_hoa,onCheckedChange:ve=>re({...K,has_hoa:ve})}),e.jsx(ue,{children:"Has HOA"})]})]})})]}),e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsx(zt,{children:"Description & Links"})}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Description"}),e.jsx(vr,{value:K.description,onChange:ve=>re({...K,description:ve.target.value}),placeholder:"Tell the story of this property...",rows:4})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Agent Notes"}),e.jsx(vr,{value:K.agent_notes,onChange:ve=>re({...K,agent_notes:ve.target.value}),placeholder:"Notes for other agents...",rows:2}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Or,{checked:K.agent_notes_public,onCheckedChange:ve=>re({...K,agent_notes_public:ve})}),e.jsx(ue,{className:"text-sm text-muted-foreground",children:"Make notes visible to other agents"})]})]}),e.jsxs("div",{className:"grid sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"MLS Link"}),e.jsx(Se,{value:K.mls_link,onChange:ve=>re({...K,mls_link:ve.target.value}),placeholder:"https://..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Video Link"}),e.jsx(Se,{value:K.video_link,onChange:ve=>re({...K,video_link:ve.target.value}),placeholder:"YouTube or Vimeo URL"})]})]})]})]}),e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(xn,{className:"h-5 w-5"}),"Property Video"]})}),e.jsx(Oe,{children:e.jsx(SRs,{selectedVideoId:K.video_id,onVideoSelect:ve=>re({...K,video_id:ve}),listingId:l?s:void 0})})]}),e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsx(zt,{children:"Photos"})}),e.jsx(Oe,{children:l&&(p!=null&&p.photos)?e.jsx(kRs,{photos:p.photos,uploading:z,onUpload:ve=>le(ve),onRemove:ve=>fe(ve),onReorder:ve=>{T.mutate({photos:ve.map(We=>({id:We.id,sort_order:We.sort_order,is_primary:We.is_primary}))})},onSetPrimary:ve=>{p&&E.mutate({photoId:ve,listingId:p.id})}}):e.jsx(IRs,{photoUrls:Z,onRemove:ne,onReorder:(ve,We)=>{J(ve),ee(We)},pendingPhotos:$,uploading:z,onUpload:ce})})]}),e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(hi,{className:"h-5 w-5"}),"Documents & Disclosures"]})}),e.jsx(Oe,{children:l&&s?e.jsx(TRs,{listingId:s}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Save the listing first, then you can upload PDFs (disclosures, floor plans, HOA docs, etc.) for other agents to download."})})]})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsx(zt,{children:"Sharing & Collaboration"})}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ue,{children:"Allow Sharing"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Other agents can share this listing"})]}),e.jsx(Or,{checked:K.allow_sharing,onCheckedChange:ve=>re({...K,allow_sharing:ve})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ue,{children:"Open to Referrals"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Accept buyer referrals"})]}),e.jsx(Or,{checked:K.open_to_referrals,onCheckedChange:ve=>re({...K,open_to_referrals:ve})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ue,{children:"Social Promotion"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Can be promoted on social media"})]}),e.jsx(Or,{checked:K.open_to_social_promotion,onCheckedChange:ve=>re({...K,open_to_social_promotion:ve})})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t",children:[e.jsxs("div",{children:[e.jsx(ue,{children:"Share with Brokerage"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Visible to agents in your brokerage"})]}),e.jsx(Or,{checked:K.share_with_brokerage,onCheckedChange:ve=>re({...K,share_with_brokerage:ve})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ue,{children:"Make Public"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Publish on listings.relevelup.com to get leads"})]}),e.jsx(Or,{checked:K.is_public,onCheckedChange:ve=>re({...K,is_public:ve})})]})]})]}),e.jsx(H,{type:"submit",className:"w-full",size:"lg",disabled:y.isPending||b.isPending,children:y.isPending||b.isPending?e.jsxs(e.Fragment,{children:[e.jsx(is,{className:"h-4 w-4 mr-2 animate-spin"}),"Saving..."]}):l?"Update Listing":"Create Listing"})]})]})]}),e.jsx(xxt,{listingId:h.listingId,open:h.open,onOpenChange:ve=>{if(!ve){const{nextPath:We}=h;m({open:!1,listingId:null,nextPath:We}),n(We)}}})]})}let qg=null;function PRs(){if(qg)return qg;try{const s=document.createElement("canvas"),t=s.getContext("webgl2")||s.getContext("webgl");if(!t)return qg={canRunVirtualBg:!1,reason:"WebGL is not supported on this device"},qg;const r=t.getExtension("WEBGL_debug_renderer_info"),n=r?t.getParameter(r.UNMASKED_RENDERER_WEBGL):"Unknown",a=["swiftshader","llvmpipe","software","microsoft basic render"],i=(n||"").toLowerCase();if(a.some(c=>i.includes(c)))return qg={canRunVirtualBg:!1,reason:"Your device uses a software renderer which may cause lag",renderer:n},qg;const o=performance;return o.memory&&o.memory.jsHeapSizeLimit<256*1024*1024?(qg={canRunVirtualBg:!1,reason:"Limited device memory detected",renderer:n},qg):navigator.hardwareConcurrency&&navigator.hardwareConcurrency<2?(qg={canRunVirtualBg:!1,reason:"Single-core device detected — virtual backgrounds may cause lag",renderer:n},qg):(qg={canRunVirtualBg:!0,renderer:n},qg)}catch{return qg={canRunVirtualBg:!0},qg}}const LRs=[{type:"none",label:"Off"},{type:"blur",label:"Blur"}];function DRs({value:s,onChange:t,isLoading:r=!1,disabled:n=!1,className:a}){const i=S.useRef(null),[l,o]=S.useState(!1),[c]=S.useState(()=>PRs()),d=!c.canRunVirtualBg,{data:h=[],refetch:m}=yt({queryKey:["video-backgrounds"],queryFn:async()=>{const{data:{user:b}}=await V.auth.getUser();if(!b)return[];const{data:j,error:k}=await V.from("video_backgrounds").select("*").eq("is_active",!0).order("sort_order",{ascending:!0});return k?(console.error("Failed to load backgrounds:",k),[]):j||[]}}),p=h.map(b=>({type:"image",label:b.name,imageUrl:b.image_url,thumbnail:b.thumbnail_url||b.image_url})),x=[...LRs,...p],y=b=>b.type!==s.type?!1:b.type==="image"?b.imageUrl===s.imageUrl:!0,_=async b=>{var k;const j=(k=b.target.files)==null?void 0:k[0];if(j){if(!j.type.startsWith("image/")){he.error("Please select an image file");return}if(j.size>5*1024*1024){he.error("Image must be under 5MB");return}o(!0);try{const{data:{user:T}}=await V.auth.getUser();if(!T)throw new Error("Not authenticated");const E=j.name.split(".").pop()||"jpg",A=`${T.id}/${crypto.randomUUID()}.${E}`,{error:D}=await V.storage.from("video-backgrounds").upload(A,j,{contentType:j.type});if(D)throw D;const{data:R}=V.storage.from("video-backgrounds").getPublicUrl(A),z=R.publicUrl,{error:O}=await V.from("video_backgrounds").insert({name:j.name.replace(/\.[^.]+$/,""),image_url:z,thumbnail_url:z,category:"custom",is_stock:!1,user_id:T.id});if(O)throw O;await m(),t({type:"image",imageUrl:z,blurRadius:15}),he.success("Background uploaded!")}catch(T){console.error("Upload error:",T),he.error("Failed to upload background")}finally{o(!1),i.current&&(i.current.value="")}}};return e.jsxs("div",{className:Ft("flex flex-col gap-1",a),children:[d&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-amber-600 bg-amber-50 dark:bg-amber-950/30 dark:text-amber-400 rounded px-2 py-1",children:[e.jsx(uu,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{children:c.reason||"Virtual backgrounds may cause lag on this device"})]}),e.jsxs("div",{className:"flex items-center gap-2 overflow-x-auto py-2 px-1 scrollbar-none",children:[e.jsx("span",{className:"text-xs text-muted-foreground whitespace-nowrap mr-1 font-medium",children:"Background:"}),r&&e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(is,{className:"h-3 w-3 animate-spin"}),e.jsx("span",{children:"Loading…"})]}),x.map((b,j)=>{const k=y(b);return e.jsxs("button",{type:"button",disabled:n,onClick:()=>t({type:b.type,imageUrl:b.imageUrl,blurRadius:15}),className:Ft("flex-shrink-0 flex flex-col items-center gap-0.5 rounded-lg border-2 p-1 transition-all","hover:border-primary/50 focus:outline-none focus:ring-2 focus:ring-primary/30",k?"border-primary bg-primary/10":"border-transparent bg-muted/50",n&&"opacity-50 cursor-not-allowed"),children:[e.jsxs("div",{className:"w-12 h-8 rounded flex items-center justify-center overflow-hidden bg-muted",children:[b.type==="none"&&e.jsx(XO,{className:"h-4 w-4 text-muted-foreground"}),b.type==="blur"&&e.jsx("div",{className:"w-full h-full bg-gradient-to-br from-primary/20 to-primary/40 flex items-center justify-center",children:e.jsx("span",{className:"text-[10px] font-medium text-primary",children:"Blur"})}),b.type==="image"&&b.thumbnail&&e.jsx("img",{src:b.thumbnail,alt:b.label,className:"w-full h-full object-cover"})]}),e.jsx("span",{className:"text-[10px] text-muted-foreground truncate max-w-14",children:b.label})]},`${b.type}-${b.imageUrl||j}`)}),e.jsxs("button",{type:"button",disabled:n||l,onClick:()=>{var b;return(b=i.current)==null?void 0:b.click()},className:Ft("flex-shrink-0 flex flex-col items-center gap-0.5 rounded-lg border-2 border-dashed p-1 transition-all","hover:border-primary/50 focus:outline-none focus:ring-2 focus:ring-primary/30","border-muted-foreground/30 bg-muted/30",(n||l)&&"opacity-50 cursor-not-allowed"),children:[e.jsx("div",{className:"w-12 h-8 rounded flex items-center justify-center",children:l?e.jsx(is,{className:"h-4 w-4 animate-spin text-muted-foreground"}):e.jsx(Ys,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:l?"Uploading":"Custom"})]}),e.jsx("input",{ref:i,type:"file",accept:"image/*",className:"hidden",onChange:_}),e.jsxs("button",{type:"button",disabled:n,onClick:()=>t({...s,mirror:!s.mirror}),className:Ft("flex-shrink-0 flex flex-col items-center gap-0.5 rounded-lg border-2 p-1 transition-all ml-1","hover:border-primary/50 focus:outline-none focus:ring-2 focus:ring-primary/30",s.mirror?"border-primary bg-primary/10":"border-transparent bg-muted/50",n&&"opacity-50 cursor-not-allowed"),children:[e.jsx("div",{className:"w-12 h-8 rounded flex items-center justify-center",children:e.jsx(dF,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:"Mirror"})]})]})]})}var zL=typeof self<"u"?self:{};function _xt(s,t){e:{for(var r=["CLOSURE_FLAGS"],n=zL,a=0;a>6|192;else{if(t>=55296&&t<=57343){if(t<=56319&&a=56320&&i<=57343){t=1024*(t-55296)+i-56320+65536,n[r++]=t>>18|240,n[r++]=t>>12&63|128,n[r++]=t>>6&63|128,n[r++]=63&t|128;continue}a--}t=65533}n[r++]=t>>12|224,n[r++]=t>>6&63|128}n[r++]=63&t|128}}s=r===n.length?n:n.subarray(0,r)}return s}function jxt(s){zL.setTimeout(()=>{throw s},0)}var T4e,BRs=_xt(610401301,!1),aGe=_xt(748402147,!0);function iGe(){var s=zL.navigator;return s&&(s=s.userAgent)?s:""}const oGe=zL.navigator;function z0e(s){return z0e[" "](s),s}T4e=oGe&&oGe.userAgentData||null,z0e[" "]=function(){};const Nxt={};let MO=null;function zRs(s){const t=s.length;let r=3*t/4;r%3?r=Math.floor(r):"=.".indexOf(s[t-1])!=-1&&(r="=.".indexOf(s[t-2])!=-1?r-2:r-1);const n=new Uint8Array(r);let a=0;return function(i,l){function o(d){for(;c>4),m!=64&&(l(h<<4&240|m>>2),p!=64&&l(m<<6&192|p))}}(s,function(i){n[a++]=i}),a!==r?n.subarray(0,a):n}function kxt(){if(!MO){MO={};var s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".split(""),t=["+/=","+/","-_=","-_.","-_"];for(let r=0;r<5;r++){const n=s.concat(t[r].split(""));Nxt[r]=n;for(let a=0;a0)&&(iGe().indexOf("Trident")!=-1||iGe().indexOf("MSIE")!=-1))&&typeof btoa=="function";const lGe=/[-_.]/g,URs={"-":"+",_:"/",".":"="};function qRs(s){return URs[s]||""}function Cxt(s){if(!Sxt)return zRs(s);s=lGe.test(s)?s.replace(lGe,qRs):s,s=atob(s);const t=new Uint8Array(s.length);for(let r=0;r=t||(r[s]=n+1,Ext(s=Error(),"incident"),jxt(s))}}function W8(){return typeof BigInt=="function"}var K8=typeof Symbol=="function"&&typeof Symbol()=="symbol";function Q_(s,t,r=!1){return typeof Symbol=="function"&&typeof Symbol()=="symbol"?r&&Symbol.for&&s?Symbol.for(s):s!=null?Symbol(s):Symbol():t}var GRs=Q_("jas",void 0,!0),cGe=Q_(void 0,"0di"),eO=Q_(void 0,"1oa"),b0=Q_(void 0,Symbol()),WRs=Q_(void 0,"0ub"),KRs=Q_(void 0,"0ubs"),A4e=Q_(void 0,"0ubsb"),YRs=Q_(void 0,"0actk"),qL=Q_("m_m","Pa",!0),dGe=Q_();const Axt={Ga:{value:0,configurable:!0,writable:!0,enumerable:!1}},Mxt=Object.defineProperties,pi=K8?GRs:"Ga";var rM;const uGe=[];function Rz(s,t){K8||pi in s||Mxt(s,Axt),s[pi]|=t}function wm(s,t){K8||pi in s||Mxt(s,Axt),s[pi]=t}function Oz(s){return Rz(s,34),s}function pB(s){return Rz(s,8192),s}wm(uGe,7),rM=Object.freeze(uGe);var VL={};function A0(s,t){return t===void 0?s.h!==LA&&!!(2&(0|s.v[pi])):!!(2&t)&&s.h!==LA}const LA={};function gMe(s,t){if(s!=null){if(typeof s=="string")s=s?new T_(s,$L):PA();else if(s.constructor!==T_)if(fMe(s))s=s.length?new T_(new Uint8Array(s),$L):PA();else{if(!t)throw Error();s=void 0}}return s}class hGe{constructor(t,r,n){this.g=t,this.h=r,this.l=n}next(){const t=this.g.next();return t.done||(t.value=this.h.call(this.l,t.value)),t}[Symbol.iterator](){return this}}var ZRs=Object.freeze({});function Ixt(s,t,r){const n=128&t?0:-1,a=s.length;var i;(i=!!a)&&(i=(i=s[a-1])!=null&&typeof i=="object"&&i.constructor===Object);const l=a+(i?-1:0);for(t=128&t?1:0;ttypeof s=="number"),mGe=$0e(s=>typeof s=="string"),QRs=$0e(s=>typeof s=="boolean"),U0e=typeof zL.BigInt=="function"&&typeof zL.BigInt(0)=="bigint";function _0(s){var t=s;if(mGe(t)){if(!/^\s*(?:-?[1-9]\d*|0)?\s*$/.test(t))throw Error(String(t))}else if(XRs(t)&&!Number.isSafeInteger(t))throw Error(String(t));return U0e?BigInt(s):s=QRs(s)?s?"1":"0":mGe(s)?s.trim()||"0":String(s)}var M4e=$0e(s=>U0e?s>=eOs&&s<=sOs:s[0]==="-"?fGe(s,JRs):fGe(s,tOs));const JRs=Number.MIN_SAFE_INTEGER.toString(),eOs=U0e?BigInt(Number.MIN_SAFE_INTEGER):void 0,tOs=Number.MAX_SAFE_INTEGER.toString(),sOs=U0e?BigInt(Number.MAX_SAFE_INTEGER):void 0;function fGe(s,t){if(s.length>t.length)return!1;if(s.lengtha)return!1;if(n>>0;cu=t,Ph=(s-t)/4294967296>>>0}function HL(s){if(s<0){pGe(-s);const[t,r]=vMe(cu,Ph);cu=t>>>0,Ph=r>>>0}else pGe(s)}function xMe(s){const t=nOs||(nOs=new DataView(new ArrayBuffer(8)));t.setFloat32(0,+s,!0),Ph=0,cu=t.getUint32(0,!0)}function Lxt(s,t){const r=4294967296*t+(s>>>0);return Number.isSafeInteger(r)?r:gB(s,t)}function aOs(s,t){return _0(W8()?BigInt.asUintN(64,(BigInt(t>>>0)<>>0)):gB(s,t))}function Dxt(s,t){return W8()?_0(BigInt.asIntN(64,(BigInt.asUintN(32,BigInt(t))<>>=0,(t>>>=0)<=2097151)var r=""+(4294967296*t+s);else W8()?r=""+(BigInt(t)<>>24|t<<8))+6710656*(t=t>>16&65535),r+=8147497*t,t*=2,s>=1e7&&(r+=s/1e7>>>0,s%=1e7),r>=1e7&&(t+=r/1e7>>>0,r%=1e7),r=t+gGe(r)+gGe(s));return r}function gGe(s){return s=String(s),"0000000".slice(s.length)+s}function yMe(s,t){if(2147483648&t)if(W8())s=""+(BigInt(0|t)<>>0));else{const[r,n]=vMe(s,t);s="-"+gB(r,n)}else s=gB(s,t);return s}function q0e(s){if(s.length<16)HL(Number(s));else if(W8())s=BigInt(s),cu=Number(s&BigInt(4294967295))>>>0,Ph=Number(s>>BigInt(32)&BigInt(4294967295));else{const t=+(s[0]==="-");Ph=cu=0;const r=s.length;for(let n=t,a=(r-t)%6+t;a<=r;n=a,a+=6){const i=Number(s.slice(n,a));Ph*=1e6,cu=1e6*cu+i,cu>=4294967296&&(Ph+=Math.trunc(cu/4294967296),Ph>>>=0,cu>>>=0)}if(t){const[n,a]=vMe(cu,Ph);cu=n,Ph=a}}}function vMe(s,t){return t=~t,s?s=1+~s:t+=1,[s,t]}function C1(s){return Array.prototype.slice.call(s)}const Fz=typeof BigInt=="function"?BigInt.asIntN:void 0,iOs=typeof BigInt=="function"?BigInt.asUintN:void 0,DA=Number.isSafeInteger,V0e=Number.isFinite,GL=Math.trunc,oOs=_0(0);function IO(s){if(s!=null&&typeof s!="number")throw Error(`Value of float/double field must be a number, found ${typeof s}: ${s}`);return s}function a_(s){return s==null||typeof s=="number"?s:s==="NaN"||s==="Infinity"||s==="-Infinity"?Number(s):void 0}function xB(s){if(s!=null&&typeof s!="boolean"){var t=typeof s;throw Error(`Expected boolean but got ${t!="object"?t:s?Array.isArray(s)?"array":t:"null"}: ${s}`)}return s}function Rxt(s){return s==null||typeof s=="boolean"?s:typeof s=="number"?!!s:void 0}const lOs=/^-?([1-9][0-9]*|0)(\.[0-9]+)?$/;function Bz(s){switch(typeof s){case"bigint":return!0;case"number":return V0e(s);case"string":return lOs.test(s);default:return!1}}function Z8(s){if(s==null)return s;if(typeof s=="string"&&s)s=+s;else if(typeof s!="number")return;return V0e(s)?0|s:void 0}function Oxt(s){if(s==null)return s;if(typeof s=="string"&&s)s=+s;else if(typeof s!="number")return;return V0e(s)?s>>>0:void 0}function Fxt(s){const t=s.length;return(s[0]==="-"?t<20||t===20&&s<="-9223372036854775808":t<19||t===19&&s<="9223372036854775807")?s:(q0e(s),yMe(cu,Ph))}function bMe(s){if(s=GL(s),!DA(s)){HL(s);var t=cu,r=Ph;(s=2147483648&r)&&(r=~r>>>0,(t=1+~t>>>0)==0&&(r=r+1>>>0)),s=typeof(t=Lxt(t,r))=="number"?s?-t:t:s?"-"+t:t}return s}function Bxt(s){var t=GL(Number(s));return DA(t)?String(t):((t=s.indexOf("."))!==-1&&(s=s.substring(0,t)),Fxt(s))}function zxt(s){var t=GL(Number(s));return DA(t)?_0(t):((t=s.indexOf("."))!==-1&&(s=s.substring(0,t)),W8()?_0(Fz(64,BigInt(s))):_0(Fxt(s)))}function $xt(s){return DA(s)?s=_0(bMe(s)):(s=GL(s),DA(s)?s=String(s):(HL(s),s=yMe(cu,Ph)),s=_0(s)),s}function ipe(s){const t=typeof s;return s==null?s:t==="bigint"?_0(Fz(64,s)):Bz(s)?t==="string"?zxt(s):$xt(s):void 0}function Uxt(s){if(typeof s!="string")throw Error();return s}function zz(s){if(s!=null&&typeof s!="string")throw Error();return s}function Gf(s){return s==null||typeof s=="string"?s:void 0}function _Me(s,t,r,n){return s!=null&&s[qL]===VL?s:Array.isArray(s)?((n=(r=0|s[pi])|32&n|2&n)!==r&&wm(s,n),new t(s)):(r?2&n?((s=t[cGe])||(Oz((s=new t).v),s=t[cGe]=s),t=s):t=new t:t=void 0,t)}function cOs(s,t,r){if(t)e:{if(!Bz(t=s))throw E4e("int64");switch(typeof t){case"string":t=zxt(t);break e;case"bigint":t=_0(Fz(64,t));break e;default:t=$xt(t)}}else t=ipe(s);return(s=t)==null?r?oOs:void 0:s}const dOs={};let uOs=function(){try{return z0e(new class extends Map{constructor(){super()}}),!1}catch{return!0}}();class pwe{constructor(){this.g=new Map}get(t){return this.g.get(t)}set(t,r){return this.g.set(t,r),this.size=this.g.size,this}delete(t){return t=this.g.delete(t),this.size=this.g.size,t}clear(){this.g.clear(),this.size=this.g.size}has(t){return this.g.has(t)}entries(){return this.g.entries()}keys(){return this.g.keys()}values(){return this.g.values()}forEach(t,r){return this.g.forEach(t,r)}[Symbol.iterator](){return this.entries()}}const hOs=uOs?(Object.setPrototypeOf(pwe.prototype,Map.prototype),Object.defineProperties(pwe.prototype,{size:{value:0,configurable:!0,enumerable:!0,writable:!0}}),pwe):class extends Map{constructor(){super()}};function xGe(s){return s}function gwe(s){if(2&s.J)throw Error("Cannot mutate an immutable Map")}var hj=class extends hOs{constructor(s,t,r=xGe,n=xGe){super(),this.J=0|s[pi],this.K=t,this.S=r,this.fa=this.K?mOs:n;for(let a=0;a{s.call(t,a.get(n),n,a)}):super.forEach(s,t)}set(s,t){return gwe(this),(s=this.S(s,!0,!1))==null?this:t==null?(super.delete(s),this):super.set(s,this.fa(t,!0,!0,this.K,!1,this.J))}Ma(s){const t=this.S(s[0],!1,!0);s=s[1],s=this.K?s===void 0?null:s:this.fa(s,!1,!0,void 0,!1,this.J),super.set(t,s)}has(s){return super.has(this.S(s,!1,!1))}get(s){s=this.S(s,!1,!1);const t=super.get(s);if(t!==void 0){var r=this.K;return r?((r=this.fa(t,!1,!0,r,this.ra,this.J))!==t&&super.set(s,r),r):t}}[Symbol.iterator](){return this.entries()}};function mOs(s,t,r,n,a,i){return s=_Me(s,n,r,i),a&&(s=jMe(s)),s}function fOs(s){return[s,this.get(s)]}let pOs;function yGe(){return pOs||(pOs=new hj(Oz([]),void 0,void 0,void 0,dOs))}function H0e(s){return b0?s[b0]:void 0}function ope(s,t){for(const r in s)!isNaN(r)&&t(s,+r,s[r])}hj.prototype.toJSON=void 0;var I4e=class{};const gOs={Ka:!0};function xOs(s,t){t<100||UL(KRs,1)}function G0e(s,t,r,n){const a=n!==void 0;n=!!n;var i,l=b0;!a&&K8&&l&&(i=s[l])&&ope(i,xOs),l=[];var o=s.length;let c;i=4294967295;let d=!1;const h=!!(64&t),m=h?128&t?0:-1:void 0;1&t||(c=o&&s[o-1],c!=null&&typeof c=="object"&&c.constructor===Object?i=--o:c=void 0,!h||128&t||a||(d=!0,i=i-m+m)),t=void 0;for(var p=0;p=i){const y=p-m;(t??(t={}))[y]=x}else l[p]=x}if(c)for(let x in c){if((o=c[x])==null||(o=r(o,n))==null)continue;let y;p=+x,h&&!Number.isNaN(p)&&(y=p+m){y[b]=C1(j)}),y.da=x.da,y}(s)),l}function yOs(s){return s[0]=yB(s[0]),s[1]=yB(s[1]),s}function yB(s){switch(typeof s){case"number":return Number.isFinite(s)?s:""+s;case"bigint":return M4e(s)?Number(s):""+s;case"boolean":return s?1:0;case"object":if(Array.isArray(s)){var t=0|s[pi];return s.length===0&&1&t?void 0:G0e(s,t,yB)}if(s!=null&&s[qL]===VL)return qxt(s);if(s instanceof T_){if((t=s.g)==null)s="";else if(typeof t=="string")s=t;else{if(Sxt){for(var r="",n=0,a=t.length-10240;n>2];i=r[(3&i)<<4|l>>4],l=r[(15&l)<<2|o>>6],o=r[63&o],n[h++]=c+i+l+o}switch(c=0,o=a,t.length-d){case 2:o=r[(15&(c=t[d+1]))<<2]||a;case 1:t=t[d],n[h]=r[t>>2]+r[(3&t)<<4|c>>4]+o+a}t=n.join("")}s=s.g=t}return s}return s instanceof hj?s=s.size!==0?s.V(yOs):void 0:void 0}return s}let vOs,bOs;function qxt(s){return G0e(s=s.v,0|s[pi],yB)}function ZE(s,t){return Vxt(s,t[0],t[1])}function Vxt(s,t,r,n=0){if(s==null){var a=32;r?(s=[r],a|=128):s=[],t&&(a=-16760833&a|(1023&t)<<14)}else{if(!Array.isArray(s))throw Error("narr");if(a=0|s[pi],aGe&&1&a)throw Error("rfarr");if(2048&a&&!(2&a)&&function(){if(aGe)throw Error("carr");UL(YRs,5)}(),256&a)throw Error("farr");if(64&a)return(a|n)!==a&&wm(s,a|n),s;if(r&&(a|=128,r!==s[0]))throw Error("mid");e:{a|=64;var i=(r=s).length;if(i){var l=i-1;const c=r[l];if(c!=null&&typeof c=="object"&&c.constructor===Object){if((l-=t=128&a?0:-1)>=1024)throw Error("pvtlmt");for(var o in c)(i=+o)1024)throw Error("spvt");a=-16760833&a|(1023&o)<<14}}}return wm(s,64|a|n),s}function _Os(s,t){if(typeof s!="object")return s;if(Array.isArray(s)){var r=0|s[pi];return s.length===0&&1&r?void 0:vGe(s,r,t)}if(s!=null&&s[qL]===VL)return bGe(s);if(s instanceof hj){if(2&(t=s.J))return s;if(!s.size)return;if(r=Oz(s.V()),s.K)for(s=0;s=i)if(l=s[i],l!=null&&typeof l=="object"&&l.constructor===Object)r=l[t],o=!0;else{if(a!==i)return;r=l}else r=s[a];if(n&&r!=null){if((n=n(r))==null)return n;if(!Object.is(n,r))return o?l[t]=n:s[a]=n,n}return r}}function Sc(s,t,r,n){J8(s),bm(s=s.v,0|s[pi],t,r,n)}function bm(s,t,r,n,a){const i=r+(a?0:-1);var l=s.length-1;if(l>=1+(a?0:-1)&&i>=l){const o=s[l];if(o!=null&&typeof o=="object"&&o.constructor===Object)return o[r]=n,t}return i<=l?(s[i]=n,t):(n!==void 0&&(r>=(l=(t??(t=0|s[pi]))>>14&1023||536870912)?n!=null&&(s[l+(a?0:-1)]={[r]:n}):s[i]=n),t)}function YT(){return ZRs===void 0?2:4}function ZT(s,t,r,n,a){let i=s.v,l=0|i[pi];n=A0(s,l)?1:n,a=!!a||n===3,n===2&&Q8(s)&&(i=s.v,l=0|i[pi]);let o=(s=kMe(i,t))===rM?7:0|s[pi],c=SMe(o,l);var d=!(4&c);if(d){4&c&&(s=C1(s),o=0,c=QE(c,l),l=bm(i,l,t,s));let h=0,m=0;for(;h{const o=_Me(l,r,!1,t);return i=o!==l&&o!=null,o}))!=null)return i&&!A0(n)&&nM(s,t),n}function Ul(s,t,r,n){let a=s.v,i=0|a[pi];if((t=Zxt(a,i,t,r,n))==null)return t;if(i=0|a[pi],!A0(s,i)){const l=jMe(t);l!==t&&(Q8(s)&&(a=s.v,i=0|a[pi]),i=bm(a,i,r,t=l,n),nM(a,i))}return t}function Xxt(s,t,r,n,a,i,l,o){var c=A0(s,r);i=c?1:i,l=!!l||i===3,c=o&&!c,(i===2||c)&&Q8(s)&&(r=0|(t=s.v)[pi]);var d=(s=kMe(t,a))===rM?7:0|s[pi],h=SMe(d,r);if(o=!(4&h)){var m=s,p=r;const x=!!(2&h);x&&(p|=2);let y=!x,_=!0,b=0,j=0;for(;b32)for(a|=(127&r)>>4,i=3;i<32&&128&r;i+=7)r=l[o++],a|=(127&r)<>>0,a>>>0);throw Error()}function PMe(s){let t=0,r=s.g;const n=r+10,a=s.h;for(;r>>0}function cpe(s){var t=s.h;const r=s.g;var n=t[r],a=t[r+1];const i=t[r+2];return t=t[r+3],JE(s,s.g+4),s=2*((a=(n<<0|a<<8|i<<16|t<<24)>>>0)>>31)+1,n=a>>>23&255,a&=8388607,n==255?a?NaN:s*(1/0):n==0?1401298464324817e-60*s*a:s*Math.pow(2,n-150)*(a+8388608)}function wOs(s){return SS(s)}function JE(s,t){if(s.g=t,t>s.l)throw Error()}function Jxt(s,t){if(t<0)throw Error();const r=s.g;if((t=r+t)>s.l)throw Error();return s.g=t,r}function e0t(s,t){if(t==0)return PA();var r=Jxt(s,t);return s.Y&&s.j?r=s.h.subarray(r,r+t):(s=s.h,r=r===(t=r+t)?new Uint8Array(0):rOs?s.slice(r,t):new Uint8Array(s.subarray(r,t))),r.length==0?PA():new T_(r,$L)}var _Ge=[];function t0t(s,t,r,n){if(dpe.length){const a=dpe.pop();return a.o(n),a.g.init(s,t,r,n),a}return new jOs(s,t,r,n)}function s0t(s){s.g.clear(),s.l=-1,s.h=-1,dpe.length<100&&dpe.push(s)}function r0t(s){var t=s.g;if(t.g==t.l)return!1;s.m=s.g.g;var r=B_(s.g);if(t=r>>>3,!((r&=7)>=0&&r<=5)||t<1)throw Error();return s.l=t,s.h=r,!0}function Rue(s){switch(s.h){case 0:s.h!=0?Rue(s):PMe(s.g);break;case 1:JE(s=s.g,s.g+8);break;case 2:if(s.h!=2)Rue(s);else{var t=B_(s.g);JE(s=s.g,s.g+t)}break;case 5:JE(s=s.g,s.g+4);break;case 3:for(t=s.l;;){if(!r0t(s))throw Error();if(s.h==4){if(s.l!=t)throw Error();break}Rue(s)}break;default:throw Error()}}function $z(s,t,r){const n=s.g.l;var a=B_(s.g);let i=(a=s.g.g+a)-n;if(i<=0&&(s.g.l=a,r(t,s,void 0,void 0,void 0),i=a-s.g.g),i)throw Error();return s.g.g=a,s.g.l=n,t}function LMe(s){var t=B_(s.g),r=Jxt(s=s.g,t);if(s=s.h,RRs){var n,a=s;(n=fwe)||(n=fwe=new TextDecoder("utf-8",{fatal:!0})),t=r+t,a=r===0&&t===a.length?a:a.subarray(r,t);try{var i=n.decode(a)}catch(o){if(Zq===void 0){try{n.decode(new Uint8Array([128]))}catch{}try{n.decode(new Uint8Array([97])),Zq=!0}catch{Zq=!1}}throw!Zq&&(fwe=void 0),o}}else{t=(i=r)+t,r=[];let o,c=null;for(;i=t?oC():(o=s[i++],l<194||(192&o)!=128?(i--,oC()):r.push((31&l)<<6|63&o)):l<240?i>=t-1?oC():(o=s[i++],(192&o)!=128||l===224&&o<160||l===237&&o>=160||(192&(n=s[i++]))!=128?(i--,oC()):r.push((15&l)<<12|(63&o)<<6|63&n)):l<=244?i>=t-2?oC():(o=s[i++],(192&o)!=128||o-144+(l<<28)>>30||(192&(n=s[i++]))!=128||(192&(a=s[i++]))!=128?(i--,oC()):(l=(7&l)<<18|(63&o)<<12|(63&n)<<6|63&a,l-=65536,r.push(55296+(l>>10&1023),56320+(1023&l)))):oC(),r.length>=8192&&(c=nGe(c,r),r.length=0)}i=nGe(c,r)}return i}function n0t(s){const t=B_(s.g);return e0t(s.g,t)}function K0e(s,t,r){var n=B_(s.g);for(n=s.g.g+n;s.g.g>>0,this.g=t>>>0}};let NOs;function jGe(s){return s?/^-?\d+$/.test(s)?(q0e(s),new L4e(cu,Ph)):null:kOs||(kOs=new L4e(0,0))}var L4e=class{constructor(s,t){this.h=s>>>0,this.g=t>>>0}};let kOs;function vP(s,t,r){for(;r>0||t>127;)s.g.push(127&t|128),t=(t>>>7|r<<25)>>>0,r>>>=7;s.g.push(t)}function tD(s,t){for(;t>127;)s.g.push(127&t|128),t>>>=7;s.g.push(t)}function Y0e(s,t){if(t>=0)tD(s,t);else{for(let r=0;r<9;r++)s.g.push(127&t|128),t>>=7;s.g.push(1)}}function DMe(s){var t=cu;s.g.push(t>>>0&255),s.g.push(t>>>8&255),s.g.push(t>>>16&255),s.g.push(t>>>24&255)}function WL(s,t){t.length!==0&&(s.l.push(t),s.h+=t.length)}function lv(s,t,r){tD(s.g,8*t+r)}function RMe(s,t){return lv(s,t,2),t=s.g.end(),WL(s,t),t.push(s.h),t}function OMe(s,t){var r=t.pop();for(r=s.h+s.g.length()-r;r>127;)t.push(127&r|128),r>>>=7,s.h++;t.push(r),s.h++}function Z0e(s,t,r){lv(s,t,2),tD(s.g,r.length),WL(s,s.g.end()),WL(s,r)}function upe(s,t,r,n){r!=null&&(t=RMe(s,t),n(r,s),OMe(s,t))}function J_(){const s=class{constructor(){throw Error()}};return Object.setPrototypeOf(s,s.prototype),s}var FMe=J_(),a0t=J_(),BMe=J_(),zMe=J_(),$Me=J_(),i0t=J_(),SOs=J_(),X0e=J_(),o0t=J_(),l0t=J_();function ew(s,t,r){var n=s.v;b0&&b0 in n&&(n=n[b0])&&delete n[t.g],t.h?t.j(s,t.h,t.g,r,t.l):t.j(s,t.g,r,t.l)}var gi=class{constructor(s,t){this.v=Vxt(s,t,void 0,2048)}toJSON(){return qxt(this)}j(){var a;var s=oFs,t=this.v,r=s.g,n=b0;if(K8&&n&&((a=t[n])==null?void 0:a[r])!=null&&UL(WRs,3),t=s.g,dGe&&b0&&dGe===void 0&&(n=(r=this.v)[b0])&&(n=n.da))try{n(r,t,gOs)}catch(i){jxt(i)}return s.h?s.m(this,s.h,s.g,s.l):s.m(this,s.g,s.defaultValue,s.l)}clone(){const s=this.v,t=0|s[pi];return NMe(this,s,t)?wMe(this,s,!0):new this.constructor(X8(s,t,!1))}};gi.prototype[qL]=VL,gi.prototype.toString=function(){return this.v.toString()};var sD=class{constructor(s,t,r){this.g=s,this.h=t,s=FMe,this.l=!!s&&r===s||!1}};function Q0e(s,t){return new sD(s,t,FMe)}function c0t(s,t,r,n,a){upe(s,r,m0t(t,n),a)}const COs=Q0e(function(s,t,r,n,a){return s.h===2&&($z(s,EMe(t,n,r),a),!0)},c0t),TOs=Q0e(function(s,t,r,n,a){return s.h===2&&($z(s,EMe(t,n,r),a),!0)},c0t);var J0e=Symbol(),eye=Symbol(),D4e=Symbol(),NGe=Symbol(),kGe=Symbol();let d0t,u0t;function aM(s,t,r,n){var a=n[s];if(a)return a;(a={}).qa=n,a.T=function(m){switch(typeof m){case"boolean":return vOs||(vOs=[0,void 0,!0]);case"number":return m>0?void 0:m===0?bOs||(bOs=[0,void 0]):[-m,void 0];case"string":return[0,m];case"object":return m}}(n[0]);var i=n[1];let l=1;i&&i.constructor===Object&&(a.ba=i,typeof(i=n[++l])=="function"&&(a.ma=!0,d0t??(d0t=i),u0t??(u0t=n[l+1]),i=n[l+=2]));const o={};for(;i&&Array.isArray(i)&&i.length&&typeof i[0]=="number"&&i[0]>0;){for(var c=0;ca(i,l,o,n):a}function qMe(s,t,r,n,a){const i=r.g;let l,o;s[t]=(c,d,h)=>i(c,d,h,o||(o=aM(eye,UMe,qMe,n).T),l||(l=VMe(n)),a)}function VMe(s){let t=s[D4e];if(t!=null)return t;const r=aM(eye,UMe,qMe,s);return t=r.ma?(n,a)=>d0t(n,a,r):(n,a)=>{for(;r0t(a)&&a.h!=4;){var i=a.l,l=r[i];if(l==null){var o=r.ba;o&&(o=o[i])&&(o=AOs(o))!=null&&(l=r[i]=o)}if(l==null||!l(a,n,i)){if(l=(o=a).m,Rue(o),o.ha)var c=void 0;else c=o.g.g-l,o.g.g=l,c=e0t(o.g,c);l=void 0,o=n,c&&((l=o[b0]??(o[b0]=new I4e))[i]??(l[i]=[])).push(c)}}return(n=H0e(n))&&(n.da=r.qa[kGe]),!0},s[D4e]=t,s[kGe]=EOs.bind(s),t}function EOs(s,t,r,n){var a=this[eye];const i=this[D4e],l=ZE(void 0,a.T),o=H0e(s);if(o){var c=!1,d=a.ba;if(d){if(a=(h,m,p)=>{if(p.length!==0)if(d[m])for(const x of p){h=t0t(x);try{c=!0,i(l,h)}finally{s0t(h)}}else n==null||n(s,m,p)},t==null)ope(o,a);else if(o!=null){const h=o[t];h&&a(o,t,h)}if(c){let h=0|s[pi];if(2&h&&2048&h&&!(r!=null&&r.Ka))throw Error();const m=Y8(h),p=(x,y)=>{if(mj(s,x,m)!=null){if((r==null?void 0:r.Qa)===1)return;throw Error()}y!=null&&(h=bm(s,h,x,y,m)),delete o[x]};t==null?Ixt(l,0|l[pi],(x,y)=>{p(x,y)}):p(t,mj(l,t,m))}}}}function AOs(s){const t=(s=h0t(s))[0].g;if(s=s[1]){const r=VMe(s),n=aM(eye,UMe,qMe,s).T;return(a,i,l)=>t(a,i,l,n,r)}return t}function tye(s,t,r){s[t]=r.h}function sye(s,t,r,n){let a,i;const l=r.h;s[t]=(o,c,d)=>l(o,c,d,i||(i=aM(J0e,tye,sye,n).T),a||(a=f0t(n)))}function f0t(s){let t=s[NGe];if(!t){const r=aM(J0e,tye,sye,s);t=(n,a)=>p0t(n,a,r),s[NGe]=t}return t}function p0t(s,t,r){Ixt(s,0|s[pi],(n,a)=>{if(a!=null){var i=function(l,o){var c=l[o];if(c)return c;if((c=l.ba)&&(c=c[o])){var d=(c=h0t(c))[0].h;if(c=c[1]){const h=f0t(c),m=aM(J0e,tye,sye,c).T;c=l.ma?u0t(m,h):(p,x,y)=>d(p,x,y,m,h)}else c=d;return l[o]=c}}(r,n);i?i(t,a,n):n<500||UL(A4e,3)}}),(s=H0e(s))&&ope(s,(n,a,i)=>{for(WL(t,t.g.end()),n=0;n{upe(s,r,ZE([l,i],n),a)});else if(Array.isArray(t)){for(let i=0;i>BigInt(32))),vP(s.g,r.h,r.g);break;default:r=jGe(t),vP(s.g,r.h,r.g)}}function y0t(s,t,r){(t=Z8(t))!=null&&t!=null&&(lv(s,r,0),Y0e(s.g,t))}function v0t(s,t,r){(t=Rxt(t))!=null&&(lv(s,r,0),s.g.g.push(t?1:0))}function b0t(s,t,r){(t=Gf(t))!=null&&Z0e(s,r,wxt(t))}function _0t(s,t,r,n,a){upe(s,r,m0t(t,n),a)}function w0t(s,t,r){(t=t==null||typeof t=="string"||t instanceof T_?t:void 0)!=null&&Z0e(s,r,MMe(t,!0).buffer)}function j0t(s,t,r){(t=Oxt(t))!=null&&t!=null&&(lv(s,r,0),tD(s.g,t))}function N0t(s,t,r){return(s.h===5||s.h===2)&&(t=eD(t,0|t[pi],r),s.h==2?K0e(s,cpe,t):t.push(cpe(s.g)),!0)}var Rh=Mp(function(s,t,r){return s.h===5&&(Ip(t,r,cpe(s.g)),!0)},g0t,X0e),POs=nD(N0t,function(s,t,r){if((t=rD(a_,t))!=null)for(let l=0;l=0?n=String(a):((a=n.indexOf("."))!==-1&&(n=n.substring(0,a)),(a=n[0]!=="-"&&((a=n.length)<20||a===20&&n<="18446744073709551615"))||(q0e(n),n=gB(cu,Ph))),n;if(a==="number")return(n=GL(n))>=0&&DA(n)||(HL(n),n=Lxt(cu,Ph)),n}}(t),t!=null&&(typeof t=="string"&&wGe(t),t!=null))switch(lv(s,r,0),typeof t){case"number":s=s.g,HL(t),vP(s,cu,Ph);break;case"bigint":r=BigInt.asUintN(64,t),r=new P4e(Number(r&BigInt(4294967295)),Number(r>>BigInt(32))),vP(s.g,r.h,r.g);break;default:r=wGe(t),vP(s.g,r.h,r.g)}},SOs),mm=Mp(function(s,t,r){return s.h===0&&(Ip(t,r,SS(s.g)),!0)},y0t,zMe),Uz=nD(function(s,t,r){return(s.h===0||s.h===2)&&(t=eD(t,0|t[pi],r),s.h==2?K0e(s,SS,t):t.push(SS(s.g)),!0)},function(s,t,r){if((t=rD(Z8,t))!=null&&t.length){r=RMe(s,r);for(let n=0;n{{const i={ea:!0};n&&Object.assign(i,n),r=t0t(r,void 0,void 0,i);try{const l=new s,o=l.v;VMe(t)(o,r);var a=l}finally{s0t(r)}}return a}}function rye(s){return function(){const t=new class{constructor(){this.l=[],this.h=0,this.g=new class{constructor(){this.g=[]}length(){return this.g.length}end(){const l=this.g;return this.g=[],l}}}};p0t(this.v,t,aM(J0e,tye,sye,s)),WL(t,t.g.end());const r=new Uint8Array(t.h),n=t.l,a=n.length;let i=0;for(let l=0;la;r=TGe.createPolicy("goog#html",{createHTML:n,createScript:n,createScriptURL:n})}catch{}return r}()),s=(t=vwe)?t.createScriptURL(s):s,new class{constructor(r){this.g=r}toString(){return this.g+""}}(s)}function Xq(s,...t){if(t.length===0)return EGe(s[0]);let r=s[0];for(let n=0;n({index:zy(n,1)??0??-1,score:lh(n,2)??0,categoryName:Gf(fu(n,3))??""??"",displayName:Gf(fu(n,4))??""??""})),headIndex:t,headName:r}}function uFs(s){const t={classifications:fj(s,GOs,1).map(r=>{var n;return JMe(((n=Ul(r,P0t,4))==null?void 0:n.g())??[],zy(r,2)??0,Gf(fu(r,3))??"")})};return function(r){return r==null?r:typeof r=="bigint"?(M4e(r)?r=Number(r):(r=Fz(64,r),r=M4e(r)?Number(r):String(r)),r):Bz(r)?typeof r=="number"?bMe(r):Bxt(r):void 0}(fu(s,2,void 0,void 0,ipe))!=null&&(t.timestampMs=iyt(fu(s,2,void 0,void 0,ipe)??Hxt)),t}function oyt(s){var l,o;var t=ZT(s,3,a_,YT()),r=ZT(s,2,Z8,YT()),n=ZT(s,1,Gf,YT()),a=ZT(s,9,Gf,YT());const i={categories:[],keypoints:[]};for(let c=0;ct>127?t-256:t)}function $Ge(s,t){if(s.length!==t.length)throw Error(`Cannot compute cosine similarity between embeddings of different sizes (${s.length} vs. ${t.length}).`);let r=0,n=0,a=0;for(let i=0;i=1&&Number(s[1])>=17))}async function UGe(s){if(typeof importScripts!="function"){const t=document.createElement("script");return t.src=s.toString(),t.crossOrigin="anonymous",new Promise((r,n)=>{t.addEventListener("load",()=>{r()},!1),t.addEventListener("error",a=>{n(a)},!1),document.body.appendChild(t)})}try{importScripts(s.toString())}catch(t){if(!(t instanceof TypeError))throw t;await self.import(s.toString())}}function dyt(s){return s.videoWidth!==void 0?[s.videoWidth,s.videoHeight]:s.naturalWidth!==void 0?[s.naturalWidth,s.naturalHeight]:s.displayWidth!==void 0?[s.displayWidth,s.displayHeight]:[s.width,s.height]}function yi(s,t,r){s.m||console.error("No wasm multistream support detected: ensure dependency inclusion of :gl_graph_runner_internal_multi_input target"),r(t=s.i.stringToNewUTF8(t)),s.i._free(t)}function qGe(s,t,r){if(!s.i.canvas)throw Error("No OpenGL canvas configured.");if(r?s.i._bindTextureToStream(r):s.i._bindTextureToCanvas(),!(r=s.i.canvas.getContext("webgl2")||s.i.canvas.getContext("webgl")))throw Error("Failed to obtain WebGL context from the provided canvas. `getContext()` should only be invoked with `webgl` or `webgl2`.");s.i.gpuOriginForWebTexturesIsBottomLeft&&r.pixelStorei(r.UNPACK_FLIP_Y_WEBGL,!0),r.texImage2D(r.TEXTURE_2D,0,r.RGBA,r.RGBA,r.UNSIGNED_BYTE,t),s.i.gpuOriginForWebTexturesIsBottomLeft&&r.pixelStorei(r.UNPACK_FLIP_Y_WEBGL,!1);const[n,a]=dyt(t);return!s.l||n===s.i.canvas.width&&a===s.i.canvas.height||(s.i.canvas.width=n,s.i.canvas.height=a),[n,a]}function VGe(s,t,r){s.m||console.error("No wasm multistream support detected: ensure dependency inclusion of :gl_graph_runner_internal_multi_input target");const n=new Uint32Array(t.length);for(let a=0;a>2),r(t);for(const a of n)s.i._free(a);s.i._free(t)}function Tb(s,t,r){s.i.simpleListeners=s.i.simpleListeners||{},s.i.simpleListeners[t]=r}function NN(s,t,r){let n=[];s.i.simpleListeners=s.i.simpleListeners||{},s.i.simpleListeners[t]=(a,i,l)=>{i?(r(n,l),n=[]):n.push(a)}}G6.forVisionTasks=function(s,t=!1){return Jq("vision",s??Xq``,t)},G6.forTextTasks=function(s,t=!1){return Jq("text",s??Xq``,t)},G6.forGenAiTasks=function(s,t=!1){return Jq("genai",s??Xq``,t)},G6.forAudioTasks=function(s,t=!1){return Jq("audio",s??Xq``,t)},G6.isSimdSupported=function(s=!1){return lyt(s)};async function mFs(s,t,r,n){return s=await(async(a,i,l,o,c)=>{if(i&&await UGe(i),!self.ModuleFactory||l&&(await UGe(l),!self.ModuleFactory))throw Error("ModuleFactory not set.");return self.Module&&c&&((i=self.Module).locateFile=c.locateFile,c.mainScriptUrlOrBlob&&(i.mainScriptUrlOrBlob=c.mainScriptUrlOrBlob)),c=await self.ModuleFactory(self.Module||c),self.ModuleFactory=self.Module=void 0,new a(c,o)})(s,r.wasmLoaderPath,r.assetLoaderPath,t,{locateFile:a=>a.endsWith(".wasm")?r.wasmBinaryPath.toString():r.assetBinaryPath&&a.endsWith(".data")?r.assetBinaryPath.toString():a}),await s.o(n),s}function wwe(s,t){const r=Ul(s.baseOptions,hpe,1)||new hpe;typeof t=="string"?(Sc(r,2,zz(t)),Sc(r,1)):t instanceof Uint8Array&&(Sc(r,1,gMe(t,!1)),Sc(r,2)),Fi(s.baseOptions,0,1,r)}function HGe(s){try{const t=s.H.length;if(t===1)throw Error(s.H[0].message);if(t>1)throw Error("Encountered multiple errors: "+s.H.map(r=>r.message).join(", "))}finally{s.H=[]}}function ri(s,t){s.C=Math.max(s.C,t)}function oye(s,t){s.B=new xx,M0(s.B,2,"PassThroughCalculator"),Zd(s.B,"free_memory"),_l(s.B,"free_memory_unused_out"),vu(t,"free_memory"),cv(t,s.B)}function KL(s,t){Zd(s.B,t),_l(s.B,t+"_unused_out")}function lye(s){s.g.addBoolToStream(!0,"free_memory",s.C)}var z4e=class{constructor(s){this.g=s,this.H=[],this.C=0,this.g.setAutoRenderToScreen(!1)}l(s,t=!0){var r,n,a,i,l,o;if(t){const c=s.baseOptions||{};if((r=s.baseOptions)!=null&&r.modelAssetBuffer&&((n=s.baseOptions)!=null&&n.modelAssetPath))throw Error("Cannot set both baseOptions.modelAssetPath and baseOptions.modelAssetBuffer");if(!((a=Ul(this.baseOptions,hpe,1))!=null&&a.g()||(i=Ul(this.baseOptions,hpe,1))!=null&&i.l()||(l=s.baseOptions)!=null&&l.modelAssetBuffer||(o=s.baseOptions)!=null&&o.modelAssetPath))throw Error("Either baseOptions.modelAssetPath or baseOptions.modelAssetBuffer must be set");if(function(d,h){let m=Ul(d.baseOptions,RGe,3);if(!m){var p=m=new RGe,x=new AGe;E7(p,4,Oue,x)}"delegate"in h&&(h.delegate==="GPU"?(h=m,p=new BOs,E7(h,2,Oue,p)):(h=m,p=new AGe,E7(h,4,Oue,p))),Fi(d.baseOptions,0,3,m)}(this,c),c.modelAssetPath)return fetch(c.modelAssetPath.toString()).then(d=>{if(d.ok)return d.arrayBuffer();throw Error(`Failed to fetch model: ${c.modelAssetPath} (${d.status})`)}).then(d=>{try{this.g.i.FS_unlink("/model.dat")}catch{}this.g.i.FS_createDataFile("/","model.dat",new Uint8Array(d),!0,!1,!1),wwe(this,"/model.dat"),this.m(),this.L()});if(c.modelAssetBuffer instanceof Uint8Array)wwe(this,c.modelAssetBuffer);else if(c.modelAssetBuffer)return async function(d){const h=[];for(var m=0;;){const{done:p,value:x}=await d.read();if(p)break;h.push(x),m+=x.length}if(h.length===0)return new Uint8Array(0);if(h.length===1)return h[0];d=new Uint8Array(m),m=0;for(const p of h)d.set(p,m),m+=p.length;return d}(c.modelAssetBuffer).then(d=>{wwe(this,d),this.m(),this.L()})}return this.m(),this.L(),Promise.resolve()}L(){}ca(){let s;if(this.g.ca(t=>{s=zOs(t)}),!s)throw Error("Failed to retrieve CalculatorGraphConfig");return s}setGraph(s,t){this.g.attachErrorListener((r,n)=>{this.H.push(Error(n))}),this.g.Ja(),this.g.setGraph(s,t),this.B=void 0,HGe(this)}finishProcessing(){this.g.finishProcessing(),HGe(this)}close(){this.B=void 0,this.g.closeGraph()}};function cS(s,t){if(!s)throw Error(`Unable to obtain required WebGL resource: ${t}`);return s}z4e.prototype.close=z4e.prototype.close;class fFs{constructor(t,r,n,a){this.g=t,this.h=r,this.m=n,this.l=a}bind(){this.g.bindVertexArray(this.h)}close(){this.g.deleteVertexArray(this.h),this.g.deleteBuffer(this.m),this.g.deleteBuffer(this.l)}}function GGe(s,t,r){const n=s.g;if(r=cS(n.createShader(r),"Failed to create WebGL shader"),n.shaderSource(r,t),n.compileShader(r),!n.getShaderParameter(r,n.COMPILE_STATUS))throw Error(`Could not compile WebGL shader: ${n.getShaderInfoLog(r)}`);return n.attachShader(s.h,r),r}function WGe(s,t){const r=s.g,n=cS(r.createVertexArray(),"Failed to create vertex array");r.bindVertexArray(n);const a=cS(r.createBuffer(),"Failed to create buffer");r.bindBuffer(r.ARRAY_BUFFER,a),r.enableVertexAttribArray(s.O),r.vertexAttribPointer(s.O,2,r.FLOAT,!1,0,0),r.bufferData(r.ARRAY_BUFFER,new Float32Array([-1,-1,-1,1,1,1,1,-1]),r.STATIC_DRAW);const i=cS(r.createBuffer(),"Failed to create buffer");return r.bindBuffer(r.ARRAY_BUFFER,i),r.enableVertexAttribArray(s.L),r.vertexAttribPointer(s.L,2,r.FLOAT,!1,0,0),r.bufferData(r.ARRAY_BUFFER,new Float32Array(t?[0,1,0,0,1,0,1,1]:[0,0,0,1,1,1,1,0]),r.STATIC_DRAW),r.bindBuffer(r.ARRAY_BUFFER,null),r.bindVertexArray(null),new fFs(r,n,a,i)}function e6e(s,t){if(s.g){if(t!==s.g)throw Error("Cannot change GL context once initialized")}else s.g=t}function pFs(s,t,r,n){return e6e(s,t),s.h||(s.m(),s.D()),r?(s.u||(s.u=WGe(s,!0)),r=s.u):(s.A||(s.A=WGe(s,!1)),r=s.A),t.useProgram(s.h),r.bind(),s.l(),s=n(),r.g.bindVertexArray(null),s}function uyt(s,t,r){return e6e(s,t),s=cS(t.createTexture(),"Failed to create texture"),t.bindTexture(t.TEXTURE_2D,s),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,r??t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,r??t.LINEAR),t.bindTexture(t.TEXTURE_2D,null),s}function hyt(s,t,r){e6e(s,t),s.B||(s.B=cS(t.createFramebuffer(),"Failed to create framebuffe.")),t.bindFramebuffer(t.FRAMEBUFFER,s.B),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,r,0)}function gFs(s){var t;(t=s.g)==null||t.bindFramebuffer(s.g.FRAMEBUFFER,null)}var myt=class{H(){return` precision mediump float; varying vec2 vTex; uniform sampler2D inputTexture; void main() { gl_FragColor = texture2D(inputTexture, vTex); } `}m(){const s=this.g;if(this.h=cS(s.createProgram(),"Failed to create WebGL program"),this.X=GGe(this,` attribute vec2 aVertex; attribute vec2 aTex; varying vec2 vTex; void main(void) { gl_Position = vec4(aVertex, 0.0, 1.0); vTex = aTex; }`,s.VERTEX_SHADER),this.W=GGe(this,this.H(),s.FRAGMENT_SHADER),s.linkProgram(this.h),!s.getProgramParameter(this.h,s.LINK_STATUS))throw Error(`Error during program linking: ${s.getProgramInfoLog(this.h)}`);this.O=s.getAttribLocation(this.h,"aVertex"),this.L=s.getAttribLocation(this.h,"aTex")}D(){}l(){}close(){if(this.h){const s=this.g;s.deleteProgram(this.h),s.deleteShader(this.X),s.deleteShader(this.W)}this.B&&this.g.deleteFramebuffer(this.B),this.A&&this.A.close(),this.u&&this.u.close()}};function C2(s,t){switch(t){case 0:return s.g.find(r=>r instanceof Uint8Array);case 1:return s.g.find(r=>r instanceof Float32Array);case 2:return s.g.find(r=>typeof WebGLTexture<"u"&&r instanceof WebGLTexture);default:throw Error(`Type is not supported: ${t}`)}}function $4e(s){var t=C2(s,1);if(!t){if(t=C2(s,0))t=new Float32Array(t).map(n=>n/255);else{t=new Float32Array(s.width*s.height);const n=YL(s);var r=t6e(s);if(hyt(r,n,fyt(s)),"iPad Simulator;iPhone Simulator;iPod Simulator;iPad;iPhone;iPod".split(";").includes(navigator.platform)||navigator.userAgent.includes("Mac")&&"document"in self&&"ontouchend"in self.document){r=new Float32Array(s.width*s.height*4),n.readPixels(0,0,s.width,s.height,n.RGBA,n.FLOAT,r);for(let a=0,i=0;aMath.round(255*r))),s.g.push(t)),t;var s,t}ia(){return $4e(this)}N(){return fyt(this)}clone(){const s=[];for(const t of this.g){let r;if(t instanceof Uint8Array)r=new Uint8Array(t);else if(t instanceof Float32Array)r=new Float32Array(t);else{if(!(t instanceof WebGLTexture))throw Error(`Type is not supported: ${t}`);{const n=YL(this),a=t6e(this);n.activeTexture(n.TEXTURE1),r=uyt(a,n,this.m?n.LINEAR:n.NEAREST),n.bindTexture(n.TEXTURE_2D,r);const i=pyt(this);n.texImage2D(n.TEXTURE_2D,0,i,this.width,this.height,0,n.RED,n.FLOAT,null),n.bindTexture(n.TEXTURE_2D,null),hyt(a,n,r),pFs(a,n,!1,()=>{gyt(this),n.clearColor(0,0,0,0),n.clear(n.COLOR_BUFFER_BIT),n.drawArrays(n.TRIANGLE_FAN,0,4),U4e(this)}),gFs(a),U4e(this)}}s.push(r)}return new Hm(s,this.m,this.R(),this.canvas,this.l,this.width,this.height)}close(){this.j&&YL(this).deleteTexture(C2(this,2)),KGe=-1}};Hm.prototype.close=Hm.prototype.close,Hm.prototype.clone=Hm.prototype.clone,Hm.prototype.getAsWebGLTexture=Hm.prototype.N,Hm.prototype.getAsFloat32Array=Hm.prototype.ia,Hm.prototype.getAsUint8Array=Hm.prototype.ja,Hm.prototype.hasWebGLTexture=Hm.prototype.R,Hm.prototype.hasFloat32Array=Hm.prototype.ka,Hm.prototype.hasUint8Array=Hm.prototype.Fa;var KGe=250;function z1(...s){return s.map(([t,r])=>({start:t,end:r}))}const xFs=function(s){return class extends s{Ja(){this.i._registerModelResourcesGraphService()}}}((YGe=class{constructor(s,t){this.l=!0,this.i=s,this.g=null,this.h=0,this.m=typeof this.i._addIntToInputStream=="function",t!==void 0?this.i.canvas=t:cyt()?this.i.canvas=new OffscreenCanvas(1,1):(console.warn("OffscreenCanvas not supported and GraphRunner constructor glCanvas parameter is undefined. Creating backup canvas."),this.i.canvas=document.createElement("canvas"))}async initializeGraph(s){const t=await(await fetch(s)).arrayBuffer();s=!(s.endsWith(".pbtxt")||s.endsWith(".textproto")),this.setGraph(new Uint8Array(t),s)}setGraphFromString(s){this.setGraph(new TextEncoder().encode(s),!1)}setGraph(s,t){const r=s.length,n=this.i._malloc(r);this.i.HEAPU8.set(s,n),t?this.i._changeBinaryGraph(r,n):this.i._changeTextGraph(r,n),this.i._free(n)}configureAudio(s,t,r,n,a){this.i._configureAudio||console.warn('Attempting to use configureAudio without support for input audio. Is build dep ":gl_graph_runner_audio" missing?'),yi(this,n||"input_audio",i=>{yi(this,a=a||"audio_header",l=>{this.i._configureAudio(i,l,s,t??0,r)})})}setAutoResizeCanvas(s){this.l=s}setAutoRenderToScreen(s){this.i._setAutoRenderToScreen(s)}setGpuBufferVerticalFlip(s){this.i.gpuOriginForWebTexturesIsBottomLeft=s}ca(s){Tb(this,"__graph_config__",t=>{s(t)}),yi(this,"__graph_config__",t=>{this.i._getGraphConfig(t,void 0)}),delete this.i.simpleListeners.__graph_config__}attachErrorListener(s){this.i.errorListener=s}attachEmptyPacketListener(s,t){this.i.emptyPacketListeners=this.i.emptyPacketListeners||{},this.i.emptyPacketListeners[s]=t}addAudioToStream(s,t,r){this.addAudioToStreamWithShape(s,0,0,t,r)}addAudioToStreamWithShape(s,t,r,n,a){const i=4*s.length;this.h!==i&&(this.g&&this.i._free(this.g),this.g=this.i._malloc(i),this.h=i),this.i.HEAPF32.set(s,this.g/4),yi(this,n,l=>{this.i._addAudioToInputStream(this.g,t,r,l,a)})}addGpuBufferToStream(s,t,r){yi(this,t,n=>{const[a,i]=qGe(this,s,n);this.i._addBoundTextureToStream(n,a,i,r)})}addBoolToStream(s,t,r){yi(this,t,n=>{this.i._addBoolToInputStream(s,n,r)})}addDoubleToStream(s,t,r){yi(this,t,n=>{this.i._addDoubleToInputStream(s,n,r)})}addFloatToStream(s,t,r){yi(this,t,n=>{this.i._addFloatToInputStream(s,n,r)})}addIntToStream(s,t,r){yi(this,t,n=>{this.i._addIntToInputStream(s,n,r)})}addUintToStream(s,t,r){yi(this,t,n=>{this.i._addUintToInputStream(s,n,r)})}addStringToStream(s,t,r){yi(this,t,n=>{yi(this,s,a=>{this.i._addStringToInputStream(a,n,r)})})}addStringRecordToStream(s,t,r){yi(this,t,n=>{VGe(this,Object.keys(s),a=>{VGe(this,Object.values(s),i=>{this.i._addFlatHashMapToInputStream(a,i,Object.keys(s).length,n,r)})})})}addProtoToStream(s,t,r,n){yi(this,r,a=>{yi(this,t,i=>{const l=this.i._malloc(s.length);this.i.HEAPU8.set(s,l),this.i._addProtoToInputStream(l,s.length,i,a,n),this.i._free(l)})})}addEmptyPacketToStream(s,t){yi(this,s,r=>{this.i._addEmptyPacketToInputStream(r,t)})}addBoolVectorToStream(s,t,r){yi(this,t,n=>{const a=this.i._allocateBoolVector(s.length);if(!a)throw Error("Unable to allocate new bool vector on heap.");for(const i of s)this.i._addBoolVectorEntry(a,i);this.i._addBoolVectorToInputStream(a,n,r)})}addDoubleVectorToStream(s,t,r){yi(this,t,n=>{const a=this.i._allocateDoubleVector(s.length);if(!a)throw Error("Unable to allocate new double vector on heap.");for(const i of s)this.i._addDoubleVectorEntry(a,i);this.i._addDoubleVectorToInputStream(a,n,r)})}addFloatVectorToStream(s,t,r){yi(this,t,n=>{const a=this.i._allocateFloatVector(s.length);if(!a)throw Error("Unable to allocate new float vector on heap.");for(const i of s)this.i._addFloatVectorEntry(a,i);this.i._addFloatVectorToInputStream(a,n,r)})}addIntVectorToStream(s,t,r){yi(this,t,n=>{const a=this.i._allocateIntVector(s.length);if(!a)throw Error("Unable to allocate new int vector on heap.");for(const i of s)this.i._addIntVectorEntry(a,i);this.i._addIntVectorToInputStream(a,n,r)})}addUintVectorToStream(s,t,r){yi(this,t,n=>{const a=this.i._allocateUintVector(s.length);if(!a)throw Error("Unable to allocate new unsigned int vector on heap.");for(const i of s)this.i._addUintVectorEntry(a,i);this.i._addUintVectorToInputStream(a,n,r)})}addStringVectorToStream(s,t,r){yi(this,t,n=>{const a=this.i._allocateStringVector(s.length);if(!a)throw Error("Unable to allocate new string vector on heap.");for(const i of s)yi(this,i,l=>{this.i._addStringVectorEntry(a,l)});this.i._addStringVectorToInputStream(a,n,r)})}addBoolToInputSidePacket(s,t){yi(this,t,r=>{this.i._addBoolToInputSidePacket(s,r)})}addDoubleToInputSidePacket(s,t){yi(this,t,r=>{this.i._addDoubleToInputSidePacket(s,r)})}addFloatToInputSidePacket(s,t){yi(this,t,r=>{this.i._addFloatToInputSidePacket(s,r)})}addIntToInputSidePacket(s,t){yi(this,t,r=>{this.i._addIntToInputSidePacket(s,r)})}addUintToInputSidePacket(s,t){yi(this,t,r=>{this.i._addUintToInputSidePacket(s,r)})}addStringToInputSidePacket(s,t){yi(this,t,r=>{yi(this,s,n=>{this.i._addStringToInputSidePacket(n,r)})})}addProtoToInputSidePacket(s,t,r){yi(this,r,n=>{yi(this,t,a=>{const i=this.i._malloc(s.length);this.i.HEAPU8.set(s,i),this.i._addProtoToInputSidePacket(i,s.length,a,n),this.i._free(i)})})}addBoolVectorToInputSidePacket(s,t){yi(this,t,r=>{const n=this.i._allocateBoolVector(s.length);if(!n)throw Error("Unable to allocate new bool vector on heap.");for(const a of s)this.i._addBoolVectorEntry(n,a);this.i._addBoolVectorToInputSidePacket(n,r)})}addDoubleVectorToInputSidePacket(s,t){yi(this,t,r=>{const n=this.i._allocateDoubleVector(s.length);if(!n)throw Error("Unable to allocate new double vector on heap.");for(const a of s)this.i._addDoubleVectorEntry(n,a);this.i._addDoubleVectorToInputSidePacket(n,r)})}addFloatVectorToInputSidePacket(s,t){yi(this,t,r=>{const n=this.i._allocateFloatVector(s.length);if(!n)throw Error("Unable to allocate new float vector on heap.");for(const a of s)this.i._addFloatVectorEntry(n,a);this.i._addFloatVectorToInputSidePacket(n,r)})}addIntVectorToInputSidePacket(s,t){yi(this,t,r=>{const n=this.i._allocateIntVector(s.length);if(!n)throw Error("Unable to allocate new int vector on heap.");for(const a of s)this.i._addIntVectorEntry(n,a);this.i._addIntVectorToInputSidePacket(n,r)})}addUintVectorToInputSidePacket(s,t){yi(this,t,r=>{const n=this.i._allocateUintVector(s.length);if(!n)throw Error("Unable to allocate new unsigned int vector on heap.");for(const a of s)this.i._addUintVectorEntry(n,a);this.i._addUintVectorToInputSidePacket(n,r)})}addStringVectorToInputSidePacket(s,t){yi(this,t,r=>{const n=this.i._allocateStringVector(s.length);if(!n)throw Error("Unable to allocate new string vector on heap.");for(const a of s)yi(this,a,i=>{this.i._addStringVectorEntry(n,i)});this.i._addStringVectorToInputSidePacket(n,r)})}attachBoolListener(s,t){Tb(this,s,t),yi(this,s,r=>{this.i._attachBoolListener(r)})}attachBoolVectorListener(s,t){NN(this,s,t),yi(this,s,r=>{this.i._attachBoolVectorListener(r)})}attachIntListener(s,t){Tb(this,s,t),yi(this,s,r=>{this.i._attachIntListener(r)})}attachIntVectorListener(s,t){NN(this,s,t),yi(this,s,r=>{this.i._attachIntVectorListener(r)})}attachUintListener(s,t){Tb(this,s,t),yi(this,s,r=>{this.i._attachUintListener(r)})}attachUintVectorListener(s,t){NN(this,s,t),yi(this,s,r=>{this.i._attachUintVectorListener(r)})}attachDoubleListener(s,t){Tb(this,s,t),yi(this,s,r=>{this.i._attachDoubleListener(r)})}attachDoubleVectorListener(s,t){NN(this,s,t),yi(this,s,r=>{this.i._attachDoubleVectorListener(r)})}attachFloatListener(s,t){Tb(this,s,t),yi(this,s,r=>{this.i._attachFloatListener(r)})}attachFloatVectorListener(s,t){NN(this,s,t),yi(this,s,r=>{this.i._attachFloatVectorListener(r)})}attachStringListener(s,t){Tb(this,s,t),yi(this,s,r=>{this.i._attachStringListener(r)})}attachStringVectorListener(s,t){NN(this,s,t),yi(this,s,r=>{this.i._attachStringVectorListener(r)})}attachProtoListener(s,t,r){Tb(this,s,t),yi(this,s,n=>{this.i._attachProtoListener(n,r||!1)})}attachProtoVectorListener(s,t,r){NN(this,s,t),yi(this,s,n=>{this.i._attachProtoVectorListener(n,r||!1)})}attachAudioListener(s,t,r){this.i._attachAudioListener||console.warn('Attempting to use attachAudioListener without support for output audio. Is build dep ":gl_graph_runner_audio_out" missing?'),Tb(this,s,(n,a)=>{n=new Float32Array(n.buffer,n.byteOffset,n.length/4),t(n,a)}),yi(this,s,n=>{this.i._attachAudioListener(n,r||!1)})}finishProcessing(){this.i._waitUntilIdle()}closeGraph(){this.i._closeGraph(),this.i.simpleListeners=void 0,this.i.emptyPacketListeners=void 0}},class extends YGe{get ga(){return this.i}pa(s,t,r){yi(this,t,n=>{const[a,i]=qGe(this,s,n);this.ga._addBoundTextureAsImageToStream(n,a,i,r)})}Z(s,t){Tb(this,s,t),yi(this,s,r=>{this.ga._attachImageListener(r)})}aa(s,t){NN(this,s,t),yi(this,s,r=>{this.ga._attachImageVectorListener(r)})}}));var YGe,$1=class extends xFs{};async function Ol(s,t,r){return async function(n,a,i,l){return mFs(n,a,i,l)}(s,r.canvas??(cyt()?void 0:document.createElement("canvas")),t,r)}function xyt(s,t,r,n){if(s.U){const i=new F0t;if(r!=null&&r.regionOfInterest){if(!s.oa)throw Error("This task doesn't support region-of-interest.");var a=r.regionOfInterest;if(a.left>=a.right||a.top>=a.bottom)throw Error("Expected RectF with left < right and top < bottom.");if(a.left<0||a.top<0||a.right>1||a.bottom>1)throw Error("Expected RectF values to be in [0,1].");Ni(i,1,(a.left+a.right)/2),Ni(i,2,(a.top+a.bottom)/2),Ni(i,4,a.right-a.left),Ni(i,3,a.bottom-a.top)}else Ni(i,1,.5),Ni(i,2,.5),Ni(i,4,1),Ni(i,3,1);if(r!=null&&r.rotationDegrees){if((r==null?void 0:r.rotationDegrees)%90!=0)throw Error("Expected rotation to be a multiple of 90°.");if(Ni(i,5,-Math.PI*r.rotationDegrees/180),(r==null?void 0:r.rotationDegrees)%180!=0){const[l,o]=dyt(t);r=lh(i,3)*o/l,a=lh(i,4)*l/o,Ni(i,4,r),Ni(i,3,a)}}s.g.addProtoToStream(i.g(),"mediapipe.NormalizedRect",s.U,n)}s.g.pa(t,s.X,n??performance.now()),s.finishProcessing()}function U1(s,t,r){var n;if((n=s.baseOptions)!=null&&n.g())throw Error("Task is not initialized with image mode. 'runningMode' must be set to 'IMAGE'.");xyt(s,t,r,s.C+1)}function sw(s,t,r,n){var a;if(!((a=s.baseOptions)!=null&&a.g()))throw Error("Task is not initialized with video mode. 'runningMode' must be set to 'VIDEO'.");xyt(s,t,r,n)}function ZL(s,t,r,n){var a=t.data;const i=t.width,l=i*(t=t.height);if((a instanceof Uint8Array||a instanceof Float32Array)&&a.length!==l)throw Error("Unsupported channel count: "+a.length/l);return s=new Hm([a],r,!1,s.g.i.canvas,s.P,i,t),n?s.clone():s}var I0=class extends z4e{constructor(s,t,r,n){super(s),this.g=s,this.X=t,this.U=r,this.oa=n,this.P=new myt}l(s,t=!0){if("runningMode"in s&&Sc(this.baseOptions,2,xB(!!s.runningMode&&s.runningMode!=="IMAGE")),s.canvas!==void 0&&this.g.i.canvas!==s.canvas)throw Error("You must create a new task to reset the canvas.");return super.l(s,t)}close(){this.P.close(),super.close()}};I0.prototype.close=I0.prototype.close;var gy=class extends I0{constructor(s,t){super(new $1(s,t),"image_in","norm_rect_in",!1),this.j={detections:[]},Fi(s=this.h=new aye,0,1,t=new Zu),Ni(this.h,2,.5),Ni(this.h,3,.3)}get baseOptions(){return Ul(this.h,Zu,1)}set baseOptions(s){Fi(this.h,0,1,s)}o(s){return"minDetectionConfidence"in s&&Ni(this.h,2,s.minDetectionConfidence??.5),"minSuppressionThreshold"in s&&Ni(this.h,3,s.minSuppressionThreshold??.3),this.l(s)}F(s,t){return this.j={detections:[]},U1(this,s,t),this.j}G(s,t,r){return this.j={detections:[]},sw(this,s,r,t),this.j}m(){var s=new F0;vu(s,"image_in"),vu(s,"norm_rect_in"),Jl(s,"detections");const t=new O0;ew(t,QOs,this.h);const r=new xx;M0(r,2,"mediapipe.tasks.vision.face_detector.FaceDetectorGraph"),Zd(r,"IMAGE:image_in"),Zd(r,"NORM_RECT:norm_rect_in"),_l(r,"DETECTIONS:detections"),r.o(t),cv(s,r),this.g.attachProtoVectorListener("detections",(n,a)=>{for(const i of n)n=D0t(i),this.j.detections.push(oyt(n));ri(this,a)}),this.g.attachEmptyPacketListener("detections",n=>{ri(this,n)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};gy.prototype.detectForVideo=gy.prototype.G,gy.prototype.detect=gy.prototype.F,gy.prototype.setOptions=gy.prototype.o,gy.createFromModelPath=async function(s,t){return Ol(gy,s,{baseOptions:{modelAssetPath:t}})},gy.createFromModelBuffer=function(s,t){return Ol(gy,s,{baseOptions:{modelAssetBuffer:t}})},gy.createFromOptions=function(s,t){return Ol(gy,s,t)};var s6e=z1([61,146],[146,91],[91,181],[181,84],[84,17],[17,314],[314,405],[405,321],[321,375],[375,291],[61,185],[185,40],[40,39],[39,37],[37,0],[0,267],[267,269],[269,270],[270,409],[409,291],[78,95],[95,88],[88,178],[178,87],[87,14],[14,317],[317,402],[402,318],[318,324],[324,308],[78,191],[191,80],[80,81],[81,82],[82,13],[13,312],[312,311],[311,310],[310,415],[415,308]),r6e=z1([263,249],[249,390],[390,373],[373,374],[374,380],[380,381],[381,382],[382,362],[263,466],[466,388],[388,387],[387,386],[386,385],[385,384],[384,398],[398,362]),n6e=z1([276,283],[283,282],[282,295],[295,285],[300,293],[293,334],[334,296],[296,336]),yyt=z1([474,475],[475,476],[476,477],[477,474]),a6e=z1([33,7],[7,163],[163,144],[144,145],[145,153],[153,154],[154,155],[155,133],[33,246],[246,161],[161,160],[160,159],[159,158],[158,157],[157,173],[173,133]),i6e=z1([46,53],[53,52],[52,65],[65,55],[70,63],[63,105],[105,66],[66,107]),vyt=z1([469,470],[470,471],[471,472],[472,469]),o6e=z1([10,338],[338,297],[297,332],[332,284],[284,251],[251,389],[389,356],[356,454],[454,323],[323,361],[361,288],[288,397],[397,365],[365,379],[379,378],[378,400],[400,377],[377,152],[152,148],[148,176],[176,149],[149,150],[150,136],[136,172],[172,58],[58,132],[132,93],[93,234],[234,127],[127,162],[162,21],[21,54],[54,103],[103,67],[67,109],[109,10]),byt=[...s6e,...r6e,...n6e,...a6e,...i6e,...o6e],_yt=z1([127,34],[34,139],[139,127],[11,0],[0,37],[37,11],[232,231],[231,120],[120,232],[72,37],[37,39],[39,72],[128,121],[121,47],[47,128],[232,121],[121,128],[128,232],[104,69],[69,67],[67,104],[175,171],[171,148],[148,175],[118,50],[50,101],[101,118],[73,39],[39,40],[40,73],[9,151],[151,108],[108,9],[48,115],[115,131],[131,48],[194,204],[204,211],[211,194],[74,40],[40,185],[185,74],[80,42],[42,183],[183,80],[40,92],[92,186],[186,40],[230,229],[229,118],[118,230],[202,212],[212,214],[214,202],[83,18],[18,17],[17,83],[76,61],[61,146],[146,76],[160,29],[29,30],[30,160],[56,157],[157,173],[173,56],[106,204],[204,194],[194,106],[135,214],[214,192],[192,135],[203,165],[165,98],[98,203],[21,71],[71,68],[68,21],[51,45],[45,4],[4,51],[144,24],[24,23],[23,144],[77,146],[146,91],[91,77],[205,50],[50,187],[187,205],[201,200],[200,18],[18,201],[91,106],[106,182],[182,91],[90,91],[91,181],[181,90],[85,84],[84,17],[17,85],[206,203],[203,36],[36,206],[148,171],[171,140],[140,148],[92,40],[40,39],[39,92],[193,189],[189,244],[244,193],[159,158],[158,28],[28,159],[247,246],[246,161],[161,247],[236,3],[3,196],[196,236],[54,68],[68,104],[104,54],[193,168],[168,8],[8,193],[117,228],[228,31],[31,117],[189,193],[193,55],[55,189],[98,97],[97,99],[99,98],[126,47],[47,100],[100,126],[166,79],[79,218],[218,166],[155,154],[154,26],[26,155],[209,49],[49,131],[131,209],[135,136],[136,150],[150,135],[47,126],[126,217],[217,47],[223,52],[52,53],[53,223],[45,51],[51,134],[134,45],[211,170],[170,140],[140,211],[67,69],[69,108],[108,67],[43,106],[106,91],[91,43],[230,119],[119,120],[120,230],[226,130],[130,247],[247,226],[63,53],[53,52],[52,63],[238,20],[20,242],[242,238],[46,70],[70,156],[156,46],[78,62],[62,96],[96,78],[46,53],[53,63],[63,46],[143,34],[34,227],[227,143],[123,117],[117,111],[111,123],[44,125],[125,19],[19,44],[236,134],[134,51],[51,236],[216,206],[206,205],[205,216],[154,153],[153,22],[22,154],[39,37],[37,167],[167,39],[200,201],[201,208],[208,200],[36,142],[142,100],[100,36],[57,212],[212,202],[202,57],[20,60],[60,99],[99,20],[28,158],[158,157],[157,28],[35,226],[226,113],[113,35],[160,159],[159,27],[27,160],[204,202],[202,210],[210,204],[113,225],[225,46],[46,113],[43,202],[202,204],[204,43],[62,76],[76,77],[77,62],[137,123],[123,116],[116,137],[41,38],[38,72],[72,41],[203,129],[129,142],[142,203],[64,98],[98,240],[240,64],[49,102],[102,64],[64,49],[41,73],[73,74],[74,41],[212,216],[216,207],[207,212],[42,74],[74,184],[184,42],[169,170],[170,211],[211,169],[170,149],[149,176],[176,170],[105,66],[66,69],[69,105],[122,6],[6,168],[168,122],[123,147],[147,187],[187,123],[96,77],[77,90],[90,96],[65,55],[55,107],[107,65],[89,90],[90,180],[180,89],[101,100],[100,120],[120,101],[63,105],[105,104],[104,63],[93,137],[137,227],[227,93],[15,86],[86,85],[85,15],[129,102],[102,49],[49,129],[14,87],[87,86],[86,14],[55,8],[8,9],[9,55],[100,47],[47,121],[121,100],[145,23],[23,22],[22,145],[88,89],[89,179],[179,88],[6,122],[122,196],[196,6],[88,95],[95,96],[96,88],[138,172],[172,136],[136,138],[215,58],[58,172],[172,215],[115,48],[48,219],[219,115],[42,80],[80,81],[81,42],[195,3],[3,51],[51,195],[43,146],[146,61],[61,43],[171,175],[175,199],[199,171],[81,82],[82,38],[38,81],[53,46],[46,225],[225,53],[144,163],[163,110],[110,144],[52,65],[65,66],[66,52],[229,228],[228,117],[117,229],[34,127],[127,234],[234,34],[107,108],[108,69],[69,107],[109,108],[108,151],[151,109],[48,64],[64,235],[235,48],[62,78],[78,191],[191,62],[129,209],[209,126],[126,129],[111,35],[35,143],[143,111],[117,123],[123,50],[50,117],[222,65],[65,52],[52,222],[19,125],[125,141],[141,19],[221,55],[55,65],[65,221],[3,195],[195,197],[197,3],[25,7],[7,33],[33,25],[220,237],[237,44],[44,220],[70,71],[71,139],[139,70],[122,193],[193,245],[245,122],[247,130],[130,33],[33,247],[71,21],[21,162],[162,71],[170,169],[169,150],[150,170],[188,174],[174,196],[196,188],[216,186],[186,92],[92,216],[2,97],[97,167],[167,2],[141,125],[125,241],[241,141],[164,167],[167,37],[37,164],[72,38],[38,12],[12,72],[38,82],[82,13],[13,38],[63,68],[68,71],[71,63],[226,35],[35,111],[111,226],[101,50],[50,205],[205,101],[206,92],[92,165],[165,206],[209,198],[198,217],[217,209],[165,167],[167,97],[97,165],[220,115],[115,218],[218,220],[133,112],[112,243],[243,133],[239,238],[238,241],[241,239],[214,135],[135,169],[169,214],[190,173],[173,133],[133,190],[171,208],[208,32],[32,171],[125,44],[44,237],[237,125],[86,87],[87,178],[178,86],[85,86],[86,179],[179,85],[84,85],[85,180],[180,84],[83,84],[84,181],[181,83],[201,83],[83,182],[182,201],[137,93],[93,132],[132,137],[76,62],[62,183],[183,76],[61,76],[76,184],[184,61],[57,61],[61,185],[185,57],[212,57],[57,186],[186,212],[214,207],[207,187],[187,214],[34,143],[143,156],[156,34],[79,239],[239,237],[237,79],[123,137],[137,177],[177,123],[44,1],[1,4],[4,44],[201,194],[194,32],[32,201],[64,102],[102,129],[129,64],[213,215],[215,138],[138,213],[59,166],[166,219],[219,59],[242,99],[99,97],[97,242],[2,94],[94,141],[141,2],[75,59],[59,235],[235,75],[24,110],[110,228],[228,24],[25,130],[130,226],[226,25],[23,24],[24,229],[229,23],[22,23],[23,230],[230,22],[26,22],[22,231],[231,26],[112,26],[26,232],[232,112],[189,190],[190,243],[243,189],[221,56],[56,190],[190,221],[28,56],[56,221],[221,28],[27,28],[28,222],[222,27],[29,27],[27,223],[223,29],[30,29],[29,224],[224,30],[247,30],[30,225],[225,247],[238,79],[79,20],[20,238],[166,59],[59,75],[75,166],[60,75],[75,240],[240,60],[147,177],[177,215],[215,147],[20,79],[79,166],[166,20],[187,147],[147,213],[213,187],[112,233],[233,244],[244,112],[233,128],[128,245],[245,233],[128,114],[114,188],[188,128],[114,217],[217,174],[174,114],[131,115],[115,220],[220,131],[217,198],[198,236],[236,217],[198,131],[131,134],[134,198],[177,132],[132,58],[58,177],[143,35],[35,124],[124,143],[110,163],[163,7],[7,110],[228,110],[110,25],[25,228],[356,389],[389,368],[368,356],[11,302],[302,267],[267,11],[452,350],[350,349],[349,452],[302,303],[303,269],[269,302],[357,343],[343,277],[277,357],[452,453],[453,357],[357,452],[333,332],[332,297],[297,333],[175,152],[152,377],[377,175],[347,348],[348,330],[330,347],[303,304],[304,270],[270,303],[9,336],[336,337],[337,9],[278,279],[279,360],[360,278],[418,262],[262,431],[431,418],[304,408],[408,409],[409,304],[310,415],[415,407],[407,310],[270,409],[409,410],[410,270],[450,348],[348,347],[347,450],[422,430],[430,434],[434,422],[313,314],[314,17],[17,313],[306,307],[307,375],[375,306],[387,388],[388,260],[260,387],[286,414],[414,398],[398,286],[335,406],[406,418],[418,335],[364,367],[367,416],[416,364],[423,358],[358,327],[327,423],[251,284],[284,298],[298,251],[281,5],[5,4],[4,281],[373,374],[374,253],[253,373],[307,320],[320,321],[321,307],[425,427],[427,411],[411,425],[421,313],[313,18],[18,421],[321,405],[405,406],[406,321],[320,404],[404,405],[405,320],[315,16],[16,17],[17,315],[426,425],[425,266],[266,426],[377,400],[400,369],[369,377],[322,391],[391,269],[269,322],[417,465],[465,464],[464,417],[386,257],[257,258],[258,386],[466,260],[260,388],[388,466],[456,399],[399,419],[419,456],[284,332],[332,333],[333,284],[417,285],[285,8],[8,417],[346,340],[340,261],[261,346],[413,441],[441,285],[285,413],[327,460],[460,328],[328,327],[355,371],[371,329],[329,355],[392,439],[439,438],[438,392],[382,341],[341,256],[256,382],[429,420],[420,360],[360,429],[364,394],[394,379],[379,364],[277,343],[343,437],[437,277],[443,444],[444,283],[283,443],[275,440],[440,363],[363,275],[431,262],[262,369],[369,431],[297,338],[338,337],[337,297],[273,375],[375,321],[321,273],[450,451],[451,349],[349,450],[446,342],[342,467],[467,446],[293,334],[334,282],[282,293],[458,461],[461,462],[462,458],[276,353],[353,383],[383,276],[308,324],[324,325],[325,308],[276,300],[300,293],[293,276],[372,345],[345,447],[447,372],[352,345],[345,340],[340,352],[274,1],[1,19],[19,274],[456,248],[248,281],[281,456],[436,427],[427,425],[425,436],[381,256],[256,252],[252,381],[269,391],[391,393],[393,269],[200,199],[199,428],[428,200],[266,330],[330,329],[329,266],[287,273],[273,422],[422,287],[250,462],[462,328],[328,250],[258,286],[286,384],[384,258],[265,353],[353,342],[342,265],[387,259],[259,257],[257,387],[424,431],[431,430],[430,424],[342,353],[353,276],[276,342],[273,335],[335,424],[424,273],[292,325],[325,307],[307,292],[366,447],[447,345],[345,366],[271,303],[303,302],[302,271],[423,266],[266,371],[371,423],[294,455],[455,460],[460,294],[279,278],[278,294],[294,279],[271,272],[272,304],[304,271],[432,434],[434,427],[427,432],[272,407],[407,408],[408,272],[394,430],[430,431],[431,394],[395,369],[369,400],[400,395],[334,333],[333,299],[299,334],[351,417],[417,168],[168,351],[352,280],[280,411],[411,352],[325,319],[319,320],[320,325],[295,296],[296,336],[336,295],[319,403],[403,404],[404,319],[330,348],[348,349],[349,330],[293,298],[298,333],[333,293],[323,454],[454,447],[447,323],[15,16],[16,315],[315,15],[358,429],[429,279],[279,358],[14,15],[15,316],[316,14],[285,336],[336,9],[9,285],[329,349],[349,350],[350,329],[374,380],[380,252],[252,374],[318,402],[402,403],[403,318],[6,197],[197,419],[419,6],[318,319],[319,325],[325,318],[367,364],[364,365],[365,367],[435,367],[367,397],[397,435],[344,438],[438,439],[439,344],[272,271],[271,311],[311,272],[195,5],[5,281],[281,195],[273,287],[287,291],[291,273],[396,428],[428,199],[199,396],[311,271],[271,268],[268,311],[283,444],[444,445],[445,283],[373,254],[254,339],[339,373],[282,334],[334,296],[296,282],[449,347],[347,346],[346,449],[264,447],[447,454],[454,264],[336,296],[296,299],[299,336],[338,10],[10,151],[151,338],[278,439],[439,455],[455,278],[292,407],[407,415],[415,292],[358,371],[371,355],[355,358],[340,345],[345,372],[372,340],[346,347],[347,280],[280,346],[442,443],[443,282],[282,442],[19,94],[94,370],[370,19],[441,442],[442,295],[295,441],[248,419],[419,197],[197,248],[263,255],[255,359],[359,263],[440,275],[275,274],[274,440],[300,383],[383,368],[368,300],[351,412],[412,465],[465,351],[263,467],[467,466],[466,263],[301,368],[368,389],[389,301],[395,378],[378,379],[379,395],[412,351],[351,419],[419,412],[436,426],[426,322],[322,436],[2,164],[164,393],[393,2],[370,462],[462,461],[461,370],[164,0],[0,267],[267,164],[302,11],[11,12],[12,302],[268,12],[12,13],[13,268],[293,300],[300,301],[301,293],[446,261],[261,340],[340,446],[330,266],[266,425],[425,330],[426,423],[423,391],[391,426],[429,355],[355,437],[437,429],[391,327],[327,326],[326,391],[440,457],[457,438],[438,440],[341,382],[382,362],[362,341],[459,457],[457,461],[461,459],[434,430],[430,394],[394,434],[414,463],[463,362],[362,414],[396,369],[369,262],[262,396],[354,461],[461,457],[457,354],[316,403],[403,402],[402,316],[315,404],[404,403],[403,315],[314,405],[405,404],[404,314],[313,406],[406,405],[405,313],[421,418],[418,406],[406,421],[366,401],[401,361],[361,366],[306,408],[408,407],[407,306],[291,409],[409,408],[408,291],[287,410],[410,409],[409,287],[432,436],[436,410],[410,432],[434,416],[416,411],[411,434],[264,368],[368,383],[383,264],[309,438],[438,457],[457,309],[352,376],[376,401],[401,352],[274,275],[275,4],[4,274],[421,428],[428,262],[262,421],[294,327],[327,358],[358,294],[433,416],[416,367],[367,433],[289,455],[455,439],[439,289],[462,370],[370,326],[326,462],[2,326],[326,370],[370,2],[305,460],[460,455],[455,305],[254,449],[449,448],[448,254],[255,261],[261,446],[446,255],[253,450],[450,449],[449,253],[252,451],[451,450],[450,252],[256,452],[452,451],[451,256],[341,453],[453,452],[452,341],[413,464],[464,463],[463,413],[441,413],[413,414],[414,441],[258,442],[442,441],[441,258],[257,443],[443,442],[442,257],[259,444],[444,443],[443,259],[260,445],[445,444],[444,260],[467,342],[342,445],[445,467],[459,458],[458,250],[250,459],[289,392],[392,290],[290,289],[290,328],[328,460],[460,290],[376,433],[433,435],[435,376],[250,290],[290,392],[392,250],[411,416],[416,433],[433,411],[341,463],[463,464],[464,341],[453,464],[464,465],[465,453],[357,465],[465,412],[412,357],[343,412],[412,399],[399,343],[360,363],[363,440],[440,360],[437,399],[399,456],[456,437],[420,456],[456,363],[363,420],[401,435],[435,288],[288,401],[372,383],[383,353],[353,372],[339,255],[255,249],[249,339],[448,261],[261,255],[255,448],[133,243],[243,190],[190,133],[133,155],[155,112],[112,133],[33,246],[246,247],[247,33],[33,130],[130,25],[25,33],[398,384],[384,286],[286,398],[362,398],[398,414],[414,362],[362,463],[463,341],[341,362],[263,359],[359,467],[467,263],[263,249],[249,255],[255,263],[466,467],[467,260],[260,466],[75,60],[60,166],[166,75],[238,239],[239,79],[79,238],[162,127],[127,139],[139,162],[72,11],[11,37],[37,72],[121,232],[232,120],[120,121],[73,72],[72,39],[39,73],[114,128],[128,47],[47,114],[233,232],[232,128],[128,233],[103,104],[104,67],[67,103],[152,175],[175,148],[148,152],[119,118],[118,101],[101,119],[74,73],[73,40],[40,74],[107,9],[9,108],[108,107],[49,48],[48,131],[131,49],[32,194],[194,211],[211,32],[184,74],[74,185],[185,184],[191,80],[80,183],[183,191],[185,40],[40,186],[186,185],[119,230],[230,118],[118,119],[210,202],[202,214],[214,210],[84,83],[83,17],[17,84],[77,76],[76,146],[146,77],[161,160],[160,30],[30,161],[190,56],[56,173],[173,190],[182,106],[106,194],[194,182],[138,135],[135,192],[192,138],[129,203],[203,98],[98,129],[54,21],[21,68],[68,54],[5,51],[51,4],[4,5],[145,144],[144,23],[23,145],[90,77],[77,91],[91,90],[207,205],[205,187],[187,207],[83,201],[201,18],[18,83],[181,91],[91,182],[182,181],[180,90],[90,181],[181,180],[16,85],[85,17],[17,16],[205,206],[206,36],[36,205],[176,148],[148,140],[140,176],[165,92],[92,39],[39,165],[245,193],[193,244],[244,245],[27,159],[159,28],[28,27],[30,247],[247,161],[161,30],[174,236],[236,196],[196,174],[103,54],[54,104],[104,103],[55,193],[193,8],[8,55],[111,117],[117,31],[31,111],[221,189],[189,55],[55,221],[240,98],[98,99],[99,240],[142,126],[126,100],[100,142],[219,166],[166,218],[218,219],[112,155],[155,26],[26,112],[198,209],[209,131],[131,198],[169,135],[135,150],[150,169],[114,47],[47,217],[217,114],[224,223],[223,53],[53,224],[220,45],[45,134],[134,220],[32,211],[211,140],[140,32],[109,67],[67,108],[108,109],[146,43],[43,91],[91,146],[231,230],[230,120],[120,231],[113,226],[226,247],[247,113],[105,63],[63,52],[52,105],[241,238],[238,242],[242,241],[124,46],[46,156],[156,124],[95,78],[78,96],[96,95],[70,46],[46,63],[63,70],[116,143],[143,227],[227,116],[116,123],[123,111],[111,116],[1,44],[44,19],[19,1],[3,236],[236,51],[51,3],[207,216],[216,205],[205,207],[26,154],[154,22],[22,26],[165,39],[39,167],[167,165],[199,200],[200,208],[208,199],[101,36],[36,100],[100,101],[43,57],[57,202],[202,43],[242,20],[20,99],[99,242],[56,28],[28,157],[157,56],[124,35],[35,113],[113,124],[29,160],[160,27],[27,29],[211,204],[204,210],[210,211],[124,113],[113,46],[46,124],[106,43],[43,204],[204,106],[96,62],[62,77],[77,96],[227,137],[137,116],[116,227],[73,41],[41,72],[72,73],[36,203],[203,142],[142,36],[235,64],[64,240],[240,235],[48,49],[49,64],[64,48],[42,41],[41,74],[74,42],[214,212],[212,207],[207,214],[183,42],[42,184],[184,183],[210,169],[169,211],[211,210],[140,170],[170,176],[176,140],[104,105],[105,69],[69,104],[193,122],[122,168],[168,193],[50,123],[123,187],[187,50],[89,96],[96,90],[90,89],[66,65],[65,107],[107,66],[179,89],[89,180],[180,179],[119,101],[101,120],[120,119],[68,63],[63,104],[104,68],[234,93],[93,227],[227,234],[16,15],[15,85],[85,16],[209,129],[129,49],[49,209],[15,14],[14,86],[86,15],[107,55],[55,9],[9,107],[120,100],[100,121],[121,120],[153,145],[145,22],[22,153],[178,88],[88,179],[179,178],[197,6],[6,196],[196,197],[89,88],[88,96],[96,89],[135,138],[138,136],[136,135],[138,215],[215,172],[172,138],[218,115],[115,219],[219,218],[41,42],[42,81],[81,41],[5,195],[195,51],[51,5],[57,43],[43,61],[61,57],[208,171],[171,199],[199,208],[41,81],[81,38],[38,41],[224,53],[53,225],[225,224],[24,144],[144,110],[110,24],[105,52],[52,66],[66,105],[118,229],[229,117],[117,118],[227,34],[34,234],[234,227],[66,107],[107,69],[69,66],[10,109],[109,151],[151,10],[219,48],[48,235],[235,219],[183,62],[62,191],[191,183],[142,129],[129,126],[126,142],[116,111],[111,143],[143,116],[118,117],[117,50],[50,118],[223,222],[222,52],[52,223],[94,19],[19,141],[141,94],[222,221],[221,65],[65,222],[196,3],[3,197],[197,196],[45,220],[220,44],[44,45],[156,70],[70,139],[139,156],[188,122],[122,245],[245,188],[139,71],[71,162],[162,139],[149,170],[170,150],[150,149],[122,188],[188,196],[196,122],[206,216],[216,92],[92,206],[164,2],[2,167],[167,164],[242,141],[141,241],[241,242],[0,164],[164,37],[37,0],[11,72],[72,12],[12,11],[12,38],[38,13],[13,12],[70,63],[63,71],[71,70],[31,226],[226,111],[111,31],[36,101],[101,205],[205,36],[203,206],[206,165],[165,203],[126,209],[209,217],[217,126],[98,165],[165,97],[97,98],[237,220],[220,218],[218,237],[237,239],[239,241],[241,237],[210,214],[214,169],[169,210],[140,171],[171,32],[32,140],[241,125],[125,237],[237,241],[179,86],[86,178],[178,179],[180,85],[85,179],[179,180],[181,84],[84,180],[180,181],[182,83],[83,181],[181,182],[194,201],[201,182],[182,194],[177,137],[137,132],[132,177],[184,76],[76,183],[183,184],[185,61],[61,184],[184,185],[186,57],[57,185],[185,186],[216,212],[212,186],[186,216],[192,214],[214,187],[187,192],[139,34],[34,156],[156,139],[218,79],[79,237],[237,218],[147,123],[123,177],[177,147],[45,44],[44,4],[4,45],[208,201],[201,32],[32,208],[98,64],[64,129],[129,98],[192,213],[213,138],[138,192],[235,59],[59,219],[219,235],[141,242],[242,97],[97,141],[97,2],[2,141],[141,97],[240,75],[75,235],[235,240],[229,24],[24,228],[228,229],[31,25],[25,226],[226,31],[230,23],[23,229],[229,230],[231,22],[22,230],[230,231],[232,26],[26,231],[231,232],[233,112],[112,232],[232,233],[244,189],[189,243],[243,244],[189,221],[221,190],[190,189],[222,28],[28,221],[221,222],[223,27],[27,222],[222,223],[224,29],[29,223],[223,224],[225,30],[30,224],[224,225],[113,247],[247,225],[225,113],[99,60],[60,240],[240,99],[213,147],[147,215],[215,213],[60,20],[20,166],[166,60],[192,187],[187,213],[213,192],[243,112],[112,244],[244,243],[244,233],[233,245],[245,244],[245,128],[128,188],[188,245],[188,114],[114,174],[174,188],[134,131],[131,220],[220,134],[174,217],[217,236],[236,174],[236,198],[198,134],[134,236],[215,177],[177,58],[58,215],[156,143],[143,124],[124,156],[25,110],[110,7],[7,25],[31,228],[228,25],[25,31],[264,356],[356,368],[368,264],[0,11],[11,267],[267,0],[451,452],[452,349],[349,451],[267,302],[302,269],[269,267],[350,357],[357,277],[277,350],[350,452],[452,357],[357,350],[299,333],[333,297],[297,299],[396,175],[175,377],[377,396],[280,347],[347,330],[330,280],[269,303],[303,270],[270,269],[151,9],[9,337],[337,151],[344,278],[278,360],[360,344],[424,418],[418,431],[431,424],[270,304],[304,409],[409,270],[272,310],[310,407],[407,272],[322,270],[270,410],[410,322],[449,450],[450,347],[347,449],[432,422],[422,434],[434,432],[18,313],[313,17],[17,18],[291,306],[306,375],[375,291],[259,387],[387,260],[260,259],[424,335],[335,418],[418,424],[434,364],[364,416],[416,434],[391,423],[423,327],[327,391],[301,251],[251,298],[298,301],[275,281],[281,4],[4,275],[254,373],[373,253],[253,254],[375,307],[307,321],[321,375],[280,425],[425,411],[411,280],[200,421],[421,18],[18,200],[335,321],[321,406],[406,335],[321,320],[320,405],[405,321],[314,315],[315,17],[17,314],[423,426],[426,266],[266,423],[396,377],[377,369],[369,396],[270,322],[322,269],[269,270],[413,417],[417,464],[464,413],[385,386],[386,258],[258,385],[248,456],[456,419],[419,248],[298,284],[284,333],[333,298],[168,417],[417,8],[8,168],[448,346],[346,261],[261,448],[417,413],[413,285],[285,417],[326,327],[327,328],[328,326],[277,355],[355,329],[329,277],[309,392],[392,438],[438,309],[381,382],[382,256],[256,381],[279,429],[429,360],[360,279],[365,364],[364,379],[379,365],[355,277],[277,437],[437,355],[282,443],[443,283],[283,282],[281,275],[275,363],[363,281],[395,431],[431,369],[369,395],[299,297],[297,337],[337,299],[335,273],[273,321],[321,335],[348,450],[450,349],[349,348],[359,446],[446,467],[467,359],[283,293],[293,282],[282,283],[250,458],[458,462],[462,250],[300,276],[276,383],[383,300],[292,308],[308,325],[325,292],[283,276],[276,293],[293,283],[264,372],[372,447],[447,264],[346,352],[352,340],[340,346],[354,274],[274,19],[19,354],[363,456],[456,281],[281,363],[426,436],[436,425],[425,426],[380,381],[381,252],[252,380],[267,269],[269,393],[393,267],[421,200],[200,428],[428,421],[371,266],[266,329],[329,371],[432,287],[287,422],[422,432],[290,250],[250,328],[328,290],[385,258],[258,384],[384,385],[446,265],[265,342],[342,446],[386,387],[387,257],[257,386],[422,424],[424,430],[430,422],[445,342],[342,276],[276,445],[422,273],[273,424],[424,422],[306,292],[292,307],[307,306],[352,366],[366,345],[345,352],[268,271],[271,302],[302,268],[358,423],[423,371],[371,358],[327,294],[294,460],[460,327],[331,279],[279,294],[294,331],[303,271],[271,304],[304,303],[436,432],[432,427],[427,436],[304,272],[272,408],[408,304],[395,394],[394,431],[431,395],[378,395],[395,400],[400,378],[296,334],[334,299],[299,296],[6,351],[351,168],[168,6],[376,352],[352,411],[411,376],[307,325],[325,320],[320,307],[285,295],[295,336],[336,285],[320,319],[319,404],[404,320],[329,330],[330,349],[349,329],[334,293],[293,333],[333,334],[366,323],[323,447],[447,366],[316,15],[15,315],[315,316],[331,358],[358,279],[279,331],[317,14],[14,316],[316,317],[8,285],[285,9],[9,8],[277,329],[329,350],[350,277],[253,374],[374,252],[252,253],[319,318],[318,403],[403,319],[351,6],[6,419],[419,351],[324,318],[318,325],[325,324],[397,367],[367,365],[365,397],[288,435],[435,397],[397,288],[278,344],[344,439],[439,278],[310,272],[272,311],[311,310],[248,195],[195,281],[281,248],[375,273],[273,291],[291,375],[175,396],[396,199],[199,175],[312,311],[311,268],[268,312],[276,283],[283,445],[445,276],[390,373],[373,339],[339,390],[295,282],[282,296],[296,295],[448,449],[449,346],[346,448],[356,264],[264,454],[454,356],[337,336],[336,299],[299,337],[337,338],[338,151],[151,337],[294,278],[278,455],[455,294],[308,292],[292,415],[415,308],[429,358],[358,355],[355,429],[265,340],[340,372],[372,265],[352,346],[346,280],[280,352],[295,442],[442,282],[282,295],[354,19],[19,370],[370,354],[285,441],[441,295],[295,285],[195,248],[248,197],[197,195],[457,440],[440,274],[274,457],[301,300],[300,368],[368,301],[417,351],[351,465],[465,417],[251,301],[301,389],[389,251],[394,395],[395,379],[379,394],[399,412],[412,419],[419,399],[410,436],[436,322],[322,410],[326,2],[2,393],[393,326],[354,370],[370,461],[461,354],[393,164],[164,267],[267,393],[268,302],[302,12],[12,268],[312,268],[268,13],[13,312],[298,293],[293,301],[301,298],[265,446],[446,340],[340,265],[280,330],[330,425],[425,280],[322,426],[426,391],[391,322],[420,429],[429,437],[437,420],[393,391],[391,326],[326,393],[344,440],[440,438],[438,344],[458,459],[459,461],[461,458],[364,434],[434,394],[394,364],[428,396],[396,262],[262,428],[274,354],[354,457],[457,274],[317,316],[316,402],[402,317],[316,315],[315,403],[403,316],[315,314],[314,404],[404,315],[314,313],[313,405],[405,314],[313,421],[421,406],[406,313],[323,366],[366,361],[361,323],[292,306],[306,407],[407,292],[306,291],[291,408],[408,306],[291,287],[287,409],[409,291],[287,432],[432,410],[410,287],[427,434],[434,411],[411,427],[372,264],[264,383],[383,372],[459,309],[309,457],[457,459],[366,352],[352,401],[401,366],[1,274],[274,4],[4,1],[418,421],[421,262],[262,418],[331,294],[294,358],[358,331],[435,433],[433,367],[367,435],[392,289],[289,439],[439,392],[328,462],[462,326],[326,328],[94,2],[2,370],[370,94],[289,305],[305,455],[455,289],[339,254],[254,448],[448,339],[359,255],[255,446],[446,359],[254,253],[253,449],[449,254],[253,252],[252,450],[450,253],[252,256],[256,451],[451,252],[256,341],[341,452],[452,256],[414,413],[413,463],[463,414],[286,441],[441,414],[414,286],[286,258],[258,441],[441,286],[258,257],[257,442],[442,258],[257,259],[259,443],[443,257],[259,260],[260,444],[444,259],[260,467],[467,445],[445,260],[309,459],[459,250],[250,309],[305,289],[289,290],[290,305],[305,290],[290,460],[460,305],[401,376],[376,435],[435,401],[309,250],[250,392],[392,309],[376,411],[411,433],[433,376],[453,341],[341,464],[464,453],[357,453],[453,465],[465,357],[343,357],[357,412],[412,343],[437,343],[343,399],[399,437],[344,360],[360,440],[440,344],[420,437],[437,456],[456,420],[360,420],[420,363],[363,360],[361,401],[401,288],[288,361],[265,372],[372,353],[353,265],[390,339],[339,249],[249,390],[339,448],[448,255],[255,339]);function ZGe(s){s.j={faceLandmarks:[],faceBlendshapes:[],facialTransformationMatrixes:[]}}var Iu=class extends I0{constructor(s,t){super(new $1(s,t),"image_in","norm_rect",!1),this.j={faceLandmarks:[],faceBlendshapes:[],facialTransformationMatrixes:[]},this.outputFacialTransformationMatrixes=this.outputFaceBlendshapes=!1,Fi(s=this.h=new q0t,0,1,t=new Zu),this.A=new U0t,Fi(this.h,0,3,this.A),this.u=new aye,Fi(this.h,0,2,this.u),pj(this.u,4,1),Ni(this.u,2,.5),Ni(this.A,2,.5),Ni(this.h,4,.5)}get baseOptions(){return Ul(this.h,Zu,1)}set baseOptions(s){Fi(this.h,0,1,s)}o(s){return"numFaces"in s&&pj(this.u,4,s.numFaces??1),"minFaceDetectionConfidence"in s&&Ni(this.u,2,s.minFaceDetectionConfidence??.5),"minTrackingConfidence"in s&&Ni(this.h,4,s.minTrackingConfidence??.5),"minFacePresenceConfidence"in s&&Ni(this.A,2,s.minFacePresenceConfidence??.5),"outputFaceBlendshapes"in s&&(this.outputFaceBlendshapes=!!s.outputFaceBlendshapes),"outputFacialTransformationMatrixes"in s&&(this.outputFacialTransformationMatrixes=!!s.outputFacialTransformationMatrixes),this.l(s)}F(s,t){return ZGe(this),U1(this,s,t),this.j}G(s,t,r){return ZGe(this),sw(this,s,r,t),this.j}m(){var s=new F0;vu(s,"image_in"),vu(s,"norm_rect"),Jl(s,"face_landmarks");const t=new O0;ew(t,eFs,this.h);const r=new xx;M0(r,2,"mediapipe.tasks.vision.face_landmarker.FaceLandmarkerGraph"),Zd(r,"IMAGE:image_in"),Zd(r,"NORM_RECT:norm_rect"),_l(r,"NORM_LANDMARKS:face_landmarks"),r.o(t),cv(s,r),this.g.attachProtoVectorListener("face_landmarks",(n,a)=>{for(const i of n)n=qz(i),this.j.faceLandmarks.push(iye(n));ri(this,a)}),this.g.attachEmptyPacketListener("face_landmarks",n=>{ri(this,n)}),this.outputFaceBlendshapes&&(Jl(s,"blendshapes"),_l(r,"BLENDSHAPES:blendshapes"),this.g.attachProtoVectorListener("blendshapes",(n,a)=>{if(this.outputFaceBlendshapes)for(const i of n)n=nye(i),this.j.faceBlendshapes.push(JMe(n.g()??[]));ri(this,a)}),this.g.attachEmptyPacketListener("blendshapes",n=>{ri(this,n)})),this.outputFacialTransformationMatrixes&&(Jl(s,"face_geometry"),_l(r,"FACE_GEOMETRY:face_geometry"),this.g.attachProtoVectorListener("face_geometry",(n,a)=>{if(this.outputFacialTransformationMatrixes)for(const i of n)(n=Ul(n=JOs(i),VOs,2))&&this.j.facialTransformationMatrixes.push({rows:zy(n,1)??0??0,columns:zy(n,2)??0??0,data:ZT(n,3,a_,YT()).slice()??[]});ri(this,a)}),this.g.attachEmptyPacketListener("face_geometry",n=>{ri(this,n)})),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};Iu.prototype.detectForVideo=Iu.prototype.G,Iu.prototype.detect=Iu.prototype.F,Iu.prototype.setOptions=Iu.prototype.o,Iu.createFromModelPath=function(s,t){return Ol(Iu,s,{baseOptions:{modelAssetPath:t}})},Iu.createFromModelBuffer=function(s,t){return Ol(Iu,s,{baseOptions:{modelAssetBuffer:t}})},Iu.createFromOptions=function(s,t){return Ol(Iu,s,t)},Iu.FACE_LANDMARKS_LIPS=s6e,Iu.FACE_LANDMARKS_LEFT_EYE=r6e,Iu.FACE_LANDMARKS_LEFT_EYEBROW=n6e,Iu.FACE_LANDMARKS_LEFT_IRIS=yyt,Iu.FACE_LANDMARKS_RIGHT_EYE=a6e,Iu.FACE_LANDMARKS_RIGHT_EYEBROW=i6e,Iu.FACE_LANDMARKS_RIGHT_IRIS=vyt,Iu.FACE_LANDMARKS_FACE_OVAL=o6e,Iu.FACE_LANDMARKS_CONTOURS=byt,Iu.FACE_LANDMARKS_TESSELATION=_yt;var l6e=z1([0,1],[1,2],[2,3],[3,4],[0,5],[5,6],[6,7],[7,8],[5,9],[9,10],[10,11],[11,12],[9,13],[13,14],[14,15],[15,16],[13,17],[0,17],[17,18],[18,19],[19,20]);function XGe(s){s.gestures=[],s.landmarks=[],s.worldLandmarks=[],s.handedness=[]}function QGe(s){return s.gestures.length===0?{gestures:[],landmarks:[],worldLandmarks:[],handedness:[],handednesses:[]}:{gestures:s.gestures,landmarks:s.landmarks,worldLandmarks:s.worldLandmarks,handedness:s.handedness,handednesses:s.handedness}}function JGe(s,t=!0){const r=[];for(const a of s){var n=nye(a);s=[];for(const i of n.g())n=t&&zy(i,1)!=null?zy(i,1)??0:-1,s.push({score:lh(i,2)??0,index:n,categoryName:Gf(fu(i,3))??""??"",displayName:Gf(fu(i,4))??""??""});r.push(s)}return r}var Bx=class extends I0{constructor(s,t){super(new $1(s,t),"image_in","norm_rect",!1),this.gestures=[],this.landmarks=[],this.worldLandmarks=[],this.handedness=[],Fi(s=this.j=new G0t,0,1,t=new Zu),this.u=new YMe,Fi(this.j,0,2,this.u),this.D=new KMe,Fi(this.u,0,3,this.D),this.A=new H0t,Fi(this.u,0,2,this.A),this.h=new tFs,Fi(this.j,0,3,this.h),Ni(this.A,2,.5),Ni(this.u,4,.5),Ni(this.D,2,.5)}get baseOptions(){return Ul(this.j,Zu,1)}set baseOptions(s){Fi(this.j,0,1,s)}o(s){var a,i,l,o;if(pj(this.A,3,s.numHands??1),"minHandDetectionConfidence"in s&&Ni(this.A,2,s.minHandDetectionConfidence??.5),"minTrackingConfidence"in s&&Ni(this.u,4,s.minTrackingConfidence??.5),"minHandPresenceConfidence"in s&&Ni(this.D,2,s.minHandPresenceConfidence??.5),s.cannedGesturesClassifierOptions){var t=new A6,r=t,n=B4e(s.cannedGesturesClassifierOptions,(a=Ul(this.h,A6,3))==null?void 0:a.l());Fi(r,0,2,n),Fi(this.h,0,3,t)}else s.cannedGesturesClassifierOptions===void 0&&((i=Ul(this.h,A6,3))==null||i.g());return s.customGesturesClassifierOptions?(Fi(r=t=new A6,0,2,n=B4e(s.customGesturesClassifierOptions,(l=Ul(this.h,A6,4))==null?void 0:l.l())),Fi(this.h,0,4,t)):s.customGesturesClassifierOptions===void 0&&((o=Ul(this.h,A6,4))==null||o.g()),this.l(s)}Ha(s,t){return XGe(this),U1(this,s,t),QGe(this)}Ia(s,t,r){return XGe(this),sw(this,s,r,t),QGe(this)}m(){var s=new F0;vu(s,"image_in"),vu(s,"norm_rect"),Jl(s,"hand_gestures"),Jl(s,"hand_landmarks"),Jl(s,"world_hand_landmarks"),Jl(s,"handedness");const t=new O0;ew(t,sFs,this.j);const r=new xx;M0(r,2,"mediapipe.tasks.vision.gesture_recognizer.GestureRecognizerGraph"),Zd(r,"IMAGE:image_in"),Zd(r,"NORM_RECT:norm_rect"),_l(r,"HAND_GESTURES:hand_gestures"),_l(r,"LANDMARKS:hand_landmarks"),_l(r,"WORLD_LANDMARKS:world_hand_landmarks"),_l(r,"HANDEDNESS:handedness"),r.o(t),cv(s,r),this.g.attachProtoVectorListener("hand_landmarks",(n,a)=>{for(const i of n){n=qz(i);const l=[];for(const o of fj(n,O0t,1))l.push({x:lh(o,1)??0,y:lh(o,2)??0,z:lh(o,3)??0,visibility:lh(o,4)??0});this.landmarks.push(l)}ri(this,a)}),this.g.attachEmptyPacketListener("hand_landmarks",n=>{ri(this,n)}),this.g.attachProtoVectorListener("world_hand_landmarks",(n,a)=>{for(const i of n){n=bP(i);const l=[];for(const o of fj(n,R0t,1))l.push({x:lh(o,1)??0,y:lh(o,2)??0,z:lh(o,3)??0,visibility:lh(o,4)??0});this.worldLandmarks.push(l)}ri(this,a)}),this.g.attachEmptyPacketListener("world_hand_landmarks",n=>{ri(this,n)}),this.g.attachProtoVectorListener("hand_gestures",(n,a)=>{this.gestures.push(...JGe(n,!1)),ri(this,a)}),this.g.attachEmptyPacketListener("hand_gestures",n=>{ri(this,n)}),this.g.attachProtoVectorListener("handedness",(n,a)=>{this.handedness.push(...JGe(n)),ri(this,a)}),this.g.attachEmptyPacketListener("handedness",n=>{ri(this,n)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};function eWe(s){return{landmarks:s.landmarks,worldLandmarks:s.worldLandmarks,handednesses:s.handedness,handedness:s.handedness}}Bx.prototype.recognizeForVideo=Bx.prototype.Ia,Bx.prototype.recognize=Bx.prototype.Ha,Bx.prototype.setOptions=Bx.prototype.o,Bx.createFromModelPath=function(s,t){return Ol(Bx,s,{baseOptions:{modelAssetPath:t}})},Bx.createFromModelBuffer=function(s,t){return Ol(Bx,s,{baseOptions:{modelAssetBuffer:t}})},Bx.createFromOptions=function(s,t){return Ol(Bx,s,t)},Bx.HAND_CONNECTIONS=l6e;var zx=class extends I0{constructor(s,t){super(new $1(s,t),"image_in","norm_rect",!1),this.landmarks=[],this.worldLandmarks=[],this.handedness=[],Fi(s=this.h=new YMe,0,1,t=new Zu),this.u=new KMe,Fi(this.h,0,3,this.u),this.j=new H0t,Fi(this.h,0,2,this.j),pj(this.j,3,1),Ni(this.j,2,.5),Ni(this.u,2,.5),Ni(this.h,4,.5)}get baseOptions(){return Ul(this.h,Zu,1)}set baseOptions(s){Fi(this.h,0,1,s)}o(s){return"numHands"in s&&pj(this.j,3,s.numHands??1),"minHandDetectionConfidence"in s&&Ni(this.j,2,s.minHandDetectionConfidence??.5),"minTrackingConfidence"in s&&Ni(this.h,4,s.minTrackingConfidence??.5),"minHandPresenceConfidence"in s&&Ni(this.u,2,s.minHandPresenceConfidence??.5),this.l(s)}F(s,t){return this.landmarks=[],this.worldLandmarks=[],this.handedness=[],U1(this,s,t),eWe(this)}G(s,t,r){return this.landmarks=[],this.worldLandmarks=[],this.handedness=[],sw(this,s,r,t),eWe(this)}m(){var s=new F0;vu(s,"image_in"),vu(s,"norm_rect"),Jl(s,"hand_landmarks"),Jl(s,"world_hand_landmarks"),Jl(s,"handedness");const t=new O0;ew(t,rFs,this.h);const r=new xx;M0(r,2,"mediapipe.tasks.vision.hand_landmarker.HandLandmarkerGraph"),Zd(r,"IMAGE:image_in"),Zd(r,"NORM_RECT:norm_rect"),_l(r,"LANDMARKS:hand_landmarks"),_l(r,"WORLD_LANDMARKS:world_hand_landmarks"),_l(r,"HANDEDNESS:handedness"),r.o(t),cv(s,r),this.g.attachProtoVectorListener("hand_landmarks",(n,a)=>{for(const i of n)n=qz(i),this.landmarks.push(iye(n));ri(this,a)}),this.g.attachEmptyPacketListener("hand_landmarks",n=>{ri(this,n)}),this.g.attachProtoVectorListener("world_hand_landmarks",(n,a)=>{for(const i of n)n=bP(i),this.worldLandmarks.push(M7(n));ri(this,a)}),this.g.attachEmptyPacketListener("world_hand_landmarks",n=>{ri(this,n)}),this.g.attachProtoVectorListener("handedness",(n,a)=>{var i=this.handedness,l=i.push;const o=[];for(const c of n){n=nye(c);const d=[];for(const h of n.g())d.push({score:lh(h,2)??0,index:zy(h,1)??0??-1,categoryName:Gf(fu(h,3))??""??"",displayName:Gf(fu(h,4))??""??""});o.push(d)}l.call(i,...o),ri(this,a)}),this.g.attachEmptyPacketListener("handedness",n=>{ri(this,n)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};zx.prototype.detectForVideo=zx.prototype.G,zx.prototype.detect=zx.prototype.F,zx.prototype.setOptions=zx.prototype.o,zx.createFromModelPath=function(s,t){return Ol(zx,s,{baseOptions:{modelAssetPath:t}})},zx.createFromModelBuffer=function(s,t){return Ol(zx,s,{baseOptions:{modelAssetBuffer:t}})},zx.createFromOptions=function(s,t){return Ol(zx,s,t)},zx.HAND_CONNECTIONS=l6e;var wyt=z1([0,1],[1,2],[2,3],[3,7],[0,4],[4,5],[5,6],[6,8],[9,10],[11,12],[11,13],[13,15],[15,17],[15,19],[15,21],[17,19],[12,14],[14,16],[16,18],[16,20],[16,22],[18,20],[11,23],[12,24],[23,24],[23,25],[24,26],[25,27],[26,28],[27,29],[28,30],[29,31],[30,32],[27,31],[28,32]);function tWe(s){s.h={faceLandmarks:[],faceBlendshapes:[],poseLandmarks:[],poseWorldLandmarks:[],poseSegmentationMasks:[],leftHandLandmarks:[],leftHandWorldLandmarks:[],rightHandLandmarks:[],rightHandWorldLandmarks:[]}}function sWe(s){try{if(!s.D)return s.h;s.D(s.h)}finally{lye(s)}}function tV(s,t){s=qz(s),t.push(iye(s))}var zd=class extends I0{constructor(s,t){super(new $1(s,t),"input_frames_image",null,!1),this.h={faceLandmarks:[],faceBlendshapes:[],poseLandmarks:[],poseWorldLandmarks:[],poseSegmentationMasks:[],leftHandLandmarks:[],leftHandWorldLandmarks:[],rightHandLandmarks:[],rightHandWorldLandmarks:[]},this.outputPoseSegmentationMasks=this.outputFaceBlendshapes=!1,Fi(s=this.j=new X0t,0,1,t=new Zu),this.I=new KMe,Fi(this.j,0,2,this.I),this.W=new nFs,Fi(this.j,0,3,this.W),this.u=new aye,Fi(this.j,0,4,this.u),this.O=new U0t,Fi(this.j,0,5,this.O),this.A=new Y0t,Fi(this.j,0,6,this.A),this.M=new Z0t,Fi(this.j,0,7,this.M),Ni(this.u,2,.5),Ni(this.u,3,.3),Ni(this.O,2,.5),Ni(this.A,2,.5),Ni(this.A,3,.3),Ni(this.M,2,.5),Ni(this.I,2,.5)}get baseOptions(){return Ul(this.j,Zu,1)}set baseOptions(s){Fi(this.j,0,1,s)}o(s){return"minFaceDetectionConfidence"in s&&Ni(this.u,2,s.minFaceDetectionConfidence??.5),"minFaceSuppressionThreshold"in s&&Ni(this.u,3,s.minFaceSuppressionThreshold??.3),"minFacePresenceConfidence"in s&&Ni(this.O,2,s.minFacePresenceConfidence??.5),"outputFaceBlendshapes"in s&&(this.outputFaceBlendshapes=!!s.outputFaceBlendshapes),"minPoseDetectionConfidence"in s&&Ni(this.A,2,s.minPoseDetectionConfidence??.5),"minPoseSuppressionThreshold"in s&&Ni(this.A,3,s.minPoseSuppressionThreshold??.3),"minPosePresenceConfidence"in s&&Ni(this.M,2,s.minPosePresenceConfidence??.5),"outputPoseSegmentationMasks"in s&&(this.outputPoseSegmentationMasks=!!s.outputPoseSegmentationMasks),"minHandLandmarksConfidence"in s&&Ni(this.I,2,s.minHandLandmarksConfidence??.5),this.l(s)}F(s,t,r){const n=typeof t!="function"?t:{};return this.D=typeof t=="function"?t:r,tWe(this),U1(this,s,n),sWe(this)}G(s,t,r,n){const a=typeof r!="function"?r:{};return this.D=typeof r=="function"?r:n,tWe(this),sw(this,s,a,t),sWe(this)}m(){var s=new F0;vu(s,"input_frames_image"),Jl(s,"pose_landmarks"),Jl(s,"pose_world_landmarks"),Jl(s,"face_landmarks"),Jl(s,"left_hand_landmarks"),Jl(s,"left_hand_world_landmarks"),Jl(s,"right_hand_landmarks"),Jl(s,"right_hand_world_landmarks");const t=new O0,r=new SGe;M0(r,1,"type.googleapis.com/mediapipe.tasks.vision.holistic_landmarker.proto.HolisticLandmarkerGraphOptions"),function(a,i){if(i!=null)if(Array.isArray(i))Sc(a,2,G0e(i,0,yB));else{if(!(typeof i=="string"||i instanceof T_||fMe(i)))throw Error("invalid value in Any.value field: "+i+" expected a ByteString, a base64 encoded string, a Uint8Array or a jspb array");YN(a,2,gMe(i,!1),PA())}}(r,this.j.g());const n=new xx;M0(n,2,"mediapipe.tasks.vision.holistic_landmarker.HolisticLandmarkerGraph"),AMe(n,8,SGe,r),Zd(n,"IMAGE:input_frames_image"),_l(n,"POSE_LANDMARKS:pose_landmarks"),_l(n,"POSE_WORLD_LANDMARKS:pose_world_landmarks"),_l(n,"FACE_LANDMARKS:face_landmarks"),_l(n,"LEFT_HAND_LANDMARKS:left_hand_landmarks"),_l(n,"LEFT_HAND_WORLD_LANDMARKS:left_hand_world_landmarks"),_l(n,"RIGHT_HAND_LANDMARKS:right_hand_landmarks"),_l(n,"RIGHT_HAND_WORLD_LANDMARKS:right_hand_world_landmarks"),n.o(t),cv(s,n),oye(this,s),this.g.attachProtoListener("pose_landmarks",(a,i)=>{tV(a,this.h.poseLandmarks),ri(this,i)}),this.g.attachEmptyPacketListener("pose_landmarks",a=>{ri(this,a)}),this.g.attachProtoListener("pose_world_landmarks",(a,i)=>{var l=this.h.poseWorldLandmarks;a=bP(a),l.push(M7(a)),ri(this,i)}),this.g.attachEmptyPacketListener("pose_world_landmarks",a=>{ri(this,a)}),this.outputPoseSegmentationMasks&&(_l(n,"POSE_SEGMENTATION_MASK:pose_segmentation_mask"),KL(this,"pose_segmentation_mask"),this.g.Z("pose_segmentation_mask",(a,i)=>{this.h.poseSegmentationMasks=[ZL(this,a,!0,!this.D)],ri(this,i)}),this.g.attachEmptyPacketListener("pose_segmentation_mask",a=>{this.h.poseSegmentationMasks=[],ri(this,a)})),this.g.attachProtoListener("face_landmarks",(a,i)=>{tV(a,this.h.faceLandmarks),ri(this,i)}),this.g.attachEmptyPacketListener("face_landmarks",a=>{ri(this,a)}),this.outputFaceBlendshapes&&(Jl(s,"extra_blendshapes"),_l(n,"FACE_BLENDSHAPES:extra_blendshapes"),this.g.attachProtoListener("extra_blendshapes",(a,i)=>{var l=this.h.faceBlendshapes;this.outputFaceBlendshapes&&(a=nye(a),l.push(JMe(a.g()??[]))),ri(this,i)}),this.g.attachEmptyPacketListener("extra_blendshapes",a=>{ri(this,a)})),this.g.attachProtoListener("left_hand_landmarks",(a,i)=>{tV(a,this.h.leftHandLandmarks),ri(this,i)}),this.g.attachEmptyPacketListener("left_hand_landmarks",a=>{ri(this,a)}),this.g.attachProtoListener("left_hand_world_landmarks",(a,i)=>{var l=this.h.leftHandWorldLandmarks;a=bP(a),l.push(M7(a)),ri(this,i)}),this.g.attachEmptyPacketListener("left_hand_world_landmarks",a=>{ri(this,a)}),this.g.attachProtoListener("right_hand_landmarks",(a,i)=>{tV(a,this.h.rightHandLandmarks),ri(this,i)}),this.g.attachEmptyPacketListener("right_hand_landmarks",a=>{ri(this,a)}),this.g.attachProtoListener("right_hand_world_landmarks",(a,i)=>{var l=this.h.rightHandWorldLandmarks;a=bP(a),l.push(M7(a)),ri(this,i)}),this.g.attachEmptyPacketListener("right_hand_world_landmarks",a=>{ri(this,a)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};zd.prototype.detectForVideo=zd.prototype.G,zd.prototype.detect=zd.prototype.F,zd.prototype.setOptions=zd.prototype.o,zd.createFromModelPath=function(s,t){return Ol(zd,s,{baseOptions:{modelAssetPath:t}})},zd.createFromModelBuffer=function(s,t){return Ol(zd,s,{baseOptions:{modelAssetBuffer:t}})},zd.createFromOptions=function(s,t){return Ol(zd,s,t)},zd.HAND_CONNECTIONS=l6e,zd.POSE_CONNECTIONS=wyt,zd.FACE_LANDMARKS_LIPS=s6e,zd.FACE_LANDMARKS_LEFT_EYE=r6e,zd.FACE_LANDMARKS_LEFT_EYEBROW=n6e,zd.FACE_LANDMARKS_LEFT_IRIS=yyt,zd.FACE_LANDMARKS_RIGHT_EYE=a6e,zd.FACE_LANDMARKS_RIGHT_EYEBROW=i6e,zd.FACE_LANDMARKS_RIGHT_IRIS=vyt,zd.FACE_LANDMARKS_FACE_OVAL=o6e,zd.FACE_LANDMARKS_CONTOURS=byt,zd.FACE_LANDMARKS_TESSELATION=_yt;var xy=class extends I0{constructor(s,t){super(new $1(s,t),"input_image","norm_rect",!0),this.j={classifications:[]},Fi(s=this.h=new Q0t,0,1,t=new Zu)}get baseOptions(){return Ul(this.h,Zu,1)}set baseOptions(s){Fi(this.h,0,1,s)}o(s){return Fi(this.h,0,2,B4e(s,Ul(this.h,GMe,2))),this.l(s)}sa(s,t){return this.j={classifications:[]},U1(this,s,t),this.j}ta(s,t,r){return this.j={classifications:[]},sw(this,s,r,t),this.j}m(){var s=new F0;vu(s,"input_image"),vu(s,"norm_rect"),Jl(s,"classifications");const t=new O0;ew(t,aFs,this.h);const r=new xx;M0(r,2,"mediapipe.tasks.vision.image_classifier.ImageClassifierGraph"),Zd(r,"IMAGE:input_image"),Zd(r,"NORM_RECT:norm_rect"),_l(r,"CLASSIFICATIONS:classifications"),r.o(t),cv(s,r),this.g.attachProtoListener("classifications",(n,a)=>{this.j=uFs(WOs(n)),ri(this,a)}),this.g.attachEmptyPacketListener("classifications",n=>{ri(this,n)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};xy.prototype.classifyForVideo=xy.prototype.ta,xy.prototype.classify=xy.prototype.sa,xy.prototype.setOptions=xy.prototype.o,xy.createFromModelPath=function(s,t){return Ol(xy,s,{baseOptions:{modelAssetPath:t}})},xy.createFromModelBuffer=function(s,t){return Ol(xy,s,{baseOptions:{modelAssetBuffer:t}})},xy.createFromOptions=function(s,t){return Ol(xy,s,t)};var $x=class extends I0{constructor(s,t){super(new $1(s,t),"image_in","norm_rect",!0),this.h=new J0t,this.embeddings={embeddings:[]},Fi(s=this.h,0,1,t=new Zu)}get baseOptions(){return Ul(this.h,Zu,1)}set baseOptions(s){Fi(this.h,0,1,s)}o(s){var t=this.h,r=Ul(this.h,DGe,2);return r=r?r.clone():new DGe,s.l2Normalize!==void 0?Sc(r,1,xB(s.l2Normalize)):"l2Normalize"in s&&Sc(r,1),s.quantize!==void 0?Sc(r,2,xB(s.quantize)):"quantize"in s&&Sc(r,2),Fi(t,0,2,r),this.l(s)}za(s,t){return U1(this,s,t),this.embeddings}Aa(s,t,r){return sw(this,s,r,t),this.embeddings}m(){var s=new F0;vu(s,"image_in"),vu(s,"norm_rect"),Jl(s,"embeddings_out");const t=new O0;ew(t,iFs,this.h);const r=new xx;M0(r,2,"mediapipe.tasks.vision.image_embedder.ImageEmbedderGraph"),Zd(r,"IMAGE:image_in"),Zd(r,"NORM_RECT:norm_rect"),_l(r,"EMBEDDINGS:embeddings_out"),r.o(t),cv(s,r),this.g.attachProtoListener("embeddings_out",(n,a)=>{n=ZOs(n),this.embeddings=function(i){return{embeddings:fj(i,YOs,1).map(l=>{var d,h;const o={headIndex:zy(l,3)??0??-1,headName:Gf(fu(l,4))??""??""};var c=l.v;return Zxt(c,0|c[pi],LGe,xwe(l,1))!==void 0?(l=ZT(l=Ul(l,LGe,xwe(l,1),void 0),1,a_,YT()),o.floatEmbedding=l.slice()):(c=new Uint8Array(0),o.quantizedEmbedding=((h=(d=Ul(l,KOs,xwe(l,2),void 0))==null?void 0:d.na())==null?void 0:h.h())??c),o}),timestampMs:iyt(fu(i,2,void 0,void 0,ipe)??Hxt)}}(n),ri(this,a)}),this.g.attachEmptyPacketListener("embeddings_out",n=>{ri(this,n)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};$x.cosineSimilarity=function(s,t){if(s.floatEmbedding&&t.floatEmbedding)s=$Ge(s.floatEmbedding,t.floatEmbedding);else{if(!s.quantizedEmbedding||!t.quantizedEmbedding)throw Error("Cannot compute cosine similarity between quantized and float embeddings.");s=$Ge(zGe(s.quantizedEmbedding),zGe(t.quantizedEmbedding))}return s},$x.prototype.embedForVideo=$x.prototype.Aa,$x.prototype.embed=$x.prototype.za,$x.prototype.setOptions=$x.prototype.o,$x.createFromModelPath=function(s,t){return Ol($x,s,{baseOptions:{modelAssetPath:t}})},$x.createFromModelBuffer=function(s,t){return Ol($x,s,{baseOptions:{modelAssetBuffer:t}})},$x.createFromOptions=function(s,t){return Ol($x,s,t)};var q4e=class{constructor(s,t,r){this.confidenceMasks=s,this.categoryMask=t,this.qualityScores=r}close(){var s,t;(s=this.confidenceMasks)==null||s.forEach(r=>{r.close()}),(t=this.categoryMask)==null||t.close()}};function yFs(s){var r,n;const t=function(a){return fj(a,xx,1)}(s.ca()).filter(a=>(Gf(fu(a,1))??"").includes("mediapipe.tasks.TensorsToSegmentationCalculator"));if(s.u=[],t.length>1)throw Error("The graph has more than one mediapipe.tasks.TensorsToSegmentationCalculator.");t.length===1&&(((n=(r=Ul(t[0],O0,7))==null?void 0:r.j())==null?void 0:n.g())??new Map).forEach((a,i)=>{s.u[Number(i)]=Gf(fu(a,1))??""})}function rWe(s){s.categoryMask=void 0,s.confidenceMasks=void 0,s.qualityScores=void 0}function nWe(s){try{const t=new q4e(s.confidenceMasks,s.categoryMask,s.qualityScores);if(!s.j)return t;s.j(t)}finally{lye(s)}}q4e.prototype.close=q4e.prototype.close;var sg=class extends I0{constructor(s,t){super(new $1(s,t),"image_in","norm_rect",!1),this.u=[],this.outputCategoryMask=!1,this.outputConfidenceMasks=!0,this.h=new QMe,this.A=new eyt,Fi(this.h,0,3,this.A),Fi(s=this.h,0,1,t=new Zu)}get baseOptions(){return Ul(this.h,Zu,1)}set baseOptions(s){Fi(this.h,0,1,s)}o(s){return s.displayNamesLocale!==void 0?Sc(this.h,2,zz(s.displayNamesLocale)):"displayNamesLocale"in s&&Sc(this.h,2),"outputCategoryMask"in s&&(this.outputCategoryMask=s.outputCategoryMask??!1),"outputConfidenceMasks"in s&&(this.outputConfidenceMasks=s.outputConfidenceMasks??!0),super.l(s)}L(){yFs(this)}segment(s,t,r){const n=typeof t!="function"?t:{};return this.j=typeof t=="function"?t:r,rWe(this),U1(this,s,n),nWe(this)}La(s,t,r,n){const a=typeof r!="function"?r:{};return this.j=typeof r=="function"?r:n,rWe(this),sw(this,s,a,t),nWe(this)}Da(){return this.u}m(){var s=new F0;vu(s,"image_in"),vu(s,"norm_rect");const t=new O0;ew(t,syt,this.h);const r=new xx;M0(r,2,"mediapipe.tasks.vision.image_segmenter.ImageSegmenterGraph"),Zd(r,"IMAGE:image_in"),Zd(r,"NORM_RECT:norm_rect"),r.o(t),cv(s,r),oye(this,s),this.outputConfidenceMasks&&(Jl(s,"confidence_masks"),_l(r,"CONFIDENCE_MASKS:confidence_masks"),KL(this,"confidence_masks"),this.g.aa("confidence_masks",(n,a)=>{this.confidenceMasks=n.map(i=>ZL(this,i,!0,!this.j)),ri(this,a)}),this.g.attachEmptyPacketListener("confidence_masks",n=>{this.confidenceMasks=[],ri(this,n)})),this.outputCategoryMask&&(Jl(s,"category_mask"),_l(r,"CATEGORY_MASK:category_mask"),KL(this,"category_mask"),this.g.Z("category_mask",(n,a)=>{this.categoryMask=ZL(this,n,!1,!this.j),ri(this,a)}),this.g.attachEmptyPacketListener("category_mask",n=>{this.categoryMask=void 0,ri(this,n)})),Jl(s,"quality_scores"),_l(r,"QUALITY_SCORES:quality_scores"),this.g.attachFloatVectorListener("quality_scores",(n,a)=>{this.qualityScores=n,ri(this,a)}),this.g.attachEmptyPacketListener("quality_scores",n=>{this.categoryMask=void 0,ri(this,n)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};sg.prototype.getLabels=sg.prototype.Da,sg.prototype.segmentForVideo=sg.prototype.La,sg.prototype.segment=sg.prototype.segment,sg.prototype.setOptions=sg.prototype.o,sg.createFromModelPath=function(s,t){return Ol(sg,s,{baseOptions:{modelAssetPath:t}})},sg.createFromModelBuffer=function(s,t){return Ol(sg,s,{baseOptions:{modelAssetBuffer:t}})},sg.createFromOptions=function(s,t){return Ol(sg,s,t)};var V4e=class{constructor(s,t,r){this.confidenceMasks=s,this.categoryMask=t,this.qualityScores=r}close(){var s,t;(s=this.confidenceMasks)==null||s.forEach(r=>{r.close()}),(t=this.categoryMask)==null||t.close()}};V4e.prototype.close=V4e.prototype.close;var Eb=class extends I0{constructor(s,t){super(new $1(s,t),"image_in","norm_rect_in",!1),this.outputCategoryMask=!1,this.outputConfidenceMasks=!0,this.h=new QMe,this.u=new eyt,Fi(this.h,0,3,this.u),Fi(s=this.h,0,1,t=new Zu)}get baseOptions(){return Ul(this.h,Zu,1)}set baseOptions(s){Fi(this.h,0,1,s)}o(s){return"outputCategoryMask"in s&&(this.outputCategoryMask=s.outputCategoryMask??!1),"outputConfidenceMasks"in s&&(this.outputConfidenceMasks=s.outputConfidenceMasks??!0),super.l(s)}segment(s,t,r,n){const a=typeof r!="function"?r:{};if(this.j=typeof r=="function"?r:n,this.qualityScores=this.categoryMask=this.confidenceMasks=void 0,r=this.C+1,n=new ryt,t.keypoint&&t.scribble)throw Error("Cannot provide both keypoint and scribble.");if(t.keypoint){var i=new _we;YN(i,3,xB(!0),!1),YN(i,1,IO(t.keypoint.x),0),YN(i,2,IO(t.keypoint.y),0),E7(n,1,F4e,i)}else{if(!t.scribble)throw Error("Must provide either a keypoint or a scribble.");{const o=new lFs;for(i of t.scribble)YN(t=new _we,3,xB(!0),!1),YN(t,1,IO(i.x),0),YN(t,2,IO(i.y),0),AMe(o,1,_we,t);E7(n,2,F4e,o)}}this.g.addProtoToStream(n.g(),"mediapipe.tasks.vision.interactive_segmenter.proto.RegionOfInterest","roi_in",r),U1(this,s,a);e:{try{const o=new V4e(this.confidenceMasks,this.categoryMask,this.qualityScores);if(!this.j){var l=o;break e}this.j(o)}finally{lye(this)}l=void 0}return l}m(){var s=new F0;vu(s,"image_in"),vu(s,"roi_in"),vu(s,"norm_rect_in");const t=new O0;ew(t,syt,this.h);const r=new xx;M0(r,2,"mediapipe.tasks.vision.interactive_segmenter.InteractiveSegmenterGraphV2"),Zd(r,"IMAGE:image_in"),Zd(r,"ROI:roi_in"),Zd(r,"NORM_RECT:norm_rect_in"),r.o(t),cv(s,r),oye(this,s),this.outputConfidenceMasks&&(Jl(s,"confidence_masks"),_l(r,"CONFIDENCE_MASKS:confidence_masks"),KL(this,"confidence_masks"),this.g.aa("confidence_masks",(n,a)=>{this.confidenceMasks=n.map(i=>ZL(this,i,!0,!this.j)),ri(this,a)}),this.g.attachEmptyPacketListener("confidence_masks",n=>{this.confidenceMasks=[],ri(this,n)})),this.outputCategoryMask&&(Jl(s,"category_mask"),_l(r,"CATEGORY_MASK:category_mask"),KL(this,"category_mask"),this.g.Z("category_mask",(n,a)=>{this.categoryMask=ZL(this,n,!1,!this.j),ri(this,a)}),this.g.attachEmptyPacketListener("category_mask",n=>{this.categoryMask=void 0,ri(this,n)})),Jl(s,"quality_scores"),_l(r,"QUALITY_SCORES:quality_scores"),this.g.attachFloatVectorListener("quality_scores",(n,a)=>{this.qualityScores=n,ri(this,a)}),this.g.attachEmptyPacketListener("quality_scores",n=>{this.categoryMask=void 0,ri(this,n)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};Eb.prototype.segment=Eb.prototype.segment,Eb.prototype.setOptions=Eb.prototype.o,Eb.createFromModelPath=function(s,t){return Ol(Eb,s,{baseOptions:{modelAssetPath:t}})},Eb.createFromModelBuffer=function(s,t){return Ol(Eb,s,{baseOptions:{modelAssetBuffer:t}})},Eb.createFromOptions=function(s,t){return Ol(Eb,s,t)};var yy=class extends I0{constructor(s,t){super(new $1(s,t),"input_frame_gpu","norm_rect",!1),this.j={detections:[]},Fi(s=this.h=new nyt,0,1,t=new Zu)}get baseOptions(){return Ul(this.h,Zu,1)}set baseOptions(s){Fi(this.h,0,1,s)}o(s){return s.displayNamesLocale!==void 0?Sc(this.h,2,zz(s.displayNamesLocale)):"displayNamesLocale"in s&&Sc(this.h,2),s.maxResults!==void 0?pj(this.h,3,s.maxResults):"maxResults"in s&&Sc(this.h,3),s.scoreThreshold!==void 0?Ni(this.h,4,s.scoreThreshold):"scoreThreshold"in s&&Sc(this.h,4),s.categoryAllowlist!==void 0?lpe(this.h,5,s.categoryAllowlist):"categoryAllowlist"in s&&Sc(this.h,5),s.categoryDenylist!==void 0?lpe(this.h,6,s.categoryDenylist):"categoryDenylist"in s&&Sc(this.h,6),this.l(s)}F(s,t){return this.j={detections:[]},U1(this,s,t),this.j}G(s,t,r){return this.j={detections:[]},sw(this,s,r,t),this.j}m(){var s=new F0;vu(s,"input_frame_gpu"),vu(s,"norm_rect"),Jl(s,"detections");const t=new O0;ew(t,cFs,this.h);const r=new xx;M0(r,2,"mediapipe.tasks.vision.ObjectDetectorGraph"),Zd(r,"IMAGE:input_frame_gpu"),Zd(r,"NORM_RECT:norm_rect"),_l(r,"DETECTIONS:detections"),r.o(t),cv(s,r),this.g.attachProtoVectorListener("detections",(n,a)=>{for(const i of n)n=D0t(i),this.j.detections.push(oyt(n));ri(this,a)}),this.g.attachEmptyPacketListener("detections",n=>{ri(this,n)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};yy.prototype.detectForVideo=yy.prototype.G,yy.prototype.detect=yy.prototype.F,yy.prototype.setOptions=yy.prototype.o,yy.createFromModelPath=async function(s,t){return Ol(yy,s,{baseOptions:{modelAssetPath:t}})},yy.createFromModelBuffer=function(s,t){return Ol(yy,s,{baseOptions:{modelAssetBuffer:t}})},yy.createFromOptions=function(s,t){return Ol(yy,s,t)};var H4e=class{constructor(s,t,r){this.landmarks=s,this.worldLandmarks=t,this.segmentationMasks=r}close(){var s;(s=this.segmentationMasks)==null||s.forEach(t=>{t.close()})}};function aWe(s){s.landmarks=[],s.worldLandmarks=[],s.segmentationMasks=void 0}function iWe(s){try{const t=new H4e(s.landmarks,s.worldLandmarks,s.segmentationMasks);if(!s.u)return t;s.u(t)}finally{lye(s)}}H4e.prototype.close=H4e.prototype.close;var Ux=class extends I0{constructor(s,t){super(new $1(s,t),"image_in","norm_rect",!1),this.landmarks=[],this.worldLandmarks=[],this.outputSegmentationMasks=!1,Fi(s=this.h=new ayt,0,1,t=new Zu),this.A=new Z0t,Fi(this.h,0,3,this.A),this.j=new Y0t,Fi(this.h,0,2,this.j),pj(this.j,4,1),Ni(this.j,2,.5),Ni(this.A,2,.5),Ni(this.h,4,.5)}get baseOptions(){return Ul(this.h,Zu,1)}set baseOptions(s){Fi(this.h,0,1,s)}o(s){return"numPoses"in s&&pj(this.j,4,s.numPoses??1),"minPoseDetectionConfidence"in s&&Ni(this.j,2,s.minPoseDetectionConfidence??.5),"minTrackingConfidence"in s&&Ni(this.h,4,s.minTrackingConfidence??.5),"minPosePresenceConfidence"in s&&Ni(this.A,2,s.minPosePresenceConfidence??.5),"outputSegmentationMasks"in s&&(this.outputSegmentationMasks=s.outputSegmentationMasks??!1),this.l(s)}F(s,t,r){const n=typeof t!="function"?t:{};return this.u=typeof t=="function"?t:r,aWe(this),U1(this,s,n),iWe(this)}G(s,t,r,n){const a=typeof r!="function"?r:{};return this.u=typeof r=="function"?r:n,aWe(this),sw(this,s,a,t),iWe(this)}m(){var s=new F0;vu(s,"image_in"),vu(s,"norm_rect"),Jl(s,"normalized_landmarks"),Jl(s,"world_landmarks"),Jl(s,"segmentation_masks");const t=new O0;ew(t,dFs,this.h);const r=new xx;M0(r,2,"mediapipe.tasks.vision.pose_landmarker.PoseLandmarkerGraph"),Zd(r,"IMAGE:image_in"),Zd(r,"NORM_RECT:norm_rect"),_l(r,"NORM_LANDMARKS:normalized_landmarks"),_l(r,"WORLD_LANDMARKS:world_landmarks"),r.o(t),cv(s,r),oye(this,s),this.g.attachProtoVectorListener("normalized_landmarks",(n,a)=>{this.landmarks=[];for(const i of n)n=qz(i),this.landmarks.push(iye(n));ri(this,a)}),this.g.attachEmptyPacketListener("normalized_landmarks",n=>{this.landmarks=[],ri(this,n)}),this.g.attachProtoVectorListener("world_landmarks",(n,a)=>{this.worldLandmarks=[];for(const i of n)n=bP(i),this.worldLandmarks.push(M7(n));ri(this,a)}),this.g.attachEmptyPacketListener("world_landmarks",n=>{this.worldLandmarks=[],ri(this,n)}),this.outputSegmentationMasks&&(_l(r,"SEGMENTATION_MASK:segmentation_masks"),KL(this,"segmentation_masks"),this.g.aa("segmentation_masks",(n,a)=>{this.segmentationMasks=n.map(i=>ZL(this,i,!0,!this.u)),ri(this,a)}),this.g.attachEmptyPacketListener("segmentation_masks",n=>{this.segmentationMasks=[],ri(this,n)})),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};Ux.prototype.detectForVideo=Ux.prototype.G,Ux.prototype.detect=Ux.prototype.F,Ux.prototype.setOptions=Ux.prototype.o,Ux.createFromModelPath=function(s,t){return Ol(Ux,s,{baseOptions:{modelAssetPath:t}})},Ux.createFromModelBuffer=function(s,t){return Ol(Ux,s,{baseOptions:{modelAssetBuffer:t}})},Ux.createFromOptions=function(s,t){return Ol(Ux,s,t)},Ux.POSE_CONNECTIONS=wyt;let XT=null,PO=null;async function vFs(){return XT||PO||(PO=(async()=>{const s=await G6.forVisionTasks("https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@latest/wasm");return XT=await sg.createFromOptions(s,{baseOptions:{modelAssetPath:"https://storage.googleapis.com/mediapipe-models/image_segmenter/selfie_multiclass_256x256/float32/latest/selfie_multiclass_256x256.tflite",delegate:"GPU"},runningMode:"VIDEO",outputCategoryMask:!1,outputConfidenceMasks:!0}),XT})(),PO)}function bFs(s,t,r,n,a){const i=new Float32Array(s.length);for(let l=0;l=0&&(o-=s[c+h]);const p=Math.min(m,r-1)-Math.max(h+1,0)+1;i[c+d]=o/p}}for(let l=0;l=0&&(o-=i[d*r+l]);const m=Math.min(h,n-1)-Math.max(d+1,0)+1;t[c*r+l]=o/m}}}function _Fs(){XT&&(XT.close(),XT=null,PO=null)}function wFs(s,t){const r=S.useRef(null),n=S.useRef(null),a=S.useRef(null),i=S.useRef(null),l=S.useRef(0);S.useRef(0);const[o,c]=S.useState(null),[d,h]=S.useState(!1),[m,p]=S.useState(null),x=t.type!=="none"&&s!==null;return S.useEffect(()=>{if(t.type==="image"&&t.imageUrl){const y=new Image;y.crossOrigin="anonymous",y.src=t.imageUrl,y.onload=()=>{i.current=y}}else i.current=null},[t.type,t.imageUrl]),S.useEffect(()=>{if(!x||!s){a.current&&(a.current.srcObject=null,a.current=null);return}const y=document.createElement("video");return y.srcObject=s,y.muted=!0,y.playsInline=!0,y.autoplay=!0,y.play().catch(()=>{}),a.current=y,()=>{y.srcObject=null,a.current=null}},[x,s]),S.useEffect(()=>{if(!x){c(null),p(null);return}let y=!1;return(async()=>{h(!0),p(null);try{const b=await vFs();if(y)return;h(!1);const j=a.current;if(!j||(await new Promise(Me=>{if(j.videoWidth>0)return Me();j.onloadedmetadata=()=>Me(),setTimeout(Me,2e3)}),y))return;const k=j.videoWidth||640,T=j.videoHeight||480,E=r.current;if(!E)return;E.width=k,E.height=T;const A=E.getContext("2d",{willReadFrequently:!1,alpha:!1});n.current||(n.current=document.createElement("canvas"));const D=n.current;D.width=k,D.height=T;const R=D.getContext("2d",{willReadFrequently:!1}),z=document.createElement("canvas");z.width=k,z.height=T;const O=z.getContext("2d",{alpha:!1}),$=document.createElement("canvas");$.width=k,$.height=T;const ee=$.getContext("2d",{willReadFrequently:!1}),Z=ee.createImageData(k,T),J=Z.data;for(let Me=0;MeK.addTrack(Me)),y||c(K);const ie=t.blurRadius??15,ce=t.mirror??!1,ne=new Float32Array(k*T),le=new Float32Array(k*T),be=new Float32Array(k*T);let fe=!1;const je=4,ve=.35,We=typeof j.requestVideoFrameCallback=="function",Ve=()=>{if(y||!a.current)return;const Me=a.current;if(Me.readyState<2){Le(Me);return}try{const ze=performance.now(),Ie=b.segmentForVideo(Me,ze).confidenceMasks;if(Ie&&Ie.length>0){le.fill(0);for(let De=1;De1?1:ct}}if(bFs(le,ne,k,T,je),fe)for(let De=0;De=1?255:tt*255|0}if(ee.putImageData(Z,0,0),t.type==="blur")O.filter=`blur(${ie}px)`,O.drawImage(Me,0,0,k,T),O.filter="none",A.drawImage(z,0,0);else if(t.type==="image"&&i.current){const De=i.current,pe=De.width/De.height,tt=k/T;let ge=0,ct=0,Ue=De.width,et=De.height;pe>tt?(Ue=De.height*tt,ge=(De.width-Ue)/2):(et=De.width/tt,ct=(De.height-et)/2),A.drawImage(De,ge,ct,Ue,et,0,0,k,T)}else A.fillStyle="#000",A.fillRect(0,0,k,T);R.globalCompositeOperation="source-over",R.clearRect(0,0,k,T),R.drawImage(Me,0,0,k,T),R.globalCompositeOperation="destination-in",R.drawImage($,0,0),R.globalCompositeOperation="source-over",ce?(A.save(),A.translate(k,0),A.scale(-1,1),A.drawImage(D,0,0),A.restore()):A.drawImage(D,0,0);for(const De of Ie)De.close()}else A.drawImage(Me,0,0,k,T)}catch{A.drawImage(Me,0,0,k,T)}Le(Me)},Le=Me=>{y||(We?Me.requestVideoFrameCallback(()=>Ve()):l.current=requestAnimationFrame(Ve))};Le(j)}catch(b){console.error("[useVirtualBackground] init error:",b),y||(h(!1),p(b.message||"Failed to initialize virtual background"))}})(),()=>{y=!0,l.current&&cancelAnimationFrame(l.current),c(null)}},[x,t.type,t.blurRadius,t.imageUrl,s]),S.useEffect(()=>()=>{_Fs()},[]),{canvasRef:r,compositedStream:o,isLoading:d,isActive:x,error:m}}function aD({maxDurationSeconds:s=600,onRecordingComplete:t,onError:r,onRecordingStateChange:n,className:a,teleprompterContent:i}){const l=S.useRef(null),o=S.useRef(null),c=S.useRef(null),[d,h]=S.useState(null),m=S.useRef([]),p=S.useRef(null),x=S.useRef(null),y=S.useRef(null),_=S.useRef(null),b=V8(),[j,k]=S.useState("camera"),T=S.useRef(null),E=S.useRef(null),A=S.useRef(null),D=S.useRef(null),R=S.useRef(null),z=S.useRef(null),[O,$]=S.useState(!0),[ee,Z]=S.useState(!0),[J,K]=S.useState(null),[re,ie]=S.useState(!1),[ce,ne]=S.useState(!1),[le,be]=S.useState(null),[fe,je]=S.useState(null),[ve,We]=S.useState(0),[Ve,Le]=S.useState("user"),[Me,ze]=S.useState(0),[Pe,Ie]=S.useState(!1),[De,pe]=S.useState(!0),[tt,ge]=S.useState(null),[ct,Ue]=S.useState(!1),[et,Qe]=S.useState(null),Ne=S.useRef(null),[$e,it]=S.useState(()=>{try{const _r=localStorage.getItem("video-bg-config");if(_r)return JSON.parse(_r)}catch{}return{type:"none"}});S.useEffect(()=>{try{localStorage.setItem("video-bg-config",JSON.stringify($e))}catch{}},[$e]);const[Je,st]=S.useState([]),[mt,wt]=S.useState([]),[at,rt]=S.useState(()=>{try{return localStorage.getItem("video-mic-id")||""}catch{return""}}),[Et,hs]=S.useState(()=>{try{return localStorage.getItem("video-cam-id")||""}catch{return""}});S.useEffect(()=>{try{localStorage.setItem("video-mic-id",at)}catch{}},[at]),S.useEffect(()=>{try{localStorage.setItem("video-cam-id",Et)}catch{}},[Et]),S.useEffect(()=>{var Hr,_a,Jt;if(!((Hr=navigator.mediaDevices)!=null&&Hr.enumerateDevices))return;const _r=async()=>{try{const Cr=await navigator.mediaDevices.enumerateDevices();st(Cr.filter(Gt=>Gt.kind==="audioinput")),wt(Cr.filter(Gt=>Gt.kind==="videoinput"))}catch(Cr){console.warn("[VideoRecorder] enumerateDevices failed",Cr)}};return _r(),(Jt=(_a=navigator.mediaDevices).addEventListener)==null||Jt.call(_a,"devicechange",_r),()=>{var Cr,Gt;return(Gt=(Cr=navigator.mediaDevices).removeEventListener)==null?void 0:Gt.call(Cr,"devicechange",_r)}},[J]);const{canvasRef:Is,compositedStream:lr,isLoading:us,isActive:St,error:xs}=wFs(d,$e),kt=S.useRef(r);kt.current=r;const fs=S.useCallback(_r=>{$(_r)},[]),Gs=S.useRef(O),_s=S.useCallback(()=>{A.current&&(cancelAnimationFrame(A.current),A.current=null),D.current&&(D.current.terminate(),D.current=null),T.current&&(T.current.getTracks().forEach(_r=>_r.stop()),T.current=null),R.current&&(R.current.getTracks().forEach(_r=>_r.stop()),R.current=null),z.current&&(z.current.srcObject=null,z.current=null)},[]),br=S.useCallback(async()=>{var _r;try{const Hr=await navigator.mediaDevices.getDisplayMedia({video:{width:{ideal:1920},height:{ideal:1080}},audio:!0});T.current=Hr;let _a=null;try{_a=await navigator.mediaDevices.getUserMedia({video:Et?{deviceId:{exact:Et},width:{ideal:320},height:{ideal:240}}:{width:{ideal:320},height:{ideal:240}},audio:!1})}catch{console.warn("[VideoRecorder] No webcam for PiP overlay")}let Jt=null;try{Jt=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,...at?{deviceId:{exact:at}}:{}}}),console.log("[VideoRecorder] mic acquired for screen recording",Jt.getAudioTracks().map(Gr=>Gr.label))}catch(Gr){console.warn("[VideoRecorder] No mic audio for screen recording",Gr);try{Jt=await navigator.mediaDevices.getUserMedia({audio:!0})}catch{}}const Cr=Hr.getVideoTracks()[0],Gt=Cr.getSettings(),Ee=Gt.width||1920,He=Gt.height||1080,ot=document.createElement("canvas");ot.width=Ee,ot.height=He,E.current=ot;const jt=ot.getContext("2d");let Dt=null;_a&&(Dt=document.createElement("video"),Dt.srcObject=_a,Dt.muted=!0,Dt.playsInline=!0,Dt.autoplay=!0,await Dt.play(),z.current=Dt);const qt=document.createElement("video");qt.srcObject=Hr,qt.muted=!0,qt.playsInline=!0,qt.autoplay=!0,await qt.play();const ss=()=>{if(jt.drawImage(qt,0,0,Ee,He),Dt&&Dt.readyState>=2){const Gr=Math.round(Ee*.2),fn=Math.round(Gr*(Dt.videoHeight/Dt.videoWidth||.75)),pn=Ee-Gr-20,Sn=He-fn-20,Aa=12;jt.save(),jt.beginPath(),jt.moveTo(pn+Aa,Sn),jt.lineTo(pn+Gr-Aa,Sn),jt.quadraticCurveTo(pn+Gr,Sn,pn+Gr,Sn+Aa),jt.lineTo(pn+Gr,Sn+fn-Aa),jt.quadraticCurveTo(pn+Gr,Sn+fn,pn+Gr-Aa,Sn+fn),jt.lineTo(pn+Aa,Sn+fn),jt.quadraticCurveTo(pn,Sn+fn,pn,Sn+fn-Aa),jt.lineTo(pn,Sn+Aa),jt.quadraticCurveTo(pn,Sn,pn+Aa,Sn),jt.closePath(),jt.clip(),jt.translate(pn+Gr,Sn),jt.scale(-1,1),jt.drawImage(Dt,0,0,Gr,fn),jt.restore(),jt.strokeStyle="rgba(255,255,255,0.6)",jt.lineWidth=2,jt.beginPath(),jt.moveTo(pn+Aa,Sn),jt.lineTo(pn+Gr-Aa,Sn),jt.quadraticCurveTo(pn+Gr,Sn,pn+Gr,Sn+Aa),jt.lineTo(pn+Gr,Sn+fn-Aa),jt.quadraticCurveTo(pn+Gr,Sn+fn,pn+Gr-Aa,Sn+fn),jt.lineTo(pn+Aa,Sn+fn),jt.quadraticCurveTo(pn,Sn+fn,pn,Sn+fn-Aa),jt.lineTo(pn,Sn+Aa),jt.quadraticCurveTo(pn,Sn,pn+Aa,Sn),jt.closePath(),jt.stroke()}},Yt="let id=null;onmessage=(e)=>{if(e.data&&e.data.type==='start'){clearInterval(id);id=setInterval(()=>postMessage('tick'),Math.round(1000/(e.data.fps||30)))}else if(e.data==='stop'){clearInterval(id);id=null}}",ls=new Blob([Yt],{type:"application/javascript"}),Xs=new Worker(URL.createObjectURL(ls));D.current=Xs,Xs.onmessage=()=>ss(),Xs.postMessage({type:"start",fps:30}),ss();const Rs=ot.captureStream(30),Er=[],ln=Hr.getAudioTracks();ln.length&&Er.push(...ln),Jt&&Er.push(...Jt.getAudioTracks());const mn=new MediaStream([...Rs.getVideoTracks(),...Er]);return R.current=mn,Cr.onended=()=>{o.current&&o.current.state!=="inactive"&&o.current.stop(),_s()},mn}catch(Hr){return console.error("[VideoRecorder] Screen capture error:",Hr),Hr.name!=="NotAllowedError"&&((_r=kt.current)==null||_r.call(kt,"Failed to start screen capture: "+(Hr.message||"Unknown error"))),null}},[_s]),zr=S.useCallback(async()=>{var Hr,_a;Z(!0),ge(null);const _r=b&&O;console.log("[VideoRecorder] initCamera start",{isMobile:b,usePortraitMode:O,shouldBePortrait:_r,facingMode:Ve});try{if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)throw new Error("Camera not available in this browser or context. Try opening in a new tab.");c.current&&(console.log("[VideoRecorder] stopping existing stream"),c.current.getTracks().forEach(jt=>jt.stop()));const Jt=b&&_r?{width:{ideal:720},height:{ideal:1280}}:{width:{ideal:1280},height:{ideal:720}},Cr=Et?{...Jt,deviceId:{exact:Et}}:{...Jt,facingMode:{ideal:Ve}},Gt={echoCancellation:!0,noiseSuppression:!0,...at?{deviceId:{exact:at}}:{}};console.log("[VideoRecorder] requesting getUserMedia",Cr);const Ee=await navigator.mediaDevices.getUserMedia({video:Cr,audio:Gt});if(console.log("[VideoRecorder] getUserMedia success"),Ee.getVideoTracks().length===0)throw new Error("Camera stream started but no video track was provided.");c.current=Ee,h(Ee),K(!0);const ot=Ee.getVideoTracks()[0].getSettings();if(console.log("[VideoRecorder] Camera initialized with dimensions:",ot.width,"x",ot.height),l.current){const jt=l.current;jt.srcObject=Ee,jt.muted=!0,jt.playsInline=!0,jt.autoplay=!0,jt.setAttribute("muted",""),jt.setAttribute("playsinline",""),jt.setAttribute("autoplay","");try{(Hr=jt.load)==null||Hr.call(jt)}catch(qt){console.warn("[VideoRecorder] videoEl.load failed",qt)}const Dt=async()=>{try{return await jt.play(),console.log("[VideoRecorder] preview play ok"),Ue(!1),setTimeout(()=>{console.debug("[VideoRecorder] preview metrics",{readyState:jt.readyState,videoWidth:jt.videoWidth,videoHeight:jt.videoHeight})},300),!0}catch(qt){return console.warn("[VideoRecorder] preview play blocked",qt),Ue(!0),!1}};await new Promise(qt=>{let ss=!1;const Yt=()=>{ss||(ss=!0,qt())},ls=()=>{Dt().finally(Yt)};jt.onloadedmetadata=ls,jt.onloadeddata=ls,setTimeout(Yt,1500)})}try{x.current=new AudioContext;const jt=x.current.createMediaStreamSource(Ee);y.current=x.current.createAnalyser(),y.current.fftSize=256,jt.connect(y.current);const Dt=()=>{if(y.current){const qt=new Uint8Array(y.current.frequencyBinCount);y.current.getByteFrequencyData(qt);const ss=qt.reduce((Yt,ls)=>Yt+ls)/qt.length;ze(Math.min(100,ss/128*100))}_.current=requestAnimationFrame(Dt)};Dt()}catch(jt){console.warn("Audio context not available:",jt)}}catch(Jt){console.error("Camera initialization error:",Jt),K(!1);let Cr="Failed to access camera or microphone.";Jt.name==="NotAllowedError"?Cr="Camera permission denied. Please allow camera access in your browser settings.":Jt.name==="NotFoundError"?Cr="No camera found. Please connect a camera and try again.":Jt.name==="NotReadableError"?Cr="Camera is in use by another application. Please close other apps using the camera.":Jt.message&&(Cr=Jt.message),ge(Cr),(_a=kt.current)==null||_a.call(kt,Cr)}finally{Z(!1)}},[Ve,b,O,at,Et]);S.useEffect(()=>{Gs.current!==O&&J&&!re&&!fe&&(Gs.current=O,zr())},[O,J,re,fe,zr]),S.useEffect(()=>(zr(),()=>{c.current&&c.current.getTracks().forEach(_r=>_r.stop()),p.current&&clearInterval(p.current),_.current&&cancelAnimationFrame(_.current),x.current&&x.current.close(),Ne.current&&clearInterval(Ne.current),fe&&URL.revokeObjectURL(fe),_s()}),[zr,fe]),S.useEffect(()=>{if(ee||J!==!0||fe)return;const _r=c.current,Hr=l.current;!_r||!Hr||St||(Hr.srcObject!==_r&&(Hr.srcObject=_r,Hr.muted=!0,Hr.playsInline=!0,Hr.autoplay=!0,Hr.setAttribute("muted",""),Hr.setAttribute("playsinline",""),Hr.setAttribute("autoplay","")),Hr.play().then(()=>Ue(!1)).catch(_a=>{Ue(!0),console.warn("Live preview play blocked on mount:",_a)}))},[J,ee,fe,St]),S.useEffect(()=>{n==null||n(re)},[re,n]);const Yr=S.useCallback(async()=>{if(fe)return;const _r=l.current;if(_r)try{await _r.play(),Ue(!1)}catch(Hr){Ue(!0),console.warn("Live preview still blocked (needs user gesture):",Hr)}},[fe]),rn=S.useCallback(()=>{o.current&&o.current.state!=="inactive"&&o.current.stop(),p.current&&(clearInterval(p.current),p.current=null),_s(),ie(!1),ne(!1)},[_s]),sn=S.useCallback(async()=>{let _r=null;if(j==="screen"){if(_r=await br(),!_r)return}else _r=St&&lr?lr:c.current;if(!_r)return;Yr(),m.current=[],We(0);const _a=["video/webm;codecs=vp9,opus","video/webm;codecs=vp8,opus","video/webm;codecs=vp9","video/webm;codecs=vp8","video/webm","video/mp4"].find(Cr=>MediaRecorder.isTypeSupported(Cr)),Jt=new MediaRecorder(_r,_a?{mimeType:_a,videoBitsPerSecond:j==="screen"?4e6:25e5}:{videoBitsPerSecond:j==="screen"?4e6:25e5});Jt.ondataavailable=Cr=>{Cr.data.size>0&&m.current.push(Cr.data)},Jt.onstop=()=>{var He;const Cr=Jt.mimeType||_a||((He=m.current[0])==null?void 0:He.type)||"video/webm",Gt=new Blob(m.current,{type:Cr});be(Gt);const Ee=URL.createObjectURL(Gt);je(Ee)},o.current=Jt,Jt.start(100),ie(!0),p.current=setInterval(()=>{We(Cr=>Cr>=s-1?(rn(),s):Cr+1)},1e3)},[Yr,s,rn,St,lr,j,br]),Vr=S.useCallback(()=>{Ne.current&&(clearInterval(Ne.current),Ne.current=null),Qe(3);let _r=3;Ne.current=setInterval(()=>{_r-=1,_r<=0?(Ne.current&&clearInterval(Ne.current),Ne.current=null,Qe(null),sn()):Qe(_r)},1e3)},[sn]),$r=S.useCallback(()=>{o.current&&o.current.state==="recording"&&(o.current.pause(),ne(!0),p.current&&clearInterval(p.current))},[]),hn=S.useCallback(()=>{o.current&&o.current.state==="paused"&&(o.current.resume(),ne(!1),p.current=setInterval(()=>{We(_r=>_r>=s-1?(rn(),s):_r+1)},1e3))},[s,rn]),Zn=S.useCallback(()=>{fe&&URL.revokeObjectURL(fe),be(null),je(null),We(0),Ie(!1),pe(!0),l.current&&c.current&&!St&&(l.current.srcObject=c.current,l.current.muted=!0,Yr())},[Yr,fe,St]),cr=S.useCallback(()=>{Le(_r=>_r==="user"?"environment":"user")},[]),on=S.useCallback(()=>{le&&t(le,ve)},[le,ve,t]),ds=S.useCallback(()=>{l.current&&fe&&(Pe?l.current.pause():(pe(!1),l.current.muted=!1,l.current.play()),Ie(!Pe))},[fe,Pe]);S.useEffect(()=>{if(!fe)return;const _r=l.current;if(!_r)return;pe(!1),_r.pause(),_r.removeAttribute("src"),_r.srcObject=null,_r.load(),_r.src=fe,_r.currentTime=0,_r.playsInline=!0,_r.muted=!1,_r.onended=()=>Ie(!1);const Hr=()=>{var Cr;const _a=_r.error,Jt=_a?`Recorded video failed to play (code ${_a.code}). Likely unsupported format/codec in this browser.`:"Recorded video failed to play.";console.warn("[VideoRecorder] recorded playback error",_a),(Cr=kt.current)==null||Cr.call(kt,Jt)};return _r.addEventListener("error",Hr),_r.load(),()=>{_r.removeEventListener("error",Hr)}},[fe]);const Na=_r=>{const Hr=Math.floor(_r/60),_a=_r%60;return`${Hr}:${_a.toString().padStart(2,"0")}`},vn=j==="screen"?"aspect-video":b&&O?"aspect-[9/16]":"aspect-video";return ee?e.jsx("div",{className:Ft("flex items-center justify-center bg-black rounded-lg",vn,a),children:e.jsxs("div",{className:"text-center text-white",children:[e.jsx(is,{className:"h-12 w-12 animate-spin mx-auto mb-4"}),e.jsx("p",{children:"Initializing camera..."})]})}):J===!1?e.jsx("div",{className:Ft("flex items-center justify-center bg-black rounded-lg",vn,a),children:e.jsxs("div",{className:"text-center text-white p-8 max-w-md",children:[e.jsx(wo,{className:"h-12 w-12 mx-auto mb-4 text-destructive"}),e.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Camera Access Required"}),e.jsx("p",{className:"text-gray-400 mb-4 text-sm",children:tt||"Please allow camera and microphone access to record videos."}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(H,{onClick:()=>zr(),variant:"secondary",className:"w-full",children:[e.jsx(po,{className:"h-4 w-4 mr-2"}),"Try Again"]}),e.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."})]})]})}):e.jsxs("div",{className:Ft("flex flex-col gap-2",a),children:[!re&&!fe&&e.jsxs("div",{className:"flex items-center justify-center gap-1 p-1 bg-muted rounded-lg",children:[e.jsxs(H,{variant:j==="camera"?"default":"ghost",size:"sm",className:"gap-1.5 flex-1",onClick:()=>k("camera"),children:[e.jsx(lx,{className:"h-4 w-4"}),"Camera"]}),e.jsxs(H,{variant:j==="screen"?"default":"ghost",size:"sm",className:"gap-1.5 flex-1",onClick:()=>k("screen"),children:[e.jsx(AE,{className:"h-4 w-4"}),"Screen"]})]}),j==="camera"&&!re&&!fe&&e.jsx(DRs,{value:$e,onChange:it,isLoading:us,disabled:re}),!re&&!fe&&(Je.length>0||mt.length>0)&&e.jsxs("div",{className:"flex flex-wrap items-center gap-3 px-3 py-2 bg-muted/40 rounded-lg",children:[Je.length>0&&e.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-[200px]",children:[e.jsx(EE,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs(Bs,{value:at||"default",onValueChange:_r=>rt(_r==="default"?"":_r),children:[e.jsx(Os,{className:"h-8 text-xs",children:e.jsx(Us,{placeholder:"Default microphone"})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"default",children:"Default microphone"}),Je.map(_r=>e.jsx(pt,{value:_r.deviceId,children:_r.label||`Microphone ${_r.deviceId.slice(0,6)}`},_r.deviceId))]})]})]}),mt.length>1&&j==="camera"&&e.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-[200px]",children:[e.jsx(lx,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs(Bs,{value:Et||"default",onValueChange:_r=>hs(_r==="default"?"":_r),children:[e.jsx(Os,{className:"h-8 text-xs",children:e.jsx(Us,{placeholder:"Default camera"})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"default",children:"Default camera"}),mt.map(_r=>e.jsx(pt,{value:_r.deviceId,children:_r.label||`Camera ${_r.deviceId.slice(0,6)}`},_r.deviceId))]})]})]})]}),j==="camera"&&b&&!re&&!fe&&e.jsxs("div",{className:"flex items-center justify-center gap-3 py-2 bg-muted/50 rounded-lg",children:[e.jsx(Vk,{className:Ft("h-4 w-4",O?"text-muted-foreground":"text-primary")}),e.jsx(ue,{htmlFor:"orientation-toggle",className:"text-sm text-muted-foreground",children:"Landscape"}),e.jsx(Or,{id:"orientation-toggle",checked:O,onCheckedChange:fs}),e.jsx(ue,{htmlFor:"orientation-toggle",className:"text-sm text-muted-foreground",children:"Portrait"}),e.jsx(Vy,{className:Ft("h-4 w-4",O?"text-primary":"text-muted-foreground")})]}),j==="screen"&&!re&&!fe&&e.jsxs("div",{className:"flex items-center justify-center gap-2 py-3 px-4 bg-muted/50 rounded-lg text-sm text-muted-foreground",children:[e.jsx(AE,{className:"h-4 w-4 text-primary"}),e.jsx("span",{children:"Press record to share your screen. Your webcam will appear as a small overlay."})]}),e.jsxs("div",{className:Ft("relative bg-black rounded-lg overflow-hidden"),onPointerDown:()=>{Yr()},children:[e.jsx("video",{ref:l,src:fe??void 0,className:Ft("w-full bg-black",O&&!fe?"object-contain":"object-cover",vn,!fe&&Ve==="user"!==($e.mirror??!1)&&"scale-x-[-1]",St&&!fe&&"hidden"),playsInline:!0,controls:!!fe,muted:fe?De:!0,autoPlay:!fe},fe??"live"),St&&!fe&&e.jsx("canvas",{ref:Is,className:Ft("w-full bg-black",O?"object-contain":"object-cover",vn,Ve==="user"!==($e.mirror??!1)&&"scale-x-[-1]")}),St&&us&&!fe&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/60 z-20",children:e.jsxs("div",{className:"text-center text-white",children:[e.jsx(is,{className:"h-8 w-8 animate-spin mx-auto mb-2"}),e.jsx("p",{className:"text-sm",children:"Loading virtual background…"})]})}),!fe&&ct&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/40",children:e.jsx(H,{type:"button",variant:"secondary",onClick:()=>void Yr(),className:"bg-white/20 hover:bg-white/30 text-white",children:"Tap to enable preview"})}),i&&!fe&&e.jsx("div",{className:"absolute inset-0 pointer-events-none",children:i}),et!==null&&!fe&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center z-30 pointer-events-none",children:e.jsxs("div",{className:"flex flex-col items-center gap-2",children:[e.jsx("div",{className:"text-white font-bold drop-shadow-lg animate-scale-in",style:{fontSize:"96px",lineHeight:1,textShadow:"0 4px 16px rgba(0,0,0,0.8)"},children:et},et),e.jsx("p",{className:"text-white/80 text-lg font-medium drop-shadow-md",children:"Get ready…"})]})}),re&&e.jsxs("div",{className:"absolute top-4 left-4 flex items-center gap-2 bg-black/50 px-3 py-1.5 rounded-full",children:[e.jsx("div",{className:Ft("w-3 h-3 rounded-full",ce?"bg-yellow-500":"bg-red-500 animate-pulse")}),e.jsxs("span",{className:"text-white text-sm font-medium",children:[Na(ve)," / ",Na(s)]})]}),re&&e.jsx("div",{className:"absolute top-0 left-0 right-0",children:e.jsx(Mi,{value:ve/s*100,className:"h-1 rounded-none"})}),!fe&&e.jsxs("div",{className:"absolute bottom-20 left-4 flex items-center gap-2 bg-black/50 px-3 py-1.5 rounded-full",children:[e.jsx(EE,{className:"h-4 w-4 text-white"}),e.jsx("div",{className:"w-20 h-2 bg-white/20 rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-green-500 transition-all duration-75",style:{width:`${Me}%`}})})]}),e.jsx("div",{className:"absolute bottom-4 left-0 right-0 flex justify-center gap-3 px-4",children:fe?e.jsxs(e.Fragment,{children:[e.jsxs(H,{variant:"secondary",size:"lg",className:"bg-white/20 hover:bg-white/30 text-white",onClick:Zn,children:[e.jsx(po,{className:"h-5 w-5 mr-2"}),"Re-record"]}),e.jsx(H,{variant:"secondary",size:"icon",className:"h-12 w-12 rounded-full bg-white/20 hover:bg-white/30 text-white",onClick:ds,children:Pe?e.jsx(Hf,{className:"h-5 w-5"}):e.jsx(El,{className:"h-5 w-5"})}),e.jsxs(H,{size:"lg",className:"bg-green-500 hover:bg-green-600 text-white",onClick:on,children:[e.jsx(va,{className:"h-5 w-5 mr-2"}),"Use This Video"]})]}):e.jsxs(e.Fragment,{children:[j==="camera"?e.jsx(H,{variant:"secondary",size:"icon",className:"h-12 w-12 rounded-full bg-white/20 hover:bg-white/30 text-white",onClick:cr,disabled:re||et!==null,children:e.jsx(qy,{className:"h-5 w-5"})}):e.jsx("div",{className:"h-12 w-12"}),!re&&et===null?e.jsx(H,{size:"icon",className:"h-16 w-16 rounded-full bg-red-500 hover:bg-red-600 text-white",onClick:j==="screen"?sn:Vr,children:j==="screen"?e.jsx(AE,{className:"h-6 w-6"}):e.jsx(xn,{className:"h-6 w-6"})}):e.jsxs(e.Fragment,{children:[e.jsx(H,{size:"icon",className:"h-12 w-12 rounded-full bg-white/20 hover:bg-white/30 text-white",onClick:ce?hn:$r,children:ce?e.jsx(El,{className:"h-5 w-5"}):e.jsx(Hf,{className:"h-5 w-5"})}),e.jsx(H,{size:"icon",className:"h-16 w-16 rounded-full bg-red-500 hover:bg-red-600 text-white",onClick:rn,children:e.jsx(Hy,{className:"h-6 w-6 fill-current"})})]}),e.jsx("div",{className:"h-12 w-12"})]})})]})]})}const jyt="teleprompter_settings",jwe={scrollSpeed:30,fontSize:24,lineHeight:1.6,opacity:.85,position:"top",isMirrored:!1};function jFs(){try{const s=localStorage.getItem(jyt);return s?{...jwe,...JSON.parse(s)}:jwe}catch{return jwe}}function NFs(s){try{localStorage.setItem(jyt,JSON.stringify(s))}catch{}}function c6e({text:s,isVisible:t,onToggleVisibility:r,isRecording:n=!1,startCountdown:a=!1,onCountdownComplete:i,className:l}){const o=S.useRef(null),c=S.useRef(null),d=S.useRef(0),h=S.useRef(0),[m,p]=S.useState(jFs),{scrollSpeed:x,fontSize:y,lineHeight:_,opacity:b,position:j,isMirrored:k}=m,T=S.useCallback((Z,J)=>{p(K=>{const re={...K,[Z]:J};return NFs(re),re})},[]),[E,A]=S.useState(!1),[D,R]=S.useState(null),z=S.useCallback(Z=>{if(!o.current)return;d.current===0&&(d.current=Z);const J=Z-d.current;d.current=Z,h.current+=x*J/1e3;const K=Math.floor(h.current);K>0&&(o.current.scrollTop+=K,h.current-=K);const{scrollTop:re,scrollHeight:ie,clientHeight:ce}=o.current;if(re+ce>=ie){A(!1);return}c.current=requestAnimationFrame(z)},[x]);S.useEffect(()=>(E?(d.current=0,h.current=0,c.current=requestAnimationFrame(z)):c.current&&cancelAnimationFrame(c.current),()=>{c.current&&cancelAnimationFrame(c.current)}),[E,z]),S.useEffect(()=>{if(n&&t)if(o.current&&(o.current.scrollTop=0),a){R(3);let Z=3;const J=setInterval(()=>{Z-=1,Z<=0?(clearInterval(J),R(null),i==null||i(),A(!0)):R(Z)},1e3);return()=>clearInterval(J)}else setTimeout(()=>A(!0),100);else n||(A(!1),R(null))},[n,t,a,i]);const O=S.useCallback(()=>{o.current&&(o.current.scrollTop=0),A(!1)},[]),$=S.useCallback(()=>{A(Z=>!Z)},[]);if(!t)return e.jsx("div",{className:Ft("absolute top-4 right-4 pointer-events-auto z-10",l),children:e.jsxs(H,{variant:"secondary",size:"sm",onClick:r,className:"bg-black/50 hover:bg-black/70 text-white border-0",children:[e.jsx(Bn,{className:"h-4 w-4 mr-2"}),"Show Script"]})});const ee={top:"top-0 pt-16",center:"top-1/2 -translate-y-1/2",bottom:"bottom-0 pb-24"};return e.jsxs("div",{className:Ft("absolute inset-0 pointer-events-none",l),children:[D!==null&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center z-20 pointer-events-none",children:e.jsxs("div",{className:"flex flex-col items-center gap-2",children:[e.jsx("div",{className:"text-white font-bold drop-shadow-lg animate-scale-in",style:{fontSize:"96px",lineHeight:1,textShadow:"0 4px 16px rgba(0,0,0,0.8)"},children:D},D),e.jsx("p",{className:"text-white/80 text-lg font-medium drop-shadow-md",children:"Get ready…"})]})}),e.jsx("div",{className:Ft("absolute left-0 right-0 h-[60%] overflow-hidden pointer-events-auto",ee[j],D!==null&&"opacity-30"),style:{opacity:D!==null?.3:b},children:e.jsxs("div",{ref:o,className:Ft("mx-auto max-w-2xl px-6 overflow-y-auto scrollbar-hide h-full",k&&"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:[e.jsx("div",{className:"h-full",style:{minHeight:"100%"}}),e.jsx("p",{className:"text-white text-center font-medium drop-shadow-lg",style:{fontSize:`${y}px`,lineHeight:_,textShadow:"0 2px 4px rgba(0,0,0,0.8)"},children:s}),e.jsx("div",{className:"h-full"})]})}),e.jsxs("div",{className:"absolute top-4 right-4 flex items-center gap-2 pointer-events-auto",children:[e.jsxs(gl,{children:[e.jsx(xl,{asChild:!0,children:e.jsx(H,{variant:"secondary",size:"icon",className:"h-9 w-9 bg-black/50 hover:bg-black/70 text-white border-0",children:e.jsx(Go,{className:"h-4 w-4"})})}),e.jsx(il,{className:"w-72",side:"left",align:"start",children:e.jsxs("div",{className:"space-y-4",children:[e.jsx("h4",{className:"font-medium",children:"Teleprompter Settings"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ue,{className:"text-xs",children:"Scroll Speed"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:x})]}),e.jsx(f1,{value:[x],onValueChange:([Z])=>T("scrollSpeed",Z),min:1,max:100,step:1})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ue,{className:"text-xs",children:"Font Size"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[y,"px"]})]}),e.jsx(f1,{value:[y],onValueChange:([Z])=>T("fontSize",Z),min:16,max:48,step:2})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ue,{className:"text-xs",children:"Line Spacing"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:_.toFixed(1)})]}),e.jsx(f1,{value:[_*10],onValueChange:([Z])=>T("lineHeight",Z/10),min:12,max:24,step:1})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ue,{className:"text-xs",children:"Opacity"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[Math.round(b*100),"%"]})]}),e.jsx(f1,{value:[b*100],onValueChange:([Z])=>T("opacity",Z/100),min:30,max:100,step:5})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{className:"text-xs",children:"Position"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(H,{variant:j==="top"?"default":"outline",size:"sm",onClick:()=>T("position","top"),children:e.jsx(cx,{className:"h-4 w-4"})}),e.jsx(H,{variant:j==="center"?"default":"outline",size:"sm",onClick:()=>T("position","center"),children:e.jsx(g_,{className:"h-4 w-4"})}),e.jsx(H,{variant:j==="bottom"?"default":"outline",size:"sm",onClick:()=>T("position","bottom"),children:e.jsx(Io,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ue,{className:"text-xs",children:"Mirror Mode"}),e.jsx(Or,{checked:k,onCheckedChange:Z=>T("isMirrored",Z)})]})]})})]}),e.jsx(H,{variant:"secondary",size:"icon",onClick:$,className:"h-9 w-9 bg-black/50 hover:bg-black/70 text-white border-0",children:E?e.jsx(Hf,{className:"h-4 w-4"}):e.jsx(El,{className:"h-4 w-4"})}),e.jsx(H,{variant:"secondary",size:"icon",onClick:O,className:"h-9 w-9 bg-black/50 hover:bg-black/70 text-white border-0",children:e.jsx(qy,{className:"h-4 w-4"})}),e.jsxs(H,{variant:"secondary",size:"sm",onClick:r,className:"bg-black/50 hover:bg-black/70 text-white border-0",children:[e.jsx($f,{className:"h-4 w-4 mr-2"}),"Hide"]})]})]})}function kFs({onSelectScript:s,onCreateNew:t,selectedScriptId:r,className:n}){const{toast:a}=li(),[i,l]=S.useState(""),[o,c]=S.useState(null),[d,h]=S.useState("levelup"),{data:m,isLoading:p}=b8s(),{data:x,isLoading:y}=_8s(),{data:_,isLoading:b}=w8s(),j=j8s(),k=S.useMemo(()=>x?x.filter(R=>{const z=!i||R.title.toLowerCase().includes(i.toLowerCase())||R.script_text.toLowerCase().includes(i.toLowerCase())||R.tags.some($=>$.toLowerCase().includes(i.toLowerCase())),O=!o||R.category_id===o;return z&&O}):[],[x,i,o]),T=S.useMemo(()=>_?_.filter(R=>!i||R.title.toLowerCase().includes(i.toLowerCase())||R.script_text.toLowerCase().includes(i.toLowerCase())):[],[_,i]),E=R=>{s({title:R.title,text:R.script_text})},A=async R=>{try{await j.mutateAsync(R),a({title:"Script saved to My Scripts"})}catch{a({title:"Failed to save script",variant:"destructive"})}},D=p||y||b;return e.jsxs("div",{className:Ft("flex flex-col h-full",n),children:[e.jsx("div",{className:"p-4 border-b",children:e.jsxs("div",{className:"relative",children:[e.jsx(Mn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Se,{placeholder:"Search scripts...",value:i,onChange:R=>l(R.target.value),className:"pl-9"})]})}),e.jsxs(ta,{value:d,onValueChange:R=>h(R),className:"flex-1 flex flex-col",children:[e.jsxs(Qn,{className:"mx-4 mt-4 grid grid-cols-2",children:[e.jsxs(ts,{value:"levelup",children:[e.jsx(kn,{className:"h-4 w-4 mr-2"}),"LevelUp Scripts"]}),e.jsxs(ts,{value:"my-scripts",children:[e.jsx(Uy,{className:"h-4 w-4 mr-2"}),"My Scripts"]})]}),e.jsxs(cs,{value:"levelup",className:"flex-1 flex flex-col mt-0 p-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-2 mb-4",children:[e.jsx(Xe,{variant:o?"outline":"default",className:"cursor-pointer",onClick:()=>c(null),children:"All"}),m==null?void 0:m.map(R=>e.jsx(Xe,{variant:o===R.id?"default":"outline",className:"cursor-pointer",onClick:()=>c(R.id),children:R.name},R.id))]}),e.jsx(Ci,{className:"flex-1 max-h-[50vh]",children:D?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(is,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):k.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(kn,{className:"h-12 w-12 mx-auto mb-2 opacity-50"}),e.jsx("p",{children:"No scripts found"})]}):e.jsx("div",{className:"space-y-2",children:k.map(R=>e.jsxs(ke,{className:Ft("cursor-pointer hover:bg-accent/50 transition-colors",r===R.id&&"ring-2 ring-primary"),onClick:()=>E(R),children:[e.jsx(Ot,{className:"p-3",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(zt,{className:"text-sm font-medium truncate",children:R.title}),R.category&&e.jsx(Xe,{variant:"secondary",className:"mt-1 text-xs",children:R.category.name})]}),e.jsxs("div",{className:"flex items-center gap-1 ml-2",children:[e.jsx(H,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:z=>{z.stopPropagation(),A(R)},children:e.jsx(Uy,{className:"h-4 w-4"})}),e.jsx($a,{className:"h-4 w-4 text-muted-foreground"})]})]})}),e.jsx(Oe,{className:"p-3 pt-0",children:e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2",children:R.script_text})})]},R.id))})})]}),e.jsxs(cs,{value:"my-scripts",className:"flex-1 flex flex-col mt-0 p-4",children:[t&&e.jsxs(H,{variant:"outline",className:"mb-4",onClick:t,children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Create New Script"]}),e.jsx(Ci,{className:"flex-1 max-h-[50vh]",children:b?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(is,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):T.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Uy,{className:"h-12 w-12 mx-auto mb-2 opacity-50"}),e.jsx("p",{children:"No saved scripts"}),e.jsx("p",{className:"text-sm mt-1",children:"Save LevelUp scripts or create your own"})]}):e.jsx("div",{className:"space-y-2",children:T.map(R=>e.jsxs(ke,{className:Ft("cursor-pointer hover:bg-accent/50 transition-colors",r===R.id&&"ring-2 ring-primary"),onClick:()=>E(R),children:[e.jsx(Ot,{className:"p-3",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(zt,{className:"text-sm font-medium truncate",children:R.title}),e.jsx("div",{className:"flex items-center gap-2 mt-1",children:R.is_custom?e.jsx(Xe,{variant:"outline",className:"text-xs",children:"Custom"}):e.jsx(Xe,{variant:"secondary",className:"text-xs",children:"Saved"})})]}),e.jsx($a,{className:"h-4 w-4 text-muted-foreground ml-2"})]})}),e.jsx(Oe,{className:"p-3 pt-0",children:e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2",children:R.script_text})})]},R.id))})})]})]})]})}function SFs({selectedTemplate:s,onSelect:t,contactName:r,saving:n=!1}){const[a,i]=S.useState(()=>{const o=iP(s);return new Set([o.category])}),l=o=>{i(c=>{const d=new Set(c);return d.has(o)?d.delete(o):d.add(o),d})};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ue,{className:"text-sm font-medium",children:"Share Page Template"}),n&&e.jsx(is,{className:"h-3 w-3 animate-spin text-muted-foreground"})]}),e.jsx("div",{className:"space-y-3",children:LVt.map(o=>{const c=DVt(o.id),d=a.has(o.id),h=c.some(m=>m.id===s);return e.jsxs(m0,{open:d,onOpenChange:()=>l(o.id),children:[e.jsxs(f0,{className:"flex items-center justify-between w-full p-2.5 rounded-lg bg-muted/50 hover:bg-muted transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium text-sm",children:o.name}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",c.length,")"]}),h&&!d&&e.jsx("span",{className:"text-xs bg-primary/10 text-primary px-1.5 py-0.5 rounded-full",children:"✓"})]}),e.jsx(Io,{className:Ft("h-4 w-4 text-muted-foreground transition-transform",d&&"rotate-180")})]}),e.jsx(p0,{className:"pt-2",children:e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2",children:c.map(m=>{const p=s===m.id;return e.jsxs("button",{type:"button",onClick:()=>t(m.id),disabled:n,className:Ft("relative rounded-lg border-2 p-2.5 text-left transition-all hover:shadow-sm disabled:opacity-50 disabled:cursor-not-allowed",p?"border-primary ring-1 ring-primary/20 bg-primary/5":"border-muted hover:border-muted-foreground/30"),children:[p&&e.jsx("div",{className:"absolute top-1 right-1 w-4 h-4 rounded-full bg-primary flex items-center justify-center",children:e.jsx(va,{className:"h-2.5 w-2.5 text-primary-foreground"})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"opacity-70 shrink-0",children:m.icon}),e.jsx("span",{className:"text-sm font-medium truncate",children:m.name})]})]},m.id)})})})]},o.id)})}),r&&s!=="default"&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:['Will show: "',iP(s).headerText(r),'"']})]})}function Nyt({open:s,onOpenChange:t,video:r,contactName:n,onTemplateUpdated:a}){const[i,l]=S.useState(r.page_template||"default"),[o,c]=S.useState(!1),[d,h]=S.useState(!1),[m,p]=S.useState(r.page_template||"default"),[x,y]=S.useState([]),[_,b]=S.useState(r.contact_id&&n?{id:r.contact_id,name:n,email:null}:null),[j,k]=S.useState(!1),[T,E]=S.useState(!1),A=r.share_token?`https://video.relevelup.com/${r.share_token}`:"";S.useEffect(()=>{s&&x.length===0&&D()},[s]);const D=async()=>{E(!0);try{const{data:re,error:ie}=await V.from("innercircle_contacts").select("id, first_name, last_name, email").order("first_name",{ascending:!0}).limit(500);if(ie)throw ie;const ce=(re||[]).map(ne=>({id:ne.id,name:[ne.first_name,ne.last_name].filter(Boolean).join(" ")||"Unnamed",email:ne.email||null}));y(ce)}catch(re){console.error("Failed to fetch contacts:",re)}finally{E(!1)}},R=async re=>{b(re),k(!1),c(!0);try{const{error:ie}=await V.from("agent_videos").update({contact_id:(re==null?void 0:re.id)||null,recipient_name:(re==null?void 0:re.name)||null}).eq("id",r.id);if(ie)throw ie;he.success(re?`Assigned to ${re.name}`:"Contact removed"),a==null||a()}catch(ie){console.error("Failed to update contact:",ie),he.error("Failed to update contact")}finally{c(!1)}},z=async re=>{l(re),c(!0);try{const{error:ie}=await V.from("agent_videos").update({page_template:re}).eq("id",r.id);if(ie)throw ie;p(re),he.success("Template saved!"),a==null||a()}catch(ie){console.error("Failed to save template:",ie),he.error("Failed to save template"),l(m)}finally{c(!1)}},O=(_==null?void 0:_.name)||null,$=()=>{const re=r.title||"Video Message",ie=r.share_token?`https://video.relevelup.com/thumb/${r.share_token}`:r.thumbnail_url||"";return``},ee=async()=>{if(!r.thumbnail_url){he.error("Video thumbnail not available yet");return}const re=$(),ie=`Watch: ${r.title||"Video Message"} ${A}`;try{const ce=new Blob([re],{type:"text/html"}),ne=new Blob([ie],{type:"text/plain"}),le=new ClipboardItem({"text/html":ce,"text/plain":ne});await navigator.clipboard.write([le]),he.success("Copied! Paste into Gmail - the thumbnail will appear after sending.")}catch{await navigator.clipboard.writeText(ie+` `+re),he.success("Copied! Paste into your email.")}},Z=async()=>{await navigator.clipboard.writeText(A),h(!0),he.success("Share link copied!"),setTimeout(()=>h(!1),2e3)},J=()=>{const ie=iP(i).headerText(O),ce=i==="default"?`Check out this video: ${A}`:`${ie} Check out this special video: ${A}`;window.open(`sms:?body=${encodeURIComponent(ce)}`,"_self")},K=()=>{const re=iP(i),ie=re.headerText(O),ce=i==="default"?r.title||"Video Message":ie,ne=`${re.subText} Watch the video: ${A}`,le=_!=null&&_.email?encodeURIComponent(_.email):"";window.open(`mailto:${le}?subject=${encodeURIComponent(ce)}&body=${encodeURIComponent(ne)}`,"_self")};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(Cs,{children:[e.jsxs(Ns,{className:"flex items-center gap-2",children:[e.jsx(Jo,{className:"h-5 w-5"}),"Share Video"]}),e.jsx(nn,{children:"Choose a themed page template and share your video"})]}),e.jsxs("div",{className:"space-y-6 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{className:"text-sm font-medium",children:"Personalize for Contact (Optional)"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(gl,{open:j,onOpenChange:k,children:[e.jsx(xl,{asChild:!0,children:e.jsxs(H,{variant:"outline",role:"combobox","aria-expanded":j,className:"flex-1 justify-between",disabled:o,children:[_?e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(io,{className:"h-4 w-4 text-muted-foreground"}),_.name]}):e.jsx("span",{className:"text-muted-foreground",children:"Select a contact..."}),e.jsx(d0,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(il,{className:"w-[300px] p-0",align:"start",children:e.jsxs(k0,{children:[e.jsx(S0,{placeholder:"Search contacts..."}),e.jsxs(C0,{children:[e.jsx(T0,{children:T?"Loading...":"No contacts found."}),e.jsx(E0,{children:x.map(re=>e.jsxs(fg,{value:re.name,onSelect:()=>R(re),children:[e.jsx(va,{className:Ft("mr-2 h-4 w-4",(_==null?void 0:_.id)===re.id?"opacity-100":"opacity-0")}),re.name]},re.id))})]})]})})]}),_&&e.jsx(H,{variant:"ghost",size:"icon",onClick:()=>R(null),disabled:o,className:"shrink-0",children:e.jsx(Rr,{className:"h-4 w-4"})})]}),_&&i!=="default"&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:['Page will show: "',iP(i).headerText(_.name),'"']})]}),e.jsx(SFs,{selectedTemplate:i,onSelect:z,contactName:O,saving:o}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Share Link"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Se,{value:A,readOnly:!0,className:"font-mono text-sm"}),e.jsx(H,{onClick:Z,variant:d?"default":"outline",className:"shrink-0 gap-2",children:d?e.jsxs(e.Fragment,{children:[e.jsx(va,{className:"h-4 w-4"}),"Copied"]}):e.jsxs(e.Fragment,{children:[e.jsx(ui,{className:"h-4 w-4"}),"Copy"]})})]})]}),r.thumbnail_url&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Share for Email"}),e.jsxs(H,{variant:"outline",className:"w-full gap-2",onClick:ee,children:[e.jsx(wl,{className:"h-4 w-4"}),"Copy with Thumbnail (for Gmail)"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Paste into Gmail to embed a clickable video thumbnail"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Quick Share"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(H,{variant:"outline",className:"flex-1 gap-2",onClick:J,children:[e.jsx(Gi,{className:"h-4 w-4"}),"Text"]}),e.jsxs(H,{variant:"outline",className:"flex-1 gap-2",onClick:K,children:[e.jsx(er,{className:"h-4 w-4"}),"Email"]})]})]})]}),e.jsx(wn,{children:e.jsx(H,{variant:"outline",onClick:()=>t(!1),children:"Done"})})]})})}function CFs(){var Qe;const s=Fr(),[t]=Ed(),{toast:r}=li(),n=t.get("contact_id"),a=t.get("task_id"),{canRecord:i,remainingMb:l,usagePercent:o,isNearLimit:c,storage:d}=Wgt(),{data:h}=Cp(),m=Cj(),p=T8s(),[x,y]=S.useState("record"),[_,b]=S.useState(""),[j,k]=S.useState(!1),[T,E]=S.useState(!1),[A,D]=S.useState(!1),[R,z]=S.useState(null),[O,$]=S.useState(0),[ee,Z]=S.useState(0),[J,K]=S.useState(null),[re,ie]=S.useState(null),[ce,ne]=S.useState(n||""),[le,be]=S.useState(""),[fe,je]=S.useState(""),[ve,We]=S.useState(null),[Ve,Le]=S.useState(null),[Me,ze]=S.useState(null),[Pe,Ie]=S.useState(!1),De=S.useCallback(async(Ne,$e)=>{z(Ne),y("uploading");try{const{videoId:it,uploadUrl:Je}=await tM(le||"Quick Video Touch");K(it);const{apiKey:st}=await sM(it),mt=new XMLHttpRequest;mt.upload.onprogress=Et=>{Et.lengthComputable&&$(Et.loaded/Et.total*100)},await new Promise((Et,hs)=>{mt.onload=()=>{mt.status>=200&&mt.status<300?Et():hs(new Error(`Upload failed: ${mt.status}`))},mt.onerror=()=>hs(new Error("Upload failed")),mt.open("PUT",Je),mt.setRequestHeader("AccessKey",st),mt.send(Ne)}),y("processing");let wt=0;const at=Date.now(),rt=90*1e3;for(;wt<4;){if(await new Promise(hs=>setTimeout(hs,3e3)),Date.now()-at>rt){const hs=Ne.size/1048576,Is=`https://iframe.mediadelivery.net/play/${it}/${it}`;await m.mutateAsync({bunny_video_id:it,playback_url:Is,file_size_mb:hs,title:le||"Quick Video Touch",notes:fe||void 0,contact_id:ce&&ce!=="none"?ce:void 0,status:"processing",touch_type:"video_touch"}),r({title:"Video saved — still processing",description:'Your video has been saved and will appear in your library with a "processing" badge. It will be ready to share once encoding completes (usually within a few minutes).',duration:8e3}),s("/mission-control/video-library");return}const Et=await F_(it);if(wt=Et.status,Z(Et.encodeProgress||0),wt===4)ie({playbackUrl:Et.directPlayUrl,thumbnailUrl:Et.thumbnailUrl,previewUrl:Et.previewUrl||null,duration:Et.length||$e,fileSizeMb:(Et.storageSize||Ne.size)/(1024*1024)});else if(wt===5||wt===6)throw new Error("Video processing failed")}y("details")}catch(it){console.error("Upload error:",it),r({title:"Upload failed",description:"Please try recording again.",variant:"destructive"}),y("record")}},[le,r]),pe=async()=>{if(!(!J||!re))try{const Ne=ce&&ce!=="none"?ce:null,$e=await m.mutateAsync({bunny_video_id:J,contact_id:Ne,playback_url:re.playbackUrl,thumbnail_url:re.thumbnailUrl,preview_url:re.previewUrl,duration_seconds:re.duration,file_size_mb:re.fileSizeMb,title:le||"Quick Video Touch",notes:fe,task_id:a||null,status:"ready"});We($e.id),Le($e.share_token||null),Ne&&await p.mutateAsync({contactId:Ne,videoId:$e.id,notes:fe}),r({title:"Video saved successfully!"}),y("share")}catch(Ne){console.error("Save video error:",Ne),r({title:"Failed to save video",description:(Ne==null?void 0:Ne.message)||"Please try again.",variant:"destructive"})}},tt=(Ne,$e)=>{navigator.clipboard.writeText($e),ze(Ne),setTimeout(()=>ze(null),2e3),r({title:"Copied to clipboard!"})},ge=()=>Ve?`https://video.relevelup.com/${Ve}`:(re==null?void 0:re.playbackUrl)||"",ct=()=>{const Ne=h==null?void 0:h.find(mt=>mt.id===ce),$e=Ne?`${Ne.first_name}`:"",it=(Ne==null?void 0:Ne.phone)||"",Je=(Ne==null?void 0:Ne.email)||"",st=ge();return{text:`Hey${$e?` ${$e}`:""}! I recorded a quick video for you: ${st}`,link:st,contactPhone:it,contactEmail:Je}},Ue=()=>{const{text:Ne,contactPhone:$e}=ct(),it=$e?`sms:${$e}?body=${encodeURIComponent(Ne)}`:`sms:?body=${encodeURIComponent(Ne)}`;window.open(it,"_self")},et=()=>{const{link:Ne,contactEmail:$e}=ct(),it="Check out this video",Je=`I recorded a quick video for you: ${Ne}`,st=$e?`mailto:${$e}?subject=${encodeURIComponent(it)}&body=${encodeURIComponent(Je)}`:`mailto:?subject=${encodeURIComponent(it)}&body=${encodeURIComponent(Je)}`;window.open(st,"_self")};return i?e.jsx(Ss,{title:"QuickVid",children:e.jsxs("div",{className:"max-w-4xl mx-auto space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(H,{variant:"ghost",size:"icon",onClick:()=>s(-1),children:e.jsx(za,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"QuickVid"}),e.jsx("p",{className:"text-muted-foreground",children:"Record a personal video message"})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(H,{variant:"outline",size:"sm",onClick:()=>s("/mission-control/video-library"),className:"gap-1.5",children:[e.jsx(kn,{className:"h-4 w-4"}),"Video Library"]}),c&&e.jsxs("div",{className:"text-right",children:[e.jsxs("p",{className:"text-sm text-warning",children:["Storage: ",o.toFixed(0),"% used"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[l.toFixed(0)," MB remaining"]})]})]})]}),x==="record"&&e.jsxs("div",{className:"grid gap-6 lg:grid-cols-3",children:[e.jsxs("div",{className:"lg:col-span-2",children:[e.jsx(aD,{maxDurationSeconds:600,onRecordingComplete:De,onRecordingStateChange:D,className:"w-full",teleprompterContent:j&&_&&e.jsx(c6e,{text:_,isVisible:j,onToggleVisibility:()=>k(!1),isRecording:A,startCountdown:!1})}),!j&&_&&e.jsxs(H,{variant:"outline",className:"mt-4",onClick:()=>k(!0),children:[e.jsx(kn,{className:"h-4 w-4 mr-2"}),"Show Teleprompter"]})]}),e.jsxs(ke,{className:"lg:col-span-1",children:[e.jsx(Ot,{className:"pb-2",children:e.jsx(zt,{className:"text-lg",children:"Teleprompter Script"})}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsx(vr,{placeholder:"Type or paste your script here...",value:_,onChange:Ne=>b(Ne.target.value),rows:6}),e.jsxs($S,{open:T,onOpenChange:E,children:[e.jsx(b5e,{asChild:!0,children:e.jsxs(H,{variant:"outline",className:"w-full",children:[e.jsx(kn,{className:"h-4 w-4 mr-2"}),"Browse Scripts"]})}),e.jsxs(vj,{side:"right",className:"w-[400px] sm:w-[540px] p-0",children:[e.jsx(US,{className:"p-4 border-b",children:e.jsx(qS,{children:"Select a Script"})}),e.jsx(kFs,{onSelectScript:Ne=>{b(Ne.text),E(!1),k(!0)},className:"h-[calc(100vh-80px)]"})]})]}),_&&e.jsx(H,{className:"w-full",onClick:()=>k(!0),children:"Use Script"})]})]})]}),x==="uploading"&&e.jsx(ke,{className:"max-w-md mx-auto",children:e.jsxs(Oe,{className:"pt-6 text-center",children:[e.jsx(Ea,{className:"h-12 w-12 mx-auto mb-4 text-primary animate-pulse"}),e.jsx("h2",{className:"text-lg font-semibold mb-2",children:"Uploading Video..."}),e.jsx(Mi,{value:O,className:"mb-2"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[O.toFixed(0),"%"]})]})}),x==="processing"&&e.jsx(ke,{className:"max-w-md mx-auto",children:e.jsxs(Oe,{className:"pt-6 text-center space-y-4",children:[e.jsx(is,{className:"h-12 w-12 mx-auto mb-4 text-primary animate-spin"}),e.jsx("h2",{className:"text-lg font-semibold mb-2",children:"Processing Video..."}),e.jsx(Mi,{value:ee,className:"mb-2"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[ee.toFixed(0),"%"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:`This usually takes 30-60 seconds. If it takes longer, we'll auto-save your video and you can find it in your Video Library — look for the "processing" badge.`})]})}),x==="details"&&e.jsxs(ke,{className:"max-w-lg mx-auto",children:[e.jsx(Ot,{children:e.jsx(zt,{children:"Video Details"})}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ue,{children:"Title"}),e.jsx(Se,{value:le,onChange:Ne=>be(Ne.target.value),placeholder:"Quick Video Touch"})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Attach to Contact (Optional)"}),e.jsxs(Bs,{value:ce,onValueChange:ne,children:[e.jsx(Os,{children:e.jsx(Us,{placeholder:"No contact - use anywhere"})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"none",children:e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(Jo,{className:"h-4 w-4"}),"No contact - use anywhere"]})}),h==null?void 0:h.map(Ne=>e.jsx(pt,{value:Ne.id,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(io,{className:"h-4 w-4"}),Ne.first_name," ",Ne.last_name]})},Ne.id))]})]})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Notes"}),e.jsx(vr,{value:fe,onChange:Ne=>je(Ne.target.value),placeholder:"Add notes about this video...",rows:3})]}),e.jsxs(H,{className:"w-full",onClick:pe,disabled:m.isPending,children:[m.isPending&&e.jsx(is,{className:"h-4 w-4 mr-2 animate-spin"}),"Save Video"]})]})]}),x==="share"&&e.jsxs(ke,{className:"max-w-lg mx-auto",children:[e.jsx(Ot,{children:e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(va,{className:"h-5 w-5 text-green-500"}),"Video Saved!"]})}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsx("p",{className:"text-muted-foreground",children:"Share your video with one click:"}),e.jsxs("div",{className:"grid gap-3",children:[e.jsxs(H,{variant:"outline",className:"justify-start",onClick:Ue,children:[e.jsx(Gi,{className:"h-4 w-4 mr-2"}),"Text Contact Video"]}),e.jsxs(H,{variant:"outline",className:"justify-start",onClick:et,children:[e.jsx(er,{className:"h-4 w-4 mr-2"}),"Email Contact Video"]}),e.jsxs(H,{variant:"outline",className:"justify-start",onClick:()=>tt("link",ct().link),children:[e.jsx(Jo,{className:"h-4 w-4 mr-2"}),"Copy Video Link",Me==="link"&&e.jsx(va,{className:"h-4 w-4 ml-auto text-green-500"})]}),e.jsxs(H,{variant:"outline",className:"justify-start",onClick:()=>Ie(!0),children:[e.jsx(pl,{className:"h-4 w-4 mr-2"}),"Send with Page Template"]})]}),e.jsxs("div",{className:"flex gap-3 pt-4",children:[e.jsx(H,{variant:"outline",onClick:()=>s("/mission-control/video-library"),children:"View Library"}),e.jsx(H,{onClick:()=>{y("record"),z(null),K(null),ie(null)},children:"Record Another"})]})]})]}),ve&&Ve&&e.jsx(Nyt,{open:Pe,onOpenChange:Ie,video:{id:ve,share_token:Ve,title:le||null,contact_id:ce||null,thumbnail_url:(re==null?void 0:re.thumbnailUrl)||null},contactName:((Qe=h==null?void 0:h.find(Ne=>Ne.id===ce))==null?void 0:Qe.first_name)||null})]})}):e.jsx(Ss,{title:"QuickVid",children:e.jsxs("div",{className:"max-w-2xl mx-auto text-center py-12",children:[e.jsx(uu,{className:"h-16 w-16 text-destructive mx-auto mb-4"}),e.jsx("h1",{className:"text-2xl font-bold mb-2",children:"Storage Limit Reached"}),e.jsx("p",{className:"text-muted-foreground mb-6",children:"You've reached your video storage limit. Delete videos from your library to record more."}),e.jsx(H,{onClick:()=>s("/mission-control/video-library"),children:"Open Video Library"})]})})}function TFs({open:s,onOpenChange:t,video:r,gmailEmail:n,signedThumbnailUrl:a,onSendComplete:i}){const[l,o]=S.useState([]),[c,d]=S.useState(null),[h,m]=S.useState(!1),[p,x]=S.useState(!1),[y,_]=S.useState(""),[b,j]=S.useState(""),[k,T]=S.useState(""),[E,A]=S.useState(!1),D=$gt(),R=r.share_token?`https://video.relevelup.com/share/video/${r.share_token}`:"",z=r.share_token?`https://video.relevelup.com/thumb/${r.share_token}`:a||r.thumbnail_url||"",O=r.title||"Video Message";S.useEffect(()=>{s&&l.length===0&&$()},[s]),S.useEffect(()=>{if(s&&(j(`I recorded a video for you — ${O}`),T("Hey! I recorded a quick video just for you. Click below to watch it:"),d(null),_(""),r.contact_id)){const ie=l.find(ce=>ce.id===r.contact_id);ie&&(d(ie),_(ie.email||""))}},[s,r.contact_id,l]);const $=async()=>{x(!0);try{const{data:ie,error:ce}=await V.from("innercircle_contacts").select("id, first_name, last_name, email").order("first_name",{ascending:!0}).limit(500);if(ce)throw ce;o(ie||[])}catch{console.error("Failed to fetch contacts")}finally{x(!1)}},ee=ie=>{d(ie),m(!1),_(ie.email||""),T(`Hey ${ie.first_name}! I recorded a quick video just for you. Click below to watch it:`),j(`I recorded a video for you — ${O}`)},Z=()=>{d(null),_(""),T("Hey! I recorded a quick video just for you. Click below to watch it:")},J=ie=>`${ie.first_name} ${ie.last_name||""}`.trim(),K=ie=>{const ce=k.split(/\n\n+/).map(be=>`

${be.replace(/\n/g,"
")}

`).join(""),ne=ie?qgt(ie):R,le=ie?``:"";return`
${ce}

▶ Watch Video

${le}
`},re=async()=>{var ie;if(!y){he.error("Please enter a recipient email");return}if(!R){he.error("Video does not have a share link");return}A(!0);try{let ce;try{const je=c?J(c):y.split("@")[0];ce=(await D.mutateAsync({video_id:r.id,recipient_email:y,recipient_name:je,contact_id:(c==null?void 0:c.id)||null,sent_via:"gmail"})).share_token}catch(je){console.warn("Failed to create tracking record, sending without tracking:",je)}const ne=K(ce),{data:le,error:be}=await V.functions.invoke("gmail-send",{body:{to:y,subject:b,body:ne,contactId:(c==null?void 0:c.id)||null}});let fe=null;if(be&&((ie=be.context)!=null&&ie.json))try{fe=await be.context.json()}catch{}if((fe==null?void 0:fe.error)==="insufficient_scope"||(le==null?void 0:le.error)==="insufficient_scope"){he.error((fe==null?void 0:fe.message)||"Gmail is missing send permission. Please disconnect and reconnect Gmail, allowing 'Send email on your behalf'.",{duration:1e4});return}if(be)throw new Error((fe==null?void 0:fe.message)||be.message);if(!(le!=null&&le.success))throw new Error((le==null?void 0:le.error)||"Failed to send");he.success("Video email sent!"),t(!1),i==null||i()}catch(ce){console.error("Gmail send error:",ce),he.error("Failed to send: "+(ce instanceof Error?ce.message:"Unknown error"))}finally{A(!1)}};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"sm:max-w-[560px] max-h-[90vh] overflow-y-auto",children:[e.jsxs(Cs,{children:[e.jsxs(Ns,{className:"flex items-center gap-2",children:[e.jsx(er,{className:"h-5 w-5 text-red-500"}),"Send Video via Gmail"]}),n&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Sending from ",e.jsx("span",{className:"font-medium",children:n})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{children:"Send to Contact"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(gl,{open:h,onOpenChange:m,children:[e.jsx(xl,{asChild:!0,children:e.jsxs(H,{variant:"outline",role:"combobox",className:"flex-1 justify-between",children:[c?e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(io,{className:"h-4 w-4 text-muted-foreground"}),J(c),c.email&&e.jsxs("span",{className:"text-muted-foreground text-xs",children:["(",c.email,")"]})]}):e.jsx("span",{className:"text-muted-foreground",children:"Select a contact..."}),e.jsx(d0,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(il,{className:"w-[350px] p-0",align:"start",children:e.jsxs(k0,{children:[e.jsx(S0,{placeholder:"Search contacts..."}),e.jsxs(C0,{children:[e.jsx(T0,{children:p?"Loading...":"No contacts found."}),e.jsx(E0,{children:l.filter(ie=>ie.email).map(ie=>e.jsxs(fg,{value:`${ie.first_name} ${ie.last_name||""} ${ie.email||""}`,onSelect:()=>ee(ie),children:[e.jsx(va,{className:Ft("mr-2 h-4 w-4",(c==null?void 0:c.id)===ie.id?"opacity-100":"opacity-0")}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:J(ie)}),e.jsx("div",{className:"text-xs text-muted-foreground",children:ie.email})]})]},ie.id))})]})]})})]}),c&&e.jsx(H,{variant:"ghost",size:"icon",onClick:Z,className:"shrink-0",children:e.jsx(Rr,{className:"h-4 w-4"})})]})]}),!c&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{htmlFor:"video-to",children:"Or type email address"}),e.jsx(Se,{id:"video-to",value:y,onChange:ie=>_(ie.target.value),placeholder:"recipient@example.com",type:"email"})]}),e.jsx(Qo,{}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{htmlFor:"video-subject",children:"Subject"}),e.jsx(Se,{id:"video-subject",value:b,onChange:ie=>j(ie.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{htmlFor:"video-message",children:"Personal Message"}),e.jsx(vr,{id:"video-message",value:k,onChange:ie=>T(ie.target.value),rows:4,className:"resize-y"})]}),e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-3 space-y-2",children:[e.jsx(ue,{className:"text-xs text-muted-foreground",children:"Video Preview (embedded in email)"}),e.jsxs("div",{className:"relative rounded-lg overflow-hidden bg-black",style:{maxWidth:320},children:[z?e.jsx("img",{src:z,alt:O,className:"w-full aspect-video object-cover"}):e.jsx("div",{className:"w-full aspect-video flex items-center justify-center bg-muted",children:e.jsx(El,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx("div",{className:"w-10 h-10 rounded-full bg-white/80 flex items-center justify-center shadow",children:e.jsx(El,{className:"h-5 w-5 text-primary ml-0.5"})})})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Recipients will see the thumbnail with a play button. Clicking opens the video page."})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(H,{variant:"outline",onClick:()=>t(!1),disabled:E,children:"Cancel"}),e.jsxs(H,{onClick:re,disabled:E||!y||!b,className:"gap-2",children:[E?e.jsx(is,{className:"h-4 w-4 animate-spin"}):e.jsx(yn,{className:"h-4 w-4"}),E?"Sending...":"Send Video Email"]})]})]})]})})}const EFs=()=>{const{user:s}=Ms();return yt({queryKey:["team-videos",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:r}=await V.rpc("get_team_videos",{_user_id:s.id});if(r)throw r;return t||[]},enabled:!!s})};function AFs({recipient:s}){return s.watched_at?e.jsxs(Xe,{className:"bg-emerald-100 text-emerald-800 text-[10px]",children:[e.jsx(El,{className:"h-2.5 w-2.5 mr-0.5"}),"Watched"]}):s.clicked_at?e.jsxs(Xe,{className:"bg-blue-100 text-blue-800 text-[10px]",children:[e.jsx(lm,{className:"h-2.5 w-2.5 mr-0.5"}),"Clicked"]}):s.opened_at?e.jsxs(Xe,{className:"bg-amber-100 text-amber-800 text-[10px]",children:[e.jsx(Bn,{className:"h-2.5 w-2.5 mr-0.5"}),"Opened"]}):e.jsxs(Xe,{variant:"outline",className:"text-[10px]",children:[e.jsx(yn,{className:"h-2.5 w-2.5 mr-0.5"}),"Sent"]})}function MFs({open:s,onOpenChange:t,videoId:r,videoTitle:n}){const{data:a=[],isLoading:i}=r8s(r);return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-2xl max-h-[80vh]",children:[e.jsx(Cs,{children:e.jsxs(Ns,{className:"flex items-center gap-2",children:[e.jsx(Bo,{className:"h-5 w-5"}),"Send Analytics: ",n]})}),i?e.jsx("div",{className:"space-y-2",children:[...Array(3)].map((l,o)=>e.jsx(Ks,{className:"h-12 w-full"},o))}):a.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"No recipients tracked for this video yet."}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-3 gap-3 mb-4",children:[e.jsxs("div",{className:"text-center p-2 rounded-lg bg-muted/50",children:[e.jsx("div",{className:"text-lg font-bold",children:a.length}),e.jsx("div",{className:"text-[10px] text-muted-foreground",children:"Sent"})]}),e.jsxs("div",{className:"text-center p-2 rounded-lg bg-amber-50",children:[e.jsx("div",{className:"text-lg font-bold text-amber-700",children:a.filter(l=>l.opened_at).length}),e.jsx("div",{className:"text-[10px] text-muted-foreground",children:"Opened"})]}),e.jsxs("div",{className:"text-center p-2 rounded-lg bg-blue-50",children:[e.jsx("div",{className:"text-lg font-bold text-blue-700",children:a.filter(l=>l.clicked_at).length}),e.jsx("div",{className:"text-[10px] text-muted-foreground",children:"Clicked"})]})]}),e.jsx(Ci,{className:"h-[400px]",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Vs,{children:[e.jsx(At,{children:"Recipient"}),e.jsx(At,{children:"Status"}),e.jsx(At,{children:"Sent"}),e.jsx(At,{children:"Last Activity"})]})}),e.jsx(da,{children:a.map(l=>e.jsxs(Vs,{children:[e.jsx(gt,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:l.recipient_name||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:l.recipient_email})]})}),e.jsx(gt,{children:e.jsx(AFs,{recipient:l})}),e.jsx(gt,{className:"text-xs text-muted-foreground",children:As(new Date(l.sent_at),"MMM d, h:mm a")}),e.jsx(gt,{className:"text-xs text-muted-foreground",children:l.last_activity_at?Hl(new Date(l.last_activity_at),{addSuffix:!0}):"—"})]},l.id))})]})})]})]})})}function IFs(){const{data:s,isLoading:t}=n8s(),{data:r=[],isLoading:n}=a8s(),[a,i]=S.useState(null),l=t||n,o=r.reduce((c,d)=>{const h=d.agent_videos,m=(h==null?void 0:h.id)||d.video_id;return c[m]||(c[m]={videoId:m,title:(h==null?void 0:h.title)||"Untitled",thumbnailUrl:h==null?void 0:h.thumbnail_url,recipients:[]}),c[m].recipients.push(d),c},{});return l?e.jsx("div",{className:"space-y-4",children:e.jsx("div",{className:"grid gap-4 md:grid-cols-4",children:[...Array(4)].map((c,d)=>e.jsxs(ke,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsx(Ks,{className:"h-4 w-20"})}),e.jsx(Oe,{children:e.jsx(Ks,{className:"h-8 w-16"})})]},d))})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 grid-cols-3",children:[e.jsxs(ke,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(zt,{className:"text-sm font-medium",children:"Total Sent"}),e.jsx(yn,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Oe,{children:e.jsx("div",{className:"text-2xl font-bold",children:(s==null?void 0:s.totalSent)||0})})]}),e.jsxs(ke,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(zt,{className:"text-sm font-medium",children:"Open Rate"}),e.jsx(Bn,{className:"h-4 w-4 text-amber-500"})]}),e.jsxs(Oe,{children:[e.jsxs("div",{className:"text-2xl font-bold",children:[(s==null?void 0:s.openRate)||0,"%"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(s==null?void 0:s.totalOpened)||0," opened"]})]})]}),e.jsxs(ke,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(zt,{className:"text-sm font-medium",children:"Click Rate"}),e.jsx(lm,{className:"h-4 w-4 text-blue-500"})]}),e.jsxs(Oe,{children:[e.jsxs("div",{className:"text-2xl font-bold",children:[(s==null?void 0:s.clickRate)||0,"%"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(s==null?void 0:s.totalClicked)||0," clicked"]})]})]})]}),e.jsxs(ke,{children:[e.jsxs(Ot,{children:[e.jsx(zt,{className:"text-sm font-medium",children:"Send History by Video"}),e.jsx(Br,{children:"Click a video to see individual recipient tracking"})]}),e.jsx(Oe,{children:Object.keys(o).length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"No tracked sends yet. Send a video via Gmail to start tracking."}):e.jsx("div",{className:"space-y-2",children:Object.values(o).map(c=>{const d=c.recipients.filter(m=>m.opened_at).length,h=c.recipients.filter(m=>m.clicked_at).length;return e.jsxs("button",{onClick:()=>i({id:c.videoId,title:c.title}),className:"w-full flex items-center gap-3 p-3 rounded-lg border hover:bg-muted/50 transition-colors text-left",children:[e.jsx("div",{className:"h-10 w-16 rounded bg-muted overflow-hidden flex-shrink-0",children:c.thumbnailUrl?e.jsx("img",{src:c.thumbnailUrl,alt:"",className:"h-full w-full object-cover",referrerPolicy:"no-referrer",onError:m=>{const p=m.currentTarget;p.style.display="none",p.parentElement.innerHTML='
'}}):e.jsx("div",{className:"h-full w-full flex items-center justify-center",children:e.jsx(xn,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:c.title}),e.jsxs("div",{className:"flex items-center gap-3 mt-0.5",children:[e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(yn,{className:"h-3 w-3"})," ",c.recipients.length]}),e.jsxs("span",{className:"text-xs text-amber-600 flex items-center gap-1",children:[e.jsx(Bn,{className:"h-3 w-3"})," ",d]}),e.jsxs("span",{className:"text-xs text-blue-600 flex items-center gap-1",children:[e.jsx(lm,{className:"h-3 w-3"})," ",h]})]})]}),e.jsx(al,{className:"h-4 w-4 text-muted-foreground"})]},c.videoId)})})})]}),e.jsx(MFs,{open:!!a,onOpenChange:c=>!c&&i(null),videoId:(a==null?void 0:a.id)||null,videoTitle:(a==null?void 0:a.title)||""})]})}function PFs({previewSrc:s,thumbnailSrc:t,alt:r,isHovered:n}){const[a,i]=S.useState(!1),[l,o]=S.useState(!1),c=n&&s&&!a,d=t&&!l;return!d&&!c?e.jsx("div",{className:"w-full h-full flex items-center justify-center absolute inset-0 bg-muted",children:e.jsx(xn,{className:"h-12 w-12 text-muted-foreground"})}):e.jsxs(e.Fragment,{children:[d&&e.jsx("img",{src:t,alt:r,loading:"lazy",className:`w-full h-full object-cover absolute inset-0 transition-opacity duration-200 ${c?"opacity-0":"opacity-100"}`,onError:()=>o(!0)}),c&&e.jsx("img",{src:s,alt:r,className:"w-full h-full object-cover absolute inset-0",onError:()=>i(!0)})]})}function LFs({video:s,previewSrc:t,thumbnailSrc:r,onOpen:n,onDelete:a,onRename:i,onNavigateToContact:l,onGetEmbedCode:o,onCopyEmailHtml:c,onEmbedToCrm:d,onShareWithTemplate:h,onSendViaGmail:m,isGmailConnected:p,getContactName:x,getShareUrl:y,copyToClipboard:_,formatDuration:b}){const[j,k]=S.useState(!1);return e.jsxs(ke,{className:"overflow-hidden group cursor-pointer",onClick:n,onMouseEnter:()=>k(!0),onMouseLeave:()=>k(!1),children:[e.jsxs("div",{className:"relative aspect-video bg-muted overflow-hidden",children:[e.jsx(PFs,{previewSrc:t,thumbnailSrc:r,alt:s.title||"Video preview",isHovered:j}),e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/40 opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx("div",{className:"w-12 h-12 rounded-full bg-white/90 flex items-center justify-center",children:e.jsx(El,{className:"h-6 w-6 text-primary ml-1"})})}),e.jsx("div",{className:"absolute bottom-2 right-2 bg-black/70 text-white text-xs px-1.5 py-0.5 rounded",children:b(s.duration_seconds)}),s.status!=="ready"&&e.jsx(Xe,{variant:s.status==="processing"?"secondary":"destructive",className:"absolute top-2 left-2",children:s.status})]}),e.jsx(Oe,{className:"p-3",children:e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("h3",{className:"font-medium truncate",children:s.title||"Untitled Video"}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground mt-1",children:[e.jsx(io,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:x(s.contact_id)})]}),e.jsxs("div",{className:"flex items-center gap-4 text-xs text-muted-foreground mt-0.5",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Pn,{className:"h-3 w-3"}),e.jsx("span",{children:As(new Date(s.created_at),"MMM d, yyyy")})]}),(s.view_count??0)>0&&e.jsxs("div",{className:"flex items-center gap-1 text-primary",children:[e.jsx(Bn,{className:"h-3 w-3"}),e.jsxs("span",{children:[s.view_count," ",s.view_count===1?"view":"views"]})]})]}),p&&s.share_token&&e.jsxs(H,{variant:"outline",size:"sm",className:"mt-2 gap-1.5 text-xs h-7",onClick:T=>{T.stopPropagation(),m==null||m()},children:[e.jsx(er,{className:"h-3 w-3"}),"Send via Gmail"]}),e.jsx("h3",{className:"font-medium truncate",children:s.title||"Untitled Video"}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground mt-1",children:[e.jsx(io,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:x(s.contact_id)})]}),e.jsxs("div",{className:"flex items-center gap-4 text-xs text-muted-foreground mt-0.5",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Pn,{className:"h-3 w-3"}),e.jsx("span",{children:As(new Date(s.created_at),"MMM d, yyyy")})]}),(s.view_count??0)>0&&e.jsxs("div",{className:"flex items-center gap-1 text-primary",children:[e.jsx(Bn,{className:"h-3 w-3"}),e.jsxs("span",{children:[s.view_count," ",s.view_count===1?"view":"views"]})]})]})]}),e.jsxs(Xu,{children:[e.jsx(Qu,{asChild:!0,children:e.jsx(H,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:T=>T.stopPropagation(),children:e.jsx(Ay,{className:"h-4 w-4"})})}),e.jsxs(wu,{align:"end",className:"bg-popover",children:[e.jsxs(di,{onClick:T=>{T.stopPropagation(),n()},children:[e.jsx(Bn,{className:"h-4 w-4 mr-2"}),"Watch"]}),e.jsx(A_,{}),e.jsxs(di,{onClick:T=>{T.stopPropagation(),h()},children:[e.jsx(pl,{className:"h-4 w-4 mr-2"}),"Share with Template"]}),e.jsxs(di,{onClick:T=>{T.stopPropagation(),_(y(s),"Share link")},children:[e.jsx(Jo,{className:"h-4 w-4 mr-2"}),"Copy Share Link"]}),e.jsxs(di,{onClick:T=>{T.stopPropagation(),o()},children:[e.jsx(pE,{className:"h-4 w-4 mr-2"}),"Get Embed Code"]}),e.jsxs(di,{onClick:T=>{T.stopPropagation(),c()},children:[e.jsx(er,{className:"h-4 w-4 mr-2"}),"Copy HTML for Email"]}),e.jsxs(di,{onClick:T=>{T.stopPropagation(),d()},children:[e.jsx(gn,{className:"h-4 w-4 mr-2"}),"Embed to CRM"]}),p&&s.share_token&&e.jsxs(di,{onClick:T=>{T.stopPropagation(),m==null||m()},children:[e.jsx(yn,{className:"h-4 w-4 mr-2"}),"Send via Gmail"]}),e.jsxs(di,{onClick:T=>{T.stopPropagation(),i()},children:[e.jsx(ni,{className:"h-4 w-4 mr-2"}),"Rename"]}),e.jsx(A_,{}),s.contact_id&&e.jsxs(di,{onClick:T=>{T.stopPropagation(),l()},children:[e.jsx(io,{className:"h-4 w-4 mr-2"}),"View Contact"]}),e.jsxs(di,{onClick:T=>{T.stopPropagation(),a()},className:"text-destructive",children:[e.jsx(Dr,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})]})})]})}function DFs(){var Is,lr;const s=Fr(),{data:t,isLoading:r,refetch:n}=N8s(),{data:a}=O0e(),{data:i}=Cp(),l=C8s(),o=S8s(),{isGmailConnected:c,gmailEmail:d}=cf(),{data:h}=sv(),{data:m=[],isLoading:p}=EFs(),[x,y]=S.useState("my"),[_,b]=S.useState(""),[j,k]=S.useState(null),[T,E]=S.useState(!1),[A,D]=S.useState(!1),[R,z]=S.useState(!1),[O,$]=S.useState(!1),[ee,Z]=S.useState(!1),[J,K]=S.useState(""),[re,ie]=S.useState(!1),[ce,ne]=S.useState(!1),[le,be]=S.useState(!1),[fe,je]=S.useState(!1),[ve,We]=S.useState(""),[Ve,Le]=S.useState({}),Me=us=>{if(!us)return"Unassigned";const St=i==null?void 0:i.find(xs=>xs.id===us);return St?`${St.first_name} ${St.last_name||""}`.trim():"Unknown"},ze=us=>{if(!us)return"0:00";const St=Math.floor(us/60),xs=us%60;return`${St}:${xs.toString().padStart(2,"0")}`},[Pe,Ie]=S.useState("all"),De=t==null?void 0:t.filter(us=>{const St=us.category||"general";if(Pe==="general"&&St!=="general"||Pe==="open_house"&&St!=="open_house")return!1;if(!_)return!0;const xs=Me(us.contact_id).toLowerCase(),kt=(us.title||"").toLowerCase(),fs=(us.notes||"").toLowerCase();return xs.includes(_.toLowerCase())||kt.includes(_.toLowerCase())||fs.includes(_.toLowerCase())}),pe=(t==null?void 0:t.filter(us=>(us.category||"general")==="open_house").length)||0,tt=(t==null?void 0:t.filter(us=>(us.category||"general")==="general").length)||0,ge=(t||[]).filter(us=>us.status==="processing"&&us.bunny_video_id).map(us=>us.id).join(",");S.useEffect(()=>{(async()=>{if(!(t!=null&&t.length))return;const St=t.filter(kt=>kt.status==="processing"&&kt.bunny_video_id);if(!St.length)return;let xs=!1;for(const kt of St)try{const{data:fs,error:Gs}=await V.functions.invoke("bunny-upload",{body:{action:"status",videoId:kt.bunny_video_id,isAgentVideo:!0}});if(Gs||!fs)continue;fs.status===4&&(await V.from("agent_videos").update({status:"ready",playback_url:fs.directPlayUrl,thumbnail_url:fs.thumbnailUrl,preview_url:fs.previewUrl,duration_seconds:fs.length||kt.duration_seconds,updated_at:new Date().toISOString()}).eq("id",kt.id),xs=!0)}catch(fs){console.warn("Reconcile check failed for video",kt.id,fs)}xs&&n()})()},[ge,n]),S.useEffect(()=>{(async()=>{if(!(t!=null&&t.length))return;const St=t.filter(_s=>(_s==null?void 0:_s.bunny_video_id)&&!Ve[_s.id]);if(!St.length)return;const xs=St.map(_s=>_s.bunny_video_id),{data:kt,error:fs}=await V.functions.invoke("bunny-upload",{body:{action:"bulk-asset-urls",videoIds:xs,isAgentVideo:!0}});if(fs)throw fs;const Gs=(kt==null?void 0:kt.assets)||{};Le(_s=>{const br={..._s};for(const zr of St)Gs[zr.bunny_video_id]&&(br[zr.id]={previewUrl:Gs[zr.bunny_video_id].previewUrl,thumbnailUrl:Gs[zr.bunny_video_id].thumbnailUrl});return br})})().catch(St=>console.warn("Failed to load signed Bunny asset URLs",St))},[t,Ve]);const ct=(a==null?void 0:a.total_storage_mb)||0,Ue=(a==null?void 0:a.max_storage_mb)||1024,et=ct/Ue*100,Qe=et>=80,Ne=et>=100,$e=async(us,St)=>{await navigator.clipboard.writeText(us),he.success(`${St} copied to clipboard`)},it=us=>us.share_token?`https://video.relevelup.com/${us.share_token}`:us.playback_url||"",Je=us=>{const St=it(us),xs=i==null?void 0:i.find(zr=>zr.id===us.contact_id),kt=Me(us.contact_id),fs=kt!=="Unassigned"?kt.split(" ")[0]:"",Gs=(xs==null?void 0:xs.phone)||"",_s=`Hey${fs?` ${fs}`:""}! I recorded a quick video message for you. Check it out: ${St}`,br=Gs?`sms:${Gs}?body=${encodeURIComponent(_s)}`:`sms:?body=${encodeURIComponent(_s)}`;window.open(br,"_self")},st=us=>{const St=i==null?void 0:i.find(br=>br.id===us.contact_id),xs=(St==null?void 0:St.email)||"",kt=it(us),fs="Check out this video",Gs=`I recorded a quick video for you: ${kt}`,_s=xs?`mailto:${xs}?subject=${encodeURIComponent(fs)}&body=${encodeURIComponent(Gs)}`:`mailto:?subject=${encodeURIComponent(fs)}&body=${encodeURIComponent(Gs)}`;window.open(_s,"_self")},mt=us=>{var fs;const St=it(us),xs=us.title||"Video Message",kt=us.share_token?`https://video.relevelup.com/thumb/${us.share_token}`:((fs=Ve[us.id])==null?void 0:fs.thumbnailUrl)||us.thumbnail_url||"";return``},wt=async us=>{if(!us.thumbnail_url&&!us.share_token){he.error("Video thumbnail not available yet");return}const St=mt(us),xs=it(us),kt=`Watch: ${us.title||"Video Message"} ${xs}`;try{const fs=new Blob([St],{type:"text/html"}),Gs=new Blob([kt],{type:"text/plain"}),_s=new ClipboardItem({"text/html":fs,"text/plain":Gs});await navigator.clipboard.write([_s]),he.success("Copied! Paste into Gmail - the thumbnail will appear after sending.")}catch{await navigator.clipboard.writeText(kt+` `+St),he.success("Copied! Paste into your email.")}},at=async us=>{try{he.loading("Preparing download...",{id:"download"});const{data:St,error:xs}=await V.functions.invoke("bunny-upload",{body:{action:"download-url",videoId:us.bunny_video_id,isAgentVideo:!0}});if(xs||!(St!=null&&St.downloadUrl))throw new Error((xs==null?void 0:xs.message)||"Failed to get download URL");const fs=`${((us.title||"video").toString().trim()||"video").replace(/[\\/:*?"<>|]+/g,"-")}.mp4`,Gs=await fetch(St.downloadUrl);if(!Gs.ok)throw new Error("Failed to fetch video file");const _s=await Gs.blob(),br=URL.createObjectURL(_s),zr=document.createElement("a");zr.href=br,zr.download=fs,zr.rel="noreferrer",document.body.appendChild(zr),zr.click(),zr.remove(),URL.revokeObjectURL(br),he.success("Download started",{id:"download"})}catch(St){console.error("Download error:",St),he.error("Could not force download (your browser may block it).",{id:"download"})}},rt=async us=>{k(us),ie(!0),K(""),Z(!0);try{const{data:St,error:xs}=await V.functions.invoke("bunny-upload",{body:{action:"crm-embed",videoId:us.bunny_video_id,title:us.title,isAgentVideo:!0,shareToken:us.share_token}});if(xs||!(St!=null&&St.html))throw new Error("Failed to generate CRM embed code");K(St.html)}catch(St){console.error("CRM embed error:",St),he.error("Failed to generate CRM embed code"),Z(!1)}finally{ie(!1)}},Et=us=>{k(us),E(!0)},hs=async()=>{if(j)try{await l.mutateAsync({id:j.id,bunnyVideoId:j.bunny_video_id,hardDelete:!0}),D(!1),k(null),he.success("Video deleted successfully")}catch{he.error("Failed to delete video")}};return e.jsx(Ss,{title:"Video Library",description:"Manage your video touches",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Video Library"}),e.jsx("p",{className:"text-muted-foreground",children:"Manage and share your video touches"})]}),e.jsxs("div",{className:"flex bg-muted rounded-lg p-1 gap-0.5 ml-2",children:[e.jsx("button",{onClick:()=>y("my"),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors ${x==="my"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:"My Videos"}),h&&((Is=h.team)==null?void 0:Is.shared_videos_enabled)&&e.jsxs("button",{onClick:()=>y("team"),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors flex items-center gap-1.5 ${x==="team"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[e.jsx(Ar,{className:"h-3.5 w-3.5"}),"Team"]}),e.jsxs("button",{onClick:()=>y("analytics"),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors flex items-center gap-1.5 ${x==="analytics"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[e.jsx(Bo,{className:"h-3.5 w-3.5"}),"Analytics"]})]})]}),x==="my"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(H,{variant:"outline",onClick:()=>z(!0),children:[e.jsx(Ea,{className:"h-4 w-4 mr-2"}),"Upload Video"]}),e.jsxs(H,{onClick:()=>s("/mission-control/video/record"),children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Record New Video"]})]})]}),x==="team"?e.jsx(RFs,{videos:m,isLoading:p,searchTerm:_,setSearchTerm:b}):x==="analytics"?e.jsx(IFs,{}):e.jsxs(e.Fragment,{children:[e.jsx(ke,{className:Qe?"border-amber-500":Ne?"border-destructive":"",children:e.jsxs(Oe,{className:"py-4",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(mF,{className:`h-5 w-5 ${Ne?"text-destructive":Qe?"text-amber-500":"text-muted-foreground"}`}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("span",{className:"text-sm font-medium",children:"Storage Used"}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:[ct.toFixed(1)," MB / ",Ue>=1024?`${(Ue/1024).toFixed(0)} GB`:`${Ue} MB`]})]}),e.jsx(Mi,{value:Math.min(et,100),className:`h-2 ${Ne?"[&>div]:bg-destructive":Qe?"[&>div]:bg-amber-500":""}`})]}),Qe&&!Ne&&e.jsxs(Xe,{variant:"outline",className:"border-amber-500 text-amber-600",children:[e.jsx(wo,{className:"h-3 w-3 mr-1"}),"Near Limit"]}),Ne&&e.jsxs(Xe,{variant:"destructive",children:[e.jsx(wo,{className:"h-3 w-3 mr-1"}),"At Limit"]})]}),Ne&&e.jsx("p",{className:"text-sm text-destructive mt-2",children:"You've reached your storage limit. Delete videos to record more."})]})}),e.jsx("div",{className:"flex gap-1 p-1 bg-muted rounded-lg w-fit",children:[{id:"all",label:"All",count:(t||[]).length},{id:"general",label:"My Videos",count:tt},{id:"open_house",label:"Open House Tours",count:pe}].map(us=>e.jsxs("button",{onClick:()=>Ie(us.id),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors ${Pe===us.id?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[us.label," ",e.jsx("span",{className:"ml-1 text-xs text-muted-foreground",children:us.count})]},us.id))}),e.jsxs("div",{className:"relative",children:[e.jsx(Mn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Se,{placeholder:"Search videos by contact, title, or notes...",value:_,onChange:us=>b(us.target.value),className:"pl-10"})]}),r?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full"})}):(De==null?void 0:De.length)===0?e.jsx(ke,{children:e.jsxs(Oe,{className:"py-12 text-center",children:[e.jsx(xn,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"font-semibold mb-2",children:"No videos yet"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"Record your first video touch to get started"}),e.jsxs(H,{onClick:()=>s("/mission-control/video/record"),children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Record Video"]})]})}):e.jsx("div",{className:"grid sm:grid-cols-2 lg:grid-cols-3 gap-4",children:De==null?void 0:De.map(us=>{var St,xs;return e.jsx(LFs,{video:us,previewSrc:(St=Ve[us.id])==null?void 0:St.previewUrl,thumbnailSrc:(xs=Ve[us.id])==null?void 0:xs.thumbnailUrl,onOpen:()=>Et(us),onDelete:()=>{k(us),D(!0)},onRename:()=>{k(us),We(us.title||""),je(!0)},onNavigateToContact:()=>s(`/mission-control/contacts/${us.contact_id}`),onGetEmbedCode:()=>{k(us),$(!0)},onCopyEmailHtml:()=>wt(us),onEmbedToCrm:()=>rt(us),onShareWithTemplate:()=>{k(us),ne(!0)},onSendViaGmail:()=>{k(us),be(!0)},isGmailConnected:c,getContactName:Me,getShareUrl:it,copyToClipboard:$e,formatDuration:ze},us.id)})}),e.jsx(bs,{open:T,onOpenChange:E,children:e.jsxs(vs,{className:"max-w-2xl",children:[e.jsxs(Cs,{children:[e.jsx(Ns,{children:(j==null?void 0:j.title)||"Video Preview"}),e.jsx(nn,{children:(j==null?void 0:j.contact_id)&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(io,{className:"h-3 w-3"}),Me(j.contact_id)]})})]}),j&&e.jsxs("div",{className:"space-y-4",children:[j.status==="processing"?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 px-6 bg-muted/50 rounded-lg border border-dashed border-border text-center space-y-4",children:[e.jsx("div",{className:"relative",children:e.jsx("div",{className:"h-16 w-16 rounded-full bg-primary/10 flex items-center justify-center",children:e.jsx(is,{className:"h-8 w-8 text-primary animate-spin"})})}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{className:"font-semibold text-lg",children:"Video is still processing"}),e.jsx("p",{className:"text-muted-foreground text-sm max-w-sm",children:"Your video is being encoded and will be ready shortly. This usually takes 1–3 minutes. Check back soon!"})]}),e.jsxs(H,{variant:"outline",size:"sm",onClick:()=>{E(!1),n()},children:[e.jsx(po,{className:"h-4 w-4 mr-2"}),"Refresh Library"]})]}):e.jsx("div",{className:"relative w-full",style:{paddingBottom:"56.25%"},children:j.playback_url?(()=>{let us=j.playback_url;return us.includes("iframe.mediadelivery.net/play/")&&(us=us.replace("/play/","/embed/"),us+=(us.includes("?")?"&":"?")+"autoplay=false&responsive=true"),us.includes("iframe.mediadelivery.net")?e.jsx("iframe",{src:us,title:j.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}):e.jsx("video",{src:j.playback_url,controls:!0,playsInline:!0,preload:"metadata",poster:j.thumbnail_url||void 0,className:"absolute top-0 left-0 w-full h-full rounded-lg object-cover",onError:()=>he.error("Video preview failed to load")},j.playback_url)})():e.jsxs("div",{className:"absolute inset-0 flex items-center justify-center bg-muted rounded-lg",children:[e.jsx(xn,{className:"h-12 w-12 text-muted-foreground"}),e.jsx("p",{className:"text-muted-foreground ml-2",children:"Video not available"})]})}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs(H,{variant:"outline",onClick:()=>Je(j),children:[e.jsx(Gi,{className:"h-4 w-4 mr-2"}),"Text Contact Video"]}),!c&&e.jsxs(H,{variant:"outline",onClick:()=>st(j),children:[e.jsx(er,{className:"h-4 w-4 mr-2"}),"Email Contact Video"]}),e.jsxs(H,{variant:"outline",onClick:()=>$e(it(j),"Share link"),children:[e.jsx(ui,{className:"h-4 w-4 mr-2"}),"Copy Share Link"]}),e.jsxs(H,{variant:"outline",onClick:()=>wt(j),children:[e.jsx(er,{className:"h-4 w-4 mr-2"}),"Copy HTML for Email"]}),e.jsxs(H,{variant:"outline",onClick:()=>at(j),children:[e.jsx(hi,{className:"h-4 w-4 mr-2"}),"Download Video"]}),e.jsxs(H,{variant:"outline",onClick:()=>{E(!1),rt(j)},children:[e.jsx(gn,{className:"h-4 w-4 mr-2"}),"Embed to CRM"]}),e.jsxs(H,{variant:"outline",onClick:()=>{E(!1),ne(!0)},children:[e.jsx(pl,{className:"h-4 w-4 mr-2"}),"Send with Page Template"]}),c&&(j==null?void 0:j.share_token)&&e.jsxs(H,{variant:"outline",onClick:()=>{E(!1),be(!0)},children:[e.jsx(yn,{className:"h-4 w-4 mr-2"}),"Send via Gmail"]})]}),e.jsx("div",{className:"flex justify-end pt-2 border-t",children:e.jsxs(H,{variant:"destructive",onClick:()=>{E(!1),D(!0)},children:[e.jsx(Dr,{className:"h-4 w-4 mr-2"}),"Delete Video"]})})]})]})}),e.jsx(bs,{open:A,onOpenChange:D,children:e.jsxs(vs,{children:[e.jsxs(Cs,{children:[e.jsx(Ns,{children:"Delete Video"}),e.jsx(nn,{children:"Are you sure you want to delete this video? This action cannot be undone."})]}),e.jsxs(wn,{children:[e.jsx(H,{variant:"outline",onClick:()=>D(!1),children:"Cancel"}),e.jsx(H,{variant:"destructive",onClick:hs,disabled:l.isPending,children:l.isPending?"Deleting...":"Delete"})]})]})}),e.jsx(Kgt,{open:R,onOpenChange:z}),e.jsx(bs,{open:O,onOpenChange:$,children:e.jsxs(vs,{className:"sm:max-w-lg",children:[e.jsxs(Cs,{children:[e.jsx(Ns,{children:"Embed Video"}),e.jsx(nn,{children:"Copy this code to embed the video on your website."})]}),j&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Embed Code"}),e.jsx(vr,{readOnly:!0,rows:5,value:``,className:"font-mono text-xs"})]}),e.jsx("div",{className:"flex gap-2",children:e.jsxs(H,{className:"flex-1",onClick:()=>{const us=``;$e(us,"Embed code")},children:[e.jsx(ui,{className:"h-4 w-4 mr-2"}),"Copy Embed Code"]})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Paste this code into your website's HTML where you want the video to appear. The video will automatically resize to fit its container."})]})]})}),j&&e.jsx(Nyt,{open:ce,onOpenChange:ne,video:j,contactName:Me(j.contact_id)}),j&&e.jsx(TFs,{open:le,onOpenChange:be,video:j,gmailEmail:d,signedThumbnailUrl:(lr=Ve[j.id])==null?void 0:lr.thumbnailUrl}),e.jsx(bs,{open:fe,onOpenChange:je,children:e.jsxs(vs,{className:"max-w-sm",children:[e.jsxs(Cs,{children:[e.jsx(Ns,{children:"Rename Video"}),e.jsx(nn,{children:"Enter a new title for this video."})]}),e.jsx(Se,{value:ve,onChange:us=>We(us.target.value),placeholder:"Video title",autoFocus:!0,onKeyDown:us=>{us.key==="Enter"&&ve.trim()&&o.mutate({id:j.id,title:ve.trim()},{onSuccess:()=>{he.success("Video renamed"),je(!1)}})}}),e.jsxs(wn,{children:[e.jsx(H,{variant:"outline",onClick:()=>je(!1),children:"Cancel"}),e.jsx(H,{disabled:!ve.trim()||o.isPending,onClick:()=>{o.mutate({id:j.id,title:ve.trim()},{onSuccess:()=>{he.success("Video renamed"),je(!1)}})},children:o.isPending?"Saving...":"Save"})]})]})}),e.jsx(bs,{open:ee,onOpenChange:Z,children:e.jsxs(vs,{className:"sm:max-w-lg",children:[e.jsxs(Cs,{children:[e.jsxs(Ns,{className:"flex items-center gap-2",children:[e.jsx(gn,{className:"h-5 w-5"}),"Embed to CRM"]}),e.jsx(nn,{children:"Copy this HTML code and paste it into your CRM's email editor. It uses a simple image + link format that works in all CRM email programs."})]}),re?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(is,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):J?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"CRM Email HTML"}),e.jsx(vr,{readOnly:!0,rows:12,value:J,className:"font-mono text-xs"})]}),e.jsxs(H,{className:"w-full",onClick:()=>{$e(J,"CRM embed code")},children:[e.jsx(ui,{className:"h-4 w-4 mr-2"}),"Copy CRM Embed Code"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Paste this into your CRM's email HTML editor. The recipient will see the video thumbnail and can click to watch. Works with Follow Up Boss, KvCORE, BoomTown, Sierra, and more."})]}):null]})})]})]})})}function RFs({videos:s,isLoading:t,searchTerm:r,setSearchTerm:n}){const a=S.useMemo(()=>{if(!r)return s;const o=r.toLowerCase();return s.filter(c=>(c.title||"").toLowerCase().includes(o)||(c.owner_name||"").toLowerCase().includes(o)||(c.recipient_name||"").toLowerCase().includes(o))},[s,r]),i=S.useMemo(()=>{const o=new Map;return a.forEach(c=>{const d=o.get(c.owner_user_id);d?d.videos.push(c):o.set(c.owner_user_id,{name:c.owner_name,avatar:c.owner_avatar_url,videos:[c]})}),Array.from(o.entries())},[a]),l=o=>{if(!o)return"0:00";const c=Math.floor(o/60),d=o%60;return`${c}:${d.toString().padStart(2,"0")}`};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"relative",children:[e.jsx(Mn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Se,{placeholder:"Search team videos by title, owner, or recipient...",value:r,onChange:o=>n(o.target.value),className:"pl-10"})]}),t?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full"})}):a.length===0?e.jsx(ke,{children:e.jsxs(Oe,{className:"py-12 text-center",children:[e.jsx(Ar,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"font-semibold mb-2",children:"No team videos"}),e.jsx("p",{className:"text-muted-foreground",children:s.length===0?"Your teammates haven't recorded any videos yet.":"No videos match your search."})]})}):e.jsx("div",{className:"space-y-6",children:i.map(([o,c])=>e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Un,{className:"h-7 w-7",children:[e.jsx(Ka,{src:c.avatar||""}),e.jsx(qn,{children:(c.name||"?").charAt(0).toUpperCase()})]}),e.jsx("h3",{className:"font-semibold text-sm",children:c.name}),e.jsx(Xe,{variant:"secondary",className:"text-xs",children:c.videos.length})]}),e.jsx("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3",children:c.videos.map(d=>e.jsxs(ke,{className:"overflow-hidden",children:[e.jsxs("div",{className:"relative aspect-video bg-muted flex items-center justify-center",children:[d.thumbnail_url?e.jsx("img",{src:d.thumbnail_url,alt:d.title||"Video",className:"w-full h-full object-cover",referrerPolicy:"no-referrer",onError:h=>{h.target.style.display="none"}}):e.jsx(xn,{className:"h-10 w-10 text-muted-foreground"}),d.duration_seconds&&e.jsx("span",{className:"absolute bottom-2 right-2 bg-black/70 text-white text-xs px-1.5 py-0.5 rounded",children:l(d.duration_seconds)})]}),e.jsxs(Oe,{className:"p-3",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:d.title||"Untitled"}),e.jsxs("div",{className:"flex items-center gap-3 mt-1 text-xs text-muted-foreground",children:[d.recipient_name&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(io,{className:"h-3 w-3"}),d.recipient_name]}),d.view_count!=null&&d.view_count>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Bn,{className:"h-3 w-3"}),d.view_count]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Pn,{className:"h-3 w-3"}),As(new Date(d.created_at),"MMM d")]})]})]})]},d.id))})]},o))})]})}const OFs=()=>{const{user:s}=Ms();return yt({queryKey:["team-deals",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:r}=await V.rpc("get_team_deals",{_user_id:s.id});if(r)throw r;return t||[]},enabled:!!s})},oWe=["#8B5CF6","#EC4899","#F59E0B","#10B981","#3B82F6","#EF4444","#06B6D4","#F97316"];function FFs({open:s,onOpenChange:t}){const{data:r,isLoading:n}=OFs(),[a,i]=S.useState(""),[l,o]=S.useState("all"),c=S.useMemo(()=>{if(!r)return new Map;const y=new Map;let _=0;return r.forEach(b=>{y.has(b.owner_user_id)||(y.set(b.owner_user_id,{name:b.owner_name||"Unknown",avatar:b.owner_avatar_url,color:oWe[_%oWe.length]}),_++)}),y},[r]),d=S.useMemo(()=>Array.from(c.entries()).map(([y,_])=>({id:y,..._})),[c]),h=S.useMemo(()=>{if(!r)return[];let y=r;if(l!=="all"&&(y=y.filter(_=>_.owner_user_id===l)),a.trim()){const _=a.toLowerCase();y=y.filter(b=>{var j,k,T,E;return b.deal_name.toLowerCase().includes(_)||((j=b.contact_name)==null?void 0:j.toLowerCase().includes(_))||((k=b.property_address)==null?void 0:k.toLowerCase().includes(_))||((T=b.city)==null?void 0:T.toLowerCase().includes(_))||((E=b.owner_name)==null?void 0:E.toLowerCase().includes(_))})}return y},[r,a,l]),m=S.useMemo(()=>{const y=new Map;return h.forEach(_=>{const b=_.stage_name||"Unknown";y.has(b)||y.set(b,{name:b,color:_.stage_color,icon:_.stage_icon,deals:[],totalValue:0});const j=y.get(b);j.deals.push(_),j.totalValue+=_.sale_price||0}),Array.from(y.values())},[h]),p=y=>y>=1e6?`$${(y/1e6).toFixed(1)}M`:y>=1e3?`$${(y/1e3).toFixed(0)}K`:`$${y.toFixed(0)}`,x=y=>y?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(y):null;return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-[95vw] w-full max-h-[90vh] flex flex-col",children:[e.jsx(Cs,{children:e.jsxs(Ns,{className:"flex items-center gap-2",children:[e.jsx(Ar,{className:"h-5 w-5"}),"Team Pipeline"]})}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsxs("div",{className:"relative flex-1 max-w-xs",children:[e.jsx(Mn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Se,{placeholder:"Search deals...",value:a,onChange:y=>i(y.target.value),className:"pl-9"})]}),e.jsxs(Bs,{value:l,onValueChange:o,children:[e.jsx(Os,{className:"w-[180px]",children:e.jsx(Us,{placeholder:"All Members"})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"all",children:"All Members"}),d.map(y=>e.jsx(pt,{value:y.id,children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"h-2 w-2 rounded-full inline-block",style:{backgroundColor:y.color}}),y.name]})},y.id))]})]}),e.jsxs("div",{className:"hidden md:flex items-center gap-3 ml-auto text-xs text-muted-foreground",children:[d.slice(0,6).map(y=>e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"h-2 w-2 rounded-full",style:{backgroundColor:y.color}}),y.name.split(" ")[0]]},y.id)),d.length>6&&e.jsxs("span",{children:["+",d.length-6," more"]})]})]}),e.jsx("div",{className:"flex-1 overflow-hidden mt-2",children:n?e.jsx("div",{className:"flex gap-4 h-full",children:[1,2,3,4].map(y=>e.jsxs("div",{className:"min-w-[260px] flex-1",children:[e.jsx(Ks,{className:"h-12 w-full mb-2 rounded-lg"}),e.jsx(Ks,{className:"h-24 w-full mb-2 rounded-lg"}),e.jsx(Ks,{className:"h-24 w-full rounded-lg"})]},y))}):m.length===0?e.jsx("div",{className:"flex items-center justify-center h-full text-muted-foreground",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Ar,{className:"h-10 w-10 mx-auto mb-3 opacity-50"}),e.jsx("p",{className:"font-medium",children:"No team deals found"}),e.jsx("p",{className:"text-sm",children:"Team members' deals will appear here."})]})}):e.jsx("div",{className:"flex gap-3 h-full overflow-x-auto pb-2",children:m.map(y=>{const _=y.icon&&Vpe[y.icon]||Gu;return e.jsxs("div",{className:"flex flex-col h-full min-w-[260px] max-w-[300px] flex-1 bg-muted/30 rounded-xl border border-border/50",children:[e.jsxs("div",{className:"p-3 border-b border-border/50 shrink-0",style:{borderTopColor:y.color||"hsl(var(--border))",borderTopWidth:3},children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-6 h-6 rounded-md flex items-center justify-center",style:{backgroundColor:y.color?`${y.color}20`:void 0},children:e.jsx(_,{className:"h-3.5 w-3.5",style:{color:y.color||void 0}})}),e.jsx("h3",{className:"font-semibold text-sm",children:y.name})]}),e.jsx(Xe,{variant:"secondary",className:"text-xs px-2",children:y.deals.length})]}),y.totalValue>0&&e.jsx("p",{className:"text-xs text-muted-foreground ml-8",children:p(y.totalValue)})]}),e.jsx(Ci,{className:"flex-1 p-2",children:e.jsx("div",{className:"space-y-2",children:y.deals.map(b=>{const j=c.get(b.owner_user_id);return e.jsx(BFs,{deal:b,ownerColor:(j==null?void 0:j.color)||"#888",ownerName:(j==null?void 0:j.name)||"Unknown",ownerAvatar:(j==null?void 0:j.avatar)||null,formatPrice:x},b.id)})})})]},y.name)})})}),e.jsxs("p",{className:"text-xs text-muted-foreground text-center pt-2 border-t shrink-0",children:[h.length," deal",h.length!==1?"s":""," across ",m.length," stage",m.length!==1?"s":""," from ",d.length," member",d.length!==1?"s":""]})]})})}function BFs({deal:s,ownerColor:t,ownerName:r,ownerAvatar:n,formatPrice:a}){const i={buyer:{label:"Buyer",className:"bg-blue-500/10 text-blue-600 border-blue-200"},seller:{label:"Seller",className:"bg-emerald-500/10 text-emerald-600 border-emerald-200"},dual:{label:"Dual",className:"bg-purple-500/10 text-purple-600 border-purple-200"},referral:{label:"Referral",className:"bg-orange-500/10 text-orange-600 border-orange-200"},lease:{label:"Lease",className:"bg-cyan-500/10 text-cyan-600 border-cyan-200"}},l=s.deal_type?i[s.deal_type]:null;return e.jsxs("div",{className:"rounded-lg border bg-card p-3 space-y-2 transition-all hover:shadow-sm",style:{borderLeftWidth:4,borderLeftColor:t},children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsxs(Un,{className:"h-4 w-4",children:[e.jsx(Ka,{src:n||""}),e.jsx(qn,{className:"text-[8px] font-semibold text-white",style:{backgroundColor:t},children:r.charAt(0).toUpperCase()})]}),e.jsx("span",{className:"text-[10px] font-medium truncate",style:{color:t},children:r})]}),e.jsxs("div",{className:"flex items-start justify-between gap-1",children:[e.jsx("h4",{className:"font-medium text-sm leading-tight line-clamp-2",children:s.deal_name}),l&&e.jsx(Xe,{variant:"outline",className:Ft("text-[10px] px-1.5 py-0 shrink-0",l.className),children:l.label})]}),s.contact_name&&e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:s.contact_name}),(s.property_address||s.city)&&e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(Fn,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate",children:s.property_address||`${s.city}, ${s.state}`})]}),s.sale_price&&e.jsxs("div",{className:"flex items-center gap-1 text-xs",children:[e.jsx(oc,{className:"h-3 w-3 text-emerald-500 shrink-0"}),e.jsx("span",{className:"font-semibold text-foreground",children:a(s.sale_price)})]})]})}function zFs({members:s,enabledMembers:t,onToggleMember:r,isOpen:n,onToggleOpen:a}){const i=t.size;return e.jsxs("div",{className:Ft("shrink-0 border-r border-border/50 bg-muted/20 transition-all duration-300 flex flex-col",n?"w-[220px]":"w-[48px]"),children:[e.jsx("div",{className:"p-2 border-b border-border/50 shrink-0",children:e.jsxs(H,{variant:"ghost",size:"sm",className:"w-full justify-start gap-2 px-2",onClick:a,children:[e.jsx(Ar,{className:"h-4 w-4 shrink-0 text-primary"}),n&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-xs font-semibold flex-1 text-left",children:"Team"}),i>0&&e.jsx("span",{className:"text-[10px] bg-primary text-primary-foreground rounded-full px-1.5 py-0.5",children:i}),e.jsx(fl,{className:"h-3 w-3 text-muted-foreground"})]}),!n&&i>0&&e.jsx("span",{className:"absolute -top-1 -right-1 text-[9px] bg-primary text-primary-foreground rounded-full w-4 h-4 flex items-center justify-center",children:i})]})}),n?e.jsxs(Ci,{className:"flex-1 p-2",children:[e.jsx("div",{className:"space-y-1",children:s.map(l=>{const o=t.has(l.id);return e.jsxs("button",{onClick:()=>r(l.id),className:Ft("w-full flex items-center gap-2 px-2 py-2 rounded-lg text-left transition-colors",o?"bg-primary/10 hover:bg-primary/15":"hover:bg-muted/50"),children:[e.jsxs("div",{className:"relative",children:[e.jsxs(Un,{className:"h-7 w-7",children:[e.jsx(Ka,{src:l.avatar_url||""}),e.jsx(qn,{className:"text-[10px] font-semibold text-white",style:{backgroundColor:l.color},children:l.name.charAt(0).toUpperCase()})]}),o&&e.jsx("div",{className:"absolute -bottom-0.5 -right-0.5 w-3 h-3 rounded-full border-2 border-background",style:{backgroundColor:l.color}})]}),e.jsx("span",{className:Ft("text-xs truncate flex-1",o?"font-medium text-foreground":"text-muted-foreground"),children:l.name}),e.jsx(Or,{checked:o,onCheckedChange:()=>r(l.id),className:"scale-75",onClick:c=>c.stopPropagation()})]},l.id)})}),s.length===0&&e.jsx("p",{className:"text-xs text-muted-foreground text-center py-4",children:"No team members"})]}):e.jsxs("div",{className:"flex-1 flex flex-col items-center pt-2 gap-2",children:[s.slice(0,5).map(l=>{const o=t.has(l.id);return e.jsx("button",{onClick:()=>r(l.id),className:"relative",title:l.name,children:e.jsxs(Un,{className:Ft("h-7 w-7 transition-all",o?"ring-2 ring-offset-1 ring-offset-background":"opacity-50"),style:o?{"--tw-ring-color":l.color}:{},children:[e.jsx(Ka,{src:l.avatar_url||""}),e.jsx(qn,{className:"text-[10px] font-semibold text-white",style:{backgroundColor:l.color},children:l.name.charAt(0).toUpperCase()})]})},l.id)}),s.length>5&&e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["+",s.length-5]})]})]})}const lWe=["#8B5CF6","#EC4899","#F59E0B","#10B981","#3B82F6","#EF4444","#06B6D4","#F97316"];function $Fs(){const s=ba(),{data:t}=sv(),r=(t==null?void 0:t.role)==="team_leader",n=t==null?void 0:t.teamId,a=yt({queryKey:["team-pipeline-members",n,s],queryFn:async()=>{const{data:i,error:l}=await V.from("team_members").select("user_id, role").eq("team_id",n).neq("user_id",s);if(l)throw l;if(!i||i.length===0)return[];const o=i.map(h=>h.user_id),{data:c,error:d}=await V.from("profiles").select("id, name, avatar_url").in("id",o);if(d)throw d;return(c||[]).map((h,m)=>({id:h.id,name:h.name||"Unknown",avatar_url:h.avatar_url,color:lWe[m%lWe.length]}))},enabled:!!n&&!!s&&r,staleTime:5*60*1e3});return{isTeamLeader:r,teamMembers:a.data||[],isLoadingMembers:a.isLoading}}function UFs(s){return yt({queryKey:["team-member-deals",s],queryFn:async()=>{if(s.length===0)return[];const{data:t,error:r}=await V.from("deal_pipeline").select(` *, contact:innercircle_contacts(id, first_name, last_name, email, phone), listing:listings(id, property_address, city, state, price, status, created_at), deal_pipeline_stages(name) `).in("owner_user_id",s).order("updated_at",{ascending:!1});if(r)throw r;return(t||[]).map(n=>{var a;return{...n,_stage_name:((a=n.deal_pipeline_stages)==null?void 0:a.name)||null}})},enabled:s.length>0})}function qFs(){const s=ba();return yt({queryKey:["all-deal-tags-map",s],queryFn:async()=>{if(!s)return{tags:[],byDeal:{},unique:[]};const{data:t,error:r}=await V.from("deal_tags").select("id, deal_id, tag").eq("owner_user_id",s);if(r)throw r;const n=t||[],a={},i=new Set;n.forEach(o=>{a[o.deal_id]||(a[o.deal_id]=[]),a[o.deal_id].push(o.tag),i.add(o.tag)});const l=Array.from(i).sort((o,c)=>o.localeCompare(c));return{tags:n,byDeal:a,unique:l}},enabled:!!s})}function kyt({stages:s,currentStageId:t,onStageSelect:r,disabled:n}){const[a,i]=S.useState(!1),l=s.find(c=>c.id===t),o=c=>{c.id!==t&&r(c.id,c.name),i(!1)};return e.jsxs(Xu,{open:a,onOpenChange:i,children:[e.jsx(Qu,{asChild:!0,children:e.jsxs(H,{variant:"outline",size:"sm",className:"h-7 text-xs gap-1.5",disabled:n,onClick:c=>c.stopPropagation(),children:[l&&e.jsx("div",{className:"w-2 h-2 rounded-full shrink-0",style:{backgroundColor:l.color}}),e.jsx("span",{className:"max-w-[80px] truncate",children:(l==null?void 0:l.name)||"Move"}),e.jsx($a,{className:"h-3 w-3 shrink-0"})]})}),e.jsx(wu,{align:"end",className:"w-48 z-50 bg-popover",onClick:c=>c.stopPropagation(),children:s.map(c=>{const d=c.icon&&Vpe[c.icon]||Gu,h=c.id===t;return e.jsxs(di,{onClick:()=>o(c),className:Ft("flex items-center gap-2 cursor-pointer",h&&"bg-accent"),children:[e.jsx("div",{className:"w-5 h-5 rounded flex items-center justify-center shrink-0",style:{backgroundColor:`${c.color}20`},children:e.jsx(d,{className:"h-3 w-3",style:{color:c.color}})}),e.jsx("span",{className:"flex-1",children:c.name}),h&&e.jsx(va,{className:"h-4 w-4 text-primary"})]},c.id)})})]})}const VFs={buyer:{label:"Buyer",color:"bg-blue-500/10 text-blue-600 border-blue-200"},seller:{label:"Seller",color:"bg-emerald-500/10 text-emerald-600 border-emerald-200"},dual:{label:"Dual",color:"bg-purple-500/10 text-purple-600 border-purple-200"},referral:{label:"Referral",color:"bg-orange-500/10 text-orange-600 border-orange-200"},lease:{label:"Lease",color:"bg-cyan-500/10 text-cyan-600 border-cyan-200"}},HFs={low:{color:"bg-slate-100 text-slate-600",dot:"bg-slate-400"},medium:{color:"bg-amber-100 text-amber-700",dot:"bg-amber-500"},high:{color:"bg-orange-100 text-orange-700",dot:"bg-orange-500"},urgent:{color:"bg-red-100 text-red-700",dot:"bg-red-500"}};function Syt({deal:s,onClick:t,isDragging:r,stages:n,onStageChange:a,showStagePicker:i=!1,isWonStage:l=!1,ownerInfo:o=null}){var k,T;const c=V8(),d=VFs[s.deal_type],h=HFs[s.priority],m=S.useMemo(()=>s.target_close_date?Jy(Tc(s.target_close_date),new Date):null,[s.target_close_date]),p=m!==null&&m<0,x=m!==null&&m<=7&&m>=0,y=S.useMemo(()=>{var D;if(s.deal_type!=="seller"&&s.deal_type!=="dual")return null;const E=((D=s.listing)==null?void 0:D.created_at)||s.listing_date;if(!E)return null;const A=s.contract_date?Tc(s.contract_date):new Date;return Jy(A,Tc(E))},[s]),_=l&&!s.scorecard_transaction_id,b=!!s.scorecard_transaction_id,j=E=>E?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(E):null;return e.jsx(ke,{className:Ft("cursor-pointer transition-all duration-200 hover:shadow-md hover:border-primary/30 group overflow-hidden",r&&"opacity-50 rotate-2 shadow-xl",p&&"border-red-200 bg-red-50/30",_&&"border-amber-300 bg-amber-50/30 dark:bg-amber-950/20"),onClick:t,style:o?{borderLeftWidth:4,borderLeftColor:o.color}:void 0,children:e.jsxs(Oe,{className:"p-3 space-y-2.5",children:[o&&e.jsxs("div",{className:"flex items-center gap-1.5 -mt-0.5 mb-1",children:[e.jsxs(Un,{className:"h-4 w-4",children:[e.jsx(Ka,{src:o.avatar_url||""}),e.jsx(qn,{className:"text-[8px] font-semibold text-white",style:{backgroundColor:o.color},children:o.name.charAt(0).toUpperCase()})]}),e.jsx("span",{className:"text-[10px] font-medium",style:{color:o.color},children:o.name})]}),e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx("h4",{className:"font-medium text-sm leading-tight line-clamp-2 group-hover:text-primary transition-colors",children:s.deal_name})}),e.jsx(Xe,{variant:"outline",className:Ft("text-[10px] px-1.5 py-0 shrink-0",d.color),children:d.label})]}),s.contact&&e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(Un,{className:"h-5 w-5",children:e.jsxs(qn,{className:"text-[10px] bg-primary/10 text-primary",children:[(k=s.contact.first_name)==null?void 0:k[0],(T=s.contact.last_name)==null?void 0:T[0]]})}),e.jsxs("span",{className:"truncate",children:[s.contact.first_name," ",s.contact.last_name]})]}),s.listing&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs",children:[e.jsx(ql,{className:"h-3 w-3 text-primary shrink-0"}),e.jsx("span",{className:"text-primary truncate",children:"Linked to Listing Exchange"})]}),_&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs bg-amber-100 dark:bg-amber-900/30 text-amber-700 dark:text-amber-400 px-2 py-1 rounded",children:[e.jsx(To,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate font-medium",children:"Add to Scorecard"})]}),b&&l&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-green-600 dark:text-green-400",children:[e.jsx(ea,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate",children:"Synced to Scorecard"})]}),y!==null&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs",children:[e.jsx(h_,{className:"h-3 w-3 text-muted-foreground shrink-0"}),e.jsxs("span",{className:Ft("font-medium",y>90?"text-red-600":y>60?"text-amber-600":"text-muted-foreground"),children:[y," DOM"]}),s.contract_date&&e.jsx("span",{className:"text-muted-foreground",children:"(final)"})]}),!s.listing&&(s.property_address||s.city)&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(Fn,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate",children:s.property_address||`${s.city}, ${s.state}`})]}),s.expected_price&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs",children:[e.jsx(oc,{className:"h-3 w-3 text-emerald-500 shrink-0"}),e.jsx("span",{className:"font-semibold text-foreground",children:j(s.expected_price)}),s.expected_commission&&e.jsxs("span",{className:"text-muted-foreground",children:["• ",j(s.expected_commission)," GCI"]}),(()=>{const E=Ry(s);return E!==null&&E!==s.expected_commission?e.jsxs("span",{className:"text-teal-600 dark:text-teal-400",children:["• ",j(E)," Net"]}):null})()]}),e.jsxs("div",{className:"flex items-center justify-between pt-1 border-t border-border/50",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:Ft("flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px]",h.color),children:[e.jsx("div",{className:Ft("w-1.5 h-1.5 rounded-full",h.dot)}),e.jsx("span",{className:"capitalize",children:s.priority})]}),e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[s.probability,"%"]})]}),i&&c&&n&&a?e.jsx(kyt,{stages:n,currentStageId:s.stage_id||"",onStageSelect:(E,A)=>a(s.id,E,A)}):s.target_close_date?e.jsxs("div",{className:Ft("flex items-center gap-1 text-[10px]",p&&"text-red-600",x&&!p&&"text-amber-600",!p&&!x&&"text-muted-foreground"),children:[p?e.jsx(wo,{className:"h-3 w-3"}):e.jsx(Nn,{className:"h-3 w-3"}),e.jsx("span",{children:p?`${Math.abs(m)}d overdue`:x?`${m}d left`:As(Tc(s.target_close_date),"MMM d")})]}):null]})]})})}function GFs({stage:s,deals:t,onDealClick:r,onAddDeal:n,onDragStart:a,onDragOver:i,onDrop:l,isDragOver:o,isWonStage:c=!1,getOwnerInfo:d}){const h=S.useRef(null),m=t.reduce((b,j)=>b+(j.expected_price||0),0),p=t.reduce((b,j)=>b+(j.expected_commission||0),0),x=t.reduce((b,j)=>b+(Ry(j)||0),0),y=b=>b>=1e6?`$${(b/1e6).toFixed(1)}M`:b>=1e3?`$${(b/1e3).toFixed(0)}K`:`$${b.toFixed(0)}`,_=s.icon&&Vpe[s.icon]||Gu;return e.jsxs("div",{ref:h,className:Ft("flex flex-col h-full min-w-[280px] max-w-[320px] bg-muted/30 rounded-xl border border-border/50 transition-all duration-200",o&&"border-primary/50 bg-primary/5 ring-2 ring-primary/20"),onDragOver:b=>i(b,s.id),onDrop:b=>l(b,s.id),children:[e.jsxs("div",{className:"p-3 border-b border-border/50 shrink-0",style:{borderTopColor:s.color,borderTopWidth:3},children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-7 h-7 rounded-lg flex items-center justify-center",style:{backgroundColor:`${s.color}20`},children:e.jsx(_,{className:"h-4 w-4",style:{color:s.color}})}),e.jsx("div",{children:e.jsx("h3",{className:"font-semibold text-sm",children:s.name})})]}),e.jsx(Xe,{variant:"secondary",className:"text-xs font-medium px-2",children:t.length})]}),m>0&&e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground flex-wrap",children:[e.jsx("span",{className:"font-medium text-foreground",children:y(m)}),e.jsx("span",{children:"•"}),e.jsxs("span",{children:[y(p)," GCI"]}),x>0&&x!==p&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"•"}),e.jsxs("span",{className:"text-teal-600 dark:text-teal-400",children:[y(x)," Net"]})]})]})]}),e.jsx(Ci,{className:"flex-1 p-2",children:e.jsxs("div",{className:"space-y-2",children:[t.map(b=>e.jsx("div",{draggable:!0,onDragStart:j=>{j.dataTransfer.effectAllowed="move",a(b.id,s.id)},children:e.jsx(Syt,{deal:b,onClick:()=>r(b),isWonStage:c,ownerInfo:(d==null?void 0:d(b))||null})},b.id)),t.length===0&&e.jsxs("div",{className:"py-8 px-4 text-center text-muted-foreground text-sm",children:[e.jsx("p",{className:"mb-2",children:"No deals yet"}),e.jsx("p",{className:"text-xs",children:"Drag deals here or add new"})]})]})}),e.jsx("div",{className:"p-2 border-t border-border/50 shrink-0",children:e.jsxs(H,{variant:"ghost",size:"sm",className:"w-full justify-start text-muted-foreground hover:text-foreground",onClick:()=>n(s.id),children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Add Deal"]})})]})}function WFs({stats:s,isLoading:t}){const r=a=>a>=1e6?`$${(a/1e6).toFixed(1)}M`:a>=1e3?`$${(a/1e3).toFixed(0)}K`:`$${a.toLocaleString()}`,n=[{label:"Active Deals",value:(s==null?void 0:s.activeDeals)||0,icon:Wu,color:"text-blue-500",bgColor:"bg-blue-500/10"},{label:"Weighted GCI",value:r((s==null?void 0:s.weightedGCI)||0),icon:EF,color:"text-indigo-500",bgColor:"bg-indigo-500/10",tooltip:"GCI adjusted by each deal's win probability"},{label:"Weighted Net",value:r((s==null?void 0:s.weightedNet)||0),icon:UF,color:"text-teal-500",bgColor:"bg-teal-500/10",tooltip:"Net to Agent adjusted by each deal's win probability"},{label:"YTD Closed Net",value:r((s==null?void 0:s.ytdWonNet)||0),icon:tF,color:"text-green-500",bgColor:"bg-green-500/10",subtitle:`${(s==null?void 0:s.ytdWonDeals)||0} deals`,tooltip:"Net commission from deals closed this year"},{label:"Projected Annual",value:r((s==null?void 0:s.projectedAnnualNet)||0),icon:al,color:"text-amber-500",bgColor:"bg-amber-500/10",tooltip:"YTD Closed Net + Weighted Active Net"}];return t?e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3",children:[1,2,3,4,5].map(a=>e.jsx(ke,{className:"animate-pulse",children:e.jsx(Oe,{className:"p-4",children:e.jsx("div",{className:"h-10 bg-muted rounded"})})},a))}):e.jsx(xj,{children:e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3",children:n.map(a=>{const i=e.jsx(ke,{className:"border-border/50 hover:shadow-sm transition-shadow",children:e.jsx(Oe,{className:"p-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:Ft("p-2 rounded-lg",a.bgColor),children:e.jsx(a.icon,{className:Ft("h-5 w-5",a.color)})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:a.label}),e.jsx("p",{className:"text-xl font-bold",children:a.value}),"subtitle"in a&&a.subtitle&&e.jsx("p",{className:"text-[10px] text-muted-foreground",children:a.subtitle})]})]})})},a.label);return"tooltip"in a&&a.tooltip?e.jsxs(rd,{children:[e.jsx(nd,{asChild:!0,children:i}),e.jsx(Rc,{children:e.jsx("p",{children:a.tooltip})})]},a.label):i})})})}function KFs({formData:s,onChange:t,isEditing:r}){const{isAdmin:n}=Ms(),[a,i]=S.useState(s.portal_enabled);if(!n)return e.jsxs("div",{className:"border rounded-lg p-4 opacity-60",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Lr,{className:"h-4 w-4 text-primary"}),e.jsx("h4",{className:"font-medium text-sm",children:"Client Portal"}),e.jsx(Xe,{variant:"secondary",className:"text-xs",children:"Coming Soon"})]})}),e.jsx("p",{className:"text-xs text-muted-foreground mt-2",children:"Give your clients a premium, real-time view of their transaction — coming soon!"})]});const l=o=>{t({...s,...o})};return e.jsx(m0,{open:a,onOpenChange:i,children:e.jsxs("div",{className:"border rounded-lg",children:[e.jsxs(f0,{className:"w-full p-4 flex items-center justify-between hover:bg-muted/50 transition-colors rounded-t-lg",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Lr,{className:"h-4 w-4 text-primary"}),e.jsx("h4",{className:"font-medium text-sm",children:"Client Portal"}),s.portal_enabled&&e.jsx(Xe,{className:"text-xs bg-emerald-500/10 text-emerald-600 border-emerald-200",variant:"outline",children:"Enabled"})]}),e.jsx(Io,{className:Ft("h-4 w-4 text-muted-foreground transition-transform",a&&"rotate-180")})]}),e.jsx(p0,{children:e.jsxs("div",{className:"px-4 pb-4 space-y-5 border-t pt-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ue,{className:"text-sm font-medium",children:"Enable Client Portal"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:"Create a beautiful portal your client can track their deal from"})]}),e.jsx(Or,{checked:s.portal_enabled,onCheckedChange:o=>l({portal_enabled:o})})]}),s.portal_enabled&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(ue,{className:"text-sm font-medium",children:"Portal Visibility"}),e.jsxs(I2,{value:s.visibility,onValueChange:o=>l({visibility:o}),className:"grid grid-cols-2 gap-3",children:[e.jsxs("label",{className:Ft("flex items-center gap-3 p-3 rounded-lg border cursor-pointer transition-colors",s.visibility==="private"?"border-primary bg-primary/5":"hover:bg-muted/50"),children:[e.jsx(ih,{value:"private"}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Td,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"text-sm font-medium",children:"Private"})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:"Link-only access"})]})]}),e.jsxs("label",{className:Ft("flex items-center gap-3 p-3 rounded-lg border cursor-pointer transition-colors",s.visibility==="public"?"border-primary bg-primary/5":"hover:bg-muted/50"),children:[e.jsx(ih,{value:"public"}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(ld,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"text-sm font-medium",children:"Public"})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:"Shareable link"})]})]})]})]}),e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg bg-muted/30",children:[e.jsx(ao,{id:"require_onboarding",checked:s.require_onboarding,onCheckedChange:o=>l({require_onboarding:!!o}),className:"mt-0.5"}),e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"require_onboarding",className:"text-sm font-medium cursor-pointer",children:"Require client onboarding before portal access"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:"Client confirms contact details + preferences before viewing portal. Info is saved to your contacts."})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ao,{id:"allow_spouse",checked:s.allow_spouse,onCheckedChange:o=>l({allow_spouse:!!o})}),e.jsx(ue,{htmlFor:"allow_spouse",className:"text-sm cursor-pointer",children:"Allow client to add spouse/partner during onboarding"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(ue,{className:"text-sm font-medium",children:"Client Invite Details"}),e.jsxs("div",{className:"grid grid-cols-1 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{className:"text-xs text-muted-foreground",children:"Client Full Name"}),e.jsx(Se,{value:s.client_name,onChange:o=>l({client_name:o.target.value}),placeholder:"Jane Smith"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{className:"text-xs text-muted-foreground",children:"Email"}),e.jsx(Se,{type:"email",value:s.client_email,onChange:o=>l({client_email:o.target.value}),placeholder:"jane@example.com"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{className:"text-xs text-muted-foreground",children:"Phone"}),e.jsx(Se,{type:"tel",value:s.client_phone,onChange:o=>l({client_phone:o.target.value}),placeholder:"(555) 123-4567"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{className:"text-xs text-muted-foreground",children:"Preferred Invite Method"}),e.jsxs(Bs,{value:s.invite_method,onValueChange:o=>l({invite_method:o}),children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"email",children:"Email"}),e.jsxs(pt,{value:"sms",disabled:!s.client_phone,children:["SMS ",!s.client_phone&&"(add phone first)"]})]})]})]})]})]})]})]})})]})})}const YFs=[{value:"buyer",label:"Buyer"},{value:"seller",label:"Seller"},{value:"dual",label:"Dual Agency"},{value:"referral",label:"Referral"},{value:"lease",label:"Lease"}],ZFs=[{value:"low",label:"Low"},{value:"medium",label:"Medium"},{value:"high",label:"High"},{value:"urgent",label:"Urgent"}];function XFs({open:s,onOpenChange:t,deal:r,defaultStageId:n}){const{data:a}=F0e(),{data:i}=Cp(),{data:l}=vot(),o=Qge(),c=vxt(),d=bxt(),h=dMe(),[m,p]=S.useState({portal_enabled:!1,visibility:"private",require_onboarding:!0,allow_spouse:!1,client_name:"",client_email:"",client_phone:"",invite_method:"email"}),[x,y]=S.useState(""),[_,b]=S.useState(!1),[j,k]=S.useState(!1),[T,E]=S.useState({first_name:"",last_name:"",email:"",phone:""}),A=(l==null?void 0:l.filter(J=>((r==null?void 0:r.listing_id)===J.id,!0)))||[],[D,R]=S.useState({deal_name:"",deal_type:"buyer",stage_id:"",contact_id:"",listing_id:"",property_address:"",city:"",state:"",zip_code:"",expected_price:"",commission_percentage:"3",brokerage_split_pct:"",team_split_pct:"",referral_fee_pct:"",franchise_fee_pct:"",transaction_fee:"",commission_calc_method:"standard",target_close_date:void 0,contract_date:void 0,listing_date:void 0,priority:"medium",probability:"50",notes:""});S.useEffect(()=>{var J,K,re,ie,ce,ne,le,be;s&&(r?(R({deal_name:r.deal_name,deal_type:r.deal_type,stage_id:r.stage_id||"",contact_id:r.contact_id||"",listing_id:r.listing_id||"",property_address:r.property_address||"",city:r.city||"",state:r.state||"",zip_code:r.zip_code||"",expected_price:((J=r.expected_price)==null?void 0:J.toString())||"",commission_percentage:((K=r.commission_percentage)==null?void 0:K.toString())||"3",brokerage_split_pct:((re=r.brokerage_split_pct)==null?void 0:re.toString())||"",team_split_pct:((ie=r.team_split_pct)==null?void 0:ie.toString())||"",referral_fee_pct:((ce=r.referral_fee_pct)==null?void 0:ce.toString())||"",franchise_fee_pct:((ne=r.franchise_fee_pct)==null?void 0:ne.toString())||"",transaction_fee:((le=r.transaction_fee)==null?void 0:le.toString())||"",commission_calc_method:r.commission_calc_method||"standard",target_close_date:r.target_close_date?Tc(r.target_close_date):void 0,contract_date:r.contract_date?Tc(r.contract_date):void 0,listing_date:r.listing_date?Tc(r.listing_date):void 0,priority:r.priority,probability:r.probability.toString(),notes:r.notes||""}),r.contact&&y(`${r.contact.first_name} ${r.contact.last_name}`)):(R({deal_name:"",deal_type:"buyer",stage_id:n||((be=a==null?void 0:a[0])==null?void 0:be.id)||"",contact_id:"",listing_id:"",property_address:"",city:"",state:"",zip_code:"",expected_price:"",commission_percentage:"3",brokerage_split_pct:"",team_split_pct:"",referral_fee_pct:"",franchise_fee_pct:"",transaction_fee:"",commission_calc_method:"standard",target_close_date:void 0,contract_date:void 0,listing_date:void 0,priority:"medium",probability:"50",notes:""}),y(""),p({portal_enabled:!1,visibility:"private",require_onboarding:!0,allow_spouse:!1,client_name:"",client_email:"",client_phone:"",invite_method:"email"})))},[s,r,n,a]);const z=i==null?void 0:i.filter(J=>{var je,ve,We,Ve,Le;const K=x.toLowerCase().trim();if(!K)return!0;const re=((je=J.first_name)==null?void 0:je.toLowerCase())||"",ie=((ve=J.last_name)==null?void 0:ve.toLowerCase())||"",ce=((We=J.email)==null?void 0:We.toLowerCase())||"",ne=((Le=(Ve=J.phone)==null?void 0:Ve.toLowerCase)==null?void 0:Le.call(Ve))||"",le=`${re} ${ie}`.trim(),be=`${ie} ${re}`.trim();if(le.includes(K)||be.includes(K)||re.includes(K)||ie.includes(K)||ce.includes(K)||ne.includes(K))return!0;const fe=K.split(/\s+/).filter(Boolean);return fe.length>1?fe.every(Me=>re.includes(Me)||ie.includes(Me)||ce.includes(Me)||ne.includes(Me)):!1}).slice(0,8),O=()=>{const J=parseFloat(D.expected_price)||0,K=parseFloat(D.commission_percentage)||0;return J*(K/100)},$=()=>{const J=O();if(!J)return null;const K=parseFloat(D.brokerage_split_pct)||0,re=parseFloat(D.team_split_pct)||0,ie=parseFloat(D.referral_fee_pct)||0,ce=parseFloat(D.franchise_fee_pct)||0,ne=parseFloat(D.transaction_fee)||0;if(D.commission_calc_method==="referral_first"){let be=J;ie&&(be-=J*ie/100);let fe=be;return K&&(fe-=be*K/100),re&&(fe-=J*re/100),ce&&(fe-=J*ce/100),ne&&(fe-=ne),Math.max(0,fe)}let le=J;return K&&(le=le*((100-K)/100)),re&&(le=le*((100-re)/100)),ie&&(le=le-J*ie/100),ce&&(le=le-J*ce/100),ne&&(le=le-ne),Math.max(0,le)},ee=async J=>{var K,re,ie;if(J.preventDefault(),!D.deal_name.trim()){he.error("Please enter a deal name");return}try{const ce={deal_name:D.deal_name,deal_type:D.deal_type,stage_id:D.stage_id||null,contact_id:D.contact_id||null,listing_id:D.listing_id||null,property_address:D.property_address||null,city:D.city||null,state:D.state||null,zip_code:D.zip_code||null,expected_price:D.expected_price?parseFloat(D.expected_price):null,expected_commission:O()||null,commission_percentage:D.commission_percentage?parseFloat(D.commission_percentage):3,brokerage_split_pct:D.brokerage_split_pct?parseFloat(D.brokerage_split_pct):null,team_split_pct:D.team_split_pct?parseFloat(D.team_split_pct):null,referral_fee_pct:D.referral_fee_pct?parseFloat(D.referral_fee_pct):null,franchise_fee_pct:D.franchise_fee_pct?parseFloat(D.franchise_fee_pct):null,transaction_fee:D.transaction_fee?parseFloat(D.transaction_fee):null,commission_calc_method:D.commission_calc_method,target_close_date:((K=D.target_close_date)==null?void 0:K.toISOString().split("T")[0])||null,contract_date:((re=D.contract_date)==null?void 0:re.toISOString().split("T")[0])||null,listing_date:((ie=D.listing_date)==null?void 0:ie.toISOString().split("T")[0])||null,priority:D.priority,probability:parseInt(D.probability)||50,notes:D.notes||null};if(r)await d.mutateAsync({id:r.id,...ce}),he.success("Deal updated successfully");else{const ne=await c.mutateAsync(ce);if(he.success("Deal created successfully"),m.portal_enabled&&(ne!=null&&ne.id))try{await h.mutateAsync({deal_id:ne.id,visibility:m.visibility,require_onboarding:m.require_onboarding,allow_spouse:m.allow_spouse,client_name:m.client_name||null,client_email:m.client_email||null,client_phone:m.client_phone||null,invite_method:m.invite_method}),he.success("Client portal created!")}catch{he.error("Deal created, but portal setup failed")}}t(!1)}catch{he.error("Failed to save deal")}},Z=c.isPending||d.isPending;return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Cs,{children:[e.jsx(Ns,{children:r?"Edit Deal":"Add New Deal"}),e.jsx(nn,{children:r?"Update the deal details below.":"Enter the details for your new deal."})]}),e.jsxs("form",{onSubmit:ee,className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"col-span-2 space-y-2",children:[e.jsx(ue,{htmlFor:"deal_name",children:"Deal Name *"}),e.jsx(Se,{id:"deal_name",value:D.deal_name,onChange:J=>R(K=>({...K,deal_name:J.target.value})),placeholder:"e.g., Smith Family - 123 Main St"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Deal Type"}),e.jsxs(Bs,{value:D.deal_type,onValueChange:J=>R(K=>({...K,deal_type:J})),children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsx(Fs,{children:YFs.map(J=>e.jsx(pt,{value:J.value,children:J.label},J.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Stage"}),e.jsxs(Bs,{value:D.stage_id||"none",onValueChange:J=>R(K=>({...K,stage_id:J==="none"?"":J})),children:[e.jsx(Os,{children:e.jsx(Us,{placeholder:"Select stage"})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"none",children:"No Stage"}),a==null?void 0:a.map(J=>e.jsx(pt,{value:J.id,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full",style:{backgroundColor:J.color}}),J.name]})},J.id))]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Link to Contact"}),e.jsxs("div",{className:"relative",children:[e.jsx(Mn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Se,{value:x,onChange:J=>{y(J.target.value),b(!0),k(!1),J.target.value||R(K=>({...K,contact_id:""}))},onFocus:()=>b(!0),placeholder:"Search contacts...",className:"pl-9"}),_&&x&&e.jsxs("div",{className:"absolute z-10 w-full mt-1 bg-background border rounded-lg shadow-lg max-h-60 overflow-y-auto",children:[z&&z.length>0?z.map(J=>e.jsxs("button",{type:"button",className:"w-full px-3 py-2 text-left hover:bg-muted flex items-center gap-2",onClick:()=>{R(K=>({...K,contact_id:J.id})),y(`${J.first_name} ${J.last_name}`),b(!1)},children:[e.jsx(io,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:[J.first_name," ",J.last_name]}),J.email&&e.jsx("span",{className:"text-xs text-muted-foreground ml-auto",children:J.email})]},J.id)):e.jsx("div",{className:"px-3 py-2 text-sm text-muted-foreground",children:"No contacts found"}),e.jsxs("button",{type:"button",className:"w-full px-3 py-2 text-left hover:bg-muted flex items-center gap-2 border-t text-primary font-medium",onClick:()=>{const J=x.trim().split(/\s+/);E({first_name:J[0]||"",last_name:J.slice(1).join(" ")||"",email:"",phone:""}),k(!0),b(!1)},children:[e.jsx(Vl,{className:"h-4 w-4"}),e.jsxs("span",{children:['Create new contact "',x.trim(),'"']})]})]})]}),j&&e.jsxs("div",{className:"border rounded-lg p-3 space-y-3 bg-muted/30",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-sm font-medium flex items-center gap-1.5",children:[e.jsx(Vl,{className:"h-3.5 w-3.5"}),"Quick Add Contact"]}),e.jsx(H,{type:"button",variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:()=>k(!1),children:"Cancel"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(Se,{placeholder:"First name *",value:T.first_name,onChange:J=>E(K=>({...K,first_name:J.target.value})),className:"h-8 text-sm"}),e.jsx(Se,{placeholder:"Last name",value:T.last_name,onChange:J=>E(K=>({...K,last_name:J.target.value})),className:"h-8 text-sm"}),e.jsx(Se,{placeholder:"Email",type:"email",value:T.email,onChange:J=>E(K=>({...K,email:J.target.value})),className:"h-8 text-sm"}),e.jsx(Se,{placeholder:"Phone",type:"tel",value:T.phone,onChange:J=>E(K=>({...K,phone:J.target.value})),className:"h-8 text-sm"})]}),e.jsx(H,{type:"button",size:"sm",className:"w-full h-8",disabled:!T.first_name.trim()||o.isPending,onClick:async()=>{try{const J=await o.mutateAsync({first_name:T.first_name.trim(),last_name:T.last_name.trim()||null,email:T.email.trim()||null,phone:T.phone.trim()||null});J&&(R(K=>({...K,contact_id:J.id})),y(`${J.first_name} ${J.last_name||""}`.trim()),k(!1))}catch{}},children:o.isPending?e.jsxs(e.Fragment,{children:[e.jsx(is,{className:"h-3.5 w-3.5 mr-1 animate-spin"})," Creating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Vl,{className:"h-3.5 w-3.5 mr-1"})," Add & Link Contact"]})})]})]}),A.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ue,{className:"flex items-center gap-2",children:[e.jsx(ql,{className:"h-4 w-4"}),"Link to Listing Exchange"]}),e.jsxs(Bs,{value:D.listing_id||"none",onValueChange:J=>{const K=J==="none"?"":J,re=A.find(ie=>ie.id===K);R(re?ie=>{var ce;return{...ie,listing_id:K,deal_type:"seller",property_address:re.property_address||ie.property_address,city:re.city||ie.city,state:re.state||ie.state,expected_price:((ce=re.price)==null?void 0:ce.toString())||ie.expected_price}}:ie=>({...ie,listing_id:K}))},children:[e.jsx(Os,{children:e.jsx(Us,{placeholder:"Select a listing to sync status..."})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"none",children:"None"}),A.map(J=>e.jsx(pt,{value:J.id,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{children:J.property_address||`${J.city}, ${J.state}`}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["$",(J.price/1e3).toFixed(0),"K"]})]})},J.id))]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Status changes will sync automatically between the deal and listing."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h4",{className:"font-medium text-sm",children:"Property Details"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"col-span-2 space-y-2",children:[e.jsx(ue,{htmlFor:"property_address",children:"Address"}),e.jsx(Se,{id:"property_address",value:D.property_address,onChange:J=>R(K=>({...K,property_address:J.target.value})),placeholder:"123 Main Street"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"city",children:"City"}),e.jsx(Se,{id:"city",value:D.city,onChange:J=>R(K=>({...K,city:J.target.value}))})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"state",children:"State"}),e.jsx(Se,{id:"state",value:D.state,onChange:J=>R(K=>({...K,state:J.target.value})),maxLength:2,placeholder:"TX"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"zip_code",children:"ZIP"}),e.jsx(Se,{id:"zip_code",value:D.zip_code,onChange:J=>R(K=>({...K,zip_code:J.target.value}))})]})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h4",{className:"font-medium text-sm",children:"Financial Details"}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"expected_price",children:"Expected Price"}),e.jsxs("div",{className:"relative",children:[e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground",children:"$"}),e.jsx(Se,{id:"expected_price",type:"number",value:D.expected_price,onChange:J=>R(K=>({...K,expected_price:J.target.value})),className:"pl-7",placeholder:"500000"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"commission_percentage",children:"Commission %"}),e.jsxs("div",{className:"relative",children:[e.jsx(Se,{id:"commission_percentage",type:"number",step:"0.1",value:D.commission_percentage,onChange:J=>R(K=>({...K,commission_percentage:J.target.value})),className:"pr-7"}),e.jsx("span",{className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground",children:"%"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Expected GCI"}),e.jsx(Se,{value:O()?`$${O().toLocaleString()}`:"-",disabled:!0,className:"bg-muted"})]})]}),e.jsxs("details",{className:"group",children:[e.jsxs("summary",{className:"text-xs font-medium text-muted-foreground cursor-pointer hover:text-foreground flex items-center gap-1 py-1",children:[e.jsx("span",{className:"group-open:rotate-90 transition-transform text-[10px]",children:"▶"}),"Commission Splits (optional)"]}),e.jsxs("div",{className:"space-y-3 mt-3",children:[e.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-lg bg-muted/50",children:[e.jsx(ue,{className:"text-xs whitespace-nowrap",children:"Calculation Method:"}),e.jsxs(Bs,{value:D.commission_calc_method,onValueChange:J=>R(K=>({...K,commission_calc_method:J})),children:[e.jsx(Os,{className:"h-7 text-xs",children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"standard",children:"Standard (all splits on GCI)"}),e.jsx(pt,{value:"referral_first",children:"Referral First (brokerage split after referral)"})]})]})]}),D.commission_calc_method==="referral_first"&&e.jsx("p",{className:"text-[10px] text-muted-foreground bg-blue-50 dark:bg-blue-950/30 p-2 rounded",children:"💡 Referral fee is deducted from GCI first, then the brokerage split is applied to the remaining amount."}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{className:"text-xs",children:"Brokerage Split"}),e.jsxs("div",{className:"relative",children:[e.jsx(Se,{type:"number",step:"1",min:"0",max:"100",value:D.brokerage_split_pct,onChange:J=>R(K=>({...K,brokerage_split_pct:J.target.value})),className:"pr-7 h-8 text-sm",placeholder:"30"}),e.jsx("span",{className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground text-xs",children:"%"})]}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"% that goes to brokerage"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{className:"text-xs",children:"Team Split"}),e.jsxs("div",{className:"relative",children:[e.jsx(Se,{type:"number",step:"1",min:"0",max:"100",value:D.team_split_pct,onChange:J=>R(K=>({...K,team_split_pct:J.target.value})),className:"pr-7 h-8 text-sm",placeholder:"0"}),e.jsx("span",{className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground text-xs",children:"%"})]}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"% that goes to team lead"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{className:"text-xs",children:"Referral Fee"}),e.jsxs("div",{className:"relative",children:[e.jsx(Se,{type:"number",step:"1",min:"0",max:"100",value:D.referral_fee_pct,onChange:J=>R(K=>({...K,referral_fee_pct:J.target.value})),className:"pr-7 h-8 text-sm",placeholder:"0"}),e.jsx("span",{className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground text-xs",children:"%"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{className:"text-xs",children:"Franchise Fee"}),e.jsxs("div",{className:"relative",children:[e.jsx(Se,{type:"number",step:"1",min:"0",max:"100",value:D.franchise_fee_pct,onChange:J=>R(K=>({...K,franchise_fee_pct:J.target.value})),className:"pr-7 h-8 text-sm",placeholder:"0"}),e.jsx("span",{className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground text-xs",children:"%"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{className:"text-xs",children:"Transaction Fee"}),e.jsxs("div",{className:"relative",children:[e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground text-xs",children:"$"}),e.jsx(Se,{type:"number",step:"1",min:"0",value:D.transaction_fee,onChange:J=>R(K=>({...K,transaction_fee:J.target.value})),className:"pl-7 h-8 text-sm",placeholder:"500"})]}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Flat fee deducted"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{className:"text-xs",children:"Net to Agent"}),e.jsx(Se,{value:$()?`$${Math.round($()).toLocaleString()}`:"-",disabled:!0,className:"bg-muted h-8 text-sm font-semibold"})]})]})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h4",{className:"font-medium text-sm",children:"Dates & Status"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Target Close Date"}),e.jsxs(gl,{children:[e.jsx(xl,{asChild:!0,children:e.jsxs(H,{variant:"outline",className:Ft("w-full justify-start text-left font-normal",!D.target_close_date&&"text-muted-foreground"),children:[e.jsx(Nn,{className:"mr-2 h-4 w-4"}),D.target_close_date?As(D.target_close_date,"PPP"):"Pick a date"]})}),e.jsx(il,{className:"w-auto p-0",align:"start",children:e.jsx(g0,{mode:"single",selected:D.target_close_date,onSelect:J=>R(K=>({...K,target_close_date:J})),initialFocus:!0,className:"pointer-events-auto"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Contract Date"}),e.jsxs(gl,{children:[e.jsx(xl,{asChild:!0,children:e.jsxs(H,{variant:"outline",className:Ft("w-full justify-start text-left font-normal",!D.contract_date&&"text-muted-foreground"),children:[e.jsx(Nn,{className:"mr-2 h-4 w-4"}),D.contract_date?As(D.contract_date,"PPP"):"Pick a date"]})}),e.jsx(il,{className:"w-auto p-0",align:"start",children:e.jsx(g0,{mode:"single",selected:D.contract_date,onSelect:J=>R(K=>({...K,contract_date:J})),initialFocus:!0,className:"pointer-events-auto"})})]})]}),(D.deal_type==="seller"||D.deal_type==="dual")&&!D.listing_id&&e.jsxs("div",{className:"space-y-2 col-span-2",children:[e.jsx(ue,{children:"Listing Date (for Days on Market)"}),e.jsxs(gl,{children:[e.jsx(xl,{asChild:!0,children:e.jsxs(H,{variant:"outline",className:Ft("w-full justify-start text-left font-normal",!D.listing_date&&"text-muted-foreground"),children:[e.jsx(Nn,{className:"mr-2 h-4 w-4"}),D.listing_date?As(D.listing_date,"PPP"):"Pick a date"]})}),e.jsx(il,{className:"w-auto p-0",align:"start",children:e.jsx(g0,{mode:"single",selected:D.listing_date,onSelect:J=>R(K=>({...K,listing_date:J})),initialFocus:!0,className:"pointer-events-auto"})})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Used to calculate Days on Market. Auto-filled for linked listings."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Priority"}),e.jsxs(Bs,{value:D.priority,onValueChange:J=>R(K=>({...K,priority:J})),children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsx(Fs,{children:ZFs.map(J=>e.jsx(pt,{value:J.value,children:J.label},J.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Win Probability"}),e.jsxs("div",{className:"relative",children:[e.jsx(Se,{type:"number",min:"0",max:"100",value:D.probability,onChange:J=>R(K=>({...K,probability:J.target.value})),className:"pr-7"}),e.jsx("span",{className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground",children:"%"})]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"notes",children:"Notes"}),e.jsx(vr,{id:"notes",value:D.notes,onChange:J=>R(K=>({...K,notes:J.target.value})),placeholder:"Add any additional notes about this deal...",rows:3})]}),!r&&e.jsx(KFs,{formData:m,onChange:p}),e.jsxs("div",{className:"flex justify-end gap-3 pt-4 border-t",children:[e.jsx(H,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(H,{type:"submit",disabled:Z,children:[Z&&e.jsx(is,{className:"h-4 w-4 mr-2 animate-spin"}),r?"Update Deal":"Create Deal"]})]})]})]})})}function QFs({dealId:s}){const t=ba(),r=ns(),[n,a]=S.useState(""),[i,l]=S.useState(!1),{data:o=[]}=yt({queryKey:["deal-tags",s],queryFn:async()=>{const{data:y,error:_}=await V.from("deal_tags").select("*").eq("deal_id",s).order("created_at");if(_)throw _;return y},enabled:!!s}),{data:c=[]}=yt({queryKey:["all-deal-tags",t],queryFn:async()=>{if(!t)return[];const{data:y,error:_}=await V.from("deal_tags").select("tag").eq("owner_user_id",t);if(_)throw _;return[...new Set(y.map(j=>j.tag))].sort()},enabled:!!t}),d=Pt({mutationFn:async y=>{if(!t)throw new Error("Not authenticated");const{error:_}=await V.from("deal_tags").insert({deal_id:s,owner_user_id:t,tag:y.trim()});if(_)throw _},onSuccess:()=>{r.invalidateQueries({queryKey:["deal-tags",s]}),r.invalidateQueries({queryKey:["all-deal-tags"]}),a("")}}),h=Pt({mutationFn:async y=>{const{error:_}=await V.from("deal_tags").delete().eq("id",y);if(_)throw _},onSuccess:()=>{r.invalidateQueries({queryKey:["deal-tags",s]})}}),m=()=>{const y=n.trim();y&&(o.some(_=>_.tag.toLowerCase()===y.toLowerCase())||d.mutate(y))},p=o.map(y=>y.tag.toLowerCase()),x=c.filter(y=>y.toLowerCase().includes(n.toLowerCase())&&!p.includes(y.toLowerCase())).slice(0,5);return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[o.map(y=>e.jsxs(Xe,{variant:"secondary",className:"gap-1 text-xs",children:[y.tag,e.jsx("button",{type:"button",onClick:()=>h.mutate(y.id),className:"ml-0.5 hover:text-destructive",children:e.jsx(Rr,{className:"h-3 w-3"})})]},y.id)),!i&&e.jsxs("button",{type:"button",onClick:()=>l(!0),className:"flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground px-2 py-0.5 rounded border border-dashed border-border hover:border-primary transition-colors",children:[e.jsx(Ys,{className:"h-3 w-3"})," Add tag"]})]}),i&&e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx(Se,{value:n,onChange:y=>a(y.target.value),onKeyDown:y=>{y.key==="Enter"&&(y.preventDefault(),m()),y.key==="Escape"&&(l(!1),a(""))},placeholder:"Type tag name...",className:"h-8 text-xs flex-1",autoFocus:!0}),e.jsx("button",{type:"button",onClick:m,disabled:!n.trim()||d.isPending,className:"h-8 px-3 rounded-md bg-primary text-primary-foreground text-xs font-medium disabled:opacity-50 shrink-0",children:"Add"}),e.jsx("button",{type:"button",onClick:()=>{l(!1),a("")},className:"h-8 px-2 rounded-md bg-muted text-muted-foreground text-xs shrink-0",children:"Cancel"})]}),n&&x.length>0&&e.jsx("div",{className:"absolute z-20 w-full mt-1 bg-background border rounded shadow-lg max-h-32 overflow-y-auto",children:x.map(y=>e.jsx("button",{type:"button",className:"w-full px-3 py-2 text-left text-xs hover:bg-muted active:bg-muted",onClick:_=>{_.preventDefault(),d.mutate(y)},children:y},y))})]})]})}function JFs(s){return yt({queryKey:["deal-files",s],queryFn:async()=>{const{data:t,error:r}=await V.from("deal_files").select("*").eq("deal_id",s).order("created_at",{ascending:!1});if(r)throw r;return t},enabled:!!s})}function e7s(){const s=ba(),t=ns();return Pt({mutationFn:async({dealId:r,file:n})=>{if(!s)throw new Error("Not authenticated");const a=n.name.split(".").pop(),i=`${s}/${r}/${crypto.randomUUID()}.${a}`,{error:l}=await V.storage.from("deal-files").upload(i,n);if(l)throw l;const{data:o,error:c}=await V.from("deal_files").insert({deal_id:r,owner_user_id:s,file_name:n.name,file_size:n.size,file_type:n.type||null,storage_path:i}).select().single();if(c)throw c;return o},onSuccess:(r,n)=>{t.invalidateQueries({queryKey:["deal-files",n.dealId]})}})}function t7s(){const s=ns();return Pt({mutationFn:async({fileId:t,storagePath:r,dealId:n})=>{await V.storage.from("deal-files").remove([r]);const{error:a}=await V.from("deal_files").delete().eq("id",t);if(a)throw a;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["deal-files",t]})}})}function s7s(){const s=ns();return Pt({mutationFn:async({fileId:t,visible:r,dealId:n})=>{const{error:a}=await V.from("deal_files").update({visible_on_portal:r}).eq("id",t);if(a)throw a;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["deal-files",t]})}})}async function r7s(s){const{data:t,error:r}=await V.storage.from("deal-files").createSignedUrl(s,3600);if(r)throw r;return t.signedUrl}const cWe={text:"Short Text",textarea:"Long Text",dropdown:"Dropdown",toggle:"Yes / No"};function Cyt({open:s,onOpenChange:t}){const{data:r,isLoading:n}=Z8s(),a=X8s(),i=Q8s(),l=J8s(),[o,c]=S.useState(!1),[d,h]=S.useState({question_text:"",field_type:"text",options:[],is_required:!1}),[m,p]=S.useState(""),x=async()=>{if(d.question_text.trim())try{await a.mutateAsync({question_text:d.question_text.trim(),field_type:d.field_type,options:d.field_type==="dropdown"?d.options:[],is_required:d.is_required,sort_order:((r==null?void 0:r.length)||0)+1}),h({question_text:"",field_type:"text",options:[],is_required:!1}),p(""),c(!1),he.success("Question added")}catch{he.error("Failed to add question")}},y=async k=>{try{await l.mutateAsync(k),he.success("Question removed")}catch{he.error("Failed to remove question")}},_=async(k,T)=>{try{await i.mutateAsync({id:k,is_required:T})}catch{he.error("Failed to update question")}},b=()=>{m.trim()&&(h(k=>({...k,options:[...k.options,m.trim()]})),p(""))},j=k=>{h(T=>({...T,options:T.options.filter((E,A)=>A!==k)}))};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-md max-h-[85vh] flex flex-col",children:[e.jsxs(Cs,{children:[e.jsx(Ns,{children:"Custom Intake Questions"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"These questions appear on all your portal onboarding forms."})]}),e.jsx(Ci,{className:"flex-1",children:e.jsxs("div",{className:"space-y-3 pr-2",children:[n&&e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(is,{className:"h-5 w-5 animate-spin text-muted-foreground"})}),r==null?void 0:r.map(k=>{var T;return e.jsx("div",{className:"border rounded-lg p-3 space-y-2",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Oh,{className:"h-4 w-4 text-muted-foreground/40 mt-0.5 flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium",children:k.question_text}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(Xe,{variant:"secondary",className:"text-xs",children:cWe[k.field_type]||k.field_type}),k.is_required&&e.jsx(Xe,{variant:"outline",className:"text-xs",children:"Required"})]}),k.field_type==="dropdown"&&((T=k.options)==null?void 0:T.length)>0&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Options: ",k.options.join(", ")]})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[e.jsx(Or,{checked:k.is_required,onCheckedChange:E=>_(k.id,E),className:"scale-75"}),e.jsx(H,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-destructive",onClick:()=>y(k.id),children:e.jsx(Dr,{className:"h-3.5 w-3.5"})})]})]})},k.id)}),!n&&(r==null?void 0:r.length)===0&&!o&&e.jsxs("div",{className:"text-center py-8 border border-dashed rounded-lg",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:"No custom questions yet"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Add questions that clients will answer during onboarding."})]}),o&&e.jsxs("div",{className:"border-2 border-primary/20 rounded-lg p-4 space-y-3 bg-primary/5",children:[e.jsxs("div",{children:[e.jsx(ue,{className:"text-sm font-medium",children:"Question"}),e.jsx(Se,{value:d.question_text,onChange:k=>h(T=>({...T,question_text:k.target.value})),className:"mt-1",placeholder:"e.g., Do you have a home to sell first?",autoFocus:!0})]}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-sm font-medium",children:"Answer Type"}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:Object.entries(cWe).map(([k,T])=>e.jsx("button",{type:"button",onClick:()=>h(E=>({...E,field_type:k,options:[]})),className:`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors ${d.field_type===k?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:border-primary/50"}`,children:T},k))})]}),d.field_type==="dropdown"&&e.jsxs("div",{children:[e.jsx(ue,{className:"text-sm font-medium",children:"Options"}),e.jsxs("div",{className:"space-y-1.5 mt-1.5",children:[d.options.map((k,T)=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"flex-1 text-sm bg-muted/50 rounded px-2 py-1",children:k}),e.jsx("button",{onClick:()=>j(T),className:"text-muted-foreground hover:text-destructive",children:e.jsx(Rr,{className:"h-3.5 w-3.5"})})]},T)),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Se,{value:m,onChange:k=>p(k.target.value),onKeyDown:k=>k.key==="Enter"&&(k.preventDefault(),b()),placeholder:"Add option...",className:"h-8 text-sm"}),e.jsx(H,{variant:"outline",size:"sm",onClick:b,disabled:!m.trim(),className:"h-8",children:e.jsx(Ys,{className:"h-3 w-3"})})]})]})]}),e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Or,{checked:d.is_required,onCheckedChange:k=>h(T=>({...T,is_required:k}))}),e.jsx(ue,{className:"text-xs text-muted-foreground",children:"Required"})]})}),e.jsxs("div",{className:"flex gap-2 pt-1",children:[e.jsx(H,{variant:"outline",size:"sm",onClick:()=>c(!1),className:"flex-1",children:"Cancel"}),e.jsxs(H,{size:"sm",onClick:x,disabled:!d.question_text.trim()||a.isPending,className:"flex-1",children:[a.isPending?e.jsx(is,{className:"h-3 w-3 mr-1 animate-spin"}):null,"Add Question"]})]})]})]})}),e.jsxs("div",{className:"flex justify-between pt-4 border-t shrink-0",children:[o?e.jsx("div",{}):e.jsxs(H,{variant:"outline",size:"sm",onClick:()=>c(!0),children:[e.jsx(Ys,{className:"h-4 w-4 mr-1"})," Add Question"]}),e.jsx(H,{variant:"ghost",size:"sm",onClick:()=>t(!1),children:"Done"})]})]})})}function n7s({override:s,onChange:t}){const r=ba(),{data:n}=Vat(),[a,i]=S.useState(null),l=d=>t({...s,...d}),o=async(d,h)=>{if(r){if(d.size>5*1024*1024){he.error("Image must be under 5MB");return}i(h);try{const m=await Hat(r,d,`${h}`);l(h==="logo"?{logo_url:m}:{cover_photo_url:m})}catch(m){he.error(`Upload failed: ${m.message||m}`)}finally{i(null)}}},c=Object.values(s||{}).some(d=>d!=null&&d!=="");return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-2 p-3 rounded-md bg-primary/5 border border-primary/10",children:[e.jsx(Lr,{className:"h-4 w-4 text-primary shrink-0 mt-0.5"}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["These settings ",e.jsx("span",{className:"font-medium text-foreground",children:"override your global Portal Branding"})," for this deal only. Leave any field empty to use your global default."]})]}),e.jsx(dWe,{label:"Logo",value:s.logo_url??null,globalValue:(n==null?void 0:n.logo_url)??null,uploading:a==="logo",onUpload:d=>o(d,"logo"),onClear:()=>l({logo_url:null}),aspect:"square"}),e.jsx(dWe,{label:"Cover Photo",value:s.cover_photo_url??null,globalValue:(n==null?void 0:n.cover_photo_url)??null,uploading:a==="cover",onUpload:d=>o(d,"cover"),onClear:()=>l({cover_photo_url:null}),aspect:"cover"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(uWe,{label:"Brand Color",value:s.brand_color??null,globalValue:(n==null?void 0:n.brand_color)??null,onChange:d=>l({brand_color:d})}),e.jsx(uWe,{label:"Accent Color",value:s.accent_color??null,globalValue:(n==null?void 0:n.accent_color)??null,onChange:d=>l({accent_color:d})})]}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-sm font-medium",children:"Tagline"}),e.jsx(Se,{value:s.tagline||"",onChange:d=>l({tagline:d.target.value||null}),placeholder:(n==null?void 0:n.tagline)||"Your trusted real estate advisor",maxLength:80,className:"mt-1"})]}),c&&e.jsxs(H,{variant:"ghost",size:"sm",onClick:()=>t({}),className:"text-xs text-muted-foreground hover:text-destructive",children:[e.jsx(Dr,{className:"h-3 w-3 mr-1"}),"Clear all overrides"]})]})}function dWe({label:s,value:t,globalValue:r,uploading:n,onUpload:a,onClear:i,aspect:l}){const o=t||r,c=!!t;return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(ue,{className:"text-sm font-medium",children:s}),c?e.jsx("span",{className:"text-[10px] font-medium text-primary",children:"Overridden"}):r?e.jsx("span",{className:"text-[10px] text-muted-foreground",children:"Using global"}):null]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:Ft("rounded-lg border-2 border-dashed flex items-center justify-center overflow-hidden bg-muted/30 shrink-0",c?"border-primary":"border-input",l==="square"?"h-16 w-16":"h-16 w-32"),children:o?e.jsx("img",{src:o,alt:s,className:"h-full w-full object-cover"}):e.jsx(wl,{className:"h-5 w-5 text-muted-foreground/40"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("label",{className:"cursor-pointer",children:[e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:d=>{var m;const h=(m=d.target.files)==null?void 0:m[0];h&&a(h),d.target.value=""}}),e.jsxs("span",{className:"inline-flex items-center gap-1.5 h-9 px-3 rounded-md border border-input bg-background hover:bg-accent text-sm font-medium",children:[n?e.jsx(is,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Ea,{className:"h-3.5 w-3.5"}),t?"Replace":"Override"]})]}),t&&e.jsx(H,{variant:"ghost",size:"sm",onClick:i,className:"text-muted-foreground hover:text-destructive",children:e.jsx(Dr,{className:"h-3.5 w-3.5"})})]})]})]})}function uWe({label:s,value:t,globalValue:r,onChange:n}){const a=t||r||"#000000",i=!!t;return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ue,{className:"text-xs text-muted-foreground",children:s}),i&&e.jsx("span",{className:"text-[10px] font-medium text-primary",children:"Overridden"})]}),e.jsxs("div",{className:Ft("mt-1 flex items-center gap-2 h-9 rounded-md border bg-background px-2",i?"border-primary":"border-input"),children:[e.jsx("input",{type:"color",value:a,onChange:l=>n(l.target.value),className:"h-6 w-8 rounded cursor-pointer border-0 bg-transparent"}),e.jsx(Se,{value:t||"",onChange:l=>n(l.target.value||null),placeholder:r||"#406E71",className:"border-0 h-7 px-1 focus-visible:ring-0 text-xs font-mono"}),t&&e.jsx(H,{variant:"ghost",size:"sm",onClick:()=>n(null),className:"h-6 w-6 p-0 text-muted-foreground hover:text-destructive",children:e.jsx(Dr,{className:"h-3 w-3"})})]})]})}function a7s({portalId:s,ownerId:t,clientEmail:r,linkedPortalId:n,onLink:a}){const[i,l]=S.useState(""),[o,c]=S.useState(!1),{data:d,isLoading:h}=yt({queryKey:["all-owner-portals",t],queryFn:async()=>{const{data:y,error:_}=await V.from("client_portals").select(` id, slug, client_name, client_email, deal_id, archived_at, deal_pipeline (id, deal_name, deal_type, property_address) `).eq("owner_user_id",t).neq("id",s).is("archived_at",null).eq("is_enabled",!0);if(_)throw _;return y},enabled:o||!!n}),m=S.useMemo(()=>!n||!d?null:d.find(y=>y.id===n),[n,d]),p=S.useMemo(()=>!d||!r?[]:d.filter(y=>{var _;return((_=y.client_email)==null?void 0:_.toLowerCase())===r.toLowerCase()&&y.id!==s}),[d,r,s]),x=S.useMemo(()=>{if(!d||!i.trim())return[];const y=i.toLowerCase();return d.filter(_=>{var j,k,T,E;const b=_.deal_pipeline;return((j=_.client_name)==null?void 0:j.toLowerCase().includes(y))||((k=_.client_email)==null?void 0:k.toLowerCase().includes(y))||((T=b==null?void 0:b.deal_name)==null?void 0:T.toLowerCase().includes(y))||((E=b==null?void 0:b.property_address)==null?void 0:E.toLowerCase().includes(y))})},[d,i]);if(n){const y=m==null?void 0:m.deal_pipeline;return e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{className:"text-sm font-medium",children:"Linked Portal"}),e.jsxs("div",{className:"flex items-center gap-2 bg-primary/5 border border-primary/20 rounded-lg p-3",children:[e.jsx(ql,{className:"h-4 w-4 text-primary shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:(m==null?void 0:m.client_name)||(y==null?void 0:y.deal_name)||"Linked Portal"}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[(y==null?void 0:y.deal_type)==="listing"?"🏠 Listing":"🔑 Purchase"," · ",(y==null?void 0:y.property_address)||"No address"]})]}),e.jsxs(H,{variant:"ghost",size:"sm",className:"text-xs text-destructive hover:text-destructive shrink-0",onClick:()=>a(null),children:[e.jsx(BE,{className:"h-3 w-3 mr-1"}),"Unlink"]})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Client will see both transactions in a tabbed view on one portal link."})]})}return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ue,{className:"text-sm font-medium",children:"Link Another Transaction"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Combine buy + sell into one portal"})]}),e.jsxs(H,{variant:"outline",size:"sm",className:"text-xs",onClick:()=>c(!o),children:[e.jsx(ql,{className:"h-3 w-3 mr-1"}),o?"Cancel":"Link"]})]}),!o&&p.length>0&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("p",{className:"text-[11px] text-muted-foreground font-medium",children:"✨ Suggested match (same client email)"}),p.map(y=>{const _=y.deal_pipeline;return e.jsxs("button",{onClick:()=>a(y.id),className:"w-full flex items-center gap-2 bg-amber-50 border border-amber-200 rounded-lg p-2.5 hover:bg-amber-100 transition-colors text-left",children:[e.jsx(Xe,{variant:"outline",className:"text-[10px] shrink-0 bg-amber-100 border-amber-300 text-amber-700",children:(_==null?void 0:_.deal_type)==="listing"?"Listing":"Purchase"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-xs font-medium truncate",children:(_==null?void 0:_.deal_name)||y.client_name}),e.jsx("p",{className:"text-[11px] text-muted-foreground truncate",children:_==null?void 0:_.property_address})]}),e.jsx(ql,{className:"h-3.5 w-3.5 text-amber-600 shrink-0"})]},y.id)})]}),o&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Mn,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(Se,{value:i,onChange:y=>l(y.target.value),placeholder:"Search by name, email, or address...",className:"pl-8 h-8 text-xs",autoFocus:!0})]}),h&&e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(is,{className:"h-4 w-4 animate-spin text-muted-foreground"})}),x.length>0&&e.jsx("div",{className:"space-y-1 max-h-[200px] overflow-y-auto",children:x.map(y=>{const _=y.deal_pipeline;return e.jsxs("button",{onClick:()=>{a(y.id),c(!1),l("")},className:"w-full flex items-center gap-2 border rounded-lg p-2 hover:bg-muted/50 transition-colors text-left",children:[e.jsx(Xe,{variant:"outline",className:"text-[10px] shrink-0",children:(_==null?void 0:_.deal_type)==="listing"?"Listing":"Purchase"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-xs font-medium truncate",children:(_==null?void 0:_.deal_name)||y.client_name}),e.jsx("p",{className:"text-[11px] text-muted-foreground truncate",children:y.client_email})]})]},y.id)})}),i&&x.length===0&&!h&&e.jsx("p",{className:"text-xs text-muted-foreground text-center py-3",children:"No portals found"})]})]})}function d6e({contactId:s,onVideoReady:t}){const[r,n]=S.useState(!1),[a,i]=S.useState("record"),[l,o]=S.useState(0),[c,d]=S.useState(0),h=Cj(),m=()=>{i("record"),o(0),d(0)},p=y=>{!y&&(a==="uploading"||a==="processing")||(n(y),y||m())},x=S.useCallback(async(y,_)=>{i("uploading");try{const b="Card Video",{videoId:j,libraryId:k}=await tM(b),{uploadUrl:T,apiKey:E}=await sM(j),A=new XMLHttpRequest;A.upload.onprogress=Z=>{Z.lengthComputable&&o(Z.loaded/Z.total*100)},await new Promise((Z,J)=>{A.onload=()=>A.status>=200&&A.status<300?Z():J(new Error("Upload failed")),A.onerror=()=>J(new Error("Upload failed")),A.open("PUT",T),A.setRequestHeader("AccessKey",E),A.send(y)}),i("processing");let D=0;const R=Date.now(),z=9e4,O=`https://iframe.mediadelivery.net/embed/${k}/${j}`;for(;D<4;){if(await new Promise(J=>setTimeout(J,3e3)),Date.now()-R>z){const J=y.size/1048576;await h.mutateAsync({bunny_video_id:j,playback_url:`https://iframe.mediadelivery.net/play/${k}/${j}`,file_size_mb:J,title:b,contact_id:s||void 0,status:"processing",touch_type:"video"}),t(O),he.success("Video saved — still encoding. It will be ready shortly."),i("done"),setTimeout(()=>{n(!1),m()},1500);return}const Z=await F_(j);if(D=Z.status,d(Z.encodeProgress||0),D===5||D===6)throw new Error("Video processing failed")}const $=await F_(j),ee=($.storageSize||y.size)/(1024*1024);await h.mutateAsync({bunny_video_id:j,contact_id:s||void 0,playback_url:$.directPlayUrl||O,thumbnail_url:$.thumbnailUrl,preview_url:$.previewUrl||null,duration_seconds:$.length||_,file_size_mb:ee,title:b,status:"ready",touch_type:"video"}),t(O),he.success("Video recorded & added to your library!"),i("done"),setTimeout(()=>{n(!1),m()},1500)}catch(b){console.error("Recording upload error:",b),he.error("Failed to process video. Please try again."),i("record")}},[s,t,h]);return e.jsxs(bs,{open:r,onOpenChange:p,children:[e.jsx(Qi,{asChild:!0,children:e.jsxs(H,{variant:"outline",size:"sm",className:"gap-1.5 w-full",children:[e.jsx(xn,{className:"h-3.5 w-3.5"}),"Record Video"]})}),e.jsxs(vs,{className:"sm:max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Cs,{children:e.jsx(Ns,{children:"Record a Video for Your Card"})}),a==="record"&&e.jsx(aD,{maxDurationSeconds:600,onRecordingComplete:x,onError:y=>he.error(y)}),a==="uploading"&&e.jsxs("div",{className:"flex flex-col items-center gap-4 py-12",children:[e.jsx(is,{className:"h-10 w-10 animate-spin text-primary"}),e.jsx("p",{className:"text-sm font-medium",children:"Uploading video..."}),e.jsx(Mi,{value:l,className:"w-64"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Math.round(l),"%"]})]}),a==="processing"&&e.jsxs("div",{className:"flex flex-col items-center gap-4 py-12",children:[e.jsx(is,{className:"h-10 w-10 animate-spin text-primary"}),e.jsx("p",{className:"text-sm font-medium",children:"Processing video..."}),e.jsx(Mi,{value:c,className:"w-64"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Math.round(c),"%"]})]}),a==="done"&&e.jsxs("div",{className:"flex flex-col items-center gap-3 py-12",children:[e.jsx(zi,{className:"h-12 w-12 text-emerald-500"}),e.jsx("p",{className:"text-sm font-medium",children:"Video attached to your card!"})]})]})]})}const i7s=s=>`portal-settings-draft:${s}`;function u6e({open:s,onOpenChange:t,portal:r,dealOwnerId:n}){const a=G8(),[i,l]=S.useState(!1),o=S.useMemo(()=>i7s(r.id),[r.id]),[c,d]=S.useState(!1),[h,m]=S.useState(r.next_step_text||""),[p,x]=S.useState(r.next_step_video_url||""),[y,_]=S.useState(r.inspection_date||""),[b,j]=S.useState(r.appraisal_date||""),[k,T]=S.useState(r.welcome_message||""),[E,A]=S.useState(r.review_url||""),[D,R]=S.useState(r.show_post_close_tips),[z,O]=S.useState(r.notify_client),[$,ee]=S.useState(r.require_onboarding),[Z,J]=S.useState(r.allow_spouse),[K,re]=S.useState(r.visibility),[ie,ce]=S.useState(r.stage_mapping||[]),[ne,le]=S.useState(null),[be,fe]=S.useState(r.linked_portal_id||null),[je,ve]=S.useState(r.referral_enabled??!0),[We,Ve]=S.useState(r.referral_reward_text||""),[Le,Me]=S.useState(r.referral_cta_headline||""),[ze,Pe]=S.useState(r.homeowner_hub_video_url||""),[Ie,De]=S.useState(r.branding_override||{}),pe=()=>{m(r.next_step_text||""),x(r.next_step_video_url||""),_(r.inspection_date||""),j(r.appraisal_date||""),T(r.welcome_message||""),A(r.review_url||""),R(r.show_post_close_tips),O(r.notify_client),ee(r.require_onboarding),J(r.allow_spouse),re(r.visibility),ce(r.stage_mapping||[]),fe(r.linked_portal_id||null),ve(r.referral_enabled??!0),Ve(r.referral_reward_text||""),Me(r.referral_cta_headline||""),Pe(r.homeowner_hub_video_url||""),De(r.branding_override||{})};S.useEffect(()=>{d(!1);const Ne=localStorage.getItem(o);if(Ne)try{const $e=JSON.parse(Ne);m($e.nextStepText||""),x($e.nextStepVideo||""),_($e.inspectionDate||""),j($e.appraisalDate||""),T($e.welcomeMessage||""),A($e.reviewUrl||""),R(!!$e.showPostClose),O(!!$e.notifyClient),ee(!!$e.requireOnboarding),J(!!$e.allowSpouse),re($e.visibility||r.visibility),ce($e.stageMapping||[]),fe($e.linkedPortalId??null),ve($e.referralEnabled??!0),Ve($e.referralRewardText||""),Me($e.referralCtaHeadline||""),Pe($e.homeownerHubVideoUrl||""),De($e.brandingOverride||{}),d(!0);return}catch{localStorage.removeItem(o)}pe(),d(!0)},[o,r]),S.useEffect(()=>{if(!c)return;const Ne={nextStepText:h,nextStepVideo:p,inspectionDate:y,appraisalDate:b,welcomeMessage:k,reviewUrl:E,showPostClose:D,notifyClient:z,requireOnboarding:$,allowSpouse:Z,visibility:K,stageMapping:ie,linkedPortalId:be,referralEnabled:je,referralRewardText:We,referralCtaHeadline:Le,homeownerHubVideoUrl:ze,brandingOverride:Ie};h!==(r.next_step_text||"")||p!==(r.next_step_video_url||"")||y!==(r.inspection_date||"")||b!==(r.appraisal_date||"")||k!==(r.welcome_message||"")||E!==(r.review_url||"")||D!==r.show_post_close_tips||z!==r.notify_client||$!==r.require_onboarding||Z!==r.allow_spouse||K!==r.visibility||JSON.stringify(ie)!==JSON.stringify(r.stage_mapping||[])||be!==(r.linked_portal_id||null)||je!==(r.referral_enabled??!0)||We!==(r.referral_reward_text||"")||Le!==(r.referral_cta_headline||"")||ze!==(r.homeowner_hub_video_url||"")||JSON.stringify(Ie)!==JSON.stringify(r.branding_override||{})?localStorage.setItem(o,JSON.stringify(Ne)):localStorage.removeItem(o)},[h,p,y,b,k,E,D,z,$,Z,K,ie,be,je,We,Le,ze,Ie,o,c,r]);const tt=()=>{localStorage.removeItem(o),pe()},ge=async()=>{try{await a.mutateAsync({id:r.id,next_step_text:h||null,next_step_video_url:p||null,inspection_date:y||null,appraisal_date:b||null,welcome_message:k||null,review_url:E||null,show_post_close_tips:D,notify_client:z,require_onboarding:$,allow_spouse:Z,visibility:K,stage_mapping:ie.length>0?ie:null,linked_portal_id:be,referral_enabled:je,referral_reward_text:We||null,referral_cta_headline:Le||null,homeowner_hub_video_url:ze||null,branding_override:Object.values(Ie).some($e=>$e!=null&&$e!=="")?Ie:null});const Ne=r.linked_portal_id;be&&be!==Ne&&await V.from("client_portals").update({linked_portal_id:r.id}).eq("id",be),!be&&Ne&&await V.from("client_portals").update({linked_portal_id:null}).eq("id",Ne),localStorage.removeItem(o),he.success("Portal settings saved"),t(!1)}catch{he.error("Failed to save settings")}},ct=()=>{ce([...ie,{label:""}])},Ue=Ne=>{ce(ie.filter(($e,it)=>it!==Ne)),ne===Ne&&le(null)},et=(Ne,$e,it)=>{const Je=[...ie];Je[Ne]={...Je[Ne],[$e]:it},ce(Je)},Qe=()=>{const $e=Bge(null).map(it=>({label:it.label,description:it.description,stageId:void 0}));ce($e)};return e.jsxs(e.Fragment,{children:[e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-lg max-h-[85vh] flex flex-col",children:[e.jsx(Cs,{children:e.jsx(Ns,{children:"Portal Settings"})}),e.jsxs(ta,{defaultValue:"general",className:"flex-1 overflow-hidden flex flex-col",children:[e.jsxs(Qn,{className:"grid grid-cols-4 shrink-0",children:[e.jsx(ts,{value:"general",children:"General"}),e.jsx(ts,{value:"timeline",children:"Timeline"}),e.jsx(ts,{value:"content",children:"Content"}),e.jsx(ts,{value:"branding",children:"Branding"})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto mt-4 min-h-0",children:[e.jsxs(cs,{value:"general",className:"space-y-4 mt-0 px-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ue,{className:"text-sm font-medium",children:"Visibility"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Public portals appear without restrictions"})]}),e.jsx("div",{className:"flex gap-1",children:["private","public"].map(Ne=>e.jsx("button",{onClick:()=>re(Ne),className:`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors ${K===Ne?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:border-primary/50"}`,children:Ne.charAt(0).toUpperCase()+Ne.slice(1)},Ne))})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ue,{className:"text-sm font-medium",children:"Require Onboarding"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Clients must fill out intake form"})]}),e.jsx(Or,{checked:$,onCheckedChange:ee})]}),$&&e.jsxs("div",{className:"flex items-center justify-between pl-4 border-l-2 border-primary/20",children:[e.jsxs("div",{children:[e.jsx(ue,{className:"text-sm font-medium",children:"Custom Questions"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Manage intake form questions"})]}),e.jsx(H,{variant:"outline",size:"sm",onClick:()=>l(!0),className:"text-xs",children:"Manage"})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ue,{className:"text-sm font-medium",children:"Allow Spouse/Partner"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Show spouse fields on onboarding"})]}),e.jsx(Or,{checked:Z,onCheckedChange:J})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ue,{className:"text-sm font-medium",children:"Post-Close Celebration"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Show congrats card when deal closes"})]}),e.jsx(Or,{checked:D,onCheckedChange:R})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ue,{className:"text-sm font-medium",children:"Notify Client on Updates"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Email client when you post portal updates"})]}),e.jsx(Or,{checked:z,onCheckedChange:O})]}),e.jsx("div",{className:"border-t pt-4",children:e.jsx(a7s,{portalId:r.id,ownerId:n,clientEmail:r.client_email,linkedPortalId:be,onLink:fe})}),e.jsx("div",{children:e.jsx(Se,{type:"date",value:y,onChange:Ne=>_(Ne.target.value),className:"mt-1"})}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-sm font-medium",children:"Appraisal Date"}),e.jsx(Se,{type:"date",value:b,onChange:Ne=>j(Ne.target.value),className:"mt-1"})]})]}),e.jsx(cs,{value:"timeline",className:"space-y-4 mt-0 px-1",children:e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{children:[e.jsx(ue,{className:"text-sm font-medium",children:"Client-Facing Stages"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Customize the client-friendly stage labels shown on the portal timeline"})]}),e.jsx(H,{variant:"outline",size:"sm",onClick:Qe,className:"text-xs",children:"Auto-map"})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground bg-muted/50 rounded-md p-2",children:'💡 These labels are what clients see. Click "More" on any stage to customize its description and add a video link. Internal pipeline stages are automatically translated to friendly names.'}),ie.length===0&&e.jsxs("div",{className:"border border-dashed rounded-lg p-4 text-center",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"No custom mapping — using default client-friendly journey stages"}),e.jsx(H,{variant:"outline",size:"sm",onClick:Qe,children:"Customize journey labels"})]}),e.jsx("div",{className:"space-y-2 mt-2",children:ie.map((Ne,$e)=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Oh,{className:"h-4 w-4 text-muted-foreground/50 flex-shrink-0"}),e.jsx(Se,{value:Ne.label,onChange:it=>et($e,"label",it.target.value),placeholder:`Stage ${$e+1} label`,className:"flex-1 h-9 text-sm"}),e.jsx(H,{variant:"ghost",size:"sm",className:"h-9 px-2 text-xs text-muted-foreground hover:text-primary",onClick:()=>le(ne===$e?null:$e),children:ne===$e?"Less":"More"}),e.jsx(H,{variant:"ghost",size:"icon",className:"h-9 w-9 text-muted-foreground hover:text-destructive",onClick:()=>Ue($e),children:e.jsx(Dr,{className:"h-3.5 w-3.5"})})]}),ne===$e&&e.jsxs("div",{className:"ml-6 space-y-2 pl-2 border-l-2 border-primary/15 pb-2",children:[e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs text-muted-foreground",children:"Description"}),e.jsx("textarea",{value:Ne.description||"",onChange:it=>et($e,"description",it.target.value),placeholder:"e.g. Now it's time to start actively looking at homes",className:"mt-0.5 w-full rounded-md border border-input bg-background px-3 py-2 text-xs min-h-[50px] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"})]}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs text-muted-foreground",children:"Video"}),Ne.video_url?e.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[e.jsx("div",{className:"flex-1 text-xs text-muted-foreground truncate bg-muted/50 rounded px-2 py-1.5 border border-input",children:Ne.video_url.length>40?Ne.video_url.slice(0,40)+"...":Ne.video_url}),e.jsx(H,{variant:"ghost",size:"sm",className:"h-7 text-xs text-destructive hover:text-destructive",onClick:()=>et($e,"video_url",""),children:"Remove"})]}):e.jsxs("div",{className:"mt-1 flex items-center gap-1.5",children:[e.jsx(d6e,{onVideoReady:it=>et($e,"video_url",it)}),e.jsx(H8,{userId:n,onSelect:it=>et($e,"video_url",it),triggerSize:"sm",triggerClassName:"gap-1.5 shrink-0 flex-1"}),e.jsxs(H,{variant:"ghost",size:"sm",className:"gap-1 text-xs text-muted-foreground flex-1",onClick:()=>{const it=prompt("Paste a YouTube or Loom URL:");it&&et($e,"video_url",it)},children:[e.jsx(Jo,{className:"h-3 w-3"}),"Paste URL"]})]})]})]})]},$e))}),ie.length>0&&e.jsxs(H,{variant:"outline",size:"sm",onClick:ct,className:"mt-2 text-xs w-full",children:[e.jsx(Ys,{className:"h-3 w-3 mr-1"})," Add Stage"]})]})}),e.jsxs(cs,{value:"content",className:"space-y-4 mt-0 px-1",children:[e.jsxs("div",{children:[e.jsx(ue,{className:"text-sm font-medium",children:"Welcome Message"}),e.jsx("textarea",{value:k,onChange:Ne=>T(Ne.target.value),className:"mt-1 w-full rounded-md border border-input bg-background px-3 py-2 text-sm min-h-[60px] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",placeholder:"Welcome! Here's everything you need for your transaction."})]}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-sm font-medium",children:"What's Next"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Tell your client what to expect next"}),e.jsx("textarea",{value:h,onChange:Ne=>m(Ne.target.value),className:"mt-1 w-full rounded-md border border-input bg-background px-3 py-2 text-sm min-h-[60px] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",placeholder:"We're waiting on the inspection report..."})]}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-sm font-medium",children:"Next Step Video (optional)"}),e.jsx(Se,{value:p,onChange:Ne=>x(Ne.target.value),className:"mt-1",placeholder:"YouTube or Loom URL"})]}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-sm font-medium",children:"Review URL"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Shown after deal closes"}),e.jsx(Se,{value:E,onChange:Ne=>A(Ne.target.value),className:"mt-1",placeholder:"https://g.page/r/..."})]}),e.jsxs("div",{className:"border-t pt-4 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-base",children:"🎁"}),e.jsx(ue,{className:"text-sm font-semibold",children:"Homeowner Hub & Referrals"})]}),e.jsx("p",{className:"text-xs text-muted-foreground -mt-2",children:'Shown automatically when the deal is in a "won" stage.'}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ue,{className:"text-sm font-medium",children:"Show Referral Card"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Big CTA asking client to refer friends"})]}),e.jsx(Or,{checked:je,onCheckedChange:ve})]}),je&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx(ue,{className:"text-sm font-medium",children:"Headline"}),e.jsx(Se,{value:Le,onChange:Ne=>Me(Ne.target.value),className:"mt-1",placeholder:"Know someone buying or selling?"})]}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-sm font-medium",children:"Reward (optional)"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"What the client gets for a successful referral"}),e.jsx(Se,{value:We,onChange:Ne=>Ve(Ne.target.value),className:"mt-1",placeholder:"$250 gift card • Donation to your charity • Closing gift"})]}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-sm font-medium",children:"Personal Welcome Video URL (optional)"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:'A "welcome home" video shown above the referral card'}),e.jsx(Se,{value:ze,onChange:Ne=>Pe(Ne.target.value),className:"mt-1",placeholder:"YouTube, Loom, or direct video URL"})]})]})]})]}),e.jsx(cs,{value:"branding",className:"space-y-4 mt-0 px-1",children:e.jsx(n7s,{override:Ie,onChange:De})})]})]}),e.jsxs("div",{className:"flex justify-between gap-2 pt-4 border-t shrink-0",children:[e.jsx(H,{variant:"ghost",onClick:tt,children:"Reset Draft"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(H,{variant:"outline",onClick:()=>t(!1),children:"Close"}),e.jsxs(H,{onClick:ge,disabled:a.isPending,children:[a.isPending?e.jsx(is,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(vc,{className:"h-4 w-4 mr-2"}),"Save Settings"]})]})]})]})}),e.jsx(Cyt,{open:i,onOpenChange:l})]})}const o7s=s=>`portal-update-draft:${s}`;function h6e({open:s,onOpenChange:t,portalId:r,portalSlug:n,notifyClient:a}){const i=S.useMemo(()=>o7s(r),[r]),[l,o]=S.useState(""),[c,d]=S.useState(""),[h,m]=S.useState(""),[p,x]=S.useState(!1),[y,_]=S.useState(a??!1),[b,j]=S.useState(!1),k=txt();S.useEffect(()=>{j(!1);const A=localStorage.getItem(i);if(A)try{const D=JSON.parse(A);o(D.title||""),d(D.content||""),m(D.videoUrl||""),x(!!D.isStageChange),_(typeof D.sendNotification=="boolean"?D.sendNotification:a??!1),j(!0);return}catch{localStorage.removeItem(i)}o(""),d(""),m(""),x(!1),_(a??!1),j(!0)},[i,a]),S.useEffect(()=>{if(!b)return;const A={title:l,content:c,videoUrl:h,isStageChange:p,sendNotification:y};l.trim()||c.trim()||h.trim()||p||y!==(a??!1)?localStorage.setItem(i,JSON.stringify(A)):localStorage.removeItem(i)},[l,c,h,p,y,b,i,a]);const T=()=>{localStorage.removeItem(i),o(""),d(""),m(""),x(!1),_(a??!1)},E=async()=>{if(l.trim())try{if(await k.mutateAsync({portal_id:r,title:l.trim(),content:c.trim()||void 0,video_url:h.trim()||void 0,is_stage_change:p}),y&&n)try{const A=C_(n);await V.functions.invoke("send-portal-notification",{body:{portal_id:r,update_title:l.trim(),update_content:c.trim()||null,portal_url:A}}),he.success("Update posted & client notified")}catch(A){console.error("Notification failed:",A),he.success("Update posted (notification failed to send)")}else he.success("Update posted to portal");T(),t(!1)}catch{he.error("Failed to post update")}};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-md",children:[e.jsx(Cs,{children:e.jsx(Ns,{children:"Post Portal Update"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ue,{className:"text-sm font-medium",children:"Title *"}),e.jsx(Se,{value:l,onChange:A=>o(A.target.value),className:"mt-1",placeholder:"Inspection cleared!"})]}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-sm font-medium",children:"Message"}),e.jsx("textarea",{value:c,onChange:A=>d(A.target.value),className:"mt-1 w-full rounded-md border border-input bg-background px-3 py-2 text-sm min-h-[80px] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",placeholder:"Everything looked great during the inspection..."})]}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-sm font-medium",children:"Video URL (optional)"}),e.jsxs("div",{className:"relative mt-1",children:[e.jsx(Se,{value:h,onChange:A=>m(A.target.value),className:"pl-9",placeholder:"YouTube or Loom link"}),e.jsx(xn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"})]})]}),e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsx("button",{type:"button",onClick:()=>x(!p),className:`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors ${p?"bg-emerald-500/10 text-emerald-700 border-emerald-200":"bg-background text-muted-foreground border-input"}`,children:"📊 Stage Change"}),e.jsxs("button",{type:"button",onClick:()=>_(!y),className:`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors flex items-center gap-1.5 ${y?"bg-blue-500/10 text-blue-700 border-blue-200":"bg-background text-muted-foreground border-input"}`,children:[y?e.jsx(wp,{className:"h-3 w-3"}):e.jsx(u_,{className:"h-3 w-3"}),y?"Notify Client":"No Notification"]})]})]}),e.jsxs("div",{className:"flex justify-between gap-2 pt-2",children:[e.jsx(H,{variant:"ghost",onClick:T,children:"Clear Draft"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(H,{variant:"outline",onClick:()=>t(!1),children:"Close"}),e.jsxs(H,{onClick:E,disabled:!l.trim()||k.isPending,children:[k.isPending?e.jsx(is,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(yn,{className:"h-4 w-4 mr-2"}),"Post Update"]})]})]})]})})}function m6e({open:s,onOpenChange:t,portal:r,dealName:n}){const a=G8(),{isGmailConnected:i,gmailEmail:l}=cf(),[o,c]=S.useState(r.client_name||""),[d,h]=S.useState(r.client_email||""),[m,p]=S.useState(!1),[x,y]=S.useState(!1),_=C_(r.slug),b=o.split(" ")[0]||"there",j=`Your Transaction Portal – ${n}`,k=`Hi ${b}, I've set up a dedicated portal where you can track the progress of your transaction in real-time. Here's your link: ${_} You can view your timeline, key dates, documents, and any updates I post along the way. Let me know if you have any questions!`,T=()=>{navigator.clipboard.writeText(_),y(!0),setTimeout(()=>y(!1),2e3),he.success("Portal link copied!")},E=async()=>{if(!d.trim()){he.error("Please enter the client email");return}p(!0);try{await a.mutateAsync({id:r.id,client_name:o||null,client_email:d||null,invite_sent_at:new Date().toISOString(),invite_method:"email"});const{error:D}=await V.functions.invoke("gmail-send",{body:{to:d,subject:j,body:k.replace(/\n/g,"
")}});if(D){let R="";try{const z=D==null?void 0:D.context;if(z&&typeof z.json=="function"){const O=await z.json();R=(O==null?void 0:O.message)||(O==null?void 0:O.error)||""}}catch{}throw new Error(R||D.message||"Failed to send invite")}he.success(`Invite sent to ${d}`),t(!1)}catch(D){he.error(D.message||"Failed to send invite")}finally{p(!1)}},A=()=>{const D=encodeURIComponent(j),R=encodeURIComponent(k);window.open(`mailto:${d}?subject=${D}&body=${R}`,"_blank"),a.mutateAsync({id:r.id,client_name:o||null,client_email:d||null,invite_sent_at:new Date().toISOString(),invite_method:"email"}).catch(()=>{})};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-md",children:[e.jsx(Cs,{children:e.jsx(Ns,{children:"Invite Client to Portal"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ue,{className:"text-sm font-medium",children:"Client Name"}),e.jsx(Se,{value:o,onChange:D=>c(D.target.value),className:"mt-1",placeholder:"John Doe"})]}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-sm font-medium",children:"Client Email"}),e.jsx(Se,{type:"email",value:d,onChange:D=>h(D.target.value),className:"mt-1",placeholder:"john@example.com"})]}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-sm font-medium",children:"Portal Link"}),e.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[e.jsx("div",{className:"flex-1 bg-muted/50 rounded-md px-3 py-2",children:e.jsx("p",{className:"text-xs font-mono text-muted-foreground truncate",children:_})}),e.jsx(H,{variant:"outline",size:"icon",onClick:T,className:"shrink-0",children:x?e.jsx(va,{className:"h-4 w-4 text-emerald-600"}):e.jsx(ui,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2 pt-2 border-t",children:[i?e.jsxs(H,{onClick:E,disabled:m||!d.trim(),className:"w-full",children:[m?e.jsx(is,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(er,{className:"h-4 w-4 mr-2"}),"Send via Gmail (",l,")"]}):e.jsxs(H,{onClick:A,disabled:!d.trim(),className:"w-full",variant:"outline",children:[e.jsx(gn,{className:"h-4 w-4 mr-2"}),"Open in Email App"]}),e.jsxs(H,{variant:"ghost",onClick:T,className:"w-full text-muted-foreground",children:[e.jsx(ui,{className:"h-4 w-4 mr-2"}),"Just Copy Link"]})]})]})]})})}function l7s({deal:s}){const{isAdmin:t,user:r}=Ms(),{data:n,isLoading:a}=K8s(s.id),i=dMe(),l=G8(),[o,c]=S.useState(!1),[d,h]=S.useState(!1),[m,p]=S.useState(!1),[x,y]=S.useState(!1),_=`portal-management-ui:${s.id}`;if(S.useEffect(()=>{const D=sessionStorage.getItem(_);if(D)try{const R=JSON.parse(D);h(!!R.settingsOpen),p(!!R.composerOpen),y(!!R.inviteOpen)}catch{sessionStorage.removeItem(_)}},[_]),S.useEffect(()=>{d||m||x?sessionStorage.setItem(_,JSON.stringify({settingsOpen:d,composerOpen:m,inviteOpen:x})):sessionStorage.removeItem(_)},[d,m,x,_]),a)return e.jsx("div",{className:"border rounded-lg p-4",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Lr,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"font-medium text-sm",children:"Client Portal"}),e.jsx(is,{className:"h-3 w-3 animate-spin ml-auto"})]})});const b=async()=>{var D,R;c(!0);try{await i.mutateAsync({deal_id:s.id,visibility:"private",require_onboarding:!0,client_name:s.contact?`${s.contact.first_name} ${s.contact.last_name}`:void 0,client_email:((D=s.contact)==null?void 0:D.email)||void 0,client_phone:((R=s.contact)==null?void 0:R.phone)||void 0}),he.success("Client portal enabled!")}catch{he.error("Failed to create portal")}finally{c(!1)}},j=async D=>{if(n)try{await l.mutateAsync({id:n.id,is_enabled:D}),he.success(D?"Portal enabled":"Portal disabled")}catch{he.error("Failed to update portal")}},k=()=>{if(!n)return;const D=C_(n.slug);navigator.clipboard.writeText(D),he.success("Portal link copied!")},T=()=>{if(!n)return;const D=C_(n.slug);window.open(D,"_blank")};if(!n)return e.jsxs("div",{className:"border rounded-lg p-4 border-dashed",children:[e.jsx("div",{className:"flex items-center justify-between mb-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Lr,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"font-medium text-sm",children:"Client Portal"})]})}),e.jsx("p",{className:"text-xs text-muted-foreground mb-3",children:"Create a beautiful portal so your client can track their deal progress in real-time."}),e.jsxs(H,{onClick:b,disabled:o,size:"sm",className:"w-full",children:[o?e.jsx(is,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Lr,{className:"h-4 w-4 mr-2"}),"Enable Client Portal"]})]});const E=C_(n.slug),A=(r==null?void 0:r.id)||"";return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"border rounded-lg p-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Lr,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"font-medium text-sm",children:"Client Portal"}),e.jsx(Xe,{variant:"outline",className:n.is_enabled?"text-xs bg-emerald-500/10 text-emerald-600 border-emerald-200":"text-xs bg-muted text-muted-foreground",children:n.is_enabled?"Active":"Disabled"})]}),e.jsx(Or,{checked:n.is_enabled,onCheckedChange:j})]}),e.jsxs("div",{className:"space-y-1.5 mb-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx("span",{children:"Visibility:"}),e.jsx(Xe,{variant:"outline",className:"text-[10px] px-1.5 py-0",children:n.visibility==="private"?"Private":"Public"})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx("span",{children:"Onboarding:"}),e.jsx("span",{className:"text-foreground",children:n.require_onboarding?"Required":"Disabled"})]}),n.client_name&&e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx("span",{children:"Client:"}),e.jsx("span",{className:"text-foreground",children:n.client_name})]})]}),e.jsx("div",{className:"bg-muted/50 rounded-md p-2 mb-3",children:e.jsx("p",{className:"text-xs font-mono text-muted-foreground truncate",children:E})}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 mb-2 w-full",children:[e.jsxs(H,{variant:"outline",size:"sm",onClick:k,className:"text-xs w-full min-w-0 px-2",children:[e.jsx(ui,{className:"h-3 w-3 mr-1 shrink-0"}),e.jsx("span",{className:"truncate",children:"Copy"})]}),e.jsxs(H,{variant:"outline",size:"sm",onClick:T,className:"text-xs w-full min-w-0 px-2",children:[e.jsx(gn,{className:"h-3 w-3 mr-1 shrink-0"}),e.jsx("span",{className:"truncate",children:"Preview"})]}),e.jsxs(H,{variant:"outline",size:"sm",onClick:()=>y(!0),className:"text-xs w-full min-w-0 px-2",children:[e.jsx(yn,{className:"h-3 w-3 mr-1 shrink-0"}),e.jsx("span",{className:"truncate",children:"Invite"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 w-full",children:[e.jsxs(H,{variant:"ghost",size:"sm",onClick:()=>p(!0),className:"text-xs text-muted-foreground w-full min-w-0 px-2",children:[e.jsx(t_,{className:"h-3 w-3 mr-1 shrink-0"}),e.jsx("span",{className:"truncate",children:"Post Update"})]}),e.jsxs(H,{variant:"ghost",size:"sm",onClick:()=>h(!0),className:"text-xs text-muted-foreground w-full min-w-0 px-2",children:[e.jsx(Go,{className:"h-3 w-3 mr-1 shrink-0"}),e.jsx("span",{className:"truncate",children:"Settings"})]})]}),e.jsxs(Xn,{to:"/mission-control/portal-referrals",className:"mt-2 flex items-center justify-center gap-1.5 text-[11px] text-muted-foreground hover:text-primary transition-colors py-1.5",children:[e.jsx(Di,{className:"h-3 w-3"}),"View incoming referrals"]})]}),e.jsx(u6e,{open:d,onOpenChange:h,portal:n,dealOwnerId:A}),e.jsx(h6e,{open:m,onOpenChange:p,portalId:n.id,portalSlug:n.slug,notifyClient:n.notify_client}),e.jsx(m6e,{open:x,onOpenChange:y,portal:n,dealName:s.deal_name})]})}const c7s=["Client","Co-Buyer","Co-Seller","Spouse","Lender","Title Company","Inspector","Appraiser","Attorney","Contractor","Other"];function d7s(s){return yt({queryKey:["deal-contacts",s],queryFn:async()=>{const{data:t,error:r}=await V.from("deal_contacts").select(` id, deal_id, contact_id, role, created_at, contact:innercircle_contacts(id, first_name, last_name, email, phone) `).eq("deal_id",s).order("created_at");if(r)throw r;return t||[]},enabled:!!s})}function u7s(){const s=ns();return Pt({mutationFn:async({dealId:t,contactId:r,role:n})=>{const{data:a,error:i}=await V.from("deal_contacts").insert({deal_id:t,contact_id:r,role:n}).select().single();if(i)throw i;return a},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["deal-contacts",r.dealId]}),he.success("Contact linked to deal")},onError:t=>{var r;(r=t.message)!=null&&r.includes("duplicate")?he.error("This contact is already linked to this deal"):he.error("Failed to link contact")}})}function h7s(){const s=ns();return Pt({mutationFn:async({id:t,dealId:r})=>{const{error:n}=await V.from("deal_contacts").delete().eq("id",t);if(n)throw n},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["deal-contacts",r.dealId]}),he.success("Contact removed from deal")},onError:()=>{he.error("Failed to remove contact")}})}function m7s({dealId:s,primaryContactId:t}){const r=Fr(),{data:n,isLoading:a}=d7s(s),{data:i}=Cp(),l=u7s(),o=h7s(),[c,d]=S.useState(!1),[h,m]=S.useState(""),[p,x]=S.useState("Client"),y=new Set((n==null?void 0:n.map(T=>T.contact_id))||[]);t&&y.add(t);const _=i==null?void 0:i.filter(T=>{var A,D,R;if(y.has(T.id))return!1;if(!h.trim())return!0;const E=h.toLowerCase();return((A=T.first_name)==null?void 0:A.toLowerCase().includes(E))||((D=T.last_name)==null?void 0:D.toLowerCase().includes(E))||((R=T.email)==null?void 0:R.toLowerCase().includes(E))}).slice(0,8),b=T=>{l.mutate({dealId:s,contactId:T,role:p}),d(!1),m("")},j=T=>{o.mutate({id:T,dealId:s})},k={Client:"bg-primary/10 text-primary","Co-Buyer":"bg-blue-500/10 text-blue-600","Co-Seller":"bg-emerald-500/10 text-emerald-600",Spouse:"bg-pink-500/10 text-pink-600",Lender:"bg-amber-500/10 text-amber-600","Title Company":"bg-purple-500/10 text-purple-600",Inspector:"bg-orange-500/10 text-orange-600",Appraiser:"bg-cyan-500/10 text-cyan-600",Attorney:"bg-slate-500/10 text-slate-600",Contractor:"bg-lime-500/10 text-lime-600",Other:"bg-muted text-muted-foreground"};return!(n!=null&&n.length)&&!c?e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("h4",{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Ar,{className:"h-4 w-4"}),"Additional Contacts"]})}),e.jsxs(gl,{open:c,onOpenChange:d,children:[e.jsx(xl,{asChild:!0,children:e.jsxs(H,{variant:"outline",size:"sm",className:"w-full text-muted-foreground",children:[e.jsx(Ys,{className:"h-3.5 w-3.5 mr-1"}),"Link a contact (lender, spouse, vendor...)"]})}),e.jsx(il,{className:"w-80 p-3",align:"start",children:e.jsx(hWe,{search:h,setSearch:m,selectedRole:p,setSelectedRole:x,filteredContacts:_,onAdd:b})})]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h4",{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Ar,{className:"h-4 w-4"}),"Linked Contacts",n&&n.length>0&&e.jsx(Xe,{variant:"secondary",className:"text-[10px] px-1.5",children:n.length})]}),e.jsxs(gl,{open:c,onOpenChange:d,children:[e.jsx(xl,{asChild:!0,children:e.jsx(H,{variant:"ghost",size:"sm",className:"h-7 px-2",children:e.jsx(Ys,{className:"h-3.5 w-3.5"})})}),e.jsx(il,{className:"w-80 p-3",align:"end",children:e.jsx(hWe,{search:h,setSearch:m,selectedRole:p,setSelectedRole:x,filteredContacts:_,onAdd:b})})]})]}),e.jsx("div",{className:"space-y-1.5",children:n==null?void 0:n.map(T=>{var E,A,D,R,z,O,$,ee;return e.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-md bg-muted/40 group",children:[e.jsx(Un,{className:"h-7 w-7",children:e.jsxs(qn,{className:"text-[10px] bg-primary/10 text-primary",children:[(A=(E=T.contact)==null?void 0:E.first_name)==null?void 0:A[0],(R=(D=T.contact)==null?void 0:D.last_name)==null?void 0:R[0]]})}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsxs("button",{onClick:()=>r(`/mission-control/contacts/${T.contact_id}`),className:"text-sm font-medium hover:underline text-primary truncate block",children:[(z=T.contact)==null?void 0:z.first_name," ",(O=T.contact)==null?void 0:O.last_name]})}),e.jsx(Xe,{variant:"outline",className:`text-[10px] px-1.5 py-0 shrink-0 ${k[T.role]||k.Other}`,children:T.role}),e.jsxs("div",{className:"flex gap-0.5 opacity-0 group-hover:opacity-100 transition-opacity",children:[(($=T.contact)==null?void 0:$.phone)&&e.jsx(H,{variant:"ghost",size:"icon",className:"h-6 w-6",asChild:!0,children:e.jsx("a",{href:`tel:${T.contact.phone}`,children:e.jsx(Yn,{className:"h-3 w-3"})})}),((ee=T.contact)==null?void 0:ee.email)&&e.jsx(H,{variant:"ghost",size:"icon",className:"h-6 w-6",asChild:!0,children:e.jsx("a",{href:`mailto:${T.contact.email}`,children:e.jsx(er,{className:"h-3 w-3"})})}),e.jsx(H,{variant:"ghost",size:"icon",className:"h-6 w-6 text-destructive",onClick:()=>j(T.id),children:e.jsx(Dr,{className:"h-3 w-3"})})]})]},T.id)})})]})}function hWe({search:s,setSearch:t,selectedRole:r,setSelectedRole:n,filteredContacts:a,onAdd:i}){return e.jsxs("div",{className:"space-y-3",children:[e.jsxs(Bs,{value:r,onValueChange:n,children:[e.jsx(Os,{className:"h-8 text-sm",children:e.jsx(Us,{placeholder:"Role"})}),e.jsx(Fs,{children:c7s.map(l=>e.jsx(pt,{value:l,children:l},l))})]}),e.jsxs("div",{className:"relative",children:[e.jsx(Mn,{className:"absolute left-2 top-2.5 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(Se,{value:s,onChange:l=>t(l.target.value),placeholder:"Search contacts...",className:"pl-7 h-8 text-sm",autoFocus:!0})]}),e.jsx(Ci,{className:"max-h-40",children:a&&a.length>0?e.jsx("div",{className:"space-y-0.5",children:a.map(l=>e.jsxs("button",{onClick:()=>i(l.id),className:"w-full text-left px-2 py-1.5 rounded hover:bg-accent transition-colors",children:[e.jsxs("div",{className:"text-sm font-medium truncate",children:[l.first_name," ",l.last_name]}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:[l.phone,l.email].filter(Boolean).join(" · ")||"No contact info"})]},l.id))}):e.jsx("p",{className:"text-xs text-muted-foreground text-center py-3",children:s?"No contacts found":"Type to search"})})]})}const f7s={buyer:{label:"Buyer",color:"bg-blue-500/10 text-blue-600 border-blue-200"},seller:{label:"Seller",color:"bg-emerald-500/10 text-emerald-600 border-emerald-200"},dual:{label:"Dual",color:"bg-purple-500/10 text-purple-600 border-purple-200"},referral:{label:"Referral",color:"bg-orange-500/10 text-orange-600 border-orange-200"},lease:{label:"Lease",color:"bg-cyan-500/10 text-cyan-600 border-cyan-200"}},p7s={note:Gi,call:Yn,email:er,meeting:Nn,stage_change:gn,task_completed:ea,document:Fn,system:Pn};function g7s({deal:s,open:t,onOpenChange:r,onEdit:n,onAddToScorecard:a,isWonStage:i}){var Me,ze;const{data:l,isLoading:o}=dRs((s==null?void 0:s.id)||""),{data:c,isLoading:d}=hRs((s==null?void 0:s.id)||""),h=uRs(),m=fRs(),p=mRs(),x=cRs(),{data:y,isLoading:_}=JFs((s==null?void 0:s.id)||""),b=e7s(),j=t7s(),k=s7s(),T=S.useRef(null),[E,A]=S.useState(""),[D,R]=S.useState(""),[z,O]=S.useState(!1),[$,ee]=S.useState(!1);if(!s)return null;const Z=f7s[s.deal_type],J=(()=>{var De;if(s.deal_type!=="seller"&&s.deal_type!=="dual")return null;const Pe=((De=s.listing)==null?void 0:De.created_at)||s.listing_date;if(!Pe)return null;const Ie=s.contract_date?Tc(s.contract_date):new Date;return Jy(Ie,Tc(Pe))})(),K=Pe=>Pe?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(Pe):"-",re=async()=>{if(E.trim())try{await h.mutateAsync({deal_id:s.id,activity_type:"note",title:"Note added",description:E}),A(""),he.success("Note added")}catch{he.error("Failed to add note")}},ie=async()=>{if(D.trim())try{await m.mutateAsync({deal_id:s.id,title:D,sort_order:((c==null?void 0:c.length)||0)+1}),R(""),he.success("Task added")}catch{he.error("Failed to add task")}},ce=async(Pe,Ie)=>{try{await p.mutateAsync({id:Pe,is_completed:Ie,deal_id:s.id})}catch{he.error("Failed to update task")}},ne=async()=>{try{await x.mutateAsync(s.id),he.success("Deal deleted"),r(!1)}catch{he.error("Failed to delete deal")}},le=(c==null?void 0:c.filter(Pe=>Pe.is_completed).length)||0,be=(c==null?void 0:c.length)||0,fe=(y==null?void 0:y.length)||0,je=Pe=>Pe<1024?`${Pe} B`:Pe<1024*1024?`${(Pe/1024).toFixed(1)} KB`:`${(Pe/(1024*1024)).toFixed(1)} MB`,ve=Pe=>Pe?Pe.startsWith("image/")?wl:Pe.includes("pdf")?kn:RI:RI,We=async Pe=>{const Ie=Pe.target.files;if(!(!Ie||!s)){ee(!0);try{for(const De of Array.from(Ie)){if(De.size>20*1024*1024){he.error(`${De.name} exceeds 20MB limit`);continue}await b.mutateAsync({dealId:s.id,file:De})}he.success("File(s) uploaded")}catch{he.error("Failed to upload file")}finally{ee(!1),T.current&&(T.current.value="")}}},Ve=async(Pe,Ie)=>{if(s)try{await j.mutateAsync({fileId:Pe,storagePath:Ie,dealId:s.id}),he.success("File deleted")}catch{he.error("Failed to delete file")}},Le=async(Pe,Ie)=>{try{const De=await r7s(Pe),pe=document.createElement("a");pe.href=De,pe.download=Ie,pe.target="_blank",document.body.appendChild(pe),pe.click(),document.body.removeChild(pe)}catch{he.error("Failed to download file")}};return e.jsxs(e.Fragment,{children:[e.jsx($S,{open:t,onOpenChange:r,children:e.jsxs(vj,{className:"w-full sm:max-w-xl p-0 flex flex-col",children:[e.jsx(US,{className:"p-6 pb-4 border-b shrink-0",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Xe,{variant:"outline",className:Ft("text-xs",Z.color),children:Z.label}),e.jsxs(Xe,{variant:"secondary",className:"text-xs capitalize",children:[s.priority," priority"]})]}),e.jsx(qS,{className:"text-xl",children:s.deal_name}),e.jsx("div",{className:"mt-2",children:e.jsx(QFs,{dealId:s.id})})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(H,{variant:"outline",size:"icon",onClick:()=>n(s),children:e.jsx(ou,{className:"h-4 w-4"})}),e.jsx(H,{variant:"outline",size:"icon",className:"text-destructive hover:bg-destructive/10",onClick:()=>O(!0),children:e.jsx(Dr,{className:"h-4 w-4"})})]})]})}),e.jsx(Ci,{className:"flex-1 [&>[data-radix-scroll-area-viewport]>div]:!block [&>[data-radix-scroll-area-viewport]>div]:!w-full",children:e.jsxs("div",{className:"p-6 space-y-6 min-w-0",children:[s.contact&&e.jsxs("div",{className:"flex items-center gap-3 p-3 bg-muted/50 rounded-lg",children:[e.jsx(Un,{className:"h-10 w-10",children:e.jsxs(qn,{className:"bg-primary/10 text-primary",children:[(Me=s.contact.first_name)==null?void 0:Me[0],(ze=s.contact.last_name)==null?void 0:ze[0]]})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("p",{className:"font-medium",children:[s.contact.first_name," ",s.contact.last_name]}),s.contact.email&&e.jsx("p",{className:"text-sm text-muted-foreground",children:s.contact.email})]}),e.jsxs("div",{className:"flex gap-2",children:[s.contact.phone&&e.jsx(H,{variant:"outline",size:"icon",asChild:!0,children:e.jsx("a",{href:`tel:${s.contact.phone}`,children:e.jsx(Yn,{className:"h-4 w-4"})})}),s.contact.email&&e.jsx(H,{variant:"outline",size:"icon",asChild:!0,children:e.jsx("a",{href:`mailto:${s.contact.email}`,children:e.jsx(er,{className:"h-4 w-4"})})})]})]}),e.jsx(m7s,{dealId:s.id,primaryContactId:s.contact_id}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[(s.property_address||s.city)&&e.jsxs("div",{className:"col-span-2 flex items-start gap-2 text-sm",children:[e.jsx(Fn,{className:"h-4 w-4 text-muted-foreground mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:s.property_address||"Address TBD"}),e.jsx("p",{className:"text-muted-foreground",children:[s.city,s.state,s.zip_code].filter(Boolean).join(", ")})]})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Expected Price"}),e.jsx("p",{className:"text-lg font-bold",children:K(s.expected_price)})]}),e.jsxs("div",{className:"bg-emerald-500/10 rounded-lg p-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Expected GCI"}),e.jsx("p",{className:"text-lg font-bold text-emerald-600",children:K(s.expected_commission)})]}),(s.brokerage_split_pct||s.team_split_pct||s.referral_fee_pct||s.franchise_fee_pct||s.transaction_fee)&&e.jsxs("div",{className:"col-span-2 bg-muted/30 rounded-lg p-3 space-y-1.5",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground mb-2",children:"Commission Splits"}),s.brokerage_split_pct!=null&&e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Brokerage Split"}),e.jsxs("span",{children:[s.brokerage_split_pct,"%",s.expected_commission?` (${K(s.expected_commission*s.brokerage_split_pct/100)})`:""]})]}),s.team_split_pct!=null&&e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Team Split"}),e.jsxs("span",{children:[s.team_split_pct,"%"]})]}),s.referral_fee_pct!=null&&e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Referral Fee"}),e.jsxs("span",{children:[s.referral_fee_pct,"%"]})]}),s.franchise_fee_pct!=null&&e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Franchise Fee"}),e.jsxs("span",{children:[s.franchise_fee_pct,"%"]})]}),s.transaction_fee!=null&&e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Transaction Fee"}),e.jsx("span",{children:K(s.transaction_fee)})]}),s.net_commission!=null&&e.jsx(e.Fragment,{children:e.jsx("div",{className:"border-t pt-1.5 mt-1.5",children:e.jsxs("div",{className:"flex justify-between text-sm font-semibold",children:[e.jsx("span",{children:"Net to Agent"}),e.jsx("span",{className:"text-emerald-600",children:K(s.net_commission)})]})})})]}),i&&!s.scorecard_transaction_id&&a&&e.jsxs(H,{onClick:()=>a(s),className:"w-full bg-green-600 hover:bg-green-700",children:[e.jsx(To,{className:"h-4 w-4 mr-2"}),"Add to Scorecard"]}),s.scorecard_transaction_id&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground bg-muted/50 rounded-lg p-3",children:[e.jsx(ea,{className:"h-4 w-4 text-green-600"}),e.jsx("span",{children:"Synced to Scorecard"})]}),J!==null&&e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3 col-span-2",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Days on Market"}),e.jsxs("p",{className:Ft("text-lg font-bold",J>90?"text-red-600":J>60?"text-amber-600":"text-foreground"),children:[J," ",s.contract_date?"(final)":"days"]})]}),s.target_close_date&&e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(Nn,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:["Close: ",As(Tc(s.target_close_date),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(oc,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:[s.probability,"% probability"]})]})]}),s.notes&&e.jsxs("div",{className:"text-sm",children:[e.jsx("p",{className:"font-medium mb-1",children:"Notes"}),e.jsx("p",{className:"text-muted-foreground",children:s.notes})]}),e.jsx(l7s,{deal:s}),e.jsxs(ta,{defaultValue:"tasks",className:"w-full",children:[e.jsxs(Qn,{className:"w-full grid grid-cols-3",children:[e.jsxs(ts,{value:"tasks",className:"gap-1",children:[e.jsx(ea,{className:"h-4 w-4"}),"Tasks ",be>0&&`(${le}/${be})`]}),e.jsxs(ts,{value:"files",className:"gap-1",children:[e.jsx(Hk,{className:"h-4 w-4"}),"Files ",fe>0&&`(${fe})`]}),e.jsxs(ts,{value:"activity",className:"gap-1",children:[e.jsx(Pn,{className:"h-4 w-4"}),"Activity"]})]}),e.jsxs(cs,{value:"tasks",className:"mt-4 space-y-3",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Se,{placeholder:"Add a new task...",value:D,onChange:Pe=>R(Pe.target.value),onKeyDown:Pe=>Pe.key==="Enter"&&ie()}),e.jsx(H,{onClick:ie,disabled:!D.trim(),children:e.jsx(Ys,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"space-y-2",children:[c==null?void 0:c.map(Pe=>e.jsxs("div",{className:Ft("flex items-center gap-3 p-3 rounded-lg border transition-colors",Pe.is_completed?"bg-muted/50 border-border":"bg-background"),children:[e.jsx(ao,{checked:Pe.is_completed,onCheckedChange:Ie=>ce(Pe.id,!!Ie)}),e.jsx("span",{className:Ft("flex-1 text-sm",Pe.is_completed&&"line-through text-muted-foreground"),children:Pe.title}),Pe.due_date&&e.jsx("span",{className:"text-xs text-muted-foreground",children:As(new Date(Pe.due_date),"MMM d")})]},Pe.id)),(c==null?void 0:c.length)===0&&e.jsx("p",{className:"text-center text-muted-foreground text-sm py-4",children:"No tasks yet. Add one above!"})]})]}),e.jsxs(cs,{value:"files",className:"mt-4 space-y-3",children:[e.jsx("input",{type:"file",ref:T,className:"hidden",multiple:!0,onChange:We,accept:".pdf,.doc,.docx,.xls,.xlsx,.jpg,.jpeg,.png,.webp,.gif,.txt,.csv"}),e.jsxs(H,{variant:"outline",className:"w-full border-dashed",onClick:()=>{var Pe;return(Pe=T.current)==null?void 0:Pe.click()},disabled:$,children:[$?e.jsx(is,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Ea,{className:"h-4 w-4 mr-2"}),$?"Uploading...":"Upload Files"]}),e.jsxs("div",{className:"space-y-2",children:[y==null?void 0:y.map(Pe=>{const Ie=ve(Pe.file_type);return e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg border bg-background",children:[e.jsx("div",{className:"w-8 h-8 rounded bg-muted flex items-center justify-center shrink-0",children:e.jsx(Ie,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:Pe.file_name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[je(Pe.file_size)," · ",As(new Date(Pe.created_at),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(xj,{children:e.jsxs(rd,{children:[e.jsx(nd,{asChild:!0,children:e.jsx(H,{variant:"ghost",size:"icon",className:`h-8 w-8 transition-colors ${Pe.visible_on_portal?"text-primary bg-primary/10 hover:bg-primary/20":"text-muted-foreground/40 hover:text-muted-foreground"}`,onClick:()=>k.mutate({fileId:Pe.id,visible:!Pe.visible_on_portal,dealId:s.id}),children:Pe.visible_on_portal?e.jsx(Bn,{className:"h-4 w-4"}):e.jsx($f,{className:"h-4 w-4"})})}),e.jsx(Rc,{side:"top",children:Pe.visible_on_portal?"Visible on client portal":"Hidden from client portal"})]})}),e.jsx(H,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>Le(Pe.storage_path,Pe.file_name),children:e.jsx(hi,{className:"h-4 w-4"})}),e.jsx(H,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:text-destructive",onClick:()=>Ve(Pe.id,Pe.storage_path),children:e.jsx(Rr,{className:"h-4 w-4"})})]})]},Pe.id)}),(y==null?void 0:y.length)===0&&e.jsx("p",{className:"text-center text-muted-foreground text-sm py-4",children:"No files yet. Upload contracts, disclosures, or other documents."})]})]}),e.jsxs(cs,{value:"activity",className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(vr,{placeholder:"Add a note...",value:E,onChange:Pe=>A(Pe.target.value),rows:2}),e.jsxs(H,{onClick:re,disabled:!E.trim(),size:"sm",className:"w-full",children:[e.jsx(yn,{className:"h-4 w-4 mr-2"}),"Add Note"]})]}),e.jsxs("div",{className:"space-y-3",children:[l==null?void 0:l.map(Pe=>{const Ie=p7s[Pe.activity_type]||Pn;return e.jsxs("div",{className:"flex gap-3",children:[e.jsx("div",{className:"w-8 h-8 rounded-full bg-muted flex items-center justify-center shrink-0",children:e.jsx(Ie,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium",children:Pe.title}),Pe.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-0.5",children:Pe.description}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:Hl(new Date(Pe.created_at),{addSuffix:!0})})]})]},Pe.id)}),(l==null?void 0:l.length)===0&&e.jsx("p",{className:"text-center text-muted-foreground text-sm py-4",children:"No activity yet"})]})]})]})]})})]})}),e.jsx(Rl,{open:z,onOpenChange:O,children:e.jsxs(jl,{children:[e.jsxs(Nl,{children:[e.jsx(Sl,{children:"Delete Deal?"}),e.jsxs(Cl,{children:['This will permanently delete "',s.deal_name,'" and all associated data. This action cannot be undone.']})]}),e.jsxs(kl,{children:[e.jsx(Tl,{children:"Cancel"}),e.jsx(ml,{onClick:ne,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})})]})}function x7s({open:s,onOpenChange:t,deal:r,onComplete:n}){const a=exe(),i=bxt(),{data:l}=v8(),{data:o}=R0(),[c,d]=S.useState({property_address:"",city:"",state:"",zip:"",transaction_type:"buyer",close_date:As(new Date,"yyyy-MM-dd"),sale_price:0,commission_amount:0,lead_source_id:"",client_type_id:"",notes:""});S.useEffect(()=>{if(r&&s){const p=r.deal_type==="seller"?"seller":"buyer",x=r.expected_price||0,y=r.commission_percentage||3,_=r.expected_commission||x*y/100;d({property_address:r.property_address||r.deal_name||"",city:r.city||"",state:r.state||"",zip:r.zip_code||"",transaction_type:p,close_date:r.actual_close_date||r.target_close_date||As(new Date,"yyyy-MM-dd"),sale_price:x,commission_amount:_,lead_source_id:"",client_type_id:"",notes:r.notes||""})}},[r,s]);const h=async p=>{if(p.preventDefault(),!!r)try{const x=await a.mutateAsync({property_address:c.property_address,city:c.city||null,state:c.state||null,zip:c.zip||null,transaction_type:c.transaction_type,close_date:c.close_date,sale_price:c.sale_price,commission_amount:c.commission_amount||null,brokerage_split_pct:r.brokerage_split_pct||null,team_split_pct:r.team_split_pct||null,franchise_fee_pct:r.franchise_fee_pct||null,referral_fee_pct:r.referral_fee_pct||null,transaction_fee:r.transaction_fee||null,lead_source_id:c.lead_source_id||null,client_type_id:c.client_type_id||null,contact_id:r.contact_id||null,notes:c.notes||null,is_win:!0});await i.mutateAsync({id:r.id,scorecard_transaction_id:x.id,actual_close_date:c.close_date}),he.success("Deal added to Scorecard! 🎉"),t(!1),n==null||n()}catch(x){console.error("Error syncing to scorecard:",x),he.error("Failed to add to scorecard")}},m=p=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:0}).format(p);return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"sm:max-w-[550px] max-h-[90vh] overflow-y-auto",children:[e.jsxs(Cs,{className:"space-y-3",children:[e.jsx("div",{className:"mx-auto flex h-12 w-12 items-center justify-center rounded-full bg-green-100 dark:bg-green-900/20",children:e.jsx(To,{className:"h-6 w-6 text-green-600 dark:text-green-400"})}),e.jsx(Ns,{className:"text-center text-xl",children:"Congratulations on Closing! 🎉"}),e.jsx(nn,{className:"text-center",children:"Review and confirm the details before adding this deal to your Scorecard."})]}),e.jsxs("form",{onSubmit:h,className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ue,{htmlFor:"property_address",className:"flex items-center gap-2",children:[e.jsx(Fn,{className:"h-4 w-4 text-muted-foreground"}),"Property Address *"]}),e.jsx(Se,{id:"property_address",value:c.property_address,onChange:p=>d(x=>({...x,property_address:p.target.value})),placeholder:"123 Main St",required:!0})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"city",children:"City"}),e.jsx(Se,{id:"city",value:c.city,onChange:p=>d(x=>({...x,city:p.target.value})),placeholder:"City"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"state",children:"State"}),e.jsx(Se,{id:"state",value:c.state,onChange:p=>d(x=>({...x,state:p.target.value})),placeholder:"TX",maxLength:2})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"zip",children:"Zip"}),e.jsx(Se,{id:"zip",value:c.zip,onChange:p=>d(x=>({...x,zip:p.target.value})),placeholder:"75001"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Transaction Type *"}),e.jsxs(Bs,{value:c.transaction_type,onValueChange:p=>d(x=>({...x,transaction_type:p})),children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"buyer",children:"Buyer"}),e.jsx(pt,{value:"seller",children:"Seller"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ue,{htmlFor:"close_date",className:"flex items-center gap-2",children:[e.jsx(Nn,{className:"h-4 w-4 text-muted-foreground"}),"Close Date *"]}),e.jsx(Se,{id:"close_date",type:"date",value:c.close_date,onChange:p=>d(x=>({...x,close_date:p.target.value})),required:!0})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ue,{htmlFor:"sale_price",className:"flex items-center gap-2",children:[e.jsx(oc,{className:"h-4 w-4 text-muted-foreground"}),"Sale Price *"]}),e.jsx(Se,{id:"sale_price",type:"number",value:c.sale_price||"",onChange:p=>d(x=>({...x,sale_price:Number(p.target.value)})),placeholder:"450000",required:!0,min:0}),c.sale_price>0&&e.jsx("p",{className:"text-xs text-muted-foreground",children:m(c.sale_price)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ue,{htmlFor:"commission_amount",className:"flex items-center gap-2",children:[e.jsx(ME,{className:"h-4 w-4 text-muted-foreground"}),"GCI (Commission)"]}),e.jsx(Se,{id:"commission_amount",type:"number",value:c.commission_amount||"",onChange:p=>d(x=>({...x,commission_amount:Number(p.target.value)})),placeholder:"13500",min:0}),c.commission_amount>0&&e.jsx("p",{className:"text-xs text-muted-foreground",children:m(c.commission_amount)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Lead Source"}),e.jsxs(Bs,{value:c.lead_source_id,onValueChange:p=>d(x=>({...x,lead_source_id:p})),children:[e.jsx(Os,{children:e.jsx(Us,{placeholder:"Select source"})}),e.jsx(Fs,{children:l==null?void 0:l.map(p=>e.jsx(pt,{value:p.id,children:p.name},p.id))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Client Type"}),e.jsxs(Bs,{value:c.client_type_id,onValueChange:p=>d(x=>({...x,client_type_id:p})),children:[e.jsx(Os,{children:e.jsx(Us,{placeholder:"Select type"})}),e.jsx(Fs,{children:o==null?void 0:o.map(p=>e.jsx(pt,{value:p.id,children:p.name},p.id))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"notes",children:"Notes"}),e.jsx(vr,{id:"notes",value:c.notes,onChange:p=>d(x=>({...x,notes:p.target.value})),placeholder:"Any additional notes about this transaction...",rows:2})]}),e.jsxs(wn,{className:"gap-2 sm:gap-0 pt-4",children:[e.jsx(H,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Skip for now"}),e.jsx(H,{type:"submit",disabled:a.isPending||i.isPending,className:"bg-green-600 hover:bg-green-700",children:a.isPending?"Adding...":e.jsxs(e.Fragment,{children:["Add to Scorecard",e.jsx(bi,{className:"ml-2 h-4 w-4"})]})})]})]})]})})}const y7s={buyer:{label:"Buyer",color:"bg-blue-500/10 text-blue-600 border-blue-200"},seller:{label:"Seller",color:"bg-emerald-500/10 text-emerald-600 border-emerald-200"},dual:{label:"Dual",color:"bg-purple-500/10 text-purple-600 border-purple-200"},referral:{label:"Referral",color:"bg-orange-500/10 text-orange-600 border-orange-200"},lease:{label:"Lease",color:"bg-cyan-500/10 text-cyan-600 border-cyan-200"}},mWe={urgent:0,high:1,medium:2,low:3};function v7s({deals:s,stages:t,onDealClick:r,onStageChange:n}){const[a,i]=S.useState("target_close_date"),[l,o]=S.useState("asc"),c=x=>{a===x?o(y=>y==="asc"?"desc":"asc"):(i(x),o("asc"))},d=S.useMemo(()=>[...s].sort((x,y)=>{var b,j;let _=0;switch(a){case"deal_name":_=x.deal_name.localeCompare(y.deal_name);break;case"stage":{const k=((b=t.find(E=>E.id===x.stage_id))==null?void 0:b.sort_order)||0,T=((j=t.find(E=>E.id===y.stage_id))==null?void 0:j.sort_order)||0;_=k-T;break}case"expected_price":_=(x.expected_price||0)-(y.expected_price||0);break;case"expected_commission":_=(x.expected_commission||0)-(y.expected_commission||0);break;case"target_close_date":{const k=x.target_close_date?Tc(x.target_close_date).getTime():1/0,T=y.target_close_date?Tc(y.target_close_date).getTime():1/0;_=k-T;break}case"priority":_=mWe[x.priority]-mWe[y.priority];break}return l==="asc"?_:-_}),[s,t,a,l]),h=x=>x?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(x):"—",m=x=>x?t.find(y=>y.id===x):null,p=({field:x,children:y})=>e.jsxs(H,{variant:"ghost",size:"sm",className:"h-8 -ml-3 font-medium",onClick:()=>c(x),children:[y,a===x?l==="asc"?e.jsx(Hu,{className:"ml-2 h-4 w-4"}):e.jsx(fm,{className:"ml-2 h-4 w-4"}):e.jsx(qu,{className:"ml-2 h-4 w-4 opacity-50"})]});return s.length===0?e.jsx("div",{className:"text-center py-16",children:e.jsx("p",{className:"text-muted-foreground",children:"No deals to display"})}):e.jsx("div",{className:"border rounded-lg overflow-hidden",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Vs,{className:"bg-muted/50",children:[e.jsx(At,{className:"w-[250px]",children:e.jsx(p,{field:"deal_name",children:"Deal Name"})}),e.jsx(At,{className:"w-[150px]",children:e.jsx(p,{field:"stage",children:"Stage"})}),e.jsx(At,{className:"w-[100px]",children:"Type"}),e.jsx(At,{className:"w-[120px]",children:e.jsx(p,{field:"expected_price",children:"Price"})}),e.jsx(At,{className:"w-[120px]",children:e.jsx(p,{field:"expected_commission",children:"GCI"})}),e.jsx(At,{className:"w-[130px]",children:e.jsx(p,{field:"target_close_date",children:"Close Date"})}),e.jsx(At,{className:"w-[100px]",children:e.jsx(p,{field:"priority",children:"Priority"})})]})}),e.jsx(da,{children:d.map(x=>{m(x.stage_id);const y=y7s[x.deal_type],_=x.target_close_date?Jy(Tc(x.target_close_date),new Date):null,b=_!==null&&_<0,j=_!==null&&_<=7&&_>=0;return e.jsxs(Vs,{className:Ft("cursor-pointer hover:bg-muted/50 transition-colors",b&&"bg-red-50/50"),onClick:()=>r(x),children:[e.jsx(gt,{className:"font-medium",children:e.jsxs("div",{children:[e.jsx("p",{className:"truncate max-w-[230px]",children:x.deal_name}),x.contact&&e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[x.contact.first_name," ",x.contact.last_name]})]})}),e.jsx(gt,{onClick:k=>k.stopPropagation(),children:e.jsx(kyt,{stages:t,currentStageId:x.stage_id||"",onStageSelect:(k,T)=>n(x.id,k,T)})}),e.jsx(gt,{children:e.jsx(Xe,{variant:"outline",className:Ft("text-xs",y.color),children:y.label})}),e.jsx(gt,{children:e.jsx("span",{className:"font-medium",children:h(x.expected_price)})}),e.jsx(gt,{children:e.jsx("span",{className:"text-emerald-600",children:h(x.expected_commission)})}),e.jsx(gt,{children:x.target_close_date?e.jsxs("div",{className:Ft("flex items-center gap-1 text-sm",b&&"text-red-600",j&&!b&&"text-amber-600"),children:[b&&e.jsx(wo,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:As(Tc(x.target_close_date),"MMM d, yyyy")})]}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(gt,{children:e.jsx(Xe,{variant:"outline",className:Ft("text-xs capitalize",x.priority==="urgent"&&"border-red-200 bg-red-50 text-red-700",x.priority==="high"&&"border-orange-200 bg-orange-50 text-orange-700",x.priority==="medium"&&"border-amber-200 bg-amber-50 text-amber-700",x.priority==="low"&&"border-slate-200 bg-slate-50 text-slate-600"),children:x.priority})})]},x.id)})})]})})}function b7s(){const s=ba();return yt({queryKey:["deal-tasks",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await V.from("deal_tasks").select(` *, deal:deal_pipeline(id, deal_name, stage_id), contact:innercircle_contacts(id, first_name, last_name), stage:deal_pipeline_stages(id, name, color) `).eq("owner_user_id",s).order("sort_order",{ascending:!0});if(r)throw r;return t},enabled:!!s})}function _7s(s){const t=ba();return yt({queryKey:["deal-tasks","deal",s,t],queryFn:async()=>{if(!t||!s)return[];const{data:r,error:n}=await V.from("deal_tasks").select(` *, stage:deal_pipeline_stages(id, name, color) `).eq("owner_user_id",t).eq("deal_id",s).order("sort_order",{ascending:!0});if(n)throw n;return r},enabled:!!t&&!!s})}function w7s(){const s=ba(),t=ns();return Pt({mutationFn:async r=>{if(!s)throw new Error("Not authenticated");const{data:n,error:a}=await V.from("deal_tasks").insert({owner_user_id:s,title:r.title,description:r.description||null,deal_id:r.deal_id||null,contact_id:r.contact_id||null,stage_id:r.stage_id||null,priority:r.priority||"medium",status:r.status||"todo",due_date:r.due_date||null,sort_order:r.sort_order||0}).select().single();if(a)throw a;return n},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-tasks"]})}})}function j7s(){const s=ns();return Pt({mutationFn:async({id:t,...r})=>{const{data:n,error:a}=await V.from("deal_tasks").update(r).eq("id",t).select().single();if(a)throw a;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-tasks"]})}})}function N7s(){const s=ns();return Pt({mutationFn:async t=>{const{error:r}=await V.from("deal_tasks").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-tasks"]})}})}function f6e(){const s=ns();return Pt({mutationFn:async({id:t,status:r})=>{const{data:n,error:a}=await V.from("deal_tasks").update({status:r,completed_at:r==="done"?new Date().toISOString():null}).eq("id",t).select().single();if(a)throw a;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-tasks"]})}})}function k7s(){const s=ns();return Pt({mutationFn:async t=>{if(t.length===0)return;const{error:r}=await V.from("deal_tasks").update({status:"done",completed_at:new Date().toISOString()}).in("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-tasks"]})}})}function S7s(s){const t=ba();return yt({queryKey:["deal-task-templates",t,s],queryFn:async()=>{if(!t)return[];let r=V.from("deal_task_templates").select("*").eq("owner_user_id",t).order("sort_order",{ascending:!0});s&&(r=r.eq("stage_id",s));const{data:n,error:a}=await r;if(a)throw a;return n},enabled:!!t})}function C7s(){const s=ba(),t=ns();return Pt({mutationFn:async r=>{if(!s)throw new Error("Not authenticated");const{data:n,error:a}=await V.from("deal_task_templates").insert({owner_user_id:s,stage_id:r.stage_id,title:r.title,description:r.description||null,priority:r.priority||"medium",default_due_offset_days:r.default_due_offset_days||null,sort_order:r.sort_order||0}).select().single();if(a)throw a;return n},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-task-templates"]})}})}function T7s(){const s=ns();return Pt({mutationFn:async t=>{const{error:r}=await V.from("deal_task_templates").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-task-templates"]})}})}function E7s(){const s=ba(),t=ns();return Pt({mutationFn:async({dealId:r,stageId:n})=>{if(!s)throw new Error("Not authenticated");const{data:a,error:i}=await V.from("deal_task_templates").select("*").eq("owner_user_id",s).eq("stage_id",n).order("sort_order");if(i)throw i;if(!a||a.length===0)return[];const{data:l}=await V.from("deal_tasks").select("title, stage_id").eq("deal_id",r).eq("stage_id",n),o=new Set((l||[]).map(m=>m.title)),c=a.filter(m=>!o.has(m.title)).map((m,p)=>({owner_user_id:s,deal_id:r,stage_id:n,title:m.title,description:m.description,priority:m.priority,due_date:m.default_due_offset_days?new Date(Date.now()+m.default_due_offset_days*864e5).toISOString().split("T")[0]:null,sort_order:p,status:"todo"}));if(c.length===0)return[];const{data:d,error:h}=await V.from("deal_tasks").insert(c).select();if(h)throw h;return d},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-tasks"]})}})}const A7s={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function M7s({open:s,onOpenChange:t,dealId:r,dealName:n,fromStageName:a,toStageName:i,toStageId:l,onConfirm:o}){const{data:c,isLoading:d}=_7s(s?r:void 0),h=k7s(),m=E7s(),[p,x]=S.useState(new Set),[y,_]=S.useState(!1),b=(c||[]).filter(E=>E.status!=="done");S.useEffect(()=>{b.length>0&&x(new Set(b.map(E=>E.id)))},[c]);const j=E=>{x(A=>{const D=new Set(A);return D.has(E)?D.delete(E):D.add(E),D})},k=async()=>{_(!0);try{const E=Array.from(p);E.length>0&&await h.mutateAsync(E),await o(),await m.mutateAsync({dealId:r,stageId:l}),t(!1)}catch(E){console.error("Stage move failed:",E),he.error((E==null?void 0:E.message)||"Failed to move deal. Please try again.")}finally{_(!1)}},T=async()=>{_(!0);try{await o(),await m.mutateAsync({dealId:r,stageId:l}),t(!1)}catch(E){console.error("Stage move (skip) failed:",E),he.error((E==null?void 0:E.message)||"Failed to move deal. Please try again.")}finally{_(!1)}};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"sm:max-w-[480px]",children:[e.jsxs(Cs,{children:[e.jsx(Ns,{children:"Move Deal"}),e.jsxs(nn,{children:["Moving ",e.jsx("span",{className:"font-medium text-foreground",children:n})]})]}),e.jsxs("div",{className:"flex items-center justify-center gap-3 py-2",children:[e.jsx(Xe,{variant:"outline",className:"text-sm",children:a}),e.jsx(bi,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(Xe,{className:"text-sm bg-primary",children:i})]}),d?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(is,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):b.length>0?e.jsxs("div",{className:"space-y-3",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["You have ",e.jsx("span",{className:"font-medium text-foreground",children:b.length})," incomplete task",b.length!==1?"s":"",". Select which to mark as done:"]}),e.jsx(Ci,{className:"max-h-[250px]",children:e.jsx("div",{className:"space-y-1",children:b.map(E=>e.jsxs("label",{className:"flex items-center gap-3 px-3 py-2 rounded-lg hover:bg-muted/50 cursor-pointer transition-colors",children:[e.jsx(ao,{checked:p.has(E.id),onCheckedChange:()=>j(E.id)}),e.jsxs("span",{className:"text-sm flex-1",children:[A7s[E.priority]," ",E.title]}),E.stage&&e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full",style:{backgroundColor:E.stage.color+"20",color:E.stage.color},children:E.stage.name})]},E.id))})}),e.jsxs("div",{className:"flex items-center justify-between gap-2 pt-2",children:[e.jsx(H,{variant:"ghost",size:"sm",onClick:()=>{p.size===b.length?x(new Set):x(new Set(b.map(E=>E.id)))},children:p.size===b.length?"Deselect All":"Select All"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(H,{variant:"outline",size:"sm",onClick:T,disabled:y,children:"Skip"}),e.jsxs(H,{size:"sm",onClick:k,disabled:y,children:[y&&e.jsx(is,{className:"h-4 w-4 mr-1 animate-spin"}),p.size>0?`Complete ${p.size} & Move`:"Move Deal"]})]})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"text-center py-4",children:[e.jsx(ea,{className:"h-8 w-8 text-emerald-500 mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"All tasks completed! Ready to move."})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(H,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(H,{onClick:k,disabled:y,children:[y&&e.jsx(is,{className:"h-4 w-4 mr-1 animate-spin"}),"Move to ",i]})]})]})]})})}const I7s=[{name:"ReLevelUp",brand:"#406E71",accent:"#2a4c64"},{name:"Slate",brand:"#0f172a",accent:"#475569"},{name:"Midnight",brand:"#111827",accent:"#3b82f6"},{name:"Forest",brand:"#14532d",accent:"#65a30d"},{name:"Burgundy",brand:"#7f1d1d",accent:"#b45309"},{name:"Royal",brand:"#1e3a8a",accent:"#7c3aed"}];function Tyt({open:s,onOpenChange:t}){const r=ba(),{data:n,isLoading:a}=Vat(),i=l$t(),[l,o]=S.useState({logo_url:null,cover_photo_url:null,brand_color:null,accent_color:null,tagline:null,welcome_message:null}),[c,d]=S.useState(null);S.useEffect(()=>{s&&o({logo_url:(n==null?void 0:n.logo_url)??null,cover_photo_url:(n==null?void 0:n.cover_photo_url)??null,brand_color:(n==null?void 0:n.brand_color)??null,accent_color:(n==null?void 0:n.accent_color)??null,tagline:(n==null?void 0:n.tagline)??null,welcome_message:(n==null?void 0:n.welcome_message)??null})},[s,n]);const h=x=>o(y=>({...y,...x})),m=async(x,y)=>{if(r){if(x.size>5*1024*1024){he.error("Image must be under 5MB");return}d(y);try{const _=await Hat(r,x,y);h(y==="logo"?{logo_url:_}:{cover_photo_url:_})}catch(_){he.error(`Upload failed: ${_.message||_}`)}finally{d(null)}}},p=async()=>{try{await i.mutateAsync(l),he.success("Portal branding saved"),t(!1)}catch{he.error("Failed to save branding")}};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-lg max-h-[90vh] flex flex-col",children:[e.jsxs(Cs,{children:[e.jsxs(Ns,{className:"flex items-center gap-2",children:[e.jsx(pl,{className:"h-5 w-5 text-primary"}),"Portal Branding"]}),e.jsx(nn,{children:"Customize how your client portals look. These defaults apply to every portal — you can override them per deal."})]}),e.jsx(Ci,{className:"flex-1 pr-3 -mr-3",children:a?e.jsx("div",{className:"py-12 flex justify-center",children:e.jsx(is,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"space-y-6 py-2",children:[e.jsx(P7s,{draft:l}),e.jsx(fWe,{label:"Logo",hint:"Shown above your name on the portal. PNG with transparent background works best.",value:l.logo_url,uploading:c==="logo",onUpload:x=>m(x,"logo"),onClear:()=>h({logo_url:null}),aspect:"square"}),e.jsx(fWe,{label:"Cover Photo",hint:"Hero background at the top of the portal. Wide landscape works best.",value:l.cover_photo_url,uploading:c==="cover",onUpload:x=>m(x,"cover"),onClear:()=>h({cover_photo_url:null}),aspect:"cover"}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ue,{className:"text-sm font-medium",children:"Brand Colors"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Used for the header background and primary buttons."})]}),e.jsx("div",{className:"grid grid-cols-3 gap-2",children:I7s.map(x=>{const y=l.brand_color===x.brand&&l.accent_color===x.accent;return e.jsxs("button",{type:"button",onClick:()=>h({brand_color:x.brand,accent_color:x.accent}),className:Ft("group relative rounded-lg border-2 p-2 text-left transition-all",y?"border-primary ring-2 ring-primary/20":"border-input hover:border-primary/40"),children:[e.jsxs("div",{className:"flex h-6 rounded-md overflow-hidden",children:[e.jsx("div",{className:"flex-1",style:{background:x.brand}}),e.jsx("div",{className:"flex-1",style:{background:x.accent}})]}),e.jsx("div",{className:"text-[11px] mt-1.5 font-medium text-foreground",children:x.name})]},x.name)})}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(pWe,{label:"Brand",value:l.brand_color,onChange:x=>h({brand_color:x})}),e.jsx(pWe,{label:"Accent",value:l.accent_color,onChange:x=>h({accent_color:x})})]})]}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-sm font-medium",children:"Tagline"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Short line shown under your name."}),e.jsx(Se,{value:l.tagline||"",onChange:x=>h({tagline:x.target.value}),placeholder:"Your trusted real estate advisor",maxLength:80})]}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-sm font-medium",children:"Default Welcome Message"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Shown on the portal hero. Per-deal welcome messages override this."}),e.jsx("textarea",{value:l.welcome_message||"",onChange:x=>h({welcome_message:x.target.value}),placeholder:"Welcome! Here's everything you need for your transaction.",className:"w-full rounded-md border border-input bg-background px-3 py-2 text-sm min-h-[70px] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",maxLength:300})]})]})}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4 border-t shrink-0",children:[e.jsx(H,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(H,{onClick:p,disabled:i.isPending,children:[i.isPending?e.jsx(is,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(vc,{className:"h-4 w-4 mr-2"}),"Save Branding"]})]})]})})}function P7s({draft:s}){const t=s.brand_color||"#2a4c64",r=s.accent_color||"#406E71";return e.jsxs("div",{className:"rounded-xl overflow-hidden border border-input shadow-sm",children:[e.jsx("div",{className:"relative h-24 flex items-center justify-center text-white",style:{background:s.cover_photo_url?`linear-gradient(135deg, ${t}cc, ${r}cc), url(${s.cover_photo_url}) center/cover`:`linear-gradient(135deg, ${t}, ${r})`},children:s.logo_url?e.jsx("img",{src:s.logo_url,alt:"logo",className:"h-12 w-12 rounded-full object-cover border-2 border-white/40 shadow"}):e.jsx("div",{className:"h-12 w-12 rounded-full bg-white/20 border-2 border-white/40"})}),e.jsxs("div",{className:"bg-white p-3 text-center",children:[e.jsx("div",{className:"text-sm font-semibold text-slate-800",children:"Your Name"}),e.jsx("div",{className:"text-[11px] text-slate-500",children:s.tagline||"Your tagline appears here"})]})]})}function fWe({label:s,hint:t,value:r,uploading:n,onUpload:a,onClear:i,aspect:l}){return e.jsxs("div",{children:[e.jsx(ue,{className:"text-sm font-medium",children:s}),e.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:t}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:Ft("rounded-lg border-2 border-dashed border-input flex items-center justify-center overflow-hidden bg-muted/30 shrink-0",l==="square"?"h-16 w-16":"h-16 w-32"),children:r?e.jsx("img",{src:r,alt:s,className:"h-full w-full object-cover"}):e.jsx(wl,{className:"h-5 w-5 text-muted-foreground/40"})}),e.jsxs("div",{className:"flex-1 flex gap-2",children:[e.jsxs("label",{className:"cursor-pointer",children:[e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:o=>{var d;const c=(d=o.target.files)==null?void 0:d[0];c&&a(c),o.target.value=""}}),e.jsxs("span",{className:"inline-flex items-center gap-1.5 h-9 px-3 rounded-md border border-input bg-background hover:bg-accent text-sm font-medium",children:[n?e.jsx(is,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Ea,{className:"h-3.5 w-3.5"}),r?"Replace":"Upload"]})]}),r&&e.jsx(H,{variant:"ghost",size:"sm",onClick:i,className:"text-muted-foreground hover:text-destructive",children:e.jsx(Dr,{className:"h-3.5 w-3.5"})})]})]})]})}function pWe({label:s,value:t,onChange:r}){const n=t||"#000000";return e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs text-muted-foreground",children:s}),e.jsxs("div",{className:"mt-1 flex items-center gap-2 h-9 rounded-md border border-input bg-background px-2",children:[e.jsx("input",{type:"color",value:n,onChange:a=>r(a.target.value),className:"h-6 w-8 rounded cursor-pointer border-0 bg-transparent"}),e.jsx(Se,{value:t||"",onChange:a=>r(a.target.value||null),placeholder:"#406E71",className:"border-0 h-7 px-1 focus-visible:ring-0 text-xs font-mono"})]})]})}function L7s(){const s=ba();return yt({queryKey:["all-client-portals",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await V.from("client_portals").select("*").eq("owner_user_id",s);if(r)throw r;return t||[]},enabled:!!s})}function D7s({dealId:s,dealName:t,contactName:r,portal:n,onSettingsOpen:a,onComposerOpen:i,onInviteOpen:l,onDeleteConfirm:o}){const c=dMe(),d=G8(),h=Qgt(),m=Jgt(),[p,x]=S.useState(!1),y=!!(n!=null&&n.archived_at),_=async()=>{x(!0);try{await c.mutateAsync({deal_id:s,visibility:"private",require_onboarding:!0}),he.success("Portal enabled!")}catch{he.error("Failed to create portal")}finally{x(!1)}},b=async A=>{if(n)try{await d.mutateAsync({id:n.id,is_enabled:A}),he.success(A?"Portal enabled":"Portal disabled")}catch{he.error("Failed to update portal")}},j=()=>{n&&(navigator.clipboard.writeText(C_(n.slug)),he.success("Link copied!"))},k=()=>{n&&window.open(C_(n.slug),"_blank")},T=async()=>{if(n)try{await h.mutateAsync(n.id),he.success("Portal archived")}catch{he.error("Failed to archive portal")}},E=async()=>{if(n)try{await m.mutateAsync(n.id),he.success("Portal restored")}catch{he.error("Failed to restore portal")}};return n?y?e.jsxs("div",{className:"flex items-center gap-4 p-4 border rounded-lg opacity-60 bg-muted/30",children:[e.jsxs(Xn,{to:`/mission-control/client-portals/${n.id}`,className:"flex-1 min-w-0 hover:opacity-80",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:t}),e.jsx(Xe,{variant:"outline",className:"text-[10px] bg-muted text-muted-foreground",children:"Archived"})]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:n.client_name||r||"No client name"})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[e.jsxs(H,{variant:"ghost",size:"sm",onClick:E,className:"text-xs gap-1",children:[e.jsx(AI,{className:"h-3.5 w-3.5"}),"Restore"]}),e.jsxs(H,{variant:"ghost",size:"sm",onClick:()=>o(n),className:"text-xs gap-1 text-destructive hover:text-destructive",children:[e.jsx(Dr,{className:"h-3.5 w-3.5"}),"Delete"]})]})]}):e.jsxs("div",{className:"flex items-center gap-4 p-4 border rounded-lg hover:border-primary/40 hover:bg-muted/30 transition-colors group",children:[e.jsxs(Xn,{to:`/mission-control/client-portals/${n.id}`,className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"font-medium text-sm truncate group-hover:text-primary transition-colors",children:t}),e.jsx(Xe,{variant:"outline",className:n.is_enabled?"text-[10px] bg-emerald-500/10 text-emerald-600 border-emerald-200":"text-[10px] bg-muted text-muted-foreground",children:n.is_enabled?"Active":"Disabled"}),e.jsx($a,{className:"h-3.5 w-3.5 text-muted-foreground opacity-0 group-hover:opacity-100 transition-opacity"})]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:n.client_name||r||"No client name"})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[e.jsx(H,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:j,title:"Copy link",children:e.jsx(ui,{className:"h-3.5 w-3.5"})}),e.jsx(H,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:k,title:"Preview",children:e.jsx(gn,{className:"h-3.5 w-3.5"})}),e.jsx(H,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>l(n,t),title:"Invite client",children:e.jsx(yn,{className:"h-3.5 w-3.5"})}),e.jsx(H,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>i(n),title:"Post update",children:e.jsx(t_,{className:"h-3.5 w-3.5"})}),e.jsx(H,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>a(n),title:"Settings",children:e.jsx(Go,{className:"h-3.5 w-3.5"})}),e.jsxs(Xu,{children:[e.jsx(Qu,{asChild:!0,children:e.jsx(H,{variant:"ghost",size:"icon",className:"h-8 w-8",children:e.jsx(Jx,{className:"h-3.5 w-3.5"})})}),e.jsx(wu,{align:"end",children:e.jsxs(di,{onClick:T,children:[e.jsx(Rk,{className:"h-4 w-4 mr-2"}),"Archive Portal"]})})]}),e.jsx(Or,{checked:n.is_enabled,onCheckedChange:b,className:"ml-1"})]})]}):e.jsxs("div",{className:"flex items-center justify-between p-4 border rounded-lg border-dashed bg-muted/20",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:t}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:r||"No contact"})]}),e.jsxs(H,{size:"sm",onClick:_,disabled:p,className:"shrink-0 ml-4",children:[p?e.jsx(is,{className:"h-3 w-3 animate-spin mr-1"}):e.jsx(Lr,{className:"h-3 w-3 mr-1"}),"Enable Portal"]})]})}function Eyt(){const{data:s,isLoading:t}=B0e(),{data:r,isLoading:n}=L7s(),[a,i]=S.useState(""),[l,o]=S.useState("all"),c=ext(),[d,h]=S.useState(null),[m,p]=S.useState(null),[x,y]=S.useState(null),[_,b]=S.useState(null),[j,k]=S.useState(!1),T=ba(),E=t||n,A=new Map;r==null||r.forEach(Z=>A.set(Z.deal_id,Z));const R=[...(s||[]).filter(Z=>{var ce,ne,le,be,fe;const J=A.get(Z.id),K=a.toLowerCase(),re=!K||Z.deal_name.toLowerCase().includes(K)||((ne=(ce=Z.contact)==null?void 0:ce.first_name)==null?void 0:ne.toLowerCase().includes(K))||((be=(le=Z.contact)==null?void 0:le.last_name)==null?void 0:be.toLowerCase().includes(K))||((fe=J==null?void 0:J.client_name)==null?void 0:fe.toLowerCase().includes(K));let ie=!0;return l==="active"?ie=!!(J!=null&&J.is_enabled)&&!(J!=null&&J.archived_at):l==="disabled"?ie=!!J&&!J.is_enabled&&!J.archived_at:l==="archived"?ie=!!(J!=null&&J.archived_at):l==="none"?ie=!J:l==="all"&&(ie=!(J!=null&&J.archived_at)||!J),re&&ie})].sort((Z,J)=>{const K=A.get(Z.id),re=A.get(J.id);if(K!=null&&K.archived_at&&!(re!=null&&re.archived_at))return 1;if(!(K!=null&&K.archived_at)&&(re!=null&&re.archived_at)||K&&!re)return-1;if(!K&&re)return 1;if(K&&re){if(K.is_enabled&&!re.is_enabled)return-1;if(!K.is_enabled&&re.is_enabled)return 1}return 0}),z=(r==null?void 0:r.filter(Z=>!Z.archived_at).length)||0,O=(r==null?void 0:r.filter(Z=>Z.is_enabled&&!Z.archived_at).length)||0,$=(r==null?void 0:r.filter(Z=>Z.archived_at).length)||0,ee=async()=>{if(_)try{await c.mutateAsync({id:_.id,dealId:_.deal_id}),he.success("Portal permanently deleted"),b(null)}catch{he.error("Failed to delete portal")}};return E?e.jsx("div",{className:"flex items-center justify-center py-16",children:e.jsx(is,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Lr,{className:"h-4 w-4 text-primary"}),e.jsxs("span",{className:"font-medium",children:[z," Portals"]})]}),e.jsxs("span",{className:"text-muted-foreground",children:[O," active · ",z-O," disabled",$>0&&` · ${$} archived`]})]}),e.jsxs(H,{variant:"outline",size:"sm",onClick:()=>k(!0),className:"gap-1.5",children:[e.jsx(pl,{className:"h-3.5 w-3.5"}),"Portal Branding"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative flex-1 max-w-sm",children:[e.jsx(Mn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Se,{placeholder:"Search deals or clients...",value:a,onChange:Z=>i(Z.target.value),className:"pl-9 pr-8"}),a&&e.jsx("button",{onClick:()=>i(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground",children:e.jsx(Rr,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"flex bg-muted rounded-lg p-1 gap-0.5",children:["all","active","disabled","archived","none"].map(Z=>e.jsx(H,{variant:l===Z?"secondary":"ghost",size:"sm",onClick:()=>o(Z),className:"text-xs px-3 capitalize",children:Z==="none"?"No Portal":Z},Z))})]}),e.jsx(Ci,{className:"h-[calc(100vh-22rem)]",children:e.jsxs("div",{className:"space-y-2 pb-4",children:[R.map(Z=>{const J=A.get(Z.id)||null,K=Z.contact?`${Z.contact.first_name||""} ${Z.contact.last_name||""}`.trim():"";return e.jsx(D7s,{dealId:Z.id,dealName:Z.deal_name,contactName:K,portal:J,onSettingsOpen:h,onComposerOpen:re=>p(re),onInviteOpen:(re,ie)=>y({portal:re,dealName:ie}),onDeleteConfirm:b},Z.id)}),R.length===0&&e.jsxs("div",{className:"text-center py-12",children:[e.jsx("div",{className:"w-12 h-12 mx-auto mb-3 bg-muted rounded-full flex items-center justify-center",children:e.jsx(Lr,{className:"h-5 w-5 text-muted-foreground"})}),e.jsx("p",{className:"text-sm font-medium",children:"No matching deals"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Try adjusting your search or filters"})]})]})})]}),d&&e.jsx(u6e,{open:!!d,onOpenChange:Z=>!Z&&h(null),portal:d,dealOwnerId:T||""}),m&&e.jsx(h6e,{open:!!m,onOpenChange:Z=>!Z&&p(null),portalId:m.id,portalSlug:m.slug,notifyClient:m.notify_client}),x&&e.jsx(m6e,{open:!!x,onOpenChange:Z=>!Z&&y(null),portal:x.portal,dealName:x.dealName}),e.jsx(Tyt,{open:j,onOpenChange:k}),e.jsx(Rl,{open:!!_,onOpenChange:Z=>!Z&&b(null),children:e.jsxs(jl,{children:[e.jsxs(Nl,{children:[e.jsx(Sl,{children:"Permanently delete this portal?"}),e.jsx(Cl,{children:"This will permanently remove the portal and all its updates. The client will no longer be able to access their portal page. This action cannot be undone."})]}),e.jsxs(kl,{children:[e.jsx(Tl,{children:"Cancel"}),e.jsx(ml,{onClick:ee,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete Permanently"})]})]})})]})}class R7s extends S.Component{constructor(t){super(t),this.state={hasError:!1,error:null}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,r){console.error("DealPipeline error:",t,r)}render(){return this.state.hasError?e.jsx(Ss,{children:e.jsxs("div",{className:"flex flex-col items-center justify-center h-[60vh] gap-4 text-center px-4",children:[e.jsx("div",{className:"w-16 h-16 bg-destructive/10 rounded-full flex items-center justify-center",children:e.jsx("span",{className:"text-2xl",children:"⚠️"})}),e.jsx("h2",{className:"text-xl font-semibold",children:"Something went wrong"}),e.jsx("p",{className:"text-muted-foreground max-w-md",children:"There was an error in the deal pipeline. Click below to try again."}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx("button",{onClick:()=>this.setState({hasError:!1,error:null}),className:"px-4 py-2 bg-primary text-primary-foreground rounded-md text-sm font-medium hover:bg-primary/90",children:"Try Again"}),e.jsx("button",{onClick:()=>window.location.reload(),className:"px-4 py-2 border border-border rounded-md text-sm font-medium hover:bg-muted",children:"Refresh Page"})]})]})}):this.props.children}}const tO="deal-pipeline-detail-sheet";function O7s(){var Gs;const s=V8(),{data:t,isLoading:r}=F0e(),{data:n,isLoading:a,refetch:i}=B0e(),{data:l,isLoading:o}=pRs(),c=yxt(),d=lRs(),[h,m]=S.useState("board"),[p,x]=S.useState(!1),[y,_]=S.useState(!1),[b,j]=S.useState(null),[k,T]=S.useState(null),[E,A]=S.useState(null),[D,R]=S.useState(null),[z,O]=S.useState(!1),[$,ee]=S.useState(null),[Z,J]=S.useState(""),[K,re]=S.useState("all"),[ie,ce]=S.useState("all"),{data:ne}=qFs(),[le,be]=S.useState(!1),[fe,je]=S.useState(!1),[ve,We]=S.useState(new Set),Ve=S.useRef(!1),[Le,Me]=S.useState(null),{data:ze}=sv(),{isTeamLeader:Pe,teamMembers:Ie}=$Fs(),De=S.useMemo(()=>Array.from(ve),[ve]),{data:pe}=UFs(De),tt=S.useMemo(()=>{const _s=new Map;return Ie.forEach(br=>_s.set(br.id,{name:br.name,avatar_url:br.avatar_url,color:br.color})),_s},[Ie]),ge=S.useCallback(_s=>_s.owner_user_id&&tt.get(_s.owner_user_id)||null,[tt]),ct=S.useCallback(_s=>{We(br=>{const zr=new Set(br);return zr.has(_s)?zr.delete(_s):zr.add(_s),zr})},[]);S.useEffect(()=>{!r&&t&&t.length===0&&c.mutate()},[r,t]);const[Ue,et]=Ed(),Qe=S.useRef(!1);S.useEffect(()=>{const _s=Ue.get("deal");if(_s&&n&&n.length>0&&!Qe.current){const br=n.find(zr=>zr.id===_s);br&&(Qe.current=!0,j(br),_(!0),Ue.delete("deal"),et(Ue,{replace:!0}))}},[n,Ue]);const Ne=S.useMemo(()=>{if(!pe||!t)return[];const _s=new Map(t.map(br=>[br.name,br.id]));return pe.map(br=>{const zr=br._stage_name&&_s.get(br._stage_name)||null;return{...br,stage_id:zr||br.stage_id}})},[pe,t]),$e=S.useMemo(()=>[...n||[],...Ne],[n,Ne]);S.useEffect(()=>{if(Ve.current||$e.length===0)return;Ve.current=!0;const _s=sessionStorage.getItem(tO);if(_s)try{const br=JSON.parse(_s);if(!br.open||!br.dealId)return;const zr=$e.find(Yr=>Yr.id===br.dealId);zr&&(j(zr),_(!0))}catch{sessionStorage.removeItem(tO)}},[$e]),S.useEffect(()=>{y&&(b!=null&&b.id)?sessionStorage.setItem(tO,JSON.stringify({dealId:b.id,open:!0})):sessionStorage.removeItem(tO)},[y,b==null?void 0:b.id]);const it=(ne==null?void 0:ne.byDeal)||{},Je=(ne==null?void 0:ne.unique)||[],st=$e.filter(_s=>{var Vr,$r,hn,Zn,cr,on;const br=Z.toLowerCase(),zr=it[_s.id]||[],Yr=!br||_s.deal_name.toLowerCase().includes(br)||(($r=(Vr=_s.contact)==null?void 0:Vr.first_name)==null?void 0:$r.toLowerCase().includes(br))||((Zn=(hn=_s.contact)==null?void 0:hn.last_name)==null?void 0:Zn.toLowerCase().includes(br))||((cr=_s.property_address)==null?void 0:cr.toLowerCase().includes(br))||((on=_s.city)==null?void 0:on.toLowerCase().includes(br))||zr.some(ds=>ds.toLowerCase().includes(br)),rn=K==="all"||_s.deal_type===K,sn=ie==="all"||zr.includes(ie);return Yr&&rn&&sn}),mt=S.useMemo(()=>{if(!t)return l||null;const _s=new Set(t.filter(Vr=>Vr.is_won_stage).map(Vr=>Vr.id)),br=new Set(t.filter(Vr=>Vr.is_lost_stage).map(Vr=>Vr.id)),zr=$e.filter(Vr=>Vr.stage_id&&!_s.has(Vr.stage_id)&&!br.has(Vr.stage_id)),Yr=$e.filter(Vr=>Vr.stage_id&&_s.has(Vr.stage_id)),rn=new Date().getFullYear(),sn=Yr.filter(Vr=>Vr.actual_close_date?new Date(Vr.actual_close_date).getFullYear()===rn:!0);return{totalDeals:$e.length,activeDeals:zr.length,wonDeals:Yr.length,pipelineValue:zr.reduce((Vr,$r)=>Vr+($r.expected_price||0),0),expectedCommission:zr.reduce((Vr,$r)=>Vr+($r.expected_commission||0),0),expectedNetToAgent:zr.reduce((Vr,$r)=>Vr+(Ry($r)||0),0),wonValue:Yr.reduce((Vr,$r)=>Vr+($r.expected_price||0),0),weightedGCI:zr.reduce((Vr,$r)=>Vr+($r.expected_commission||0)*(($r.probability??50)/100),0),weightedNet:zr.reduce((Vr,$r)=>Vr+(Ry($r)||0)*(($r.probability??50)/100),0),ytdWonDeals:sn.length,ytdWonGCI:sn.reduce((Vr,$r)=>Vr+($r.expected_commission||0),0),ytdWonNet:sn.reduce((Vr,$r)=>Vr+(Ry($r)||0),0),projectedAnnualNet:sn.reduce((Vr,$r)=>Vr+(Ry($r)||0),0)+zr.reduce((Vr,$r)=>Vr+(Ry($r)||0)*(($r.probability??50)/100),0)}},[$e,t,l]),wt=_s=>{j(_s),_(!0)},at=_s=>{T(_s||null),j(null),x(!0)},rt=_s=>{j(_s),_(!1),x(!0)},Et=_s=>{_(_s),_s||sessionStorage.removeItem(tO)},hs=(_s,br)=>{A(_s)},Is=(_s,br)=>{_s.preventDefault(),_s.dataTransfer.dropEffect="move",R(br)},lr=async(_s,br)=>{if(_s.preventDefault(),R(null),!E)return;const zr=n==null?void 0:n.find(sn=>sn.id===E),Yr=t==null?void 0:t.find(sn=>sn.id===br),rn=t==null?void 0:t.find(sn=>sn.id===(zr==null?void 0:zr.stage_id));if(!zr||!Yr||zr.stage_id===br){A(null);return}Me({dealId:E,dealName:zr.deal_name,fromStageName:(rn==null?void 0:rn.name)||"Unknown",toStageName:Yr.name,toStageId:br,isWonStage:Yr.is_won_stage,deal:zr}),A(null)},us=async()=>{if(!Le)return;const{dealId:_s,toStageId:br,toStageName:zr,isWonStage:Yr,deal:rn}=Le;if(await d.mutateAsync({dealId:_s,stageId:br,stageName:zr}),he.success(`Moved to ${zr}`),Yr&&!rn.scorecard_transaction_id){const sn={...rn,stage_id:br};ee(sn),O(!0)}},St=S.useCallback(async(_s,br,zr)=>{const Yr=n==null?void 0:n.find(Vr=>Vr.id===_s),rn=t==null?void 0:t.find(Vr=>Vr.id===br),sn=t==null?void 0:t.find(Vr=>Vr.id===(Yr==null?void 0:Yr.stage_id));!Yr||!rn||Yr.stage_id===br||Me({dealId:_s,dealName:Yr.deal_name,fromStageName:(sn==null?void 0:sn.name)||"Unknown",toStageName:zr,toStageId:br,isWonStage:rn.is_won_stage,deal:Yr})},[n,t]),xs=_s=>st.filter(br=>br.stage_id===_s),kt=r||a,fs=s?"list":h;return e.jsxs(Ss,{children:[e.jsxs("div",{className:"flex flex-col h-[calc(100vh-4rem)]",children:[e.jsxs("div",{className:"shrink-0 p-4 md:p-6 pb-0 space-y-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Deal Pipeline"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Track and manage your active deals"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(H,{variant:"outline",size:"icon",onClick:()=>i(),className:"shrink-0",children:e.jsx(po,{className:"h-4 w-4"})}),!s&&e.jsx(xj,{children:e.jsxs("div",{className:"flex bg-muted rounded-lg p-1 gap-0.5",children:[e.jsxs(rd,{children:[e.jsx(nd,{asChild:!0,children:e.jsxs(H,{variant:h==="board"?"secondary":"ghost",size:"sm",onClick:()=>m("board"),className:"px-3 gap-1.5",children:[e.jsx(_g,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline text-xs",children:"Board"})]})}),e.jsx(Rc,{children:"Kanban board view"})]}),e.jsxs(rd,{children:[e.jsx(nd,{asChild:!0,children:e.jsxs(H,{variant:h==="list"?"secondary":"ghost",size:"sm",onClick:()=>m("list"),className:"px-3 gap-1.5",children:[e.jsx(Vf,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline text-xs",children:"List"})]})}),e.jsx(Rc,{children:"Grouped list view"})]}),e.jsxs(rd,{children:[e.jsx(nd,{asChild:!0,children:e.jsxs(H,{variant:h==="table"?"secondary":"ghost",size:"sm",onClick:()=>m("table"),className:"px-3 gap-1.5",children:[e.jsx(YI,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline text-xs",children:"Table"})]})}),e.jsx(Rc,{children:"Sortable table view"})]}),e.jsxs(rd,{children:[e.jsx(nd,{asChild:!0,children:e.jsxs(H,{variant:h==="portals"?"secondary":"ghost",size:"sm",onClick:()=>m("portals"),className:"px-3 gap-1.5",children:[e.jsx(Lr,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline text-xs",children:"Portals"})]})}),e.jsx(Rc,{children:"Client portal management"})]})]})}),ze&&!Pe&&e.jsxs(H,{variant:"outline",onClick:()=>be(!0),children:[e.jsx(Ar,{className:"h-4 w-4 mr-2"}),"Team"]}),e.jsxs(H,{onClick:()=>at(),children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Add Deal"]})]})]}),fs!=="portals"&&e.jsx(WFs,{stats:mt,isLoading:o}),fs!=="portals"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative flex-1 max-w-sm",children:[e.jsx(Mn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Se,{placeholder:"Search deals, contacts, addresses, tags...",value:Z,onChange:_s=>J(_s.target.value),className:"pl-9 pr-8"}),Z&&e.jsx("button",{onClick:()=>J(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground",children:e.jsx(Rr,{className:"h-4 w-4"})})]}),e.jsxs(Bs,{value:K,onValueChange:re,children:[e.jsx(Os,{className:"w-[140px]",children:e.jsx(Us,{placeholder:"All Types"})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"all",children:"All Types"}),e.jsx(pt,{value:"buyer",children:"Buyer"}),e.jsx(pt,{value:"seller",children:"Seller"}),e.jsx(pt,{value:"dual",children:"Dual"}),e.jsx(pt,{value:"referral",children:"Referral"}),e.jsx(pt,{value:"lease",children:"Lease"})]})]}),e.jsxs(Bs,{value:ie,onValueChange:ce,children:[e.jsxs(Os,{className:"w-[160px]",children:[e.jsx(xm,{className:"h-3.5 w-3.5 mr-1.5 text-muted-foreground"}),e.jsx(Us,{placeholder:"All Tags"})]}),e.jsxs(Fs,{className:"max-h-[300px]",children:[e.jsx(pt,{value:"all",children:"All Tags"}),Je.length===0&&e.jsx("div",{className:"px-2 py-1.5 text-xs text-muted-foreground",children:"No tags yet"}),Je.map(_s=>e.jsx(pt,{value:_s,children:_s},_s))]})]}),ie!=="all"&&e.jsxs(Xe,{variant:"secondary",className:"gap-1",children:[e.jsx(xm,{className:"h-3 w-3"}),ie,e.jsx("button",{onClick:()=>ce("all"),className:"ml-1 hover:text-foreground","aria-label":"Clear tag filter",children:e.jsx(Rr,{className:"h-3 w-3"})})]}),(Z||K!=="all"||ie!=="all")&&e.jsxs("span",{className:"text-xs text-muted-foreground whitespace-nowrap",children:[st.length," of ",(n==null?void 0:n.length)||0," deals"]})]})]}),e.jsxs("div",{className:"flex-1 min-h-0 flex",children:[Pe&&!s&&Ie.length>0&&e.jsx(zFs,{members:Ie,enabledMembers:ve,onToggleMember:ct,isOpen:fe,onToggleOpen:()=>je(_s=>!_s)}),e.jsx("div",{className:"flex-1 min-w-0 min-h-0 p-4 md:p-6 pt-4",children:kt?e.jsx("div",{className:"flex gap-4 h-full",children:[1,2,3,4].map(_s=>e.jsx("div",{className:"min-w-[280px] max-w-[320px] flex-shrink-0",children:e.jsx(Ks,{className:"h-full rounded-xl"})},_s))}):fs==="board"?e.jsxs(Ci,{className:"h-full -mx-4 md:-mx-6 px-4 md:px-6",children:[e.jsx("div",{className:"flex gap-4 h-full pb-4",children:t==null?void 0:t.map(_s=>e.jsx(GFs,{stage:_s,deals:xs(_s.id),onDealClick:wt,onAddDeal:at,onDragStart:hs,onDragOver:Is,onDrop:lr,isDragOver:D===_s.id,isWonStage:_s.is_won_stage,getOwnerInfo:ge},_s.id))}),e.jsx(Ige,{orientation:"horizontal"})]}):fs==="table"?e.jsx(Ci,{className:"h-full",children:e.jsx(v7s,{deals:st,stages:t||[],onDealClick:wt,onStageChange:St})}):fs==="portals"?e.jsx(Eyt,{}):e.jsx(Ci,{className:"h-full",children:e.jsxs("div",{className:"space-y-6",children:[t==null?void 0:t.map(_s=>{const br=xs(_s.id);return br.length===0?null:e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx("div",{className:"w-3 h-3 rounded-full",style:{backgroundColor:_s.color}}),e.jsx("h3",{className:"font-semibold",children:_s.name}),e.jsxs("span",{className:"text-muted-foreground text-sm",children:["(",br.length,")"]})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3",children:br.map(zr=>e.jsx(Syt,{deal:zr,onClick:()=>wt(zr),stages:t,onStageChange:St,showStagePicker:!0,isWonStage:_s.is_won_stage,ownerInfo:ge(zr)},zr.id))})]},_s.id)}),(n==null?void 0:n.length)===0&&e.jsxs("div",{className:"text-center py-16",children:[e.jsx("div",{className:"w-16 h-16 mx-auto mb-4 bg-muted rounded-full flex items-center justify-center",children:e.jsx(_g,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx("h3",{className:"font-semibold text-lg mb-2",children:"No deals yet"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"Start tracking your opportunities by adding your first deal"}),e.jsxs(H,{onClick:()=>at(),children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Add Your First Deal"]})]}),((n==null?void 0:n.length)||0)>0&&st.length===0&&e.jsxs("div",{className:"text-center py-16",children:[e.jsx("div",{className:"w-16 h-16 mx-auto mb-4 bg-muted rounded-full flex items-center justify-center",children:e.jsx(Mn,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx("h3",{className:"font-semibold text-lg mb-2",children:"No matching deals"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"Try adjusting your search or filters"}),e.jsx(H,{variant:"outline",onClick:()=>{J(""),re("all")},children:"Clear Filters"})]})]})})})]})]}),e.jsx(XFs,{open:p,onOpenChange:x,deal:b,defaultStageId:k}),e.jsx(g7s,{deal:b,open:y,onOpenChange:Et,onEdit:rt,isWonStage:b?(Gs=t==null?void 0:t.find(_s=>_s.id===b.stage_id))==null?void 0:Gs.is_won_stage:!1,onAddToScorecard:_s=>{ee(_s),O(!0),_(!1)}}),e.jsx(x7s,{open:z,onOpenChange:O,deal:$,onComplete:()=>{i(),ee(null)}}),Le&&e.jsx(M7s,{open:!!Le,onOpenChange:_s=>{_s||Me(null)},dealId:Le.dealId,dealName:Le.dealName,fromStageName:Le.fromStageName,toStageName:Le.toStageName,toStageId:Le.toStageId,onConfirm:us}),e.jsx(FFs,{open:le,onOpenChange:be})]})}function F7s(){return e.jsx(R7s,{children:e.jsx(O7s,{})})}function Ayt({open:s,onOpenChange:t,editTask:r,defaultDealId:n,defaultStageId:a}){var J;const i=w7s(),l=j7s(),{data:o}=B0e(),c=ba(),{data:d}=yt({queryKey:["contacts-for-tasks",c],queryFn:async()=>{if(!c)return[];const{data:K,error:re}=await V.from("innercircle_contacts").select("id, first_name, last_name").eq("owner_user_id",c).order("first_name").limit(500);if(re)throw re;return K},enabled:!!c&&s}),[h,m]=S.useState(""),[p,x]=S.useState(""),[y,_]=S.useState("none"),[b,j]=S.useState("none"),[k,T]=S.useState("medium"),[E,A]=S.useState("todo"),[D,R]=S.useState(),[z,O]=S.useState(!1),[$,ee]=S.useState(!1);S.useEffect(()=>{r?(m(r.title),x(r.description||""),_(r.deal_id||"none"),j(r.contact_id||"none"),T(r.priority),A(r.status),R(r.due_date?dg(r.due_date):void 0)):(m(""),x(""),_(n||"none"),j("none"),T("medium"),A("todo"),R(void 0))},[r,s,n]);const Z=async()=>{if(!h.trim()){he.error("Task title is required");return}try{const K={title:h.trim(),description:p.trim()||null,deal_id:y==="none"?null:y,contact_id:b==="none"?null:b,stage_id:a||null,priority:k,status:E,due_date:D?As(D,"yyyy-MM-dd"):null};r?(await l.mutateAsync({id:r.id,...K}),he.success("Task updated")):(await i.mutateAsync(K),he.success("Task created")),t(!1)}catch{he.error("Failed to save task")}};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"sm:max-w-[480px]",children:[e.jsx(Cs,{children:e.jsx(Ns,{children:r?"Edit Task":"New Task"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ue,{children:"Title *"}),e.jsx(Se,{value:h,onChange:K=>m(K.target.value),placeholder:"e.g., Send inspection report"})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Description"}),e.jsx(vr,{value:p,onChange:K=>x(K.target.value),placeholder:"Optional details...",rows:2})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ue,{children:"Priority"}),e.jsxs(Bs,{value:k,onValueChange:K=>T(K),children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"low",children:"🟢 Low"}),e.jsx(pt,{value:"medium",children:"🟡 Medium"}),e.jsx(pt,{value:"high",children:"🟠 High"}),e.jsx(pt,{value:"urgent",children:"🔴 Urgent"})]})]})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Status"}),e.jsxs(Bs,{value:E,onValueChange:K=>A(K),children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"todo",children:"To Do"}),e.jsx(pt,{value:"in_progress",children:"In Progress"}),e.jsx(pt,{value:"done",children:"Done"})]})]})]})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Due Date"}),e.jsxs(gl,{children:[e.jsx(xl,{asChild:!0,children:e.jsxs(H,{variant:"outline",className:Ft("w-full justify-start text-left font-normal",!D&&"text-muted-foreground"),children:[e.jsx(Nn,{className:"mr-2 h-4 w-4"}),D?As(D,"PPP"):"Pick a date"]})}),e.jsx(il,{className:"w-auto p-0",align:"start",children:e.jsx(g0,{mode:"single",selected:D,onSelect:R,initialFocus:!0,className:"p-3 pointer-events-auto"})})]})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Link to Deal"}),e.jsxs(gl,{open:z,onOpenChange:O,children:[e.jsx(xl,{asChild:!0,children:e.jsxs(H,{variant:"outline",role:"combobox",className:"w-full justify-between font-normal",children:[e.jsxs("span",{className:"flex items-center gap-2 truncate",children:[e.jsx(Xa,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),y!=="none"?((J=o==null?void 0:o.find(K=>K.id===y))==null?void 0:J.deal_name)||"Select deal":"No Deal"]}),e.jsx(d0,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(il,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(k0,{children:[e.jsx(S0,{placeholder:"Search deals..."}),e.jsxs(C0,{children:[e.jsx(T0,{children:"No deals found."}),e.jsxs(E0,{children:[e.jsxs(fg,{value:"no-deal",onSelect:()=>{_("none"),O(!1)},children:[e.jsx(va,{className:Ft("mr-2 h-4 w-4",y==="none"?"opacity-100":"opacity-0")}),"No Deal"]}),o==null?void 0:o.map(K=>e.jsxs(fg,{value:K.deal_name,onSelect:()=>{_(K.id),O(!1)},children:[e.jsx(va,{className:Ft("mr-2 h-4 w-4",y===K.id?"opacity-100":"opacity-0")}),K.deal_name]},K.id))]})]})]})})]})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Link to Contact"}),e.jsxs(gl,{open:$,onOpenChange:ee,children:[e.jsx(xl,{asChild:!0,children:e.jsxs(H,{variant:"outline",role:"combobox",className:"w-full justify-between font-normal",children:[e.jsxs("span",{className:"flex items-center gap-2 truncate",children:[e.jsx(io,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),b!=="none"?(()=>{const K=d==null?void 0:d.find(re=>re.id===b);return K?`${K.first_name} ${K.last_name}`:"Select contact"})():"No Contact"]}),e.jsx(d0,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(il,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(k0,{children:[e.jsx(S0,{placeholder:"Search contacts..."}),e.jsxs(C0,{children:[e.jsx(T0,{children:"No contacts found."}),e.jsxs(E0,{children:[e.jsxs(fg,{value:"no-contact",onSelect:()=>{j("none"),ee(!1)},children:[e.jsx(va,{className:Ft("mr-2 h-4 w-4",b==="none"?"opacity-100":"opacity-0")}),"No Contact"]}),d==null?void 0:d.map(K=>e.jsxs(fg,{value:`${K.first_name} ${K.last_name}`,onSelect:()=>{j(K.id),ee(!1)},children:[e.jsx(va,{className:Ft("mr-2 h-4 w-4",b===K.id?"opacity-100":"opacity-0")}),K.first_name," ",K.last_name]},K.id))]})]})]})})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(H,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(H,{onClick:Z,disabled:i.isPending||l.isPending,children:r?"Save Changes":"Create Task"})]})]})]})})}const B7s={urgent:{label:"Urgent",color:"bg-red-500/10 text-red-600 border-red-200",dot:"🔴"},high:{label:"High",color:"bg-orange-500/10 text-orange-600 border-orange-200",dot:"🟠"},medium:{label:"Medium",color:"bg-amber-500/10 text-amber-600 border-amber-200",dot:"🟡"},low:{label:"Low",color:"bg-emerald-500/10 text-emerald-600 border-emerald-200",dot:"🟢"}};function z7s({tasks:s}){const t=f6e(),r=N7s(),n=Fr(),[a,i]=S.useState(null),l=async h=>{const m=h.status==="done"?"todo":"done";try{await t.mutateAsync({id:h.id,status:m})}catch{he.error("Failed to update task")}},o=async h=>{try{await r.mutateAsync(h),he.success("Task deleted")}catch{he.error("Failed to delete task")}};if(s.length===0)return e.jsxs("div",{className:"flex flex-col items-center justify-center py-20 text-center",children:[e.jsx(ea,{className:"h-12 w-12 text-muted-foreground/30 mb-3"}),e.jsx("p",{className:"text-muted-foreground font-medium",children:"No tasks found"}),e.jsx("p",{className:"text-muted-foreground/60 text-sm",children:"Create a new task to get started"})]});const c=new Map,d=[];return s.forEach(h=>{if(h.deal){const m=c.get(h.deal.id)||{dealName:h.deal.deal_name,tasks:[]};m.tasks.push(h),c.set(h.deal.id,m)}else d.push(h)}),e.jsxs("div",{className:"space-y-4",children:[d.length>0&&e.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[e.jsx("div",{className:"bg-muted/30 px-4 py-2 border-b",children:e.jsx("h3",{className:"font-medium text-sm text-muted-foreground",children:"General Tasks"})}),d.map(h=>e.jsx(gWe,{task:h,onToggle:l,onDelete:o,onEdit:i,onNavigateDeal:m=>n(`/mission-control/pipeline?deal=${m}`)},h.id))]}),Array.from(c.entries()).map(([h,m])=>e.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[e.jsxs("button",{onClick:()=>n(`/mission-control/pipeline?deal=${h}`),className:"w-full bg-muted/30 px-4 py-2 border-b flex items-center gap-2 hover:bg-muted/50 transition-colors text-left",children:[e.jsx(Xa,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("h3",{className:"font-medium text-sm",children:m.dealName}),e.jsxs(Xe,{variant:"secondary",className:"ml-auto text-xs",children:[m.tasks.filter(p=>p.status==="done").length,"/",m.tasks.length]}),e.jsx($a,{className:"h-3.5 w-3.5 text-muted-foreground"})]}),m.tasks.map(p=>e.jsx(gWe,{task:p,onToggle:l,onDelete:o,onEdit:i,onNavigateDeal:x=>n(`/mission-control/pipeline?deal=${x}`)},p.id))]},h)),a&&e.jsx(Ayt,{open:!!a,onOpenChange:()=>i(null),editTask:a})]})}function gWe({task:s,onToggle:t,onDelete:r,onEdit:n,onNavigateDeal:a}){const i=s.status==="done",l=!i&&s.due_date&&__(dg(s.due_date))&&!cm(dg(s.due_date)),o=!i&&s.due_date&&cm(dg(s.due_date)),c=B7s[s.priority];return e.jsxs("div",{className:Ft("flex items-center gap-3 px-4 py-3 border-b last:border-b-0 group hover:bg-muted/30 transition-colors",i&&"opacity-60"),children:[e.jsx("button",{onClick:()=>t(s),className:"shrink-0",children:i?e.jsx(ea,{className:"h-5 w-5 text-emerald-500"}):e.jsx(Gu,{className:"h-5 w-5 text-muted-foreground hover:text-primary transition-colors"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:Ft("text-sm font-medium truncate",i&&"line-through text-muted-foreground"),children:s.title}),e.jsxs("div",{className:"flex items-center gap-2 mt-0.5 flex-wrap",children:[s.stage&&e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full font-medium",style:{backgroundColor:s.stage.color+"20",color:s.stage.color},children:s.stage.name}),s.contact&&e.jsxs("span",{className:"text-[10px] text-muted-foreground flex items-center gap-0.5",children:[e.jsx(io,{className:"h-2.5 w-2.5"}),s.contact.first_name," ",s.contact.last_name]})]})]}),e.jsxs(Xe,{variant:"outline",className:Ft("text-[10px] shrink-0",c.color),children:[c.dot," ",c.label]}),s.due_date&&e.jsxs("span",{className:Ft("text-xs shrink-0 flex items-center gap-1",l&&"text-destructive font-medium",o&&"text-amber-600 font-medium",!l&&!o&&"text-muted-foreground"),children:[e.jsx(Pn,{className:"h-3 w-3"}),As(dg(s.due_date),"MMM d")]}),e.jsxs("div",{className:"flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity",children:[e.jsx("button",{onClick:()=>n(s),className:"p-1 hover:bg-muted rounded",children:e.jsx(ou,{className:"h-3.5 w-3.5 text-muted-foreground"})}),e.jsx("button",{onClick:()=>r(s.id),className:"p-1 hover:bg-destructive/10 rounded",children:e.jsx(Dr,{className:"h-3.5 w-3.5 text-destructive"})})]})]})}const $7s=[{status:"todo",label:"To Do",icon:Gu,color:"border-t-slate-400"},{status:"in_progress",label:"In Progress",icon:cg,color:"border-t-blue-500"},{status:"done",label:"Done",icon:ea,color:"border-t-emerald-500"}],U7s={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function q7s({tasks:s}){const t=f6e(),r=S.useMemo(()=>{const i={todo:[],in_progress:[],done:[]};return s.forEach(l=>i[l.status].push(l)),i},[s]),n=(i,l)=>{i.dataTransfer.setData("taskId",l)},a=async(i,l)=>{i.preventDefault();const o=i.dataTransfer.getData("taskId");if(!o)return;const c=s.find(d=>d.id===o);if(!(!c||c.status===l))try{await t.mutateAsync({id:o,status:l})}catch{he.error("Failed to move task")}};return e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:$7s.map(i=>e.jsxs("div",{className:Ft("border rounded-lg border-t-4 bg-muted/20",i.color),onDragOver:l=>l.preventDefault(),onDrop:l=>a(l,i.status),children:[e.jsxs("div",{className:"px-4 py-3 flex items-center gap-2",children:[e.jsx(i.icon,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("h3",{className:"font-semibold text-sm",children:i.label}),e.jsx(Xe,{variant:"secondary",className:"ml-auto text-xs",children:r[i.status].length})]}),e.jsxs("div",{className:"p-2 space-y-2 min-h-[200px]",children:[r[i.status].map(l=>e.jsx(V7s,{task:l,onDragStart:n},l.id)),r[i.status].length===0&&e.jsx("p",{className:"text-xs text-muted-foreground text-center py-8",children:"Drag tasks here"})]})]},i.status))})}function V7s({task:s,onDragStart:t}){const r=s.status==="done",n=!r&&s.due_date&&__(dg(s.due_date))&&!cm(dg(s.due_date)),a=!r&&s.due_date&&cm(dg(s.due_date));return e.jsx("div",{draggable:!0,onDragStart:i=>t(i,s.id),className:Ft("bg-background border rounded-lg p-3 cursor-grab active:cursor-grabbing shadow-sm hover:shadow-md transition-shadow",n&&"border-destructive/50"),children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"text-xs mt-0.5",children:U7s[s.priority]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:Ft("text-sm font-medium",r&&"line-through text-muted-foreground"),children:s.title}),e.jsxs("div",{className:"flex items-center gap-2 mt-1.5 flex-wrap",children:[s.deal&&e.jsxs("span",{className:"text-[10px] text-muted-foreground flex items-center gap-0.5",children:[e.jsx(Xa,{className:"h-2.5 w-2.5"}),s.deal.deal_name]}),s.contact&&e.jsxs("span",{className:"text-[10px] text-muted-foreground flex items-center gap-0.5",children:[e.jsx(io,{className:"h-2.5 w-2.5"}),s.contact.first_name," ",s.contact.last_name]})]}),s.due_date&&e.jsxs("div",{className:Ft("text-[10px] mt-1.5 flex items-center gap-1",n&&"text-destructive font-medium",a&&"text-amber-600 font-medium",!n&&!a&&"text-muted-foreground"),children:[e.jsx(Pn,{className:"h-2.5 w-2.5"}),n?"Overdue — ":a?"Due today — ":"",As(dg(s.due_date),"MMM d")]}),s.stage&&e.jsx("span",{className:"inline-block text-[10px] px-1.5 py-0.5 rounded-full font-medium mt-1.5",style:{backgroundColor:s.stage.color+"20",color:s.stage.color},children:s.stage.name})]})]})})}const xWe={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function H7s({tasks:s}){const[t,r]=S.useState(new Date),n=f6e(),a=Gd(t),i=Ny(t),l=Np(a),o=Sge(i),c=v8t({start:l,end:o}),d=S.useMemo(()=>{const p=new Map;return s.forEach(x=>{if(!x.due_date)return;const y=x.due_date,_=p.get(y)||[];_.push(x),p.set(y,_)}),p},[s]),h=S.useMemo(()=>s.filter(p=>!p.due_date),[s]),m=async p=>{const x=p.status==="done"?"todo":"done";try{await n.mutateAsync({id:p.id,status:x})}catch{he.error("Failed to update task")}};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(H,{variant:"ghost",size:"icon",onClick:()=>r(RT(t,1)),children:e.jsx(fl,{className:"h-4 w-4"})}),e.jsx("h3",{className:"font-semibold",children:As(t,"MMMM yyyy")}),e.jsx(H,{variant:"ghost",size:"icon",onClick:()=>r(wg(t,1)),children:e.jsx($a,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"grid grid-cols-7 text-center",children:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"].map(p=>e.jsx("div",{className:"text-xs font-medium text-muted-foreground py-2",children:p},p))}),e.jsx("div",{className:"grid grid-cols-7 border-l border-t",children:c.map(p=>{const x=As(p,"yyyy-MM-dd"),y=d.get(x)||[],_=Tge(p,t),b=cm(p);return e.jsxs("div",{className:Ft("border-r border-b min-h-[100px] p-1",!_&&"bg-muted/30",b&&"bg-primary/5"),children:[e.jsx("div",{className:Ft("text-xs font-medium mb-1 text-right px-1",!_&&"text-muted-foreground/40",b&&"text-primary font-bold"),children:As(p,"d")}),e.jsxs("div",{className:"space-y-0.5",children:[y.slice(0,3).map(j=>e.jsxs("button",{onClick:()=>m(j),className:Ft("w-full text-left text-[10px] px-1 py-0.5 rounded truncate flex items-center gap-0.5 hover:bg-muted transition-colors",j.status==="done"?"text-muted-foreground line-through":"text-foreground"),children:[j.status==="done"?e.jsx(ea,{className:"h-2.5 w-2.5 text-emerald-500 shrink-0"}):e.jsx(Gu,{className:"h-2.5 w-2.5 shrink-0"}),e.jsxs("span",{className:"truncate",children:[xWe[j.priority]," ",j.title]})]},j.id)),y.length>3&&e.jsxs("p",{className:"text-[9px] text-muted-foreground text-center",children:["+",y.length-3," more"]})]})]},x)})}),h.length>0&&e.jsxs("div",{className:"border rounded-lg p-3",children:[e.jsxs("h4",{className:"text-sm font-medium text-muted-foreground mb-2",children:["No Due Date (",h.length,")"]}),e.jsx("div",{className:"space-y-1",children:h.map(p=>e.jsxs("button",{onClick:()=>m(p),className:Ft("w-full text-left text-xs px-2 py-1.5 rounded flex items-center gap-2 hover:bg-muted transition-colors",p.status==="done"&&"opacity-50 line-through"),children:[p.status==="done"?e.jsx(ea,{className:"h-3.5 w-3.5 text-emerald-500 shrink-0"}):e.jsx(Gu,{className:"h-3.5 w-3.5 shrink-0"}),e.jsxs("span",{className:"truncate",children:[xWe[p.priority]," ",p.title]}),p.deal&&e.jsxs("span",{className:"text-muted-foreground ml-auto shrink-0",children:["• ",p.deal.deal_name]})]},p.id))})]})]})}const G7s={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function W7s({open:s,onOpenChange:t,stages:r}){var j;const[n,a]=S.useState(((j=r[0])==null?void 0:j.id)||""),{data:i,isLoading:l}=S7s(n||void 0),o=C7s(),c=T7s(),[d,h]=S.useState(""),[m,p]=S.useState("medium"),[x,y]=S.useState(""),_=async()=>{if(!(!d.trim()||!n))try{await o.mutateAsync({stage_id:n,title:d.trim(),priority:m,default_due_offset_days:x?parseInt(x):null,sort_order:((i==null?void 0:i.length)||0)+1}),h(""),y(""),he.success("Template added")}catch{he.error("Failed to add template")}},b=async k=>{try{await c.mutateAsync(k),he.success("Template deleted")}catch{he.error("Failed to delete template")}};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"sm:max-w-[560px]",children:[e.jsx(Cs,{children:e.jsxs(Ns,{className:"flex items-center gap-2",children:[e.jsx(lF,{className:"h-5 w-5"}),"Task Templates by Stage"]})}),e.jsx("p",{className:"text-sm text-muted-foreground -mt-2",children:"Create default tasks that auto-populate when a deal enters a stage."}),e.jsxs("div",{children:[e.jsx(ue,{children:"Pipeline Stage"}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:r.filter(k=>!k.is_won_stage&&!k.is_lost_stage).map(k=>e.jsx("button",{onClick:()=>a(k.id),className:Ft("px-3 py-1.5 rounded-full text-xs font-medium border transition-colors",n===k.id?"border-primary bg-primary/10 text-primary":"border-border hover:bg-muted"),children:k.name},k.id))})]}),e.jsx(Ci,{className:"max-h-[250px]",children:e.jsxs("div",{className:"space-y-1.5",children:[i==null?void 0:i.map((k,T)=>e.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 border rounded-lg group",children:[e.jsx("span",{className:"text-xs",children:G7s[k.priority]}),e.jsx("span",{className:"text-sm flex-1 truncate",children:k.title}),k.default_due_offset_days&&e.jsxs(Xe,{variant:"outline",className:"text-[10px]",children:["+",k.default_due_offset_days,"d"]}),e.jsx("button",{onClick:()=>b(k.id),className:"opacity-0 group-hover:opacity-100 p-1 hover:bg-destructive/10 rounded transition-opacity",children:e.jsx(Dr,{className:"h-3.5 w-3.5 text-destructive"})})]},k.id)),(i==null?void 0:i.length)===0&&n&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"No templates for this stage yet"})]})}),n&&e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[e.jsx(ue,{className:"text-xs text-muted-foreground",children:"Add Template Task"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Se,{placeholder:"Task title...",value:d,onChange:k=>h(k.target.value),className:"flex-1",onKeyDown:k=>k.key==="Enter"&&_()}),e.jsxs(Bs,{value:m,onValueChange:k=>p(k),children:[e.jsx(Os,{className:"w-[100px]",children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"low",children:"🟢 Low"}),e.jsx(pt,{value:"medium",children:"🟡 Med"}),e.jsx(pt,{value:"high",children:"🟠 High"}),e.jsx(pt,{value:"urgent",children:"🔴 Urgent"})]})]})]}),e.jsxs("div",{className:"flex gap-2 items-end",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx(ue,{className:"text-xs",children:"Due offset (days from entering stage)"}),e.jsx(Se,{type:"number",placeholder:"e.g., 7",value:x,onChange:k=>y(k.target.value)})]}),e.jsxs(H,{onClick:_,disabled:!d.trim()||o.isPending,children:[e.jsx(Ys,{className:"h-4 w-4 mr-1"}),"Add"]})]})]})]})})}function K7s(){const{data:s,isLoading:t}=b7s(),{data:r}=F0e(),[n,a]=S.useState("list"),[i,l]=S.useState(""),[o,c]=S.useState("active"),[d,h]=S.useState("all"),[m,p]=S.useState("all"),[x,y]=S.useState(!1),[_,b]=S.useState(!1),j=S.useMemo(()=>{if(!s)return[];const E=new Map;return s.forEach(A=>{A.deal&&E.set(A.deal.id,A.deal.deal_name)}),Array.from(E,([A,D])=>({id:A,name:D}))},[s]),k=S.useMemo(()=>s?s.filter(E=>{var $,ee,Z,J;const A=i.toLowerCase(),D=!A||E.title.toLowerCase().includes(A)||((ee=($=E.deal)==null?void 0:$.deal_name)==null?void 0:ee.toLowerCase().includes(A))||`${((Z=E.contact)==null?void 0:Z.first_name)||""} ${((J=E.contact)==null?void 0:J.last_name)||""}`.toLowerCase().includes(A),R=o==="all"||o==="active"&&E.status!=="done"||o==="todo"&&E.status==="todo"||o==="in_progress"&&E.status==="in_progress"||o==="done"&&E.status==="done"||o==="overdue"&&E.status!=="done"&&E.due_date&&__(dg(E.due_date))&&!cm(dg(E.due_date)),z=d==="all"||E.priority===d,O=m==="all"||m==="no_deal"&&!E.deal_id||E.deal_id===m;return D&&R&&z&&O}):[],[s,i,o,d,m]),T=S.useMemo(()=>{if(!s)return{total:0,overdue:0,dueToday:0,dueThisWeek:0,completed:0};const E=s.filter(A=>A.status!=="done");return{total:E.length,overdue:E.filter(A=>A.due_date&&__(dg(A.due_date))&&!cm(dg(A.due_date))).length,dueToday:E.filter(A=>A.due_date&&cm(dg(A.due_date))).length,dueThisWeek:E.filter(A=>A.due_date&&pRt(dg(A.due_date))).length,completed:s.filter(A=>A.status==="done").length}},[s]);return e.jsx(Ss,{children:e.jsxs("div",{className:"space-y-6 p-4 md:p-6 max-w-[1600px] mx-auto",children:[e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold tracking-tight",children:"Tasks"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Manage tasks across deals and contacts"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(H,{variant:"outline",size:"sm",onClick:()=>b(!0),children:[e.jsx(v1,{className:"h-4 w-4 mr-1"}),"Templates"]}),e.jsxs(H,{size:"sm",onClick:()=>y(!0),children:[e.jsx(Ys,{className:"h-4 w-4 mr-1"}),"New Task"]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3",children:[e.jsxs("button",{onClick:()=>c("active"),className:`p-3 rounded-lg border text-left transition-colors ${o==="active"?"border-primary bg-primary/5":"hover:bg-muted/50"}`,children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-xs font-medium",children:[e.jsx(Vf,{className:"h-3.5 w-3.5"}),"Active"]}),e.jsx("p",{className:"text-xl font-bold mt-1",children:T.total})]}),e.jsxs("button",{onClick:()=>c("overdue"),className:`p-3 rounded-lg border text-left transition-colors ${o==="overdue"?"border-destructive bg-destructive/5":"hover:bg-muted/50"}`,children:[e.jsxs("div",{className:"flex items-center gap-2 text-destructive text-xs font-medium",children:[e.jsx(uu,{className:"h-3.5 w-3.5"}),"Overdue"]}),e.jsx("p",{className:"text-xl font-bold mt-1 text-destructive",children:T.overdue})]}),e.jsxs("button",{onClick:()=>{c("active")},className:"p-3 rounded-lg border text-left hover:bg-muted/50 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2 text-amber-600 text-xs font-medium",children:[e.jsx(Pn,{className:"h-3.5 w-3.5"}),"Due Today"]}),e.jsx("p",{className:"text-xl font-bold mt-1",children:T.dueToday})]}),e.jsxs("button",{onClick:()=>{c("active")},className:"p-3 rounded-lg border text-left hover:bg-muted/50 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2 text-blue-600 text-xs font-medium",children:[e.jsx(xu,{className:"h-3.5 w-3.5"}),"This Week"]}),e.jsx("p",{className:"text-xl font-bold mt-1",children:T.dueThisWeek})]}),e.jsxs("button",{onClick:()=>c("done"),className:`p-3 rounded-lg border text-left transition-colors ${o==="done"?"border-emerald-500 bg-emerald-500/5":"hover:bg-muted/50"}`,children:[e.jsxs("div",{className:"flex items-center gap-2 text-emerald-600 text-xs font-medium",children:[e.jsx(ea,{className:"h-3.5 w-3.5"}),"Completed"]}),e.jsx("p",{className:"text-xl font-bold mt-1",children:T.completed})]})]}),e.jsxs("div",{className:"flex flex-col md:flex-row gap-3 items-start md:items-center",children:[e.jsxs("div",{className:"relative flex-1 max-w-sm",children:[e.jsx(Mn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Se,{placeholder:"Search tasks...",value:i,onChange:E=>l(E.target.value),className:"pl-9"})]}),e.jsxs(Bs,{value:d,onValueChange:h,children:[e.jsx(Os,{className:"w-[130px]",children:e.jsx(Us,{placeholder:"Priority"})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"all",children:"All Priorities"}),e.jsx(pt,{value:"urgent",children:"🔴 Urgent"}),e.jsx(pt,{value:"high",children:"🟠 High"}),e.jsx(pt,{value:"medium",children:"🟡 Medium"}),e.jsx(pt,{value:"low",children:"🟢 Low"})]})]}),e.jsxs(Bs,{value:m,onValueChange:p,children:[e.jsx(Os,{className:"w-[160px]",children:e.jsx(Us,{placeholder:"Deal"})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"all",children:"All Deals"}),e.jsx(pt,{value:"no_deal",children:"No Deal"}),j.map(E=>e.jsx(pt,{value:E.id,children:E.name},E.id))]})]}),e.jsxs("div",{className:"flex items-center border rounded-lg p-0.5 ml-auto",children:[e.jsx("button",{onClick:()=>a("list"),className:`p-1.5 rounded-md transition-colors ${n==="list"?"bg-primary text-primary-foreground":"text-muted-foreground hover:text-foreground"}`,children:e.jsx(Vf,{className:"h-4 w-4"})}),e.jsx("button",{onClick:()=>a("kanban"),className:`p-1.5 rounded-md transition-colors ${n==="kanban"?"bg-primary text-primary-foreground":"text-muted-foreground hover:text-foreground"}`,children:e.jsx(p_,{className:"h-4 w-4"})}),e.jsx("button",{onClick:()=>a("calendar"),className:`p-1.5 rounded-md transition-colors ${n==="calendar"?"bg-primary text-primary-foreground":"text-muted-foreground hover:text-foreground"}`,children:e.jsx(xu,{className:"h-4 w-4"})})]})]}),t?e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx("div",{className:"animate-spin h-8 w-8 border-2 border-primary border-t-transparent rounded-full"})}):e.jsxs(e.Fragment,{children:[n==="list"&&e.jsx(z7s,{tasks:k}),n==="kanban"&&e.jsx(q7s,{tasks:k}),n==="calendar"&&e.jsx(H7s,{tasks:k})]}),e.jsx(Ayt,{open:x,onOpenChange:y}),e.jsx(W7s,{open:_,onOpenChange:b,stages:r||[]})]})})}function Myt(){const s=ba();return yt({queryKey:["portal-referrals",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await V.from("portal_referrals").select("*, client_portals!inner(slug, client_name, deal_id)").eq("owner_user_id",s).order("created_at",{ascending:!1});if(r)throw r;return t||[]},enabled:!!s})}function Y7s(){const s=ns();return Pt({mutationFn:async({id:t,...r})=>{const{data:n,error:a}=await V.from("portal_referrals").update(r).eq("id",t).select().single();if(a)throw a;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["portal-referrals"]})}})}function Z7s(){const s=ns();return Pt({mutationFn:async t=>{const{error:r}=await V.from("portal_referrals").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["portal-referrals"]})}})}const X7s=s=>new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric"}).format(new Date(s)),Nwe=[{value:"new",label:"New",className:"bg-blue-500/10 text-blue-700 border-blue-200"},{value:"contacted",label:"Contacted",className:"bg-amber-500/10 text-amber-700 border-amber-200"},{value:"converted",label:"Converted 🎉",className:"bg-emerald-500/10 text-emerald-700 border-emerald-200"},{value:"lost",label:"Lost",className:"bg-slate-500/10 text-slate-700 border-slate-200"}],Q7s={buying:"Buying",selling:"Selling",both:"Buying & Selling",unsure:"Not sure yet"};function Iyt(){const{data:s=[],isLoading:t}=Myt(),r=Y7s(),n=Z7s(),[a,i]=S.useState("all"),[l,o]=S.useState({}),c=S.useMemo(()=>a==="all"?s:s.filter(x=>x.status===a),[s,a]),d=S.useMemo(()=>({total:s.length,new:s.filter(x=>x.status==="new").length,converted:s.filter(x=>x.status==="converted").length}),[s]),h=(x,y)=>{r.mutate({id:x.id,status:y}),he.success("Status updated")},m=x=>{const y=l[x.id];r.mutate({id:x.id,agent_notes:y}),o(_=>{const{[x.id]:b,...j}=_;return j}),he.success("Notes saved")},p=x=>{confirm(`Delete referral for ${x.friend_name}?`)&&n.mutate(x.id)};return e.jsxs("div",{className:"container max-w-5xl py-6 px-4",children:[e.jsx(el,{children:e.jsx("title",{children:"Client Portal Referrals"})}),e.jsxs("div",{className:"flex items-start justify-between mb-6 flex-wrap gap-3",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-2xl font-bold flex items-center gap-2",children:[e.jsx(Di,{className:"h-6 w-6 text-primary"}),"Portal Referrals"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Referrals sent in by happy clients via their post-close portal."})]}),e.jsxs("div",{className:"flex gap-3",children:[e.jsxs("div",{className:"bg-card border rounded-lg px-4 py-2 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:d.total}),e.jsx("div",{className:"text-[10px] uppercase tracking-wide text-muted-foreground",children:"Total"})]}),e.jsxs("div",{className:"bg-card border rounded-lg px-4 py-2 text-center",children:[e.jsx("div",{className:"text-2xl font-bold text-blue-600",children:d.new}),e.jsx("div",{className:"text-[10px] uppercase tracking-wide text-muted-foreground",children:"New"})]}),e.jsxs("div",{className:"bg-card border rounded-lg px-4 py-2 text-center",children:[e.jsx("div",{className:"text-2xl font-bold text-emerald-600",children:d.converted}),e.jsx("div",{className:"text-[10px] uppercase tracking-wide text-muted-foreground",children:"Closed"})]})]})]}),e.jsx("div",{className:"flex flex-wrap gap-2 mb-4",children:[{v:"all",l:"All"},...Nwe.map(x=>({v:x.value,l:x.label}))].map(x=>e.jsx("button",{onClick:()=>i(x.v),className:`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors ${a===x.v?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:border-primary/50"}`,children:x.l},x.v))}),t?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(is,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):c.length===0?e.jsx(ke,{children:e.jsxs(Oe,{className:"py-12 text-center",children:[e.jsx(Di,{className:"h-10 w-10 text-muted-foreground/40 mx-auto mb-3"}),e.jsx("p",{className:"text-sm font-medium",children:"No referrals yet"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Once your closed clients refer friends from their portal, they'll show up here."})]})}):e.jsx("div",{className:"space-y-3",children:c.map(x=>{var j,k;const y=Nwe.find(T=>T.value===x.status),_=(j=x.client_portals)==null?void 0:j.slug,b=x.referrer_name||((k=x.client_portals)==null?void 0:k.client_name)||"Anonymous client";return e.jsxs(ke,{children:[e.jsx(Ot,{className:"pb-3",children:e.jsxs("div",{className:"flex items-start justify-between flex-wrap gap-2",children:[e.jsxs("div",{children:[e.jsx(zt,{className:"text-lg",children:x.friend_name}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1 flex items-center gap-1.5",children:[e.jsx(Nn,{className:"h-3 w-3"}),"Referred by ",e.jsx("span",{className:"font-medium text-foreground",children:b})," ·"," ",X7s(x.created_at)]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Xe,{variant:"outline",className:y==null?void 0:y.className,children:(y==null?void 0:y.label)||x.status}),e.jsxs(Bs,{value:x.status,onValueChange:T=>h(x,T),children:[e.jsx(Os,{className:"h-8 w-[130px] text-xs",children:e.jsx(Us,{})}),e.jsx(Fs,{children:Nwe.map(T=>e.jsx(pt,{value:T.value,className:"text-xs",children:T.label},T.value))})]})]})]})}),e.jsxs(Oe,{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[x.friend_interest&&e.jsx(Xe,{variant:"secondary",className:"text-xs",children:Q7s[x.friend_interest]||x.friend_interest}),x.friend_email&&e.jsxs("a",{href:`mailto:${x.friend_email}`,className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[e.jsx(er,{className:"h-3 w-3"}),x.friend_email]}),x.friend_phone&&e.jsxs(e.Fragment,{children:[e.jsxs("a",{href:`tel:${x.friend_phone}`,className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[e.jsx(Yn,{className:"h-3 w-3"}),x.friend_phone]}),e.jsxs("a",{href:`sms:${x.friend_phone}`,className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[e.jsx(qc,{className:"h-3 w-3"}),"Text"]})]})]}),x.friend_message&&e.jsxs("div",{className:"bg-muted/50 rounded-md p-3 text-sm",children:[e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-muted-foreground mb-1",children:"Note from referrer"}),e.jsxs("p",{className:"italic text-foreground",children:['"',x.friend_message,'"']})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-muted-foreground mb-1",children:"Your notes"}),l[x.id]!==void 0?e.jsxs("div",{className:"space-y-2",children:[e.jsx(vr,{value:l[x.id],onChange:T=>o(E=>({...E,[x.id]:T.target.value})),rows:3,className:"text-sm"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(H,{size:"sm",onClick:()=>m(x),children:"Save"}),e.jsx(H,{size:"sm",variant:"ghost",onClick:()=>o(T=>{const{[x.id]:E,...A}=T;return A}),children:"Cancel"})]})]}):e.jsx("button",{onClick:()=>o(T=>({...T,[x.id]:x.agent_notes||""})),className:"text-sm text-left w-full p-2 rounded border border-dashed border-input hover:border-primary/50 hover:bg-muted/30 transition-colors",children:x.agent_notes||e.jsx("span",{className:"text-muted-foreground italic",children:"Click to add notes..."})})]}),e.jsxs("div",{className:"flex items-center justify-between border-t pt-3",children:[_&&e.jsxs("a",{href:`/portal/${_}`,target:"_blank",rel:"noopener noreferrer",className:"text-xs text-muted-foreground hover:text-primary inline-flex items-center gap-1",children:[e.jsx(gn,{className:"h-3 w-3"}),"View source portal"]}),e.jsx(H,{variant:"ghost",size:"sm",onClick:()=>p(x),className:"text-destructive hover:text-destructive ml-auto h-8",children:e.jsx(Dr,{className:"h-3.5 w-3.5"})})]})]})]},x.id)})})]})}function Pyt({vendor:s,onEdit:t,onDelete:r,onToggleVisible:n,isVisible:a,showOwnerBadge:i,clickCount:l}){var c;const o=((c=nz.find(d=>d.value===s.category))==null?void 0:c.label)||s.category;return e.jsxs(ke,{className:"p-4 flex flex-col gap-3",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-12 h-12 rounded-lg bg-muted flex items-center justify-center overflow-hidden shrink-0",children:s.logo_url?e.jsx("img",{src:s.logo_url,alt:s.name,className:"w-full h-full object-cover"}):e.jsx("span",{className:"text-lg font-semibold text-muted-foreground",children:s.name.charAt(0).toUpperCase()})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-1.5 flex-wrap",children:[e.jsx("h3",{className:"font-semibold truncate",children:s.name}),s.is_required&&e.jsx(Td,{className:"w-3.5 h-3.5 text-amber-600","aria-label":"Required"}),s.is_featured&&e.jsx(ya,{className:"w-3.5 h-3.5 text-amber-500 fill-amber-500","aria-label":"Featured"})]}),s.company&&e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:s.company}),e.jsxs("div",{className:"flex items-center gap-1 mt-1 flex-wrap",children:[e.jsx(Xe,{variant:"secondary",className:"text-[10px]",children:o}),i==="brokerage"&&e.jsx(Xe,{variant:"outline",className:"text-[10px]",children:"Brokerage"}),i==="agent"&&e.jsx(Xe,{variant:"outline",className:"text-[10px]",children:"Personal"}),!s.is_active&&e.jsx(Xe,{variant:"destructive",className:"text-[10px]",children:"Inactive"}),typeof l=="number"&&l>0&&e.jsxs(Xe,{variant:"outline",className:"text-[10px]",children:[l," clicks"]})]})]})]}),s.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2",children:s.description}),e.jsxs("div",{className:"text-xs text-muted-foreground space-y-1",children:[s.phone&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Yn,{className:"w-3 h-3"}),s.phone]}),s.email&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(er,{className:"w-3 h-3"}),e.jsx("span",{className:"truncate",children:s.email})]}),s.website&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(ld,{className:"w-3 h-3"}),e.jsx("span",{className:"truncate",children:s.website})]}),s.booking_url&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Nn,{className:"w-3 h-3"}),e.jsx("span",{className:"truncate",children:"Booking link"})]}),s.address&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Qa,{className:"w-3 h-3"}),e.jsx("span",{className:"truncate",children:s.address})]})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-2 border-t",children:[n&&e.jsxs(H,{size:"sm",variant:a?"default":"outline",onClick:()=>n(!a),disabled:s.is_required&&!a,className:"flex-1",children:[a?e.jsx(Bn,{className:"w-3.5 h-3.5 mr-1.5"}):e.jsx($f,{className:"w-3.5 h-3.5 mr-1.5"}),a?"Showing in portals":"Hidden"]}),t&&e.jsx(H,{size:"sm",variant:"ghost",onClick:t,children:e.jsx(ou,{className:"w-3.5 h-3.5"})}),r&&e.jsx(H,{size:"sm",variant:"ghost",onClick:r,className:"text-destructive",children:e.jsx(Dr,{className:"w-3.5 h-3.5"})})]})]})}function Lyt({open:s,onOpenChange:t,vendor:r,ownerType:n,brokerageId:a,agentUserId:i,showBrokerageOnlyFields:l}){const o=Gzt(),[c,d]=S.useState({}),[h,m]=S.useState(!1),p=S.useRef(null),x=async b=>{if(!b.type.startsWith("image/")){he.error("Please select an image");return}if(b.size>5*1024*1024){he.error("Image must be under 5MB");return}m(!0);try{const j=b.name.split(".").pop()||"png",k=`${n}/${a||i||"misc"}/${Date.now()}.${j}`,{error:T}=await V.storage.from("vendor-logos").upload(k,b,{upsert:!0,contentType:b.type});if(T)throw T;const{data:E}=V.storage.from("vendor-logos").getPublicUrl(k);d(A=>({...A,logo_url:E.publicUrl})),he.success("Logo uploaded")}catch(j){he.error(j.message||"Upload failed")}finally{m(!1)}};S.useEffect(()=>{s&&d(r||{owner_type:n,owner_brokerage_id:n==="brokerage"&&a||null,owner_user_id:n==="agent"&&i||null,category:"other",action_type:"call",is_active:!0,is_featured:!1,is_required:!1})},[s,r,n,a,i]);const y=(b,j)=>d(k=>({...k,[b]:j})),_=async()=>{var b;if(!((b=c.name)!=null&&b.trim())){he.error("Name is required");return}try{await o.mutateAsync(c),he.success(r?"Vendor updated":"Vendor added"),t(!1)}catch(j){he.error(j.message||"Failed to save vendor")}};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Cs,{children:e.jsx(Ns,{children:r?"Edit Vendor":"Add Vendor"})}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(ue,{children:"Contact Name *"}),e.jsx(Se,{value:c.name||"",onChange:b=>y("name",b.target.value),placeholder:"Bob Smith"})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Company"}),e.jsx(Se,{value:c.company||"",onChange:b=>y("company",b.target.value),placeholder:"Smith Inspections"})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Category"}),e.jsxs(Bs,{value:c.category,onValueChange:b=>y("category",b),children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsx(Fs,{children:nz.map(b=>e.jsx(pt,{value:b.value,children:b.label},b.value))})]})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Phone"}),e.jsx(Se,{value:c.phone||"",onChange:b=>y("phone",b.target.value),placeholder:"(555) 123-4567"})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Email"}),e.jsx(Se,{type:"email",value:c.email||"",onChange:b=>y("email",b.target.value),placeholder:"bob@smithinsp.com"})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Website"}),e.jsx(Se,{value:c.website||"",onChange:b=>y("website",b.target.value),placeholder:"https://..."})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Logo"}),e.jsx("input",{ref:p,type:"file",accept:"image/*",className:"hidden",onChange:b=>{var k;const j=(k=b.target.files)==null?void 0:k[0];j&&x(j),b.target.value=""}}),e.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[c.logo_url?e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:c.logo_url,alt:"Vendor logo",className:"h-14 w-14 rounded-md object-cover border"}),e.jsx("button",{type:"button",onClick:()=>y("logo_url",""),className:"absolute -top-2 -right-2 bg-background border rounded-full p-0.5 shadow","aria-label":"Remove logo",children:e.jsx(Rr,{className:"h-3 w-3"})})]}):e.jsx("div",{className:"h-14 w-14 rounded-md border border-dashed flex items-center justify-center text-muted-foreground",children:e.jsx(Ea,{className:"h-5 w-5"})}),e.jsxs(H,{type:"button",variant:"outline",size:"sm",onClick:()=>{var b;return(b=p.current)==null?void 0:b.click()},disabled:h,children:[h?e.jsx(is,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Ea,{className:"h-4 w-4 mr-2"}),c.logo_url?"Replace":"Upload Logo"]})]})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(ue,{children:"Address"}),e.jsx(Se,{value:c.address||"",onChange:b=>y("address",b.target.value)})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(ue,{children:"Description"}),e.jsx(vr,{rows:3,value:c.description||"",onChange:b=>y("description",b.target.value),placeholder:"Why your clients should use this vendor..."})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Primary Action"}),e.jsxs(Bs,{value:c.action_type,onValueChange:b=>y("action_type",b),children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsx(Fs,{children:qzt.map(b=>e.jsx(pt,{value:b.value,children:b.label},b.value))})]})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Booking URL (Calendly etc.)"}),e.jsx(Se,{value:c.booking_url||"",onChange:b=>y("booking_url",b.target.value),placeholder:"https://calendly.com/..."})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(ue,{children:"Compliance Disclosure (optional)"}),e.jsx(vr,{rows:2,value:c.disclosure_text||"",onChange:b=>y("disclosure_text",b.target.value),placeholder:"e.g. Agent receives no compensation for this referral."})]}),e.jsxs("div",{className:"flex items-center justify-between md:col-span-2 border rounded-lg p-3",children:[e.jsxs("div",{children:[e.jsx(ue,{className:"font-medium",children:"Active"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Show this vendor in client portals"})]}),e.jsx(Or,{checked:!!c.is_active,onCheckedChange:b=>y("is_active",b)})]}),l&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between border rounded-lg p-3",children:[e.jsxs("div",{children:[e.jsx(ue,{className:"font-medium",children:"Featured"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Highlight in agent library"})]}),e.jsx(Or,{checked:!!c.is_featured,onCheckedChange:b=>y("is_featured",b)})]}),e.jsxs("div",{className:"flex items-center justify-between border rounded-lg p-3",children:[e.jsxs("div",{children:[e.jsx(ue,{className:"font-medium",children:"Required"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Agents cannot hide"})]}),e.jsx(Or,{checked:!!c.is_required,onCheckedChange:b=>y("is_required",b)})]})]})]}),e.jsxs(wn,{children:[e.jsx(H,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(H,{onClick:_,disabled:o.isPending,children:o.isPending?"Saving...":"Save Vendor"})]})]})})}function Dyt({embedded:s=!1}={}){const t=ba(),{brokerageId:r}=Ms(),{data:n,isLoading:a}=Hzt(),{data:i={}}=zat("agent",t),l=Bat(),o=Wzt(),[c,d]=S.useState(null),[h,m]=S.useState(!1),[p,x]=S.useState(""),[y,_]=S.useState("all"),b=(n==null?void 0:n.vendors)||[],j=(n==null?void 0:n.selections)||[],k=S.useMemo(()=>{const $=new Map;return j.forEach(ee=>$.set(ee.vendor_id,ee.is_visible)),$},[j]),T=S.useMemo(()=>b.filter($=>!(y!=="all"&&$.category!==y||p&&!`${$.name} ${$.company||""}`.toLowerCase().includes(p.toLowerCase()))),[b,p,y]),E=T.filter($=>$.owner_type==="agent"),A=T.filter($=>$.owner_type==="brokerage"),D=async $=>{if(confirm("Delete this vendor?"))try{await l.mutateAsync($),he.success("Vendor deleted")}catch(ee){he.error(ee.message)}},R=async($,ee)=>{try{await o.mutateAsync({vendorId:$,isVisible:ee})}catch(Z){he.error(Z.message)}},z=$=>$.is_required?!0:k.get($.id)??$.owner_type==="agent",O=e.jsxs("div",{className:s?"space-y-6":"max-w-6xl mx-auto p-4 md:p-8 space-y-6",children:[e.jsxs("div",{className:"flex items-start justify-between flex-wrap gap-4",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-2xl font-bold flex items-center gap-2",children:[e.jsx(pm,{className:"w-6 h-6 text-primary"}),"My Vendor Library"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Curate trusted partners that show up in your client portals — inspector, lender, movers and more."})]}),e.jsxs(H,{onClick:()=>{d(null),m(!0)},children:[e.jsx(Ys,{className:"w-4 h-4 mr-2"})," Add Personal Vendor"]})]}),e.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[e.jsxs("div",{className:"relative flex-1 min-w-[200px]",children:[e.jsx(Mn,{className:"w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"}),e.jsx(Se,{className:"pl-9",placeholder:"Search vendors...",value:p,onChange:$=>x($.target.value)})]}),e.jsxs("select",{value:y,onChange:$=>_($.target.value),className:"border rounded-md px-3 py-2 text-sm bg-background",children:[e.jsx("option",{value:"all",children:"All categories"}),nz.map($=>e.jsx("option",{value:$.value,children:$.label},$.value))]})]}),a?e.jsx("div",{className:"text-center text-muted-foreground py-12",children:"Loading vendors..."}):e.jsxs(ta,{defaultValue:r?"all":"personal",children:[e.jsxs(Qn,{children:[e.jsxs(ts,{value:"all",children:["All (",T.length,")"]}),r&&e.jsxs(ts,{value:"brokerage",children:["From Brokerage (",A.length,")"]}),e.jsxs(ts,{value:"personal",children:["My Personal (",E.length,")"]})]}),e.jsx(cs,{value:"all",className:"mt-4",children:e.jsx(kwe,{vendors:T,isVisibleInPortals:z,onToggle:R,onEdit:$=>{d($),m(!0)},onDelete:D,userId:t,clicks:i})}),r&&e.jsx(cs,{value:"brokerage",className:"mt-4",children:A.length===0?e.jsx(yWe,{icon:e.jsx(Lr,{className:"w-12 h-12"}),title:"No brokerage vendors yet",desc:"Your brokerage hasn't added any vendors. Ask your manager to set them up."}):e.jsx(kwe,{vendors:A,isVisibleInPortals:z,onToggle:R,userId:t,clicks:i})}),e.jsx(cs,{value:"personal",className:"mt-4",children:E.length===0?e.jsx(yWe,{icon:e.jsx(pm,{className:"w-12 h-12"}),title:"No personal vendors yet",desc:"Add your trusted inspector, lender, mover — they'll show in every client portal you create.",action:e.jsxs(H,{onClick:()=>{d(null),m(!0)},children:[e.jsx(Ys,{className:"w-4 h-4 mr-2"})," Add Your First Vendor"]})}):e.jsx(kwe,{vendors:E,isVisibleInPortals:z,onToggle:R,onEdit:$=>{d($),m(!0)},onDelete:D,userId:t,clicks:i})})]}),e.jsx(Lyt,{open:h,onOpenChange:m,vendor:c,ownerType:"agent",agentUserId:t})]});return s?O:e.jsx(Ss,{children:O})}function kwe({vendors:s,isVisibleInPortals:t,onToggle:r,onEdit:n,onDelete:a,userId:i,clicks:l}){return e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:s.map(o=>e.jsx(Pyt,{vendor:o,isVisible:t(o),onToggleVisible:c=>r(o.id,c),onEdit:o.owner_type==="agent"&&o.owner_user_id===i?()=>n==null?void 0:n(o):void 0,onDelete:o.owner_type==="agent"&&o.owner_user_id===i?()=>a==null?void 0:a(o.id):void 0,showOwnerBadge:o.owner_type,clickCount:l[o.id]},o.id))})}function yWe({icon:s,title:t,desc:r,action:n}){return e.jsxs("div",{className:"text-center py-16 border-2 border-dashed rounded-xl",children:[e.jsx("div",{className:"text-muted-foreground inline-block mb-3",children:s}),e.jsx("h3",{className:"font-semibold",children:t}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 mb-4 max-w-md mx-auto",children:r}),n]})}function J7s(){const{brokerageId:s,isBrokerageManager:t,isAdmin:r,loading:n}=Ms(),{data:a=[],isLoading:i}=Vzt(s),{data:l={}}=zat("brokerage",s),o=Bat(),[c,d]=S.useState(null),[h,m]=S.useState(!1),[p,x]=S.useState(""),[y,_]=S.useState("all");if(n)return e.jsx(Ss,{children:e.jsx("div",{className:"p-8",children:"Loading..."})});if(!t&&!r)return e.jsx(Ss,{children:e.jsx("div",{className:"p-8 text-center",children:e.jsx("h2",{className:"text-xl font-semibold",children:"Brokerage managers only"})})});const b=a.filter(k=>!(y!=="all"&&k.category!==y||p&&!`${k.name} ${k.company||""}`.toLowerCase().includes(p.toLowerCase()))),j=async k=>{if(confirm("Delete this vendor? This will remove it from all agent libraries."))try{await o.mutateAsync(k),he.success("Vendor deleted")}catch(T){he.error(T.message)}};return e.jsx(Ss,{children:e.jsxs("div",{className:"max-w-6xl mx-auto p-4 md:p-8 space-y-6",children:[e.jsxs("div",{className:"flex items-start justify-between flex-wrap gap-4",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-2xl font-bold flex items-center gap-2",children:[e.jsx(Xa,{className:"w-6 h-6 text-primary"}),"Brokerage Vendor Library"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Manage preferred vendors that all agents in your brokerage can offer to their clients."})]}),e.jsxs(H,{onClick:()=>{d(null),m(!0)},children:[e.jsx(Ys,{className:"w-4 h-4 mr-2"})," Add Vendor"]})]}),e.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[e.jsxs("div",{className:"relative flex-1 min-w-[200px]",children:[e.jsx(Mn,{className:"w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"}),e.jsx(Se,{className:"pl-9",placeholder:"Search vendors...",value:p,onChange:k=>x(k.target.value)})]}),e.jsxs("select",{value:y,onChange:k=>_(k.target.value),className:"border rounded-md px-3 py-2 text-sm bg-background",children:[e.jsx("option",{value:"all",children:"All categories"}),nz.map(k=>e.jsx("option",{value:k.value,children:k.label},k.value))]})]}),i?e.jsx("div",{className:"text-center text-muted-foreground py-12",children:"Loading vendors..."}):b.length===0?e.jsxs("div",{className:"text-center py-16 border-2 border-dashed rounded-xl",children:[e.jsx(Xa,{className:"w-12 h-12 text-muted-foreground mx-auto mb-3"}),e.jsx("h3",{className:"font-semibold",children:"No vendors yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 mb-4",children:"Add preferred lenders, inspectors, title companies, and more."}),e.jsxs(H,{onClick:()=>{d(null),m(!0)},children:[e.jsx(Ys,{className:"w-4 h-4 mr-2"})," Add Your First Vendor"]})]}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:b.map(k=>e.jsx(Pyt,{vendor:k,onEdit:()=>{d(k),m(!0)},onDelete:()=>j(k.id),clickCount:l[k.id]},k.id))}),e.jsx(Lyt,{open:h,onOpenChange:m,vendor:c,ownerType:"brokerage",brokerageId:s,showBrokerageOnlyFields:!0})]})})}const e9s=[{value:"overview",label:"Portals",icon:_g},{value:"vendors",label:"Vendors",icon:zk},{value:"referrals",label:"Referrals",icon:Di},{value:"branding",label:"Branding",icon:pl},{value:"questions",label:"Onboarding",icon:V2}];function t9s(){const[s,t]=Ed(),r=s.get("tab")||"overview",[n,a]=S.useState(r),[i,l]=S.useState(!1),[o,c]=S.useState(!1);return S.useEffect(()=>{t(d=>{const h=new URLSearchParams(d);return h.set("tab",n),h},{replace:!0})},[n,t]),e.jsxs(Ss,{children:[e.jsx(el,{children:e.jsx("title",{children:"Client Portals"})}),e.jsxs("div",{className:"max-w-6xl mx-auto p-4 md:p-8 space-y-6",children:[e.jsx("div",{className:"flex items-start justify-between flex-wrap gap-4",children:e.jsxs("div",{children:[e.jsxs("h1",{className:"text-2xl font-bold flex items-center gap-2",children:[e.jsx(Lr,{className:"w-6 h-6 text-primary"}),"Client Portals"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 max-w-2xl",children:"Your central hub for everything client-facing — manage active portals, curate trusted vendors, tune branding, and inbox referrals from happy clients."})]})}),e.jsx("div",{className:"border rounded-xl p-5 bg-card",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"rounded-lg bg-primary/10 p-3",children:e.jsx(qF,{className:"w-5 h-5 text-primary"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h2",{className:"text-base font-semibold",children:"Create portals from Deal Pipeline"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 max-w-3xl",children:"This page is for managing portals after they’ve been created. To create a new client portal, open the deal inside Deal Pipeline and enable the portal from that deal."})]}),e.jsx(H,{asChild:!0,variant:"outline",size:"sm",className:"shrink-0",children:e.jsx(Xn,{to:"/mission-control/pipeline",children:"Open Deal Pipeline"})})]})}),e.jsxs(ta,{value:n,onValueChange:a,className:"w-full",children:[e.jsx(Qn,{className:"w-full justify-start overflow-x-auto h-auto flex-wrap",children:e9s.map(d=>e.jsxs(ts,{value:d.value,className:"gap-2",children:[e.jsx(d.icon,{className:"w-4 h-4"}),d.label]},d.value))}),e.jsx(cs,{value:"overview",className:"mt-6",children:e.jsx(Eyt,{})}),e.jsx(cs,{value:"vendors",className:"mt-6",children:e.jsx(s9s,{})}),e.jsx(cs,{value:"referrals",className:"mt-6",children:e.jsx(r9s,{})}),e.jsx(cs,{value:"branding",className:"mt-6",children:e.jsx("div",{className:"border rounded-xl p-8 bg-card",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"rounded-lg bg-primary/10 p-3",children:e.jsx(pl,{className:"w-6 h-6 text-primary"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Portal Branding Defaults"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 mb-4 max-w-xl",children:"Set the default logo, colors, cover photo and welcome message that appear at the top of every client portal you create. You can still override per-portal in any deal's settings."}),e.jsxs(H,{onClick:()=>l(!0),children:[e.jsx(Go,{className:"w-4 h-4 mr-2"}),"Edit Branding Defaults"]})]})]})})}),e.jsx(cs,{value:"questions",className:"mt-6",children:e.jsx("div",{className:"border rounded-xl p-8 bg-card",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"rounded-lg bg-primary/10 p-3",children:e.jsx(V2,{className:"w-6 h-6 text-primary"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Custom Onboarding Questions"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 mb-4 max-w-xl",children:"Questions you want every new client to answer when they first open their portal — preferred contact times, kids/pets, must-have features, and anything else that helps you serve them better."}),e.jsxs(H,{onClick:()=>c(!0),children:[e.jsx(Go,{className:"w-4 h-4 mr-2"}),"Manage Questions"]})]})]})})})]})]}),e.jsx(Tyt,{open:i,onOpenChange:l}),e.jsx(Cyt,{open:o,onOpenChange:c})]})}function s9s(){return e.jsx(Dyt,{embedded:!0})}function r9s(){return e.jsx(Iyt,{})}const M6=s=>new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric"}).format(new Date(s));function n9s(s){return yt({queryKey:["client-portal-by-id",s],queryFn:async()=>{if(!s)return null;const{data:t,error:r}=await V.from("client_portals").select("*").eq("id",s).maybeSingle();if(r)throw r;if(!t)return{portal:null,deal:null};const{data:n,error:a}=await V.from("deal_pipeline").select("deal_name, contact_id").eq("id",t.deal_id).maybeSingle();if(a)throw a;let i=null;if(n!=null&&n.contact_id){const{data:l,error:o}=await V.from("innercircle_contacts").select("first_name, last_name, email, phone").eq("id",n.contact_id).maybeSingle();if(o)throw o;i=l}return{portal:t,deal:n?{deal_name:n.deal_name,contact_id:n.contact_id,contact:i}:null}},enabled:!!s})}function a9s(){const{portalId:s}=Po(),t=Fr(),r=ba(),{data:n,isLoading:a}=n9s(s),{data:i=[]}=Y8s(s),{data:l=[]}=Myt(),o=G8(),c=Qgt(),d=Jgt(),h=ext(),[m,p]=S.useState(!1),[x,y]=S.useState(!1),[_,b]=S.useState(!1),[j,k]=S.useState(!1),T=(n==null?void 0:n.portal)??null,E=(n==null?void 0:n.deal)??null,A=S.useMemo(()=>T?l.filter(ie=>ie.portal_id===T.id):[],[l,T==null?void 0:T.id]);if(a)return e.jsx(Ss,{children:e.jsx("div",{className:"flex items-center justify-center py-24",children:e.jsx(is,{className:"h-6 w-6 animate-spin text-muted-foreground"})})});if(!T)return e.jsx(Ss,{children:e.jsxs("div",{className:"max-w-3xl mx-auto p-8 text-center",children:[e.jsx("h1",{className:"text-xl font-semibold mb-2",children:"Portal not found"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"This portal may have been deleted or you don't have access to it."}),e.jsx(H,{asChild:!0,variant:"outline",children:e.jsxs(Xn,{to:"/mission-control/client-portals",children:[e.jsx(za,{className:"w-4 h-4 mr-2"}),"Back to Portals"]})})]})});const D=C_(T.slug),R=(E==null?void 0:E.deal_name)||"Untitled deal",z=E==null?void 0:E.contact,O=z?`${z.first_name||""} ${z.last_name||""}`.trim():"",$=!!T.archived_at,ee=()=>{navigator.clipboard.writeText(D),he.success("Portal link copied!")},Z=async ie=>{try{await o.mutateAsync({id:T.id,is_enabled:ie}),he.success(ie?"Portal enabled":"Portal disabled")}catch{he.error("Failed to update")}},J=async()=>{try{await c.mutateAsync(T.id),he.success("Portal archived")}catch{he.error("Failed to archive")}},K=async()=>{try{await d.mutateAsync(T.id),he.success("Portal restored")}catch{he.error("Failed to restore")}},re=async()=>{try{await h.mutateAsync({id:T.id,dealId:T.deal_id}),he.success("Portal deleted"),t("/mission-control/client-portals")}catch{he.error("Failed to delete")}};return e.jsxs(Ss,{children:[e.jsx(el,{children:e.jsxs("title",{children:[R," — Client Portal"]})}),e.jsxs("div",{className:"max-w-6xl mx-auto p-4 md:p-8 space-y-6",children:[e.jsx("div",{children:e.jsx(H,{asChild:!0,variant:"ghost",size:"sm",className:"-ml-2 text-muted-foreground",children:e.jsxs(Xn,{to:"/mission-control/client-portals?tab=overview",children:[e.jsx(za,{className:"w-4 h-4 mr-1"})," All Client Portals"]})})}),e.jsxs("div",{className:"border rounded-xl p-6 bg-gradient-to-br from-card to-muted/30",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4 flex-wrap",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2 flex-wrap",children:[e.jsx(Lr,{className:"w-5 h-5 text-primary"}),e.jsx("h1",{className:"text-2xl font-bold truncate",children:R}),e.jsx(Xe,{variant:"outline",className:$?"bg-muted text-muted-foreground":T.is_enabled?"bg-emerald-500/10 text-emerald-700 border-emerald-200":"bg-muted text-muted-foreground",children:$?"Archived":T.is_enabled?"Active":"Disabled"}),e.jsx(Xe,{variant:"outline",className:"capitalize text-xs",children:T.visibility})]}),e.jsxs("p",{className:"text-sm text-muted-foreground flex items-center gap-2 flex-wrap",children:[e.jsx(io,{className:"w-3.5 h-3.5"}),T.client_name||O||"No client name set",(z==null?void 0:z.email)&&e.jsxs(e.Fragment,{children:["· ",e.jsx(er,{className:"w-3.5 h-3.5"}),e.jsx("span",{className:"truncate",children:z.email})]}),(z==null?void 0:z.phone)&&e.jsxs(e.Fragment,{children:["· ",e.jsx(Yn,{className:"w-3.5 h-3.5"}),z.phone]})]}),e.jsx("div",{className:"mt-3 flex items-center gap-2 bg-background/60 border rounded-md px-3 py-1.5 max-w-full",children:e.jsx("code",{className:"text-xs font-mono text-muted-foreground truncate flex-1",children:D})})]}),!$&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Live"}),e.jsx(Or,{checked:T.is_enabled,onCheckedChange:Z})]})]}),e.jsxs("div",{className:"mt-5 flex items-center gap-2 flex-wrap",children:[e.jsxs(H,{onClick:ee,variant:"outline",size:"sm",children:[e.jsx(ui,{className:"w-4 h-4 mr-1.5"})," Copy Link"]}),e.jsxs(H,{onClick:()=>window.open(D,"_blank"),variant:"outline",size:"sm",children:[e.jsx(gn,{className:"w-4 h-4 mr-1.5"})," Preview"]}),e.jsxs(H,{onClick:()=>b(!0),size:"sm",children:[e.jsx(yn,{className:"w-4 h-4 mr-1.5"})," Invite Client"]}),e.jsxs(H,{onClick:()=>y(!0),variant:"outline",size:"sm",children:[e.jsx(t_,{className:"w-4 h-4 mr-1.5"})," Post Update"]}),e.jsxs(H,{onClick:()=>p(!0),variant:"outline",size:"sm",children:[e.jsx(Go,{className:"w-4 h-4 mr-1.5"})," Settings"]}),e.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[$?e.jsxs(H,{onClick:K,variant:"outline",size:"sm",children:[e.jsx(AI,{className:"w-4 h-4 mr-1.5"})," Restore"]}):e.jsxs(H,{onClick:J,variant:"ghost",size:"sm",children:[e.jsx(Rk,{className:"w-4 h-4 mr-1.5"})," Archive"]}),e.jsx(H,{onClick:()=>k(!0),variant:"ghost",size:"sm",className:"text-destructive hover:text-destructive",children:e.jsx(Dr,{className:"w-4 h-4"})})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsx(sV,{icon:t_,label:"Updates Posted",value:i.length}),e.jsx(sV,{icon:Di,label:"Referrals",value:A.length}),e.jsx(sV,{icon:Nn,label:"Inspection",value:T.inspection_date?M6(T.inspection_date):"—"}),e.jsx(sV,{icon:Nn,label:"Appraisal",value:T.appraisal_date?M6(T.appraisal_date):"—"})]}),e.jsxs(ta,{defaultValue:"updates",className:"w-full",children:[e.jsxs(Qn,{children:[e.jsxs(ts,{value:"updates",children:["Updates (",i.length,")"]}),e.jsxs(ts,{value:"referrals",children:["Referrals (",A.length,")"]}),e.jsx(ts,{value:"branding",children:"Branding"}),e.jsx(ts,{value:"details",children:"Details"})]}),e.jsx(cs,{value:"updates",className:"mt-4",children:e.jsx(ke,{children:e.jsxs(Oe,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h3",{className:"font-semibold",children:"Portal Update Feed"}),e.jsxs(H,{size:"sm",onClick:()=>y(!0),children:[e.jsx(t_,{className:"w-4 h-4 mr-1.5"})," New Update"]})]}),i.length===0?e.jsxs("div",{className:"text-center py-12 border-2 border-dashed rounded-lg",children:[e.jsx(t_,{className:"w-10 h-10 text-muted-foreground/40 mx-auto mb-3"}),e.jsx("p",{className:"text-sm font-medium",children:"No updates posted yet"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Keep your client in the loop — post your first update."})]}):e.jsx("div",{className:"space-y-3",children:i.map(ie=>e.jsx("div",{className:"border rounded-lg p-4",children:e.jsx("div",{className:"flex items-start justify-between gap-2",children:e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("h4",{className:"font-medium text-sm",children:ie.title}),ie.is_stage_change&&e.jsx(Xe,{variant:"outline",className:"text-[10px] bg-emerald-500/10 text-emerald-700 border-emerald-200",children:"Stage Change"})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground mt-0.5",children:M6(ie.created_at)}),ie.content&&e.jsx("p",{className:"text-sm text-muted-foreground mt-2 whitespace-pre-wrap",children:ie.content}),ie.video_url&&e.jsxs("a",{href:ie.video_url,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 text-xs text-primary hover:underline mt-2",children:[e.jsx(xn,{className:"w-3 h-3"})," View video"]})]})})},ie.id))})]})})}),e.jsx(cs,{value:"referrals",className:"mt-4",children:e.jsx(ke,{children:e.jsxs(Oe,{className:"p-4",children:[e.jsx("h3",{className:"font-semibold mb-4",children:"Referrals from this Portal"}),A.length===0?e.jsxs("div",{className:"text-center py-12 border-2 border-dashed rounded-lg",children:[e.jsx(Di,{className:"w-10 h-10 text-muted-foreground/40 mx-auto mb-3"}),e.jsx("p",{className:"text-sm font-medium",children:"No referrals yet"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"When your client refers a friend, they'll show up here."})]}):e.jsx("div",{className:"space-y-2",children:A.map(ie=>e.jsx(Xn,{to:"/mission-control/client-portals?tab=referrals",className:"block border rounded-lg p-3 hover:bg-muted/50 transition-colors",children:e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:ie.friend_name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[ie.friend_email||ie.friend_phone||"No contact info"," · ",M6(ie.created_at)]})]}),e.jsx(Xe,{variant:"outline",className:"text-xs capitalize",children:ie.status})]})},ie.id))})]})})}),e.jsx(cs,{value:"branding",className:"mt-4",children:e.jsx(ke,{children:e.jsx(Oe,{className:"p-6",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"rounded-lg bg-primary/10 p-3",children:e.jsx(pl,{className:"w-6 h-6 text-primary"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"font-semibold mb-1",children:"Portal Branding"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4 max-w-xl",children:"Override your default branding for this specific portal — custom logo, colors, cover photo, and welcome message just for this client."}),e.jsxs(H,{onClick:()=>p(!0),children:[e.jsx(Go,{className:"w-4 h-4 mr-2"}),"Edit Branding (in Settings)"]})]})]})})})}),e.jsx(cs,{value:"details",className:"mt-4",children:e.jsx(ke,{children:e.jsxs(Oe,{className:"p-6 space-y-4",children:[e.jsx(kN,{label:"Visibility",value:T.visibility}),e.jsx(kN,{label:"Onboarding Required",value:T.require_onboarding?"Yes":"No"}),e.jsx(kN,{label:"Allow Spouse",value:T.allow_spouse?"Yes":"No"}),e.jsx(kN,{label:"Notify Client on Updates",value:T.notify_client?"Yes":"No"}),e.jsx(kN,{label:"Show Post-Close Tips",value:T.show_post_close_tips?"Yes":"No"}),e.jsx(kN,{label:"Slug",value:T.slug,mono:!0}),e.jsx(kN,{label:"Created",value:M6(T.created_at)}),e.jsx(kN,{label:"Last Updated",value:M6(T.updated_at)}),e.jsx("div",{className:"pt-2",children:e.jsxs(H,{variant:"outline",onClick:()=>p(!0),children:[e.jsx(Go,{className:"w-4 h-4 mr-2"})," Edit All Settings"]})})]})})})]})]}),e.jsx(u6e,{open:m,onOpenChange:p,portal:T,dealOwnerId:r||""}),e.jsx(h6e,{open:x,onOpenChange:y,portalId:T.id,portalSlug:T.slug,notifyClient:T.notify_client}),e.jsx(m6e,{open:_,onOpenChange:b,portal:T,dealName:R}),e.jsx(Rl,{open:j,onOpenChange:k,children:e.jsxs(jl,{children:[e.jsxs(Nl,{children:[e.jsx(Sl,{children:"Permanently delete this portal?"}),e.jsx(Cl,{children:"This removes the portal and all its updates. The client will lose access. This action cannot be undone."})]}),e.jsxs(kl,{children:[e.jsx(Tl,{children:"Cancel"}),e.jsx(ml,{onClick:re,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete Permanently"})]})]})})]})}function sV({icon:s,label:t,value:r}){return e.jsxs("div",{className:"border rounded-lg p-4 bg-card",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(s,{className:"w-3.5 h-3.5"}),e.jsx("span",{className:"text-[11px] uppercase tracking-wide",children:t})]}),e.jsx("p",{className:"text-xl font-semibold truncate",children:r})]})}function kN({label:s,value:t,mono:r}){return e.jsxs("div",{className:"flex items-center justify-between gap-4 border-b pb-2 last:border-b-0 last:pb-0",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:s}),e.jsx("span",{className:`text-sm ${r?"font-mono text-xs":""} text-right truncate`,children:t})]})}const G4e=[{value:"video_intro",label:"Video Intro",icon:xn,description:"Add an intro video"},{value:"testimonials",label:"Testimonials",icon:HI,description:"Client testimonials carousel"},{value:"specialties",label:"Specialties",icon:xm,description:"Tags for your specialties"},{value:"custom_links",label:"Custom Links",icon:ql,description:"Custom CTA buttons"},{value:"social_media",label:"Social Media",icon:cd,description:"Links to your social profiles"}],i9s=["First-Time Buyers","Luxury Homes","Investment Properties","Relocation","New Construction","Condos & Townhomes","Waterfront","Commercial","Land & Lots","Senior Living","Military/VA","Short Sales & Foreclosures"],o9s={video_intro:{video_url:""},testimonials:{testimonials:[{name:"",quote:"",role:""}]},specialties:{tags:[]},custom_links:{links:[{label:"",url:""}]},social_media:{platforms:[]}};function Ryt({cardId:s}){const{data:t,isLoading:r}=rLt(s),n=nLt(),a=aLt(),i=iLt(),[l,o]=S.useState(!1),[c,d]=S.useState(""),[h,m]=S.useState(null);if(r)return e.jsxs("div",{className:"space-y-3",children:[e.jsx(Ks,{className:"h-16 w-full"}),e.jsx(Ks,{className:"h-16 w-full"})]});const p=()=>{c&&n.mutate({card_id:s,block_type:c,sort_order:(t==null?void 0:t.length)||0,config:o9s[c]||{}},{onSuccess:()=>{o(!1),d("")}})},x=k=>{a.mutate({id:k.id,is_visible:!k.is_visible})},y=(k,T)=>{if(!t)return;const E=t.findIndex(R=>R.id===k.id),A=T==="up"?E-1:E+1;if(A<0||A>=t.length)return;const D=t[A];a.mutate({id:k.id,sort_order:D.sort_order}),a.mutate({id:D.id,sort_order:k.sort_order})},_=k=>{confirm("Remove this block from this card?")&&i.mutate(k.id)},b=(k,T)=>{a.mutate({id:k.id,config:T},{onSuccess:()=>m(null)})},j=k=>G4e.find(T=>T.value===k);return e.jsxs("div",{className:"space-y-3",children:[!t||t.length===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx("p",{className:"text-muted-foreground mb-4 text-sm",children:"No blocks yet. Add a block to customize this card."}),e.jsxs(H,{size:"sm",onClick:()=>o(!0),children:[e.jsx(Ys,{className:"h-4 w-4 mr-1"})," Add Block"]})]}):e.jsxs(e.Fragment,{children:[t.map((k,T)=>{const E=j(k.block_type),A=(E==null?void 0:E.icon)||xm;return e.jsx(ke,{className:k.is_visible?"":"opacity-50",children:e.jsx(Oe,{className:"p-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Oh,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}),e.jsx(A,{className:"h-4 w-4 text-primary flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-xs",children:(E==null?void 0:E.label)||k.block_type}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:l9s(k)})]}),e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsx(H,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>y(k,"up"),disabled:T===0,children:e.jsx(Hu,{className:"h-3 w-3"})}),e.jsx(H,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>y(k,"down"),disabled:T===t.length-1,children:e.jsx(fm,{className:"h-3 w-3"})}),e.jsx(H,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>x(k),children:k.is_visible?e.jsx(Bn,{className:"h-3 w-3"}):e.jsx($f,{className:"h-3 w-3"})}),e.jsx(H,{variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>m(k),children:"Edit"}),e.jsx(H,{variant:"ghost",size:"icon",className:"h-7 w-7 text-destructive",onClick:()=>_(k),children:e.jsx(Dr,{className:"h-3 w-3"})})]})]})})},k.id)}),e.jsxs(H,{variant:"outline",size:"sm",className:"w-full",onClick:()=>o(!0),children:[e.jsx(Ys,{className:"h-4 w-4 mr-1"})," Add Block"]})]}),e.jsx(bs,{open:l,onOpenChange:o,children:e.jsxs(vs,{children:[e.jsx(Cs,{children:e.jsx(Ns,{children:"Add Block"})}),e.jsx("div",{className:"grid gap-3",children:G4e.map(k=>{const T=k.icon;return e.jsxs("button",{onClick:()=>d(k.value),className:`flex items-center gap-3 p-3 rounded-lg border text-left transition-colors ${c===k.value?"border-primary bg-primary/5":"border-border hover:bg-muted"}`,children:[e.jsx(T,{className:"h-5 w-5 text-primary flex-shrink-0"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:k.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:k.description})]})]},k.value)})}),e.jsxs(wn,{children:[e.jsx(H,{variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsx(H,{onClick:p,disabled:!c||n.isPending,children:"Add Block"})]})]})}),h&&e.jsx(c9s,{block:h,onSave:k=>b(h,k),onClose:()=>m(null)})]})}function l9s(s){var r;const t=s.config;switch(s.block_type){case"video_intro":return t.video_url?"Video configured":"No video set";case"testimonials":{const n=((r=t.testimonials)==null?void 0:r.length)||0;return`${n} testimonial${n!==1?"s":""}`}case"specialties":{const n=t.tags||[];return n.length?n.slice(0,3).join(", ")+(n.length>3?"...":""):"No tags"}case"custom_links":{const n=t.links||[];return`${n.length} link${n.length!==1?"s":""}`}case"social_media":{const n=t.platforms||[];return n.length?n.map(a=>a.platform).join(", "):"No platforms"}default:return""}}function c9s({block:s,onSave:t,onClose:r}){const[n,a]=S.useState(s.config),i=G4e.find(l=>l.value===s.block_type);return e.jsx(bs,{open:!0,onOpenChange:r,children:e.jsxs(vs,{className:"max-w-lg max-h-[80vh] overflow-y-auto",children:[e.jsx(Cs,{children:e.jsxs(Ns,{children:["Edit ",i==null?void 0:i.label]})}),s.block_type==="video_intro"&&e.jsx(d9s,{config:n,onChange:a,cardId:s.card_id}),s.block_type==="testimonials"&&e.jsx(u9s,{config:n,onChange:a}),s.block_type==="specialties"&&e.jsx(h9s,{config:n,onChange:a}),s.block_type==="custom_links"&&e.jsx(m9s,{config:n,onChange:a}),s.block_type==="social_media"&&e.jsx(f9s,{config:n,onChange:a}),e.jsxs(wn,{children:[e.jsx(H,{variant:"outline",onClick:r,children:"Cancel"}),e.jsx(H,{onClick:()=>t(n),children:"Save"})]})]})})}function d9s({config:s,onChange:t,cardId:r}){var x,y;const[n,a]=S.useState(""),[i,l]=S.useState((x=s.video_url)!=null&&x.includes("youtube")||(y=s.video_url)!=null&&y.includes("youtu.be")?"youtube":"library"),{data:o}=yt({queryKey:["card-owner",r],queryFn:async()=>{const{data:_}=await V.from("agent_cards").select("user_id").eq("id",r).single();return _==null?void 0:_.user_id},enabled:!!r}),{data:c,isLoading:d}=yt({queryKey:["agent-videos-library",o],queryFn:async()=>{const{data:_,error:b}=await V.from("agent_videos").select("id, title, bunny_video_id, thumbnail_url, playback_url, created_at").eq("owner_user_id",o).eq("is_deleted",!1).eq("status","ready").order("created_at",{ascending:!1});if(b)throw b;return _||[]},enabled:!!o}),h=(c==null?void 0:c.filter(_=>!n||(_.title||"").toLowerCase().includes(n.toLowerCase())))||[],m=s.bunny_video_id,p=_=>{var T;const b=(T=_.playback_url)==null?void 0:T.match(/\/(?:play|embed)\/(\d+)\//),k=`https://iframe.mediadelivery.net/embed/${b?b[1]:"570924"}/${_.bunny_video_id}?autoplay=false&responsive=true`;t({...s,video_url:k,bunny_video_id:_.bunny_video_id,video_source:"library"})};return e.jsx("div",{className:"space-y-4",children:e.jsxs(ta,{value:i,onValueChange:l,children:[e.jsxs(Qn,{className:"w-full",children:[e.jsx(ts,{value:"library",className:"flex-1",children:"Video Library"}),e.jsx(ts,{value:"youtube",className:"flex-1",children:"YouTube URL"})]}),e.jsxs(cs,{value:"library",className:"space-y-3 mt-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Mn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Se,{placeholder:"Search videos...",value:n,onChange:_=>a(_.target.value),className:"pl-9"})]}),e.jsx(Ci,{className:"h-[240px]",children:d?e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ks,{className:"h-14 w-full"}),e.jsx(Ks,{className:"h-14 w-full"})]}):h.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:(c==null?void 0:c.length)===0?"No videos in library yet":"No matching videos"}):e.jsx("div",{className:"space-y-1.5 pr-3",children:h.map(_=>e.jsxs("button",{onClick:()=>p(_),className:`w-full flex items-center gap-3 p-2 rounded-lg border text-left transition-colors ${m===_.bunny_video_id?"border-primary bg-primary/5":"border-border hover:bg-muted"}`,children:[_.thumbnail_url?e.jsx("img",{src:_.thumbnail_url,alt:"",className:"h-10 w-16 rounded object-cover flex-shrink-0 bg-muted",onError:b=>{var j;b.currentTarget.style.display="none",(j=b.currentTarget.nextElementSibling)==null||j.classList.remove("hidden")}}):null,e.jsx("div",{className:`h-10 w-16 rounded bg-muted flex items-center justify-center flex-shrink-0 ${_.thumbnail_url?"hidden":""}`,children:e.jsx(xn,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{className:"text-sm font-medium truncate flex-1",children:_.title||"Untitled Video"}),m===_.bunny_video_id&&e.jsx(va,{className:"h-4 w-4 text-primary flex-shrink-0"})]},_.id))})})]}),e.jsx(cs,{value:"youtube",className:"space-y-3 mt-3",children:e.jsxs("div",{children:[e.jsx(ue,{children:"YouTube URL"}),e.jsx(Se,{placeholder:"https://www.youtube.com/watch?v=...",value:s.video_source==="youtube"&&s.video_url||"",onChange:_=>t({...s,video_url:_.target.value,bunny_video_id:null,video_source:"youtube"})}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Paste a YouTube video link"})]})})]})})}function u9s({config:s,onChange:t}){const r=s.testimonials||[],n=(l,o,c)=>{const d=[...r];d[l]={...d[l],[o]:c},t({...s,testimonials:d})},a=()=>t({...s,testimonials:[...r,{name:"",quote:"",role:""}]}),i=l=>t({...s,testimonials:r.filter((o,c)=>c!==l)});return e.jsxs("div",{className:"space-y-4",children:[r.map((l,o)=>e.jsx(ke,{children:e.jsxs(Oe,{className:"p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(ue,{className:"text-xs font-medium",children:["Testimonial ",o+1]}),r.length>1&&e.jsx(H,{variant:"ghost",size:"icon",className:"h-6 w-6 text-destructive",onClick:()=>i(o),children:e.jsx(Dr,{className:"h-3 w-3"})})]}),e.jsx(Se,{placeholder:"Client name",value:l.name,onChange:c=>n(o,"name",c.target.value)}),e.jsx(Se,{placeholder:"Role/title (optional)",value:l.role||"",onChange:c=>n(o,"role",c.target.value)}),e.jsx("textarea",{className:"w-full min-h-[60px] rounded-md border border-input bg-background px-3 py-2 text-sm",placeholder:"Their testimonial quote...",value:l.quote,onChange:c=>n(o,"quote",c.target.value)})]})},o)),e.jsxs(H,{variant:"outline",size:"sm",onClick:a,className:"w-full",children:[e.jsx(Ys,{className:"h-4 w-4 mr-1"})," Add Testimonial"]})]})}function h9s({config:s,onChange:t}){const r=s.tags||[],[n,a]=S.useState(""),i=o=>{t({...s,tags:r.includes(o)?r.filter(c=>c!==o):[...r,o]})},l=()=>{n.trim()&&!r.includes(n.trim())&&(t({...s,tags:[...r,n.trim()]}),a(""))};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ue,{className:"text-sm mb-2 block",children:"Preset Specialties"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:i9s.map(o=>e.jsx("button",{onClick:()=>i(o),className:`px-3 py-1.5 text-xs rounded-full border transition-colors ${r.includes(o)?"bg-primary text-primary-foreground border-primary":"bg-muted border-border hover:bg-muted/80"}`,children:o},o))})]}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-sm mb-2 block",children:"Custom Tag"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Se,{placeholder:"Add your own...",value:n,onChange:o=>a(o.target.value),onKeyDown:o=>o.key==="Enter"&&(o.preventDefault(),l())}),e.jsx(H,{variant:"outline",size:"sm",onClick:l,children:"Add"})]})]}),r.length>0&&e.jsxs("div",{children:[e.jsxs(ue,{className:"text-xs text-muted-foreground mb-1 block",children:["Selected (",r.length,")"]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:r.map(o=>e.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-1 text-xs bg-primary/10 text-primary rounded-full",children:[o,e.jsx("button",{onClick:()=>i(o),className:"hover:text-destructive",children:"×"})]},o))})]})]})}function m9s({config:s,onChange:t}){const r=s.links||[],n=(l,o,c)=>{const d=[...r];d[l]={...d[l],[o]:c},t({...s,links:d})},a=()=>t({...s,links:[...r,{label:"",url:""}]}),i=l=>t({...s,links:r.filter((o,c)=>c!==l)});return e.jsxs("div",{className:"space-y-3",children:[r.map((l,o)=>e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(Se,{placeholder:"Button label",value:l.label,onChange:c=>n(o,"label",c.target.value)}),e.jsx(Se,{placeholder:"https://...",value:l.url,onChange:c=>n(o,"url",c.target.value)})]}),r.length>1&&e.jsx(H,{variant:"ghost",size:"icon",className:"h-8 w-8 mt-1 text-destructive",onClick:()=>i(o),children:e.jsx(Dr,{className:"h-3 w-3"})})]},o)),e.jsxs(H,{variant:"outline",size:"sm",onClick:a,className:"w-full",children:[e.jsx(Ys,{className:"h-4 w-4 mr-1"})," Add Link"]})]})}const vWe=[{value:"instagram",label:"Instagram"},{value:"facebook",label:"Facebook"},{value:"linkedin",label:"LinkedIn"},{value:"twitter",label:"X (Twitter)"},{value:"youtube",label:"YouTube"},{value:"tiktok",label:"TikTok"},{value:"zillow",label:"Zillow"},{value:"realtor",label:"Realtor.com"},{value:"spotify",label:"Spotify"},{value:"apple_music",label:"Apple Music"}];function f9s({config:s,onChange:t}){const r=s.platforms||[],n=c=>{r.find(d=>d.platform===c)||t({...s,platforms:[...r,{platform:c,url:""}]})},a=(c,d)=>{const h=[...r];h[c]={...h[c],url:d},t({...s,platforms:h})},i=c=>{t({...s,platforms:r.filter((d,h)=>h!==c)})},l=vWe.filter(c=>!r.find(d=>d.platform===c.value)),o=c=>{const d=Jje[c],h=vWe.find(m=>m.value===c);return{label:(h==null?void 0:h.label)||c,color:(d==null?void 0:d.color)||"#666",iconPath:d==null?void 0:d.icon}};return e.jsxs("div",{className:"space-y-4",children:[r.length>0&&e.jsx("div",{className:"space-y-3",children:r.map((c,d)=>{const h=o(c.platform);return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-9 w-9 rounded-lg flex items-center justify-center flex-shrink-0 border",style:{borderColor:h.color+"30",backgroundColor:h.color+"10"},children:h.iconPath&&e.jsx("svg",{viewBox:"0 0 24 24",width:16,height:16,fill:h.color,children:e.jsx("path",{d:h.iconPath})})}),e.jsx("div",{className:"flex-1",children:e.jsx(Se,{placeholder:`Your ${h.label} profile URL`,value:c.url,onChange:m=>a(d,m.target.value)})}),e.jsx(H,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive flex-shrink-0",onClick:()=>i(d),children:e.jsx(Dr,{className:"h-3.5 w-3.5"})})]},d)})}),l.length>0&&e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs text-muted-foreground mb-2 block",children:"Add a platform"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:l.map(c=>{const d=Jje[c.value];return e.jsxs("button",{onClick:()=>n(c.value),className:"inline-flex items-center gap-1.5 px-3 py-1.5 text-xs rounded-full border border-border bg-muted hover:bg-muted/80 transition-colors",children:[(d==null?void 0:d.icon)&&e.jsx("svg",{viewBox:"0 0 24 24",width:12,height:12,fill:d.color,children:e.jsx("path",{d:d.icon})}),c.label]},c.value)})})]}),r.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"Tap a platform above to add your social media profile."})]})}var p9s=Object.defineProperty,mpe=Object.getOwnPropertySymbols,Oyt=Object.prototype.hasOwnProperty,Fyt=Object.prototype.propertyIsEnumerable,bWe=(s,t,r)=>t in s?p9s(s,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):s[t]=r,W4e=(s,t)=>{for(var r in t||(t={}))Oyt.call(t,r)&&bWe(s,r,t[r]);if(mpe)for(var r of mpe(t))Fyt.call(t,r)&&bWe(s,r,t[r]);return s},K4e=(s,t)=>{var r={};for(var n in s)Oyt.call(s,n)&&t.indexOf(n)<0&&(r[n]=s[n]);if(s!=null&&mpe)for(var n of mpe(s))t.indexOf(n)<0&&Fyt.call(s,n)&&(r[n]=s[n]);return r};/** * @license QR Code generator library (TypeScript) * Copyright (c) Project Nayuki. * SPDX-License-Identifier: MIT */var RA;(s=>{const t=class Zo{constructor(c,d,h,m){if(this.version=c,this.errorCorrectionLevel=d,this.modules=[],this.isFunction=[],cZo.MAX_VERSION)throw new RangeError("Version value out of range");if(m<-1||m>7)throw new RangeError("Mask value out of range");this.size=c*4+17;let p=[];for(let y=0;y7)throw new RangeError("Invalid value");let y,_;for(y=h;;y++){const T=Zo.getNumDataCodewords(y,d)*8,E=l.getTotalBits(c,y);if(E<=T){_=E;break}if(y>=m)throw new RangeError("Data too long")}for(const T of[Zo.Ecc.MEDIUM,Zo.Ecc.QUARTILE,Zo.Ecc.HIGH])x&&_<=Zo.getNumDataCodewords(y,T)*8&&(d=T);let b=[];for(const T of c){r(T.mode.modeBits,4,b),r(T.numChars,T.mode.numCharCountBits(y),b);for(const E of T.getData())b.push(E)}a(b.length==_);const j=Zo.getNumDataCodewords(y,d)*8;a(b.length<=j),r(0,Math.min(4,j-b.length),b),r(0,(8-b.length%8)%8,b),a(b.length%8==0);for(let T=236;b.lengthk[E>>>3]|=T<<7-(E&7)),new Zo(y,d,k,p)}getModule(c,d){return 0<=c&&c>>9)*1335;const m=(d<<10|h)^21522;a(m>>>15==0);for(let p=0;p<=5;p++)this.setFunctionModule(8,p,n(m,p));this.setFunctionModule(8,7,n(m,6)),this.setFunctionModule(8,8,n(m,7)),this.setFunctionModule(7,8,n(m,8));for(let p=9;p<15;p++)this.setFunctionModule(14-p,8,n(m,p));for(let p=0;p<8;p++)this.setFunctionModule(this.size-1-p,8,n(m,p));for(let p=8;p<15;p++)this.setFunctionModule(8,this.size-15+p,n(m,p));this.setFunctionModule(8,this.size-8,!0)}drawVersion(){if(this.version<7)return;let c=this.version;for(let h=0;h<12;h++)c=c<<1^(c>>>11)*7973;const d=this.version<<12|c;a(d>>>18==0);for(let h=0;h<18;h++){const m=n(d,h),p=this.size-11+h%3,x=Math.floor(h/3);this.setFunctionModule(p,x,m),this.setFunctionModule(x,p,m)}}drawFinderPattern(c,d){for(let h=-4;h<=4;h++)for(let m=-4;m<=4;m++){const p=Math.max(Math.abs(m),Math.abs(h)),x=c+m,y=d+h;0<=x&&x{(T!=_-p||A>=y)&&k.push(E[T])});return a(k.length==x),k}drawCodewords(c){if(c.length!=Math.floor(Zo.getNumRawDataModules(this.version)/8))throw new RangeError("Invalid argument");let d=0;for(let h=this.size-1;h>=1;h-=2){h==6&&(h=5);for(let m=0;m>>3],7-(d&7)),d++)}}a(d==c.length*8)}applyMask(c){if(c<0||c>7)throw new RangeError("Mask value out of range");for(let d=0;d5&&c++):(this.finderPenaltyAddHistory(y,_),x||(c+=this.finderPenaltyCountPatterns(_)*Zo.PENALTY_N3),x=this.modules[p][b],y=1);c+=this.finderPenaltyTerminateAndCount(x,y,_)*Zo.PENALTY_N3}for(let p=0;p5&&c++):(this.finderPenaltyAddHistory(y,_),x||(c+=this.finderPenaltyCountPatterns(_)*Zo.PENALTY_N3),x=this.modules[b][p],y=1);c+=this.finderPenaltyTerminateAndCount(x,y,_)*Zo.PENALTY_N3}for(let p=0;px+(y?1:0),d);const h=this.size*this.size,m=Math.ceil(Math.abs(d*20-h*10)/h)-1;return a(0<=m&&m<=9),c+=m*Zo.PENALTY_N4,a(0<=c&&c<=2568888),c}getAlignmentPatternPositions(){if(this.version==1)return[];{const c=Math.floor(this.version/7)+2,d=this.version==32?26:Math.ceil((this.version*4+4)/(c*2-2))*2;let h=[6];for(let m=this.size-7;h.lengthZo.MAX_VERSION)throw new RangeError("Version number out of range");let d=(16*c+128)*c+64;if(c>=2){const h=Math.floor(c/7)+2;d-=(25*h-10)*h-55,c>=7&&(d-=36)}return a(208<=d&&d<=29648),d}static getNumDataCodewords(c,d){return Math.floor(Zo.getNumRawDataModules(c)/8)-Zo.ECC_CODEWORDS_PER_BLOCK[d.ordinal][c]*Zo.NUM_ERROR_CORRECTION_BLOCKS[d.ordinal][c]}static reedSolomonComputeDivisor(c){if(c<1||c>255)throw new RangeError("Degree out of range");let d=[];for(let m=0;m0);for(const m of c){const p=m^h.shift();h.push(0),d.forEach((x,y)=>h[y]^=Zo.reedSolomonMultiply(x,p))}return h}static reedSolomonMultiply(c,d){if(c>>>8||d>>>8)throw new RangeError("Byte out of range");let h=0;for(let m=7;m>=0;m--)h=h<<1^(h>>>7)*285,h^=(d>>>m&1)*c;return a(h>>>8==0),h}finderPenaltyCountPatterns(c){const d=c[1];a(d<=this.size*3);const h=d>0&&c[2]==d&&c[3]==d*3&&c[4]==d&&c[5]==d;return(h&&c[0]>=d*4&&c[6]>=d?1:0)+(h&&c[6]>=d*4&&c[0]>=d?1:0)}finderPenaltyTerminateAndCount(c,d,h){return c&&(this.finderPenaltyAddHistory(d,h),d=0),d+=this.size,this.finderPenaltyAddHistory(d,h),this.finderPenaltyCountPatterns(h)}finderPenaltyAddHistory(c,d){d[0]==0&&(c+=this.size),d.pop(),d.unshift(c)}};t.MIN_VERSION=1,t.MAX_VERSION=40,t.PENALTY_N1=3,t.PENALTY_N2=3,t.PENALTY_N3=40,t.PENALTY_N4=10,t.ECC_CODEWORDS_PER_BLOCK=[[-1,7,10,15,20,26,18,20,24,30,18,20,24,26,30,22,24,28,30,28,28,28,28,30,30,26,28,30,30,30,30,30,30,30,30,30,30,30,30,30,30],[-1,10,16,26,18,24,16,18,22,22,26,30,22,22,24,24,28,28,26,26,26,26,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28],[-1,13,22,18,26,18,24,18,22,20,24,28,26,24,20,30,24,28,28,26,30,28,30,30,30,30,28,30,30,30,30,30,30,30,30,30,30,30,30,30,30],[-1,17,28,22,16,22,28,26,26,24,28,24,28,22,24,24,30,28,28,26,28,30,24,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30]],t.NUM_ERROR_CORRECTION_BLOCKS=[[-1,1,1,1,1,1,2,2,2,2,4,4,4,4,4,6,6,6,6,7,8,8,9,9,10,12,12,12,13,14,15,16,17,18,19,19,20,21,22,24,25],[-1,1,1,1,2,2,4,4,4,5,5,5,8,9,9,10,10,11,13,14,16,17,17,18,20,21,23,25,26,28,29,31,33,35,37,38,40,43,45,47,49],[-1,1,1,2,2,4,4,6,6,8,8,8,10,12,16,12,17,16,18,21,20,23,23,25,27,29,34,34,35,38,40,43,45,48,51,53,56,59,62,65,68],[-1,1,1,2,4,4,4,5,6,8,8,11,11,16,16,18,16,19,21,25,25,25,34,30,32,35,37,40,42,45,48,51,54,57,60,63,66,70,74,77,81]],s.QrCode=t;function r(o,c,d){if(c<0||c>31||o>>>c)throw new RangeError("Value out of range");for(let h=c-1;h>=0;h--)d.push(o>>>h&1)}function n(o,c){return(o>>>c&1)!=0}function a(o){if(!o)throw new Error("Assertion error")}const i=class Pu{constructor(c,d,h){if(this.mode=c,this.numChars=d,this.bitData=h,d<0)throw new RangeError("Invalid argument");this.bitData=h.slice()}static makeBytes(c){let d=[];for(const h of c)r(h,8,d);return new Pu(Pu.Mode.BYTE,c.length,d)}static makeNumeric(c){if(!Pu.isNumeric(c))throw new RangeError("String contains non-numeric characters");let d=[];for(let h=0;h=1<{(t=>{const r=class{constructor(a,i){this.ordinal=a,this.formatBits=i}};r.LOW=new r(0,1),r.MEDIUM=new r(1,0),r.QUARTILE=new r(2,3),r.HIGH=new r(3,2),t.Ecc=r})(s.QrCode||(s.QrCode={}))})(RA||(RA={}));(s=>{(t=>{const r=class{constructor(a,i){this.modeBits=a,this.numBitsCharCount=i}numCharCountBits(a){return this.numBitsCharCount[Math.floor((a+7)/17)]}};r.NUMERIC=new r(1,[10,12,14]),r.ALPHANUMERIC=new r(2,[9,11,13]),r.BYTE=new r(4,[8,16,16]),r.KANJI=new r(8,[8,10,12]),r.ECI=new r(7,[0,0,0]),t.Mode=r})(s.QrSegment||(s.QrSegment={}))})(RA||(RA={}));var _I=RA;/** * @license qrcode.react * Copyright (c) Paul O'Shannessy * SPDX-License-Identifier: ISC */var g9s={L:_I.QrCode.Ecc.LOW,M:_I.QrCode.Ecc.MEDIUM,Q:_I.QrCode.Ecc.QUARTILE,H:_I.QrCode.Ecc.HIGH},Byt=128,zyt="L",$yt="#FFFFFF",Uyt="#000000",qyt=!1,Vyt=1,x9s=4,y9s=0,v9s=.1;function Hyt(s,t=0){const r=[];return s.forEach(function(n,a){let i=null;n.forEach(function(l,o){if(!l&&i!==null){r.push(`M${i+t} ${a+t}h${o-i}v1H${i+t}z`),i=null;return}if(o===n.length-1){if(!l)return;i===null?r.push(`M${o+t},${a+t} h1v1H${o+t}z`):r.push(`M${i+t},${a+t} h${o+1-i}v1H${i+t}z`);return}l&&i===null&&(i=o)})}),r.join("")}function Gyt(s,t){return s.slice().map((r,n)=>n=t.y+t.h?r:r.map((a,i)=>i=t.x+t.w?a:!1))}function b9s(s,t,r,n){if(n==null)return null;const a=s.length+r*2,i=Math.floor(t*v9s),l=a/t,o=(n.width||i)*l,c=(n.height||i)*l,d=n.x==null?s.length/2-o/2:n.x*l,h=n.y==null?s.length/2-c/2:n.y*l,m=n.opacity==null?1:n.opacity;let p=null;if(n.excavate){let y=Math.floor(d),_=Math.floor(h),b=Math.ceil(o+d-y),j=Math.ceil(c+h-_);p={x:y,y:_,w:b,h:j}}const x=n.crossOrigin;return{x:d,y:h,h:c,w:o,excavation:p,opacity:m,crossOrigin:x}}function _9s(s,t){return t!=null?Math.max(Math.floor(t),0):s?x9s:y9s}function Wyt({value:s,level:t,minVersion:r,includeMargin:n,marginSize:a,imageSettings:i,size:l,boostLevel:o}){let c=Nt.useMemo(()=>{const y=(Array.isArray(s)?s:[s]).reduce((_,b)=>(_.push(..._I.QrSegment.makeSegments(b)),_),[]);return _I.QrCode.encodeSegments(y,g9s[t],r,void 0,void 0,o)},[s,t,r,o]);const{cells:d,margin:h,numCells:m,calculatedImageSettings:p}=Nt.useMemo(()=>{let x=c.getModules();const y=_9s(n,a),_=x.length+y*2,b=b9s(x,l,y,i);return{cells:x,margin:y,numCells:_,calculatedImageSettings:b}},[c,l,i,n,a]);return{qrcode:c,margin:h,cells:d,numCells:m,calculatedImageSettings:p}}var w9s=function(){try{new Path2D().addPath(new Path2D)}catch{return!1}return!0}(),j9s=Nt.forwardRef(function(t,r){const n=t,{value:a,size:i=Byt,level:l=zyt,bgColor:o=$yt,fgColor:c=Uyt,includeMargin:d=qyt,minVersion:h=Vyt,boostLevel:m,marginSize:p,imageSettings:x}=n,_=K4e(n,["value","size","level","bgColor","fgColor","includeMargin","minVersion","boostLevel","marginSize","imageSettings"]),{style:b}=_,j=K4e(_,["style"]),k=x==null?void 0:x.src,T=Nt.useRef(null),E=Nt.useRef(null),A=Nt.useCallback(K=>{T.current=K,typeof r=="function"?r(K):r&&(r.current=K)},[r]),[D,R]=Nt.useState(!1),{margin:z,cells:O,numCells:$,calculatedImageSettings:ee}=Wyt({value:a,level:l,minVersion:h,boostLevel:m,includeMargin:d,marginSize:p,imageSettings:x,size:i});Nt.useEffect(()=>{if(T.current!=null){const K=T.current,re=K.getContext("2d");if(!re)return;let ie=O;const ce=E.current,ne=ee!=null&&ce!==null&&ce.complete&&ce.naturalHeight!==0&&ce.naturalWidth!==0;ne&&ee.excavation!=null&&(ie=Gyt(O,ee.excavation));const le=window.devicePixelRatio||1;K.height=K.width=i*le;const be=i/$*le;re.scale(be,be),re.fillStyle=o,re.fillRect(0,0,$,$),re.fillStyle=c,w9s?re.fill(new Path2D(Hyt(ie,z))):O.forEach(function(fe,je){fe.forEach(function(ve,We){ve&&re.fillRect(We+z,je+z,1,1)})}),ee&&(re.globalAlpha=ee.opacity),ne&&re.drawImage(ce,ee.x+z,ee.y+z,ee.w,ee.h)}}),Nt.useEffect(()=>{R(!1)},[k]);const Z=W4e({height:i,width:i},b);let J=null;return k!=null&&(J=Nt.createElement("img",{src:k,key:k,style:{display:"none"},onLoad:()=>{R(!0)},ref:E,crossOrigin:ee==null?void 0:ee.crossOrigin})),Nt.createElement(Nt.Fragment,null,Nt.createElement("canvas",W4e({style:Z,height:i,width:i,ref:A,role:"img"},j)),J)});j9s.displayName="QRCodeCanvas";var Vz=Nt.forwardRef(function(t,r){const n=t,{value:a,size:i=Byt,level:l=zyt,bgColor:o=$yt,fgColor:c=Uyt,includeMargin:d=qyt,minVersion:h=Vyt,boostLevel:m,title:p,marginSize:x,imageSettings:y}=n,_=K4e(n,["value","size","level","bgColor","fgColor","includeMargin","minVersion","boostLevel","title","marginSize","imageSettings"]),{margin:b,cells:j,numCells:k,calculatedImageSettings:T}=Wyt({value:a,level:l,minVersion:h,boostLevel:m,includeMargin:d,marginSize:x,imageSettings:y,size:i});let E=j,A=null;y!=null&&T!=null&&(T.excavation!=null&&(E=Gyt(j,T.excavation)),A=Nt.createElement("image",{href:y.src,height:T.h,width:T.w,x:T.x+b,y:T.y+b,preserveAspectRatio:"none",opacity:T.opacity,crossOrigin:T.crossOrigin}));const D=Hyt(E,b);return Nt.createElement("svg",W4e({height:i,width:i,viewBox:`0 0 ${k} ${k}`,ref:r,role:"img"},_),!!p&&Nt.createElement("title",null,p),Nt.createElement("path",{fill:o,d:`M0,0 h${k}v${k}H0z`,shapeRendering:"crispEdges"}),Nt.createElement("path",{fill:c,d:D,shapeRendering:"crispEdges"}),A)});Vz.displayName="QRCodeSVG";function N9s({slug:s,agentName:t}){const r=S.useRef(null),n=`https://cards.relevelup.com/${s}`,a=S.useCallback(()=>{var m;const i=(m=r.current)==null?void 0:m.querySelector("svg");if(!i)return;const l=document.createElement("canvas"),o=1024;l.width=o,l.height=o;const c=l.getContext("2d");if(!c)return;const d=new XMLSerializer().serializeToString(i),h=new Image;h.onload=()=>{c.fillStyle="#ffffff",c.fillRect(0,0,o,o),c.drawImage(h,0,0,o,o);const p=document.createElement("a");p.download=`${s}-qr-code.png`,p.href=l.toDataURL("image/png"),p.click(),he.success("QR code downloaded!")},h.src="data:image/svg+xml;base64,"+btoa(unescape(encodeURIComponent(d)))},[s]);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(ue,{className:"text-sm font-medium",children:"QR Code"}),e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{ref:r,className:"bg-white p-3 rounded-lg border shadow-sm shrink-0",children:e.jsx(Vz,{value:n,size:120,level:"H",bgColor:"#ffffff",fgColor:"#000000"})}),e.jsxs("div",{className:"space-y-2 min-w-0",children:[e.jsx("p",{className:"text-xs text-muted-foreground leading-relaxed",children:"Download this QR code to use on business cards, flyers, signs, or any print materials. Scanning it opens your digital card instantly."}),e.jsxs(H,{variant:"outline",size:"sm",onClick:a,className:"gap-1.5",children:[e.jsx(hi,{className:"h-3.5 w-3.5"}),"Download PNG"]})]})]})]})}function Swe(s){return{is_published:s.is_published,theme:s.theme,title:s.title||"",positioning_statement:s.positioning_statement||"",bio:s.bio||"",review_snippet:s.review_snippet||"",review_source_url:s.review_source_url||"",booking_url:s.booking_url||"",custom_cta_label:s.custom_cta_label||"",show_photo:s.show_photo,show_bio:s.show_bio,show_credentials:s.show_credentials,show_social_links:s.show_social_links,show_save_contact:s.show_save_contact,show_leave_review:s.show_leave_review,show_refer_friend:s.show_refer_friend,brokerage_display_name:s.brokerage_display_name||"",brokerage_logo_url:s.brokerage_logo_url||"",brokerage_logo_size:s.brokerage_logo_size||56,team_name:s.team_name||"",team_logo_url:s.team_logo_url||"",team_logo_size:s.team_logo_size||56,bold_theme_colors:s.bold_theme_colors||null,display_email:s.display_email||""}}function k9s(){const{user:s}=Ms(),{data:t,isLoading:r}=eLt(s==null?void 0:s.id),n=V8(),[a,i]=S.useState(null),l=S.useMemo(()=>a||(t?Swe(t):null),[a,t]);if(r)return e.jsx(Ss,{children:e.jsxs("div",{className:"max-w-2xl mx-auto p-4 space-y-4",children:[e.jsx(Ks,{className:"h-8 w-48"}),e.jsx(Ks,{className:"h-32 w-full"}),e.jsx(Ks,{className:"h-32 w-full"})]})});if(!t)return e.jsx(Ss,{children:e.jsx(C9s,{userId:s==null?void 0:s.id})});const o=l||Swe(t),c=d=>{i(h=>{const m=h||Swe(t);return typeof d=="function"?d(m):d})};return e.jsx(Ss,{children:e.jsxs("div",{className:"flex gap-6 items-start",children:[e.jsxs("div",{className:`${n?"w-full":"flex-1 min-w-0"} max-w-2xl p-4 space-y-6 animate-fade-in`,children:[e.jsx(T9s,{card:t}),e.jsx(I9s,{card:t,form:o,setForm:c})]}),!n&&e.jsx("div",{className:"w-[400px] shrink-0","aria-hidden":"true"}),!n&&e.jsx("div",{className:"fixed right-8 top-[5.5rem] w-[400px] z-30",style:{height:"calc(100vh - 6.5rem)"},children:e.jsxs("div",{className:"rounded-xl border bg-muted/30 overflow-hidden h-full flex flex-col",children:[e.jsxs("div",{className:"flex items-center gap-2 px-4 py-2.5 border-b bg-card shrink-0",children:[e.jsx(Vk,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-sm font-medium",children:"Live Preview"})]}),e.jsx("div",{className:"flex-1 overflow-y-auto",children:e.jsx(S9s,{card:t,form:o})})]})})]})})}function S9s({card:s,form:t}){const{data:r}=yt({queryKey:["card-preview-profile",s.user_id],queryFn:async()=>{const{data:a}=await V.from("profiles").select("name, email, phone, avatar_url, brokerage_id").eq("id",s.user_id).single();let i=(a==null?void 0:a.avatar_url)||null;if(!i){const{data:l}=await V.storage.from("avatars").list(`${s.user_id}`);if(l&&l.length>0){const{data:o}=V.storage.from("avatars").getPublicUrl(`${s.user_id}/${l[0].name}`);i=`${o.publicUrl}?t=${Date.now()}`}}return{...a,avatar_url:i}}}),n=S.useMemo(()=>({...s,is_published:t.is_published,theme:t.theme,title:t.title||null,positioning_statement:t.positioning_statement||null,bio:t.bio||null,review_snippet:t.review_snippet||null,review_source_url:t.review_source_url||null,booking_url:t.booking_url||null,custom_cta_label:t.custom_cta_label||null,custom_cta_url:s.custom_cta_url,show_photo:t.show_photo,show_bio:t.show_bio,show_video:s.show_video,show_credentials:t.show_credentials,show_social_links:t.show_social_links,show_save_contact:t.show_save_contact,show_leave_review:t.show_leave_review,show_refer_friend:t.show_refer_friend,brokerage_display_name:t.brokerage_display_name||null,brokerage_logo_url:t.brokerage_logo_url||null,brokerage_logo_size:t.brokerage_logo_size,team_name:t.team_name||null,team_logo_url:t.team_logo_url||null,team_logo_size:t.team_logo_size,display_email:t.display_email||null,social_links:s.social_links||[],profile:{name:(r==null?void 0:r.name)||null,email:t.display_email||(r==null?void 0:r.email)||null,phone:(r==null?void 0:r.phone)||null,brokerage_id:(r==null?void 0:r.brokerage_id)||null},brokerage_name:t.brokerage_display_name||null,avatar_url:(r==null?void 0:r.avatar_url)||null}),[s,t,r]);return e.jsx("div",{className:"transform scale-[0.85] origin-top",children:e.jsx(o5e,{card:n})})}function C9s({userId:s}){var c;const[t,r]=S.useState(""),n=Yst(),{data:a}=yt({queryKey:["my-profile-for-card",s],queryFn:async()=>{if(!s)return null;const{data:d}=await V.from("profiles").select("name").eq("id",s).single();return d},enabled:!!s}),i=((c=a==null?void 0:a.name)==null?void 0:c.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,""))||"",l=()=>{if(!s)return;const d=(t.trim()||i).toLowerCase().replace(/[^a-z0-9-]/g,"-");if(!d){he.error("Please enter a URL slug for your card");return}n.mutate({user_id:s,slug:d,is_published:!0},{onSuccess:()=>he.success("Your digital card has been created!")})},o=[{icon:ld,title:"Shareable Link",desc:"One link that works everywhere"},{icon:ym,title:"Lead Capture",desc:"Collect leads automatically"},{icon:Fh,title:"Always Up-to-Date",desc:"Edit anytime, changes are instant"},{icon:pl,title:"Fully Customizable",desc:"Themes, colors, and content blocks"}];return e.jsxs("div",{className:"max-w-2xl mx-auto p-4 animate-fade-in",children:[e.jsxs("div",{className:"relative overflow-hidden rounded-2xl bg-gradient-to-br from-primary/90 via-primary to-primary/80 p-8 md:p-12 mb-8 text-primary-foreground",children:[e.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(circle_at_30%_20%,rgba(255,255,255,0.15),transparent_50%)]"}),e.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(circle_at_80%_80%,rgba(0,0,0,0.1),transparent_50%)]"}),e.jsxs("div",{className:"relative z-10",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 px-3 py-1 rounded-full bg-white/20 backdrop-blur-sm text-sm font-medium mb-4",children:[e.jsx(Lr,{className:"h-3.5 w-3.5"}),"New Feature"]}),e.jsx("h1",{className:"text-3xl md:text-4xl font-bold mb-3 tracking-tight",children:"Your Digital Business Card"}),e.jsx("p",{className:"text-primary-foreground/80 text-lg max-w-md leading-relaxed",children:"Ditch the paper. Share a beautiful, interactive card that captures leads and makes a lasting impression."})]})]}),e.jsx("div",{className:"grid grid-cols-2 gap-3 mb-8",children:o.map(d=>e.jsxs("div",{className:"flex items-start gap-3 p-4 rounded-xl border bg-card hover:shadow-md transition-shadow",children:[e.jsx("div",{className:"mt-0.5 p-2 rounded-lg bg-primary/10 shrink-0",children:e.jsx(d.icon,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-sm",children:d.title}),e.jsx("p",{className:"text-xs text-muted-foreground",children:d.desc})]})]},d.title))}),e.jsxs(ke,{className:"shadow-lg border-2",children:[e.jsxs(Ot,{className:"text-center pb-2",children:[e.jsx(zt,{className:"text-xl",children:"Set Up Your Card"}),e.jsx(Br,{children:"Choose a URL slug — this is the link you'll share with clients"})]}),e.jsxs(Oe,{className:"p-6 pt-2 space-y-5",children:[e.jsxs("div",{children:[e.jsx(ue,{className:"text-sm font-medium",children:"Your Card URL"}),e.jsxs("div",{className:"flex items-center gap-0 mt-1.5",children:[e.jsx("span",{className:"inline-flex items-center px-3 h-10 rounded-l-md border border-r-0 bg-muted text-sm text-muted-foreground whitespace-nowrap",children:"cards.relevelup.com/"}),e.jsx(Se,{value:t||i,onChange:d=>r(d.target.value),placeholder:"your-name",className:"rounded-l-none"})]})]}),e.jsxs(H,{onClick:l,disabled:n.isPending,className:"w-full h-11 text-base font-semibold",size:"lg",children:[e.jsx(Lr,{className:"h-4 w-4 mr-2"}),n.isPending?"Creating...":"Create My Card"]})]})]})]})}function T9s({card:s}){const r=`https://cards.relevelup.com/${s.slug}`,n=()=>{navigator.clipboard.writeText(r),he.success("Card link copied!")};return e.jsx("div",{className:"rounded-xl border bg-card p-5",children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h1",{className:"text-xl font-bold",children:"My Digital Card"}),e.jsx(Xe,{variant:s.is_published?"default":"secondary",className:"text-[10px] uppercase tracking-wider",children:s.is_published?"Live":"Draft"})]}),e.jsxs("p",{className:"text-sm text-muted-foreground flex items-center gap-1",children:[e.jsx(ld,{className:"h-3.5 w-3.5"}),"cards.relevelup.com/",s.slug]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(H,{variant:"outline",size:"sm",onClick:n,className:"gap-1.5",children:[e.jsx(ui,{className:"h-3.5 w-3.5"})," Copy Link"]}),e.jsx(H,{size:"sm",asChild:!0,className:"gap-1.5",children:e.jsxs("a",{href:r,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(gn,{className:"h-3.5 w-3.5"})," Preview"]})})]})]})})}function E9s({userId:s}){const t=ns(),r=S.useRef(null),[n,a]=S.useState(!1),[i,l]=S.useState(""),{data:o,isLoading:c}=yt({queryKey:["card-editor-profile",s],queryFn:async()=>{const{data:ee}=await V.from("profiles").select("name, email, phone, avatar_url").eq("id",s).single();let Z=(ee==null?void 0:ee.avatar_url)||null;if(!Z){const{data:J}=await V.storage.from("avatars").list(`${s}`);if(J&&J.length>0){const{data:K}=V.storage.from("avatars").getPublicUrl(`${s}/${J[0].name}`);Z=`${K.publicUrl}?t=${Date.now()}`,await V.from("profiles").update({avatar_url:Z}).eq("id",s)}}return{...ee,avatar_url:Z}}}),[d,h]=S.useState(null),[m,p]=S.useState(null),[x,y]=S.useState(null),[_,b]=S.useState(!1),j=d??(o==null?void 0:o.name)??"",k=m??(o==null?void 0:o.phone)??"",T=x??(o==null?void 0:o.email)??"",E=o==null?void 0:o.avatar_url,A=((o==null?void 0:o.name)||"A").split(" ").map(ee=>ee[0]).join("").toUpperCase().slice(0,2),D=!(o!=null&&o.avatar_url)||!(o!=null&&o.phone),R=Pt({mutationFn:async ee=>{const{error:Z}=await V.from("profiles").update(ee).eq("id",s);if(Z)throw Z},onSuccess:()=>{t.invalidateQueries({queryKey:["card-editor-profile",s]}),t.invalidateQueries({queryKey:["card-preview-profile",s]}),t.invalidateQueries({queryKey:["agent-card-user"]}),he.success("Profile updated!")},onError:()=>he.error("Failed to update profile")}),z=()=>{const ee={};if(d!==null&&d!==(o==null?void 0:o.name)&&(ee.name=d),m!==null&&m!==(o==null?void 0:o.phone)&&(ee.phone=m||null),x!==null&&x!==(o==null?void 0:o.email)&&(ee.email=x),Object.keys(ee).length===0){he.info("No changes to save");return}R.mutate(ee)},O=ee=>{var K;const Z=(K=ee.target.files)==null?void 0:K[0];if(!Z)return;if(!Z.type.startsWith("image/")){he.error("Please select an image file");return}const J=new FileReader;J.onloadend=()=>{l(J.result),a(!0)},J.readAsDataURL(Z),ee.target.value=""},$=async ee=>{b(!0);try{const{data:Z}=await V.storage.from("avatars").list(`${s}`);Z&&Z.length>0&&await V.storage.from("avatars").remove(Z.map(ce=>`${s}/${ce.name}`));const J=`${s}/avatar.jpg`,{error:K}=await V.storage.from("avatars").upload(J,ee,{upsert:!0,contentType:"image/jpeg"});if(K)throw K;const{data:re}=V.storage.from("avatars").getPublicUrl(J),ie=re.publicUrl+"?t="+Date.now();await V.from("profiles").update({avatar_url:ie}).eq("id",s),t.invalidateQueries({queryKey:["card-editor-profile",s]}),t.invalidateQueries({queryKey:["card-preview-profile",s]}),t.invalidateQueries({queryKey:["agent-card-user"]}),he.success("Photo updated!")}catch{he.error("Failed to upload photo")}finally{b(!1)}};return c?e.jsx(Ks,{className:"h-32 w-full rounded-xl"}):e.jsxs(e.Fragment,{children:[e.jsx(ke,{className:D?"border-amber-300 dark:border-amber-700":"",children:e.jsxs(Oe,{className:"p-5 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(ue,{className:"text-sm font-semibold",children:"Profile Info"}),D&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-amber-600 dark:text-amber-400 font-medium",children:[e.jsx(wo,{className:"h-3 w-3"}),"Missing info — complete below so your card looks great"]})]}),e.jsx("p",{className:"text-xs text-muted-foreground -mt-3",children:"This info shows on your digital card and updates your profile everywhere."}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"relative group cursor-pointer",onClick:()=>{var ee;return(ee=r.current)==null?void 0:ee.click()},children:[e.jsxs(Un,{className:"h-16 w-16 ring-2 ring-muted",children:[e.jsx(Ka,{src:E||void 0,alt:j}),e.jsx(qn,{className:"text-lg font-semibold bg-primary/10 text-primary",children:A})]}),e.jsx("div",{className:"absolute inset-0 bg-black/40 rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx(lx,{className:"h-5 w-5 text-white"})}),e.jsx("input",{ref:r,type:"file",accept:"image/*",className:"hidden",onChange:O})]}),e.jsxs("div",{className:"flex-1 space-y-0.5",children:[e.jsx("p",{className:"text-sm font-medium",children:_?"Uploading...":E?"Tap to change photo":"Add a profile photo"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This photo appears on your card, profile, and community posts"})]})]}),e.jsxs("div",{className:"grid gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{className:"text-xs font-medium text-muted-foreground",children:"Full Name"}),e.jsx(Se,{value:j,onChange:ee=>h(ee.target.value),placeholder:"Your full name",className:"h-10"})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{className:"text-xs font-medium text-muted-foreground",children:"Phone Number"}),e.jsx(Se,{value:k,onChange:ee=>p(ee.target.value),placeholder:"(555) 123-4567",className:"h-10",type:"tel"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{className:"text-xs font-medium text-muted-foreground",children:"Email"}),e.jsx(Se,{value:T,onChange:ee=>y(ee.target.value),placeholder:"you@example.com",className:"h-10",type:"email"})]})]})]}),e.jsx(H,{variant:"outline",size:"sm",onClick:z,disabled:R.isPending,className:"w-full",children:R.isPending?"Saving...":"Update Profile Info"})]})}),e.jsx(fEe,{open:n,onClose:()=>a(!1),imageSrc:i,onCropComplete:$,aspectRatio:1})]})}function A9s({form:s,setForm:t,userId:r}){const[n,a]=S.useState(null),[i,l]=S.useState(s.brokerage_logo_url?"logo":"name"),[o,c]=S.useState(s.team_logo_url?"logo":"name"),d=x=>{l(x),t(x==="name"?y=>({...y,brokerage_logo_url:""}):y=>({...y,brokerage_display_name:""}))},h=x=>{c(x),t(x==="name"?y=>({...y,team_logo_url:""}):y=>({...y,team_name:""}))},m=async(x,y)=>{var b;const _=(b=x.target.files)==null?void 0:b[0];if(_){if(!_.type.startsWith("image/")){he.error("Please select an image file");return}a(y);try{const j=_.name.split(".").pop()||"png",T=`${r}/${y==="brokerage_logo_url"?"brokerage-logo":"team-logo"}.${j}`,{error:E}=await V.storage.from("card-logos").upload(T,_,{upsert:!0});if(E)throw E;const{data:A}=V.storage.from("card-logos").getPublicUrl(T),D=A.publicUrl+"?t="+Date.now();t(y==="brokerage_logo_url"?R=>({...R,[y]:D,brokerage_display_name:""}):R=>({...R,[y]:D,team_name:""})),he.success("Logo uploaded!")}catch{he.error("Failed to upload logo")}finally{a(null),x.target.value=""}}},p=x=>{t(y=>({...y,[x]:""}))};return e.jsx(ke,{children:e.jsxs(Oe,{className:"p-5 space-y-5",children:[e.jsxs("div",{children:[e.jsx(ue,{className:"text-sm font-semibold",children:"Brokerage & Team Branding"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:"Choose either a name or a logo for each — not both."})]}),e.jsxs("div",{className:"space-y-3 p-3 rounded-lg bg-muted/30 border",children:[e.jsx(ue,{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Brokerage"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(H,{type:"button",variant:i==="name"?"default":"outline",size:"sm",className:"text-xs",onClick:()=>d("name"),children:"Use Name"}),e.jsx(H,{type:"button",variant:i==="logo"?"default":"outline",size:"sm",className:"text-xs",onClick:()=>d("logo"),children:"Use Logo"})]}),i==="name"?e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{className:"text-xs font-medium text-muted-foreground",children:"Brokerage Name"}),e.jsx(Se,{value:s.brokerage_display_name,onChange:x=>t(y=>({...y,brokerage_display_name:x.target.value})),placeholder:"e.g. Keller Williams Realty",className:"h-10"})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsx(ue,{className:"text-xs font-medium text-muted-foreground",children:"Brokerage Logo"}),e.jsxs("div",{className:"flex items-center gap-3",children:[s.brokerage_logo_url?e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:s.brokerage_logo_url,alt:"Brokerage logo",style:{height:`${s.brokerage_logo_size||56}px`},className:"max-w-[200px] object-contain rounded border bg-white p-1"}),e.jsx("button",{onClick:()=>p("brokerage_logo_url"),className:"absolute -top-1.5 -right-1.5 h-5 w-5 rounded-full bg-destructive text-destructive-foreground text-xs flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity",children:"×"})]}):null,e.jsxs("label",{className:"cursor-pointer",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 px-3 py-1.5 rounded-md border text-xs font-medium hover:bg-muted transition-colors",children:[e.jsx(lx,{className:"h-3.5 w-3.5"}),n==="brokerage_logo_url"?"Uploading...":s.brokerage_logo_url?"Change":"Upload Logo"]}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:x=>m(x,"brokerage_logo_url"),disabled:n!==null})]})]}),s.brokerage_logo_url&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ue,{className:"text-xs font-medium text-muted-foreground",children:"Logo Size"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[s.brokerage_logo_size||56,"px"]})]}),e.jsx(f1,{value:[s.brokerage_logo_size||56],onValueChange:([x])=>t(y=>({...y,brokerage_logo_size:x})),min:24,max:120,step:4})]})]})]}),e.jsxs("div",{className:"space-y-3 p-3 rounded-lg bg-muted/30 border",children:[e.jsx(ue,{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Team"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(H,{type:"button",variant:o==="name"?"default":"outline",size:"sm",className:"text-xs",onClick:()=>h("name"),children:"Use Name"}),e.jsx(H,{type:"button",variant:o==="logo"?"default":"outline",size:"sm",className:"text-xs",onClick:()=>h("logo"),children:"Use Logo"})]}),o==="name"?e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{className:"text-xs font-medium text-muted-foreground",children:"Team Name"}),e.jsx(Se,{value:s.team_name,onChange:x=>t(y=>({...y,team_name:x.target.value})),placeholder:"e.g. The Smith Group",className:"h-10"})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsx(ue,{className:"text-xs font-medium text-muted-foreground",children:"Team Logo"}),e.jsxs("div",{className:"flex items-center gap-3",children:[s.team_logo_url?e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:s.team_logo_url,alt:"Team logo",style:{height:`${s.team_logo_size||56}px`},className:"max-w-[200px] object-contain rounded border bg-white p-1"}),e.jsx("button",{onClick:()=>p("team_logo_url"),className:"absolute -top-1.5 -right-1.5 h-5 w-5 rounded-full bg-destructive text-destructive-foreground text-xs flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity",children:"×"})]}):null,e.jsxs("label",{className:"cursor-pointer",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 px-3 py-1.5 rounded-md border text-xs font-medium hover:bg-muted transition-colors",children:[e.jsx(lx,{className:"h-3.5 w-3.5"}),n==="team_logo_url"?"Uploading...":s.team_logo_url?"Change":"Upload Logo"]}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:x=>m(x,"team_logo_url"),disabled:n!==null})]})]}),s.team_logo_url&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ue,{className:"text-xs font-medium text-muted-foreground",children:"Logo Size"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[s.team_logo_size||56,"px"]})]}),e.jsx(f1,{value:[s.team_logo_size||56],onValueChange:([x])=>t(y=>({...y,team_logo_size:x})),min:24,max:120,step:4})]})]})]})]})})}function M9s({form:s,setForm:t}){const r={accent:"#ff5722",dark:"#1a1a2e",button:"#ff5722"},n=s.bold_theme_colors||r,a=(o,c)=>{t(d=>({...d,bold_theme_colors:{...r,...d.bold_theme_colors,[o]:c}}))},i=()=>{t(o=>({...o,bold_theme_colors:null}))},l=[{key:"accent",label:"Accent Color",desc:"Page background, icons, highlights"},{key:"dark",label:"Dark Color",desc:"Header background, action buttons, social icons"},{key:"button",label:"CTA Button Color",desc:"Main call-to-action button"}];return e.jsxs("div",{className:"space-y-3 p-4 rounded-xl border bg-muted/30",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(ue,{className:"text-sm font-semibold flex items-center gap-1.5",children:[e.jsx(pl,{className:"h-4 w-4"})," Brand Colors"]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:"Customize colors to match your brand"})]}),e.jsx(H,{variant:"ghost",size:"sm",className:"text-xs h-7",onClick:i,children:"Reset to Default"})]}),e.jsx("div",{className:"grid gap-3",children:l.map(({key:o,label:c,desc:d})=>e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("label",{className:"relative shrink-0",children:[e.jsx("input",{type:"color",value:n[o],onChange:h=>a(o,h.target.value),className:"sr-only"}),e.jsx("div",{className:"h-10 w-10 rounded-lg border-2 border-border cursor-pointer shadow-sm hover:scale-105 transition-transform",style:{backgroundColor:n[o]}})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium",children:c}),e.jsx("p",{className:"text-xs text-muted-foreground",children:d})]}),e.jsx(Se,{value:n[o],onChange:h=>{const m=h.target.value;/^#[0-9a-fA-F]{0,6}$/.test(m)&&a(o,m)},className:"w-24 h-8 text-xs font-mono",placeholder:"#ff5722"})]},o))}),e.jsxs("div",{className:"flex items-center gap-2 pt-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Preview:"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx("div",{className:"h-6 w-12 rounded",style:{backgroundColor:n.accent}}),e.jsx("div",{className:"h-6 w-12 rounded",style:{backgroundColor:n.dark}}),e.jsx("div",{className:"h-6 w-12 rounded",style:{backgroundColor:n.button}})]})]})]})}function I9s({card:s,form:t,setForm:r}){var _;const n=Zst(),a=ns(),{data:i}=Xst(s.id),[l,o]=S.useState(s.slug),[c,d]=S.useState(!1),[h,m]=S.useState("idle"),p=S.useRef(JSON.stringify(t)),x=S.useRef(null);S.useEffect(()=>{const b=JSON.stringify(t);if(b!==p.current)return x.current&&clearTimeout(x.current),x.current=setTimeout(()=>{m("saving"),n.mutate({id:s.id,...t,is_published:!0,title:t.title||null,positioning_statement:t.positioning_statement||null,bio:t.bio||null,review_snippet:t.review_snippet||null,review_source_url:t.review_source_url||null,booking_url:t.booking_url||null,custom_cta_label:t.custom_cta_label||null,brokerage_display_name:t.brokerage_display_name||null,brokerage_logo_url:t.brokerage_logo_url||null,brokerage_logo_size:t.brokerage_logo_size,team_name:t.team_name||null,team_logo_url:t.team_logo_url||null,team_logo_size:t.team_logo_size,bold_theme_colors:t.bold_theme_colors||null,display_email:t.display_email||null},{onSuccess:()=>{p.current=b,m("saved"),setTimeout(()=>m("idle"),2e3)},onError:()=>m("idle")})},1500),()=>{x.current&&clearTimeout(x.current)}},[t]);const y=async()=>{const b=l.trim().toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/(^-|-$)/g,"");if(!b){he.error("Please enter a valid URL");return}if(b===s.slug){he.info("No changes to save");return}d(!0);try{const{data:j}=await V.from("agent_cards").select("id").eq("slug",b).neq("id",s.id).maybeSingle();if(j){he.error("This URL is already taken. Try another one.");return}const{error:k}=await V.from("agent_cards").update({slug:b}).eq("id",s.id);if(k)throw k;o(b),a.invalidateQueries({queryKey:["agent-card"]}),he.success("Card address updated!")}catch{he.error("Failed to update card address")}finally{d(!1)}};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs(ta,{defaultValue:"content",children:[e.jsxs(Qn,{className:"w-full h-11 p-1",children:[e.jsxs(ts,{value:"content",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(u0,{className:"h-3.5 w-3.5 hidden sm:inline"}),"Content"]}),e.jsxs(ts,{value:"sections",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(Bn,{className:"h-3.5 w-3.5 hidden sm:inline"}),"Sections"]}),e.jsxs(ts,{value:"blocks",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(ym,{className:"h-3.5 w-3.5 hidden sm:inline"}),"Blocks"]}),e.jsxs(ts,{value:"qrcode",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(y_,{className:"h-3.5 w-3.5 hidden sm:inline"}),"QR Code"]}),e.jsxs(ts,{value:"analytics",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(Kd,{className:"h-3.5 w-3.5 hidden sm:inline"}),"Analytics"]})]}),e.jsxs(cs,{value:"content",className:"mt-4 space-y-4",children:[e.jsx(E9s,{userId:s.user_id}),e.jsx(A9s,{form:t,setForm:r,userId:s.user_id}),e.jsx(ke,{children:e.jsxs(Oe,{className:"p-5 space-y-5",children:[e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg bg-muted/50",children:[e.jsxs("div",{children:[e.jsx(ue,{className:"text-sm font-semibold",children:"Card Status"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Toggle your card on or off"})]}),e.jsx(Or,{checked:t.is_published,onCheckedChange:b=>r(j=>({...j,is_published:b}))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{className:"text-sm font-medium",children:"Card Address"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"flex flex-1",children:[e.jsx("span",{className:"inline-flex items-center px-3 rounded-l-md border border-r-0 bg-muted text-muted-foreground text-xs whitespace-nowrap",children:"cards.relevelup.com/"}),e.jsx(Se,{value:l,onChange:b=>o(b.target.value.toLowerCase().replace(/[^a-z0-9-]/g,"-")),placeholder:"your-name",className:"rounded-l-none h-10"})]}),e.jsx(H,{variant:"outline",size:"sm",onClick:y,disabled:c||l===s.slug,className:"shrink-0",children:c?"Saving...":"Update"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This is your unique card URL. Only letters, numbers, and dashes allowed."})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{className:"text-sm font-medium",children:"Card Email (Override)"}),e.jsx(Se,{value:t.display_email,onChange:b=>r(j=>({...j,display_email:b.target.value})),placeholder:"you@yourbusiness.com",className:"h-11",type:"email"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Optional — use a different email on your card instead of your sign-in email."})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{className:"text-sm font-medium",children:"Theme"}),e.jsxs(Bs,{value:t.theme,onValueChange:b=>r(j=>({...j,theme:b})),children:[e.jsx(Os,{className:"h-11",children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"standard",children:"✨ Standard — Modern & Clean"}),e.jsx(pt,{value:"luxury",children:"🌙 Luxury — Dark & Gold"}),e.jsx(pt,{value:"bold",children:"🔥 Bold — Vibrant & Punchy"}),e.jsx(pt,{value:"classic",children:"📋 Classic — Professional"})]})]})]}),t.theme==="bold"&&e.jsx(M9s,{form:t,setForm:r}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{className:"text-sm font-medium",children:"Title / Tagline"}),e.jsx(Se,{value:t.title,onChange:b=>r(j=>({...j,title:b.target.value})),placeholder:"e.g. Luxury Real Estate Specialist",className:"h-11"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Shown below your name on the card"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{className:"text-sm font-medium",children:"Positioning Statement"}),e.jsx(Se,{value:t.positioning_statement,onChange:b=>r(j=>({...j,positioning_statement:b.target.value})),placeholder:"Your home journey, handled with care.",className:"h-11"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{className:"text-sm font-medium",children:"Bio"}),e.jsx(vr,{value:t.bio,onChange:b=>r(j=>({...j,bio:b.target.value})),placeholder:"A short intro about you and what makes you different...",rows:3})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{className:"text-sm font-medium",children:"Review Snippet"}),e.jsx(Se,{value:t.review_snippet,onChange:b=>r(j=>({...j,review_snippet:b.target.value})),placeholder:"Best agent we've ever worked with...",className:"h-11"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{className:"text-sm font-medium",children:"Review Source URL"}),e.jsx(Se,{value:t.review_source_url,onChange:b=>r(j=>({...j,review_source_url:b.target.value})),placeholder:"https://g.page/your-business/review",className:"h-11"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{className:"text-sm font-medium",children:"Booking URL"}),e.jsx(Se,{value:t.booking_url,onChange:b=>r(j=>({...j,booking_url:b.target.value})),placeholder:"https://calendly.com/your-link",className:"h-11"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Leave empty to show a built-in lead form instead"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{className:"text-sm font-medium",children:"Custom CTA Label"}),e.jsx(Se,{value:t.custom_cta_label,onChange:b=>r(j=>({...j,custom_cta_label:b.target.value})),placeholder:"Book a Call",className:"h-11"})]})]})})]}),e.jsx(cs,{value:"sections",className:"mt-4",children:e.jsx(ke,{children:e.jsx(Oe,{className:"p-5 divide-y",children:[{key:"show_photo",label:"Photo",desc:"Uses the photo from your Profile Info above"},{key:"show_bio",label:"Bio Section",desc:"Display your bio on the card"},{key:"show_credentials",label:"Credentials",desc:"Show star rating and reviews"},{key:"show_social_links",label:"Social Links",desc:"Display your social media links"},{key:"show_save_contact",label:"Save Contact",desc:"Let visitors save you as a contact"},{key:"show_leave_review",label:"Leave Review",desc:"Link to your review page"},{key:"show_refer_friend",label:"Refer a Friend",desc:"Enable referral submissions"}].map(({key:b,label:j,desc:k})=>e.jsxs("div",{className:"flex items-center justify-between py-4 first:pt-0 last:pb-0",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(ue,{className:"text-sm font-medium",children:j}),e.jsx("p",{className:"text-xs text-muted-foreground",children:k})]}),e.jsx(Or,{checked:t[b],onCheckedChange:T=>r(E=>({...E,[b]:T}))})]},b))})})}),e.jsx(cs,{value:"blocks",className:"mt-4",children:e.jsx(Ryt,{cardId:s.id})}),e.jsx(cs,{value:"analytics",className:"mt-4",children:e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"grid grid-cols-3 gap-3",children:[{label:"Views",value:(i==null?void 0:i.views)??0,icon:Bn,color:"text-blue-600 bg-blue-100 dark:text-blue-400 dark:bg-blue-900/30"},{label:"Clicks",value:(i==null?void 0:i.clicks)??0,icon:Kd,color:"text-amber-600 bg-amber-100 dark:text-amber-400 dark:bg-amber-900/30"},{label:"Leads",value:((_=i==null?void 0:i.leads)==null?void 0:_.length)??0,icon:Vl,color:"text-emerald-600 bg-emerald-100 dark:text-emerald-400 dark:bg-emerald-900/30"}].map(b=>e.jsx(ke,{className:"overflow-hidden",children:e.jsxs(Oe,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("div",{className:`p-1.5 rounded-md ${b.color}`,children:e.jsx(b.icon,{className:"h-3.5 w-3.5"})}),e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:b.label})]}),e.jsx("div",{className:"text-2xl font-bold",children:b.value})]})},b.label))}),i&&i.leads.length>0&&e.jsxs(ke,{children:[e.jsx(Ot,{className:"pb-3",children:e.jsx(zt,{className:"text-base",children:"Recent Leads"})}),e.jsx(Oe,{className:"pt-0 space-y-2",children:i.leads.slice(0,5).map(b=>e.jsxs("div",{className:"flex items-center justify-between text-sm p-3 rounded-lg bg-muted/50",children:[e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:b.name}),b.phone&&e.jsx("span",{className:"text-muted-foreground ml-2",children:b.phone})]}),b.intent&&e.jsx(Xe,{variant:"secondary",className:"text-xs",children:b.intent})]},b.id))})]}),(!i||i.leads.length===0)&&e.jsx(ke,{children:e.jsxs(Oe,{className:"p-8 text-center",children:[e.jsx(Kd,{className:"h-10 w-10 text-muted-foreground/40 mx-auto mb-3"}),e.jsx("p",{className:"font-medium text-muted-foreground",children:"No analytics data yet"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Share your card link to start tracking"})]})})]})}),e.jsx(cs,{value:"qrcode",className:"mt-4 space-y-4",children:e.jsx(ke,{children:e.jsx(Oe,{className:"p-6",children:e.jsx(N9s,{slug:s.slug})})})})]}),e.jsxs("div",{className:"flex items-center justify-center gap-2 py-2 text-sm text-muted-foreground",children:[h==="saving"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-amber-400 animate-pulse"})," Saving..."]}),h==="saved"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-green-500"})," All changes saved"]}),h==="idle"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-muted-foreground/30"})," Changes auto-save"]})]})]})}function P9s(){const s=ns(),[t,r]=S.useState(""),[n,a]=S.useState(!1),[i,l]=S.useState(!1),[o,c]=S.useState(null),[d,h]=S.useState(!1),[m,p]=S.useState(!1),[x,y]=S.useState(null),[_,b]=S.useState(null),[j,k]=S.useState(0),[T,E]=S.useState(""),[A,D]=S.useState(!1),{data:R,isLoading:z}=yt({queryKey:["boldtrail-status"],queryFn:async()=>{const{data:le,error:be}=await V.functions.invoke("boldtrail-sync",{body:{action:"status"}});if(be)throw be;return le}}),O=Pt({mutationFn:async le=>{const{data:be,error:fe}=await V.functions.invoke("boldtrail-sync",{body:{action:"save_token",api_token:le}});if(fe)throw fe;if(be!=null&&be.error)throw new Error(be.error);return be},onSuccess:()=>{s.invalidateQueries({queryKey:["boldtrail-status"]}),r(""),he.success("BoldTrail connected successfully!")},onError:le=>{he.error(le.message||"Failed to connect BoldTrail")}}),$=Pt({mutationFn:async()=>{const{data:le,error:be}=await V.functions.invoke("boldtrail-sync",{body:{action:"disconnect"}});if(be)throw be;return le},onSuccess:()=>{s.invalidateQueries({queryKey:["boldtrail-status"]}),he.success("BoldTrail disconnected")},onError:()=>he.error("Failed to disconnect")}),ee=Pt({mutationFn:async le=>{const{data:be,error:fe}=await V.functions.invoke("boldtrail-sync",{body:{action:"save_direction",sync_direction:le}});if(fe)throw fe;if(be!=null&&be.error)throw new Error(be.error);return be},onSuccess:()=>{s.invalidateQueries({queryKey:["boldtrail-status"]}),he.success("Sync direction saved")},onError:le=>{he.error(le.message||"Failed to save sync direction")}}),Z=Pt({mutationFn:async()=>{const{data:le,error:be}=await V.functions.invoke("boldtrail-sync",{body:{action:"detect_owner"}});if(be)throw be;if(le!=null&&le.error)throw new Error(le.error);return le},onSuccess:le=>{if(s.invalidateQueries({queryKey:["boldtrail-status"]}),le.kvcore_user_id){const be=le.detected_name||le.detected_email||`ID ${le.kvcore_user_id}`;he.success(`Detected your BoldTrail account: ${be}`)}else if(le.candidates&&le.candidates.length>0){const be=le.candidates.slice(0,5).map(fe=>`${fe.id} (${fe.count} contacts)`).join(", ");he.warning(`Couldn't auto-detect your ID. Owner IDs found in your contacts: ${be}. Pick yours and enter it below.`,{duration:12e3}),D(!0)}else he.warning("Couldn't auto-detect your BoldTrail user ID. Please find it in BoldTrail (My Profile URL) and enter it manually."),D(!0)},onError:le=>he.error(le.message||"Detection failed")}),J=Pt({mutationFn:async le=>{const{data:be,error:fe}=await V.functions.invoke("boldtrail-sync",{body:{action:"save_owner_settings",...le}});if(fe)throw fe;if(be!=null&&be.error)throw new Error(be.error);return be},onSuccess:()=>{s.invalidateQueries({queryKey:["boldtrail-status"]}),he.success("Settings saved"),D(!1)},onError:le=>he.error(le.message||"Failed to save settings")}),K=Pt({mutationFn:async()=>{const{data:le,error:be}=await V.functions.invoke("boldtrail-sync",{body:{action:"sync_preview"}});if(be)throw be;if(le!=null&&le.error)throw new Error(le.error);return le},onSuccess:le=>{y(null),c(le),a(!0)},onError:le=>{he.error(le.message||"Failed to generate sync preview")}}),re=Pt({mutationFn:async()=>{b("Initializing sync..."),k(5);const{data:le,error:be}=await V.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:"init",sync_direction:ne}});if(be)throw be;if(le!=null&&le.error)throw new Error(le.error);const fe=le;let je=fe.sync_log_id,ve=fe.next_phase,We=fe.next_offset,Ve=fe.push_total||0,Le=fe.pull_total||0,Me=0,ze=0;for(;ve!=="finalize";){const De=Ve+Le;ve==="fetch_bt"?b("Fetching BoldTrail contacts..."):ve==="analyze"?(b("Analyzing contacts..."),k(15)):ve==="push"?(b(`Pushing contacts to BoldTrail... (${Me}/${Ve})`),k(De>0?Me/De*100:0)):ve==="pull"&&(b(`Pulling contacts from BoldTrail... (${ze}/${Le})`),k(De>0?(Ve+ze)/De*100:0));const{data:pe,error:tt}=await V.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:ve,offset:We,sync_log_id:je,sync_direction:ne}});if(tt)throw tt;if(pe!=null&&pe.error)throw new Error(pe.error);const ge=pe;Me+=ge.chunk_pushed||0,ze+=ge.chunk_pulled||0,ge.push_total!==void 0&&(Ve=ge.push_total||0),ge.pull_total!==void 0&&(Le=ge.pull_total||0),ge.progress&&b(ge.progress),ve==="pull"&&Le>0?k(Math.min(95,ze/Le*100)):ve==="push"&&Ve>0&&k(Math.min(95,Me/Ve*100)),ve=ge.next_phase,We=ge.next_offset}b("Finalizing sync..."),k(95);const{data:Pe,error:Ie}=await V.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:"finalize",sync_log_id:je,sync_direction:ne}});if(Ie)throw Ie;return k(100),Pe},onSuccess:le=>{b(null),k(0),a(!1),s.invalidateQueries({queryKey:["boldtrail-status"]}),s.invalidateQueries({queryKey:["contacts"]}),s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact-counts"]}),s.invalidateQueries({queryKey:["contacts-last-touch"]}),he.success(`Sync complete! Pushed ${le.contacts_pushed||0}, pulled ${le.contacts_pulled||0}, skipped ${le.contacts_skipped||0} duplicates.`)},onError:le=>{b(null),k(0),he.error(le.message||"Sync failed")}}),ie=R==null?void 0:R.connected,ce=(R==null?void 0:R.sync_direction)||"bidirectional",ne=x??ce;return e.jsxs(e.Fragment,{children:[e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-emerald-500/10 flex items-center justify-center",children:e.jsx(qu,{className:"h-5 w-5 text-emerald-600"})}),e.jsxs("div",{children:[e.jsxs(zt,{className:"text-lg flex items-center gap-2",children:["BoldTrail",ie&&e.jsx(Xe,{variant:"default",className:"text-xs bg-green-600",children:"Connected"}),e.jsxs("button",{onClick:()=>l(!0),className:"flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(cg,{className:"h-3.5 w-3.5"}),"Learn More"]})]}),e.jsx(Br,{children:"Sync contacts bidirectionally between Agent OS and your BoldTrail (kvCORE) CRM."})]})]})}),e.jsx(Oe,{children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-2 text-sm text-muted-foreground",children:[e.jsx(zi,{className:"h-4 w-4 mt-0.5 text-green-500 shrink-0"}),e.jsx("span",{children:"Two-way contact sync with duplicate prevention"})]}),e.jsxs("div",{className:"flex items-start gap-2 text-sm text-muted-foreground",children:[e.jsx(zi,{className:"h-4 w-4 mt-0.5 text-green-500 shrink-0"}),e.jsx("span",{children:"Preview what will sync before executing"})]}),e.jsxs("div",{className:"flex items-start gap-2 text-sm text-muted-foreground",children:[e.jsx(zi,{className:"h-4 w-4 mt-0.5 text-green-500 shrink-0"}),e.jsx("span",{children:"Syncs name, email, phone, address, notes, and lead source"})]}),ie?e.jsxs("div",{className:"space-y-3 mt-4",children:[e.jsx("div",{className:"rounded-lg border p-3 space-y-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:"BoldTrail Connected"}),(R==null?void 0:R.last_sync_at)&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Last sync: ",new Date(R.last_sync_at).toLocaleString(),R.last_sync_status&&e.jsx(Xe,{variant:R.last_sync_status==="success"?"default":"secondary",className:"ml-2 text-[10px]",children:R.last_sync_status})]}),(R==null?void 0:R.boldtrail_contact_count)!=null&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[R.boldtrail_contact_count," contacts in BoldTrail"]}),(R==null?void 0:R.last_sync_message)&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:R.last_sync_message})]}),e.jsxs(Rl,{children:[e.jsx(vp,{asChild:!0,children:e.jsx(H,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(Dr,{className:"h-4 w-4"})})}),e.jsxs(jl,{children:[e.jsxs(Nl,{children:[e.jsx(Sl,{children:"Disconnect BoldTrail?"}),e.jsx(Cl,{children:"This will remove your API token. Previously synced contacts will remain in both systems."})]}),e.jsxs(kl,{children:[e.jsx(Tl,{children:"Cancel"}),e.jsx(ml,{onClick:()=>$.mutate(),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]})}),e.jsxs("div",{className:"rounded-lg border p-3 space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(j1,{className:"h-4 w-4 mt-0.5 text-emerald-600 shrink-0"}),e.jsxs("div",{className:"flex-1 space-y-1",children:[e.jsx("p",{className:"text-sm font-medium",children:"Only sync contacts I own in BoldTrail"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"If your token has access to the whole brokerage's contacts, turn this on to sync just the contacts assigned to you."})]}),e.jsx(Or,{checked:!!(R!=null&&R.sync_only_owned),onCheckedChange:le=>J.mutate({sync_only_owned:le}),disabled:J.isPending})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(ue,{className:"text-xs",children:"Your BoldTrail Agent ID"}),A?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Se,{type:"number",placeholder:"e.g. 12345",value:T,onChange:le=>E(le.target.value),className:"h-8 text-sm"}),e.jsx(H,{size:"sm",onClick:()=>{const le=T.trim()===""?null:Number(T);J.mutate({kvcore_user_id:le})},disabled:J.isPending,children:"Save"}),e.jsx(H,{size:"sm",variant:"ghost",onClick:()=>D(!1),children:"Cancel"})]}):e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-sm font-mono",children:(R==null?void 0:R.kvcore_user_id)??e.jsx("span",{className:"text-muted-foreground",children:"Not set"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(H,{size:"sm",variant:"outline",onClick:()=>Z.mutate(),disabled:Z.isPending,children:[Z.isPending?e.jsx(po,{className:"h-3 w-3 mr-1 animate-spin"}):null,"Auto-detect"]}),e.jsx(H,{size:"sm",variant:"ghost",onClick:()=>{var le;E(((le=R==null?void 0:R.kvcore_user_id)==null?void 0:le.toString())??""),D(!0)},children:"Edit"})]})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Your numeric BoldTrail (kvCORE) user ID. To find it: log into BoldTrail → click your avatar (top right) → ",e.jsx("strong",{children:"My Profile"}),". The ID appears in the page URL after ",e.jsx("code",{children:"/users/"})," (e.g. ",e.jsxs("code",{children:[".../users/",e.jsx("strong",{children:"12345"})]}),"). You can also open any contact you own in BoldTrail and look at the URL — your ID is shown as the assigned agent. Auto-detect tries to find it via your API token first."]})]})]}),e.jsx("div",{className:"rounded-lg border p-3",children:e.jsx(w4e,{value:ce,onChange:le=>ee.mutate(le)})}),e.jsx("div",{className:"flex gap-2",children:e.jsxs(H,{onClick:()=>K.mutate(),disabled:K.isPending||re.isPending,variant:"outline",className:"gap-2",children:[K.isPending?e.jsx(po,{className:"h-4 w-4 animate-spin"}):e.jsx(Bn,{className:"h-4 w-4"}),"Preview Sync"]})})]}):e.jsxs("div",{className:"mt-4 space-y-3",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Se,{type:"password",placeholder:"Paste your BoldTrail API token",value:t,onChange:le=>r(le.target.value),className:"flex-1"}),e.jsxs(H,{onClick:()=>O.mutate(t),disabled:!t||t.length<10||O.isPending,children:[O.isPending?e.jsx(po,{className:"h-4 w-4 animate-spin mr-2"}):null,"Connect"]})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Find your API token in BoldTrail → Lead Engine → Lead Dropbox → My API Tokens. Generate a ",e.jsx("strong",{children:"Contacts"})," scope token."]})]})]})})]}),e.jsx(bs,{open:n,onOpenChange:le=>{re.isPending||a(le)},children:e.jsxs(vs,{className:"sm:max-w-lg",children:[e.jsxs(Cs,{children:[e.jsxs(Ns,{className:"flex items-center gap-2",children:[e.jsx(qu,{className:"h-5 w-5 text-emerald-600"}),"Sync Preview"]}),e.jsx(nn,{children:"Review what will happen when you sync your contacts."})]}),o&&(()=>{const le=ne==="pull_only"?0:o.to_push,be=ne==="push_only"?0:o.to_pull;return e.jsxs("div",{className:"space-y-4",children:[e.jsx(w4e,{value:ne,onChange:y,size:"sm"}),o.owner_filter_active&&e.jsxs("div",{className:"rounded-md border border-emerald-200 bg-emerald-50 p-2 text-xs text-emerald-900 flex items-start gap-2",children:[e.jsx(j1,{className:"h-3.5 w-3.5 mt-0.5 shrink-0"}),e.jsxs("span",{children:["Owner filter is on. Only contacts assigned to your BoldTrail account",o.kvcore_user_id?` (ID ${o.kvcore_user_id})`:""," will be synced.",o.boldtrail_total_brokerage!=null&&e.jsxs(e.Fragment,{children:[" Brokerage total: ",e.jsx("strong",{children:o.boldtrail_total_brokerage.toLocaleString()}),"."]})]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:`rounded-lg border p-3 text-center ${ne==="pull_only"?"opacity-40":""}`,children:[e.jsx("p",{className:"text-2xl font-bold text-emerald-600",children:le}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(Hu,{className:"h-3 w-3"})," Push to BoldTrail"]})]}),e.jsxs("div",{className:`rounded-lg border p-3 text-center ${ne==="push_only"?"opacity-40":""}`,children:[e.jsx("p",{className:"text-2xl font-bold text-blue-600",children:be}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(fm,{className:"h-3 w-3"})," Pull to Agent OS"]})]}),e.jsxs("div",{className:"rounded-lg border p-3 text-center",children:[e.jsx("p",{className:"text-2xl font-bold text-muted-foreground",children:o.already_synced}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(Ar,{className:"h-3 w-3"})," Already synced"]})]})]}),e.jsxs("div",{className:"text-xs text-muted-foreground text-center",children:["Agent OS: ",o.agent_os_total," contacts · BoldTrail: ",o.boldtrail_total," contacts"]}),re.isPending&&e.jsxs("div",{className:"space-y-2 py-2",children:[e.jsx(Mi,{value:j||10,className:"h-2"}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:_||"Sync in progress..."})]}),le>0&&e.jsxs(m0,{open:d,onOpenChange:h,children:[e.jsx(f0,{asChild:!0,children:e.jsxs(H,{variant:"ghost",size:"sm",className:"w-full justify-between text-xs",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Hu,{className:"h-3 w-3 text-emerald-600"}),le," contacts to push to BoldTrail"]}),e.jsx(Io,{className:`h-3 w-3 transition-transform ${d?"rotate-180":""}`})]})}),e.jsx(p0,{children:e.jsxs("div",{className:"rounded border divide-y max-h-40 overflow-y-auto",children:[o.push_preview.map((fe,je)=>e.jsxs("div",{className:"px-3 py-1.5 text-xs flex justify-between",children:[e.jsx("span",{className:"font-medium",children:fe.name||"No name"}),e.jsx("span",{className:"text-muted-foreground",children:fe.email})]},je)),o.to_push>20&&e.jsxs("div",{className:"px-3 py-1.5 text-xs text-muted-foreground text-center",children:["...and ",o.to_push-20," more"]})]})})]}),be>0&&e.jsxs(m0,{open:m,onOpenChange:p,children:[e.jsx(f0,{asChild:!0,children:e.jsxs(H,{variant:"ghost",size:"sm",className:"w-full justify-between text-xs",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(fm,{className:"h-3 w-3 text-blue-600"}),be," contacts to pull from BoldTrail"]}),e.jsx(Io,{className:`h-3 w-3 transition-transform ${m?"rotate-180":""}`})]})}),e.jsx(p0,{children:e.jsxs("div",{className:"rounded border divide-y max-h-40 overflow-y-auto",children:[o.pull_preview.map((fe,je)=>e.jsxs("div",{className:"px-3 py-1.5 text-xs flex justify-between",children:[e.jsx("span",{className:"font-medium",children:fe.name||"No name"}),e.jsx("span",{className:"text-muted-foreground",children:fe.email})]},je)),o.to_pull>20&&e.jsxs("div",{className:"px-3 py-1.5 text-xs text-muted-foreground text-center",children:["...and ",o.to_pull-20," more"]})]})})]}),le===0&&be===0&&e.jsx("div",{className:"text-center py-4 text-sm text-muted-foreground",children:"✅ Everything is already in sync! No contacts to transfer."}),e.jsxs("div",{className:"flex gap-2 justify-end pt-2",children:[e.jsx(H,{variant:"outline",onClick:()=>a(!1),disabled:re.isPending,children:"Cancel"}),e.jsxs(H,{onClick:()=>re.mutate(),disabled:re.isPending||le===0&&be===0,className:"gap-2",children:[re.isPending?e.jsx(po,{className:"h-4 w-4 animate-spin"}):e.jsx(qu,{className:"h-4 w-4"}),re.isPending?"Syncing...":"Sync Now"]})]})]})})()]})}),e.jsx(bs,{open:i,onOpenChange:l,children:e.jsxs(vs,{className:"sm:max-w-2xl p-0 overflow-hidden",children:[e.jsx(Cs,{className:"p-6 pb-0",children:e.jsxs(Ns,{className:"flex items-center gap-2",children:[e.jsx(qu,{className:"h-5 w-5 text-emerald-600"}),"How BoldTrail Sync Works"]})}),e.jsx("div",{className:"px-6 pb-6",children:e.jsx("video",{src:"/videos/BoldTrailIntegration.mp4",controls:!0,autoPlay:!0,className:"w-full rounded-lg",controlsList:"nodownload"})})]})})]})}function L9s(){const s=ns(),[t,r]=S.useState(""),[n,a]=S.useState(!1),[i,l]=S.useState(0),[o,c]=S.useState(null),{data:d,isLoading:h}=yt({queryKey:["fub-status"],queryFn:async()=>{const{data:_,error:b}=await V.functions.invoke("followupboss-sync",{body:{action:"status"}});if(b)throw b;return _}}),m=Pt({mutationFn:async _=>{const{data:b,error:j}=await V.functions.invoke("followupboss-sync",{body:{action:"save_token",api_key:_}});if(j)throw j;if(b!=null&&b.error)throw new Error(b.error);return b},onSuccess:()=>{he.success("Connected to Follow Up Boss"),r(""),s.invalidateQueries({queryKey:["fub-status"]})},onError:_=>he.error(_.message)}),p=Pt({mutationFn:async()=>{const{error:_}=await V.functions.invoke("followupboss-sync",{body:{action:"disconnect"}});if(_)throw _},onSuccess:()=>{he.success("Disconnected"),s.invalidateQueries({queryKey:["fub-status"]})}}),x=Pt({mutationFn:async _=>{const{error:b}=await V.functions.invoke("followupboss-sync",{body:{action:"set_direction",sync_direction:_}});if(b)throw b},onSuccess:()=>s.invalidateQueries({queryKey:["fub-status"]})}),y=async()=>{a(!0),l(0),c("Pulling from FUB…");let _=0,b=0,j=0,k=0;try{for(;;){const{data:D,error:R}=await V.functions.invoke("followupboss-sync",{body:{action:"sync",offset:_}});if(R)throw R;if(D!=null&&D.error)throw new Error(D.error);b+=D.chunk_created||0,j+=D.chunk_updated||0,k+=D.chunk_skipped||0,_=D.next_offset;const z=D.total?Math.min(100,Math.round(_/D.total*100)):100;if(l(z),c(`Pulling · ${_} / ${D.total||"?"}`),D.done)break;await new Promise(O=>setTimeout(O,400))}let T=0,E=0;if((d==null?void 0:d.sync_direction)==="bidirectional"){let D=0;for(l(0),c("Pushing to FUB…");;){const{data:R,error:z}=await V.functions.invoke("followupboss-sync",{body:{action:"push",offset:D}});if(z)throw z;if(R!=null&&R.error)throw new Error(R.error);T+=R.chunk_pushed||0,E+=R.chunk_failed||0,D=R.next_offset;const O=R.total?Math.min(100,Math.round(D/R.total*100)):100;if(l(O),c(`Pushing · ${D} / ${R.total||"?"}`),R.done)break;await new Promise($=>setTimeout($,400))}}const A=T||E?` · pushed ${T}${E?`, ${E} failed`:""}`:"";he.success(`Sync complete · ${b} new, ${j} updated${k?`, ${k} skipped`:""}${A}`),s.invalidateQueries({queryKey:["fub-status"]})}catch(T){he.error(T.message||"Sync failed")}finally{a(!1),setTimeout(()=>{l(0),c(null)},2500)}};return e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsx("div",{className:"flex items-start justify-between gap-3",children:e.jsxs("div",{children:[e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(IE,{className:"h-5 w-5 text-primary"}),"Follow Up Boss",(d==null?void 0:d.connected)&&e.jsxs(Xe,{variant:"default",className:"ml-1",children:[e.jsx(zi,{className:"h-3 w-3 mr-1"})," Connected"]})]}),e.jsx(Br,{children:"Sync your Follow Up Boss contacts into Agent OS."})]})})}),e.jsx(Oe,{className:"space-y-4",children:h?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading…"}):d!=null&&d.connected?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3 text-sm",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Last sync"}),e.jsx("p",{className:"font-medium",children:d.last_sync_at?new Date(d.last_sync_at).toLocaleString():"Never"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"FUB contacts"}),e.jsx("p",{className:"font-medium",children:d.fub_contact_count??"—"})]})]}),d.last_sync_status==="error"&&e.jsx("p",{className:"text-sm text-destructive",children:d.last_sync_message}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border px-3 py-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Two-way sync"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Off = pull from FUB only. On = also push new Agent OS contacts to FUB."})]}),e.jsx(Or,{checked:d.sync_direction==="bidirectional",onCheckedChange:_=>x.mutate(_?"bidirectional":"pull_only"),disabled:n||x.isPending})]}),o&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(Mi,{value:i}),e.jsx("p",{className:"text-xs text-muted-foreground",children:o})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(H,{onClick:y,disabled:n,children:[e.jsx(po,{className:`h-4 w-4 mr-2 ${n?"animate-spin":""}`}),n?"Syncing…":"Sync Now"]}),e.jsxs(Rl,{children:[e.jsx(vp,{asChild:!0,children:e.jsxs(H,{variant:"outline",disabled:n,children:[e.jsx(Dr,{className:"h-4 w-4 mr-2"})," Disconnect"]})}),e.jsxs(jl,{children:[e.jsxs(Nl,{children:[e.jsx(Sl,{children:"Disconnect Follow Up Boss?"}),e.jsx(Cl,{children:"Your API key will be removed. Synced contacts stay in Agent OS."})]}),e.jsxs(kl,{children:[e.jsx(Tl,{children:"Cancel"}),e.jsx(ml,{onClick:()=>p.mutate(),children:"Disconnect"})]})]})]})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ue,{htmlFor:"fub-key",children:"Follow Up Boss API Key"}),e.jsx(Se,{id:"fub-key",type:"password",placeholder:"fka_live_...",value:t,onChange:_=>r(_.target.value)}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1 flex items-center gap-1",children:["Find your key in FUB → Admin → API.",e.jsxs("a",{href:"https://app.followupboss.com/2/api",target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-0.5 text-primary hover:underline",children:["Open ",e.jsx(gn,{className:"h-3 w-3"})]})]})]}),e.jsx(H,{onClick:()=>m.mutate(t),disabled:!t.trim()||m.isPending,children:m.isPending?"Connecting…":"Connect"})]})})]})}function Kyt(){const s=Fr(),[t,r]=S.useState(""),[n,a]=S.useState(""),[i,l]=S.useState("Test from ReLevelUp"),[o,c]=S.useState(!1),{data:d,isLoading:h}=yt({queryKey:["ses-config"],queryFn:async()=>{const{data:{session:x}}=await V.auth.getSession();if(!x)throw new Error("Not authenticated");return(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ses-send-campaign",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${x.access_token}`},body:JSON.stringify({action:"check_config"})})).json()}}),m=async()=>{if(!t||!n){he.error("Please fill in From and To email addresses");return}c(!0);try{const{data:{session:x}}=await V.auth.getSession();if(!x)throw new Error("Not authenticated");const _=await(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ses-send-campaign",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${x.access_token}`},body:JSON.stringify({action:"test_send",to:t,from_email:n,subject:i,body_html:"

Test Email

This is a test email sent via Amazon SES from the ReLevelUp platform.

If you received this, SES is configured correctly! 🎉

"})})).json();_.success?he.success(`Test email sent! Message ID: ${_.messageId}`):he.error(_.error||"Failed to send test email")}catch(x){he.error(x.message||"Failed to send test email")}finally{c(!1)}},p=(d==null?void 0:d.configured)===!0;return e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-orange-500/10 flex items-center justify-center",children:e.jsx(er,{className:"h-5 w-5 text-orange-600"})}),e.jsxs("div",{children:[e.jsx(zt,{className:"text-lg",children:"Amazon SES — Mass Email"}),e.jsx(Br,{children:"Send bulk email campaigns via Amazon SES"})]})]}),e.jsx(Xe,{variant:p?"default":"secondary",children:h?"Checking...":p?e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(zi,{className:"h-3 w-3"})," Connected"]}):e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(wo,{className:"h-3 w-3"})," Not Configured"]})})]})}),p&&e.jsxs(Oe,{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-lg border p-4 space-y-3",children:[e.jsx("h4",{className:"font-medium text-sm",children:"Send Test Email"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:'Verify your SES setup by sending a test email. The "From" address must be verified in SES or belong to a verified domain.'}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(ue,{className:"text-xs",children:"From Email"}),e.jsx(Se,{placeholder:"notifications@mail.relevelup.com",value:n,onChange:x=>a(x.target.value),className:"text-sm"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(ue,{className:"text-xs",children:"To Email"}),e.jsx(Se,{placeholder:"your@email.com",value:t,onChange:x=>r(x.target.value),className:"text-sm"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(ue,{className:"text-xs",children:"Subject"}),e.jsx(Se,{value:i,onChange:x=>l(x.target.value),className:"text-sm"})]})]}),e.jsxs(H,{onClick:m,disabled:o,size:"sm",children:[o?e.jsx(is,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(yn,{className:"h-4 w-4 mr-2"}),"Send Test"]})]}),e.jsxs(H,{onClick:()=>s("/admin/email-campaigns"),className:"w-full",children:[e.jsx(ph,{className:"h-4 w-4 mr-2"})," Launch Campaign Composer"]}),e.jsxs("div",{className:"text-xs text-muted-foreground space-y-1",children:[e.jsxs("p",{children:[e.jsx("strong",{children:"Region:"})," ",d==null?void 0:d.region]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Domain:"})," send.relevelup.com (verified)"]})]})]}),!p&&!h&&e.jsx(Oe,{children:e.jsxs("p",{className:"text-sm text-muted-foreground",children:["AWS SES credentials are not configured. Add ",e.jsx("code",{children:"AWS_SES_ACCESS_KEY_ID"}),", ",e.jsx("code",{children:"AWS_SES_SECRET_ACCESS_KEY"}),", and ",e.jsx("code",{children:"AWS_SES_REGION"})," as secrets to enable."]})})]})}async function Cwe(s){const{data:{session:t}}=await V.auth.getSession();if(!t)throw new Error("Not authenticated");const r=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ses-verify-sender",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.access_token}`},body:JSON.stringify(s)}),n=await r.json();if(!r.ok)throw new Error(n.error||"Request failed");return n}function D9s({status:s}){return s==="verified"?e.jsxs(Xe,{className:"bg-green-500/10 text-green-700 hover:bg-green-500/20 border-green-500/20",children:[e.jsx(ea,{className:"h-3 w-3 mr-1"})," Verified"]}):s==="pending"?e.jsxs(Xe,{variant:"secondary",children:[e.jsx(Pn,{className:"h-3 w-3 mr-1"})," Pending — check inbox"]}):s==="failed"||s==="temporary_failure"?e.jsxs(Xe,{variant:"destructive",children:[e.jsx(wo,{className:"h-3 w-3 mr-1"})," Failed"]}):e.jsxs(Xe,{variant:"outline",children:[e.jsx(wo,{className:"h-3 w-3 mr-1"})," Not started"]})}function Yyt({brokerageId:s,onVerifiedSelect:t}){const r=ns(),[n,a]=S.useState(""),[i,l]=S.useState(""),[o,c]=S.useState(!1),[d,h]=S.useState(null),[m,p]=S.useState(null),{data:x,isLoading:y}=yt({queryKey:["brokerage-verified-senders",s],queryFn:async()=>{const{data:k,error:T}=await V.from("brokerage_verified_senders").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1});if(T)throw T;return k||[]}}),_=Pt({mutationFn:async()=>Cwe({action:"request_verification",brokerage_id:s,email:n,display_name:i||void 0}),onSuccess:()=>{r.invalidateQueries({queryKey:["brokerage-verified-senders",s]}),he.success("Verification email sent",{description:`Check ${n} and click the AWS verification link.`}),a(""),l(""),c(!1)},onError:k=>he.error(k.message)}),b=async k=>{var T,E;h(k.id);try{const A=await Cwe({action:"check_status",sender_id:k.id});r.invalidateQueries({queryKey:["brokerage-verified-senders",s]}),((T=A.sender)==null?void 0:T.status)==="verified"?he.success(`${k.email} is verified! 🎉`):he.info(`Status: ${((E=A.sender)==null?void 0:E.status)||"unknown"}`)}catch(A){he.error(A.message)}finally{h(null)}},j=Pt({mutationFn:async k=>Cwe({action:"delete",sender_id:k}),onSuccess:()=>{r.invalidateQueries({queryKey:["brokerage-verified-senders",s]}),he.success("Sender removed"),p(null)},onError:k=>he.error(k.message)});return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium mb-1",children:"Verified Sender Addresses"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Verify any email address (yours or your brokerage's) so recruiting emails can be sent from that address. Anyone managing this brokerage can use these senders."})]}),y?e.jsx("div",{className:"text-xs text-muted-foreground py-3",children:"Loading…"}):x&&x.length>0?e.jsx("div",{className:"space-y-2",children:x.map(k=>e.jsxs("div",{className:"flex items-center justify-between gap-3 p-3 rounded-lg border bg-card",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[e.jsx("div",{className:"h-9 w-9 rounded-full bg-muted flex items-center justify-center shrink-0",children:e.jsx(er,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-sm font-medium truncate",children:k.email}),e.jsx(D9s,{status:k.status})]}),k.display_name&&e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:['"',k.display_name,'"']})]})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[k.status==="verified"&&t&&e.jsx(H,{size:"sm",variant:"outline",onClick:()=>t(k.email),children:"Use"}),k.status!=="verified"&&e.jsx(H,{size:"sm",variant:"ghost",onClick:()=>b(k),disabled:d===k.id,title:"Refresh status from AWS",children:d===k.id?e.jsx(is,{className:"h-4 w-4 animate-spin"}):e.jsx(po,{className:"h-4 w-4"})}),e.jsx(H,{size:"sm",variant:"ghost",onClick:()=>p(k),className:"text-destructive hover:text-destructive",children:e.jsx(Dr,{className:"h-4 w-4"})})]})]},k.id))}):e.jsx("div",{className:"text-xs text-muted-foreground py-2 italic",children:"No verified senders yet. Add one below."}),o?e.jsxs("div",{className:"rounded-lg border p-4 space-y-3 bg-muted/30",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(ue,{className:"text-xs",children:"Email Address *"}),e.jsx(Se,{type:"email",value:n,onChange:k=>a(k.target.value),placeholder:"broker@yourbrokerage.com",className:"text-sm"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(ue,{className:"text-xs",children:"Display Name (optional)"}),e.jsx(Se,{value:i,onChange:k=>l(k.target.value),placeholder:"John at Acme Realty",className:"text-sm"})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground leading-relaxed",children:"We'll ask AWS to send a verification email to this address. The owner must click the link before this sender can be used."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(H,{size:"sm",onClick:()=>_.mutate(),disabled:!n.trim()||_.isPending,children:[_.isPending?e.jsx(is,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(er,{className:"h-4 w-4 mr-2"}),"Send Verification Email"]}),e.jsx(H,{size:"sm",variant:"ghost",onClick:()=>{c(!1),a(""),l("")},children:"Cancel"})]})]}):e.jsxs(H,{size:"sm",variant:"outline",onClick:()=>c(!0),children:[e.jsx(Ys,{className:"h-4 w-4 mr-1"})," Add Sender Address"]}),e.jsx(Rl,{open:!!m,onOpenChange:k=>!k&&p(null),children:e.jsxs(jl,{children:[e.jsxs(Nl,{children:[e.jsx(Sl,{children:"Remove this sender?"}),e.jsxs(Cl,{children:['"',m==null?void 0:m.email,`" will be removed from your verified senders and from Amazon SES. You'd need to verify it again to use it.`]})]}),e.jsxs(kl,{children:[e.jsx(Tl,{children:"Cancel"}),e.jsx(ml,{onClick:()=>m&&j.mutate(m.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Remove"})]})]})})]})}async function Twe(s){const{data:{session:t}}=await V.auth.getSession();if(!t)throw new Error("Not authenticated");const r=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ses-verify-sender",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.access_token}`},body:JSON.stringify(s)}),n=await r.json();if(!r.ok)throw new Error(n.error||"Request failed");return n}function R9s({status:s}){return s==="verified"?e.jsxs(Xe,{className:"bg-green-500/10 text-green-700 hover:bg-green-500/20 border-green-500/20",children:[e.jsx(ea,{className:"h-3 w-3 mr-1"})," Verified"]}):s==="pending"?e.jsxs(Xe,{variant:"secondary",children:[e.jsx(Pn,{className:"h-3 w-3 mr-1"})," Pending — check inbox"]}):s==="failed"||s==="temporary_failure"?e.jsxs(Xe,{variant:"destructive",children:[e.jsx(wo,{className:"h-3 w-3 mr-1"})," Failed"]}):e.jsxs(Xe,{variant:"outline",children:[e.jsx(wo,{className:"h-3 w-3 mr-1"})," Not started"]})}function O9s({userId:s,onVerifiedSelect:t}){const r=ns(),[n,a]=S.useState(""),[i,l]=S.useState(""),[o,c]=S.useState(!1),[d,h]=S.useState(null),[m,p]=S.useState(null),{data:x,isLoading:y}=yt({queryKey:["user-verified-senders",s],queryFn:async()=>{const{data:k,error:T}=await V.from("user_verified_senders").select("*").eq("user_id",s).order("created_at",{ascending:!1});if(T)throw T;return k||[]}}),_=Pt({mutationFn:async()=>Twe({action:"request_verification",scope:"user",email:n,display_name:i||void 0}),onSuccess:()=>{r.invalidateQueries({queryKey:["user-verified-senders",s]}),he.success("Verification email sent",{description:`Check ${n} and click the AWS verification link.`}),a(""),l(""),c(!1)},onError:k=>he.error(k.message)}),b=async k=>{var T,E;h(k.id);try{const A=await Twe({action:"check_status",sender_id:k.id});r.invalidateQueries({queryKey:["user-verified-senders",s]}),((T=A.sender)==null?void 0:T.status)==="verified"?he.success(`${k.email} is verified! 🎉`):he.info(`Status: ${((E=A.sender)==null?void 0:E.status)||"unknown"}`)}catch(A){he.error(A.message)}finally{h(null)}},j=Pt({mutationFn:async k=>Twe({action:"delete",sender_id:k}),onSuccess:()=>{r.invalidateQueries({queryKey:["user-verified-senders",s]}),he.success("Sender removed"),p(null)},onError:k=>he.error(k.message)});return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium mb-1",children:"Your Verified Sender Addresses"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Verify your email address with Amazon so mass emails can be sent ",e.jsx("em",{children:"from"})," you. Add an address, then click the verification link Amazon sends to that inbox."]})]}),y?e.jsx("div",{className:"text-xs text-muted-foreground py-3",children:"Loading…"}):x&&x.length>0?e.jsx("div",{className:"space-y-2",children:x.map(k=>e.jsxs("div",{className:"flex items-center justify-between gap-3 p-3 rounded-lg border bg-card",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[e.jsx("div",{className:"h-9 w-9 rounded-full bg-muted flex items-center justify-center shrink-0",children:e.jsx(er,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-sm font-medium truncate",children:k.email}),e.jsx(R9s,{status:k.status})]}),k.display_name&&e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:['"',k.display_name,'"']})]})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[k.status==="verified"&&t&&e.jsx(H,{size:"sm",variant:"outline",onClick:()=>t(k.email),children:"Use"}),k.status!=="verified"&&e.jsx(H,{size:"sm",variant:"ghost",onClick:()=>b(k),disabled:d===k.id,title:"Refresh status from AWS",children:d===k.id?e.jsx(is,{className:"h-4 w-4 animate-spin"}):e.jsx(po,{className:"h-4 w-4"})}),e.jsx(H,{size:"sm",variant:"ghost",onClick:()=>p(k),className:"text-destructive hover:text-destructive",children:e.jsx(Dr,{className:"h-4 w-4"})})]})]},k.id))}):e.jsx("div",{className:"text-xs text-muted-foreground py-2 italic",children:"No verified senders yet. Add one below."}),o?e.jsxs("div",{className:"rounded-lg border p-4 space-y-3 bg-muted/30",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(ue,{className:"text-xs",children:"Email Address *"}),e.jsx(Se,{type:"email",value:n,onChange:k=>a(k.target.value),placeholder:"you@yourdomain.com",className:"text-sm"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(ue,{className:"text-xs",children:"Display Name (optional)"}),e.jsx(Se,{value:i,onChange:k=>l(k.target.value),placeholder:"Jane at Acme Realty",className:"text-sm"})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground leading-relaxed",children:"We'll ask Amazon to send a verification email to this address. You must click the link before this sender can be used in a campaign."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(H,{size:"sm",onClick:()=>_.mutate(),disabled:!n.trim()||_.isPending,children:[_.isPending?e.jsx(is,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(er,{className:"h-4 w-4 mr-2"}),"Send Verification Email"]}),e.jsx(H,{size:"sm",variant:"ghost",onClick:()=>{c(!1),a(""),l("")},children:"Cancel"})]})]}):e.jsxs(H,{size:"sm",variant:"outline",onClick:()=>c(!0),children:[e.jsx(Ys,{className:"h-4 w-4 mr-1"})," Add Sender Address"]}),e.jsx(Rl,{open:!!m,onOpenChange:k=>!k&&p(null),children:e.jsxs(jl,{children:[e.jsxs(Nl,{children:[e.jsx(Sl,{children:"Remove this sender?"}),e.jsxs(Cl,{children:['"',m==null?void 0:m.email,`" will be removed from your verified senders and from Amazon. You'd need to verify it again to use it.`]})]}),e.jsxs(kl,{children:[e.jsx(Tl,{children:"Cancel"}),e.jsx(ml,{onClick:()=>m&&j.mutate(m.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Remove"})]})]})})]})}function F9s(){var E,A,D,R,z;const{user:s,isBrokerageManager:t,isAdmin:r,managedBrokerages:n,selectedBrokerageId:a}=Ms(),i=a||((E=n==null?void 0:n[0])==null?void 0:E.id)||null,l=(t||r)&&!!i,o=ns(),[c,d]=S.useState(!1),[h,m]=S.useState(""),[p,x]=S.useState(""),{data:y}=yt({queryKey:["mass-email-settings",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:O,error:$}=await V.from("mass_email_settings").select("*").eq("user_id",s.id).maybeSingle();if($)throw $;return O}}),{data:_}=yt({queryKey:["agent-profile-email",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:O,error:$}=await V.from("profiles").select("email, name").eq("id",s.id).single();if($)throw $;return O}}),b=((A=y==null?void 0:y.reply_to_email)==null?void 0:A.trim())||((D=_==null?void 0:_.email)==null?void 0:D.trim())||"",j=((R=y==null?void 0:y.display_name)==null?void 0:R.trim())||((z=_==null?void 0:_.name)==null?void 0:z.trim())||"";S.useEffect(()=>{c||(m(b),x(j))},[c,b,j]);const k=Pt({mutationFn:async()=>{if(!s||!h.trim())throw new Error("Please enter a reply-to email");const O={reply_to_email:h.trim(),display_name:p.trim()||null,updated_at:new Date().toISOString()};if(y){const{error:$}=await V.from("mass_email_settings").update(O).eq("user_id",s.id);if($)throw $}else{const{error:$}=await V.from("mass_email_settings").insert({user_id:s.id,...O});if($)throw $}},onSuccess:()=>{o.invalidateQueries({queryKey:["mass-email-settings",s==null?void 0:s.id]}),o.invalidateQueries({queryKey:["mass-email-ready",s==null?void 0:s.id]}),o.invalidateQueries({queryKey:["mass-email-settings-check",s==null?void 0:s.id]}),he.success("Reply-to email saved!"),d(!1)},onError:O=>he.error(O.message)}),T=!!b;return e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-orange-500/10 flex items-center justify-center",children:e.jsx(yn,{className:"h-5 w-5 text-orange-600"})}),e.jsxs("div",{children:[e.jsxs(zt,{className:"text-lg flex items-center gap-2",children:["Mass Email",T?e.jsxs(Xe,{variant:"default",className:"text-xs bg-green-600",children:[e.jsx(zi,{className:"h-3 w-3 mr-1"})," Set Up"]}):e.jsx(Xe,{variant:"secondary",className:"text-xs",children:"Setup Required"})]}),e.jsx(Br,{children:"Set the email address where replies from your campaigns will be sent. If you haven't customized it yet, we'll use your profile email."})]})]})}),e.jsxs(Oe,{className:"space-y-3",children:[T&&!c?e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:j||"No display name"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:b})]}),e.jsxs(H,{variant:"ghost",size:"sm",onClick:()=>d(!0),children:[e.jsx(ni,{className:"h-3 w-3 mr-1"})," Edit"]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(ue,{className:"text-xs",children:"Display Name"}),e.jsx(Se,{placeholder:"e.g. 🏡 Karen Hall",value:p,onChange:O=>x(O.target.value)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"How your name appears in the recipient's inbox"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(ue,{className:"text-xs",children:"Reply-To Email *"}),e.jsx(Se,{type:"email",placeholder:"your@email.com",value:h,onChange:O=>m(O.target.value)})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(H,{size:"sm",onClick:()=>k.mutate(),disabled:k.isPending||!h.trim(),children:[e.jsx(vc,{className:"h-4 w-4 mr-1"})," Save"]}),c&&e.jsxs(H,{size:"sm",variant:"outline",onClick:()=>{d(!1),m(b),x(j)},children:[e.jsx(Rr,{className:"h-4 w-4 mr-1"})," Cancel"]})]})]}),s&&e.jsxs(e.Fragment,{children:[e.jsx(Qo,{className:"my-2"}),e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-3 space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("div",{className:"h-8 w-8 rounded-md bg-primary/10 flex items-center justify-center shrink-0",children:e.jsx(w1,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm font-semibold",children:"Verified Sender Addresses"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Before you can send mass emails ",e.jsx("em",{children:"from"})," an address, Amazon requires that address to be verified. Add the email you want to send from below and click the verification link Amazon sends to that inbox."]})]})]}),e.jsx(O9s,{userId:s.id,onVerifiedSelect:O=>{m(O),d(!0)}})]})]}),l&&e.jsxs(e.Fragment,{children:[e.jsx(Qo,{className:"my-2"}),e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-3 space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("div",{className:"h-8 w-8 rounded-md bg-primary/10 flex items-center justify-center shrink-0",children:e.jsx(w1,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm font-semibold",children:"Brokerage-Shared Sender Addresses"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Addresses verified here can be used by anyone managing this brokerage."})]})]}),e.jsx(Yyt,{brokerageId:i})]})]})]})]})}function B9s(){const{isAdmin:s}=Ms(),t=ns(),[r,n]=S.useState(!1),[a,i]=S.useState(!1),[l,o]=S.useState(!1),{data:c,isLoading:d}=yt({queryKey:["gmail-integration"],queryFn:async()=>{const{data:E,error:A}=await V.from("gmail_integrations").select("*").maybeSingle();if(A)throw A;return E}}),{data:h}=yt({queryKey:["social-accounts"],queryFn:async()=>{const{data:{user:E}}=await V.auth.getUser();if(!E)return[];const{data:A,error:D}=await V.from("social_accounts").select("*").eq("user_id",E.id).order("created_at",{ascending:!1});if(D)throw D;return A}}),m=async()=>{n(!0);try{const{data:E,error:A}=await V.functions.invoke("gmail-oauth",{body:{action:"get_auth_url"}});if(A)throw A;if(E!=null&&E.authUrl)window.location.href=E.authUrl;else throw new Error("Failed to get authorization URL")}catch(E){console.error("Gmail OAuth error:",E),he.error("Failed to start Gmail connection"),n(!1)}},p=async E=>{i(!0);try{const{data:A,error:D}=await V.functions.invoke("meta-oauth",{body:{action:"get_auth_url",callbackPath:"/social-connections/callback",authMode:E}});if(D)throw D;if(A!=null&&A.authUrl)window.location.href=A.authUrl;else throw new Error("Failed to get authorization URL")}catch(A){console.error("Meta OAuth error:",A),he.error("Failed to start connection. Make sure Meta App credentials are configured."),i(!1)}},x=async()=>{o(!0);try{const{data:E,error:A}=await V.functions.invoke("linkedin-oauth",{body:{action:"get_auth_url",callbackPath:"/social-connections/linkedin-callback"}});if(A)throw A;if(E!=null&&E.authUrl)window.location.href=E.authUrl;else throw new Error("Failed to get LinkedIn authorization URL")}catch(E){console.error("LinkedIn OAuth error:",E),he.error("Failed to start LinkedIn connection. Please try again."),o(!1)}},y=Pt({mutationFn:async E=>{const{error:A}=await V.from("gmail_integrations").delete().eq("id",E);if(A)throw A},onSuccess:()=>{t.invalidateQueries({queryKey:["gmail-integration"]}),he.success("Gmail disconnected")},onError:()=>{he.error("Failed to disconnect Gmail")}}),_=Pt({mutationFn:async E=>{const{error:A}=await V.from("social_accounts").delete().eq("id",E);if(A)throw A},onSuccess:()=>{t.invalidateQueries({queryKey:["social-accounts"]}),he.success("Account disconnected")},onError:()=>{he.error("Failed to disconnect account")}}),b=!!(c!=null&&c.is_active),j=(h==null?void 0:h.filter(E=>E.platform==="facebook"))||[],k=(h==null?void 0:h.filter(E=>E.platform==="instagram"))||[],T=(h==null?void 0:h.filter(E=>E.platform==="linkedin"))||[];return e.jsx(Ss,{children:e.jsxs("div",{className:"max-w-3xl mx-auto space-y-6 animate-fade-in",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold tracking-tight",children:"Integrations"}),e.jsx("p",{className:"text-muted-foreground",children:"Connect third-party services to supercharge your Agent OS workflow."})]}),e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-destructive/10 flex items-center justify-center",children:e.jsx(er,{className:"h-5 w-5 text-destructive"})}),e.jsxs("div",{children:[e.jsxs(zt,{className:"text-lg flex items-center gap-2",children:["Gmail",b&&e.jsx(Xe,{variant:"default",className:"text-xs bg-green-600",children:"Connected"})]}),e.jsx(Br,{children:"Send emails directly from your contact pages and auto-log them as touchpoints."})]})]})}),e.jsx(Oe,{children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-2 text-sm text-muted-foreground",children:[e.jsx(zi,{className:"h-4 w-4 mt-0.5 text-green-500 shrink-0"}),e.jsx("span",{children:"Send personalized emails from your Gmail account"})]}),e.jsxs("div",{className:"flex items-start gap-2 text-sm text-muted-foreground",children:[e.jsx(zi,{className:"h-4 w-4 mt-0.5 text-green-500 shrink-0"}),e.jsx("span",{children:"Automatically log emails as activity touchpoints"})]}),e.jsxs("div",{className:"flex items-start gap-2 text-sm text-muted-foreground",children:[e.jsx(zi,{className:"h-4 w-4 mt-0.5 text-green-500 shrink-0"}),e.jsx("span",{children:"Quick compose from any contact detail page"})]}),b?e.jsxs("div",{className:"flex items-center justify-between mt-4 p-3 rounded-lg border",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:c.gmail_email}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Connected Gmail account"})]}),e.jsxs(Rl,{children:[e.jsx(vp,{asChild:!0,children:e.jsx(H,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(Dr,{className:"h-4 w-4"})})}),e.jsxs(jl,{children:[e.jsxs(Nl,{children:[e.jsx(Sl,{children:"Disconnect Gmail?"}),e.jsx(Cl,{children:"This will remove your Gmail connection. You'll need to reconnect to send emails."})]}),e.jsxs(kl,{children:[e.jsx(Tl,{children:"Cancel"}),e.jsx(ml,{onClick:()=>y.mutate(c.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]}):e.jsxs(H,{className:"mt-4",onClick:m,disabled:r||d,children:[r?e.jsx(po,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(er,{className:"h-4 w-4 mr-2"}),"Connect Gmail",e.jsx(bi,{className:"h-4 w-4 ml-2"})]})]})})]}),e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-blue-500/10 flex items-center justify-center",children:e.jsx(fh,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsxs(zt,{className:"text-lg flex items-center gap-2",children:["Facebook",j.length>0&&e.jsx(Xe,{variant:"default",className:"text-xs bg-green-600",children:"Connected"})]}),e.jsx(Br,{children:"Connect Facebook Pages to post content and reach your audience."})]})]})}),e.jsxs(Oe,{className:"space-y-3",children:[j.length>0&&e.jsx("div",{className:"space-y-2",children:j.map(E=>e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(Un,{className:"h-8 w-8",children:[e.jsx(Ka,{src:E.profile_picture_url||""}),e.jsx(qn,{children:e.jsx(fh,{className:"h-4 w-4"})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:E.page_name||E.platform_username||"Facebook Page"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Connected Facebook Page"})]})]}),e.jsxs(Rl,{children:[e.jsx(vp,{asChild:!0,children:e.jsx(H,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(Dr,{className:"h-4 w-4"})})}),e.jsxs(jl,{children:[e.jsxs(Nl,{children:[e.jsx(Sl,{children:"Disconnect Facebook?"}),e.jsx(Cl,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(kl,{children:[e.jsx(Tl,{children:"Cancel"}),e.jsx(ml,{onClick:()=>_.mutate(E.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},E.id))}),e.jsxs(H,{onClick:()=>p("facebook"),disabled:a,variant:"outline",className:"gap-2",children:[a?e.jsx(po,{className:"h-4 w-4 animate-spin"}):e.jsx(Ys,{className:"h-4 w-4"}),"Connect Facebook Page"]})]})]}),e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-pink-500/10 flex items-center justify-center",children:e.jsx(yu,{className:"h-5 w-5 text-pink-600"})}),e.jsxs("div",{children:[e.jsxs(zt,{className:"text-lg flex items-center gap-2",children:["Instagram",k.length>0&&e.jsx(Xe,{variant:"default",className:"text-xs bg-green-600",children:"Connected"})]}),e.jsx(Br,{children:"Connect an Instagram Business or Creator account to schedule and publish posts. Personal accounts are not supported by Meta's API."})]})]})}),e.jsxs(Oe,{className:"space-y-3",children:[k.length>0&&e.jsx("div",{className:"space-y-2",children:k.map(E=>e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(Un,{className:"h-8 w-8",children:[e.jsx(Ka,{src:E.profile_picture_url||""}),e.jsx(qn,{children:e.jsx(yu,{className:"h-4 w-4"})})]}),e.jsxs("div",{children:[e.jsxs("p",{className:"font-medium text-sm",children:["@",E.platform_username||"Instagram Account"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Connected Instagram account"})]})]}),e.jsxs(Rl,{children:[e.jsx(vp,{asChild:!0,children:e.jsx(H,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(Dr,{className:"h-4 w-4"})})}),e.jsxs(jl,{children:[e.jsxs(Nl,{children:[e.jsx(Sl,{children:"Disconnect Instagram?"}),e.jsx(Cl,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(kl,{children:[e.jsx(Tl,{children:"Cancel"}),e.jsx(ml,{onClick:()=>_.mutate(E.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},E.id))}),e.jsxs(H,{onClick:()=>p("instagram"),disabled:a,variant:"outline",className:"gap-2",children:[a?e.jsx(po,{className:"h-4 w-4 animate-spin"}):e.jsx(Ys,{className:"h-4 w-4"}),"Connect Instagram Professional"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Uses Instagram's professional login for Business or Creator accounts. Personal accounts cannot post via Meta's API — convert your account in the Instagram app (Profile → Menu → Settings → Account type → Switch to Professional)."})]})]}),e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-blue-700/10 flex items-center justify-center",children:e.jsx(qf,{className:"h-5 w-5 text-blue-700"})}),e.jsxs("div",{children:[e.jsxs(zt,{className:"text-lg flex items-center gap-2",children:["LinkedIn",T.length>0&&e.jsx(Xe,{variant:"default",className:"text-xs bg-green-600",children:"Connected"})]}),e.jsx(Br,{children:"Connect your LinkedIn profile to share content and grow your professional network."})]})]})}),e.jsxs(Oe,{className:"space-y-3",children:[T.length>0&&e.jsx("div",{className:"space-y-2",children:T.map(E=>e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(Un,{className:"h-8 w-8",children:[e.jsx(Ka,{src:E.profile_picture_url||""}),e.jsx(qn,{children:e.jsx(qf,{className:"h-4 w-4"})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:E.platform_username||"LinkedIn Account"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Connected LinkedIn profile"})]})]}),e.jsxs(Rl,{children:[e.jsx(vp,{asChild:!0,children:e.jsx(H,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(Dr,{className:"h-4 w-4"})})}),e.jsxs(jl,{children:[e.jsxs(Nl,{children:[e.jsx(Sl,{children:"Disconnect LinkedIn?"}),e.jsx(Cl,{children:"This will remove your LinkedIn connection. You'll need to reconnect to post content."})]}),e.jsxs(kl,{children:[e.jsx(Tl,{children:"Cancel"}),e.jsx(ml,{onClick:()=>_.mutate(E.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},E.id))}),e.jsxs(H,{onClick:x,disabled:l,variant:"outline",className:"gap-2",children:[l?e.jsx(po,{className:"h-4 w-4 animate-spin"}):e.jsx(Ys,{className:"h-4 w-4"}),"Connect LinkedIn"]})]})]}),e.jsx(P9s,{}),e.jsx(L9s,{}),e.jsx(F9s,{}),s&&e.jsx(Kyt,{})]})})}const z9s="https://chromewebstore.google.com/detail/levelup-companion/lppakdeaencigddecnkcifdcemlfpkkk";function $9s(){const[s,t]=S.useState(null),[r,n]=S.useState(!1),[a,i]=S.useState(0),[l,o]=S.useState(!1),c="/levelup-extension.zip",d="https://tile-portal.lovable.app/levelup-extension.zip",h=window.location.hostname.startsWith("id-preview--"),m=async b=>{const j=new Uint8Array(await b.slice(0,4).arrayBuffer());return j[0]===80&&j[1]===75&&j[2]===3&&j[3]===4||j[0]===80&&j[1]===75&&j[2]===5&&j[3]===6||j[0]===80&&j[1]===75&&j[2]===7&&j[3]===8},p=b=>{const j=document.createElement("a");j.href=b,j.download="levelup-extension.zip",j.rel="noopener noreferrer",j.target="_blank",document.body.appendChild(j),j.click(),j.remove()},x=async()=>{o(!0);try{if(h){p(`${d}?v=${Date.now()}`);return}const b=await fetch(`${c}?v=${Date.now()}`,{cache:"no-store"});if(!b.ok)throw new Error(`Download failed (${b.status})`);const j=await b.blob();if(!await m(j)){p(`${d}?v=${Date.now()}`);return}const k=new Blob([j],{type:"application/zip"}),T=URL.createObjectURL(k),E=document.createElement("a");E.href=T,E.download="levelup-extension.zip",document.body.appendChild(E),E.click(),E.remove(),setTimeout(()=>URL.revokeObjectURL(T),1e3)}catch(b){he.error(b.message||"Download failed")}finally{o(!1)}},y=async()=>{n(!0);try{await V.auth.refreshSession();const{data:b}=await V.auth.getSession();if(!b.session){he.error("Your session has expired. Please sign in again.");return}const{data:j,error:k}=await V.functions.invoke("extension-pair-start",{headers:{Authorization:`Bearer ${b.session.access_token}`}});if(k)throw k;t(j.code),i(j.expires_in||300);const T=setInterval(()=>{i(E=>E<=1?(clearInterval(T),t(null),0):E-1)},1e3)}catch(b){console.error("generateCode error",b),he.error("We couldn't generate a pairing code",{description:"Please refresh the page and try again. If it still fails, sign out and sign back in, then click Generate pairing code.",duration:8e3})}finally{n(!1)}},_=()=>{s&&(navigator.clipboard.writeText(s),he.success("Copied"))};return e.jsx(Ss,{title:"Browser Extension",children:e.jsxs("div",{className:"container max-w-3xl mx-auto py-8 px-4 space-y-6",children:[e.jsxs(el,{children:[e.jsx("title",{children:"Browser Extension | LevelUp"}),e.jsx("meta",{name:"description",content:"Install the LevelUp browser extension to add contacts and import listings from any webpage."})]}),e.jsx("header",{className:"space-y-2",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-12 h-12 rounded-xl bg-primary text-primary-foreground flex items-center justify-center",children:e.jsx(fE,{className:"w-6 h-6"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Browser Extension"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Add contacts and import listings from anywhere on the web."})]})]})}),e.jsxs(ke,{className:"p-6 space-y-4 border-2 border-primary/20",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-6 h-6 rounded-full bg-primary text-primary-foreground flex items-center justify-center text-xs font-bold",children:"1"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Install from the Chrome Web Store"})]}),e.jsxs("ul",{className:"text-sm text-muted-foreground space-y-1 list-disc list-inside",children:[e.jsx("li",{children:"Quick-add contacts from any webpage with one click or right-click"}),e.jsx("li",{children:"Import listings from Zillow, Realtor.com, and Redfin as drafts"}),e.jsx("li",{children:'"Add to LevelUp" button on Gmail threads and LinkedIn profiles'}),e.jsx("li",{children:"Toolbar launcher with shortcuts to Dashboard, ReelFlow, Card Studio, and more"})]}),e.jsxs(H,{size:"lg",className:"w-full",onClick:()=>window.open(z9s,"_blank","noopener,noreferrer"),children:[e.jsx(fE,{className:"w-4 h-4 mr-2"}),"Add to Chrome",e.jsx(gn,{className:"w-3.5 h-3.5 ml-2 opacity-70"})]}),e.jsx("p",{className:"text-xs text-center text-muted-foreground",children:"Works in Chrome, Edge, Brave, and Arc. Free to install."})]}),e.jsxs(ke,{className:"p-6 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-6 h-6 rounded-full bg-primary text-primary-foreground flex items-center justify-center text-xs font-bold",children:"2"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Pair the extension"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Generate a one-time pairing code, then enter it inside the extension popup."}),s?e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"bg-muted rounded-xl p-6 text-center",children:[e.jsx("div",{className:"text-4xl font-mono font-bold tracking-[0.4em] text-primary",children:s}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-3",children:["Expires in ",Math.floor(a/60),":",String(a%60).padStart(2,"0")]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(H,{onClick:_,variant:"outline",className:"flex-1",children:[e.jsx(ui,{className:"w-4 h-4 mr-2"})," Copy"]}),e.jsxs(H,{onClick:y,variant:"outline",className:"flex-1",children:[e.jsx(po,{className:"w-4 h-4 mr-2"})," New code"]})]}),e.jsxs("div",{className:"flex items-start gap-2 text-sm text-muted-foreground bg-muted/50 rounded-lg p-3",children:[e.jsx(va,{className:"w-4 h-4 mt-0.5 text-primary"}),e.jsx("span",{children:"Click the LevelUp icon in your browser toolbar and paste this code. You only need to do this once per browser."})]})]}):e.jsx(H,{onClick:y,disabled:r,size:"lg",className:"w-full",children:r?e.jsxs(e.Fragment,{children:[e.jsx(po,{className:"w-4 h-4 mr-2 animate-spin"}),"Generating…"]}):"Generate pairing code"})]}),e.jsxs(ke,{className:"p-6 space-y-4 bg-muted/30 border-dashed",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(yc,{className:"w-5 h-5 text-muted-foreground"}),e.jsx("h2",{className:"text-base font-semibold text-muted-foreground",children:"Manual install (advanced)"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"If you prefer to load the extension unpacked, or the Web Store is unavailable, download the ZIP below."}),e.jsxs("ol",{className:"text-sm space-y-2 list-decimal list-inside text-muted-foreground",children:[e.jsx("li",{children:e.jsx(H,{variant:"link",className:"h-auto p-0 text-sm",onClick:x,disabled:l,children:"Download the extension ZIP"})}),e.jsx("li",{children:"Unzip the downloaded file"}),e.jsxs("li",{children:["Open"," ",e.jsx("code",{className:"px-1.5 py-0.5 rounded bg-muted text-foreground",children:"chrome://extensions"})," ","in Chrome, Edge, Brave, or Arc"]}),e.jsxs("li",{children:["Turn on ",e.jsx("b",{className:"text-foreground",children:"Developer mode"})," (top-right toggle)"]}),e.jsxs("li",{children:["Click ",e.jsx("b",{className:"text-foreground",children:"Load unpacked"})," and pick the unzipped folder"]}),e.jsx("li",{children:"Pin the LevelUp icon to your toolbar"})]})]})]})})}function U9s(){const[s]=Ed(),t=Fr(),[r,n]=S.useState("loading"),[a,i]=S.useState("Connecting your Gmail account...");return S.useEffect(()=>{(async()=>{const o=s.get("code"),c=s.get("error"),d=s.get("error_description"),h=s.get("state");if(c){n("error"),i(d||"Authorization was denied"),he.error("Connection failed: "+(d||c));return}if(!o){n("error"),i("No authorization code received"),he.error("No authorization code received");return}try{const{data:m,error:p}=await V.functions.invoke("gmail-oauth",{body:{action:"exchange_code",code:o,state:h}});if(p)throw p;if(m!=null&&m.success)n("success"),i(m.message||"Gmail connected successfully!"),he.success("Gmail connected!");else throw new Error((m==null?void 0:m.error)||"Unknown error")}catch(m){console.error("Gmail OAuth callback error:",m),n("error"),i(m instanceof Error?m.message:"Failed to connect Gmail"),he.error("Failed to connect: "+(m instanceof Error?m.message:"Unknown error"))}})()},[s]),e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsxs(ke,{className:"w-full max-w-md",children:[e.jsxs(Ot,{className:"text-center",children:[r==="loading"&&e.jsx(is,{className:"h-12 w-12 animate-spin mx-auto text-primary"}),r==="success"&&e.jsx(zi,{className:"h-12 w-12 mx-auto text-green-500"}),r==="error"&&e.jsx(kd,{className:"h-12 w-12 mx-auto text-destructive"}),e.jsxs(zt,{className:"mt-4",children:[r==="loading"&&"Connecting...",r==="success"&&"Connected!",r==="error"&&"Connection Failed"]}),e.jsx(Br,{children:a})]}),e.jsx(Oe,{className:"flex justify-center",children:r!=="loading"&&e.jsx(H,{onClick:()=>t("/mission-control/integrations"),children:r==="success"?"Back to Integrations":"Try Again"})})]})})}function q9s(){const s=Fr();return S.useEffect(()=>{const t=setTimeout(()=>{s("/mission-control/integrations",{replace:!0})},1500);return()=>clearTimeout(t)},[s]),e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background",children:e.jsxs("div",{className:"text-center space-y-4",children:[e.jsx("div",{className:"h-10 w-10 animate-spin rounded-full border-4 border-primary border-t-transparent mx-auto"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Finishing Canva connection…"})]})})}function V9s(){const[s]=Ed(),t=Fr(),[r,n]=S.useState("loading"),[a,i]=S.useState("Processing your connection...");return S.useEffect(()=>{(async()=>{var m;const o=s.get("code"),c=s.get("error"),d=s.get("error_description"),h=s.get("state");if(c){n("error"),i(d||"Authorization was denied"),he.error("Connection failed: "+(d||c));return}if(!o){n("error"),i("No authorization code received"),he.error("No authorization code received");return}try{const{data:p,error:x}=await V.functions.invoke("meta-oauth",{body:{action:"exchange_code",code:o,state:h,callbackPath:"/mission-control/integrations/meta/callback"}});if(p&&p.success===!1)throw new Error(p.error||"Failed to connect accounts");if(x){let y=x.message||"Failed to connect accounts";try{const _=x.context;if(_&&typeof _.json=="function"){const b=await _.json();b!=null&&b.error&&(y=b.error)}}catch{}throw new Error(y)}if(p!=null&&p.success)n("success"),i(`Successfully connected ${((m=p.accounts)==null?void 0:m.length)||0} account(s)!`),he.success("Social accounts connected successfully!");else throw new Error((p==null?void 0:p.error)||"Unknown error")}catch(p){console.error("OAuth callback error:",p),n("error"),i(p instanceof Error?p.message:"Failed to connect accounts"),he.error("Failed to connect: "+(p instanceof Error?p.message:"Unknown error"))}})()},[s]),e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsxs(ke,{className:"w-full max-w-md",children:[e.jsxs(Ot,{className:"text-center",children:[r==="loading"&&e.jsx(is,{className:"h-12 w-12 animate-spin mx-auto text-primary"}),r==="success"&&e.jsx(zi,{className:"h-12 w-12 mx-auto text-green-500"}),r==="error"&&e.jsx(kd,{className:"h-12 w-12 mx-auto text-destructive"}),e.jsxs(zt,{className:"mt-4",children:[r==="loading"&&"Connecting...",r==="success"&&"Connected!",r==="error"&&"Connection Failed"]}),e.jsx(Br,{children:a})]}),e.jsx(Oe,{className:"flex justify-center",children:r!=="loading"&&e.jsx(H,{onClick:()=>t("/mission-control/integrations"),children:r==="success"?"View Integrations":"Try Again"})})]})})}const Zyt=new Date().getFullYear(),H9s=Array.from({length:5},(s,t)=>Zyt-t);function G9s(){const[s,t]=S.useState(Zyt),r=Fr(),{data:n,isLoading:a}=YHt();return a?e.jsx(Ss,{title:"Scorecard Admin",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Ks,{className:"h-8 w-64"}),e.jsx("div",{className:"grid grid-cols-4 gap-4",children:[1,2,3,4].map(i=>e.jsx(Ks,{className:"h-24"},i))}),e.jsx(Ks,{className:"h-96"})]})}):e.jsx(Ss,{title:"Scorecard Admin",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Scorecard Admin"}),e.jsx("p",{className:"text-muted-foreground",children:"View agent performance and scorecards"})]}),e.jsxs(Bs,{value:String(s),onValueChange:i=>t(Number(i)),children:[e.jsx(Os,{className:"w-[120px]",children:e.jsx(Us,{})}),e.jsx(Fs,{children:H9s.map(i=>e.jsx(pt,{value:String(i),children:i},i))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(ke,{children:e.jsxs(Oe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Ar,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Agents Tracking"})]}),e.jsx("p",{className:"text-2xl font-bold",children:(n==null?void 0:n.length)||0})]})}),e.jsx(ke,{children:e.jsxs(Oe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Bo,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Total Agents"})]}),e.jsx("p",{className:"text-2xl font-bold",children:(n==null?void 0:n.length)||0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"with transactions"})]})})]}),e.jsxs(ke,{children:[e.jsxs(Ot,{children:[e.jsx(zt,{children:"Agents with Scorecards"}),e.jsx(Br,{children:"Click to view individual agent scorecards"})]}),e.jsx(Oe,{children:!n||n.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Bo,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No agents have added transactions yet"})]}):e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Vs,{children:[e.jsx(At,{children:"Agent"}),e.jsx(At,{children:"Email"}),e.jsx(At,{className:"text-right",children:"Actions"})]})}),e.jsx(da,{children:n.map(i=>e.jsxs(Vs,{children:[e.jsx(gt,{className:"font-medium",children:i.name}),e.jsx(gt,{className:"text-muted-foreground",children:i.email}),e.jsx(gt,{className:"text-right",children:e.jsxs(H,{variant:"ghost",size:"sm",onClick:()=>r(`/admin/scorecard/${i.id}`),children:[e.jsx(Bn,{className:"h-4 w-4 mr-2"}),"View Scorecard"]})})]},i.id))})]})})]})]})})}const Xyt=new Date().getFullYear(),W9s=Array.from({length:10},(s,t)=>Xyt-t);function _We(){var _;const{userId:s}=Po(),t=Fr(),n=Vc().pathname.startsWith("/mission-control"),[a,i]=S.useState(Xyt),{data:l,isLoading:o}=yt({queryKey:["agent-profile",s],queryFn:async()=>{const{data:b,error:j}=await V.from("profiles").select("id, name, email").eq("id",s).single();if(j)throw j;return b},enabled:!!s}),{data:c,isLoading:d}=jTe(a,s),{yearStats:h,lifetimeStats:m,isLoading:p,showCommission:x}=Eot(a,s),{data:y}=Tot(a,s);return o?e.jsx(Ss,{title:"Agent Scorecard",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Ks,{className:"h-8 w-64"}),e.jsx("div",{className:"grid grid-cols-4 gap-4",children:[1,2,3,4].map(b=>e.jsx(Ks,{className:"h-24"},b))})]})}):e.jsx(Ss,{title:`${l==null?void 0:l.name}'s Scorecard`,children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(H,{variant:"ghost",size:"icon",onClick:()=>t(n?"/mission-control/scorecard":"/admin/scorecard"),children:e.jsx(za,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:l==null?void 0:l.name}),e.jsx("p",{className:"text-muted-foreground",children:l==null?void 0:l.email})]})]}),e.jsxs(Bs,{value:String(a),onValueChange:b=>i(Number(b)),children:[e.jsx(Os,{className:"w-[120px]",children:e.jsx(Us,{})}),e.jsx(Fs,{children:W9s.map(b=>e.jsx(pt,{value:String(b),children:b},b))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-5 gap-4",children:[e.jsx(ke,{children:e.jsxs(Oe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Fn,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Transactions"})]}),e.jsx("p",{className:"text-2xl font-bold",children:h.totalTransactions}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[m.totalTransactions," lifetime"]})]})}),e.jsx(ke,{children:e.jsxs(Oe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Ar,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Buyer/Seller"})]}),e.jsxs("p",{className:"text-2xl font-bold",children:[h.buyerCount,"/",h.sellerCount]})]})}),e.jsx(ke,{children:e.jsxs(Oe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(oc,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Volume"})]}),e.jsx("p",{className:"text-2xl font-bold",children:sd(h.totalVolume,!0)})]})}),e.jsx(ke,{children:e.jsxs(Oe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(al,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Avg Price"})]}),e.jsx("p",{className:"text-2xl font-bold",children:sd(h.averagePrice,!0)})]})}),e.jsx(ke,{children:e.jsxs(Oe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Bc,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Top Source"})]}),e.jsx("p",{className:"text-lg font-bold truncate",children:((_=h.topLeadSource)==null?void 0:_.name)||"-"})]})})]}),y&&e.jsx(axt,{goals:y,stats:h,year:a,showCommission:x}),e.jsxs(ta,{defaultValue:"transactions",className:"space-y-4",children:[e.jsxs(Qn,{children:[e.jsx(ts,{value:"transactions",children:"Transactions"}),e.jsx(ts,{value:"charts",children:"Charts"}),e.jsxs(ts,{value:"map",children:[e.jsx(Qa,{className:"h-4 w-4 mr-1"}),"Map"]})]}),e.jsx(cs,{value:"transactions",children:e.jsx(uMe,{transactions:c||[],showCommission:x,isLoading:d})}),e.jsx(cs,{value:"charts",children:e.jsx(hMe,{stats:h,year:a})}),e.jsx(cs,{value:"map",children:e.jsx(mMe,{transactions:c||[],isLoading:d})})]})]})})}function K9s(){const s=ns(),[t,r]=S.useState(""),[n,a]=S.useState("all"),[i,l]=S.useState(null);Zat();const{data:o,refetch:c}=yt({queryKey:["listing-exchange-flag"],queryFn:async()=>{const{data:O}=await V.from("feature_flags").select("enabled").eq("key","listing_exchange_enabled").single();return(O==null?void 0:O.enabled)??!1}}),{data:d,isLoading:h}=yt({queryKey:["admin-listings"],queryFn:async()=>{const{data:O,error:$}=await V.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($)throw $;return O}}),{data:m}=yt({queryKey:["admin-listing-stats"],queryFn:async()=>{const{data:O}=await V.from("listings").select("id, is_approved, status"),{data:$}=await V.from("listing_shares").select("id"),{data:ee}=await V.from("listing_views").select("id"),{count:Z}=await V.from("listing_leads").select("id",{count:"exact",head:!0}),J=new Date(Date.now()-7*24*60*60*1e3).toISOString(),{count:K}=await V.from("listing_leads").select("id",{count:"exact",head:!0}).gte("created_at",J);return{total:(O==null?void 0:O.length)||0,pending:(O==null?void 0:O.filter(re=>!re.is_approved).length)||0,active:(O==null?void 0:O.filter(re=>re.status==="active").length)||0,totalShares:($==null?void 0:$.length)||0,totalViews:(ee==null?void 0:ee.length)||0,totalLeads:Z||0,leadsLast7:K||0}}}),{data:p}=yt({queryKey:["admin-listing-lead-counts"],queryFn:async()=>{const O={};let $=0;const ee=1e3;for(;;){const{data:Z,error:J}=await V.from("listing_leads").select("listing_id").range($,$+ee-1);if(J)throw J;if(!Z||Z.length===0)break;for(const K of Z)K.listing_id&&(O[K.listing_id]=(O[K.listing_id]||0)+1);if(Z.length{const{data:O,error:$}=await V.from("listing_leads").select("*").eq("listing_id",i.listingId).order("created_at",{ascending:!1});if($)throw $;return O}}),_=async(O,$,ee="submit_url")=>{try{const{data:{session:Z}}=await V.auth.getSession();if(!Z)return;const{data:J,error:K}=await V.functions.invoke("google-indexing",{body:{action:ee,listing_id:O,listing_slug:$}});if(K)throw K;if((J==null?void 0:J.configured)===!1)return;J!=null&&J.success&&he.success("Submitted to Google for indexing")}catch(Z){console.error("Google indexing submission failed:",Z)}},b=Pt({mutationFn:async()=>{const{data:{session:O}}=await V.auth.getSession();if(!O)throw new Error("Not authenticated");const{data:$,error:ee}=await V.functions.invoke("google-indexing",{body:{action:"submit_all"}});if(ee)throw ee;return $},onSuccess:O=>{if((O==null?void 0:O.configured)===!1){he.error("Google Indexing API not configured. Add the GOOGLE_INDEXING_SERVICE_ACCOUNT secret.");return}he.success(`Submitted ${(O==null?void 0:O.succeeded)||0} URLs to Google (${(O==null?void 0:O.failed)||0} failed)`)},onError:O=>{he.error("Failed to submit to Google"),console.error(O)}}),j=Pt({mutationFn:async({id:O,approved:$,slug:ee})=>{const{error:Z}=await V.from("listings").update({is_approved:$}).eq("id",O);if(Z)throw Z;return{id:O,approved:$,slug:ee}},onSuccess:O=>{s.invalidateQueries({queryKey:["admin-listings"]}),s.invalidateQueries({queryKey:["admin-listing-stats"]}),he.success(O.approved?"Listing approved":"Listing unapproved"),O.approved?_(O.id,O.slug||null,"submit_url"):_(O.id,O.slug||null,"remove_url")}}),k=Pt({mutationFn:async({id:O,featured:$})=>{const{error:ee}=await V.from("listings").update({is_featured:$}).eq("id",O);if(ee)throw ee},onSuccess:(O,{featured:$})=>{s.invalidateQueries({queryKey:["admin-listings"]}),he.success($?"Listing featured":"Listing unfeatured")}}),T=Pt({mutationFn:async O=>{const{error:$}=await V.from("listings").delete().eq("id",O);if($)throw $},onSuccess:()=>{s.invalidateQueries({queryKey:["admin-listings"]}),s.invalidateQueries({queryKey:["admin-listing-stats"]}),he.success("Listing deleted")}}),E=Pt({mutationFn:async O=>{const{error:$}=await V.from("feature_flags").update({enabled:O}).eq("key","listing_exchange_enabled");if($)throw $},onSuccess:()=>{c(),he.success("Feature flag updated")}}),A=o??!1,D=d==null?void 0:d.filter(O=>{var Z,J,K,re;const $=((Z=O.city)==null?void 0:Z.toLowerCase().includes(t.toLowerCase()))||((K=(J=O.agent)==null?void 0:J.name)==null?void 0:K.toLowerCase().includes(t.toLowerCase()))||((re=O.property_address)==null?void 0:re.toLowerCase().includes(t.toLowerCase())),ee=n==="all"||n==="pending"&&!O.is_approved||n==="approved"&&O.is_approved;return $&&ee}),R=O=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(O),z=O=>{const $={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 $[O]||$.active};return e.jsxs(Ss,{title:"Listing Exchange Admin",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Listing Exchange"}),e.jsx("p",{className:"text-muted-foreground",children:"Manage community listings"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(H,{variant:"outline",size:"sm",onClick:()=>b.mutate(),disabled:b.isPending,className:"gap-2",children:[b.isPending?e.jsx(is,{className:"h-4 w-4 animate-spin"}):e.jsx(ld,{className:"h-4 w-4"}),"Submit All to Google"]}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Feature visible to agents"}),e.jsx(Or,{checked:A,onCheckedChange:O=>E.mutate(O)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-6 gap-4",children:[e.jsx(ke,{children:e.jsxs(Oe,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Xa,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Total Listings"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:(m==null?void 0:m.total)||0})]})}),e.jsx(ke,{children:e.jsxs(Oe,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(al,{className:"h-4 w-4 text-green-500"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Active"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:(m==null?void 0:m.active)||0})]})}),e.jsx(ke,{children:e.jsxs(Oe,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ar,{className:"h-4 w-4 text-amber-500"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Pending Review"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:(m==null?void 0:m.pending)||0})]})}),e.jsx(ke,{children:e.jsxs(Oe,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Bn,{className:"h-4 w-4 text-blue-500"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Total Views"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:(m==null?void 0:m.totalViews)||0})]})}),e.jsx(ke,{children:e.jsxs(Oe,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(cd,{className:"h-4 w-4 text-purple-500"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Total Shares"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:(m==null?void 0:m.totalShares)||0})]})}),e.jsx(ke,{children:e.jsxs(Oe,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Vl,{className:"h-4 w-4 text-teal-600"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Leads"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:(m==null?void 0:m.totalLeads)||0}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:[(m==null?void 0:m.leadsLast7)||0," in last 7 days"]})]})})]}),e.jsx(ke,{children:e.jsx(Oe,{className:"p-4",children:e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Mn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Se,{placeholder:"Search by city, address, or agent...",value:t,onChange:O=>r(O.target.value),className:"pl-9"})]}),e.jsx(ta,{value:n,onValueChange:O=>a(O),children:e.jsxs(Qn,{children:[e.jsx(ts,{value:"all",children:"All"}),e.jsx(ts,{value:"pending",children:"Pending"}),e.jsx(ts,{value:"approved",children:"Approved"})]})})]})})}),e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsxs(zt,{children:["Listings (",(D==null?void 0:D.length)||0,")"]})}),e.jsx(Oe,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Vs,{children:[e.jsx(At,{children:"Property"}),e.jsx(At,{children:"Agent"}),e.jsx(At,{children:"Price"}),e.jsx(At,{children:"Status"}),e.jsx(At,{className:"text-center",children:"Approved"}),e.jsx(At,{className:"text-center",children:"Featured"}),e.jsx(At,{children:"Views"}),e.jsx(At,{children:"Shares"}),e.jsx(At,{children:"Leads"}),e.jsx(At,{children:"Date"}),e.jsx(At,{})]})}),e.jsx(da,{children:h?e.jsx(Vs,{children:e.jsx(gt,{colSpan:11,className:"text-center py-8 text-muted-foreground",children:"Loading..."})}):(D==null?void 0:D.length)===0?e.jsx(Vs,{children:e.jsx(gt,{colSpan:11,className:"text-center py-8 text-muted-foreground",children:"No listings found"})}):D==null?void 0:D.map(O=>{var $,ee,Z,J,K;return e.jsxs(Vs,{children:[e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[(ee=($=O.photos)==null?void 0:$[0])!=null&&ee.photo_url?e.jsx("img",{src:O.photos[0].photo_url,alt:"",className:"w-12 h-12 object-cover rounded"}):e.jsx("div",{className:"w-12 h-12 bg-muted rounded flex items-center justify-center",children:e.jsx(Xa,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:O.property_address||`${O.city}, ${O.state}`}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(Z=O.property_type)==null?void 0:Z.replace("_"," ")})]})]})}),e.jsx(gt,{children:e.jsx("p",{className:"text-sm",children:((J=O.agent)==null?void 0:J.name)||"Unknown"})}),e.jsx(gt,{className:"font-medium",children:R(O.price)}),e.jsx(gt,{children:e.jsx(Xe,{variant:"outline",className:z(O.status),children:(K=O.status)==null?void 0:K.replace("_"," ")})}),e.jsx(gt,{className:"text-center",children:e.jsx(Or,{checked:O.is_approved??!1,onCheckedChange:re=>j.mutate({id:O.id,approved:re,slug:O.slug})})}),e.jsx(gt,{className:"text-center",children:e.jsx(Or,{checked:O.is_featured??!1,onCheckedChange:re=>k.mutate({id:O.id,featured:re})})}),e.jsx(gt,{children:O.view_count||0}),e.jsx(gt,{children:O.share_count||0}),e.jsx(gt,{children:((p==null?void 0:p[O.id])??0)>0?e.jsx(H,{variant:"link",size:"sm",className:"px-0 h-auto font-semibold text-teal-600",onClick:()=>l({listingId:O.id,label:O.property_address||`${O.city}, ${O.state}`}),children:p==null?void 0:p[O.id]}):e.jsx("span",{className:"text-muted-foreground",children:"0"})}),e.jsx(gt,{className:"text-sm text-muted-foreground",children:As(new Date(O.created_at),"MMM d, yyyy")}),e.jsx(gt,{children:e.jsxs(Xu,{children:[e.jsx(Qu,{asChild:!0,children:e.jsx(H,{variant:"ghost",size:"icon",children:e.jsx(Jx,{className:"h-4 w-4"})})}),e.jsxs(wu,{align:"end",children:[e.jsxs(di,{onClick:()=>window.open(`/mission-control/listings/${O.id}`,"_blank"),children:[e.jsx(Bn,{className:"h-4 w-4 mr-2"}),"View Listing"]}),e.jsxs(di,{onClick:()=>k.mutate({id:O.id,featured:!O.is_featured}),children:[e.jsx(ya,{className:"h-4 w-4 mr-2"}),O.is_featured?"Unfeature":"Feature"]}),e.jsxs(di,{className:"text-destructive",onClick:()=>{confirm("Are you sure you want to delete this listing?")&&T.mutate(O.id)},children:[e.jsx(Rr,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})})]},O.id)})})]})})})]})]}),e.jsx(bs,{open:!!i,onOpenChange:O=>!O&&l(null),children:e.jsxs(vs,{className:"max-w-3xl max-h-[80vh] overflow-y-auto",children:[e.jsxs(Cs,{children:[e.jsx(Ns,{children:"Leads from listing"}),e.jsx(nn,{children:i==null?void 0:i.label})]}),y?e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx(is,{className:"h-5 w-5 animate-spin inline mr-2"}),"Loading leads..."]}):!x||x.length===0?e.jsx("div",{className:"py-8 text-center text-muted-foreground",children:"No leads yet."}):e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Vs,{children:[e.jsx(At,{children:"Name"}),e.jsx(At,{children:"Email"}),e.jsx(At,{children:"Phone"}),e.jsx(At,{children:"Type"}),e.jsx(At,{children:"Captured"})]})}),e.jsx(da,{children:x.map(O=>{var $;return e.jsxs(Vs,{children:[e.jsx(gt,{className:"font-medium",children:[O.first_name,O.last_name].filter(Boolean).join(" ")||"—"}),e.jsx(gt,{children:O.email}),e.jsx(gt,{children:O.phone||"—"}),e.jsx(gt,{children:e.jsx(Xe,{variant:"outline",children:($=O.lead_type)==null?void 0:$.replace("_"," ")})}),e.jsx(gt,{className:"text-sm text-muted-foreground",children:As(new Date(O.created_at),"MMM d, yyyy h:mm a")})]},O.id)})})]})]})})]})}const Y9s=()=>{var m,p;const[s,t]=S.useState(""),[r,n]=S.useState(null),{data:a,isLoading:i}=yt({queryKey:["membership-reviews"],queryFn:async()=>{const{data:x,error:y}=await V.from("membership_reviews").select("*").order("created_at",{ascending:!1});if(y)throw y;const _=(x==null?void 0:x.map(k=>k.user_id))||[],{data:b}=await V.from("profiles").select("id, name, email").in("id",_);return x==null?void 0:x.map(k=>({...k,profiles:(b==null?void 0:b.find(T=>T.id===k.user_id))||null}))}}),l=a==null?void 0:a.filter(x=>{var _,b,j,k,T;const y=s.toLowerCase();return((b=(_=x.profiles)==null?void 0:_.name)==null?void 0:b.toLowerCase().includes(y))||((k=(j=x.profiles)==null?void 0:j.email)==null?void 0:k.toLowerCase().includes(y))||((T=x.review_text)==null?void 0:T.toLowerCase().includes(y))}),o=a!=null&&a.length?(a.reduce((x,y)=>x+y.rating,0)/a.length).toFixed(1):"0.0",c=a==null?void 0:a.reduce((x,y)=>(x[y.rating]=(x[y.rating]||0)+1,x),{}),d=(a==null?void 0:a.filter(x=>x.posted_to_google).length)||0,h=x=>e.jsx("div",{className:"flex gap-0.5",children:[1,2,3,4,5].map(y=>e.jsx(ya,{className:Ft("h-4 w-4",x>=y?"fill-yellow-400 text-yellow-400":"text-muted-foreground")},y))});return e.jsx(Ss,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(km,{title:"Membership Reviews",description:"View and manage feedback from LevelUp members"}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-4",children:[e.jsx(ke,{children:e.jsxs(Ot,{className:"pb-2",children:[e.jsx(Br,{children:"Total Reviews"}),e.jsx(zt,{className:"text-3xl",children:(a==null?void 0:a.length)||0})]})}),e.jsx(ke,{children:e.jsxs(Ot,{className:"pb-2",children:[e.jsx(Br,{children:"Average Rating"}),e.jsxs(zt,{className:"flex items-center gap-2 text-3xl",children:[o,e.jsx(ya,{className:"h-6 w-6 fill-yellow-400 text-yellow-400"})]})]})}),e.jsx(ke,{children:e.jsxs(Ot,{className:"pb-2",children:[e.jsx(Br,{children:"5-Star Reviews"}),e.jsx(zt,{className:"text-3xl",children:(c==null?void 0:c[5])||0})]})}),e.jsx(ke,{children:e.jsxs(Ot,{className:"pb-2",children:[e.jsx(Br,{children:"Posted to Google"}),e.jsxs(zt,{className:"flex items-center gap-2 text-3xl",children:[d,e.jsx(gn,{className:"h-5 w-5 text-muted-foreground"})]})]})})]}),e.jsxs("div",{className:"relative max-w-sm",children:[e.jsx(Mn,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(Se,{placeholder:"Search by name, email, or review...",value:s,onChange:x=>t(x.target.value),className:"pl-9"})]}),e.jsx(ke,{children:e.jsx(Oe,{className:"p-0",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Vs,{children:[e.jsx(At,{children:"Member"}),e.jsx(At,{children:"Rating"}),e.jsx(At,{className:"hidden md:table-cell",children:"Review"}),e.jsx(At,{children:"Google"}),e.jsx(At,{children:"Date"})]})}),e.jsx(da,{children:i?e.jsx(Vs,{children:e.jsx(gt,{colSpan:5,className:"text-center py-8",children:"Loading reviews..."})}):(l==null?void 0:l.length)===0?e.jsx(Vs,{children:e.jsx(gt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No reviews found"})}):l==null?void 0:l.map(x=>{var y,_;return e.jsxs(Vs,{className:"cursor-pointer hover:bg-muted/50",onClick:()=>n(x),children:[e.jsx(gt,{children:e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:((y=x.profiles)==null?void 0:y.name)||"Unknown"}),e.jsx("div",{className:"text-sm text-muted-foreground",children:(_=x.profiles)==null?void 0:_.email})]})}),e.jsx(gt,{children:h(x.rating)}),e.jsx(gt,{className:"hidden md:table-cell max-w-xs",children:e.jsx("p",{className:"truncate text-sm text-muted-foreground",children:x.review_text||"-"})}),e.jsx(gt,{children:x.posted_to_google?e.jsx(Xe,{variant:"secondary",className:"bg-green-100 text-green-800",children:"Posted"}):e.jsx(Xe,{variant:"outline",children:"No"})}),e.jsx(gt,{className:"text-sm text-muted-foreground",children:As(new Date(x.created_at),"MMM d, yyyy")})]},x.id)})})]})})}),e.jsx(bs,{open:!!r,onOpenChange:()=>n(null),children:e.jsxs(vs,{className:"max-w-lg",children:[e.jsx(Cs,{children:e.jsx(Ns,{children:"Review Details"})}),r&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-4 p-4 bg-muted/50 rounded-lg",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"font-semibold text-lg",children:((m=r.profiles)==null?void 0:m.name)||"Unknown Member"}),((p=r.profiles)==null?void 0:p.email)&&e.jsxs("a",{href:`mailto:${r.profiles.email}`,className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-primary",children:[e.jsx(er,{className:"h-3 w-3"}),r.profiles.email]})]}),e.jsxs("div",{className:"text-right",children:[h(r.rating),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[r.rating," out of 5 stars"]})]})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-medium mb-2",children:"Review"}),e.jsx("p",{className:"text-sm text-muted-foreground whitespace-pre-wrap",children:r.review_text||"No written review provided."})]}),e.jsxs("div",{className:"flex items-center justify-between pt-4 border-t",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Nn,{className:"h-4 w-4"}),As(new Date(r.created_at),"MMMM d, yyyy 'at' h:mm a")]}),r.posted_to_google?e.jsxs(Xe,{variant:"secondary",className:"bg-green-100 text-green-800",children:[e.jsx(gn,{className:"h-3 w-3 mr-1"}),"Posted to Google"]}):e.jsx(Xe,{variant:"outline",children:"Not posted to Google"})]})]})]})})]})})},Z9s=[{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"}],X9s=Array.from({length:24},(s,t)=>({value:String(t),label:t===0?"12:00 AM":t<12?`${t}:00 AM`:t===12?"12:00 PM":`${t-12}:00 PM`}));function Q9s(){const s=ns(),{user:t}=Ms(),[r,n]=S.useState(!1),[a,i]=S.useState(!1),[l,o]=S.useState(!1),{data:c,isLoading:d}=yt({queryKey:["weekly-digest-settings"],queryFn:async()=>{const{data:z,error:O}=await V.from("weekly_digest_settings").select("*").single();if(O)throw O;return z}}),{data:h,isLoading:m}=yt({queryKey:["weekly-digest-logs"],queryFn:async()=>{const{data:z,error:O}=await V.from("weekly_digest_logs").select("*").order("sent_at",{ascending:!1}).limit(100);if(O)throw O;return z}}),{data:p}=yt({queryKey:["digest-subscriber-count"],queryFn:async()=>{const{count:z,error:O}=await V.from("profiles").select("id",{count:"exact",head:!0}).eq("digest_opt_out",!1).not("email","is",null);if(O)throw O;return z||0}}),{data:x,refetch:y}=yt({queryKey:["digest-queue-status"],queryFn:async()=>{const z=new Date;z.setUTCHours(0,0,0,0);const[O,$,ee,Z]=await Promise.all([V.from("weekly_digest_send_queue").select("id",{count:"exact",head:!0}).eq("status","pending").gte("created_at",z.toISOString()),V.from("weekly_digest_send_queue").select("id",{count:"exact",head:!0}).eq("status","processing").gte("created_at",z.toISOString()),V.from("weekly_digest_send_queue").select("id",{count:"exact",head:!0}).eq("status","sent").gte("created_at",z.toISOString()),V.from("weekly_digest_send_queue").select("id",{count:"exact",head:!0}).eq("status","failed").gte("created_at",z.toISOString())]);return{pending:O.count||0,processing:$.count||0,sent:ee.count||0,failed:Z.count||0,total:(O.count||0)+($.count||0)+(ee.count||0)+(Z.count||0)}},refetchInterval:5e3});S.useEffect(()=>{if(x&&(x.pending>0||x.processing>0)){const z=setInterval(()=>{y(),s.invalidateQueries({queryKey:["weekly-digest-logs"]}),s.invalidateQueries({queryKey:["digest-today-failed-count"]}),s.invalidateQueries({queryKey:["digest-today-missing-count"]})},5e3);return()=>clearInterval(z)}},[x,y,s]);const{data:_=0}=yt({queryKey:["digest-today-failed-count"],queryFn:async()=>{const z=new Date;z.setUTCHours(0,0,0,0);const{count:O,error:$}=await V.from("weekly_digest_logs").select("id",{count:"exact",head:!0}).eq("delivery_status","failed").gte("sent_at",z.toISOString());if($)throw $;return O||0}}),b=Pt({mutationFn:async z=>{const{error:O}=await V.from("weekly_digest_settings").update(z).eq("id",c==null?void 0:c.id);if(O)throw O},onSuccess:()=>{s.invalidateQueries({queryKey:["weekly-digest-settings"]}),he.success("Settings updated")},onError:z=>{he.error("Failed to update settings: "+z.message)}}),j=async()=>{n(!0);try{const{data:z,error:O}=await V.functions.invoke("send-weekly-digest",{body:{manual:!0}});if(O)throw O;z.queued?he.success(`${z.queued.toLocaleString()} emails queued! They'll be sent automatically (~80/minute).`):z.sent!==void 0&&he.success(`Digest sent! ${z.sent} emails delivered, ${z.failed} failed`),y(),s.invalidateQueries({queryKey:["weekly-digest-logs"]})}catch(z){he.error("Failed to send digest: "+z.message)}finally{n(!1)}},k=async()=>{var z,O,$,ee,Z,J;if(!(t!=null&&t.email)){he.error("No email found for your account");return}i(!0);try{const{data:K,error:re}=await V.functions.invoke("send-weekly-digest",{body:{preview:!0,previewEmail:t.email}});if(re)throw re;const ie=K==null?void 0:K.resendId,ce=K==null?void 0:K.resendDetails,ne=ce==null?void 0:ce.status,le=((z=ce==null?void 0:ce.body)==null?void 0:z.status)||(($=(O=ce==null?void 0:ce.body)==null?void 0:O.data)==null?void 0:$.status),be=((Z=(ee=ce==null?void 0:ce.body)==null?void 0:ee.error)==null?void 0:Z.message)||((J=ce==null?void 0:ce.body)==null?void 0:J.message);he.success(ie?`Preview accepted by email provider (id: ${ie})${ne?`, status check: ${ne}`:""}${le?`, provider: ${le}`:""}${be?` (${be})`:""}. Check spam/promotions—delivery can take a few minutes.`:"Preview accepted by email provider. Check spam/promotions—delivery can take a few minutes.")}catch(K){he.error("Failed to send preview: "+K.message)}finally{i(!1)}},T=async()=>{o(!0);try{const{data:z,error:O}=await V.functions.invoke("send-weekly-digest",{body:{retryFailed:!0}});if(O)throw O;z.queued===0||z.sent===0&&z.failed===0&&!z.queued?he.info("No failed emails to retry"):z.queued?he.success(`${z.queued} emails queued for retry!`):he.success(`Retry complete! ${z.sent} emails delivered, ${z.failed} failed`),y(),s.invalidateQueries({queryKey:["weekly-digest-logs"]}),s.invalidateQueries({queryKey:["digest-today-failed-count"]}),s.invalidateQueries({queryKey:["digest-today-missing-count"]})}catch(z){he.error("Failed to retry: "+z.message)}finally{o(!1)}},E=x!=null&&x.total?Math.round((x.sent+x.failed)/x.total*100):0,A=((x==null?void 0:x.pending)||0)>0||((x==null?void 0:x.processing)||0)>0,{data:D}=yt({queryKey:["digest-delivery-stats"],queryFn:async()=>{var J,K;const z=new Date;z.setUTCHours(0,0,0,0);const[O,$,ee,Z]=await Promise.all([V.from("weekly_digest_logs").select("id",{count:"exact",head:!0}).eq("delivery_status","sent").gte("sent_at",z.toISOString()),V.from("weekly_digest_logs").select("id",{count:"exact",head:!0}).eq("delivery_status","failed").gte("sent_at",z.toISOString()),V.from("weekly_digest_logs").select("id",{count:"exact",head:!0}).eq("has_agent_os_activity",!0).gte("sent_at",z.toISOString()),V.from("weekly_digest_logs").select("sent_at").order("sent_at",{ascending:!1}).limit(1)]);return{totalSent:O.count||0,totalFailed:$.count||0,agentOsEngaged:ee.count||0,lastSent:((K=(J=Z.data)==null?void 0:J[0])==null?void 0:K.sent_at)||null}},refetchInterval:A?5e3:!1}),R={totalSent:(D==null?void 0:D.totalSent)||0,totalFailed:(D==null?void 0:D.totalFailed)||0,lastSent:D==null?void 0:D.lastSent,agentOsEngaged:(D==null?void 0:D.agentOsEngaged)||0};return d?e.jsx(Ss,{title:"Weekly Digest",description:"Manage automated weekly email digests",children:e.jsxs("div",{className:"animate-pulse space-y-4",children:[e.jsx("div",{className:"h-32 bg-muted rounded-lg"}),e.jsx("div",{className:"h-64 bg-muted rounded-lg"})]})}):e.jsx(Ss,{title:"Weekly Digest",description:"Configure and manage automated weekly email digests for members",children:e.jsxs(ta,{defaultValue:"settings",className:"space-y-6",children:[e.jsxs(Qn,{children:[e.jsxs(ts,{value:"settings",className:"flex items-center gap-2",children:[e.jsx(Go,{className:"h-4 w-4"}),"Settings"]}),e.jsxs(ts,{value:"stats",className:"flex items-center gap-2",children:[e.jsx(Bo,{className:"h-4 w-4"}),"Delivery Stats"]})]}),e.jsxs(cs,{value:"settings",className:"space-y-6",children:[A&&x&&e.jsx(ke,{className:"border-primary/50 bg-primary/5",children:e.jsxs(Oe,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center gap-4 mb-4",children:[e.jsx(is,{className:"h-5 w-5 animate-spin text-primary"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"font-medium",children:"Sending emails..."}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[x.sent.toLocaleString()," sent, ",x.pending.toLocaleString()," pending",x.failed>0&&`, ${x.failed} failed`]})]}),e.jsxs("span",{className:"text-sm font-medium",children:[E,"%"]})]}),e.jsx(Mi,{value:E,className:"h-2"}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:["Processing ~80 emails per minute. Estimated time remaining: ~",Math.ceil(x.pending/80)," min"]})]})}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4",children:[e.jsx(ke,{children:e.jsx(Oe,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"p-3 rounded-full bg-primary/10",children:e.jsx(Ar,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:p}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Subscribers"})]})]})})}),e.jsx(ke,{children:e.jsx(Oe,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"p-3 rounded-full bg-emerald-500/10",children:e.jsx(ea,{className:"h-5 w-5 text-emerald-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:R.totalSent}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Delivered"})]})]})})}),e.jsx(ke,{children:e.jsx(Oe,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"p-3 rounded-full bg-destructive/10",children:e.jsx(kd,{className:"h-5 w-5 text-destructive"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:R.totalFailed}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Failed"})]})]})})}),e.jsx(ke,{children:e.jsx(Oe,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"p-3 rounded-full bg-primary/10",children:e.jsx(Pn,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:R.lastSent?As(new Date(R.lastSent),"MMM d"):"Never"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Last Sent"})]})]})})})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs(ke,{children:[e.jsxs(Ot,{children:[e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(Pn,{className:"h-5 w-5"}),"Schedule"]}),e.jsx(Br,{children:"Configure when the digest is sent"})]}),e.jsxs(Oe,{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ue,{children:"Enable Weekly Digest"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Send automated weekly emails to members"})]}),e.jsx(Or,{checked:c==null?void 0:c.is_enabled,onCheckedChange:z=>b.mutate({is_enabled:z})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Cron Frequency"}),e.jsxs(Bs,{value:(c==null?void 0:c.cron_frequency)||"daily",onValueChange:z=>b.mutate({cron_frequency:z}),children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"daily",children:"Daily (runs once at selected time)"}),e.jsx(pt,{value:"hourly",children:"Hourly (checks every hour)"})]})]}),e.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)."})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Day of Week"}),e.jsxs(Bs,{value:String(c==null?void 0:c.send_day),onValueChange:z=>b.mutate({send_day:parseInt(z)}),children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsx(Fs,{children:Z9s.map(z=>e.jsx(pt,{value:z.value,children:z.label},z.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Time (UTC)"}),e.jsxs(Bs,{value:String(c==null?void 0:c.send_hour),onValueChange:z=>b.mutate({send_hour:parseInt(z)}),disabled:(c==null?void 0:c.cron_frequency)==="daily",children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsx(Fs,{children:X9s.map(z=>e.jsx(pt,{value:z.value,children:z.label},z.value))})]})]})]}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(H,{onClick:k,disabled:a,variant:"outline",className:"flex-1",children:[e.jsx(Bn,{className:"h-4 w-4 mr-2"}),a?"Sending...":"Send Preview to Me"]}),e.jsxs(H,{onClick:j,disabled:r,className:"flex-1",children:[e.jsx(yn,{className:"h-4 w-4 mr-2"}),r?"Sending...":"Send to All"]})]}),_>0&&e.jsxs(H,{onClick:T,disabled:l,variant:"outline",className:"w-full",children:[e.jsx(po,{className:`h-4 w-4 mr-2 ${l?"animate-spin":""}`}),l?"Retrying...":`Retry ${_} Failed`]})]})]})]}),e.jsxs(ke,{children:[e.jsxs(Ot,{children:[e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(kn,{className:"h-5 w-5"}),"Content Sections"]}),e.jsx(Br,{children:"Choose what to include in the digest"})]}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(kn,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(ue,{children:"New Resources"})]}),e.jsx(Or,{checked:c==null?void 0:c.include_new_resources,onCheckedChange:z=>b.mutate({include_new_resources:z})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ar,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(ue,{children:"Community Highlights"})]}),e.jsx(Or,{checked:c==null?void 0:c.include_community_posts,onCheckedChange:z=>b.mutate({include_community_posts:z})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Bo,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(ue,{children:"Agent OS Stats"})]}),e.jsx(Or,{checked:c==null?void 0:c.include_agent_os_stats,onCheckedChange:z=>b.mutate({include_agent_os_stats:z})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Nn,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(ue,{children:"Upcoming Events"})]}),e.jsx(Or,{checked:c==null?void 0:c.include_upcoming_events,onCheckedChange:z=>b.mutate({include_upcoming_events:z})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Wu,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(ue,{children:"Goals Progress"})]}),e.jsx(Or,{checked:c==null?void 0:c.include_goals_progress,onCheckedChange:z=>b.mutate({include_goals_progress:z})})]})]})]})]}),e.jsxs(ke,{children:[e.jsxs(Ot,{children:[e.jsx(zt,{children:"Custom Introduction"}),e.jsx(Br,{children:"Personalize the intro message (optional)"})]}),e.jsx(Oe,{children:e.jsx(vr,{placeholder:"Here's what's new this week to help you grow your business...",value:(c==null?void 0:c.custom_intro_text)||"",onChange:z=>b.mutate({custom_intro_text:z.target.value||null}),rows:3})})]})]}),e.jsx(cs,{value:"stats",children:e.jsxs(ke,{children:[e.jsxs(Ot,{children:[e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(er,{className:"h-5 w-5"}),"Delivery History"]}),e.jsx(Br,{children:"Recent digest emails sent to members"})]}),e.jsx(Oe,{children:m?e.jsx("div",{className:"animate-pulse space-y-2",children:[1,2,3,4,5].map(z=>e.jsx("div",{className:"h-12 bg-muted rounded"},z))}):h&&h.length>0?e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Vs,{children:[e.jsx(At,{children:"Email"}),e.jsx(At,{children:"Sent At"}),e.jsx(At,{children:"Status"}),e.jsx(At,{children:"Resources"}),e.jsx(At,{children:"Agent OS"})]})}),e.jsx(da,{children:h.map(z=>e.jsxs(Vs,{children:[e.jsx(gt,{className:"font-medium",children:z.email_sent_to}),e.jsx(gt,{children:As(new Date(z.sent_at),"MMM d, yyyy h:mm a")}),e.jsx(gt,{children:e.jsx(Xe,{variant:z.delivery_status==="sent"?"default":"destructive",children:z.delivery_status})}),e.jsx(gt,{children:z.resources_count}),e.jsx(gt,{children:z.has_agent_os_activity?e.jsx(Xe,{variant:"secondary",children:"Active"}):e.jsx(Xe,{variant:"outline",children:"Not Started"})})]},z.id))})]}):e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(er,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No digests sent yet"}),e.jsx("p",{className:"text-sm",children:"Send your first digest to see delivery stats"})]})})]})})]})})}const J9s={first_event:"bg-emerald-100 text-emerald-800 dark:bg-emerald-900 dark:text-emerald-200",streak_3:"bg-orange-100 text-orange-800 dark:bg-orange-900 dark:text-orange-200",streak_5:"bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200",events_5:"bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200",events_10:"bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-200",events_25:"bg-amber-100 text-amber-800 dark:bg-amber-900 dark:text-amber-200"};function eBs(){var je,ve,We;const s=ns(),[t,r]=S.useState(""),[n,a]=S.useState(null),[i,l]=S.useState(!1),[o,c]=S.useState(!1),[d,h]=S.useState(""),[m,p]=S.useState(""),[x,y]=S.useState(!0),[_,b]=S.useState(!1),[j,k]=S.useState(""),[T,E]=S.useState(null),{data:A,isLoading:D}=yt({queryKey:["admin-agent-points"],queryFn:async()=>{const{data:Ve,error:Le}=await V.from("agent_attendance_stats").select("*").order("total_points",{ascending:!1});if(Le)throw Le;const Me=(Ve==null?void 0:Ve.map(Ie=>Ie.user_id))||[],{data:ze}=await V.from("profiles").select("id, name, email").in("id",Me),Pe=new Map((ze==null?void 0:ze.map(Ie=>[Ie.id,{name:Ie.name,email:Ie.email}]))||[]);return Ve==null?void 0:Ve.map(Ie=>({...Ie,profile:Pe.get(Ie.user_id)||null}))}}),{data:R}=yt({queryKey:["all-profiles-for-points",A],queryFn:async()=>{const Le=[];let Me=0;for(;;){const{data:ze,error:Pe}=await V.from("profiles").select("id, name, email").order("name").range(Me,Me+1e3-1);if(Pe)throw Pe;if(Le.push(...ze),!ze||ze.length<1e3)break;Me+=1e3}return Le}}),O=((R==null?void 0:R.filter(Ve=>!(A!=null&&A.some(Le=>Le.user_id===Ve.id))))||[]).filter(Ve=>{var Me,ze;if(!j)return!0;const Le=j.toLowerCase();return((Me=Ve.name)==null?void 0:Me.toLowerCase().includes(Le))||((ze=Ve.email)==null?void 0:ze.toLowerCase().includes(Le))}),{data:$,isLoading:ee}=yt({queryKey:["agent-point-history",n==null?void 0:n.user_id],queryFn:async()=>{if(!(n!=null&&n.user_id))return[];const{data:Ve,error:Le}=await V.from("agent_points").select("*").eq("user_id",n.user_id).order("created_at",{ascending:!1});if(Le)throw Le;return Ve},enabled:!!(n!=null&&n.user_id)&&o}),{data:Z}=yt({queryKey:["agent-badges",n==null?void 0:n.user_id],queryFn:async()=>{if(!(n!=null&&n.user_id))return[];const{data:Ve,error:Le}=await V.from("agent_badges").select("*").eq("user_id",n.user_id).order("earned_at",{ascending:!1});if(Le)throw Le;return Ve},enabled:!!(n!=null&&n.user_id)}),J=Pt({mutationFn:async({userId:Ve,points:Le,reason:Me})=>{const{error:ze}=await V.from("agent_points").insert({user_id:Ve,points:Le,reason:Me});if(ze)throw ze;const{data:Pe}=await V.from("agent_attendance_stats").select("total_points, spendable_points").eq("user_id",Ve).maybeSingle(),Ie=((Pe==null?void 0:Pe.total_points)||0)+Le,De=((Pe==null?void 0:Pe.spendable_points)||0)+Le,{error:pe}=await V.from("agent_attendance_stats").upsert({user_id:Ve,total_points:Math.max(0,Ie),spendable_points:Math.max(0,De),updated_at:new Date().toISOString()},{onConflict:"user_id"});if(pe)throw pe},onSuccess:()=>{s.invalidateQueries({queryKey:["admin-agent-points"]}),s.invalidateQueries({queryKey:["agent-point-history"]}),l(!1),h(""),p(""),he.success(x?"Points awarded successfully!":"Points deducted successfully!")},onError:Ve=>{console.error("Error modifying points:",Ve),he.error("Failed to modify points")}}),K=()=>{if(!n||!d||!m){he.error("Please fill in all fields");return}const Ve=parseInt(d);if(isNaN(Ve)||Ve<=0){he.error("Please enter a valid positive number");return}J.mutate({userId:n.user_id,points:x?Ve:-Ve,reason:m})},re=()=>{if(!T||!d||!m){he.error("Please fill in all fields");return}const Ve=parseInt(d);if(isNaN(Ve)||Ve<=0){he.error("Please enter a valid positive number");return}J.mutate({userId:T.id,points:Ve,reason:m},{onSuccess:()=>{b(!1),E(null),k("")}})},ie=(Ve,Le)=>{a(Ve),y(Le),l(!0)},ce=Ve=>{a(Ve),c(!0)},ne=A==null?void 0:A.filter(Ve=>{var Pe,Ie,De,pe;const Le=((Ie=(Pe=Ve.profile)==null?void 0:Pe.name)==null?void 0:Ie.toLowerCase())||"",Me=((pe=(De=Ve.profile)==null?void 0:De.email)==null?void 0:pe.toLowerCase())||"",ze=t.toLowerCase();return Le.includes(ze)||Me.includes(ze)}),le=(A==null?void 0:A.reduce((Ve,Le)=>Ve+Le.total_points,0))||0,be=(A==null?void 0:A.length)||0,fe=be>0?Math.round(le/be):0;return D?e.jsx(Ss,{title:"Agent Points",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Ks,{className:"h-8 w-64"}),e.jsx("div",{className:"grid grid-cols-3 gap-4",children:[1,2,3].map(Ve=>e.jsx(Ks,{className:"h-24"},Ve))}),e.jsx(Ks,{className:"h-96"})]})}):e.jsx(Ss,{title:"Agent Points",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Agent Points Management"}),e.jsx("p",{className:"text-muted-foreground",children:"Track, view, and manage agent gamification points"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsx(ke,{children:e.jsxs(Oe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Ar,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Total Agents"})]}),e.jsx("p",{className:"text-2xl font-bold",children:be}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"with points tracked"})]})}),e.jsx(ke,{children:e.jsxs(Oe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(To,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Total Points"})]}),e.jsx("p",{className:"text-2xl font-bold",children:le.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"awarded across all agents"})]})}),e.jsx(ke,{children:e.jsxs(Oe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(al,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Average Points"})]}),e.jsx("p",{className:"text-2xl font-bold",children:fe}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"per agent"})]})})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 items-start sm:items-center justify-between",children:[e.jsxs("div",{className:"relative max-w-sm w-full",children:[e.jsx(Mn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Se,{placeholder:"Search agents...",value:t,onChange:Ve=>r(Ve.target.value),className:"pl-10"})]}),e.jsxs(H,{onClick:()=>b(!0),children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Award Points to New Agent"]})]}),e.jsxs(ke,{children:[e.jsxs(Ot,{children:[e.jsx(zt,{children:"Agent Leaderboard"}),e.jsx(Br,{children:"All agents with their points, events, and streaks"})]}),e.jsx(Oe,{children:!ne||ne.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(To,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No agents with points yet"})]}):e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Vs,{children:[e.jsx(At,{className:"w-12",children:"#"}),e.jsx(At,{children:"Agent"}),e.jsx(At,{className:"text-center",children:"Total Points"}),e.jsx(At,{className:"text-center",children:"Spendable"}),e.jsx(At,{className:"text-center",children:"Events"}),e.jsx(At,{className:"text-center",children:"Streak"}),e.jsx(At,{className:"text-right",children:"Actions"})]})}),e.jsx(da,{children:ne.map((Ve,Le)=>{var Me,ze,Pe,Ie;return e.jsxs(Vs,{children:[e.jsx(gt,{className:"font-medium",children:Le<3?e.jsx("div",{className:`w-6 h-6 rounded-full flex items-center justify-center ${Le===0?"bg-yellow-100 text-yellow-700":Le===1?"bg-gray-100 text-gray-600":"bg-amber-100 text-amber-700"}`,children:Le+1}):e.jsx("span",{className:"text-muted-foreground",children:Le+1})}),e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Un,{className:"h-8 w-8",children:e.jsx(qn,{children:((ze=(Me=Ve.profile)==null?void 0:Me.name)==null?void 0:ze.charAt(0))||"?"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((Pe=Ve.profile)==null?void 0:Pe.name)||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(Ie=Ve.profile)==null?void 0:Ie.email})]})]})}),e.jsx(gt,{className:"text-center",children:e.jsxs(Xe,{variant:"secondary",className:"font-bold",children:[e.jsx(ya,{className:"h-3 w-3 mr-1"}),Ve.total_points]})}),e.jsx(gt,{className:"text-center",children:e.jsxs(Xe,{variant:"outline",className:"font-bold text-primary",children:[e.jsx(Di,{className:"h-3 w-3 mr-1"}),Ve.spendable_points||0]})}),e.jsx(gt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(Nn,{className:"h-3 w-3 text-muted-foreground"}),Ve.total_events_attended]})}),e.jsx(gt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(od,{className:"h-3 w-3 text-orange-500"}),Ve.current_streak]})}),e.jsx(gt,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx(H,{variant:"ghost",size:"sm",onClick:()=>ie(Ve,!0),title:"Award points",children:e.jsx(Ys,{className:"h-4 w-4 text-green-600"})}),e.jsx(H,{variant:"ghost",size:"sm",onClick:()=>ie(Ve,!1),title:"Deduct points",children:e.jsx(g_,{className:"h-4 w-4 text-red-600"})}),e.jsx(H,{variant:"ghost",size:"sm",onClick:()=>ce(Ve),title:"View history",children:e.jsx(BI,{className:"h-4 w-4"})})]})})]},Ve.user_id)})})]})})]}),e.jsx(bs,{open:i,onOpenChange:l,children:e.jsxs(vs,{children:[e.jsxs(Cs,{children:[e.jsx(Ns,{children:x?"Award Points":"Deduct Points"}),e.jsxs(nn,{children:[x?"Award":"Deduct"," points ",x?"to":"from"," ",((je=n==null?void 0:n.profile)==null?void 0:je.name)||"this agent"]})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"points",children:"Points Amount"}),e.jsx(Se,{id:"points",type:"number",min:"1",placeholder:"Enter points...",value:d,onChange:Ve=>h(Ve.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"reason",children:"Reason"}),e.jsx(vr,{id:"reason",placeholder:"Enter reason for this adjustment...",value:m,onChange:Ve=>p(Ve.target.value)})]})]}),e.jsxs(wn,{children:[e.jsx(H,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx(H,{onClick:K,disabled:J.isPending,className:x?"bg-green-600 hover:bg-green-700":"bg-red-600 hover:bg-red-700",children:J.isPending?"Saving...":x?"Award Points":"Deduct Points"})]})]})}),e.jsx(bs,{open:o,onOpenChange:c,children:e.jsxs(vs,{className:"max-w-2xl",children:[e.jsxs(Cs,{children:[e.jsxs(Ns,{children:["Point History: ",(ve=n==null?void 0:n.profile)==null?void 0:ve.name]}),e.jsx(nn,{children:"View all point transactions and badges for this agent"})]}),e.jsxs(ta,{defaultValue:"history",className:"w-full",children:[e.jsxs(Qn,{className:"grid w-full grid-cols-2",children:[e.jsx(ts,{value:"history",children:"Point History"}),e.jsx(ts,{value:"badges",children:"Badges"})]}),e.jsx(cs,{value:"history",className:"mt-4",children:ee?e.jsx("div",{className:"space-y-2",children:[1,2,3].map(Ve=>e.jsx(Ks,{className:"h-12"},Ve))}):!$||$.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(BI,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),e.jsx("p",{children:"No point history yet"})]}):e.jsx("div",{className:"max-h-80 overflow-y-auto space-y-2",children:$.map(Ve=>e.jsxs("div",{className:"flex items-center justify-between p-3 border rounded-lg",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"font-medium",children:Ve.reason}),e.jsx("p",{className:"text-xs text-muted-foreground",children:As(new Date(Ve.created_at),"MMM d, yyyy h:mm a")})]}),e.jsxs(Xe,{variant:Ve.points>=0?"default":"destructive",className:Ve.points>=0?"bg-green-100 text-green-800":"",children:[Ve.points>=0?"+":"",Ve.points]})]},Ve.id))})}),e.jsx(cs,{value:"badges",className:"mt-4",children:!Z||Z.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Bc,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),e.jsx("p",{children:"No badges earned yet"})]}):e.jsx("div",{className:"grid grid-cols-2 gap-3",children:Z.map(Ve=>e.jsxs("div",{className:`p-3 rounded-lg ${J9s[Ve.badge_type]||"bg-gray-100"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Bc,{className:"h-5 w-5"}),e.jsx("span",{className:"font-medium",children:Ve.badge_name})]}),Ve.badge_description&&e.jsx("p",{className:"text-xs mt-1 opacity-80",children:Ve.badge_description}),e.jsxs("p",{className:"text-xs mt-1 opacity-60",children:["Earned ",As(new Date(Ve.earned_at),"MMM d, yyyy")]})]},Ve.id))})})]})]})}),e.jsx(bs,{open:_,onOpenChange:Ve=>{b(Ve),Ve||(E(null),k(""),h(""),p(""))},children:e.jsxs(vs,{className:"max-w-md",children:[e.jsxs(Cs,{children:[e.jsx(Ns,{children:"Award Points to New Agent"}),e.jsx(nn,{children:"Select an agent who doesn't have points yet and award them points"})]}),e.jsx("div",{className:"space-y-4 py-4",children:T?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-3 p-3 bg-muted/50 rounded-lg",children:[e.jsx(Un,{className:"h-10 w-10",children:e.jsx(qn,{children:((We=T.name)==null?void 0:We.charAt(0))||"?"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"font-medium",children:T.name||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:T.email})]}),e.jsx(H,{variant:"ghost",size:"sm",onClick:()=>E(null),children:"Change"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"new-points",children:"Points Amount"}),e.jsx(Se,{id:"new-points",type:"number",min:"1",placeholder:"Enter points...",value:d,onChange:Ve=>h(Ve.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"new-reason",children:"Reason"}),e.jsx(vr,{id:"new-reason",placeholder:"Enter reason for awarding points...",value:m,onChange:Ve=>p(Ve.target.value)})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Search Agent"}),e.jsxs("div",{className:"relative",children:[e.jsx(Mn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Se,{placeholder:"Search by name or email...",value:j,onChange:Ve=>k(Ve.target.value),className:"pl-10"})]})]}),e.jsx("div",{className:"max-h-60 overflow-y-auto border rounded-lg",children:O.length===0?e.jsxs("div",{className:"text-center py-4 text-muted-foreground",children:[e.jsx(Ar,{className:"h-6 w-6 mx-auto mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:j?"No matching agents found":"All agents already have points"})]}):O.slice(0,20).map(Ve=>{var Le;return e.jsxs("button",{onClick:()=>E(Ve),className:"w-full flex items-center gap-3 p-3 hover:bg-muted/50 transition-colors border-b last:border-b-0 text-left",children:[e.jsx(Un,{className:"h-8 w-8",children:e.jsx(qn,{children:((Le=Ve.name)==null?void 0:Le.charAt(0))||"?"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:Ve.name||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:Ve.email})]})]},Ve.id)})})]})}),e.jsxs(wn,{children:[e.jsx(H,{variant:"outline",onClick:()=>b(!1),children:"Cancel"}),T&&e.jsxs(H,{onClick:re,disabled:J.isPending,className:"bg-green-600 hover:bg-green-700",children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Award Points"]})]})]})})]})})}function tBs(){const{data:s,isLoading:t}=JPt(),[r,n]=S.useState(null),[a,i]=S.useState(!1),[l,o]=S.useState(""),[c,d]=S.useState("all"),[h,m]=S.useState("newest"),[p,x]=S.useState("table"),y=S.useMemo(()=>(s==null?void 0:s.map(T=>T.user_id))||[],[s]),_=S.useMemo(()=>(s==null?void 0:s.map(T=>T.id))||[],[s]),{data:b}=yt({queryKey:["card-profiles-lookup",y],queryFn:async()=>{if(y.length===0)return{};const{data:T}=await V.from("profiles").select("id, name, email").in("id",y),E={};return T==null||T.forEach(A=>{E[A.id]={name:A.name||"",email:A.email||""}}),E},enabled:y.length>0}),{data:j}=yt({queryKey:["card-stats-all",_],queryFn:async()=>{if(_.length===0)return{};const T={};_.forEach(D=>{T[D]={views:0,leads:0}});const{data:E}=await V.from("agent_card_interactions").select("card_id").in("card_id",_).eq("interaction_type","card_view");E==null||E.forEach(D=>{T[D.card_id]&&T[D.card_id].views++});const{data:A}=await V.from("agent_card_leads").select("card_id").in("card_id",_);return A==null||A.forEach(D=>{T[D.card_id]&&T[D.card_id].leads++}),T},enabled:_.length>0}),k=S.useMemo(()=>{if(!s)return[];let T=[...s];if(c==="live"?T=T.filter(E=>E.is_published):c==="draft"&&(T=T.filter(E=>!E.is_published)),l.trim()){const E=l.toLowerCase();T=T.filter(A=>{var R,z;const D=b==null?void 0:b[A.user_id];return A.slug.toLowerCase().includes(E)||((R=D==null?void 0:D.name)==null?void 0:R.toLowerCase().includes(E))||((z=D==null?void 0:D.email)==null?void 0:z.toLowerCase().includes(E))})}return h==="newest"?T.sort((E,A)=>new Date(A.created_at).getTime()-new Date(E.created_at).getTime()):h==="oldest"?T.sort((E,A)=>new Date(E.created_at).getTime()-new Date(A.created_at).getTime()):h==="name"?T.sort((E,A)=>{var D,R;return(((D=b==null?void 0:b[E.user_id])==null?void 0:D.name)||"").localeCompare(((R=b==null?void 0:b[A.user_id])==null?void 0:R.name)||"")}):h==="slug"?T.sort((E,A)=>E.slug.localeCompare(A.slug)):h==="views_desc"?T.sort((E,A)=>{var D,R;return(((D=j==null?void 0:j[A.id])==null?void 0:D.views)||0)-(((R=j==null?void 0:j[E.id])==null?void 0:R.views)||0)}):h==="views_asc"?T.sort((E,A)=>{var D,R;return(((D=j==null?void 0:j[E.id])==null?void 0:D.views)||0)-(((R=j==null?void 0:j[A.id])==null?void 0:R.views)||0)}):h==="leads_desc"?T.sort((E,A)=>{var D,R;return(((D=j==null?void 0:j[A.id])==null?void 0:D.leads)||0)-(((R=j==null?void 0:j[E.id])==null?void 0:R.leads)||0)}):h==="leads_asc"&&T.sort((E,A)=>{var D,R;return(((D=j==null?void 0:j[E.id])==null?void 0:D.leads)||0)-(((R=j==null?void 0:j[A.id])==null?void 0:R.leads)||0)}),T},[s,c,l,h,b]);return e.jsxs(Ss,{title:"Digital Agent Cards",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Digital Agent Cards"}),e.jsx("p",{className:"text-muted-foreground",children:"Create and manage agent digital business cards"})]}),e.jsxs(H,{onClick:()=>i(!0),children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Create Card"]})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Mn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Se,{placeholder:"Search by name, email, or slug...",value:l,onChange:T=>o(T.target.value),className:"pl-9"})]}),e.jsxs(Bs,{value:c,onValueChange:d,children:[e.jsx(Os,{className:"w-full sm:w-36",children:e.jsx(Us,{placeholder:"Status"})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"all",children:"All Status"}),e.jsx(pt,{value:"live",children:"Live"}),e.jsx(pt,{value:"draft",children:"Draft"})]})]}),e.jsxs(Bs,{value:h,onValueChange:m,children:[e.jsx(Os,{className:"w-full sm:w-44",children:e.jsx(Us,{placeholder:"Sort by"})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"newest",children:"Newest First"}),e.jsx(pt,{value:"oldest",children:"Oldest First"}),e.jsx(pt,{value:"name",children:"Name A–Z"}),e.jsx(pt,{value:"slug",children:"Slug A–Z"}),e.jsx(pt,{value:"views_desc",children:"Most Views"}),e.jsx(pt,{value:"views_asc",children:"Fewest Views"}),e.jsx(pt,{value:"leads_desc",children:"Most Leads"}),e.jsx(pt,{value:"leads_asc",children:"Fewest Leads"})]})]}),e.jsxs("div",{className:"flex border rounded-md",children:[e.jsx(H,{variant:p==="table"?"default":"ghost",size:"sm",onClick:()=>x("table"),className:"rounded-r-none",children:e.jsx(YI,{className:"h-4 w-4"})}),e.jsx(H,{variant:p==="grid"?"default":"ghost",size:"sm",onClick:()=>x("grid"),className:"rounded-l-none",children:e.jsx(_g,{className:"h-4 w-4"})})]})]}),!t&&s&&s.length>0&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Showing ",k.length," of ",s.length," cards"]}),t?e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:[1,2,3].map(T=>e.jsx(Ks,{className:"h-48"},T))}):k.length>0?p==="table"?e.jsx(sBs,{cards:k,cardProfiles:b,cardStats:j,onEdit:n,sortBy:h,setSortBy:m}):e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:k.map(T=>e.jsx(rBs,{card:T,onEdit:()=>n(T),stats:j==null?void 0:j[T.id]},T.id))}):s&&s.length>0?e.jsx(ke,{children:e.jsxs(Oe,{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(Mn,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold mb-1",children:"No matching cards"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Try adjusting your search or filters"})]})}):e.jsx(ke,{children:e.jsxs(Oe,{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(Ar,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold mb-1",children:"No cards yet"}),e.jsx("p",{className:"text-muted-foreground text-sm mb-4",children:"Create your first digital agent card"}),e.jsxs(H,{onClick:()=>i(!0),children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Create Card"]})]})})]}),e.jsx(nBs,{open:a,onOpenChange:i}),r&&e.jsx(aBs,{card:r,open:!!r,onOpenChange:T=>!T&&n(null)})]})}function sBs({cards:s,cardProfiles:t,cardStats:r,onEdit:n,sortBy:a,setSortBy:i}){const l=c=>{a===`${c}_desc`?i(`${c}_asc`):i(`${c}_desc`)},o=({field:c})=>a===`${c}_desc`?e.jsx(fm,{className:"h-3 w-3"}):a===`${c}_asc`?e.jsx(Hu,{className:"h-3 w-3"}):e.jsx(qu,{className:"h-3 w-3 opacity-40"});return e.jsx(ke,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b bg-muted/50",children:[e.jsx("th",{className:"text-left p-3 font-medium",children:e.jsxs("button",{onClick:()=>{i(a==="name"?"newest":"name")},className:"flex items-center gap-1 hover:text-foreground text-muted-foreground",children:["Agent ",a==="name"&&e.jsx(Hu,{className:"h-3 w-3"})]})}),e.jsx("th",{className:"text-left p-3 font-medium text-muted-foreground hidden md:table-cell",children:"Slug"}),e.jsx("th",{className:"text-center p-3 font-medium text-muted-foreground",children:"Status"}),e.jsx("th",{className:"text-right p-3 font-medium",children:e.jsxs("button",{onClick:()=>l("views"),className:"flex items-center gap-1 ml-auto hover:text-foreground text-muted-foreground",children:["Views ",e.jsx(o,{field:"views"})]})}),e.jsx("th",{className:"text-right p-3 font-medium",children:e.jsxs("button",{onClick:()=>l("leads"),className:"flex items-center gap-1 ml-auto hover:text-foreground text-muted-foreground",children:["Leads ",e.jsx(o,{field:"leads"})]})}),e.jsx("th",{className:"text-right p-3 font-medium text-muted-foreground",children:"Actions"})]})}),e.jsx("tbody",{children:s.map(c=>{const d=t==null?void 0:t[c.user_id],h=r==null?void 0:r[c.id],m=`https://cards.relevelup.com/${c.slug}`;return e.jsxs("tr",{className:"border-b last:border-0 hover:bg-muted/30 transition-colors",children:[e.jsx("td",{className:"p-3",children:e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:(d==null?void 0:d.name)||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(d==null?void 0:d.email)||""})]})}),e.jsx("td",{className:"p-3 hidden md:table-cell",children:e.jsxs("span",{className:"text-xs text-muted-foreground font-mono",children:["/",c.slug]})}),e.jsx("td",{className:"p-3 text-center",children:e.jsx(Xe,{variant:c.is_published?"default":"secondary",className:"text-xs",children:c.is_published?"Live":"Draft"})}),e.jsx("td",{className:"p-3 text-right tabular-nums font-medium",children:(h==null?void 0:h.views)??0}),e.jsx("td",{className:"p-3 text-right tabular-nums font-medium",children:(h==null?void 0:h.leads)??0}),e.jsx("td",{className:"p-3",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx(H,{variant:"ghost",size:"sm",onClick:()=>n(c),className:"h-8 w-8 p-0",children:e.jsx(ni,{className:"h-3.5 w-3.5"})}),e.jsx(H,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>{navigator.clipboard.writeText(m),he.success("Link copied!")},children:e.jsx(ui,{className:"h-3.5 w-3.5"})}),e.jsx(H,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",asChild:!0,children:e.jsx("a",{href:m,target:"_blank",rel:"noopener noreferrer",children:e.jsx(gn,{className:"h-3.5 w-3.5"})})})]})})]},c.id)})})]})})})}function rBs({card:s,onEdit:t,stats:r}){const[n,a]=S.useState(null);S.useEffect(()=>{(async()=>{const{data:c}=await V.from("profiles").select("name").eq("id",s.user_id).single();let d=null;try{const{data:h}=await V.storage.from("avatars").list(`${s.user_id}`);if(h&&h.length>0){const{data:m}=V.storage.from("avatars").getPublicUrl(`${s.user_id}/${h[0].name}`);d=m.publicUrl}}catch{}a({name:(c==null?void 0:c.name)||"Unknown",avatar_url:d})})()},[s.user_id]);const i=`https://cards.relevelup.com/${s.slug}`,l=()=>{navigator.clipboard.writeText(i),he.success("Link copied!")};return e.jsx(ke,{children:e.jsxs(Oe,{className:"p-4",children:[e.jsxs("div",{className:"flex items-start gap-3 mb-3",children:[e.jsxs(Un,{className:"h-10 w-10",children:[e.jsx(Ka,{src:(n==null?void 0:n.avatar_url)||void 0}),e.jsx(qn,{children:((n==null?void 0:n.name)||"U")[0]})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-semibold truncate",children:(n==null?void 0:n.name)||"Loading..."}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:["/card/",s.slug]})]}),e.jsx(Xe,{variant:s.is_published?"default":"secondary",children:s.is_published?"Live":"Draft"})]}),e.jsxs("div",{className:"flex items-center gap-3 mb-3 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Bn,{className:"h-3.5 w-3.5"}),(r==null?void 0:r.views)??0," views"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ar,{className:"h-3.5 w-3.5"}),(r==null?void 0:r.leads)??0," leads"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(H,{variant:"outline",size:"sm",onClick:t,className:"flex-1",children:[e.jsx(ni,{className:"h-3 w-3 mr-1"}),"Edit"]}),e.jsx(H,{variant:"outline",size:"sm",onClick:l,children:e.jsx(ui,{className:"h-3 w-3"})}),e.jsx(H,{variant:"outline",size:"sm",asChild:!0,children:e.jsx("a",{href:i,target:"_blank",rel:"noopener noreferrer",children:e.jsx(gn,{className:"h-3 w-3"})})})]})]})})}function nBs({open:s,onOpenChange:t}){const[r,n]=S.useState(""),[a,i]=S.useState(""),[l,o]=S.useState(""),[c,d]=S.useState(!1),h=Yst(),m=l.trim(),{data:p}=yt({queryKey:["profiles-search-for-cards",m],queryFn:async()=>{let k=V.from("profiles").select("id, name, email").order("name").limit(50);m.length>=2&&(k=k.or(`name.ilike.%${m}%,email.ilike.%${m}%`));const{data:T}=await k;return T||[]},enabled:s}),[x,y]=S.useState(null),_=(p==null?void 0:p.find(k=>k.id===r))||x,b=()=>{if(!r||!a.trim()){he.error("Select an agent and enter a slug");return}h.mutate({user_id:r,slug:a.trim().toLowerCase().replace(/[^a-z0-9-]/g,"-"),is_published:!0},{onSuccess:()=>{t(!1),n(""),i(""),o("")}})},j=k=>{var E;n(k),d(!1);const T=p==null?void 0:p.find(A=>A.id===k);T&&(y(T),i(((E=T.name)==null?void 0:E.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,""))||""))};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{children:[e.jsxs(Cs,{children:[e.jsx(Ns,{children:"Create Agent Card"}),e.jsx(nn,{children:"Select an agent and set their card URL slug."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ue,{children:"Agent"}),e.jsxs(gl,{open:c,onOpenChange:d,children:[e.jsx(xl,{asChild:!0,children:e.jsxs(H,{variant:"outline",role:"combobox","aria-expanded":c,className:"w-full justify-between font-normal",children:[_?`${_.name} (${_.email})`:"Search for an agent...",e.jsx(d0,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(il,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(k0,{shouldFilter:!1,children:[e.jsx(S0,{placeholder:"Search by name or email...",value:l,onValueChange:o}),e.jsxs(C0,{children:[e.jsx(T0,{children:"No agents found."}),e.jsx(E0,{children:(p||[]).map(k=>e.jsxs(fg,{value:k.id,onSelect:j,children:[e.jsx(va,{className:Ft("mr-2 h-4 w-4",r===k.id?"opacity-100":"opacity-0")}),k.name," (",k.email,")"]},k.id))})]})]})})]})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"URL Slug"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"/card/"}),e.jsx(Se,{value:a,onChange:k=>i(k.target.value),placeholder:"john-doe"})]})]}),e.jsx(H,{onClick:b,disabled:h.isPending,className:"w-full",children:h.isPending?"Creating...":"Create Card"})]})]})})}function aBs({card:s,open:t,onOpenChange:r}){const n=Zst(),{data:a}=Xst(s.id),i=ns(),[l,o]=S.useState(null),[c,d]=S.useState(!1),[h,m]=S.useState(!1),[p,x]=S.useState(""),[y,_]=S.useState(s.slug),[b,j]=S.useState(!1),[k,T]=S.useState({is_published:s.is_published,theme:s.theme,title:s.title||"",positioning_statement:s.positioning_statement||"",bio:s.bio||"",review_snippet:s.review_snippet||"",review_source_url:s.review_source_url||"",booking_url:s.booking_url||"",custom_cta_label:s.custom_cta_label||"",custom_cta_url:s.custom_cta_url||"",show_photo:s.show_photo,show_bio:s.show_bio,show_credentials:s.show_credentials,show_social_links:s.show_social_links,show_save_contact:s.show_save_contact,show_leave_review:s.show_leave_review,show_refer_friend:s.show_refer_friend,brokerage_display_name:s.brokerage_display_name||"",brokerage_logo_url:s.brokerage_logo_url||"",brokerage_logo_size:s.brokerage_logo_size||56,team_name:s.team_name||"",team_logo_url:s.team_logo_url||"",team_logo_size:s.team_logo_size||56});S.useEffect(()=>{t&&(async()=>{try{const{data:$}=await V.storage.from("avatars").list(`${s.user_id}`);if($&&$.length>0){const{data:ee}=V.storage.from("avatars").getPublicUrl(`${s.user_id}/${$[0].name}`);o(`${ee.publicUrl}?t=${Date.now()}`)}}catch{}})()},[s.user_id,t]);const E=O=>{var Z;const $=(Z=O.target.files)==null?void 0:Z[0];if(!$)return;if(!$.type.startsWith("image/")){he.error("Please select an image file");return}if($.size>5*1024*1024){he.error("Image must be under 5MB");return}const ee=new FileReader;ee.onloadend=()=>{x(ee.result),m(!0)},ee.readAsDataURL($),O.target.value=""},A=async O=>{d(!0);try{const{data:$}=await V.storage.from("avatars").list(`${s.user_id}`);$&&$.length>0&&await V.storage.from("avatars").remove($.map(re=>`${s.user_id}/${re.name}`));const ee=`${s.user_id}/avatar.jpg`,{error:Z}=await V.storage.from("avatars").upload(ee,O,{upsert:!0,contentType:"image/jpeg"});if(Z)throw Z;const{data:J}=V.storage.from("avatars").getPublicUrl(ee),K=`${J.publicUrl}?t=${Date.now()}`;o(K),await V.from("profiles").update({avatar_url:K}).eq("id",s.user_id),i.invalidateQueries({queryKey:["agent-card-public"]}),he.success("Photo updated!")}catch($){he.error($.message||"Upload failed")}finally{d(!1)}},D=async()=>{const O=y.trim().toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/(^-|-$)/g,"");if(!O){he.error("Please enter a valid URL");return}if(O===s.slug){he.info("No changes to save");return}j(!0);try{const{data:$}=await V.from("agent_cards").select("id").eq("slug",O).neq("id",s.id).maybeSingle();if($){he.error("This URL is already taken. Try another one.");return}const{error:ee}=await V.from("agent_cards").update({slug:O}).eq("id",s.id);if(ee)throw ee;_(O),i.invalidateQueries({queryKey:["agent-cards-admin"]}),he.success("Card address updated!")}catch{he.error("Failed to update card address")}finally{j(!1)}},R=async(O,$)=>{var Z;const ee=(Z=O.target.files)==null?void 0:Z[0];if(ee){if(!ee.type.startsWith("image/")){he.error("Please select an image file");return}try{const J=ee.name.split(".").pop()||"png",K=$==="brokerage_logo_url"?"brokerage-logo":"team-logo",re=`${s.user_id}/${K}.${J}`,{error:ie}=await V.storage.from("card-logos").upload(re,ee,{upsert:!0});if(ie)throw ie;const{data:ce}=V.storage.from("card-logos").getPublicUrl(re),ne=ce.publicUrl+"?t="+Date.now();T($==="brokerage_logo_url"?le=>({...le,[$]:ne,brokerage_display_name:""}):le=>({...le,[$]:ne,team_name:""})),he.success("Logo uploaded!")}catch{he.error("Failed to upload logo")}finally{O.target.value=""}}},z=()=>{n.mutate({id:s.id,...k,title:k.title||null,positioning_statement:k.positioning_statement||null,bio:k.bio||null,review_snippet:k.review_snippet||null,review_source_url:k.review_source_url||null,booking_url:k.booking_url||null,custom_cta_label:k.custom_cta_label||null,custom_cta_url:k.custom_cta_url||null,brokerage_display_name:k.brokerage_display_name||null,brokerage_logo_url:k.brokerage_logo_url||null,brokerage_logo_size:k.brokerage_logo_size,team_name:k.team_name||null,team_logo_url:k.team_logo_url||null,team_logo_size:k.team_logo_size},{onSuccess:()=>r(!1)})};return e.jsxs(e.Fragment,{children:[e.jsx(bs,{open:t,onOpenChange:r,children:e.jsxs(vs,{className:"max-w-2xl max-h-[85vh] overflow-y-auto",children:[e.jsxs(Cs,{children:[e.jsx(Ns,{children:"Edit Agent Card"}),e.jsxs(nn,{children:["/card/",s.slug]})]}),e.jsxs(ta,{defaultValue:"content",children:[e.jsxs(Qn,{className:"w-full",children:[e.jsx(ts,{value:"content",className:"flex-1",children:"Content"}),e.jsx(ts,{value:"sections",className:"flex-1",children:"Sections"}),e.jsx(ts,{value:"blocks",className:"flex-1",children:"Blocks"}),e.jsx(ts,{value:"analytics",className:"flex-1",children:"Analytics"})]}),e.jsxs(cs,{value:"content",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ue,{children:"Published"}),e.jsx(Or,{checked:k.is_published,onCheckedChange:O=>T($=>({...$,is_published:O}))})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Agent Photo"}),e.jsxs("div",{className:"flex items-center gap-4 mt-1",children:[e.jsxs(Un,{className:"h-16 w-16",children:[e.jsx(Ka,{src:l||void 0}),e.jsx(qn,{children:"?"})]}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:E,disabled:c}),e.jsx(H,{variant:"outline",size:"sm",asChild:!0,disabled:c,children:e.jsx("span",{children:c?e.jsxs(e.Fragment,{children:[e.jsx(is,{className:"h-3 w-3 mr-1 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ea,{className:"h-3 w-3 mr-1"}),"Change Photo"]})})})]})]})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Card Address"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsxs("div",{className:"flex flex-1",children:[e.jsx("span",{className:"inline-flex items-center px-3 rounded-l-md border border-r-0 bg-muted text-muted-foreground text-xs whitespace-nowrap",children:"cards.relevelup.com/"}),e.jsx(Se,{value:y,onChange:O=>_(O.target.value.toLowerCase().replace(/[^a-z0-9-]/g,"-")),placeholder:"agent-name",className:"rounded-l-none"})]}),e.jsx(H,{variant:"outline",size:"sm",onClick:D,disabled:b||y===s.slug,className:"shrink-0",children:b?"Saving...":"Update"})]})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Theme"}),e.jsxs(Bs,{value:k.theme,onValueChange:O=>T($=>({...$,theme:O})),children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"standard",children:"✨ Standard (Modern Clean)"}),e.jsx(pt,{value:"luxury",children:"🌙 Luxury (Dark & Gold)"}),e.jsx(pt,{value:"bold",children:"🔥 Bold (Vibrant & Punchy)"}),e.jsx(pt,{value:"classic",children:"📋 Classic (Professional)"})]})]})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Title / Tagline"}),e.jsx(Se,{value:k.title,onChange:O=>T($=>({...$,title:O.target.value})),placeholder:"e.g. Luxury Real Estate Specialist"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Shown below the agent's name on the card"})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Positioning Statement"}),e.jsx(Se,{value:k.positioning_statement,onChange:O=>T($=>({...$,positioning_statement:O.target.value})),placeholder:"Your home journey, handled with care."})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Bio"}),e.jsx(vr,{value:k.bio,onChange:O=>T($=>({...$,bio:O.target.value})),placeholder:"Short about me...",rows:3})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Review Snippet"}),e.jsx(Se,{value:k.review_snippet,onChange:O=>T($=>({...$,review_snippet:O.target.value})),placeholder:"Best agent we've ever worked with..."})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Review Source URL"}),e.jsx(Se,{value:k.review_source_url,onChange:O=>T($=>({...$,review_source_url:O.target.value})),placeholder:"https://g.page/your-business/review"})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Booking URL (optional — if empty, shows lead form)"}),e.jsx(Se,{value:k.booking_url,onChange:O=>T($=>({...$,booking_url:O.target.value})),placeholder:"https://calendly.com/your-link"})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Custom CTA Label (optional)"}),e.jsx(Se,{value:k.custom_cta_label,onChange:O=>T($=>({...$,custom_cta_label:O.target.value})),placeholder:"Book a Call"})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Custom CTA URL (optional)"}),e.jsx(Se,{value:k.custom_cta_url,onChange:O=>T($=>({...$,custom_cta_url:O.target.value})),placeholder:"https://example.com/landing"})]}),e.jsxs("div",{className:"space-y-3 p-3 rounded-lg bg-muted/30 border",children:[e.jsx(ue,{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Brokerage Branding"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Se,{value:k.brokerage_display_name,onChange:O=>T($=>({...$,brokerage_display_name:O.target.value,brokerage_logo_url:""})),placeholder:"Brokerage name (or upload logo below)",disabled:!!k.brokerage_logo_url}),e.jsxs("div",{className:"flex items-center gap-3",children:[k.brokerage_logo_url&&e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:k.brokerage_logo_url,alt:"Brokerage logo",style:{height:`${k.brokerage_logo_size||56}px`},className:"max-w-[200px] object-contain rounded border bg-white p-1"}),e.jsx("button",{onClick:()=>T(O=>({...O,brokerage_logo_url:""})),className:"absolute -top-1.5 -right-1.5 h-5 w-5 rounded-full bg-destructive text-destructive-foreground text-xs flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity",children:"×"})]}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 px-3 py-1.5 rounded-md border text-xs font-medium hover:bg-muted transition-colors",children:[e.jsx(Ea,{className:"h-3.5 w-3.5"}),k.brokerage_logo_url?"Change Logo":"Upload Logo"]}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:O=>R(O,"brokerage_logo_url")})]})]}),k.brokerage_logo_url&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ue,{className:"text-xs font-medium text-muted-foreground",children:"Logo Size"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[k.brokerage_logo_size||56,"px"]})]}),e.jsx(f1,{value:[k.brokerage_logo_size||56],onValueChange:([O])=>T($=>({...$,brokerage_logo_size:O})),min:24,max:120,step:4})]})]})]}),e.jsxs("div",{className:"space-y-3 p-3 rounded-lg bg-muted/30 border",children:[e.jsx(ue,{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Team Branding"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Se,{value:k.team_name,onChange:O=>T($=>({...$,team_name:O.target.value,team_logo_url:""})),placeholder:"Team name (or upload logo below)",disabled:!!k.team_logo_url}),e.jsxs("div",{className:"flex items-center gap-3",children:[k.team_logo_url&&e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:k.team_logo_url,alt:"Team logo",style:{height:`${k.team_logo_size||56}px`},className:"max-w-[200px] object-contain rounded border bg-white p-1"}),e.jsx("button",{onClick:()=>T(O=>({...O,team_logo_url:""})),className:"absolute -top-1.5 -right-1.5 h-5 w-5 rounded-full bg-destructive text-destructive-foreground text-xs flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity",children:"×"})]}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 px-3 py-1.5 rounded-md border text-xs font-medium hover:bg-muted transition-colors",children:[e.jsx(Ea,{className:"h-3.5 w-3.5"}),k.team_logo_url?"Change Logo":"Upload Logo"]}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:O=>R(O,"team_logo_url")})]})]}),k.team_logo_url&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ue,{className:"text-xs font-medium text-muted-foreground",children:"Logo Size"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[k.team_logo_size||56,"px"]})]}),e.jsx(f1,{value:[k.team_logo_size||56],onValueChange:([O])=>T($=>({...$,team_logo_size:O})),min:24,max:120,step:4})]})]})]})]}),e.jsx(cs,{value:"sections",className:"space-y-4 mt-4",children:[{key:"show_photo",label:"Show Photo",hint:"Photo is pulled from the agent's profile."},{key:"show_bio",label:"Show Bio"},{key:"show_credentials",label:"Show Credentials"},{key:"show_social_links",label:"Show Social Links"},{key:"show_save_contact",label:"Save Contact Button"},{key:"show_leave_review",label:"Leave Review Button"},{key:"show_refer_friend",label:"Refer a Friend Button"}].map(({key:O,label:$,hint:ee})=>e.jsxs("div",{className:"flex items-center justify-between py-2",children:[e.jsxs("div",{children:[e.jsx(ue,{children:$}),ee&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:[ee," ",O==="show_photo"&&e.jsx("a",{href:"/profile",target:"_blank",rel:"noopener noreferrer",className:"text-primary underline hover:no-underline",children:"Update Profile"})]})]}),e.jsx(Or,{checked:k[O],onCheckedChange:Z=>T(J=>({...J,[O]:Z}))})]},O))}),e.jsx(cs,{value:"blocks",className:"mt-4",children:e.jsx(Ryt,{cardId:s.id})}),e.jsx(cs,{value:"analytics",className:"mt-4",children:a?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsx(ke,{children:e.jsxs(Oe,{className:"p-4 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:a.views}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Views"})]})}),e.jsx(ke,{children:e.jsxs(Oe,{className:"p-4 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:a.clicks}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Clicks"})]})}),e.jsx(ke,{children:e.jsxs(Oe,{className:"p-4 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:a.leads.length}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Leads"})]})})]}),a.leads.length>0&&e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold mb-2",children:"Recent Leads"}),e.jsx("div",{className:"space-y-2",children:a.leads.slice(0,5).map(O=>e.jsxs("div",{className:"text-sm p-2 bg-muted/50 rounded-lg",children:[e.jsx("span",{className:"font-medium",children:O.name}),O.phone&&e.jsxs("span",{className:"text-muted-foreground",children:[" · ",O.phone]}),O.intent&&e.jsx(Xe,{variant:"secondary",className:"ml-2 text-xs",children:O.intent})]},O.id))})]})]}):e.jsx("p",{className:"text-center text-muted-foreground py-8",children:"No analytics data yet"})})]}),e.jsx(H,{onClick:z,disabled:n.isPending,className:"w-full mt-4",children:n.isPending?"Saving...":"Save Changes"})]})}),e.jsx(fEe,{open:h,onClose:()=>m(!1),imageSrc:p,onCropComplete:A,aspectRatio:1})]})}const _P={pending_payment:"Pending Payment",order_submitted:"Order Submitted",awaiting_proof_approval:"Awaiting Proof Approval",proof_approved:"Proof Approved",processing:"Processing",in_production:"In Production",shipped:"Shipped",completed:"Completed",cancelled:"Cancelled",refunded:"Refunded"},p6e={pending_payment:"bg-yellow-100 text-yellow-800",order_submitted:"bg-blue-100 text-blue-800",awaiting_proof_approval:"bg-orange-100 text-orange-800",proof_approved:"bg-green-100 text-green-800",processing:"bg-purple-100 text-purple-800",in_production:"bg-indigo-100 text-indigo-800",shipped:"bg-cyan-100 text-cyan-800",completed:"bg-green-200 text-green-900",cancelled:"bg-red-100 text-red-800",refunded:"bg-gray-100 text-gray-800"};function g6e(s=!0){return yt({queryKey:["marketplace-categories",s],queryFn:async()=>{let t=V.from("marketplace_categories").select("*").order("sort_order",{ascending:!0});s&&(t=t.eq("is_active",!0));const{data:r,error:n}=await t;if(n)throw n;return r}})}function iBs(){const s=ns();return Pt({mutationFn:async t=>{const{data:r,error:n}=await V.from("marketplace_categories").insert([t]).select().single();if(n)throw n;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["marketplace-categories"]}),he.success("Category created successfully")},onError:t=>{he.error("Failed to create category: "+t.message)}})}function oBs(){const s=ns();return Pt({mutationFn:async({id:t,...r})=>{const{data:n,error:a}=await V.from("marketplace_categories").update(r).eq("id",t).select().single();if(a)throw a;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["marketplace-categories"]}),he.success("Category updated successfully")},onError:t=>{he.error("Failed to update category: "+t.message)}})}function lBs(){const s=ns();return Pt({mutationFn:async t=>{const{error:r}=await V.from("marketplace_categories").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["marketplace-categories"]}),he.success("Category deleted successfully")},onError:t=>{he.error("Failed to delete category: "+t.message)}})}function Qyt(s,t=!0){return yt({queryKey:["marketplace-products",s,t],queryFn:async()=>{let r=V.from("marketplace_products").select(` *, category:marketplace_categories(*), images:marketplace_product_images(*), video:marketplace_product_videos(*), variants:marketplace_product_variants(*) `).order("sort_order",{ascending:!0});s&&(r=r.eq("category_id",s)),t&&(r=r.eq("is_active",!0));const{data:n,error:a}=await r;if(a)throw a;return n}})}function cBs(s){return yt({queryKey:["marketplace-product",s],queryFn:async()=>{const{data:t,error:r}=await V.from("marketplace_products").select(` *, category:marketplace_categories(*), images:marketplace_product_images(*), video:marketplace_product_videos(*), variants:marketplace_product_variants(*) `).eq("id",s).single();if(r)throw r;return t},enabled:!!s})}function dBs(){const s=ns();return Pt({mutationFn:async t=>{const{data:r,error:n}=await V.from("marketplace_products").insert([t]).select().single();if(n)throw n;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["marketplace-products"]}),he.success("Product created successfully")},onError:t=>{he.error("Failed to create product: "+t.message)}})}function uBs(){const s=ns();return Pt({mutationFn:async({id:t,...r})=>{const{data:n,error:a}=await V.from("marketplace_products").update(r).eq("id",t).select().single();if(a)throw a;return n},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["marketplace-products"]}),s.invalidateQueries({queryKey:["marketplace-product",r.id]}),he.success("Product updated successfully")},onError:t=>{he.error("Failed to update product: "+t.message)}})}function hBs(){const s=ns();return Pt({mutationFn:async t=>{const{error:r}=await V.from("marketplace_products").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["marketplace-products"]}),he.success("Product deleted successfully")},onError:t=>{he.error("Failed to delete product: "+t.message)}})}function mBs(){const s=ns();return Pt({mutationFn:async t=>{const{data:r,error:n}=await V.from("marketplace_product_images").insert([t]).select().single();if(n)throw n;return r},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["marketplace-products"]}),s.invalidateQueries({queryKey:["marketplace-product",r.product_id]})}})}function fBs(){const s=ns();return Pt({mutationFn:async({id:t,productId:r})=>{const{error:n}=await V.from("marketplace_product_images").delete().eq("id",t);if(n)throw n;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["marketplace-products"]}),s.invalidateQueries({queryKey:["marketplace-product",t]}),he.success("Image deleted successfully")},onError:t=>{he.error("Failed to delete image: "+t.message)}})}function pBs(){const s=ns();return Pt({mutationFn:async({imageId:t,productId:r})=>{const{error:n}=await V.from("marketplace_product_images").update({is_primary:!1}).eq("product_id",r);if(n)throw n;const{error:a}=await V.from("marketplace_product_images").update({is_primary:!0}).eq("id",t);if(a)throw a;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["marketplace-products"]}),s.invalidateQueries({queryKey:["marketplace-product",t]}),he.success("Primary image updated")},onError:t=>{he.error("Failed to set primary image: "+t.message)}})}function gBs(){const s=ns();return Pt({mutationFn:async t=>{const{data:r,error:n}=await V.from("marketplace_product_variants").insert([t]).select().single();if(n)throw n;return r},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["marketplace-products"]}),s.invalidateQueries({queryKey:["marketplace-product",r.product_id]}),he.success("Variant added successfully")}})}function xBs(){const s=ns();return Pt({mutationFn:async({id:t,productId:r})=>{const{error:n}=await V.from("marketplace_product_variants").delete().eq("id",t);if(n)throw n;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["marketplace-products"]}),s.invalidateQueries({queryKey:["marketplace-product",t]}),he.success("Variant deleted successfully")}})}function yBs(){const s=ns();return Pt({mutationFn:async({productId:t,videoUrl:r})=>{await V.from("marketplace_product_videos").delete().eq("product_id",t);const{data:n,error:a}=await V.from("marketplace_product_videos").insert({product_id:t,video_url:r}).select().single();if(a)throw a;return n},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["marketplace-products"]}),s.invalidateQueries({queryKey:["marketplace-product",r.productId]}),he.success("Video updated successfully")}})}function vBs(s){const{isAdmin:t}=Ms();return yt({queryKey:["marketplace-orders",s,t],queryFn:async()=>{let r=V.from("marketplace_orders").select(` *, items:marketplace_order_items(*), status_history:marketplace_order_status_history(*) `).order("created_at",{ascending:!1});const{data:n,error:a}=await r;if(a)throw a;if(t&&n){const i=[...new Set(n.map(c=>c.user_id))],{data:l}=await V.from("profiles").select("id, name, email").in("id",i),o=new Map((l==null?void 0:l.map(c=>[c.id,c]))||[]);return n.map(c=>({...c,user:o.get(c.user_id)}))}return n}})}function bBs(){const{user:s}=Ms();return yt({queryKey:["my-marketplace-orders",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:r}=await V.from("marketplace_orders").select(` *, items:marketplace_order_items(*), status_history:marketplace_order_status_history(*) `).eq("user_id",s.id).order("created_at",{ascending:!1});if(r)throw r;return t},enabled:!!(s!=null&&s.id)})}function _Bs(s){return yt({queryKey:["marketplace-order",s],queryFn:async()=>{const{data:t,error:r}=await V.from("marketplace_orders").select(` *, items:marketplace_order_items(*), status_history:marketplace_order_status_history(*) `).eq("id",s).single();if(r)throw r;return t},enabled:!!s})}function wBs(){const s=ns(),{user:t}=Ms();return Pt({mutationFn:async({orderId:r,status:n,notes:a,trackingNumber:i,trackingUrl:l,previousStatus:o})=>{const c={status:n};i!==void 0&&(c.tracking_number=i),l!==void 0&&(c.tracking_url=l);const{error:d}=await V.from("marketplace_orders").update(c).eq("id",r);if(d)throw d;const{error:h}=await V.from("marketplace_order_status_history").insert({order_id:r,status:n,notes:a,created_by:t==null?void 0:t.id});if(h)throw h;if(["shipped","in_production","processing","completed"].includes(n)&&n!==o)try{await V.functions.invoke("marketplace-order-notify",{body:{orderId:r,notificationType:n==="shipped"?"shipped":"status_update",newStatus:n,trackingNumber:i,trackingUrl:l}})}catch(p){console.error("Failed to send notification email:",p)}},onSuccess:(r,n)=>{s.invalidateQueries({queryKey:["marketplace-orders"]}),s.invalidateQueries({queryKey:["marketplace-order",n.orderId]}),s.invalidateQueries({queryKey:["my-marketplace-orders"]}),he.success("Order status updated")},onError:r=>{he.error("Failed to update order: "+r.message)}})}function jBs(){const s=ns();return Pt({mutationFn:async({itemId:t,proofUrl:r,proofNotes:n,orderId:a})=>{const{error:i}=await V.from("marketplace_order_items").update({proof_url:r,proof_notes:n,proof_status:"pending"}).eq("id",t);if(i)throw i;await V.from("marketplace_orders").update({status:"awaiting_proof_approval"}).eq("id",a);try{await V.functions.invoke("marketplace-order-notify",{body:{orderId:a,notificationType:"proof_ready"}})}catch(l){console.error("Failed to send proof notification:",l)}return a},onSuccess:t=>{s.invalidateQueries({queryKey:["marketplace-orders"]}),s.invalidateQueries({queryKey:["marketplace-order",t]}),s.invalidateQueries({queryKey:["my-marketplace-orders"]}),he.success("Proof uploaded & customer notified")}})}function NBs(){const s=ns();return Pt({mutationFn:async({itemId:t,orderId:r})=>{const{error:n}=await V.from("marketplace_order_items").update({proof_status:"approved"}).eq("id",t);if(n)throw n;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["marketplace-orders"]}),s.invalidateQueries({queryKey:["marketplace-order",t]}),s.invalidateQueries({queryKey:["my-marketplace-orders"]}),he.success("Proof approved")}})}function kBs(){const s=ns();return Pt({mutationFn:async({itemId:t,orderId:r,reason:n})=>{const{error:a}=await V.from("marketplace_order_items").update({proof_status:"rejected",proof_notes:n}).eq("id",t);if(a)throw a;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["marketplace-orders"]}),s.invalidateQueries({queryKey:["marketplace-order",t]}),s.invalidateQueries({queryKey:["my-marketplace-orders"]}),he.success("Proof rejected - please upload a new proof")}})}function SBs(){const{data:s,isLoading:t}=g6e(!1),r=iBs(),n=oBs(),a=lBs(),[i,l]=S.useState(!1),[o,c]=S.useState(null),[d,h]=S.useState({name:"",description:"",image_url:"",sort_order:0,is_active:!0}),m=()=>{h({name:"",description:"",image_url:"",sort_order:0,is_active:!0}),c(null)},p=_=>{c(_),h({name:_.name,description:_.description||"",image_url:_.image_url||"",sort_order:_.sort_order,is_active:_.is_active}),l(!0)},x=async _=>{_.preventDefault(),o?await n.mutateAsync({id:o.id,...d}):await r.mutateAsync(d),l(!1),m()},y=async _=>{confirm("Are you sure you want to delete this category?")&&await a.mutateAsync(_)};return t?e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsx(Ks,{className:"h-8 w-48"})}),e.jsx(Oe,{children:e.jsx("div",{className:"space-y-4",children:[1,2,3].map(_=>e.jsx(Ks,{className:"h-12 w-full"},_))})})]}):e.jsxs(ke,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between",children:[e.jsx(zt,{children:"Categories"}),e.jsxs(bs,{open:i,onOpenChange:_=>{l(_),_||m()},children:[e.jsx(Qi,{asChild:!0,children:e.jsxs(H,{children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Add Category"]})}),e.jsxs(vs,{children:[e.jsx(Cs,{children:e.jsx(Ns,{children:o?"Edit Category":"Add Category"})}),e.jsxs("form",{onSubmit:x,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"name",children:"Name"}),e.jsx(Se,{id:"name",value:d.name,onChange:_=>h({...d,name:_.target.value}),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"description",children:"Description"}),e.jsx(vr,{id:"description",value:d.description,onChange:_=>h({...d,description:_.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"image_url",children:"Image URL"}),e.jsx(Se,{id:"image_url",value:d.image_url,onChange:_=>h({...d,image_url:_.target.value}),placeholder:"https://..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"sort_order",children:"Sort Order"}),e.jsx(Se,{id:"sort_order",type:"number",value:d.sort_order,onChange:_=>h({...d,sort_order:parseInt(_.target.value)||0})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Or,{id:"is_active",checked:d.is_active,onCheckedChange:_=>h({...d,is_active:_})}),e.jsx(ue,{htmlFor:"is_active",children:"Active"})]}),e.jsx(H,{type:"submit",className:"w-full",disabled:r.isPending||n.isPending,children:o?"Update Category":"Create Category"})]})]})]})]}),e.jsx(Oe,{children:s&&s.length>0?e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Vs,{children:[e.jsx(At,{children:"Name"}),e.jsx(At,{children:"Description"}),e.jsx(At,{children:"Sort Order"}),e.jsx(At,{children:"Status"}),e.jsx(At,{className:"text-right",children:"Actions"})]})}),e.jsx(da,{children:s.map(_=>e.jsxs(Vs,{children:[e.jsx(gt,{className:"font-medium",children:_.name}),e.jsx(gt,{className:"max-w-xs truncate",children:_.description}),e.jsx(gt,{children:_.sort_order}),e.jsx(gt,{children:e.jsx("span",{className:`px-2 py-1 rounded-full text-xs ${_.is_active?"bg-green-100 text-green-800":"bg-gray-100 text-gray-800"}`,children:_.is_active?"Active":"Inactive"})}),e.jsx(gt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(H,{variant:"ghost",size:"icon",onClick:()=>p(_),children:e.jsx(ni,{className:"h-4 w-4"})}),e.jsx(H,{variant:"ghost",size:"icon",onClick:()=>y(_.id),disabled:a.isPending,children:e.jsx(Dr,{className:"h-4 w-4 text-destructive"})})]})})]},_.id))})]}):e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No categories yet. Create your first category to get started."})})]})}function CBs(){var fe,je;const{data:s,isLoading:t}=Qyt(void 0,!1),{data:r}=g6e(!1),n=dBs(),a=uBs(),i=hBs(),l=mBs(),o=fBs(),c=pBs(),d=gBs(),h=xBs(),m=yBs(),[p,x]=S.useState(!1),[y,_]=S.useState(!1),[b,j]=S.useState(!1),[k,T]=S.useState(null),[E,A]=S.useState(null),[D,R]=S.useState(!1),[z,O]=S.useState({name:"",description:"",base_price:0,shipping_fee:0,category_id:"",allow_artwork_upload:!1,requires_proof_approval:!1,is_active:!0,sort_order:0}),[$,ee]=S.useState({name:"",price_adjustment:0}),[Z,J]=S.useState(""),K=()=>{O({name:"",description:"",base_price:0,shipping_fee:0,category_id:"",allow_artwork_upload:!1,requires_proof_approval:!1,is_active:!0,sort_order:0}),T(null)},re=ve=>{T(ve),O({name:ve.name,description:ve.description||"",base_price:Number(ve.base_price),shipping_fee:Number(ve.shipping_fee),category_id:ve.category_id||"",allow_artwork_upload:ve.allow_artwork_upload,requires_proof_approval:ve.requires_proof_approval,is_active:ve.is_active,sort_order:ve.sort_order}),x(!0)},ie=async ve=>{ve.preventDefault();const We={...z,category_id:z.category_id||null};k?await a.mutateAsync({id:k.id,...We}):await n.mutateAsync(We),x(!1),K()},ce=async ve=>{confirm("Are you sure you want to delete this product?")&&await i.mutateAsync(ve)},ne=async ve=>{if(!E||!ve.target.files||ve.target.files.length===0)return;R(!0);const We=ve.target.files[0],Ve=We.name.split(".").pop(),Le=`products/${E.id}/${Date.now()}.${Ve}`;try{const{error:Me}=await V.storage.from("marketplace").upload(Le,We);if(Me)throw Me;const{data:{publicUrl:ze}}=V.storage.from("marketplace").getPublicUrl(Le);await l.mutateAsync({product_id:E.id,image_url:ze,is_primary:!E.images||E.images.length===0}),he.success("Image uploaded successfully")}catch(Me){he.error("Failed to upload image: "+Me.message)}finally{R(!1)}},le=async ve=>{ve.preventDefault(),E&&(await d.mutateAsync({product_id:E.id,name:$.name,price_adjustment:$.price_adjustment}),ee({name:"",price_adjustment:0}))},be=async()=>{!E||!Z||(await m.mutateAsync({productId:E.id,videoUrl:Z}),J(""))};return t?e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsx(Ks,{className:"h-8 w-48"})}),e.jsx(Oe,{children:e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:[1,2,3].map(ve=>e.jsx(Ks,{className:"h-64 w-full"},ve))})})]}):e.jsxs(e.Fragment,{children:[e.jsxs(ke,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between",children:[e.jsx(zt,{children:"Products"}),e.jsxs(bs,{open:p,onOpenChange:ve=>{x(ve),ve||K()},children:[e.jsx(Qi,{asChild:!0,children:e.jsxs(H,{children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Add Product"]})}),e.jsxs(vs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Cs,{children:e.jsx(Ns,{children:k?"Edit Product":"Add Product"})}),e.jsxs("form",{onSubmit:ie,className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"name",children:"Product Name"}),e.jsx(Se,{id:"name",value:z.name,onChange:ve=>O({...z,name:ve.target.value}),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"category",children:"Category"}),e.jsxs(Bs,{value:z.category_id,onValueChange:ve=>O({...z,category_id:ve}),children:[e.jsx(Os,{children:e.jsx(Us,{placeholder:"Select category"})}),e.jsx(Fs,{children:r==null?void 0:r.map(ve=>e.jsx(pt,{value:ve.id,children:ve.name},ve.id))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"description",children:"Description"}),e.jsx(vr,{id:"description",value:z.description,onChange:ve=>O({...z,description:ve.target.value}),rows:4})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"base_price",children:"Base Price ($)"}),e.jsx(Se,{id:"base_price",type:"number",step:"0.01",min:"0",value:z.base_price,onChange:ve=>O({...z,base_price:parseFloat(ve.target.value)||0}),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"shipping_fee",children:"Shipping Fee ($)"}),e.jsx(Se,{id:"shipping_fee",type:"number",step:"0.01",min:"0",value:z.shipping_fee,onChange:ve=>O({...z,shipping_fee:parseFloat(ve.target.value)||0})})]})]}),e.jsx("div",{className:"grid grid-cols-2 gap-4",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"sort_order",children:"Sort Order"}),e.jsx(Se,{id:"sort_order",type:"number",value:z.sort_order,onChange:ve=>O({...z,sort_order:parseInt(ve.target.value)||0})})]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Or,{id:"allow_artwork_upload",checked:z.allow_artwork_upload,onCheckedChange:ve=>O({...z,allow_artwork_upload:ve})}),e.jsx(ue,{htmlFor:"allow_artwork_upload",children:"Allow customer to upload artwork"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Or,{id:"requires_proof_approval",checked:z.requires_proof_approval,onCheckedChange:ve=>O({...z,requires_proof_approval:ve})}),e.jsx(ue,{htmlFor:"requires_proof_approval",children:"Requires proof approval"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Or,{id:"is_active",checked:z.is_active,onCheckedChange:ve=>O({...z,is_active:ve})}),e.jsx(ue,{htmlFor:"is_active",children:"Active"})]})]}),e.jsx(H,{type:"submit",className:"w-full",disabled:n.isPending||a.isPending,children:k?"Update Product":"Create Product"})]})]})]})]}),e.jsx(Oe,{children:s&&s.length>0?e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:s.map(ve=>{var We,Ve;return e.jsxs(ke,{className:"overflow-hidden",children:[e.jsxs("div",{className:"aspect-video bg-muted relative",children:[ve.images&&ve.images.length>0?e.jsx("img",{src:((We=ve.images.find(Le=>Le.is_primary))==null?void 0:We.image_url)||ve.images[0].image_url,alt:ve.name,className:"w-full h-full object-cover"}):e.jsx("div",{className:"flex items-center justify-center h-full text-muted-foreground",children:"No image"}),!ve.is_active&&e.jsx(Xe,{variant:"secondary",className:"absolute top-2 right-2",children:"Inactive"})]}),e.jsxs(Oe,{className:"p-4",children:[e.jsx("h3",{className:"font-semibold mb-1",children:ve.name}),e.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:((Ve=ve.category)==null?void 0:Ve.name)||"No category"}),e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("span",{className:"font-bold",children:["$",Number(ve.base_price).toFixed(2)]}),Number(ve.shipping_fee)>0&&e.jsxs("span",{className:"text-sm text-muted-foreground",children:["+$",Number(ve.shipping_fee).toFixed(2)," shipping"]})]}),e.jsxs("div",{className:"flex flex-wrap gap-1 mb-3",children:[ve.allow_artwork_upload&&e.jsx(Xe,{variant:"outline",className:"text-xs",children:"Artwork Upload"}),ve.requires_proof_approval&&e.jsx(Xe,{variant:"outline",className:"text-xs",children:"Proof Required"}),ve.variants&&ve.variants.length>0&&e.jsxs(Xe,{variant:"outline",className:"text-xs",children:[ve.variants.length," Variants"]})]}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs(H,{variant:"outline",size:"sm",onClick:()=>re(ve),children:[e.jsx(ni,{className:"h-3 w-3 mr-1"}),"Edit"]}),e.jsxs(H,{variant:"outline",size:"sm",onClick:()=>{A(ve),_(!0)},children:[e.jsx(f_,{className:"h-3 w-3 mr-1"}),"Images"]}),e.jsxs(H,{variant:"outline",size:"sm",onClick:()=>{A(ve),j(!0)},children:[e.jsx(xm,{className:"h-3 w-3 mr-1"}),"Variants"]}),e.jsx(H,{variant:"ghost",size:"sm",onClick:()=>ce(ve.id),children:e.jsx(Dr,{className:"h-3 w-3 text-destructive"})})]})]})]},ve.id)})}):e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No products yet. Create your first product to get started."})})]}),e.jsx(bs,{open:y,onOpenChange:_,children:e.jsxs(vs,{className:"max-w-2xl",children:[e.jsx(Cs,{children:e.jsxs(Ns,{children:["Manage Images - ",E==null?void 0:E.name]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"grid grid-cols-3 gap-4",children:(fe=E==null?void 0:E.images)==null?void 0:fe.map(ve=>e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:ve.image_url,alt:"",className:"w-full aspect-square object-cover rounded-lg"}),ve.is_primary&&e.jsx(Xe,{className:"absolute top-2 left-2",variant:"default",children:"Primary"}),e.jsxs("div",{className:"absolute top-2 right-2 flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity",children:[!ve.is_primary&&e.jsx(H,{variant:"secondary",size:"icon",onClick:async()=>{var We;await c.mutateAsync({imageId:ve.id,productId:E.id}),A({...E,images:(We=E.images)==null?void 0:We.map(Ve=>({...Ve,is_primary:Ve.id===ve.id}))})},disabled:c.isPending,title:"Set as primary",children:e.jsx(ya,{className:"h-4 w-4"})}),e.jsx(H,{variant:"destructive",size:"icon",onClick:async()=>{var Ve;await o.mutateAsync({id:ve.id,productId:E.id});const We=s==null?void 0:s.find(Le=>Le.id===E.id);We&&A({...We,images:(Ve=We.images)==null?void 0:Ve.filter(Le=>Le.id!==ve.id)})},disabled:o.isPending,children:e.jsx(Dr,{className:"h-4 w-4"})})]})]},ve.id))}),e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-6 text-center",children:[e.jsx("input",{type:"file",accept:"image/*",onChange:ne,className:"hidden",id:"image-upload",disabled:D}),e.jsxs("label",{htmlFor:"image-upload",className:"cursor-pointer",children:[e.jsx(f_,{className:"h-8 w-8 mx-auto mb-2 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:D?"Uploading...":"Click to upload an image"})]})]}),e.jsxs("div",{className:"border-t pt-4 mt-4",children:[e.jsx(ue,{children:"Product Video (optional)"}),e.jsxs("div",{className:"flex gap-2 mt-2",children:[e.jsx(Se,{placeholder:"Enter video URL (YouTube, Vimeo, etc.)",value:Z,onChange:ve=>J(ve.target.value)}),e.jsxs(H,{onClick:be,disabled:!Z,children:[e.jsx(xn,{className:"h-4 w-4 mr-2"}),"Set Video"]})]}),(E==null?void 0:E.video)&&e.jsxs("p",{className:"text-sm text-muted-foreground mt-2",children:["Current video: ",E.video.video_url]})]})]})]})}),e.jsx(bs,{open:b,onOpenChange:j,children:e.jsxs(vs,{children:[e.jsx(Cs,{children:e.jsxs(Ns,{children:["Manage Variants - ",E==null?void 0:E.name]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("form",{onSubmit:le,className:"flex gap-2",children:[e.jsx(Se,{placeholder:"Variant name (e.g., 500 count)",value:$.name,onChange:ve=>ee({...$,name:ve.target.value}),required:!0}),e.jsx(Se,{type:"number",step:"0.01",placeholder:"Price adj.",value:$.price_adjustment,onChange:ve=>ee({...$,price_adjustment:parseFloat(ve.target.value)||0}),className:"w-32"}),e.jsx(H,{type:"submit",children:"Add"})]}),e.jsxs("div",{className:"space-y-2",children:[(je=E==null?void 0:E.variants)==null?void 0:je.map(ve=>e.jsxs("div",{className:"flex items-center justify-between p-3 bg-muted rounded-lg",children:[e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:ve.name}),e.jsxs("span",{className:"text-sm text-muted-foreground ml-2",children:[Number(ve.price_adjustment)>=0?"+":"","$",Number(ve.price_adjustment).toFixed(2)]})]}),e.jsx(H,{variant:"ghost",size:"icon",onClick:()=>h.mutateAsync({id:ve.id,productId:E.id}),children:e.jsx(Dr,{className:"h-4 w-4 text-destructive"})})]},ve.id)),(!(E!=null&&E.variants)||E.variants.length===0)&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:'No variants yet. Add variants like "250 count", "500 count", etc.'})]})]})]})})]})}const TBs=["pending_payment","order_submitted","awaiting_proof_approval","proof_approved","processing","in_production","shipped","completed","cancelled","refunded"];function EBs(){var _,b,j;const{data:s,isLoading:t}=vBs(),r=wBs(),n=jBs(),[a,i]=S.useState(null),[l,o]=S.useState(!1),[c,d]=S.useState({status:"",notes:"",trackingNumber:"",trackingUrl:""}),[h,m]=S.useState(!1),p=k=>{i(k),d({status:k.status,notes:"",trackingNumber:k.tracking_number||"",trackingUrl:k.tracking_url||""}),o(!0)},x=async()=>{a&&(await r.mutateAsync({orderId:a.id,status:c.status,notes:c.notes,trackingNumber:c.trackingNumber,trackingUrl:c.trackingUrl,previousStatus:a.status}),o(!1))},y=async(k,T)=>{if(!a||!k.target.files||k.target.files.length===0)return;m(!0);const E=k.target.files[0],A=E.name.split(".").pop(),D=`proofs/${a.id}/${T}/${Date.now()}.${A}`;try{const{error:R}=await V.storage.from("marketplace").upload(D,E);if(R)throw R;const{data:{publicUrl:z}}=V.storage.from("marketplace").getPublicUrl(D);await n.mutateAsync({itemId:T,proofUrl:z,orderId:a.id}),he.success("Proof uploaded successfully")}catch(R){he.error("Failed to upload proof: "+R.message)}finally{m(!1)}};return t?e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsx(Ks,{className:"h-8 w-48"})}),e.jsx(Oe,{children:e.jsx("div",{className:"space-y-4",children:[1,2,3].map(k=>e.jsx(Ks,{className:"h-16 w-full"},k))})})]}):e.jsxs(e.Fragment,{children:[e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsx(zt,{children:"Orders"})}),e.jsx(Oe,{children:s&&s.length>0?e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Vs,{children:[e.jsx(At,{children:"Order #"}),e.jsx(At,{children:"Customer"}),e.jsx(At,{children:"Date"}),e.jsx(At,{children:"Total"}),e.jsx(At,{children:"Status"}),e.jsx(At,{className:"text-right",children:"Actions"})]})}),e.jsx(da,{children:s.map(k=>{var T,E;return e.jsxs(Vs,{children:[e.jsx(gt,{className:"font-mono",children:k.order_number}),e.jsx(gt,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((T=k.user)==null?void 0:T.name)||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(E=k.user)==null?void 0:E.email})]})}),e.jsx(gt,{children:As(new Date(k.created_at),"MMM d, yyyy")}),e.jsxs(gt,{className:"font-bold",children:["$",Number(k.total).toFixed(2)]}),e.jsx(gt,{children:e.jsx(Xe,{className:p6e[k.status],children:_P[k.status]})}),e.jsx(gt,{className:"text-right",children:e.jsxs(H,{variant:"ghost",size:"sm",onClick:()=>p(k),children:[e.jsx(Bn,{className:"h-4 w-4 mr-1"}),"View"]})})]},k.id)})})]}):e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No orders yet."})})]}),e.jsx(bs,{open:l,onOpenChange:o,children:e.jsxs(vs,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Cs,{children:e.jsxs(Ns,{children:["Order ",a==null?void 0:a.order_number]})}),a&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium mb-2",children:"Customer"}),e.jsx("p",{children:(_=a.user)==null?void 0:_.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(b=a.user)==null?void 0:b.email})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium mb-2",children:"Shipping Address"}),e.jsx("p",{children:a.shipping_name}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[a.shipping_address,e.jsx("br",{}),a.shipping_city,", ",a.shipping_state," ",a.shipping_zip]})]})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium mb-2",children:"Order Items"}),e.jsx("div",{className:"space-y-3",children:(j=a.items)==null?void 0:j.map(k=>e.jsxs("div",{className:"border rounded-lg p-4",children:[e.jsxs("div",{className:"flex justify-between items-start mb-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:k.product_name}),k.variant_name&&e.jsx("p",{className:"text-sm text-muted-foreground",children:k.variant_name})]}),e.jsxs("p",{className:"font-bold",children:["$",Number(k.unit_price).toFixed(2)," x ",k.quantity]})]}),k.artwork_url&&e.jsxs("div",{className:"mt-2",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-1",children:"Customer Artwork:"}),e.jsx("a",{href:k.artwork_url,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline text-sm",children:"View Artwork"})]}),e.jsx("div",{className:"mt-3 pt-3 border-t",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Proof Status: "}),e.jsx(Xe,{variant:k.proof_status==="approved"?"default":"secondary",children:k.proof_status||"No proof yet"})]}),k.proof_url?e.jsx("a",{href:k.proof_url,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline text-sm",children:"View Proof"}):e.jsxs("div",{children:[e.jsx("input",{type:"file",accept:"image/*,.pdf",onChange:T=>y(T,k.id),className:"hidden",id:`proof-${k.id}`,disabled:h}),e.jsx("label",{htmlFor:`proof-${k.id}`,children:e.jsx(H,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("span",{children:[e.jsx(Ea,{className:"h-4 w-4 mr-1"}),h?"Uploading...":"Upload Proof"]})})})]})]})})]},k.id))})]}),e.jsxs("div",{className:"border-t pt-4",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{children:"Subtotal"}),e.jsxs("span",{children:["$",Number(a.subtotal).toFixed(2)]})]}),e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{children:"Shipping"}),e.jsxs("span",{children:["$",Number(a.shipping_total).toFixed(2)]})]}),e.jsxs("div",{className:"flex justify-between font-bold text-lg mt-2",children:[e.jsx("span",{children:"Total"}),e.jsxs("span",{children:["$",Number(a.total).toFixed(2)]})]})]}),e.jsxs("div",{className:"border-t pt-4",children:[e.jsx("h4",{className:"font-medium mb-3",children:"Update Order Status"}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Status"}),e.jsxs(Bs,{value:c.status,onValueChange:k=>d({...c,status:k}),children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsx(Fs,{children:TBs.map(k=>e.jsx(pt,{value:k,children:_P[k]},k))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Tracking Number"}),e.jsx(Se,{value:c.trackingNumber,onChange:k=>d({...c,trackingNumber:k.target.value}),placeholder:"Enter tracking number"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Tracking URL"}),e.jsx(Se,{value:c.trackingUrl,onChange:k=>d({...c,trackingUrl:k.target.value}),placeholder:"https://..."})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Notes (optional)"}),e.jsx(vr,{value:c.notes,onChange:k=>d({...c,notes:k.target.value}),placeholder:"Add a note about this status change..."})]}),e.jsxs(H,{onClick:x,disabled:r.isPending,className:"w-full",children:[e.jsx(yc,{className:"h-4 w-4 mr-2"}),"Update Status"]})]})]}),a.status_history&&a.status_history.length>0&&e.jsxs("div",{className:"border-t pt-4",children:[e.jsx("h4",{className:"font-medium mb-3",children:"Status History"}),e.jsx("div",{className:"space-y-2",children:a.status_history.map(k=>e.jsxs("div",{className:"flex justify-between text-sm p-2 bg-muted rounded",children:[e.jsxs("div",{children:[e.jsx(Xe,{variant:"outline",children:_P[k.status]}),k.notes&&e.jsx("p",{className:"text-muted-foreground mt-1",children:k.notes})]}),e.jsx("span",{className:"text-muted-foreground",children:As(new Date(k.created_at),"MMM d, h:mm a")})]},k.id))})]})]})]})})]})}function ABs(){const[s,t]=S.useState("products"),r=Fr();return e.jsx(Ss,{title:"Marketplace Management",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Marketplace Management"}),e.jsx("p",{className:"text-muted-foreground",children:"Manage products, categories, and orders"})]}),e.jsxs(H,{variant:"outline",onClick:()=>r("/marketplace"),children:[e.jsx(gn,{className:"h-4 w-4 mr-2"}),"View Store"]})]}),e.jsxs(ta,{value:s,onValueChange:t,children:[e.jsxs(Qn,{className:"grid w-full grid-cols-3",children:[e.jsxs(ts,{value:"products",className:"flex items-center gap-2",children:[e.jsx(yc,{className:"h-4 w-4"}),"Products"]}),e.jsxs(ts,{value:"categories",className:"flex items-center gap-2",children:[e.jsx(Uf,{className:"h-4 w-4"}),"Categories"]}),e.jsxs(ts,{value:"orders",className:"flex items-center gap-2",children:[e.jsx(sx,{className:"h-4 w-4"}),"Orders"]})]}),e.jsx(cs,{value:"products",children:e.jsx(CBs,{})}),e.jsx(cs,{value:"categories",children:e.jsx(SBs,{})}),e.jsx(cs,{value:"orders",children:e.jsx(EBs,{})})]})]})})}function Jyt(){return yt({queryKey:["reward-categories"],queryFn:async()=>{const{data:s,error:t}=await V.from("reward_store_categories").select("*").order("sort_order",{ascending:!0});if(t)throw t;return s}})}function MBs(s){return yt({queryKey:["reward-items",s],queryFn:async()=>{let t=V.from("reward_store_items").select(` *, category:reward_store_categories(*) `).order("created_at",{ascending:!1});const{data:r,error:n}=await t;if(n)throw n;return r}})}function IBs(s){return yt({queryKey:["active-reward-items",s],queryFn:async()=>{let t=V.from("reward_store_items").select(` *, category:reward_store_categories(*) `).eq("is_active",!0).order("created_at",{ascending:!1});s&&(t=t.eq("category_id",s));const{data:r,error:n}=await t;if(n)throw n;return r}})}function PBs(s){return yt({queryKey:["user-purchases",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await V.from("reward_store_purchases").select(` *, item:reward_store_items(*) `).eq("user_id",s).order("purchased_at",{ascending:!1});if(r)throw r;return t},enabled:!!s})}function LBs(){return yt({queryKey:["all-reward-purchases"],queryFn:async()=>{const{data:s,error:t}=await V.from("reward_store_purchases").select(` *, item:reward_store_items(*) `).order("purchased_at",{ascending:!1});if(t)throw t;if(!s||s.length===0)return[];const r=[...new Set(s.map(l=>l.user_id))],{data:n,error:a}=await V.from("profiles").select("id, name, email").in("id",r);if(a)throw a;const i=new Map((n==null?void 0:n.map(l=>[l.id,l]))||[]);return s.map(l=>({...l,user:i.get(l.user_id)||null}))}})}function DBs(s){return yt({queryKey:["spendable-points",s],queryFn:async()=>{if(!s)return 0;const{data:t,error:r}=await V.from("agent_attendance_stats").select("spendable_points").eq("user_id",s).single();if(r&&r.code!=="PGRST116")throw r;return(t==null?void 0:t.spendable_points)||0},enabled:!!s})}function RBs(){const s=ns();return Pt({mutationFn:async t=>{const{data:r,error:n}=await V.rpc("purchase_reward_item",{p_item_id:t});if(n)throw n;const a=r;if(!a.success)throw new Error(a.error||"Purchase failed");return a},onSuccess:()=>{s.invalidateQueries({queryKey:["user-purchases"]}),s.invalidateQueries({queryKey:["spendable-points"]}),s.invalidateQueries({queryKey:["active-reward-items"]}),s.invalidateQueries({queryKey:["reward-items"]}),s.invalidateQueries({queryKey:["homereel-credits"]})}})}function OBs(){const s=ns();return Pt({mutationFn:async t=>{const{data:r,error:n}=await V.from("reward_store_categories").insert([t]).select().single();if(n)throw n;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["reward-categories"]})}})}function FBs(){const s=ns();return Pt({mutationFn:async({id:t,...r})=>{const{data:n,error:a}=await V.from("reward_store_categories").update(r).eq("id",t).select().single();if(a)throw a;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["reward-categories"]})}})}function BBs(){const s=ns();return Pt({mutationFn:async t=>{const{error:r}=await V.from("reward_store_categories").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["reward-categories"]})}})}function zBs(){const s=ns();return Pt({mutationFn:async t=>{const{data:r,error:n}=await V.from("reward_store_items").insert([t]).select().single();if(n)throw n;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["reward-items"]}),s.invalidateQueries({queryKey:["active-reward-items"]})}})}function $Bs(){const s=ns();return Pt({mutationFn:async({id:t,...r})=>{const{data:n,error:a}=await V.from("reward_store_items").update(r).eq("id",t).select().single();if(a)throw a;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["reward-items"]}),s.invalidateQueries({queryKey:["active-reward-items"]})}})}function UBs(){const s=ns();return Pt({mutationFn:async t=>{const{error:r}=await V.from("reward_store_items").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["reward-items"]}),s.invalidateQueries({queryKey:["active-reward-items"]})}})}function qBs(s){const t=s.match(/\/storage\/v1\/object\/public\/([^/]+)\/(.+)$/);return t?{bucket:t[1],path:t[2]}:null}async function Ewe(s,t){const r=qBs(s);if(r)try{const{data:n,error:a}=await V.storage.from(r.bucket).download(r.path);if(a){console.error("Error downloading file:",a),he.error("Failed to download file");return}const i=URL.createObjectURL(n),l=document.createElement("a");l.href=i,l.download=t||r.path.split("/").pop()||"download",document.body.appendChild(l),l.click(),document.body.removeChild(l),setTimeout(()=>URL.revokeObjectURL(i),100)}catch(n){console.error("Download error:",n),he.error("Failed to download file")}else try{const a=await(await fetch(s)).blob(),i=URL.createObjectURL(a),l=document.createElement("a");l.href=i,l.download=t||s.split("/").pop()||"download",document.body.appendChild(l),l.click(),document.body.removeChild(l),setTimeout(()=>URL.revokeObjectURL(i),100)}catch(n){console.error("External download error:",n),he.error("Failed to download file")}}function evt(){return yt({queryKey:["point-reward-settings"],queryFn:async()=>{const{data:s,error:t}=await V.from("point_reward_settings").select("*").order("action_name");if(t)throw t;return s}})}function VBs(){const s=ns();return Pt({mutationFn:async({id:t,points:r,is_active:n})=>{const a={points:r};n!==void 0&&(a.is_active=n);const{data:i,error:l}=await V.from("point_reward_settings").update(a).eq("id",t).select().single();if(l)throw l;return i},onSuccess:()=>{s.invalidateQueries({queryKey:["point-reward-settings"]})}})}function HBs(){const{user:s}=Ms(),[t,r]=S.useState("items"),[n,a]=S.useState(!1),[i,l]=S.useState(null),[o,c]=S.useState(""),[d,h]=S.useState(""),[m,p]=S.useState(""),[x,y]=S.useState(null),[_,b]=S.useState(!1),[j,k]=S.useState(null),[T,E]=S.useState(""),[A,D]=S.useState(""),[R,z]=S.useState(null),[O,$]=S.useState(""),[ee,Z]=S.useState("file"),[J,K]=S.useState(""),[re,ie]=S.useState(""),[ce,ne]=S.useState(""),[le,be]=S.useState(!0),[fe,je]=S.useState(null),[ve,We]=S.useState(!1),[Ve,Le]=S.useState(!1),Me=S.useRef(null),ze=S.useRef(null),{data:Pe,isLoading:Ie}=Jyt(),{data:De,isLoading:pe}=MBs(),{data:tt,isLoading:ge}=LBs(),{data:ct,isLoading:Ue}=evt(),et=OBs(),Qe=FBs(),Ne=BBs(),$e=zBs(),it=$Bs(),Je=UBs(),st=VBs(),[mt,wt]=S.useState({}),at=kt=>{kt?(l(kt),c(kt.name),h(kt.description||""),p(kt.icon||"")):(l(null),c(""),h(""),p("")),a(!0)},rt=async()=>{if(!o.trim()){he.error("Please enter a category name");return}try{i?(await Qe.mutateAsync({id:i.id,name:o,description:d||null,icon:m||null}),he.success("Category updated successfully")):(await et.mutateAsync({name:o,description:d||null,icon:m||null,sort_order:((Pe==null?void 0:Pe.length)||0)+1}),he.success("Category created successfully")),a(!1)}catch(kt){console.error("Error saving category:",kt),he.error("Failed to save category")}},Et=async()=>{if(x)try{await Ne.mutateAsync(x),he.success("Category deleted successfully"),y(null)}catch(kt){console.error("Error deleting category:",kt),he.error("Failed to delete category")}},hs=kt=>{var fs;kt?(k(kt),E(kt.name),D(kt.description||""),z(kt.category_id),$(kt.points_cost.toString()),Z(kt.item_type),K(kt.file_url||""),ie(kt.preview_image_url||""),ne(((fs=kt.max_quantity)==null?void 0:fs.toString())||""),be(kt.is_active)):(k(null),E(""),D(""),z(null),$(""),Z("file"),K(""),ie(""),ne(""),be(!0)),b(!0)},Is=async(kt,fs)=>{fs==="file"?We(!0):Le(!0);try{const Gs=kt.name.split(".").pop(),_s=`${Date.now()}-${Math.random().toString(36).substring(7)}.${Gs}`,br=`${fs==="file"?"items":"previews"}/${_s}`,{error:zr}=await V.storage.from("reward-store").upload(br,kt);if(zr)throw zr;const{data:{publicUrl:Yr}}=V.storage.from("reward-store").getPublicUrl(br);fs==="file"?K(Yr):ie(Yr),he.success("File uploaded successfully")}catch(Gs){console.error("Error uploading file:",Gs),he.error("Failed to upload file")}finally{fs==="file"?We(!1):Le(!1)}},lr=async()=>{if(!T.trim()){he.error("Please enter an item name");return}if(!O||parseInt(O)<0){he.error("Please enter a valid points cost");return}try{const kt={name:T,description:A||null,category_id:R,points_cost:parseInt(O),item_type:ee,file_url:J||null,preview_image_url:re||null,max_quantity:ce?parseInt(ce):null,current_quantity:ce?parseInt(ce):null,is_active:le,created_by:s==null?void 0:s.id};j?(await it.mutateAsync({id:j.id,...kt,current_quantity:j.max_quantity!==(ce?parseInt(ce):null)?ce?parseInt(ce):null:j.current_quantity}),he.success("Item updated successfully")):(await $e.mutateAsync(kt),he.success("Item created successfully")),b(!1)}catch(kt){console.error("Error saving item:",kt),he.error("Failed to save item")}},us=async()=>{if(fe)try{await Je.mutateAsync(fe),he.success("Item deleted successfully"),je(null)}catch(kt){console.error("Error deleting item:",kt),he.error("Failed to delete item")}},St=async(kt,fs)=>{const Gs=mt[kt];if(Gs===void 0||Gs===fs.toString())return;const _s=parseInt(Gs);if(isNaN(_s)||_s<0){he.error("Please enter a valid positive number");return}try{await st.mutateAsync({id:kt,points:_s}),he.success("Points updated successfully"),wt(br=>{const zr={...br};return delete zr[kt],zr})}catch(br){console.error("Error updating points:",br),he.error("Failed to update points")}};return Ie||pe||ge||Ue?e.jsx(Ss,{title:"Reward Store",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Ks,{className:"h-8 w-64"}),e.jsx(Ks,{className:"h-96"})]})}):e.jsxs(Ss,{title:"Reward Store",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Reward Store Management"}),e.jsx("p",{className:"text-muted-foreground",children:"Manage store items that agents can purchase with their points"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsx(ke,{children:e.jsxs(Oe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(yc,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Total Items"})]}),e.jsx("p",{className:"text-2xl font-bold",children:(De==null?void 0:De.length)||0}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(De==null?void 0:De.filter(kt=>kt.is_active).length)||0," active"]})]})}),e.jsx(ke,{children:e.jsxs(Oe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Uf,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Categories"})]}),e.jsx("p",{className:"text-2xl font-bold",children:(Pe==null?void 0:Pe.length)||0})]})}),e.jsx(ke,{children:e.jsxs(Oe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(ya,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Avg. Cost"})]}),e.jsxs("p",{className:"text-2xl font-bold",children:[De&&De.length>0?Math.round(De.reduce((kt,fs)=>kt+fs.points_cost,0)/De.length):0," pts"]})]})})]}),e.jsxs(ta,{value:t,onValueChange:r,children:[e.jsxs(Qn,{children:[e.jsx(ts,{value:"items",children:"Items"}),e.jsx(ts,{value:"categories",children:"Categories"}),e.jsx(ts,{value:"purchases",children:"Purchases"}),e.jsx(ts,{value:"point-settings",children:"Point Settings"})]}),e.jsx(cs,{value:"items",className:"mt-4",children:e.jsxs(ke,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(zt,{children:"Store Items"}),e.jsx(Br,{children:"Manage rewards that agents can purchase"})]}),e.jsxs(H,{onClick:()=>hs(),children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Add Item"]})]}),e.jsx(Oe,{children:!De||De.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Di,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No items yet. Add your first reward item!"})]}):e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Vs,{children:[e.jsx(At,{children:"Item"}),e.jsx(At,{children:"Category"}),e.jsx(At,{className:"text-center",children:"Cost"}),e.jsx(At,{className:"text-center",children:"Type"}),e.jsx(At,{className:"text-center",children:"Quantity"}),e.jsx(At,{className:"text-center",children:"Status"}),e.jsx(At,{className:"text-right",children:"Actions"})]})}),e.jsx(da,{children:De.map(kt=>e.jsxs(Vs,{children:[e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[kt.preview_image_url?e.jsx("img",{src:kt.preview_image_url,alt:kt.name,className:"h-10 w-10 rounded object-cover"}):e.jsx("div",{className:"h-10 w-10 rounded bg-muted flex items-center justify-center",children:e.jsx(Di,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:kt.name}),e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-1",children:kt.description||"No description"})]})]})}),e.jsx(gt,{children:kt.category?e.jsx(Xe,{variant:"outline",children:kt.category.name}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(gt,{className:"text-center",children:e.jsxs(Xe,{variant:"secondary",className:"font-bold",children:[e.jsx(ya,{className:"h-3 w-3 mr-1"}),kt.points_cost]})}),e.jsx(gt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[kt.item_type==="file"?e.jsx(kn,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(Jo,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-xs capitalize",children:kt.item_type})]})}),e.jsx(gt,{className:"text-center",children:kt.max_quantity!==null?e.jsxs("span",{className:kt.current_quantity===0?"text-red-500":"",children:[kt.current_quantity,"/",kt.max_quantity]}):e.jsx("span",{className:"text-muted-foreground",children:"Unlimited"})}),e.jsx(gt,{className:"text-center",children:e.jsx(Xe,{variant:kt.is_active?"default":"secondary",children:kt.is_active?"Active":"Inactive"})}),e.jsx(gt,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx(H,{variant:"ghost",size:"sm",onClick:()=>hs(kt),children:e.jsx(ni,{className:"h-4 w-4"})}),e.jsx(H,{variant:"ghost",size:"sm",onClick:()=>je(kt.id),children:e.jsx(Dr,{className:"h-4 w-4 text-destructive"})})]})})]},kt.id))})]})})]})}),e.jsx(cs,{value:"categories",className:"mt-4",children:e.jsxs(ke,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(zt,{children:"Categories"}),e.jsx(Br,{children:"Organize your store items into categories"})]}),e.jsxs(H,{onClick:()=>at(),children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Add Category"]})]}),e.jsx(Oe,{children:!Pe||Pe.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Uf,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No categories yet. Add your first category!"})]}):e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Vs,{children:[e.jsx(At,{children:"Name"}),e.jsx(At,{children:"Description"}),e.jsx(At,{className:"text-center",children:"Items"}),e.jsx(At,{className:"text-right",children:"Actions"})]})}),e.jsx(da,{children:Pe.map(kt=>e.jsxs(Vs,{children:[e.jsxs(gt,{className:"font-medium",children:[kt.icon&&e.jsx("span",{className:"mr-2",children:kt.icon}),kt.name]}),e.jsx(gt,{className:"text-muted-foreground",children:kt.description||"—"}),e.jsx(gt,{className:"text-center",children:(De==null?void 0:De.filter(fs=>fs.category_id===kt.id).length)||0}),e.jsx(gt,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx(H,{variant:"ghost",size:"sm",onClick:()=>at(kt),children:e.jsx(ni,{className:"h-4 w-4"})}),e.jsx(H,{variant:"ghost",size:"sm",onClick:()=>y(kt.id),children:e.jsx(Dr,{className:"h-4 w-4 text-destructive"})})]})})]},kt.id))})]})})]})}),e.jsx(cs,{value:"purchases",className:"mt-4",children:e.jsxs(ke,{children:[e.jsxs(Ot,{children:[e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(sx,{className:"h-5 w-5"}),"Purchase History"]}),e.jsx(Br,{children:"View all reward redemptions by agents"})]}),e.jsx(Oe,{children:!tt||tt.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(sx,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No purchases yet."})]}):e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Vs,{children:[e.jsx(At,{children:"Date"}),e.jsx(At,{children:"Agent"}),e.jsx(At,{children:"Item"}),e.jsx(At,{className:"text-center",children:"Points Spent"})]})}),e.jsx(da,{children:tt.map(kt=>{var fs,Gs,_s,br;return e.jsxs(Vs,{children:[e.jsx(gt,{className:"text-muted-foreground",children:As(new Date(kt.purchased_at),"MMM d, yyyy 'at' h:mm a")}),e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-8 w-8 rounded-full bg-muted flex items-center justify-center",children:e.jsx(io,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((fs=kt.user)==null?void 0:fs.name)||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:((Gs=kt.user)==null?void 0:Gs.email)||"—"})]})]})}),e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[(_s=kt.item)!=null&&_s.preview_image_url?e.jsx("img",{src:kt.item.preview_image_url,alt:kt.item.name,className:"h-8 w-8 rounded object-cover"}):e.jsx("div",{className:"h-8 w-8 rounded bg-muted flex items-center justify-center",children:e.jsx(Di,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{children:((br=kt.item)==null?void 0:br.name)||"Deleted item"})]})}),e.jsx(gt,{className:"text-center",children:e.jsxs(Xe,{variant:"secondary",className:"font-bold",children:[e.jsx(ya,{className:"h-3 w-3 mr-1"}),kt.points_spent]})})]},kt.id)})})]})})]})})]})]}),e.jsx(bs,{open:n,onOpenChange:a,children:e.jsxs(vs,{children:[e.jsxs(Cs,{children:[e.jsx(Ns,{children:i?"Edit Category":"Add Category"}),e.jsx(nn,{children:i?"Update the category details":"Create a new category for your store items"})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"categoryName",children:"Name"}),e.jsx(Se,{id:"categoryName",value:o,onChange:kt=>c(kt.target.value),placeholder:"e.g., Templates, Resources"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"categoryDescription",children:"Description"}),e.jsx(vr,{id:"categoryDescription",value:d,onChange:kt=>h(kt.target.value),placeholder:"Optional description..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"categoryIcon",children:"Icon (emoji)"}),e.jsx(Se,{id:"categoryIcon",value:m,onChange:kt=>p(kt.target.value),placeholder:"e.g., 📄, 🎁"})]})]}),e.jsxs(wn,{children:[e.jsx(H,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(H,{onClick:rt,disabled:et.isPending||Qe.isPending,children:et.isPending||Qe.isPending?"Saving...":"Save"})]})]})}),e.jsx(bs,{open:_,onOpenChange:b,children:e.jsxs(vs,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(Cs,{children:[e.jsx(Ns,{children:j?"Edit Item":"Add Item"}),e.jsx(nn,{children:j?"Update the item details":"Create a new reward item for agents to purchase"})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"itemName",children:"Name *"}),e.jsx(Se,{id:"itemName",value:T,onChange:kt=>E(kt.target.value),placeholder:"e.g., Premium Template Pack"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"itemDescription",children:"Description"}),e.jsx(vr,{id:"itemDescription",value:A,onChange:kt=>D(kt.target.value),placeholder:"Describe the item..."})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"itemCategory",children:"Category"}),e.jsxs(Bs,{value:R||"none",onValueChange:kt=>z(kt==="none"?null:kt),children:[e.jsx(Os,{children:e.jsx(Us,{placeholder:"Select category"})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"none",children:"No category"}),Pe==null?void 0:Pe.map(kt=>e.jsxs(pt,{value:kt.id,children:[kt.icon&&`${kt.icon} `,kt.name]},kt.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"itemPointsCost",children:"Points Cost *"}),e.jsx(Se,{id:"itemPointsCost",type:"number",min:"0",value:O,onChange:kt=>$(kt.target.value),placeholder:"e.g., 100"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"itemType",children:"Type"}),e.jsxs(Bs,{value:ee,onValueChange:Z,children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"file",children:"File Download"}),e.jsx(pt,{value:"link",children:"External Link"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"itemMaxQuantity",children:"Max Quantity"}),e.jsx(Se,{id:"itemMaxQuantity",type:"number",min:"1",value:ce,onChange:kt=>ne(kt.target.value),placeholder:"Leave empty for unlimited"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"File / Link URL"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Se,{value:J,onChange:kt=>K(kt.target.value),placeholder:ee==="file"?"Upload a file or paste URL":"Paste external link"}),ee==="file"&&e.jsxs(e.Fragment,{children:[e.jsx(H,{type:"button",variant:"outline",size:"icon",onClick:()=>{var kt;return(kt=Me.current)==null?void 0:kt.click()},disabled:ve,children:e.jsx(Ea,{className:"h-4 w-4"})}),e.jsx("input",{ref:Me,type:"file",className:"hidden",onChange:kt=>{var Gs;const fs=(Gs=kt.target.files)==null?void 0:Gs[0];fs&&Is(fs,"file")}})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Preview Image"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Se,{value:re,onChange:kt=>ie(kt.target.value),placeholder:"Upload an image or paste URL"}),e.jsx(H,{type:"button",variant:"outline",size:"icon",onClick:()=>{var kt;return(kt=ze.current)==null?void 0:kt.click()},disabled:Ve,children:e.jsx(wl,{className:"h-4 w-4"})}),e.jsx("input",{ref:ze,type:"file",accept:"image/*",className:"hidden",onChange:kt=>{var Gs;const fs=(Gs=kt.target.files)==null?void 0:Gs[0];fs&&Is(fs,"preview")}})]}),re&&e.jsx("img",{src:re,alt:"Preview",className:"mt-2 h-24 rounded object-cover"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Or,{id:"itemIsActive",checked:le,onCheckedChange:be}),e.jsx(ue,{htmlFor:"itemIsActive",children:"Active (visible to agents)"})]})]}),e.jsxs(wn,{children:[e.jsx(H,{variant:"outline",onClick:()=>b(!1),children:"Cancel"}),e.jsx(H,{onClick:lr,disabled:$e.isPending||it.isPending,children:$e.isPending||it.isPending?"Saving...":"Save"})]})]})}),e.jsx(Rl,{open:!!x,onOpenChange:()=>y(null),children:e.jsxs(jl,{children:[e.jsxs(Nl,{children:[e.jsx(Sl,{children:"Delete Category"}),e.jsx(Cl,{children:"Are you sure you want to delete this category? Items in this category will become uncategorized."})]}),e.jsxs(kl,{children:[e.jsx(Tl,{children:"Cancel"}),e.jsx(ml,{onClick:Et,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})}),e.jsx(Rl,{open:!!fe,onOpenChange:()=>je(null),children:e.jsxs(jl,{children:[e.jsxs(Nl,{children:[e.jsx(Sl,{children:"Delete Item"}),e.jsx(Cl,{children:"Are you sure you want to delete this item? This action cannot be undone."})]}),e.jsxs(kl,{children:[e.jsx(Tl,{children:"Cancel"}),e.jsx(ml,{onClick:us,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})}),t==="point-settings"&&e.jsxs(ke,{className:"mt-4",children:[e.jsx(Ot,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Go,{className:"h-5 w-5"}),e.jsxs("div",{children:[e.jsx(zt,{children:"Point Reward Settings"}),e.jsx(Br,{children:"Configure how many points agents earn for various actions. Adjust these values to run double-points promotions."})]})]})}),e.jsx(Oe,{children:!ct||ct.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Go,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No point settings configured."})]}):e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Vs,{children:[e.jsx(At,{children:"Action"}),e.jsx(At,{children:"Description"}),e.jsx(At,{className:"text-center w-32",children:"Points"}),e.jsx(At,{className:"text-right w-24",children:"Save"})]})}),e.jsx(da,{children:ct.map(kt=>e.jsxs(Vs,{children:[e.jsx(gt,{children:e.jsx("p",{className:"font-medium",children:kt.action_name})}),e.jsx(gt,{children:e.jsx("p",{className:"text-sm text-muted-foreground",children:kt.description})}),e.jsx(gt,{className:"text-center",children:e.jsx(Se,{type:"number",min:"0",className:"w-20 mx-auto text-center",value:mt[kt.id]??kt.points.toString(),onChange:fs=>wt(Gs=>({...Gs,[kt.id]:fs.target.value}))})}),e.jsx(gt,{className:"text-right",children:e.jsx(H,{size:"sm",variant:"outline",disabled:mt[kt.id]===void 0||mt[kt.id]===kt.points.toString()||st.isPending,onClick:()=>St(kt.id,kt.points),children:e.jsx(vc,{className:"h-4 w-4"})})})]},kt.id))})]})})]})]})}const wWe=()=>e.jsxs("svg",{viewBox:"0 0 100 100",className:"h-5 w-5",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[e.jsx("rect",{width:"100",height:"100",rx:"20",fill:"#7D2AE8"}),e.jsx("path",{d:"M50 20C33.43 20 20 33.43 20 50C20 66.57 33.43 80 50 80C66.57 80 80 66.57 80 50C80 33.43 66.57 20 50 20ZM63.5 63.5C58.3 68.7 50 70.6 43.1 67.6C36.2 64.6 32 57.6 32 50C32 42.4 36.2 35.4 43.1 32.4C50 29.4 58.3 31.3 63.5 36.5L59.3 40.7C55.8 37.2 50.7 35.8 46 37.3C41.3 38.8 37.7 42.8 36.6 47.6C35.5 52.4 37 57.4 40.4 60.8C43.8 64.2 48.8 65.7 53.6 64.6C58.4 63.5 62.4 59.9 63.9 55.2L68.7 56.7C66.9 61.3 65.5 61.5 63.5 63.5Z",fill:"white"})]}),jWe=[{value:"template",label:"Templates"},{value:"brand",label:"Brand Assets"},{value:"listing",label:"Listing Assets"},{value:"social",label:"Social Media"},{value:"general",label:"General"}];function GBs(){const s=ns(),[t,r]=S.useState(!1),[n,a]=S.useState(!1),[i,l]=S.useState(!1),[o,c]=S.useState({brokerage_id:"",folder_id:"",folder_name:"",folder_type:"template",description:""}),{data:d,isLoading:h}=yt({queryKey:["canva-integration"],queryFn:async()=>{const{data:k,error:T}=await V.from("canva_integration").select("*").eq("is_active",!0).maybeSingle();if(T)throw T;return k}}),{data:m}=yt({queryKey:["brokerages-list"],queryFn:async()=>{const{data:k,error:T}=await V.from("brokerages").select("id, name").order("name");if(T)throw T;return k}}),{data:p}=yt({queryKey:["canva-brokerage-folders"],queryFn:async()=>{const{data:k,error:T}=await V.from("canva_brokerage_folders").select("*, brokerages(name)").order("sort_order");if(T)throw T;return k}}),x=async()=>{var k;r(!0);try{const{data:T}=await V.auth.getSession(),E=(k=T==null?void 0:T.session)==null?void 0:k.access_token;if(!E)throw new Error("Not authenticated");const R=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/canva-oauth",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${E}`,apikey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJlbHplamlzd25vdGlramd2amh6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE5NTAzNDQsImV4cCI6MjA3NzUyNjM0NH0.dzIkIr_oFSbFE3oWS0ktIr83iKHHkZxt40Gc7SpC_mM"},body:JSON.stringify({action:"get_auth_url"})}),z=await R.json();if(!R.ok||z!=null&&z.error)throw new Error((z==null?void 0:z.error)||"Failed to get authorization URL");if(z!=null&&z.authUrl){localStorage.setItem("canva_code_verifier",z.codeVerifier),localStorage.setItem("canva_oauth_state",z.state);const O=window.open(z.authUrl,"canva-oauth","width=600,height=700,scrollbars=yes,resizable=yes");if(!O){he.error("Popup was blocked. Please allow popups for this site and try again."),r(!1);return}const $=Z=>{var J,K;Z.origin===window.location.origin&&(((J=Z.data)==null?void 0:J.type)==="canva-oauth-success"?(window.removeEventListener("message",$),he.success("Canva connected successfully!"),s.invalidateQueries({queryKey:["canva-integration"]}),r(!1)):((K=Z.data)==null?void 0:K.type)==="canva-oauth-error"&&(window.removeEventListener("message",$),he.error("Canva connection failed: "+(Z.data.error||"Unknown error")),r(!1)))};window.addEventListener("message",$);const ee=setInterval(()=>{O.closed&&(clearInterval(ee),window.removeEventListener("message",$),s.invalidateQueries({queryKey:["canva-integration"]}),r(!1))},500)}else throw new Error("Failed to get authorization URL")}catch(T){console.error("Canva connect error:",T);const E=(T==null?void 0:T.message)||"";E.includes("CANVA_CLIENT_ID")?he.error("Canva app credentials not configured yet."):he.error(E||"Failed to start Canva connection"),r(!1)}},y=Pt({mutationFn:async k=>{var O;const{data:T}=await V.auth.getSession(),E=(O=T==null?void 0:T.session)==null?void 0:O.access_token;if(!E)throw new Error("Not authenticated");const R=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/canva-oauth",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${E}`,apikey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJlbHplamlzd25vdGlramd2amh6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE5NTAzNDQsImV4cCI6MjA3NzUyNjM0NH0.dzIkIr_oFSbFE3oWS0ktIr83iKHHkZxt40Gc7SpC_mM"},body:JSON.stringify({action:"disconnect",integrationId:k})}),z=await R.json();if(!R.ok||z!=null&&z.error)throw new Error((z==null?void 0:z.error)||"Failed to disconnect")},onSuccess:()=>{s.invalidateQueries({queryKey:["canva-integration"]}),he.success("Canva disconnected")},onError:k=>{he.error(k.message||"Failed to disconnect Canva")}}),_=Pt({mutationFn:async k=>{const{error:T}=await V.from("canva_brokerage_folders").insert({brokerage_id:k.brokerage_id,folder_id:k.folder_id.trim(),folder_name:k.folder_name.trim(),folder_type:k.folder_type,description:k.description.trim()||null,sort_order:(p==null?void 0:p.length)||0});if(T)throw T},onSuccess:()=>{s.invalidateQueries({queryKey:["canva-brokerage-folders"]}),he.success("Folder added"),l(!1),c({brokerage_id:"",folder_id:"",folder_name:"",folder_type:"template",description:""})},onError:()=>he.error("Failed to add folder")}),b=Pt({mutationFn:async k=>{const{error:T}=await V.from("canva_brokerage_folders").delete().eq("id",k);if(T)throw T},onSuccess:()=>{s.invalidateQueries({queryKey:["canva-brokerage-folders"]}),he.success("Folder removed")},onError:()=>he.error("Failed to remove folder")}),j=!!d;return e.jsxs(e.Fragment,{children:[e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-accent flex items-center justify-center",children:e.jsx(wWe,{})}),e.jsxs("div",{children:[e.jsxs(zt,{className:"text-lg flex items-center gap-2",children:["Canva Connect",j&&e.jsx(Xe,{variant:"default",className:"text-xs",children:"Connected"}),e.jsx(Xe,{variant:"outline",className:"text-xs",children:"Admin Only"})]}),e.jsx(Br,{children:"Auto-share brokerage asset folders with agents when they connect their Canva accounts."})]})]})})}),e.jsx(Oe,{children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-2 text-sm text-muted-foreground",children:[e.jsx(zi,{className:"h-4 w-4 mt-0.5 text-primary shrink-0"}),e.jsx("span",{children:"OAuth 2.0 + PKCE for secure authorization"})]}),e.jsxs("div",{className:"flex items-start gap-2 text-sm text-muted-foreground",children:[e.jsx(zi,{className:"h-4 w-4 mt-0.5 text-primary shrink-0"}),e.jsx("span",{children:"Map brokerage folders to auto-share with agents on connection"})]}),e.jsxs("div",{className:"flex items-start gap-2 text-sm text-muted-foreground",children:[e.jsx(zi,{className:"h-4 w-4 mt-0.5 text-primary shrink-0"}),e.jsx("span",{children:"Multiple folders per brokerage (templates, brand assets, listings)"})]}),e.jsxs("div",{className:"mt-4 p-3 rounded-lg bg-muted border border-dashed",children:[e.jsx("p",{className:"text-xs font-medium text-foreground mb-1",children:"Canva App Redirect URL"}),e.jsx("code",{className:"text-xs text-muted-foreground break-all select-all",children:"https://dashboard.relevelup.com/canva-callback.html"})]}),j?e.jsxs("div",{className:"space-y-3 mt-4",children:[e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:d.canva_team_id?`Team: ${d.canva_team_id}`:"Canva Account"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:d.expires_at?`Token expires ${new Date(d.expires_at).toLocaleDateString()}`:"Platform integration active"})]}),e.jsxs(Rl,{children:[e.jsx(vp,{asChild:!0,children:e.jsx(H,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(Dr,{className:"h-4 w-4"})})}),e.jsxs(jl,{children:[e.jsxs(Nl,{children:[e.jsx(Sl,{children:"Disconnect Canva?"}),e.jsx(Cl,{children:"This will remove the Canva platform integration. Agents who have already connected will not be affected, but new folder sharing will stop."})]}),e.jsxs(kl,{children:[e.jsx(Tl,{children:"Cancel"}),e.jsx(ml,{onClick:()=>y.mutate(d.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]}),e.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[e.jsxs("button",{onClick:()=>a(!n),className:"w-full flex items-center justify-between p-3 text-sm font-medium hover:bg-muted transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Uf,{className:"h-4 w-4 text-primary"}),"Brokerage Folder Mappings",p&&p.length>0&&e.jsx(Xe,{variant:"secondary",className:"text-xs",children:p.length})]}),n?e.jsx(cx,{className:"h-4 w-4"}):e.jsx(Io,{className:"h-4 w-4"})]}),n&&e.jsxs("div",{className:"border-t p-3 space-y-2",children:[p&&p.length>0?p.map(k=>{var T,E;return e.jsxs("div",{className:"flex items-center justify-between p-2 rounded-md bg-muted/50 text-sm",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"font-medium truncate",children:k.folder_name}),e.jsx(Xe,{variant:"outline",className:"text-xs shrink-0",children:((T=jWe.find(A=>A.value===k.folder_type))==null?void 0:T.label)||k.folder_type})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(E=k.brokerages)==null?void 0:E.name," · ID: ",e.jsx("span",{className:"font-mono",children:k.folder_id})]})]}),e.jsx(H,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-destructive shrink-0 ml-2",onClick:()=>b.mutate(k.id),children:e.jsx(Rr,{className:"h-3.5 w-3.5"})})]},k.id)}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-2",children:"No folders mapped yet"}),e.jsxs(H,{variant:"outline",size:"sm",className:"w-full gap-1.5 mt-1",onClick:()=>l(!0),children:[e.jsx(Ys,{className:"h-3.5 w-3.5"}),"Add Folder Mapping"]})]})]})]}):e.jsxs(H,{className:"mt-4",onClick:x,disabled:t||h,children:[t?e.jsx(po,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx("div",{className:"mr-2",children:e.jsx(wWe,{})}),"Connect Canva",e.jsx(bi,{className:"h-4 w-4 ml-2"})]})]})})]}),e.jsx(bs,{open:i,onOpenChange:l,children:e.jsxs(vs,{children:[e.jsx(Cs,{children:e.jsx(Ns,{children:"Add Brokerage Folder Mapping"})}),e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{children:"Brokerage"}),e.jsxs(Bs,{value:o.brokerage_id,onValueChange:k=>c(T=>({...T,brokerage_id:k})),children:[e.jsx(Os,{children:e.jsx(Us,{placeholder:"Select a brokerage…"})}),e.jsx(Fs,{children:m==null?void 0:m.map(k=>e.jsx(pt,{value:k.id,children:k.name},k.id))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{children:"Canva Folder ID"}),e.jsx(Se,{placeholder:"e.g. FABCdef123456",value:o.folder_id,onChange:k=>c(T=>({...T,folder_id:k.target.value}))}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Found in the Canva folder URL: canva.com/folder/",e.jsx("strong",{children:"FOLDER_ID"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{children:"Folder Display Name"}),e.jsx(Se,{placeholder:"e.g. Brand Templates 2024",value:o.folder_name,onChange:k=>c(T=>({...T,folder_name:k.target.value}))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{children:"Folder Type"}),e.jsxs(Bs,{value:o.folder_type,onValueChange:k=>c(T=>({...T,folder_type:k})),children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsx(Fs,{children:jWe.map(k=>e.jsx(pt,{value:k.value,children:k.label},k.value))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(ue,{children:["Description ",e.jsx("span",{className:"text-muted-foreground",children:"(optional)"})]}),e.jsx(Se,{placeholder:"What's in this folder?",value:o.description,onChange:k=>c(T=>({...T,description:k.target.value}))})]})]}),e.jsxs(wn,{children:[e.jsx(H,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsxs(H,{onClick:()=>_.mutate(o),disabled:!o.brokerage_id||!o.folder_id||!o.folder_name||_.isPending,children:[_.isPending?e.jsx(po,{className:"h-4 w-4 mr-2 animate-spin"}):null,"Add Folder"]})]})]})})]})}function WBs(){const s=Fr();return e.jsx(Ss,{children:e.jsxs("div",{className:"space-y-6 p-4 md:p-8",children:[e.jsx(km,{title:"Integrations",description:"Manage platform-level service connections"}),e.jsxs(ke,{className:"p-6 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"p-3 rounded-lg bg-primary/10",children:e.jsx(cd,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold",children:"User Social Connections"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"See which agents have connected Facebook, Instagram, LinkedIn, and Google."})]})]}),e.jsxs(H,{onClick:()=>s("/admin/social-connections"),children:["View ",e.jsx(bi,{className:"h-4 w-4 ml-1"})]})]}),e.jsx(GBs,{}),e.jsx(Kyt,{})]})})}const NWe=s=>{const t="h-4 w-4";return s==="facebook"?e.jsx(fh,{className:t}):s==="instagram"?e.jsx(yu,{className:t}):s==="linkedin"?e.jsx(qf,{className:t}):s==="google"?e.jsx(er,{className:t}):null},KBs=s=>s?new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",year:"numeric",month:"short",day:"numeric"}).format(new Date(s)):"—";function YBs(){const[s,t]=S.useState([]),[r,n]=S.useState(!0),[a,i]=S.useState(""),[l,o]=S.useState("all");S.useEffect(()=>{(async()=>{n(!0);const{data:p,error:x}=await V.rpc("admin_get_social_connections");if(x){he.error(x.message),n(!1);return}t(p||[]),n(!1)})()},[]);const c=S.useMemo(()=>{const p=a.trim().toLowerCase();return s.filter(x=>l!=="all"&&x.platform!==l?!1:p?(x.user_name||"").toLowerCase().includes(p)||(x.user_email||"").toLowerCase().includes(p)||(x.page_name||"").toLowerCase().includes(p)||(x.platform_username||"").toLowerCase().includes(p):!0)},[s,a,l]),d=S.useMemo(()=>{const p=new Map;return s.forEach(x=>{const y=p.get(x.user_id)||{name:x.user_name,email:x.user_email,platforms:new Set,count:0};y.platforms.add(x.platform),y.count+=1,p.set(x.user_id,y)}),Array.from(p.entries()).map(([x,y])=>({user_id:x,...y}))},[s]),h=S.useMemo(()=>{const p=new Map;return s.forEach(x=>p.set(x.platform,(p.get(x.platform)||0)+1)),{uniqueUsers:d.length,totalConnections:s.length,byPlatform:Array.from(p.entries())}},[s,d]),m=p=>p&&new Date(p).getTime()e.jsxs(ke,{className:"p-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground capitalize flex items-center gap-2",children:[NWe(p)," ",p]}),e.jsx("div",{className:"text-2xl font-bold",children:x})]},p))]}),e.jsxs("div",{className:"flex flex-col md:flex-row gap-3",children:[e.jsx(Se,{placeholder:"Search by user, email, page, or handle…",value:a,onChange:p=>i(p.target.value),className:"md:max-w-md"}),e.jsxs(Bs,{value:l,onValueChange:o,children:[e.jsx(Os,{className:"md:w-48",children:e.jsx(Us,{placeholder:"All platforms"})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"all",children:"All platforms"}),e.jsx(pt,{value:"facebook",children:"Facebook"}),e.jsx(pt,{value:"instagram",children:"Instagram"}),e.jsx(pt,{value:"linkedin",children:"LinkedIn"}),e.jsx(pt,{value:"google",children:"Google"})]})]})]}),e.jsx(ke,{children:r?e.jsx("div",{className:"flex items-center justify-center p-12",children:e.jsx(is,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Vs,{children:[e.jsx(At,{children:"User"}),e.jsx(At,{children:"Platform"}),e.jsx(At,{children:"Page / Account"}),e.jsx(At,{children:"Status"}),e.jsx(At,{children:"Connected"})]})}),e.jsx(da,{children:c.length===0?e.jsx(Vs,{children:e.jsx(gt,{colSpan:5,className:"text-center text-muted-foreground py-8",children:"No connections found."})}):c.map(p=>{const x=m(p.token_expires_at);return e.jsxs(Vs,{children:[e.jsxs(gt,{children:[e.jsx("div",{className:"font-medium",children:p.user_name||"—"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:p.user_email})]}),e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-2 capitalize",children:[NWe(p.platform)," ",p.platform]})}),e.jsxs(gt,{children:[e.jsx("div",{className:"font-medium",children:p.page_name||p.platform_username||"—"}),p.instagram_business_id&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["IG Business: ",p.instagram_business_id]})]}),e.jsx(gt,{children:p.is_active?x?e.jsxs(Xe,{variant:"destructive",className:"gap-1",children:[e.jsx(wo,{className:"h-3 w-3"})," Expired"]}):e.jsx(Xe,{children:"Active"}):e.jsx(Xe,{variant:"secondary",children:"Inactive"})}),e.jsx(gt,{className:"text-sm text-muted-foreground",children:KBs(p.created_at)})]},p.id)})})]})})]})})}const ZBs={new_events:{label:"New Events",icon:"📅"},new_templates:{label:"New Templates",icon:"📄"},new_toolbox:{label:"New Toolbox Resources",icon:"🧰"},new_social_swag:{label:"New Social Swag",icon:"🎨"},new_newsletters:{label:"New Newsletters",icon:"📰"},new_community_posts:{label:"New Community Posts",icon:"💬"}};function sO(s,t=18,r=10){return s.length<=t+r+3?s:`${s.slice(0,t)}…${s.slice(-r)}`}function XBs(){var ee,Z,J,K,re;const s=ns(),[t,r]=S.useState("Test Push"),[n,a]=S.useState("Testing web push notification"),[i,l]=S.useState("/community"),[o,c]=S.useState(!1),[d,h]=S.useState(!1),[m,p]=S.useState({isSupported:typeof window<"u"&&"serviceWorker"in navigator&&"PushManager"in window}),[x,y]=S.useState(null),[_,b]=S.useState(null),{data:j,isLoading:k}=yt({queryKey:["push-notification-settings"],queryFn:async()=>{const{data:ie,error:ce}=await V.from("push_notification_settings").select("*").order("setting_key");if(ce)throw ce;return ie}}),{data:T,isLoading:E}=yt({queryKey:["push-subscription-stats"],queryFn:async()=>{const{count:ie,error:ce}=await V.from("push_subscriptions").select("*",{count:"exact",head:!0});if(ce)throw ce;return{totalSubscriptions:ie||0}}}),A=Pt({mutationFn:async({settingKey:ie,isEnabled:ce})=>{const{error:ne}=await V.from("push_notification_settings").update({is_enabled:ce}).eq("setting_key",ie);if(ne)throw ne},onSuccess:()=>{s.invalidateQueries({queryKey:["push-notification-settings"]}),he.success("Notification setting updated")},onError:ie=>{he.error("Failed to update setting: "+ie.message)}}),D=S.useMemo(()=>{var ie,ce;return m.isSupported?`perm=${m.permission??"unknown"} · controller=${m.controllerPresent?"yes":"no"} · sw=${((ie=m.serviceWorker)==null?void 0:ie.activeState)??"unknown"} · sub=${(ce=m.subscription)!=null&&ce.endpoint?"yes":"no"}`:"Push not supported in this browser."},[m]);S.useEffect(()=>{let ie=!0;const ce=async()=>{var fe,je,ve,We,Ve,Le,Me;const le="serviceWorker"in navigator&&"PushManager"in window,be={isSupported:le,permission:typeof Notification<"u"?Notification.permission:void 0,controllerPresent:!!((fe=navigator.serviceWorker)!=null&&fe.controller)};if(!le){ie&&p(be);return}try{const{data:ze,error:Pe}=await V.functions.invoke("get-vapid-public-key",{body:{}});if(Pe)throw Pe;be.vapidPublicKey=ze==null?void 0:ze.vapidPublicKey;const De=(await navigator.serviceWorker.getRegistrations()).find(pe=>{var ge,ct,Ue;return(((ge=pe.active)==null?void 0:ge.scriptURL)||((ct=pe.waiting)==null?void 0:ct.scriptURL)||((Ue=pe.installing)==null?void 0:Ue.scriptURL)||"").includes("/sw.js")});if(De){be.pushWorkerScriptUrl=((je=De.active)==null?void 0:je.scriptURL)||((ve=De.waiting)==null?void 0:ve.scriptURL)||((We=De.installing)==null?void 0:We.scriptURL),be.serviceWorker={scope:De.scope,activeState:(Ve=De.active)==null?void 0:Ve.state};const pe=await De.pushManager.getSubscription();if(pe){const tt=pe.toJSON();be.subscription={endpoint:tt.endpoint,p256dh:(Le=tt.keys)==null?void 0:Le.p256dh,auth:(Me=tt.keys)==null?void 0:Me.auth}}}}catch(ze){be.error=(ze==null?void 0:ze.message)||String(ze)}ie&&p(be)};ce();const ne=window.setInterval(ce,4e3);return()=>{ie=!1,window.clearInterval(ne)}},[]);const R=async()=>{if(typeof Notification>"u"){he.error("Notifications API not available in this browser.");return}try{if(Notification.permission!=="granted"&&await Notification.requestPermission()!=="granted"){he.error("Notification permission not granted.");return}new Notification("Local notification test",{body:"If you see this, OS/browser notifications can display."}),he.success("Triggered a local notification (not push).")}catch(ie){he.error(`Local notification failed: ${(ie==null?void 0:ie.message)||String(ie)}`)}},z=async()=>{c(!0),y(null);try{const{data:ie,error:ce}=await V.functions.invoke("send-push-notification",{body:{title:t,body:n,url:i}});if(ce)throw ce;y({sent:ie==null?void 0:ie.sent,failed:ie==null?void 0:ie.failed,expiredCleaned:ie==null?void 0:ie.expiredCleaned,vapidPublicKey:ie==null?void 0:ie.vapidPublicKey}),(ie==null?void 0:ie.sent)>0?he.success(`Test notification sent to ${ie.sent} subscriber(s)`):(ie==null?void 0:ie.failed)>0?he.warning(`Notification failed for ${ie.failed} subscriber(s). ${ie.expired||0} expired subscriptions cleaned up.`):he.info("No active subscriptions to send to")}catch(ie){console.error("Error sending test notification:",ie),y({error:(ie==null?void 0:ie.message)||String(ie)}),he.error("Failed to send test notification: "+(ie.message||"Unknown error"))}finally{c(!1)}},O=async()=>{h(!0),b(null);try{const{data:ie,error:ce}=await V.functions.invoke("generate-vapid-keys",{body:{}});if(ce)throw ce;const ne=ie==null?void 0:ie.publicKey,le=ie==null?void 0:ie.privateKey;if(!ne||!le)throw new Error("generate-vapid-keys did not return keys");b({publicKey:ne,privateKey:le}),he.success("Generated new VAPID keys. Update backend secrets, then clear + re-subscribe.")}catch(ie){console.error("Error generating VAPID keys:",ie),he.error("Failed to generate VAPID keys: "+((ie==null?void 0:ie.message)||"Unknown error"))}finally{h(!1)}},$=Pt({mutationFn:async()=>{const{error:ie}=await V.from("push_subscriptions").delete().neq("id","00000000-0000-0000-0000-000000000000");if(ie)throw ie},onSuccess:()=>{he.success("All subscriptions cleared. Users will need to re-enable notifications."),s.invalidateQueries({queryKey:["push-subscription-stats"]})},onError:ie=>{he.error("Failed to clear subscriptions: "+ie.message)}});return e.jsx(Ss,{title:"Notification Settings",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(km,{title:"Notification Settings",description:"Manage push notifications and test the notification system"}),e.jsxs(ke,{children:[e.jsxs(Ot,{children:[e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(Ar,{className:"h-5 w-5"}),"Push Notification Subscribers"]}),e.jsx(Br,{children:"Current active push notification subscriptions"})]}),e.jsx(Oe,{children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"text-4xl font-bold",children:E?"...":(T==null?void 0:T.totalSubscriptions)||0}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"active subscriptions"})]})})]}),e.jsxs(ke,{children:[e.jsxs(Ot,{children:[e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(Go,{className:"h-5 w-5"}),"Notification Types"]}),e.jsx(Br,{children:"Control which types of push notifications are sent to users"})]}),e.jsx(Oe,{children:k?e.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading settings..."}):e.jsx("div",{className:"space-y-4",children:j==null?void 0:j.map(ie=>{const ce=ZBs[ie.setting_key]||{label:ie.setting_key,icon:"🔔"};return e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-2xl",children:ce.icon}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:ce.label}),e.jsx("div",{className:"text-sm text-muted-foreground",children:ie.description})]})]}),e.jsx(Or,{checked:ie.is_enabled,onCheckedChange:ne=>A.mutate({settingKey:ie.setting_key,isEnabled:ne}),disabled:A.isPending})]},ie.id)})})})]}),e.jsxs(ke,{children:[e.jsxs(Ot,{children:[e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(wp,{className:"h-5 w-5"}),"Send Test Notification"]}),e.jsx(Br,{children:"Send a test push notification to all subscribed users"})]}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-md border bg-muted/30 p-3 text-sm",children:[e.jsx("div",{className:"font-medium",children:"Client push debug"}),e.jsx("div",{className:"mt-1 text-muted-foreground",children:D}),m.error&&e.jsx("div",{className:"mt-2 text-destructive",children:m.error}),e.jsxs("div",{className:"mt-2 grid gap-2 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Backend VAPID public key"}),e.jsx("div",{className:"break-all rounded-md border bg-background p-2 font-mono text-xs",children:m.vapidPublicKey?sO(m.vapidPublicKey):"(not loaded)"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Service worker"}),e.jsxs("div",{className:"rounded-md border bg-background p-2 font-mono text-xs",children:[e.jsxs("div",{children:["scope: ",(ee=m.serviceWorker)!=null&&ee.scope?sO(m.serviceWorker.scope,24,8):"none"]}),e.jsxs("div",{children:["active: ",((Z=m.serviceWorker)==null?void 0:Z.activeState)??"none"]})]})]}),e.jsxs("div",{className:"space-y-1 sm:col-span-2",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Current browser subscription"}),e.jsxs("div",{className:"rounded-md border bg-background p-2 font-mono text-xs",children:[e.jsxs("div",{children:["endpoint: ",(J=m.subscription)!=null&&J.endpoint?sO(m.subscription.endpoint,40,12):"none"]}),e.jsxs("div",{children:["p256dh: ",(K=m.subscription)!=null&&K.p256dh?sO(m.subscription.p256dh,22,10):"none"]}),e.jsxs("div",{children:["auth: ",(re=m.subscription)!=null&&re.auth?sO(m.subscription.auth,22,10):"none"]})]})]})]}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsx(H,{variant:"outline",onClick:R,children:"Local notification test"}),e.jsx(H,{variant:"outline",onClick:()=>window.location.reload(),children:"Reload page"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"test-title",children:"Notification Title"}),e.jsx(Se,{id:"test-title",value:t,onChange:ie=>r(ie.target.value),placeholder:"Enter notification title"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"test-body",children:"Notification Body"}),e.jsx(vr,{id:"test-body",value:n,onChange:ie=>a(ie.target.value),placeholder:"Enter notification message",rows:3})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"test-url",children:"Click URL (optional)"}),e.jsx(Se,{id:"test-url",value:i,onChange:ie=>l(ie.target.value),placeholder:"/community or full URL"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Where users will be taken when they click the notification"})]}),e.jsxs(H,{onClick:z,disabled:o||!t||!n,className:"w-full sm:w-auto",children:[e.jsx(yn,{className:"h-4 w-4 mr-2"}),o?"Sending...":"Send Test Notification"]}),x&&e.jsxs("div",{className:"rounded-md border bg-muted/30 p-3 text-sm",children:[e.jsx("div",{className:"font-medium",children:"Last send debug"}),x.error?e.jsxs("div",{className:"mt-1 text-destructive",children:["Error: ",x.error]}):e.jsxs("div",{className:"mt-1 space-y-1 text-muted-foreground",children:[e.jsxs("div",{children:["Result: ",x.sent??0," sent, ",x.failed??0," failed, ",x.expiredCleaned??0," expired cleaned"]}),x.vapidPublicKey?e.jsxs("div",{className:"break-all",children:["Backend VAPID public key: ",e.jsx("span",{className:"font-mono",children:x.vapidPublicKey})]}):e.jsx("div",{children:"Backend VAPID public key: (not returned)"})]})]})]})]}),e.jsxs(ke,{children:[e.jsxs(Ot,{children:[e.jsxs(zt,{className:"flex items-center gap-2 text-destructive",children:[e.jsx(Dr,{className:"h-5 w-5"}),"Subscription Maintenance"]}),e.jsx(Br,{children:"Clear all push subscriptions if VAPID keys were changed or subscriptions are invalid"})]}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"If you've recently updated the VAPID keys, existing subscriptions will no longer work. Use this to clear all subscriptions so users can re-subscribe with the new keys."}),e.jsxs(H,{variant:"destructive",onClick:()=>$.mutate(),disabled:$.isPending,children:[e.jsx(Dr,{className:"h-4 w-4 mr-2"}),$.isPending?"Clearing...":"Clear All Subscriptions"]}),e.jsxs("div",{className:"rounded-md border bg-muted/30 p-3 text-sm",children:[e.jsx("div",{className:"font-medium",children:"VAPID key rotation helper"}),e.jsx("div",{className:"mt-1 text-muted-foreground",children:"If you suspect the backend public/private keys don’t match, generate a fresh pair, update backend secrets, then clear subscriptions and have users re-enable push."}),e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:e.jsx(H,{variant:"outline",onClick:O,disabled:d,children:d?"Generating…":"Generate VAPID keys"})}),_&&e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsxs("div",{className:"text-muted-foreground",children:["Copy these into backend secrets ",e.jsx("span",{className:"font-mono",children:"VAPID_PUBLIC_KEY"})," and ",e.jsx("span",{className:"font-mono",children:"VAPID_PRIVATE_KEY"}),"."]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Public key"}),e.jsx("div",{className:"break-all rounded-md border bg-background p-2 font-mono text-xs",children:_.publicKey})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Private key (keep secret)"}),e.jsx("div",{className:"break-all rounded-md border bg-background p-2 font-mono text-xs",children:_.privateKey})]})]})]})]})]})]})})}function QBs(){const{toast:s}=li(),[t,r]=S.useState([]),[n,a]=S.useState({totalPresentations:0,totalViews:0,totalLeads:0,totalCtaClicks:0,agentsUsing:0}),[i,l]=S.useState(!0),{sortKey:o,sortDirection:c,handleSort:d,sortData:h}=yz("presentation_count","desc"),m=h(t,{name:y=>{var _;return((_=y.name)==null?void 0:_.toLowerCase())||""},presentations:y=>y.presentation_count,views:y=>y.total_views,leads:y=>y.total_leads,cta_clicks:y=>y.total_cta_clicks,conversion:y=>y.total_views>0?y.total_leads/y.total_views*100:0});S.useEffect(()=>{p()},[]);const p=async()=>{try{l(!0);const{data:y,error:_}=await V.rpc("get_admin_presentation_stats");if(_)throw _;if(!y||y.length===0){l(!1);return}const b=y.map(A=>A.owner_user_id),{data:j,error:k}=await V.from("profiles").select("id, name, email, avatar_url").in("id",b);if(k)throw k;const T=new Map((j==null?void 0:j.map(A=>[A.id,A]))||[]),E=y.map(A=>{const D=T.get(A.owner_user_id);return{owner_user_id:A.owner_user_id,name:(D==null?void 0:D.name)||"Unknown",email:(D==null?void 0:D.email)||"",avatar_url:(D==null?void 0:D.avatar_url)||null,presentation_count:Number(A.presentation_count),total_views:Number(A.total_views),total_leads:Number(A.total_leads),total_cta_clicks:Number(A.total_cta_clicks)}});r(E),r(E),a({totalPresentations:E.reduce((A,D)=>A+D.presentation_count,0),totalViews:E.reduce((A,D)=>A+D.total_views,0),totalLeads:E.reduce((A,D)=>A+D.total_leads,0),totalCtaClicks:E.reduce((A,D)=>A+D.total_cta_clicks,0),agentsUsing:E.length})}catch(y){console.error("Error loading presentation stats:",y),s({title:"Error",description:"Failed to load presentation analytics",variant:"destructive"})}finally{l(!1)}},x=[{label:"Agents Using",value:n.agentsUsing,icon:Ar,color:"text-blue-600"},{label:"Total Presentations",value:n.totalPresentations,icon:_1,color:"text-violet-600"},{label:"Total Views",value:n.totalViews,icon:Bn,color:"text-emerald-600"},{label:"Total Leads",value:n.totalLeads,icon:Vl,color:"text-amber-600"},{label:"CTA Clicks",value:n.totalCtaClicks,icon:Kd,color:"text-rose-600"}];return e.jsx(Ss,{title:"Presentation Analytics",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Presentation Analytics"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Track Smart Presentations usage and engagement across all agents"})]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-4",children:x.map(y=>e.jsxs(ke,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(zt,{className:"text-sm font-medium",children:y.label}),e.jsx(y.icon,{className:`h-4 w-4 ${y.color}`})]}),e.jsx(Oe,{children:i?e.jsx(Ks,{className:"h-8 w-16"}):e.jsx("div",{className:"text-2xl font-bold",children:y.value.toLocaleString()})})]},y.label))}),e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(al,{className:"h-5 w-5"}),"Agent Breakdown"]})}),e.jsx(Oe,{children:i?e.jsx("div",{className:"space-y-3",children:[...Array(5)].map((y,_)=>e.jsx(Ks,{className:"h-12 w-full"},_))}):t.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-8",children:"No presentations created yet."}):e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Vs,{children:[e.jsx(pc,{sortKey:"name",currentSortKey:o,currentDirection:c,onSort:d,children:"Agent"}),e.jsx(pc,{sortKey:"presentations",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"Presentations"}),e.jsx(pc,{sortKey:"views",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"Views"}),e.jsx(pc,{sortKey:"leads",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"Leads"}),e.jsx(pc,{sortKey:"cta_clicks",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"CTA Clicks"}),e.jsx(pc,{sortKey:"conversion",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"Conversion"})]})}),e.jsx(da,{children:m.map(y=>{var b,j;const _=y.total_views>0?(y.total_leads/y.total_views*100).toFixed(1):"0.0";return e.jsxs(Vs,{children:[e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-8 w-8 rounded-full bg-muted flex items-center justify-center overflow-hidden",children:y.avatar_url?e.jsx("img",{src:y.avatar_url,alt:"",className:"h-full w-full object-cover"}):e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:((j=(b=y.name)==null?void 0:b.charAt(0))==null?void 0:j.toUpperCase())||"?"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-sm",children:y.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:y.email})]})]})}),e.jsx(gt,{className:"text-center font-medium",children:y.presentation_count}),e.jsx(gt,{className:"text-center",children:y.total_views.toLocaleString()}),e.jsx(gt,{className:"text-center",children:y.total_leads>0?e.jsx(Xe,{variant:"secondary",children:y.total_leads}):e.jsx("span",{className:"text-muted-foreground",children:"0"})}),e.jsx(gt,{className:"text-center",children:y.total_cta_clicks}),e.jsx(gt,{className:"text-center",children:e.jsxs("span",{className:Number(_)>0?"text-emerald-600 font-medium":"text-muted-foreground",children:[_,"%"]})})]},y.owner_user_id)})})]})})]})]})})}function JBs(){const{toast:s}=li(),[t,r]=S.useState([]),[n,a]=S.useState({totalOpenHouses:0,totalVisitors:0,totalLeads:0,activeOpenHouses:0,agentsUsing:0}),[i,l]=S.useState(!0);S.useEffect(()=>{o()},[]);const o=async()=>{try{l(!0);const{data:d,error:h}=await V.rpc("get_admin_guest_book_stats");if(h)throw h;if(!d||d.length===0){l(!1);return}const m=d.map(b=>b.agent_id),{data:p,error:x}=await V.from("profiles").select("id, name, email, avatar_url").in("id",m);if(x)throw x;const y=new Map((p==null?void 0:p.map(b=>[b.id,b]))||[]),_=d.map(b=>{const j=y.get(b.agent_id);return{agent_id:b.agent_id,name:(j==null?void 0:j.name)||"Unknown",email:(j==null?void 0:j.email)||"",avatar_url:(j==null?void 0:j.avatar_url)||null,open_house_count:Number(b.open_house_count),total_visitors:Number(b.total_visitors),total_leads:Number(b.total_leads),active_count:Number(b.active_count)}});_.sort((b,j)=>j.total_visitors-b.total_visitors),r(_),a({totalOpenHouses:_.reduce((b,j)=>b+j.open_house_count,0),totalVisitors:_.reduce((b,j)=>b+j.total_visitors,0),totalLeads:_.reduce((b,j)=>b+j.total_leads,0),activeOpenHouses:_.reduce((b,j)=>b+j.active_count,0),agentsUsing:_.length})}catch(d){console.error("Error loading guest book stats:",d),s({title:"Error",description:"Failed to load guest book analytics",variant:"destructive"})}finally{l(!1)}},c=[{label:"Agents Using",value:n.agentsUsing,icon:Ar,color:"text-blue-600"},{label:"Total Open Houses",value:n.totalOpenHouses,icon:Fn,color:"text-violet-600"},{label:"Active Now",value:n.activeOpenHouses,icon:zi,color:"text-emerald-600"},{label:"Total Visitors",value:n.totalVisitors,icon:Bn,color:"text-amber-600"},{label:"Leads Created",value:n.totalLeads,icon:Vl,color:"text-rose-600"}];return e.jsx(Ss,{title:"Guest Book Analytics",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Guest Book Analytics"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Track open house sign-in usage and lead generation across all agents"})]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-4",children:c.map(d=>e.jsxs(ke,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(zt,{className:"text-sm font-medium",children:d.label}),e.jsx(d.icon,{className:`h-4 w-4 ${d.color}`})]}),e.jsx(Oe,{children:i?e.jsx(Ks,{className:"h-8 w-16"}):e.jsx("div",{className:"text-2xl font-bold",children:d.value.toLocaleString()})})]},d.label))}),e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(al,{className:"h-5 w-5"}),"Agent Breakdown"]})}),e.jsx(Oe,{children:i?e.jsx("div",{className:"space-y-3",children:[...Array(5)].map((d,h)=>e.jsx(Ks,{className:"h-12 w-full"},h))}):t.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-8",children:"No open houses created yet."}):e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Vs,{children:[e.jsx(At,{children:"Agent"}),e.jsx(At,{className:"text-center",children:"Open Houses"}),e.jsx(At,{className:"text-center",children:"Active"}),e.jsx(At,{className:"text-center",children:"Visitors"}),e.jsx(At,{className:"text-center",children:"Leads"}),e.jsx(At,{className:"text-center",children:"Conversion"})]})}),e.jsx(da,{children:t.map(d=>{var m,p;const h=d.total_visitors>0?(d.total_leads/d.total_visitors*100).toFixed(1):"0.0";return e.jsxs(Vs,{children:[e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-8 w-8 rounded-full bg-muted flex items-center justify-center overflow-hidden",children:d.avatar_url?e.jsx("img",{src:d.avatar_url,alt:"",className:"h-full w-full object-cover"}):e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:((p=(m=d.name)==null?void 0:m.charAt(0))==null?void 0:p.toUpperCase())||"?"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-sm",children:d.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:d.email})]})]})}),e.jsx(gt,{className:"text-center font-medium",children:d.open_house_count}),e.jsx(gt,{className:"text-center",children:d.active_count>0?e.jsx(Xe,{variant:"secondary",className:"bg-emerald-100 text-emerald-700",children:d.active_count}):e.jsx("span",{className:"text-muted-foreground",children:"0"})}),e.jsx(gt,{className:"text-center",children:d.total_visitors.toLocaleString()}),e.jsx(gt,{className:"text-center",children:d.total_leads>0?e.jsx(Xe,{variant:"secondary",children:d.total_leads}):e.jsx("span",{className:"text-muted-foreground",children:"0"})}),e.jsx(gt,{className:"text-center",children:e.jsxs("span",{className:Number(h)>0?"text-emerald-600 font-medium":"text-muted-foreground",children:[h,"%"]})})]},d.agent_id)})})]})})]})]})})}function ezs(){const[s]=Ed(),t=Fr(),[r,n]=S.useState("loading"),[a,i]=S.useState("Processing connection...");return S.useEffect(()=>{(async()=>{const o=s.get("code"),c=s.get("error"),d=s.get("error_description"),h=s.get("state");if(c){n("error"),i(d||"Authorization was denied"),he.error("Failed to connect: "+(d||c));return}if(!o){n("error"),i("No authorization code received"),he.error("Failed to connect: No authorization code");return}try{const{data:m,error:p}=await V.functions.invoke("meta-oauth",{body:{action:"exchange_code",code:o,state:h}});if(m&&m.success===!1)throw new Error(m.error||"Failed to connect accounts");if(p){let x=p.message||"Failed to connect accounts";try{const y=p.context;if(y&&typeof y.json=="function"){const _=await y.json();_!=null&&_.error&&(x=_.error)}}catch{}throw new Error(x)}if(m!=null&&m.success)n("success"),i(m.message||"Accounts connected successfully!"),he.success(m.message||"Social accounts connected!");else throw new Error((m==null?void 0:m.error)||"Failed to connect accounts")}catch(m){console.error("Callback error:",m),n("error"),i(m.message||"Failed to complete connection"),he.error(m.message||"Failed to connect accounts")}})()},[s]),e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background p-4",children:e.jsxs(ke,{className:"w-full max-w-md",children:[e.jsxs(Ot,{className:"text-center",children:[e.jsxs("div",{className:"mx-auto mb-4",children:[r==="loading"&&e.jsx(is,{className:"h-12 w-12 animate-spin text-primary"}),r==="success"&&e.jsx(zi,{className:"h-12 w-12 text-green-500"}),r==="error"&&e.jsx(kd,{className:"h-12 w-12 text-destructive"})]}),e.jsxs(zt,{children:[r==="loading"&&"Connecting...",r==="success"&&"Connected!",r==="error"&&"Connection Failed"]}),e.jsx(Br,{children:a})]}),e.jsx(Oe,{className:"flex justify-center",children:e.jsx(H,{onClick:()=>t("/admin/integrations"),children:r==="success"?"View Integrations":"Back to Integrations"})})]})})}function tzs(){const s=ns(),[t,r]=S.useState(""),[n,a]=S.useState(""),[i,l]=S.useState([]),o=S.useRef(null),{data:c,isLoading:d}=yt({queryKey:["prospect-emails"],queryFn:async()=>{const{data:b,error:j}=await V.from("prospect_emails").select("*").order("sent_at",{ascending:!1});if(j)throw j;return b}}),h={total:(c==null?void 0:c.length)||0,sent:(c==null?void 0:c.filter(b=>b.status==="sent").length)||0,converted:(c==null?void 0:c.filter(b=>b.status==="converted").length)||0,conversionRate:c!=null&&c.length?Math.round(c.filter(b=>b.status==="converted").length/c.length*100):0},m=Pt({mutationFn:async b=>{const{data:j,error:k}=await V.functions.invoke("send-prospect-email",{body:{emails:b}});if(k)throw k;return j},onSuccess:b=>{s.invalidateQueries({queryKey:["prospect-emails"]}),he.success(`${b.sent} email${b.sent>1?"s":""} sent successfully!`),r(""),a(""),l([])},onError:b=>{he.error("Failed to send: "+b.message)}}),p=Pt({mutationFn:async()=>{var T,E;const{data:{user:b}}=await V.auth.getUser();if(!(b!=null&&b.email))throw new Error("Could not get your email");const{data:j,error:k}=await V.functions.invoke("send-prospect-email",{body:{emails:[{email:b.email,first_name:(E=(T=b.user_metadata)==null?void 0:T.name)==null?void 0:E.split(" ")[0]}],test_mode:!0}});if(k)throw k;return j},onSuccess:()=>{he.success("Test email sent to your inbox!")},onError:b=>{he.error("Failed to send test: "+b.message)}}),x=()=>{if(!t.trim()){he.error("Please enter an email address");return}if(c==null?void 0:c.find(j=>j.email.toLowerCase()===t.trim().toLowerCase())){he.error("This email has already been prospected");return}m.mutate([{email:t.trim(),first_name:n.trim()||void 0}])},y=b=>{var T;const j=(T=b.target.files)==null?void 0:T[0];if(!j)return;const k=new FileReader;k.onload=E=>{var O,$;const D=((O=E.target)==null?void 0:O.result).split(` `).filter(ee=>ee.trim()),R=[],z=($=D[0])!=null&&$.toLowerCase().includes("email")?1:0;for(let ee=z;eere.trim().replace(/"/g,"")),J=Z[0],K=Z[1];J&&J.includes("@")&&R.push({email:J,first_name:K||void 0})}l(R),he.success(`${R.length} entries loaded from CSV`)},k.readAsText(j),o.current&&(o.current.value="")},_=()=>{if(i.length===0){he.error("No entries to send");return}const b=new Set((c==null?void 0:c.map(k=>k.email.toLowerCase()))||[]),j=i.filter(k=>!b.has(k.email.toLowerCase()));if(j.length===0){he.error("All emails have already been prospected");return}j.lengthp.mutate(),disabled:p.isPending,className:"gap-2 ml-4 shrink-0",children:[p.isPending?e.jsx(is,{className:"h-3 w-3 animate-spin"}):e.jsx(er,{className:"h-3 w-3"}),"Send Test to Me"]})]})]}),e.jsx(Oe,{children:e.jsxs(ta,{defaultValue:"single",children:[e.jsxs(Qn,{className:"mb-4",children:[e.jsxs(ts,{value:"single",children:[e.jsx(yn,{className:"h-4 w-4 mr-2"}),"Single Send"]}),e.jsxs(ts,{value:"bulk",children:[e.jsx(Ea,{className:"h-4 w-4 mr-2"}),"Bulk CSV"]})]}),e.jsx(cs,{value:"single",children:e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx(ue,{htmlFor:"prospect-email",className:"sr-only",children:"Email"}),e.jsx(Se,{id:"prospect-email",type:"email",placeholder:"agent@example.com",value:t,onChange:b=>r(b.target.value),onKeyDown:b=>b.key==="Enter"&&x()})]}),e.jsxs("div",{className:"w-full sm:w-48",children:[e.jsx(ue,{htmlFor:"prospect-name",className:"sr-only",children:"First Name"}),e.jsx(Se,{id:"prospect-name",placeholder:"First name (optional)",value:n,onChange:b=>a(b.target.value),onKeyDown:b=>b.key==="Enter"&&x()})]}),e.jsxs(H,{onClick:x,disabled:m.isPending,className:"gap-2",children:[m.isPending?e.jsx(is,{className:"h-4 w-4 animate-spin"}):e.jsx(yn,{className:"h-4 w-4"}),"Send Invite"]})]})}),e.jsx(cs,{value:"bulk",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("input",{ref:o,type:"file",accept:".csv",onChange:y,className:"hidden"}),e.jsxs(H,{variant:"outline",onClick:()=>{var b;return(b=o.current)==null?void 0:b.click()},className:"gap-2",children:[e.jsx(kn,{className:"h-4 w-4"}),"Upload CSV"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Format: email, first_name (one per line)"})]}),i.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Xe,{variant:"secondary",className:"gap-1",children:[e.jsx(Ar,{className:"h-3 w-3"}),i.length," entries ready"]}),e.jsxs(H,{variant:"ghost",size:"sm",onClick:()=>l([]),children:[e.jsx(Rr,{className:"h-4 w-4"}),"Clear"]})]}),e.jsxs("div",{className:"max-h-40 overflow-y-auto border rounded-lg p-3 bg-muted/30 text-sm font-mono space-y-1",children:[i.slice(0,20).map((b,j)=>e.jsxs("div",{className:"text-muted-foreground",children:[b.email,b.first_name?` — ${b.first_name}`:""]},j)),i.length>20&&e.jsxs("div",{className:"text-muted-foreground/60",children:["...and ",i.length-20," more"]})]}),e.jsxs(H,{onClick:_,disabled:m.isPending,className:"gap-2",children:[m.isPending?e.jsx(is,{className:"h-4 w-4 animate-spin"}):e.jsx(yn,{className:"h-4 w-4"}),"Send ",i.length," Invites"]})]})]})})]})})]}),e.jsxs(ke,{children:[e.jsxs(Ot,{children:[e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(er,{className:"h-5 w-5"}),"Prospect Log"]}),e.jsx(Br,{children:"Track all sent invitations and their conversion status"})]}),e.jsx(Oe,{children:d?e.jsx("div",{className:"space-y-3",children:[...Array(5)].map((b,j)=>e.jsx(Ks,{className:"h-12 w-full"},j))}):c&&c.length>0?e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b",children:[e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-muted-foreground",children:"Email"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-muted-foreground",children:"Name"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-muted-foreground",children:"Sent"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-muted-foreground",children:"Status"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-muted-foreground",children:"Converted"})]})}),e.jsx("tbody",{children:c.map(b=>e.jsxs("tr",{className:"border-b last:border-0 hover:bg-muted/30",children:[e.jsx("td",{className:"py-3 px-4 text-sm font-medium text-foreground",children:b.email}),e.jsx("td",{className:"py-3 px-4 text-sm text-muted-foreground",children:b.first_name||"—"}),e.jsx("td",{className:"py-3 px-4 text-sm text-muted-foreground",children:As(new Date(b.sent_at),"MMM d, yyyy")}),e.jsx("td",{className:"py-3 px-4",children:b.status==="converted"?e.jsxs(Xe,{className:"bg-green-500/10 text-green-700 hover:bg-green-500/20 border-0",children:[e.jsx(ea,{className:"h-3 w-3 mr-1"}),"Converted"]}):e.jsxs(Xe,{variant:"secondary",className:"gap-1",children:[e.jsx(Pn,{className:"h-3 w-3"}),"Sent"]})}),e.jsx("td",{className:"py-3 px-4 text-sm text-muted-foreground",children:b.converted_at?As(new Date(b.converted_at),"MMM d, yyyy"):"—"})]},b.id))})]})}):e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Wu,{className:"h-12 w-12 text-muted-foreground/30 mx-auto mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:"No prospects yet. Send your first invite above!"})]})})]})]})})}function Hz(s){const t=ns(),{toast:r}=li(),n=yt({queryKey:["recruit-stages",s],queryFn:async()=>{if(!s)return[];const{data:c,error:d}=await V.from("recruit_pipeline_stages").select("*").eq("brokerage_id",s).order("sort_order");if(d)throw d;return c},enabled:!!s}),a=yt({queryKey:["recruit-prospects",s],queryFn:async()=>{if(!s)return[];const c=1e3;let d=[],h=0,m=!0;for(;m;){const{data:p,error:x}=await V.from("recruit_prospects").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1}).range(h,h+c-1);if(x)throw x;d=d.concat(p),m=p.length===c,h+=c}return d},enabled:!!s}),i=Pt({mutationFn:async c=>{const{data:{user:d}}=await V.auth.getUser();if(!d)throw new Error("Not authenticated");const h={first_name:c.first_name||"",last_name:c.last_name||null,email:c.email||null,phone:c.phone||null,current_brokerage:c.current_brokerage||null,license_number:c.license_number||null,experience_years:c.experience_years??null,annual_production:c.annual_production||null,source:c.source||"manual",notes:c.notes||null,stage_id:c.stage_id||null,brokerage_id:s,created_by:d.id,address:c.address||null,city:c.city||null,state:c.state||null,zip_code:c.zip_code||null,last_year_volume:c.last_year_volume||null,last_year_transactions:c.last_year_transactions??null,avg_sale_price:c.avg_sale_price||null,specialties:c.specialties||null,linkedin_url:c.linkedin_url||null,website_url:c.website_url||null,instagram_handle:c.instagram_handle||null,facebook_url:c.facebook_url||null,birthday:c.birthday||null,spouse_name:c.spouse_name||null,interests:c.interests||null,referred_by:c.referred_by||null},{data:m,error:p}=await V.from("recruit_prospects").insert(h).select().single();if(p)throw p;return m},onSuccess:()=>{t.invalidateQueries({queryKey:["recruit-prospects",s]}),r({title:"Prospect added"})},onError:c=>r({title:"Error",description:c.message,variant:"destructive"})}),l=Pt({mutationFn:async({id:c,...d})=>{const{data:h,error:m}=await V.from("recruit_prospects").update({...d,updated_at:new Date().toISOString()}).eq("id",c).select().single();if(m)throw m;return h},onSuccess:()=>{t.invalidateQueries({queryKey:["recruit-prospects",s]})},onError:c=>r({title:"Error",description:c.message,variant:"destructive"})}),o=Pt({mutationFn:async c=>{const{error:d}=await V.from("recruit_prospects").delete().eq("id",c);if(d)throw d},onSuccess:()=>{t.invalidateQueries({queryKey:["recruit-prospects",s]}),r({title:"Prospect removed"})}});return{stages:n.data||[],prospects:a.data||[],isLoading:n.isLoading||a.isLoading,addProspect:i,updateProspect:l,deleteProspect:o}}function szs(s){const t=ns(),{toast:r}=li(),n=yt({queryKey:["recruit-activities",s],queryFn:async()=>{if(!s)return[];const{data:i,error:l}=await V.from("recruit_activities").select("*").eq("prospect_id",s).order("created_at",{ascending:!1});if(l)throw l;return i},enabled:!!s}),a=Pt({mutationFn:async i=>{const{data:{user:l}}=await V.auth.getUser();if(!l)throw new Error("Not authenticated");const{data:o,error:c}=await V.from("recruit_activities").insert({...i,created_by:l.id}).select().single();if(c)throw c;return o},onSuccess:()=>{t.invalidateQueries({queryKey:["recruit-activities",s]}),r({title:"Activity logged"})},onError:i=>r({title:"Error",description:i.message,variant:"destructive"})});return{activities:n.data||[],isLoading:n.isLoading,addActivity:a}}const kWe=(s,t)=>{var r;return{first_name:"",last_name:"",email:"",phone:"",current_brokerage:"",license_number:"",experience_years:"",annual_production:"",source:"manual",notes:"",stage_id:s||((r=t==null?void 0:t[0])==null?void 0:r.id)||"",address:"",city:"",state:"",zip_code:"",last_year_volume:"",last_year_transactions:"",avg_sale_price:"",specialties:"",linkedin_url:"",website_url:"",instagram_handle:"",facebook_url:"",birthday:"",spouse_name:"",interests:"",referred_by:""}};function tvt({open:s,onOpenChange:t,stages:r,defaultStageId:n,onSubmit:a,isSubmitting:i}){const[l,o]=S.useState(kWe(n,r)),c=h=>m=>o(p=>({...p,[h]:m.target.value})),d=h=>{h.preventDefault(),a({...l,experience_years:l.experience_years?parseInt(l.experience_years):null,last_year_transactions:l.last_year_transactions?parseInt(l.last_year_transactions):null,stage_id:l.stage_id||null}),o(kWe(n,r)),t(!1)};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Cs,{children:e.jsx(Ns,{children:"Add Recruit Prospect"})}),e.jsxs("form",{onSubmit:d,className:"space-y-4",children:[e.jsxs(ta,{defaultValue:"basic",className:"w-full",children:[e.jsxs(Qn,{className:"grid w-full grid-cols-4",children:[e.jsx(ts,{value:"basic",children:"Basic Info"}),e.jsx(ts,{value:"production",children:"Production"}),e.jsx(ts,{value:"social",children:"Social & Web"}),e.jsx(ts,{value:"personal",children:"Personal"})]}),e.jsxs(cs,{value:"basic",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ue,{children:"First Name *"}),e.jsx(Se,{required:!0,value:l.first_name,onChange:c("first_name")})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Last Name"}),e.jsx(Se,{value:l.last_name,onChange:c("last_name")})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ue,{children:"Email"}),e.jsx(Se,{type:"email",value:l.email,onChange:c("email")})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Phone"}),e.jsx(Se,{value:l.phone,onChange:c("phone")})]})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Current Brokerage"}),e.jsx(Se,{value:l.current_brokerage,onChange:c("current_brokerage")})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ue,{children:"License #"}),e.jsx(Se,{value:l.license_number,onChange:c("license_number")})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Experience (years)"}),e.jsx(Se,{type:"number",min:"0",value:l.experience_years,onChange:c("experience_years")})]})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Address"}),e.jsx(Se,{placeholder:"Street address",value:l.address,onChange:c("address")})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx(ue,{children:"City"}),e.jsx(Se,{value:l.city,onChange:c("city")})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"State"}),e.jsx(Se,{value:l.state,onChange:c("state")})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Zip"}),e.jsx(Se,{value:l.zip_code,onChange:c("zip_code")})]})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Pipeline Stage"}),e.jsxs(Bs,{value:l.stage_id,onValueChange:h=>o(m=>({...m,stage_id:h})),children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsx(Fs,{children:r.map(h=>e.jsx(pt,{value:h.id,children:h.name},h.id))})]})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Referred By"}),e.jsx(Se,{placeholder:"Who referred this prospect?",value:l.referred_by,onChange:c("referred_by")})]})]}),e.jsxs(cs,{value:"production",className:"space-y-4 mt-4",children:[e.jsxs("div",{children:[e.jsx(ue,{children:"Annual Production Volume"}),e.jsx(Se,{placeholder:"e.g. $5M, 20 transactions",value:l.annual_production,onChange:c("annual_production")})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ue,{children:"Last Year Volume"}),e.jsx(Se,{placeholder:"e.g. $8.2M",value:l.last_year_volume,onChange:c("last_year_volume")})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Last Year Transactions"}),e.jsx(Se,{type:"number",min:"0",placeholder:"e.g. 24",value:l.last_year_transactions,onChange:c("last_year_transactions")})]})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Avg Sale Price"}),e.jsx(Se,{placeholder:"e.g. $350K",value:l.avg_sale_price,onChange:c("avg_sale_price")})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Specialties / Niche"}),e.jsx(Se,{placeholder:"e.g. Luxury, First-time buyers, Investment",value:l.specialties,onChange:c("specialties")})]})]}),e.jsxs(cs,{value:"social",className:"space-y-4 mt-4",children:[e.jsxs("div",{children:[e.jsx(ue,{children:"LinkedIn URL"}),e.jsx(Se,{type:"url",placeholder:"https://linkedin.com/in/...",value:l.linkedin_url,onChange:c("linkedin_url")})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Website URL"}),e.jsx(Se,{type:"url",placeholder:"https://...",value:l.website_url,onChange:c("website_url")})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Instagram Handle"}),e.jsx(Se,{placeholder:"@handle",value:l.instagram_handle,onChange:c("instagram_handle")})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Facebook URL"}),e.jsx(Se,{type:"url",placeholder:"https://facebook.com/...",value:l.facebook_url,onChange:c("facebook_url")})]})]}),e.jsxs(cs,{value:"personal",className:"space-y-4 mt-4",children:[e.jsxs("div",{children:[e.jsx(ue,{children:"Birthday"}),e.jsx(Se,{type:"date",value:l.birthday,onChange:c("birthday")})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Spouse / Partner Name"}),e.jsx(Se,{value:l.spouse_name,onChange:c("spouse_name")})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Interests / Hobbies"}),e.jsx(Se,{placeholder:"Golf, travel, community events...",value:l.interests,onChange:c("interests")})]})]})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Notes"}),e.jsx(vr,{value:l.notes,onChange:c("notes"),rows:3})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(H,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(H,{type:"submit",disabled:i,children:"Add Prospect"})]})]})]})})}function cye(){const{user:s}=Ms();return yt({queryKey:["recruit-email-senders",s==null?void 0:s.id],enabled:!!s,staleTime:6e4,queryFn:async()=>{const[t,r]=await Promise.all([V.from("user_verified_senders").select("email, display_name, status").eq("user_id",s.id).eq("status","verified").limit(1).maybeSingle(),V.from("gmail_integrations").select("gmail_email, is_active").eq("user_id",s.id).eq("is_active",!0).maybeSingle()]);return{massEmail:t.data?{email:t.data.email,displayName:t.data.display_name}:null,gmail:r.data?{email:r.data.gmail_email}:null}}})}function x6e({value:s,onChange:t}){const{data:r,isLoading:n}=cye();return e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs",children:"Send from"}),e.jsxs(Bs,{value:s,onValueChange:a=>t(a),disabled:n,children:[e.jsx(Os,{className:"mt-1",children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"default",children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Xa,{className:"h-3.5 w-3.5"})," Brokerage default sender"]})}),e.jsx(pt,{value:"mass_email",disabled:!(r!=null&&r.massEmail),children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Uk,{className:"h-3.5 w-3.5"}),"Mass Email",r!=null&&r.massEmail?` (${r.massEmail.email})`:" — not configured"]})}),e.jsx(pt,{value:"gmail",disabled:!(r!=null&&r.gmail),children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(er,{className:"h-3.5 w-3.5"}),"Gmail",r!=null&&r.gmail?` (${r.gmail.email})`:" — not connected"]})})]})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground mt-1",children:"Mass Email and Gmail use your own verified sender. Configure them under Integrations."})]})}function svt({open:s,onOpenChange:t,recruitVideoId:r,brokerageId:n,prospectName:a,prospectEmail:i,videoTitle:l,defaultMessage:o}){const c=(a||"").split(" ")[0]||"there",[d,h]=S.useState(""),[m,p]=S.useState(""),[x,y]=S.useState("default"),[_,b]=S.useState(!1),j=ns(),{data:k}=cye();S.useEffect(()=>{s&&(h(`${c}, I made you a quick video 🎥`),p(o||""),y(k!=null&&k.massEmail?"mass_email":k!=null&&k.gmail?"gmail":"default"))},[s,c,o,k==null?void 0:k.massEmail,k==null?void 0:k.gmail]);const T=async()=>{var E,A;if(!i){he.error("This prospect has no email address on file.");return}b(!0);try{const{data:D,error:R}=await V.functions.invoke("send-recruit-video-email",{body:{recruit_video_ids:[r],brokerage_id:n,subject_override:d.trim()||void 0,message_override:m.trim()||void 0,send_via:x}});if(R)throw R;if(((D==null?void 0:D.sent)??0)>0)he.success(`Email sent to ${i}`),j.invalidateQueries({queryKey:["recruit-videos"]}),j.invalidateQueries({queryKey:["recruit-videos-prospect"]}),t(!1);else{const O=((A=(E=D==null?void 0:D.results)==null?void 0:E[0])==null?void 0:A.error)||"Failed to send";he.error(O)}}catch(D){he.error((D==null?void 0:D.message)||"Failed to send email")}finally{b(!1)}};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-lg",children:[e.jsx(Cs,{children:e.jsxs(Ns,{className:"flex items-center gap-2",children:[e.jsx(er,{className:"h-5 w-5"})," Email video to ",a]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs",children:"To"}),e.jsx(Se,{value:i||"— no email on file —",disabled:!0,className:"mt-1"})]}),e.jsx(x6e,{value:x,onChange:y}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs",children:"Subject"}),e.jsx(Se,{value:d,onChange:E=>h(E.target.value),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs",children:"Personal message (optional)"}),e.jsx(vr,{value:m,onChange:E=>p(E.target.value),rows:5,placeholder:`Hi ${c}, wanted to share a quick video...`,className:"mt-1"})]}),l&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Video: ",e.jsx("span",{className:"font-medium",children:l})]})]}),e.jsxs(wn,{children:[e.jsx(H,{variant:"ghost",onClick:()=>t(!1),disabled:_,children:"Cancel"}),e.jsxs(H,{onClick:T,disabled:_||!i,children:[_?e.jsx(is,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(yn,{className:"h-4 w-4 mr-2"}),"Send Email"]})]})]})})}function i_(s){return s?s.share_token?`https://video.relevelup.com/thumb/${s.share_token}`:s.thumbnail_url||s.preview_url||null:null}const Y4e=[{value:"why_switch",label:"Why Switch Brokerages"},{value:"commission",label:"Commission & Splits"},{value:"culture",label:"Culture & Team"},{value:"follow_up",label:"Follow Up"},{value:"general",label:"General Pitch"}];function rzs(s){return yt({queryKey:["recruit-videos",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await V.from("recruit_videos").select(` *, prospect:recruit_prospects(id, first_name, last_name, email, phone, current_brokerage), video:agent_videos(id, title, thumbnail_url, playback_url, preview_url, duration_seconds, status, share_token) `).eq("brokerage_id",s).order("created_at",{ascending:!1});if(r)throw r;return t},enabled:!!s})}function nzs(s){return yt({queryKey:["recruit-videos-prospect",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await V.from("recruit_videos").select(` *, video:agent_videos(id, title, thumbnail_url, playback_url, preview_url, duration_seconds, status, share_token) `).eq("prospect_id",s).order("created_at",{ascending:!1});if(r)throw r;return t},enabled:!!s})}function rvt(){const s=ns(),{toast:t}=li();return Pt({mutationFn:async r=>{const{data:{user:n}}=await V.auth.getUser();if(!n)throw new Error("Not authenticated");const{data:a,error:i}=await V.from("recruit_videos").insert({prospect_id:r.prospect_id,video_id:r.video_id,brokerage_id:r.brokerage_id,message:r.message||null,created_by:n.id}).select("*, prospect:recruit_prospects(id, first_name, last_name, email, phone, current_brokerage), video:agent_videos(id, title, thumbnail_url, playback_url, preview_url, duration_seconds, status, share_token)").single();if(i)throw i;return a},onSuccess:r=>{s.invalidateQueries({queryKey:["recruit-videos"]}),s.invalidateQueries({queryKey:["recruit-videos-prospect",r.prospect_id]}),t({title:"Video linked to prospect"})},onError:r=>t({title:"Error",description:r.message,variant:"destructive"})})}function nvt(){const s=ns();return Pt({mutationFn:async({id:t,sent_via:r})=>{const{error:n}=await V.from("recruit_videos").update({sent_at:new Date().toISOString(),sent_via:r,updated_at:new Date().toISOString()}).eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["recruit-videos"]})}})}function avt(s){return yt({queryKey:["recruit-video-scripts",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await V.from("recruit_video_scripts").select("*").or(`brokerage_id.eq.${s},is_global.eq.true`).order("created_at",{ascending:!1});if(r)throw r;return t},enabled:!!s})}function azs(){const s=ns(),{toast:t}=li();return Pt({mutationFn:async r=>{const{data:{user:n}}=await V.auth.getUser();if(!n)throw new Error("Not authenticated");const{data:a,error:i}=await V.from("recruit_video_scripts").insert({...r,created_by:n.id}).select().single();if(i)throw i;return a},onSuccess:()=>{s.invalidateQueries({queryKey:["recruit-video-scripts"]}),t({title:"Script saved"})},onError:r=>t({title:"Error",description:r.message,variant:"destructive"})})}function izs(){const s=ns();return Pt({mutationFn:async t=>{const{error:r}=await V.from("recruit_video_scripts").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["recruit-video-scripts"]})}})}function ozs({prospectId:s,prospectName:t,prospectEmail:r,brokerageId:n}){var re;const{data:a=[],isLoading:i}=nzs(s),{data:l=[]}=avt(n),o=rvt(),c=Cj();nvt();const[d,h]=S.useState("idle"),[m,p]=S.useState(0),[x,y]=S.useState(0),[_,b]=S.useState(""),[j,k]=S.useState(""),[T,E]=S.useState(!1),[A,D]=S.useState(null),[R,z]=S.useState(null),[O,$]=S.useState(null),ee=((re=l.find(ie=>ie.id===_))==null?void 0:re.script_text)||"",Z=()=>{h("idle"),p(0),y(0),b(""),k("")},J=S.useCallback(async(ie,ce)=>{h("uploading");try{const ne=`Recruiting: ${t}`,{videoId:le,libraryId:be}=await tM(ne),{uploadUrl:fe,apiKey:je}=await sM(le),ve=new XMLHttpRequest;ve.upload.onprogress=De=>{De.lengthComputable&&p(De.loaded/De.total*100)},await new Promise((De,pe)=>{ve.onload=()=>ve.status>=200&&ve.status<300?De():pe(new Error("Upload failed")),ve.onerror=()=>pe(new Error("Upload failed")),ve.open("PUT",fe),ve.setRequestHeader("AccessKey",je),ve.send(ie)}),h("processing");let We=0;const Ve=Date.now(),Le=9e4,Me=`https://iframe.mediadelivery.net/embed/${be}/${le}`;for(;We<4&&(await new Promise(pe=>setTimeout(pe,3e3)),!(Date.now()-Ve>Le));){const De=await F_(le);if(We=De.status,y(De.encodeProgress||0),We===5||We===6)throw new Error("Video processing failed")}const ze=await F_(le),Pe=(ze.storageSize||ie.size)/(1024*1024),Ie=await c.mutateAsync({bunny_video_id:le,playback_url:ze.directPlayUrl||Me,thumbnail_url:ze.thumbnailUrl,preview_url:ze.previewUrl||null,duration_seconds:ze.length||ce,file_size_mb:Pe,title:ne,status:We>=4?"ready":"processing",touch_type:"recruiting"});await o.mutateAsync({prospect_id:s,video_id:Ie.id,brokerage_id:n,message:j||void 0}),h("done"),he.success("Video recorded and linked to prospect!"),setTimeout(()=>{E(!1),Z()},1500)}catch(ne){he.error(ne.message||"Failed to upload video"),h("record")}},[s,t,n,j,c,o]),K=ie=>{ie&&(navigator.clipboard.writeText(`${window.location.origin}/recruit-video/${ie}`),he.success("Share link copied"))};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h3",{className:"font-semibold text-sm flex items-center gap-1.5",children:[e.jsx(xn,{className:"h-4 w-4"})," Video Outreach"]}),e.jsxs(bs,{open:T,onOpenChange:ie=>{!ie&&(d==="uploading"||d==="processing")||(E(ie),ie||Z())},children:[e.jsx(Qi,{asChild:!0,children:e.jsxs(H,{size:"sm",variant:"outline",onClick:()=>h("script"),children:[e.jsx(Ys,{className:"h-3.5 w-3.5 mr-1"})," Record Video"]})}),e.jsxs(vs,{className:"max-w-2xl",children:[e.jsx(Cs,{children:e.jsxs(Ns,{children:["Record Video for ",t]})}),d==="script"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs",children:"Choose a Script (optional)"}),e.jsxs(Bs,{value:_,onValueChange:b,children:[e.jsx(Os,{className:"mt-1",children:e.jsx(Us,{placeholder:"No script — speak freely"})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"none",children:"No script"}),l.map(ie=>{var ce;return e.jsx(pt,{value:ie.id,children:e.jsxs("span",{className:"flex items-center gap-2",children:[ie.title,e.jsx(Xe,{variant:"outline",className:"text-[9px] ml-1",children:(ce=Y4e.find(ne=>ne.value===ie.category))==null?void 0:ce.label})]})},ie.id)})]})]}),ee&&e.jsx("div",{className:"mt-2 p-3 bg-muted/50 rounded-md text-sm max-h-32 overflow-y-auto whitespace-pre-wrap",children:ee})]}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs",children:"Personal Message (shown on landing page)"}),e.jsx(vr,{value:j,onChange:ie=>k(ie.target.value),placeholder:`Hi ${t.split(" ")[0]}, I'd love to chat about what we're building here...`,rows:3,className:"mt-1"})]}),e.jsxs(H,{onClick:()=>h("record"),className:"w-full",children:[e.jsx(xn,{className:"h-4 w-4 mr-2"})," Start Recording"]})]}),d==="record"&&e.jsx(aD,{maxDurationSeconds:600,onRecordingComplete:J,teleprompterContent:ee||void 0}),d==="uploading"&&e.jsxs("div",{className:"py-8 space-y-4 text-center",children:[e.jsx("p",{className:"font-medium",children:"Uploading video…"}),e.jsx(Mi,{value:m,className:"mx-auto max-w-sm"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[Math.round(m),"%"]})]}),d==="processing"&&e.jsxs("div",{className:"py-8 space-y-4 text-center",children:[e.jsx("p",{className:"font-medium",children:"Processing video…"}),e.jsx(Mi,{value:x,className:"mx-auto max-w-sm"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[Math.round(x),"%"]})]}),d==="done"&&e.jsxs("div",{className:"py-8 text-center",children:[e.jsx("div",{className:"h-12 w-12 rounded-full bg-emerald-100 flex items-center justify-center mx-auto mb-3",children:e.jsx(El,{className:"h-6 w-6 text-emerald-600"})}),e.jsx("p",{className:"font-medium text-emerald-600",children:"Video ready!"})]})]})]})]}),i?e.jsx("div",{className:"text-center py-4",children:e.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-primary border-t-transparent mx-auto"})}):a.length===0?e.jsx("p",{className:"text-xs text-muted-foreground text-center py-3",children:"No videos sent yet"}):e.jsx("div",{className:"space-y-2",children:a.map(ie=>{var ce;return e.jsxs("div",{className:"flex items-center gap-3 p-2 rounded-md border text-sm",children:[e.jsx("div",{className:"h-10 w-16 rounded bg-muted overflow-hidden flex-shrink-0",children:i_(ie.video)?e.jsx("img",{src:i_(ie.video),alt:"",className:"h-full w-full object-cover",referrerPolicy:"no-referrer"}):e.jsx("div",{className:"h-full w-full flex items-center justify-center",children:e.jsx(xn,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-xs truncate",children:((ce=ie.video)==null?void 0:ce.title)||"Untitled"}),e.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[ie.view_count>0?e.jsxs(Xe,{variant:"secondary",className:"text-[9px] h-4",children:[e.jsx(Bn,{className:"h-2.5 w-2.5 mr-0.5"}),ie.view_count]}):ie.sent_at?e.jsxs(Xe,{variant:"outline",className:"text-[9px] h-4",children:[e.jsx(yn,{className:"h-2.5 w-2.5 mr-0.5"}),"Sent"]}):e.jsxs(Xe,{variant:"outline",className:"text-[9px] h-4",children:[e.jsx(Pn,{className:"h-2.5 w-2.5 mr-0.5"}),"Draft"]}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:As(new Date(ie.created_at),"MMM d")})]})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(H,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>K(ie.share_token),title:"Copy link",children:e.jsx(ui,{className:"h-3 w-3"})}),e.jsxs(H,{variant:ie.sent_at?"ghost":"default",size:"sm",className:"h-7 gap-1",disabled:!r,onClick:()=>{var ne;D(ie.id),z(((ne=ie.video)==null?void 0:ne.title)||null),$(ie.message||null)},title:r?"Email video to prospect":"No email on file",children:[e.jsx(er,{className:"h-3 w-3"}),e.jsx("span",{className:"text-[10px]",children:ie.sent_at?"Resend":"Email"})]})]})]},ie.id)})}),A&&e.jsx(svt,{open:!!A,onOpenChange:ie=>{ie||D(null)},recruitVideoId:A,brokerageId:n,prospectName:t,prospectEmail:r,videoTitle:R,defaultMessage:O})]})}function lzs({brokerageId:s,onSelect:t}){const{data:r=[],isLoading:n}=yt({queryKey:["recruit-email-templates",s??"global-only"],queryFn:async()=>{let i=V.from("recruit_email_templates").select("id,brokerage_id,category,title,subject,body,sort_order").eq("is_active",!0).order("sort_order");s?i=i.or(`brokerage_id.is.null,brokerage_id.eq.${s}`):i=i.is("brokerage_id",null);const{data:l,error:o}=await i;if(o)throw o;return l}}),a=r.reduce((i,l)=>{var o;return(i[o=l.category]||(i[o]=[])).push(l),i},{});return e.jsxs(Xu,{children:[e.jsx(Qu,{asChild:!0,children:e.jsxs(H,{variant:"outline",size:"sm",className:"gap-2",type:"button",children:[e.jsx(kn,{className:"h-4 w-4"}),"Use Template",e.jsx(Io,{className:"h-3.5 w-3.5 opacity-60"})]})}),e.jsx(wu,{align:"end",className:"w-80 max-h-[420px] overflow-y-auto",children:n?e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(is,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):r.length===0?e.jsx("div",{className:"px-3 py-4 text-xs text-muted-foreground text-center",children:"No templates available."}):Object.entries(a).map(([i,l],o)=>e.jsxs("div",{children:[o>0&&e.jsx(A_,{}),e.jsx(l9,{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:i}),l.map(c=>e.jsxs(di,{onClick:()=>t(c),className:"flex flex-col items-start gap-0.5 py-2",children:[e.jsxs("div",{className:"flex w-full items-center justify-between gap-2",children:[e.jsx("span",{className:"text-sm font-medium truncate",children:c.title}),c.brokerage_id===null&&e.jsx(Xe,{variant:"secondary",className:"text-[9px] shrink-0",children:"Built-in"})]}),e.jsx("span",{className:"text-xs text-muted-foreground line-clamp-1",children:c.subject})]},c.id))]},i))})]})}function czs({open:s,onOpenChange:t,prospectId:r,brokerageId:n,prospectName:a,prospectEmail:i}){const{user:l}=Ms(),o=(a||"").split(" ")[0]||"there",[c,d]=S.useState(""),[h,m]=S.useState(""),[p,x]=S.useState("default"),[y,_]=S.useState(!1),[b,j]=S.useState(null),[k,T]=S.useState(!1),E=ns(),{data:A}=cye();S.useEffect(()=>{if(s){d(`Hi ${o}`),m("");const ee=A!=null&&A.massEmail?"mass_email":A!=null&&A.gmail?"gmail":"default";x(ee),j(null),T(!1)}},[s,o,A==null?void 0:A.massEmail,A==null?void 0:A.gmail]);const{data:D=[],isLoading:R}=yt({queryKey:["prospect-email-video-library",l==null?void 0:l.id],queryFn:async()=>{const{data:ee,error:Z}=await V.from("agent_videos").select("id, title, thumbnail_url, duration_seconds, touch_type, created_at, share_token").eq("owner_user_id",l.id).eq("status","ready").eq("is_deleted",!1).order("created_at",{ascending:!1}).limit(50);if(Z)throw Z;return ee??[]},enabled:s&&!!(l!=null&&l.id)}),z=D.find(ee=>ee.id===b)||null,O=async()=>{var ee,Z;if(!i){he.error("This prospect has no email address on file.");return}if(!c.trim()||!h.trim()){he.error("Subject and message are required.");return}_(!0);try{if(b){const{data:J}=await V.from("recruit_videos").select("id").eq("prospect_id",r).eq("video_id",b).maybeSingle();let K=J==null?void 0:J.id;if(!K){const{data:ne,error:le}=await V.from("recruit_videos").insert({prospect_id:r,video_id:b,brokerage_id:n,message:h.trim(),created_by:l.id}).select("id").single();if(le)throw le;K=ne.id}const{data:re,error:ie}=await V.functions.invoke("send-recruit-video-email",{body:{recruit_video_ids:[K],brokerage_id:n,subject_override:c.trim(),message_override:h.trim(),send_via:p}});if(ie)throw ie;if(((re==null?void 0:re.sent)??0)>0)he.success(`Email sent to ${i}`),E.invalidateQueries({queryKey:["recruit-videos"]}),E.invalidateQueries({queryKey:["recruit-videos-prospect",r]}),E.invalidateQueries({queryKey:["recruit-activities",r]}),E.invalidateQueries({queryKey:["recruit-sent-emails"]}),t(!1);else{const ne=((Z=(ee=re==null?void 0:re.results)==null?void 0:ee[0])==null?void 0:Z.error)||"Failed to send";he.error(ne)}}else{const{data:J,error:K}=await V.functions.invoke("send-recruit-prospect-email",{body:{prospect_id:r,brokerage_id:n,subject:c.trim(),message:h.trim(),send_via:p}});if(K)throw K;J!=null&&J.success?(he.success(`Email sent to ${i}`),E.invalidateQueries({queryKey:["recruit-activities",r]}),E.invalidateQueries({queryKey:["recruit-sent-emails"]}),t(!1)):he.error((J==null?void 0:J.error)||"Failed to send")}}catch(J){he.error((J==null?void 0:J.message)||"Failed to send email")}finally{_(!1)}},$=ee=>{const Z=J=>J.replace(/\[First Name\]/gi,o);d(Z(ee.subject)),m(Z(ee.body)),he.success(`Loaded "${ee.title}"`)};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(Cs,{children:e.jsxs(Ns,{className:"flex items-center gap-2",children:[e.jsx(er,{className:"h-5 w-5"})," Email ",a]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs",children:"To"}),e.jsx(Se,{value:i||"— no email on file —",disabled:!0,className:"mt-1"})]}),e.jsx(x6e,{value:p,onChange:x}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx(ue,{className:"text-xs",children:"Subject"}),e.jsx(lzs,{brokerageId:n,onSelect:$})]}),e.jsx(Se,{value:c,onChange:ee=>d(ee.target.value)}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs",children:"Message"}),e.jsx(vr,{value:h,onChange:ee=>m(ee.target.value),rows:8,placeholder:`Hi ${o}, wanted to reach out…`,className:"mt-1"})]}),e.jsxs("div",{className:"rounded-md border p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(ue,{className:"text-xs flex items-center gap-1.5",children:[e.jsx(xn,{className:"h-3.5 w-3.5"})," Include a video"]}),z?e.jsxs(H,{type:"button",variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>{j(null),T(!1)},children:[e.jsx(Rr,{className:"h-3 w-3 mr-1"})," Remove"]}):e.jsx(H,{type:"button",variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>T(ee=>!ee),children:k?"Hide library":"Pick from library"})]}),z&&e.jsxs("div",{className:"flex items-center gap-3 p-2 rounded bg-muted/40",children:[e.jsx("div",{className:"h-10 w-16 rounded bg-muted overflow-hidden flex-shrink-0",children:i_(z)?e.jsx("img",{src:i_(z),alt:"",className:"h-full w-full object-cover",referrerPolicy:"no-referrer"}):e.jsx("div",{className:"h-full w-full flex items-center justify-center",children:e.jsx(xn,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsx("p",{className:"text-xs font-medium truncate flex-1",children:z.title||"Untitled video"})]}),!z&&k&&e.jsx("div",{className:"max-h-56 overflow-y-auto space-y-1 -mx-1 px-1",children:R?e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(is,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):D.length===0?e.jsx("p",{className:"text-xs text-muted-foreground text-center py-3",children:"No videos in your library yet. Record one from a prospect to get started."}):D.map(ee=>e.jsxs("button",{type:"button",onClick:()=>{j(ee.id),T(!1)},className:"w-full flex items-center gap-3 p-2 rounded hover:bg-accent text-left transition-colors",children:[e.jsx("div",{className:"h-10 w-16 rounded bg-muted overflow-hidden flex-shrink-0",children:i_(ee)?e.jsx("img",{src:i_(ee),alt:"",className:"h-full w-full object-cover",referrerPolicy:"no-referrer"}):e.jsx("div",{className:"h-full w-full flex items-center justify-center",children:e.jsx(xn,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-xs font-medium truncate",children:ee.title||"Untitled video"}),ee.duration_seconds&&e.jsxs("p",{className:"text-[10px] text-muted-foreground",children:[Math.floor(ee.duration_seconds/60),":",String(Math.floor(ee.duration_seconds%60)).padStart(2,"0")]})]})]},ee.id))}),z&&e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"A tracked share link with thumbnail will be added to the email automatically."})]})]}),e.jsxs(wn,{children:[e.jsx(H,{variant:"ghost",onClick:()=>t(!1),disabled:y,children:"Cancel"}),e.jsxs(H,{onClick:O,disabled:y||!i,children:[y?e.jsx(is,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(yn,{className:"h-4 w-4 mr-2"}),"Send Email"]})]})]})})}function dzs(s){return yt({queryKey:["recruit-campaign-sends",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await V.from("recruit_campaign_sends").select("id, prospect_id, subject, email_number, status, sent_at, opened_at, clicked_at, error_message, created_at").eq("prospect_id",s).neq("status","failed").order("created_at",{ascending:!1});if(r)throw r;return t},enabled:!!s})}const SWe=[{value:"call",label:"Phone Call",icon:Yn},{value:"email",label:"Email",icon:er},{value:"text",label:"Text Message",icon:Gi},{value:"meeting",label:"Meeting",icon:Nn},{value:"note",label:"Note",icon:kn},{value:"campaign_email",label:"Campaign Email",icon:yn}];function qx({label:s,value:t,icon:r}){return t?e.jsxs("div",{children:[e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[r&&e.jsx(r,{className:"h-3 w-3"})," ",s]}),e.jsx("p",{className:"font-medium text-sm",children:t})]}):null}function rV({label:s,url:t,icon:r}){return t?e.jsxs("a",{href:t.startsWith("http")?t:`https://${t}`,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-2 text-sm text-primary hover:underline",children:[e.jsx(r,{className:"h-3.5 w-3.5"})," ",s," ",e.jsx(gn,{className:"h-3 w-3 opacity-50"})]}):null}function bd({label:s,value:t,onChange:r,type:n="text",placeholder:a}){return e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs",children:s}),e.jsx(Se,{type:n,value:t,onChange:i=>r(i.target.value),placeholder:a,className:"mt-1 h-8 text-sm"})]})}function ivt({prospect:s,stages:t,brokerageId:r,open:n,onOpenChange:a,onUpdate:i,onDelete:l}){const{activities:o,addActivity:c}=szs((s==null?void 0:s.id)||null),{data:d=[]}=dzs((s==null?void 0:s.id)||null),[h,m]=S.useState({type:"note",title:"",description:""}),[p,x]=S.useState(!1),[y,_]=S.useState(!1),[b,j]=S.useState({}),[k,T]=S.useState(!1);if(!s)return null;const E=()=>{var K,re;j({first_name:s.first_name||"",last_name:s.last_name||"",email:s.email||"",phone:s.phone||"",current_brokerage:s.current_brokerage||"",license_number:s.license_number||"",experience_years:((K=s.experience_years)==null?void 0:K.toString())||"",notes:s.notes||"",source:s.source||"",address:s.address||"",city:s.city||"",state:s.state||"",zip_code:s.zip_code||"",last_year_volume:s.last_year_volume||"",last_year_transactions:((re=s.last_year_transactions)==null?void 0:re.toString())||"",avg_sale_price:s.avg_sale_price||"",specialties:s.specialties||"",annual_production:s.annual_production||"",linkedin_url:s.linkedin_url||"",website_url:s.website_url||"",instagram_handle:s.instagram_handle||"",facebook_url:s.facebook_url||"",birthday:s.birthday||"",spouse_name:s.spouse_name||"",interests:s.interests||"",referred_by:s.referred_by||""}),_(!0)},A=()=>{const K={id:s.id};for(const[re,ie]of Object.entries(b))re==="experience_years"||re==="last_year_transactions"?K[re]=ie?parseInt(ie):null:K[re]=ie||null;i(K),_(!1)},D=()=>_(!1),R=K=>re=>j(ie=>({...ie,[K]:re})),z=()=>{h.title.trim()&&(c.mutate({prospect_id:s.id,activity_type:h.type,title:h.title,description:h.description||null}),m({type:"note",title:"",description:""}),x(!1))},O=t.find(K=>K.id===s.stage_id),$=s.address||s.city||s.state,ee=s.last_year_volume||s.last_year_transactions||s.avg_sale_price||s.specialties||s.annual_production,Z=s.linkedin_url||s.website_url||s.instagram_handle||s.facebook_url,J=s.birthday||s.spouse_name||s.interests||s.referred_by;return e.jsxs($S,{open:n,onOpenChange:K=>{K||_(!1),a(K)},children:[e.jsx(vj,{className:"w-full sm:max-w-lg p-0",children:e.jsx(Ci,{className:"h-full",children:e.jsxs("div",{className:"p-6 space-y-5",children:[e.jsx(US,{children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsxs(qS,{className:"text-xl",children:[s.first_name," ",s.last_name]}),O&&e.jsx(Xe,{variant:"outline",style:{borderColor:O.color,color:O.color},className:"mt-1",children:O.name})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[y?e.jsxs(e.Fragment,{children:[e.jsx(H,{variant:"ghost",size:"icon",onClick:D,children:e.jsx(Rr,{className:"h-4 w-4"})}),e.jsx(H,{variant:"default",size:"icon",onClick:A,children:e.jsx(vc,{className:"h-4 w-4"})})]}):e.jsx(H,{variant:"ghost",size:"icon",onClick:E,title:"Edit prospect",children:e.jsx(ni,{className:"h-4 w-4"})}),e.jsxs(Rl,{children:[e.jsx(vp,{asChild:!0,children:e.jsx(H,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(Dr,{className:"h-4 w-4"})})}),e.jsxs(jl,{children:[e.jsxs(Nl,{children:[e.jsx(Sl,{children:"Delete prospect?"}),e.jsx(Cl,{children:"This will permanently remove this prospect and all their activity history."})]}),e.jsxs(kl,{children:[e.jsx(Tl,{children:"Cancel"}),e.jsx(ml,{onClick:()=>{l(s.id),a(!1)},children:"Delete"})]})]})]})]})]})}),!y&&e.jsxs("div",{className:"space-y-2 text-sm",children:[s.email&&e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground min-w-0",children:[e.jsx(er,{className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:s.email})]}),e.jsxs(H,{size:"sm",variant:"outline",className:"h-7 gap-1.5 flex-shrink-0",onClick:()=>T(!0),children:[e.jsx(er,{className:"h-3 w-3"})," Email"]})]}),s.phone&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(Yn,{className:"h-3.5 w-3.5"})," ",s.phone]}),$&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(Qa,{className:"h-3.5 w-3.5"}),[s.address,s.city,s.state,s.zip_code].filter(Boolean).join(", ")]})]}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs text-muted-foreground",children:"Move to Stage"}),e.jsxs(Bs,{value:s.stage_id||"",onValueChange:K=>i({id:s.id,stage_id:K}),children:[e.jsx(Os,{className:"mt-1",children:e.jsx(Us,{})}),e.jsx(Fs,{children:t.map(K=>e.jsx(pt,{value:K.id,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-2.5 w-2.5 rounded-full",style:{backgroundColor:K.color}}),K.name]})},K.id))})]})]}),e.jsxs(ta,{defaultValue:"details",className:"w-full",children:[e.jsxs(Qn,{className:"grid w-full grid-cols-4 h-8 text-xs",children:[e.jsx(ts,{value:"details",className:"text-xs",children:"Details"}),e.jsx(ts,{value:"production",className:"text-xs",children:"Production"}),e.jsx(ts,{value:"social",className:"text-xs",children:"Social"}),e.jsx(ts,{value:"personal",className:"text-xs",children:"Personal"})]}),y?e.jsxs(e.Fragment,{children:[e.jsxs(cs,{value:"details",className:"mt-3 space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(bd,{label:"First Name",value:b.first_name,onChange:R("first_name")}),e.jsx(bd,{label:"Last Name",value:b.last_name,onChange:R("last_name")})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(bd,{label:"Email",value:b.email,onChange:R("email"),type:"email"}),e.jsx(bd,{label:"Phone",value:b.phone,onChange:R("phone")})]}),e.jsx(bd,{label:"Current Brokerage",value:b.current_brokerage,onChange:R("current_brokerage")}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(bd,{label:"License #",value:b.license_number,onChange:R("license_number")}),e.jsx(bd,{label:"Experience (years)",value:b.experience_years,onChange:R("experience_years"),type:"number"})]}),e.jsx(bd,{label:"Address",value:b.address,onChange:R("address"),placeholder:"Street address"}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsx(bd,{label:"City",value:b.city,onChange:R("city")}),e.jsx(bd,{label:"State",value:b.state,onChange:R("state")}),e.jsx(bd,{label:"Zip",value:b.zip_code,onChange:R("zip_code")})]}),e.jsx(bd,{label:"Source",value:b.source,onChange:R("source")}),e.jsx(bd,{label:"Referred By",value:b.referred_by,onChange:R("referred_by")}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs",children:"Notes"}),e.jsx(vr,{value:b.notes,onChange:K=>j(re=>({...re,notes:K.target.value})),rows:3,className:"mt-1 text-sm"})]})]}),e.jsxs(cs,{value:"production",className:"mt-3 space-y-3",children:[e.jsx(bd,{label:"Annual Production",value:b.annual_production,onChange:R("annual_production"),placeholder:"e.g. $5M"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(bd,{label:"Last Year Volume",value:b.last_year_volume,onChange:R("last_year_volume"),placeholder:"e.g. $8.2M"}),e.jsx(bd,{label:"Last Year Transactions",value:b.last_year_transactions,onChange:R("last_year_transactions"),type:"number",placeholder:"e.g. 24"})]}),e.jsx(bd,{label:"Avg Sale Price",value:b.avg_sale_price,onChange:R("avg_sale_price"),placeholder:"e.g. $350K"}),e.jsx(bd,{label:"Specialties / Niche",value:b.specialties,onChange:R("specialties"),placeholder:"e.g. Luxury, Investment"})]}),e.jsxs(cs,{value:"social",className:"mt-3 space-y-3",children:[e.jsx(bd,{label:"LinkedIn URL",value:b.linkedin_url,onChange:R("linkedin_url"),type:"url",placeholder:"https://linkedin.com/in/..."}),e.jsx(bd,{label:"Website URL",value:b.website_url,onChange:R("website_url"),type:"url",placeholder:"https://..."}),e.jsx(bd,{label:"Instagram Handle",value:b.instagram_handle,onChange:R("instagram_handle"),placeholder:"@handle"}),e.jsx(bd,{label:"Facebook URL",value:b.facebook_url,onChange:R("facebook_url"),type:"url",placeholder:"https://facebook.com/..."})]}),e.jsxs(cs,{value:"personal",className:"mt-3 space-y-3",children:[e.jsx(bd,{label:"Birthday",value:b.birthday,onChange:R("birthday"),type:"date"}),e.jsx(bd,{label:"Spouse / Partner",value:b.spouse_name,onChange:R("spouse_name")}),e.jsx(bd,{label:"Interests / Hobbies",value:b.interests,onChange:R("interests"),placeholder:"Golf, travel, community events..."})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(cs,{value:"details",className:"mt-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(qx,{label:"Current Brokerage",value:s.current_brokerage}),e.jsx(qx,{label:"License #",value:s.license_number}),e.jsx(qx,{label:"Experience",value:s.experience_years!=null?`${s.experience_years} years`:null}),e.jsx(qx,{label:"Referred By",value:s.referred_by}),e.jsx(qx,{label:"Source",value:s.source})]}),s.notes&&e.jsxs("div",{className:"mt-3",children:[e.jsx(ue,{className:"text-xs text-muted-foreground",children:"Notes"}),e.jsx("p",{className:"text-sm mt-1 whitespace-pre-wrap",children:s.notes})]})]}),e.jsx(cs,{value:"production",className:"mt-3",children:ee?e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(qx,{label:"Annual Production",value:s.annual_production}),e.jsx(qx,{label:"Last Year Volume",value:s.last_year_volume}),e.jsx(qx,{label:"Last Year Transactions",value:s.last_year_transactions}),e.jsx(qx,{label:"Avg Sale Price",value:s.avg_sale_price}),e.jsx(qx,{label:"Specialties / Niche",value:s.specialties})]}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No production data added yet"})}),e.jsx(cs,{value:"social",className:"mt-3",children:Z?e.jsxs("div",{className:"space-y-2",children:[e.jsx(rV,{label:"LinkedIn",url:s.linkedin_url,icon:qf}),e.jsx(rV,{label:"Website",url:s.website_url,icon:ld}),s.instagram_handle&&e.jsx(rV,{label:s.instagram_handle,url:`https://instagram.com/${s.instagram_handle.replace("@","")}`,icon:yu}),e.jsx(rV,{label:"Facebook",url:s.facebook_url,icon:fh})]}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No social profiles added yet"})}),e.jsx(cs,{value:"personal",className:"mt-3",children:J?e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(qx,{label:"Birthday",value:s.birthday?As(new Date(s.birthday+"T00:00:00"),"MMMM d, yyyy"):null,icon:Di}),e.jsx(qx,{label:"Spouse / Partner",value:s.spouse_name,icon:Bi}),e.jsx("div",{className:"col-span-2",children:e.jsx(qx,{label:"Interests / Hobbies",value:s.interests})})]}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No personal details added yet"})})]})]}),e.jsx(ozs,{prospectId:s.id,prospectName:`${s.first_name} ${s.last_name||""}`,prospectEmail:s.email,brokerageId:r}),e.jsx(Qo,{}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("h3",{className:"font-semibold text-sm",children:"Activity Log"}),e.jsxs(H,{size:"sm",variant:"outline",onClick:()=>x(!p),children:[e.jsx(Ys,{className:"h-3.5 w-3.5 mr-1"})," Log Activity"]})]}),p&&e.jsxs("div",{className:"border rounded-lg p-3 mb-4 space-y-3 bg-muted/30",children:[e.jsxs(Bs,{value:h.type,onValueChange:K=>m(re=>({...re,type:K})),children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsx(Fs,{children:SWe.map(K=>e.jsx(pt,{value:K.value,children:K.label},K.value))})]}),e.jsx(Se,{placeholder:"Subject / Title",value:h.title,onChange:K=>m(re=>({...re,title:K.target.value}))}),e.jsx(vr,{placeholder:"Details (optional)",value:h.description,onChange:K=>m(re=>({...re,description:K.target.value})),rows:2}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(H,{size:"sm",variant:"ghost",onClick:()=>x(!1),children:"Cancel"}),e.jsx(H,{size:"sm",onClick:z,disabled:!h.title.trim(),children:"Save"})]})]}),e.jsx("div",{className:"space-y-3",children:(()=>{const K=[...o.map(re=>({type:"manual",data:re,date:re.created_at})),...d.map(re=>({type:"campaign_email",data:re,date:re.sent_at||re.created_at}))].sort((re,ie)=>new Date(ie.date).getTime()-new Date(re.date).getTime());return K.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No activity logged yet"}):K.map(re=>{if(re.type==="manual"){const ce=re.data,ne=SWe.find(be=>be.value===ce.activity_type),le=(ne==null?void 0:ne.icon)||kn;return e.jsxs("div",{className:"flex gap-3 text-sm",children:[e.jsx("div",{className:"mt-0.5",children:e.jsx("div",{className:"h-7 w-7 rounded-full bg-muted flex items-center justify-center",children:e.jsx(le,{className:"h-3.5 w-3.5 text-muted-foreground"})})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium",children:ce.title}),ce.description&&e.jsx("p",{className:"text-muted-foreground text-xs mt-0.5",children:ce.description}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:As(new Date(ce.created_at),"MMM d, yyyy h:mm a")})]})]},`activity-${ce.id}`)}const ie=re.data;return e.jsxs("div",{className:"flex gap-3 text-sm",children:[e.jsx("div",{className:"mt-0.5",children:e.jsx("div",{className:"h-7 w-7 rounded-full bg-primary/10 flex items-center justify-center",children:e.jsx(yn,{className:"h-3.5 w-3.5 text-primary"})})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("p",{className:"font-medium",children:["Campaign Email #",ie.email_number]}),e.jsx("p",{className:"text-muted-foreground text-xs mt-0.5",children:ie.subject}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 mt-1.5",children:[ie.status==="failed"?e.jsx(Xe,{variant:"destructive",className:"text-[10px] px-1.5 py-0 h-4",children:"Failed"}):e.jsxs(Xe,{variant:"outline",className:"text-[10px] px-1.5 py-0 h-4 border-green-500 text-green-600",children:[e.jsx(yn,{className:"h-2.5 w-2.5 mr-0.5"})," Sent"]}),ie.opened_at?e.jsxs(Xe,{variant:"outline",className:"text-[10px] px-1.5 py-0 h-4 border-blue-500 text-blue-600",children:[e.jsx(Bn,{className:"h-2.5 w-2.5 mr-0.5"})," Opened ",As(new Date(ie.opened_at),"MMM d, h:mm a")]}):ie.status!=="failed"?e.jsx(Xe,{variant:"outline",className:"text-[10px] px-1.5 py-0 h-4 text-muted-foreground",children:"Not opened"}):null,ie.clicked_at&&e.jsxs(Xe,{variant:"outline",className:"text-[10px] px-1.5 py-0 h-4 border-purple-500 text-purple-600",children:[e.jsx(lm,{className:"h-2.5 w-2.5 mr-0.5"})," Clicked ",As(new Date(ie.clicked_at),"MMM d, h:mm a")]})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:As(new Date(ie.sent_at||ie.created_at),"MMM d, yyyy h:mm a")})]})]},`send-${ie.id}`)})})()})]})]})})}),e.jsx(czs,{open:k,onOpenChange:T,prospectId:s.id,brokerageId:s.brokerage_id,prospectName:`${s.first_name} ${s.last_name??""}`.trim(),prospectEmail:s.email})]})}const uzs=["first_name","last_name","email","phone","current_brokerage","license_number","experience_years","annual_production","notes","address","city","state","zip_code","last_year_volume","last_year_transactions","avg_sale_price","linkedin_url","website_url","specialties","referred_by"];function ovt({open:s,onOpenChange:t,brokerageId:r,stages:n}){var $;const{toast:a}=li(),i=ns(),l=S.useRef(null),[o,c]=S.useState([]),[d,h]=S.useState([]),[m,p]=S.useState({}),[x,y]=S.useState((($=n[0])==null?void 0:$.id)||""),[_,b]=S.useState(!1),[j,k]=S.useState("upload"),[T,E]=S.useState(0),A=()=>{c([]),h([]),p({}),k("upload"),E(0)},D=ee=>{var K;const Z=(K=ee.target.files)==null?void 0:K[0];if(!Z)return;const J=new FileReader;J.onload=re=>{var je;const ce=((je=re.target)==null?void 0:je.result).split(/\r?\n/).filter(ve=>ve.trim());if(ce.length<2){a({title:"Invalid CSV",description:"File must have a header row and at least one data row",variant:"destructive"});return}const ne=R(ce[0]);h(ne);const le={},be=new Set;ne.forEach((ve,We)=>{const Ve=ve.toLowerCase().replace(/[^a-z0-9]/g,"");let Le=null;/^firstname$/.test(Ve)||Ve==="first"?Le="first_name":/^lastname$/.test(Ve)||Ve==="last"?Le="last_name":/^email$/.test(Ve)||Ve==="emailaddress"?Le="email":/^mobile$|^phone$|^cellphone$|^mobilephone$/.test(Ve)?Le="phone":/officename|currentbrokerage|brokerage|company/.test(Ve)?Le="current_brokerage":/membernumber|licensenumber|license/.test(Ve)?Le="license_number":/experienceyears|yearsexperience/.test(Ve)?Le="experience_years":/^totalvolume$|annualproduction/.test(Ve)?Le="annual_production":/^address$/.test(Ve)?Le="address":/^city$/.test(Ve)?Le="city":/^state$/.test(Ve)?Le="state":/^postalcode$|^zip$|^zipcode$/.test(Ve)?Le="zip_code":/listsidevolume|lastyearvolume/.test(Ve)?Le="last_year_volume":/^totalcount$|lastyeartransactions/.test(Ve)?Le="last_year_transactions":/avgsaleprice|averageprice/.test(Ve)?Le="avg_sale_price":/linkedin/.test(Ve)?Le="linkedin_url":/website/.test(Ve)?Le="website_url":/specialt/.test(Ve)?Le="specialties":/referr/.test(Ve)?Le="referred_by":/^notes$|^note$/.test(Ve)&&(Le="notes"),Le&&!be.has(Le)&&(le[String(We)]=Le,be.add(Le))}),p(le);const fe=ce.slice(1).map(ve=>{const We=R(ve),Ve={};return ne.forEach((Le,Me)=>{Ve[String(Me)]=We[Me]||""}),Ve});c(fe),k("map")},J.readAsText(Z)},R=ee=>{const Z=[];let J="",K=!1;for(const re of ee)re==='"'?K=!K:re===","&&!K?(Z.push(J.trim()),J=""):J+=re;return Z.push(J.trim()),Z},z=async()=>{b(!0);try{const{data:{user:ee}}=await V.auth.getUser();if(!ee)throw new Error("Not authenticated");const Z=o.map(K=>{const re={brokerage_id:r,created_by:ee.id,stage_id:x,source:"csv_import",first_name:"Unknown"},ie=re;return Object.entries(m).forEach(([ce,ne])=>{var be;const le=(be=K[ce])==null?void 0:be.trim();le&&(ne==="experience_years"||ne==="last_year_transactions"?ie[ne]=parseInt(le.replace(/[^0-9.-]/g,""))||null:ne==="annual_production"||ne==="last_year_volume"||ne==="avg_sale_price"?ie[ne]=le.replace(/[^0-9.$,.-]/g,""):ie[ne]=le)}),re});let J=0;for(let K=0;K{const ee=`first_name,last_name,email,phone,current_brokerage,license_number,experience_years,annual_production,notes Jane,Smith,jane@example.com,555-0100,ABC Realty,RE12345,8,$5M,Met at conference`,Z=new Blob([ee],{type:"text/csv"}),J=URL.createObjectURL(Z),K=document.createElement("a");K.href=J,K.download="recruit-prospects-template.csv",K.click(),URL.revokeObjectURL(J)};return e.jsx(bs,{open:s,onOpenChange:ee=>{ee||A(),t(ee)},children:e.jsxs(vs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Cs,{children:e.jsx(Ns,{children:"Import Prospects from CSV"})}),j==="upload"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-8 text-center",children:[e.jsx($2,{className:"h-10 w-10 mx-auto text-muted-foreground mb-3"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Upload a CSV file with prospect data"}),e.jsx("input",{ref:l,type:"file",accept:".csv",className:"hidden",onChange:D}),e.jsxs(H,{onClick:()=>{var ee;return(ee=l.current)==null?void 0:ee.click()},children:[e.jsx(Ea,{className:"h-4 w-4 mr-2"})," Choose File"]})]}),e.jsx(H,{variant:"link",className:"text-xs",onClick:O,children:"Download CSV template"})]}),j==="map"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:[o.length," rows found"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm",children:"Import to stage:"}),e.jsxs(Bs,{value:x,onValueChange:y,children:[e.jsx(Os,{className:"w-[180px]",children:e.jsx(Us,{})}),e.jsx(Fs,{children:n.map(ee=>e.jsx(pt,{value:ee.id,children:ee.name},ee.id))})]})]})]}),e.jsx("div",{className:"border rounded-lg overflow-hidden",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Vs,{children:[e.jsx(At,{className:"w-[140px]",children:"CSV Column"}),e.jsx(At,{className:"w-[160px]",children:"Map To"}),e.jsx(At,{children:"Preview"})]})}),e.jsx(da,{children:d.map((ee,Z)=>{var J;return e.jsxs(Vs,{children:[e.jsx(gt,{className:"font-medium text-xs",children:ee}),e.jsx(gt,{children:e.jsxs(Bs,{value:m[String(Z)]||"skip",onValueChange:K=>p(re=>({...re,[String(Z)]:K==="skip"?"":K})),children:[e.jsx(Os,{className:"h-8 text-xs",children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"skip",children:"— Skip —"}),uzs.map(K=>e.jsx(pt,{value:K,children:K.replace(/_/g," ")},K))]})]})}),e.jsx(gt,{className:"text-xs text-muted-foreground truncate max-w-[200px]",children:((J=o[0])==null?void 0:J[String(Z)])||"—"})]},Z)})})]})}),!Object.values(m).includes("first_name")&&e.jsxs("div",{className:"flex items-center gap-2 text-amber-600 text-sm",children:[e.jsx(wo,{className:"h-4 w-4"}),' Map at least "first name" to proceed']}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(H,{variant:"outline",onClick:()=>{A()},children:"Back"}),e.jsx(H,{onClick:z,disabled:_||!Object.values(m).includes("first_name"),children:_?"Importing...":`Import ${o.length} Prospects`})]})]}),j==="done"&&e.jsxs("div",{className:"text-center py-6 space-y-3",children:[e.jsx("div",{className:"h-12 w-12 rounded-full bg-green-500/10 flex items-center justify-center mx-auto",children:e.jsx(va,{className:"h-6 w-6 text-green-600"})}),e.jsxs("p",{className:"font-semibold",children:[T," prospects imported successfully!"]}),e.jsx(H,{onClick:()=>{A(),t(!1)},children:"Close"})]})]})})}function lvt({brokerageId:s}){const{stages:t,prospects:r,isLoading:n,addProspect:a,updateProspect:i,deleteProspect:l}=Hz(s),[o,c]=S.useState(!1),[d,h]=S.useState(),[m,p]=S.useState(null),[x,y]=S.useState(!1),[_,b]=S.useState(!1),[j,k]=S.useState(null);if(n)return e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})});const T=O=>r.filter($=>$.stage_id===O),E=(O,$)=>{k($),O.dataTransfer.effectAllowed="move"},A=O=>{O.preventDefault(),O.dataTransfer.dropEffect="move"},D=(O,$)=>{O.preventDefault(),j&&(i.mutate({id:j,stage_id:$}),k(null))},R=O=>{h(O),c(!0)},z=O=>{p(O),y(!0)};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{children:e.jsxs("p",{className:"text-sm text-muted-foreground",children:[r.length," prospect",r.length!==1?"s":""]})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(H,{variant:"outline",onClick:()=>b(!0),children:[e.jsx(Ea,{className:"h-4 w-4 mr-2"})," Import CSV"]}),e.jsxs(H,{onClick:()=>{h(void 0),c(!0)},children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"})," Add Prospect"]})]})]}),e.jsxs(Ci,{className:"w-full",children:[e.jsx("div",{className:"flex gap-4 pb-4",style:{minWidth:t.length*300},children:t.map(O=>{const $=T(O.id);return e.jsxs("div",{className:"w-[280px] flex-shrink-0 flex flex-col",onDragOver:A,onDrop:ee=>D(ee,O.id),children:[e.jsxs("div",{className:"flex items-center justify-between mb-3 px-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-3 w-3 rounded-full",style:{backgroundColor:O.color}}),e.jsx("h3",{className:"font-semibold text-sm",children:O.name}),e.jsx(Xe,{variant:"secondary",className:"text-xs h-5 px-1.5",children:$.length})]}),e.jsx(H,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>R(O.id),children:e.jsx(Ys,{className:"h-3.5 w-3.5"})})]}),e.jsx("div",{className:"space-y-2 min-h-[200px] bg-muted/30 rounded-lg p-2",children:$.map(ee=>e.jsx(ke,{className:"p-3 cursor-pointer hover:shadow-md transition-shadow border-l-4 group",style:{borderLeftColor:O.color},draggable:!0,onDragStart:Z=>E(Z,ee.id),onClick:()=>z(ee),children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Oh,{className:"h-4 w-4 text-muted-foreground/40 mt-0.5 opacity-0 group-hover:opacity-100 transition-opacity cursor-grab"}),e.jsxs("div",{className:"flex-1 min-w-0 space-y-1.5",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(io,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsxs("span",{className:"font-medium text-sm truncate",children:[ee.first_name," ",ee.last_name]})]}),ee.current_brokerage&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(Xa,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:ee.current_brokerage})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[ee.email&&e.jsx(er,{className:"h-3 w-3 text-muted-foreground"}),ee.phone&&e.jsx(Yn,{className:"h-3 w-3 text-muted-foreground"}),ee.experience_years!=null&&e.jsxs(Xe,{variant:"secondary",className:"text-[10px] h-4 px-1",children:[ee.experience_years,"yr"]})]})]})]})},ee.id))})]},O.id)})}),e.jsx(Ige,{orientation:"horizontal"})]}),e.jsx(tvt,{open:o,onOpenChange:c,stages:t,defaultStageId:d,onSubmit:O=>a.mutate(O),isSubmitting:a.isPending}),e.jsx(ivt,{prospect:m,stages:t,brokerageId:s,open:x,onOpenChange:y,onUpdate:O=>{i.mutate(O),p($=>$?{...$,...O}:null)},onDelete:O=>l.mutate(O)}),e.jsx(ovt,{open:_,onOpenChange:b,brokerageId:s,stages:t})]})}function fpe({brokerageId:s}){const{stages:t,prospects:r,isLoading:n,addProspect:a,updateProspect:i,deleteProspect:l}=Hz(s),{user:o}=Ms(),c=ns(),[d,h]=S.useState(!1),[m,p]=S.useState(null),[x,y]=S.useState(!1),[_,b]=S.useState(!1),[j,k]=S.useState(""),[T,E]=S.useState("all"),[A,D]=S.useState("all"),[R,z]=S.useState("all"),[O,$]=S.useState(null),[ee,Z]=S.useState("asc"),[J,K]=S.useState(new Set),[re,ie]=S.useState(!1),[ce,ne]=S.useState(""),le=S.useMemo(()=>{const pe=new Set;return r.forEach(tt=>{tt.current_brokerage&&pe.add(tt.current_brokerage)}),Array.from(pe).sort()},[r]),{data:be=[]}=yt({queryKey:["recruit-campaigns-list",s],queryFn:async()=>{const{data:pe,error:tt}=await V.from("recruit_campaigns").select("id, name, warmth_level").or(`brokerage_id.is.null,brokerage_id.eq.${s}`).order("name");if(tt)throw tt;return pe}}),{data:fe=[]}=yt({queryKey:["recruit-campaign-assignments-lookup",s],queryFn:async()=>{let tt=[],ge=0;for(;;){const{data:ct,error:Ue}=await V.from("recruit_campaign_assignments").select("prospect_id, campaign_id, status").eq("brokerage_id",s).range(ge,ge+1e3-1);if(Ue)throw Ue;if(tt=tt.concat(ct??[]),!ct||ct.length<1e3)break;ge+=1e3}return tt}}),je=S.useMemo(()=>{const pe=new Map;return fe.forEach(tt=>{pe.has(tt.prospect_id)||pe.set(tt.prospect_id,new Set),pe.get(tt.prospect_id).add(tt.campaign_id)}),pe},[fe]),ve=pe=>{O===pe?Z(tt=>tt==="asc"?"desc":"asc"):($(pe),Z("asc"))},We=({column:pe})=>O!==pe?e.jsx(qu,{className:"h-3.5 w-3.5 ml-1 text-muted-foreground/50"}):ee==="asc"?e.jsx(Hu,{className:"h-3.5 w-3.5 ml-1 text-primary"}):e.jsx(fm,{className:"h-3.5 w-3.5 ml-1 text-primary"}),Ve=pe=>t.find(tt=>tt.id===pe),Le=S.useMemo(()=>{let pe=r.filter(tt=>{var Qe,Ne,$e;const ge=!j||`${tt.first_name} ${tt.last_name}`.toLowerCase().includes(j.toLowerCase())||((Qe=tt.email)==null?void 0:Qe.toLowerCase().includes(j.toLowerCase()))||((Ne=tt.current_brokerage)==null?void 0:Ne.toLowerCase().includes(j.toLowerCase())),ct=T==="all"||tt.stage_id===T,Ue=A==="all"||tt.current_brokerage===A;let et=!0;return R==="in_campaign"?et=je.has(tt.id):R==="not_in_campaign"?et=!je.has(tt.id):R!=="all"&&(et=(($e=je.get(tt.id))==null?void 0:$e.has(R))??!1),ge&&ct&&Ue&&et});return O&&(pe=[...pe].sort((tt,ge)=>{var Qe,Ne;let ct=null,Ue=null;switch(O){case"name":ct=`${tt.first_name} ${tt.last_name||""}`.toLowerCase(),Ue=`${ge.first_name} ${ge.last_name||""}`.toLowerCase();break;case"stage":ct=((Qe=Ve(tt.stage_id))==null?void 0:Qe.sort_order)??999,Ue=((Ne=Ve(ge.stage_id))==null?void 0:Ne.sort_order)??999;break;case"brokerage":ct=(tt.current_brokerage||"").toLowerCase(),Ue=(ge.current_brokerage||"").toLowerCase();break;case"experience":ct=tt.experience_years??-1,Ue=ge.experience_years??-1;break;case"production":ct=(tt.annual_production||"").toLowerCase(),Ue=(ge.annual_production||"").toLowerCase();break;case"source":ct=(tt.source||"").toLowerCase(),Ue=(ge.source||"").toLowerCase();break;default:return 0}if(ct===Ue)return 0;if(ct==null)return 1;if(Ue==null)return-1;const et=ct0&&Le.every(pe=>J.has(pe.id)),ze=Le.some(pe=>J.has(pe.id)),Pe=()=>{K(Me?new Set:new Set(Le.map(pe=>pe.id)))},Ie=pe=>{K(tt=>{const ge=new Set(tt);return ge.has(pe)?ge.delete(pe):ge.add(pe),ge})},De=Pt({mutationFn:async()=>{if(!ce||!(o!=null&&o.id))throw new Error("Select a campaign");const pe=new Set(fe.filter(ct=>ct.campaign_id===ce).map(ct=>ct.prospect_id)),tt=Array.from(J).filter(ct=>!pe.has(ct)).map(ct=>({prospect_id:ct,campaign_id:ce,brokerage_id:s,assigned_by:o.id,status:"active",current_email_number:0}));if(tt.length===0)throw new Error("All selected prospects are already in this campaign");const{error:ge}=await V.from("recruit_campaign_assignments").insert(tt);if(ge)throw ge;return tt.length},onSuccess:pe=>{he.success(`${pe} prospect(s) added to campaign`),ie(!1),K(new Set),ne(""),c.invalidateQueries({queryKey:["recruit-campaign-assignments-lookup"]})},onError:pe=>he.error(pe.message)});return n?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4 flex-wrap",children:[e.jsxs("div",{className:"relative flex-1 max-w-sm min-w-[200px]",children:[e.jsx(Mn,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(Se,{placeholder:"Search prospects...",value:j,onChange:pe=>k(pe.target.value),className:"pl-8"})]}),e.jsxs("div",{className:"flex gap-2",children:[J.size>0&&e.jsxs(H,{variant:"secondary",onClick:()=>ie(!0),className:"gap-1.5",children:[e.jsx(yn,{className:"h-4 w-4"})," Add ",J.size," to Campaign"]}),e.jsxs(H,{variant:"outline",onClick:()=>b(!0),children:[e.jsx(Ea,{className:"h-4 w-4 mr-2"})," Import CSV"]}),e.jsxs(H,{onClick:()=>h(!0),children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"})," Add Prospect"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(v1,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs(Bs,{value:T,onValueChange:E,children:[e.jsx(Os,{className:"w-[160px] h-8 text-xs",children:e.jsx(Us,{placeholder:"All stages"})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"all",children:"All stages"}),t.map(pe=>e.jsx(pt,{value:pe.id,children:pe.name},pe.id))]})]}),e.jsxs(Bs,{value:A,onValueChange:D,children:[e.jsxs(Os,{className:"w-[200px] h-8 text-xs",children:[e.jsx(Xa,{className:"h-3.5 w-3.5 mr-1.5"}),e.jsx(Us,{placeholder:"All brokerages"})]}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"all",children:"All brokerages"}),le.map(pe=>e.jsx(pt,{value:pe,children:pe},pe))]})]}),e.jsxs(Bs,{value:R,onValueChange:z,children:[e.jsxs(Os,{className:"w-[200px] h-8 text-xs",children:[e.jsx(er,{className:"h-3.5 w-3.5 mr-1.5"}),e.jsx(Us,{placeholder:"Campaign status"})]}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"all",children:"All contacts"}),e.jsx(pt,{value:"in_campaign",children:"In any campaign"}),e.jsx(pt,{value:"not_in_campaign",children:"Not in any campaign"}),be.map(pe=>e.jsxs(pt,{value:pe.id,children:["In: ",pe.name]},pe.id))]})]}),(T!=="all"||A!=="all"||R!=="all")&&e.jsx(H,{variant:"ghost",size:"sm",className:"h-8 text-xs text-muted-foreground",onClick:()=>{E("all"),D("all"),z("all")},children:"Clear filters"})]}),e.jsx("div",{className:"rounded-md border",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Vs,{children:[e.jsx(At,{className:"w-[40px]",children:e.jsx(ao,{checked:Me,onCheckedChange:Pe,"aria-label":"Select all",...ze&&!Me?{"data-state":"indeterminate"}:{}})}),e.jsx(At,{className:"cursor-pointer select-none",onClick:()=>ve("name"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Name ",e.jsx(We,{column:"name"})]})}),e.jsx(At,{className:"cursor-pointer select-none",onClick:()=>ve("stage"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Stage ",e.jsx(We,{column:"stage"})]})}),e.jsx(At,{className:"hidden md:table-cell cursor-pointer select-none",onClick:()=>ve("brokerage"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Brokerage ",e.jsx(We,{column:"brokerage"})]})}),e.jsx(At,{className:"hidden md:table-cell",children:"Contact"}),e.jsx(At,{className:"hidden lg:table-cell cursor-pointer select-none",onClick:()=>ve("experience"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Experience ",e.jsx(We,{column:"experience"})]})}),e.jsx(At,{className:"hidden lg:table-cell cursor-pointer select-none",onClick:()=>ve("production"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Production ",e.jsx(We,{column:"production"})]})}),e.jsx(At,{className:"hidden lg:table-cell",children:"Campaigns"}),e.jsx(At,{className:"w-[50px]"})]})}),e.jsx(da,{children:Le.length===0?e.jsx(Vs,{children:e.jsx(gt,{colSpan:9,className:"text-center text-muted-foreground py-8",children:"No prospects found"})}):Le.map(pe=>{const tt=Ve(pe.stage_id),ge=je.get(pe.id),ct=(ge==null?void 0:ge.size)??0;return e.jsxs(Vs,{className:"cursor-pointer",onClick:()=>{p(pe),y(!0)},children:[e.jsx(gt,{onClick:Ue=>Ue.stopPropagation(),children:e.jsx(ao,{checked:J.has(pe.id),onCheckedChange:()=>Ie(pe.id),"aria-label":`Select ${pe.first_name}`})}),e.jsxs(gt,{className:"font-medium",children:[pe.first_name," ",pe.last_name]}),e.jsx(gt,{children:tt?e.jsxs(Xe,{variant:"outline",className:"text-xs gap-1 whitespace-nowrap",style:{borderColor:tt.color,color:tt.color,backgroundColor:`${tt.color}10`},children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full inline-block",style:{backgroundColor:tt.color}}),tt.name]}):e.jsx("span",{className:"text-muted-foreground text-xs",children:"—"})}),e.jsx(gt,{className:"hidden md:table-cell",children:pe.current_brokerage?e.jsxs("div",{className:"flex items-center gap-1.5 text-sm",children:[e.jsx(Xa,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate max-w-[150px]",children:pe.current_brokerage})]}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(gt,{className:"hidden md:table-cell",children:e.jsxs("div",{className:"flex items-center gap-2",children:[pe.email&&e.jsx(er,{className:"h-3.5 w-3.5 text-muted-foreground"}),pe.phone&&e.jsx(Yn,{className:"h-3.5 w-3.5 text-muted-foreground"}),!pe.email&&!pe.phone&&e.jsx("span",{className:"text-muted-foreground",children:"—"})]})}),e.jsx(gt,{className:"hidden lg:table-cell",children:pe.experience_years!=null?`${pe.experience_years} yr`:"—"}),e.jsx(gt,{className:"hidden lg:table-cell",children:pe.annual_production||"—"}),e.jsx(gt,{className:"hidden lg:table-cell",children:ct>0?e.jsxs(Xe,{variant:"secondary",className:"text-xs",children:[ct," campaign",ct>1?"s":""]}):e.jsx("span",{className:"text-muted-foreground text-xs",children:"None"})}),e.jsx(gt,{children:e.jsx(H,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-destructive",onClick:Ue=>{Ue.stopPropagation(),l.mutate(pe.id)},children:e.jsx(Dr,{className:"h-3.5 w-3.5"})})})]},pe.id)})})]})}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[J.size>0&&e.jsxs("span",{className:"font-medium text-foreground",children:[J.size," selected · "]}),Le.length," of ",r.length," prospects"]}),e.jsx(bs,{open:re,onOpenChange:ie,children:e.jsxs(vs,{className:"sm:max-w-md",children:[e.jsx(Cs,{children:e.jsx(Ns,{children:"Add to Campaign"})}),e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Add ",e.jsx("span",{className:"font-medium text-foreground",children:J.size})," selected prospect(s) to a recruiting campaign drip."]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Campaign"}),e.jsxs(Bs,{value:ce,onValueChange:ne,children:[e.jsx(Os,{children:e.jsx(Us,{placeholder:"Select a campaign..."})}),e.jsx(Fs,{children:be.map(pe=>e.jsxs(pt,{value:pe.id,children:[pe.name," ",e.jsxs("span",{className:"text-muted-foreground ml-1",children:["(",pe.warmth_level,")"]})]},pe.id))})]})]})]}),e.jsxs(wn,{children:[e.jsx(H,{variant:"outline",onClick:()=>ie(!1),children:"Cancel"}),e.jsx(H,{onClick:()=>De.mutate(),disabled:!ce||De.isPending,children:De.isPending?"Adding...":"Add to Campaign"})]})]})}),e.jsx(tvt,{open:d,onOpenChange:h,stages:t,onSubmit:pe=>a.mutate(pe),isSubmitting:a.isPending}),e.jsx(ivt,{prospect:m,stages:t,brokerageId:s,open:x,onOpenChange:y,onUpdate:pe=>{i.mutate(pe),p(tt=>tt?{...tt,...pe}:null)},onDelete:pe=>l.mutate(pe)}),e.jsx(ovt,{open:_,onOpenChange:b,brokerageId:s,stages:t})]})}function cvt({brokerageId:s}){const{stages:t,prospects:r,isLoading:n}=Hz(s),a=S.useMemo(()=>{if(!t.length||!r.length)return null;const i=r.length,l=t.find(j=>j.name==="Signed"),o=t.find(j=>j.name==="Onboarded"),c=r.filter(j=>j.stage_id===(l==null?void 0:l.id)||j.stage_id===(o==null?void 0:o.id)).length,d=i>0?(c/i*100).toFixed(1):"0",h=new Date,m=i>0?Math.round(r.reduce((j,k)=>j+Jy(h,new Date(k.created_at)),0)/i):0,p=t.map(j=>({...j,count:r.filter(k=>k.stage_id===j.id).length})),x={};r.forEach(j=>{const k=j.source||"unknown";x[k]=(x[k]||0)+1});const y=Object.entries(x).sort((j,k)=>k[1]-j[1]),_=new Date;_.setDate(_.getDate()-30);const b=r.filter(j=>new Date(j.created_at)>=_).length;return{total:i,signed:c,conversionRate:d,avgDays:m,byStage:p,bySrc:y,recentCount:b}},[t,r]);return n?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):a?e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(ke,{children:e.jsx(Oe,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-blue-500/10 flex items-center justify-center",children:e.jsx(Ar,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:a.total}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Total Prospects"})]})]})})}),e.jsx(ke,{children:e.jsx(Oe,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-green-500/10 flex items-center justify-center",children:e.jsx(al,{className:"h-5 w-5 text-green-600"})}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-2xl font-bold",children:[a.conversionRate,"%"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Conversion Rate"})]})]})})}),e.jsx(ke,{children:e.jsx(Oe,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-amber-500/10 flex items-center justify-center",children:e.jsx(Pn,{className:"h-5 w-5 text-amber-600"})}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-2xl font-bold",children:[a.avgDays,"d"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Avg Days in Pipeline"})]})]})})}),e.jsx(ke,{children:e.jsx(Oe,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-violet-500/10 flex items-center justify-center",children:e.jsx(Wu,{className:"h-5 w-5 text-violet-600"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:a.recentCount}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Added (30 days)"})]})]})})})]}),e.jsxs("div",{className:"grid md:grid-cols-2 gap-6",children:[e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-base",children:"Pipeline Breakdown"})}),e.jsx(Oe,{className:"space-y-3",children:a.byStage.map(i=>{const l=a.total>0?i.count/a.total*100:0;return e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-2.5 w-2.5 rounded-full",style:{backgroundColor:i.color}}),e.jsx("span",{children:i.name})]}),e.jsx("span",{className:"font-medium",children:i.count})]}),e.jsx("div",{className:"h-2 bg-muted rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${l}%`,backgroundColor:i.color}})})]},i.id)})})]}),e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-base",children:"Lead Sources"})}),e.jsxs(Oe,{className:"space-y-3",children:[a.bySrc.map(([i,l])=>e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Xe,{variant:"secondary",className:"capitalize",children:i.replace(/_/g," ")}),e.jsx("span",{className:"text-sm font-medium",children:l})]},i)),a.bySrc.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No source data"})]})]})]})]}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"No prospect data yet. Add prospects to see metrics."})}const hzs=["Outreach","Follow-up","Interview","Offer","Referral","Other"];function dvt({brokerageId:s}){const{toast:t}=li(),{user:r}=Ms(),n=ns(),[a,i]=S.useState(null),[l,o]=S.useState(null),[c,d]=S.useState(!1),[h,m]=S.useState(null),{data:p=[],isLoading:x}=yt({queryKey:["recruit-email-templates-manage",s],queryFn:async()=>{const{data:E,error:A}=await V.from("recruit_email_templates").select("*").or(`brokerage_id.is.null,brokerage_id.eq.${s}`).order("sort_order");if(A)throw A;return E}}),y=Pt({mutationFn:async E=>{if(E.id){const{error:A}=await V.from("recruit_email_templates").update({category:E.category,title:E.title,subject:E.subject,body:E.body}).eq("id",E.id);if(A)throw A}else{const{error:A}=await V.from("recruit_email_templates").insert({brokerage_id:s,category:E.category||"Outreach",title:E.title,subject:E.subject,body:E.body,created_by:r==null?void 0:r.id,sort_order:100});if(A)throw A}},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-email-templates-manage",s]}),n.invalidateQueries({queryKey:["recruit-email-templates"]}),t({title:"Template saved"}),d(!1),m(null)},onError:E=>t({title:"Save failed",description:E.message,variant:"destructive"})}),_=Pt({mutationFn:async E=>{const{error:A}=await V.from("recruit_email_templates").delete().eq("id",E);if(A)throw A},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-email-templates-manage",s]}),n.invalidateQueries({queryKey:["recruit-email-templates"]}),t({title:"Template deleted"})},onError:E=>t({title:"Delete failed",description:E.message,variant:"destructive"})}),b=(E,A)=>{navigator.clipboard.writeText(E),i(A),t({title:"Copied to clipboard!"}),setTimeout(()=>i(null),2e3)},j=()=>{m({category:"Outreach",title:"",subject:"",body:""}),d(!0)},k=E=>{m(E),d(!0)},T=Array.from(new Set(p.map(E=>E.category)));return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 flex-wrap",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Pre-built and custom recruiting templates. Built-in templates are global; your custom ones are private to this brokerage."}),e.jsxs(H,{onClick:j,size:"sm",className:"gap-1.5",children:[e.jsx(Ys,{className:"h-4 w-4"})," New Template"]})]}),x?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(is,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):T.map(E=>e.jsxs("div",{className:"space-y-3",children:[e.jsxs("h3",{className:"font-semibold text-sm flex items-center gap-2",children:[e.jsx(er,{className:"h-4 w-4"})," ",E]}),p.filter(A=>A.category===E).map(A=>{const D=A.brokerage_id!==null;return e.jsxs(ke,{className:`transition-all ${l===A.id?"ring-2 ring-primary/20":"hover:shadow-sm"}`,children:[e.jsx(Ot,{className:"pb-2 cursor-pointer",onClick:()=>o(l===A.id?null:A.id),children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs(zt,{className:"text-sm flex items-center gap-2",children:[e.jsx("span",{className:"truncate",children:A.title}),!D&&e.jsx(Xe,{variant:"secondary",className:"text-[10px] shrink-0",children:"Built-in"}),D&&e.jsx(Xe,{className:"text-[10px] shrink-0",children:"Custom"})]}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5 truncate",children:["Subject: ",A.subject]})]}),e.jsx(Xe,{variant:"outline",className:"text-[10px] shrink-0",children:A.category})]})}),l===A.id&&e.jsxs(Oe,{className:"pt-0 space-y-3",children:[e.jsxs("div",{className:"bg-muted/50 rounded-lg p-4",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground mb-1",children:"Subject Line:"}),e.jsx("p",{className:"text-sm mb-3",children:A.subject}),e.jsx("p",{className:"text-xs font-medium text-muted-foreground mb-1",children:"Body:"}),e.jsx("pre",{className:"text-sm whitespace-pre-wrap font-sans",children:A.body})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(H,{size:"sm",variant:"outline",onClick:()=>b(A.subject,A.id+"-s"),children:[a===A.id+"-s"?e.jsx(va,{className:"h-3.5 w-3.5 mr-1"}):e.jsx(ui,{className:"h-3.5 w-3.5 mr-1"}),"Copy Subject"]}),e.jsxs(H,{size:"sm",variant:"outline",onClick:()=>b(A.body,A.id+"-b"),children:[a===A.id+"-b"?e.jsx(va,{className:"h-3.5 w-3.5 mr-1"}):e.jsx(ui,{className:"h-3.5 w-3.5 mr-1"}),"Copy Body"]}),D&&e.jsxs(e.Fragment,{children:[e.jsxs(H,{size:"sm",variant:"outline",onClick:()=>k(A),children:[e.jsx(ni,{className:"h-3.5 w-3.5 mr-1"})," Edit"]}),e.jsxs(H,{size:"sm",variant:"outline",className:"text-destructive hover:text-destructive",onClick:()=>{confirm("Delete this template?")&&_.mutate(A.id)},children:[e.jsx(Dr,{className:"h-3.5 w-3.5 mr-1"})," Delete"]})]})]})]})]},A.id)})]},E)),e.jsx(bs,{open:c,onOpenChange:d,children:e.jsxs(vs,{className:"max-w-2xl",children:[e.jsx(Cs,{children:e.jsx(Ns,{children:h!=null&&h.id?"Edit Template":"New Template"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs",children:"Title"}),e.jsx(Se,{value:(h==null?void 0:h.title)||"",onChange:E=>m(A=>({...A,title:E.target.value})),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs",children:"Category"}),e.jsx("select",{value:(h==null?void 0:h.category)||"Outreach",onChange:E=>m(A=>({...A,category:E.target.value})),className:"mt-1 flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm",children:hzs.map(E=>e.jsx("option",{value:E,children:E},E))})]})]}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs",children:"Subject"}),e.jsx(Se,{value:(h==null?void 0:h.subject)||"",onChange:E=>m(A=>({...A,subject:E.target.value})),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs",children:"Body"}),e.jsx(vr,{value:(h==null?void 0:h.body)||"",onChange:E=>m(A=>({...A,body:E.target.value})),rows:12,className:"mt-1 font-sans",placeholder:`Hi [First Name], ... Best, [Your Name]`}),e.jsx("p",{className:"text-[11px] text-muted-foreground mt-1",children:"Available placeholders: [First Name], [Your Name], [Brokerage Name]"})]})]}),e.jsxs(wn,{children:[e.jsx(H,{variant:"ghost",onClick:()=>d(!1),children:"Cancel"}),e.jsxs(H,{onClick:()=>y.mutate(h||{}),disabled:y.isPending||!(h!=null&&h.title)||!(h!=null&&h.subject)||!(h!=null&&h.body),children:[y.isPending&&e.jsx(is,{className:"h-4 w-4 mr-2 animate-spin"}),"Save Template"]})]})]})})]})}const CWe={call:Yn,email:er,text:Gi,meeting:Nn,note:kn};function uvt({brokerageId:s}){const{data:t,isLoading:r}=yt({queryKey:["recruit-activity-report",s],queryFn:async()=>{const{data:n,error:a}=await V.from("recruit_prospects").select("id, created_by").eq("brokerage_id",s);if(a)throw a;const i=(n==null?void 0:n.map(x=>x.id))||[];if(i.length===0)return{recruiters:[],recentActivities:[]};const{data:l,error:o}=await V.from("recruit_activities").select("*").in("prospect_id",i).order("created_at",{ascending:!1});if(o)throw o;const c=[...new Set([...n.map(x=>x.created_by),...(l||[]).map(x=>x.created_by)])],{data:d}=await V.from("profiles").select("id, name, email").in("id",c),h=Object.fromEntries((d||[]).map(x=>[x.id,x])),m=mue(new Date,30);return{recruiters:c.map(x=>{var k,T;const y=(l||[]).filter(E=>E.created_by===x),_=y.filter(E=>new Date(E.created_at)>=m),b={};_.forEach(E=>{b[E.activity_type]=(b[E.activity_type]||0)+1});const j=n.filter(E=>E.created_by===x).length;return{id:x,name:((k=h[x])==null?void 0:k.name)||"Unknown",email:((T=h[x])==null?void 0:T.email)||"",totalActivities:y.length,recentActivities:_.length,byType:b,prospectsCreated:j}}).sort((x,y)=>y.recentActivities-x.recentActivities),recentActivities:(l||[]).slice(0,20)}},enabled:!!s});return r?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):t!=null&&t.recruiters.length?e.jsxs("div",{className:"space-y-6",children:[e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-base",children:"Recruiter Leaderboard (Last 30 Days)"})}),e.jsx(Oe,{className:"space-y-4",children:t.recruiters.map((n,a)=>e.jsxs("div",{className:"flex items-center gap-4 p-3 rounded-lg bg-muted/30",children:[e.jsx("div",{className:"flex items-center justify-center h-8 w-8 rounded-full bg-primary/10 text-primary font-bold text-sm",children:a+1}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(io,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"font-medium text-sm",children:n.name})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:Object.entries(n.byType).map(([i,l])=>{const o=CWe[i]||kn;return e.jsxs(Xe,{variant:"outline",className:"text-[10px] gap-1",children:[e.jsx(o,{className:"h-2.5 w-2.5"})," ",l," ",i,l!==1?"s":""]},i)})})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("p",{className:"text-lg font-bold",children:n.recentActivities}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"activities"})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("p",{className:"text-lg font-bold",children:n.prospectsCreated}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"prospects"})]})]},n.id))})]}),e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-base",children:"Recent Activity"})}),e.jsx(Oe,{className:"space-y-3",children:t.recentActivities.map(n=>{const a=CWe[n.activity_type]||kn;return e.jsxs("div",{className:"flex items-start gap-3 text-sm",children:[e.jsx("div",{className:"h-7 w-7 rounded-full bg-muted flex items-center justify-center flex-shrink-0 mt-0.5",children:e.jsx(a,{className:"h-3.5 w-3.5 text-muted-foreground"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium",children:n.title}),n.description&&e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:n.description}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:As(new Date(n.created_at),"MMM d, h:mm a")})]})]},n.id)})})]})]}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"No recruiter activity yet."})}function hvt({brokerageId:s}){const{toast:t}=li(),r=ns(),[n,a]=S.useState(!1),[i,l]=S.useState({first_name:"",last_name:"",email:"",phone:"",current_brokerage:"",notes:""}),{data:o=[],isLoading:c}=yt({queryKey:["recruit-referrals",s],queryFn:async()=>{const{data:b,error:j}=await V.from("recruit_referrals").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1});if(j)throw j;return b}}),d=[...new Set(o.map(b=>b.referred_by))],{data:h=[]}=yt({queryKey:["referral-profiles",d],queryFn:async()=>{if(!d.length)return[];const{data:b}=await V.from("profiles").select("id, name, email").in("id",d);return b||[]},enabled:d.length>0}),m=Object.fromEntries(h.map(b=>[b.id,b])),p=Pt({mutationFn:async b=>{const{data:{user:j}}=await V.auth.getUser();if(!j)throw new Error("Not authenticated");const{error:k}=await V.from("recruit_referrals").insert({brokerage_id:s,referred_by:j.id,referee_first_name:b.first_name,referee_last_name:b.last_name||null,referee_email:b.email||null,referee_phone:b.phone||null,referee_current_brokerage:b.current_brokerage||null,notes:b.notes||null});if(k)throw k},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-referrals",s]}),t({title:"Referral submitted!"}),l({first_name:"",last_name:"",email:"",phone:"",current_brokerage:"",notes:""}),a(!1)},onError:b=>t({title:"Error",description:b.message,variant:"destructive"})}),x=Pt({mutationFn:async({id:b,status:j,incentive_status:k})=>{const T={updated_at:new Date().toISOString()};j&&(T.status=j),k&&(T.incentive_status=k);const{error:E}=await V.from("recruit_referrals").update(T).eq("id",b);if(E)throw E},onSuccess:()=>r.invalidateQueries({queryKey:["recruit-referrals",s]})}),y=b=>b==="approved"||b==="signed"?e.jsx(va,{className:"h-3 w-3"}):b==="rejected"?e.jsx(kd,{className:"h-3 w-3"}):e.jsx(Pn,{className:"h-3 w-3"}),_=b=>b==="approved"||b==="signed"||b==="paid"?"bg-green-500/10 text-green-600 border-green-200":b==="rejected"?"bg-red-500/10 text-red-600 border-red-200":"bg-amber-500/10 text-amber-600 border-amber-200";return c?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:[o.length," referral",o.length!==1?"s":""]}),e.jsxs(H,{onClick:()=>a(!0),children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"})," Submit Referral"]})]}),o.length===0?e.jsxs(ke,{className:"py-12 text-center",children:[e.jsx(Vl,{className:"h-10 w-10 mx-auto text-muted-foreground mb-3"}),e.jsx("p",{className:"text-muted-foreground",children:"No referrals yet. Agents can refer potential recruits here."})]}):e.jsx("div",{className:"space-y-3",children:o.map(b=>{var j;return e.jsx(ke,{className:"p-4",children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsxs("span",{className:"font-medium",children:[b.referee_first_name," ",b.referee_last_name]}),e.jsxs(Xe,{variant:"outline",className:_(b.status),children:[y(b.status)," ",b.status]}),b.incentive_status&&e.jsxs(Xe,{variant:"outline",className:_(b.incentive_status),children:[e.jsx(Di,{className:"h-3 w-3 mr-1"})," ",b.incentive_status]})]}),e.jsxs("div",{className:"text-xs text-muted-foreground space-y-0.5",children:[b.referee_email&&e.jsx("p",{children:b.referee_email}),b.referee_phone&&e.jsx("p",{children:b.referee_phone}),b.referee_current_brokerage&&e.jsxs("p",{children:["Currently at: ",b.referee_current_brokerage]}),e.jsxs("p",{children:["Referred by: ",((j=m[b.referred_by])==null?void 0:j.name)||"Unknown"," • ",As(new Date(b.created_at),"MMM d, yyyy")]})]}),b.notes&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1 italic",children:b.notes})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsxs(Bs,{value:b.status,onValueChange:k=>x.mutate({id:b.id,status:k}),children:[e.jsx(Os,{className:"h-7 text-xs w-[110px]",children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"pending",children:"Pending"}),e.jsx(pt,{value:"contacted",children:"Contacted"}),e.jsx(pt,{value:"approved",children:"Approved"}),e.jsx(pt,{value:"signed",children:"Signed"}),e.jsx(pt,{value:"rejected",children:"Rejected"})]})]}),e.jsxs(Bs,{value:b.incentive_status||"pending",onValueChange:k=>x.mutate({id:b.id,incentive_status:k}),children:[e.jsx(Os,{className:"h-7 text-xs w-[100px]",children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"pending",children:"Unpaid"}),e.jsx(pt,{value:"paid",children:"Paid"}),e.jsx(pt,{value:"n/a",children:"N/A"})]})]})]})]})},b.id)})}),e.jsx(bs,{open:n,onOpenChange:a,children:e.jsxs(vs,{children:[e.jsx(Cs,{children:e.jsx(Ns,{children:"Submit a Recruit Referral"})}),e.jsxs("form",{onSubmit:b=>{b.preventDefault(),p.mutate(i)},className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ue,{children:"First Name *"}),e.jsx(Se,{required:!0,value:i.first_name,onChange:b=>l(j=>({...j,first_name:b.target.value}))})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Last Name"}),e.jsx(Se,{value:i.last_name,onChange:b=>l(j=>({...j,last_name:b.target.value}))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ue,{children:"Email"}),e.jsx(Se,{type:"email",value:i.email,onChange:b=>l(j=>({...j,email:b.target.value}))})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Phone"}),e.jsx(Se,{value:i.phone,onChange:b=>l(j=>({...j,phone:b.target.value}))})]})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Current Brokerage"}),e.jsx(Se,{value:i.current_brokerage,onChange:b=>l(j=>({...j,current_brokerage:b.target.value}))})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Notes"}),e.jsx(vr,{value:i.notes,onChange:b=>l(j=>({...j,notes:b.target.value})),rows:2})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(H,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(H,{type:"submit",disabled:p.isPending,children:"Submit"})]})]})]})})]})}function mvt({brokerageId:s}){const{toast:t}=li(),r=ns(),[n,a]=S.useState(!1),{data:i}=yt({queryKey:["brokerage-recruit-form",s],queryFn:async()=>{const{data:p,error:x}=await V.from("brokerages").select("id, name, recruit_form_slug, recruit_form_enabled").eq("id",s).single();if(x)throw x;return p}}),{data:l=[]}=yt({queryKey:["recruit-interest-submissions",s],queryFn:async()=>{const{data:p,error:x}=await V.from("recruit_interest_submissions").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1});if(x)throw x;return p}}),o=Pt({mutationFn:async p=>{const{error:x}=await V.from("brokerages").update({recruit_form_enabled:p}).eq("id",s);if(x)throw x},onSuccess:()=>{r.invalidateQueries({queryKey:["brokerage-recruit-form",s]}),t({title:i!=null&&i.recruit_form_enabled?"Form disabled":"Form enabled"})}}),c=Pt({mutationFn:async({id:p,status:x})=>{const{error:y}=await V.from("recruit_interest_submissions").update({status:x}).eq("id",p);if(y)throw y},onSuccess:()=>r.invalidateQueries({queryKey:["recruit-interest-submissions",s]})}),d=`https://bestbrokerage.relevelup.com/join-brokerage/${(i==null?void 0:i.recruit_form_slug)||""}`,h=()=>{navigator.clipboard.writeText(d),a(!0),t({title:"Link copied!"}),setTimeout(()=>a(!1),2e3)},m=p=>p==="contacted"||p==="converted"?"bg-green-500/10 text-green-600":p==="dismissed"?"bg-red-500/10 text-red-600":"bg-blue-500/10 text-blue-600";return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-base",children:"Public Interest Form"})}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ue,{children:"Enable Public Form"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Allow agents to express interest in joining via a public link"})]}),e.jsx(Or,{checked:(i==null?void 0:i.recruit_form_enabled)||!1,onCheckedChange:p=>o.mutate(p)})]}),(i==null?void 0:i.recruit_form_enabled)&&e.jsxs("div",{className:"flex items-center gap-2 p-3 bg-muted/50 rounded-lg",children:[e.jsx("code",{className:"text-xs flex-1 truncate",children:d}),e.jsx(H,{size:"sm",variant:"outline",onClick:h,children:n?e.jsx(va,{className:"h-3.5 w-3.5"}):e.jsx(ui,{className:"h-3.5 w-3.5"})}),e.jsx(H,{size:"sm",variant:"outline",asChild:!0,children:e.jsx("a",{href:d,target:"_blank",rel:"noopener noreferrer",children:e.jsx(gn,{className:"h-3.5 w-3.5"})})})]})]})]}),e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsxs(zt,{className:"text-base",children:["Interest Submissions (",l.length,")"]})}),e.jsx(Oe,{children:l.length===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx(Vl,{className:"h-8 w-8 mx-auto text-muted-foreground mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No submissions yet"})]}):e.jsx("div",{className:"space-y-3",children:l.map(p=>e.jsxs("div",{className:"flex items-start justify-between gap-4 p-3 border rounded-lg",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsxs("span",{className:"font-medium text-sm",children:[p.first_name," ",p.last_name]}),e.jsx(Xe,{variant:"outline",className:m(p.status),children:p.status})]}),e.jsxs("div",{className:"flex flex-wrap gap-3 text-xs text-muted-foreground",children:[p.email&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(er,{className:"h-3 w-3"}),p.email]}),p.phone&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Yn,{className:"h-3 w-3"}),p.phone]}),p.current_brokerage&&e.jsxs("span",{children:["From: ",p.current_brokerage]}),p.experience_years&&e.jsxs("span",{children:[p.experience_years,"yr exp"]})]}),p.why_interested&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1 italic",children:['"',p.why_interested,'"']}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:As(new Date(p.created_at),"MMM d, yyyy h:mm a")})]}),e.jsxs(Bs,{value:p.status,onValueChange:x=>c.mutate({id:p.id,status:x}),children:[e.jsx(Os,{className:"h-7 text-xs w-[110px]",children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"new",children:"New"}),e.jsx(pt,{value:"contacted",children:"Contacted"}),e.jsx(pt,{value:"converted",children:"Converted"}),e.jsx(pt,{value:"dismissed",children:"Dismissed"})]})]})]},p.id))})})]})]})}function fvt({brokerageId:s}){const{toast:t}=li(),r=ns(),[n,a]=S.useState(!1),[i,l]=S.useState({prospect_id:"",title:"",description:"",due_date:As(Lc(new Date,1),"yyyy-MM-dd'T'HH:mm")}),[o,c]=S.useState("pending"),{data:d=[]}=yt({queryKey:["recruit-prospects-list",s],queryFn:async()=>{const{data:A,error:D}=await V.from("recruit_prospects").select("id, first_name, last_name").eq("brokerage_id",s).order("first_name");if(D)throw D;return A}}),{data:h=[],isLoading:m}=yt({queryKey:["recruit-follow-ups",s],queryFn:async()=>{const A=d.map(z=>z.id);if(!A.length)return[];const{data:D,error:R}=await V.from("recruit_follow_ups").select("*").in("prospect_id",A).order("due_date");if(R)throw R;return D},enabled:d.length>0}),p=Object.fromEntries(d.map(A=>[A.id,A])),x=Pt({mutationFn:async A=>{const{data:{user:D}}=await V.auth.getUser();if(!D)throw new Error("Not authenticated");const{error:R}=await V.from("recruit_follow_ups").insert({prospect_id:A.prospect_id,assigned_to:D.id,title:A.title,description:A.description||null,due_date:new Date(A.due_date).toISOString()});if(R)throw R},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-follow-ups",s]}),t({title:"Follow-up scheduled"}),l({prospect_id:"",title:"",description:"",due_date:As(Lc(new Date,1),"yyyy-MM-dd'T'HH:mm")}),a(!1)},onError:A=>t({title:"Error",description:A.message,variant:"destructive"})}),y=Pt({mutationFn:async({id:A,completed:D})=>{const{error:R}=await V.from("recruit_follow_ups").update({completed_at:D?new Date().toISOString():null}).eq("id",A);if(R)throw R},onSuccess:()=>r.invalidateQueries({queryKey:["recruit-follow-ups",s]})}),_=h.filter(A=>o==="pending"?!A.completed_at:o==="completed"?!!A.completed_at:!0),b=_.filter(A=>!A.completed_at&&__(new Date(A.due_date))&&!cm(new Date(A.due_date))),j=_.filter(A=>!A.completed_at&&cm(new Date(A.due_date))),k=_.filter(A=>!A.completed_at&&!__(new Date(A.due_date))&&!cm(new Date(A.due_date))),T=_.filter(A=>!!A.completed_at),E=A=>{const D=p[A.prospect_id],R=!A.completed_at&&__(new Date(A.due_date))&&!cm(new Date(A.due_date));return e.jsxs("div",{className:"flex items-start gap-3 p-3 border rounded-lg",children:[e.jsx(ao,{checked:!!A.completed_at,onCheckedChange:z=>y.mutate({id:A.id,completed:z}),className:"mt-0.5"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:`text-sm font-medium ${A.completed_at?"line-through text-muted-foreground":""}`,children:A.title}),A.description&&e.jsx("p",{className:"text-xs text-muted-foreground",children:A.description}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 text-xs text-muted-foreground",children:[D&&e.jsxs(Xe,{variant:"secondary",className:"text-[10px]",children:[D.first_name," ",D.last_name]}),e.jsxs("span",{className:`flex items-center gap-1 ${R?"text-destructive font-medium":""}`,children:[R?e.jsx(wo,{className:"h-3 w-3"}):e.jsx(Nn,{className:"h-3 w-3"}),As(new Date(A.due_date),"MMM d, h:mm a")]}),A.is_automated&&e.jsx(Xe,{variant:"outline",className:"text-[10px]",children:"Auto"})]})]})]},A.id)};return m?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"flex gap-2",children:["pending","completed","all"].map(A=>e.jsxs(H,{size:"sm",variant:o===A?"default":"outline",onClick:()=>c(A),className:"capitalize text-xs",children:[A," ",A==="pending"&&b.length+j.length+k.length>0&&`(${b.length+j.length+k.length})`]},A))}),e.jsxs(H,{size:"sm",onClick:()=>a(!0),children:[e.jsx(Ys,{className:"h-4 w-4 mr-1"})," Add Follow-up"]})]}),o!=="completed"&&b.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h3",{className:"text-xs font-semibold text-destructive flex items-center gap-1",children:[e.jsx(wo,{className:"h-3.5 w-3.5"})," Overdue (",b.length,")"]}),b.map(E)]}),o!=="completed"&&j.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h3",{className:"text-xs font-semibold text-amber-600 flex items-center gap-1",children:[e.jsx(Pn,{className:"h-3.5 w-3.5"})," Today (",j.length,")"]}),j.map(E)]}),o!=="completed"&&k.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h3",{className:"text-xs font-semibold text-muted-foreground flex items-center gap-1",children:[e.jsx(Nn,{className:"h-3.5 w-3.5"})," Upcoming (",k.length,")"]}),k.map(E)]}),o!=="pending"&&T.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h3",{className:"text-xs font-semibold text-muted-foreground flex items-center gap-1",children:[e.jsx(va,{className:"h-3.5 w-3.5"})," Completed (",T.length,")"]}),T.map(E)]}),_.length===0&&e.jsxs("p",{className:"text-sm text-muted-foreground text-center py-8",children:["No follow-ups ",o!=="all"?`(${o})`:""]}),e.jsx(bs,{open:n,onOpenChange:a,children:e.jsxs(vs,{children:[e.jsx(Cs,{children:e.jsx(Ns,{children:"Schedule Follow-up"})}),e.jsxs("form",{onSubmit:A=>{A.preventDefault(),x.mutate(i)},className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ue,{children:"Prospect *"}),e.jsxs("select",{className:"w-full rounded-md border border-input bg-background px-3 py-2 text-sm",required:!0,value:i.prospect_id,onChange:A=>l(D=>({...D,prospect_id:A.target.value})),children:[e.jsx("option",{value:"",children:"Select prospect..."}),d.map(A=>e.jsxs("option",{value:A.id,children:[A.first_name," ",A.last_name]},A.id))]})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Task *"}),e.jsx(Se,{required:!0,value:i.title,onChange:A=>l(D=>({...D,title:A.target.value})),placeholder:"e.g. Follow-up call"})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Details"}),e.jsx(vr,{value:i.description,onChange:A=>l(D=>({...D,description:A.target.value})),rows:2})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Due Date *"}),e.jsx(Se,{type:"datetime-local",required:!0,value:i.due_date,onChange:A=>l(D=>({...D,due_date:A.target.value}))})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(H,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(H,{type:"submit",disabled:x.isPending,children:"Schedule"})]})]})]})})]})}const mzs=[{title:"Competitive Splits",description:"Industry-leading commission structure",icon:"💰"},{title:"Tech & Tools",description:"CRM, marketing automation, and more",icon:"🛠️"},{title:"Training & Support",description:"Ongoing mentorship and education",icon:"📚"}];function pvt({brokerageId:s}){const{toast:t}=li(),r=ns(),[n,a]=S.useState(null),{data:i,isLoading:l}=yt({queryKey:["recruit-landing-settings",s],queryFn:async()=>{const{data:b,error:j}=await V.from("recruit_landing_page_settings").select("*").eq("brokerage_id",s).maybeSingle();if(j)throw j;return b}}),[o,c]=S.useState({brokerage_id:s,hero_headline:"Join Our Team",hero_subtext:"Take your real estate career to the next level.",hero_image_url:null,logo_url:null,primary_color:"#406E71",accent_color:"#2a4c64",benefits:mzs,testimonials:[],gallery_images:[],calculator_enabled:!1,calculator_config:{headline:"See What You Could Earn With Us",subtext:"Confidential 60-second calculator — no signup required.",commission_split_pct:80,cap_amount:16e3,post_cap_split_pct:100,monthly_fee:99,transaction_fee:0,show_email_capture:!0,email_capture_label:"Want the full breakdown? Enter your email."},lead_magnet_enabled:!1,lead_magnet_config:{title:"Get the Full Comp Plan PDF",description:"See exactly how splits, caps, and fees work — no call required.",button_text:"Email Me the PDF",pdf_url:null},form_style:"classic",confidential_messaging:!0});S.useEffect(()=>{i&&c({id:i.id,brokerage_id:i.brokerage_id,hero_headline:i.hero_headline,hero_subtext:i.hero_subtext||"",hero_image_url:i.hero_image_url,logo_url:i.logo_url,primary_color:i.primary_color,accent_color:i.accent_color,benefits:i.benefits||[],testimonials:i.testimonials||[],gallery_images:i.gallery_images||[],calculator_enabled:i.calculator_enabled??!1,calculator_config:i.calculator_config||{},lead_magnet_enabled:i.lead_magnet_enabled??!1,lead_magnet_config:i.lead_magnet_config||{},form_style:i.form_style||"classic",confidential_messaging:i.confidential_messaging??!0})},[i]);const d=Pt({mutationFn:async()=>{const b={brokerage_id:s,hero_headline:o.hero_headline,hero_subtext:o.hero_subtext,hero_image_url:o.hero_image_url,logo_url:o.logo_url,primary_color:o.primary_color,accent_color:o.accent_color,benefits:JSON.parse(JSON.stringify(o.benefits)),testimonials:JSON.parse(JSON.stringify(o.testimonials)),gallery_images:JSON.parse(JSON.stringify(o.gallery_images)),calculator_enabled:o.calculator_enabled,calculator_config:JSON.parse(JSON.stringify(o.calculator_config)),lead_magnet_enabled:o.lead_magnet_enabled,lead_magnet_config:JSON.parse(JSON.stringify(o.lead_magnet_config)),form_style:o.form_style,confidential_messaging:o.confidential_messaging,updated_at:new Date().toISOString()};if(o.id){const{error:j}=await V.from("recruit_landing_page_settings").update(b).eq("id",o.id);if(j)throw j}else{const{error:j}=await V.from("recruit_landing_page_settings").insert(b);if(j)throw j}},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-landing-settings",s]}),t({title:"Landing page saved!"})},onError:b=>t({title:"Error",description:b.message,variant:"destructive"})}),h=async(b,j)=>{const k=b.name.split(".").pop(),T=`${s}/${j}-${Date.now()}.${k}`,{error:E}=await V.storage.from("recruit-landing").upload(T,b);if(E)throw E;const{data:{publicUrl:A}}=V.storage.from("recruit-landing").getPublicUrl(T);return A},m=async(b,j)=>{var T;const k=(T=b.target.files)==null?void 0:T[0];if(k){a(j);try{const E=await h(k,j);c(A=>({...A,[j]:E})),t({title:"Image uploaded!"})}catch(E){t({title:"Upload failed",description:E.message,variant:"destructive"})}finally{a(null)}}},p=async b=>{var k;const j=(k=b.target.files)==null?void 0:k[0];if(j){a("gallery");try{const T=await h(j,"gallery");c(E=>({...E,gallery_images:[...E.gallery_images,T]})),t({title:"Gallery image added!"})}catch(T){t({title:"Upload failed",description:T.message,variant:"destructive"})}finally{a(null)}}},x=async(b,j)=>{var T;const k=(T=b.target.files)==null?void 0:T[0];if(k){a(`testimonial-${j}`);try{const E=await h(k,`testimonial-${j}`);c(A=>{const D=[...A.testimonials];return D[j]={...D[j],photo_url:E},{...A,testimonials:D}})}catch(E){t({title:"Upload failed",description:E.message,variant:"destructive"})}finally{a(null)}}},{data:y}=yt({queryKey:["brokerage-slug-for-landing",s],queryFn:async()=>{const{data:b,error:j}=await V.from("brokerages").select("recruit_form_slug, recruit_form_enabled").eq("id",s).single();if(j)throw j;return b}}),_=`https://bestbrokerage.relevelup.com/join-brokerage/${(y==null?void 0:y.recruit_form_slug)||""}`;return l?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):e.jsxs("div",{className:"space-y-6",children:[(y==null?void 0:y.recruit_form_enabled)&&e.jsxs("div",{className:"flex items-center gap-2 p-3 bg-muted/50 rounded-lg border",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Live page:"}),e.jsx("code",{className:"text-xs flex-1 truncate",children:_}),e.jsx(H,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:_,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(gn,{className:"h-3.5 w-3.5 mr-1"})," Preview"]})})]}),e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-base",children:"Branding"})}),e.jsx(Oe,{className:"space-y-4",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(ue,{children:"Logo"}),e.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[o.logo_url&&e.jsx("img",{src:o.logo_url,alt:"Logo",className:"h-10 w-auto rounded"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(H,{variant:"outline",size:"sm",asChild:!0,disabled:n==="logo_url",children:e.jsxs("span",{children:[e.jsx(Ea,{className:"h-3.5 w-3.5 mr-1"}),n==="logo_url"?"Uploading...":"Upload Logo"]})}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:b=>m(b,"logo_url")})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ue,{children:"Primary Color"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("input",{type:"color",value:o.primary_color,onChange:b=>c(j=>({...j,primary_color:b.target.value})),className:"h-9 w-12 rounded border cursor-pointer"}),e.jsx(Se,{value:o.primary_color,onChange:b=>c(j=>({...j,primary_color:b.target.value})),className:"font-mono text-xs"})]})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Accent Color"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("input",{type:"color",value:o.accent_color,onChange:b=>c(j=>({...j,accent_color:b.target.value})),className:"h-9 w-12 rounded border cursor-pointer"}),e.jsx(Se,{value:o.accent_color,onChange:b=>c(j=>({...j,accent_color:b.target.value})),className:"font-mono text-xs"})]})]})]})]})})]}),e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-base",children:"Hero Section"})}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ue,{children:"Headline"}),e.jsx(Se,{value:o.hero_headline,onChange:b=>c(j=>({...j,hero_headline:b.target.value})),placeholder:"Join Our Team"})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Subtext"}),e.jsx(vr,{value:o.hero_subtext,onChange:b=>c(j=>({...j,hero_subtext:b.target.value})),rows:2,placeholder:"Take your career to the next level..."})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Background Image"}),e.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[o.hero_image_url&&e.jsx("img",{src:o.hero_image_url,alt:"Hero",className:"h-16 w-28 object-cover rounded"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(H,{variant:"outline",size:"sm",asChild:!0,disabled:n==="hero_image_url",children:e.jsxs("span",{children:[e.jsx(Ea,{className:"h-3.5 w-3.5 mr-1"}),n==="hero_image_url"?"Uploading...":"Upload Image"]})}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:b=>m(b,"hero_image_url")})]}),o.hero_image_url&&e.jsx(H,{variant:"ghost",size:"sm",onClick:()=>c(b=>({...b,hero_image_url:null})),children:e.jsx(Dr,{className:"h-3.5 w-3.5"})})]})]})]})]}),e.jsxs(ke,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between",children:[e.jsx(zt,{className:"text-base",children:"Benefits / Why Join Us"}),e.jsxs(H,{size:"sm",variant:"outline",onClick:()=>c(b=>({...b,benefits:[...b.benefits,{title:"",description:"",icon:"✨"}]})),children:[e.jsx(Ys,{className:"h-3.5 w-3.5 mr-1"})," Add"]})]}),e.jsxs(Oe,{className:"space-y-3",children:[o.benefits.map((b,j)=>e.jsxs("div",{className:"flex items-start gap-3 p-3 border rounded-lg",children:[e.jsx(Oh,{className:"h-4 w-4 mt-2 text-muted-foreground"}),e.jsx(Se,{value:b.icon,onChange:k=>{const T=[...o.benefits];T[j]={...b,icon:k.target.value},c(E=>({...E,benefits:T}))},className:"w-14 text-center"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(Se,{value:b.title,onChange:k=>{const T=[...o.benefits];T[j]={...b,title:k.target.value},c(E=>({...E,benefits:T}))},placeholder:"Benefit title"}),e.jsx(Se,{value:b.description,onChange:k=>{const T=[...o.benefits];T[j]={...b,description:k.target.value},c(E=>({...E,benefits:T}))},placeholder:"Short description"})]}),e.jsx(H,{variant:"ghost",size:"sm",onClick:()=>c(k=>({...k,benefits:k.benefits.filter((T,E)=>E!==j)})),children:e.jsx(Dr,{className:"h-3.5 w-3.5 text-destructive"})})]},j)),o.benefits.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No benefits added yet"})]})]}),e.jsxs(ke,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between",children:[e.jsx(zt,{className:"text-base",children:"Testimonials"}),e.jsxs(H,{size:"sm",variant:"outline",onClick:()=>c(b=>({...b,testimonials:[...b.testimonials,{name:"",role:"",quote:""}]})),children:[e.jsx(Ys,{className:"h-3.5 w-3.5 mr-1"})," Add"]})]}),e.jsxs(Oe,{className:"space-y-3",children:[o.testimonials.map((b,j)=>{var k;return e.jsxs("div",{className:"flex items-start gap-3 p-3 border rounded-lg",children:[e.jsxs("div",{className:"flex flex-col items-center gap-1",children:[b.photo_url?e.jsx("img",{src:b.photo_url,alt:b.name,className:"h-10 w-10 rounded-full object-cover"}):e.jsx("div",{className:"h-10 w-10 rounded-full bg-muted flex items-center justify-center text-xs text-muted-foreground",children:((k=b.name)==null?void 0:k[0])||"?"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx("span",{className:"text-[10px] text-primary hover:underline",children:n===`testimonial-${j}`?"...":"Photo"}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:T=>x(T,j)})]})]}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(Se,{value:b.name,onChange:T=>{const E=[...o.testimonials];E[j]={...b,name:T.target.value},c(A=>({...A,testimonials:E}))},placeholder:"Name"}),e.jsx(Se,{value:b.role,onChange:T=>{const E=[...o.testimonials];E[j]={...b,role:T.target.value},c(A=>({...A,testimonials:E}))},placeholder:"Role / Title"})]}),e.jsx(vr,{value:b.quote,onChange:T=>{const E=[...o.testimonials];E[j]={...b,quote:T.target.value},c(A=>({...A,testimonials:E}))},placeholder:"What they say about working here...",rows:2})]}),e.jsx(H,{variant:"ghost",size:"sm",onClick:()=>c(T=>({...T,testimonials:T.testimonials.filter((E,A)=>A!==j)})),children:e.jsx(Dr,{className:"h-3.5 w-3.5 text-destructive"})})]},j)}),o.testimonials.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No testimonials added yet"})]})]}),e.jsxs(ke,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between",children:[e.jsx(zt,{className:"text-base",children:"Team & Culture Gallery"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(H,{size:"sm",variant:"outline",asChild:!0,disabled:n==="gallery",children:e.jsxs("span",{children:[e.jsx(wl,{className:"h-3.5 w-3.5 mr-1"}),n==="gallery"?"Uploading...":"Add Photo"]})}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:p})]})]}),e.jsx(Oe,{children:o.gallery_images.length>0?e.jsx("div",{className:"grid grid-cols-3 md:grid-cols-4 gap-2",children:o.gallery_images.map((b,j)=>e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:b,alt:`Gallery ${j+1}`,className:"h-24 w-full object-cover rounded-lg"}),e.jsx(H,{variant:"destructive",size:"sm",className:"absolute top-1 right-1 h-6 w-6 p-0 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>c(k=>({...k,gallery_images:k.gallery_images.filter((T,E)=>E!==j)})),children:e.jsx(Dr,{className:"h-3 w-3"})})]},j))}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No gallery images added yet"})})]}),e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsxs(zt,{className:"text-base flex items-center gap-2",children:[e.jsx(Lr,{className:"h-4 w-4 text-primary"})," Form Style & Trust"]})}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ue,{children:"Application Form Style"}),e.jsxs(Bs,{value:o.form_style,onValueChange:b=>c(j=>({...j,form_style:b})),children:[e.jsx(Os,{className:"mt-1.5",children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"classic",children:"Classic — single-page form (all fields visible)"}),e.jsx(pt,{value:"multi_step",children:"Multi-Step Wizard — 3-step soft CTA (recommended)"})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1.5",children:"Multi-step wizards convert ~30% better than single long forms."})]}),e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border bg-muted/30",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Td,{className:"h-4 w-4 mt-0.5 text-primary"}),e.jsxs("div",{children:[e.jsx(ue,{children:"Show Confidentiality Badges"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:'Adds "100% Confidential" + "No spam" trust signals around the form.'})]})]}),e.jsx(Or,{checked:o.confidential_messaging,onCheckedChange:b=>c(j=>({...j,confidential_messaging:b}))})]})]})]}),e.jsxs(ke,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between",children:[e.jsxs(zt,{className:"text-base flex items-center gap-2",children:[e.jsx(II,{className:"h-4 w-4 text-primary"})," Split & Income Calculator"]}),e.jsx(Or,{checked:o.calculator_enabled,onCheckedChange:b=>c(j=>({...j,calculator_enabled:b}))})]}),o.calculator_enabled&&e.jsxs(Oe,{className:"space-y-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Highest-converting recruiting tool. Agents enter their GCI and instantly see what they'd earn at your brokerage."}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs",children:"Calculator Headline"}),e.jsx(Se,{value:o.calculator_config.headline||"",onChange:b=>c(j=>({...j,calculator_config:{...j.calculator_config,headline:b.target.value}})),placeholder:"See What You Could Earn With Us"})]}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs",children:"Subtext"}),e.jsx(Se,{value:o.calculator_config.subtext||"",onChange:b=>c(j=>({...j,calculator_config:{...j.calculator_config,subtext:b.target.value}})),placeholder:"Confidential 60-second calculator"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs",children:"Pre-Cap Split % (agent keeps)"}),e.jsx(Se,{type:"number",value:o.calculator_config.commission_split_pct??80,onChange:b=>c(j=>({...j,calculator_config:{...j.calculator_config,commission_split_pct:parseFloat(b.target.value)||0}}))}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:"e.g. 80 for an 80/20"})]}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs",children:"Cap Amount ($)"}),e.jsx(Se,{type:"number",value:o.calculator_config.cap_amount??16e3,onChange:b=>c(j=>({...j,calculator_config:{...j.calculator_config,cap_amount:parseFloat(b.target.value)||0}}))}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:"Annual cap to brokerage"})]}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs",children:"Post-Cap Split % (agent keeps)"}),e.jsx(Se,{type:"number",value:o.calculator_config.post_cap_split_pct??100,onChange:b=>c(j=>({...j,calculator_config:{...j.calculator_config,post_cap_split_pct:parseFloat(b.target.value)||0}}))}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:"e.g. 95 for 95/5 after cap, 100 for 100%"})]}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs",children:"Monthly Fee ($)"}),e.jsx(Se,{type:"number",value:o.calculator_config.monthly_fee??99,onChange:b=>c(j=>({...j,calculator_config:{...j.calculator_config,monthly_fee:parseFloat(b.target.value)||0}}))})]}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs",children:"Per-Transaction Fee ($)"}),e.jsx(Se,{type:"number",value:o.calculator_config.transaction_fee??0,onChange:b=>c(j=>({...j,calculator_config:{...j.calculator_config,transaction_fee:parseFloat(b.target.value)||0}}))}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:"Multiplied by # of transactions"})]})]}),e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border bg-muted/30",children:[e.jsxs("div",{children:[e.jsx(ue,{className:"text-sm",children:"Capture email at end of calculator"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"After seeing results, agents can request a full breakdown via email."})]}),e.jsx(Or,{checked:o.calculator_config.show_email_capture!==!1,onCheckedChange:b=>c(j=>({...j,calculator_config:{...j.calculator_config,show_email_capture:b}}))})]})]})]}),e.jsxs(ke,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between",children:[e.jsxs(zt,{className:"text-base flex items-center gap-2",children:[e.jsx(yE,{className:"h-4 w-4 text-primary"})," Lead Magnet (Gated PDF)"]}),e.jsx(Or,{checked:o.lead_magnet_enabled,onCheckedChange:b=>c(j=>({...j,lead_magnet_enabled:b}))})]}),o.lead_magnet_enabled&&e.jsxs(Oe,{className:"space-y-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Captures emails from agents not ready to talk. Offer a comp plan PDF, recruiting deck, or guide."}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs",children:"Title"}),e.jsx(Se,{value:o.lead_magnet_config.title||"",onChange:b=>c(j=>({...j,lead_magnet_config:{...j.lead_magnet_config,title:b.target.value}})),placeholder:"Get the Full Comp Plan PDF"})]}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs",children:"Description"}),e.jsx(vr,{rows:2,value:o.lead_magnet_config.description||"",onChange:b=>c(j=>({...j,lead_magnet_config:{...j.lead_magnet_config,description:b.target.value}})),placeholder:"See exactly how splits, caps, and fees work..."})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs",children:"Button Text"}),e.jsx(Se,{value:o.lead_magnet_config.button_text||"",onChange:b=>c(j=>({...j,lead_magnet_config:{...j.lead_magnet_config,button_text:b.target.value}})),placeholder:"Email Me the PDF"})]}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs",children:"PDF / File URL"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(Se,{value:o.lead_magnet_config.pdf_url||"",onChange:b=>c(j=>({...j,lead_magnet_config:{...j.lead_magnet_config,pdf_url:b.target.value||null}})),placeholder:"https://...",className:"flex-1"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(H,{variant:"outline",size:"sm",asChild:!0,disabled:n==="lead_magnet_pdf",children:e.jsxs("span",{children:[e.jsx(Ea,{className:"h-3.5 w-3.5 mr-1"}),n==="lead_magnet_pdf"?"...":"Upload"]})}),e.jsx("input",{type:"file",accept:"application/pdf,.pdf,.doc,.docx",className:"hidden",onChange:async b=>{var k;const j=(k=b.target.files)==null?void 0:k[0];if(j){a("lead_magnet_pdf");try{const T=await h(j,"lead-magnet");c(E=>({...E,lead_magnet_config:{...E.lead_magnet_config,pdf_url:T}})),t({title:"PDF uploaded!"})}catch(T){t({title:"Upload failed",description:T.message,variant:"destructive"})}finally{a(null)}}}})]})]})]})]})]})]}),e.jsx(fzs,{brokerageId:s}),e.jsx("div",{className:"flex justify-end",children:e.jsxs(H,{onClick:()=>d.mutate(),disabled:d.isPending,size:"lg",children:[e.jsx(vc,{className:"h-4 w-4 mr-2"}),d.isPending?"Saving...":"Save Landing Page"]})})]})}function fzs({brokerageId:s}){const{data:t=[]}=yt({queryKey:["lead-magnet-downloads",s],queryFn:async()=>{const{data:r,error:n}=await V.from("recruit_lead_magnet_downloads").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1}).limit(100);if(n)throw n;return r}});return t.length===0?null:e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsxs(zt,{className:"text-base flex items-center gap-2",children:[e.jsx(hi,{className:"h-4 w-4 text-primary"})," Lead Magnet Downloads (",t.length,")"]})}),e.jsx(Oe,{children:e.jsx("div",{className:"space-y-2 max-h-80 overflow-y-auto",children:t.map(r=>e.jsx("div",{className:"flex items-center justify-between gap-3 p-2.5 border rounded-lg text-sm",children:e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-medium truncate",children:[r.first_name||"—"," · ",r.email]}),e.jsxs("div",{className:"text-[11px] text-muted-foreground",children:[As(new Date(r.created_at),"MMM d, yyyy h:mm a")," · via ",r.source]})]})},r.id))})})]})}function gvt({brokerageId:s,trigger:t,initialProspectId:r,open:n,onOpenChange:a}){const[i,l]=S.useState(!1),o=n??i,c=a??l,[d,h]=S.useState("pick-recipients"),[m,p]=S.useState(new Set(r?[r]:[])),[x,y]=S.useState("all"),[_,b]=S.useState(""),[j,k]=S.useState(null),[T,E]=S.useState(""),[A,D]=S.useState(0),[R,z]=S.useState(0),[O,$]=S.useState(""),[ee,Z]=S.useState(""),{data:J}=cye(),[K,re]=S.useState("default");S.useEffect(()=>{re(J!=null&&J.massEmail?"mass_email":J!=null&&J.gmail?"gmail":"default")},[J==null?void 0:J.massEmail,J==null?void 0:J.gmail]);const[ie,ce]=S.useState(null),{prospects:ne,stages:le}=Hz(s),be=rvt(),fe=Cj(),{data:je=[]}=yt({queryKey:["brokerage-recruit-video-pool",s],queryFn:async()=>{const{data:pe,error:tt}=await V.from("agent_videos").select("id, title, thumbnail_url, duration_seconds, created_at, owner_user_id, share_token").eq("touch_type","recruiting").eq("status","ready").eq("is_deleted",!1).order("created_at",{ascending:!1}).limit(50);if(tt)throw tt;return pe??[]},enabled:o&&d==="pick-video"}),ve=S.useCallback(()=>{h("pick-recipients"),p(new Set(r?[r]:[])),y("all"),b(""),k(null),E(""),D(0),z(0),$(""),Z(""),re("default"),ce(null)},[r]),We=pe=>{!pe&&(d==="uploading"||d==="processing"||d==="sending")||(c(pe),pe||setTimeout(ve,200))},Ve=S.useMemo(()=>ne.filter(pe=>{if(!pe.email||x!=="all"&&pe.stage_id!==x)return!1;if(_){const tt=_.toLowerCase();if(!`${pe.first_name} ${pe.last_name??""}`.toLowerCase().includes(tt)&&!pe.email.toLowerCase().includes(tt))return!1}return!0}),[ne,x,_]),Le=pe=>{p(tt=>{const ge=new Set(tt);return ge.has(pe)?ge.delete(pe):ge.add(pe),ge})},Me=()=>{m.size===Ve.length?p(new Set):p(new Set(Ve.map(pe=>pe.id)))},ze=S.useCallback(async(pe,tt)=>{h("uploading");try{const ge=`Recruiting blast (${m.size} recipients)`,{videoId:ct,libraryId:Ue}=await tM(ge),{uploadUrl:et,apiKey:Qe}=await sM(ct),Ne=new XMLHttpRequest;Ne.upload.onprogress=rt=>{rt.lengthComputable&&D(rt.loaded/rt.total*100)},await new Promise((rt,Et)=>{Ne.onload=()=>Ne.status>=200&&Ne.status<300?rt():Et(new Error("Upload failed")),Ne.onerror=()=>Et(new Error("Upload failed")),Ne.open("PUT",et),Ne.setRequestHeader("AccessKey",Qe),Ne.send(pe)}),h("processing");const $e=`https://iframe.mediadelivery.net/embed/${Ue}/${ct}`;let it=0;const Je=Date.now(),st=9e4;for(;it<4&&(await new Promise(Et=>setTimeout(Et,3e3)),!(Date.now()-Je>st));){const rt=await F_(ct);if(it=rt.status,z(rt.encodeProgress||0),it===5||it===6)throw new Error("Video processing failed")}const mt=await F_(ct),wt=(mt.storageSize||pe.size)/(1024*1024),at=await fe.mutateAsync({bunny_video_id:ct,playback_url:mt.directPlayUrl||$e,thumbnail_url:mt.thumbnailUrl,preview_url:mt.previewUrl||null,duration_seconds:mt.length||tt,file_size_mb:wt,title:ge,status:it>=4?"ready":"processing",touch_type:"recruiting"});k(at.id),E(ge),h("compose")}catch(ge){he.error((ge==null?void 0:ge.message)||"Failed to upload video"),h("pick-video")}},[m.size,fe]),Pe=S.useCallback(async()=>{if(!(!j||m.size===0)){h("sending");try{const pe=[];for(const ct of m){const Ue=await be.mutateAsync({prospect_id:ct,video_id:j,brokerage_id:s,message:ee||void 0});pe.push(Ue.id)}const{data:tt,error:ge}=await V.functions.invoke("send-recruit-video-email",{body:{recruit_video_ids:pe,brokerage_id:s,subject_override:O||void 0,message_override:ee||void 0,send_via:K}});if(ge)throw new Error(ge.message);ce({sent:(tt==null?void 0:tt.sent)??0,total:(tt==null?void 0:tt.total)??pe.length}),h("done"),he.success(`Sent ${(tt==null?void 0:tt.sent)??0} of ${(tt==null?void 0:tt.total)??pe.length} videos`)}catch(pe){he.error((pe==null?void 0:pe.message)||"Failed to send"),h("compose")}}},[j,m,s,ee,O,K,be]),Ie=m.size,De=ne.filter(pe=>!pe.email).length;return e.jsxs(bs,{open:o,onOpenChange:We,children:[t&&e.jsx(Qi,{asChild:!0,children:t}),e.jsxs(vs,{className:"max-w-3xl max-h-[90vh] overflow-hidden flex flex-col",children:[e.jsx(Cs,{children:e.jsxs(Ns,{className:"flex items-center gap-2",children:[e.jsx(xn,{className:"h-5 w-5 text-primary"}),"Send Recruiting Video",Ie>0&&e.jsxs(Xe,{variant:"secondary",className:"ml-2",children:[e.jsx(Ar,{className:"h-3 w-3 mr-1"}),Ie," ",Ie===1?"recipient":"recipients"]})]})}),d==="pick-recipients"&&e.jsxs("div",{className:"flex-1 overflow-hidden flex flex-col gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Mn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Se,{placeholder:"Search prospects...",value:_,onChange:pe=>b(pe.target.value),className:"pl-9"})]}),e.jsxs(Bs,{value:x,onValueChange:y,children:[e.jsx(Os,{className:"w-48",children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"all",children:"All stages"}),le.map(pe=>e.jsx(pt,{value:pe.id,children:pe.name},pe.id))]})]})]}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground",children:[e.jsxs("button",{onClick:Me,className:"hover:underline",children:[m.size===Ve.length&&Ve.length>0?"Deselect all":"Select all"," ","(",Ve.length,")"]}),De>0&&e.jsxs("span",{children:[De," prospect(s) hidden — no email on file"]})]}),e.jsx(Ci,{className:"flex-1 border rounded-md",children:Ve.length===0?e.jsx("div",{className:"p-8 text-center text-sm text-muted-foreground",children:"No prospects match. Make sure prospects have email addresses."}):e.jsx("div",{className:"divide-y",children:Ve.map(pe=>{const tt=m.has(pe.id),ge=le.find(ct=>ct.id===pe.stage_id);return e.jsxs("label",{className:"flex items-center gap-3 p-3 hover:bg-muted/30 cursor-pointer",children:[e.jsx(ao,{checked:tt,onCheckedChange:()=>Le(pe.id)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("p",{className:"font-medium text-sm truncate",children:[pe.first_name," ",pe.last_name]}),ge&&e.jsx(Xe,{variant:"outline",className:"text-[10px]",style:{borderColor:ge.color,color:ge.color},children:ge.name})]}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[pe.email," ",pe.current_brokerage&&`· ${pe.current_brokerage}`]})]})]},pe.id)})})}),e.jsxs(wn,{children:[e.jsx(H,{variant:"outline",onClick:()=>We(!1),children:"Cancel"}),e.jsx(H,{disabled:Ie===0,onClick:()=>h("pick-video"),children:"Next: Choose Video"})]})]}),d==="pick-video"&&e.jsxs("div",{className:"flex-1 overflow-hidden flex flex-col",children:[e.jsxs(ta,{defaultValue:"record",className:"flex-1 flex flex-col overflow-hidden",children:[e.jsxs(Qn,{className:"self-start",children:[e.jsxs(ts,{value:"record",children:[e.jsx(Ys,{className:"h-3.5 w-3.5 mr-1"}),"Record New"]}),e.jsxs(ts,{value:"library",children:[e.jsx(NE,{className:"h-3.5 w-3.5 mr-1"}),"Use Existing"]})]}),e.jsx(cs,{value:"record",className:"flex-1 overflow-auto",children:e.jsxs("div",{className:"text-center py-8 space-y-4",children:[e.jsx(Qm,{className:"h-12 w-12 mx-auto text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Record a fresh video"}),e.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:["Same video sent to all ",Ie," ",Ie===1?"recipient":"recipients"," — each gets their own tracked link."]})]}),e.jsxs(H,{onClick:()=>h("record"),children:[e.jsx(xn,{className:"h-4 w-4 mr-2"}),"Start Recording"]})]})}),e.jsx(cs,{value:"library",className:"flex-1 overflow-auto",children:je.length===0?e.jsx("div",{className:"text-center py-8 text-sm text-muted-foreground",children:"No recruiting videos in library yet."}):e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-3 p-1",children:je.map(pe=>e.jsxs("button",{onClick:()=>{k(pe.id),E(pe.title||"Untitled"),h("compose")},className:"text-left group rounded-md border overflow-hidden hover:border-primary transition-colors",children:[e.jsx("div",{className:"aspect-video bg-muted relative",children:i_(pe)?e.jsx("img",{src:i_(pe),alt:"",className:"w-full h-full object-cover",referrerPolicy:"no-referrer"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(xn,{className:"h-8 w-8 text-muted-foreground"})})}),e.jsx("div",{className:"p-2",children:e.jsx("p",{className:"text-xs font-medium truncate",children:pe.title||"Untitled"})})]},pe.id))})})]}),e.jsx(wn,{children:e.jsx(H,{variant:"outline",onClick:()=>h("pick-recipients"),children:"Back"})})]}),d==="record"&&e.jsxs("div",{className:"flex-1 overflow-auto",children:[e.jsx(aD,{maxDurationSeconds:600,onRecordingComplete:ze}),e.jsx("div",{className:"mt-2 flex justify-start",children:e.jsx(H,{variant:"ghost",size:"sm",onClick:()=>h("pick-video"),children:"← Back"})})]}),(d==="uploading"||d==="processing")&&e.jsxs("div",{className:"py-12 space-y-4 text-center",children:[e.jsx(is,{className:"h-8 w-8 animate-spin mx-auto text-primary"}),e.jsx("p",{className:"font-medium",children:d==="uploading"?"Uploading video…":"Processing video…"}),e.jsx(Mi,{value:d==="uploading"?A:R,className:"mx-auto max-w-sm"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[Math.round(d==="uploading"?A:R),"%"]})]}),d==="compose"&&e.jsxs("div",{className:"flex-1 overflow-auto space-y-4",children:[e.jsxs("div",{className:"rounded-md border p-3 bg-muted/30 flex items-center gap-3",children:[e.jsx(ea,{className:"h-4 w-4 text-primary"}),e.jsxs("div",{className:"flex-1 text-sm",children:[e.jsx("span",{className:"font-medium",children:T})," selected · sending to ",e.jsx("strong",{children:Ie})," recipient",Ie===1?"":"s"]})]}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs",children:"Subject (optional override)"}),e.jsx(Se,{value:O,onChange:pe=>$(pe.target.value),placeholder:"[First Name], I made you a quick video 🎥",className:"mt-1"}),e.jsx("p",{className:"text-[11px] text-muted-foreground mt-1",children:"Leave blank to use the default personalized subject."})]}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs",children:"Personal message shown in the email & on the landing page"}),e.jsx(vr,{value:ee,onChange:pe=>Z(pe.target.value),placeholder:"Hey there — wanted to share a quick thought on what we're building here...",rows:5,className:"mt-1"})]}),e.jsx(x6e,{value:K,onChange:re}),e.jsxs(wn,{children:[e.jsx(H,{variant:"outline",onClick:()=>h("pick-video"),children:"Back"}),e.jsxs(H,{onClick:Pe,disabled:!j||Ie===0,children:[e.jsx(yn,{className:"h-4 w-4 mr-2"})," Send to ",Ie," ",Ie===1?"prospect":"prospects"]})]})]}),d==="sending"&&e.jsxs("div",{className:"py-12 text-center space-y-3",children:[e.jsx(is,{className:"h-8 w-8 animate-spin mx-auto text-primary"}),e.jsxs("p",{className:"font-medium",children:["Sending to ",Ie," recipient",Ie===1?"":"s","…"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Each prospect gets their own tracked share link."})]}),d==="done"&&ie&&e.jsxs("div",{className:"py-12 text-center space-y-4",children:[e.jsx("div",{className:`h-16 w-16 rounded-full mx-auto flex items-center justify-center ${ie.sent===ie.total?"bg-primary/10":"bg-muted"}`,children:ie.sent===ie.total?e.jsx(ea,{className:"h-8 w-8 text-primary"}):e.jsx(wo,{className:"h-8 w-8 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsxs("p",{className:"font-semibold text-lg",children:[ie.sent," of ",ie.total," sent"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"View engagement under the Video Outreach tab."})]}),e.jsx(H,{onClick:()=>We(!1),children:"Done"})]})]})]})}function pzs(s){if(!s)return"—";const t=Math.floor(s/60),r=s%60;return t>0?`${t}m ${r}s`:`${r}s`}function gzs({video:s}){return s.cta_clicked_at?e.jsx(Xe,{className:"bg-emerald-500/10 text-emerald-600 border-emerald-200",children:"CTA Clicked"}):s.view_count>0?e.jsxs(Xe,{className:"bg-blue-500/10 text-blue-600 border-blue-200",children:[e.jsx(Bn,{className:"h-3 w-3 mr-1"}),s.view_count," views"]}):s.sent_at?e.jsxs(Xe,{variant:"secondary",children:[e.jsx(yn,{className:"h-3 w-3 mr-1"}),"Sent"]}):e.jsxs(Xe,{variant:"outline",children:[e.jsx(Pn,{className:"h-3 w-3 mr-1"}),"Draft"]})}function xvt({brokerageId:s}){var T,E,A,D;const{data:t=[],isLoading:r}=rzs(s),{data:n=[]}=avt(s),a=azs(),i=izs(),l=nvt(),[o,c]=S.useState(""),[d,h]=S.useState(!1),[m,p]=S.useState({title:"",script_text:"",category:"general"}),[x,y]=S.useState(null),_=t.filter(R=>{var O,$,ee,Z;return o?`${((O=R.prospect)==null?void 0:O.first_name)||""} ${(($=R.prospect)==null?void 0:$.last_name)||""}`.toLowerCase().includes(o.toLowerCase())||((Z=(ee=R.video)==null?void 0:ee.title)==null?void 0:Z.toLowerCase().includes(o.toLowerCase())):!0}),b={total:t.length,sent:t.filter(R=>R.sent_at).length,viewed:t.filter(R=>R.view_count>0).length,ctaClicked:t.filter(R=>R.cta_clicked_at).length},j=S.useCallback(R=>{if(!R)return;const z=`${window.location.origin}/recruit-video/${R}`;navigator.clipboard.writeText(z),he.success("Share link copied")},[]);S.useCallback((R,z)=>{l.mutate({id:R,sent_via:z})},[l]);const k=()=>{!m.title.trim()||!m.script_text.trim()||a.mutate({brokerage_id:s,...m},{onSuccess:()=>{p({title:"",script_text:"",category:"general"}),h(!1)}})};return e.jsxs("div",{className:"space-y-6",children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[{label:"Total Videos",value:b.total,icon:xn,color:"text-primary"},{label:"Sent",value:b.sent,icon:yn,color:"text-blue-500"},{label:"Viewed",value:b.viewed,icon:Bn,color:"text-amber-500"},{label:"CTA Clicked",value:b.ctaClicked,icon:ea,color:"text-emerald-500"}].map(R=>e.jsx(ke,{children:e.jsxs(Oe,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:`h-10 w-10 rounded-lg bg-muted flex items-center justify-center ${R.color}`,children:e.jsx(R.icon,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:R.value}),e.jsx("p",{className:"text-xs text-muted-foreground",children:R.label})]})]})},R.label))}),e.jsxs(ta,{defaultValue:"videos",className:"space-y-4",children:[e.jsxs(Qn,{children:[e.jsxs(ts,{value:"videos",children:[e.jsx(xn,{className:"h-4 w-4 mr-1.5"}),"All Videos"]}),e.jsxs(ts,{value:"scripts",children:[e.jsx(kn,{className:"h-4 w-4 mr-1.5"}),"Script Library"]}),e.jsxs(ts,{value:"analytics",children:[e.jsx(Bo,{className:"h-4 w-4 mr-1.5"}),"Engagement"]})]}),e.jsx(cs,{value:"videos",children:e.jsxs(ke,{children:[e.jsx(Ot,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap",children:[e.jsx(zt,{className:"text-lg",children:"Video Outreach"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative w-64",children:[e.jsx(Mn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Se,{placeholder:"Search by name or title...",value:o,onChange:R=>c(R.target.value),className:"pl-9"})]}),e.jsx(gvt,{brokerageId:s,trigger:e.jsxs(H,{size:"sm",className:"gap-1.5",children:[e.jsx(er,{className:"h-4 w-4"})," Send Video Email"]})})]})]})}),e.jsx(Oe,{children:r?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):_.length===0?e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(xn,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{className:"font-medium",children:"No video outreach yet"}),e.jsx("p",{className:"text-sm mt-1",children:"Record a personalized video from any prospect's profile card"})]}):e.jsx("div",{className:"space-y-3",children:_.map(R=>{var z,O,$,ee,Z,J,K;return e.jsxs("div",{className:"flex items-center gap-4 p-3 rounded-lg border bg-card hover:bg-muted/30 transition-colors",children:[e.jsxs("div",{className:"relative h-16 w-28 rounded-md overflow-hidden bg-muted flex-shrink-0",children:[i_(R.video)?e.jsx("img",{src:i_(R.video),alt:"",className:"h-full w-full object-cover",referrerPolicy:"no-referrer"}):e.jsx("div",{className:"h-full w-full flex items-center justify-center",children:e.jsx(xn,{className:"h-6 w-6 text-muted-foreground"})}),e.jsx("div",{className:"absolute bottom-1 right-1 bg-black/70 text-white text-[10px] px-1 rounded",children:pzs(((z=R.video)==null?void 0:z.duration_seconds)??null)})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("p",{className:"font-medium truncate",children:[(O=R.prospect)==null?void 0:O.first_name," ",($=R.prospect)==null?void 0:$.last_name]}),e.jsx(gzs,{video:R})]}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:((ee=R.video)==null?void 0:ee.title)||"Untitled video"}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:[As(new Date(R.created_at),"MMM d, yyyy"),((Z=R.prospect)==null?void 0:Z.current_brokerage)&&` · ${R.prospect.current_brokerage}`]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(H,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>j(R.share_token),title:"Copy share link",children:e.jsx(ui,{className:"h-4 w-4"})}),e.jsxs(H,{variant:R.sent_at?"ghost":"default",size:"sm",className:"h-8 gap-1.5",onClick:()=>y(R),disabled:!((J=R.prospect)!=null&&J.email),title:(K=R.prospect)!=null&&K.email?"Email this video to the prospect":"Prospect has no email",children:[e.jsx(er,{className:"h-4 w-4"}),R.sent_at?"Resend":"Email"]}),R.share_token&&e.jsx(H,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>window.open(`/recruit-video/${R.share_token}`,"_blank"),title:"Preview landing page",children:e.jsx(gn,{className:"h-4 w-4"})})]})]},R.id)})})})]})}),e.jsx(cs,{value:"scripts",children:e.jsxs(ke,{children:[e.jsx(Ot,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(zt,{className:"text-lg",children:"Recruiting Scripts"}),e.jsxs(bs,{open:d,onOpenChange:h,children:[e.jsx(Qi,{asChild:!0,children:e.jsxs(H,{size:"sm",children:[e.jsx(Ys,{className:"h-4 w-4 mr-1.5"}),"New Script"]})}),e.jsxs(vs,{children:[e.jsx(Cs,{children:e.jsx(Ns,{children:"Create Recruiting Script"})}),e.jsxs("div",{className:"space-y-4 mt-2",children:[e.jsxs("div",{children:[e.jsx(ue,{children:"Title"}),e.jsx(Se,{value:m.title,onChange:R=>p(z=>({...z,title:R.target.value})),placeholder:"e.g., Why Switch to Our Brokerage"})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Category"}),e.jsxs(Bs,{value:m.category,onValueChange:R=>p(z=>({...z,category:R})),children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsx(Fs,{children:Y4e.map(R=>e.jsx(pt,{value:R.value,children:R.label},R.value))})]})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Script"}),e.jsx(vr,{value:m.script_text,onChange:R=>p(z=>({...z,script_text:R.target.value})),placeholder:"Hi [Name], I noticed you've been doing great work at [Brokerage]...",rows:8})]}),e.jsx(H,{onClick:k,disabled:!m.title.trim()||!m.script_text.trim(),className:"w-full",children:"Save Script"})]})]})]})]})}),e.jsx(Oe,{children:n.length===0?e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(kn,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{className:"font-medium",children:"No scripts yet"}),e.jsx("p",{className:"text-sm mt-1",children:"Create teleprompter scripts for common recruiting conversations"})]}):e.jsx("div",{className:"grid gap-3 md:grid-cols-2",children:n.map(R=>{var O;const z=((O=Y4e.find($=>$.value===R.category))==null?void 0:O.label)||R.category;return e.jsx(ke,{className:"relative group",children:e.jsxs(Oe,{className:"p-4",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsx(Xe,{variant:"outline",className:"text-[10px] mb-2",children:z}),e.jsx("h4",{className:"font-medium text-sm",children:R.title})]}),e.jsx(H,{variant:"ghost",size:"icon",className:"h-7 w-7 opacity-0 group-hover:opacity-100 transition-opacity text-destructive",onClick:()=>i.mutate(R.id),children:e.jsx(Dr,{className:"h-3.5 w-3.5"})})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-2 line-clamp-3",children:R.script_text}),R.is_global&&e.jsx(Xe,{variant:"secondary",className:"mt-2 text-[10px]",children:"Template"})]})},R.id)})})})]})}),e.jsx(cs,{value:"analytics",children:e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-lg",children:"Engagement Funnel"})}),e.jsxs(Oe,{children:[e.jsx("div",{className:"space-y-4",children:[{label:"Videos Created",count:b.total,pct:100,color:"bg-primary"},{label:"Sent to Prospects",count:b.sent,pct:b.total?Math.round(b.sent/b.total*100):0,color:"bg-blue-500"},{label:"Viewed by Prospect",count:b.viewed,pct:b.sent?Math.round(b.viewed/b.sent*100):0,color:"bg-amber-500"},{label:"CTA Clicked",count:b.ctaClicked,pct:b.viewed?Math.round(b.ctaClicked/b.viewed*100):0,color:"bg-emerald-500"}].map(R=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{children:R.label}),e.jsxs("span",{className:"font-medium",children:[R.count," (",R.pct,"%)"]})]}),e.jsx("div",{className:"h-3 bg-muted rounded-full overflow-hidden",children:e.jsx("div",{className:`h-full ${R.color} rounded-full transition-all`,style:{width:`${R.pct}%`}})})]},R.label))}),t.filter(R=>R.view_count>0).length>0&&e.jsxs("div",{className:"mt-8",children:[e.jsx("h4",{className:"font-medium text-sm mb-3",children:"Most Engaged Prospects"}),e.jsx("div",{className:"space-y-2",children:t.filter(R=>R.view_count>0).sort((R,z)=>z.view_count-R.view_count).slice(0,5).map(R=>{var z,O;return e.jsxs("div",{className:"flex items-center justify-between text-sm p-2 rounded-md bg-muted/30",children:[e.jsxs("span",{className:"font-medium",children:[(z=R.prospect)==null?void 0:z.first_name," ",(O=R.prospect)==null?void 0:O.last_name]}),e.jsxs("div",{className:"flex items-center gap-3 text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Bn,{className:"h-3.5 w-3.5"})," ",R.view_count]}),R.cta_clicked_at&&e.jsx(ea,{className:"h-4 w-4 text-emerald-500"})]})]},R.id)})})]})]})]})})]}),x&&e.jsx(svt,{open:!!x,onOpenChange:R=>{R||y(null)},recruitVideoId:x.id,brokerageId:s,prospectName:`${((T=x.prospect)==null?void 0:T.first_name)||""} ${((E=x.prospect)==null?void 0:E.last_name)||""}`.trim(),prospectEmail:(A=x.prospect)==null?void 0:A.email,videoTitle:(D=x.video)==null?void 0:D.title,defaultMessage:x.message})]})}function yvt({brokerageId:s}){const{toast:t}=li(),r=ns(),{stages:n,prospects:a}=Hz(s),[i,l]=S.useState(!1),[o,c]=S.useState({title:"",target_count:"10",target_stage_id:"",period_start:As(new Date,"yyyy-MM-dd"),period_end:As(new Date(new Date().getFullYear(),new Date().getMonth()+3,0),"yyyy-MM-dd")}),{data:d=[],isLoading:h}=yt({queryKey:["recruit-goals",s],queryFn:async()=>{const{data:y,error:_}=await V.from("recruit_goals").select("*").eq("brokerage_id",s).order("period_end",{ascending:!1});if(_)throw _;return y}}),m=Pt({mutationFn:async y=>{const{data:{user:_}}=await V.auth.getUser();if(!_)throw new Error("Not authenticated");const{error:b}=await V.from("recruit_goals").insert({brokerage_id:s,title:y.title,target_count:parseInt(y.target_count),target_stage_id:y.target_stage_id||null,period_start:y.period_start,period_end:y.period_end,created_by:_.id});if(b)throw b},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-goals",s]}),t({title:"Goal created"}),l(!1)},onError:y=>t({title:"Error",description:y.message,variant:"destructive"})}),p=Pt({mutationFn:async y=>{const{error:_}=await V.from("recruit_goals").delete().eq("id",y);if(_)throw _},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-goals",s]}),t({title:"Goal removed"})}}),x=y=>{const _=n.find(j=>j.id===y.target_stage_id);return{count:a.filter(j=>s1(new Date(j.created_at),{start:new Date(y.period_start),end:new Date(y.period_end)})?y.target_stage_id?j.stage_id===y.target_stage_id:!0:!1).length,stage:_}};return h?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:[d.length," goal",d.length!==1?"s":""]}),e.jsxs(H,{size:"sm",onClick:()=>l(!0),children:[e.jsx(Ys,{className:"h-4 w-4 mr-1"})," New Goal"]})]}),d.length===0?e.jsxs(ke,{className:"py-12 text-center",children:[e.jsx(Wu,{className:"h-10 w-10 mx-auto text-muted-foreground mb-3"}),e.jsx("p",{className:"text-muted-foreground",children:"No goals set. Create a recruiting target to track progress."})]}):e.jsx("div",{className:"grid md:grid-cols-2 gap-4",children:d.map(y=>{const{count:_,stage:b}=x(y),j=Math.min(100,_/y.target_count*100),k=s1(new Date,{start:new Date(y.period_start),end:new Date(y.period_end)});return e.jsxs(ke,{className:k?"":"opacity-60",children:[e.jsx(Ot,{className:"pb-2",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsx(zt,{className:"text-sm",children:y.title}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:[As(new Date(y.period_start),"MMM d")," – ",As(new Date(y.period_end),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[k?e.jsx(Xe,{className:"text-[10px]",children:"Active"}):e.jsx(Xe,{variant:"secondary",className:"text-[10px]",children:"Ended"}),e.jsx(H,{variant:"ghost",size:"icon",className:"h-6 w-6 text-muted-foreground",onClick:()=>p.mutate(y.id),children:e.jsx(Dr,{className:"h-3.5 w-3.5"})})]})]})}),e.jsxs(Oe,{className:"space-y-2",children:[b&&e.jsxs(Xe,{variant:"outline",className:"text-[10px]",style:{borderColor:b.color,color:b.color},children:["Stage: ",b.name]}),e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"font-bold text-lg",children:_}),e.jsxs("span",{className:"text-muted-foreground",children:["/ ",y.target_count]})]}),e.jsx(Mi,{value:j,className:"h-2"}),e.jsxs("p",{className:"text-xs text-muted-foreground text-right",children:[j.toFixed(0),"% complete"]})]})]},y.id)})}),e.jsx(bs,{open:i,onOpenChange:l,children:e.jsxs(vs,{children:[e.jsx(Cs,{children:e.jsx(Ns,{children:"Create Recruiting Goal"})}),e.jsxs("form",{onSubmit:y=>{y.preventDefault(),m.mutate(o)},className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ue,{children:"Goal Title *"}),e.jsx(Se,{required:!0,value:o.title,onChange:y=>c(_=>({..._,title:y.target.value})),placeholder:"e.g. Q2 Recruiting Target"})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Target Count *"}),e.jsx(Se,{type:"number",min:"1",required:!0,value:o.target_count,onChange:y=>c(_=>({..._,target_count:y.target.value}))})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Target Stage (optional)"}),e.jsxs("select",{className:"w-full rounded-md border border-input bg-background px-3 py-2 text-sm",value:o.target_stage_id,onChange:y=>c(_=>({..._,target_stage_id:y.target.value})),children:[e.jsx("option",{value:"",children:"All stages (total prospects)"}),n.map(y=>e.jsx("option",{value:y.id,children:y.name},y.id))]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Count prospects that reach this stage"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ue,{children:"Start Date"}),e.jsx(Se,{type:"date",required:!0,value:o.period_start,onChange:y=>c(_=>({..._,period_start:y.target.value}))})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"End Date"}),e.jsx(Se,{type:"date",required:!0,value:o.period_end,onChange:y=>c(_=>({..._,period_end:y.target.value}))})]})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(H,{type:"button",variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx(H,{type:"submit",disabled:m.isPending,children:"Create Goal"})]})]})]})})]})}const xzs={first_name:"Sarah",brokerage_name:"ABC Realty",city:"Austin",sender_name:"Jeremy"};function vvt({email:s,mergeValues:t=xzs,selectedSubjectIndex:r,onClose:n}){var c;const a=d=>d.replace(/\{\{first_name\}\}/g,t.first_name).replace(/\{\{brokerage_name\}\}/g,t.brokerage_name).replace(/\{\{city\}\}/g,t.city).replace(/\{\{sender_name\}\}/g,t.sender_name).replace(/\{\{landing_page_link\}\}/g,"https://bestbrokerage.relevelup.com/join-brokerage/your-slug"),i=((c=s.subject_line_options)==null?void 0:c.length)>0?s.subject_line_options:[s.subject_line],l=r??0,o=i[l]||s.subject_line;return e.jsx(bs,{open:!0,onOpenChange:()=>n(),children:e.jsxs(vs,{className:"max-w-2xl max-h-[85vh] overflow-y-auto p-0",children:[e.jsxs(Cs,{className:"px-6 pt-6 pb-4 border-b",children:[e.jsxs(Ns,{className:"text-base",children:["Email #",s.email_number," — ",s.title]}),e.jsxs("div",{className:"flex items-center gap-3 mt-2",children:[e.jsxs(Xe,{variant:"outline",className:"text-xs gap-1",children:[e.jsx(Pn,{className:"h-3 w-3"}),s.email_number===1?"Sent immediately":`Day ${s.delay_days}`]}),i.length>1&&e.jsxs(Xe,{variant:"secondary",className:"text-xs",children:[i.length," subject variants"]})]})]}),e.jsxs("div",{className:"space-y-0",children:[i.length>1&&e.jsxs("div",{className:"px-6 py-3 border-b bg-muted/20",children:[e.jsx("p",{className:"text-[10px] font-medium text-muted-foreground uppercase tracking-wider mb-2",children:"Subject Line Options"}),e.jsx("div",{className:"flex flex-col gap-1.5",children:i.map((d,h)=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`text-[10px] font-bold uppercase px-1.5 py-0.5 rounded ${h===l?"bg-primary/10 text-primary":"bg-muted text-muted-foreground"}`,children:h===l?"Selected":h===0?"Primary":`Alt ${h}`}),e.jsx("span",{className:"text-sm",children:a(d)})]},h))})]}),e.jsxs("div",{className:"border-b",children:[e.jsxs("div",{className:"px-6 py-2 flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx("span",{className:"font-medium w-14",children:"From:"}),e.jsxs("span",{children:[t.sender_name," "]})]}),e.jsxs("div",{className:"px-6 py-2 flex items-center gap-2 text-xs text-muted-foreground border-t",children:[e.jsx("span",{className:"font-medium w-14",children:"To:"}),e.jsxs("span",{children:[t.first_name," "]})]}),e.jsxs("div",{className:"px-6 py-2 flex items-center gap-2 text-xs border-t",children:[e.jsx("span",{className:"font-medium w-14 text-muted-foreground",children:"Subject:"}),e.jsx("span",{className:"font-medium",children:a(o)})]})]}),e.jsx("div",{className:"bg-white px-8 py-6",children:e.jsx("div",{className:"prose prose-sm max-w-none [&_p]:my-3 [&_p+p]:mt-4 [&_br]:block [&_br]:mt-2",style:{fontSize:"15px",lineHeight:"1.75",color:"#1a1a1a"},dangerouslySetInnerHTML:{__html:a(s.body_html)}})})]})]})})}function y6e({brokerageId:s}){const t=ns(),{user:r}=Ms(),[n,a]=S.useState(""),[i,l]=S.useState(!1),[o,c]=S.useState({brokerage_id:s,sender_name:"LevelUp",sender_email:"recruiting@relevelup.com",reply_to_email:"",merge_fields:{city:"",broker_name:""}}),{data:d}=yt({queryKey:["brokerage-recruit-settings",s],queryFn:async()=>{const{data:y,error:_}=await V.from("brokerage_recruit_settings").select("*").eq("brokerage_id",s).maybeSingle();if(_)throw _;return y}}),{data:h}=yt({queryKey:["brokerage-detail",s],queryFn:async()=>{const{data:y,error:_}=await V.from("brokerages").select("name, city, state").eq("id",s).single();if(_)throw _;return y}});S.useEffect(()=>{d?c({...d,merge_fields:d.merge_fields||{city:"",broker_name:""}}):h&&c(y=>({...y,merge_fields:{...y.merge_fields,brokerage_name:h.name,city:h.city||""}}))},[d,h]),S.useEffect(()=>{r!=null&&r.id&&V.from("profiles").select("recruit_cta_url").eq("id",r.id).single().then(({data:y})=>a((y==null?void 0:y.recruit_cta_url)||""))},[r==null?void 0:r.id]);const m=async()=>{if(!(r!=null&&r.id))return;l(!0);const{error:y}=await V.from("profiles").update({recruit_cta_url:n.trim()||null}).eq("id",r.id);l(!1),y?he.error(y.message):he.success("Scheduling link saved!")},p=Pt({mutationFn:async()=>{const y={brokerage_id:s,sender_name:o.sender_name,sender_email:o.sender_email,reply_to_email:o.reply_to_email||null,merge_fields:o.merge_fields,updated_at:new Date().toISOString()};if(d!=null&&d.id){const{error:_}=await V.from("brokerage_recruit_settings").update(y).eq("id",d.id);if(_)throw _}else{const{error:_}=await V.from("brokerage_recruit_settings").insert(y);if(_)throw _}},onSuccess:()=>{t.invalidateQueries({queryKey:["brokerage-recruit-settings",s]}),he.success("Recruiting email settings saved!")},onError:y=>he.error(y.message)}),x=(y,_)=>{c(b=>({...b,merge_fields:{...b.merge_fields,[y]:_}}))};return e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Configure the sender identity and merge fields for recruiting emails sent to this brokerage's prospects."}),e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-4 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Nn,{className:"h-4 w-4 text-primary"}),e.jsx("p",{className:"text-sm font-medium",children:"Your Scheduling Link"})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["This URL powers the ",e.jsx("strong",{children:'"Schedule a Conversation"'})," button on every recruiting video page you send. Paste your Calendly, HubSpot Meetings, Google Calendar booking link, etc."]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Se,{value:n,onChange:y=>a(y.target.value),placeholder:"https://calendly.com/your-name/intro"}),e.jsxs(H,{onClick:m,disabled:i,size:"sm",children:[e.jsx(vc,{className:"h-4 w-4 mr-1"})," Save"]})]}),!n&&e.jsx("p",{className:"text-xs text-amber-600",children:"⚠️ No link set — the CTA button will be hidden on your video pages until you add one."})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(ue,{className:"text-xs",children:"Sender Display Name"}),e.jsx(Se,{value:o.sender_name,onChange:y=>c({...o,sender_name:y.target.value}),placeholder:"e.g. Jeremy at LevelUp"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(ue,{className:"text-xs",children:"Sender Email Address"}),e.jsx(Se,{value:o.sender_email,onChange:y=>c({...o,sender_email:y.target.value}),placeholder:"recruiting@relevelup.com"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Must be a verified SES identity. Verify your own address below to send from it."})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(ue,{className:"text-xs",children:"Reply-To Email (optional)"}),e.jsx(Se,{value:o.reply_to_email,onChange:y=>c({...o,reply_to_email:y.target.value}),placeholder:"jeremy@relevelup.com"})]})]}),e.jsxs("div",{className:"border-t pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(w1,{className:"h-4 w-4 text-primary"}),e.jsx("p",{className:"text-sm font-medium",children:"Sender Verification (Amazon SES)"})]}),e.jsxs("p",{className:"text-xs text-muted-foreground mb-4",children:["Verify any email address with AWS so recruiting emails can be sent from that address (e.g. your own broker email, instead of ",e.jsx("code",{className:"px-1 py-0.5 rounded bg-muted text-[10px]",children:"recruiting@relevelup.com"}),")."]}),e.jsx(Yyt,{brokerageId:s,onVerifiedSelect:y=>{c(_=>({..._,sender_email:y})),he.success(`Sender set to ${y}`)}})]}),e.jsxs("div",{className:"border-t pt-4",children:[e.jsx("p",{className:"text-sm font-medium mb-3",children:"Default Merge Fields"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-3",children:"These values will auto-fill in campaign emails for this brokerage."}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(ue,{className:"text-xs",children:"{{brokerage_name}}"}),e.jsx(Se,{value:o.merge_fields.brokerage_name||"",onChange:y=>x("brokerage_name",y.target.value),placeholder:(h==null?void 0:h.name)||"Brokerage Name"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(ue,{className:"text-xs",children:"{{city}}"}),e.jsx(Se,{value:o.merge_fields.city||"",onChange:y=>x("city",y.target.value),placeholder:"e.g. Austin"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(ue,{className:"text-xs",children:"{{sender_name}}"}),e.jsx(Se,{value:o.merge_fields.sender_name||"",onChange:y=>x("sender_name",y.target.value),placeholder:"e.g. Jeremy"})]})]})]}),e.jsxs(H,{onClick:()=>p.mutate(),disabled:p.isPending,className:"w-full",children:[e.jsx(vc,{className:"h-4 w-4 mr-1"})," Save Settings"]})]})}const yzs=M1.create({name:"underline",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"u"},{style:"text-decoration",consuming:!1,getAttrs:s=>s.includes("underline")?{}:!1}]},renderHTML({HTMLAttributes:s}){return["u",Xd(this.options.HTMLAttributes,s),0]},addCommands(){return{setUnderline:()=>({commands:s})=>s.setMark(this.name),toggleUnderline:()=>({commands:s})=>s.toggleMark(this.name),unsetUnderline:()=>({commands:s})=>s.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-u":()=>this.editor.commands.toggleUnderline(),"Mod-U":()=>this.editor.commands.toggleUnderline()}}}),TWe=[{key:"first_name",label:"First Name",preview:"Sarah"},{key:"brokerage_name",label:"Brokerage Name",preview:"ABC Realty"},{key:"city",label:"City",preview:"Austin"},{key:"sender_name",label:"Sender Name",preview:"Jeremy"},{key:"landing_page_link",label:"Landing Page URL",preview:"https://bestbrokerage.relevelup.com/join-brokerage/your-slug"}];function Cf({onClick:s,active:t,disabled:r,icon:n,tooltip:a}){return e.jsxs(rd,{children:[e.jsx(nd,{asChild:!0,children:e.jsx(H,{type:"button",variant:"ghost",size:"sm",onClick:s,disabled:r,className:`h-8 w-8 p-0 ${t?"bg-accent text-accent-foreground":"text-muted-foreground hover:text-foreground"}`,children:e.jsx(n,{className:"h-4 w-4"})})}),e.jsx(Rc,{side:"bottom",className:"text-xs",children:a})]})}function vzs({content:s,onChange:t}){const r=XTe({extensions:[JTe.configure({heading:{levels:[1,2,3]}}),yzs,cEe.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline cursor-pointer"}}),dEe.configure({types:["heading","paragraph"]}),uEe,Lgt],content:s,editorProps:{attributes:{class:"prose prose-sm max-w-none focus:outline-none min-h-[350px] px-5 py-4",style:"font-size: 15px; line-height: 1.75; color: #1a1a1a;"}},onUpdate:({editor:i})=>{t(i.getHTML())}});S.useEffect(()=>{r&&s!==r.getHTML()&&r.commands.setContent(s)},[s,r]);const n=S.useCallback(()=>{if(!r)return;const i=r.getAttributes("link").href,l=window.prompt("Enter URL",i);if(l!==null){if(l===""){r.chain().focus().extendMarkRange("link").unsetLink().run();return}r.chain().focus().extendMarkRange("link").setLink({href:l}).run()}},[r]),a=S.useCallback(i=>{r&&r.chain().focus().insertContent(`{{${i}}}`).run()},[r]);return r?e.jsx(xj,{delayDuration:300,children:e.jsxs("div",{className:"border rounded-xl overflow-hidden bg-background shadow-sm",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-0.5 px-2 py-1.5 border-b bg-muted/30",children:[e.jsx(Cf,{onClick:()=>r.chain().focus().toggleBold().run(),active:r.isActive("bold"),icon:Ok,tooltip:"Bold"}),e.jsx(Cf,{onClick:()=>r.chain().focus().toggleItalic().run(),active:r.isActive("italic"),icon:qk,tooltip:"Italic"}),e.jsx(Cf,{onClick:()=>r.chain().focus().toggleUnderline().run(),active:r.isActive("underline"),icon:XI,tooltip:"Underline"}),e.jsx(Cf,{onClick:()=>r.chain().focus().toggleStrike().run(),active:r.isActive("strike"),icon:LF,tooltip:"Strikethrough"}),e.jsx(Qo,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(Cf,{onClick:()=>r.chain().focus().toggleHeading({level:1}).run(),active:r.isActive("heading",{level:1}),icon:OI,tooltip:"Heading 1"}),e.jsx(Cf,{onClick:()=>r.chain().focus().toggleHeading({level:2}).run(),active:r.isActive("heading",{level:2}),icon:FI,tooltip:"Heading 2"}),e.jsx(Cf,{onClick:()=>r.chain().focus().toggleHeading({level:3}).run(),active:r.isActive("heading",{level:3}),icon:fF,tooltip:"Heading 3"}),e.jsx(Qo,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(Cf,{onClick:()=>r.chain().focus().toggleBulletList().run(),active:r.isActive("bulletList"),icon:Vf,tooltip:"Bullet List"}),e.jsx(Cf,{onClick:()=>r.chain().focus().toggleOrderedList().run(),active:r.isActive("orderedList"),icon:b1,tooltip:"Numbered List"}),e.jsx(Cf,{onClick:()=>r.chain().focus().toggleBlockquote().run(),active:r.isActive("blockquote"),icon:Kk,tooltip:"Blockquote"}),e.jsx(Cf,{onClick:()=>r.chain().focus().setHorizontalRule().run(),icon:g_,tooltip:"Divider"}),e.jsx(Qo,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(Cf,{onClick:()=>r.chain().focus().setTextAlign("left").run(),active:r.isActive({textAlign:"left"}),icon:uE,tooltip:"Align Left"}),e.jsx(Cf,{onClick:()=>r.chain().focus().setTextAlign("center").run(),active:r.isActive({textAlign:"center"}),icon:dE,tooltip:"Align Center"}),e.jsx(Cf,{onClick:()=>r.chain().focus().setTextAlign("right").run(),active:r.isActive({textAlign:"right"}),icon:hE,tooltip:"Align Right"}),e.jsx(Qo,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(Cf,{onClick:n,active:r.isActive("link"),icon:Jo,tooltip:"Insert Link"}),e.jsx(Qo,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(Cf,{onClick:()=>r.chain().focus().undo().run(),disabled:!r.can().undo(),icon:Xk,tooltip:"Undo"}),e.jsx(Cf,{onClick:()=>r.chain().focus().redo().run(),disabled:!r.can().redo(),icon:Yk,tooltip:"Redo"}),e.jsx("div",{className:"flex-1"}),e.jsx(H,{type:"button",variant:"outline",size:"sm",className:"h-8 gap-1.5 text-xs font-medium",onClick:()=>{r&&r.chain().focus().insertContent('

Learn More About Us

').run()},children:"🔘 CTA Button"}),e.jsxs(Xu,{children:[e.jsx(Qu,{asChild:!0,children:e.jsxs(H,{type:"button",variant:"outline",size:"sm",className:"h-8 gap-1.5 text-xs font-medium",children:[e.jsx(QI,{className:"h-3.5 w-3.5"}),"Merge Tags"]})}),e.jsx(wu,{align:"end",className:"w-56",children:TWe.map(i=>e.jsxs(di,{onClick:()=>a(i.key),className:"flex flex-col items-start gap-0.5",children:[e.jsx("span",{className:"font-medium text-sm",children:i.label}),e.jsx("span",{className:"text-xs text-muted-foreground font-mono",children:`{{${i.key}}}`})]},i.key))})]})]}),e.jsx("div",{className:"bg-white",children:e.jsx(YTe,{editor:r,className:"[&_.ProseMirror]:outline-none [&_.ProseMirror]:min-h-[350px] [&_.ProseMirror_p]:my-3 [&_.ProseMirror_ul]:my-3 [&_.ProseMirror_ol]:my-3 [&_.ProseMirror_blockquote]:my-3 [&_.ProseMirror_h1]:my-4 [&_.ProseMirror_h2]:my-3 [&_.ProseMirror_h3]:my-2"})}),e.jsx("div",{className:"border-t px-4 py-2.5 bg-muted/20",children:e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground font-medium",children:"Tags:"}),TWe.map(i=>e.jsx(Xe,{variant:"secondary",className:"cursor-pointer hover:bg-secondary/80 font-mono text-[10px] px-2 py-0.5",onClick:()=>a(i.key),children:`{{${i.key}}}`},i.key))]})})]})}):null}function bzs({open:s,onClose:t,campaignName:r,stat:n}){return e.jsx(bs,{open:s,onOpenChange:a=>!a&&t(),children:e.jsxs(vs,{className:"max-w-3xl max-h-[85vh] overflow-y-auto",children:[e.jsxs(Cs,{children:[e.jsxs(Ns,{className:"flex items-center gap-2",children:[e.jsx(al,{className:"h-5 w-5 text-primary"}),r," — Engagement Stats"]}),e.jsx(nn,{children:"Per-email breakdown of sends, opens, and clicks for this campaign at your brokerage."})]}),!n||n.sent===0?e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(yn,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{className:"font-medium",children:"No emails sent yet for this campaign"}),e.jsx("p",{className:"text-sm",children:"Stats will appear once emails start sending"})]}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsx(nV,{icon:er,color:"text-blue-500",label:"Total Sent",value:n.sent.toLocaleString()}),e.jsx(nV,{icon:Bn,color:"text-amber-500",label:"Opens",value:`${n.opened.toLocaleString()}`,sub:`${n.openRate.toFixed(1)}% open rate`}),e.jsx(nV,{icon:Kd,color:"text-green-500",label:"Clicks",value:`${n.clicked.toLocaleString()}`,sub:`${n.clickRate.toFixed(1)}% click rate`}),e.jsx(nV,{icon:uu,color:"text-destructive",label:"Failed",value:n.failed.toLocaleString()})]}),n.lastSentAt&&e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1.5",children:[e.jsx(Pn,{className:"h-3 w-3"})," Last sent: ",As(new Date(n.lastSentAt),"MMM d, yyyy h:mm a")]}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-semibold mb-2 mt-4",children:"Per-Email Performance"}),e.jsx("div",{className:"space-y-2",children:n.byEmail.map(a=>{const i=a.sent_count>0?a.opened_count/a.sent_count*100:0,l=a.sent_count>0?a.clicked_count/a.sent_count*100:0;return e.jsx(ke,{className:"overflow-hidden",children:e.jsxs(Oe,{className:"py-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"h-8 w-8 rounded-full bg-primary/10 text-primary font-bold text-xs flex items-center justify-center shrink-0",children:["#",a.email_number]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:a.title}),e.jsxs("div",{className:"flex flex-wrap gap-1.5 mt-1",children:[e.jsxs(Xe,{variant:"outline",className:"text-[10px] gap-1",children:[e.jsx(er,{className:"h-2.5 w-2.5"})," ",a.sent_count.toLocaleString()," sent"]}),e.jsxs(Xe,{variant:"outline",className:"text-[10px] gap-1 border-amber-500/30 text-amber-600",children:[e.jsx(Bn,{className:"h-2.5 w-2.5"})," ",a.opened_count.toLocaleString()," (",i.toFixed(1),"%)"]}),e.jsxs(Xe,{variant:"outline",className:"text-[10px] gap-1 border-green-500/30 text-green-600",children:[e.jsx(Kd,{className:"h-2.5 w-2.5"})," ",a.clicked_count.toLocaleString()," (",l.toFixed(1),"%)"]}),a.failed_count>0&&e.jsxs(Xe,{variant:"outline",className:"text-[10px] gap-1 border-destructive/30 text-destructive",children:[e.jsx(uu,{className:"h-2.5 w-2.5"})," ",a.failed_count.toLocaleString()," failed"]})]})]})]}),a.sent_count>0&&e.jsxs("div",{className:"mt-2 space-y-1",children:[e.jsx("div",{className:"h-1.5 bg-muted rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-amber-500 transition-all",style:{width:`${Math.min(i,100)}%`}})}),e.jsx("div",{className:"h-1.5 bg-muted rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-green-500 transition-all",style:{width:`${Math.min(l,100)}%`}})})]})]})},a.campaign_email_id)})})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground italic",children:"Open rates count when the email is loaded with images on. Click rates count any tracked link click in the email."})]})]})})}function nV({icon:s,color:t,label:r,value:n,sub:a}){return e.jsx(ke,{children:e.jsx(Oe,{className:"pt-4 pb-3",children:e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx(s,{className:`h-6 w-6 ${t}`}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-xl font-bold leading-none",children:n}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:r}),a&&e.jsx("p",{className:"text-[10px] text-muted-foreground",children:a})]})]})})})}function bvt(s){return yt({queryKey:["recruit-campaign-stats",s],enabled:!!s,staleTime:6e4,queryFn:async()=>{const{data:t,error:r}=await V.from("recruit_campaign_email_stats").select("*").eq("brokerage_id",s);if(r)throw r;const n=t??[],a={};for(const i of n){a[i.campaign_id]||(a[i.campaign_id]={campaign_id:i.campaign_id,sent:0,opened:0,clicked:0,failed:0,openRate:0,clickRate:0,byEmail:[],lastSentAt:null});const l=a[i.campaign_id];l.sent+=i.sent_count,l.opened+=i.opened_count,l.clicked+=i.clicked_count,l.failed+=i.failed_count,l.byEmail.push(i),i.last_sent_at&&(!l.lastSentAt||i.last_sent_at>l.lastSentAt)&&(l.lastSentAt=i.last_sent_at)}return Object.values(a).forEach(i=>{i.openRate=i.sent>0?i.opened/i.sent*100:0,i.clickRate=i.sent>0?i.clicked/i.sent*100:0,i.byEmail.sort((l,o)=>l.email_number-o.email_number)}),a}})}const EWe={cold:{icon:h1,color:"text-blue-500",bg:"bg-blue-50 dark:bg-blue-950/30",label:"Cold — Curiosity"},warm:{icon:W2,color:"text-amber-500",bg:"bg-amber-50 dark:bg-amber-950/30",label:"Warm — Growth"},hot:{icon:od,color:"text-red-500",bg:"bg-red-50 dark:bg-red-950/30",label:"Hot — Private Invite"}};function _vt({brokerageId:s}){var Me,ze,Pe,Ie;const{user:t}=Ms(),r=ns(),[n,a]=S.useState(null),[i,l]=S.useState(null),[o,c]=S.useState(null),[d,h]=S.useState(!1),[m,p]=S.useState(!1),[x,y]=S.useState("editor"),[_,b]=S.useState(null),[j,k]=S.useState(null),{data:T={}}=bvt(s),[E,A]=S.useState({name:"",description:"",theme:"",goal:"",primary_cta:"Learn more",warmth_level:"warm",sender_name:"",sender_email:"",reply_to_email:""}),{data:D}=yt({queryKey:["brokerage-detail",s],queryFn:async()=>{const{data:De,error:pe}=await V.from("brokerages").select("name, city, state").eq("id",s).single();if(pe)throw pe;return De}}),{data:R}=yt({queryKey:["brokerage-recruit-settings",s],queryFn:async()=>{const{data:De,error:pe}=await V.from("brokerage_recruit_settings").select("*").eq("brokerage_id",s).maybeSingle();if(pe)throw pe;return De}}),z={first_name:"Sarah",brokerage_name:((Me=R==null?void 0:R.merge_fields)==null?void 0:Me.brokerage_name)||(D==null?void 0:D.name)||"Your Brokerage",city:((ze=R==null?void 0:R.merge_fields)==null?void 0:ze.city)||(D==null?void 0:D.city)||"Your City",sender_name:((Pe=R==null?void 0:R.merge_fields)==null?void 0:Pe.sender_name)||(R==null?void 0:R.sender_name)||"Your Name"},O=De=>De.replace(/\{\{first_name\}\}/g,z.first_name).replace(/\{\{brokerage_name\}\}/g,z.brokerage_name).replace(/\{\{city\}\}/g,z.city).replace(/\{\{sender_name\}\}/g,z.sender_name),{data:$=[],isLoading:ee}=yt({queryKey:["recruit-campaigns",s],queryFn:async()=>{const{data:De,error:pe}=await V.from("recruit_campaigns").select("*").or(`brokerage_id.is.null,brokerage_id.eq.${s}`).order("sort_order");if(pe)throw pe;return De}}),{data:Z={}}=yt({queryKey:["recruit-campaign-emails",s],enabled:$.length>0,queryFn:async()=>{const De=$.map(ct=>ct.id),{data:pe,error:tt}=await V.from("recruit_campaign_emails").select("*").in("campaign_id",De).order("email_number");if(tt)throw tt;const ge={};return pe.forEach(ct=>{ge[ct.campaign_id]||(ge[ct.campaign_id]=[]),ge[ct.campaign_id].push(ct)}),ge}}),J=Object.values(Z).flat().map(De=>De.id),{data:K=[]}=yt({queryKey:["recruit-subject-overrides",s],enabled:J.length>0,queryFn:async()=>{const{data:De,error:pe}=await V.from("recruit_brokerage_subject_overrides").select("*").eq("brokerage_id",s);if(pe)throw pe;return De}}),re={};K.forEach(De=>{re[De.campaign_email_id]=De.selected_subject_index});const ie=Pt({mutationFn:async({campaignEmailId:De,selectedIndex:pe})=>{const{error:tt}=await V.from("recruit_brokerage_subject_overrides").upsert({brokerage_id:s,campaign_email_id:De,selected_subject_index:pe,updated_at:new Date().toISOString()},{onConflict:"brokerage_id,campaign_email_id"});if(tt)throw tt},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-subject-overrides",s]}),he.success("Subject line updated for your brokerage")},onError:De=>he.error(De.message)}),ce=Pt({mutationFn:async De=>{const{error:pe}=await V.from("recruit_campaign_emails").update({title:De.title,subject_line:De.subject_line,subject_line_options:De.subject_line_options,body_html:De.body_html,body_text:De.body_text,delay_days:De.delay_days,updated_at:new Date().toISOString()}).eq("id",De.id);if(pe)throw pe},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-campaign-emails"]}),he.success("Email template saved!"),l(null)},onError:De=>he.error(De.message)}),ne=Pt({mutationFn:async()=>{const De=E.name.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,""),{data:pe,error:tt}=await V.from("recruit_campaigns").insert({name:E.name,slug:De,description:E.description||null,theme:E.theme||null,goal:E.goal||null,primary_cta:E.primary_cta||"Learn more",warmth_level:E.warmth_level,brokerage_id:s,created_by:t==null?void 0:t.id,sender_name:E.sender_name||null,sender_email:E.sender_email||null,reply_to_email:E.reply_to_email||null,is_active:!0,sort_order:$.length+1}).select().single();if(tt)throw tt;const ge=[{email_number:1,title:"Introduction",subject_line:"Hey {{first_name}}, quick question",delay_days:0},{email_number:2,title:"Follow Up",subject_line:"Following up, {{first_name}}",delay_days:7},{email_number:3,title:"Value Add",subject_line:"{{first_name}}, thought you'd want to see this",delay_days:14},{email_number:4,title:"Final Touch",subject_line:"Last note, {{first_name}}",delay_days:21}],{error:ct}=await V.from("recruit_campaign_emails").insert(ge.map(Ue=>({campaign_id:pe.id,...Ue,body_html:"

Hi {{first_name}},

Write your message here...

Best,
{{sender_name}}

",body_text:"",subject_line_options:[],is_active:!0})));if(ct)throw ct;return pe},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-campaigns"]}),r.invalidateQueries({queryKey:["recruit-campaign-emails"]}),he.success("Campaign created with 4 starter emails!"),p(!1),A({name:"",description:"",theme:"",goal:"",primary_cta:"Learn more",warmth_level:"warm",sender_name:"",sender_email:"",reply_to_email:""})},onError:De=>he.error(De.message)}),le=Pt({mutationFn:async De=>{const{error:pe}=await V.from("recruit_campaigns").update({name:De.name,description:De.description,theme:De.theme,goal:De.goal,primary_cta:De.primary_cta,warmth_level:De.warmth_level,sender_name:De.sender_name,sender_email:De.sender_email,reply_to_email:De.reply_to_email,updated_at:new Date().toISOString()}).eq("id",De.id);if(pe)throw pe},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-campaigns"]}),he.success("Campaign settings saved!"),b(null)},onError:De=>he.error(De.message)}),be=Pt({mutationFn:async De=>{var et,Qe;const{data:pe}=await V.from("recruit_campaign_emails").select("email_number, delay_days").eq("campaign_id",De).order("email_number",{ascending:!1}).limit(1),tt=((et=pe==null?void 0:pe[0])==null?void 0:et.email_number)??0,ge=((Qe=pe==null?void 0:pe[0])==null?void 0:Qe.delay_days)??0,ct=tt+1,{error:Ue}=await V.from("recruit_campaign_emails").insert({campaign_id:De,email_number:ct,title:`Email ${ct}`,subject_line:"Hey {{first_name}}",subject_line_options:[],body_html:"

Hi {{first_name}},

Write your message here...

Best,
{{sender_name}}

",body_text:"",delay_days:ge+7,is_active:!0});if(Ue)throw Ue},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-campaign-emails"]}),he.success("Email added to campaign!")},onError:De=>he.error(De.message)}),fe=Pt({mutationFn:async De=>{const{error:pe}=await V.from("recruit_campaigns").delete().eq("id",De);if(pe)throw pe},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-campaigns"]}),r.invalidateQueries({queryKey:["recruit-campaign-emails"]}),he.success("Campaign deleted")},onError:De=>he.error(De.message)}),je=Pt({mutationFn:async De=>{const{error:pe}=await V.from("recruit_campaign_emails").delete().eq("id",De);if(pe)throw pe},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-campaign-emails"]}),he.success("Email removed from campaign")},onError:De=>he.error(De.message)}),ve=Pt({mutationFn:async({emailId:De,delay_days:pe})=>{const{error:tt}=await V.from("recruit_campaign_emails").update({delay_days:pe,updated_at:new Date().toISOString()}).eq("id",De);if(tt)throw tt},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-campaign-emails"]}),he.success("Send delay updated")},onError:De=>he.error(De.message)});if(ee)return e.jsx("div",{className:"flex justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})});const We=$.filter(De=>!De.brokerage_id),Ve=$.filter(De=>De.brokerage_id===s);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-bold",children:"Recruiting Campaigns"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"System campaigns + custom campaigns · Each can have its own email settings"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(H,{variant:"outline",size:"sm",onClick:()=>h(!0),className:"gap-1.5",children:[e.jsx(Go,{className:"h-4 w-4"})," Default Settings"]}),e.jsxs(H,{size:"sm",onClick:()=>p(!0),className:"gap-1.5",children:[e.jsx(Ys,{className:"h-4 w-4"})," New Campaign"]})]})]}),e.jsx(ke,{className:"border-primary/20 bg-primary/5",children:e.jsx(Oe,{className:"py-3",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Lr,{className:"h-5 w-5 text-primary mt-0.5 shrink-0"}),e.jsxs("div",{className:"text-sm",children:[e.jsx("p",{className:"font-semibold",children:"Per-Campaign Email Settings"}),e.jsxs("p",{className:"text-muted-foreground",children:["Each campaign can override the default sender name, email, and reply-to. Click the ",e.jsx(Go,{className:"inline h-3.5 w-3.5"})," icon on any campaign to customize."]})]})]})})}),Ve.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h3",{className:"text-sm font-semibold text-muted-foreground uppercase tracking-wider flex items-center gap-2",children:[e.jsx(yF,{className:"h-4 w-4"})," Your Custom Campaigns"]}),e.jsx("div",{className:"space-y-3",children:Ve.map(De=>Le(De,!0))})]}),We.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h3",{className:"text-sm font-semibold text-muted-foreground uppercase tracking-wider flex items-center gap-2",children:[e.jsx(Lr,{className:"h-4 w-4"})," System Campaigns"]}),e.jsx("div",{className:"space-y-3",children:We.map(De=>Le(De,!1))})]}),$.length===0&&e.jsx(ke,{children:e.jsxs(Oe,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(er,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No campaigns yet. Create your first campaign to start automated outreach."}),e.jsxs(H,{className:"mt-4",onClick:()=>p(!0),children:[e.jsx(Ys,{className:"h-4 w-4 mr-1"})," Create Campaign"]})]})}),e.jsx(bzs,{open:!!j,onClose:()=>k(null),campaignName:(j==null?void 0:j.name)||"",stat:j&&T[j.id]||null}),o&&e.jsx(vvt,{email:o,mergeValues:z,selectedSubjectIndex:re[o.id],onClose:()=>c(null)}),e.jsx(bs,{open:!!i,onOpenChange:De=>!De&&l(null),children:e.jsxs(vs,{className:"max-w-4xl max-h-[90vh] overflow-y-auto p-0",children:[e.jsxs(Cs,{className:"px-6 pt-6 pb-4 border-b",children:[e.jsxs(Ns,{className:"flex items-center gap-2",children:[e.jsx($k,{className:"h-5 w-5 text-primary"}),"Edit Email #",i==null?void 0:i.email_number]}),e.jsx(nn,{children:i==null?void 0:i.title})]}),i&&e.jsxs("div",{className:"px-6 py-5 space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Email Title"}),e.jsx(Se,{value:i.title,onChange:De=>l({...i,title:De.target.value}),className:"h-9"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Delay (days after previous)"}),e.jsx(Se,{type:"number",min:0,max:90,value:i.delay_days,onChange:De=>l({...i,delay_days:parseInt(De.target.value)||7}),className:"h-9"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Subject Line"}),e.jsx(Se,{value:i.subject_line,onChange:De=>l({...i,subject_line:De.target.value}),placeholder:"e.g. Hey {{first_name}}, quick question...",className:"h-9"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(ue,{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:["Alternative Subject Lines ",e.jsx("span",{className:"text-muted-foreground font-normal normal-case",children:"(one per line, for A/B testing)"})]}),e.jsx(vr,{value:((Ie=i.subject_line_options)==null?void 0:Ie.join(` `))||"",onChange:De=>l({...i,subject_line_options:De.target.value.split(` `).filter(Boolean)}),rows:2,className:"text-sm resize-none"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ue,{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Email Body"}),e.jsx(ta,{value:x,onValueChange:De=>y(De),children:e.jsxs(Qn,{className:"h-7",children:[e.jsx(ts,{value:"editor",className:"text-xs px-3 h-6",children:"Editor"}),e.jsx(ts,{value:"preview",className:"text-xs px-3 h-6",children:"Preview"})]})})]}),x==="editor"?e.jsx(vzs,{content:i.body_html,onChange:De=>l({...i,body_html:De})}):e.jsxs("div",{className:"border rounded-xl overflow-hidden",children:[e.jsxs("div",{className:"bg-muted/50 px-4 py-2 border-b space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx("span",{className:"font-medium w-12",children:"From:"}),e.jsxs("span",{children:[z.sender_name," "]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx("span",{className:"font-medium w-12",children:"To:"}),e.jsxs("span",{children:[z.first_name," "]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx("span",{className:"font-medium w-12 text-muted-foreground",children:"Subject:"}),e.jsx("span",{className:"font-medium",children:O(i.subject_line)})]})]}),e.jsx("div",{className:"bg-white p-6",children:e.jsx("div",{className:"prose prose-sm max-w-none",style:{fontSize:"15px",lineHeight:"1.75",color:"#1a1a1a"},dangerouslySetInnerHTML:{__html:O(i.body_html)}})})]})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Changes are saved to this campaign's templates"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(H,{variant:"outline",size:"sm",onClick:()=>l(null),children:"Cancel"}),e.jsxs(H,{size:"sm",onClick:()=>ce.mutate(i),disabled:ce.isPending,className:"gap-1.5",children:[e.jsx(vc,{className:"h-3.5 w-3.5"})," Save Changes"]})]})]})]})]})}),e.jsx(bs,{open:m,onOpenChange:p,children:e.jsxs(vs,{className:"max-w-lg",children:[e.jsxs(Cs,{children:[e.jsxs(Ns,{className:"flex items-center gap-2",children:[e.jsx(Ys,{className:"h-5 w-5 text-primary"})," Create Custom Campaign"]}),e.jsx(nn,{children:"Build your own recruiting email sequence with custom sender settings."})]}),e.jsxs("div",{className:"space-y-4 pt-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{className:"text-xs font-medium",children:"Campaign Name *"}),e.jsx(Se,{value:E.name,onChange:De=>A({...E,name:De.target.value}),placeholder:"e.g. Q2 Agent Outreach"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{className:"text-xs font-medium",children:"Warmth Level"}),e.jsxs(Bs,{value:E.warmth_level,onValueChange:De=>A({...E,warmth_level:De}),children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"cold",children:"❄️ Cold — Curiosity"}),e.jsx(pt,{value:"warm",children:"☀️ Warm — Growth"}),e.jsx(pt,{value:"hot",children:"🔥 Hot — Private Invite"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{className:"text-xs font-medium",children:"Primary CTA"}),e.jsx(Se,{value:E.primary_cta,onChange:De=>A({...E,primary_cta:De.target.value}),placeholder:"Learn more"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{className:"text-xs font-medium",children:"Description"}),e.jsx(vr,{value:E.description,onChange:De=>A({...E,description:De.target.value}),placeholder:"What is this campaign about?",rows:2})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{className:"text-xs font-medium",children:"Goal"}),e.jsx(Se,{value:E.goal,onChange:De=>A({...E,goal:De.target.value}),placeholder:"e.g. Convert warm leads to meetings"})]}),e.jsxs(m0,{children:[e.jsx(f0,{asChild:!0,children:e.jsxs(H,{variant:"ghost",size:"sm",className:"w-full justify-between text-xs font-medium text-muted-foreground hover:text-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(er,{className:"h-3.5 w-3.5"})," Email Settings Override"]}),e.jsx(Io,{className:"h-3.5 w-3.5"})]})}),e.jsxs(p0,{className:"space-y-3 pt-2",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Leave blank to use brokerage defaults."}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{className:"text-xs",children:"Sender Name"}),e.jsx(Se,{value:E.sender_name,onChange:De=>A({...E,sender_name:De.target.value}),placeholder:"e.g. Jeremy at LevelUp"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{className:"text-xs",children:"Sender Email"}),e.jsx(Se,{value:E.sender_email,onChange:De=>A({...E,sender_email:De.target.value}),placeholder:"e.g. recruiting@send.relevelup.com"}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Must be a verified sending domain"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{className:"text-xs",children:"Reply-To Email"}),e.jsx(Se,{value:E.reply_to_email,onChange:De=>A({...E,reply_to_email:De.target.value}),placeholder:"e.g. jeremy@mybrokerage.com"})]})]})]}),e.jsxs(H,{className:"w-full",disabled:!E.name.trim()||ne.isPending,onClick:()=>ne.mutate(),children:[e.jsx(Ys,{className:"h-4 w-4 mr-1"})," Create Campaign"]})]})]})}),e.jsx(bs,{open:!!_,onOpenChange:De=>!De&&b(null),children:e.jsxs(vs,{className:"max-w-lg",children:[e.jsxs(Cs,{children:[e.jsxs(Ns,{className:"flex items-center gap-2",children:[e.jsx(Go,{className:"h-5 w-5 text-primary"})," Campaign Email Settings"]}),e.jsx(nn,{children:"Override the default sender for this campaign. Leave blank to use brokerage defaults."})]}),_&&e.jsxs("div",{className:"space-y-4 pt-2",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{className:"text-xs font-medium",children:"Campaign Name"}),e.jsx(Se,{value:_.name,onChange:De=>b({..._,name:De.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{className:"text-xs font-medium",children:"Warmth Level"}),e.jsxs(Bs,{value:_.warmth_level,onValueChange:De=>b({..._,warmth_level:De}),children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"cold",children:"❄️ Cold"}),e.jsx(pt,{value:"warm",children:"☀️ Warm"}),e.jsx(pt,{value:"hot",children:"🔥 Hot"})]})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{className:"text-xs font-medium",children:"Goal"}),e.jsx(Se,{value:_.goal||"",onChange:De=>b({..._,goal:De.target.value})})]}),e.jsxs("div",{className:"border-t pt-4 space-y-3",children:[e.jsxs("p",{className:"text-sm font-semibold flex items-center gap-1.5",children:[e.jsx(er,{className:"h-4 w-4 text-primary"})," Email Sender Override"]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{className:"text-xs",children:"Sender Name"}),e.jsx(Se,{value:_.sender_name||"",onChange:De=>b({..._,sender_name:De.target.value}),placeholder:"Uses brokerage default"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{className:"text-xs",children:"Sender Email"}),e.jsx(Se,{value:_.sender_email||"",onChange:De=>b({..._,sender_email:De.target.value}),placeholder:"Uses brokerage default"}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Must be a verified sending domain"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{className:"text-xs",children:"Reply-To Email"}),e.jsx(Se,{value:_.reply_to_email||"",onChange:De=>b({..._,reply_to_email:De.target.value}),placeholder:"Uses brokerage default"})]})]}),e.jsxs(H,{className:"w-full",onClick:()=>le.mutate(_),disabled:le.isPending,children:[e.jsx(vc,{className:"h-4 w-4 mr-1"})," Save Campaign Settings"]})]})]})}),e.jsx(bs,{open:d,onOpenChange:h,children:e.jsxs(vs,{className:"max-w-lg",children:[e.jsxs(Cs,{children:[e.jsx(Ns,{children:"Default Recruiting Email Settings"}),e.jsx(nn,{children:"These defaults apply to campaigns without their own overrides."})]}),e.jsx(y6e,{brokerageId:s})]})})]});function Le(De,pe){const tt=EWe[De.warmth_level]||EWe.cold,ge=tt.icon,ct=Z[De.id]||[],Ue=n===De.id,et=!!(De.sender_name||De.sender_email||De.reply_to_email),Qe=T[De.id];return e.jsxs(ke,{className:"overflow-hidden transition-shadow hover:shadow-md",children:[e.jsx(Ot,{className:"cursor-pointer hover:bg-muted/40 transition-colors py-4",onClick:()=>a(Ue?null:De.id),children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:`h-11 w-11 rounded-xl ${tt.bg} flex items-center justify-center`,children:e.jsx(ge,{className:`h-5 w-5 ${tt.color}`})}),e.jsxs("div",{children:[e.jsxs(zt,{className:"text-base flex items-center gap-2",children:[De.name,e.jsx(Xe,{variant:De.is_active?"default":"secondary",className:"text-[10px] px-1.5",children:De.is_active?"Active":"Draft"}),pe&&e.jsx(Xe,{variant:"outline",className:"text-[10px] px-1.5",children:"Custom"}),et&&e.jsxs(Xe,{variant:"outline",className:"text-[10px] px-1.5 border-primary/30 text-primary",children:[e.jsx(er,{className:"h-2.5 w-2.5 mr-0.5"})," Custom Sender"]})]}),e.jsx(Br,{className:"text-xs mt-0.5",children:De.theme||De.description})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(H,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:Ne=>{Ne.stopPropagation(),b({...De})},children:e.jsx(Go,{className:"h-4 w-4 text-muted-foreground"})}),pe&&e.jsx(H,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:Ne=>{Ne.stopPropagation(),confirm("Delete this campaign and all its emails? This cannot be undone.")&&fe.mutate(De.id)},children:e.jsx(Dr,{className:"h-4 w-4"})}),Qe&&Qe.sent>0&&e.jsxs("div",{className:"hidden md:flex items-center gap-1.5",children:[e.jsxs(Xe,{variant:"outline",className:"text-[10px] gap-1 font-medium",title:"Total emails sent",children:[e.jsx(er,{className:"h-2.5 w-2.5"})," ",Qe.sent.toLocaleString()]}),e.jsxs(Xe,{variant:"outline",className:"text-[10px] gap-1 border-amber-500/30 text-amber-600 font-medium",title:`${Qe.openRate.toFixed(1)}% open rate`,children:[e.jsx(Bn,{className:"h-2.5 w-2.5"})," ",Qe.opened.toLocaleString()," (",Qe.openRate.toFixed(0),"%)"]}),e.jsxs(Xe,{variant:"outline",className:"text-[10px] gap-1 border-green-500/30 text-green-600 font-medium",title:`${Qe.clickRate.toFixed(1)}% click rate`,children:[e.jsx(Kd,{className:"h-2.5 w-2.5"})," ",Qe.clicked.toLocaleString()," (",Qe.clickRate.toFixed(1),"%)"]})]}),e.jsxs(H,{variant:"outline",size:"sm",className:"h-7 px-2 gap-1 text-xs",onClick:Ne=>{Ne.stopPropagation(),k(De)},title:"View detailed engagement stats",children:[e.jsx(Bo,{className:"h-3.5 w-3.5"})," Stats"]}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(er,{className:"h-3.5 w-3.5"}),e.jsxs("span",{children:[ct.length," emails"]})]}),e.jsx("div",{className:"h-7 w-7 rounded-md flex items-center justify-center",children:Ue?e.jsx(cx,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(Io,{className:"h-4 w-4 text-muted-foreground"})})]})]})}),Ue&&e.jsxs(Oe,{className:"pt-0 pb-4 space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4 p-3 rounded-lg bg-muted/40 text-sm",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Goal"}),e.jsx("p",{className:"mt-0.5",children:De.goal||"—"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Primary CTA"}),e.jsx("p",{className:"mt-0.5",children:De.primary_cta||"—"})]})]}),et&&e.jsxs("div",{className:"p-3 rounded-lg bg-primary/5 border border-primary/10 text-sm",children:[e.jsxs("p",{className:"text-xs font-semibold text-primary mb-1 flex items-center gap-1",children:[e.jsx(er,{className:"h-3 w-3"})," Campaign Sender Override"]}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 text-xs text-muted-foreground",children:[De.sender_name&&e.jsxs("p",{children:[e.jsx("span",{className:"font-medium",children:"Name:"})," ",De.sender_name]}),De.sender_email&&e.jsxs("p",{children:[e.jsx("span",{className:"font-medium",children:"Email:"})," ",De.sender_email]}),De.reply_to_email&&e.jsxs("p",{children:[e.jsx("span",{className:"font-medium",children:"Reply-To:"})," ",De.reply_to_email]})]})]}),e.jsx("div",{className:"relative",children:ct.map((Ne,$e)=>{var it,Je;return e.jsxs("div",{className:"relative flex gap-4 pb-4 last:pb-0",children:[$est.stopPropagation(),onBlur:st=>{const mt=parseInt(st.target.value)||0;mt!==Ne.delay_days&&ve.mutate({emailId:Ne.id,delay_days:mt})},onKeyDown:st=>{st.key==="Enter"&&st.target.blur()}}),"days"]})]}):e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Pn,{className:"h-3 w-3"}),Ne.email_number===1?"Sent immediately":`Day ${Ne.delay_days}`]}),e.jsx("span",{className:"text-border",children:"•"}),e.jsxs("span",{className:"truncate",children:["Subject: ",O(((it=Ne.subject_line_options)==null?void 0:it.length)>0&&Ne.subject_line_options[re[Ne.id]??0]||Ne.subject_line)]})]}),((Je=Ne.subject_line_options)==null?void 0:Je.length)>1&&e.jsx("div",{className:"mt-2",children:e.jsxs(Bs,{value:String(re[Ne.id]??0),onValueChange:st=>ie.mutate({campaignEmailId:Ne.id,selectedIndex:parseInt(st)}),children:[e.jsx(Os,{className:"h-7 text-xs w-full max-w-sm",children:e.jsx(Us,{placeholder:"Choose subject line"})}),e.jsx(Fs,{children:Ne.subject_line_options.map((st,mt)=>e.jsxs(pt,{value:String(mt),className:"text-xs",children:[e.jsxs("span",{className:"font-medium mr-1.5",children:[mt===0?"Primary":`Alt ${mt}`,":"]}),O(st)]},mt))})]})})]}),e.jsxs("div",{className:"flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity shrink-0",children:[e.jsx(H,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>c(Ne),children:e.jsx(Bn,{className:"h-4 w-4"})}),e.jsx(H,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>{l({...Ne}),y("editor")},children:e.jsx(ni,{className:"h-4 w-4"})}),pe&&ct.length>1&&e.jsx(H,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:()=>{confirm("Delete this email from the sequence?")&&je.mutate(Ne.id)},children:e.jsx(Dr,{className:"h-4 w-4"})})]})]})})]},Ne.id)})}),pe&&e.jsxs(H,{variant:"outline",size:"sm",className:"w-full gap-1.5",onClick:()=>be.mutate(De.id),disabled:be.isPending,children:[e.jsx(Ys,{className:"h-3.5 w-3.5"})," Add Email to Sequence"]})]})]},De.id)}}const AWe={active:{icon:El,color:"bg-green-500/10 text-green-600",label:"Active"},paused:{icon:Hf,color:"bg-amber-500/10 text-amber-600",label:"Paused"},completed:{icon:zi,color:"bg-blue-500/10 text-blue-600",label:"Completed"},cancelled:{icon:kd,color:"bg-red-500/10 text-red-600",label:"Cancelled"}},MWe={sent:{icon:er,color:"text-blue-500"},opened:{icon:Bn,color:"text-amber-500"},clicked:{icon:Kd,color:"text-green-500"},failed:{icon:uu,color:"text-destructive"}};function wvt({brokerageId:s}){var Me,ze,Pe,Ie,De;const{user:t}=Ms(),r=ns(),[n,a]=S.useState(!1),[i,l]=S.useState(""),[o,c]=S.useState(new Set),[d,h]=S.useState("assignments"),[m,p]=S.useState(null),[x,y]=S.useState(""),[_,b]=S.useState("all"),[j,k]=S.useState("all"),{data:T={}}=yt({queryKey:["recruit-campaign-emails-for-preview",s],queryFn:async()=>{const{data:pe,error:tt}=await V.from("recruit_campaign_emails").select("*").order("email_number");if(tt)throw tt;const ge={};return(pe??[]).forEach(ct=>{ge[ct.campaign_id]||(ge[ct.campaign_id]=[]),ge[ct.campaign_id].push(ct)}),ge}}),{data:E}=yt({queryKey:["brokerage-detail",s],queryFn:async()=>{const{data:pe,error:tt}=await V.from("brokerages").select("name, city, state").eq("id",s).single();if(tt)throw tt;return pe}}),{data:A}=yt({queryKey:["brokerage-recruit-settings",s],queryFn:async()=>{const{data:pe,error:tt}=await V.from("brokerage_recruit_settings").select("*").eq("brokerage_id",s).maybeSingle();if(tt)throw tt;return pe}}),{data:D=[]}=yt({queryKey:["recruit-subject-overrides",s],queryFn:async()=>{const{data:pe,error:tt}=await V.from("recruit_brokerage_subject_overrides").select("*").eq("brokerage_id",s);if(tt)throw tt;return pe}}),R={};D.forEach(pe=>{R[pe.campaign_email_id]=pe.selected_subject_index});const z={first_name:((Me=m==null?void 0:m.prospect)==null?void 0:Me.first_name)||"Sarah",brokerage_name:((ze=A==null?void 0:A.merge_fields)==null?void 0:ze.brokerage_name)||(E==null?void 0:E.name)||"Your Brokerage",city:((Pe=A==null?void 0:A.merge_fields)==null?void 0:Pe.city)||(E==null?void 0:E.city)||"Your City",sender_name:((Ie=A==null?void 0:A.merge_fields)==null?void 0:Ie.sender_name)||(A==null?void 0:A.sender_name)||"Your Name"},O=pe=>{const tt=T[pe.campaign_id]||[],ge=pe.current_email_number+1;return tt.find(ct=>ct.email_number===ge)||null},{data:$=[],isLoading:ee}=yt({queryKey:["recruit-campaign-assignments",s],queryFn:async()=>{let tt=[],ge=0;for(;;){const{data:ct,error:Ue}=await V.from("recruit_campaign_assignments").select(` *, prospect:recruit_prospects(first_name, last_name, email), campaign:recruit_campaigns(name, warmth_level) `).eq("brokerage_id",s).order("created_at",{ascending:!1}).range(ge,ge+1e3-1);if(Ue)throw Ue;if(tt=tt.concat(ct??[]),!ct||ct.length<1e3)break;ge+=1e3}return tt}}),{data:Z=[]}=yt({queryKey:["recruit-campaign-sends",s],queryFn:async()=>{const{data:pe,error:tt}=await V.from("recruit_campaign_sends").select(` *, prospect:recruit_prospects(first_name, last_name, email), campaign_email:recruit_campaign_emails(title, campaign_id) `).eq("brokerage_id",s).neq("status","failed").order("sent_at",{ascending:!1}).limit(500);if(tt)throw tt;return pe}}),{data:J=[]}=yt({queryKey:["recruit-campaigns"],queryFn:async()=>{const{data:pe,error:tt}=await V.from("recruit_campaigns").select("id, name, warmth_level").eq("is_active",!0).order("sort_order");if(tt)throw tt;return pe}}),{data:K=[]}=yt({queryKey:["recruit-prospects-for-assign",s],queryFn:async()=>{let tt=[],ge=0;for(;;){const{data:ct,error:Ue}=await V.from("recruit_prospects").select("id, first_name, last_name, email").eq("brokerage_id",s).order("first_name").range(ge,ge+1e3-1);if(Ue)throw Ue;if(tt=tt.concat(ct??[]),!ct||ct.length<1e3)break;ge+=1e3}return tt}}),re=new Set($.map(pe=>`${pe.prospect_id}-${pe.campaign_id}`)),ie=Pt({mutationFn:async()=>{if(!i||o.size===0)throw new Error("Select a campaign and at least one prospect");const pe=new Date,tt=Array.from(o).filter(ct=>!re.has(`${ct}-${i}`)).map(ct=>({prospect_id:ct,campaign_id:i,brokerage_id:s,assigned_by:t.id,status:"active",current_email_number:0,next_send_at:pe.toISOString(),started_at:pe.toISOString()}));if(tt.length===0)throw new Error("All selected prospects are already assigned to this campaign");const{error:ge}=await V.from("recruit_campaign_assignments").insert(tt);if(ge)throw ge},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-campaign-assignments",s]}),he.success(`Campaign assigned to ${o.size} prospect(s)!`),a(!1),l(""),c(new Set)},onError:pe=>he.error(pe.message)}),ce=Pt({mutationFn:async({id:pe,newStatus:tt})=>{const{error:ge}=await V.from("recruit_campaign_assignments").update({status:tt,updated_at:new Date().toISOString()}).eq("id",pe);if(ge)throw ge},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-campaign-assignments",s]}),he.success("Assignment updated")}}),ne=Pt({mutationFn:async()=>{const{data:pe,error:tt}=await V.functions.invoke("ses-recruit-drip",{body:{action:"process_drips"}});if(tt)throw tt;return pe},onSuccess:pe=>{r.invalidateQueries({queryKey:["recruit-campaign-assignments",s]}),r.invalidateQueries({queryKey:["recruit-campaign-sends",s]}),he.success(`Wave sent! ${pe.sent} emails delivered, ${pe.skipped} skipped, ${pe.failed} failed`)},onError:pe=>he.error(`Send failed: ${pe.message}`)}),le=$.filter(pe=>pe.status==="active").length;$.filter(pe=>pe.status==="completed").length;const be=$.filter(pe=>pe.status==="active"&&pe.next_send_at&&new Date(pe.next_send_at)<=new Date).length,{data:fe={}}=bvt(s),je=$.reduce((pe,tt)=>pe+Math.max(0,tt.current_email_number||0),0),ve=Object.values(fe).reduce((pe,tt)=>pe+tt.opened,0),We=Object.values(fe).reduce((pe,tt)=>pe+tt.clicked,0);Object.values(fe).reduce((pe,tt)=>pe+tt.failed,0);const Ve=je>0?Math.round(ve/je*100):0,Le=je>0?We/je*100:0;return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-bold",children:"Campaign Assignments"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Assign recruiting campaigns to prospects — emails auto-send weekly via SES"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[be>0&&e.jsxs(H,{variant:"outline",onClick:()=>ne.mutate(),disabled:ne.isPending,className:"border-amber-500/50 text-amber-600 hover:bg-amber-500/10",children:[e.jsx(ym,{className:"h-4 w-4 mr-1"}),ne.isPending?"Sending...":`Send Next Wave (${be})`]}),e.jsxs(H,{onClick:()=>a(!0),children:[e.jsx(yn,{className:"h-4 w-4 mr-1"})," Assign Campaign"]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3",children:[e.jsx(ke,{children:e.jsxs(Oe,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(Ar,{className:"h-7 w-7 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xl font-bold",children:$.length}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Assigned"})]})]})}),e.jsx(ke,{children:e.jsxs(Oe,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(El,{className:"h-7 w-7 text-green-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xl font-bold",children:le}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Active"})]})]})}),e.jsx(ke,{children:e.jsxs(Oe,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(er,{className:"h-7 w-7 text-blue-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xl font-bold",children:je.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Emails Sent"})]})]})}),e.jsx(ke,{children:e.jsxs(Oe,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(Bn,{className:"h-7 w-7 text-amber-500"}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-xl font-bold",children:[Ve,"%"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Open Rate (",ve.toLocaleString(),")"]})]})]})}),e.jsx(ke,{children:e.jsxs(Oe,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(Kd,{className:"h-7 w-7 text-green-500"}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-xl font-bold",children:[Le.toFixed(1),"%"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Click Rate (",We.toLocaleString(),")"]})]})]})})]}),e.jsxs(ta,{value:d,onValueChange:h,children:[e.jsxs(Qn,{children:[e.jsxs(ts,{value:"assignments",children:["Active Drips (",le,")"]}),e.jsxs(ts,{value:"history",children:["Send History (",je.toLocaleString(),")"]})]}),e.jsx(cs,{value:"assignments",className:"mt-4",children:ee?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-2 border-primary border-t-transparent"})}):$.length===0?e.jsx(ke,{children:e.jsxs(Oe,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(yn,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{className:"font-medium",children:"No campaigns assigned yet"}),e.jsx("p",{className:"text-sm",children:"Assign a recruiting campaign to your prospects to start automated outreach"})]})}):e.jsx("div",{className:"space-y-2",children:$.map(pe=>{var Qe,Ne,$e,it;const tt=AWe[pe.status]||AWe.active,ge=tt.icon,Ue=(T[pe.campaign_id]||[]).length||4,et=O(pe);return e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border hover:bg-muted/30 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsxs(Xe,{className:`text-xs ${tt.color} border-0`,children:[e.jsx(ge,{className:"h-3 w-3 mr-1"}),tt.label]}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("p",{className:"font-medium text-sm",children:[(Qe=pe.prospect)==null?void 0:Qe.first_name," ",(Ne=pe.prospect)==null?void 0:Ne.last_name,e.jsx("span",{className:"text-muted-foreground font-normal ml-2",children:($e=pe.prospect)==null?void 0:$e.email})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(it=pe.campaign)==null?void 0:it.name," · Email ",pe.current_email_number,"/",Ue,pe.next_send_at&&pe.status==="active"&&e.jsxs(e.Fragment,{children:[" ","· ",e.jsx(Pn,{className:"h-3 w-3 inline"})," Next: ",As(new Date(pe.next_send_at),"MMM d, h:mm a"),new Date(pe.next_send_at)<=new Date&&e.jsx(Xe,{variant:"outline",className:"ml-1 text-[10px] px-1 py-0 border-amber-500 text-amber-600",children:"DUE"})]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[et&&e.jsx(H,{variant:"ghost",size:"sm",title:"Preview next email",onClick:()=>p(pe),children:e.jsx(Bn,{className:"h-3.5 w-3.5"})}),pe.status==="active"&&e.jsx(H,{variant:"ghost",size:"sm",onClick:()=>ce.mutate({id:pe.id,newStatus:"paused"}),children:e.jsx(Hf,{className:"h-3.5 w-3.5"})}),pe.status==="paused"&&e.jsx(H,{variant:"ghost",size:"sm",onClick:()=>ce.mutate({id:pe.id,newStatus:"active"}),children:e.jsx(El,{className:"h-3.5 w-3.5"})}),(pe.status==="active"||pe.status==="paused")&&e.jsx(H,{variant:"ghost",size:"sm",className:"text-destructive",onClick:()=>ce.mutate({id:pe.id,newStatus:"cancelled"}),children:e.jsx(kd,{className:"h-3.5 w-3.5"})})]})]},pe.id)})})}),e.jsxs(cs,{value:"history",className:"mt-4 space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Filter:"}),e.jsxs(Bs,{value:_,onValueChange:b,children:[e.jsx(Os,{className:"w-[220px] h-8 text-xs",children:e.jsx(Us,{placeholder:"All campaigns"})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"all",children:"All campaigns"}),J.map(pe=>e.jsx(pt,{value:pe.id,children:pe.name},pe.id))]})]}),e.jsxs(Bs,{value:j,onValueChange:k,children:[e.jsx(Os,{className:"w-[160px] h-8 text-xs",children:e.jsx(Us,{placeholder:"All statuses"})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"all",children:"All statuses"}),e.jsx(pt,{value:"sent",children:"Sent (no engagement)"}),e.jsx(pt,{value:"opened",children:"Opened"}),e.jsx(pt,{value:"clicked",children:"Clicked"})]})]}),(_!=="all"||j!=="all")&&e.jsx(H,{variant:"ghost",size:"sm",className:"h-8 text-xs",onClick:()=>{b("all"),k("all")},children:"Clear"})]}),(()=>{var tt;const pe=Z.filter(ge=>{var ct;return!(_!=="all"&&((ct=ge.campaign_email)==null?void 0:ct.campaign_id)!==_||j==="opened"&&!ge.opened_at||j==="clicked"&&!ge.clicked_at||j==="sent"&&(ge.opened_at||ge.clicked_at))});return pe.length===0?e.jsx(ke,{children:e.jsxs(Oe,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(er,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{className:"font-medium",children:Z.length===0?"No emails sent yet":"No emails match these filters"}),e.jsx("p",{className:"text-sm",children:Z.length===0?"Emails will appear here once campaigns start sending":"Try clearing the filters above"})]})}):e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Showing ",pe.length," of ",Z.length," recent sends",_!=="all"&&` · ${(tt=J.find(ge=>ge.id===_))==null?void 0:tt.name}`]}),e.jsx("div",{className:"space-y-1",children:pe.map(ge=>{var Qe,Ne,$e;const ct=MWe[ge.status]||MWe.sent,Ue=ct.icon,et=(Qe=J.find(it=>{var Je;return it.id===((Je=ge.campaign_email)==null?void 0:Je.campaign_id)}))==null?void 0:Qe.name;return e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border hover:bg-muted/30 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx(Ue,{className:`h-4 w-4 flex-shrink-0 ${ct.color}`}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("p",{className:"font-medium text-sm truncate",children:[(Ne=ge.prospect)==null?void 0:Ne.first_name," ",($e=ge.prospect)==null?void 0:$e.last_name,e.jsxs("span",{className:"text-muted-foreground font-normal ml-2",children:["Email #",ge.email_number]}),et&&e.jsx(Xe,{variant:"outline",className:"ml-2 text-[10px] px-1.5 py-0 font-normal",children:et})]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:ge.subject})]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground flex-shrink-0",children:[ge.opened_at&&e.jsxs("span",{className:"flex items-center gap-1 text-amber-500",children:[e.jsx(Bn,{className:"h-3 w-3"})," ",As(new Date(ge.opened_at),"MMM d")]}),ge.clicked_at&&e.jsxs("span",{className:"flex items-center gap-1 text-green-500",children:[e.jsx(Kd,{className:"h-3 w-3"})," ",As(new Date(ge.clicked_at),"MMM d")]}),e.jsx("span",{children:As(new Date(ge.sent_at),"MMM d, h:mm a")})]})]},ge.id)})})]})})()]})]}),e.jsx(bs,{open:n,onOpenChange:pe=>{a(pe),pe||(y(""),c(new Set),l(""))},children:e.jsxs(vs,{className:"max-w-lg max-h-[85vh] flex flex-col p-0",children:[e.jsxs(Cs,{className:"px-6 pt-6 pb-4",children:[e.jsx(Ns,{children:"Assign Campaign to Prospects"}),e.jsx(nn,{children:"Select a campaign and choose which prospects to enroll. The first email will be sent automatically."})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto px-6 space-y-4 pb-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{className:"text-sm font-medium",children:"1. Select Campaign"}),e.jsxs(Bs,{value:i,onValueChange:l,children:[e.jsx(Os,{children:e.jsx(Us,{placeholder:"Choose a campaign..."})}),e.jsx(Fs,{children:J.map(pe=>e.jsx(pt,{value:pe.id,children:pe.name},pe.id))})]})]}),i&&(()=>{const pe=x.toLowerCase(),tt=K.filter(Ue=>`${Ue.first_name} ${Ue.last_name}`.toLowerCase().includes(pe)||Ue.email.toLowerCase().includes(pe)),ge=tt.filter(Ue=>!re.has(`${Ue.id}-${i}`)),ct=ge.length>0&&ge.every(Ue=>o.has(Ue.id));return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ue,{className:"text-sm font-medium",children:"2. Select Prospects"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[o.size," selected"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Mn,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(Se,{placeholder:"Search by name or email...",value:x,onChange:Ue=>y(Ue.target.value),className:"pl-9 h-9"})]}),e.jsxs(H,{variant:"outline",size:"sm",className:"h-9 whitespace-nowrap",onClick:()=>{if(ct){const Ue=new Set(o);ge.forEach(et=>Ue.delete(et.id)),c(Ue)}else{const Ue=new Set(o);ge.forEach(et=>Ue.add(et.id)),c(Ue)}},children:[e.jsx(nF,{className:"h-3.5 w-3.5 mr-1"}),ct?"Deselect All":`Select All (${ge.length})`]})]}),e.jsx("div",{className:"border rounded-lg max-h-60 overflow-y-auto divide-y",children:tt.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:x?"No prospects match your search":"No prospects found for this brokerage"}):tt.map(Ue=>{const et=re.has(`${Ue.id}-${i}`);return e.jsxs("label",{className:`flex items-center gap-3 p-2.5 hover:bg-muted/50 cursor-pointer ${et?"opacity-40":""}`,children:[e.jsx(ao,{checked:o.has(Ue.id),disabled:et,onCheckedChange:Qe=>{const Ne=new Set(o);Qe?Ne.add(Ue.id):Ne.delete(Ue.id),c(Ne)}}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("p",{className:"text-sm font-medium truncate",children:[Ue.first_name," ",Ue.last_name]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:Ue.email})]}),et&&e.jsx(Xe,{variant:"outline",className:"text-[10px] shrink-0",children:"Already assigned"})]},Ue.id)})}),tt.length>0&&e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:["Showing ",tt.length," of ",K.length," prospects",ge.length0&&e.jsx(ke,{className:"bg-primary/5 border-primary/20",children:e.jsxs(Oe,{className:"pt-3 pb-2 text-sm space-y-1",children:[e.jsxs("p",{className:"font-medium text-primary",children:["✅ Ready to assign ",o.size," prospect",o.size>1?"s":""]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["• Campaign: ",e.jsx("strong",{children:(De=J.find(pe=>pe.id===i))==null?void 0:De.name})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"• First email sends immediately · follow-ups every 7 days"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"• You can pause or cancel any assignment at any time"})]})})]}),e.jsxs(wn,{className:"px-6 py-4 border-t",children:[e.jsx(H,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsxs(H,{onClick:()=>ie.mutate(),disabled:ie.isPending||!i||o.size===0,children:[e.jsx(yn,{className:"h-4 w-4 mr-1"}),ie.isPending?"Assigning...":`Assign & Start (${o.size})`]})]})]})}),m&&(()=>{const pe=O(m);return pe?e.jsx(vvt,{email:pe,mergeValues:z,selectedSubjectIndex:R[pe.id],onClose:()=>p(null)}):null})()]})}function jvt({brokerageId:s}){const t=ns(),[r,n]=S.useState([]),[a,i]=S.useState([]),[l,o]=S.useState(!1),c=S.useRef(!1),{data:d,isLoading:h}=yt({queryKey:["recruit-stages-editor",s],queryFn:async()=>{const{data:b,error:j}=await V.from("recruit_pipeline_stages").select("*").eq("brokerage_id",s).order("sort_order");if(j)throw j;return b},enabled:!!s});S.useEffect(()=>{if(d){if(c.current){c.current=!1;return}n(d.map(b=>({id:b.id,name:b.name,color:b.color,sort_order:b.sort_order}))),i([]),o(!1)}},[d]);const m=Pt({mutationFn:async()=>{for(const k of a){const{error:T}=await V.from("recruit_pipeline_stages").delete().eq("id",k);if(T)throw T}const b=r.filter(k=>k.id&&!k.isNew),j=r.filter(k=>!k.id||k.isNew);for(const k of b){const{error:T}=await V.from("recruit_pipeline_stages").update({name:k.name,color:k.color,sort_order:k.sort_order}).eq("id",k.id);if(T)throw T}if(j.length>0){const{error:k}=await V.from("recruit_pipeline_stages").insert(j.map(T=>({brokerage_id:s,name:T.name,color:T.color,sort_order:T.sort_order})));if(k)throw k}},onSuccess:()=>{i([]),t.invalidateQueries({queryKey:["recruit-stages-editor",s]}),t.invalidateQueries({queryKey:["recruit-stages",s]}),he.success("Pipeline stages saved!"),o(!1)},onError:b=>he.error(b.message)}),p=(b,j,k)=>{n(T=>T.map((E,A)=>A===b?{...E,[j]:k}:E)),o(!0)},x=()=>{const b=r.length>0?Math.max(...r.map(j=>j.sort_order)):0;n(j=>[...j,{name:"",color:"#6366f1",sort_order:b+1,isNew:!0}]),o(!0)},y=b=>{const j=r[b];j.id&&!j.isNew&&i(k=>[...k,j.id]),n(k=>k.filter((T,E)=>E!==b)),o(!0)},_=(b,j)=>{const k=b+j;if(k<0||k>=r.length)return;const T=[...r];[T[b],T[k]]=[T[k],T[b]],T.forEach((E,A)=>E.sort_order=A+1),n(T),o(!0)};return h?e.jsx("div",{className:"text-sm text-muted-foreground py-8 text-center",children:"Loading stages…"}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold mb-1",children:"Pipeline Stages"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Customize the recruiting pipeline stages for this brokerage. Changes will apply to the Kanban board and all prospect tracking."})]}),e.jsx("div",{className:"space-y-2",children:r.map((b,j)=>e.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-lg border bg-card",children:[e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsx("button",{type:"button",onClick:()=>_(j,-1),disabled:j===0,className:"text-muted-foreground hover:text-foreground disabled:opacity-30 text-xs",children:"▲"}),e.jsx("button",{type:"button",onClick:()=>_(j,1),disabled:j===r.length-1,className:"text-muted-foreground hover:text-foreground disabled:opacity-30 text-xs",children:"▼"})]}),e.jsx(Oh,{className:"h-4 w-4 text-muted-foreground/50 shrink-0"}),e.jsx("input",{type:"color",value:b.color,onChange:k=>p(j,"color",k.target.value),className:"h-8 w-8 rounded cursor-pointer border-0 p-0 shrink-0"}),e.jsx(Se,{value:b.name,onChange:k=>p(j,"name",k.target.value),placeholder:"Stage name…",className:"flex-1"}),e.jsx("span",{className:"text-xs text-muted-foreground w-6 text-center shrink-0",children:j+1}),e.jsx(H,{variant:"ghost",size:"icon",onClick:()=>y(j),className:"text-destructive hover:text-destructive shrink-0 h-8 w-8",children:e.jsx(Dr,{className:"h-4 w-4"})})]},b.id||`new-${j}`))}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(H,{variant:"outline",size:"sm",onClick:x,className:"gap-1",children:[e.jsx(Ys,{className:"h-4 w-4"})," Add Stage"]}),l&&e.jsxs(H,{size:"sm",onClick:()=>m.mutate(),disabled:m.isPending,className:"gap-1",children:[e.jsx(vc,{className:"h-4 w-4"})," Save Changes"]})]}),r.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No stages configured. Add stages to build your recruiting pipeline."})]})}function _zs({brokerageId:s}){const{data:t=[],isLoading:r}=yt({queryKey:["recruit-unsubscribed",s],queryFn:async()=>{const{data:n,error:a}=await V.from("recruit_prospects").select("id, first_name, last_name, email, unsubscribed_at, unsubscribe_reason, current_brokerage").eq("brokerage_id",s).not("unsubscribed_at","is",null).order("unsubscribed_at",{ascending:!1}).limit(500);if(a)throw a;return n||[]},enabled:!!s});return r?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-2 border-primary border-t-transparent"})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs("h3",{className:"text-lg font-semibold flex items-center gap-2",children:[e.jsx(DE,{className:"h-5 w-5 text-muted-foreground"}),"Unsubscribed Prospects"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Prospects who opted out of recruiting emails. They will not receive further outreach."})]}),e.jsxs(Xe,{variant:"secondary",className:"text-base px-3 py-1",children:[t.length," total"]})]}),t.length===0?e.jsx(ke,{children:e.jsxs(Oe,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(DE,{className:"h-10 w-10 mx-auto mb-3 opacity-40"}),e.jsx("p",{className:"text-sm",children:"No prospects have unsubscribed. Nice work!"})]})}):e.jsx("div",{className:"grid gap-3",children:t.map(n=>e.jsxs(ke,{className:"hover:shadow-sm transition-shadow",children:[e.jsx(Ot,{className:"pb-3",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs(zt,{className:"text-base",children:[n.first_name," ",n.last_name]}),e.jsxs("div",{className:"flex items-center gap-3 text-xs text-muted-foreground mt-1",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(er,{className:"h-3 w-3"}),n.email]}),n.current_brokerage&&e.jsxs("span",{children:["· ",n.current_brokerage]})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground whitespace-nowrap",children:[e.jsx(Nn,{className:"h-3 w-3"}),n.unsubscribed_at&&As(new Date(n.unsubscribed_at),"MMM d, yyyy")]})]})}),n.unsubscribe_reason&&e.jsx(Oe,{className:"pt-0",children:e.jsxs("div",{className:"text-sm bg-muted/40 rounded-md px-3 py-2 italic text-muted-foreground",children:['"',n.unsubscribe_reason,'"']})})]},n.id))})]})}function wzs(){var o;const[s,t]=S.useState(""),[r,n]=S.useState("board"),{data:a=[],isLoading:i}=yt({queryKey:["all-brokerages"],queryFn:async()=>{const{data:c,error:d}=await V.from("brokerages").select("id, name").order("name");if(d)throw d;return c}}),l=s||((o=a[0])==null?void 0:o.id)||"";return i?e.jsx(Ss,{title:"Recruiting",description:"Agent Recruiting Pipeline",children:e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):e.jsx(Ss,{title:"Recruiting",description:"Agent Recruiting Pipeline",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 flex-wrap",children:[a.length>1?e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Brokerage:"}),e.jsxs(Bs,{value:l,onValueChange:t,children:[e.jsxs(Os,{className:"w-[280px]",children:[e.jsx(Xa,{className:"mr-2 h-4 w-4"}),e.jsx(Us,{placeholder:"Select brokerage"})]}),e.jsx(Fs,{children:a.map(c=>e.jsx(pt,{value:c.id,children:c.name},c.id))})]})]}):e.jsx("div",{}),l&&e.jsx(gvt,{brokerageId:l,trigger:e.jsxs(H,{size:"sm",className:"gap-1.5",children:[e.jsx(xn,{className:"h-4 w-4"})," Record & Send Video"]})})]}),l?e.jsxs(ta,{defaultValue:"pipeline",className:"space-y-4",children:[e.jsxs(Qn,{className:"flex-wrap h-auto gap-1",children:[e.jsx(ts,{value:"pipeline",children:"Pipeline"}),e.jsxs(ts,{value:"contacts",children:[e.jsx(Ar,{className:"h-3.5 w-3.5 mr-1"}),"Contacts"]}),e.jsxs(ts,{value:"video-outreach",children:[e.jsx(xn,{className:"h-3.5 w-3.5 mr-1"}),"Video Outreach"]}),e.jsx(ts,{value:"follow-ups",children:"Follow-ups"}),e.jsx(ts,{value:"referrals",children:"Referrals"}),e.jsx(ts,{value:"interest",children:"Interest Form"}),e.jsx(ts,{value:"landing-page",children:"Landing Page"}),e.jsx(ts,{value:"goals",children:"Goals"}),e.jsx(ts,{value:"metrics",children:"Metrics"}),e.jsx(ts,{value:"templates",children:"Email Templates"}),e.jsxs(ts,{value:"campaigns",children:[e.jsx(er,{className:"h-3.5 w-3.5 mr-1"}),"Campaigns"]}),e.jsxs(ts,{value:"drip-assignments",children:[e.jsx(yn,{className:"h-3.5 w-3.5 mr-1"}),"Drip Assignments"]}),e.jsx(ts,{value:"activity",children:"Recruiter Activity"}),e.jsxs(ts,{value:"email-settings",children:[e.jsx(Go,{className:"h-3.5 w-3.5 mr-1"}),"Email Settings"]}),e.jsxs(ts,{value:"pipeline-stages",children:[e.jsx(OE,{className:"h-3.5 w-3.5 mr-1"}),"Pipeline Stages"]}),e.jsxs(ts,{value:"unsubscribed",children:[e.jsx(DE,{className:"h-3.5 w-3.5 mr-1"}),"Unsubscribed"]})]}),e.jsxs(cs,{value:"pipeline",children:[e.jsx("div",{className:"flex justify-end mb-3",children:e.jsxs("div",{className:"flex items-center rounded-md border bg-muted p-0.5",children:[e.jsxs(H,{variant:r==="board"?"default":"ghost",size:"sm",className:"h-7 px-2.5 gap-1.5",onClick:()=>n("board"),children:[e.jsx(_g,{className:"h-3.5 w-3.5"})," Board"]}),e.jsxs(H,{variant:r==="table"?"default":"ghost",size:"sm",className:"h-7 px-2.5 gap-1.5",onClick:()=>n("table"),children:[e.jsx(ZI,{className:"h-3.5 w-3.5"})," Table"]})]})}),r==="board"?e.jsx(lvt,{brokerageId:l}):e.jsx(fpe,{brokerageId:l})]}),e.jsx(cs,{value:"contacts",children:e.jsx(fpe,{brokerageId:l})}),e.jsx(cs,{value:"video-outreach",children:e.jsx(xvt,{brokerageId:l})}),e.jsx(cs,{value:"follow-ups",children:e.jsx(fvt,{brokerageId:l})}),e.jsx(cs,{value:"referrals",children:e.jsx(hvt,{brokerageId:l})}),e.jsx(cs,{value:"interest",children:e.jsx(mvt,{brokerageId:l})}),e.jsx(cs,{value:"landing-page",children:e.jsx(pvt,{brokerageId:l})}),e.jsx(cs,{value:"goals",children:e.jsx(yvt,{brokerageId:l})}),e.jsx(cs,{value:"metrics",children:e.jsx(cvt,{brokerageId:l})}),e.jsx(cs,{value:"templates",children:e.jsx(dvt,{brokerageId:l})}),e.jsx(cs,{value:"campaigns",children:e.jsx(_vt,{brokerageId:l})}),e.jsx(cs,{value:"drip-assignments",children:e.jsx(wvt,{brokerageId:l})}),e.jsx(cs,{value:"activity",children:e.jsx(uvt,{brokerageId:l})}),e.jsx(cs,{value:"email-settings",children:e.jsxs("div",{className:"max-w-2xl",children:[e.jsx("h3",{className:"text-lg font-semibold mb-1",children:"Email Settings"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Configure sender identity, merge fields, and brokerage location for recruiting emails."}),e.jsx(y6e,{brokerageId:l})]})}),e.jsx(cs,{value:"pipeline-stages",children:e.jsx("div",{className:"max-w-2xl",children:e.jsx(jvt,{brokerageId:l})})}),e.jsx(cs,{value:"unsubscribed",children:e.jsx(_zs,{brokerageId:l})})]}):e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(Xa,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No brokerages found. Create a brokerage first."})]})]})})}function jzs({brokerageId:s}){const[t,r]=S.useState(""),[n,a]=S.useState("all"),{data:i,isLoading:l}=yt({queryKey:["recruit-sent-emails",s],queryFn:async()=>{var b;const{data:d,error:h}=await V.from("recruit_prospects").select("id, first_name, last_name, email").eq("brokerage_id",s);if(h)throw h;const m=new Map((d||[]).map(j=>[j.id,j]));if(Array.from(m.keys()).length===0)return[];const{data:x}=await V.from("recruit_videos").select("id, prospect_id, share_token, sent_at, sent_via, view_count, first_viewed_at, cta_clicked_at, video:agent_videos(title)").eq("brokerage_id",s).not("sent_at","is",null).order("sent_at",{ascending:!1}),{data:y}=await V.from("recruit_campaign_sends").select("id, prospect_id, subject, status, sent_at, opened_at, clicked_at, error_message, email_number").eq("brokerage_id",s).order("sent_at",{ascending:!1,nullsFirst:!1}),_=[];for(const j of x||[]){const k=m.get(j.prospect_id);k&&_.push({id:`v-${j.id}`,kind:"video",prospect_id:j.prospect_id,prospect_name:`${k.first_name||""} ${k.last_name||""}`.trim()||"—",prospect_email:k.email,subject:(b=j.video)!=null&&b.title?`Video: ${j.video.title}`:"Recruiting Video",status:j.cta_clicked_at?"clicked":j.first_viewed_at?"viewed":"sent",sent_at:j.sent_at,opened_at:j.first_viewed_at,clicked_at:j.cta_clicked_at,view_count:j.view_count,share_token:j.share_token})}for(const j of y||[]){if(!j.sent_at)continue;const k=m.get(j.prospect_id);k&&_.push({id:`c-${j.id}`,kind:"campaign",prospect_id:j.prospect_id,prospect_name:`${k.first_name||""} ${k.last_name||""}`.trim()||"—",prospect_email:k.email,subject:j.subject||`Email #${j.email_number}`,status:j.status||"sent",sent_at:j.sent_at,opened_at:j.opened_at,clicked_at:j.clicked_at,error:j.error_message})}return _.sort((j,k)=>new Date(k.sent_at).getTime()-new Date(j.sent_at).getTime()),_}}),o=S.useMemo(()=>{const d=i||[];return{total:d.length,videos:d.filter(h=>h.kind==="video").length,campaigns:d.filter(h=>h.kind==="campaign").length,opened:d.filter(h=>h.opened_at).length,clicked:d.filter(h=>h.clicked_at).length}},[i]),c=S.useMemo(()=>(i||[]).filter(h=>{if(n!=="all"&&h.kind!==n)return!1;if(!t)return!0;const m=t.toLowerCase();return h.prospect_name.toLowerCase().includes(m)||(h.prospect_email||"").toLowerCase().includes(m)||h.subject.toLowerCase().includes(m)}),[i,t,n]);return e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3",children:[{label:"Total Sent",value:o.total,icon:yn,color:"text-primary"},{label:"Video Emails",value:o.videos,icon:xn,color:"text-blue-500"},{label:"Campaign Emails",value:o.campaigns,icon:er,color:"text-violet-500"},{label:"Opened / Viewed",value:o.opened,icon:Bn,color:"text-amber-500"},{label:"Clicked",value:o.clicked,icon:Kd,color:"text-emerald-500"}].map(d=>e.jsx(ke,{children:e.jsxs(Oe,{className:"p-3 flex items-center gap-2.5",children:[e.jsx("div",{className:`h-9 w-9 rounded-lg bg-muted flex items-center justify-center ${d.color}`,children:e.jsx(d.icon,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xl font-bold leading-tight",children:d.value}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:d.label})]})]})},d.label))}),e.jsxs(ke,{children:[e.jsx(Ot,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap",children:[e.jsx(zt,{className:"text-lg",children:"Sent Emails"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ta,{value:n,onValueChange:d=>a(d),children:e.jsxs(Qn,{className:"h-8",children:[e.jsx(ts,{value:"all",className:"text-xs h-7",children:"All"}),e.jsx(ts,{value:"video",className:"text-xs h-7",children:"Video"}),e.jsx(ts,{value:"campaign",className:"text-xs h-7",children:"Campaign"})]})}),e.jsxs("div",{className:"relative w-56",children:[e.jsx(Mn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Se,{placeholder:"Search recruit, subject...",value:t,onChange:d=>r(d.target.value),className:"pl-9 h-9"})]})]})]})}),e.jsx(Oe,{children:l?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):c.length===0?e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(er,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{className:"font-medium",children:"No emails sent yet"}),e.jsx("p",{className:"text-sm mt-1",children:"Emails sent from Video Outreach or Drip Campaigns will appear here."})]}):e.jsx("div",{className:"rounded-lg border overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-muted/40 text-xs text-muted-foreground",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left font-medium px-3 py-2",children:"Type"}),e.jsx("th",{className:"text-left font-medium px-3 py-2",children:"Recruit"}),e.jsx("th",{className:"text-left font-medium px-3 py-2",children:"Subject"}),e.jsx("th",{className:"text-left font-medium px-3 py-2",children:"Status"}),e.jsx("th",{className:"text-left font-medium px-3 py-2",children:"Sent"}),e.jsx("th",{className:"text-right font-medium px-3 py-2",children:"Engagement"})]})}),e.jsx("tbody",{children:c.map(d=>e.jsxs("tr",{className:"border-t hover:bg-muted/30 transition-colors",children:[e.jsx("td",{className:"px-3 py-2",children:d.kind==="video"?e.jsxs(Xe,{variant:"outline",className:"gap-1",children:[e.jsx(xn,{className:"h-3 w-3"}),"Video"]}):e.jsxs(Xe,{variant:"outline",className:"gap-1",children:[e.jsx(er,{className:"h-3 w-3"}),"Campaign"]})}),e.jsxs("td",{className:"px-3 py-2",children:[e.jsx("div",{className:"font-medium",children:d.prospect_name}),d.prospect_email&&e.jsx("div",{className:"text-xs text-muted-foreground",children:d.prospect_email})]}),e.jsx("td",{className:"px-3 py-2 max-w-xs truncate",children:d.subject}),e.jsxs("td",{className:"px-3 py-2",children:[d.status==="failed"||d.status==="bounced"?e.jsxs(Xe,{variant:"destructive",className:"gap-1",children:[e.jsx(wo,{className:"h-3 w-3"}),d.status]}):d.clicked_at?e.jsxs(Xe,{className:"bg-emerald-500/15 text-emerald-700 border-emerald-200 gap-1",children:[e.jsx(Kd,{className:"h-3 w-3"}),"Clicked"]}):d.opened_at?e.jsxs(Xe,{className:"bg-blue-500/15 text-blue-700 border-blue-200 gap-1",children:[e.jsx(Bn,{className:"h-3 w-3"}),"Opened"]}):e.jsxs(Xe,{variant:"secondary",className:"gap-1",children:[e.jsx(yn,{className:"h-3 w-3"}),"Sent"]}),d.error&&e.jsx("p",{className:"text-[10px] text-destructive mt-0.5 max-w-[200px] truncate",title:d.error,children:d.error})]}),e.jsxs("td",{className:"px-3 py-2 text-xs text-muted-foreground whitespace-nowrap",children:[As(new Date(d.sent_at),"MMM d, yyyy"),e.jsx("div",{className:"text-[10px]",children:As(new Date(d.sent_at),"h:mm a")})]}),e.jsx("td",{className:"px-3 py-2 text-right",children:e.jsxs("div",{className:"flex items-center gap-2 justify-end text-xs text-muted-foreground",children:[d.kind==="video"&&d.view_count!=null&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Bn,{className:"h-3 w-3"}),d.view_count]}),d.kind==="video"&&d.share_token&&e.jsx(H,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>window.open(`/recruit-video/${d.share_token}`,"_blank"),title:"Open landing page",children:e.jsx(gn,{className:"h-3.5 w-3.5"})})]})})]},d.id))})]})})})]})]})}function Nzs(){var l;const{managedBrokerages:s,selectedBrokerageId:t,setSelectedBrokerageId:r}=Ms(),[n,a]=S.useState("board"),i=t||((l=s[0])==null?void 0:l.id)||"";return s.length===0?e.jsx(Ss,{title:"Recruiting",description:"Agent Recruiting Pipeline",children:e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(Xa,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No brokerages assigned to you. Contact an admin for access."})]})}):e.jsx(Ss,{title:"Recruiting",description:"Agent Recruiting Pipeline",children:e.jsxs("div",{className:"space-y-6",children:[s.length>1&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Brokerage:"}),e.jsxs(Bs,{value:i,onValueChange:r,children:[e.jsxs(Os,{className:"w-[280px]",children:[e.jsx(Xa,{className:"mr-2 h-4 w-4"}),e.jsx(Us,{placeholder:"Select brokerage"})]}),e.jsx(Fs,{children:s.map(o=>e.jsx(pt,{value:o.id,children:o.name},o.id))})]})]}),i?e.jsxs(ta,{defaultValue:"pipeline",className:"space-y-4",children:[e.jsxs(Qn,{className:"flex-wrap h-auto gap-1",children:[e.jsx(ts,{value:"pipeline",children:"Pipeline"}),e.jsxs(ts,{value:"contacts",children:[e.jsx(Ar,{className:"h-3.5 w-3.5 mr-1"}),"Contacts"]}),e.jsxs(ts,{value:"video-outreach",children:[e.jsx(xn,{className:"h-3.5 w-3.5 mr-1"}),"Video Outreach"]}),e.jsx(ts,{value:"follow-ups",children:"Follow-ups"}),e.jsx(ts,{value:"referrals",children:"Referrals"}),e.jsx(ts,{value:"interest",children:"Interest Form"}),e.jsx(ts,{value:"landing-page",children:"Landing Page"}),e.jsx(ts,{value:"goals",children:"Goals"}),e.jsx(ts,{value:"metrics",children:"Metrics"}),e.jsx(ts,{value:"templates",children:"Email Templates"}),e.jsxs(ts,{value:"campaigns",children:[e.jsx(er,{className:"h-3.5 w-3.5 mr-1"}),"Campaigns"]}),e.jsxs(ts,{value:"drip-assignments",children:[e.jsx(yn,{className:"h-3.5 w-3.5 mr-1"}),"Drip Assignments"]}),e.jsxs(ts,{value:"sent-emails",children:[e.jsx(Uk,{className:"h-3.5 w-3.5 mr-1"}),"Sent Emails"]}),e.jsx(ts,{value:"activity",children:"Recruiter Activity"}),e.jsxs(ts,{value:"email-settings",children:[e.jsx(Go,{className:"h-3.5 w-3.5 mr-1"}),"Email Settings"]}),e.jsxs(ts,{value:"pipeline-stages",children:[e.jsx(OE,{className:"h-3.5 w-3.5 mr-1"}),"Pipeline Stages"]})]}),e.jsxs(cs,{value:"pipeline",children:[e.jsx("div",{className:"flex justify-end mb-3",children:e.jsxs("div",{className:"flex items-center rounded-md border bg-muted p-0.5",children:[e.jsxs(H,{variant:n==="board"?"default":"ghost",size:"sm",className:"h-7 px-2.5 gap-1.5",onClick:()=>a("board"),children:[e.jsx(_g,{className:"h-3.5 w-3.5"})," Board"]}),e.jsxs(H,{variant:n==="table"?"default":"ghost",size:"sm",className:"h-7 px-2.5 gap-1.5",onClick:()=>a("table"),children:[e.jsx(ZI,{className:"h-3.5 w-3.5"})," Table"]})]})}),n==="board"?e.jsx(lvt,{brokerageId:i}):e.jsx(fpe,{brokerageId:i})]}),e.jsx(cs,{value:"contacts",children:e.jsx(fpe,{brokerageId:i})}),e.jsx(cs,{value:"video-outreach",children:e.jsx(xvt,{brokerageId:i})}),e.jsx(cs,{value:"follow-ups",children:e.jsx(fvt,{brokerageId:i})}),e.jsx(cs,{value:"referrals",children:e.jsx(hvt,{brokerageId:i})}),e.jsx(cs,{value:"interest",children:e.jsx(mvt,{brokerageId:i})}),e.jsx(cs,{value:"landing-page",children:e.jsx(pvt,{brokerageId:i})}),e.jsx(cs,{value:"goals",children:e.jsx(yvt,{brokerageId:i})}),e.jsx(cs,{value:"metrics",children:e.jsx(cvt,{brokerageId:i})}),e.jsx(cs,{value:"templates",children:e.jsx(dvt,{brokerageId:i})}),e.jsx(cs,{value:"campaigns",children:e.jsx(_vt,{brokerageId:i})}),e.jsx(cs,{value:"drip-assignments",children:e.jsx(wvt,{brokerageId:i})}),e.jsx(cs,{value:"sent-emails",children:e.jsx(jzs,{brokerageId:i})}),e.jsx(cs,{value:"activity",children:e.jsx(uvt,{brokerageId:i})}),e.jsx(cs,{value:"email-settings",children:e.jsxs("div",{className:"max-w-2xl",children:[e.jsx("h3",{className:"text-lg font-semibold mb-1",children:"Email Settings"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Configure sender identity, merge fields, and brokerage location for recruiting emails."}),e.jsx(y6e,{brokerageId:i})]})}),e.jsx(cs,{value:"pipeline-stages",children:e.jsx("div",{className:"max-w-2xl",children:e.jsx(jvt,{brokerageId:i})})})]}):e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(Xa,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No brokerages found."})]})]})})}function kzs(){const[s,t]=S.useState(""),{data:r,isLoading:n}=yt({queryKey:["admin-brokerage-content-activity"],queryFn:async()=>{const{data:o}=await V.from("brokerages").select("id, name");if(!o)return[];const{data:c}=await V.from("brokerage_content").select("id, brokerage_id, content_type, created_at"),{data:d}=await V.from("brokerage_content_categories").select("id, brokerage_id"),h=c||[],m=d||[],p=o.map(x=>{const y=h.filter(j=>j.brokerage_id===x.id),_=m.filter(j=>j.brokerage_id===x.id),b=y.length>0?y.reduce((j,k)=>k.created_at>j?k.created_at:j,y[0].created_at):null;return{brokerage_id:x.id,brokerage_name:x.name,total_items:y.length,videos:y.filter(j=>j.content_type==="video").length,pdfs:y.filter(j=>j.content_type==="pdf").length,links:y.filter(j=>j.content_type==="link"||j.content_type==="canva_link").length,events:y.filter(j=>j.content_type==="event").length,graphics:y.filter(j=>j.content_type==="graphic").length,latest_item_date:b,categories:_.length}});return p.sort((x,y)=>y.total_items-x.total_items),p}}),a=(r||[]).filter(o=>o.brokerage_name.toLowerCase().includes(s.toLowerCase())),i=a.reduce((o,c)=>o+c.total_items,0),l=a.filter(o=>o.total_items>0).length;return e.jsx(Ss,{title:"Brokerage Content Activity",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(km,{title:"Brokerage Content Activity",description:"See which brokerages are creating custom content for their agents"}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-4",children:[e.jsxs(ke,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsx(zt,{className:"text-sm font-medium text-muted-foreground",children:"Active Brokerages"})}),e.jsxs(Oe,{children:[e.jsx("p",{className:"text-2xl font-bold",children:l}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"with content uploaded"})]})]}),e.jsxs(ke,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsx(zt,{className:"text-sm font-medium text-muted-foreground",children:"Total Content Items"})}),e.jsxs(Oe,{children:[e.jsx("p",{className:"text-2xl font-bold",children:i}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"across all brokerages"})]})]}),e.jsxs(ke,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsx(zt,{className:"text-sm font-medium text-muted-foreground",children:"Total Brokerages"})}),e.jsxs(Oe,{children:[e.jsx("p",{className:"text-2xl font-bold",children:a.length}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"registered"})]})]})]}),e.jsxs("div",{className:"relative max-w-sm",children:[e.jsx(Mn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Se,{placeholder:"Search brokerages...",value:s,onChange:o=>t(o.target.value),className:"pl-9"})]}),e.jsx(ke,{children:e.jsx(Oe,{className:"p-0",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Vs,{children:[e.jsx(At,{children:"Brokerage"}),e.jsx(At,{className:"text-center",children:"Total"}),e.jsx(At,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(xn,{className:"h-3 w-3"})," Videos"]})}),e.jsx(At,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(kn,{className:"h-3 w-3"})," PDFs"]})}),e.jsx(At,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(ql,{className:"h-3 w-3"})," Links"]})}),e.jsx(At,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(xu,{className:"h-3 w-3"})," Events"]})}),e.jsx(At,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(wl,{className:"h-3 w-3"})," Graphics"]})}),e.jsx(At,{className:"text-center",children:"Categories"}),e.jsx(At,{children:"Last Upload"})]})}),e.jsx(da,{children:n?e.jsx(Vs,{children:e.jsx(gt,{colSpan:9,className:"text-center py-8 text-muted-foreground",children:"Loading..."})}):a.length===0?e.jsx(Vs,{children:e.jsx(gt,{colSpan:9,className:"text-center py-8 text-muted-foreground",children:"No brokerages found"})}):a.map(o=>e.jsxs(Vs,{className:o.total_items===0?"opacity-50":"",children:[e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Xa,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsx("span",{className:"font-medium",children:o.brokerage_name})]})}),e.jsx(gt,{className:"text-center",children:o.total_items>0?e.jsx(Xe,{variant:"secondary",className:"font-bold",children:o.total_items}):e.jsx("span",{className:"text-muted-foreground",children:"0"})}),e.jsx(gt,{className:"text-center",children:o.videos||"–"}),e.jsx(gt,{className:"text-center",children:o.pdfs||"–"}),e.jsx(gt,{className:"text-center",children:o.links||"–"}),e.jsx(gt,{className:"text-center",children:o.events||"–"}),e.jsx(gt,{className:"text-center",children:o.graphics||"–"}),e.jsx(gt,{className:"text-center",children:o.categories||"–"}),e.jsx(gt,{children:o.latest_item_date?e.jsx("span",{className:"text-sm text-muted-foreground",children:As(new Date(o.latest_item_date),"MMM d, yyyy")}):e.jsx("span",{className:"text-muted-foreground",children:"–"})})]},o.brokerage_id))})]})})})]})})}const Szs=[{value:"just-listed",label:"Just Listed",icon:"🏠"},{value:"just-sold",label:"Just Sold",icon:"🎉"},{value:"open-house",label:"Open House",icon:"🚪"},{value:"price-drop",label:"Price Drop",icon:"📉"}],IWe=[{value:"instagram-square",label:"Instagram Post",dimensions:"1080×1080",icon:e.jsx(yu,{className:"h-4 w-4"})},{value:"instagram-story",label:"Instagram Story",dimensions:"1080×1920",icon:e.jsx(yu,{className:"h-4 w-4"})},{value:"facebook-post",label:"Facebook Post",dimensions:"1200×630",icon:e.jsx(fh,{className:"h-4 w-4"})}],Czs=[{value:"luxury-dark",label:"Luxury Dark",description:"Dark & gold, high-end feel",preview:"🌙"},{value:"modern-clean",label:"Modern Clean",description:"White, bold, contemporary",preview:"✨"},{value:"bold-colorful",label:"Bold & Vibrant",description:"Energetic gradients & punch",preview:"🔥"},{value:"editorial",label:"Editorial",description:"Magazine-style sophistication",preview:"📰"}],PWe=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s),LWe={"luxury-dark":REe,"modern-clean":OEe,"bold-colorful":FEe,editorial:BEe};function Tzs(){const[s,t]=S.useState(""),[r,n]=S.useState("address"),[a,i]=S.useState(!1),[l,o]=S.useState([]),[c,d]=S.useState(null),[h,m]=S.useState(0),[p,x]=S.useState("just-listed"),[y,_]=S.useState(["instagram-square"]),[b,j]=S.useState("luxury-dark"),[k,T]=S.useState(!1),[E,A]=S.useState(""),[D,R]=S.useState(""),[z,O]=S.useState(""),[$,ee]=S.useState(!1),[Z,J]=S.useState(!1),[K,re]=S.useState([]),[ie,ce]=S.useState("search"),ne=S.useRef({});S.useEffect(()=>{(async()=>{const{data:{user:ze}}=await V.auth.getUser();if(!ze)return;const{data:Pe}=await V.from("profiles").select("name, avatar_url, brokerages(name)").eq("id",ze.id).single();if(Pe){A(Pe.name||""),O(Pe.avatar_url||"");const Ie=Pe.brokerages;R((Ie==null?void 0:Ie.name)||"")}})()},[]);const le=async()=>{var Me;if(s.trim()){i(!0),o([]);try{const{data:ze,error:Pe}=await V.functions.invoke("repliers-mls-search",{body:{searchType:r,query:s.trim()}});if(Pe)throw Pe;if(ze.error)throw new Error(ze.error);o(ze.listings||[]),((Me=ze.listings)==null?void 0:Me.length)===0&&he.info("No listings found. Try a different search.")}catch(ze){he.error(ze.message||"Search failed")}finally{i(!1)}}},be=Me=>{var ze;d(Me),m(0),ce("customize"),Me.soldDate||(ze=Me.status)!=null&&ze.toLowerCase().includes("sold")?x("just-sold"):x("just-listed")},fe=Me=>{_(ze=>ze.includes(Me)?ze.filter(Pe=>Pe!==Me):[...ze,Me])},je=S.useCallback(async()=>{if(!(!c||y.length===0)){ee(!0),re([]),ce("generate");try{await new Promise(ze=>setTimeout(ze,500));const Me=[];for(const ze of y){const Pe=`${b}-${ze}`,Ie=ne.current[Pe];if(!Ie)continue;const De=Sk[ze],pe=await DEe(Ie,{width:De.width,height:De.height,pixelRatio:1,cacheBust:!0,style:{transform:"none",transformOrigin:"top left"}});Me.push({format:ze,imageUrl:pe})}re(Me),he.success(`Generated ${Me.length} social post${Me.length>1?"s":""}!`)}catch(Me){he.error(Me.message||"Generation failed")}finally{ee(!1)}}},[c,y,b,h,k,E,D,z,p]),ve=async()=>{if(!(!c||y.length===0)){ee(!0),re([]),ce("generate");try{const Me={...c,photos:c.photos.length>0?[c.photos[h]]:[]},ze=[];for(const Pe of y){const{data:Ie,error:De}=await V.functions.invoke("generate-listing-social-post",{body:{listing:Me,postType:p,format:Pe,branding:k?{enabled:!0,agentName:E,brokerage:D}:{enabled:!1}}});if(De)throw De;if(Ie.error)throw new Error(Ie.error);ze.push({format:Pe,imageUrl:Ie.imageUrl})}re(ze),he.success(`Generated ${ze.length} AI post${ze.length>1?"s":""}!`)}catch(Me){he.error(Me.message||"AI generation failed")}finally{ee(!1)}}},We=()=>Z?ve():je(),Ve=(Me,ze)=>{var Ie;const Pe=document.createElement("a");Pe.href=Me,Pe.download=`${((Ie=c==null?void 0:c.address)==null?void 0:Ie.replace(/\s+/g,"-"))||"listing"}-${p}-${ze}.png`,document.body.appendChild(Pe),Pe.click(),document.body.removeChild(Pe)},Le=c?{listing:c,postType:p,format:"instagram-square",branding:k?{enabled:!0,agentName:E,brokerage:D,agentPhotoUrl:z||void 0}:{enabled:!1},selectedPhotoIndex:h}:null;return e.jsx(Ss,{children:e.jsxs("div",{className:"space-y-6 p-4 md:p-8",children:[e.jsx(km,{title:"Social Post Generator",description:"Search MLS listings and generate stunning social media posts"}),e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsxs("button",{onClick:()=>ce("search"),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full transition-colors ${ie==="search"?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground hover:text-foreground"}`,children:[e.jsx(Mn,{className:"h-3.5 w-3.5"})," 1. Find Listing"]}),e.jsx($a,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("button",{onClick:()=>c&&ce("customize"),disabled:!c,className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full transition-colors ${ie==="customize"?"bg-primary text-primary-foreground":c?"bg-muted text-muted-foreground hover:text-foreground":"bg-muted text-muted-foreground/50 cursor-not-allowed"}`,children:[e.jsx(Lr,{className:"h-3.5 w-3.5"})," 2. Customize"]}),e.jsx($a,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full ${ie==="generate"?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground/50"}`,children:[e.jsx(wl,{className:"h-3.5 w-3.5"})," 3. Generate"]})]}),ie==="search"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs(ke,{children:[e.jsxs(Ot,{children:[e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(Mn,{className:"h-5 w-5 text-primary"})," Search MLS Listings ",e.jsx(jot,{})]}),e.jsx(Br,{children:"Find a listing by MLS number or property address using Repliers.io"})]}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsx(ta,{value:r,onValueChange:Me=>n(Me),children:e.jsxs(Qn,{children:[e.jsxs(ts,{value:"address",children:[e.jsx(Qa,{className:"h-4 w-4 mr-1.5"})," Address"]}),e.jsxs(ts,{value:"mls",children:[e.jsx(xm,{className:"h-4 w-4 mr-1.5"})," MLS #"]})]})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Se,{value:s,onChange:Me=>t(Me.target.value),placeholder:r==="mls"?"Enter MLS number...":"Enter property address...",className:"flex-1",onKeyDown:Me=>Me.key==="Enter"&&le()}),e.jsxs(H,{onClick:le,disabled:a||!s.trim(),children:[a?e.jsx(is,{className:"h-4 w-4 animate-spin"}):e.jsx(Mn,{className:"h-4 w-4"})," Search"]})]})]})]}),l.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("h3",{className:"text-sm font-medium text-muted-foreground",children:[l.length," listing",l.length!==1?"s":""," found"]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:l.map((Me,ze)=>{var Pe;return e.jsx(ke,{className:"cursor-pointer hover:border-primary/50 hover:shadow-md transition-all group",onClick:()=>be(Me),children:e.jsx(Oe,{className:"p-0",children:e.jsxs("div",{className:"flex",children:[e.jsx("div",{className:"w-32 h-28 flex-shrink-0 bg-muted rounded-l-lg overflow-hidden",children:(Pe=Me.photos)!=null&&Pe[0]?e.jsx("img",{src:Me.photos[0],alt:Me.address,className:"w-full h-full object-cover group-hover:scale-105 transition-transform"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(Fn,{className:"h-8 w-8 text-muted-foreground/40"})})}),e.jsxs("div",{className:"flex-1 p-3 min-w-0",children:[e.jsx("p",{className:"font-bold text-foreground",children:PWe(Me.price)}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:Me.address}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Me.city,", ",Me.state," ",Me.zip]}),e.jsxs("div",{className:"flex items-center gap-3 mt-1.5 text-xs text-muted-foreground",children:[Me.bedrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(B2,{className:"h-3 w-3"})," ",Me.bedrooms]}),Me.bathrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(_p,{className:"h-3 w-3"})," ",Me.bathrooms]}),Me.sqft>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(CE,{className:"h-3 w-3"})," ",Me.sqft.toLocaleString()]})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(Xe,{variant:"outline",className:"text-[10px]",children:Me.mlsNumber}),e.jsx(Xe,{variant:"outline",className:"text-[10px]",children:Me.status})]})]})]})})},Me.mlsNumber||ze)})})]})]}),ie==="customize"&&c&&e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsxs(ke,{className:"lg:col-span-1",children:[e.jsx(Ot,{className:"pb-3",children:e.jsx(zt,{className:"text-base",children:"Selected Listing"})}),e.jsxs(Oe,{className:"space-y-3",children:[c.photos.length>0&&e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"aspect-[4/3] rounded-lg overflow-hidden bg-muted",children:e.jsx("img",{src:c.photos[h],alt:"Listing photo",className:"w-full h-full object-cover"})}),c.photos.length>1&&e.jsxs("div",{className:"flex items-center justify-between mt-2",children:[e.jsx(H,{variant:"outline",size:"icon",className:"h-7 w-7",onClick:()=>m(Me=>Math.max(0,Me-1)),disabled:h===0,children:e.jsx(fl,{className:"h-4 w-4"})}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[h+1," of ",c.photos.length]}),e.jsx(H,{variant:"outline",size:"icon",className:"h-7 w-7",onClick:()=>m(Me=>Math.min(c.photos.length-1,Me+1)),disabled:h===c.photos.length-1,children:e.jsx($a,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-bold text-lg",children:PWe(c.price)}),e.jsx("p",{className:"text-sm text-muted-foreground",children:c.address}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[c.city,", ",c.state," ",c.zip]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 text-center",children:[c.bedrooms>0&&e.jsxs("div",{className:"bg-muted/50 rounded-lg p-2",children:[e.jsx("p",{className:"text-sm font-semibold",children:c.bedrooms}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Beds"})]}),c.bathrooms>0&&e.jsxs("div",{className:"bg-muted/50 rounded-lg p-2",children:[e.jsx("p",{className:"text-sm font-semibold",children:c.bathrooms}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Baths"})]}),c.sqft>0&&e.jsxs("div",{className:"bg-muted/50 rounded-lg p-2",children:[e.jsx("p",{className:"text-sm font-semibold",children:c.sqft.toLocaleString()}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Sq Ft"})]})]}),e.jsxs(H,{variant:"outline",size:"sm",className:"w-full",onClick:()=>{ce("search"),d(null)},children:[e.jsx(qy,{className:"h-3.5 w-3.5 mr-1.5"})," Choose Different Listing"]})]})]}),e.jsxs(ke,{className:"lg:col-span-2",children:[e.jsxs(Ot,{children:[e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(Lr,{className:"h-5 w-5 text-primary"})," Customize Your Post"]}),e.jsx(Br,{children:"Choose template, post type, format, and branding"})]}),e.jsxs(Oe,{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border bg-muted/30",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pl,{className:"h-4 w-4 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:Z?"AI Custom Generation":"Template-Based (Free)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Z?"Uses AI credits for unique designs":"Instant, no credits used"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Use AI"}),e.jsx(Or,{checked:Z,onCheckedChange:J}),Z&&e.jsx(My,{className:"h-4 w-4 text-purple-500"})]})]}),!Z&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ue,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(pl,{className:"h-4 w-4"})," Template Style"]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2",children:Czs.map(Me=>e.jsxs("button",{onClick:()=>j(Me.value),className:`flex flex-col items-center gap-1 px-3 py-3 rounded-lg border-2 transition-all text-center ${b===Me.value?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("span",{className:"text-2xl",children:Me.preview}),e.jsx("span",{className:"text-sm font-medium",children:Me.label}),e.jsx("span",{className:"text-[10px] text-muted-foreground leading-tight",children:Me.description})]},Me.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{className:"text-sm font-medium",children:"Post Type"}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2",children:Szs.map(Me=>e.jsxs("button",{onClick:()=>x(Me.value),className:`flex items-center gap-2 px-3 py-2.5 rounded-lg border-2 transition-all text-sm font-medium ${p===Me.value?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("span",{className:"text-lg",children:Me.icon})," ",Me.label]},Me.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{className:"text-sm font-medium",children:"Output Formats"}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-2",children:IWe.map(Me=>e.jsxs("button",{onClick:()=>fe(Me.value),className:`flex items-center gap-2 px-3 py-2.5 rounded-lg border-2 transition-all text-sm ${y.includes(Me.value)?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[Me.icon,e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"font-medium",children:Me.label}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:Me.dimensions})]})]},Me.value))})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(ue,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(io,{className:"h-4 w-4"})," Agent Branding"]}),e.jsx(Or,{checked:k,onCheckedChange:T})]}),k&&e.jsxs("div",{className:"space-y-3 pl-6 border-l-2 border-primary/20",children:[z&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("img",{src:z,alt:"Agent",className:"w-12 h-12 rounded-full object-cover border-2 border-primary/30"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Profile photo will appear on the post"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(ue,{className:"text-xs text-muted-foreground",children:"Agent Name"}),e.jsx(Se,{value:E,onChange:Me=>A(Me.target.value),placeholder:"Jane Smith"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(ue,{className:"text-xs text-muted-foreground",children:"Brokerage (optional)"}),e.jsx(Se,{value:D,onChange:Me=>R(Me.target.value),placeholder:"XYZ Realty"})]})]})]})]}),!Z&&Le&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{className:"text-sm font-medium",children:"Preview"}),e.jsx("div",{className:"bg-muted/30 rounded-lg p-4 flex justify-center overflow-hidden",children:e.jsx("div",{style:{width:400,height:400*(Sk[y[0]||"instagram-square"].height/Sk[y[0]||"instagram-square"].width)},children:(()=>{const Me=LWe[b],ze=y[0]||"instagram-square";return e.jsx(Me,{...Le,format:ze})})()})})]}),e.jsx(H,{onClick:We,disabled:y.length===0||$,size:"lg",className:"w-full gap-2",children:$?e.jsxs(e.Fragment,{children:[e.jsx(is,{className:"h-5 w-5 animate-spin"})," Generating ",y.length," post",y.length>1?"s":"","..."]}):e.jsxs(e.Fragment,{children:[Z?e.jsx(My,{className:"h-5 w-5"}):e.jsx(Lr,{className:"h-5 w-5"}),"Generate ",y.length," Social Post",y.length>1?"s":"",Z&&e.jsx(Xe,{variant:"outline",className:"ml-2 text-[10px]",children:"Uses Credits"})]})})]})]})]}),ie==="generate"&&e.jsxs("div",{className:"space-y-4",children:[$&&e.jsx(ke,{children:e.jsxs(Oe,{className:"flex flex-col items-center justify-center py-16",children:[e.jsx(is,{className:"h-12 w-12 animate-spin text-primary mb-4"}),e.jsx("p",{className:"text-lg font-medium",children:"Generating your social posts..."}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:Z?"AI is creating your unique designs":"Rendering templates to high-res images"})]})}),K.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-lg font-semibold",children:"Generated Posts"}),e.jsxs(H,{variant:"outline",size:"sm",onClick:()=>ce("customize"),children:[e.jsx(qy,{className:"h-3.5 w-3.5 mr-1.5"})," Regenerate"]})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:K.map((Me,ze)=>{const Pe=IWe.find(Ie=>Ie.value===Me.format);return e.jsxs(ke,{className:"overflow-hidden",children:[e.jsx("div",{className:"bg-muted/30 p-1",children:e.jsx("img",{src:Me.imageUrl,alt:`${Me.format} social post`,className:"w-full rounded"})}),e.jsxs(Oe,{className:"p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[Pe==null?void 0:Pe.icon,e.jsx("span",{className:"text-sm font-medium",children:Pe==null?void 0:Pe.label})]}),e.jsx(Xe,{variant:"outline",className:"text-[10px]",children:Pe==null?void 0:Pe.dimensions})]}),e.jsxs(H,{size:"sm",className:"w-full gap-1.5",onClick:()=>Ve(Me.imageUrl,Me.format),children:[e.jsx(hi,{className:"h-3.5 w-3.5"})," Download"]})]})]},ze)})})]})]}),ie==="generate"&&!Z&&c&&Le&&e.jsx("div",{style:{position:"absolute",left:"-9999px",top:0},"aria-hidden":!0,children:y.map(Me=>{const ze=LWe[b],Pe=Sk[Me];return e.jsx("div",{style:{width:Pe.width,height:Pe.height},children:e.jsx(ze,{ref:Ie=>{ne.current[`${b}-${Me}`]=Ie},...Le,format:Me})},`${b}-${Me}`)})})]})})}function Ezs(){return yt({queryKey:["lms-courses-admin"],queryFn:async()=>{const{data:s,error:t}=await V.from("lms_courses").select("*, modules:lms_modules(count), access:lms_course_access(*)").order("sort_order");if(t)throw t;return s}})}function Azs(s){return yt({queryKey:["lms-course-admin",s],queryFn:async()=>{if(!s)return null;const{data:t,error:r}=await V.from("lms_courses").select("*, modules:lms_modules(*, resources:lms_module_resources(*)), access:lms_course_access(*)").eq("id",s).single();if(r)throw r;return t!=null&&t.modules&&(t.modules.sort((n,a)=>n.sort_order-a.sort_order),t.modules.forEach(n=>{n.resources&&n.resources.sort((a,i)=>a.sort_order-i.sort_order)})),t},enabled:!!s})}function Mzs(){const s=ns();return Pt({mutationFn:async t=>{const{data:r,error:n}=await V.from("lms_courses").insert(t).select().single();if(n)throw n;return r},onSuccess:()=>s.invalidateQueries({queryKey:["lms-courses"]})})}function Nvt(){const s=ns();return Pt({mutationFn:async({id:t,...r})=>{const{data:n,error:a}=await V.from("lms_courses").update({...r,updated_at:new Date().toISOString()}).eq("id",t).select().single();if(a)throw a;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-courses"]}),s.invalidateQueries({queryKey:["lms-course"]}),s.invalidateQueries({queryKey:["lms-courses-admin"]}),s.invalidateQueries({queryKey:["lms-course-admin"]})}})}function Izs(){const s=ns();return Pt({mutationFn:async t=>{const{error:r}=await V.from("lms_courses").delete().eq("id",t);if(r)throw r},onSuccess:()=>s.invalidateQueries({queryKey:["lms-courses"]})})}function Pzs(){const s=ns();return Pt({mutationFn:async t=>{const{data:r,error:n}=await V.from("lms_modules").insert(t).select().single();if(n)throw n;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-course"]}),s.invalidateQueries({queryKey:["lms-course-admin"]})}})}function Lzs(){const s=ns();return Pt({mutationFn:async({id:t,...r})=>{const{data:n,error:a}=await V.from("lms_modules").update({...r,updated_at:new Date().toISOString()}).eq("id",t).select().single();if(a)throw a;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-course"]}),s.invalidateQueries({queryKey:["lms-course-admin"]})}})}function Dzs(){const s=ns();return Pt({mutationFn:async t=>{const{error:r}=await V.from("lms_modules").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-course"]}),s.invalidateQueries({queryKey:["lms-course-admin"]})}})}function Rzs(){const s=ns();return Pt({mutationFn:async t=>{const{data:r,error:n}=await V.from("lms_module_resources").insert(t).select().single();if(n)throw n;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-course"]}),s.invalidateQueries({queryKey:["lms-course-admin"]})}})}function Ozs(){const s=ns();return Pt({mutationFn:async t=>{const{error:r}=await V.from("lms_module_resources").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-course"]}),s.invalidateQueries({queryKey:["lms-course-admin"]})}})}function Fzs(){const s=ns();return Pt({mutationFn:async({courseId:t,accessRules:r})=>{const{error:n}=await V.from("lms_course_access").delete().eq("course_id",t);if(n)throw n;if(r.length>0){const a=r.map(l=>({...l,course_id:t})),{error:i}=await V.from("lms_course_access").insert(a);if(i)throw i}},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-courses"]}),s.invalidateQueries({queryKey:["lms-course"]})}})}function Bzs(){return yt({queryKey:["lms-courses-agent"],queryFn:async()=>{const{data:s,error:t}=await V.from("lms_courses").select("*, modules:lms_modules(id)").eq("is_published",!0).order("sort_order");if(t)throw t;return s}})}function zzs(s){return yt({queryKey:["lms-course-agent",s],queryFn:async()=>{if(!s)return null;const{data:t,error:r}=await V.from("lms_courses").select("*, modules:lms_modules(*, resources:lms_module_resources(*))").eq("id",s).single();if(r)throw r;return t!=null&&t.modules&&(t.modules.sort((n,a)=>n.sort_order-a.sort_order),t.modules.forEach(n=>{n.resources&&n.resources.sort((a,i)=>a.sort_order-i.sort_order)})),t},enabled:!!s})}function kvt(s){return yt({queryKey:["lms-progress",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await V.from("lms_progress").select("*").eq("course_id",s);if(r)throw r;return t},enabled:!!s})}function $zs(){const s=ns();return Pt({mutationFn:async({courseId:t,moduleId:r,userId:n})=>{const{data:a,error:i}=await V.from("lms_progress").upsert({user_id:n,course_id:t,module_id:r,completed:!0,completed_at:new Date().toISOString()},{onConflict:"user_id,module_id"}).select().single();if(i)throw i;return a},onSuccess:()=>s.invalidateQueries({queryKey:["lms-progress"]})})}function Uzs(){const{user:s}=Ms(),t=Fr(),{data:r,isLoading:n}=Ezs(),a=Mzs(),i=Nvt(),l=Izs(),[o,c]=S.useState(!1),[d,h]=S.useState(""),[m,p]=S.useState(""),[x,y]=S.useState(!0),_=async()=>{if(!(!d.trim()||!s))try{const k=await a.mutateAsync({title:d.trim(),description:m.trim()||void 0,is_sequential:x,created_by:s.id});he.success("Course created"),c(!1),h(""),p(""),y(!0),t(`/admin/lms/${k.id}`)}catch{he.error("Failed to create course")}},b=async k=>{try{await i.mutateAsync({id:k.id,is_published:!k.is_published}),he.success(k.is_published?"Course unpublished":"Course published")}catch{he.error("Failed to update course")}},j=async k=>{if(confirm("Delete this course and all its modules? This cannot be undone."))try{await l.mutateAsync(k),he.success("Course deleted")}catch{he.error("Failed to delete")}};return e.jsxs(Ss,{title:"LevelUp U - Admin",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-2xl font-bold text-foreground flex items-center gap-2",children:[e.jsx(Vu,{className:"h-7 w-7 text-primary"}),"LevelUp U — Course Manager"]}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Create and manage training courses for your agents"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(H,{variant:"outline",onClick:()=>t("/admin/lms/stats"),children:[e.jsx(Bo,{className:"h-4 w-4 mr-2"}),"Analytics"]}),e.jsxs(H,{onClick:()=>c(!0),children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"New Course"]})]})]}),n?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4",children:[1,2,3].map(k=>e.jsx(ke,{className:"animate-pulse",children:e.jsxs(Ot,{children:[e.jsx("div",{className:"h-5 bg-muted rounded w-2/3"}),e.jsx("div",{className:"h-3 bg-muted rounded w-1/2 mt-2"})]})},k))}):r!=null&&r.length?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4",children:r.map(k=>{var D,R;const T=((R=(D=k.modules)==null?void 0:D[0])==null?void 0:R.count)??0,E=k.access||[],A=E.length===0?"No access set":E.some(z=>z.access_type==="all")?"All agents":`${E.length} rule(s)`;return e.jsxs(ke,{className:"group hover:shadow-md transition-all hover:border-primary/50 cursor-pointer",onClick:()=>t(`/admin/lms/${k.id}`),children:[e.jsx(Ot,{className:"pb-3",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(zt,{className:"text-base truncate",children:k.title}),k.description&&e.jsx(Br,{className:"mt-1 line-clamp-2",children:k.description})]}),e.jsx(Xe,{variant:k.is_published?"default":"secondary",className:"ml-2 shrink-0",children:k.is_published?"Published":"Draft"})]})}),e.jsxs(Oe,{className:"pt-0",children:[e.jsxs("div",{className:"flex items-center gap-4 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(tf,{className:"h-3.5 w-3.5"}),T," module",T!==1?"s":""]}),e.jsxs("span",{className:"flex items-center gap-1",children:[k.is_sequential?e.jsx(b1,{className:"h-3.5 w-3.5"}):e.jsx(RE,{className:"h-3.5 w-3.5"}),k.is_sequential?"Sequential":"Free order"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ar,{className:"h-3.5 w-3.5"}),A]})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-3 opacity-0 group-hover:opacity-100 transition-opacity",children:[e.jsxs(H,{size:"sm",variant:"ghost",onClick:z=>{z.stopPropagation(),b(k)},children:[k.is_published?e.jsx($f,{className:"h-3.5 w-3.5 mr-1"}):e.jsx(Bn,{className:"h-3.5 w-3.5 mr-1"}),k.is_published?"Unpublish":"Publish"]}),e.jsx(H,{size:"sm",variant:"ghost",className:"text-destructive",onClick:z=>{z.stopPropagation(),j(k.id)},children:e.jsx(Dr,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:"flex-1"}),e.jsx(bi,{className:"h-4 w-4 text-muted-foreground"})]})]})]},k.id)})}):e.jsx(ke,{className:"border-dashed",children:e.jsxs(Oe,{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx(tf,{className:"h-12 w-12 text-muted-foreground/50 mb-4"}),e.jsx("h3",{className:"text-lg font-semibold text-foreground mb-1",children:"No courses yet"}),e.jsx("p",{className:"text-muted-foreground text-sm mb-4",children:"Create your first training course to get started"}),e.jsxs(H,{onClick:()=>c(!0),children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Create Course"]})]})})]}),e.jsx(bs,{open:o,onOpenChange:c,children:e.jsxs(vs,{children:[e.jsxs(Cs,{children:[e.jsx(Ns,{children:"Create New Course"}),e.jsx(nn,{children:"Set up a new training course for your agents"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ue,{children:"Course Title"}),e.jsx(Se,{value:d,onChange:k=>h(k.target.value),placeholder:"e.g. LevelUp Onboarding"})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Description"}),e.jsx(vr,{value:m,onChange:k=>p(k.target.value),placeholder:"What will agents learn?",rows:3})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Sequential Learning"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Agents must complete modules in order"})]}),e.jsx(Or,{checked:x,onCheckedChange:y})]})]}),e.jsxs(wn,{children:[e.jsx(H,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsx(H,{onClick:_,disabled:!d.trim()||a.isPending,children:a.isPending?"Creating...":"Create Course"})]})]})})]})}function qzs(){const{courseId:s}=Po(),t=Fr(),{data:r,isLoading:n}=Azs(s),a=Nvt(),i=Pzs(),l=Lzs(),o=Dzs(),c=Rzs(),d=Ozs(),h=Fzs(),{data:m}=yt({queryKey:["all-brokerages"],queryFn:async()=>{const{data:Je}=await V.from("brokerages").select("id, name").order("name");return Je||[]}}),[p,x]=S.useState(null),[y,_]=S.useState(!1),[b,j]=S.useState({title:"",description:"",video_url:"",text_content:"",duration_minutes:""}),[k,T]=S.useState(null),[E,A]=S.useState({title:"",resource_type:"link",url:""}),[D,R]=S.useState(new Set),[z,O]=S.useState(null),[$,ee]=S.useState(0),[Z,J]=S.useState(!1),K=S.useRef(null),re=S.useRef(null),[ie,ce]=S.useState(!1),[ne,le]=S.useState(""),[be,fe]=S.useState(""),[je,ve]=S.useState(""),[We,Ve]=S.useState(!1);if(n)return e.jsx(Ss,{title:"Loading...",children:e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})});if(!r)return e.jsx(Ss,{title:"Course Not Found",children:e.jsxs("div",{className:"text-center py-20",children:[e.jsx("p",{className:"text-muted-foreground",children:"Course not found"}),e.jsxs(H,{variant:"outline",className:"mt-4",onClick:()=>t("/admin/lms"),children:[e.jsx(za,{className:"h-4 w-4 mr-2"})," Back to Courses"]})]})});const Le=r.modules||[],Me=r.access||[],ze=Me.some(Je=>Je.access_type==="all"),Pe=Me.filter(Je=>Je.access_type==="brokerage").map(Je=>Je.brokerage_id),Ie=(m||[]).filter(Je=>Je.name.toLowerCase().includes(ne.toLowerCase())),De=Je=>{const st=new Set(D);st.has(Je)?st.delete(Je):st.add(Je),R(st)},pe=async()=>{if(!z)return null;J(!0),ee(0);try{const{data:Je,error:st}=await V.functions.invoke("bunny-upload",{body:{action:"create",title:z.name}});if(st)throw new Error(st.message);const{videoId:mt,libraryId:wt}=Je,{data:at,error:rt}=await V.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:mt,libraryId:wt}});if(rt)throw new Error(rt.message);const Et=new XMLHttpRequest;return await new Promise((hs,Is)=>{Et.upload.onprogress=lr=>{lr.lengthComputable&&ee(Math.round(lr.loaded/lr.total*100))},Et.onload=()=>Et.status>=200&&Et.status<300?hs():Is(new Error(`Upload failed: ${Et.status}`)),Et.onerror=()=>Is(new Error("Upload failed")),Et.open("PUT",at.uploadUrl),Et.setRequestHeader("AccessKey",at.apiKey),Et.send(z)}),`https://iframe.mediadelivery.net/embed/${wt}/${mt}`}catch(Je){return console.error("Bunny upload error:",Je),he.error("Video upload failed"),null}finally{J(!1),ee(0)}},tt=async()=>{if(b.title.trim())try{let Je=b.video_url.trim()||void 0;if(z){const st=await pe();if(!st)return;Je=st}await i.mutateAsync({course_id:r.id,title:b.title.trim(),description:b.description.trim()||void 0,video_url:Je,text_content:b.text_content.trim()||void 0,duration_minutes:b.duration_minutes?parseInt(b.duration_minutes):void 0,sort_order:Le.length}),he.success("Module added"),_(!1),j({title:"",description:"",video_url:"",text_content:"",duration_minutes:""}),O(null)}catch{he.error("Failed to add module")}},ge=async()=>{if(p)try{let Je=b.video_url.trim()||null;if(z){const st=await pe();if(!st)return;Je=st}await l.mutateAsync({id:p.id,title:b.title.trim(),description:b.description.trim()||null,video_url:Je,text_content:b.text_content.trim()||null,duration_minutes:b.duration_minutes?parseInt(b.duration_minutes):null}),he.success("Module updated"),x(null),O(null)}catch{he.error("Failed to update")}},ct=async Je=>{if(confirm("Delete this module?"))try{await o.mutateAsync(Je),he.success("Module deleted")}catch{he.error("Failed to delete")}},Ue=async Je=>{if(E.title.trim())try{await c.mutateAsync({module_id:Je,title:E.title.trim(),resource_type:E.resource_type,url:E.url.trim()||void 0}),he.success("Resource added"),T(null),A({title:"",resource_type:"link",url:""})}catch{he.error("Failed to add resource")}},et=async()=>{try{await h.mutateAsync({courseId:r.id,accessRules:[{access_type:"all"}]}),he.success("Access updated: All brokerages / all agents")}catch{he.error("Failed to update access")}},Qe=async Je=>{const st=Me.filter(rt=>rt.access_type==="brokerage").map(rt=>rt.brokerage_id),mt=st.includes(Je);let wt;mt?wt=st.filter(rt=>rt!==Je):wt=[...st,Je];const at=wt.map(rt=>({access_type:"brokerage",brokerage_id:rt}));try{await h.mutateAsync({courseId:r.id,accessRules:at}),he.success(mt?"Brokerage removed":"Brokerage added")}catch{he.error("Failed to update access")}},Ne=async()=>{try{await h.mutateAsync({courseId:r.id,accessRules:[]}),he.success("Access cleared")}catch{he.error("Failed")}},$e=async(Je,st)=>{const mt=st==="up"?Je-1:Je+1;if(!(mt<0||mt>=Le.length))try{await Promise.all([l.mutateAsync({id:Le[Je].id,sort_order:mt}),l.mutateAsync({id:Le[mt].id,sort_order:Je})])}catch{he.error("Failed to reorder")}},it=async()=>{try{await a.mutateAsync({id:r.id,title:be,description:je||null}),he.success("Course updated"),Ve(!1)}catch{he.error("Failed to update")}};return e.jsxs(Ss,{title:r.title,children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(H,{variant:"ghost",size:"icon",onClick:()=>t("/admin/lms"),children:e.jsx(za,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:r.title}),e.jsx(Xe,{variant:r.is_published?"default":"secondary",children:r.is_published?"Published":"Draft"})]}),r.description&&e.jsx("p",{className:"text-muted-foreground mt-1",children:r.description}),e.jsxs("div",{className:"flex items-center gap-3 mt-2 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[r.is_sequential?e.jsx(b1,{className:"h-3.5 w-3.5"}):e.jsx(RE,{className:"h-3.5 w-3.5"}),r.is_sequential?"Sequential":"Free order"]}),e.jsxs("span",{children:[Le.length," module",Le.length!==1?"s":""]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(H,{variant:"outline",size:"sm",onClick:()=>{fe(r.title),ve(r.description||""),Ve(!0)},children:[e.jsx(ni,{className:"h-3.5 w-3.5 mr-1"})," Edit"]}),e.jsxs(H,{variant:r.is_published?"secondary":"default",size:"sm",onClick:()=>a.mutateAsync({id:r.id,is_published:!r.is_published}).then(()=>he.success(r.is_published?"Unpublished":"Published")),children:[r.is_published?e.jsx($f,{className:"h-3.5 w-3.5 mr-1"}):e.jsx(Bn,{className:"h-3.5 w-3.5 mr-1"}),r.is_published?"Unpublish":"Publish"]})]})]}),e.jsxs(ta,{defaultValue:"modules",className:"w-full",children:[e.jsxs(Qn,{children:[e.jsx(ts,{value:"modules",children:"Modules"}),e.jsx(ts,{value:"access",children:"Access & Permissions"}),e.jsx(ts,{value:"settings",children:"Settings"})]}),e.jsxs(cs,{value:"modules",className:"mt-6 space-y-4",children:[Le.map((Je,st)=>e.jsxs(ke,{className:"overflow-hidden",children:[e.jsxs("div",{className:"flex items-center gap-3 p-4 cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>De(Je.id),children:[e.jsx("span",{className:"flex items-center gap-1 text-muted-foreground",children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("button",{onClick:mt=>{mt.stopPropagation(),$e(st,"up")},disabled:st===0,className:"hover:text-foreground disabled:opacity-30",children:e.jsx(cx,{className:"h-3.5 w-3.5"})}),e.jsx("button",{onClick:mt=>{mt.stopPropagation(),$e(st,"down")},disabled:st===Le.length-1,className:"hover:text-foreground disabled:opacity-30",children:e.jsx(Io,{className:"h-3.5 w-3.5"})})]})}),e.jsx(Xe,{variant:"outline",className:"shrink-0 font-mono text-xs",children:st+1}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:Je.title}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground mt-0.5",children:[Je.video_url&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(xn,{className:"h-3 w-3"})," Video"]}),Je.text_content&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(kn,{className:"h-3 w-3"})," Text"]}),Je.duration_minutes&&e.jsxs("span",{children:[Je.duration_minutes," min"]}),Je.resources&&Je.resources.length>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(ql,{className:"h-3 w-3"})," ",Je.resources.length," resource(s)"]})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(H,{size:"sm",variant:"ghost",onClick:mt=>{var wt;mt.stopPropagation(),x(Je),j({title:Je.title,description:Je.description||"",video_url:Je.video_url||"",text_content:Je.text_content||"",duration_minutes:((wt=Je.duration_minutes)==null?void 0:wt.toString())||""})},children:e.jsx(ni,{className:"h-3.5 w-3.5"})}),e.jsx(H,{size:"sm",variant:"ghost",className:"text-destructive",onClick:mt=>{mt.stopPropagation(),ct(Je.id)},children:e.jsx(Dr,{className:"h-3.5 w-3.5"})})]})]}),D.has(Je.id)&&e.jsxs("div",{className:"border-t bg-muted/30 p-4 space-y-3",children:[Je.description&&e.jsx("p",{className:"text-sm text-muted-foreground",children:Je.description}),Je.video_url&&e.jsxs("div",{className:"text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"Video: "}),e.jsx("a",{href:Je.video_url,target:"_blank",rel:"noreferrer",className:"text-primary hover:underline break-all",children:Je.video_url})]}),Je.text_content&&e.jsx("div",{className:"text-sm bg-background rounded-md p-3 border max-h-40 overflow-auto whitespace-pre-wrap",children:Je.text_content}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"Resources"}),e.jsxs(H,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:()=>{T(Je.id),A({title:"",resource_type:"link",url:""})},children:[e.jsx(Ys,{className:"h-3 w-3 mr-1"})," Add Resource"]})]}),Je.resources&&Je.resources.length>0?e.jsx("div",{className:"space-y-1",children:Je.resources.map(mt=>e.jsxs("div",{className:"flex items-center gap-2 text-sm bg-background rounded p-2 border",children:[e.jsx(Xe,{variant:"outline",className:"text-[10px]",children:mt.resource_type}),e.jsx("span",{className:"flex-1 truncate",children:mt.title}),mt.url&&e.jsx("a",{href:mt.url,target:"_blank",rel:"noreferrer",className:"text-primary hover:underline text-xs",children:"Open"}),e.jsx(H,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0 text-destructive",onClick:()=>d.mutateAsync(mt.id),children:e.jsx(Rr,{className:"h-3 w-3"})})]},mt.id))}):e.jsx("p",{className:"text-xs text-muted-foreground",children:"No resources yet"})]})]})]},Je.id)),e.jsxs(H,{variant:"outline",className:"w-full border-dashed",onClick:()=>{_(!0),j({title:"",description:"",video_url:"",text_content:"",duration_minutes:""})},children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"})," Add Module"]})]}),e.jsx(cs,{value:"access",className:"mt-6 space-y-4",children:e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-base",children:"Who can access this course?"})}),e.jsxs(Oe,{className:"space-y-5",children:[e.jsxs("div",{className:Ft("flex items-center gap-3 p-4 rounded-xl border-2 cursor-pointer transition-all",ze?"border-primary bg-primary/5":"border-muted hover:border-muted-foreground/30"),onClick:et,children:[e.jsx("div",{className:Ft("h-10 w-10 rounded-full flex items-center justify-center shrink-0",ze?"bg-primary/15 text-primary":"bg-muted text-muted-foreground"),children:e.jsx(ld,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm font-semibold",children:"All Brokerages / All Agents"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Every agent on the platform can access this course"})]}),e.jsx(Or,{checked:ze,onCheckedChange:et})]}),!ze&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold",children:"Select Brokerages"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Pe.length===0?"No brokerages selected — agents won't see this course":`${Pe.length} brokerage${Pe.length!==1?"s":""} selected`})]}),Pe.length>0&&e.jsx(H,{size:"sm",variant:"ghost",className:"text-xs text-muted-foreground",onClick:Ne,children:"Clear all"})]}),e.jsx(Se,{placeholder:"Search brokerages...",value:ne,onChange:Je=>le(Je.target.value),className:"h-9"}),e.jsx("div",{className:"border rounded-lg divide-y max-h-[360px] overflow-auto",children:Ie.length===0?e.jsx("div",{className:"p-4 text-center text-sm text-muted-foreground",children:"No brokerages found"}):Ie.map(Je=>{const st=Pe.includes(Je.id);return e.jsxs("div",{className:Ft("flex items-center gap-3 px-3 py-2.5 cursor-pointer transition-colors",st?"bg-primary/5":"hover:bg-muted/50"),onClick:()=>Qe(Je.id),children:[e.jsx("div",{className:Ft("h-5 w-5 rounded border-2 flex items-center justify-center shrink-0 transition-colors",st?"bg-primary border-primary":"border-muted-foreground/30"),children:st&&e.jsx("svg",{className:"h-3 w-3 text-primary-foreground",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:3,children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5 13l4 4L19 7"})})}),e.jsx(Xa,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsx("span",{className:"text-sm flex-1 truncate",children:Je.name}),st&&e.jsx(Xe,{variant:"secondary",className:"text-[10px] shrink-0",children:"Active"})]},Je.id)})})]})]})]})}),e.jsxs(cs,{value:"settings",className:"mt-6 space-y-4",children:[e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-base",children:"Course Thumbnail"})}),e.jsx(Oe,{children:e.jsxs("div",{className:"flex items-start gap-6",children:[r.thumbnail_url?e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:r.thumbnail_url,alt:"Course thumbnail",className:"w-48 h-28 object-cover rounded-lg border"}),e.jsx("button",{onClick:()=>a.mutateAsync({id:r.id,thumbnail_url:null}).then(()=>he.success("Thumbnail removed")),className:"absolute -top-2 -right-2 bg-destructive text-destructive-foreground rounded-full p-1 opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx(Rr,{className:"h-3 w-3"})})]}):e.jsxs("div",{className:"w-48 h-28 rounded-lg border-2 border-dashed border-muted-foreground/25 flex flex-col items-center justify-center text-muted-foreground",children:[e.jsx(f_,{className:"h-8 w-8 mb-1 opacity-50"}),e.jsx("span",{className:"text-xs",children:"No thumbnail"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Upload a thumbnail image for this course. Recommended: 800×450px (16:9)."}),e.jsx("input",{ref:re,type:"file",accept:"image/*",className:"hidden",onChange:async Je=>{var mt;const st=(mt=Je.target.files)==null?void 0:mt[0];if(!(!st||!r)){ce(!0);try{const wt=st.name.split(".").pop(),at=`${r.id}/thumbnail.${wt}`,{error:rt}=await V.storage.from("lms-thumbnails").upload(at,st,{upsert:!0});if(rt)throw rt;const{data:Et}=V.storage.from("lms-thumbnails").getPublicUrl(at),hs=`${Et.publicUrl}?t=${Date.now()}`;await a.mutateAsync({id:r.id,thumbnail_url:hs}),he.success("Thumbnail uploaded")}catch{he.error("Failed to upload thumbnail")}finally{ce(!1),re.current&&(re.current.value="")}}}}),e.jsxs(H,{variant:"outline",size:"sm",disabled:ie,onClick:()=>{var Je;return(Je=re.current)==null?void 0:Je.click()},children:[ie?e.jsx(is,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Ea,{className:"h-4 w-4 mr-2"}),ie?"Uploading...":"Upload Thumbnail"]})]})]})})]}),e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-base",children:"Course Settings"})}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Sequential Learning"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Agents must complete modules in order before advancing"})]}),e.jsx(Or,{checked:r.is_sequential,onCheckedChange:Je=>a.mutateAsync({id:r.id,is_sequential:Je}).then(()=>he.success("Updated"))})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Published"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Make this course visible to agents with access"})]}),e.jsx(Or,{checked:r.is_published,onCheckedChange:Je=>a.mutateAsync({id:r.id,is_published:Je}).then(()=>he.success("Updated"))})]})]})]})]})]})]}),e.jsx(bs,{open:y||!!p,onOpenChange:Je=>{Je||(_(!1),x(null))},children:e.jsxs(vs,{className:"max-w-lg",children:[e.jsxs(Cs,{children:[e.jsx(Ns,{children:p?"Edit Module":"Add Module"}),e.jsx(nn,{children:"Configure the module content"})]}),e.jsxs("div",{className:"space-y-4 max-h-[60vh] overflow-auto",children:[e.jsxs("div",{children:[e.jsx(ue,{children:"Title"}),e.jsx(Se,{value:b.title,onChange:Je=>j(st=>({...st,title:Je.target.value})),placeholder:"Module title"})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Description"}),e.jsx(vr,{value:b.description,onChange:Je=>j(st=>({...st,description:Je.target.value})),placeholder:"Brief description",rows:2})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Video"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:Ft("border-2 border-dashed rounded-lg p-4 text-center cursor-pointer transition-colors hover:border-primary/50",z?"border-primary bg-primary/5":"border-muted-foreground/25"),onClick:()=>{var Je;return(Je=K.current)==null?void 0:Je.click()},children:[e.jsx("input",{ref:K,type:"file",accept:"video/*",className:"hidden",onChange:Je=>{var mt;const st=(mt=Je.target.files)==null?void 0:mt[0];st&&(O(st),j(wt=>({...wt,video_url:""})))}}),z?e.jsxs("div",{className:"flex items-center justify-center gap-2 text-sm",children:[e.jsx(xn,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"font-medium text-primary",children:z.name}),e.jsx(H,{type:"button",size:"sm",variant:"ghost",className:"h-6 w-6 p-0",onClick:Je=>{Je.stopPropagation(),O(null)},children:e.jsx(Rr,{className:"h-3 w-3"})})]}):e.jsxs("div",{className:"flex flex-col items-center gap-1 text-muted-foreground",children:[e.jsx(Ea,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs",children:"Click to upload a video file"})]})]}),Z&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(is,{className:"h-3.5 w-3.5 animate-spin"}),e.jsxs("span",{children:["Uploading to Bunny.net... ",$,"%"]})]}),e.jsx(Mi,{value:$,className:"h-1.5"})]}),!z&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx("div",{className:"flex-1 h-px bg-border"}),e.jsx("span",{children:"or paste a URL"}),e.jsx("div",{className:"flex-1 h-px bg-border"})]}),e.jsx(Se,{value:b.video_url,onChange:Je=>j(st=>({...st,video_url:Je.target.value})),placeholder:"YouTube, Vimeo, or Bunny.net URL"})]})]})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Text Content"}),e.jsx(vr,{value:b.text_content,onChange:Je=>j(st=>({...st,text_content:Je.target.value})),placeholder:"Additional text content, instructions, notes...",rows:4})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Duration (minutes)"}),e.jsx(Se,{type:"number",value:b.duration_minutes,onChange:Je=>j(st=>({...st,duration_minutes:Je.target.value})),placeholder:"e.g. 15"})]})]}),e.jsxs(wn,{children:[e.jsx(H,{variant:"outline",onClick:()=>{_(!1),x(null),O(null)},children:"Cancel"}),e.jsxs(H,{onClick:p?ge:tt,disabled:!b.title.trim()||Z,children:[Z?e.jsx(is,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(vc,{className:"h-4 w-4 mr-2"}),Z?"Uploading...":p?"Save Changes":"Add Module"]})]})]})}),e.jsx(bs,{open:!!k,onOpenChange:Je=>{Je||T(null)},children:e.jsxs(vs,{children:[e.jsxs(Cs,{children:[e.jsx(Ns,{children:"Add Resource"}),e.jsx(nn,{children:"Add a link, document, or other resource to this module"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ue,{children:"Title"}),e.jsx(Se,{value:E.title,onChange:Je=>A(st=>({...st,title:Je.target.value})),placeholder:"Resource title"})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Type"}),e.jsxs(Bs,{value:E.resource_type,onValueChange:Je=>A(st=>({...st,resource_type:Je})),children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"link",children:"Link"}),e.jsx(pt,{value:"pdf",children:"PDF"}),e.jsx(pt,{value:"template",children:"Template"}),e.jsx(pt,{value:"worksheet",children:"Worksheet"})]})]})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"URL"}),e.jsx(Se,{value:E.url,onChange:Je=>A(st=>({...st,url:Je.target.value})),placeholder:"https://..."})]})]}),e.jsxs(wn,{children:[e.jsx(H,{variant:"outline",onClick:()=>T(null),children:"Cancel"}),e.jsx(H,{onClick:()=>k&&Ue(k),disabled:!E.title.trim(),children:"Add Resource"})]})]})}),e.jsx(bs,{open:We,onOpenChange:Ve,children:e.jsxs(vs,{children:[e.jsxs(Cs,{children:[e.jsx(Ns,{children:"Edit Course"}),e.jsx(nn,{children:"Update the course title and description"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ue,{children:"Title"}),e.jsx(Se,{value:be,onChange:Je=>fe(Je.target.value)})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Description"}),e.jsx(vr,{value:je,onChange:Je=>ve(Je.target.value),rows:3})]})]}),e.jsxs(wn,{children:[e.jsx(H,{variant:"outline",onClick:()=>Ve(!1),children:"Cancel"}),e.jsx(H,{onClick:it,disabled:!be.trim(),children:"Save"})]})]})})]})}function Vzs(){return yt({queryKey:["lms-stats-overview"],queryFn:async()=>{const{data:s,error:t}=await V.rpc("get_lms_stats");if(t)throw t;return s}})}function Hzs(){return yt({queryKey:["lms-stats-courses"],queryFn:async()=>{const{data:s,error:t}=await V.rpc("get_lms_course_stats");if(t)throw t;return s||[]}})}function Gzs(s){return yt({queryKey:["lms-stats-agents",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await V.rpc("get_lms_agent_progress",{p_course_id:s});if(r)throw r;return t||[]},enabled:!!s})}function Wzs(){const s=Fr(),{data:t,isLoading:r}=Vzs(),{data:n,isLoading:a}=Hzs(),[i,l]=S.useState(null),{data:o,isLoading:c}=Gzs(i),[d,h]=S.useState(""),m=n==null?void 0:n.find(y=>y.course_id===i),p=o==null?void 0:o.filter(y=>{var _,b;return!d||((_=y.agent_name)==null?void 0:_.toLowerCase().includes(d.toLowerCase()))||((b=y.email)==null?void 0:b.toLowerCase().includes(d.toLowerCase()))}),x=[{label:"Total Courses",value:(t==null?void 0:t.total_courses)??0,icon:tf,color:"text-primary"},{label:"Published",value:(t==null?void 0:t.published_courses)??0,icon:ea,color:"text-emerald-500"},{label:"Enrolled Agents",value:(t==null?void 0:t.total_enrollments)??0,icon:Ar,color:"text-blue-500"},{label:"Modules Completed",value:(t==null?void 0:t.total_completions)??0,icon:To,color:"text-amber-500"},{label:"Active (30d)",value:(t==null?void 0:t.active_learners)??0,icon:al,color:"text-violet-500"},{label:"Total Modules",value:(t==null?void 0:t.total_modules)??0,icon:Bo,color:"text-rose-500"}];return e.jsx(Ss,{title:"LevelUp U - Stats",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(H,{variant:"ghost",size:"icon",onClick:()=>s("/admin/lms"),children:e.jsx(za,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsxs("h1",{className:"text-2xl font-bold text-foreground flex items-center gap-2",children:[e.jsx(Vu,{className:"h-7 w-7 text-primary"}),"LevelUp U — Analytics"]}),e.jsx("p",{className:"text-muted-foreground text-sm mt-0.5",children:"Track enrollment, progress, and completion across all courses"})]})]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 xl:grid-cols-6 gap-3",children:x.map(y=>e.jsx(ke,{className:Ft("transition-all",r&&"animate-pulse"),children:e.jsxs(Oe,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(y.icon,{className:Ft("h-4 w-4",y.color)}),e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:y.label})]}),e.jsx("p",{className:"text-2xl font-bold text-foreground",children:r?"—":y.value})]})},y.label))}),e.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-5 gap-6",children:[e.jsxs("div",{className:"xl:col-span-2 space-y-3",children:[e.jsxs("h2",{className:"text-lg font-semibold text-foreground flex items-center gap-2",children:[e.jsx(Bo,{className:"h-5 w-5 text-primary"}),"Course Breakdown"]}),a?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(y=>e.jsx(ke,{className:"animate-pulse",children:e.jsx(Oe,{className:"p-4",children:e.jsx("div",{className:"h-16 bg-muted rounded"})})},y))}):n!=null&&n.length?e.jsx("div",{className:"space-y-2",children:n.map(y=>{const _=i===y.course_id;return e.jsx(ke,{className:Ft("cursor-pointer transition-all hover:shadow-md",_?"border-primary ring-1 ring-primary/30 shadow-md":"hover:border-primary/40"),onClick:()=>l(_?null:y.course_id),children:e.jsxs(Oe,{className:"p-4",children:[e.jsxs("div",{className:"flex items-start justify-between mb-3",children:[e.jsx("div",{className:"flex-1 min-w-0",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"font-semibold text-sm text-foreground truncate",children:y.course_title}),e.jsx(Xe,{variant:y.is_published?"default":"secondary",className:"shrink-0 text-[10px] px-1.5 py-0",children:y.is_published?"Live":"Draft"})]})}),e.jsx($a,{className:Ft("h-4 w-4 text-muted-foreground transition-transform shrink-0 ml-2",_&&"rotate-90")})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3 text-center",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-bold text-foreground",children:y.enrolled_agents}),e.jsx("p",{className:"text-[10px] text-muted-foreground uppercase tracking-wide",children:"Enrolled"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-bold text-foreground",children:y.total_completions}),e.jsx("p",{className:"text-[10px] text-muted-foreground uppercase tracking-wide",children:"Completed"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-bold text-foreground",children:y.total_modules}),e.jsx("p",{className:"text-[10px] text-muted-foreground uppercase tracking-wide",children:"Modules"})]})]}),e.jsxs("div",{className:"mt-3",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs mb-1",children:[e.jsx("span",{className:"text-muted-foreground",children:"Avg. Completion"}),e.jsxs("span",{className:"font-semibold text-foreground",children:[y.avg_completion_pct,"%"]})]}),e.jsx(Mi,{value:y.avg_completion_pct,className:"h-2"})]})]})},y.course_id)})}):e.jsx(ke,{className:"border-dashed",children:e.jsx(Oe,{className:"py-10 text-center",children:e.jsx("p",{className:"text-muted-foreground text-sm",children:"No courses created yet"})})})]}),e.jsxs("div",{className:"xl:col-span-3 space-y-3",children:[e.jsxs("h2",{className:"text-lg font-semibold text-foreground flex items-center gap-2",children:[e.jsx(j1,{className:"h-5 w-5 text-primary"}),m?`Agent Progress — ${m.course_title}`:"Agent Progress"]}),i?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"relative",children:[e.jsx(Mn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Se,{value:d,onChange:y=>h(y.target.value),placeholder:"Search agents...",className:"pl-9"})]}),c?e.jsx("div",{className:"space-y-2",children:[1,2,3,4].map(y=>e.jsx(ke,{className:"animate-pulse",children:e.jsx(Oe,{className:"p-4",children:e.jsx("div",{className:"h-12 bg-muted rounded"})})},y))}):p!=null&&p.length?e.jsx("div",{className:"space-y-2 max-h-[600px] overflow-y-auto pr-1",children:p.map((y,_)=>{const b=y.completion_pct>=100;return e.jsx(ke,{className:Ft("transition-all",b&&"border-emerald-200 bg-emerald-50/30 dark:border-emerald-900/40 dark:bg-emerald-950/10"),children:e.jsx(Oe,{className:"p-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:Ft("flex items-center justify-center w-7 h-7 rounded-full text-xs font-bold shrink-0",_===0?"bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400":_===1?"bg-slate-100 text-slate-600 dark:bg-slate-800 dark:text-slate-400":_===2?"bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-400":"bg-muted text-muted-foreground"),children:_+1}),e.jsxs(Un,{className:"h-9 w-9 shrink-0",children:[e.jsx(Ka,{src:y.avatar_url||void 0}),e.jsx(qn,{className:"text-xs bg-primary/10 text-primary",children:(y.agent_name||y.email||"?").charAt(0).toUpperCase()})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"text-sm font-medium text-foreground truncate",children:y.agent_name||y.email}),b&&e.jsxs(Xe,{variant:"default",className:"text-[10px] px-1.5 py-0 bg-emerald-500 hover:bg-emerald-600 shrink-0",children:[e.jsx(ea,{className:"h-3 w-3 mr-0.5"})," Complete"]})]}),e.jsxs("div",{className:"flex items-center gap-3 text-[11px] text-muted-foreground mt-0.5",children:[e.jsxs("span",{children:[y.modules_completed,"/",y.total_modules," modules"]}),y.last_activity&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Pn,{className:"h-3 w-3"}),As(new Date(y.last_activity),"MMM d, yyyy")]})]})]}),e.jsxs("div",{className:"text-right shrink-0 w-20",children:[e.jsxs("p",{className:Ft("text-sm font-bold",b?"text-emerald-600 dark:text-emerald-400":"text-foreground"),children:[y.completion_pct,"%"]}),e.jsx(Mi,{value:y.completion_pct,className:"h-1.5 mt-1"})]})]})})},y.user_id)})}):e.jsx(ke,{className:"border-dashed",children:e.jsx(Oe,{className:"py-10 text-center",children:e.jsx("p",{className:"text-muted-foreground text-sm",children:d?"No agents match your search":"No agents have started this course yet"})})})]}):e.jsx(ke,{className:"border-dashed",children:e.jsxs(Oe,{className:"py-16 text-center",children:[e.jsx(Ar,{className:"h-10 w-10 text-muted-foreground/40 mx-auto mb-3"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Select a course to view agent progress"})]})})]})]})]})})}function Kzs(){const{user:s}=Ms(),t=Fr(),{data:r,isLoading:n}=Bzs();return e.jsx(Ss,{title:"LevelUp U",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"relative overflow-hidden rounded-2xl bg-gradient-to-br from-primary/10 via-primary/5 to-background border p-8",children:[e.jsx("div",{className:"relative z-10",children:e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("div",{className:"h-12 w-12 rounded-xl bg-primary/15 flex items-center justify-center",children:e.jsx(Vu,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"LevelUp U"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Your training & development hub"})]})]})}),e.jsx("div",{className:"absolute top-0 right-0 w-64 h-64 bg-primary/5 rounded-full -translate-y-1/2 translate-x-1/2"})]}),n?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[1,2,3].map(a=>e.jsx(ke,{className:"animate-pulse",children:e.jsxs(Oe,{className:"p-6",children:[e.jsx("div",{className:"h-5 bg-muted rounded w-2/3"}),e.jsx("div",{className:"h-3 bg-muted rounded w-1/2 mt-3"})]})},a))}):r!=null&&r.length?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:r.map(a=>e.jsx(Yzs,{course:a,userId:s==null?void 0:s.id,onClick:()=>t(`/levelup-u/${a.id}`)},a.id))}):e.jsx(ke,{className:"border-dashed",children:e.jsxs(Oe,{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx(tf,{className:"h-12 w-12 text-muted-foreground/50 mb-4"}),e.jsx("h3",{className:"text-lg font-semibold mb-1",children:"No courses available yet"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Check back soon for new training content"})]})})]})})}function Yzs({course:s,userId:t,onClick:r}){var o;const n=((o=s.modules)==null?void 0:o.length)??0,{data:a}=kvt(s.id),i=(a==null?void 0:a.filter(c=>c.completed).length)??0,l=n>0?Math.round(i/n*100):0;return e.jsxs(ke,{className:"group cursor-pointer hover:shadow-lg transition-all hover:border-primary/50 overflow-hidden",onClick:r,children:[s.thumbnail_url?e.jsx("div",{className:"aspect-video bg-muted overflow-hidden",children:e.jsx("img",{src:s.thumbnail_url,alt:s.title,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"})}):e.jsx("div",{className:"aspect-video bg-gradient-to-br from-primary/15 via-primary/5 to-muted flex items-center justify-center",children:e.jsx(Vu,{className:"h-10 w-10 text-primary/40"})}),e.jsxs(Oe,{className:"p-4 space-y-3",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-foreground group-hover:text-primary transition-colors line-clamp-1",children:s.title}),s.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1 line-clamp-2",children:s.description})]}),e.jsxs("div",{className:"flex items-center gap-3 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(tf,{className:"h-3.5 w-3.5"}),n," module",n!==1?"s":""]}),e.jsxs("span",{className:"flex items-center gap-1",children:[s.is_sequential?e.jsx(b1,{className:"h-3.5 w-3.5"}):e.jsx(RE,{className:"h-3.5 w-3.5"}),s.is_sequential?"In order":"Any order"]})]}),n>0&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsxs("span",{className:"text-muted-foreground",children:[i," of ",n," completed"]}),e.jsxs("span",{className:"font-medium text-foreground",children:[l,"%"]})]}),e.jsx(Mi,{value:l,className:"h-1.5"})]}),e.jsx("div",{className:"flex items-center justify-end",children:e.jsxs("span",{className:"text-xs text-primary font-medium flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity",children:[l===100?"Review":l>0?"Continue":"Start"," Course",e.jsx($a,{className:"h-3.5 w-3.5"})]})})]})]})}function Zzs(){const{courseId:s}=Po(),t=Fr(),{user:r}=Ms(),{data:n,isLoading:a}=zzs(s),{data:i}=kvt(s),l=$zs(),[o,c]=S.useState(null),d=(n==null?void 0:n.modules)||[],h=new Set((i==null?void 0:i.filter(k=>k.completed).map(k=>k.module_id))||[]),m=h.size,p=d.length>0?Math.round(m/d.length*100):0;S.useEffect(()=>{if(d.length>0&&!o){const k=d.find(T=>!h.has(T.id));c((k==null?void 0:k.id)||d[0].id)}},[d,o,h]);const x=d.find(k=>k.id===o),y=d.findIndex(k=>k.id===o),_=(k,T)=>{if(!(n!=null&&n.is_sequential)||T===0)return!1;for(let E=0;E{if(!(!x||!r||!s))try{await l.mutateAsync({courseId:s,moduleId:x.id,userId:r.id}),he.success("Module completed! 🎉"),y{const T=k.match(/(?:youtube\.com\/(?:watch\?v=|embed\/)|youtu\.be\/)([a-zA-Z0-9_-]{11})/);if(T)return`https://www.youtube.com/embed/${T[1]}`;const E=k.match(/vimeo\.com\/(\d+)/);if(E)return`https://player.vimeo.com/video/${E[1]}`;const A=k.match(/(?:iframe\.mediadelivery\.net|video\.bunnycdn\.com)\/(?:play|embed)\/(\d+)\/([a-f0-9-]+)/);return A?`https://iframe.mediadelivery.net/embed/${A[1]}/${A[2]}?responsive=true`:k};return a?e.jsx(Ss,{title:"Loading...",children:e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):n?e.jsx(Ss,{title:n.title,children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(H,{variant:"ghost",size:"icon",onClick:()=>t("/levelup-u"),children:e.jsx(za,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h1",{className:"text-xl font-bold text-foreground truncate",children:n.title}),e.jsxs("div",{className:"flex items-center gap-3 text-xs text-muted-foreground mt-0.5",children:[e.jsxs("span",{children:[m,"/",d.length," completed"]}),e.jsxs("span",{children:[p,"%"]})]})]}),e.jsx("div",{className:"w-32",children:e.jsx(Mi,{value:p,className:"h-2"})})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-[320px_1fr] gap-4 items-start",children:[e.jsx(ke,{className:"lg:sticky lg:top-4",children:e.jsxs(Oe,{className:"p-0",children:[e.jsx("div",{className:"p-3 border-b",children:e.jsx("p",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"Modules"})}),e.jsx(Ci,{className:"max-h-[calc(100vh-280px)]",children:e.jsx("div",{className:"p-1",children:d.map((k,T)=>{const E=_(k,T),A=h.has(k.id),D=k.id===o;return e.jsxs("button",{disabled:E,onClick:()=>!E&&c(k.id),className:Ft("w-full flex items-center gap-3 p-3 rounded-lg text-left transition-all text-sm",D?"bg-primary/10 text-primary":"hover:bg-muted/50",E&&"opacity-50 cursor-not-allowed"),children:[e.jsx("div",{className:"shrink-0",children:E?e.jsx(Td,{className:"h-4 w-4 text-muted-foreground"}):A?e.jsx(ea,{className:"h-4 w-4 text-green-500"}):e.jsx(Gu,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("p",{className:Ft("font-medium truncate",D&&"text-primary"),children:[T+1,". ",k.title]}),k.duration_minutes&&e.jsxs("span",{className:"text-[11px] text-muted-foreground flex items-center gap-0.5 mt-0.5",children:[e.jsx(Pn,{className:"h-3 w-3"})," ",k.duration_minutes," min"]})]})]},k.id)})})})]})}),e.jsx("div",{className:"space-y-4",children:x?e.jsxs(e.Fragment,{children:[x.video_url&&e.jsx(ke,{className:"overflow-hidden",children:e.jsx("div",{className:"aspect-video bg-black",children:e.jsx("iframe",{src:j(x.video_url),className:"w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})})}),e.jsx(ke,{children:e.jsxs(Oe,{className:"p-6 space-y-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold",children:x.title}),x.description&&e.jsx("p",{className:"text-muted-foreground mt-1",children:x.description})]}),h.has(x.id)?e.jsxs(Xe,{className:"bg-green-500/15 text-green-600 border-green-500/30 shrink-0",children:[e.jsx(ea,{className:"h-3.5 w-3.5 mr-1"})," Completed"]}):e.jsxs(H,{size:"sm",onClick:b,disabled:l.isPending,children:[e.jsx(ea,{className:"h-4 w-4 mr-1"}),"Mark Complete"]})]}),x.text_content&&e.jsx("div",{className:"prose prose-sm max-w-none text-foreground border-t pt-4 whitespace-pre-wrap",children:x.text_content}),x.resources&&x.resources.length>0&&e.jsxs("div",{className:"border-t pt-4",children:[e.jsx("p",{className:"text-sm font-medium mb-2",children:"Resources"}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:x.resources.map(k=>e.jsxs("a",{href:k.url||k.file_url||"#",target:"_blank",rel:"noreferrer",className:"flex items-center gap-2 p-3 rounded-lg border hover:bg-muted/50 transition-colors text-sm",children:[k.resource_type==="pdf"?e.jsx(kn,{className:"h-4 w-4 text-red-500 shrink-0"}):k.resource_type==="template"?e.jsx(Vu,{className:"h-4 w-4 text-purple-500 shrink-0"}):e.jsx(ql,{className:"h-4 w-4 text-blue-500 shrink-0"}),e.jsx("span",{className:"flex-1 truncate",children:k.title}),e.jsx(gn,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"})]},k.id))})]}),e.jsxs("div",{className:"flex items-center justify-between border-t pt-4",children:[e.jsxs(H,{variant:"outline",size:"sm",disabled:y===0,onClick:()=>y>0&&c(d[y-1].id),children:[e.jsx(za,{className:"h-3.5 w-3.5 mr-1"})," Previous"]}),yc(d[y+1].id),children:["Next ",e.jsx($a,{className:"h-3.5 w-3.5 ml-1"})]}):p===100&&e.jsx(Xe,{className:"bg-green-500/15 text-green-600 border-green-500/30 text-sm px-3 py-1.5",children:"🎉 Course Complete!"})]})]})})]}):e.jsx(ke,{children:e.jsx(Oe,{className:"flex items-center justify-center py-16 text-muted-foreground",children:"Select a module to begin"})})})]})]})}):e.jsx(Ss,{title:"Not Found",children:e.jsxs("div",{className:"text-center py-20",children:[e.jsx("p",{className:"text-muted-foreground",children:"Course not found"}),e.jsxs(H,{variant:"outline",className:"mt-4",onClick:()=>t("/levelup-u"),children:[e.jsx(za,{className:"h-4 w-4 mr-2"})," Back"]})]})})}function Xzs({headline:s,subtext:t,primaryColor:r,accentColor:n,heroImageUrl:a,logoUrl:i,brokerageName:l}){return e.jsxs("section",{className:"relative min-h-screen flex items-center justify-center overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0",style:{background:`linear-gradient(160deg, ${n} 0%, ${r} 50%, ${n}ee 100%)`}}),a&&e.jsx("div",{className:"absolute inset-0 bg-cover bg-center opacity-20",style:{backgroundImage:`url(${a})`}}),e.jsx("div",{className:"absolute inset-0 opacity-[0.03]",style:{backgroundImage:"radial-gradient(circle at 25% 25%, white 1px, transparent 1px), radial-gradient(circle at 75% 75%, white 1px, transparent 1px)",backgroundSize:"60px 60px"}}),e.jsx("div",{className:"absolute bottom-0 left-0 right-0 h-32 bg-gradient-to-t from-white to-transparent"}),e.jsxs("div",{className:"relative z-10 text-center max-w-4xl mx-auto px-6 py-24",children:[i&&e.jsx(Ur.img,{src:i,alt:l,className:"h-14 md:h-20 w-auto mx-auto mb-10 drop-shadow-2xl",initial:{opacity:0,scale:.8},animate:{opacity:1,scale:1},transition:{duration:.8,delay:.2}}),e.jsx(Ur.div,{initial:{opacity:0,y:30},animate:{opacity:1,y:0},transition:{duration:.8,delay:.3},children:e.jsx("span",{className:"inline-block text-white/70 text-sm md:text-base font-medium tracking-[0.2em] uppercase mb-6",children:"Your Next Chapter Starts Here"})}),e.jsx(Ur.h1,{className:"text-4xl md:text-6xl lg:text-7xl font-bold text-white mb-8 leading-[1.1] tracking-tight",initial:{opacity:0,y:40},animate:{opacity:1,y:0},transition:{duration:.9,delay:.5},children:s}),e.jsx(Ur.p,{className:"text-lg md:text-xl text-white/80 mb-12 max-w-2xl mx-auto leading-relaxed font-light",initial:{opacity:0,y:30},animate:{opacity:1,y:0},transition:{duration:.8,delay:.7},children:t}),e.jsxs(Ur.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{duration:.7,delay:.9},className:"flex flex-col sm:flex-row items-center justify-center gap-4",children:[e.jsxs("a",{href:"#apply",className:"group inline-flex items-center gap-3 px-10 py-4 rounded-full text-lg font-semibold shadow-2xl transition-all duration-300 hover:scale-105 hover:shadow-3xl",style:{backgroundColor:"white",color:n},children:["Get In Touch",e.jsx(bi,{className:"h-5 w-5 transition-transform group-hover:translate-x-1"})]}),e.jsx("a",{href:"#benefits",className:"inline-flex items-center gap-2 px-8 py-4 rounded-full text-base font-medium text-white/90 border border-white/30 backdrop-blur-sm transition-all duration-300 hover:bg-white/10 hover:border-white/50",children:"Learn More"})]})]}),e.jsx(Ur.div,{className:"absolute bottom-8 left-1/2 -translate-x-1/2 z-10",animate:{y:[0,8,0]},transition:{duration:2,repeat:1/0,ease:"easeInOut"},children:e.jsx("div",{className:"w-6 h-10 border-2 border-white/40 rounded-full flex justify-center pt-2",children:e.jsx("div",{className:"w-1.5 h-3 bg-white/60 rounded-full"})})})]})}function P0({children:s,className:t="",delay:r=0,direction:n="up"}){const a=S.useRef(null),i=Lzt(a,{once:!0,margin:"-80px"}),l={hidden:{opacity:0,y:n==="up"?40:0,x:n==="left"?-40:n==="right"?40:0},visible:{opacity:1,y:0,x:0}};return e.jsx(Ur.div,{ref:a,initial:"hidden",animate:i?"visible":"hidden",variants:l,transition:{duration:.7,delay:r,ease:[.25,.46,.45,.94]},className:t,children:s})}function Qzs({benefits:s,accentColor:t,primaryColor:r}){return s.length===0?null:e.jsx("section",{id:"benefits",className:"py-24 md:py-32 px-6 bg-white",children:e.jsxs("div",{className:"max-w-6xl mx-auto",children:[e.jsx(P0,{children:e.jsxs("div",{className:"text-center mb-16",children:[e.jsx("span",{className:"text-sm font-semibold tracking-[0.15em] uppercase mb-4 block",style:{color:r},children:"Why Top Agents Choose Us"}),e.jsx("h2",{className:"text-3xl md:text-5xl font-bold mb-4 tracking-tight",style:{color:t},children:"Built For Your Success"}),e.jsx("div",{className:"w-16 h-1 mx-auto rounded-full mt-6",style:{backgroundColor:r}})]})}),e.jsx("div",{className:"grid md:grid-cols-2 lg:grid-cols-3 gap-6 md:gap-8",children:s.map((n,a)=>e.jsx(P0,{delay:a*.1,children:e.jsxs("div",{className:"group relative p-8 rounded-2xl border border-gray-100 bg-white hover:border-transparent hover:shadow-2xl transition-all duration-500 h-full",children:[e.jsx("div",{className:"absolute inset-0 rounded-2xl opacity-0 group-hover:opacity-100 transition-opacity duration-500",style:{background:`linear-gradient(135deg, ${r}08, ${t}05)`}}),e.jsxs("div",{className:"relative z-10",children:[e.jsx("div",{className:"w-14 h-14 rounded-xl flex items-center justify-center text-2xl mb-5 transition-transform duration-300 group-hover:scale-110",style:{backgroundColor:`${r}12`},children:n.icon}),e.jsx("h3",{className:"text-xl font-bold mb-3 tracking-tight",style:{color:t},children:n.title}),e.jsx("p",{className:"text-gray-500 leading-relaxed text-[15px]",children:n.description})]})]})},a))})]})})}function Jzs({images:s,primaryColor:t,accentColor:r}){const[n,a]=S.useState(null);return s.length===0?null:e.jsxs(e.Fragment,{children:[e.jsx("section",{className:"py-24 md:py-32 px-6 bg-gray-50",children:e.jsxs("div",{className:"max-w-6xl mx-auto",children:[e.jsx(P0,{children:e.jsxs("div",{className:"text-center mb-16",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 px-4 py-2 rounded-full bg-white border border-gray-200 mb-6",children:[e.jsx(Ar,{className:"h-4 w-4",style:{color:t}}),e.jsx("span",{className:"text-sm font-medium text-gray-600",children:"Life at Our Brokerage"})]}),e.jsx("h2",{className:"text-3xl md:text-5xl font-bold tracking-tight",style:{color:r},children:"Our Team & Culture"})]})}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-3 md:gap-4",children:s.map((i,l)=>e.jsx(P0,{delay:l*.08,children:e.jsxs("button",{onClick:()=>a(l),className:"relative w-full aspect-[4/3] overflow-hidden rounded-xl group cursor-pointer",children:[e.jsx("img",{src:i,alt:`Team ${l+1}`,className:"w-full h-full object-cover transition-transform duration-700 group-hover:scale-110"}),e.jsx("div",{className:"absolute inset-0 bg-black/0 group-hover:bg-black/20 transition-all duration-500"})]})},l))})]})}),n!==null&&e.jsxs("div",{className:"fixed inset-0 z-50 bg-black/90 flex items-center justify-center p-4 cursor-pointer",onClick:()=>a(null),children:[e.jsx("button",{onClick:()=>a(null),className:"absolute top-6 right-6 text-white/80 hover:text-white transition-colors",children:e.jsx(Rr,{className:"h-8 w-8"})}),e.jsx("img",{src:s[n],alt:"Gallery",className:"max-w-full max-h-[85vh] object-contain rounded-lg",onClick:i=>i.stopPropagation()})]})]})}function e$s({testimonials:s,primaryColor:t,accentColor:r}){return s.length===0?null:e.jsx("section",{className:"py-24 md:py-32 px-6 bg-white",children:e.jsxs("div",{className:"max-w-6xl mx-auto",children:[e.jsx(P0,{children:e.jsxs("div",{className:"text-center mb-16",children:[e.jsx("span",{className:"text-sm font-semibold tracking-[0.15em] uppercase mb-4 block",style:{color:t},children:"Agent Testimonials"}),e.jsx("h2",{className:"text-3xl md:text-5xl font-bold tracking-tight",style:{color:r},children:"Hear From Our Agents"}),e.jsx("div",{className:"w-16 h-1 mx-auto rounded-full mt-6",style:{backgroundColor:t}})]})}),e.jsx("div",{className:"grid md:grid-cols-2 gap-8",children:s.map((n,a)=>{var i;return e.jsx(P0,{delay:a*.15,direction:a%2===0?"left":"right",children:e.jsxs("div",{className:"relative p-8 md:p-10 rounded-2xl bg-gray-50 border border-gray-100 h-full",children:[e.jsx(Kk,{className:"h-8 w-8 mb-5 opacity-20",style:{color:t}}),e.jsxs("p",{className:"text-gray-700 text-lg leading-relaxed mb-8 font-light italic",children:['"',n.quote,'"']}),e.jsxs("div",{className:"flex items-center gap-4",children:[n.photo_url?e.jsx("img",{src:n.photo_url,alt:n.name,className:"h-12 w-12 rounded-full object-cover ring-2 ring-white shadow-md"}):e.jsx("div",{className:"h-12 w-12 rounded-full flex items-center justify-center text-white text-base font-bold shadow-md",style:{background:`linear-gradient(135deg, ${t}, ${r})`},children:((i=n.name)==null?void 0:i[0])||"?"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-base",style:{color:r},children:n.name}),n.role&&e.jsx("p",{className:"text-sm text-gray-500",children:n.role})]})]})]})},a)})})]})})}function t$s({form:s,setForm:t,onSubmit:r,isPending:n,primaryColor:a,accentColor:i}){return e.jsxs("section",{id:"apply",className:"py-24 md:py-32 px-6 relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 top-0 h-1/2",style:{background:`linear-gradient(160deg, ${i}, ${a})`}}),e.jsx("div",{className:"absolute inset-0 top-1/2 bg-gray-50"}),e.jsxs("div",{className:"relative z-10 max-w-xl mx-auto",children:[e.jsx(P0,{children:e.jsxs("div",{className:"text-center mb-10",children:[e.jsx("h2",{className:"text-3xl md:text-4xl font-bold text-white mb-3 tracking-tight",children:"Want to Learn More?"}),e.jsx("p",{className:"text-white/70 text-lg font-light",children:"Drop your info below and we'll share more about what makes us different."})]})}),e.jsx(P0,{delay:.2,children:e.jsxs("form",{onSubmit:l=>{l.preventDefault(),r()},className:"bg-white rounded-3xl shadow-2xl p-8 md:p-10 space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{className:"text-gray-700 text-sm font-medium",children:"First Name *"}),e.jsx(Se,{required:!0,value:s.first_name,onChange:l=>t(o=>({...o,first_name:l.target.value})),className:"h-11 rounded-lg border-gray-200 focus:border-gray-400 transition-colors",placeholder:"John"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{className:"text-gray-700 text-sm font-medium",children:"Last Name"}),e.jsx(Se,{value:s.last_name,onChange:l=>t(o=>({...o,last_name:l.target.value})),className:"h-11 rounded-lg border-gray-200 focus:border-gray-400 transition-colors",placeholder:"Smith"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{className:"text-gray-700 text-sm font-medium",children:"Email *"}),e.jsx(Se,{type:"email",required:!0,value:s.email,onChange:l=>t(o=>({...o,email:l.target.value})),className:"h-11 rounded-lg border-gray-200 focus:border-gray-400 transition-colors",placeholder:"john@email.com"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{className:"text-gray-700 text-sm font-medium",children:"Phone"}),e.jsx(Se,{value:s.phone,onChange:l=>t(o=>({...o,phone:l.target.value})),className:"h-11 rounded-lg border-gray-200 focus:border-gray-400 transition-colors",placeholder:"(555) 123-4567"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{className:"text-gray-700 text-sm font-medium",children:"Current Brokerage"}),e.jsx(Se,{value:s.current_brokerage,onChange:l=>t(o=>({...o,current_brokerage:l.target.value})),className:"h-11 rounded-lg border-gray-200 focus:border-gray-400 transition-colors",placeholder:"Your current brokerage name"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{className:"text-gray-700 text-sm font-medium",children:"License #"}),e.jsx(Se,{value:s.license_number,onChange:l=>t(o=>({...o,license_number:l.target.value})),className:"h-11 rounded-lg border-gray-200 focus:border-gray-400 transition-colors"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{className:"text-gray-700 text-sm font-medium",children:"Years Experience"}),e.jsx(Se,{type:"number",min:"0",value:s.experience_years,onChange:l=>t(o=>({...o,experience_years:l.target.value})),className:"h-11 rounded-lg border-gray-200 focus:border-gray-400 transition-colors"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{className:"text-gray-700 text-sm font-medium",children:"Annual Production"}),e.jsx(Se,{value:s.annual_production,onChange:l=>t(o=>({...o,annual_production:l.target.value})),className:"h-11 rounded-lg border-gray-200 focus:border-gray-400 transition-colors",placeholder:"e.g. $5M, 20 transactions"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{className:"text-gray-700 text-sm font-medium",children:"Why are you interested?"}),e.jsx(vr,{value:s.why_interested,onChange:l=>t(o=>({...o,why_interested:l.target.value})),rows:3,className:"rounded-lg border-gray-200 focus:border-gray-400 transition-colors resize-none",placeholder:"Tell us about your goals and what you're looking for..."})]}),e.jsx(H,{type:"submit",className:"w-full h-13 text-base font-semibold rounded-xl group transition-all duration-300 hover:shadow-lg",style:{background:`linear-gradient(135deg, ${a}, ${i})`},disabled:n,children:n?e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-4 w-4 animate-spin rounded-full border-2 border-white border-t-transparent"}),"Submitting..."]}):e.jsxs("span",{className:"flex items-center gap-2",children:["Send My Info",e.jsx(bi,{className:"h-4 w-4 transition-transform group-hover:translate-x-1"})]})}),e.jsxs("div",{className:"flex items-center justify-center gap-2 text-xs text-gray-400 pt-1",children:[e.jsx(Fh,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Your information is confidential and will not be shared."})]})]})})]})]})}function s$s({form:s,setForm:t,onSubmit:r,isPending:n,primaryColor:a,accentColor:i,showConfidentialBadges:l=!0}){const[o,c]=S.useState(1),[d,h]=S.useState(""),m=3,p=!!s.first_name&&!!s.email,x=y=>{h(y),t(_=>({..._,why_interested:y})),setTimeout(()=>c(2),200)};return e.jsxs("section",{id:"apply",className:"py-24 md:py-32 px-6 relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 top-0 h-1/2",style:{background:`linear-gradient(160deg, ${i}, ${a})`}}),e.jsx("div",{className:"absolute inset-0 top-1/2 bg-gray-50"}),e.jsxs("div",{className:"relative z-10 max-w-xl mx-auto",children:[e.jsx(P0,{children:e.jsxs("div",{className:"text-center mb-8",children:[l&&e.jsxs("div",{className:"inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-[11px] font-semibold bg-white/15 text-white backdrop-blur mb-4",children:[e.jsx(Td,{className:"h-2.5 w-2.5"})," 100% Confidential"]}),e.jsx("h2",{className:"text-3xl md:text-4xl font-bold text-white mb-3 tracking-tight",children:"Start a Confidential Conversation"}),e.jsx("p",{className:"text-white/70 text-lg font-light",children:"No high-pressure sales calls. Ever."})]})}),e.jsx(P0,{delay:.15,children:e.jsxs("div",{className:"bg-white rounded-3xl shadow-2xl p-8 md:p-10",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-7",children:[[1,2,3].map(y=>e.jsx("div",{className:"h-1 flex-1 rounded-full transition-colors duration-500",style:{backgroundColor:y<=o?a:"#e5e7eb"}},y)),e.jsxs("span",{className:"text-xs text-gray-400 ml-2",children:[o,"/",m]})]}),e.jsxs(J5e,{mode:"wait",children:[o===1&&e.jsxs(Ur.div,{initial:{opacity:0,x:20},animate:{opacity:1,x:0},exit:{opacity:0,x:-20},transition:{duration:.25},className:"space-y-3",children:[e.jsx("h3",{className:"text-lg font-semibold mb-1",style:{color:i},children:"What's most important to you?"}),e.jsx("p",{className:"text-sm text-gray-500 mb-5",children:"Pick the one that resonates most. We'll tailor the conversation."}),[{val:"Better commission split / cap",label:"Better Splits & Caps",icon:"💰"},{val:"Better technology and tools",label:"Better Tech & Tools",icon:"🛠️"},{val:"Better training and mentorship",label:"Better Training",icon:"📚"},{val:"Better culture and team",label:"Better Culture",icon:"🤝"},{val:"Just exploring options confidentially",label:"Just Exploring",icon:"🔍"}].map(y=>e.jsxs("button",{type:"button",onClick:()=>x(y.val),className:"w-full flex items-center gap-3 p-4 rounded-xl border-2 border-gray-100 hover:border-gray-300 transition-all text-left group",children:[e.jsx("span",{className:"text-2xl",children:y.icon}),e.jsx("span",{className:"font-medium text-gray-700 group-hover:text-gray-900 flex-1",children:y.label}),e.jsx(bi,{className:"h-4 w-4 text-gray-300 group-hover:text-gray-500 group-hover:translate-x-1 transition-all"})]},y.val))]},"step1"),o===2&&e.jsxs(Ur.div,{initial:{opacity:0,x:20},animate:{opacity:1,x:0},exit:{opacity:0,x:-20},transition:{duration:.25},className:"space-y-4",children:[e.jsx("h3",{className:"text-lg font-semibold mb-1",style:{color:i},children:"How can we reach you?"}),e.jsx("p",{className:"text-sm text-gray-500 mb-3",children:"We'll text first, on your schedule."}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{className:"text-gray-700 text-sm font-medium",children:"First Name *"}),e.jsx(Se,{required:!0,value:s.first_name,onChange:y=>t(_=>({..._,first_name:y.target.value})),className:"h-11",placeholder:"John"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{className:"text-gray-700 text-sm font-medium",children:"Last Name"}),e.jsx(Se,{value:s.last_name,onChange:y=>t(_=>({..._,last_name:y.target.value})),className:"h-11",placeholder:"Smith"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{className:"text-gray-700 text-sm font-medium",children:"Email *"}),e.jsx(Se,{type:"email",required:!0,value:s.email,onChange:y=>t(_=>({..._,email:y.target.value})),className:"h-11",placeholder:"john@email.com"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{className:"text-gray-700 text-sm font-medium",children:"Phone (preferred)"}),e.jsx(Se,{value:s.phone,onChange:y=>t(_=>({..._,phone:y.target.value})),className:"h-11",placeholder:"(555) 123-4567"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsxs(H,{type:"button",variant:"ghost",onClick:()=>c(1),className:"h-11",children:[e.jsx(za,{className:"h-4 w-4 mr-1"})," Back"]}),e.jsxs(H,{type:"button",disabled:!p,onClick:()=>c(3),className:"flex-1 h-11 text-white font-semibold",style:{background:`linear-gradient(135deg, ${a}, ${i})`},children:["Continue ",e.jsx(bi,{className:"h-4 w-4 ml-1"})]})]})]},"step2"),o===3&&e.jsxs(Ur.div,{initial:{opacity:0,x:20},animate:{opacity:1,x:0},exit:{opacity:0,x:-20},transition:{duration:.25},className:"space-y-4",children:[e.jsx("h3",{className:"text-lg font-semibold mb-1",style:{color:i},children:"A few quick details (optional)"}),e.jsx("p",{className:"text-sm text-gray-500 mb-3",children:"Helps us prepare a more personalized comp comparison."}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{className:"text-gray-700 text-sm font-medium",children:"Current Brokerage"}),e.jsx(Se,{value:s.current_brokerage,onChange:y=>t(_=>({..._,current_brokerage:y.target.value})),className:"h-11",placeholder:"(stays private)"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{className:"text-gray-700 text-sm font-medium",children:"Years Experience"}),e.jsx(Se,{type:"number",min:"0",value:s.experience_years,onChange:y=>t(_=>({..._,experience_years:y.target.value})),className:"h-11"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{className:"text-gray-700 text-sm font-medium",children:"Annual Production"}),e.jsx(Se,{value:s.annual_production,onChange:y=>t(_=>({..._,annual_production:y.target.value})),className:"h-11",placeholder:"e.g. $5M"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{className:"text-gray-700 text-sm font-medium",children:"Anything else?"}),e.jsx(vr,{value:s.why_interested,onChange:y=>t(_=>({..._,why_interested:y.target.value})),rows:2,className:"resize-none",placeholder:"Optional message..."})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsxs(H,{type:"button",variant:"ghost",onClick:()=>c(2),className:"h-11",children:[e.jsx(za,{className:"h-4 w-4 mr-1"})," Back"]}),e.jsx(H,{type:"button",onClick:r,disabled:n,className:"flex-1 h-12 text-white font-semibold rounded-xl",style:{background:`linear-gradient(135deg, ${a}, ${i})`},children:n?e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-4 w-4 animate-spin rounded-full border-2 border-white border-t-transparent"}),"Sending..."]}):e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(va,{className:"h-4 w-4"})," Start the Conversation"]})})]})]},"step3")]}),l&&e.jsxs("div",{className:"mt-6 pt-5 border-t border-gray-100 grid grid-cols-3 gap-2 text-[10px] text-gray-400",children:[e.jsxs("div",{className:"flex items-center gap-1 justify-center",children:[e.jsx(Fh,{className:"h-3 w-3"})," Confidential"]}),e.jsxs("div",{className:"flex items-center gap-1 justify-center",children:[e.jsx(Gi,{className:"h-3 w-3"})," Text first"]}),e.jsxs("div",{className:"flex items-center gap-1 justify-center",children:[e.jsx(Yn,{className:"h-3 w-3"})," No spam"]})]})]})})]})]})}function r$s({config:s,primaryColor:t,accentColor:r,brokerageId:n,brokerageName:a}){const{toast:i}=li(),[l,o]=S.useState("250000"),[c,d]=S.useState("12"),[h,m]=S.useState("70"),[p,x]=S.useState("150"),[y,_]=S.useState(""),[b,j]=S.useState(!1),[k,T]=S.useState(!1),E=s.commission_split_pct??80,A=s.cap_amount??16e3,D=s.post_cap_split_pct??100,R=s.monthly_fee??99,z=s.transaction_fee??0,O=S.useMemo(()=>{const Z=parseFloat(l)||0,J=Math.max(0,parseInt(c,10)||0),K=parseFloat(h)||0,re=parseFloat(p)||0,ie=Z*(K/100)-re*12-z*J,ce=1-E/100,ne=ce>0?A/ce:Z,le=Math.min(Z,ne),be=Math.max(0,Z-ne),fe=le*ce+be*(1-D/100),je=Z-fe-R*12-z*J,ve=je-ie;return{currentNet:ie,newNet:je,diff:ve}},[l,c,h,p,E,A,D,R,z]),$=Z=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(Z),ee=async Z=>{if(Z.preventDefault(),!!y){T(!0);try{const{error:J}=await V.from("recruit_lead_magnet_downloads").insert({brokerage_id:n,email:y,source:"calculator"});if(J)throw J;const{error:K}=await V.functions.invoke("send-calculator-breakdown",{body:{brokerage_id:n,brokerage_name:a,email:y,inputs:{gci:parseFloat(l)||0,transactions:parseInt(c,10)||0,current_split_pct:parseFloat(h)||0,current_monthly_fee:parseFloat(p)||0},plan:{commission_split_pct:E,cap_amount:A,post_cap_split_pct:D,monthly_fee:R,transaction_fee:z},result:O,primary_color:t,accent_color:r}});K&&console.error("Breakdown email failed:",K),j(!0),i({title:"Sent!",description:"Check your email for the full breakdown."})}catch(J){i({title:"Error",description:J.message,variant:"destructive"})}finally{T(!1)}}};return e.jsx("section",{className:"py-20 md:py-28 px-6 bg-gray-50",children:e.jsxs("div",{className:"max-w-5xl mx-auto",children:[e.jsx(P0,{children:e.jsxs("div",{className:"text-center mb-10",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 px-4 py-1.5 rounded-full text-xs font-semibold mb-4",style:{backgroundColor:`${t}15`,color:r},children:[e.jsx(Td,{className:"h-3 w-3"})," 100% Confidential — No Signup Required"]}),e.jsx("h2",{className:"text-3xl md:text-4xl font-bold tracking-tight mb-3",style:{color:r},children:s.headline||"See What You Could Earn With Us"}),e.jsx("p",{className:"text-gray-500 text-lg font-light max-w-xl mx-auto",children:s.subtext||"Confidential 60-second calculator — no signup required."})]})}),e.jsx(P0,{delay:.15,children:e.jsxs("div",{className:"bg-white rounded-3xl shadow-xl overflow-hidden grid md:grid-cols-2",children:[e.jsxs("div",{className:"p-8 md:p-10 border-r border-gray-100",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-6",children:[e.jsx(II,{className:"h-5 w-5",style:{color:t}}),e.jsx("h3",{className:"font-semibold",style:{color:r},children:"Your Numbers"})]}),e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{children:[e.jsx(ue,{className:"text-gray-600 text-sm",children:"Your GCI Last 12 Months"}),e.jsxs("div",{className:"relative mt-1.5",children:[e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 text-sm",children:"$"}),e.jsx(Se,{type:"number",value:l,onChange:Z=>o(Z.target.value),className:"pl-7 h-11 text-base",placeholder:"250,000"})]})]}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-gray-600 text-sm",children:"Transactions per Year"}),e.jsx(Se,{type:"number",min:"0",value:c,onChange:Z=>d(Z.target.value),className:"mt-1.5 h-11 text-base",placeholder:"12"})]}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-gray-600 text-sm",children:"Your Current Commission Split (%)"}),e.jsx(Se,{type:"number",value:h,onChange:Z=>m(Z.target.value),className:"mt-1.5 h-11 text-base",placeholder:"70"})]}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-gray-600 text-sm",children:"Your Current Monthly Fees"}),e.jsxs("div",{className:"relative mt-1.5",children:[e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 text-sm",children:"$"}),e.jsx(Se,{type:"number",value:p,onChange:Z=>x(Z.target.value),className:"pl-7 h-11 text-base",placeholder:"150"})]})]})]})]}),e.jsxs("div",{className:"p-8 md:p-10 text-white",style:{background:`linear-gradient(160deg, ${r}, ${t})`},children:[e.jsxs("div",{className:"flex items-center gap-2 mb-6",children:[e.jsx(al,{className:"h-5 w-5"}),e.jsxs("h3",{className:"font-semibold",children:["Your Earnings at ",a]})]}),e.jsxs("div",{className:"space-y-4 mb-6",children:[e.jsxs("div",{className:"flex items-baseline justify-between border-b border-white/20 pb-3",children:[e.jsx("span",{className:"text-white/70 text-sm",children:"Current take-home"}),e.jsx("span",{className:"text-xl font-semibold",children:$(O.currentNet)})]}),e.jsxs("div",{className:"flex items-baseline justify-between border-b border-white/20 pb-3",children:[e.jsx("span",{className:"text-white/70 text-sm",children:"With us"}),e.jsx("span",{className:"text-xl font-semibold",children:$(O.newNet)})]})]}),e.jsxs(Ur.div,{initial:{scale:.95,opacity:0},animate:{scale:1,opacity:1},className:"bg-white/10 backdrop-blur rounded-2xl p-5 text-center",children:[e.jsx("p",{className:"text-white/80 text-xs uppercase tracking-wide mb-1",children:O.diff>=0?"You could earn":"Difference"}),e.jsxs("p",{className:"text-4xl font-bold mb-1",children:[O.diff>=0?"+":"",$(O.diff)]}),e.jsx("p",{className:"text-white/70 text-xs",children:O.diff>=0?"more per year":"per year"})]},O.diff),s.show_email_capture&&!b&&e.jsxs("form",{onSubmit:ee,className:"mt-6 space-y-2",children:[e.jsx("p",{className:"text-white/80 text-xs",children:s.email_capture_label||"Want the full breakdown? Enter your email."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Se,{type:"email",required:!0,value:y,onChange:Z=>_(Z.target.value),placeholder:"you@email.com",className:"bg-white/95 border-0 text-gray-900 h-10 text-sm"}),e.jsx(H,{type:"submit",disabled:k,className:"h-10 bg-white text-gray-900 hover:bg-white/90 text-sm font-semibold",children:"Send"})]})]}),b&&e.jsxs("div",{className:"mt-6 flex items-center gap-2 text-sm text-white/90 bg-white/10 rounded-lg p-3",children:[e.jsx(va,{className:"h-4 w-4"})," Check your inbox shortly."]})]})]})}),e.jsx("p",{className:"text-center text-xs text-gray-400 mt-4",children:"Estimates only. Actual results vary by individual production and plan terms."})]})})}function n$s({config:s,primaryColor:t,accentColor:r,brokerageId:n}){const{toast:a}=li(),[i,l]=S.useState(""),[o,c]=S.useState(""),[d,h]=S.useState(!1),[m,p]=S.useState(!1),x=async y=>{y.preventDefault(),p(!0);try{const{error:_}=await V.from("recruit_lead_magnet_downloads").insert({brokerage_id:n,email:i,first_name:o||null,source:"lead_magnet",user_agent:navigator.userAgent,referrer:document.referrer||null});if(_)throw _;h(!0),s.pdf_url&&window.open(s.pdf_url,"_blank","noopener,noreferrer")}catch(_){a({title:"Error",description:_.message,variant:"destructive"})}finally{p(!1)}};return e.jsx("section",{className:"py-20 md:py-24 px-6 bg-white",children:e.jsx("div",{className:"max-w-3xl mx-auto",children:e.jsx(P0,{children:e.jsx("div",{className:"rounded-3xl p-8 md:p-12 shadow-xl border border-gray-100",style:{background:`linear-gradient(135deg, ${t}08, ${r}08)`},children:e.jsxs("div",{className:"flex flex-col md:flex-row items-center gap-8",children:[e.jsx("div",{className:"shrink-0 h-24 w-24 rounded-2xl flex items-center justify-center shadow-lg",style:{background:`linear-gradient(135deg, ${t}, ${r})`},children:e.jsx(yE,{className:"h-12 w-12 text-white"})}),e.jsxs("div",{className:"flex-1 text-center md:text-left",children:[e.jsxs("div",{className:"inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-[11px] font-semibold mb-3",style:{backgroundColor:`${t}15`,color:r},children:[e.jsx(Td,{className:"h-2.5 w-2.5"})," No call required — instant download"]}),e.jsx("h3",{className:"text-2xl md:text-3xl font-bold tracking-tight mb-2",style:{color:r},children:s.title||"Get the Full Comp Plan PDF"}),e.jsx("p",{className:"text-gray-500 leading-relaxed mb-5",children:s.description||"See exactly how splits, caps, and fees work — no call required."}),d?e.jsxs("div",{className:"flex items-center gap-2 p-4 rounded-xl bg-green-50 border border-green-200 text-green-800 text-sm",children:[e.jsx(va,{className:"h-5 w-5 shrink-0"}),e.jsxs("span",{children:["Sent! ",s.pdf_url?"Your download should open in a new tab.":"Check your email shortly."]})]}):e.jsxs("form",{onSubmit:x,className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsx(Se,{value:o,onChange:y=>c(y.target.value),placeholder:"First name (optional)",className:"h-11"}),e.jsx(Se,{type:"email",required:!0,value:i,onChange:y=>l(y.target.value),placeholder:"your@email.com",className:"h-11"})]}),e.jsxs(H,{type:"submit",disabled:m,className:"w-full sm:w-auto h-12 px-6 text-white font-semibold",style:{background:`linear-gradient(135deg, ${t}, ${r})`},children:[e.jsx(yE,{className:"h-4 w-4 mr-2"}),m?"Sending...":s.button_text||"Email Me the PDF"]})]})]})]})})})})})}function a$s(){const{slug:s}=Po(),{toast:t}=li(),[r,n]=S.useState(!1),[a,i]=S.useState({first_name:"",last_name:"",email:"",phone:"",current_brokerage:"",experience_years:"",annual_production:"",license_number:"",why_interested:""});S.useEffect(()=>{document.body.classList.add("recruit-landing-page");const O=()=>{['[id*="lc_text_widget"]','[class*="lc-text-widget"]','[class*="lc_text_widget"]','[id*="chat-widget"]','[class*="chat-widget"]','iframe[src*="leadconnector"]','iframe[src*="msgsndr"]',"[data-chat-widget]",'div[id^="hubspot"]',".widget-visible"].forEach(J=>document.querySelectorAll(J).forEach(K=>K.style.display="none"))};O();const $=[setTimeout(O,500),setTimeout(O,1500),setTimeout(O,3e3)],ee=new MutationObserver(O);return ee.observe(document.body,{childList:!0,subtree:!0}),()=>{document.body.classList.remove("recruit-landing-page"),$.forEach(clearTimeout),ee.disconnect()}},[]);const{data:l,isLoading:o,error:c}=yt({queryKey:["recruit-form-brokerage",s],queryFn:async()=>{const{data:O,error:$}=await V.from("brokerages").select("id, name, recruit_form_enabled").eq("recruit_form_slug",s).single();if($)throw $;return O},enabled:!!s}),{data:d}=yt({queryKey:["recruit-landing-public",l==null?void 0:l.id],queryFn:async()=>{const{data:O,error:$}=await V.from("recruit_landing_page_settings").select("*").eq("brokerage_id",l.id).single();if($&&$.code!=="PGRST116")throw $;return O},enabled:!!(l!=null&&l.id)}),h=Pt({mutationFn:async()=>{const O={brokerage_id:l.id,first_name:a.first_name,last_name:a.last_name||null,email:a.email,phone:a.phone||null,current_brokerage:a.current_brokerage||null,experience_years:a.experience_years?parseInt(a.experience_years):null,annual_production:a.annual_production||null,license_number:a.license_number||null,why_interested:a.why_interested||null},{error:$}=await V.from("recruit_interest_submissions").insert(O);if($)throw $;V.functions.invoke("recruit-lead-notify",{body:{lead:O,brokerage_id:l.id}}).catch(ee=>console.error("Lead notification error:",ee))},onSuccess:()=>n(!0),onError:O=>t({title:"Error",description:O.message,variant:"destructive"})});if(o)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-white",children:e.jsxs("div",{className:"flex flex-col items-center gap-3",children:[e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-3 border-gray-200 border-t-gray-800"}),e.jsx("span",{className:"text-sm text-gray-400 tracking-wide",children:"Loading..."})]})});if(c||!l||!l.recruit_form_enabled)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-white",children:e.jsxs("div",{className:"max-w-md w-full mx-4 text-center",children:[e.jsx(Xa,{className:"h-10 w-10 mx-auto text-gray-300 mb-4"}),e.jsx("p",{className:"text-gray-400 text-lg",children:"This page is not available."})]})});const m=d,p=(m==null?void 0:m.primary_color)||"#406E71",x=(m==null?void 0:m.accent_color)||"#2a4c64",y=(m==null?void 0:m.benefits)||[],_=(m==null?void 0:m.testimonials)||[],b=(m==null?void 0:m.gallery_images)||[],j=(m==null?void 0:m.hero_headline)||`Join ${l.name}`,k=(m==null?void 0:m.hero_subtext)||"Take your real estate career to the next level with a brokerage that invests in your growth.",T=(m==null?void 0:m.calculator_enabled)===!0,E=(m==null?void 0:m.calculator_config)||{},A=(m==null?void 0:m.lead_magnet_enabled)===!0,D=(m==null?void 0:m.lead_magnet_config)||{},R=(m==null?void 0:m.form_style)||"classic",z=(m==null?void 0:m.confidential_messaging)!==!1;return r?e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-white",children:e.jsxs(Ur.div,{initial:{opacity:0,scale:.9},animate:{opacity:1,scale:1},transition:{duration:.6},className:"max-w-md w-full mx-4 text-center",children:[e.jsx("div",{className:"h-20 w-20 rounded-full flex items-center justify-center mx-auto mb-6 shadow-lg",style:{background:`linear-gradient(135deg, ${p}, ${x})`},children:e.jsx(va,{className:"h-10 w-10 text-white"})}),e.jsx("h2",{className:"text-3xl font-bold mb-3 tracking-tight",style:{color:x},children:"Thank You!"}),e.jsxs("p",{className:"text-gray-500 text-lg leading-relaxed mb-8",children:["Your interest in joining ",e.jsx("span",{className:"font-semibold",style:{color:x},children:l.name})," has been received. A member of our recruitment team will be in touch shortly."]}),e.jsx("div",{className:"w-16 h-1 mx-auto rounded-full",style:{backgroundColor:p}})]})}):e.jsxs("div",{className:"min-h-screen bg-white",style:{"--recruit-primary":p,"--recruit-accent":x},children:[e.jsx("nav",{className:"fixed top-0 left-0 right-0 z-40 bg-white/80 backdrop-blur-lg border-b border-gray-100/50",children:e.jsxs("div",{className:"max-w-6xl mx-auto px-6 h-14 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[(m==null?void 0:m.logo_url)&&e.jsx("img",{src:m.logo_url,alt:l.name,className:"h-8 w-auto"}),e.jsx("span",{className:"font-semibold text-sm tracking-tight",style:{color:x},children:l.name})]}),e.jsxs("a",{href:"#apply",className:"inline-flex items-center gap-2 px-5 py-2 rounded-full text-sm font-semibold text-white transition-all duration-300 hover:shadow-md hover:scale-105",style:{background:`linear-gradient(135deg, ${p}, ${x})`},children:["Apply Now ",e.jsx(bi,{className:"h-3.5 w-3.5"})]})]})}),e.jsx(Xzs,{headline:j,subtext:k,primaryColor:p,accentColor:x,heroImageUrl:m==null?void 0:m.hero_image_url,logoUrl:m==null?void 0:m.logo_url,brokerageName:l.name}),e.jsx(Qzs,{benefits:y,accentColor:x,primaryColor:p}),e.jsx(Jzs,{images:b,primaryColor:p,accentColor:x}),e.jsx(e$s,{testimonials:_,primaryColor:p,accentColor:x}),T&&e.jsx(r$s,{config:E,primaryColor:p,accentColor:x,brokerageId:l.id,brokerageName:l.name}),A&&e.jsx(n$s,{config:D,primaryColor:p,accentColor:x,brokerageId:l.id}),R==="multi_step"?e.jsx(s$s,{form:a,setForm:i,onSubmit:()=>h.mutate(),isPending:h.isPending,primaryColor:p,accentColor:x,showConfidentialBadges:z}):e.jsx(t$s,{form:a,setForm:i,onSubmit:()=>h.mutate(),isPending:h.isPending,primaryColor:p,accentColor:x}),e.jsx("footer",{className:"py-10 text-center bg-white border-t border-gray-100",children:e.jsxs("p",{className:"text-sm text-gray-400",children:["© ",new Date().getFullYear()," ",l.name,". All rights reserved."]})})]})}function i$s(s){const t=s.match(/(?:iframe\.mediadelivery\.net\/(?:embed|play)\/|video\.bunnycdn\.com\/play\/)(\d+)\/([a-f0-9-]+)/i);return t?`https://iframe.mediadelivery.net/embed/${t[1]}/${t[2]}?autoplay=false&responsive=true`:s}function o$s(){var p,x,y,_;const{shareToken:s}=Po(),t=S.useRef(!1),{data:r,isLoading:n,error:a}=yt({queryKey:["public-recruit-video",s],queryFn:async()=>{var A;if(!s)throw new Error("No token");const{data:b,error:j}=await V.from("recruit_videos").select(` *, prospect:recruit_prospects(first_name, last_name), video:agent_videos(id, title, playback_url, thumbnail_url, duration_seconds, owner_user_id) `).eq("share_token",s).single();if(j)throw j;const{data:k}=await V.from("profiles").select("name, avatar_url, title, recruit_cta_url").eq("id",(A=b.video)==null?void 0:A.owner_user_id).single(),{data:T}=await V.from("brokerages").select("name").eq("id",b.brokerage_id).single(),{data:E}=await V.from("recruit_landing_page_settings").select("logo_url, primary_color, accent_color, hero_headline").eq("brokerage_id",b.brokerage_id).maybeSingle();return{rv:b,profile:k,brokerage:T,settings:E}},enabled:!!s});if(S.useEffect(()=>{var b;!((b=r==null?void 0:r.rv)!=null&&b.id)||t.current||(t.current=!0,V.rpc("log_recruit_video_view",{p_recruit_video_id:r.rv.id,p_user_agent:navigator.userAgent,p_referrer:document.referrer||null}).then(()=>{}))},[(p=r==null?void 0:r.rv)==null?void 0:p.id]),n)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})});if(a||!r)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:e.jsx("p",{className:"text-muted-foreground",children:"This video is no longer available."})});const{rv:i,profile:l,brokerage:o,settings:c}=r,d=(c==null?void 0:c.primary_color)||"#3b82f6",h=((x=i.prospect)==null?void 0:x.first_name)||"there",m=(y=i.video)!=null&&y.playback_url?i$s(i.video.playback_url):null;return e.jsxs(e.Fragment,{children:[e.jsx(el,{children:e.jsx("title",{children:o!=null&&o.name?`${o.name} — A Message For You`:"Personal Video Message"})}),e.jsxs("div",{className:"min-h-screen bg-gradient-to-br from-slate-50 to-slate-100",children:[e.jsx("header",{className:"border-b bg-white/80 backdrop-blur-sm",children:e.jsxs("div",{className:"max-w-3xl mx-auto px-4 py-4 flex items-center gap-3",children:[(c==null?void 0:c.logo_url)&&e.jsx("img",{src:c.logo_url,alt:"",className:"h-8 object-contain"}),e.jsx("span",{className:"font-semibold text-sm",style:{color:d},children:(o==null?void 0:o.name)||"Recruiting"})]})}),e.jsxs("main",{className:"max-w-3xl mx-auto px-4 py-8 space-y-6",children:[e.jsxs("div",{className:"text-center space-y-2",children:[e.jsxs("h1",{className:"text-2xl font-bold text-foreground",children:["Hey ",h,", ",l==null?void 0:l.name," has a message for you"]}),i.message&&e.jsx("p",{className:"text-muted-foreground max-w-xl mx-auto",children:i.message})]}),m&&e.jsx("div",{className:"rounded-xl overflow-hidden shadow-xl bg-black",children:e.jsx("div",{style:{position:"relative",paddingTop:"56.25%"},children:e.jsx("iframe",{src:m,loading:"lazy",style:{border:0,position:"absolute",top:0,left:0,width:"100%",height:"100%"},allow:"accelerometer; gyroscope; autoplay; encrypted-media; picture-in-picture",allowFullScreen:!0})})}),e.jsxs("div",{className:"bg-white rounded-xl shadow-sm border p-6 flex items-center gap-4",children:[l!=null&&l.avatar_url?e.jsx("img",{src:l.avatar_url,alt:"",className:"h-14 w-14 rounded-full object-cover"}):e.jsx("div",{className:"h-14 w-14 rounded-full flex items-center justify-center text-white text-lg font-bold",style:{backgroundColor:d},children:((_=l==null?void 0:l.name)==null?void 0:_.charAt(0))||"?"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"font-semibold",children:l==null?void 0:l.name}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[(l==null?void 0:l.title)||"Recruiter"," · ",o==null?void 0:o.name]})]})]}),(l==null?void 0:l.recruit_cta_url)&&e.jsx("div",{className:"text-center",children:e.jsx(H,{size:"lg",asChild:!0,className:"text-white shadow-lg hover:shadow-xl transition-shadow px-8",style:{backgroundColor:d},onClick:()=>{V.from("recruit_videos").update({cta_clicked_at:new Date().toISOString()}).eq("id",i.id).then(()=>{})},children:e.jsxs("a",{href:l.recruit_cta_url,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Nn,{className:"h-5 w-5 mr-2"})," Schedule a Conversation"]})})})]}),e.jsx("footer",{className:"text-center py-6 text-xs text-muted-foreground",children:"Powered by LevelUp"})]})]})}const l$s="relzejiswnotikjgvjhz",DWe=`https://${l$s}.supabase.co/functions/v1/recruit-unsubscribe`;function c$s(){const[s]=Ed(),t=s.get("token")||"",[r,n]=S.useState(!0),[a,i]=S.useState(!1),[l,o]=S.useState(!1),[c,d]=S.useState(""),[h,m]=S.useState({});S.useEffect(()=>{document.body.classList.add("recruit-unsubscribe-page");const x=()=>{['[id*="lc_text_widget"]','[class*="lc-text-widget"]','[class*="lc_text_widget"]','[id*="chat-widget"]','[class*="chat-widget"]','iframe[src*="leadconnector"]','iframe[src*="msgsndr"]',"[data-chat-widget]",'div[id^="hubspot"]',".widget-visible"].forEach(j=>document.querySelectorAll(j).forEach(k=>k.style.display="none"))};x();const y=[setTimeout(x,500),setTimeout(x,1500),setTimeout(x,3e3)],_=new MutationObserver(x);return _.observe(document.body,{childList:!0,subtree:!0}),()=>{document.body.classList.remove("recruit-unsubscribe-page"),y.forEach(clearTimeout),_.disconnect()}},[]),S.useEffect(()=>{if(!t){m({error:"Missing unsubscribe token in link."}),n(!1);return}fetch(`${DWe}?token=${encodeURIComponent(t)}`).then(async x=>{const y=await x.json();if(!x.ok)throw new Error(y.error||"Lookup failed");m(y),y.already_unsubscribed&&o(!0)}).catch(x=>m({error:x.message||"Could not load status"})).finally(()=>n(!1))},[t]);const p=async()=>{i(!0);try{const x=await fetch(DWe,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t,reason:c.trim()||null})}),y=await x.json();if(!x.ok)throw new Error(y.error||"Failed");o(!0)}catch(x){m({...h,error:x.message||"Could not unsubscribe"})}finally{i(!1)}};return e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-50 via-white to-slate-100 flex items-center justify-center p-6",children:e.jsx("div",{className:"w-full max-w-lg bg-white rounded-2xl shadow-xl border border-slate-200 p-8 sm:p-10",children:r?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 gap-3 text-slate-500",children:[e.jsx(is,{className:"h-8 w-8 animate-spin"}),e.jsx("p",{className:"text-sm",children:"Loading…"})]}):h.error?e.jsxs("div",{className:"text-center space-y-3",children:[e.jsx("div",{className:"mx-auto w-14 h-14 rounded-full bg-red-50 flex items-center justify-center",children:e.jsx(wo,{className:"h-7 w-7 text-red-500"})}),e.jsx("h1",{className:"text-xl font-semibold text-slate-800",children:"Link Invalid"}),e.jsx("p",{className:"text-sm text-slate-500",children:h.error}),e.jsx("p",{className:"text-xs text-slate-400 pt-2",children:"If you continue to receive emails you don't want, please reply directly to one of them and we'll remove you immediately."})]}):l?e.jsxs("div",{className:"text-center space-y-4",children:[e.jsx("div",{className:"mx-auto w-14 h-14 rounded-full bg-emerald-50 flex items-center justify-center",children:e.jsx(ea,{className:"h-7 w-7 text-emerald-500"})}),e.jsxs("h1",{className:"text-xl font-semibold text-slate-800",children:["You're unsubscribed",h.first_name?`, ${h.first_name}`:""]}),e.jsxs("p",{className:"text-sm text-slate-500",children:["You won't receive any more recruiting emails from ",h.brokerage_name||"this brokerage",". Your conversation remains 100% confidential."]}),e.jsxs("div",{className:"flex items-center justify-center gap-2 text-xs text-slate-400 pt-2",children:[e.jsx(w1,{className:"h-3.5 w-3.5"}),"Confidential opt-out · Confirmed"]})]}):e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx("div",{className:"mx-auto w-14 h-14 rounded-full bg-slate-100 flex items-center justify-center",children:e.jsx(w1,{className:"h-7 w-7 text-slate-500"})}),e.jsxs("h1",{className:"text-xl font-semibold text-slate-800",children:["Unsubscribe",h.first_name?`, ${h.first_name}`:"","?"]}),e.jsxs("p",{className:"text-sm text-slate-500",children:["You'll be removed from ",h.brokerage_name||"this brokerage","'s recruiting emails immediately. Everything stays confidential."]}),h.email&&e.jsx("p",{className:"text-xs text-slate-400",children:h.email})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"reason",className:"text-xs text-slate-500",children:"Optional — what's the main reason? (helps us improve)"}),e.jsx(vr,{id:"reason",value:c,onChange:x=>d(x.target.value),placeholder:"e.g. Not currently looking, too many emails, already moved…",rows:3,className:"resize-none"})]}),e.jsx(H,{onClick:p,disabled:a,className:"w-full h-11",variant:"default",children:a?e.jsxs(e.Fragment,{children:[e.jsx(is,{className:"h-4 w-4 mr-2 animate-spin"}),"Unsubscribing…"]}):"Confirm Unsubscribe"}),e.jsx("p",{className:"text-[11px] text-slate-400 text-center",children:"No login required. We process your request instantly."})]})})})}function d$s(){const s=Fr(),t=ns(),{isAdmin:r}=Ms(),[n,a]=S.useState(!1),[i,l]=S.useState(null),[o,c]=S.useState(null),{data:d,isLoading:h}=yt({queryKey:["my-social-accounts"],queryFn:async()=>{const{data:{user:A},error:D}=await V.auth.getUser();if(D)throw D;if(!A)return[];const{data:R,error:z}=await V.from("social_accounts").select("*").eq("user_id",A.id).order("created_at",{ascending:!1});if(z)throw z;return R}}),m=Pt({mutationFn:async A=>{const{data:{user:D},error:R}=await V.auth.getUser();if(R)throw R;if(!D)throw new Error("Not authenticated");const{error:z}=await V.from("social_accounts").delete().eq("id",A).eq("user_id",D.id);if(z)throw z},onSuccess:()=>{t.invalidateQueries({queryKey:["my-social-accounts"]}),t.invalidateQueries({queryKey:["social-accounts-for-post"]}),he.success("Account disconnected successfully")},onError:()=>{he.error("Failed to disconnect account")}}),p=async A=>{a(!0);try{const{data:D,error:R}=await V.functions.invoke("meta-oauth",{body:{action:"get_auth_url",callbackPath:"/social-connections/callback",authMode:A}});if(R)throw R;if(D!=null&&D.authUrl)window.location.href=D.authUrl;else throw new Error("Failed to get authorization URL")}catch(D){console.error("Meta OAuth error:",D),he.error("Failed to start connection. Please try again."),a(!1)}},x=async()=>{a(!0);try{const{data:A,error:D}=await V.functions.invoke("linkedin-oauth",{body:{action:"get_auth_url",callbackPath:"/social-connections/linkedin-callback"}});if(D)throw D;if(A!=null&&A.authUrl)window.location.href=A.authUrl;else throw new Error("Failed to get LinkedIn authorization URL")}catch(A){console.error("LinkedIn OAuth error:",A),he.error("Failed to start LinkedIn connection. Please try again."),a(!1)}},y=async()=>{a(!0);try{const{data:A,error:D}=await V.functions.invoke("google-business-oauth",{body:{action:"get_auth_url"}});if(D)throw D;if(A!=null&&A.authUrl)window.location.href=A.authUrl;else throw new Error("Failed to get Google authorization URL")}catch(A){console.error("Google OAuth error:",A),he.error("Failed to start Google connection. Please try again."),a(!1)}},_=(d==null?void 0:d.filter(A=>A.platform==="facebook"))||[],b=(d==null?void 0:d.filter(A=>A.platform==="instagram"))||[],j=(d==null?void 0:d.filter(A=>A.platform==="linkedin"))||[],k=(d==null?void 0:d.filter(A=>A.platform==="google_business"))||[],T=((d==null?void 0:d.length)||0)>0,E=async(A,D)=>{l(A),c(null);try{const{data:R,error:z}=await V.functions.invoke("meta-api-test",{body:{testType:"all",accountId:A}});if(z)throw z;c(R.results||[]),he.success(R.summary||"API tests completed")}catch(R){console.error("Meta API test error:",R),he.error("Failed to run API tests")}finally{l(null)}};return e.jsx(Ss,{title:"Social Connections",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"relative overflow-hidden rounded-2xl bg-gradient-to-br from-pink-500 via-purple-500 to-blue-500 p-6 md:p-8 text-white",children:[e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmYiIGZpbGwtb3BhY2l0eT0iMC4xIj48cGF0aCBkPSJNMzYgMzRjMC0yIDItNCAyLTRzMiAyIDIgNC0yIDQtMiA0LTItMi0yLTR6Ii8+PC9nPjwvZz48L3N2Zz4=')] opacity-30"}),e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"flex items-center gap-2 mb-3",children:e.jsxs(Xe,{variant:"secondary",className:"bg-white/20 text-white border-0 backdrop-blur-sm",children:[e.jsx(Lr,{className:"h-3 w-3 mr-1"}),"Post directly from Social Swag"]})}),e.jsx("h1",{className:"text-2xl md:text-3xl font-bold mb-2",children:"Connect Your Social Accounts"}),e.jsx("p",{className:"text-white/90 max-w-xl",children:"Link your Facebook Pages and Instagram Business accounts to post content directly from Social Swag with one click."})]})]}),e.jsxs(H,{variant:"ghost",onClick:()=>s("/social-swag-2"),className:"gap-2",children:[e.jsx(za,{className:"h-4 w-4"}),"Back to Social Swag"]}),T&&e.jsx(ke,{className:"border-green-200 bg-green-50 dark:bg-green-950/20 dark:border-green-900",children:e.jsxs(Oe,{className:"flex items-center gap-4 p-4",children:[e.jsx("div",{className:"rounded-full bg-green-500 p-2",children:e.jsx(zi,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-green-800 dark:text-green-200",children:"You're all set!"}),e.jsx("p",{className:"text-sm text-green-600 dark:text-green-400",children:"You can now post directly to your connected accounts from Social Swag."})]})]})}),e.jsxs("div",{className:"grid gap-6 md:grid-cols-2 lg:grid-cols-3",children:[e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"rounded-full bg-blue-500/10 p-3",children:e.jsx(fh,{className:"h-6 w-6 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(zt,{className:"text-lg",children:"Facebook"}),e.jsx(Br,{children:"Connect your Facebook Pages"})]})]})}),e.jsxs(Oe,{className:"space-y-4",children:[h?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(po,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):_.length>0?e.jsx("div",{className:"space-y-3",children:_.map(A=>e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(Un,{className:"h-10 w-10",children:[e.jsx(Ka,{src:A.profile_picture_url||""}),e.jsx(qn,{children:e.jsx(fh,{className:"h-5 w-5"})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:A.page_name||A.platform_username||"Facebook Page"}),e.jsx(Xe,{variant:A.is_active?"default":"secondary",className:"text-xs",children:A.is_active?"Connected":"Inactive"})]})]}),e.jsxs(Rl,{children:[e.jsx(vp,{asChild:!0,children:e.jsx(H,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(Dr,{className:"h-4 w-4"})})}),e.jsxs(jl,{children:[e.jsxs(Nl,{children:[e.jsx(Sl,{children:"Disconnect Facebook?"}),e.jsx(Cl,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(kl,{children:[e.jsx(Tl,{children:"Cancel"}),e.jsx(ml,{onClick:()=>m.mutate(A.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},A.id))}):e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No Facebook pages connected yet"}),e.jsxs(H,{onClick:()=>p("facebook"),disabled:n,className:"w-full gap-2",variant:_.length>0?"outline":"default",children:[n?e.jsx(po,{className:"h-4 w-4 animate-spin"}):e.jsx(Ys,{className:"h-4 w-4"}),_.length>0?"Connect Another Page":"Connect Facebook Page"]})]})]}),e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"rounded-full bg-gradient-to-br from-purple-500/10 via-pink-500/10 to-orange-500/10 p-3",children:e.jsx(yu,{className:"h-6 w-6 text-pink-600"})}),e.jsxs("div",{children:[e.jsx(zt,{className:"text-lg",children:"Instagram"}),e.jsx(Br,{children:"Connect Instagram Business accounts"})]})]})}),e.jsxs(Oe,{className:"space-y-4",children:[h?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(po,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):b.length>0?e.jsx("div",{className:"space-y-3",children:b.map(A=>e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(Un,{className:"h-10 w-10",children:[e.jsx(Ka,{src:A.profile_picture_url||""}),e.jsx(qn,{children:e.jsx(yu,{className:"h-5 w-5"})})]}),e.jsxs("div",{children:[e.jsxs("p",{className:"font-medium",children:["@",A.platform_username||"Instagram Account"]}),e.jsx(Xe,{variant:A.is_active?"default":"secondary",className:"text-xs",children:A.is_active?"Connected":"Inactive"})]})]}),e.jsxs(Rl,{children:[e.jsx(vp,{asChild:!0,children:e.jsx(H,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(Dr,{className:"h-4 w-4"})})}),e.jsxs(jl,{children:[e.jsxs(Nl,{children:[e.jsx(Sl,{children:"Disconnect Instagram?"}),e.jsx(Cl,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(kl,{children:[e.jsx(Tl,{children:"Cancel"}),e.jsx(ml,{onClick:()=>m.mutate(A.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},A.id))}):e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No Instagram accounts connected yet"}),e.jsxs(H,{onClick:()=>p("instagram"),disabled:n,className:"w-full gap-2",variant:b.length>0?"outline":"default",children:[n?e.jsx(po,{className:"h-4 w-4 animate-spin"}):e.jsx(Ys,{className:"h-4 w-4"}),b.length>0?"Connect Another Account":"Connect Instagram Professional"]}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:"Use Instagram login for Business or Creator accounts; Facebook Page login is only needed if you want to connect Pages."})]})]}),e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"rounded-full bg-blue-600/10 p-3",children:e.jsx(qf,{className:"h-6 w-6 text-blue-700"})}),e.jsxs("div",{children:[e.jsx(zt,{className:"text-lg",children:"LinkedIn"}),e.jsx(Br,{children:"Connect your LinkedIn profile"})]})]})}),e.jsxs(Oe,{className:"space-y-4",children:[h?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(po,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):j.length>0?e.jsx("div",{className:"space-y-3",children:j.map(A=>e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(Un,{className:"h-10 w-10",children:[e.jsx(Ka,{src:A.profile_picture_url||""}),e.jsx(qn,{children:e.jsx(qf,{className:"h-5 w-5"})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:A.platform_username||"LinkedIn Account"}),e.jsx(Xe,{variant:A.is_active?"default":"secondary",className:"text-xs",children:A.is_active?"Connected":"Inactive"})]})]}),e.jsxs(Rl,{children:[e.jsx(vp,{asChild:!0,children:e.jsx(H,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(Dr,{className:"h-4 w-4"})})}),e.jsxs(jl,{children:[e.jsxs(Nl,{children:[e.jsx(Sl,{children:"Disconnect LinkedIn?"}),e.jsx(Cl,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(kl,{children:[e.jsx(Tl,{children:"Cancel"}),e.jsx(ml,{onClick:()=>m.mutate(A.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},A.id))}):e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No LinkedIn account connected yet"}),e.jsxs(H,{onClick:x,disabled:n,className:"w-full gap-2",variant:j.length>0?"outline":"default",children:[n?e.jsx(po,{className:"h-4 w-4 animate-spin"}):e.jsx(Ys,{className:"h-4 w-4"}),j.length>0?"Reconnect LinkedIn":"Connect LinkedIn"]}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:"Share content directly to your LinkedIn profile"})]})]}),e.jsxs(ke,{className:`relative overflow-hidden ${r?"":"opacity-75"}`,children:[!r&&e.jsx("div",{className:"absolute top-3 right-3 z-10",children:e.jsx(Xe,{variant:"secondary",className:"bg-amber-100 text-amber-800 dark:bg-amber-900/30 dark:text-amber-400",children:"Coming Soon"})}),r&&e.jsx("div",{className:"absolute top-3 right-3 z-10",children:e.jsx(Xe,{variant:"secondary",className:"bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400",children:"Admin Testing"})}),e.jsx(Ot,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"rounded-full bg-red-500/10 p-3",children:e.jsx(Qa,{className:"h-6 w-6 text-red-600"})}),e.jsxs("div",{children:[e.jsx(zt,{className:"text-lg",children:"Google Business"}),e.jsx(Br,{children:"Connect your Google Business Profile"})]})]})}),e.jsxs(Oe,{className:"space-y-4",children:[h?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(po,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):k.length>0?e.jsx("div",{className:"space-y-3",children:k.map(A=>e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(Un,{className:"h-10 w-10",children:[e.jsx(Ka,{src:A.profile_picture_url||""}),e.jsx(qn,{children:e.jsx(Qa,{className:"h-5 w-5"})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:A.page_name||A.platform_username||"Google Business"}),e.jsx(Xe,{variant:A.is_active?"default":"secondary",className:"text-xs",children:A.is_active?"Connected":"Inactive"})]})]}),e.jsxs(Rl,{children:[e.jsx(vp,{asChild:!0,children:e.jsx(H,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(Dr,{className:"h-4 w-4"})})}),e.jsxs(jl,{children:[e.jsxs(Nl,{children:[e.jsx(Sl,{children:"Disconnect Google Business?"}),e.jsx(Cl,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(kl,{children:[e.jsx(Tl,{children:"Cancel"}),e.jsx(ml,{onClick:()=>m.mutate(A.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},A.id))}):e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:r?"No Google Business account connected yet":"Google Business Profile integration is coming soon!"}),e.jsxs(H,{onClick:r?y:void 0,disabled:!r||n,className:"w-full gap-2",variant:k.length>0?"outline":"default",children:[n?e.jsx(po,{className:"h-4 w-4 animate-spin"}):e.jsx(Ys,{className:"h-4 w-4"}),k.length>0?"Reconnect Google Business":"Connect Google Business"]}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:"Post updates directly to your Google Business Profile"})]})]})]}),r&&(_.length>0||b.length>0)&&e.jsxs(ke,{className:"border-amber-200 bg-amber-50 dark:bg-amber-950/20 dark:border-amber-900",children:[e.jsx(Ot,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"rounded-full bg-amber-500/10 p-3",children:e.jsx(Bk,{className:"h-6 w-6 text-amber-600"})}),e.jsxs("div",{children:[e.jsx(zt,{className:"text-lg",children:"Meta API Testing (Admin Only)"}),e.jsx(Br,{children:"Run API tests to trigger all required permissions for Meta App Review"})]})]})}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:['Click "Run Tests" on an account to trigger API calls for: ',e.jsx("strong",{children:"public_profile"}),", ",e.jsx("strong",{children:"pages_show_list"}),", ",e.jsx("strong",{children:"pages_read_engagement"}),", ",e.jsx("strong",{children:"instagram_basic"}),", ",e.jsx("strong",{children:"pages_manage_posts"}),", and ",e.jsx("strong",{children:"instagram_content_publish"}),"."]}),e.jsxs("div",{className:"space-y-3",children:[_.map(A=>e.jsxs("div",{className:"flex items-center justify-between rounded-lg border bg-background p-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(fh,{className:"h-5 w-5 text-blue-600"}),e.jsx("span",{className:"font-medium",children:A.page_name||"Facebook Page"})]}),e.jsx(H,{size:"sm",variant:"outline",onClick:()=>E(A.id),disabled:i===A.id,children:i===A.id?e.jsxs(e.Fragment,{children:[e.jsx(is,{className:"h-4 w-4 mr-2 animate-spin"}),"Testing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Bk,{className:"h-4 w-4 mr-2"}),"Run Tests"]})})]},`test-fb-${A.id}`)),b.map(A=>e.jsxs("div",{className:"flex items-center justify-between rounded-lg border bg-background p-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(yu,{className:"h-5 w-5 text-pink-600"}),e.jsxs("span",{className:"font-medium",children:["@",A.platform_username||"Instagram"]})]}),e.jsx(H,{size:"sm",variant:"outline",onClick:()=>E(A.id),disabled:i===A.id,children:i===A.id?e.jsxs(e.Fragment,{children:[e.jsx(is,{className:"h-4 w-4 mr-2 animate-spin"}),"Testing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Bk,{className:"h-4 w-4 mr-2"}),"Run Tests"]})})]},`test-ig-${A.id}`))]}),o&&o.length>0&&e.jsxs("div",{className:"mt-4 rounded-lg border bg-background p-4",children:[e.jsx("h4",{className:"font-medium mb-3",children:"Test Results"}),e.jsx("div",{className:"space-y-2",children:o.map((A,D)=>e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[A.status==="success"?e.jsx(ea,{className:"h-4 w-4 text-green-600 mt-0.5 shrink-0"}):A.status==="pending"?e.jsx(is,{className:"h-4 w-4 text-amber-600 mt-0.5 shrink-0"}):e.jsx(kd,{className:"h-4 w-4 text-red-600 mt-0.5 shrink-0"}),e.jsxs("div",{children:[e.jsx("span",{className:"font-mono text-xs bg-muted px-1 rounded",children:A.test}),e.jsx("span",{className:"ml-2 text-muted-foreground",children:A.details})]})]},D))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Note: Facebook posts are auto-deleted. Instagram posts will remain and should be manually deleted. Allow up to 24 hours for Meta to register the API calls."})]})]}),e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-lg",children:"How it works"})}),e.jsx(Oe,{children:e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsxs("div",{className:"flex gap-3",children:[e.jsx("div",{className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-primary text-primary-foreground text-sm font-medium",children:"1"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Connect your accounts"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Link your Facebook, Instagram, or LinkedIn account"})]})]}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx("div",{className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-primary text-primary-foreground text-sm font-medium",children:"2"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Browse Social Swag"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Find the perfect image and caption for your post"})]})]}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx("div",{className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-primary text-primary-foreground text-sm font-medium",children:"3"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Post with one click"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:'Click "Create Post" to share directly to your accounts'})]})]})]})})]})]})})}function u$s(){const[s]=Ed(),t=Fr(),[r,n]=S.useState("loading"),[a,i]=S.useState("Processing your connection...");return S.useEffect(()=>{(async()=>{var m;const o=s.get("code"),c=s.get("error"),d=s.get("error_description"),h=s.get("state");if(c){n("error"),i(d||"Authorization was denied"),he.error("Connection failed: "+(d||c));return}if(!o){n("error"),i("No authorization code received"),he.error("No authorization code received");return}try{const{data:p,error:x}=await V.functions.invoke("meta-oauth",{body:{action:"exchange_code",code:o,state:h,callbackPath:"/social-connections/callback"}});if(x)throw x;if(p!=null&&p.success)n("success"),i(`Successfully connected ${((m=p.accounts)==null?void 0:m.length)||0} account(s)!`),he.success("Social accounts connected successfully!");else throw new Error((p==null?void 0:p.error)||"Unknown error")}catch(p){console.error("OAuth callback error:",p),n("error"),i(p instanceof Error?p.message:"Failed to connect accounts"),he.error("Failed to connect: "+(p instanceof Error?p.message:"Unknown error"))}})()},[s]),e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsxs(ke,{className:"w-full max-w-md",children:[e.jsxs(Ot,{className:"text-center",children:[r==="loading"&&e.jsx(is,{className:"h-12 w-12 animate-spin mx-auto text-primary"}),r==="success"&&e.jsx(zi,{className:"h-12 w-12 mx-auto text-green-500"}),r==="error"&&e.jsx(kd,{className:"h-12 w-12 mx-auto text-destructive"}),e.jsxs(zt,{className:"mt-4",children:[r==="loading"&&"Connecting...",r==="success"&&"Connected!",r==="error"&&"Connection Failed"]}),e.jsx(Br,{children:a})]}),e.jsx(Oe,{className:"flex justify-center",children:r!=="loading"&&e.jsx(H,{onClick:()=>t("/mission-control/integrations"),children:r==="success"?"View Connected Accounts":"Try Again"})})]})})}function h$s(){const[s]=Ed(),t=Fr(),[r,n]=S.useState("loading"),[a,i]=S.useState("Connecting your Google Business Profile...");return S.useEffect(()=>{(async()=>{const o=s.get("code"),c=s.get("error"),d=s.get("error_description"),h=s.get("state");if(c){n("error"),i(d||"Authorization was denied"),he.error("Connection failed: "+(d||c));return}if(!o){n("error"),i("No authorization code received"),he.error("No authorization code received");return}try{const{data:m,error:p}=await V.functions.invoke("google-business-oauth",{body:{action:"exchange_code",code:o,state:h}});if(p)throw p;if(m!=null&&m.success)n("success"),i(m.message||"Successfully connected Google Business Profile!"),he.success("Google Business Profile connected!");else throw new Error((m==null?void 0:m.error)||"Unknown error")}catch(m){console.error("Google OAuth callback error:",m),n("error"),i(m instanceof Error?m.message:"Failed to connect Google Business Profile"),he.error("Failed to connect: "+(m instanceof Error?m.message:"Unknown error"))}})()},[s]),e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsxs(ke,{className:"w-full max-w-md",children:[e.jsxs(Ot,{className:"text-center",children:[r==="loading"&&e.jsx(is,{className:"h-12 w-12 animate-spin mx-auto text-primary"}),r==="success"&&e.jsx(zi,{className:"h-12 w-12 mx-auto text-green-500"}),r==="error"&&e.jsx(kd,{className:"h-12 w-12 mx-auto text-destructive"}),e.jsxs(zt,{className:"mt-4",children:[r==="loading"&&"Connecting...",r==="success"&&"Connected!",r==="error"&&"Connection Failed"]}),e.jsx(Br,{children:a})]}),e.jsx(Oe,{className:"flex justify-center",children:r!=="loading"&&e.jsx(H,{onClick:()=>t("/social-connections"),children:r==="success"?"View Connected Accounts":"Try Again"})})]})})}function m$s(){const[s]=Ed(),t=Fr(),[r,n]=S.useState("loading"),[a,i]=S.useState("Connecting your LinkedIn account...");return S.useEffect(()=>{(async()=>{var m;const o=s.get("code"),c=s.get("state"),d=s.get("error"),h=s.get("error_description");if(d){console.error("LinkedIn OAuth error:",d,h),n("error"),i(h||"Failed to connect LinkedIn account"),he.error(h||"Failed to connect LinkedIn");return}if(!o){n("error"),i("No authorization code received"),he.error("No authorization code received");return}try{const{data:p,error:x}=await V.functions.invoke("linkedin-oauth",{body:{action:"exchange_code",code:o,state:c,callbackPath:"/social-connections/linkedin-callback"}});if(x)throw x;if(p!=null&&p.success)n("success"),i(`Successfully connected ${((m=p.accounts)==null?void 0:m.length)||1} LinkedIn account`),he.success("LinkedIn connected successfully!");else throw new Error((p==null?void 0:p.error)||"Failed to connect LinkedIn account")}catch(p){console.error("LinkedIn callback error:",p),n("error"),i(p instanceof Error?p.message:"Failed to connect LinkedIn account"),he.error("Failed to connect LinkedIn")}})()},[s]),e.jsx("div",{className:"min-h-screen flex items-center justify-center p-4 bg-background",children:e.jsxs(ke,{className:"w-full max-w-md",children:[e.jsxs(Ot,{className:"text-center",children:[e.jsxs("div",{className:"mx-auto mb-4 rounded-full bg-blue-600/10 p-4 w-fit",children:[r==="loading"&&e.jsx(is,{className:"h-8 w-8 animate-spin text-blue-600"}),r==="success"&&e.jsx(zi,{className:"h-8 w-8 text-green-600"}),r==="error"&&e.jsx(kd,{className:"h-8 w-8 text-red-600"})]}),e.jsxs(zt,{className:"flex items-center justify-center gap-2",children:[e.jsx(qf,{className:"h-5 w-5 text-blue-600"}),r==="loading"&&"Connecting...",r==="success"&&"Connected!",r==="error"&&"Connection Failed"]}),e.jsx(Br,{children:a})]}),e.jsx(Oe,{className:"flex justify-center",children:e.jsx(H,{onClick:()=>t("/mission-control/integrations"),disabled:r==="loading",children:r==="success"?"View Integrations":"Back to Integrations"})})]})})}function f$s(){const s=Fr(),[t,r]=S.useState(null),{data:n,isLoading:a}=Qyt(t||void 0,!0),{data:i,isLoading:l}=g6e(!0),{cartItems:o}=Yge(),c=o.reduce((h,m)=>h+m.quantity,0),d=h=>{s(`/marketplace/${h.id}`)};return a||l?e.jsx(Ss,{title:"Marketplace",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx("div",{className:"flex gap-2 overflow-x-auto pb-2",children:[1,2,3].map(h=>e.jsx(Ks,{className:"h-10 w-24 flex-shrink-0"},h))}),e.jsx("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4",children:[1,2,3,4].map(h=>e.jsx(Ks,{className:"h-72 w-full"},h))})]})}):e.jsx(Ss,{title:"Marketplace",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-5xl font-bold text-foreground",children:"Marketplace"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Shop exclusive products for LevelUp members"})]}),e.jsxs(H,{variant:"outline",onClick:()=>s("/marketplace/cart"),className:"relative",children:[e.jsx(sx,{className:"h-4 w-4 mr-2"}),"Cart",c>0&&e.jsx(Xe,{className:"absolute -top-2 -right-2 h-5 w-5 flex items-center justify-center p-0 text-xs",children:c})]})]}),i&&i.length>0&&e.jsxs("div",{className:"flex gap-2 overflow-x-auto pb-2",children:[e.jsx(H,{variant:t===null?"default":"outline",size:"sm",onClick:()=>r(null),children:"All"}),i.map(h=>e.jsx(H,{variant:t===h.id?"default":"outline",size:"sm",onClick:()=>r(h.id),children:h.name},h.id))]}),n&&n.length>0?e.jsx("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4",children:n.map(h=>{var m;return e.jsxs(ke,{className:"overflow-hidden cursor-pointer hover:shadow-lg transition-shadow",onClick:()=>d(h),children:[e.jsxs("div",{className:"aspect-square bg-muted relative",children:[h.images&&h.images.length>0?e.jsx("img",{src:((m=h.images.find(p=>p.is_primary))==null?void 0:m.image_url)||h.images[0].image_url,alt:h.name,className:"w-full h-full object-cover"}):e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx(yc,{className:"h-12 w-12 text-muted-foreground"})}),h.category&&e.jsx(Xe,{className:"absolute top-2 left-2",variant:"secondary",children:h.category.name})]}),e.jsxs(Oe,{className:"p-4",children:[e.jsx("h3",{className:"font-semibold mb-1 line-clamp-1",children:h.name}),h.description&&e.jsx("p",{className:"text-sm text-muted-foreground mb-2 line-clamp-2",children:h.description}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"font-bold text-lg",children:["$",Number(h.base_price).toFixed(2)]}),h.variants&&h.variants.length>0&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:[h.variants.length," options"]})]})]})]},h.id)})}):e.jsxs("div",{className:"text-center py-12",children:[e.jsx(yc,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:"No products available yet."})]})]})})}const Svt=S.forwardRef(({...s},t)=>e.jsx("nav",{ref:t,"aria-label":"breadcrumb",...s}));Svt.displayName="Breadcrumb";const Cvt=S.forwardRef(({className:s,...t},r)=>e.jsx("ol",{ref:r,className:Ft("flex flex-wrap items-center gap-1.5 break-words text-sm text-muted-foreground sm:gap-2.5",s),...t}));Cvt.displayName="BreadcrumbList";const Fue=S.forwardRef(({className:s,...t},r)=>e.jsx("li",{ref:r,className:Ft("inline-flex items-center gap-1.5",s),...t}));Fue.displayName="BreadcrumbItem";const Z4e=S.forwardRef(({asChild:s,className:t,...r},n)=>{const a=s?p3e:"a";return e.jsx(a,{ref:n,className:Ft("transition-colors hover:text-foreground",t),...r})});Z4e.displayName="BreadcrumbLink";const Tvt=S.forwardRef(({className:s,...t},r)=>e.jsx("span",{ref:r,role:"link","aria-disabled":"true","aria-current":"page",className:Ft("font-normal text-foreground",s),...t}));Tvt.displayName="BreadcrumbPage";const X4e=({children:s,className:t,...r})=>e.jsx("li",{role:"presentation","aria-hidden":"true",className:Ft("[&>svg]:size-3.5",t),...r,children:s??e.jsx($a,{})});X4e.displayName="BreadcrumbSeparator";function p$s(){var J,K;const{productId:s}=Po(),t=Fr(),{data:r,isLoading:n}=cBs(s||""),{addToCart:a,cartItems:i}=Yge(),[l,o]=S.useState(null),[c,d]=S.useState(1),[h,m]=S.useState(0),[p,x]=S.useState(null),[y,_]=S.useState(!1),[b,j]=S.useState(!1),k=(J=r==null?void 0:r.variants)==null?void 0:J.find(re=>re.id===l),T=((K=r==null?void 0:r.variants)==null?void 0:K.filter(re=>re.is_active))||[],E=Number((r==null?void 0:r.base_price)||0),A=k?Number(k.price_adjustment):0,D=E+A,R=Number((r==null?void 0:r.shipping_fee)||0),z=i.reduce((re,ie)=>re+ie.quantity,0),O=async re=>{if(!re.target.files||re.target.files.length===0)return;_(!0);const ie=re.target.files[0],ce=ie.name.split(".").pop(),ne=`artwork/${Date.now()}-${Math.random().toString(36).substring(7)}.${ce}`;try{const{error:le}=await V.storage.from("marketplace").upload(ne,ie);if(le)throw le;const{data:{publicUrl:be}}=V.storage.from("marketplace").getPublicUrl(ne);x(be),he.success("Artwork uploaded successfully")}catch(le){he.error("Failed to upload artwork: "+le.message)}finally{_(!1)}},$=()=>{if(r){if(T.length>0&&!l){he.error("Please select an option");return}a(r,k||void 0,c,p||void 0),j(!0),he.success("Added to cart!"),setTimeout(()=>j(!1),2e3)}},ee=()=>{r!=null&&r.images&&m(re=>(re+1)%r.images.length)},Z=()=>{r!=null&&r.images&&m(re=>(re-1+r.images.length)%r.images.length)};return n?e.jsx(Ss,{title:"Product",children:e.jsxs("div",{className:"grid gap-8 lg:grid-cols-2",children:[e.jsx(Ks,{className:"aspect-square w-full"}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ks,{className:"h-8 w-3/4"}),e.jsx(Ks,{className:"h-6 w-1/4"}),e.jsx(Ks,{className:"h-24 w-full"}),e.jsx(Ks,{className:"h-12 w-full"})]})]})}):r?e.jsxs(Ss,{title:r.name,children:[e.jsx(Svt,{className:"mb-6",children:e.jsxs(Cvt,{children:[e.jsx(Fue,{children:e.jsx(Z4e,{asChild:!0,children:e.jsx(Xn,{to:"/marketplace",children:"Marketplace"})})}),r.category&&e.jsxs(e.Fragment,{children:[e.jsx(X4e,{}),e.jsx(Fue,{children:e.jsx(Z4e,{asChild:!0,children:e.jsx(Xn,{to:`/marketplace?category=${r.category.id}`,children:r.category.name})})})]}),e.jsx(X4e,{}),e.jsx(Fue,{children:e.jsx(Tvt,{children:r.name})})]})}),e.jsxs("div",{className:"grid gap-8 lg:grid-cols-2",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"relative aspect-square bg-muted rounded-lg overflow-hidden flex items-center justify-center",children:r.images&&r.images.length>0?e.jsxs(e.Fragment,{children:[e.jsx("img",{src:r.images[h].image_url,alt:r.name,className:"max-w-full max-h-full object-contain"}),r.images.length>1&&e.jsxs(e.Fragment,{children:[e.jsx(H,{variant:"ghost",size:"icon",className:"absolute left-2 top-1/2 -translate-y-1/2 bg-background/80 hover:bg-background",onClick:Z,children:e.jsx(fl,{className:"h-6 w-6"})}),e.jsx(H,{variant:"ghost",size:"icon",className:"absolute right-2 top-1/2 -translate-y-1/2 bg-background/80 hover:bg-background",onClick:ee,children:e.jsx($a,{className:"h-6 w-6"})})]})]}):e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx(yc,{className:"h-24 w-24 text-muted-foreground"})})}),r.images&&r.images.length>1&&e.jsx("div",{className:"flex gap-2 overflow-x-auto pb-2",children:r.images.map((re,ie)=>e.jsx("button",{onClick:()=>m(ie),className:`w-16 h-16 flex-shrink-0 rounded-md overflow-hidden border-2 ${ie===h?"border-primary":"border-transparent"}`,children:e.jsx("img",{src:re.image_url,alt:"",className:"w-full h-full object-cover"})},re.id))}),r.video&&e.jsx(ke,{children:e.jsxs(Oe,{className:"p-4",children:[e.jsx("h4",{className:"font-medium mb-2",children:"Product Video"}),e.jsx("div",{className:"aspect-video",children:e.jsx("iframe",{src:r.video.video_url,className:"w-full h-full rounded-lg",allowFullScreen:!0})})]})})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[r.category&&e.jsx(Xe,{variant:"secondary",className:"mb-2",children:r.category.name}),e.jsx("h1",{className:"text-3xl font-bold mb-2",children:r.name}),e.jsxs("div",{className:"flex items-baseline gap-2",children:[e.jsxs("span",{className:"text-3xl font-bold",children:["$",D.toFixed(2)]}),R>0&&e.jsxs("span",{className:"text-muted-foreground",children:["+ $",R.toFixed(2)," shipping"]})]})]}),r.description&&e.jsx("div",{className:"prose prose-sm max-w-none",children:e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:r.description})}),T.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(ue,{children:"Select Option"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:T.map(re=>e.jsxs(H,{variant:l===re.id?"default":"outline",onClick:()=>o(re.id),children:[re.name,Number(re.price_adjustment)!==0&&e.jsxs("span",{className:"ml-1 opacity-70",children:["(",Number(re.price_adjustment)>0?"+":"","$",Number(re.price_adjustment).toFixed(2),")"]})]},re.id))})]}),r.allow_artwork_upload&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(ue,{children:"Upload Your Artwork (Optional)"}),p?e.jsxs("div",{className:"relative inline-block",children:[e.jsx("img",{src:p,alt:"Your artwork",className:"h-24 w-auto rounded-lg border"}),e.jsx(H,{variant:"ghost",size:"sm",className:"absolute -top-2 -right-2",onClick:()=>x(null),children:"×"})]}):e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-6",children:[e.jsx("input",{type:"file",accept:"image/*,.pdf,.ai,.eps",onChange:O,className:"hidden",id:"artwork-upload",disabled:y}),e.jsxs("label",{htmlFor:"artwork-upload",className:"flex flex-col items-center cursor-pointer",children:[e.jsx(Ea,{className:"h-8 w-8 text-muted-foreground mb-2"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:y?"Uploading...":"Click to upload artwork"}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"Supported: JPG, PNG, PDF, AI, EPS"})]})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(ue,{children:"Quantity"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(H,{variant:"outline",size:"icon",onClick:()=>d(re=>Math.max(1,re-1)),children:"-"}),e.jsx(Se,{type:"number",value:c,onChange:re=>d(Math.max(1,parseInt(re.target.value)||1)),className:"w-20 text-center",min:"1"}),e.jsx(H,{variant:"outline",size:"icon",onClick:()=>d(re=>re+1),children:"+"})]})]}),e.jsxs("div",{className:"flex gap-4",children:[e.jsx(H,{size:"lg",className:"flex-1",onClick:$,disabled:b,children:b?e.jsxs(e.Fragment,{children:[e.jsx(va,{className:"h-5 w-5 mr-2"}),"Added!"]}):e.jsxs(e.Fragment,{children:[e.jsx(sx,{className:"h-5 w-5 mr-2"}),"Add to Cart"]})}),e.jsxs(H,{variant:"outline",size:"lg",onClick:()=>t("/marketplace/cart"),className:"relative",children:[e.jsx(sx,{className:"h-5 w-5"}),z>0&&e.jsx(Xe,{className:"absolute -top-2 -right-2 h-5 w-5 flex items-center justify-center p-0 text-xs",children:z})]})]}),r.requires_proof_approval&&e.jsx("p",{className:"text-sm text-muted-foreground bg-muted p-3 rounded-lg",children:"📋 This product requires proof approval before production. You'll receive a proof to review after your order is placed."})]})]})]}):e.jsx(Ss,{title:"Product Not Found",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx(yc,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"Product not found"}),e.jsx(H,{onClick:()=>t("/marketplace"),children:"Back to Marketplace"})]})})}function g$s(){const s=Fr(),{cartItems:t,removeFromCart:r,updateQuantity:n,getItemPrice:a,getSubtotal:i,getShippingTotal:l,getTotal:o,clearCart:c}=Yge(),[d,h]=S.useState(!1),[m,p]=S.useState(""),x=async()=>{if(t.length===0){he.error("Your cart is empty");return}h(!0);try{const{data:y,error:_}=await V.functions.invoke("marketplace-checkout",{body:{items:t.map(b=>{var j;return{product_id:b.product.id,variant_id:((j=b.variant)==null?void 0:j.id)||null,quantity:b.quantity,artwork_url:b.artworkUrl||null}}),notes:m.trim()||null}});if(_)throw _;if(y!=null&&y.url)c(),window.open(y.url,"_blank");else throw new Error("No checkout URL received")}catch(y){he.error("Checkout failed: "+y.message)}finally{h(!1)}};return t.length===0?e.jsx(Ss,{title:"Shopping Cart",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx(b_,{className:"h-16 w-16 mx-auto text-muted-foreground mb-4"}),e.jsx("h2",{className:"text-xl font-semibold mb-2",children:"Your cart is empty"}),e.jsx("p",{className:"text-muted-foreground mb-6",children:"Add some products to get started!"}),e.jsx(H,{onClick:()=>s("/marketplace"),children:"Browse Marketplace"})]})}):e.jsx(Ss,{title:"Shopping Cart",children:e.jsxs("div",{className:"grid gap-8 lg:grid-cols-3",children:[e.jsxs("div",{className:"lg:col-span-2 space-y-4",children:[t.map(y=>{var _,b;return e.jsx(ke,{children:e.jsx(Oe,{className:"p-4",children:e.jsxs("div",{className:"flex gap-4",children:[e.jsx("div",{className:"w-24 h-24 flex-shrink-0 bg-muted rounded-lg overflow-hidden",children:y.product.images&&y.product.images.length>0?e.jsx("img",{src:((_=y.product.images.find(j=>j.is_primary))==null?void 0:_.image_url)||y.product.images[0].image_url,alt:y.product.name,className:"w-full h-full object-cover"}):e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx(b_,{className:"h-8 w-8 text-muted-foreground"})})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-semibold line-clamp-1",children:y.product.name}),y.variant&&e.jsx("p",{className:"text-sm text-muted-foreground",children:y.variant.name}),e.jsxs("p",{className:"font-medium mt-1",children:["$",a(y).toFixed(2),Number(y.product.shipping_fee)>0&&e.jsxs("span",{className:"text-sm text-muted-foreground ml-2",children:["+ $",Number(y.product.shipping_fee).toFixed(2)," shipping"]})]}),y.artworkUrl&&e.jsx("div",{className:"mt-2",children:e.jsx("span",{className:"text-xs text-muted-foreground",children:"Artwork uploaded ✓"})})]}),e.jsxs("div",{className:"flex flex-col items-end gap-2",children:[e.jsx(H,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>{var j;return r(y.product.id,(j=y.variant)==null?void 0:j.id)},children:e.jsx(Dr,{className:"h-4 w-4 text-destructive"})}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(H,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>{var j;return n(y.product.id,(j=y.variant)==null?void 0:j.id,y.quantity-1)},disabled:y.quantity<=1,children:e.jsx(g_,{className:"h-3 w-3"})}),e.jsx(Se,{type:"number",value:y.quantity,onChange:j=>{var k;return n(y.product.id,(k=y.variant)==null?void 0:k.id,parseInt(j.target.value)||1)},className:"w-14 h-8 text-center text-sm",min:"1"}),e.jsx(H,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>{var j;return n(y.product.id,(j=y.variant)==null?void 0:j.id,y.quantity+1)},children:e.jsx(Ys,{className:"h-3 w-3"})})]})]})]})})},`${y.product.id}-${((b=y.variant)==null?void 0:b.id)||"base"}`)}),e.jsx(H,{variant:"ghost",className:"text-destructive",onClick:c,children:"Clear Cart"})]}),e.jsx("div",{children:e.jsxs(ke,{className:"sticky top-4",children:[e.jsx(Ot,{children:e.jsx(zt,{children:"Order Summary"})}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsxs("span",{children:["Subtotal (",t.reduce((y,_)=>y+_.quantity,0)," items)"]}),e.jsxs("span",{children:["$",i().toFixed(2)]})]}),e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{children:"Shipping"}),e.jsxs("span",{children:["$",l().toFixed(2)]})]}),e.jsx(Qo,{}),e.jsxs("div",{className:"flex justify-between font-bold text-lg",children:[e.jsx("span",{children:"Total"}),e.jsxs("span",{children:["$",o().toFixed(2)]})]}),e.jsx(Qo,{}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"orderNotes",children:"Order Notes (Optional)"}),e.jsx(vr,{id:"orderNotes",placeholder:"Add any special instructions, design notes, or comments for your order...",value:m,onChange:y=>p(y.target.value),rows:3,className:"resize-none"})]}),e.jsx(H,{className:"w-full",size:"lg",onClick:x,disabled:d,children:d?e.jsxs(e.Fragment,{children:[e.jsx(is,{className:"h-5 w-5 mr-2 animate-spin"}),"Processing..."]}):e.jsxs(e.Fragment,{children:["Checkout",e.jsx(bi,{className:"h-5 w-5 ml-2"})]})}),e.jsx("p",{className:"text-xs text-center text-muted-foreground",children:"Secure checkout powered by Stripe"})]})]})})]})})}function x$s(){const s=Fr(),{data:t,isLoading:r}=bBs();return r?e.jsx(Ss,{title:"My Orders",children:e.jsx("div",{className:"space-y-4",children:[1,2,3].map(n=>e.jsx(Ks,{className:"h-32 w-full"},n))})}):!t||t.length===0?e.jsx(Ss,{title:"My Orders",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx(yc,{className:"h-16 w-16 mx-auto text-muted-foreground mb-4"}),e.jsx("h2",{className:"text-xl font-semibold mb-2",children:"No orders yet"}),e.jsx("p",{className:"text-muted-foreground mb-6",children:"Start shopping to see your orders here!"}),e.jsx(H,{onClick:()=>s("/marketplace"),children:"Browse Marketplace"})]})}):e.jsx(Ss,{title:"My Orders",children:e.jsx("div",{className:"space-y-4",children:t.map(n=>{var a,i,l;return e.jsx(ke,{className:"cursor-pointer hover:shadow-md transition-shadow",onClick:()=>s(`/marketplace/orders/${n.id}`),children:e.jsxs(Oe,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold",children:n.order_number}),e.jsx("span",{className:"text-muted-foreground text-sm ml-2",children:As(new Date(n.created_at),"MMM d, yyyy")})]}),e.jsx(Xe,{className:p6e[n.status],children:_P[n.status]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"flex -space-x-2",children:[(a=n.items)==null?void 0:a.slice(0,3).map((o,c)=>e.jsxs("div",{className:"w-10 h-10 bg-muted rounded border-2 border-background flex items-center justify-center text-xs font-medium",style:{zIndex:3-c},children:[o.quantity,"×"]},o.id)),n.items&&n.items.length>3&&e.jsxs("div",{className:"w-10 h-10 bg-muted rounded border-2 border-background flex items-center justify-center text-xs font-medium",children:["+",n.items.length-3]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm",children:((i=n.items)==null?void 0:i.length)===1?n.items[0].product_name:`${(l=n.items)==null?void 0:l.length} items`}),e.jsxs("p",{className:"font-semibold",children:["$",Number(n.total).toFixed(2)]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[n.tracking_url&&e.jsxs(H,{variant:"outline",size:"sm",onClick:o=>{o.stopPropagation(),window.open(n.tracking_url,"_blank")},children:[e.jsx(gn,{className:"h-4 w-4 mr-1"}),"Track"]}),e.jsx($a,{className:"h-5 w-5 text-muted-foreground"})]})]})]})},n.id)})})})}const RWe=["order_submitted","awaiting_proof_approval","proof_approved","processing","in_production","shipped","completed"];function y$s({currentStatus:s,statusHistory:t}){const r=RWe.indexOf(s);return e.jsx("div",{className:"space-y-3",children:RWe.map((n,a)=>{const i=t==null?void 0:t.find(d=>d.status===n),l=ar;return e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:`mt-0.5 flex-shrink-0 w-6 h-6 rounded-full flex items-center justify-center ${l?"bg-green-500 text-white":o?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground"}`,children:l?e.jsx(ea,{className:"h-4 w-4"}):o?e.jsx(Pn,{className:"h-4 w-4"}):e.jsx("span",{className:"text-xs",children:a+1})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:`font-medium ${c?"text-muted-foreground":""}`,children:_P[n]}),i&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[As(new Date(i.created_at),"MMM d, yyyy h:mm a"),i.notes&&` — ${i.notes}`]})]})]},n)})})}function v$s(){var j;const{orderId:s}=Po(),t=Fr(),{data:r,isLoading:n,refetch:a}=_Bs(s||""),i=NBs(),l=kBs(),[o,c]=S.useState(!1),[d,h]=S.useState(null),[m,p]=S.useState(""),[x,y]=S.useState(null),_=async k=>{y(k);try{await i.mutateAsync({orderId:s,itemId:k}),he.success("Proof approved!"),a()}catch{he.error("Failed to approve proof")}finally{y(null)}},b=async()=>{if(d){y(d);try{await l.mutateAsync({orderId:s,itemId:d,reason:m}),he.success("Revision requested"),c(!1),p(""),h(null),a()}catch{he.error("Failed to request revision")}finally{y(null)}}};return n?e.jsx(Ss,{title:"Order Details",children:e.jsxs("div",{className:"grid gap-6 lg:grid-cols-3",children:[e.jsxs("div",{className:"lg:col-span-2 space-y-6",children:[e.jsx(Ks,{className:"h-64 w-full"}),e.jsx(Ks,{className:"h-48 w-full"})]}),e.jsx(Ks,{className:"h-96 w-full"})]})}):r?e.jsxs(Ss,{title:`Order ${r.order_number}`,children:[e.jsxs("div",{className:"grid gap-6 lg:grid-cols-3",children:[e.jsxs("div",{className:"lg:col-span-2 space-y-6",children:[e.jsxs(ke,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between",children:[e.jsx(zt,{children:"Order Status"}),e.jsx(Xe,{className:p6e[r.status],children:_P[r.status]})]}),e.jsx(Oe,{children:e.jsx(y$s,{currentStatus:r.status,statusHistory:r.status_history})})]}),e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsx(zt,{children:"Items"})}),e.jsx(Oe,{className:"space-y-4",children:(j=r.items)==null?void 0:j.map(k=>e.jsxs("div",{className:"border rounded-lg p-4",children:[e.jsxs("div",{className:"flex justify-between items-start mb-3",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"font-semibold",children:k.product_name}),k.variant_name&&e.jsx("p",{className:"text-sm text-muted-foreground",children:k.variant_name}),e.jsxs("p",{className:"text-sm",children:["Qty: ",k.quantity," × $",Number(k.unit_price).toFixed(2)]})]}),e.jsxs("p",{className:"font-semibold",children:["$",(Number(k.unit_price)*k.quantity).toFixed(2)]})]}),k.artwork_url&&e.jsxs("div",{className:"mb-3",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:"Your Artwork:"}),e.jsxs("a",{href:k.artwork_url,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-2 text-primary hover:underline",children:[e.jsx(z2,{className:"h-4 w-4"}),"View Artwork",e.jsx(gn,{className:"h-3 w-3"})]})]}),k.proof_url&&e.jsxs("div",{className:"bg-muted rounded-lg p-3",children:[e.jsx("p",{className:"text-sm font-medium mb-2",children:"Proof Ready for Review"}),e.jsxs("a",{href:k.proof_url,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-2 text-primary hover:underline mb-3",children:[e.jsx(z2,{className:"h-4 w-4"}),"View Proof",e.jsx(gn,{className:"h-3 w-3"})]}),k.proof_status==="pending"&&e.jsxs("div",{className:"flex gap-2 mt-3",children:[e.jsxs(H,{size:"sm",onClick:()=>_(k.id),disabled:x===k.id,children:[x===k.id?e.jsx(is,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(sf,{className:"h-4 w-4 mr-1"}),"Approve"]}),e.jsxs(H,{size:"sm",variant:"outline",onClick:()=>{h(k.id),c(!0)},disabled:x===k.id,children:[e.jsx(DF,{className:"h-4 w-4 mr-1"}),"Request Changes"]})]}),k.proof_status==="approved"&&e.jsxs(Xe,{className:"bg-green-100 text-green-800",children:[e.jsx(ea,{className:"h-3 w-3 mr-1"}),"Proof Approved"]}),k.proof_status==="rejected"&&k.proof_notes&&e.jsxs("div",{className:"mt-2",children:[e.jsx(Xe,{variant:"destructive",className:"mb-2",children:"Revision Requested"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:k.proof_notes})]})]})]},k.id))})]}),r.shipping_name&&e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(OF,{className:"h-5 w-5"}),"Shipping"]})}),e.jsxs(Oe,{children:[e.jsx("p",{className:"font-medium",children:r.shipping_name}),e.jsxs("p",{className:"text-muted-foreground",children:[r.shipping_address,e.jsx("br",{}),r.shipping_city,", ",r.shipping_state," ",r.shipping_zip]}),r.tracking_number&&e.jsxs("div",{className:"mt-4 p-3 bg-muted rounded-lg",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Tracking Number:"}),e.jsx("p",{className:"font-mono font-medium",children:r.tracking_number}),r.tracking_url&&e.jsxs(H,{variant:"link",className:"p-0 h-auto mt-1",onClick:()=>window.open(r.tracking_url,"_blank"),children:["Track Package",e.jsx(gn,{className:"h-3 w-3 ml-1"})]})]})]})]})]}),e.jsx("div",{children:e.jsxs(ke,{className:"sticky top-4",children:[e.jsx(Ot,{children:e.jsx(zt,{children:"Order Summary"})}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:["Placed on ",As(new Date(r.created_at),"MMMM d, yyyy")]}),e.jsx(Qo,{}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{children:"Subtotal"}),e.jsxs("span",{children:["$",Number(r.subtotal).toFixed(2)]})]}),e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{children:"Shipping"}),e.jsxs("span",{children:["$",Number(r.shipping_total).toFixed(2)]})]})]}),e.jsx(Qo,{}),e.jsxs("div",{className:"flex justify-between font-bold text-lg",children:[e.jsx("span",{children:"Total"}),e.jsxs("span",{children:["$",Number(r.total).toFixed(2)]})]}),r.notes&&e.jsxs(e.Fragment,{children:[e.jsx(Qo,{}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium mb-1",children:"Order Notes"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:r.notes})]})]})]})]})})]}),e.jsx(bs,{open:o,onOpenChange:c,children:e.jsxs(vs,{children:[e.jsxs(Cs,{children:[e.jsx(Ns,{children:"Request Changes"}),e.jsx(nn,{children:"Please describe what changes you'd like made to the proof."})]}),e.jsx(vr,{placeholder:"Describe the changes needed...",value:m,onChange:k=>p(k.target.value),rows:4}),e.jsxs(wn,{children:[e.jsx(H,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsxs(H,{onClick:b,disabled:!m.trim()||x!==null,children:[x?e.jsx(is,{className:"h-4 w-4 mr-2 animate-spin"}):null,"Submit Request"]})]})]})})]}):e.jsx(Ss,{title:"Order Not Found",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx(yc,{className:"h-16 w-16 mx-auto text-muted-foreground mb-4"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"Order not found"}),e.jsx(H,{onClick:()=>t("/marketplace/orders"),children:"View All Orders"})]})})}function b$s(){const s=Fr(),[t]=Ed();return t.get("session_id"),S.useEffect(()=>{localStorage.removeItem("marketplace-cart")},[]),e.jsx(Ss,{title:"Order Confirmed",children:e.jsx("div",{className:"max-w-lg mx-auto text-center py-8",children:e.jsx(ke,{children:e.jsxs(Oe,{className:"pt-8 pb-6",children:[e.jsx("div",{className:"w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-6",children:e.jsx(ea,{className:"h-8 w-8 text-green-600"})}),e.jsx("h1",{className:"text-2xl font-bold mb-2",children:"Thank You for Your Order!"}),e.jsx("p",{className:"text-muted-foreground mb-6",children:"Your order has been confirmed and is being processed. You'll receive an email confirmation shortly."}),e.jsxs("div",{className:"bg-muted rounded-lg p-4 mb-6 text-left",children:[e.jsxs("h3",{className:"font-medium mb-2 flex items-center gap-2",children:[e.jsx(yc,{className:"h-4 w-4"}),"What happens next?"]}),e.jsxs("ul",{className:"text-sm text-muted-foreground space-y-2",children:[e.jsx("li",{children:"• We'll review your order and prepare it for production"}),e.jsx("li",{children:"• If your order requires a proof, you'll receive it for approval"}),e.jsx("li",{children:"• Once approved, we'll begin production and ship when ready"}),e.jsx("li",{children:"• You'll receive tracking info when your order ships"})]})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs(H,{className:"flex-1",onClick:()=>s("/marketplace/orders"),children:["View My Orders",e.jsx(bi,{className:"h-4 w-4 ml-2"})]}),e.jsx(H,{variant:"outline",className:"flex-1",onClick:()=>s("/marketplace"),children:"Continue Shopping"})]})]})})})})}function _$s(){const{user:s}=Ms(),[t,r]=S.useState("store"),[n,a]=S.useState(null),[i,l]=S.useState(null),[o,c]=S.useState(!1),[d,h]=S.useState(5),[m,p]=S.useState(""),[x,y]=S.useState(!1),[_,b]=S.useState(!1),[j,k]=S.useState(""),[T,E]=S.useState(null),[A,D]=S.useState(!1),{hasSubmittedReview:R,submitReview:z,markPostedToGoogle:O}=Fit(),{data:$}=evt(),{data:ee,isLoading:Z}=Jyt(),{data:J,isLoading:K}=IBs(n),{data:re,isLoading:ie}=PBs(s==null?void 0:s.id),{data:ce=0}=DBs(s==null?void 0:s.id),ne=RBs(),le=new Set((re==null?void 0:re.map(Le=>Le.item_id))||[]),be=async()=>{if(i)try{const Le=await ne.mutateAsync(i.id);i.item_type==="reelflow_credits"?he.success(`🎬 ${i.max_quantity} ReelFlow credits added to your balance!`):he.success(`Successfully purchased "${i.name}"!`),l(null)}catch(Le){he.error(Le.message||"Failed to purchase item")}},fe=async()=>{if(!m.trim()){he.error("Please write a review");return}y(!0);const Le=await z(d,m);y(!1),Le.success?(he.success("Thank you for your review! You earned 25 points!"),k(m),b(!0),p(""),h(5)):he.error(Le.error||"Failed to submit review")},je=()=>{navigator.clipboard.writeText(j),he.success("Review copied to clipboard!")},ve=()=>{O(),window.open("https://g.page/r/CT8bqTBTm7nJEBM/review","_blank")},We=()=>{b(!1),c(!1),k("")};return Z||K||ie?e.jsx(Ss,{title:"Reward Store",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Ks,{className:"h-24 w-full"}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[1,2,3,4,5,6].map(Le=>e.jsx(Ks,{className:"h-64"},Le))})]})}):e.jsxs(Ss,{title:"Reward Store",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-5xl font-bold text-foreground",children:"Reward Store"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Redeem your points for exclusive rewards"})]}),e.jsx(ke,{className:"bg-gradient-to-r from-primary/10 to-primary/5 border-primary/20",children:e.jsx(Oe,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"h-12 w-12 rounded-full bg-primary/20 flex items-center justify-center",children:e.jsx(ya,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Your Spendable Points"}),e.jsx("p",{className:"text-3xl font-bold text-primary",children:ce.toLocaleString()})]})]}),e.jsxs("div",{className:"flex items-center gap-6 text-sm text-muted-foreground",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(To,{className:"h-4 w-4"}),e.jsx("span",{children:"Earn points by attending events"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(od,{className:"h-4 w-4 text-orange-500"}),e.jsx("span",{children:"Streak bonuses add extra points!"})]})]})]})})}),e.jsx(m0,{open:A,onOpenChange:D,children:e.jsxs(ke,{className:"border-primary/20",children:[e.jsx(f0,{asChild:!0,children:e.jsx(Ot,{className:"cursor-pointer hover:bg-muted/50 transition-colors",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-full bg-primary/10 flex items-center justify-center",children:e.jsx(To,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(zt,{className:"text-base",children:"How to Earn Points"}),e.jsx(Br,{children:"See all the ways you can earn spendable points"})]})]}),A?e.jsx(cx,{className:"h-5 w-5 text-muted-foreground"}):e.jsx(Io,{className:"h-5 w-5 text-muted-foreground"})]})})}),e.jsx(p0,{children:e.jsx(Oe,{className:"pt-0",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3",children:[$==null?void 0:$.filter(Le=>Le.is_active).map(Le=>{const Me=ze=>{switch(ze){case"event_attendance":return e.jsx(Nn,{className:"h-5 w-5"});case"leave_review":return e.jsx(ya,{className:"h-5 w-5"});case"add_listing":return e.jsx(Fn,{className:"h-5 w-5"});case"first_contact":return e.jsx(Ar,{className:"h-5 w-5"});case"first_video":return e.jsx(xn,{className:"h-5 w-5"});case"first_community_post":return e.jsx(Gi,{className:"h-5 w-5"});default:return e.jsx(Di,{className:"h-5 w-5"})}};return e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg bg-muted/50 border",children:[e.jsx("div",{className:"h-10 w-10 rounded-full bg-primary/10 flex items-center justify-center text-primary shrink-0",children:Me(Le.action_key)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm",children:Le.action_name}),Le.description&&e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:Le.description})]}),e.jsxs(Xe,{variant:"secondary",className:"font-bold shrink-0",children:["+",Le.points]})]},Le.id)}),e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg bg-orange-500/10 border border-orange-500/20",children:[e.jsx("div",{className:"h-10 w-10 rounded-full bg-orange-500/20 flex items-center justify-center text-orange-500 shrink-0",children:e.jsx(od,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm",children:"Streak Bonuses"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Attend consecutive weeks for bonus points!"})]}),e.jsx(Xe,{variant:"outline",className:"font-bold shrink-0 border-orange-500/50 text-orange-600",children:"+Bonus"})]})]})})})]})}),!R&&e.jsx(ke,{className:"bg-gradient-to-r from-yellow-500/10 to-orange-500/10 border-yellow-500/20",children:e.jsx(Oe,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"h-12 w-12 rounded-full bg-yellow-500/20 flex items-center justify-center",children:e.jsx(Gi,{className:"h-6 w-6 text-yellow-600"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Earn 25 Free Points!"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Leave a quick review and earn 25 spendable points"})]})]}),e.jsxs(H,{onClick:()=>c(!0),className:"bg-yellow-600 hover:bg-yellow-700",children:[e.jsx(ya,{className:"h-4 w-4 mr-2"}),"Leave Review"]})]})})}),e.jsxs(ta,{value:t,onValueChange:r,children:[e.jsxs(Qn,{children:[e.jsxs(ts,{value:"store",className:"flex items-center gap-2",children:[e.jsx(b_,{className:"h-4 w-4"}),"Store"]}),e.jsxs(ts,{value:"my-rewards",className:"flex items-center gap-2",children:[e.jsx(yc,{className:"h-4 w-4"}),"My Rewards",re&&re.length>0&&e.jsx(Xe,{variant:"secondary",className:"ml-1",children:re.length})]})]}),e.jsxs(cs,{value:"store",className:"mt-6",children:[ee&&ee.length>0&&e.jsxs("div",{className:"flex flex-wrap gap-2 mb-6",children:[e.jsx(H,{variant:n===null?"default":"outline",size:"sm",onClick:()=>a(null),children:"All"}),ee.map(Le=>e.jsxs(H,{variant:n===Le.id?"default":"outline",size:"sm",onClick:()=>a(Le.id),children:[Le.icon&&`${Le.icon} `,Le.name]},Le.id))]}),!J||J.length===0?e.jsx(ke,{children:e.jsx(Oe,{className:"py-12",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(Di,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{className:"font-medium",children:"No items available"}),e.jsx("p",{className:"text-sm",children:"Check back later for new rewards!"})]})})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:J.map(Le=>{const Me=Le.item_type==="reelflow_credits",ze=!Me&&le.has(Le.id),Pe=!Me&&Le.max_quantity!==null&&Le.current_quantity===0,Ie=ce>=Le.points_cost;return e.jsxs(ke,{className:`overflow-hidden transition-all cursor-pointer hover:shadow-lg ${ze?"ring-2 ring-green-500/50 bg-green-500/5":""}`,onClick:()=>E(Le),children:[Le.preview_image_url?e.jsxs("div",{className:"aspect-video relative overflow-hidden bg-muted",children:[e.jsx("img",{src:Le.preview_image_url,alt:Le.name,className:"w-full h-full object-cover"}),ze&&e.jsx("div",{className:"absolute top-2 right-2",children:e.jsxs(Xe,{className:"bg-green-500 text-white",children:[e.jsx(ea,{className:"h-3 w-3 mr-1"}),"Owned"]})}),Pe&&!ze&&e.jsx("div",{className:"absolute inset-0 bg-black/50 flex items-center justify-center",children:e.jsx(Xe,{variant:"destructive",children:"Sold Out"})})]}):e.jsxs("div",{className:"aspect-video bg-muted flex items-center justify-center relative",children:[e.jsx(Di,{className:"h-12 w-12 text-muted-foreground/50"}),ze&&e.jsx("div",{className:"absolute top-2 right-2",children:e.jsxs(Xe,{className:"bg-green-500 text-white",children:[e.jsx(ea,{className:"h-3 w-3 mr-1"}),"Owned"]})})]}),e.jsxs(Ot,{className:"pb-2",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsx(zt,{className:"text-lg",children:Le.name}),e.jsxs(Xe,{variant:"secondary",className:"font-bold shrink-0",children:[e.jsx(ya,{className:"h-3 w-3 mr-1"}),Le.points_cost]})]}),Le.category&&e.jsxs(Xe,{variant:"outline",className:"w-fit",children:[Le.category.icon&&`${Le.category.icon} `,Le.category.name]})]}),e.jsxs(Oe,{children:[e.jsx(Br,{className:"mb-4 line-clamp-2",children:Le.description||"No description available"}),Le.max_quantity!==null&&!ze&&!Me&&e.jsxs("p",{className:"text-xs text-muted-foreground mb-3",children:[Le.current_quantity," of ",Le.max_quantity," remaining"]}),Me&&e.jsxs("p",{className:"text-xs text-violet-600 font-medium mb-3",children:["🎬 Grants ",Le.max_quantity," ReelFlow credits per purchase"]}),ze?e.jsx(H,{className:"w-full",onClick:De=>{De.stopPropagation(),Le.file_url&&Ewe(Le.file_url,Le.name)},disabled:!Le.file_url,children:Le.item_type==="file"?e.jsxs(e.Fragment,{children:[e.jsx(hi,{className:"h-4 w-4 mr-2"}),"Download"]}):e.jsxs(e.Fragment,{children:[e.jsx(gn,{className:"h-4 w-4 mr-2"}),"Access"]})}):e.jsx(H,{className:"w-full",onClick:De=>{De.stopPropagation(),l(Le)},disabled:Pe||!Ie,children:Pe?"Sold Out":Ie?e.jsxs(e.Fragment,{children:[e.jsx(b_,{className:"h-4 w-4 mr-2"}),"Purchase"]}):`Need ${Le.points_cost-ce} more pts`})]})]},Le.id)})})]}),e.jsx(cs,{value:"my-rewards",className:"mt-6",children:!re||re.length===0?e.jsx(ke,{children:e.jsx(Oe,{className:"py-12",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(yc,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{className:"font-medium",children:"No rewards yet"}),e.jsx("p",{className:"text-sm",children:"Purchase items from the store to see them here!"})]})})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:re.map(Le=>{var Me,ze,Pe,Ie,De,pe,tt;return e.jsxs(ke,{className:"overflow-hidden",children:[(Me=Le.item)!=null&&Me.preview_image_url?e.jsx("div",{className:"aspect-video relative overflow-hidden bg-muted",children:e.jsx("img",{src:Le.item.preview_image_url,alt:((ze=Le.item)==null?void 0:ze.name)||"Reward",className:"w-full h-full object-cover"})}):e.jsx("div",{className:"aspect-video bg-muted flex items-center justify-center",children:e.jsx(Di,{className:"h-12 w-12 text-muted-foreground/50"})}),e.jsxs(Ot,{className:"pb-2",children:[e.jsx(zt,{className:"text-lg",children:((Pe=Le.item)==null?void 0:Pe.name)||"Unknown Item"}),e.jsxs(Br,{className:"text-xs",children:["Purchased for ",Le.points_spent," points • ",new Date(Le.purchased_at).toLocaleDateString()]})]}),e.jsx(Oe,{children:((Ie=Le.item)==null?void 0:Ie.item_type)==="reelflow_credits"?e.jsxs(H,{className:"w-full",variant:"outline",disabled:!0,children:[e.jsx(ea,{className:"h-4 w-4 mr-2 text-green-500"}),(De=Le.item)==null?void 0:De.max_quantity," Credits Applied"]}):e.jsx(H,{className:"w-full",onClick:()=>{var ge,ct;(ge=Le.item)!=null&&ge.file_url&&Ewe(Le.item.file_url,(ct=Le.item)==null?void 0:ct.name)},disabled:!((pe=Le.item)!=null&&pe.file_url),children:((tt=Le.item)==null?void 0:tt.item_type)==="file"?e.jsxs(e.Fragment,{children:[e.jsx(hi,{className:"h-4 w-4 mr-2"}),"Download"]}):e.jsxs(e.Fragment,{children:[e.jsx(gn,{className:"h-4 w-4 mr-2"}),"Access"]})})})]},Le.id)})})})]})]}),e.jsx(Rl,{open:!!i,onOpenChange:()=>l(null),children:e.jsxs(jl,{children:[e.jsxs(Nl,{children:[e.jsx(Sl,{children:"Confirm Purchase"}),e.jsxs(Cl,{children:['Are you sure you want to purchase "',i==null?void 0:i.name,'" for ',i==null?void 0:i.points_cost," points?",(i==null?void 0:i.item_type)==="reelflow_credits"&&e.jsxs(e.Fragment,{children:[e.jsx("br",{}),e.jsx("br",{}),"🎬 ",e.jsxs("strong",{children:[i==null?void 0:i.max_quantity," ReelFlow credits"]})," will be added to your balance instantly."]}),e.jsx("br",{}),e.jsx("br",{}),"You currently have ",e.jsxs("strong",{children:[ce," points"]}),". After this purchase, you'll have"," ",e.jsxs("strong",{children:[ce-((i==null?void 0:i.points_cost)||0)," points"]})," remaining."]})]}),e.jsxs(kl,{children:[e.jsx(Tl,{children:"Cancel"}),e.jsx(ml,{onClick:be,disabled:ne.isPending,children:ne.isPending?"Purchasing...":"Confirm Purchase"})]})]})}),e.jsx(bs,{open:o,onOpenChange:Le=>{!Le&&_?We():c(Le)},children:e.jsx(vs,{children:_?e.jsxs(e.Fragment,{children:[e.jsxs(Cs,{children:[e.jsxs(Ns,{className:"flex items-center gap-2",children:[e.jsx(ea,{className:"h-5 w-5 text-green-500"}),"Thank You for Your Review!"]}),e.jsx(nn,{children:"Would you also share your review on Google? It helps other agents discover LevelUp!"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"bg-muted p-4 rounded-lg",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:"Your review:"}),e.jsxs("p",{className:"text-sm italic",children:['"',j,'"']})]}),e.jsxs(H,{variant:"outline",className:"w-full",onClick:je,children:[e.jsx(ui,{className:"h-4 w-4 mr-2"}),"Copy Review to Clipboard"]})]}),e.jsxs(wn,{className:"flex-col sm:flex-row gap-2",children:[e.jsx(H,{variant:"outline",onClick:We,children:"Maybe Later"}),e.jsxs(H,{onClick:ve,className:"bg-blue-600 hover:bg-blue-700",children:[e.jsx(gn,{className:"h-4 w-4 mr-2"}),"Leave Google Review"]})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(Cs,{children:[e.jsx(Ns,{children:"Leave a Review"}),e.jsx(nn,{children:"Share your experience with LevelUp and earn 25 spendable points!"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium mb-2 block",children:"Your Rating"}),e.jsx("div",{className:"flex gap-1",children:[1,2,3,4,5].map(Le=>e.jsx("button",{type:"button",onClick:()=>h(Le),className:"focus:outline-none",children:e.jsx(ya,{className:`h-8 w-8 transition-colors ${d>=Le?"fill-yellow-400 text-yellow-400":"text-muted-foreground hover:text-yellow-400"}`})},Le))})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium mb-2 block",children:"Your Review"}),e.jsx(vr,{placeholder:"What do you love about LevelUp? How has it helped your business?",value:m,onChange:Le=>p(Le.target.value),rows:4})]})]}),e.jsxs(wn,{children:[e.jsx(H,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsx(H,{onClick:fe,disabled:x,className:"bg-yellow-600 hover:bg-yellow-700",children:x?"Submitting...":"Submit & Earn 25 Points"})]})]})})}),e.jsx(bs,{open:!!T,onOpenChange:()=>E(null),children:e.jsxs(vs,{className:"max-w-lg",children:[e.jsxs(Cs,{children:[e.jsxs(Ns,{className:"flex items-center gap-2",children:[T==null?void 0:T.name,e.jsxs(Xe,{variant:"secondary",className:"font-bold",children:[e.jsx(ya,{className:"h-3 w-3 mr-1"}),T==null?void 0:T.points_cost]})]}),(T==null?void 0:T.category)&&e.jsxs(Xe,{variant:"outline",className:"w-fit",children:[T.category.icon&&`${T.category.icon} `,T.category.name]})]}),(T==null?void 0:T.preview_image_url)&&e.jsx("div",{className:"aspect-video relative overflow-hidden bg-muted rounded-lg",children:e.jsx("img",{src:T.preview_image_url,alt:T.name,className:"w-full h-full object-cover"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-muted-foreground",children:(T==null?void 0:T.description)||"No description available"}),(T==null?void 0:T.item_type)==="reelflow_credits"&&e.jsxs("p",{className:"text-sm text-violet-600 font-medium",children:["🎬 Grants ",T==null?void 0:T.max_quantity," ReelFlow credits per purchase"]}),(T==null?void 0:T.item_type)!=="reelflow_credits"&&(T==null?void 0:T.max_quantity)!==null&&!le.has((T==null?void 0:T.id)||"")&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:[T==null?void 0:T.current_quantity," of ",T==null?void 0:T.max_quantity," remaining"]})]}),e.jsx(wn,{children:T&&T.item_type!=="reelflow_credits"&&le.has(T.id)?e.jsx(H,{className:"w-full",onClick:()=>{T.file_url&&Ewe(T.file_url,T.name)},disabled:!T.file_url,children:T.item_type==="file"?e.jsxs(e.Fragment,{children:[e.jsx(hi,{className:"h-4 w-4 mr-2"}),"Download"]}):e.jsxs(e.Fragment,{children:[e.jsx(gn,{className:"h-4 w-4 mr-2"}),"Access"]})}):T&&e.jsx(H,{className:"w-full",onClick:()=>{E(null),l(T)},disabled:T.item_type!=="reelflow_credits"&&T.max_quantity!==null&&T.current_quantity===0||ce{s&&ie()},[s==null?void 0:s.id]);const ie=async()=>{if(!s)return;o(!0),j(!1),_(!0);const{data:De}=await V.from("point_reward_settings").select("action_key, points").in("action_key",["referral_signup","referral_paid"]);De==null||De.forEach(ct=>{ct.action_key==="referral_signup"&&m(ct.points),ct.action_key==="referral_paid"&&x(ct.points)});const{data:pe}=await V.from("profiles").select("name").eq("id",s.id).maybeSingle();pe!=null&&pe.name&&T(pe.name);let{data:tt}=await V.from("agent_referral_codes").select("code").eq("user_id",s.id).maybeSingle();if(!tt){const{data:ct}=await V.rpc("generate_agent_referral_code",{_user_id:s.id}),Ue=ct||`agent${s.id.slice(0,6)}`,{data:et,error:Qe}=await V.from("agent_referral_codes").insert({user_id:s.id,code:Ue}).select("code").maybeSingle();!Qe&&et&&(tt=et)}i((tt==null?void 0:tt.code)??null);const{data:ge}=await V.from("agent_referrals").select("id, referred_user_id, status, signed_up_at, qualified_at, signup_points_awarded, paid_points_awarded").eq("referrer_user_id",s.id).order("signed_up_at",{ascending:!1});if(ge&&ge.length>0){const ct=ge.map(Qe=>Qe.referred_user_id),{data:Ue}=await V.from("profiles").select("id, name, email").in("id",ct),et=new Map((Ue==null?void 0:Ue.map(Qe=>[Qe.id,Qe]))??[]);d(ge.map(Qe=>({...Qe,referred_profile:et.get(Qe.referred_user_id)??null})))}else d([]);o(!1)},ce=S.useMemo(()=>a?`${w$s}/trial?ref=${a}`:"",[a]),ne=c.length,le=c.filter(De=>De.status==="qualified").length,be=c.filter(De=>De.signup_points_awarded).length*h+c.filter(De=>De.paid_points_awarded).length*p,fe=async()=>{ce&&(await navigator.clipboard.writeText(ce),he.success("Referral link copied!"))},je=()=>{const De=encodeURIComponent("Join me on LevelUp"),pe=encodeURIComponent(`Hi — I've been using LevelUp to grow my real estate business and thought you'd love it too. Sign up using my link and we'll both get a head start: ${ce} Let me know if you have any questions!`);window.location.href=`mailto:?subject=${De}&body=${pe}`},ve=()=>{const De=encodeURIComponent(`Hey! I think you'd love LevelUp for your business — sign up with my link: ${ce}`);window.location.href=`sms:?&body=${De}`},We=async()=>{if(navigator.share&&ce)try{await navigator.share({title:"Join me on LevelUp",text:"I use LevelUp to grow my real estate business — try it with my link:",url:ce})}catch{}else fe()},Ve=De=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(De.trim()),Le=De=>{const pe=(De??D).trim().replace(/,$/,"");if(!pe)return;const tt=pe.split(/[\s,;]+/).filter(Boolean),ge=[...z];let ct=0;for(const Ue of tt){if(!Ve(Ue)){he.error(`Invalid email: ${Ue}`);continue}ge.includes(Ue)||(ge.push(Ue),ct++)}O(ge),ct>0&&R("")},Me=De=>O(z.filter(pe=>pe!==De)),ze=()=>{J(`${k?k.split(" ")[0]+" invited you to":"Join me on"} LevelUp`),ee("I've been using LevelUp to grow my real estate business and it's been a game changer. I think you'd love it too — sign up with my link and we'll both get a head start."),A(!0)},Pe=De=>{const pe=De.replace(/&/g,"&").replace(//g,">").replace(/\n/g,"
"),tt=k||"A fellow agent",ge="https://relzejiswnotikjgvjhz.supabase.co/storage/v1/object/public/email-assets/levelup-logo-email.png",ct=ce;return`
LevelUp
You're Invited

${tt} thinks you'd love LevelUp 🎉

${pe}

What you get
  • AI tools built for real estate agents
  • Lead generation, marketing & CRM in one place
  • Branded lead sites, video tools & more
Start Your Free Trial →

Or copy & paste this link:
${ct}

Sent by ${tt} via LevelUp · relevelup.com

`.trim()},Ie=async()=>{if(z.length===0&&(D.trim()&&Le(),z.length===0)){he.error("Add at least one recipient");return}if(!Z.trim()){he.error("Subject is required");return}re(!0);const De=Pe($);let pe=0,tt=0;for(const ge of z)try{const{data:ct,error:Ue}=await V.functions.invoke("gmail-send",{body:{to:ge,subject:Z,body:De,source:"referral_invite"}});if(Ue||ct!=null&&ct.error)throw new Error((Ue==null?void 0:Ue.message)||(ct==null?void 0:ct.error));pe++}catch(ct){console.error("Gmail send failed for",ge,ct),tt++}re(!1),pe>0?(he.success(`Invite sent to ${pe} ${pe===1?"person":"people"}`+(tt>0?` (${tt} failed)`:"")),O([]),R(""),A(!1)):he.error("Failed to send invites")};return!b&&!y?e.jsx(Ss,{title:"Refer & Earn",children:e.jsxs("div",{className:"container max-w-3xl mx-auto p-4 md:p-8",children:[e.jsx(el,{children:e.jsx("title",{children:"Refer & Earn | LevelUp"})}),e.jsxs(ke,{className:"border-2 border-dashed",children:[e.jsxs(Ot,{className:"text-center",children:[e.jsx("div",{className:"mx-auto h-14 w-14 rounded-full bg-muted flex items-center justify-center mb-3",children:e.jsx(Td,{className:"h-6 w-6 text-muted-foreground"})}),e.jsx(zt,{children:"Refer & Earn is for active members"}),e.jsx(Br,{children:"Activate your subscription to unlock your personal referral link and start earning points."})]}),e.jsx(Oe,{className:"flex justify-center",children:e.jsx(H,{onClick:()=>t("/subscription"),children:"View Subscription"})})]})]})}):e.jsxs(Ss,{title:"Refer & Earn",children:[e.jsxs("div",{className:"container max-w-5xl mx-auto p-4 md:p-8 space-y-6",children:[e.jsxs(el,{children:[e.jsx("title",{children:"Refer & Earn | LevelUp"}),e.jsx("meta",{name:"description",content:"Invite peers to LevelUp and earn points for every agent who joins."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Di,{className:"h-7 w-7 text-primary"}),e.jsx("h1",{className:"text-3xl font-bold tracking-tight",children:"Refer & Earn"})]}),e.jsxs("p",{className:"text-muted-foreground",children:["Share LevelUp with peers, mentees, or fellow agents. Earn"," ",e.jsxs("span",{className:"font-semibold text-foreground",children:[h," points"]})," when they sign up and"," ",e.jsxs("span",{className:"font-semibold text-foreground",children:[p," more"]})," when they activate a paid plan."]})]}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[e.jsx(ke,{children:e.jsxs(Oe,{className:"p-4 flex items-center gap-3",children:[e.jsx(Ar,{className:"h-5 w-5 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold",children:ne}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Friends signed up"})]})]})}),e.jsx(ke,{children:e.jsxs(Oe,{className:"p-4 flex items-center gap-3",children:[e.jsx(ea,{className:"h-5 w-5 text-emerald-600"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold",children:le}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Activated paid plan"})]})]})}),e.jsx(ke,{children:e.jsxs(Oe,{className:"p-4 flex items-center gap-3",children:[e.jsx(To,{className:"h-5 w-5 text-amber-500"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold",children:be.toLocaleString()}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Points earned"})]})]})})]}),e.jsxs(ke,{children:[e.jsxs(Ot,{children:[e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(Lr,{className:"h-5 w-5 text-primary"}),"Your referral link"]}),e.jsx(Br,{children:"Anyone who signs up through this link is credited to you."})]}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2",children:[e.jsx(Se,{readOnly:!0,value:l?"Loading…":ce,className:"font-mono text-sm",onFocus:De=>De.currentTarget.select()}),e.jsxs(H,{onClick:fe,disabled:!ce,children:[e.jsx(ui,{className:"h-4 w-4 mr-2"}),"Copy link"]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[r&&e.jsxs(H,{size:"sm",onClick:ze,disabled:!ce,className:"bg-primary hover:bg-primary/90",children:[e.jsx(yn,{className:"h-4 w-4 mr-2"})," Send via Gmail"]}),e.jsxs(H,{variant:"outline",size:"sm",onClick:je,disabled:!ce,children:[e.jsx(er,{className:"h-4 w-4 mr-2"})," Email"]}),e.jsxs(H,{variant:"outline",size:"sm",onClick:ve,disabled:!ce,children:[e.jsx(Gi,{className:"h-4 w-4 mr-2"})," Text"]}),e.jsxs(H,{variant:"outline",size:"sm",onClick:We,disabled:!ce,children:[e.jsx(cd,{className:"h-4 w-4 mr-2"})," More…"]})]}),!r&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["💡 ",e.jsx("button",{onClick:()=>t("/integrations"),className:"underline hover:text-foreground",children:"Connect Gmail"})," to send branded invite emails directly from your inbox."]}),a&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Your code: ",e.jsx("span",{className:"font-mono font-semibold text-foreground",children:a})]})]})]}),e.jsxs(ke,{children:[e.jsxs(Ot,{children:[e.jsx(zt,{children:"Your Referrals"}),e.jsx(Br,{children:"Track who joined and when they upgrade."})]}),e.jsx(Oe,{children:l?e.jsx("p",{className:"text-sm text-muted-foreground py-6 text-center",children:"Loading…"}):c.length===0?e.jsxs("div",{className:"text-center py-10 space-y-2",children:[e.jsx(Ar,{className:"h-10 w-10 mx-auto text-muted-foreground/50"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No referrals yet. Share your link to get started!"})]}):e.jsx("div",{className:"divide-y",children:c.map(De=>{var ge,ct;const pe=((ge=De.referred_profile)==null?void 0:ge.name)||((ct=De.referred_profile)==null?void 0:ct.email)||"New agent",tt=new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric"}).format(new Date(De.signed_up_at));return e.jsxs("div",{className:"py-3 flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-medium truncate",children:pe}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Joined ",tt]})]}),De.status==="qualified"?e.jsxs(Xe,{className:"bg-emerald-100 text-emerald-700 border-emerald-200 hover:bg-emerald-100",children:[e.jsx(ea,{className:"h-3 w-3 mr-1"})," Paid · +",h+p," pts"]}):e.jsxs(Xe,{variant:"secondary",children:[e.jsx(Pn,{className:"h-3 w-3 mr-1"})," Signed up · +",h," pts"]})]},De.id)})})})]}),e.jsx(ke,{className:"bg-muted/30",children:e.jsxs(Oe,{className:"p-6",children:[e.jsxs("h3",{className:"font-semibold mb-3 flex items-center gap-2",children:[e.jsx(Lr,{className:"h-4 w-4 text-primary"})," How it works"]}),e.jsxs("ol",{className:"text-sm text-muted-foreground space-y-2 list-decimal list-inside",children:[e.jsx("li",{children:"Share your unique link with peers, mentees, or other agents."}),e.jsxs("li",{children:["They sign up — you instantly earn ",e.jsxs("strong",{className:"text-foreground",children:[h," points"]}),"."]}),e.jsxs("li",{children:["When they activate a paid plan, you earn another ",e.jsxs("strong",{className:"text-foreground",children:[p," points"]}),"."]}),e.jsxs("li",{children:["Redeem points in the ",e.jsx("a",{href:"/reward-store",className:"text-primary underline",children:"Reward Store"}),"."]})]})]})}),e.jsx(Qo,{className:"opacity-0"})]}),e.jsx(bs,{open:E,onOpenChange:A,children:e.jsxs(vs,{className:"sm:max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Cs,{children:[e.jsxs(Ns,{className:"flex items-center gap-2",children:[e.jsx(yn,{className:"h-5 w-5 text-primary"})," Send referral invites via Gmail"]}),e.jsxs(nn,{children:["Sending from ",e.jsx("span",{className:"font-medium text-foreground",children:n}),". We'll deliver a branded LevelUp invite with your personal note."]})]}),e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Recipients"}),e.jsxs("div",{className:"flex flex-wrap gap-1.5 p-2 border rounded-md min-h-[44px] bg-background",children:[z.map(De=>e.jsxs(Xe,{variant:"secondary",className:"gap-1 pr-1",children:[De,e.jsx("button",{type:"button",onClick:()=>Me(De),className:"hover:bg-muted-foreground/20 rounded-full p-0.5","aria-label":`Remove ${De}`,children:e.jsx(Rr,{className:"h-3 w-3"})})]},De)),e.jsx("input",{type:"email",value:D,onChange:De=>R(De.target.value),onKeyDown:De=>{De.key==="Enter"||De.key===","||De.key===" "?(De.preventDefault(),Le()):De.key==="Backspace"&&!D&&z.length>0&&O(z.slice(0,-1))},onBlur:()=>D.trim()&&Le(),onPaste:De=>{const pe=De.clipboardData.getData("text");/[\s,;]/.test(pe)&&(De.preventDefault(),Le(pe))},placeholder:z.length===0?"name@example.com, another@example.com":"Add another…",className:"flex-1 min-w-[160px] bg-transparent outline-none text-sm"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Press Enter, comma, or space to add. You can paste multiple emails at once."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"email-subject",children:"Subject"}),e.jsx(Se,{id:"email-subject",value:Z,onChange:De=>J(De.target.value),placeholder:"Subject line"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{htmlFor:"personal-note",children:"Your personal note"}),e.jsx(vr,{id:"personal-note",value:$,onChange:De=>ee(De.target.value),rows:4,placeholder:"Write a quick note explaining why they'd love LevelUp…"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Preview"}),e.jsxs("div",{className:"border rounded-md overflow-hidden bg-muted/30",children:[e.jsxs("div",{className:"px-3 py-2 bg-muted/60 border-b text-xs text-muted-foreground flex items-center justify-between",children:[e.jsxs("span",{className:"truncate",children:["From: ",n]}),e.jsxs("span",{className:"truncate ml-2",children:["Subject: ",Z||"(no subject)"]})]}),e.jsx("iframe",{title:"Email preview",srcDoc:Pe($),className:"w-full h-[420px] bg-white"})]})]})]}),e.jsxs(wn,{children:[e.jsx(H,{variant:"outline",onClick:()=>A(!1),disabled:K,children:"Cancel"}),e.jsxs(H,{onClick:Ie,disabled:K,children:[e.jsx(yn,{className:"h-4 w-4 mr-2"}),K?"Sending…":`Send${z.length>0?` to ${z.length}`:""}`]})]})]})})]})}const Evt=()=>{const{user:s}=Ms(),t=ns(),r=yt({queryKey:["smart-presentations",s==null?void 0:s.id],queryFn:async()=>{const{data:d,error:h}=await V.from("smart_presentations").select("*").eq("owner_user_id",s.id).neq("status","archived").order("created_at",{ascending:!1});if(h)throw h;return d||[]},enabled:!!s}),n=yt({queryKey:["smart-presentation-templates",s==null?void 0:s.id],queryFn:async()=>{const{data:d,error:h}=await V.from("smart_presentation_templates").select("*").eq("is_active",!0).order("created_at",{ascending:!0});if(h)throw h;return d||[]},enabled:!!s}),a=Pt({mutationFn:async d=>{const{data:h,error:m}=await V.from("smart_presentations").insert({owner_user_id:s.id,...d}).select().single();if(m)throw m;return h},onSuccess:()=>{t.invalidateQueries({queryKey:["smart-presentations"]})}}),i=Pt({mutationFn:async({id:d,...h})=>{const{data:m,error:p}=await V.from("smart_presentations").update(h).eq("id",d).select().single();if(p)throw p;return m},onSuccess:()=>{t.invalidateQueries({queryKey:["smart-presentations"]})}}),l=Pt({mutationFn:async d=>{const{data:h,error:m}=await V.from("smart_presentations").update({status:"published",published_at:new Date().toISOString()}).eq("id",d).select().single();if(m)throw m;return h},onSuccess:()=>{t.invalidateQueries({queryKey:["smart-presentations"]}),he.success("Presentation published!")}}),o=Pt({mutationFn:async d=>{const{error:h}=await V.from("smart_presentations").update({status:"archived"}).eq("id",d);if(h)throw h},onSuccess:()=>{t.invalidateQueries({queryKey:["smart-presentations"]}),he.success("Presentation archived")}}),c=Pt({mutationFn:async d=>{const{error:h}=await V.from("smart_presentation_templates").insert({owner_user_id:s.id,name:d.title+" Template",description:"Created from "+d.title,template_type:"custom",icon:"📄",sections:d.sections,cta_config:{type:d.cta_type,label:d.cta_label},is_system:!1});if(h)throw h},onSuccess:()=>{t.invalidateQueries({queryKey:["smart-presentation-templates"]}),he.success("Saved as template!")}});return{presentations:r.data||[],templates:n.data||[],isLoading:r.isLoading,templatesLoading:n.isLoading,createPresentation:a,updatePresentation:i,publishPresentation:l,archivePresentation:o,saveAsTemplate:c}},N$s=()=>{const s=Fr(),{presentations:t,isLoading:r,archivePresentation:n,saveAsTemplate:a}=Evt(),i=o=>o.status==="draft"?e.jsx(Xe,{variant:"outline",className:"text-xs",children:"Draft"}):o.view_count>1?e.jsx(Xe,{className:"text-xs bg-emerald-100 text-emerald-700 border-emerald-200",children:"Revisited"}):o.view_count===1?e.jsx(Xe,{className:"text-xs bg-blue-100 text-blue-700 border-blue-200",children:"Opened"}):e.jsx(Xe,{variant:"secondary",className:"text-xs",children:"Not Opened"}),l=o=>{const c=`https://presentations.relevelup.com/${o}`;navigator.clipboard.writeText(c),he.success("Link copied!")};return e.jsx(Ss,{title:"Smart Presentations",children:e.jsxs("div",{className:"max-w-5xl mx-auto space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("h1",{className:"text-2xl font-serif font-bold text-foreground",children:"Smart Presentations"})}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Create personalized, video-first presentations for your clients"})]}),e.jsxs(H,{onClick:()=>s("/mission-control/presentations/new"),className:"gap-2",children:[e.jsx(Ys,{className:"h-4 w-4"}),"Create Presentation"]})]}),r?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(o=>e.jsx(Ks,{className:"h-20 w-full rounded-lg"},o))}):t.length===0?e.jsx(ke,{children:e.jsxs(Oe,{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx("div",{className:"w-16 h-16 rounded-full bg-primary/10 flex items-center justify-center mb-4",children:e.jsx(_1,{className:"h-8 w-8 text-primary"})}),e.jsx("h3",{className:"text-lg font-semibold mb-2",children:"No presentations yet"}),e.jsx("p",{className:"text-muted-foreground mb-6 max-w-md",children:"Create your first Smart Presentation to impress clients with personalized, video-first content."}),e.jsxs(H,{onClick:()=>s("/mission-control/presentations/new"),className:"gap-2",children:[e.jsx(Ys,{className:"h-4 w-4"}),"Create Your First Presentation"]})]})}):e.jsx("div",{className:"space-y-3",children:t.map(o=>e.jsx(ke,{className:"hover:shadow-sm transition-shadow",children:e.jsx(Oe,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-primary/10 flex items-center justify-center shrink-0",children:e.jsx(kn,{className:"h-5 w-5 text-primary"})}),e.jsx("div",{className:"min-w-0 flex-1",children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-start sm:justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("h3",{className:"font-semibold truncate",children:o.title}),i(o)]}),e.jsxs("div",{className:"flex items-center gap-x-3 gap-y-0.5 flex-wrap text-sm text-muted-foreground mt-0.5",children:[o.client_name&&e.jsx("span",{children:o.client_name}),e.jsxs("span",{children:["Created ",As(new Date(o.created_at),"MMM d, yyyy")]}),o.view_count>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Bn,{className:"h-3 w-3"})," ",o.view_count," view",o.view_count!==1?"s":""]}),o.cta_clicked_count>0&&e.jsx("span",{className:"text-emerald-600 font-medium",children:"CTA clicked"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap sm:flex-nowrap sm:shrink-0",children:[o.status==="published"&&o.share_token&&e.jsxs(H,{variant:"outline",size:"sm",onClick:()=>l(o.share_token),children:[e.jsx(ui,{className:"h-3.5 w-3.5 mr-1"}),"Copy Link"]}),o.status==="published"&&e.jsx(H,{variant:"outline",size:"sm",onClick:()=>s(`/mission-control/presentations/${o.id}?edit=true`),children:"Edit"}),e.jsx(H,{variant:"outline",size:"sm",onClick:()=>s(`/mission-control/presentations/${o.id}`),children:o.status==="draft"?"Edit":"View"}),e.jsxs(Xu,{children:[e.jsx(Qu,{asChild:!0,children:e.jsx(H,{variant:"ghost",size:"icon",className:"h-8 w-8",children:e.jsx(Ay,{className:"h-4 w-4"})})}),e.jsxs(wu,{align:"end",children:[o.status==="published"&&o.share_token&&e.jsxs(di,{onClick:()=>window.open(`https://presentations.relevelup.com/${o.share_token}`,"_blank"),children:[e.jsx(gn,{className:"h-4 w-4 mr-2"}),"Preview Link"]}),e.jsxs(di,{onClick:()=>a.mutate(o),children:[e.jsx(kn,{className:"h-4 w-4 mr-2"}),"Save as Template"]}),e.jsxs(di,{onClick:()=>n.mutate(o.id),className:"text-destructive",children:[e.jsx(Rk,{className:"h-4 w-4 mr-2"}),"Archive"]})]})]})]})]})})]})})},o.id))})]})})},OWe={Welcome:[{label:"Warm & Personal",text:"Hey there! I'm so glad you're here. I put this presentation together just for you because I truly believe we'd make a great team. Over the next few minutes, I'll walk you through exactly how I can help you achieve your real estate goals. Let's dive in!"},{label:"Professional & Confident",text:"Welcome! Thank you for taking the time to check this out. I've prepared this presentation specifically with your needs in mind. I want to show you what sets me apart, the results I've delivered, and how I plan to make your experience smooth and successful. Let's get started!"}],"About Me":[{label:"Relatable Story",text:"Let me tell you a little about myself. I didn't just fall into real estate — I chose it because I love helping people with one of the biggest decisions of their lives. Every client I work with gets my full attention, my honest advice, and someone who truly has their back from start to finish."},{label:"Results-Focused",text:"Here's what I want you to know about me: I'm not just another agent. I've helped dozens of families find their perfect home and get top dollar for their properties. I stay on top of the market, I communicate constantly, and I don't stop until we hit your goals."}],"Market Update":[{label:"Engaging Overview",text:"Let's talk about what's happening in the market right now. I want you to feel confident and informed, so here's the honest picture. I'll break down the key numbers, what they mean for you, and how we can use current conditions to your advantage. Knowledge is power!"},{label:"Buyer-Focused",text:"The market is always moving, and I want to make sure you're in the best position possible. Here's what the latest data tells us, what opportunities are out there for you, and why timing matters. Let me walk you through it."}],"My Process":[{label:"Step-by-Step",text:"I want you to know exactly what to expect when we work together. My process is simple, clear, and designed to take the stress out of the equation. From our first conversation all the way to closing day, I'll be right there guiding you every step of the way. Here's how it works."},{label:"Client-Centered",text:"One thing my clients always tell me is how easy and stress-free the process was. That's not by accident — I've refined my approach over the years to make sure you always know what's happening, what's next, and that someone's got your back. Let me show you how."}],Testimonials:[{label:"Social Proof",text:"Don't just take my word for it — let me share what some of my past clients have said. These are real people, real experiences, and real results. I'm proud of the relationships I've built and the outcomes we've achieved together."}],Pricing:[{label:"Transparent & Value-Driven",text:"Let's talk about the investment. I believe in being completely transparent about pricing because trust is everything. Here's what you get when you work with me, and why my clients say it's the best decision they made. Let me walk you through it."}],"Call to Action":[{label:"Warm Close",text:"So here's my ask — let's connect! I'd love to hop on a quick call, answer any questions you have, and see how I can help. No pressure, no obligation — just a real conversation about your goals. Click the button below and let's make it happen!"},{label:"Urgency Close",text:"The market waits for no one, and neither should you. Let's get started today! Click the link below to schedule a quick chat. I promise — this could be the best 15 minutes you invest in your real estate journey."}]},k$s=[{label:"Engaging Introduction",text:"In this section, I want to share something important with you. I've put real thought into this, and I think you'll find it valuable. Let me walk you through what I've prepared — I'm excited for you to see it!"},{label:"Keep It Simple",text:"Let me keep this short and sweet. Here's what you need to know, and why it matters for you. I'm always about giving you the real picture — no fluff, just the facts and my honest take."}];function S$s(s){const t=OWe[s];if(t)return t;const r=s.toLowerCase();for(const[n,a]of Object.entries(OWe))if(r.includes(n.toLowerCase())||n.toLowerCase().includes(r))return a;return k$s}function C$s({sectionTitle:s,contactId:t,onVideoReady:r}){const[n,a]=S.useState(!1),[i,l]=S.useState("script"),[o,c]=S.useState(0),[d,h]=S.useState(0),{canRecord:m}=Wgt(),p=Cj(),[x,y]=S.useState(""),[_,b]=S.useState(!1),[j,k]=S.useState(!0),[T,E]=S.useState(!1),[A,D]=S.useState(null),R=S$s(s),z=()=>{l("script"),c(0),h(0),y(""),b(!1),k(!0),E(!1),D(null)},O=K=>{!K&&(i==="uploading"||i==="processing")||(a(K),K||z())},$=K=>{D(K),y(R[K].text),b(!1)},ee=()=>{l("record"),k(x.trim().length>0)},Z=()=>{y(""),k(!1),l("record")},J=S.useCallback(async(K,re)=>{l("uploading");try{const ie=s||"Presentation Video",{videoId:ce,uploadUrl:ne,libraryId:le}=await tM(ie),{apiKey:be}=await sM(ce),fe=new XMLHttpRequest;fe.upload.onprogress=Le=>{Le.lengthComputable&&c(Le.loaded/Le.total*100)},await new Promise((Le,Me)=>{fe.onload=()=>fe.status>=200&&fe.status<300?Le():Me(new Error("Upload failed")),fe.onerror=()=>Me(new Error("Upload failed")),fe.open("PUT",ne),fe.setRequestHeader("AccessKey",be),fe.send(K)}),l("processing");let je=0;const ve=Date.now(),We=9e4;let Ve=null;for(;je<4;){if(await new Promise(Me=>setTimeout(Me,3e3)),Date.now()-ve>We){const Me=K.size/1048576,ze=`https://iframe.mediadelivery.net/embed/${le}/${ce}?responsive=true`;await p.mutateAsync({bunny_video_id:ce,playback_url:ze,file_size_mb:Me,title:ie,contact_id:t||void 0,status:"processing",touch_type:"presentation"}),r(ze),he.success("Video saved — still encoding. It will be ready shortly."),l("done"),setTimeout(()=>a(!1),1500);return}const Le=await F_(ce);if(je=Le.status,h(Le.encodeProgress||0),je===4)Ve={playbackUrl:Le.directPlayUrl,thumbnailUrl:Le.thumbnailUrl,previewUrl:Le.previewUrl||null,duration:Le.length||re,fileSizeMb:(Le.storageSize||K.size)/(1024*1024)};else if(je===5||je===6)throw new Error("Video processing failed")}if(!Ve)throw new Error("No video data");await p.mutateAsync({bunny_video_id:ce,contact_id:t||void 0,playback_url:Ve.playbackUrl,thumbnail_url:Ve.thumbnailUrl,preview_url:Ve.previewUrl,duration_seconds:Ve.duration,file_size_mb:Ve.fileSizeMb,title:ie,status:"ready",touch_type:"presentation"}),r(Ve.playbackUrl),he.success("Video recorded, saved to library & attached!"),l("done"),setTimeout(()=>a(!1),1500)}catch(ie){console.error("Recording upload error:",ie),he.error("Failed to process video. Please try again."),l("record")}},[s,t,r,p]);return e.jsxs(bs,{open:n,onOpenChange:O,children:[e.jsx(Qi,{asChild:!0,children:e.jsxs(H,{variant:"outline",size:"sm",className:"gap-1.5 shrink-0",title:"Record a video",children:[e.jsx(xn,{className:"h-3.5 w-3.5"}),"Record"]})}),e.jsxs(vs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto !top-[5%] !translate-y-0 sm:!top-[5%] sm:!translate-y-0",children:[e.jsx(Cs,{children:e.jsxs(Ns,{children:[i==="script"&&`Prepare your script for "${s}"`,i==="record"&&`Record video for "${s}"`,i==="uploading"&&"Uploading...",i==="processing"&&"Processing...",i==="done"&&"Done!"]})}),i==="script"&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Choose a starter script below, edit it to make it yours, or skip and speak freely."}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"Starter Scripts"}),e.jsx("div",{className:"grid gap-2",children:R.map((K,re)=>e.jsxs("button",{onClick:()=>$(re),className:Ft("text-left p-3 rounded-lg border transition-all hover:bg-accent/50",A===re?"border-primary bg-primary/5 ring-1 ring-primary":"border-border"),children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(kn,{className:"h-3.5 w-3.5 text-primary shrink-0"}),e.jsx("span",{className:"text-sm font-medium",children:K.label})]}),e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 ml-5.5",children:K.text})]},re))})]}),x&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"Your Script"}),!_&&e.jsxs(H,{variant:"ghost",size:"sm",onClick:()=>b(!0),className:"h-7 text-xs gap-1",children:[e.jsx(ni,{className:"h-3 w-3"}),"Edit"]})]}),_?e.jsx(vr,{value:x,onChange:K=>y(K.target.value),rows:5,placeholder:"Type your script here...",className:"text-sm"}):e.jsx("div",{className:"p-3 rounded-lg bg-muted/50 text-sm text-foreground leading-relaxed",children:x})]}),!x&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"Or Write Your Own"}),e.jsx(vr,{value:x,onChange:K=>{y(K.target.value),D(null)},rows:4,placeholder:"Type your own script here...",className:"text-sm"})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2",children:[e.jsx(H,{variant:"ghost",size:"sm",onClick:Z,className:"text-muted-foreground",children:"Skip — no teleprompter"}),e.jsx(H,{onClick:ee,disabled:!1,children:x.trim()?"Continue with Script":"Continue Without Script"})]})]}),!m&&i==="record"?e.jsxs("div",{className:"flex flex-col items-center gap-3 py-8 text-center",children:[e.jsx(uu,{className:"h-10 w-10 text-destructive"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"You've reached your video storage limit. Delete some videos to free up space."})]}):i==="record"?e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Record up to 5 minutes. Saved to your library & auto-attached."}),x.trim()&&e.jsxs(H,{variant:"ghost",size:"sm",onClick:()=>k(!j),className:"h-7 text-xs gap-1",children:[j?e.jsx($f,{className:"h-3 w-3"}):e.jsx(Bn,{className:"h-3 w-3"}),j?"Hide Script":"Show Script"]})]}),e.jsx(aD,{maxDurationSeconds:600,onRecordingComplete:J,onRecordingStateChange:E,onError:K=>he.error(K),teleprompterContent:x.trim()?e.jsx(c6e,{text:x,isVisible:j,onToggleVisibility:()=>k(!j),isRecording:T,startCountdown:!1}):void 0}),e.jsx(H,{variant:"ghost",size:"sm",onClick:()=>l("script"),className:"text-xs text-muted-foreground",children:"← Back to script"})]}):i==="uploading"?e.jsxs("div",{className:"flex flex-col items-center gap-4 py-12",children:[e.jsx(is,{className:"h-10 w-10 animate-spin text-primary"}),e.jsxs("div",{className:"w-full max-w-xs space-y-2",children:[e.jsx(Mi,{value:o,className:"h-2"}),e.jsxs("p",{className:"text-sm text-muted-foreground text-center",children:["Uploading... ",Math.round(o),"%"]})]})]}):i==="processing"?e.jsxs("div",{className:"flex flex-col items-center gap-4 py-12",children:[e.jsx(is,{className:"h-10 w-10 animate-spin text-primary"}),e.jsxs("div",{className:"w-full max-w-xs space-y-2",children:[e.jsx(Mi,{value:d,className:"h-2"}),e.jsxs("p",{className:"text-sm text-muted-foreground text-center",children:["Processing... ",Math.round(d),"%"]}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:"This usually takes less than a minute"})]})]}):i==="done"?e.jsxs("div",{className:"flex flex-col items-center gap-3 py-12",children:[e.jsx(zi,{className:"h-12 w-12 text-emerald-500"}),e.jsx("p",{className:"text-sm font-medium text-foreground",children:"Video attached!"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Saved to your video library"})]}):null]})]})}function T$s({sectionTitle:s,contactId:t,onVideoReady:r}){const[n,a]=S.useState(!1),[i,l]=S.useState(null),[o,c]=S.useState("idle"),[d,h]=S.useState(0),m=S.useRef(null),p=Cj(),{data:x}=O0e(),y=(x==null?void 0:x.total_storage_mb)||0,b=((x==null?void 0:x.max_storage_mb)||1024)-y,j=()=>{l(null),c("idle"),h(0)},k=R=>{!R&&o!=="idle"&&o!=="done"||(a(R),R||j())},T=R=>{var $;const z=($=R.target.files)==null?void 0:$[0];if(!z)return;if(!z.type.startsWith("video/")){he.error("Please select a video file");return}const O=z.size/(1024*1024);if(O>500){he.error("Video file must be less than 500MB");return}if(O>b){he.error(`Not enough storage. You have ${b.toFixed(1)} MB remaining.`);return}l(z)},E=S.useCallback(async()=>{if(i){c("creating"),h(0);try{const R=s||i.name,{data:z,error:O}=await V.functions.invoke("bunny-upload",{body:{action:"create",title:R,isAgentVideo:!0}});if(O)throw new Error(O.message);const{videoId:$,libraryId:ee}=z;c("uploading");const{data:Z,error:J}=await V.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:$,isAgentVideo:!0}});if(J)throw new Error(J.message);await new Promise((ie,ce)=>{const ne=new XMLHttpRequest;ne.upload.addEventListener("progress",le=>{le.lengthComputable&&h(Math.round(le.loaded/le.total*100))}),ne.addEventListener("load",()=>ne.status>=200&&ne.status<300?ie():ce(new Error(`Upload failed (${ne.status})`))),ne.addEventListener("error",()=>ce(new Error("Upload failed"))),ne.open("PUT",Z.uploadUrl),ne.setRequestHeader("AccessKey",Z.apiKey),ne.send(i)}),c("processing");const K=i.size/(1024*1024),re=`https://iframe.mediadelivery.net/embed/${ee}/${$}`;await p.mutateAsync({bunny_video_id:$,playback_url:re,file_size_mb:K,title:R,contact_id:t||void 0,status:"processing",touch_type:"presentation"}),r(re),c("done"),he.success("Video uploaded & attached to section!"),setTimeout(()=>a(!1),1200)}catch(R){console.error("Upload error:",R),he.error(R instanceof Error?R.message:"Failed to upload video"),c("idle")}}},[i,s,t,r,p]),A=()=>{switch(o){case"creating":return"Preparing upload...";case"uploading":return`Uploading... ${d}%`;case"processing":return"Saving video...";case"done":return"Done!";default:return""}},D=o!=="idle"&&o!=="done";return e.jsxs(bs,{open:n,onOpenChange:k,children:[e.jsx(Qi,{asChild:!0,children:e.jsxs(H,{variant:"outline",size:"sm",className:"gap-1.5 shrink-0",title:"Upload a video file",children:[e.jsx(Ea,{className:"h-3.5 w-3.5"}),"Upload"]})}),e.jsxs(vs,{className:"sm:max-w-md",children:[e.jsx(Cs,{children:e.jsxs(Ns,{children:['Upload Video for "',s,'"']})}),e.jsxs("div",{className:"space-y-4 py-2",children:[i?e.jsxs("div",{className:"flex items-center gap-3 p-3 bg-muted rounded-lg",children:[e.jsx(xn,{className:"h-8 w-8 text-primary flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:i.name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(i.size/(1024*1024)).toFixed(1)," MB"]})]}),!D&&e.jsx(H,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>l(null),children:e.jsx(Rr,{className:"h-4 w-4"})})]}):e.jsxs("div",{className:"border-2 border-dashed border-muted-foreground/25 rounded-lg p-8 text-center cursor-pointer hover:border-primary/50 transition-colors",onClick:()=>{var R;return(R=m.current)==null?void 0:R.click()},children:[e.jsx(Ea,{className:"h-8 w-8 mx-auto text-muted-foreground mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Click to select a video file"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"MP4, MOV, WebM (max 500MB)"})]}),e.jsx("input",{ref:m,type:"file",accept:"video/*",className:"hidden",onChange:T,disabled:D}),D&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(is,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{children:A()})]}),e.jsx(Mi,{value:o==="uploading"?d:o==="processing"?100:10})]})]}),e.jsxs(wn,{children:[e.jsx(H,{variant:"outline",onClick:()=>k(!1),disabled:D,children:"Cancel"}),e.jsx(H,{onClick:E,disabled:!i||D,children:D?e.jsxs(e.Fragment,{children:[e.jsx(is,{className:"h-4 w-4 mr-2 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ea,{className:"h-4 w-4 mr-2"}),"Upload & Attach"]})})]})]})]})}const FWe=[{value:"schedule_call",label:"Schedule a Call"},{value:"ready_to_list",label:"Ready to List"},{value:"request_pricing",label:"Request Pricing Update"},{value:"sign_agreement",label:"Sign Buyer Agreement"},{value:"text_questions",label:"Text Me Questions"}],BWe=()=>{const s=Fr(),{id:t}=Po(),{user:r}=Ms(),{templates:n,templatesLoading:a,createPresentation:i,updatePresentation:l,publishPresentation:o}=Evt(),{isGmailConnected:c,gmailEmail:d}=cf(),[h,m]=S.useState(!1),[p,x]=S.useState("client"),[y,_]=S.useState(!1),[b,j]=S.useState(""),[k,T]=S.useState([]),[E,A]=S.useState(!1),[D,R]=S.useState(null),[z,O]=S.useState(!1),[$,ee]=S.useState(""),[Z,J]=S.useState(""),[K,re]=S.useState(""),[ie,ce]=S.useState("buyer"),[ne,le]=S.useState(""),[be,fe]=S.useState(null),[je,ve]=S.useState(""),[We,Ve]=S.useState([]),[Le,Me]=S.useState("schedule_call"),[ze,Pe]=S.useState("Schedule a Call"),[Ie,De]=S.useState(""),[pe,tt]=S.useState(""),[ge,ct]=S.useState(null),[Ue,et]=S.useState(t||null),[Qe,Ne]=S.useState(null),[$e,it]=S.useState(!1),Je=async(kt,fs)=>{if(!r)return;const Gs=5*1024*1024;if(kt.size>Gs){he.error("Image must be under 5MB");return}if(!kt.type.startsWith("image/")){he.error("Please upload an image file");return}ct(fs);try{const _s=kt.name.split(".").pop()||"jpg",br=`${r.id}/${Date.now()}.${_s}`,{error:zr}=await V.storage.from("listing-photos").upload(br,kt);if(zr)throw zr;const{data:{publicUrl:Yr}}=V.storage.from("listing-photos").getPublicUrl(br);Et(fs,{image_url:Yr}),he.success("Image uploaded")}catch{he.error("Failed to upload image")}finally{ct(null)}};S.useEffect(()=>{t&&st(t)},[t]);const st=async kt=>{const{data:fs,error:Gs}=await V.from("smart_presentations").select("*").eq("id",kt).single();if(Gs||!fs)return;const _s=fs;if(_(!0),ve(_s.title),ee(_s.client_name||""),le(_s.property_address||""),Ve(_s.sections||[]),Me(_s.cta_type||"schedule_call"),Pe(_s.cta_label||"Schedule a Call"),De(_s.cta_url||""),tt(_s.heading||""),Ne(_s.share_token),it(_s.status==="published"),et(_s.id),x("builder"),_s.contact_id){const{data:br}=await V.from("innercircle_contacts").select("id, first_name, last_name, email, phone").eq("id",_s.contact_id).maybeSingle();br&&(R(br),J(br.email||""),re(br.phone||""))}};S.useEffect(()=>{if(!r||b.length<1){T([]);return}const kt=setTimeout(async()=>{A(!0);const{data:fs}=await V.from("innercircle_contacts").select("id, first_name, last_name, email, phone, lead_source").eq("owner_user_id",r.id).or(`first_name.ilike.%${b}%,last_name.ilike.%${b}%,email.ilike.%${b}%`).limit(10);T(fs||[]),A(!1)},300);return()=>clearTimeout(kt)},[b,r]);const mt=kt=>{R(kt),ee(`${kt.first_name} ${kt.last_name||""}`.trim()),J(kt.email||""),re(kt.phone||""),O(!1)},wt=async()=>{if(!$.trim()){he.error("Client name is required");return}const kt=$.trim().split(" "),fs=kt[0],Gs=kt.slice(1).join(" ")||null,{data:_s,error:br}=await V.from("innercircle_contacts").insert({owner_user_id:r.id,first_name:fs,last_name:Gs,email:Z||null,phone:K||null,lead_source:"Smart Presentation"}).select().single();if(br){he.error("Failed to create client");return}R(_s),he.success("Client created & saved to Agent OS"),x("template")},at=kt=>{fe(kt);const fs=(kt.sections||[]).map(Gs=>({...Gs,is_visible:!0,video_url:"",text:""}));if(Ve(fs),ve(kt.name+($?` for ${$}`:"")),kt.cta_config){const Gs=kt.cta_config;Me(Gs.type||"schedule_call"),Pe(Gs.label||"Schedule a Call")}x("builder")},rt=()=>{Ve([{title:"Welcome",description:"A personal welcome",type:"video",icon:"👋",is_visible:!0}]),ve($?`Presentation for ${$}`:"New Presentation"),x("builder")},Et=(kt,fs)=>{Ve(Gs=>Gs.map((_s,br)=>br===kt?{..._s,...fs}:_s))},hs=kt=>{Et(kt,{is_visible:!We[kt].is_visible})},Is=()=>{Ve(kt=>[...kt,{title:"New Section",description:"",type:"video",icon:"📝",is_visible:!0}])},lr=kt=>{Ve(fs=>fs.filter((Gs,_s)=>_s!==kt))},us=async()=>{if(!je.trim()){he.error("Title is required");return}try{if(Ue){const kt=await l.mutateAsync({id:Ue,title:je,sections:We,client_name:$,property_address:ne||null,cta_type:Le,cta_label:ze,cta_url:Ie||null,heading:pe||null});he.success("Saved")}else{const kt=await i.mutateAsync({title:je,contact_id:(D==null?void 0:D.id)||void 0,client_name:$,property_address:ne||void 0,template_id:(be==null?void 0:be.id)||void 0,sections:We,cta_type:Le,cta_label:ze,cta_url:Ie||void 0,heading:pe||void 0});et(kt.id),Ne(kt.share_token),he.success("Presentation created!")}}catch(kt){console.error("Failed to save presentation:",kt);const fs=(kt==null?void 0:kt.message)||(kt==null?void 0:kt.toString())||"Unknown error";he.error(`Failed to save: ${fs}`)}},St=async()=>{try{await us();const kt=Ue;if(kt){const fs=await o.mutateAsync(kt);Ne(fs.share_token),it(!0),x("share")}}catch(kt){console.error("Failed to publish presentation:",kt),he.error(`Failed to publish: ${(kt==null?void 0:kt.message)||"Unknown error"}`)}},xs=Qe?`https://presentations.relevelup.com/${Qe}`:"";return e.jsx(Ss,{title:"Smart Presentations",children:e.jsxs("div",{className:"max-w-4xl mx-auto space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(H,{variant:"ghost",size:"icon",onClick:()=>s("/mission-control/presentations"),children:e.jsx(za,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-xl font-serif font-bold text-foreground",children:y?"Edit Presentation":"Create Smart Presentation"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[p==="client"&&"Who is this presentation for?",p==="template"&&"Choose a starting template",p==="builder"&&"Customize your presentation",p==="share"&&"Share with your client"]})]})]}),!y&&e.jsx("div",{className:"flex items-center gap-2",children:["client","template","builder","share"].map((kt,fs)=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:Ft("w-8 h-8 rounded-full flex items-center justify-center text-sm font-medium transition-colors",p===kt?"bg-primary text-primary-foreground":fs<["client","template","builder","share"].indexOf(p)?"bg-emerald-100 text-emerald-700":"bg-muted text-muted-foreground"),children:fs<["client","template","builder","share"].indexOf(p)?e.jsx(va,{className:"h-4 w-4"}):fs+1}),e.jsx("span",{className:"text-sm font-medium capitalize hidden sm:inline",children:kt}),fs<3&&e.jsx("div",{className:"w-8 h-px bg-border"})]},kt))}),p==="client"&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs("button",{onClick:()=>{R(null),ee(""),J(""),re(""),O(!1),x("template")},className:"w-full group flex items-center justify-between gap-4 rounded-xl border border-dashed border-primary/30 bg-primary/5 hover:bg-primary/10 transition-all p-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-full bg-primary/10 flex items-center justify-center shrink-0",children:e.jsx(yn,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"font-semibold text-foreground text-sm",children:"Skip — Use as Lead Gen Tool"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"No specific client. Share broadly to capture new leads."})]})]}),e.jsx(bi,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors shrink-0"})]}),e.jsxs("div",{className:"grid gap-6 md:grid-cols-2",children:[e.jsxs(ke,{children:[e.jsx(Ot,{className:"pb-3",children:e.jsxs(zt,{className:"text-base flex items-center gap-2",children:[e.jsx(Mn,{className:"h-4 w-4 text-muted-foreground"}),"Select Existing Client"]})}),e.jsxs(Oe,{className:"space-y-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Mn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Se,{placeholder:"Search by name or email...",value:b,onChange:kt=>j(kt.target.value),className:"pl-10"})]}),e.jsxs("div",{className:"space-y-2 max-h-56 overflow-y-auto",children:[E&&e.jsx(Ks,{className:"h-12 w-full"}),k.map(kt=>e.jsxs("button",{onClick:()=>mt(kt),className:Ft("w-full text-left p-3 rounded-lg border transition-colors",(D==null?void 0:D.id)===kt.id?"border-primary bg-primary/5":"border-border hover:border-primary/50"),children:[e.jsxs("p",{className:"font-medium text-sm",children:[kt.first_name," ",kt.last_name]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:kt.email||kt.phone||"No contact info"})]},kt.id)),!b&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"Start typing to search your contacts"}),b&&k.length===0&&!E&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"No clients found"})]}),D&&e.jsxs(H,{onClick:()=>x("template"),className:"w-full gap-2",children:["Continue with ",D.first_name,e.jsx(bi,{className:"h-4 w-4"})]})]})]}),e.jsxs(ke,{children:[e.jsx(Ot,{className:"pb-3",children:e.jsxs(zt,{className:"text-base flex items-center gap-2",children:[e.jsx(Vl,{className:"h-4 w-4 text-muted-foreground"}),"Add New Client"]})}),e.jsxs(Oe,{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"col-span-2",children:[e.jsx(ue,{className:"text-xs",children:"Name *"}),e.jsx(Se,{value:$,onChange:kt=>{ee(kt.target.value),O(!0),R(null)},placeholder:"Sarah & Mike Johnson"})]}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs",children:"Email"}),e.jsx(Se,{value:Z,onChange:kt=>J(kt.target.value),placeholder:"Optional",type:"email"})]}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs",children:"Phone"}),e.jsx(Se,{value:K,onChange:kt=>re(kt.target.value),placeholder:"Optional"})]}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs",children:"Client Type"}),e.jsxs(Bs,{value:ie,onValueChange:ce,children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"buyer",children:"Buyer"}),e.jsx(pt,{value:"seller",children:"Seller"}),e.jsx(pt,{value:"recruit",children:"Recruit"}),e.jsx(pt,{value:"other",children:"Other"})]})]})]}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs",children:"Property Address"}),e.jsx(Se,{value:ne,onChange:kt=>le(kt.target.value),placeholder:"Optional"})]})]}),z&&$&&e.jsxs(H,{onClick:wt,className:"w-full gap-2",children:["Create Client & Continue",e.jsx(bi,{className:"h-4 w-4"})]})]})]})]})]}),p==="template"&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs(ta,{defaultValue:"system",children:[e.jsxs(Qn,{children:[e.jsx(ts,{value:"mine",children:"My Core Templates"}),e.jsx(ts,{value:"system",children:"LevelUp Smart Templates"}),e.jsx(ts,{value:"blank",children:"+ Start Blank"})]}),e.jsx(cs,{value:"mine",className:"mt-4",children:a?e.jsx("div",{className:"grid grid-cols-2 gap-4",children:[1,2].map(kt=>e.jsx(Ks,{className:"h-32"},kt))}):e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:n.filter(kt=>!kt.is_system).length===0?e.jsx("p",{className:"text-muted-foreground col-span-2 text-center py-8",children:"You haven't saved any templates yet. Create a presentation and save it as a template!"}):n.filter(kt=>!kt.is_system).map(kt=>e.jsx(zWe,{template:kt,onSelect:at},kt.id))})}),e.jsx(cs,{value:"system",className:"mt-4",children:e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:n.filter(kt=>kt.is_system).map(kt=>e.jsx(zWe,{template:kt,onSelect:at},kt.id))})}),e.jsx(cs,{value:"blank",className:"mt-4",children:e.jsx(ke,{children:e.jsxs(Oe,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx("p",{className:"text-muted-foreground mb-4",children:"Start with a blank canvas and add your own sections."}),e.jsx(H,{onClick:rt,children:"Start from Scratch"})]})})})]}),e.jsxs(H,{variant:"outline",onClick:()=>x("client"),className:"gap-2",children:[e.jsx(za,{className:"h-4 w-4"}),"Back"]})]}),p==="builder"&&e.jsxs("div",{className:"space-y-6",children:[e.jsx(ke,{children:e.jsxs(Oe,{className:"pt-6 space-y-4",children:[e.jsxs("div",{children:[e.jsx(ue,{children:"Presentation Title"}),e.jsx(Se,{value:je,onChange:kt=>ve(kt.target.value)})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Page Heading"}),e.jsx(Se,{value:pe,onChange:kt=>tt(kt.target.value),placeholder:$?`Welcome, ${$}!`:"e.g. Welcome! or Your Custom Listing Plan"}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:['The main heading visitors see. Leave blank for "Welcome, ',"",'!"']})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(ue,{children:"Client Name"}),e.jsx(Se,{value:$,onChange:kt=>ee(kt.target.value)})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Property Address"}),e.jsx(Se,{value:ne,onChange:kt=>le(kt.target.value),placeholder:"Optional"})]})]})]})}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Sections"}),e.jsx(H,{variant:"outline",size:"sm",onClick:Is,children:"+ Add Section"})]}),e.jsx("div",{className:"space-y-3",children:We.map((kt,fs)=>e.jsx(ke,{className:Ft(!kt.is_visible&&"opacity-50"),children:e.jsx(Oe,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsxs("div",{className:"flex flex-col items-center gap-1 pt-1",children:[e.jsx(Oh,{className:"h-4 w-4 text-muted-foreground cursor-grab"}),e.jsx("span",{className:"text-lg",children:kt.icon})]}),e.jsxs("div",{className:"flex-1 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Se,{value:kt.title,onChange:Gs=>Et(fs,{title:Gs.target.value}),className:"font-semibold border-none p-0 h-auto text-base focus-visible:ring-0 bg-transparent"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(H,{variant:"ghost",size:"icon",onClick:()=>hs(fs),children:kt.is_visible?e.jsx(Bn,{className:"h-4 w-4"}):e.jsx($f,{className:"h-4 w-4"})}),e.jsx(H,{variant:"ghost",size:"icon",onClick:()=>lr(fs),className:"text-destructive hover:text-destructive",children:e.jsx(Dr,{className:"h-4 w-4"})})]})]}),e.jsx(Se,{value:kt.description||"",onChange:Gs=>Et(fs,{description:Gs.target.value}),placeholder:"Section description...",className:"text-sm"}),e.jsxs("div",{className:"flex items-end gap-2",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx(ue,{className:"text-xs",children:"Video URL"}),e.jsx(Se,{value:kt.video_url||"",onChange:Gs=>Et(fs,{video_url:Gs.target.value}),placeholder:"Paste a YouTube or video URL...",className:"text-sm"})]}),e.jsx(C$s,{sectionTitle:kt.title,contactId:D==null?void 0:D.id,onVideoReady:Gs=>Et(fs,{video_url:Gs})}),e.jsx(T$s,{sectionTitle:kt.title,contactId:D==null?void 0:D.id,onVideoReady:Gs=>Et(fs,{video_url:Gs})}),e.jsx(H8,{userId:r==null?void 0:r.id,onSelect:Gs=>Et(fs,{video_url:Gs})})]}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs",children:"Image (optional — shown if no video is set)"}),kt.image_url?e.jsxs("div",{className:"relative mt-1 rounded-lg overflow-hidden border border-border bg-muted/30 group",children:[e.jsx("img",{src:kt.image_url,alt:"",className:"w-full max-h-40 object-cover"}),e.jsx(H,{variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-7 w-7 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>Et(fs,{image_url:""}),children:e.jsx(Rr,{className:"h-3.5 w-3.5"})})]}):e.jsxs("label",{className:"mt-1 flex items-center gap-2 cursor-pointer rounded-lg border border-dashed border-border hover:border-primary/50 p-3 transition-colors",children:[ge===fs?e.jsx(is,{className:"h-4 w-4 animate-spin text-muted-foreground"}):e.jsx(f_,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:ge===fs?"Uploading...":"Click to upload an image"}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",disabled:ge===fs,onChange:Gs=>{var br;const _s=(br=Gs.target.files)==null?void 0:br[0];_s&&Je(_s,fs),Gs.target.value=""}})]})]}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs",children:"Text (optional)"}),e.jsx(R1,{content:kt.text||"",onChange:Gs=>Et(fs,{text:Gs}),placeholder:"Add supporting text...",minHeight:"80px",compact:!0})]})]})]})})},fs))})]}),e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-base",children:"Call to Action"})}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ue,{children:"CTA Type"}),e.jsxs(Bs,{value:Le,onValueChange:kt=>{Me(kt);const fs=FWe.find(Gs=>Gs.value===kt);fs&&Pe(fs.label)},children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsx(Fs,{children:FWe.map(kt=>e.jsx(pt,{value:kt.value,children:kt.label},kt.value))})]})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Button Label"}),e.jsx(Se,{value:ze,onChange:kt=>Pe(kt.target.value)})]}),e.jsxs("div",{children:[e.jsxs(ue,{children:["Link URL ",e.jsx("span",{className:"text-muted-foreground",children:"(optional — leave blank to show a lead capture form instead)"})]}),e.jsx(Se,{value:Ie,onChange:kt=>De(kt.target.value),placeholder:"https://calendly.com/..."}),!Ie&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Without a URL, clients will see a contact form — their info gets added to your contacts and you'll receive an email notification."})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[!y&&e.jsxs(H,{variant:"outline",onClick:()=>x("template"),className:"gap-2",children:[e.jsx(za,{className:"h-4 w-4"}),"Back"]}),e.jsxs("div",{className:"flex gap-3 ml-auto",children:[e.jsx(H,{variant:"outline",onClick:us,disabled:i.isPending||l.isPending,children:"Save Draft"}),e.jsxs(H,{onClick:St,disabled:o.isPending,className:"gap-2",children:[e.jsx(yn,{className:"h-4 w-4"}),$e?"Update & Reshare":"Publish & Share"]})]})]})]}),p==="share"&&Qe&&e.jsxs("div",{className:"space-y-6",children:[e.jsx(ke,{children:e.jsxs(Oe,{className:"flex flex-col items-center py-12 text-center",children:[e.jsx("div",{className:"w-16 h-16 rounded-full bg-emerald-100 flex items-center justify-center mb-4",children:e.jsx(va,{className:"h-8 w-8 text-emerald-600"})}),e.jsx("h2",{className:"text-xl font-semibold mb-2",children:"Your Presentation is Live!"}),e.jsxs("p",{className:"text-muted-foreground mb-6 max-w-md",children:["Share this link with ",$||"your client",". You'll be notified when they view it."]}),e.jsxs("div",{className:"flex items-center gap-2 w-full max-w-lg",children:[e.jsx(Se,{value:xs,readOnly:!0,className:"text-center font-mono text-sm"}),e.jsx(H,{onClick:()=>{navigator.clipboard.writeText(xs),he.success("Link copied!")},children:e.jsx(ui,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex gap-3 mt-6",children:[e.jsxs(H,{variant:"outline",className:"gap-2",onClick:()=>{const kt=`Hi ${$||""}! I put together something for you — check it out: ${xs}`;navigator.clipboard.writeText(kt),he.success("Message copied!")},children:[e.jsx(Gi,{className:"h-4 w-4"}),"Copy Text Message"]}),e.jsxs(H,{variant:"outline",className:"gap-2",onClick:()=>{c?m(!0):window.open(`mailto:${Z||""}?subject=${encodeURIComponent(je)}&body=${encodeURIComponent(`Hi ${(D==null?void 0:D.first_name)||($==null?void 0:$.split(" ")[0])||""}, I put together a personalized presentation for you: ${xs} Looking forward to connecting!`)}`)},children:[e.jsx(er,{className:"h-4 w-4"}),"Send Email"]})]}),c&&e.jsx(X_,{open:h,onOpenChange:m,contact:D?{id:D.id,first_name:D.first_name,last_name:D.last_name,email:Z||D.email||""}:Z?{id:"",first_name:($==null?void 0:$.split(" ")[0])||"",last_name:($==null?void 0:$.split(" ").slice(1).join(" "))||"",email:Z}:void 0,defaultSubject:je,defaultBody:`Hi ${(D==null?void 0:D.first_name)||($==null?void 0:$.split(" ")[0])||""}, I put together a personalized presentation for you: ${xs} Looking forward to connecting!`,gmailEmail:d})]})}),e.jsxs("div",{className:"flex justify-between",children:[e.jsxs(H,{variant:"outline",onClick:()=>x("builder"),children:[e.jsx(za,{className:"h-4 w-4 mr-2"}),"Edit Presentation"]}),e.jsx(H,{onClick:()=>s("/mission-control/presentations"),children:"Done"})]})]})]})})},zWe=({template:s,onSelect:t})=>e.jsx(ke,{className:"hover:shadow-sm transition-shadow",children:e.jsxs(Oe,{className:"p-5",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("span",{className:"text-2xl",children:s.icon}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-semibold",children:s.name}),e.jsx("p",{className:"text-sm text-muted-foreground mt-0.5",children:s.description}),e.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[e.jsx(Xe,{variant:"outline",className:"text-xs capitalize",children:s.template_type}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[(s.sections||[]).length," sections"]})]})]})]}),e.jsx(H,{className:"w-full mt-4",size:"sm",onClick:()=>t(s),children:"Use Template"})]})}),E$s=()=>{var _;const{shareToken:s}=Po(),[t,r]=S.useState(null),[n,a]=S.useState(!0),[i,l]=S.useState(0),[o,c]=S.useState(!1);S.useEffect(()=>(document.body.classList.add("presentation-page"),()=>{document.body.classList.remove("presentation-page")}),[]),S.useEffect(()=>{s&&d()},[s]);const d=async()=>{const{data:b,error:j}=await V.from("smart_presentations").select("*").eq("share_token",s).eq("status","published").single();if(j||!b){c(!0),a(!1);return}const{data:k}=await V.from("profiles").select("name, email, phone, avatar_url, title, brokerage_id").eq("id",b.owner_user_id).single();let T;if(k!=null&&k.brokerage_id){const{data:A}=await V.from("brokerages").select("name").eq("id",k.brokerage_id).single();T=(A==null?void 0:A.name)||void 0}let E=null;if(b.contact_id){const{data:A}=await V.from("innercircle_contacts").select("first_name, last_name, email, phone").eq("id",b.contact_id).single();E=A}r({...b,owner_name:k==null?void 0:k.name,owner_email:k==null?void 0:k.email,owner_phone:k==null?void 0:k.phone,owner_avatar:k==null?void 0:k.avatar_url,owner_title:(k==null?void 0:k.title)||void 0,brokerage_name:T,contact_name:E?[E.first_name,E.last_name].filter(Boolean).join(" "):void 0,contact_email:(E==null?void 0:E.email)||void 0,contact_phone:(E==null?void 0:E.phone)||void 0}),a(!1);try{await V.rpc("log_presentation_view",{p_presentation_id:b.id,p_section_index:0,p_cta_clicked:!1,p_ip_hash:null,p_user_agent:navigator.userAgent,p_referrer:document.referrer||null})}catch{}},h=async()=>{if(t){try{await V.rpc("log_presentation_view",{p_presentation_id:t.id,p_section_index:null,p_cta_clicked:!0,p_ip_hash:null,p_user_agent:navigator.userAgent,p_referrer:null})}catch{}t.cta_url&&window.open(t.cta_url,"_blank")}};if(n)return e.jsx("div",{className:"min-h-screen bg-white flex items-center justify-center",children:e.jsxs("div",{className:"space-y-4 w-full max-w-2xl px-4",children:[e.jsx(Ks,{className:"h-12 w-3/4 mx-auto"}),e.jsx(Ks,{className:"h-64 w-full"}),e.jsx(Ks,{className:"h-8 w-1/2 mx-auto"})]})});if(o||!t)return e.jsx("div",{className:"min-h-screen bg-white flex items-center justify-center",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold mb-2",children:"Presentation Not Found"}),e.jsx("p",{className:"text-gray-500",children:"This presentation may have been removed or is no longer available."})]})});const m=t.sections.filter(b=>b.is_visible!==!1),p=m[i],x=b=>{const j=b.match(/(?:youtube\.com\/watch\?v=|youtu\.be\/)([a-zA-Z0-9_-]+)/);if(j)return`https://www.youtube.com/embed/${j[1]}?rel=0`;if(b.includes("iframe.mediadelivery.net/play/")){const E=b.replace("/play/","/embed/"),A=E.includes("?")?"&":"?";return`${E}${A}responsive=true`}if(b.includes("iframe.mediadelivery.net")){if(b.match(/\/embed\/(\d+)\/([a-f0-9-]+)/)){const A=b.includes("?")?"&":"?";return`${b}${A}responsive=true`}return""}const k=b.match(/loom\.com\/share\/([a-zA-Z0-9]+)/);if(k)return`https://www.loom.com/embed/${k[1]}`;const T=b.match(/video\.bunnycdn\.com\/play\/(\d+)\/([a-f0-9-]+)/);return T?`https://iframe.mediadelivery.net/embed/${T[1]}/${T[2]}?responsive=true`:b},y=!!((_=t.cta_url)!=null&&_.trim());return e.jsxs("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white",children:[e.jsx("header",{className:"bg-white border-b border-gray-100 sticky top-0 z-10",children:e.jsxs("div",{className:"max-w-5xl mx-auto px-4 py-3 flex items-center justify-between",children:[e.jsx("div",{}),e.jsxs("div",{className:"flex items-center gap-3",children:[t.owner_avatar&&e.jsx("img",{src:t.owner_avatar,alt:t.owner_name||"Agent",className:"h-10 w-10 rounded-full object-cover border border-gray-200"}),e.jsxs("div",{className:"text-right text-sm",children:[e.jsx("p",{className:"font-semibold text-gray-900",children:t.owner_name}),t.owner_title&&e.jsx("p",{className:"text-gray-500 text-xs",children:t.owner_title}),t.brokerage_name&&!t.owner_title&&e.jsx("p",{className:"text-gray-500 text-xs",children:t.brokerage_name})]})]})]})}),e.jsxs("main",{className:"max-w-5xl mx-auto px-4 py-8",children:[e.jsxs("div",{className:"text-center mb-8",children:[e.jsx("h1",{className:"text-3xl md:text-4xl font-bold text-gray-900 mb-2",children:t.heading||(t.client_name?`Welcome, ${t.client_name}!`:t.title)}),t.property_address&&e.jsxs("p",{className:"text-lg text-gray-600",children:["Here's the plan for your home at ",e.jsx("strong",{children:t.property_address}),"."]})]}),e.jsxs("div",{className:"grid md:grid-cols-5 gap-8",children:[e.jsxs("div",{className:"md:col-span-3",children:[p!=null&&p.video_url&&x(p.video_url)?e.jsx("div",{className:"relative w-full rounded-xl overflow-hidden shadow-lg bg-gray-900",style:{paddingTop:"56.25%"},children:e.jsx("iframe",{src:x(p.video_url),className:"absolute inset-0 w-full h-full border-0",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,loading:"lazy"})}):p!=null&&p.image_url?e.jsx("div",{className:"rounded-xl overflow-hidden shadow-lg",children:e.jsx("img",{src:p.image_url,alt:p.title,className:"w-full h-auto object-cover",loading:"lazy"})}):e.jsxs("div",{className:"aspect-video bg-gradient-to-br from-blue-50 to-slate-100 rounded-xl flex flex-col items-center justify-center shadow-lg",children:[e.jsx("span",{className:"text-5xl mb-3",children:p==null?void 0:p.icon}),e.jsx("h3",{className:"text-xl font-semibold text-gray-800",children:p==null?void 0:p.title}),e.jsx("p",{className:"text-gray-500 mt-1 text-sm",children:p==null?void 0:p.description})]}),(p==null?void 0:p.text)&&e.jsx("div",{className:"mt-4 p-4 bg-white rounded-lg border text-gray-700 text-sm leading-relaxed prose prose-sm max-w-none",dangerouslySetInnerHTML:{__html:p.text}})]}),e.jsx("div",{className:"md:col-span-2 space-y-3",children:m.map((b,j)=>e.jsx("button",{onClick:()=>l(j),className:Ft("w-full text-left p-4 rounded-xl border transition-all",i===j?"border-blue-500 bg-blue-50 shadow-sm":"border-gray-200 bg-white hover:border-blue-200 hover:bg-blue-50/50"),children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsxs("span",{className:"text-blue-600 font-bold text-sm mt-0.5",children:[String(j+1).padStart(2,"0"),"."]}),e.jsxs("div",{children:[e.jsx("span",{className:"mr-2",children:b.icon}),e.jsx("span",{className:"font-semibold text-gray-900",children:b.title}),e.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:b.description})]})]})},j))})]}),e.jsxs("div",{className:"mt-12 max-w-md mx-auto bg-white rounded-2xl border border-gray-200 shadow-sm p-6 text-center",children:[t.owner_avatar&&e.jsx("img",{src:t.owner_avatar,alt:t.owner_name||"Agent",className:"h-20 w-20 rounded-full object-cover mx-auto mb-3 border-2 border-gray-100"}),e.jsx("h3",{className:"text-lg font-bold text-gray-900",children:t.owner_name}),t.owner_title&&e.jsx("p",{className:"text-sm text-gray-500",children:t.owner_title}),t.brokerage_name&&e.jsx("p",{className:"text-sm text-gray-500",children:t.brokerage_name}),e.jsxs("div",{className:"mt-3 flex flex-col items-center gap-1 text-sm text-gray-600",children:[t.owner_phone&&e.jsx("a",{href:`tel:${t.owner_phone}`,className:"hover:text-blue-600 transition-colors",children:t.owner_phone}),t.owner_email&&e.jsx("a",{href:`mailto:${t.owner_email}`,className:"hover:text-blue-600 transition-colors",children:t.owner_email})]})]}),t.cta_label&&e.jsxs("div",{className:"text-center mt-8 py-8",children:[e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-4",children:"Ready to Get Started?"}),y?e.jsxs(H,{size:"lg",onClick:h,className:"text-lg px-8 py-6 rounded-xl bg-blue-600 hover:bg-blue-700 text-white shadow-lg",children:[t.cta_label,e.jsx(gn,{className:"h-5 w-5 ml-2"})]}):e.jsx("div",{className:"max-w-md mx-auto bg-white rounded-2xl border border-gray-200 shadow-sm p-6",children:e.jsx(Qst,{presentationId:t.id,ctaLabel:t.cta_label,agentName:t.owner_name||void 0,prefillName:t.contact_name,prefillEmail:t.contact_email,prefillPhone:t.contact_phone})})]})]}),e.jsx("footer",{className:"border-t border-gray-100 bg-white mt-12 py-6 text-center text-xs text-gray-400",children:"Powered by LevelUp"})]})};function A$s({openHouseId:s,enableSurvey:t,onToggleSurvey:r}){const{data:n,isLoading:a}=DLt(s),i=BLt(),l=zLt(),o=$Lt(),c=ULt(),[d,h]=S.useState(""),[m,p]=S.useState("rating"),x=async j=>{r(j),j&&(!n||n.length===0)&&await c.mutateAsync(s)},y=async()=>{if(!d.trim())return;const j=(n==null?void 0:n.reduce((k,T)=>Math.max(k,T.sort_order),0))??0;await i.mutateAsync({open_house_id:s,question_type:m,question_text:d.trim(),sort_order:j+1}),h("")},_=async j=>{await l.mutateAsync({id:j.id,open_house_id:s,is_active:!j.is_active})},b=async j=>{await o.mutateAsync({id:j.id,open_house_id:s})};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsxs(ue,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Fk,{className:"h-4 w-4"}),"Property Feedback Survey"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Show a quick feedback survey after visitors sign in"})]}),e.jsx(Or,{checked:t,onCheckedChange:x})]}),t&&e.jsx("div",{className:"space-y-3 pt-2 border-t border-border",children:a?e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(is,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"space-y-2",children:n==null?void 0:n.map(j=>e.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-lg border border-border bg-muted/20",children:[e.jsx(Oh,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm truncate",children:j.question_text}),e.jsx("p",{className:"text-xs text-muted-foreground capitalize",children:j.question_type.replace("_"," ")})]}),e.jsx(Or,{checked:j.is_active,onCheckedChange:()=>_(j),className:"scale-75"}),e.jsx(H,{variant:"ghost",size:"icon",className:"h-7 w-7 shrink-0 text-muted-foreground hover:text-destructive",onClick:()=>b(j),children:e.jsx(Dr,{className:"h-3.5 w-3.5"})})]},j.id))}),e.jsxs("div",{className:"flex items-end gap-2",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx(ue,{className:"text-xs text-muted-foreground",children:"Add Question"}),e.jsx(Se,{value:d,onChange:j=>h(j.target.value),placeholder:"e.g. How did you hear about this listing?",className:"mt-1 h-9 text-sm",onKeyDown:j=>j.key==="Enter"&&y()})]}),e.jsxs(Bs,{value:m,onValueChange:p,children:[e.jsx(Os,{className:"w-28 h-9 text-xs",children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"rating",children:"Rating"}),e.jsx(pt,{value:"open_text",children:"Text"})]})]}),e.jsx(H,{size:"sm",variant:"outline",onClick:y,disabled:!d.trim()||i.isPending,className:"h-9",children:e.jsx(Ys,{className:"h-3.5 w-3.5"})})]})]})})]})}function M$s({openHouseId:s}){const{user:t}=Ms(),{data:r=[],isLoading:n}=GLt(s),a=KLt(),[i,l]=S.useState(""),[o,c]=S.useState(!1),d=async()=>{const h=i.trim();if(h){c(!0);try{await a.mutateAsync({open_house_id:s,name:h,sort_order:r.length}),l("")}finally{c(!1)}}};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ue,{className:"text-sm font-medium",children:"Rooms"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Add rooms and upload photos or videos. Visitors swipe through them on mobile and tab through them on desktop."})]}),n?e.jsxs("div",{className:"py-6 text-center text-sm text-muted-foreground",children:[e.jsx(is,{className:"h-4 w-4 animate-spin inline"})," Loading…"]}):r.length===0?e.jsx("p",{className:"text-xs text-muted-foreground italic",children:"No rooms yet — add your first below."}):e.jsx("div",{className:"space-y-3",children:r.map((h,m)=>e.jsx(I$s,{room:h,index:m,total:r.length,userId:(t==null?void 0:t.id)||"",openHouseId:s},h.id))}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(Se,{value:i,onChange:h=>l(h.target.value),placeholder:"e.g. Kitchen, Primary Bedroom, Backyard…",onKeyDown:h=>{h.key==="Enter"&&(h.preventDefault(),d())}}),e.jsx(H,{onClick:d,disabled:!i.trim()||o,size:"sm",children:o?e.jsx(is,{className:"h-4 w-4 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(Ys,{className:"h-4 w-4 mr-1"})," Add"]})})]})]})}function I$s({room:s,index:t,total:r,userId:n,openHouseId:a}){const i=YLt(),l=ZLt(),o=XLt(),c=QLt(),d=S.useRef(null),[h,m]=S.useState(!0),[p,x]=S.useState(s.name),[y,_]=S.useState(s.description||""),[b,j]=S.useState(!1),k=S.useMemo(()=>s.media.filter(O=>O.kind==="video"&&O.agent_video_id).map(O=>O.agent_video_id),[s.media]),{data:T={}}=yt({queryKey:["room-video-statuses",s.id,k.join(",")],enabled:k.length>0,queryFn:async()=>{const{data:O,error:$}=await V.from("agent_videos").select("id, status, bunny_video_id, thumbnail_url, preview_url").in("id",k);if($)throw $;const ee=O||[],Z=ee.filter(K=>K.status==="processing"&&K.bunny_video_id);await Promise.all(Z.map(async K=>{try{const{data:re}=await V.functions.invoke("bunny-upload",{body:{action:"status",videoId:K.bunny_video_id,isAgentVideo:!0}});re&&re.status===4&&(await V.from("agent_videos").update({status:"ready",playback_url:re.directPlayUrl,thumbnail_url:re.thumbnailUrl,preview_url:re.previewUrl,duration_seconds:re.length||void 0,updated_at:new Date().toISOString()}).eq("id",K.id),K.status="ready",K.thumbnail_url=re.thumbnailUrl,K.preview_url=re.previewUrl)}catch{}}));const J={};return ee.forEach(K=>{J[K.id]={status:K.status,thumbnail_url:K.thumbnail_url,preview_url:K.preview_url}}),J},refetchInterval:O=>{const $=O.state.data;return $?Object.values($).some(ee=>ee.status!=="ready"&&ee.status!=="failed")?5e3:!1:5e3}}),E=()=>{p.trim()&&p!==s.name&&i.mutate({id:s.id,open_house_id:a,name:p.trim()})},A=()=>{y!==(s.description||"")&&i.mutate({id:s.id,open_house_id:a,description:y.trim()||null})},D=()=>{confirm(`Delete "${s.name}" and all its media?`)&&l.mutate({id:s.id,open_house_id:a})},R=O=>{i.mutate({id:s.id,open_house_id:a,sort_order:t+O})},z=async O=>{const $=Array.from(O.target.files||[]);if(!(!$.length||!n)){j(!0);try{for(const ee of $){const Z=ee.type.startsWith("video/"),J=Z?500*1024*1024:15*1024*1024;if(ee.size>J){En({title:`${ee.name} is too large`,description:Z?"Videos must be under 500MB":"Photos must be under 15MB",variant:"destructive"});continue}if(Z){try{const ne=`${s.name} – ${ee.name.replace(/\.[^/.]+$/,"")}`,{data:le,error:be}=await V.functions.invoke("bunny-upload",{body:{action:"create",title:ne,isAgentVideo:!0}});if(be||!le)throw new Error((be==null?void 0:be.message)||"Could not start upload");const{videoId:fe,libraryId:je}=le,{data:ve,error:We}=await V.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:fe,isAgentVideo:!0}});if(We||!ve)throw new Error((We==null?void 0:We.message)||"Could not get upload URL");await new Promise((Pe,Ie)=>{const De=new XMLHttpRequest;De.addEventListener("load",()=>{De.status>=200&&De.status<300?Pe():Ie(new Error(`Upload failed (${De.status})`))}),De.addEventListener("error",()=>Ie(new Error("Upload failed"))),De.open("PUT",ve.uploadUrl),De.setRequestHeader("AccessKey",ve.apiKey),De.send(ee)});const Ve=`https://iframe.mediadelivery.net/embed/${je}/${fe}`,Le=ee.size/(1024*1024),{data:Me,error:ze}=await V.from("agent_videos").insert({owner_user_id:n,bunny_video_id:fe,playback_url:Ve,file_size_mb:Le,title:ne,status:"processing",touch_type:"open_house_tour",category:"open_house",page_template:"default"}).select().single();if(ze)throw ze;await o.mutateAsync({open_house_id:a,room_id:s.id,kind:"video",url:Ve,sort_order:s.media.length,agent_video_id:Me.id}),En({title:"Video uploaded",description:"Processing in the background — it’ll appear in your Video Library too."})}catch(ne){En({title:"Video upload failed",description:(ne==null?void 0:ne.message)||"Try again",variant:"destructive"})}continue}const K=ee.name.split(".").pop()||"jpg",re=`${n}/${a}/rooms/${s.id}-${Date.now()}-${Math.random().toString(36).slice(2,7)}.${K}`,{error:ie}=await V.storage.from("open-house-tour-media").upload(re,ee,{upsert:!1,contentType:ee.type});if(ie){En({title:"Upload failed",description:ie.message,variant:"destructive"});continue}const{data:ce}=V.storage.from("open-house-tour-media").getPublicUrl(re);await o.mutateAsync({open_house_id:a,room_id:s.id,kind:"photo",url:ce.publicUrl,sort_order:s.media.length})}}finally{j(!1),d.current&&(d.current.value="")}}};return e.jsxs("div",{className:"rounded-lg border border-border bg-card",children:[e.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 border-b border-border",children:[e.jsx(Oh,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("button",{onClick:()=>m(O=>!O),className:"flex-1 text-left text-sm font-medium truncate",children:[s.name," ",e.jsxs("span",{className:"text-muted-foreground font-normal text-xs",children:["· ",s.media.length," ",s.media.length===1?"item":"items"]})]}),e.jsx(H,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>R(-1),disabled:t===0,children:e.jsx(cx,{className:"h-4 w-4"})}),e.jsx(H,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>R(1),disabled:t===r-1,children:e.jsx(Io,{className:"h-4 w-4"})}),e.jsx(H,{size:"icon",variant:"ghost",className:"h-7 w-7 text-destructive",onClick:D,children:e.jsx(Dr,{className:"h-4 w-4"})})]}),h&&e.jsxs("div",{className:"p-3 space-y-3",children:[e.jsx(Se,{value:p,onChange:O=>x(O.target.value),onBlur:E,placeholder:"Room name",className:"h-9"}),e.jsx(vr,{value:y,onChange:O=>_(O.target.value),onBlur:A,placeholder:"Optional description — what makes this room special?",rows:2,className:"text-sm"}),s.media.length>0&&e.jsx("div",{className:"grid grid-cols-3 gap-2",children:s.media.map(O=>{const $=O.agent_video_id?T[O.agent_video_id]:void 0,ee=$==null?void 0:$.status,Z=O.kind==="video"&&ee&&ee!=="ready"&&ee!=="failed",J=O.kind==="video"&&ee==="failed",K=($==null?void 0:$.thumbnail_url)||($==null?void 0:$.preview_url);return e.jsxs("div",{className:"relative aspect-square rounded-md overflow-hidden bg-muted group",children:[O.kind==="video"?e.jsxs(e.Fragment,{children:[K?e.jsx("img",{src:K,alt:"",className:"w-full h-full object-cover"}):/iframe\.mediadelivery\.net\/embed\//.test(O.url)?e.jsx("div",{className:"w-full h-full bg-slate-800"}):e.jsx("video",{src:O.url,className:"w-full h-full object-cover"}),!Z&&!J&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/30 pointer-events-none",children:e.jsx(xn,{className:"h-6 w-6 text-white"})}),Z&&e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center bg-black/70 text-white gap-1 pointer-events-none",children:[e.jsx(is,{className:"h-5 w-5 animate-spin"}),e.jsx("span",{className:"text-[10px] font-medium uppercase tracking-wide",children:"Processing"})]}),J&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-destructive/80 text-white text-[10px] font-medium uppercase tracking-wide pointer-events-none px-2 text-center",children:"Failed"})]}):e.jsx("img",{src:O.url,alt:"",className:"w-full h-full object-cover"}),e.jsx("button",{onClick:()=>c.mutate({id:O.id,open_house_id:a}),className:"absolute top-1 right-1 w-6 h-6 rounded-full bg-black/60 text-white flex items-center justify-center opacity-0 group-hover:opacity-100 transition",children:e.jsx(Rr,{className:"h-3.5 w-3.5"})})]},O.id)})}),e.jsx("input",{ref:d,type:"file",accept:"image/*,video/*",multiple:!0,onChange:z,className:"hidden"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(H,{variant:"outline",size:"sm",onClick:()=>{var O;return(O=d.current)==null?void 0:O.click()},disabled:b,className:"flex-1",children:b?e.jsx(is,{className:"h-4 w-4 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(Ea,{className:"h-4 w-4 mr-2"})," Upload"]})}),e.jsx(H8,{userId:n,triggerLabel:"From Video Library",triggerClassName:"gap-1.5 flex-1 justify-center",onSelect:()=>{},onSelectVideo:async O=>{try{await o.mutateAsync({open_house_id:a,room_id:s.id,kind:"video",url:O.playback_url||"",sort_order:s.media.length,agent_video_id:O.id}),En({title:"Video added to room"})}catch($){En({title:"Failed to add video",description:$==null?void 0:$.message,variant:"destructive"})}}})]})]})]})}function P$s({open:s,onOpenChange:t,openHouse:r}){const n=ert(),{user:a}=Ms(),i=S.useRef(null),l=S.useRef(null),o=S.useRef(null),c=r.kind==="virtual",[d,h]=S.useState(r.auto_forward_to_card??!1),[m,p]=S.useState(r.disclosure_pdf_url??""),[x,y]=S.useState(r.enable_survey??!1),[_,b]=S.useState(r.ask_visitor_intent??!0),[j,k]=S.useState(r.photo_url??""),[T,E]=S.useState(!1),[A,D]=S.useState(!1),[R,z]=S.useState(!1),[O,$]=S.useState(r.hero_video_url??""),[ee,Z]=S.useState(!1),[J,K]=S.useState(r.price!=null?String(r.price):""),[re,ie]=S.useState(r.beds!=null?String(r.beds):""),[ce,ne]=S.useState(r.baths!=null?String(r.baths):""),[le,be]=S.useState(r.sqft!=null?String(r.sqft):""),[fe,je]=S.useState(r.enable_question??!0),[ve,We]=S.useState(r.enable_showing??!0),[Ve,Le]=S.useState(r.enable_disclosures??!0),[Me,ze]=S.useState(r.enable_offer??!0),[Pe,Ie]=S.useState(r.brand_color_override??""),[De,pe]=S.useState(r.property_description??""),tt=async Ne=>{var wt;const $e=(wt=Ne.target.files)==null?void 0:wt[0];if(!$e||!a)return;if($e.size>200*1024*1024){En({title:"Video must be under 200MB",variant:"destructive"});return}if(!$e.type.startsWith("video/")){En({title:"Please upload a video file",variant:"destructive"});return}Z(!0);const it=$e.name.split(".").pop()||"mp4",Je=`${a.id}/${r.id}/hero-${Date.now()}.${it}`,{error:st}=await V.storage.from("open-house-tour-media").upload(Je,$e,{upsert:!0,contentType:$e.type});if(st){En({title:"Upload failed",description:st.message,variant:"destructive"}),Z(!1);return}const{data:mt}=V.storage.from("open-house-tour-media").getPublicUrl(Je);$(mt.publicUrl),Z(!1),En({title:"Video uploaded!"})},ge=async Ne=>{var wt;const $e=(wt=Ne.target.files)==null?void 0:wt[0];if(!$e||!a)return;if($e.size>10*1024*1024){En({title:"Image must be under 10MB",variant:"destructive"});return}if(!$e.type.startsWith("image/")){En({title:"Please upload an image file",variant:"destructive"});return}D(!0);const it=$e.name.split(".").pop()||"jpg",Je=`${a.id}/${r.id}-${Date.now()}.${it}`,{error:st}=await V.storage.from("open-house-photos").upload(Je,$e,{upsert:!0});if(st){En({title:"Upload failed",description:st.message,variant:"destructive"}),D(!1);return}const{data:mt}=V.storage.from("open-house-photos").getPublicUrl(Je);k(mt.publicUrl),D(!1),En({title:"Photo updated!"})},ct=()=>{k(""),l.current&&(l.current.value="")},Ue=async Ne=>{var mt;const $e=(mt=Ne.target.files)==null?void 0:mt[0];if(!$e||!a)return;if($e.size>20*1024*1024){En({title:"File must be under 20MB",variant:"destructive"});return}if($e.type!=="application/pdf"){En({title:"Only PDF files are accepted",variant:"destructive"});return}E(!0);const it=`${a.id}/disclosures/${r.id}-${Date.now()}.pdf`,{error:Je}=await V.storage.from("open-house-photos").upload(it,$e,{upsert:!0});if(Je){En({title:"Upload failed",description:Je.message,variant:"destructive"}),E(!1);return}const{data:st}=V.storage.from("open-house-photos").getPublicUrl(it);p(st.publicUrl),E(!1),En({title:"PDF uploaded!"})},et=()=>{p(""),i.current&&(i.current.value="")},Qe=async()=>{z(!0);try{const Ne={id:r.id,auto_forward_to_card:d,disclosure_pdf_url:m||null,enable_survey:x,ask_visitor_intent:_,photo_url:j||null};c&&(Ne.hero_video_url=O||null,Ne.price=J.trim()?Number(J):null,Ne.beds=re.trim()?parseInt(re,10):null,Ne.baths=ce.trim()?Number(ce):null,Ne.sqft=le.trim()?parseInt(le,10):null,Ne.enable_question=fe,Ne.enable_showing=ve,Ne.enable_disclosures=Ve,Ne.enable_offer=Me,Ne.brand_color_override=Pe.trim()||null,Ne.property_description=De.trim()||null),await n.mutateAsync(Ne),En({title:"Settings saved!"}),t(!1)}catch{En({title:"Failed to save",variant:"destructive"})}finally{z(!1)}};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"sm:max-w-md max-h-[85vh] overflow-y-auto",children:[e.jsxs(Cs,{children:[e.jsx(Ns,{children:c?"Virtual Open House Settings":"Guest Book Settings"}),e.jsx(nn,{className:"truncate",children:r.property_address})]}),e.jsxs("div",{className:"space-y-6 pt-2",children:[c&&e.jsxs(e.Fragment,{children:[r.tour_mode==="single_video"?e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ue,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(xn,{className:"h-4 w-4"})," Hero Tour Video"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"The video visitors watch right after they sign in. MP4 recommended (max 200MB)."}),e.jsx("input",{ref:o,type:"file",accept:"video/*",onChange:tt,className:"hidden"}),O?e.jsxs("div",{className:"relative rounded-lg overflow-hidden border border-border bg-black",children:[e.jsx("video",{src:O,controls:!0,className:"w-full max-h-48"}),e.jsxs("div",{className:"absolute top-2 right-2 flex gap-2",children:[e.jsx(H,{variant:"secondary",size:"sm",className:"h-8",onClick:()=>{var Ne;return(Ne=o.current)==null?void 0:Ne.click()},disabled:ee,children:ee?e.jsx(is,{className:"h-3.5 w-3.5 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(Ea,{className:"h-3.5 w-3.5 mr-1"}),"Replace"]})}),e.jsx(H,{variant:"secondary",size:"icon",className:"h-8 w-8",onClick:()=>$(""),children:e.jsx(Rr,{className:"h-4 w-4"})})]})]}):e.jsx("button",{type:"button",onClick:()=>{var Ne;return(Ne=o.current)==null?void 0:Ne.click()},disabled:ee,className:"w-full h-32 rounded-xl border-2 border-dashed border-muted-foreground/25 hover:border-muted-foreground/50 flex flex-col items-center justify-center gap-2 text-muted-foreground hover:text-foreground transition-colors",children:ee?e.jsx(is,{className:"h-5 w-5 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(xn,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs",children:"Upload tour video (max 200MB)"})]})})]}):e.jsx(M$s,{openHouseId:r.id}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{className:"text-sm font-medium",children:"Property Details"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs text-muted-foreground",children:"Price (USD)"}),e.jsx(Se,{type:"number",value:J,onChange:Ne=>K(Ne.target.value),placeholder:"650000",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs text-muted-foreground",children:"Sq Ft"}),e.jsx(Se,{type:"number",value:le,onChange:Ne=>be(Ne.target.value),placeholder:"2200",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs text-muted-foreground",children:"Beds"}),e.jsx(Se,{type:"number",value:re,onChange:Ne=>ie(Ne.target.value),placeholder:"3",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs text-muted-foreground",children:"Baths"}),e.jsx(Se,{type:"number",step:"0.5",value:ce,onChange:Ne=>ne(Ne.target.value),placeholder:"2.5",className:"mt-1"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{className:"text-sm font-medium",children:"Property Description"}),e.jsx("p",{className:"text-xs text-muted-foreground -mt-1",children:"Showcase the home — features, finishes, location highlights. Shown on the virtual tour page below the headline."}),e.jsx(vr,{value:De,onChange:Ne=>pe(Ne.target.value),placeholder:"Stunning 4-bedroom in the heart of River Oaks. Chef's kitchen, oversized primary suite, and a backyard oasis perfect for entertaining…",rows:5,className:"w-full resize-y"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(ue,{className:"text-sm font-medium",children:"Visitor Actions"}),e.jsx("p",{className:"text-xs text-muted-foreground -mt-1",children:"Choose what visitors can do during the tour."}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm",children:"Ask a question"}),e.jsx(Or,{checked:fe,onCheckedChange:je})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm",children:"Schedule a private showing"}),e.jsx(Or,{checked:ve,onCheckedChange:We})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm",children:"Request seller disclosures"}),e.jsx(Or,{checked:Ve,onCheckedChange:Le})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm",children:"Make an offer / express interest"}),e.jsx(Or,{checked:Me,onCheckedChange:ze})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{className:"text-sm font-medium",children:"Brand Accent Color"}),e.jsx("p",{className:"text-xs text-muted-foreground -mt-1",children:"Used for highlights and CTA buttons on your virtual tour page. Leave blank to use the default."}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:Pe||"#0f172a",onChange:Ne=>Ie(Ne.target.value),className:"h-10 w-14 rounded-md border border-input cursor-pointer bg-transparent"}),e.jsx(Se,{value:Pe,onChange:Ne=>Ie(Ne.target.value),placeholder:"#0f172a",className:"flex-1 font-mono text-sm"}),Pe&&e.jsx(H,{variant:"ghost",size:"sm",onClick:()=>Ie(""),children:"Reset"})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5 pt-1",children:["#0f172a","#406E71","#2a4c64","#7c2d12","#1e3a8a","#581c87","#9f1239","#065f46"].map(Ne=>e.jsx("button",{type:"button",onClick:()=>Ie(Ne),className:"w-6 h-6 rounded-full border border-border hover:scale-110 transition-transform",style:{backgroundColor:Ne},"aria-label":Ne},Ne))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{className:"text-sm font-medium",children:"Property Photo"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Shown on the sign-in screen and printable QR sheet"}),e.jsx("input",{ref:l,type:"file",accept:"image/*",onChange:ge,className:"hidden"}),j?e.jsxs("div",{className:"relative rounded-lg overflow-hidden border border-border",children:[e.jsx("img",{src:j,alt:"Property",className:"w-full h-40 object-cover"}),e.jsxs("div",{className:"absolute top-2 right-2 flex gap-2",children:[e.jsxs(H,{variant:"secondary",size:"sm",className:"h-8",onClick:()=>{var Ne;return(Ne=l.current)==null?void 0:Ne.click()},disabled:A,children:[A?e.jsx(is,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Ea,{className:"h-3.5 w-3.5 mr-1"}),A?"":"Replace"]}),e.jsx(H,{variant:"secondary",size:"icon",className:"h-8 w-8",onClick:ct,children:e.jsx(Rr,{className:"h-4 w-4"})})]})]}):e.jsx("button",{type:"button",onClick:()=>{var Ne;return(Ne=l.current)==null?void 0:Ne.click()},disabled:A,className:"w-full h-32 rounded-xl border-2 border-dashed border-muted-foreground/25 hover:border-muted-foreground/50 flex flex-col items-center justify-center gap-2 text-muted-foreground hover:text-foreground transition-colors",children:A?e.jsx(is,{className:"h-5 w-5 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(wl,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs",children:"Upload property photo (max 10MB)"})]})})]}),e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(ue,{className:"text-sm font-medium",children:"Auto-forward to Digital Card"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"After check-in, redirect visitors to your digital business card"})]}),e.jsx(Or,{checked:d,onCheckedChange:h})]})}),!d&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{className:"text-sm font-medium",children:"Seller's Disclosures (PDF)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Visitors can view or download this on the thank you screen after check-in"}),e.jsx("input",{ref:i,type:"file",accept:"application/pdf",onChange:Ue,className:"hidden"}),m?e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg border border-border bg-muted/30",children:[e.jsx(kn,{className:"h-5 w-5 text-primary shrink-0"}),e.jsx("span",{className:"text-sm truncate flex-1",children:"Disclosure PDF uploaded"}),e.jsx(H,{variant:"ghost",size:"icon",className:"h-7 w-7 shrink-0",onClick:et,children:e.jsx(Rr,{className:"h-4 w-4"})})]}):e.jsx("button",{type:"button",onClick:()=>{var Ne;return(Ne=i.current)==null?void 0:Ne.click()},disabled:T,className:"w-full h-24 rounded-xl border-2 border-dashed border-muted-foreground/25 hover:border-muted-foreground/50 flex flex-col items-center justify-center gap-2 text-muted-foreground hover:text-foreground transition-colors",children:T?e.jsx(is,{className:"h-5 w-5 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(Ea,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs",children:"Upload PDF (max 20MB)"})]})})]}),e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(ue,{className:"text-sm font-medium",children:'Ask "What brings you here?"'}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Show the buying / selling / browsing question after sign-in. Turn off to let visitors check in without picking an option."})]}),e.jsx(Or,{checked:_,onCheckedChange:b})]})}),e.jsx(A$s,{openHouseId:r.id,enableSurvey:x,onToggleSurvey:y}),e.jsx(H,{onClick:Qe,disabled:R,className:"w-full",children:R?"Saving...":"Save Settings"})]})]})})}const Avt={5:"Excellent",4:"Good",3:"Neutral",2:"Bad",1:"Very Bad"};function L$s({question:s,responses:t}){const r=t.filter(l=>l.question_id===s.id&&l.rating_value!=null),n=r.length;if(n===0)return null;const a=r.reduce((l,o)=>l+(o.rating_value||0),0)/n,i=[5,4,3,2,1].map(l=>({val:l,count:r.filter(o=>o.rating_value===l).length,pct:Math.round(r.filter(o=>o.rating_value===l).length/n*100)}));return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm font-medium",children:s.question_text}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:[a.toFixed(1)," avg (",n," responses)"]})]}),e.jsx("div",{className:"space-y-1",children:i.map(l=>e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx("span",{className:"w-16 text-muted-foreground text-right",children:Avt[l.val]}),e.jsx("div",{className:"flex-1 h-4 bg-muted/30 rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-primary/70 rounded-full transition-all",style:{width:`${l.pct}%`}})}),e.jsx("span",{className:"w-8 text-muted-foreground",children:l.count})]},l.val))})]})}function D$s({openHouseId:s}){const{data:t,isLoading:r}=FLt(s),{data:n}=Jst(s),a=S.useMemo(()=>{const m={};return n==null||n.forEach(p=>{m[p.id]=p}),m},[n]);if(r||!t)return null;const{questions:i,responses:l}=t;if(i.length===0)return null;const o=i.filter(m=>m.question_type==="rating"),c=i.filter(m=>m.question_type!=="rating"),d=[...new Set(l.map(m=>m.visitor_id))],h=d.length;return h===0?e.jsxs(ke,{children:[e.jsx(Ot,{className:"pb-3",children:e.jsxs(zt,{className:"text-base flex items-center gap-2",children:[e.jsx(Fk,{className:"h-4 w-4"}),"Survey Results"]})}),e.jsx(Oe,{children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"No survey responses yet."})})]}):e.jsxs(ke,{children:[e.jsx(Ot,{className:"pb-3",children:e.jsxs(zt,{className:"text-base flex items-center gap-2",children:[e.jsx(Fk,{className:"h-4 w-4"}),"Survey Results",e.jsxs("span",{className:"text-xs font-normal text-muted-foreground ml-auto",children:[h," respondent",h!==1?"s":""]})]})}),e.jsx(Oe,{children:e.jsxs(ta,{defaultValue:"summary",children:[e.jsxs(Qn,{className:"mb-4",children:[e.jsxs(ts,{value:"summary",className:"text-xs gap-1",children:[e.jsx(Bo,{className:"h-3.5 w-3.5"})," Summary"]}),e.jsxs(ts,{value:"individual",className:"text-xs gap-1",children:[e.jsx(io,{className:"h-3.5 w-3.5"})," Per Visitor"]})]}),e.jsxs(cs,{value:"summary",className:"space-y-6",children:[o.map(m=>e.jsx(L$s,{question:m,responses:l},m.id)),c.map(m=>{const p=l.filter(x=>x.question_id===m.id&&x.text_value);return p.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsx("span",{className:"text-sm font-medium",children:m.question_text}),e.jsx("div",{className:"space-y-1.5 max-h-40 overflow-y-auto",children:p.map(x=>{const y=a[x.visitor_id];return e.jsxs("div",{className:"text-sm p-2 bg-muted/30 rounded-lg",children:[e.jsxs("span",{className:"text-muted-foreground text-xs",children:[y?`${y.first_name} ${y.last_name||""}`.trim():"Visitor",":"]}),e.jsx("p",{className:"mt-0.5",children:x.text_value})]},x.id)})})]},m.id)})]}),e.jsx(cs,{value:"individual",className:"space-y-4",children:d.map(m=>{const p=a[m],x=l.filter(y=>y.visitor_id===m);return e.jsxs("div",{className:"p-3 rounded-lg border border-border space-y-2",children:[e.jsxs("p",{className:"text-sm font-medium",children:[p?`${p.first_name} ${p.last_name||""}`.trim():"Unknown Visitor",(p==null?void 0:p.email)&&e.jsx("span",{className:"text-xs text-muted-foreground ml-2",children:p.email})]}),e.jsx("div",{className:"space-y-1",children:x.map(y=>{const _=i.find(b=>b.id===y.question_id);return _?e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:_.question_text}),e.jsx("span",{className:"font-medium",children:y.rating_value!=null?Avt[y.rating_value]||y.rating_value:y.text_value})]},y.id):null})})]},m)})})]})})]})}const R$s={question:{label:"Question",icon:Gi,color:"text-sky-700 dark:text-sky-300",bg:"bg-sky-100 dark:bg-sky-950"},showing:{label:"Showing",icon:Nn,color:"text-orange-700 dark:text-orange-300",bg:"bg-orange-100 dark:bg-orange-950"},disclosure:{label:"Disclosures",icon:kn,color:"text-indigo-700 dark:text-indigo-300",bg:"bg-indigo-100 dark:bg-indigo-950"},offer:{label:"Hot Lead",icon:oc,color:"text-emerald-700 dark:text-emerald-300",bg:"bg-emerald-100 dark:bg-emerald-950"}},$We={preferred_date:"Preferred date",preferred_time:"Preferred time",alternate_date:"Alternate date",requested_documents:"Requested",offer_amount:"Offer",financing:"Financing",timeline:"Timeline",pre_approved:"Pre-approved"};function O$s({openHouseId:s}){const{data:t=[],isLoading:r}=JLt(s),n=e8t(),[a,i]=S.useState(null),[l,o]=S.useState("all"),c=t.filter(m=>l==="all"?!0:l==="new"?m.status==="new":m.action_type===l),d={all:t.length,new:t.filter(m=>m.status==="new").length,question:t.filter(m=>m.action_type==="question").length,showing:t.filter(m=>m.action_type==="showing").length,disclosure:t.filter(m=>m.action_type==="disclosure").length,offer:t.filter(m=>m.action_type==="offer").length},h=(m,p)=>{n.mutate({id:m,status:p,open_house_id:s})};return r?e.jsx("div",{className:"text-sm text-muted-foreground py-4",children:"Loading leads…"}):e.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[e.jsxs("div",{className:"px-4 py-3 bg-muted/40 border-b flex items-center justify-between flex-wrap gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold",children:[e.jsx(Uk,{className:"h-4 w-4"}),"Virtual Open House Leads",e.jsx(Xe,{variant:"secondary",className:"ml-1",children:d.all}),d.new>0&&e.jsxs(Xe,{className:"bg-emerald-600 hover:bg-emerald-600",children:[d.new," new"]})]}),e.jsx("div",{className:"flex items-center gap-1 flex-wrap",children:[["all","All",d.all],["new","New",d.new],["offer","Hot",d.offer],["showing","Showings",d.showing],["question","Questions",d.question],["disclosure","Docs",d.disclosure]].map(([m,p,x])=>e.jsxs("button",{onClick:()=>o(m),className:`text-xs px-2.5 py-1 rounded-full transition-colors ${l===m?"bg-foreground text-background":"bg-background hover:bg-muted text-muted-foreground"}`,children:[p," ",e.jsx("span",{className:"opacity-60",children:x})]},m))})]}),c.length===0?e.jsx("div",{className:"px-4 py-10 text-center text-sm text-muted-foreground",children:t.length===0?"No leads yet. Share your virtual open house link to start capturing leads.":"No leads match this filter."}):e.jsx("ul",{className:"divide-y",children:c.map(m=>{const p=R$s[m.action_type],x=p.icon,y=m.payload||{},_=a===m.id,b=m.status==="contacted",j=m.status==="archived";return e.jsxs("li",{className:`transition-colors ${j?"opacity-60":""} ${m.status==="new"?"bg-emerald-50/40 dark:bg-emerald-950/10":""}`,children:[e.jsxs("button",{onClick:()=>i(_?null:m.id),className:"w-full text-left px-4 py-3 flex items-start gap-3 hover:bg-muted/40 transition-colors",children:[e.jsx("div",{className:`w-9 h-9 rounded-lg flex items-center justify-center shrink-0 ${p.bg}`,children:e.jsx(x,{className:`h-4 w-4 ${p.color}`})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"font-semibold text-sm truncate",children:y.visitor_name||"Visitor"}),e.jsx(Xe,{variant:"outline",className:`text-[10px] ${p.color}`,children:p.label}),m.status==="new"&&e.jsx("span",{className:"text-[10px] font-bold text-emerald-600 uppercase tracking-wide",children:"New"}),b&&e.jsxs("span",{className:"text-[10px] font-bold text-muted-foreground uppercase tracking-wide flex items-center gap-1",children:[e.jsx(ea,{className:"h-3 w-3"}),"Contacted"]})]}),y.message&&e.jsxs("p",{className:"text-sm text-muted-foreground line-clamp-1 mt-0.5 italic",children:['"',y.message,'"']}),e.jsxs("div",{className:"flex items-center gap-3 text-[11px] text-muted-foreground mt-1",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Pn,{className:"h-3 w-3"}),As(new Date(m.created_at),"MMM d, h:mm a")]}),y.email&&e.jsxs("span",{className:"flex items-center gap-1 truncate",children:[e.jsx(er,{className:"h-3 w-3"}),y.email]}),y.phone&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Yn,{className:"h-3 w-3"}),y.phone]})]})]}),_?e.jsx(Io,{className:"h-4 w-4 mt-1 text-muted-foreground"}):e.jsx($a,{className:"h-4 w-4 mt-1 text-muted-foreground"})]}),_&&e.jsxs("div",{className:"px-4 pb-4 pl-16 space-y-3",children:[y.message&&e.jsxs("div",{className:"bg-muted/40 rounded-md p-3 text-sm border-l-2 border-foreground/30",children:['"',y.message,'"']}),Object.keys($We).some(k=>y[k]!=null&&y[k]!==""&&!(Array.isArray(y[k])&&y[k].length===0))&&e.jsx("div",{className:"grid grid-cols-2 gap-x-4 gap-y-1.5 text-sm",children:Object.entries($We).map(([k,T])=>{const E=y[k];return E==null||E===""||Array.isArray(E)&&E.length===0?null:e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] text-muted-foreground uppercase tracking-wide",children:T}),e.jsx("div",{className:"font-medium",children:Array.isArray(E)?E.join(", "):String(E)})]},k)})}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 pt-1",children:[y.email&&e.jsx("a",{href:`mailto:${y.email}?subject=${encodeURIComponent("Re: your open house inquiry")}`,children:e.jsxs(H,{size:"sm",variant:"default",className:"gap-1.5",children:[e.jsx(er,{className:"h-3.5 w-3.5"}),"Reply"]})}),y.phone&&e.jsx("a",{href:`tel:${String(y.phone).replace(/[^0-9+]/g,"")}`,children:e.jsxs(H,{size:"sm",variant:"outline",className:"gap-1.5",children:[e.jsx(Yn,{className:"h-3.5 w-3.5"}),"Call"]})}),!b&&e.jsxs(H,{size:"sm",variant:"outline",className:"gap-1.5",onClick:()=>h(m.id,"contacted"),children:[e.jsx(ea,{className:"h-3.5 w-3.5"}),"Mark contacted"]}),j?e.jsx(H,{size:"sm",variant:"ghost",className:"gap-1.5 text-muted-foreground",onClick:()=>h(m.id,"new"),children:"Restore"}):e.jsxs(H,{size:"sm",variant:"ghost",className:"gap-1.5 text-muted-foreground",onClick:()=>h(m.id,"archived"),children:[e.jsx(Rk,{className:"h-3.5 w-3.5"}),"Archive"]})]})]})]},m.id)})})]})}function F$s({open:s,onOpenChange:t,openHouse:r}){const{isGmailConnected:n,gmailEmail:a}=cf(),i=ba(),[l,o]=S.useState([]),[c,d]=S.useState([]),[h,m]=S.useState(!1),[p,x]=S.useState(!1),[y,_]=S.useState(""),[b,j]=S.useState(""),[k,T]=S.useState(""),[E,A]=S.useState(!1),[D,R]=S.useState(!1),[z,O]=S.useState(!1),$=`https://guestbook.relevelup.com/${r.slug}`;S.useEffect(()=>{s&&(j(`Take a virtual tour of ${r.property_address}`),T(`I wanted to share an immersive virtual tour of ${r.property_address} with you. Step inside from anywhere — explore every room at your own pace.`),d([]),_(""),A(n),l.length===0&&ee())},[s,r.id,n]);const ee=async()=>{if(i){x(!0);try{const{data:le,error:be}=await V.from("innercircle_contacts").select("id, first_name, last_name, email").eq("owner_user_id",i).not("email","is",null).neq("email","").order("first_name",{ascending:!0}).limit(1e3);if(be)throw be;o(le||[])}catch{he.error("Failed to load contacts")}finally{x(!1)}}},Z=le=>`${le.first_name} ${le.last_name||""}`.trim(),J=le=>{d(be=>be.find(fe=>fe.id===le.id)?be.filter(fe=>fe.id!==le.id):[...be,le])},K=()=>{const le=y.trim();if(!le)return;if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(le)){he.error("Invalid email");return}d(fe=>[...fe,{id:`manual-${le}`,first_name:le.split("@")[0],last_name:null,email:le}]),_("")},re=S.useMemo(()=>c.filter(le=>!!le.email).map(le=>({email:le.email,name:Z(le)})),[c]),ie=le=>{const be=le?`Hi ${le},`:"Hi there,",fe=k.split(/\n\n+/).map(je=>`

${je.replace(/\n/g,"
")}

`).join("");return`

${be}

${fe}

▶ Start Virtual Tour

Or copy this link: ${$}

`},ce=async()=>{var le;if(re.length===0){he.error("Add at least one recipient");return}R(!0);try{if(E&&n){let be=0;for(const fe of re){const{data:je,error:ve}=await V.functions.invoke("gmail-send",{body:{to:fe.email,subject:b,body:ie((le=fe.name)==null?void 0:le.split(" ")[0])}});!ve&&(je!=null&&je.success)?be+=1:console.warn("gmail-send error",ve,je)}if(be===0)throw new Error("Gmail send failed");he.success(`Sent to ${be} of ${re.length} via Gmail`)}else{const{data:be,error:fe}=await V.functions.invoke("send-virtual-tour-invite",{body:{openHouseId:r.id,recipients:re,subject:b,personalMessage:k}});if(fe)throw fe;if(!(be!=null&&be.success))throw new Error((be==null?void 0:be.error)||"Send failed");he.success(`Sent to ${be.sent} of ${be.total} recipient${be.total===1?"":"s"}`)}t(!1)}catch(be){he.error((be==null?void 0:be.message)||"Failed to send")}finally{R(!1)}},ne=async()=>{await navigator.clipboard.writeText($),O(!0),setTimeout(()=>O(!1),1500)};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"sm:max-w-[560px] w-[calc(100vw-2rem)] max-h-[90vh] overflow-y-auto overflow-x-hidden",children:[e.jsxs(Cs,{className:"min-w-0",children:[e.jsxs(Ns,{className:"flex items-center gap-2",children:[e.jsx(er,{className:"h-5 w-5 text-primary"}),"Share Virtual Tour"]}),e.jsx(nn,{className:"truncate",children:r.property_address})]}),e.jsxs("div",{className:"space-y-4 min-w-0",children:[e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-3 flex items-center gap-2 min-w-0",children:[e.jsx(Jo,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsx("code",{className:"flex-1 min-w-0 text-xs truncate",children:$}),e.jsxs(H,{variant:"ghost",size:"sm",onClick:ne,className:"shrink-0 h-7 gap-1",children:[z?e.jsx(va,{className:"h-3.5 w-3.5 text-emerald-600"}):e.jsx(ui,{className:"h-3.5 w-3.5"}),z?"Copied":"Copy"]})]}),n&&e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(H,{type:"button",variant:E?"default":"outline",size:"sm",onClick:()=>A(!0),className:"gap-1.5",children:[e.jsx(er,{className:"h-3.5 w-3.5"}),"Send from Gmail"]}),e.jsx(H,{type:"button",variant:E?"outline":"default",size:"sm",onClick:()=>A(!1),className:"gap-1.5",children:"Send from LevelUp"})]}),E&&a&&e.jsxs("p",{className:"text-xs text-muted-foreground -mt-2",children:["Sending as ",e.jsx("span",{className:"font-medium",children:a})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(ue,{className:"flex items-center gap-1.5",children:[e.jsx(Ar,{className:"h-3.5 w-3.5"}),"Recipients"]}),e.jsxs(gl,{open:h,onOpenChange:m,modal:!0,children:[e.jsx(xl,{asChild:!0,children:e.jsxs(H,{variant:"outline",role:"combobox",className:"w-full justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:c.length?`${c.length} selected`:"Select contacts..."}),e.jsx(d0,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(il,{className:"w-[440px] max-w-[calc(100vw-2rem)] p-0",align:"start",children:e.jsxs(k0,{children:[e.jsx(S0,{placeholder:"Search contacts..."}),e.jsxs(C0,{className:"max-h-[300px] overflow-y-auto",children:[e.jsx(T0,{children:p?"Loading...":"No contacts found."}),e.jsx(E0,{children:l.map(le=>{const be=!!c.find(ve=>ve.id===le.id),fe=Z(le).slice(0,80),je=(le.email||"").slice(0,80);return e.jsxs(fg,{value:`${fe} ${je}`,onSelect:()=>J(le),className:"py-2",children:[e.jsx(va,{className:Ft("mr-2 h-4 w-4 shrink-0",be?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"font-medium text-sm truncate",children:fe||"(no name)"}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:je})]})]},le.id)})})]})]})})]}),c.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5 pt-1",children:c.map(le=>e.jsxs(Xe,{variant:"secondary",className:"gap-1 pl-2 pr-1 py-0.5",children:[e.jsx("span",{className:"text-xs",children:Z(le)}),e.jsx("button",{onClick:()=>J(le),className:"hover:bg-muted-foreground/20 rounded p-0.5",children:e.jsx(Rr,{className:"h-3 w-3"})})]},le.id))}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(Se,{value:y,onChange:le=>_(le.target.value),placeholder:"Or type an email...",type:"email",onKeyDown:le=>{le.key==="Enter"&&(le.preventDefault(),K())}}),e.jsx(H,{type:"button",variant:"outline",size:"sm",onClick:K,children:"Add"})]})]}),e.jsx(Qo,{}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{htmlFor:"vt-subject",children:"Subject"}),e.jsx(Se,{id:"vt-subject",value:b,onChange:le=>j(le.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{htmlFor:"vt-message",children:"Personal Message"}),e.jsx(vr,{id:"vt-message",value:k,onChange:le=>T(le.target.value),rows:4,className:"resize-y"})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(H,{variant:"outline",onClick:()=>t(!1),disabled:D,children:"Cancel"}),e.jsxs(H,{onClick:ce,disabled:D||re.length===0||!b.trim(),className:"gap-2",children:[D?e.jsx(is,{className:"h-4 w-4 animate-spin"}):e.jsx(yn,{className:"h-4 w-4"}),D?"Sending...":`Send${re.length?` to ${re.length}`:""}`]})]})]})]})})}const Q4e="guestbook.relevelup.com";function B$s(){const{data:s,isLoading:t}=MLt(),r=ILt(),n=ert(),a=PLt(),[i,l]=S.useState(!1),[o,c]=S.useState(null),{user:d}=Ms(),h=ba(),[m,p]=S.useState(null),[x,y]=S.useState(null),[_,b]=S.useState(!1),j=S.useRef(null),[k,T]=S.useState({property_address:"",city:"",state:"",zip:"",event_date:As(new Date,"yyyy-MM-dd"),start_time:"10:00",end_time:"14:00",agent_greeting:"Welcome! Please sign in below.",event_type:"property",kind:"physical",tour_mode:"rooms"}),E=z=>{var $;const O=($=z.target.files)==null?void 0:$[0];if(O){if(O.size>5*1024*1024){En({title:"Photo must be under 5MB",variant:"destructive"});return}p(O),y(URL.createObjectURL(O))}},A=()=>{p(null),y(null),j.current&&(j.current.value="")},D=async()=>{if(!k.property_address){En({title:k.event_type==="community"?"Event name is required":"Address is required",variant:"destructive"});return}let z;if(m&&d){b(!0);const $=m.name.split(".").pop(),ee=`${h}/${Date.now()}.${$}`,{error:Z}=await V.storage.from("open-house-photos").upload(ee,m,{upsert:!0});if(Z){En({title:"Photo upload failed",description:Z.message,variant:"destructive"}),b(!1);return}const{data:J}=V.storage.from("open-house-photos").getPublicUrl(ee);z=J.publicUrl,b(!1)}const O=k.kind==="virtual"?{...k,start_time:void 0,end_time:void 0,photo_url:z}:{...k,photo_url:z};await r.mutateAsync(O),l(!1),T({property_address:"",city:"",state:"",zip:"",event_date:As(new Date,"yyyy-MM-dd"),start_time:"10:00",end_time:"14:00",agent_greeting:"Welcome! Please sign in below.",event_type:"property",kind:"physical",tour_mode:"rooms"}),A()},R=z=>{navigator.clipboard.writeText(`https://${Q4e}/${z}`),En({title:"Link copied!"})};return e.jsxs(Ss,{title:"Guest Book",children:[e.jsx(el,{children:e.jsx("title",{children:"Guest Book | LevelUp"})}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold font-serif text-foreground",children:"Guest Book"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"The modern open house sign-in experience"})]}),e.jsxs(bs,{open:i,onOpenChange:l,children:[e.jsx(Qi,{asChild:!0,children:e.jsxs(H,{children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"New Open House"]})}),e.jsxs(vs,{className:"sm:max-w-lg max-h-[90vh] flex flex-col",children:[e.jsxs(Cs,{children:[e.jsx(Ns,{children:"Create Open House"}),e.jsx(nn,{children:"Set up a new open house sign-in page"})]}),e.jsxs("div",{className:"space-y-4 pt-2 overflow-y-auto flex-1 pr-1",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Open House Type"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>T(z=>({...z,kind:"physical"})),className:`p-3 rounded-lg border text-left transition-all ${k.kind==="physical"?"border-primary bg-primary/5 ring-2 ring-primary/30":"border-border hover:border-muted-foreground/50"}`,children:[e.jsx("div",{className:"text-sm font-semibold",children:"Physical Open House"}),e.jsx("div",{className:"text-xs text-muted-foreground mt-0.5",children:"In-person sign-in at the property"})]}),e.jsxs("button",{type:"button",onClick:()=>T(z=>({...z,kind:"virtual",event_type:"property"})),className:`p-3 rounded-lg border text-left transition-all ${k.kind==="virtual"?"border-primary bg-primary/5 ring-2 ring-primary/30":"border-border hover:border-muted-foreground/50"}`,children:[e.jsxs("div",{className:"text-sm font-semibold flex items-center gap-1.5",children:["Virtual Open House ",e.jsx("span",{className:"text-[10px] font-medium px-1.5 py-0.5 rounded bg-primary/10 text-primary uppercase tracking-wide",children:"New"})]}),e.jsx("div",{className:"text-xs text-muted-foreground mt-0.5",children:"Always-on branded tour via link or QR"})]})]})]}),k.kind==="physical"&&e.jsx("div",{className:"flex items-center gap-3 p-3 rounded-lg border border-border bg-muted/30",children:e.jsxs("div",{className:"flex gap-1 flex-1",children:[e.jsx("button",{type:"button",onClick:()=>T(z=>({...z,event_type:"property"})),className:`flex-1 px-3 py-2 rounded-md text-sm font-medium transition-colors ${k.event_type==="property"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:"Single Property"}),e.jsx("button",{type:"button",onClick:()=>T(z=>({...z,event_type:"community"})),className:`flex-1 px-3 py-2 rounded-md text-sm font-medium transition-colors ${k.event_type==="community"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:"Community Event"})]})}),k.kind==="virtual"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Tour Format"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>T(z=>({...z,tour_mode:"rooms"})),className:`p-3 rounded-lg border text-left transition-all ${k.tour_mode==="rooms"?"border-primary bg-primary/5 ring-2 ring-primary/30":"border-border hover:border-muted-foreground/50"}`,children:[e.jsx("div",{className:"text-sm font-semibold",children:"Room-by-room"}),e.jsx("div",{className:"text-xs text-muted-foreground mt-0.5",children:"Photos & videos per room"})]}),e.jsxs("button",{type:"button",onClick:()=>T(z=>({...z,tour_mode:"single_video"})),className:`p-3 rounded-lg border text-left transition-all ${k.tour_mode==="single_video"?"border-primary bg-primary/5 ring-2 ring-primary/30":"border-border hover:border-muted-foreground/50"}`,children:[e.jsx("div",{className:"text-sm font-semibold",children:"Single video"}),e.jsx("div",{className:"text-xs text-muted-foreground mt-0.5",children:"One walkthrough video"})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"You can add the video or room media in settings after creating."})]}),e.jsxs("div",{children:[e.jsx(ue,{children:k.event_type==="community"?"Event Name *":"Property Address *"}),e.jsx(Se,{value:k.property_address,onChange:z=>T(O=>({...O,property_address:z.target.value})),placeholder:k.event_type==="community"?"Spring Festival at Riverside Estates":"123 Main Street"})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx(ue,{children:"City"}),e.jsx(Se,{value:k.city,onChange:z=>T(O=>({...O,city:z.target.value})),placeholder:"Austin"})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"State"}),e.jsx(Se,{value:k.state,onChange:z=>T(O=>({...O,state:z.target.value})),placeholder:"TX",maxLength:2})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"ZIP"}),e.jsx(Se,{value:k.zip,onChange:z=>T(O=>({...O,zip:z.target.value})),placeholder:"78701"})]})]}),k.kind==="virtual"?e.jsxs("div",{className:"rounded-lg border border-dashed border-muted-foreground/30 bg-muted/20 p-3 text-xs text-muted-foreground",children:["🕒 Virtual open houses are ",e.jsx("span",{className:"font-medium text-foreground",children:"always on"})," — no date or time needed. Visitors can tour any time via your link or QR code."]}):e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx(ue,{children:"Date"}),e.jsx(Se,{type:"date",value:k.event_date,onChange:z=>T(O=>({...O,event_date:z.target.value}))})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Start Time"}),e.jsx(Se,{type:"time",value:k.start_time,onChange:z=>T(O=>({...O,start_time:z.target.value}))})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"End Time"}),e.jsx(Se,{type:"time",value:k.end_time,onChange:z=>T(O=>({...O,end_time:z.target.value}))})]})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Welcome Message"}),e.jsx(vr,{value:k.agent_greeting,onChange:z=>T(O=>({...O,agent_greeting:z.target.value})),placeholder:"Welcome! Please sign in below."})]}),e.jsxs("div",{children:[e.jsx(ue,{children:k.event_type==="community"?"Event Photo":"Property Photo"}),e.jsx("input",{ref:j,type:"file",accept:"image/*",onChange:E,className:"hidden"}),x?e.jsxs("div",{className:"relative mt-1 rounded-xl overflow-hidden border border-border",children:[e.jsx("img",{src:x,alt:"Property preview",className:"w-full h-40 object-cover"}),e.jsx("button",{type:"button",onClick:A,className:"absolute top-2 right-2 bg-black/60 hover:bg-black/80 text-white rounded-full p-1 transition-colors",children:e.jsx(Rr,{className:"h-4 w-4"})})]}):e.jsxs("button",{type:"button",onClick:()=>{var z;return(z=j.current)==null?void 0:z.click()},className:"mt-1 w-full h-32 rounded-xl border-2 border-dashed border-muted-foreground/25 hover:border-muted-foreground/50 flex flex-col items-center justify-center gap-2 text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(f_,{className:"h-6 w-6"}),e.jsxs("span",{className:"text-sm",children:["Add a ",k.event_type==="community"?"cover":"property"," photo"]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Max 5MB"})]})]}),e.jsx(H,{onClick:D,disabled:r.isPending||_,className:"w-full",children:_?"Uploading photo...":r.isPending?"Creating...":k.kind==="virtual"?"Create Virtual Open House":k.event_type==="community"?"Create Community Event":"Create Open House"})]})]})]})]}),t?e.jsx("div",{className:"grid gap-4",children:[1,2].map(z=>e.jsx(ke,{className:"animate-pulse",children:e.jsxs(Ot,{children:[e.jsx("div",{className:"h-5 bg-muted rounded w-48"}),e.jsx("div",{className:"h-4 bg-muted rounded w-32 mt-2"})]})},z))}):s!=null&&s.length?e.jsx("div",{className:"space-y-4",children:s.map(z=>e.jsx(z$s,{openHouse:z,isExpanded:o===z.id,onToggle:()=>c(o===z.id?null:z.id),onCopyLink:()=>R(z.slug||""),onToggleActive:()=>n.mutate({id:z.id,is_active:!z.is_active}),onDelete:()=>a.mutate(z.id)},z.id))}):e.jsx(ke,{className:"border-dashed",children:e.jsxs(Oe,{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx("div",{className:"w-16 h-16 rounded-2xl bg-primary/10 flex items-center justify-center mb-4",children:e.jsx(y_,{className:"h-8 w-8 text-primary"})}),e.jsx("h3",{className:"text-lg font-semibold mb-1",children:"No Open Houses Yet"}),e.jsx("p",{className:"text-muted-foreground text-sm max-w-sm mb-6",children:"Create your first open house to get a beautiful, mobile-friendly sign-in page with a shareable link and QR code."}),e.jsxs(H,{onClick:()=>l(!0),children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Create Your First Open House"]})]})})]})]})}function z$s({openHouse:s,isExpanded:t,onToggle:r,onCopyLink:n,onToggleActive:a,onDelete:i}){const{data:l}=Jst(t?s.id:void 0),{data:o}=yt({queryKey:["agent-profile-flyer",s.agent_id],queryFn:async()=>{const{data:R,error:z}=await V.from("profiles").select("name, avatar_url, phone, title, brokerages:brokerage_id(name)").eq("id",s.agent_id).single();if(z)throw z;const O=R.brokerages;return{...R,brokerage_name:(O==null?void 0:O.name)||null}},enabled:!!s.agent_id}),[c,d]=S.useState(!1),[h,m]=S.useState(!1),[p,x]=S.useState(!1),[y,_]=S.useState(!1),b=S.useRef(null),j=`https://${Q4e}/${s.slug}`,k=R=>{if(!R)return"";const[z,O]=R.split(":"),$=parseInt(z),ee=$>=12?"PM":"AM";return`${$>12?$-12:$||12}:${O} ${ee}`},T=()=>{if(!(l!=null&&l.length))return;const R=["First Name","Last Name","Email","Phone","Intent","Wants Market Updates","Message","Signed In"],z=l.map(J=>[J.first_name,J.last_name||"",J.email||"",J.phone||"",J.visitor_intent||"",J.wants_market_updates?"Yes":"No",(J.message||"").replace(/"/g,'""'),As(new Date(J.created_at),"MM/dd/yyyy h:mm a")]),O=[R,...z].map(J=>J.map(K=>`"${K}"`).join(",")).join(` `),$=new Blob([O],{type:"text/csv"}),ee=URL.createObjectURL($),Z=document.createElement("a");Z.href=ee,Z.download=`${s.property_address.replace(/[^a-zA-Z0-9]/g,"-")}-visitors.csv`,Z.click(),URL.revokeObjectURL(ee)},E=S.useCallback(()=>{if(!b.current)return;const R=b.current.querySelector("svg");if(!R)return;const z=new XMLSerializer().serializeToString(R),O=document.createElement("canvas");O.width=1024,O.height=1024;const $=O.getContext("2d"),ee=new Image;ee.onload=()=>{$==null||$.drawImage(ee,0,0,1024,1024);const Z=document.createElement("a");Z.download=`${s.property_address.replace(/[^a-zA-Z0-9]/g,"-")}-qr.png`,Z.href=O.toDataURL("image/png"),Z.click()},ee.src="data:image/svg+xml;base64,"+btoa(unescape(encodeURIComponent(z)))},[s.property_address]),A=S.useCallback(()=>{var ge;if(!b.current)return;const R=b.current.querySelector("svg");if(!R)return;const z=new XMLSerializer().serializeToString(R),O="data:image/svg+xml;base64,"+btoa(unescape(encodeURIComponent(z))),$=As(new Date(s.event_date+"T00:00:00"),"EEEE, MMMM d, yyyy"),ee=s.start_time?`${k(s.start_time)}${s.end_time?" – "+k(s.end_time):""}`:"",Z=[s.city,s.state].filter(Boolean).join(", "),J=s.agent_greeting||"Welcome! Please sign in below.",K=!!s.photo_url,re=!!o,ie=K||re,ce=K&&re,ne=ce?"0.35in 0.75in 0.3in":"0.55in 0.75in 0.45in",le=ce?"28px":"34px",be=ce?"0.2in 0.75in":ie?"0.3in 0.75in":"0.4in 0.75in",fe=ie?"0.15in":"0.3in",je=ie?"0.15in":"0.3in",ve=ce?"14px 36px":"22px 44px",We=ce?"20px":"24px",Ve=ie?"0.2in":"0.35in",Le=ce?"1.8in":"2.4in",Me=ie?"0.15in":"0.3in",ze=ce?"140px":ie?"160px":"200px",Pe=ce?"16px":"24px",Ie=ce?"10px 20px":"16px 28px",De=ce?"44px":"56px",pe="0.15in",tt=window.open("","_blank");tt&&(tt.document.write(` Open House – ${s.property_address}
${s.event_type==="community"?"Community Event":"Open House"}
${s.property_address}
${Z?`
${Z}${s.zip?" "+s.zip:""}
`:""}
Date
${$}
${ee?`
Time
${ee}
`:""}
${J}
${o?`
${o.avatar_url?`${o.name}`:`
${((ge=o.name)==null?void 0:ge.charAt(0))||"A"}
`}
Hosted By
${o.name}
${o.title?`
${o.title}
`:""} ${o.brokerage_name?`
${o.brokerage_name}
`:""} ${o.phone?`
${o.phone}
`:""}
`:""} ${s.photo_url?`Property`:""}
QR Code
Scan to Sign In
Point your phone camera at the QR code
`),tt.document.close(),setTimeout(()=>{tt.focus(),tt.print()},500))},[s,j,o]),D=async()=>{_(!0);try{const{error:R}=await V.functions.invoke("guestbook-email-link",{body:{openHouseId:s.id}});if(R)throw R;En({title:"Email sent!",description:"Check your inbox for the guest book link."})}catch(R){En({title:"Failed to send",description:R.message,variant:"destructive"})}finally{_(!1)}};return e.jsxs(ke,{className:`transition-all ${s.is_active?"border-primary/30":"opacity-75"}`,children:[e.jsx(Ot,{className:"pb-3",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(zt,{className:"text-base leading-snug break-words",children:s.property_address}),e.jsxs("div",{className:"flex items-center gap-1.5 mt-1.5 flex-wrap",children:[e.jsx(Xe,{variant:s.is_active?"default":"secondary",className:"shrink-0 text-[11px]",children:s.is_active?"Active":"Inactive"}),s.kind==="virtual"?e.jsxs(Xe,{variant:"outline",className:"shrink-0 gap-1 text-[11px] bg-purple-50 text-purple-700 dark:bg-purple-900/30 dark:text-purple-300 border-purple-200 dark:border-purple-800",children:[e.jsx(Bn,{className:"h-3 w-3"}),"Virtual"]}):e.jsxs(Xe,{variant:"outline",className:"shrink-0 gap-1 text-[11px] bg-emerald-50 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-300 border-emerald-200 dark:border-emerald-800",children:[e.jsx(Qa,{className:"h-3 w-3"}),"In-Person"]}),s.agent_name&&e.jsxs(Xe,{variant:"outline",className:"shrink-0 gap-1 text-[11px] bg-blue-50 text-blue-700 dark:bg-blue-900/30 dark:text-blue-300 border-blue-200 dark:border-blue-800",children:[e.jsx(io,{className:"h-3 w-3"}),s.agent_name]}),s.event_type==="community"&&e.jsxs(Xe,{variant:"outline",className:"shrink-0 gap-1 text-[11px]",children:[e.jsx(Xa,{className:"h-3 w-3"}),"Community"]})]})]}),e.jsx(H,{variant:"ghost",size:"icon",onClick:r,className:"shrink-0 -mr-2 -mt-1",children:t?e.jsx(cx,{className:"h-4 w-4"}):e.jsx(Io,{className:"h-4 w-4"})})]}),e.jsxs(Br,{className:"flex flex-wrap items-center gap-x-4 gap-y-1 text-xs",children:[s.city&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Qa,{className:"h-3 w-3"}),s.city,s.state?`, ${s.state}`:""]}),s.kind==="virtual"?e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Pn,{className:"h-3 w-3"}),"Always on"]}):e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Nn,{className:"h-3 w-3"}),As(new Date(s.event_date+"T00:00:00"),"MMM d, yyyy")]}),s.start_time&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Pn,{className:"h-3 w-3"}),k(s.start_time),s.end_time?` – ${k(s.end_time)}`:""]})]}),e.jsxs("span",{className:"flex items-center gap-1 font-medium",children:[e.jsx(Ar,{className:"h-3 w-3"}),s.visitor_count," signed in"]}),s.qr_scan_count>0&&e.jsxs("span",{className:"flex items-center gap-1 text-muted-foreground",children:[e.jsx(y_,{className:"h-3 w-3"}),s.qr_scan_count," scan",s.qr_scan_count===1?"":"s"]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 sm:flex sm:flex-wrap sm:items-center",children:[e.jsxs(H,{variant:"outline",size:"sm",onClick:()=>window.location.href=`/mission-control/guest-book/live/${s.id}`,title:"Go Live",className:"h-9 w-full justify-center gap-1.5 text-xs text-emerald-600 border-emerald-200 hover:bg-emerald-50 dark:text-emerald-400 dark:border-emerald-800 dark:hover:bg-emerald-900/20 sm:h-8 sm:w-auto",children:[e.jsx(G2,{className:"h-3.5 w-3.5"}),"Live"]}),e.jsxs(H,{variant:"outline",size:"sm",onClick:n,title:"Copy link",className:"h-9 w-full justify-center gap-1.5 text-xs sm:h-8 sm:w-auto",children:[e.jsx(ui,{className:"h-3.5 w-3.5"}),"Copy"]}),s.kind==="virtual"&&e.jsxs(H,{variant:"outline",size:"sm",onClick:()=>x(!0),title:"Share tour via email",className:"h-9 w-full justify-center gap-1.5 text-xs text-primary border-primary/30 hover:bg-primary/10 sm:h-8 sm:w-auto",children:[e.jsx(cd,{className:"h-3.5 w-3.5"}),"Share"]}),s.kind==="virtual"&&e.jsxs(H,{variant:"outline",size:"sm",onClick:()=>window.open(`/guestbook/${s.slug}?preview=1`,"_blank"),title:"Preview tour as visitor",className:"h-9 w-full justify-center gap-1.5 text-xs text-primary border-primary/30 hover:bg-primary/10 sm:h-8 sm:w-auto",children:[e.jsx(Bn,{className:"h-3.5 w-3.5"}),"Preview Tour"]}),e.jsxs(H,{variant:"outline",size:"sm",onClick:()=>d(!0),title:"QR Code",className:"h-9 w-full justify-center gap-1.5 text-xs sm:h-8 sm:w-auto",children:[e.jsx(y_,{className:"h-3.5 w-3.5"}),"QR"]}),e.jsx(H,{variant:"outline",size:"sm",onClick:()=>m(!0),title:"Settings",className:"h-9 w-full justify-center text-xs sm:h-8 sm:w-auto",children:e.jsx(Go,{className:"h-3.5 w-3.5"})}),e.jsx(H,{variant:"outline",size:"sm",onClick:()=>window.open(j,"_blank"),title:"Preview",className:"h-9 w-full justify-center text-xs sm:h-8 sm:w-auto",children:e.jsx(gn,{className:"h-3.5 w-3.5"})}),e.jsx(H,{variant:"outline",size:"sm",onClick:a,title:s.is_active?"Deactivate":"Activate",className:"h-9 w-full justify-center text-xs sm:h-8 sm:w-auto",children:s.is_active?e.jsx($f,{className:"h-3.5 w-3.5"}):e.jsx(Bn,{className:"h-3.5 w-3.5"})}),e.jsx(H,{variant:"outline",size:"sm",onClick:i,title:"Delete",className:"h-9 w-full justify-center text-xs text-destructive border-destructive/30 hover:bg-destructive/10 sm:h-8 sm:w-auto",children:e.jsx(Dr,{className:"h-3.5 w-3.5"})})]})]})}),t&&e.jsxs(Oe,{className:"pt-0",children:[e.jsx(Qo,{className:"mb-4"}),e.jsxs("div",{className:"mb-3",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground mb-1",children:"Share Link"}),e.jsxs("code",{className:"text-xs bg-muted/50 px-2 py-1 rounded block truncate",children:["https://",Q4e,"/",s.slug]})]}),l!=null&&l.length?e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-xs font-medium text-muted-foreground",children:[l.length," Visitor",l.length!==1?"s":""]}),e.jsxs(H,{variant:"outline",size:"sm",onClick:T,className:"h-7 text-xs gap-1",children:[e.jsx(hi,{className:"h-3 w-3"}),"Export CSV"]})]}),e.jsx("div",{className:"rounded-lg border overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-muted/30 text-xs text-muted-foreground",children:[e.jsx("th",{className:"text-left p-2 font-medium",children:"Name"}),e.jsx("th",{className:"text-left p-2 font-medium hidden sm:table-cell",children:"Contact"}),e.jsx("th",{className:"text-left p-2 font-medium hidden md:table-cell",children:"Intent"}),e.jsx("th",{className:"text-left p-2 font-medium",children:"Time"})]})}),e.jsx("tbody",{children:l.map(R=>e.jsxs("tr",{className:"border-t border-border/50",children:[e.jsxs("td",{className:"p-2 font-medium",children:[R.first_name,R.last_name?` ${R.last_name}`:""]}),e.jsxs("td",{className:"p-2 text-muted-foreground hidden sm:table-cell",children:[R.email&&e.jsx("div",{className:"truncate max-w-[180px]",children:R.email}),R.phone&&e.jsx("div",{className:"text-xs",children:R.phone})]}),e.jsx("td",{className:"p-2 hidden md:table-cell",children:R.visitor_intent?e.jsx(Xe,{variant:"outline",className:"text-xs capitalize",children:R.visitor_intent}):R.partial_signin?e.jsx(Xe,{variant:"outline",className:"text-xs text-amber-600 border-amber-300 dark:text-amber-400 dark:border-amber-700",children:"Didn't finish"}):null}),e.jsx("td",{className:"p-2 text-xs text-muted-foreground",children:As(new Date(R.created_at),"h:mm a")})]},R.id))})]})})]}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"No visitors yet. Share the link to start collecting sign-ins!"}),s.kind==="virtual"&&e.jsx("div",{className:"mt-4",children:e.jsx(O$s,{openHouseId:s.id})}),s.enable_survey&&e.jsx("div",{className:"mt-4",children:e.jsx(D$s,{openHouseId:s.id})})]}),e.jsx(bs,{open:c,onOpenChange:d,children:e.jsxs(vs,{className:"sm:max-w-sm",children:[e.jsxs(Cs,{children:[e.jsx(Ns,{children:"QR Code"}),e.jsx(nn,{className:"truncate",children:s.property_address})]}),e.jsxs("div",{className:"flex flex-col items-center gap-4 py-4",children:[e.jsx("div",{ref:b,className:"bg-white p-4 rounded-xl",children:e.jsx(Vz,{value:j,size:240,level:"H"})}),e.jsx("p",{className:"text-xs text-muted-foreground text-center break-all",children:j}),e.jsxs("div",{className:"flex gap-2 w-full",children:[e.jsxs(H,{variant:"outline",className:"flex-1",onClick:E,children:[e.jsx(hi,{className:"h-4 w-4 mr-2"}),"Download"]}),e.jsxs(H,{variant:"outline",className:"flex-1",onClick:A,children:[e.jsx(SF,{className:"h-4 w-4 mr-2"}),"Print Flyer"]})]}),e.jsxs(H,{variant:"default",className:"w-full",onClick:D,disabled:y,children:[e.jsx(er,{className:"h-4 w-4 mr-2"}),y?"Sending...":"Email Link to Me"]})]})]})}),e.jsx(P$s,{open:h,onOpenChange:m,openHouse:s}),s.kind==="virtual"&&e.jsx(F$s,{open:p,onOpenChange:x,openHouse:{id:s.id,slug:s.slug,property_address:s.property_address,city:s.city,state:s.state}})]})}function $$s(){const{slug:s}=Po();return s?e.jsx(Gat,{slug:s}):e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center p-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Portal Not Found"}),e.jsx("p",{className:"text-slate-500",children:"No portal slug was provided."})]})})}function Mvt({photoUrl:s,videoUrl:t,onPhotoChange:r,onVideoChange:n,contactId:a}){const{user:i}=Ms(),l=Cj(),o=S.useRef(null),c=S.useRef(null),[d,h]=S.useState(!1),[m,p]=S.useState(!1),[x,y]=S.useState(0),_=async j=>{if(i){h(!0);try{const k=j.name.split(".").pop()||"jpg",T=`${i.id}/card-${Date.now()}.${k}`,{error:E}=await V.storage.from("listing-photos").upload(T,j);if(E)throw E;const{data:{publicUrl:A}}=V.storage.from("listing-photos").getPublicUrl(T);r(A),he.success("Photo uploaded")}catch(k){he.error(k.message||"Failed to upload photo")}finally{h(!1)}}},b=async j=>{if(i){if(j.size>500*1024*1024){he.error("Video must be under 500MB");return}p(!0),y(0);try{const{videoId:k,libraryId:T}=await tM(`Card Video - ${Date.now()}`),{uploadUrl:E,apiKey:A}=await sM(k);await new Promise((z,O)=>{const $=new XMLHttpRequest;$.upload.addEventListener("progress",ee=>{ee.lengthComputable&&y(Math.round(ee.loaded/ee.total*100))}),$.addEventListener("load",()=>{$.status>=200&&$.status<300?z():O(new Error("Upload failed"))}),$.addEventListener("error",()=>O(new Error("Upload failed"))),$.open("PUT",E),$.setRequestHeader("AccessKey",A),$.send(j)});const D=`https://iframe.mediadelivery.net/embed/${T}/${k}`;n(D);const R=parseFloat((j.size/(1024*1024)).toFixed(2));await l.mutateAsync({bunny_video_id:k,playback_url:`https://iframe.mediadelivery.net/play/${T}/${k}`,file_size_mb:R,title:"Card Video",status:"processing",touch_type:"video",contact_id:a||void 0}),he.success("Video uploaded & added to your library")}catch(k){he.error(k.message||"Failed to upload video")}finally{p(!1),y(0)}}};return e.jsxs("div",{className:"space-y-3",children:[e.jsx(ue,{children:"Media (optional)"}),e.jsxs(ta,{defaultValue:"photo",className:"w-full",children:[e.jsxs(Qn,{className:"grid w-full grid-cols-2",children:[e.jsxs(ts,{value:"photo",className:"gap-1.5 text-xs",children:[e.jsx(wl,{className:"h-3.5 w-3.5"}),"Photo"]}),e.jsxs(ts,{value:"video",className:"gap-1.5 text-xs",children:[e.jsx(xn,{className:"h-3.5 w-3.5"}),"Video"]})]}),e.jsxs(cs,{value:"photo",className:"mt-3",children:[s?e.jsxs("div",{className:"relative rounded-lg overflow-hidden border border-border",children:[e.jsx("img",{src:s,alt:"Card photo",className:"w-full h-40 object-cover"}),e.jsx(H,{variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-7 w-7",onClick:()=>r(null),children:e.jsx(Rr,{className:"h-3.5 w-3.5"})})]}):e.jsx("button",{onClick:()=>{var j;return(j=o.current)==null?void 0:j.click()},disabled:d,className:"w-full h-32 border-2 border-dashed border-border rounded-lg flex flex-col items-center justify-center gap-2 text-muted-foreground hover:border-primary/40 hover:bg-accent/50 transition-colors",children:d?e.jsx(is,{className:"h-6 w-6 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(lx,{className:"h-6 w-6"}),e.jsx("span",{className:"text-xs",children:"Upload a photo"})]})}),e.jsx("input",{ref:o,type:"file",accept:"image/*",className:"hidden",onChange:j=>{var T;const k=(T=j.target.files)==null?void 0:T[0];k&&_(k),j.target.value=""}})]}),e.jsxs(cs,{value:"video",className:"mt-3",children:[t?e.jsxs("div",{className:"relative rounded-lg overflow-hidden border border-border",children:[e.jsx("iframe",{src:`${t}?autoplay=false&responsive=true`,className:"w-full aspect-video",allow:"autoplay; encrypted-media",allowFullScreen:!0}),e.jsx(H,{variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-7 w-7",onClick:()=>n(null),children:e.jsx(Rr,{className:"h-3.5 w-3.5"})})]}):e.jsx("button",{onClick:()=>{var j;return(j=c.current)==null?void 0:j.click()},disabled:m,className:"w-full h-32 border-2 border-dashed border-border rounded-lg flex flex-col items-center justify-center gap-2 text-muted-foreground hover:border-primary/40 hover:bg-accent/50 transition-colors",children:m?e.jsxs("div",{className:"flex flex-col items-center gap-2",children:[e.jsx(is,{className:"h-6 w-6 animate-spin"}),e.jsxs("span",{className:"text-xs",children:["Uploading... ",x,"%"]}),e.jsx("div",{className:"w-32 h-1.5 bg-muted rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-primary rounded-full transition-all",style:{width:`${x}%`}})})]}):e.jsxs(e.Fragment,{children:[e.jsx(Ea,{className:"h-6 w-6"}),e.jsx("span",{className:"text-xs",children:"Upload a video (max 500MB)"})]})}),!t&&!m&&e.jsx("div",{className:"mt-2",children:e.jsx(d6e,{contactId:a,onVideoReady:j=>n(j)})}),e.jsx("input",{ref:c,type:"file",accept:"video/*",className:"hidden",onChange:j=>{var T;const k=(T=j.target.files)==null?void 0:T[0];k&&b(k),j.target.value=""}}),e.jsx("p",{className:"text-[10px] text-muted-foreground/60 mt-1.5 text-center",children:"Videos are also saved to your Video Library"})]})]})]})}const U$s=[{type:"home_anniversary",label:"Home Anniversary",emoji:"🏡",description:"Celebrate their homeownership milestone",gradient:"from-blue-500/20 to-slate-500/20 border-blue-200 dark:border-blue-800"},{type:"birthday",label:"Birthday",emoji:"🎂",description:"Wish them a happy birthday",gradient:"from-pink-500/20 to-purple-500/20 border-pink-200 dark:border-pink-800"},{type:"just_sold",label:"Just Sold",emoji:"🎉",description:"Announce a successful closing",gradient:"from-emerald-500/20 to-teal-500/20 border-emerald-200 dark:border-emerald-800"},{type:"just_listed",label:"Just Listed",emoji:"🏠",description:"Share a new listing announcement",gradient:"from-amber-500/20 to-orange-500/20 border-amber-200 dark:border-amber-800"},{type:"thank_you",label:"Thank You",emoji:"💐",description:"Show your appreciation",gradient:"from-rose-500/20 to-pink-500/20 border-rose-200 dark:border-rose-800"},{type:"congratulations",label:"Congratulations",emoji:"🏆",description:"Celebrate their achievements",gradient:"from-yellow-500/20 to-amber-500/20 border-yellow-200 dark:border-yellow-800"},{type:"holiday",label:"Holiday",emoji:"🎄",description:"Send seasonal greetings",gradient:"from-red-500/20 to-green-500/20 border-red-200 dark:border-red-800"},{type:"thinking_of_you",label:"Thinking of You",emoji:"💭",description:"Stay top of mind with a personal touch",gradient:"from-violet-500/20 to-indigo-500/20 border-violet-200 dark:border-violet-800"}];function q$s({onSelect:s}){return e.jsx("div",{className:"grid grid-cols-2 gap-2.5",children:U$s.map((t,r)=>e.jsxs(Ur.button,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:r*.04,duration:.25},onClick:()=>s(t.type),className:`group relative flex flex-col items-start gap-1 p-3.5 rounded-xl border bg-gradient-to-br ${t.gradient} hover:shadow-md hover:scale-[1.02] active:scale-[0.98] transition-all text-left`,children:[e.jsx("span",{className:"text-2xl",children:t.emoji}),e.jsx("span",{className:"text-sm font-semibold text-foreground",children:t.label}),e.jsx("span",{className:"text-[11px] text-muted-foreground leading-tight",children:t.description})]},t.type))})}const iD={home_anniversary:{title:["Happy Home","Anniversary"],icon:"🏡",emojis:["🏡","✨","🎉","❤️","🎊","🏠"],defaultMessage:"Wishing you many more wonderful years of memories in your beautiful home. Thank you for letting me be part of your journey."},just_listed:{title:["Just","Listed!"],icon:"🏠",emojis:["🏠","📋","🔑","⭐","🎯","✨"],defaultMessage:"Exciting news — this beautiful property just hit the market! Contact me for a private showing."},just_sold:{title:["Just","Sold!"],icon:"🎉",emojis:["🎉","🏡","🔑","🥂","🎊","💰"],defaultMessage:"Another successful closing! Congratulations to the new homeowners. It was a pleasure making this happen."},congratulations:{title:["Congratulations!",""],icon:"🏆",emojis:["🎉","🥳","🏆","⭐","🎊","✨"],defaultMessage:"What an incredible milestone! I'm so happy for you. Wishing you all the best in this exciting new chapter."},birthday:{title:["Happy","Birthday!"],icon:"🎂",emojis:["🎂","🎈","🎁","🥳","🎉","🧁"],defaultMessage:"Wishing you the happiest of birthdays! May this year bring you joy, laughter, and everything you've been dreaming of."},holiday:{title:["Happy","Holidays!"],icon:"🎄",emojis:["🎄","❄️","🎁","⭐","🕯️","🎅"],defaultMessage:"Wishing you and your family a season filled with warmth, joy, and cherished moments. Happy Holidays!"},thank_you:{title:["Thank","You!"],icon:"💐",emojis:["💐","🙏","❤️","⭐","✨","🤝"],defaultMessage:"Thank you so much for your trust and confidence. It truly means the world to me. I'm always here for you!"},thinking_of_you:{title:["Thinking","Of You"],icon:"💭",emojis:["💭","❤️","🌸","☀️","🦋","💫"],defaultMessage:"Just wanted to reach out and let you know I'm thinking of you. I hope you're doing well — don't hesitate to reach out anytime!"}};function UWe({initialOpen:s,initialCardType:t,initialContactId:r,initialRecipientName:n,initialAddress:a,initialDate:i,onOpenChange:l}){const{user:o}=Ms(),c=ns(),[d,h]=S.useState(!1),[m,p]=S.useState("type"),[x,y]=S.useState(""),[_,b]=S.useState(null),[j,k]=S.useState(!1),[T,E]=S.useState("home_anniversary"),[A,D]=S.useState(""),[R,z]=S.useState(""),[O,$]=S.useState(""),[ee,Z]=S.useState(""),[J,K]=S.useState("elegant"),[re,ie]=S.useState(null),[ce,ne]=S.useState(null),le=S.useState(!1);!le[0]&&s&&t&&(le[1](!0),h(!0),E(t),r&&b(r),n&&D(n),a&&z(a),i&&$(i),p(n?"details":"contact"));const{data:be}=yt({queryKey:["contacts-for-card",o==null?void 0:o.id,x],queryFn:async()=>{let Ie=V.from("innercircle_contacts").select("id, first_name, last_name, address, city, state, home_anniversary, email, phone").eq("owner_user_id",o.id).order("first_name").limit(20);x&&(Ie=Ie.or(`first_name.ilike.%${x}%,last_name.ilike.%${x}%`));const{data:De,error:pe}=await Ie;if(pe)throw pe;return De},enabled:!!(o!=null&&o.id)&&d}),{data:fe}=yt({queryKey:["agent-profile-card",o==null?void 0:o.id],queryFn:async()=>{const{data:Ie,error:De}=await V.from("profiles").select("name, email, phone, avatar_url, brokerage:brokerages(name)").eq("id",o.id).single();if(De)throw De;return Ie},enabled:!!(o!=null&&o.id)}),je=Ie=>{b(Ie.id),D(`${Ie.first_name}${Ie.last_name?" "+Ie.last_name:""}`),z([Ie.address,Ie.city,Ie.state].filter(Boolean).join(", ")),$(Ie.home_anniversary||""),p("details")},ve=Ie=>{E(Ie),p("contact")},We=async()=>{var Ie;if(!(!o||!fe)){k(!0);try{const De={owner_user_id:o.id,contact_id:_,card_type:T,template:J,recipient_name:A,property_address:R||null,home_anniversary_date:O||null,custom_message:ee||null,property_photo_url:re||null,video_url:ce||null,agent_name:fe.name||"Agent",agent_photo_url:fe.avatar_url,agent_phone:fe.phone,agent_email:fe.email,agent_brokerage:((Ie=fe.brokerage)==null?void 0:Ie.name)||null},{error:pe}=await V.from("sendable_cards").insert(De);if(pe)throw pe;he.success("Card created! Copy the link to share it."),c.invalidateQueries({queryKey:["sendable-cards"]}),Ve()}catch(De){he.error(De.message||"Failed to create card")}finally{k(!1)}}},Ve=()=>{h(!1),p("type"),E("home_anniversary"),y(""),b(null),D(""),z(""),$(""),Z(""),K("elegant"),ie(null),ne(null)},Le={home_anniversary:"Home Anniversary",just_listed:"Just Listed",just_sold:"Just Sold",congratulations:"Congratulations",birthday:"Birthday",holiday:"Holiday",thank_you:"Thank You",thinking_of_you:"Thinking of You"},Me=iD[T],ze=T==="home_anniversary",Pe=["home_anniversary","just_listed","just_sold"].includes(T);return e.jsxs(bs,{open:d,onOpenChange:Ie=>{Ie?h(!0):(Ve(),l==null||l(!1))},children:[e.jsx(Qi,{asChild:!0,children:e.jsxs(H,{className:"gap-2",children:[e.jsx(Ys,{className:"h-4 w-4"}),"Create Card"]})}),e.jsxs(vs,{className:"sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(Cs,{children:e.jsx(Ns,{children:m==="type"?"What type of card?":m==="contact"?`${Le[T]} — Choose a Contact`:`${Le[T]} — Customize`})}),m==="type"&&e.jsx(q$s,{onSelect:ve}),m==="contact"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs(H,{variant:"ghost",size:"sm",className:"gap-1.5 -ml-2 text-muted-foreground",onClick:()=>p("type"),children:[e.jsx(za,{className:"h-3.5 w-3.5"})," Back to card types"]}),e.jsxs("div",{className:"relative",children:[e.jsx(Mn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Se,{placeholder:"Search contacts...",value:x,onChange:Ie=>y(Ie.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"space-y-1 max-h-64 overflow-y-auto",children:[be==null?void 0:be.map(Ie=>e.jsxs("button",{onClick:()=>je(Ie),className:"w-full flex items-center gap-3 p-3 rounded-lg hover:bg-accent text-left transition-colors",children:[e.jsx("div",{className:"h-9 w-9 rounded-full bg-primary/10 flex items-center justify-center shrink-0",children:e.jsx(io,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("p",{className:"text-sm font-medium truncate",children:[Ie.first_name," ",Ie.last_name]}),Ie.address&&e.jsxs("p",{className:"text-xs text-muted-foreground truncate flex items-center gap-1",children:[e.jsx(Fn,{className:"h-3 w-3"}),Ie.address]})]}),Ie.home_anniversary&&T==="home_anniversary"&&e.jsx("span",{className:"text-[10px] text-emerald-600 bg-emerald-500/10 px-2 py-0.5 rounded-full shrink-0",children:"Anniversary set"})]},Ie.id)),(be==null?void 0:be.length)===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"No contacts found"})]}),e.jsx("div",{className:"border-t pt-3",children:e.jsx(H,{variant:"outline",size:"sm",className:"w-full",onClick:()=>{p("details")},children:"Skip — enter details manually"})})]}),m==="details"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs(H,{variant:"ghost",size:"sm",className:"gap-1.5 -ml-2 text-muted-foreground",onClick:()=>p("contact"),children:[e.jsx(za,{className:"h-3.5 w-3.5"})," Back"]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Recipient Name"}),e.jsx(Se,{value:A,onChange:Ie=>D(Ie.target.value),placeholder:"John & Jane Smith"})]}),Pe&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Property Address"}),e.jsx(Se,{value:R,onChange:Ie=>z(Ie.target.value),placeholder:"123 Main St, Austin, TX"})]}),ze&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Home Anniversary Date"}),e.jsx(Se,{type:"date",value:O,onChange:Ie=>$(Ie.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Personal Message (optional)"}),e.jsx(vr,{value:ee,onChange:Ie=>Z(Ie.target.value),placeholder:Me.defaultMessage,rows:3})]}),e.jsx(Mvt,{photoUrl:re,videoUrl:ce,onPhotoChange:ie,onVideoChange:ne,contactId:_}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Template Style"}),e.jsx("div",{className:"grid grid-cols-5 gap-2",children:[{key:"elegant",label:"Elegant",gradient:"bg-gradient-to-br from-slate-100 to-blue-100 dark:from-slate-800 dark:to-slate-700"},{key:"bold",label:"Bold",gradient:"bg-gradient-to-br from-violet-500 to-fuchsia-500"},{key:"warm",label:"Warm",gradient:"bg-gradient-to-br from-amber-200 to-orange-300"},{key:"glass",label:"Glass",gradient:"bg-gradient-to-br from-slate-900 via-blue-900/50 to-slate-900 border border-white/10"},{key:"cinematic",label:"Cinema",gradient:"bg-gradient-to-br from-slate-950 via-blue-950 to-slate-950"}].map(({key:Ie,label:De,gradient:pe})=>e.jsxs("button",{onClick:()=>K(Ie),className:`p-2 rounded-lg border-2 transition-all text-center ${J===Ie?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("div",{className:`h-10 rounded-md mb-1.5 ${pe}`}),e.jsx("span",{className:"text-[10px] font-medium",children:De})]},Ie))})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(H,{variant:"outline",onClick:()=>p("contact"),className:"flex-1",children:"Back"}),e.jsx(H,{onClick:We,disabled:!A||j,className:"flex-1 gap-2",children:j?"Creating...":"Create Card"})]})]})]})]})}const V$s={home_anniversary:"Home Anniversary",just_listed:"Just Listed",just_sold:"Just Sold",congratulations:"Congratulations",birthday:"Birthday",holiday:"Holiday",thank_you:"Thank You",thinking_of_you:"Thinking of You"};function H$s({card:s}){Ms();const{isGmailConnected:t}=cf(),r=ns(),[n,a]=S.useState(!1),[i,l]=S.useState("");S.useEffect(()=>{n&&s.contact_id&&!i&&V.from("innercircle_contacts").select("email").eq("id",s.contact_id).maybeSingle().then(({data:y})=>{y!=null&&y.email&&l(y.email)})},[n,s.contact_id]);const o={home_anniversary:`🏡 Happy Home Anniversary, ${s.recipient_name}!`,just_listed:`🏠 Just Listed — Check This Out, ${s.recipient_name}!`,just_sold:`🎉 Just Sold! Congrats, ${s.recipient_name}!`,congratulations:`🏆 Congratulations, ${s.recipient_name}!`,birthday:`🎂 Happy Birthday, ${s.recipient_name}!`,holiday:`🎄 Happy Holidays, ${s.recipient_name}!`,thank_you:`💐 Thank You, ${s.recipient_name}!`,thinking_of_you:`💭 Thinking of You, ${s.recipient_name}!`},[c,d]=S.useState(o[s.card_type]||`A Special Card for ${s.recipient_name}!`),[h,m]=S.useState(""),p=`https://cardstudio.relevelup.com/c/${s.share_token}`,x=Pt({mutationFn:async()=>{var k;if(!i)throw new Error("Recipient email is required");const y=`
${h?`

${h.replace(/\n/g,"
")}


`:""}

I made you a special ${V$s[s.card_type]||s.card_type} card — click below to view it!

${s.property_address?`

${s.property_address}

`:""}
`,{data:_}=await V.auth.getSession(),b=(k=_==null?void 0:_.session)==null?void 0:k.access_token,j=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/gmail-send",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${b}`},body:JSON.stringify({to:i,subject:c,body:y,contactId:s.contact_id||void 0})});if(!j.ok){const T=await j.json();throw new Error(T.error||"Failed to send")}return j.json()},onSuccess:async()=>{await V.from("sendable_cards").update({sent_at:new Date().toISOString(),sent_via:"gmail"}).eq("id",s.id),r.invalidateQueries({queryKey:["sendable-cards"]}),he.success(`Card sent to ${i}!`),a(!1)},onError:y=>{he.error(y.message||"Failed to send email")}});return t?e.jsxs(bs,{open:n,onOpenChange:a,children:[e.jsx(Qi,{asChild:!0,children:e.jsx(H,{variant:"outline",size:"sm",className:"gap-1 text-xs",children:e.jsx(yn,{className:"h-3 w-3"})})}),e.jsxs(vs,{className:"sm:max-w-md",children:[e.jsx(Cs,{children:e.jsx(Ns,{children:"Send Card via Gmail"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"To"}),e.jsx(Se,{type:"email",value:i,onChange:y=>l(y.target.value),placeholder:"recipient@email.com"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Subject"}),e.jsx(Se,{value:c,onChange:y=>d(y.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Personal Note (optional)"}),e.jsx(vr,{value:h,onChange:y=>m(y.target.value),placeholder:"Add a warm personal note before the card link...",rows:3})]}),e.jsxs("div",{className:"rounded-lg bg-muted/50 p-3 text-xs text-muted-foreground",children:["The email will include a beautiful button linking to your card at:",e.jsx("br",{}),e.jsx("span",{className:"font-mono text-foreground",children:p})]}),e.jsx(H,{onClick:()=>x.mutate(),disabled:!i||x.isPending,className:"w-full gap-2",children:x.isPending?e.jsxs(e.Fragment,{children:[e.jsx(is,{className:"h-4 w-4 animate-spin"})," Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(yn,{className:"h-4 w-4"})," Send Card"]})})]})]})]}):e.jsx(H,{variant:"outline",size:"sm",className:"gap-1 text-xs opacity-50 cursor-not-allowed",title:"Connect Gmail in Settings to send cards via email",disabled:!0,children:e.jsx(yn,{className:"h-3 w-3"})})}function G$s({card:s}){const t=ns(),[r,n]=S.useState(!1),[a,i]=S.useState(!1),[l,o]=S.useState(s.recipient_name),[c,d]=S.useState(s.property_address||""),[h,m]=S.useState(s.home_anniversary_date||""),[p,x]=S.useState(s.custom_message||""),[y,_]=S.useState(s.template),[b,j]=S.useState(s.property_photo_url),[k,T]=S.useState(s.video_url||null),E=D=>{D&&(o(s.recipient_name),d(s.property_address||""),m(s.home_anniversary_date||""),x(s.custom_message||""),_(s.template),j(s.property_photo_url),T(s.video_url||null)),n(D)},A=async()=>{if(!l.trim()){he.error("Recipient name is required");return}i(!0);try{const{error:D}=await V.from("sendable_cards").update({recipient_name:l.trim(),property_address:c.trim()||null,home_anniversary_date:h||null,custom_message:p.trim()||null,template:y,property_photo_url:b||null,video_url:k||null}).eq("id",s.id);if(D)throw D;t.invalidateQueries({queryKey:["sendable-cards"]}),he.success("Card updated"),n(!1)}catch(D){he.error(D.message||"Failed to update card")}finally{i(!1)}};return e.jsxs(bs,{open:r,onOpenChange:E,children:[e.jsx(Qi,{asChild:!0,children:e.jsx(H,{variant:"outline",size:"sm",className:"gap-1 text-xs",children:e.jsx(ni,{className:"h-3 w-3"})})}),e.jsxs(vs,{className:"sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(Cs,{children:e.jsx(Ns,{children:"Edit Card"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Recipient Name"}),e.jsx(Se,{value:l,onChange:D=>o(D.target.value),placeholder:"John & Jane Smith"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Property Address"}),e.jsx(Se,{value:c,onChange:D=>d(D.target.value),placeholder:"123 Main St, Austin, TX"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Home Anniversary Date"}),e.jsx(Se,{type:"date",value:h,onChange:D=>m(D.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Personal Message (optional)"}),e.jsx(vr,{value:p,onChange:D=>x(D.target.value),placeholder:"Wishing you many more happy years in your beautiful home!",rows:3})]}),e.jsx(Mvt,{photoUrl:b,videoUrl:k,onPhotoChange:j,onVideoChange:T,contactId:s.contact_id}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Template Style"}),e.jsx("div",{className:"grid grid-cols-3 gap-2",children:["elegant","bold","warm"].map(D=>e.jsxs("button",{onClick:()=>_(D),className:`p-3 rounded-lg border-2 transition-all text-center ${y===D?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("div",{className:`h-12 rounded-md mb-2 ${D==="elegant"?"bg-gradient-to-br from-slate-100 to-slate-200 dark:from-slate-800 dark:to-slate-700":D==="bold"?"bg-gradient-to-br from-violet-500 to-fuchsia-500":"bg-gradient-to-br from-amber-200 to-orange-300"}`}),e.jsx("span",{className:"text-xs font-medium capitalize",children:D})]},D))})]}),e.jsx(H,{onClick:A,disabled:!l.trim()||a,className:"w-full gap-2",children:a?e.jsxs(e.Fragment,{children:[e.jsx(is,{className:"h-4 w-4 animate-spin"})," Saving..."]}):"Save Changes"})]})]})]})}function W$s(){const{user:s}=Ms(),t=ns(),[r,n]=S.useState(""),[a,i]=Ed(),l=a.get("cardType"),o=a.get("contactId"),c=a.get("name"),d=a.get("address"),h=a.get("date"),m=!!l,{data:p,isLoading:x}=yt({queryKey:["sendable-cards",s==null?void 0:s.id],queryFn:async()=>{const{data:T,error:E}=await V.from("sendable_cards").select("*").eq("owner_user_id",s.id).order("created_at",{ascending:!1});if(E)throw E;return T},enabled:!!(s!=null&&s.id)}),y=Pt({mutationFn:async T=>{const{error:E}=await V.from("sendable_cards").delete().eq("id",T);if(E)throw E},onSuccess:()=>{t.invalidateQueries({queryKey:["sendable-cards"]}),he.success("Card deleted")}}),_=T=>{const E=`https://cardstudio.relevelup.com/c/${T}`;navigator.clipboard.writeText(E),he.success("Share link copied!")},b=p==null?void 0:p.filter(T=>{var E;return!r||T.recipient_name.toLowerCase().includes(r.toLowerCase())||((E=T.property_address)==null?void 0:E.toLowerCase().includes(r.toLowerCase()))}),j={elegant:"Elegant",bold:"Bold",warm:"Warm"},k={home_anniversary:"Home Anniversary",just_listed:"Just Listed",just_sold:"Just Sold",congratulations:"Congratulations",birthday:"Birthday",holiday:"Holiday",thank_you:"Thank You",thinking_of_you:"Thinking of You"};return e.jsx(Ss,{title:"Card Studio",children:e.jsxs("div",{className:"max-w-6xl mx-auto space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Card Studio"})}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Create & send beautiful branded cards to your clients"})]}),e.jsx(UWe,{initialOpen:m,initialCardType:l,initialContactId:o||void 0,initialRecipientName:c||void 0,initialAddress:d||void 0,initialDate:h||void 0,onOpenChange:()=>i({})})]}),e.jsxs("div",{className:"relative max-w-sm",children:[e.jsx(Mn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Se,{placeholder:"Search cards...",value:r,onChange:T=>n(T.target.value),className:"pl-9"})]}),x?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[1,2,3].map(T=>e.jsx(ke,{className:"animate-pulse",children:e.jsxs(Oe,{className:"p-4",children:[e.jsx("div",{className:"h-40 bg-muted rounded-lg mb-3"}),e.jsx("div",{className:"h-4 bg-muted rounded w-2/3 mb-2"}),e.jsx("div",{className:"h-3 bg-muted rounded w-1/2"})]})},T))}):b!=null&&b.length?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:b.map(T=>e.jsxs(ke,{className:"group overflow-hidden hover:shadow-lg transition-shadow",children:[e.jsxs("div",{className:`aspect-[16/10] flex items-center justify-center relative overflow-hidden ${T.template==="elegant"?"bg-gradient-to-br from-slate-50 via-slate-100 to-slate-200 dark:from-slate-900 dark:via-slate-800 dark:to-slate-700":T.template==="bold"?"bg-gradient-to-br from-violet-600 via-fuchsia-500 to-pink-500":"bg-gradient-to-br from-amber-100 via-orange-200 to-rose-200 dark:from-amber-900 dark:via-orange-800 dark:to-rose-800"}`,children:[T.template==="elegant"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"absolute top-0 left-0 w-full h-full opacity-10",children:[e.jsx("div",{className:"absolute top-3 left-3 w-16 h-16 border-t-2 border-l-2 border-primary/40 rounded-tl-lg"}),e.jsx("div",{className:"absolute bottom-3 right-3 w-16 h-16 border-b-2 border-r-2 border-primary/40 rounded-br-lg"})]}),e.jsx("div",{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-32 h-32 rounded-full border border-primary/10"})]}),T.template==="bold"&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"absolute -top-8 -right-8 w-32 h-32 rounded-full bg-white/10 blur-sm"}),e.jsx("div",{className:"absolute -bottom-6 -left-6 w-24 h-24 rounded-full bg-white/10 blur-sm"}),e.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(ellipse_at_center,rgba(255,255,255,0.15)_0%,transparent_70%)]"})]}),T.template==="warm"&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"absolute -top-4 -left-4 w-28 h-28 rounded-full bg-orange-400/15 blur-md"}),e.jsx("div",{className:"absolute -bottom-6 -right-6 w-32 h-32 rounded-full bg-rose-400/15 blur-md"})]}),e.jsxs("div",{className:"text-center px-4 relative z-10",children:[e.jsx("div",{className:"text-3xl mb-1.5 opacity-80",children:T.card_type==="home_anniversary"?"🏡":T.card_type==="birthday"?"🎂":T.card_type==="just_sold"?"🎉":T.card_type==="just_listed"?"🏠":T.card_type==="thank_you"?"💐":T.card_type==="congratulations"?"🏆":T.card_type==="holiday"?"🎄":T.card_type==="thinking_of_you"?"💭":"✉️"}),e.jsx("p",{className:`text-[10px] uppercase tracking-[0.2em] mb-1 ${T.template==="bold"?"text-white/70":"text-muted-foreground"}`,children:k[T.card_type]||T.card_type}),e.jsx("p",{className:`font-semibold text-base ${T.template==="bold"?"text-white":"text-foreground"}`,children:T.recipient_name}),T.property_address&&e.jsx("p",{className:`text-xs mt-1 ${T.template==="bold"?"text-white/60":"text-muted-foreground"}`,children:T.property_address})]}),e.jsx("div",{className:"absolute top-2 right-2 z-10",children:e.jsx(Xe,{variant:T.template==="bold"?"outline":"secondary",className:`text-[10px] ${T.template==="bold"?"border-white/30 text-white/80":""}`,children:j[T.template]||T.template})})]}),e.jsxs(Oe,{className:"p-3",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(Bn,{className:"h-3 w-3"}),T.view_count," views"]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Hl(new Date(T.created_at),{addSuffix:!0})})]}),T.sent_at&&e.jsxs("p",{className:"text-[10px] text-emerald-600 mb-2",children:["Sent ",As(new Date(T.sent_at),"MMM d, yyyy")," via ",T.sent_via]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsxs(H,{variant:"outline",size:"sm",className:"flex-1 gap-1 text-xs",onClick:()=>_(T.share_token),children:[e.jsx(ui,{className:"h-3 w-3"}),"Copy Link"]}),e.jsx(G$s,{card:T}),e.jsx(H$s,{card:T}),e.jsx(H,{variant:"outline",size:"sm",className:"gap-1 text-xs",onClick:()=>window.open(`https://cardstudio.relevelup.com/c/${T.share_token}`,"_blank"),children:e.jsx(gn,{className:"h-3 w-3"})}),e.jsx(H,{variant:"ghost",size:"sm",className:"text-destructive hover:text-destructive gap-1 text-xs",onClick:()=>y.mutate(T.id),children:e.jsx(Dr,{className:"h-3 w-3"})})]})]})]},T.id))}):e.jsx(ke,{className:"border-dashed",children:e.jsxs(Oe,{className:"flex flex-col items-center justify-center py-16",children:[e.jsx("div",{className:"h-16 w-16 rounded-full bg-primary/10 flex items-center justify-center mb-4",children:e.jsx(er,{className:"h-8 w-8 text-primary"})}),e.jsx("h3",{className:"font-semibold text-lg mb-1",children:"No cards yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Create your first digital card to send to a client"}),e.jsx(UWe,{initialOpen:m,initialCardType:l,initialContactId:o||void 0,initialRecipientName:c||void 0,initialAddress:d||void 0,initialDate:h||void 0,onOpenChange:()=>i({})})]})})]})})}const aV=[{id:"mls",label:"MLS Description",tag:"Standard",icon:Fn,accent:"from-sky-500 to-cyan-500",desc:"Polished MLS-ready listing",category:"listing"},{id:"luxury",label:"Luxury MLS",tag:"Premium",icon:zf,accent:"from-amber-500 to-orange-500",desc:"Evocative, high-end voice",category:"listing"},{id:"short",label:"Short MLS",tag:"Concise",icon:ym,accent:"from-violet-500 to-fuchsia-500",desc:"Punchy 60–90 words",category:"listing"},{id:"openHouse",label:"Open House",tag:"Promo",icon:m_,accent:"from-emerald-500 to-teal-500",desc:"Friendly invite copy",category:"listing",extras:["openHouse"]},{id:"newConstruction",label:"New Construction",tag:"Build",icon:uF,accent:"from-rose-500 to-pink-500",desc:"Builder-focused angle",category:"listing",extras:["newConstruction"]},{id:"investment",label:"Investment",tag:"ROI",icon:al,accent:"from-indigo-500 to-blue-500",desc:"Cap rate & income hooks",category:"listing",extras:["investment"]},{id:"facebookPost",label:"Facebook Post",tag:"Social",icon:fh,accent:"from-blue-600 to-blue-400",desc:"Engaging FB caption",category:"social"},{id:"instagramPost",label:"Instagram Post",tag:"Social",icon:yu,accent:"from-pink-500 via-fuchsia-500 to-orange-400",desc:"IG caption + hashtags",category:"social"},{id:"linkedinPost",label:"LinkedIn Post",tag:"Social",icon:qf,accent:"from-sky-700 to-sky-500",desc:"Professional tone",category:"social"},{id:"justListed",label:"Just Listed",tag:"Announce",icon:ph,accent:"from-emerald-500 to-green-500",desc:"Hit the market announcement",category:"social"},{id:"comingSoon",label:"Coming Soon",tag:"Tease",icon:Pn,accent:"from-amber-500 to-yellow-500",desc:"Build pre-market buzz",category:"social",extras:["comingSoon"]},{id:"priceImprovement",label:"Price Improvement",tag:"Update",icon:K2,accent:"from-orange-500 to-red-500",desc:"New price announcement",category:"social",extras:["priceImprovement"]},{id:"openHousePost",label:"Open House Post",tag:"Event",icon:xu,accent:"from-teal-500 to-emerald-500",desc:"Social invite to OH",category:"social",extras:["openHouse"]},{id:"underContract",label:"Under Contract",tag:"Status",icon:oF,accent:"from-indigo-500 to-purple-500",desc:"Pending celebration",category:"social",extras:["underContract"]},{id:"justSold",label:"Just Sold",tag:"Celebrate",icon:gh,accent:"from-fuchsia-500 to-pink-500",desc:"Sold success post",category:"social",extras:["sold"]},{id:"propertyTourScript",label:"Property Tour",tag:"Script",icon:xn,accent:"from-red-500 to-rose-500",desc:"Full walkthrough script",category:"video",extras:["signoff"]},{id:"reelScript",label:"Reel Script",tag:"Short",icon:Qm,accent:"from-fuchsia-500 to-pink-500",desc:"30–60s reel structure",category:"video",extras:["vibe","signoff"]},{id:"shortFormHooks",label:"Short-Form Hooks",tag:"Hooks",icon:EE,accent:"from-violet-500 to-purple-500",desc:"5 scroll-stopping hooks",category:"video",extras:["vibe"]},{id:"luxuryWalkthrough",label:"Luxury Walkthrough",tag:"Premium",icon:zf,accent:"from-amber-500 to-yellow-500",desc:"Cinematic, refined tone",category:"video",extras:["signoff"]},{id:"droneScript",label:"Drone Script",tag:"Aerial",icon:NF,accent:"from-sky-500 to-blue-500",desc:"Voiceover for aerial b-roll",category:"video",extras:["signoff"]},{id:"neighborhoodTour",label:"Neighborhood Tour",tag:"Local",icon:Qa,accent:"from-emerald-500 to-teal-500",desc:"Area lifestyle script",category:"video",extras:["neighborhood","signoff"]},{id:"justListedEmail",label:"Just Listed Email",tag:"Announce",icon:er,accent:"from-emerald-500 to-green-500",desc:"Email blast for new listing",category:"email",extras:["signoff"]},{id:"openHouseEmail",label:"Open House Invite",tag:"Invite",icon:xF,accent:"from-teal-500 to-cyan-500",desc:"Public OH invitation",category:"email",extras:["openHouse","signoff"]},{id:"brokerOpenEmail",label:"Broker Open Invite",tag:"Agents",icon:Ar,accent:"from-indigo-500 to-blue-500",desc:"Invite to fellow agents",category:"email",extras:["openHouse","brokerOpen","signoff"]},{id:"priceReductionEmail",label:"Price Reduction",tag:"Update",icon:K2,accent:"from-orange-500 to-red-500",desc:"Price drop notification",category:"email",extras:["priceImprovement","signoff"]},{id:"justSoldEmail",label:"Just Sold Email",tag:"Celebrate",icon:QO,accent:"from-fuchsia-500 to-pink-500",desc:"Sold announcement email",category:"email",extras:["sold","signoff"]},{id:"neighborhoodEmail",label:"Neighborhood Email",tag:"Nurture",icon:Qa,accent:"from-sky-500 to-indigo-500",desc:"Area update / market touch",category:"email",extras:["neighborhood","signoff"]}];function K$s(){var Aa,vo,fo,ai,Cn,Wi,Ki,ii,Ji,co,ia;const{user:s}=Ms(),[t,r]=S.useState(""),[n,a]=S.useState(""),[i,l]=S.useState([]),[o,c]=S.useState(""),[d,h]=S.useState([]),[m,p]=S.useState(""),[x,y]=S.useState(""),[_,b]=S.useState(""),[j,k]=S.useState(""),[T,E]=S.useState(""),[A,D]=S.useState(""),[R,z]=S.useState(""),[O,$]=S.useState(null),[ee,Z]=S.useState(""),[J,K]=S.useState(""),[re,ie]=S.useState(""),[ce,ne]=S.useState(""),[le,be]=S.useState(""),[fe,je]=S.useState(""),[ve,We]=S.useState(""),[Ve,Le]=S.useState(""),[Me,ze]=S.useState(""),[Pe,Ie]=S.useState(""),[De,pe]=S.useState(""),[tt,ge]=S.useState(""),[ct,Ue]=S.useState(""),[et,Qe]=S.useState(""),[Ne,$e]=S.useState(""),[it,Je]=S.useState(""),[st,mt]=S.useState(""),[wt,at]=S.useState(""),[rt,Et]=S.useState(""),[hs,Is]=S.useState(""),[lr,us]=S.useState(""),[St,xs]=S.useState(""),[kt,fs]=S.useState(""),[Gs,_s]=S.useState(""),[br,zr]=S.useState(""),[Yr,rn]=S.useState("listing"),[sn,Vr]=S.useState("mls"),[$r,hn]=S.useState({}),[Zn,cr]=S.useState({}),[on,ds]=S.useState(!1),[Na,vn]=S.useState(!1),_r=hr=>{rn(hr);const Sa=aV.find(Yi=>Yi.category===hr);Sa&&Vr(Sa.id)},{data:Hr}=yt({queryKey:["listing-studio-listings",s==null?void 0:s.id],enabled:!!(s!=null&&s.id)&&on,queryFn:async()=>{const{data:hr,error:Sa}=await V.from("listings").select("id, property_address, city, state, price, bedrooms, bathrooms, square_footage, property_type, description").eq("agent_id",s.id).order("created_at",{ascending:!1}).limit(50);if(Sa)throw Sa;return hr||[]}}),_a=()=>{const hr=o.trim();hr&&(l(Sa=>[...Sa,hr]),c(""))},Jt=hr=>l(Sa=>Sa.filter((Yi,$o)=>$o!==hr)),Cr=hr=>{var Sa,Yi,$o,cl;$(hr.id),r(hr.property_address||""),D(hr.city||""),z(hr.state||""),k(((Sa=hr.price)==null?void 0:Sa.toString())||""),p(((Yi=hr.bedrooms)==null?void 0:Yi.toString())||""),y((($o=hr.bathrooms)==null?void 0:$o.toString())||""),b(((cl=hr.square_footage)==null?void 0:cl.toString())||""),E(hr.property_type||""),a(hr.description||""),ds(!1),he.success("Listing imported")},Gt=async hr=>{if(!(!hr.target.files||!(s!=null&&s.id))){vn(!0);try{const Sa=[];for(const Yi of Array.from(hr.target.files).slice(0,10)){const $o=`${s.id}/${Date.now()}-${Yi.name.replace(/[^\w.-]/g,"_")}`,{error:cl}=await V.storage.from("listing-photos").upload($o,Yi,{upsert:!1});if(cl){console.error(cl);continue}const{data:bo}=V.storage.from("listing-photos").getPublicUrl($o);Sa.push(bo.publicUrl)}h(Yi=>[...Yi,...Sa]),Sa.length&&he.success(`${Sa.length} photo(s) uploaded`)}catch(Sa){he.error(Sa.message||"Photo upload failed")}finally{vn(!1)}}},Ee=aV.find(hr=>hr.id===sn),He=async hr=>{var Yi,$o,cl;const Sa=aV.find(bo=>bo.id===hr);if(!t.trim()&&!n.trim()&&i.length===0){he.error("Add a property address, MLS remarks, or features first");return}if((Yi=Sa.extras)!=null&&Yi.includes("openHouse")&&(!ee||!J||!re)){he.error("Add the open house date, start and end time");return}if(($o=Sa.extras)!=null&&$o.includes("priceImprovement")&&(!ce||!le)){he.error("Add previous and new price");return}if((cl=Sa.extras)!=null&&cl.includes("sold")&&!fe){he.error("Add the sold price");return}Vr(hr),cr(bo=>({...bo,[hr]:!0}));try{const{data:bo,error:md}=await V.functions.invoke("listing-studio-generate",{body:{copyType:hr,propertyAddress:t,mlsRemarks:n,features:i,photoUrls:d,listingId:O,bedrooms:m?Number(m):null,bathrooms:x?Number(x):null,squareFootage:_?Number(_):null,price:j?Number(j):null,propertyType:T||null,city:A||null,state:R||null,openHouseDate:ee||null,openHouseStart:J||null,openHouseEnd:re||null,previousPrice:ce?Number(ce):null,newPrice:le?Number(le):null,soldPrice:fe?Number(fe):null,soldDate:ve||null,comingSoonDate:Ve||null,builderName:Me||null,yearBuilt:Pe?Number(Pe):null,warrantyInfo:De||null,monthlyRent:tt?Number(tt):null,capRate:ct||null,occupancy:et||null,daysOnMarket:Ne?Number(Ne):null,offerCount:it?Number(it):null,originalListPrice:st?Number(st):null,soldDaysOnMarket:wt?Number(wt):null,commissionOffered:rt||null,refreshments:hs||null,vibe:lr||null,neighborhoodHighlights:St||null,agentName:kt||null,agentBrokerage:Gs||null,agentContact:br||null}});if(md)throw md;if(bo!=null&&bo.error)throw new Error(bo.error);hn(Nu=>({...Nu,[hr]:bo.content}))}catch(bo){he.error(bo.message||"Generation failed")}finally{cr(bo=>({...bo,[hr]:!1}))}},ot=hr=>{navigator.clipboard.writeText(hr),he.success("Copied to clipboard")},jt=Ee.icon,Dt=$r[sn]?$r[sn].trim().split(/\s+/).length:0,qt=hr=>e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-3",children:aV.filter(Sa=>Sa.category===hr).map(Sa=>{const Yi=Sa.icon,$o=sn===Sa.id,cl=!!$r[Sa.id];return e.jsxs("button",{onClick:()=>Vr(Sa.id),className:Ft("relative text-left p-4 rounded-2xl border transition-all overflow-hidden group",$o?"border-primary shadow-lg shadow-primary/10 bg-card":"border-border/60 hover:border-border bg-card/50 hover:bg-card"),children:[$o&&e.jsx("div",{className:Ft("absolute inset-0 opacity-[0.07] bg-gradient-to-br",Sa.accent)}),e.jsxs("div",{className:"relative space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:Ft("h-9 w-9 rounded-xl grid place-items-center text-white bg-gradient-to-br shadow-sm",Sa.accent),children:e.jsx(Yi,{className:"h-4 w-4"})}),cl&&e.jsx("div",{className:"h-5 w-5 rounded-full bg-emerald-500/15 text-emerald-600 grid place-items-center",children:e.jsx(va,{className:"h-3 w-3"})})]}),e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold text-sm",children:Sa.label}),e.jsx("div",{className:"text-xs text-muted-foreground line-clamp-1",children:Sa.desc})]})]})]},Sa.id)})}),ss=(Aa=Ee.extras)==null?void 0:Aa.includes("openHouse"),Yt=(vo=Ee.extras)==null?void 0:vo.includes("priceImprovement"),ls=(fo=Ee.extras)==null?void 0:fo.includes("sold"),Xs=(ai=Ee.extras)==null?void 0:ai.includes("comingSoon"),Rs=(Cn=Ee.extras)==null?void 0:Cn.includes("newConstruction"),Er=(Wi=Ee.extras)==null?void 0:Wi.includes("investment"),ln=(Ki=Ee.extras)==null?void 0:Ki.includes("underContract"),mn=(ii=Ee.extras)==null?void 0:ii.includes("brokerOpen"),Gr=(Ji=Ee.extras)==null?void 0:Ji.includes("vibe"),fn=(co=Ee.extras)==null?void 0:co.includes("neighborhood"),pn=(ia=Ee.extras)==null?void 0:ia.includes("signoff"),Sn=ss||Yt||ls||Xs||Rs||Er||ln||mn||Gr||fn||pn;return e.jsx(Ss,{title:"Listing Studio",children:e.jsxs("div",{className:"space-y-8 animate-fade-in",children:[e.jsxs("div",{className:"relative overflow-hidden rounded-3xl border bg-gradient-to-br from-fuchsia-500/10 via-violet-500/5 to-sky-500/10 dark:from-fuchsia-500/20 dark:via-violet-500/10 dark:to-sky-500/20",children:[e.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(circle_at_top_right,_hsl(var(--primary)/0.15),_transparent_60%)]"}),e.jsx("div",{className:"absolute -top-24 -right-24 h-72 w-72 rounded-full bg-fuchsia-500/20 blur-3xl"}),e.jsx("div",{className:"absolute -bottom-24 -left-24 h-72 w-72 rounded-full bg-sky-500/20 blur-3xl"}),e.jsxs("div",{className:"relative px-6 py-8 sm:px-10 sm:py-12 flex flex-col md:flex-row md:items-center gap-6",children:[e.jsxs("div",{className:"flex-1 space-y-3",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 px-3 py-1 rounded-full bg-background/60 backdrop-blur-sm border text-xs font-medium",children:[e.jsx(Lr,{className:"h-3.5 w-3.5 text-fuchsia-500"}),"AI-powered listing & social copy"]}),e.jsx("h1",{className:"text-3xl sm:text-4xl font-bold tracking-tight bg-gradient-to-br from-foreground to-foreground/60 bg-clip-text",children:"Listing Studio"}),e.jsx("p",{className:"text-muted-foreground max-w-xl",children:"Drop in a property, generate magnetic MLS copy, luxury narratives, open-house promos, and ready-to-post social content — all in seconds."})]}),e.jsxs(bs,{open:on,onOpenChange:ds,children:[e.jsx(Qi,{asChild:!0,children:e.jsxs(H,{size:"lg",variant:"secondary",className:"shadow-lg shadow-fuchsia-500/10",children:[e.jsx(kn,{className:"h-4 w-4 mr-2"}),"Import from Listings"]})}),e.jsxs(vs,{className:"max-w-2xl max-h-[80vh] overflow-y-auto",children:[e.jsx(Cs,{children:e.jsx(Ns,{children:"Import from Listing Exchange"})}),e.jsxs("div",{className:"space-y-2 mt-2",children:[!(Hr!=null&&Hr.length)&&e.jsx("p",{className:"text-sm text-muted-foreground py-8 text-center",children:"No listings found yet."}),Hr==null?void 0:Hr.map(hr=>e.jsxs("button",{onClick:()=>Cr(hr),className:"w-full text-left p-4 border rounded-xl hover:border-primary hover:bg-accent/50 transition-all",children:[e.jsx("div",{className:"font-medium",children:hr.property_address||"Untitled listing"}),e.jsxs("div",{className:"text-sm text-muted-foreground mt-0.5",children:[[hr.city,hr.state].filter(Boolean).join(", "),hr.price?` · $${Number(hr.price).toLocaleString()}`:"",hr.bedrooms?` · ${hr.bedrooms}bd`:"",hr.bathrooms?` · ${hr.bathrooms}ba`:""]})]},hr.id))]})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-5 gap-6",children:[e.jsx(ke,{className:"lg:col-span-2 border-border/60 shadow-sm",children:e.jsxs(Oe,{className:"p-6 space-y-5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-8 w-8 rounded-lg bg-primary/10 grid place-items-center",children:e.jsx(Fn,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold",children:"Property Details"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Fill in what you have — AI handles the rest"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Address"}),e.jsx(Se,{value:t,onChange:hr=>r(hr.target.value),placeholder:"123 Main St"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"City"}),e.jsx(Se,{value:A,onChange:hr=>D(hr.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"State"}),e.jsx(Se,{value:R,onChange:hr=>z(hr.target.value)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Price"}),e.jsx(Se,{type:"number",value:j,onChange:hr=>k(hr.target.value),placeholder:"$"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Type"}),e.jsx(Se,{value:T,onChange:hr=>E(hr.target.value),placeholder:"Single Family"})]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Beds"}),e.jsx(Se,{type:"number",value:m,onChange:hr=>p(hr.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Baths"}),e.jsx(Se,{type:"number",step:"0.5",value:x,onChange:hr=>y(hr.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Sqft"}),e.jsx(Se,{type:"number",value:_,onChange:hr=>b(hr.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"MLS Remarks / Notes"}),e.jsx(vr,{value:n,onChange:hr=>a(hr.target.value),placeholder:"Paste existing MLS remarks or rough notes...",rows:4,className:"resize-none"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Features"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Se,{value:o,onChange:hr=>c(hr.target.value),onKeyDown:hr=>hr.key==="Enter"&&(hr.preventDefault(),_a()),placeholder:"e.g. Quartz countertops"}),e.jsx(H,{type:"button",size:"icon",variant:"secondary",onClick:_a,children:e.jsx(Ys,{className:"h-4 w-4"})})]}),i.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5 mt-2 animate-fade-in",children:i.map((hr,Sa)=>e.jsxs(Xe,{variant:"secondary",className:"pl-3 pr-1 py-1 gap-1",children:[hr,e.jsx("button",{onClick:()=>Jt(Sa),className:"ml-0.5 p-0.5 hover:bg-background/60 rounded-full",children:e.jsx(Rr,{className:"h-3 w-3"})})]},Sa))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Photos (optional)"}),e.jsxs("label",{className:"flex items-center justify-center gap-2 p-4 border-2 border-dashed rounded-xl cursor-pointer hover:border-primary hover:bg-accent/30 transition-colors text-sm text-muted-foreground",children:[e.jsx(f_,{className:"h-4 w-4"}),Na?"Uploading…":"Click to upload photos",e.jsx("input",{type:"file",accept:"image/*",multiple:!0,onChange:Gt,disabled:Na,className:"hidden"})]}),d.length>0&&e.jsx("div",{className:"grid grid-cols-4 gap-2 mt-2",children:d.map((hr,Sa)=>e.jsxs("div",{className:"relative aspect-square rounded-lg overflow-hidden group",children:[e.jsx("img",{src:hr,alt:"",className:"w-full h-full object-cover"}),e.jsx("button",{onClick:()=>h(Yi=>Yi.filter(($o,cl)=>cl!==Sa)),className:"absolute top-1 right-1 bg-background/90 backdrop-blur rounded-full p-1 opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx(Rr,{className:"h-3 w-3"})})]},Sa))})]}),Sn&&e.jsxs("div",{className:"space-y-4 p-4 rounded-xl border border-dashed border-primary/40 bg-primary/5 animate-fade-in",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Lr,{className:"h-4 w-4 text-primary"}),e.jsxs("div",{className:"text-sm font-semibold",children:["Extra info for ",Ee.label]})]}),ss&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Date"}),e.jsx(Se,{type:"date",value:ee,onChange:hr=>Z(hr.target.value)})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Start"}),e.jsx(Se,{type:"time",value:J,onChange:hr=>K(hr.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"End"}),e.jsx(Se,{type:"time",value:re,onChange:hr=>ie(hr.target.value)})]})]})]}),Yt&&e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Previous Price"}),e.jsx(Se,{type:"number",value:ce,onChange:hr=>ne(hr.target.value),placeholder:"$"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"New Price"}),e.jsx(Se,{type:"number",value:le,onChange:hr=>be(hr.target.value),placeholder:"$"})]})]}),ls&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Sold Price"}),e.jsx(Se,{type:"number",value:fe,onChange:hr=>je(hr.target.value),placeholder:"$"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Sold Date"}),e.jsx(Se,{type:"date",value:ve,onChange:hr=>We(hr.target.value)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Original List Price (optional)"}),e.jsx(Se,{type:"number",value:st,onChange:hr=>mt(hr.target.value),placeholder:"$"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Days on Market (optional)"}),e.jsx(Se,{type:"number",value:wt,onChange:hr=>at(hr.target.value)})]})]})]}),Xs&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Expected Live Date (optional)"}),e.jsx(Se,{type:"date",value:Ve,onChange:hr=>Le(hr.target.value)})]}),Rs&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Builder Name"}),e.jsx(Se,{value:Me,onChange:hr=>ze(hr.target.value),placeholder:"ABC Homes"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Year Built"}),e.jsx(Se,{type:"number",value:Pe,onChange:hr=>Ie(hr.target.value),placeholder:"2026"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Warranty / Energy / Smart-home (optional)"}),e.jsx(Se,{value:De,onChange:hr=>pe(hr.target.value),placeholder:"10-yr structural, ENERGY STAR, smart-home pkg"})]})]}),Er&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Monthly Rent (optional)"}),e.jsx(Se,{type:"number",value:tt,onChange:hr=>ge(hr.target.value),placeholder:"$"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Cap Rate (optional)"}),e.jsx(Se,{value:ct,onChange:hr=>Ue(hr.target.value),placeholder:"6.5%"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Occupancy"}),e.jsxs("select",{value:et,onChange:hr=>Qe(hr.target.value),className:"w-full h-10 rounded-md border border-input bg-background px-3 text-sm",children:[e.jsx("option",{value:"",children:"Select…"}),e.jsx("option",{value:"Vacant",children:"Vacant"}),e.jsx("option",{value:"Tenant-occupied",children:"Tenant-occupied"}),e.jsx("option",{value:"Owner-occupied",children:"Owner-occupied"}),e.jsx("option",{value:"Short-term rental",children:"Short-term rental"})]})]})]}),ln&&e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Days on Market (optional)"}),e.jsx(Se,{type:"number",value:Ne,onChange:hr=>$e(hr.target.value),placeholder:"e.g. 3"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"# of Offers (optional)"}),e.jsx(Se,{type:"number",value:it,onChange:hr=>Je(hr.target.value),placeholder:"e.g. 5"})]})]}),mn&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Commission / Co-op Offered (optional)"}),e.jsx(Se,{value:rt,onChange:hr=>Et(hr.target.value),placeholder:"2.5% buyer agent commission"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Refreshments / Perks (optional)"}),e.jsx(Se,{value:hs,onChange:hr=>Is(hr.target.value),placeholder:"Lunch + raffle for $100 gift card"})]})]}),Gr&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Vibe / Tone"}),e.jsxs("select",{value:lr,onChange:hr=>us(hr.target.value),className:"w-full h-10 rounded-md border border-input bg-background px-3 text-sm",children:[e.jsx("option",{value:"",children:"Default"}),e.jsx("option",{value:"Energetic",children:"Energetic & fun"}),e.jsx("option",{value:"Luxury",children:"Luxury & cinematic"}),e.jsx("option",{value:"Cozy",children:"Warm & cozy"}),e.jsx("option",{value:"Humorous",children:"Humorous"}),e.jsx("option",{value:"Educational",children:"Educational"}),e.jsx("option",{value:"Bold",children:"Bold & confident"})]})]}),fn&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Nearby Highlights (optional)"}),e.jsx(vr,{value:St,onChange:hr=>xs(hr.target.value),rows:3,placeholder:"Top schools, parks, coffee shops, restaurants, commute, walkability…"})]}),pn&&e.jsxs("div",{className:"space-y-3 pt-2 border-t border-border/40",children:[e.jsx("div",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Sign-off (optional)"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{className:"text-xs font-medium text-muted-foreground",children:"Agent Name"}),e.jsx(Se,{value:kt,onChange:hr=>fs(hr.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{className:"text-xs font-medium text-muted-foreground",children:"Brokerage"}),e.jsx(Se,{value:Gs,onChange:hr=>_s(hr.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{className:"text-xs font-medium text-muted-foreground",children:"Phone / Email"}),e.jsx(Se,{value:br,onChange:hr=>zr(hr.target.value),placeholder:"555-123-4567 or you@brand.com"})]})]})]})]})}),e.jsxs("div",{className:"lg:col-span-3 space-y-6",children:[e.jsx("div",{className:"flex gap-2 p-1 rounded-xl bg-muted/60 border border-border/40 overflow-x-auto",children:[{key:"listing",label:"Listing Copy",icon:kn},{key:"social",label:"Social Media",icon:yu},{key:"video",label:"Video Scripts",icon:xn},{key:"email",label:"Email Marketing",icon:er}].map(hr=>{const Sa=hr.icon,Yi=Yr===hr.key;return e.jsxs("button",{onClick:()=>_r(hr.key),className:Ft("flex-1 flex items-center justify-center gap-2 px-4 py-2.5 rounded-lg text-sm font-medium transition-all",Yi?"bg-card shadow-sm text-foreground border border-border/60":"text-muted-foreground hover:text-foreground hover:bg-background/50"),children:[e.jsx(Sa,{className:"h-4 w-4"}),hr.label]},hr.key)})}),qt(Yr),e.jsxs(ke,{className:"border-border/60 shadow-sm overflow-hidden",children:[e.jsx("div",{className:Ft("h-1 bg-gradient-to-r",Ee.accent)}),e.jsxs(Oe,{className:"p-6 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4 flex-wrap",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:Ft("h-10 w-10 rounded-xl grid place-items-center text-white bg-gradient-to-br",Ee.accent),children:e.jsx(jt,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsxs("div",{className:"font-semibold flex items-center gap-2",children:[Ee.label,e.jsx(Xe,{variant:"outline",className:"text-[10px] font-normal",children:Ee.tag})]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:$r[sn]?`${Dt} words`:"Ready to generate"})]})]}),e.jsxs("div",{className:"flex gap-2",children:[$r[sn]&&e.jsxs(H,{variant:"outline",size:"sm",onClick:()=>ot($r[sn]),children:[e.jsx(ui,{className:"h-4 w-4 mr-2"})," Copy"]}),e.jsx(H,{onClick:()=>He(sn),disabled:Zn[sn],className:Ft("shadow-lg shadow-primary/10 bg-gradient-to-r text-white border-0 hover:opacity-90",Ee.accent),size:"sm",children:Zn[sn]?e.jsxs(e.Fragment,{children:[e.jsx(is,{className:"h-4 w-4 mr-2 animate-spin"})," Generating"]}):$r[sn]?e.jsxs(e.Fragment,{children:[e.jsx(po,{className:"h-4 w-4 mr-2"})," Regenerate"]}):e.jsxs(e.Fragment,{children:[e.jsx(My,{className:"h-4 w-4 mr-2"})," Generate"]})})]})]}),$r[sn]?e.jsx(vr,{value:$r[sn],onChange:hr=>hn(Sa=>({...Sa,[sn]:hr.target.value})),rows:16,className:"resize-none font-serif text-[15px] leading-relaxed bg-muted/30 border-border/60 animate-fade-in"}):e.jsxs("div",{className:"border border-dashed rounded-xl p-12 text-center bg-muted/20",children:[e.jsx("div",{className:Ft("mx-auto h-14 w-14 rounded-2xl grid place-items-center text-white bg-gradient-to-br mb-4",Ee.accent),children:e.jsx(My,{className:"h-6 w-6"})}),e.jsxs("div",{className:"font-medium mb-1",children:["Generate a ",Ee.label.toLowerCase()]}),e.jsx("p",{className:"text-sm text-muted-foreground max-w-sm mx-auto",children:"Fill in property details on the left, then click Generate. Your copy appears here — fully editable."})]})]})]})]})]})]})})}function rO({delay:s,x:t,y:r,size:n}){return e.jsx(Ur.div,{className:"absolute rounded-full bg-slate-300/30 dark:bg-slate-500/20",style:{left:t,top:r,width:n,height:n},animate:{y:[0,-20,0],opacity:[.3,.7,.3],scale:[1,1.2,1]},transition:{duration:4,delay:s,repeat:1/0,ease:"easeInOut"}})}function Y$s(s){const{cardType:t,recipientName:r,propertyAddress:n,anniversaryYears:a,customMessage:i,agentName:l,agentPhotoUrl:o,agentPhone:c,agentEmail:d,agentBrokerage:h,propertyPhotoUrl:m,videoUrl:p}=s,x=iD[t];return e.jsxs("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 via-blue-50/30 to-white dark:from-slate-950 dark:to-slate-900 flex items-center justify-center p-4 overflow-hidden relative",children:[e.jsxs("div",{className:"absolute inset-0 overflow-hidden",children:[e.jsx(Ur.div,{className:"absolute -top-20 -right-20 w-72 h-72 rounded-full bg-gradient-to-br from-blue-100/40 to-slate-100/20 blur-3xl",animate:{scale:[1,1.1,1],rotate:[0,5,0]},transition:{duration:8,repeat:1/0,ease:"easeInOut"}}),e.jsx(Ur.div,{className:"absolute -bottom-20 -left-20 w-64 h-64 rounded-full bg-gradient-to-tr from-slate-200/30 to-blue-100/20 blur-3xl",animate:{scale:[1,1.15,1],rotate:[0,-5,0]},transition:{duration:10,repeat:1/0,ease:"easeInOut"}}),e.jsx(rO,{delay:0,x:"15%",y:"20%",size:8}),e.jsx(rO,{delay:1,x:"80%",y:"30%",size:6}),e.jsx(rO,{delay:2,x:"60%",y:"70%",size:10}),e.jsx(rO,{delay:.5,x:"25%",y:"80%",size:7}),e.jsx(rO,{delay:1.5,x:"70%",y:"15%",size:5})]}),e.jsxs(Ur.div,{className:"w-full max-w-md relative z-10",initial:{opacity:0,y:30},animate:{opacity:1,y:0},transition:{duration:.8,ease:"easeOut"},children:[e.jsxs(Ur.div,{className:"bg-white/80 dark:bg-slate-900/80 backdrop-blur-xl rounded-3xl shadow-[0_20px_60px_-15px_rgba(0,0,0,0.1)] overflow-hidden border border-slate-200/60 dark:border-slate-700/50",initial:{scale:.95},animate:{scale:1},transition:{duration:.6,delay:.2},children:[e.jsx("div",{className:"relative h-2 bg-gradient-to-r from-slate-200 via-blue-300 to-slate-200 dark:from-slate-700 dark:via-blue-500 dark:to-slate-700 overflow-hidden",children:e.jsx(Ur.div,{className:"absolute inset-0 bg-gradient-to-r from-transparent via-white/60 to-transparent",animate:{x:["-100%","200%"]},transition:{duration:3,repeat:1/0,repeatDelay:2,ease:"easeInOut"}})}),e.jsxs("div",{className:"px-8 py-10 text-center",children:[e.jsxs(Ur.div,{className:"mx-auto mb-6 h-20 w-20 rounded-2xl bg-gradient-to-br from-slate-100 to-blue-50 dark:from-slate-800 dark:to-slate-700 flex items-center justify-center shadow-lg relative",initial:{scale:0,rotate:-10},animate:{scale:1,rotate:0},transition:{duration:.5,delay:.4,type:"spring",stiffness:200},children:[e.jsx(Ur.div,{className:"absolute inset-0 rounded-2xl border-2 border-slate-200/50 dark:border-slate-600/50",animate:{scale:[1,1.15,1],opacity:[.5,0,.5]},transition:{duration:2.5,repeat:1/0,ease:"easeInOut"}}),e.jsx("span",{className:"text-4xl",children:x.icon})]}),t==="home_anniversary"&&a!==null&&a>0&&e.jsx(Ur.div,{className:"inline-block mb-4",initial:{opacity:0,scale:.8},animate:{opacity:1,scale:1},transition:{duration:.4,delay:.6},children:e.jsxs("span",{className:"text-sm font-semibold tracking-[0.25em] uppercase text-blue-400 dark:text-blue-300",children:[a," ",a===1?"Year":"Years"]})}),e.jsx(Ur.h1,{className:"text-4xl font-light text-slate-800 dark:text-slate-100 mb-1 tracking-tight",initial:{opacity:0,y:15},animate:{opacity:1,y:0},transition:{duration:.5,delay:.7},children:x.title[0]}),x.title[1]&&e.jsx(Ur.h2,{className:"text-4xl font-bold text-slate-800 dark:text-slate-100 mb-8 tracking-tight",initial:{opacity:0,y:15},animate:{opacity:1,y:0},transition:{duration:.5,delay:.85},children:x.title[1]}),e.jsxs(Ur.div,{initial:{opacity:0},animate:{opacity:1},transition:{duration:.5,delay:1},children:[e.jsx("p",{className:"text-xl font-medium text-slate-700 dark:text-slate-200 mb-1",children:r}),n&&e.jsx("p",{className:"text-sm text-slate-400 dark:text-slate-500 mb-6",children:n})]}),e.jsx(Ur.div,{className:"h-px bg-gradient-to-r from-transparent via-slate-300 dark:via-slate-600 to-transparent mx-auto mb-6",initial:{width:0},animate:{width:"80%"},transition:{duration:.8,delay:1.1},style:{margin:"0 auto 1.5rem"}}),m&&e.jsx(Ur.div,{className:"mb-6 rounded-xl overflow-hidden shadow-md",initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{delay:1.15,duration:.5},children:e.jsx("img",{src:m,alt:"Property",className:"w-full h-48 object-cover"})}),p&&e.jsx(Ur.div,{className:"mb-6 rounded-xl overflow-hidden shadow-md",initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{delay:1.2,duration:.5},children:e.jsx("iframe",{src:`${p}?autoplay=false&responsive=true`,className:"w-full aspect-video",allow:"autoplay; encrypted-media",allowFullScreen:!0})}),e.jsx(Ur.p,{className:"text-sm text-slate-500 dark:text-slate-400 leading-relaxed max-w-xs mx-auto mb-8 italic",initial:{opacity:0},animate:{opacity:1},transition:{duration:.6,delay:1.3},children:i||x.defaultMessage}),e.jsxs(Ur.div,{className:"border-t border-slate-100 dark:border-slate-800 pt-6",initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{duration:.5,delay:1.5},children:[e.jsxs("div",{className:"flex items-center justify-center gap-3",children:[o?e.jsx(Ur.img,{src:o,alt:l,className:"h-12 w-12 rounded-full object-cover ring-2 ring-slate-200 dark:ring-slate-700 shadow-md",whileHover:{scale:1.1}}):e.jsx("div",{className:"h-12 w-12 rounded-full bg-gradient-to-br from-slate-200 to-blue-100 dark:from-slate-700 dark:to-slate-600 flex items-center justify-center shadow-md",children:e.jsx("span",{className:"text-sm font-semibold text-slate-600 dark:text-slate-300",children:l.charAt(0)})}),e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"text-sm font-semibold text-slate-700 dark:text-slate-200",children:l}),h&&e.jsx("p",{className:"text-xs text-slate-400 dark:text-slate-500",children:h})]})]}),e.jsxs("div",{className:"flex items-center justify-center gap-3 mt-4",children:[c&&e.jsxs(Ur.a,{href:`tel:${c}`,className:"flex items-center gap-1.5 px-4 py-2 rounded-full bg-slate-100 dark:bg-slate-800 text-xs font-medium text-slate-600 dark:text-slate-300 hover:bg-slate-200 dark:hover:bg-slate-700 transition-colors shadow-sm",whileHover:{scale:1.05},whileTap:{scale:.95},children:[e.jsx(Yn,{className:"h-3.5 w-3.5"})," Call"]}),d&&e.jsxs(Ur.a,{href:`mailto:${d}`,className:"flex items-center gap-1.5 px-4 py-2 rounded-full bg-slate-100 dark:bg-slate-800 text-xs font-medium text-slate-600 dark:text-slate-300 hover:bg-slate-200 dark:hover:bg-slate-700 transition-colors shadow-sm",whileHover:{scale:1.05},whileTap:{scale:.95},children:[e.jsx(er,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})]}),e.jsx(Ur.p,{className:"text-center text-[10px] text-slate-400 dark:text-slate-600 mt-4",initial:{opacity:0},animate:{opacity:1},transition:{delay:2},children:"Powered by LevelUp"})]})]})}function Awe({delay:s,x:t,y:r,color:n,size:a}){return e.jsx(Ur.div,{className:`absolute rounded-full blur-2xl ${n}`,style:{left:t,top:r,width:a,height:a},animate:{scale:[1,1.4,1],opacity:[.2,.5,.2]},transition:{duration:5,delay:s,repeat:1/0,ease:"easeInOut"}})}function nO({delay:s,x:t,y:r}){return e.jsx(Ur.div,{className:"absolute text-white/30 text-lg",style:{left:t,top:r},animate:{opacity:[0,1,0],scale:[.5,1,.5],rotate:[0,180,360]},transition:{duration:3,delay:s,repeat:1/0,ease:"easeInOut"},children:"✦"})}const qWe={home_anniversary:{bg:"from-violet-950 via-purple-900 to-fuchsia-950",orbs:["bg-violet-500/30","bg-fuchsia-500/25","bg-purple-400/20"]},birthday:{bg:"from-pink-950 via-rose-900 to-fuchsia-950",orbs:["bg-pink-500/30","bg-rose-500/25","bg-fuchsia-400/20"]},just_sold:{bg:"from-emerald-950 via-teal-900 to-cyan-950",orbs:["bg-emerald-500/30","bg-teal-500/25","bg-cyan-400/20"]},just_listed:{bg:"from-amber-950 via-orange-900 to-yellow-950",orbs:["bg-amber-500/30","bg-orange-500/25","bg-yellow-400/20"]},thank_you:{bg:"from-rose-950 via-pink-900 to-red-950",orbs:["bg-rose-500/30","bg-pink-500/25","bg-red-400/20"]},congratulations:{bg:"from-yellow-950 via-amber-900 to-orange-950",orbs:["bg-yellow-500/30","bg-amber-500/25","bg-orange-400/20"]},holiday:{bg:"from-red-950 via-rose-900 to-emerald-950",orbs:["bg-red-500/30","bg-green-500/25","bg-rose-400/20"]},thinking_of_you:{bg:"from-indigo-950 via-violet-900 to-purple-950",orbs:["bg-indigo-500/30","bg-violet-500/25","bg-purple-400/20"]}};function Z$s(s){const{cardType:t,recipientName:r,propertyAddress:n,anniversaryYears:a,customMessage:i,agentName:l,agentPhotoUrl:o,agentPhone:c,agentEmail:d,agentBrokerage:h,propertyPhotoUrl:m,videoUrl:p}=s,x=iD[t],y=qWe[t]||qWe.home_anniversary;return e.jsxs("div",{className:`min-h-screen bg-gradient-to-br ${y.bg} flex items-center justify-center p-4 overflow-hidden relative`,children:[e.jsx(Awe,{delay:0,x:"10%",y:"10%",color:y.orbs[0],size:200}),e.jsx(Awe,{delay:1,x:"70%",y:"60%",color:y.orbs[1],size:180}),e.jsx(Awe,{delay:2,x:"50%",y:"20%",color:y.orbs[2],size:150}),e.jsx(nO,{delay:0,x:"20%",y:"25%"}),e.jsx(nO,{delay:.8,x:"75%",y:"15%"}),e.jsx(nO,{delay:1.6,x:"85%",y:"65%"}),e.jsx(nO,{delay:2.4,x:"10%",y:"75%"}),e.jsx(nO,{delay:.4,x:"45%",y:"85%"}),e.jsxs(Ur.div,{className:"w-full max-w-md relative z-10",initial:{opacity:0,y:40},animate:{opacity:1,y:0},transition:{duration:.7,ease:"easeOut"},children:[e.jsxs(Ur.div,{className:"relative rounded-3xl overflow-hidden",initial:{scale:.9},animate:{scale:1},transition:{duration:.5,delay:.2,type:"spring",stiffness:150},children:[e.jsx(Ur.div,{className:"absolute -inset-[1px] rounded-3xl bg-gradient-to-r from-violet-500 via-fuchsia-500 to-violet-500 opacity-50",animate:{backgroundPosition:["0% 50%","100% 50%","0% 50%"]},transition:{duration:4,repeat:1/0,ease:"linear"},style:{backgroundSize:"200% 200%"}}),e.jsxs("div",{className:"relative bg-white/5 backdrop-blur-xl border border-white/10 rounded-3xl px-8 py-10 text-center m-[1px]",children:[e.jsxs(Ur.div,{className:"mx-auto mb-6 h-20 w-20 rounded-2xl bg-gradient-to-br from-violet-500 to-fuchsia-500 flex items-center justify-center shadow-2xl shadow-violet-500/40 relative",initial:{scale:0,rotate:-20},animate:{scale:1,rotate:0},transition:{duration:.6,delay:.4,type:"spring",stiffness:200},children:[e.jsx(Ur.div,{className:"absolute inset-0 rounded-2xl bg-gradient-to-br from-violet-500 to-fuchsia-500",animate:{scale:[1,1.3,1],opacity:[.6,0,.6]},transition:{duration:2,repeat:1/0,ease:"easeInOut"}}),e.jsx("span",{className:"text-4xl relative z-10",children:x.icon})]}),t==="home_anniversary"&&a!==null&&a>0&&e.jsxs(Ur.div,{className:"inline-flex items-center gap-2 mb-5 px-5 py-2 rounded-full bg-white/10 border border-white/15 backdrop-blur-sm",initial:{opacity:0,scale:.8},animate:{opacity:1,scale:1},transition:{duration:.4,delay:.6},children:[e.jsx(Ur.span,{className:"text-3xl font-black text-white",initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:.8},children:a}),e.jsx("span",{className:"text-xs font-semibold text-violet-200 uppercase tracking-widest",children:a===1?"Year":"Years"})]}),e.jsx(Ur.h1,{className:"text-5xl font-black text-transparent bg-clip-text bg-gradient-to-r from-violet-200 via-white to-fuchsia-200 mb-2 leading-tight",initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{duration:.5,delay:.7},children:x.title[0]}),x.title[1]&&e.jsx(Ur.h2,{className:"text-5xl font-black text-transparent bg-clip-text bg-gradient-to-r from-fuchsia-300 via-violet-200 to-purple-300 mb-2 leading-tight",initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{duration:.5,delay:.85},children:x.title[1]}),e.jsx(Ur.div,{className:"text-3xl mb-4",initial:{opacity:0,scale:0},animate:{opacity:1,scale:1},transition:{duration:.4,delay:1,type:"spring",stiffness:300},children:x.emojis.slice(0,3).join("")}),e.jsxs(Ur.div,{initial:{opacity:0},animate:{opacity:1},transition:{delay:1.1},children:[e.jsx("p",{className:"text-xl font-semibold text-white/90 mb-1",children:r}),n&&e.jsxs("p",{className:"text-sm text-violet-300/70 mb-6 flex items-center justify-center gap-1.5",children:[e.jsx(Fn,{className:"h-3.5 w-3.5"}),n]})]}),m&&e.jsx(Ur.div,{className:"mb-6 rounded-2xl overflow-hidden border border-white/10 shadow-lg",initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{delay:1.2,duration:.5},children:e.jsx("img",{src:m,alt:"Property",className:"w-full h-48 object-cover"})}),p&&e.jsx(Ur.div,{className:"mb-6 rounded-2xl overflow-hidden border border-white/10 shadow-lg",initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{delay:1.25,duration:.5},children:e.jsx("iframe",{src:`${p}?autoplay=false&responsive=true`,className:"w-full aspect-video",allow:"autoplay; encrypted-media",allowFullScreen:!0})}),e.jsx(Ur.div,{className:"bg-white/5 rounded-2xl p-5 border border-white/10 mb-8 backdrop-blur-sm",initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:1.3},children:e.jsx("p",{className:"text-sm text-violet-100/80 leading-relaxed",children:i||x.defaultMessage})}),e.jsxs(Ur.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:1.5},children:[e.jsxs("div",{className:"flex items-center justify-center gap-3",children:[o?e.jsx(Ur.img,{src:o,alt:l,className:"h-12 w-12 rounded-xl object-cover ring-2 ring-violet-500/40 shadow-lg",whileHover:{scale:1.1}}):e.jsx("div",{className:"h-12 w-12 rounded-xl bg-gradient-to-br from-violet-500 to-fuchsia-500 flex items-center justify-center shadow-lg",children:e.jsx("span",{className:"text-sm font-bold text-white",children:l.charAt(0)})}),e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"text-sm font-bold text-white",children:l}),h&&e.jsx("p",{className:"text-xs text-violet-300/60",children:h})]})]}),e.jsxs("div",{className:"flex items-center justify-center gap-2 mt-5",children:[c&&e.jsxs(Ur.a,{href:`tel:${c}`,className:"flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-gradient-to-r from-violet-500/30 to-fuchsia-500/30 text-xs font-semibold text-white hover:from-violet-500/50 hover:to-fuchsia-500/50 transition-all border border-white/15 shadow-lg",whileHover:{scale:1.05},whileTap:{scale:.95},children:[e.jsx(Yn,{className:"h-3.5 w-3.5"})," Call Me"]}),d&&e.jsxs(Ur.a,{href:`mailto:${d}`,className:"flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-gradient-to-r from-violet-500/30 to-fuchsia-500/30 text-xs font-semibold text-white hover:from-violet-500/50 hover:to-fuchsia-500/50 transition-all border border-white/15 shadow-lg",whileHover:{scale:1.05},whileTap:{scale:.95},children:[e.jsx(er,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})]}),e.jsx(Ur.p,{className:"text-center text-[10px] text-violet-400/40 mt-4",initial:{opacity:0},animate:{opacity:1},transition:{delay:2},children:"Powered by LevelUp"})]})]})}function X$s({emoji:s,delay:t,x:r,duration:n}){return e.jsx(Ur.div,{className:"absolute text-2xl pointer-events-none",style:{left:r,bottom:-20},animate:{y:[0,-600],opacity:[0,1,1,0],x:[0,15,-10,5],rotate:[0,20,-15,10]},transition:{duration:n,delay:t,repeat:1/0,ease:"easeOut"},children:s})}const VWe={home_anniversary:{bg:"from-amber-50 via-orange-50 to-rose-50",header:"from-amber-400 via-orange-400 to-rose-400",accent:"text-amber-900",text:"text-amber-800"},birthday:{bg:"from-pink-50 via-rose-50 to-fuchsia-50",header:"from-pink-400 via-rose-400 to-fuchsia-400",accent:"text-pink-900",text:"text-pink-800"},just_sold:{bg:"from-emerald-50 via-teal-50 to-cyan-50",header:"from-emerald-400 via-teal-400 to-cyan-400",accent:"text-emerald-900",text:"text-emerald-800"},just_listed:{bg:"from-sky-50 via-blue-50 to-indigo-50",header:"from-sky-400 via-blue-400 to-indigo-400",accent:"text-blue-900",text:"text-blue-800"},thank_you:{bg:"from-rose-50 via-pink-50 to-red-50",header:"from-rose-400 via-pink-400 to-red-400",accent:"text-rose-900",text:"text-rose-800"},congratulations:{bg:"from-yellow-50 via-amber-50 to-orange-50",header:"from-yellow-400 via-amber-400 to-orange-400",accent:"text-amber-900",text:"text-amber-800"},holiday:{bg:"from-red-50 via-green-50 to-emerald-50",header:"from-red-500 via-green-500 to-emerald-500",accent:"text-green-900",text:"text-green-800"},thinking_of_you:{bg:"from-violet-50 via-purple-50 to-indigo-50",header:"from-violet-400 via-purple-400 to-indigo-400",accent:"text-violet-900",text:"text-violet-800"}};function Q$s(s){const{cardType:t,recipientName:r,propertyAddress:n,anniversaryYears:a,customMessage:i,agentName:l,agentPhotoUrl:o,agentPhone:c,agentEmail:d,agentBrokerage:h,propertyPhotoUrl:m,videoUrl:p}=s,x=iD[t],y=VWe[t]||VWe.home_anniversary;return e.jsxs("div",{className:`min-h-screen bg-gradient-to-b ${y.bg} flex items-center justify-center p-4 overflow-hidden relative`,children:[x.emojis.map((_,b)=>e.jsx(X$s,{emoji:_,delay:b*1.2,x:`${15+b*14}%`,duration:5+b%3},b)),e.jsx(Ur.div,{className:"absolute top-1/4 left-1/2 -translate-x-1/2 w-96 h-96 bg-gradient-to-r from-amber-200/30 to-rose-200/30 rounded-full blur-[100px]",animate:{scale:[1,1.2,1],opacity:[.3,.5,.3]},transition:{duration:6,repeat:1/0,ease:"easeInOut"}}),e.jsxs(Ur.div,{className:"w-full max-w-md relative z-10",initial:{opacity:0,y:30},animate:{opacity:1,y:0},transition:{duration:.7},children:[e.jsxs(Ur.div,{className:"bg-white rounded-3xl shadow-[0_20px_60px_-15px_rgba(251,146,60,0.2)] overflow-hidden border border-amber-100",initial:{scale:.9},animate:{scale:1},transition:{duration:.5,delay:.2,type:"spring",stiffness:150},children:[e.jsxs(Ur.div,{className:`h-28 bg-gradient-to-r ${y.header} relative overflow-hidden`,children:[e.jsx(Ur.div,{className:"absolute inset-0 bg-gradient-to-r from-transparent via-white/20 to-transparent",animate:{x:["-100%","200%"]},transition:{duration:3,repeat:1/0,repeatDelay:2,ease:"easeInOut"}}),e.jsx(Ur.div,{className:"absolute top-3 left-10 text-5xl",animate:{rotate:[0,10,-5,0],y:[0,-3,0]},transition:{duration:3,repeat:1/0,ease:"easeInOut"},children:x.emojis[0]}),e.jsx(Ur.div,{className:"absolute top-2 right-14 text-3xl",animate:{scale:[1,1.3,1],rotate:[0,15,0]},transition:{duration:2,repeat:1/0,ease:"easeInOut",delay:.5},children:x.emojis[1]}),e.jsx(Ur.div,{className:"absolute bottom-2 left-1/2 -translate-x-1/2 text-3xl",animate:{y:[0,-5,0],scale:[1,1.1,1]},transition:{duration:2.5,repeat:1/0,ease:"easeInOut",delay:1},children:x.emojis[2]})]}),e.jsxs("div",{className:"px-8 py-8 text-center -mt-10 relative",children:[e.jsx(Ur.div,{className:"mx-auto mb-4 h-20 w-20 rounded-full bg-white shadow-xl flex items-center justify-center border-4 border-white relative",initial:{scale:0},animate:{scale:1},transition:{delay:.4,type:"spring",stiffness:300},children:e.jsx(Ur.div,{animate:{scale:[1,1.2,1]},transition:{duration:1.5,repeat:1/0,ease:"easeInOut"},children:e.jsx("span",{className:"text-3xl",children:x.icon})})}),t==="home_anniversary"&&a!==null&&a>0&&e.jsx(Ur.div,{className:"mb-3",initial:{opacity:0,scale:.8},animate:{opacity:1,scale:1},transition:{delay:.6},children:e.jsxs("span",{className:`inline-flex items-baseline gap-1.5 ${y.accent}`,children:[e.jsx(Ur.span,{className:"text-5xl font-black",initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:.8},children:a}),e.jsx("span",{className:"text-sm font-semibold",children:a===1?"year":"wonderful years"})]})}),e.jsxs(Ur.h1,{className:`text-3xl font-bold ${y.accent} mb-1`,initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:.9},children:[x.title.join(" ")," ",x.emojis[4]]}),e.jsxs(Ur.div,{initial:{opacity:0},animate:{opacity:1},transition:{delay:1.1},children:[e.jsx("p",{className:`text-lg font-semibold ${y.text} mb-1`,children:r}),n&&e.jsxs("p",{className:`text-sm ${y.text} opacity-70 flex items-center justify-center gap-1 mb-5`,children:[e.jsx(Qa,{className:"h-3 w-3"}),n]})]}),m&&e.jsx(Ur.div,{className:"mb-5 rounded-2xl overflow-hidden border border-amber-200 shadow-md",initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{delay:1.2,duration:.5},children:e.jsx("img",{src:m,alt:"Property",className:"w-full h-48 object-cover"})}),p&&e.jsx(Ur.div,{className:"mb-5 rounded-2xl overflow-hidden border border-amber-200 shadow-md",initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{delay:1.25,duration:.5},children:e.jsx("iframe",{src:`${p}?autoplay=false&responsive=true`,className:"w-full aspect-video",allow:"autoplay; encrypted-media",allowFullScreen:!0})}),e.jsx(Ur.div,{className:"bg-gradient-to-br from-amber-50 to-orange-50 rounded-2xl p-5 mb-6 border border-amber-100 shadow-inner",initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:1.3},children:e.jsxs("p",{className:`text-sm ${y.text} leading-relaxed italic`,children:['"',i||x.defaultMessage,'"']})}),e.jsxs(Ur.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:1.5},children:[e.jsxs("div",{className:"flex items-center gap-3 justify-center",children:[o?e.jsx(Ur.img,{src:o,alt:l,className:"h-12 w-12 rounded-full object-cover ring-2 ring-amber-200 shadow-md",whileHover:{scale:1.1}}):e.jsx("div",{className:`h-12 w-12 rounded-full bg-gradient-to-br ${y.header} flex items-center justify-center shadow-md`,children:e.jsx("span",{className:"text-sm font-bold text-white",children:l.charAt(0)})}),e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:`text-sm font-bold ${y.accent}`,children:l}),h&&e.jsx("p",{className:`text-xs ${y.text} opacity-60`,children:h})]})]}),e.jsxs("div",{className:"flex items-center justify-center gap-2 mt-4",children:[c&&e.jsxs(Ur.a,{href:`tel:${c}`,className:`flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-gradient-to-r ${y.header} text-xs font-semibold text-white shadow-md`,whileHover:{scale:1.05},whileTap:{scale:.95},children:[e.jsx(Yn,{className:"h-3.5 w-3.5"})," Call"]}),d&&e.jsxs(Ur.a,{href:`mailto:${d}`,className:`flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-gradient-to-r ${y.header} text-xs font-semibold text-white shadow-md`,whileHover:{scale:1.05},whileTap:{scale:.95},children:[e.jsx(er,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})]}),e.jsx(Ur.p,{className:"text-center text-[10px] text-amber-400 mt-4",initial:{opacity:0},animate:{opacity:1},transition:{delay:2},children:"Powered by LevelUp"})]})]})}function iV({delay:s,x:t,y:r,size:n,color:a}){return e.jsx(Ur.div,{className:`absolute rounded-full ${a} blur-3xl`,style:{left:t,top:r,width:n,height:n},animate:{scale:[1,1.3,1],opacity:[.4,.7,.4],x:[0,20,-10,0],y:[0,-15,10,0]},transition:{duration:8,delay:s,repeat:1/0,ease:"easeInOut"}})}function Mwe({delay:s,x:t,y:r,size:n}){return e.jsx(Ur.div,{className:"absolute rounded-full border border-white/10",style:{left:t,top:r,width:n,height:n},animate:{scale:[1,1.2,1],opacity:[.1,.3,.1],rotate:[0,180,360]},transition:{duration:12,delay:s,repeat:1/0,ease:"linear"}})}const HWe={home_anniversary:{mesh:["bg-sky-400/40","bg-indigo-500/30","bg-violet-400/25"],accent:"text-sky-200",glow:"shadow-sky-500/20"},birthday:{mesh:["bg-pink-400/40","bg-fuchsia-500/30","bg-purple-400/25"],accent:"text-pink-200",glow:"shadow-pink-500/20"},just_sold:{mesh:["bg-emerald-400/40","bg-teal-500/30","bg-cyan-400/25"],accent:"text-emerald-200",glow:"shadow-emerald-500/20"},just_listed:{mesh:["bg-amber-400/40","bg-orange-500/30","bg-yellow-400/25"],accent:"text-amber-200",glow:"shadow-amber-500/20"},thank_you:{mesh:["bg-rose-400/40","bg-pink-500/30","bg-red-400/25"],accent:"text-rose-200",glow:"shadow-rose-500/20"},congratulations:{mesh:["bg-yellow-400/40","bg-amber-500/30","bg-orange-400/25"],accent:"text-yellow-200",glow:"shadow-yellow-500/20"},holiday:{mesh:["bg-red-400/40","bg-emerald-500/30","bg-green-400/25"],accent:"text-red-200",glow:"shadow-red-500/20"},thinking_of_you:{mesh:["bg-violet-400/40","bg-indigo-500/30","bg-blue-400/25"],accent:"text-violet-200",glow:"shadow-violet-500/20"}};function J$s(s){const{cardType:t,recipientName:r,propertyAddress:n,anniversaryYears:a,customMessage:i,agentName:l,agentPhotoUrl:o,agentPhone:c,agentEmail:d,agentBrokerage:h,propertyPhotoUrl:m,videoUrl:p}=s,x=iD[t],y=HWe[t]||HWe.home_anniversary;return e.jsxs("div",{className:"min-h-screen bg-slate-950 flex items-center justify-center p-4 overflow-hidden relative",children:[e.jsx(iV,{delay:0,x:"5%",y:"10%",size:300,color:y.mesh[0]}),e.jsx(iV,{delay:2,x:"60%",y:"50%",size:250,color:y.mesh[1]}),e.jsx(iV,{delay:4,x:"30%",y:"70%",size:200,color:y.mesh[2]}),e.jsx(iV,{delay:1,x:"80%",y:"15%",size:180,color:y.mesh[0]}),e.jsx(Mwe,{delay:0,x:"15%",y:"20%",size:100}),e.jsx(Mwe,{delay:3,x:"70%",y:"60%",size:140}),e.jsx(Mwe,{delay:6,x:"40%",y:"10%",size:80}),e.jsx("div",{className:"absolute inset-0 opacity-[0.03]",style:{backgroundImage:`url("data:image/svg+xml,%3Csvg viewBox='0 0 256 256' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='noise'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23noise)'/%3E%3C/svg%3E")`}}),e.jsxs(Ur.div,{className:"w-full max-w-md relative z-10",initial:{opacity:0,y:40},animate:{opacity:1,y:0},transition:{duration:.8,ease:[.16,1,.3,1]},children:[e.jsxs(Ur.div,{className:`relative rounded-[28px] overflow-hidden backdrop-blur-2xl bg-white/[0.06] border border-white/[0.12] shadow-2xl ${y.glow}`,initial:{scale:.92},animate:{scale:1},transition:{duration:.6,delay:.2,type:"spring",stiffness:120},children:[e.jsx("div",{className:"relative h-[2px] bg-gradient-to-r from-transparent via-white/20 to-transparent overflow-hidden",children:e.jsx(Ur.div,{className:"absolute inset-0 bg-gradient-to-r from-transparent via-white/60 to-transparent",animate:{x:["-100%","200%"]},transition:{duration:4,repeat:1/0,repeatDelay:3,ease:"easeInOut"}})}),e.jsxs("div",{className:"px-8 py-10 text-center",children:[e.jsxs(Ur.div,{className:"mx-auto mb-6 h-24 w-24 rounded-3xl bg-white/[0.08] backdrop-blur-xl border border-white/[0.15] flex items-center justify-center relative",initial:{scale:0,rotate:-15},animate:{scale:1,rotate:0},transition:{duration:.6,delay:.4,type:"spring",stiffness:180},children:[e.jsx(Ur.div,{className:"absolute -inset-1 rounded-3xl border border-white/[0.08]",animate:{scale:[1,1.1,1],opacity:[.3,0,.3]},transition:{duration:3,repeat:1/0,ease:"easeInOut"}}),e.jsx(Ur.span,{className:"text-5xl",animate:{scale:[1,1.08,1]},transition:{duration:2,repeat:1/0,ease:"easeInOut"},children:x.icon})]}),t==="home_anniversary"&&a!==null&&a>0&&e.jsxs(Ur.div,{className:"inline-flex items-center gap-2 mb-5 px-5 py-2 rounded-full bg-white/[0.06] border border-white/[0.1] backdrop-blur-sm",initial:{opacity:0,scale:.8},animate:{opacity:1,scale:1},transition:{duration:.4,delay:.6},children:[e.jsx(Ur.span,{className:"text-3xl font-black text-white",initial:{opacity:0},animate:{opacity:1},transition:{delay:.8},children:a}),e.jsx("span",{className:`text-[10px] font-bold uppercase tracking-[0.2em] ${y.accent}`,children:a===1?"Year":"Years"})]}),e.jsx(Ur.h1,{className:"text-4xl font-extralight text-white/90 mb-1 tracking-tight",initial:{opacity:0,y:15},animate:{opacity:1,y:0},transition:{duration:.6,delay:.7},children:x.title[0]}),x.title[1]&&e.jsx(Ur.h2,{className:"text-4xl font-bold text-white mb-6 tracking-tight",initial:{opacity:0,y:15},animate:{opacity:1,y:0},transition:{duration:.6,delay:.85},children:x.title[1]}),e.jsxs(Ur.div,{initial:{opacity:0},animate:{opacity:1},transition:{delay:1},children:[e.jsx("p",{className:"text-xl font-medium text-white/80 mb-1",children:r}),n&&e.jsxs("p",{className:"text-sm text-white/30 mb-6 flex items-center justify-center gap-1.5",children:[e.jsx(Qa,{className:"h-3 w-3"})," ",n]})]}),e.jsx(Ur.div,{className:"h-px bg-gradient-to-r from-transparent via-white/15 to-transparent mx-auto mb-6",initial:{width:0},animate:{width:"70%"},transition:{duration:1,delay:1.1},style:{margin:"0 auto 1.5rem"}}),m&&e.jsx(Ur.div,{className:"mb-6 rounded-2xl overflow-hidden border border-white/10",initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{delay:1.15,duration:.5},children:e.jsx("img",{src:m,alt:"Property",className:"w-full h-48 object-cover"})}),p&&e.jsx(Ur.div,{className:"mb-6 rounded-2xl overflow-hidden border border-white/10",initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{delay:1.2,duration:.5},children:e.jsx("iframe",{src:`${p}?autoplay=false&responsive=true`,className:"w-full aspect-video",allow:"autoplay; encrypted-media",allowFullScreen:!0})}),e.jsx(Ur.div,{className:"bg-white/[0.04] rounded-2xl p-5 border border-white/[0.08] mb-8 backdrop-blur-sm",initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:1.3},children:e.jsxs("p",{className:"text-sm text-white/60 leading-relaxed italic",children:['"',i||x.defaultMessage,'"']})}),e.jsxs(Ur.div,{className:"border-t border-white/[0.06] pt-6",initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:1.5},children:[e.jsxs("div",{className:"flex items-center justify-center gap-3",children:[o?e.jsx(Ur.img,{src:o,alt:l,className:"h-12 w-12 rounded-2xl object-cover ring-1 ring-white/10",whileHover:{scale:1.08}}):e.jsx("div",{className:"h-12 w-12 rounded-2xl bg-white/[0.08] border border-white/[0.1] flex items-center justify-center",children:e.jsx("span",{className:"text-sm font-semibold text-white/60",children:l.charAt(0)})}),e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"text-sm font-semibold text-white/80",children:l}),h&&e.jsx("p",{className:"text-xs text-white/30",children:h})]})]}),e.jsxs("div",{className:"flex items-center justify-center gap-2 mt-4",children:[c&&e.jsxs(Ur.a,{href:`tel:${c}`,className:"flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-white/[0.06] border border-white/[0.1] text-xs font-medium text-white/70 hover:bg-white/[0.12] transition-colors backdrop-blur-sm",whileHover:{scale:1.05},whileTap:{scale:.95},children:[e.jsx(Yn,{className:"h-3.5 w-3.5"})," Call"]}),d&&e.jsxs(Ur.a,{href:`mailto:${d}`,className:"flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-white/[0.06] border border-white/[0.1] text-xs font-medium text-white/70 hover:bg-white/[0.12] transition-colors backdrop-blur-sm",whileHover:{scale:1.05},whileTap:{scale:.95},children:[e.jsx(er,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})]}),e.jsx(Ur.p,{className:"text-center text-[10px] text-white/20 mt-4",initial:{opacity:0},animate:{opacity:1},transition:{delay:2},children:"Powered by LevelUp"})]})]})}function Iwe({delay:s,x:t,angle:r,color:n}){return e.jsx(Ur.div,{className:`absolute h-[400px] w-[1px] ${n} origin-top`,style:{left:t,top:"-10%",transform:`rotate(${r}deg)`},animate:{opacity:[0,.4,0],scaleY:[.5,1,.5]},transition:{duration:6,delay:s,repeat:1/0,ease:"easeInOut"}})}function oV({delay:s,x:t}){return e.jsx(Ur.div,{className:"absolute w-1 h-1 rounded-full bg-amber-400/60",style:{left:t,bottom:"20%"},animate:{y:[0,-200,-400],x:[0,15,-10],opacity:[0,.8,0],scale:[0,1.5,0]},transition:{duration:4,delay:s,repeat:1/0,ease:"easeOut"}})}const GWe={home_anniversary:{gradient:"from-slate-950 via-blue-950 to-slate-950",accent:"from-blue-400 to-cyan-300",stripe:"bg-blue-400/20"},birthday:{gradient:"from-slate-950 via-rose-950 to-slate-950",accent:"from-rose-400 to-pink-300",stripe:"bg-rose-400/20"},just_sold:{gradient:"from-slate-950 via-emerald-950 to-slate-950",accent:"from-emerald-400 to-green-300",stripe:"bg-emerald-400/20"},just_listed:{gradient:"from-slate-950 via-amber-950 to-slate-950",accent:"from-amber-400 to-yellow-300",stripe:"bg-amber-400/20"},thank_you:{gradient:"from-slate-950 via-pink-950 to-slate-950",accent:"from-pink-400 to-rose-300",stripe:"bg-pink-400/20"},congratulations:{gradient:"from-slate-950 via-yellow-950 to-slate-950",accent:"from-yellow-400 to-amber-300",stripe:"bg-yellow-400/20"},holiday:{gradient:"from-slate-950 via-red-950 to-slate-950",accent:"from-red-400 to-green-400",stripe:"bg-red-400/20"},thinking_of_you:{gradient:"from-slate-950 via-purple-950 to-slate-950",accent:"from-purple-400 to-violet-300",stripe:"bg-purple-400/20"}};function eUs(s){const{cardType:t,recipientName:r,propertyAddress:n,anniversaryYears:a,customMessage:i,agentName:l,agentPhotoUrl:o,agentPhone:c,agentEmail:d,agentBrokerage:h,propertyPhotoUrl:m,videoUrl:p}=s,x=iD[t],y=GWe[t]||GWe.home_anniversary;return e.jsxs("div",{className:`min-h-screen bg-gradient-to-b ${y.gradient} flex items-center justify-center p-4 overflow-hidden relative`,children:[e.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(ellipse_at_top,rgba(255,255,255,0.04)_0%,transparent_60%)]"}),e.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(ellipse_at_bottom,rgba(0,0,0,0.6)_0%,transparent_60%)]"}),e.jsx(Iwe,{delay:0,x:"20%",angle:15,color:y.stripe}),e.jsx(Iwe,{delay:2,x:"75%",angle:-12,color:y.stripe}),e.jsx(Iwe,{delay:4,x:"50%",angle:5,color:y.stripe}),e.jsx(oV,{delay:0,x:"30%"}),e.jsx(oV,{delay:1.5,x:"60%"}),e.jsx(oV,{delay:3,x:"45%"}),e.jsx(oV,{delay:.7,x:"75%"}),e.jsx("div",{className:"absolute inset-0 opacity-[0.015] mix-blend-overlay",style:{backgroundImage:`url("data:image/svg+xml,%3Csvg viewBox='0 0 512 512' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.7' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E")`}}),e.jsxs(Ur.div,{className:"w-full max-w-md relative z-10",initial:{opacity:0},animate:{opacity:1},transition:{duration:1.2},children:[e.jsx(Ur.div,{className:"relative overflow-hidden",initial:{y:50},animate:{y:0},transition:{duration:.8,delay:.3,ease:[.16,1,.3,1]},children:e.jsxs("div",{className:"px-8 py-12 text-center",children:[e.jsx(Ur.div,{className:"mx-auto mb-8 relative",initial:{scale:0},animate:{scale:1},transition:{duration:.8,delay:.5,type:"spring",stiffness:100},children:e.jsx(Ur.div,{className:`h-20 w-20 mx-auto rounded-2xl bg-gradient-to-br ${y.accent} flex items-center justify-center shadow-2xl`,animate:{boxShadow:["0 0 40px rgba(255,255,255,0.05)","0 0 80px rgba(255,255,255,0.1)","0 0 40px rgba(255,255,255,0.05)"]},transition:{duration:3,repeat:1/0,ease:"easeInOut"},children:e.jsx("span",{className:"text-4xl",children:x.icon})})}),t==="home_anniversary"&&a!==null&&a>0&&e.jsxs(Ur.div,{className:"mb-6",initial:{opacity:0},animate:{opacity:1},transition:{delay:.7},children:[e.jsx(Ur.span,{className:`text-6xl font-black bg-gradient-to-r ${y.accent} bg-clip-text text-transparent`,initial:{scale:.5,opacity:0},animate:{scale:1,opacity:1},transition:{delay:.9,type:"spring"},children:a}),e.jsx("p",{className:"text-[10px] font-bold uppercase tracking-[0.4em] text-white/30 mt-1",children:a===1?"Year":"Years"})]}),e.jsx("div",{className:"overflow-hidden mb-2",children:e.jsx(Ur.h1,{className:"text-5xl font-thin text-white/90 tracking-wide",initial:{y:"100%"},animate:{y:0},transition:{duration:.7,delay:.8,ease:[.16,1,.3,1]},children:x.title[0]})}),x.title[1]&&e.jsx("div",{className:"overflow-hidden mb-8",children:e.jsx(Ur.h2,{className:`text-5xl font-black bg-gradient-to-r ${y.accent} bg-clip-text text-transparent`,initial:{y:"100%"},animate:{y:0},transition:{duration:.7,delay:.95,ease:[.16,1,.3,1]},children:x.title[1]})}),e.jsxs(Ur.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:1.1,duration:.6},children:[e.jsx("p",{className:"text-lg font-light text-white/70 tracking-wide",children:r}),n&&e.jsxs("p",{className:"text-xs text-white/25 mt-1 flex items-center justify-center gap-1",children:[e.jsx(Qa,{className:"h-3 w-3"})," ",n]})]}),e.jsxs(Ur.div,{className:"flex items-center justify-center gap-3 my-8",initial:{opacity:0},animate:{opacity:1},transition:{delay:1.2},children:[e.jsx(Ur.div,{className:"h-px flex-1 max-w-[60px] bg-gradient-to-r from-transparent to-white/15",initial:{scaleX:0},animate:{scaleX:1},transition:{delay:1.3,duration:.8},style:{transformOrigin:"right"}}),e.jsx(Ur.span,{className:"text-white/10 text-xs",animate:{rotate:[0,360]},transition:{duration:20,repeat:1/0,ease:"linear"},children:"✦"}),e.jsx(Ur.div,{className:"h-px flex-1 max-w-[60px] bg-gradient-to-l from-transparent to-white/15",initial:{scaleX:0},animate:{scaleX:1},transition:{delay:1.3,duration:.8},style:{transformOrigin:"left"}})]}),m&&e.jsxs(Ur.div,{className:"mb-8 rounded-2xl overflow-hidden ring-1 ring-white/5",initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:1.3,duration:.6},children:[e.jsx("img",{src:m,alt:"Property",className:"w-full h-48 object-cover"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-slate-950/30 to-transparent pointer-events-none"})]}),p&&e.jsx(Ur.div,{className:"mb-8 rounded-2xl overflow-hidden ring-1 ring-white/5",initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:1.35,duration:.6},children:e.jsx("iframe",{src:`${p}?autoplay=false&responsive=true`,className:"w-full aspect-video",allow:"autoplay; encrypted-media",allowFullScreen:!0})}),e.jsx(Ur.p,{className:"text-sm text-white/40 leading-relaxed max-w-xs mx-auto mb-10 font-light",initial:{opacity:0},animate:{opacity:1},transition:{delay:1.4,duration:.8},children:i||x.defaultMessage}),e.jsxs(Ur.div,{className:"pt-6 border-t border-white/[0.04]",initial:{opacity:0,y:15},animate:{opacity:1,y:0},transition:{delay:1.6,duration:.6},children:[e.jsxs("div",{className:"flex items-center justify-center gap-3 mb-4",children:[o?e.jsx(Ur.img,{src:o,alt:l,className:"h-12 w-12 rounded-full object-cover ring-2 ring-white/10 shadow-xl",whileHover:{scale:1.1}}):e.jsx("div",{className:`h-12 w-12 rounded-full bg-gradient-to-br ${y.accent} flex items-center justify-center shadow-xl`,children:e.jsx("span",{className:"text-sm font-bold text-slate-900",children:l.charAt(0)})}),e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"text-sm font-medium text-white/70",children:l}),h&&e.jsx("p",{className:"text-[11px] text-white/25",children:h})]})]}),e.jsxs("div",{className:"flex items-center justify-center gap-2",children:[c&&e.jsxs(Ur.a,{href:`tel:${c}`,className:`flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-gradient-to-r ${y.accent} text-xs font-semibold text-slate-900 shadow-lg`,whileHover:{scale:1.05,boxShadow:"0 10px 40px rgba(255,255,255,0.15)"},whileTap:{scale:.95},children:[e.jsx(Yn,{className:"h-3.5 w-3.5"})," Call"]}),d&&e.jsxs(Ur.a,{href:`mailto:${d}`,className:"flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-white/[0.06] border border-white/[0.1] text-xs font-medium text-white/60 hover:bg-white/[0.12] transition-colors",whileHover:{scale:1.05},whileTap:{scale:.95},children:[e.jsx(er,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})}),e.jsx(Ur.p,{className:"text-center text-[10px] text-white/10 mt-6",initial:{opacity:0},animate:{opacity:1},transition:{delay:2.2},children:"Powered by LevelUp"})]})]})}function Ivt(){const{shareToken:s}=Po(),{data:t,isLoading:r,error:n}=yt({queryKey:["public-sendable-card",s],queryFn:async()=>{const{data:l,error:o}=await V.from("sendable_cards").select("*").eq("share_token",s).single();if(o)throw o;return l},enabled:!!s});if(S.useEffect(()=>{s&&V.rpc("log_sendable_card_view",{p_share_token:s}).then(({error:l})=>{l&&console.error("Error tracking view:",l)})},[s]),r)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:e.jsxs("div",{className:"animate-pulse space-y-4 text-center",children:[e.jsx("div",{className:"h-8 w-48 bg-muted rounded mx-auto"}),e.jsx("div",{className:"h-4 w-32 bg-muted rounded mx-auto"})]})});if(n||!t)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold mb-2",children:"Card not found"}),e.jsx("p",{className:"text-muted-foreground",children:"This card may have been removed or the link is invalid."})]})});const a=t.home_anniversary_date?Math.floor((Date.now()-Tc(t.home_anniversary_date).getTime())/(365.25*24*60*60*1e3)):null,i={cardType:t.card_type||"home_anniversary",recipientName:t.recipient_name,propertyAddress:t.property_address,anniversaryYears:a,customMessage:t.custom_message,agentName:t.agent_name,agentPhotoUrl:t.agent_photo_url,agentPhone:t.agent_phone,agentEmail:t.agent_email,agentBrokerage:t.agent_brokerage,propertyPhotoUrl:t.property_photo_url,videoUrl:t.video_url||null};switch(t.template){case"bold":return e.jsx(Z$s,{...i});case"warm":return e.jsx(Q$s,{...i});case"glass":return e.jsx(J$s,{...i});case"cinematic":return e.jsx(eUs,{...i});case"elegant":default:return e.jsx(Y$s,{...i})}}function tUs(){const s=ba();return yt({queryKey:["drip-settings",s],queryFn:async()=>{if(!s)return null;const{data:t,error:r}=await V.from("drip_settings").select("*").eq("user_id",s).maybeSingle();if(r)throw r;return t},enabled:!!s})}function sUs(){const s=ba(),t=ns();return Pt({mutationFn:async r=>{if(!s)throw new Error("Not authenticated");const{data:n}=await V.from("drip_settings").select("id").eq("user_id",s).maybeSingle();if(n){const{data:a,error:i}=await V.from("drip_settings").update(r).eq("user_id",s).select().single();if(i)throw i;return a}else{const{data:a,error:i}=await V.from("drip_settings").insert({user_id:s,is_globally_enabled:r.is_globally_enabled??!1,append_signature:r.append_signature??!0}).select().single();if(i)throw i;return a}},onSuccess:()=>{t.invalidateQueries({queryKey:["drip-settings"]})}})}function rUs(){const s=Fr(),{isGmailConnected:t,gmailEmail:r}=cf(),{data:n,isLoading:a}=tUs(),i=sUs(),[l,o]=S.useState(!1),[c,d]=S.useState(!0),[h,m]=S.useState(!1);S.useEffect(()=>{n&&(o(n.is_globally_enabled),d(n.append_signature))},[n]);const p=async y=>{if(y&&!t){he.error("Connect your Gmail account first before enabling Smart Drips");return}o(y);try{await i.mutateAsync({is_globally_enabled:y}),he.success(y?"Smart Drips enabled globally":"Smart Drips paused globally")}catch{o(!y),he.error("Failed to update settings")}},x=async y=>{d(y);try{await i.mutateAsync({append_signature:y}),he.success(y?"Signature will be appended to drip emails":"Signature disabled for drip emails")}catch{d(!y),he.error("Failed to update settings")}};return e.jsxs(bs,{open:h,onOpenChange:m,children:[e.jsx(Qi,{asChild:!0,children:e.jsxs(H,{variant:"outline",size:"sm",className:"gap-1.5",children:[e.jsx(Go,{className:"h-3.5 w-3.5"}),"Settings"]})}),e.jsxs(vs,{className:"sm:max-w-md",children:[e.jsxs(Cs,{children:[e.jsxs(Ns,{className:"flex items-center gap-2",children:[e.jsx(Go,{className:"h-5 w-5 text-primary"}),"Smart Drip Settings"]}),e.jsx(nn,{children:"Configure how your automated drip emails are sent."})]}),e.jsxs("div",{className:"space-y-5 pt-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Email Connection"}),e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border bg-muted/30",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:`p-2 rounded-full ${t?"bg-emerald-500/10":"bg-destructive/10"}`,children:e.jsx(er,{className:`h-4 w-4 ${t?"text-emerald-600":"text-destructive"}`})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:t?"Gmail Connected":"Gmail Not Connected"}),r&&e.jsx("p",{className:"text-xs text-muted-foreground",children:r})]})]}),t?e.jsxs(Xe,{variant:"outline",className:"gap-1 text-emerald-600 border-emerald-200 bg-emerald-500/10 text-[10px]",children:[e.jsx(ea,{className:"h-3 w-3"}),"Active"]}):e.jsxs(H,{variant:"outline",size:"sm",className:"text-xs gap-1",onClick:()=>{m(!1),s("/mission-control/integrations")},children:[e.jsx(gn,{className:"h-3 w-3"}),"Connect"]})]}),!t&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Smart Drips sends emails from your Gmail account. Connect Gmail to get started."})]}),e.jsx(Qo,{}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:`p-2 rounded-full ${l?"bg-emerald-500/10":"bg-muted"}`,children:e.jsx(kF,{className:`h-4 w-4 ${l?"text-emerald-600":"text-muted-foreground"}`})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Enable Smart Drips"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:l?"Active drips will send when deals move stages":"All drips are paused — nothing will send"})]})]}),e.jsx(Or,{checked:l,onCheckedChange:p,disabled:a||i.isPending})]}),e.jsx(Qo,{}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:`p-2 rounded-full ${c?"bg-primary/10":"bg-muted"}`,children:e.jsx(Wb,{className:`h-4 w-4 ${c?"text-primary":"text-muted-foreground"}`})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Append Email Signature"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:c?"Your signature from Profile settings will be added":"Drip emails will send without a signature"})]})]}),e.jsx(Or,{checked:c,onCheckedChange:x,disabled:a||i.isPending})]}),c&&e.jsxs(H,{variant:"ghost",size:"sm",className:"w-full text-xs text-muted-foreground",onClick:()=>{m(!1),s("/profile")},children:[e.jsx(Wb,{className:"h-3 w-3 mr-1"}),"Edit your email signature in Profile settings"]})]})]})]})}function nUs(){const s=ba();return yt({queryKey:["drip-templates",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await V.from("drip_templates").select("*").or(`owner_user_id.eq.${s},is_starter.eq.true`).order("sort_order",{ascending:!0});if(r)throw r;return t},enabled:!!s})}function aUs(){const s=ba();return yt({queryKey:["drip-pipeline-stages",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await V.from("deal_pipeline_stages").select("*").eq("owner_user_id",s).order("sort_order",{ascending:!0});if(r)throw r;return t},enabled:!!s})}function iUs(){const s=ba(),t=ns();return Pt({mutationFn:async r=>{if(!s)throw new Error("Not authenticated");const{data:n,error:a}=await V.from("drip_templates").insert({owner_user_id:s,stage_id:r.stage_id,title:r.title||"",subject:r.subject||"",body:r.body||"",video_url:r.video_url||null,channel:r.channel||"email",delay_type:r.delay_type||"instant",delay_minutes:r.delay_minutes||0,is_enabled:!1,deal_type:r.deal_type||null,sort_order:r.sort_order||0}).select().single();if(a)throw a;return n},onSuccess:()=>{t.invalidateQueries({queryKey:["drip-templates"]})}})}function oUs(){const s=ns();return Pt({mutationFn:async({id:t,...r})=>{const{data:n,error:a}=await V.from("drip_templates").update(r).eq("id",t).select().single();if(a)throw a;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["drip-templates"]})}})}function lUs(){const s=ns();return Pt({mutationFn:async t=>{const{error:r}=await V.from("drip_templates").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["drip-templates"]})}})}function cUs(){const s=ba(),t=ns();return Pt({mutationFn:async({templateId:r,stageId:n})=>{if(!s)throw new Error("Not authenticated");const{data:a,error:i}=await V.from("drip_templates").select("*").eq("id",r).single();if(i)throw i;const{data:l,error:o}=await V.from("drip_templates").insert({owner_user_id:s,stage_id:n,title:a.title,subject:a.subject,body:a.body,video_url:a.video_url,channel:a.channel,delay_type:a.delay_type,delay_minutes:a.delay_minutes,is_enabled:!1,is_starter:!1,deal_type:a.deal_type}).select().single();if(o)throw o;return l},onSuccess:()=>{t.invalidateQueries({queryKey:["drip-templates"]})}})}const dUs=[{key:"{{client_first_name}}",label:"Client First Name"},{key:"{{client_last_name}}",label:"Client Last Name"},{key:"{{property_address}}",label:"Property Address"},{key:"{{agent_name}}",label:"Your Name"},{key:"{{agent_phone}}",label:"Your Phone"},{key:"{{close_date}}",label:"Target Close Date"},{key:"{{stage_name}}",label:"Current Stage"},{key:"{{portal_link}}",label:"Portal Link"},{key:"{{review_link}}",label:"Review Link"}];function uUs({open:s,onOpenChange:t,campaignId:r,campaignName:n}){const{data:a,isLoading:i}=p8s(r||void 0),l=x8s(),o=Ggt(),c=async(m,p)=>{try{await l.mutateAsync({id:m,status:p}),he.success(`Enrollment ${p}`)}catch{he.error("Failed to update")}},d=async m=>{if(r)try{const p=await o.mutateAsync({campaignId:r,contactIds:[m]});p.enrolled>0?he.success("Contact re-enrolled — first email queued"):p.skipped>0?he.message("Already active in this campaign"):he.error("Could not re-enroll")}catch{he.error("Failed to re-enroll")}},h=m=>{const p={active:"bg-emerald-500/10 text-emerald-600 border-emerald-200",paused:"bg-amber-500/10 text-amber-600 border-amber-200",completed:"bg-blue-500/10 text-blue-600 border-blue-200",exited:"bg-muted text-muted-foreground"};return e.jsx(Xe,{variant:"outline",className:`text-[10px] capitalize ${p[m]||""}`,children:m})};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-2xl max-h-[85vh] flex flex-col p-0 overflow-hidden",children:[e.jsxs("div",{className:"p-5 border-b shrink-0",children:[e.jsxs(Ns,{className:"flex items-center gap-2",children:[e.jsx(Ar,{className:"h-4 w-4 text-primary"}),"Enrollments — ",n||"Campaign"]}),e.jsx(nn,{className:"text-xs mt-1",children:"Manage every contact currently in this campaign. Pause to take over, or exit to remove."})]}),e.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:e.jsx("div",{className:"p-5",children:i?e.jsx("div",{className:"space-y-2",children:[1,2,3].map(m=>e.jsx(Ks,{className:"h-14"},m))}):!a||a.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Ar,{className:"h-10 w-10 text-muted-foreground/40 mx-auto mb-3"}),e.jsx("p",{className:"text-sm font-medium mb-1",children:"No contacts enrolled yet"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Head to your contacts page and bulk-enroll to start nurturing."})]}):e.jsx("div",{className:"space-y-2",children:a.map(m=>{var p,x,y,_;return e.jsxs("div",{className:"flex items-center gap-3 p-3 border rounded-lg bg-card",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("p",{className:"font-medium text-sm truncate",children:[(p=m.contact)==null?void 0:p.first_name," ",(x=m.contact)==null?void 0:x.last_name]}),h(m.status)]}),e.jsxs("div",{className:"flex items-center gap-3 text-[11px] text-muted-foreground mt-0.5",children:[((y=m.contact)==null?void 0:y.email)&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(er,{className:"h-2.5 w-2.5"})," ",m.contact.email]}),e.jsxs("span",{children:["Step ",m.current_step]}),m.next_send_at&&m.status==="active"&&e.jsxs("span",{children:["Next: ",As(new Date(m.next_send_at),"MMM d, h:mma")]}),m.exit_reason&&e.jsxs("span",{children:["Exit: ",m.exit_reason]})]})]}),m.status==="active"&&e.jsx(H,{size:"sm",variant:"ghost",onClick:()=>c(m.id,"paused"),title:"Pause",children:e.jsx(Hf,{className:"h-3.5 w-3.5"})}),m.status==="paused"&&e.jsx(H,{size:"sm",variant:"ghost",onClick:()=>c(m.id,"active"),title:"Resume",children:e.jsx(El,{className:"h-3.5 w-3.5"})}),(m.status==="active"||m.status==="paused")&&e.jsx(H,{size:"sm",variant:"ghost",onClick:()=>c(m.id,"exited"),title:"Exit",children:e.jsx(Rr,{className:"h-3.5 w-3.5 text-destructive"})}),(m.status==="exited"||m.status==="completed")&&((_=m.contact)==null?void 0:_.id)&&e.jsxs(H,{size:"sm",variant:"outline",className:"h-7 text-[11px] gap-1",onClick:()=>d(m.contact.id),disabled:o.isPending,children:[e.jsx(qy,{className:"h-3 w-3"}),"Re-enroll"]})]},m.id)})})})})]})})}function hUs(){var T;const{data:s,isLoading:t}=cMe(),{hasLeadSite:r}=av(),n=u8s(),a=d8s(),i=Vgt(),[l,o]=S.useState(null),[c,d]=S.useState(!1),[h,m]=S.useState(null),[p,x]=S.useState(null),y=(s||[]).filter(E=>!E.is_starter),_=(s||[]).filter(E=>E.is_starter).filter(E=>!E.requires_lead_site||r),b=async E=>{try{await n.mutateAsync(E),he.success("Campaign added to your library — customize and activate it!"),o(null)}catch(A){he.error(A.message||"Failed to copy campaign")}},j=async E=>{try{await i.mutateAsync({id:E.id,is_active:!E.is_active}),he.success(E.is_active?"Campaign paused":"Campaign activated")}catch{he.error("Failed to update")}},k=async E=>{if(confirm("Delete this campaign? Active enrollments will be removed."))try{await a.mutateAsync(E),he.success("Campaign deleted")}catch{he.error("Failed to delete")}};return t?e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:[1,2,3,4,5,6].map(E=>e.jsx(Ks,{className:"h-44 rounded-xl"},E))}):e.jsxs("div",{className:"space-y-8",children:[e.jsx("div",{className:"rounded-xl border bg-gradient-to-br from-primary/5 via-background to-background p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"h-8 w-8 rounded-lg bg-primary/10 flex items-center justify-center shrink-0",children:e.jsx(bE,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-semibold text-sm mb-1",children:"How Smart Drips work"}),e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3 mt-2",children:[e.jsxs("div",{className:"flex gap-2 text-xs",children:[e.jsx(Wu,{className:"h-3.5 w-3.5 text-amber-500 shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-foreground",children:"Stage Drips (automatic)"}),e.jsx("p",{className:"text-muted-foreground",children:"Trigger when a contact moves to a deal stage (Listing, Under Contract, etc)."})]})]}),e.jsxs("div",{className:"flex gap-2 text-xs",children:[e.jsx(yn,{className:"h-3.5 w-3.5 text-primary shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-foreground",children:"Campaigns (manual / bulk)"}),e.jsx("p",{className:"text-muted-foreground",children:"You enroll contacts yourself — from this page or the Contacts list."})]})]})]}),e.jsxs("p",{className:"text-[11px] text-muted-foreground mt-2.5 italic",children:["Tip: A campaign must be ",e.jsx("strong",{children:"Active"})," before its emails will send to enrolled contacts."]})]})]})}),e.jsxs("section",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-lg font-semibold flex items-center gap-2",children:[e.jsx(Ar,{className:"h-4 w-4 text-primary"}),"My Campaigns"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Custom drip campaigns you've created or copied"})]}),e.jsxs(H,{size:"sm",onClick:()=>{m(null),d(!0)},children:[e.jsx(Ys,{className:"h-3.5 w-3.5 mr-1.5"})," New Campaign"]})]}),y.length===0?e.jsxs("div",{className:"text-center py-10 border border-dashed rounded-xl bg-muted/20",children:[e.jsx(Lr,{className:"h-10 w-10 text-muted-foreground/40 mx-auto mb-3"}),e.jsx("h3",{className:"font-semibold mb-1",children:"No custom campaigns yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Build one from scratch or clone a starter from the library below."}),e.jsxs(H,{size:"sm",onClick:()=>{m(null),d(!0)},children:[e.jsx(Ys,{className:"h-3.5 w-3.5 mr-1.5"})," Create your first campaign"]})]}):e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:y.map(E=>e.jsx(mUs,{campaign:E,onPreview:()=>o(E.id),onToggleActive:()=>j(E),onDelete:()=>k(E.id),onEdit:()=>{m(E.id),d(!0)},onViewEnrollments:()=>x(E.id)},E.id))})]}),e.jsxs("section",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-lg font-semibold flex items-center gap-2",children:[e.jsx(Lr,{className:"h-4 w-4 text-amber-500"}),"Starter Library"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Premium, ready-to-go campaigns crafted for real estate. One-click copy."})]}),e.jsxs(Xe,{variant:"outline",className:"text-[10px]",children:[_.length," templates"]})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:_.map(E=>e.jsx(fUs,{campaign:E,onPreview:()=>o(E.id)},E.id))})]}),e.jsx(pUs,{campaignId:l,open:!!l,onOpenChange:E=>!E&&o(null),onClone:b,isCloning:n.isPending,onEdit:E=>{o(null),m(E),d(!0)}}),e.jsx(Ygt,{open:c,onOpenChange:d,campaignId:h}),e.jsx(uUs,{open:!!p,onOpenChange:E=>!E&&x(null),campaignId:p,campaignName:(T=y.find(E=>E.id===p))==null?void 0:T.name})]})}function mUs({campaign:s,onPreview:t,onToggleActive:r,onDelete:n,onEdit:a,onViewEnrollments:i}){const o=g8s(s.id).data??0,c=!s.is_active&&o>0;return e.jsxs("div",{className:"group rounded-xl border bg-card overflow-hidden hover:shadow-lg transition-shadow",children:[e.jsxs("div",{className:`h-20 bg-gradient-to-br ${s.cover_color} relative flex items-center justify-center`,children:[e.jsx("span",{className:"text-4xl drop-shadow-sm",children:s.icon}),s.is_active&&e.jsx(Xe,{className:"absolute top-2 right-2 bg-emerald-500 hover:bg-emerald-500 text-white text-[10px]",children:"Active"})]}),e.jsxs("div",{className:"p-3.5",children:[e.jsx("h3",{className:"font-semibold text-sm truncate",children:s.name}),e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 mt-1 min-h-[2rem]",children:s.description||"No description"}),e.jsx(Xe,{variant:"outline",className:"text-[9px] mt-2",children:R0e[s.category]}),c&&e.jsxs("button",{onClick:r,className:"mt-2 w-full flex items-start gap-1.5 p-2 rounded-md bg-amber-500/10 border border-amber-500/30 text-left hover:bg-amber-500/15 transition-colors",children:[e.jsx(uu,{className:"h-3 w-3 text-amber-600 dark:text-amber-400 shrink-0 mt-0.5"}),e.jsxs("span",{className:"text-[10px] leading-tight text-amber-700 dark:text-amber-300",children:[e.jsxs("strong",{children:[o," contact",o===1?"":"s"," enrolled"]})," but not sending — tap to activate"]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-1.5 mt-3",children:[e.jsxs(H,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:a,children:[e.jsx(ni,{className:"h-3 w-3 mr-1"})," Edit"]}),e.jsx(H,{size:"sm",variant:s.is_active?"secondary":"default",className:"h-7 text-xs",onClick:r,children:s.is_active?"Pause":"Activate"})]}),e.jsxs("div",{className:"flex items-center justify-between mt-2 text-[10px]",children:[e.jsx("button",{onClick:i,className:"text-primary hover:underline",children:"View enrollments"}),e.jsx("button",{onClick:t,className:"text-muted-foreground hover:underline",children:"Preview"}),e.jsx("button",{onClick:n,className:"text-muted-foreground hover:text-destructive",children:"Delete"})]})]})]})}function fUs({campaign:s,onPreview:t}){return e.jsxs("button",{onClick:t,className:"group rounded-xl border bg-card overflow-hidden hover:shadow-xl hover:scale-[1.02] transition-all text-left",children:[e.jsxs("div",{className:`h-24 bg-gradient-to-br ${s.cover_color} relative flex items-center justify-center`,children:[e.jsx("span",{className:"text-5xl drop-shadow-sm",children:s.icon}),e.jsxs(Xe,{className:"absolute top-2 right-2 bg-white/90 text-foreground hover:bg-white text-[10px]",children:[e.jsx(Lr,{className:"h-2.5 w-2.5 mr-0.5"})," Starter"]})]}),e.jsxs("div",{className:"p-3.5",children:[e.jsx("h3",{className:"font-semibold text-sm",children:s.name}),e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 mt-1 min-h-[2rem]",children:s.description}),e.jsx(Xe,{variant:"outline",className:"text-[9px] mt-2",children:R0e[s.category]})]})]})}function pUs({campaignId:s,open:t,onOpenChange:r,onClone:n,isCloning:a,onEdit:i}){const{data:l}=cMe(),{data:o}=Hgt(s||void 0),[c,d]=S.useState(new Set),h=l==null?void 0:l.find(x=>x.id===s);if(!h)return null;const m=x=>{d(y=>{const _=new Set(y);return _.has(x)?_.delete(x):_.add(x),_})},p=(x,y)=>{if(x.delay_type==="calendar_anchor"){const b=x.anchor_field==="birthday"?"birthday":"home anniversary",j=x.anchor_offset_days||0;return j===0?`On their ${b}`:j<0?`${Math.abs(j)} days before ${b}`:`${j} days after ${b}`}if(y===0&&x.delay_days===0&&x.delay_hours===0)return"Sends immediately";const _=[];return x.delay_days&&_.push(`${x.delay_days}d`),x.delay_hours&&_.push(`${x.delay_hours}h`),y===0?`After ${_.join(" ")}`:`+${_.join(" ")}`};return e.jsx(bs,{open:t,onOpenChange:r,children:e.jsxs(vs,{className:"max-w-2xl max-h-[85vh] flex flex-col p-0 overflow-hidden",children:[e.jsx("div",{className:`bg-gradient-to-br ${h.cover_color} p-6 text-white shrink-0`,children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("span",{className:"text-5xl drop-shadow-sm",children:h.icon}),e.jsxs("div",{className:"flex-1",children:[e.jsx(Ns,{className:"text-xl font-bold text-white",children:h.name}),e.jsx(nn,{className:"text-white/90 mt-1",children:h.description}),e.jsxs("div",{className:"flex gap-2 mt-3",children:[e.jsx(Xe,{className:"bg-white/20 text-white border-white/20 hover:bg-white/20",children:R0e[h.category]}),e.jsxs(Xe,{className:"bg-white/20 text-white border-white/20 hover:bg-white/20",children:[(o==null?void 0:o.length)||0," step",(o==null?void 0:o.length)!==1?"s":""]})]})]})]})}),e.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:e.jsxs("div",{className:"p-6 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"The sequence"}),h.is_starter?e.jsx("span",{className:"text-[10px] text-muted-foreground italic",children:"Copy to your library to edit"}):e.jsx("span",{className:"text-[10px] text-muted-foreground italic",children:"Tap a step to expand · Edit to customize"})]}),o==null?void 0:o.map((x,y)=>{const _=c.has(x.id);return e.jsxs("div",{className:"flex gap-3",children:[e.jsxs("div",{className:"shrink-0 flex flex-col items-center",children:[e.jsx("div",{className:"h-8 w-8 rounded-full bg-primary/10 text-primary flex items-center justify-center text-xs font-semibold",children:y+1}),ym(x.id),className:"flex-1 pb-4 text-left",children:e.jsxs("div",{className:"border rounded-lg p-3 bg-muted/20 hover:bg-muted/30 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1.5 text-xs text-muted-foreground",children:[x.delay_type==="calendar_anchor"?e.jsx(Nn,{className:"h-3 w-3"}):e.jsx(Pn,{className:"h-3 w-3"}),e.jsx("span",{children:p(x,y)}),e.jsx("span",{children:"·"}),e.jsx(er,{className:"h-3 w-3"}),e.jsx("span",{className:"capitalize",children:x.channel})]}),e.jsx("p",{className:"font-medium text-sm",children:x.subject}),_?e.jsx("p",{className:"text-xs text-muted-foreground mt-2 whitespace-pre-line",children:x.body}):e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 mt-1 whitespace-pre-line",children:x.body}),x.body&&x.body.length>160&&e.jsx("span",{className:"text-[10px] text-primary mt-1.5 inline-block",children:_?"Show less":"Show full email"})]})})]},x.id)})]})}),e.jsxs(wn,{className:"border-t p-4 shrink-0",children:[e.jsx(H,{variant:"outline",onClick:()=>r(!1),children:"Close"}),!h.is_starter&&i&&e.jsxs(H,{variant:"secondary",onClick:()=>i(h.id),children:[e.jsx(ni,{className:"h-3.5 w-3.5 mr-1.5"})," Edit Campaign"]}),h.is_starter&&e.jsxs(H,{onClick:()=>n(h.id),disabled:a,children:[a?e.jsx(is,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(ui,{className:"h-3.5 w-3.5 mr-1.5"}),"Copy to my campaigns"]})]})]})})}function gUs(){const s=ba(),t=Fr(),{isGmailConnected:r,gmailEmail:n,isLoading:a}=cf(),{data:i,isLoading:l}=nUs(),{data:o,isLoading:c}=aUs(),d=iUs(),h=oUs(),m=lUs(),p=cUs(),[x,y]=S.useState(null),[_,b]=S.useState(null),j=(i==null?void 0:i.filter(O=>!O.is_starter&&O.owner_user_id===s))||[],k=(i==null?void 0:i.filter(O=>O.is_starter))||[],T=O=>j.filter($=>$.stage_id===O),E=async O=>{try{await h.mutateAsync({id:O.id,is_enabled:!O.is_enabled}),he.success(O.is_enabled?"Drip disabled":"Drip enabled")}catch{he.error("Failed to update")}},A=async O=>{try{const $=o==null?void 0:o.find(ee=>ee.id===O);await d.mutateAsync({stage_id:O,title:`${($==null?void 0:$.name)||"Stage"} follow-up`,subject:"",body:"",channel:"email",delay_type:"instant",delay_minutes:0}),y(O),he.success("Drip template created")}catch{he.error("Failed to create template")}},D=async O=>{try{await m.mutateAsync(O),he.success("Template deleted")}catch{he.error("Failed to delete")}},R=async O=>{if(!o||o.length===0){he.error("No pipeline stages found");return}const $=o[0].id;try{await p.mutateAsync({templateId:O,stageId:$}),he.success("Template copied to your drips!")}catch{he.error("Failed to copy template")}},z=l||c;return e.jsx(Ss,{children:e.jsxs("div",{className:"container max-w-4xl mx-auto py-6 px-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ym,{className:"h-5 w-5 text-primary"}),e.jsx("h1",{className:"text-2xl font-bold",children:"Smart Drips"}),e.jsx(Xe,{variant:"outline",className:"text-[9px] font-bold uppercase tracking-wide px-1 py-0.5 border-amber-500 text-amber-600 bg-amber-500/10",children:"Beta"})]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Automatically send personalized emails when deals move through your pipeline."})]}),e.jsx(rUs,{})]}),e.jsxs("div",{className:"bg-primary/5 border border-primary/15 rounded-xl p-4 mb-4 flex items-start gap-3",children:[e.jsx(bE,{className:"h-4 w-4 text-primary mt-0.5 shrink-0"}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[e.jsx("p",{className:"font-medium text-foreground mb-1",children:"How it works"}),e.jsxs("p",{children:["When a deal moves to a new stage in your pipeline, Smart Drips automatically sends your pre-written email to the client. Nothing sends until you create a template ",e.jsx("strong",{children:"and"})," toggle it on."]})]})]}),!a&&(r?e.jsxs("div",{className:"bg-emerald-500/5 border border-emerald-500/20 rounded-xl p-4 mb-6 flex items-start gap-3",children:[e.jsx(er,{className:"h-4 w-4 text-emerald-600 mt-0.5 shrink-0"}),e.jsxs("div",{className:"text-sm flex-1",children:[e.jsxs("p",{className:"font-medium text-foreground mb-0.5",children:["Sending from your Gmail",n?` (${n})`:""]}),e.jsx("p",{className:"text-muted-foreground",children:"Drips will send directly from your connected Gmail for the most personal feel and best deliverability."})]})]}):e.jsxs("div",{className:"bg-amber-500/5 border border-amber-500/20 rounded-xl p-4 mb-6 flex items-start gap-3",children:[e.jsx(bE,{className:"h-4 w-4 text-amber-600 mt-0.5 shrink-0"}),e.jsxs("div",{className:"text-sm flex-1",children:[e.jsx("p",{className:"font-medium text-foreground mb-0.5",children:"Drips will send from our shared sender"}),e.jsxs("p",{className:"text-muted-foreground mb-2",children:["You haven't connected Gmail, so drips will send from ",e.jsx("strong",{children:"send.relevelup.com"})," with your name on the From line and your email as Reply-To. Connect Gmail to send directly from your own inbox for better deliverability and a more personal touch."]}),e.jsxs(H,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>t("/mission-control/integrations"),children:[e.jsx(er,{className:"h-3 w-3 mr-1.5"}),"Connect Gmail"]})]})]})),e.jsxs(ta,{defaultValue:"my-drips",children:[e.jsxs(Qn,{className:"grid grid-cols-3 w-full max-w-lg mb-6",children:[e.jsx(ts,{value:"my-drips",children:"Stage Drips"}),e.jsxs(ts,{value:"campaigns",children:["Campaigns",e.jsx(Xe,{variant:"outline",className:"ml-1.5 text-[9px] bg-amber-500/10 text-amber-600 border-amber-200 px-1 py-0",children:"New"})]}),e.jsxs(ts,{value:"starters",children:["Stage Starters",k.length>0&&e.jsx(Xe,{variant:"secondary",className:"ml-1.5 text-[10px] px-1.5 py-0",children:k.length})]})]}),e.jsx(cs,{value:"campaigns",children:e.jsx(hUs,{})}),e.jsx(cs,{value:"my-drips",children:z?e.jsx("div",{className:"space-y-3",children:[1,2,3,4].map(O=>e.jsx(Ks,{className:"h-16 w-full rounded-xl"},O))}):!o||o.length===0?e.jsxs("div",{className:"text-center py-12 border border-dashed rounded-xl",children:[e.jsx(ym,{className:"h-10 w-10 text-muted-foreground/40 mx-auto mb-3"}),e.jsx("h3",{className:"font-semibold text-lg mb-1",children:"No Pipeline Stages"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Create pipeline stages first to set up drip automations."})]}):e.jsxs("div",{className:"space-y-2",children:[o.filter(O=>!O.is_won_stage&&!O.is_lost_stage).map(O=>{const $=T(O.id),ee=x===O.id,Z=$.some(J=>J.is_enabled);return e.jsxs("div",{className:"border rounded-xl overflow-hidden",children:[e.jsxs("button",{onClick:()=>y(ee?null:O.id),className:"w-full flex items-center gap-3 p-4 hover:bg-muted/30 transition-colors text-left",children:[e.jsx("div",{className:"w-3 h-3 rounded-full shrink-0",style:{backgroundColor:O.color||"#94A3B8"}}),e.jsx("span",{className:"font-medium text-sm flex-1",children:O.name}),$.length>0&&e.jsxs(Xe,{variant:"outline",className:`text-[10px] ${Z?"bg-emerald-500/10 text-emerald-600 border-emerald-200":"text-muted-foreground"}`,children:[$.length," drip",$.length!==1?"s":"",Z&&" · Active"]}),ee?e.jsx(Io,{className:"h-4 w-4 text-muted-foreground"}):e.jsx($a,{className:"h-4 w-4 text-muted-foreground"})]}),ee&&e.jsx("div",{className:"border-t bg-muted/10 p-4 space-y-3",children:$.length===0?e.jsxs("div",{className:"text-center py-6",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-3",children:"No drip set for this stage"}),e.jsxs(H,{variant:"outline",size:"sm",onClick:()=>A(O.id),disabled:d.isPending,children:[e.jsx(Ys,{className:"h-3.5 w-3.5 mr-1.5"}),"Create Drip"]})]}):e.jsxs(e.Fragment,{children:[$.map(J=>e.jsx(WWe,{template:J,isEditing:_===J.id,onToggleEdit:()=>b(_===J.id?null:J.id),onToggleEnabled:()=>E(J),onUpdate:K=>h.mutateAsync({id:J.id,...K}),onDelete:()=>D(J.id),userId:s||""},J.id)),e.jsxs(H,{variant:"ghost",size:"sm",className:"w-full text-xs text-muted-foreground",onClick:()=>A(O.id),children:[e.jsx(Ys,{className:"h-3 w-3 mr-1"})," Add another drip"]})]})})]},O.id)}),o.filter(O=>O.is_won_stage||O.is_lost_stage).length>0&&e.jsxs("div",{className:"pt-2",children:[e.jsx("p",{className:"text-xs text-muted-foreground font-medium mb-2 px-1",children:"Closing Stages"}),o.filter(O=>O.is_won_stage||O.is_lost_stage).map(O=>{const $=T(O.id),ee=x===O.id,Z=$.some(J=>J.is_enabled);return e.jsxs("div",{className:"border rounded-xl overflow-hidden mb-2",children:[e.jsxs("button",{onClick:()=>y(ee?null:O.id),className:"w-full flex items-center gap-3 p-4 hover:bg-muted/30 transition-colors text-left",children:[e.jsx("div",{className:"w-3 h-3 rounded-full shrink-0",style:{backgroundColor:O.color||"#94A3B8"}}),e.jsx("span",{className:"font-medium text-sm flex-1",children:O.name}),$.length>0&&e.jsxs(Xe,{variant:"outline",className:`text-[10px] ${Z?"bg-emerald-500/10 text-emerald-600 border-emerald-200":"text-muted-foreground"}`,children:[$.length," drip",$.length!==1?"s":"",Z&&" · Active"]}),ee?e.jsx(Io,{className:"h-4 w-4 text-muted-foreground"}):e.jsx($a,{className:"h-4 w-4 text-muted-foreground"})]}),ee&&e.jsx("div",{className:"border-t bg-muted/10 p-4 space-y-3",children:$.length===0?e.jsxs("div",{className:"text-center py-6",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-3",children:"No drip set for this stage"}),e.jsxs(H,{variant:"outline",size:"sm",onClick:()=>A(O.id),disabled:d.isPending,children:[e.jsx(Ys,{className:"h-3.5 w-3.5 mr-1.5"})," Create Drip"]})]}):e.jsxs(e.Fragment,{children:[$.map(J=>e.jsx(WWe,{template:J,isEditing:_===J.id,onToggleEdit:()=>b(_===J.id?null:J.id),onToggleEnabled:()=>E(J),onUpdate:K=>h.mutateAsync({id:J.id,...K}),onDelete:()=>D(J.id),userId:s||""},J.id)),e.jsxs(H,{variant:"ghost",size:"sm",className:"w-full text-xs text-muted-foreground",onClick:()=>A(O.id),children:[e.jsx(Ys,{className:"h-3 w-3 mr-1"})," Add another drip"]})]})})]},O.id)})]})]})}),e.jsx(cs,{value:"starters",children:k.length===0?e.jsxs("div",{className:"text-center py-12 border border-dashed rounded-xl",children:[e.jsx(Lr,{className:"h-10 w-10 text-muted-foreground/40 mx-auto mb-3"}),e.jsx("h3",{className:"font-semibold text-lg mb-1",children:"No Starter Templates Yet"}),e.jsx("p",{className:"text-sm text-muted-foreground max-w-md mx-auto",children:"Admin-created starter templates will appear here. You'll be able to copy them into your own drips."})]}):e.jsx("div",{className:"space-y-3",children:k.map(O=>e.jsx(xUs,{template:O,onCopy:()=>R(O.id),isCopying:p.isPending},O.id))})})]})]})})}function WWe({template:s,isEditing:t,onToggleEdit:r,onToggleEnabled:n,onUpdate:a,onDelete:i,userId:l}){const[o,c]=S.useState(s.title),[d,h]=S.useState(s.subject),[m,p]=S.useState(s.body),[x,y]=S.useState(s.video_url||""),[_,b]=S.useState(s.channel),[j,k]=S.useState(s.delay_type),[T,E]=S.useState(s.delay_minutes),[A,D]=S.useState(!1),R=async()=>{D(!0);try{await a({title:o,subject:d,body:m,video_url:x||null,channel:_,delay_type:j,delay_minutes:T}),he.success("Drip saved"),r()}catch{he.error("Failed to save")}finally{D(!1)}},z=O=>{p($=>$+O)};return e.jsxs("div",{className:"border rounded-lg bg-background overflow-hidden",children:[e.jsxs("div",{className:"flex items-center gap-3 p-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",role:"button",onClick:r,children:[e.jsx("p",{className:"text-sm font-medium truncate",children:s.title||"Untitled drip"}),e.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[s.channel==="sms"?e.jsx(Gi,{className:"h-3 w-3 text-muted-foreground"}):e.jsx(er,{className:"h-3 w-3 text-muted-foreground"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:s.delay_type==="instant"?"Sends instantly":`Sends after ${s.delay_minutes>=60?`${Math.round(s.delay_minutes/60)}h`:`${s.delay_minutes}m`}`}),s.video_url&&e.jsx(xn,{className:"h-3 w-3 text-primary"})]})]}),e.jsx(Or,{checked:s.is_enabled,onCheckedChange:n})]}),t&&e.jsxs("div",{className:"border-t p-4 space-y-4",children:[e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs font-medium",children:"Title (internal)"}),e.jsx(Se,{value:o,onChange:O=>c(O.target.value),className:"mt-1 h-8 text-sm",placeholder:"e.g. Buyer intro video"})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx(ue,{className:"text-xs font-medium",children:"Channel"}),e.jsx("div",{className:"flex gap-1 mt-1",children:["email","sms"].map(O=>e.jsxs("button",{onClick:()=>b(O),className:`flex-1 flex items-center justify-center gap-1.5 px-3 py-1.5 rounded-md text-xs font-medium border transition-colors ${_===O?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:border-primary/50"}`,children:[O==="sms"?e.jsx(Gi,{className:"h-3 w-3"}):e.jsx(er,{className:"h-3 w-3"}),O==="sms"?"SMS":"Email"]},O))})]}),e.jsxs("div",{className:"flex-1",children:[e.jsx(ue,{className:"text-xs font-medium",children:"Timing"}),e.jsxs("div",{className:"flex gap-1 mt-1",children:[e.jsx("button",{onClick:()=>k("instant"),className:`flex-1 px-3 py-1.5 rounded-md text-xs font-medium border transition-colors ${j==="instant"?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:border-primary/50"}`,children:"Instant"}),e.jsxs("button",{onClick:()=>k("scheduled"),className:`flex-1 px-3 py-1.5 rounded-md text-xs font-medium border transition-colors ${j==="scheduled"?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:border-primary/50"}`,children:[e.jsx(Pn,{className:"h-3 w-3 mr-1 inline"}),"Delay"]})]})]})]}),j==="scheduled"&&e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs font-medium",children:"Delay"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(Se,{type:"number",min:1,value:T>=60?Math.round(T/60):T,onChange:O=>{const $=parseInt(O.target.value)||0;E(T>=60?$*60:$)},className:"h-8 w-20 text-sm"}),e.jsx("div",{className:"flex gap-1",children:[{label:"Minutes",mins:T<60?T:30},{label:"Hours",mins:T>=60?T:60},{label:"Days",mins:T>=1440?T:1440}].map(O=>e.jsx("button",{className:`px-2 py-1 rounded text-xs border transition-colors ${O.label==="Minutes"&&T<60||O.label==="Hours"&&T>=60&&T<1440||O.label==="Days"&&T>=1440?"bg-primary/10 text-primary border-primary/30":"text-muted-foreground border-input"}`,onClick:()=>{O.label==="Minutes"?E(30):O.label==="Hours"?E(60):E(1440)},children:O.label},O.label))})]})]}),_==="email"&&e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs font-medium",children:"Subject Line"}),e.jsx(Se,{value:d,onChange:O=>h(O.target.value),className:"mt-1 h-8 text-sm",placeholder:"e.g. Next steps for your home purchase"})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx(ue,{className:"text-xs font-medium",children:_==="sms"?"Message":"Email Body"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"text-[10px] text-muted-foreground",children:"Insert:"}),e.jsxs("select",{className:"text-[10px] border rounded px-1 py-0.5 bg-background text-muted-foreground",value:"",onChange:O=>{O.target.value&&z(O.target.value),O.target.value=""},children:[e.jsx("option",{value:"",children:"Merge variable..."}),dUs.map(O=>e.jsx("option",{value:O.key,children:O.label},O.key))]})]})]}),e.jsx("textarea",{value:m,onChange:O=>p(O.target.value),placeholder:_==="sms"?"Hey {{client_first_name}}, great talking with you today! Here's a quick video about what's next...":`Hi {{client_first_name}}, It was great meeting with you! Here's a video about what to expect next...`,className:"w-full rounded-md border border-input bg-background px-3 py-2 text-sm min-h-[100px] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"})]}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs font-medium",children:"Attached Video"}),x?e.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[e.jsxs("div",{className:"flex-1 text-xs text-muted-foreground truncate bg-muted/50 rounded px-2 py-1.5 border border-input",children:[e.jsx(xn,{className:"h-3 w-3 inline mr-1 text-primary"}),x.length>50?x.slice(0,50)+"...":x]}),e.jsx(H,{variant:"ghost",size:"sm",className:"h-7 text-xs text-destructive",onClick:()=>y(""),children:"Remove"})]}):e.jsxs("div",{className:"mt-1 flex items-center gap-1.5",children:[e.jsx(d6e,{onVideoReady:O=>y(O)}),e.jsx(H8,{userId:l,onSelect:O=>y(O),triggerSize:"sm",triggerClassName:"gap-1.5 flex-1"}),e.jsxs(H,{variant:"ghost",size:"sm",className:"gap-1 text-xs text-muted-foreground flex-1",onClick:()=>{const O=prompt("Paste a YouTube or Loom URL:");O&&y(O)},children:[e.jsx(Jo,{className:"h-3 w-3"})," Paste URL"]})]})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t",children:[e.jsxs(H,{variant:"ghost",size:"sm",className:"text-xs text-destructive hover:text-destructive",onClick:i,children:[e.jsx(Dr,{className:"h-3 w-3 mr-1"})," Delete"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(H,{variant:"outline",size:"sm",className:"text-xs",onClick:r,children:"Cancel"}),e.jsx(H,{size:"sm",className:"text-xs",onClick:R,disabled:A,children:A?"Saving...":"Save Drip"})]})]})]})]})}function xUs({template:s,onCopy:t,isCopying:r}){const[n,a]=S.useState(!1),i=s.body.replace(/<[^>]+>/g,""),l=s.deal_type==="buyer"?"Buyer":s.deal_type==="seller"?"Seller":null,o=s.delay_type==="instant"?"Sends instantly":s.delay_minutes>=1440?`Sends after ${Math.round(s.delay_minutes/1440)} day${Math.round(s.delay_minutes/1440)!==1?"s":""}`:s.delay_minutes>=60?`Sends after ${Math.round(s.delay_minutes/60)} hour${Math.round(s.delay_minutes/60)!==1?"s":""}`:`Sends after ${s.delay_minutes} min`;return e.jsxs("div",{className:"border rounded-xl overflow-hidden transition-all hover:shadow-sm",children:[e.jsxs("button",{onClick:()=>a(!n),className:"w-full flex items-start gap-3 p-4 text-left hover:bg-muted/30 transition-colors",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h4",{className:"font-medium text-sm",children:s.title}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 truncate",children:s.subject}),!n&&e.jsx("p",{className:"text-xs text-muted-foreground/70 line-clamp-1 mt-1",children:i})]}),e.jsxs("div",{className:"flex items-center gap-1.5 shrink-0 pt-0.5",children:[l&&e.jsx(Xe,{variant:"secondary",className:"text-[10px] px-1.5 py-0",children:l}),e.jsxs(Xe,{variant:"outline",className:"text-[10px] gap-1",children:[s.channel==="sms"?e.jsx(Gi,{className:"h-3 w-3"}):e.jsx(er,{className:"h-3 w-3"}),s.channel==="sms"?"SMS":"Email"]}),e.jsxs(Xe,{variant:"outline",className:"text-[10px] gap-1",children:[e.jsx(Pn,{className:"h-3 w-3"}),s.delay_type==="instant"?"Instant":o.replace("Sends ","")]}),n?e.jsx(Io,{className:"h-4 w-4 text-muted-foreground ml-1"}):e.jsx($a,{className:"h-4 w-4 text-muted-foreground ml-1"})]})]}),n&&e.jsxs("div",{className:"border-t bg-muted/10 p-4 space-y-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase font-semibold text-muted-foreground tracking-wider mb-1",children:"Subject Line"}),e.jsx("p",{className:"text-sm font-medium",children:s.subject})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase font-semibold text-muted-foreground tracking-wider mb-1",children:"Email Body"}),e.jsx("div",{className:"text-sm text-foreground/80 bg-background rounded-lg border p-4 prose prose-sm max-w-none [&_ul]:list-disc [&_ul]:pl-5 [&_ol]:list-decimal [&_ol]:pl-5 [&_li]:my-0.5 [&_p]:my-2 [&_a]:text-primary [&_a]:underline",dangerouslySetInnerHTML:{__html:s.body}})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(Pn,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:o})]}),e.jsxs(H,{onClick:c=>{c.stopPropagation(),t()},size:"sm",className:"w-full gap-1.5",disabled:r,children:[e.jsx(ui,{className:"h-3.5 w-3.5"}),"Use This Template"]})]})]})}const Pvt=()=>{const s=Vc();return S.useEffect(()=>{console.error("404 Error: User attempted to access non-existent route:",s.pathname)},[s.pathname]),e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-gray-100",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"mb-4 text-4xl font-bold",children:"404"}),e.jsx("p",{className:"mb-4 text-xl text-gray-600",children:"Oops! Page not found"}),e.jsx("a",{href:"/",className:"text-blue-500 underline hover:text-blue-700",children:"Return to Home"})]})})};function yUs(){return S.useEffect(()=>(document.body.classList.add("cardstudio-page"),()=>{document.body.classList.remove("cardstudio-page")}),[]),e.jsxs(She,{children:[e.jsx(gs,{path:"/c/:shareToken",element:e.jsx(Ivt,{})}),e.jsx(gs,{path:"*",element:e.jsx(Pvt,{})})]})}const Pwe={Home:"🏠",Search:"🔍",DollarSign:"💰",Coffee:"☕",Calendar:"📅",Users:"👥",Phone:"📞",Video:"🎥"};function Lvt({slugOverride:s}){const t=Po(),r=s||t.slug,[n,a]=S.useState("types"),[i,l]=S.useState(null),[o,c]=S.useState(null),[d,h]=S.useState(null),[m,p]=S.useState(new Date),[x,y]=S.useState({name:"",email:"",phone:"",message:""}),[_,b]=S.useState(!1),{data:j,isLoading:k}=yt({queryKey:["public-booking-settings",r],queryFn:async()=>{const{data:K,error:re}=await V.from("agent_booking_settings").select("*").eq("slug",r).eq("is_active",!0).single();if(re)throw re;return K},enabled:!!r}),{data:T}=yt({queryKey:["public-booking-profile",j==null?void 0:j.user_id],queryFn:async()=>{const{data:K,error:re}=await V.from("profiles").select("name, avatar_url, email, phone, title, bio").eq("id",j.user_id).single();if(re)throw re;return K},enabled:!!(j!=null&&j.user_id)}),{data:E=[]}=yt({queryKey:["public-booking-types",j==null?void 0:j.user_id],queryFn:async()=>{const{data:K,error:re}=await V.from("agent_booking_types").select("id, name, description, duration_minutes, color, icon, qualification_enabled").eq("user_id",j.user_id).eq("is_active",!0).order("sort_order");if(re)throw re;return K},enabled:!!(j!=null&&j.user_id)}),{data:A=[]}=yt({queryKey:["public-availability",j==null?void 0:j.user_id],queryFn:async()=>{const{data:K,error:re}=await V.from("agent_availability_slots").select("day_of_week, start_time, end_time").eq("user_id",j.user_id).eq("is_active",!0);if(re)throw re;return K},enabled:!!(j!=null&&j.user_id)}),{data:D=[]}=yt({queryKey:["public-blocked-dates",j==null?void 0:j.user_id],queryFn:async()=>{const{data:K,error:re}=await V.from("agent_blocked_dates").select("blocked_date").eq("user_id",j.user_id);if(re)throw re;return K.map(ie=>ie.blocked_date)},enabled:!!(j!=null&&j.user_id)}),{data:R=[]}=yt({queryKey:["public-existing-bookings",j==null?void 0:j.user_id,o],queryFn:async()=>{if(!o)return[];const K=As(o,"yyyy-MM-dd"),{data:re,error:ie}=await V.from("bookings").select("start_time, end_time").eq("agent_user_id",j.user_id).eq("booking_date",K).eq("status","confirmed");if(ie)throw ie;return re},enabled:!!(j!=null&&j.user_id)&&!!o}),z=S.useMemo(()=>[...new Set(A.map(K=>K.day_of_week))],[A]),O=K=>{const re=jg(new Date),ie=Lc(re,(j==null?void 0:j.max_advance_days)||30),ce=Lc(re,0);return fA(K,ce)||mA(K,ie)||D.includes(As(K,"yyyy-MM-dd"))?!1:z.includes(K.getDay())},$=S.useMemo(()=>{if(!o||!i||!j)return[];const K=A.filter(be=>be.day_of_week===o.getDay()),re=i.duration_minutes,ie=j.buffer_minutes||0,ce=[],ne=new Date,le=(j.min_notice_hours||2)*60*60*1e3;for(const be of K){const[fe,je]=be.start_time.split(":").map(Number),[ve,We]=be.end_time.split(":").map(Number);let Ve=YF(KF(o,fe),je);const Le=YF(KF(o,ve),We);for(;oI(Ve,re)<=Le;){const Me=As(Ve,"HH:mm"),ze=As(oI(Ve,re),"HH:mm");Ve.getTime()-ne.getTime()>=le&&(R.some(Ie=>{const De=Ie.start_time.slice(0,5),pe=Ie.end_time.slice(0,5);return MeDe})||ce.push(Me)),Ve=oI(Ve,re+ie)}}return ce},[o,i,A,j,R]),ee=S.useMemo(()=>{const K=m.getFullYear(),re=m.getMonth(),ie=new Date(K,re,1),ce=new Date(K,re+1,0),ne=ie.getDay(),le=[];for(let be=0;be{if(!(!i||!o||!d||!x.name||!j)){b(!0);try{const K=As(oI(YF(KF(new Date,parseInt(d.split(":")[0])),parseInt(d.split(":")[1])),i.duration_minutes),"HH:mm"),{error:re}=await V.from("bookings").insert({agent_user_id:j.user_id,booking_type_id:i.id,booking_date:As(o,"yyyy-MM-dd"),start_time:d,end_time:K,guest_name:x.name,guest_email:x.email||null,guest_phone:x.phone||null,guest_message:x.message||null});if(re)throw re;V.functions.invoke("booking-notify",{body:{agentUserId:j.user_id,guestName:x.name,guestEmail:x.email||null,guestPhone:x.phone||null,guestMessage:x.message||null,bookingTypeName:i.name,bookingDate:As(o,"yyyy-MM-dd"),startTime:d,endTime:K,durationMinutes:i.duration_minutes,meetingLink:j.meeting_link||null}}).catch(ie=>console.error("Booking notify error:",ie)),a("confirmed")}catch(K){he.error("Failed to book: "+K.message)}finally{b(!1)}}},J=K=>{const[re,ie]=K.split(":").map(Number),ce=re>=12?"PM":"AM";return`${re%12||12}:${ie.toString().padStart(2,"0")} ${ce}`};return k?e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-[#f0f4f8] via-white to-[#e8f0f8] flex items-center justify-center",children:e.jsxs("div",{className:"flex flex-col items-center gap-3",children:[e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-2 border-[#406E71] border-t-transparent"}),e.jsx("p",{className:"text-sm text-slate-500",children:"Loading booking page..."})]})}):j?e.jsxs("div",{className:"min-h-screen bg-gradient-to-br from-[#f0f4f8] via-white to-[#e8f0f8]",children:[e.jsx("div",{className:"h-1.5 bg-gradient-to-r from-[#406E71] via-[#5a9a9d] to-[#2a4c64]"}),e.jsxs("div",{className:"max-w-lg mx-auto px-4 py-6 sm:py-10",children:[e.jsxs("div",{className:"bg-white rounded-2xl shadow-lg shadow-slate-200/60 border border-slate-100 overflow-hidden mb-6",children:[e.jsx("div",{className:"relative bg-gradient-to-r from-[#406E71] to-[#2a4c64] px-6 pt-6 pb-12",children:e.jsxs("div",{className:"absolute inset-0 opacity-10",children:[e.jsx("div",{className:"absolute top-2 right-8 w-20 h-20 rounded-full border-2 border-white/30"}),e.jsx("div",{className:"absolute bottom-4 left-12 w-10 h-10 rounded-full border border-white/20"})]})}),e.jsx("div",{className:"relative -mt-10 px-6",children:e.jsxs("div",{className:"flex items-end gap-4",children:[T!=null&&T.avatar_url?e.jsx("img",{src:T.avatar_url,alt:(T==null?void 0:T.name)||"Agent",className:"w-20 h-20 sm:w-24 sm:h-24 rounded-2xl object-cover border-4 border-white shadow-md"}):e.jsx("div",{className:"w-20 h-20 sm:w-24 sm:h-24 rounded-2xl bg-gradient-to-br from-[#406E71] to-[#2a4c64] border-4 border-white shadow-md flex items-center justify-center",children:e.jsx(io,{className:"h-10 w-10 text-white"})}),e.jsxs("div",{className:"pb-1.5",children:[e.jsx("h1",{className:"text-xl sm:text-2xl font-bold text-slate-800 leading-tight",children:(T==null?void 0:T.name)||"Agent"}),(T==null?void 0:T.title)&&e.jsx("p",{className:"text-sm text-slate-500 mt-0.5",children:T.title})]})]})}),e.jsxs("div",{className:"px-6 py-4 flex flex-wrap gap-2",children:[(T==null?void 0:T.phone)&&e.jsxs("a",{href:`tel:${T.phone}`,className:"inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full bg-[#406E71]/8 hover:bg-[#406E71]/15 text-[#406E71] text-xs font-medium transition-colors",children:[e.jsx(Yn,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden sm:inline",children:T.phone}),e.jsx("span",{className:"sm:hidden",children:"Call"})]}),(T==null?void 0:T.email)&&e.jsxs("a",{href:`mailto:${T.email}`,className:"inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full bg-[#2a4c64]/8 hover:bg-[#2a4c64]/15 text-[#2a4c64] text-xs font-medium transition-colors",children:[e.jsx(er,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden sm:inline",children:T.email}),e.jsx("span",{className:"sm:hidden",children:"Email"})]})]})]}),e.jsx("div",{className:"bg-white rounded-2xl shadow-lg shadow-slate-200/60 border border-slate-100 overflow-hidden",children:e.jsxs("div",{className:"p-5 sm:p-6",children:[n==="types"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-base font-semibold text-slate-800",children:"Select a meeting type"}),e.jsx("p",{className:"text-xs text-slate-400 mt-0.5",children:"Choose the type of meeting you'd like to schedule"})]}),e.jsx("div",{className:"space-y-2.5",children:E.map(K=>e.jsx("button",{onClick:()=>{l(K),a("date")},className:"w-full text-left group",children:e.jsx("div",{className:"relative rounded-xl border border-slate-150 p-4 transition-all duration-200 hover:shadow-md hover:border-[#406E71]/30 hover:-translate-y-0.5 active:translate-y-0",style:{borderLeftWidth:"3px",borderLeftColor:K.color},children:e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-start gap-3 min-w-0",children:[e.jsx("span",{className:"text-2xl shrink-0 mt-0.5",children:Pwe[K.icon]||"📅"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-semibold text-sm text-slate-800 group-hover:text-[#406E71] transition-colors",children:K.name}),K.description&&e.jsx("p",{className:"text-xs text-slate-500 mt-0.5 line-clamp-2",children:K.description})]})]}),e.jsxs("div",{className:"shrink-0 flex items-center gap-1 px-2.5 py-1 rounded-full bg-slate-100 text-slate-600 text-xs font-medium",children:[e.jsx(Pn,{className:"h-3 w-3"}),K.duration_minutes,"m"]})]})})},K.id))})]}),n==="date"&&i&&e.jsxs("div",{className:"space-y-5",children:[e.jsxs("button",{onClick:()=>{a("types"),c(null),h(null)},className:"flex items-center gap-1.5 text-xs font-medium text-slate-500 hover:text-slate-800 transition-colors",children:[e.jsx(za,{className:"h-3.5 w-3.5"})," Back to meeting types"]}),e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-xl border",style:{borderColor:i.color+"40",backgroundColor:i.color+"08"},children:[e.jsx("span",{className:"text-xl",children:Pwe[i.icon]||"📅"}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx("p",{className:"font-semibold text-sm text-slate-800",children:i.name})}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-slate-500 font-medium",children:[e.jsx(Pn,{className:"h-3 w-3"}),i.duration_minutes," min"]})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h3",{className:"font-semibold text-sm text-slate-800",children:As(m,"MMMM yyyy")}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx("button",{className:"h-8 w-8 rounded-lg flex items-center justify-center text-slate-500 hover:bg-slate-100 hover:text-slate-800 transition-colors",onClick:()=>p(new Date(m.getFullYear(),m.getMonth()-1)),children:e.jsx(fl,{className:"h-4 w-4"})}),e.jsx("button",{className:"h-8 w-8 rounded-lg flex items-center justify-center text-slate-500 hover:bg-slate-100 hover:text-slate-800 transition-colors",onClick:()=>p(new Date(m.getFullYear(),m.getMonth()+1)),children:e.jsx($a,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"grid grid-cols-7 gap-0.5 text-center",children:[["Su","Mo","Tu","We","Th","Fr","Sa"].map(K=>e.jsx("div",{className:"text-[10px] uppercase tracking-wider text-slate-400 font-semibold py-2",children:K},K)),ee.map((K,re)=>{if(!K)return e.jsx("div",{},`pad-${re}`);const ie=O(K),ce=o&&Cc(K,o),ne=Cc(K,new Date);return e.jsx("button",{disabled:!ie,onClick:()=>{c(K),h(null)},className:`h-10 w-10 mx-auto rounded-xl text-sm font-medium transition-all duration-150 ${ce?"bg-[#406E71] text-white shadow-md shadow-[#406E71]/30 scale-105":ie?"hover:bg-[#406E71]/10 text-slate-700 hover:text-[#406E71]":"text-slate-200 cursor-not-allowed"} ${ne&&!ce?"ring-1 ring-[#406E71]/40":""}`,children:K.getDate()},K.toISOString())})]})]}),o&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xu,{className:"h-4 w-4 text-[#406E71]"}),e.jsx("h3",{className:"font-semibold text-sm text-slate-800",children:As(o,"EEEE, MMMM d")})]}),$.length===0?e.jsxs("div",{className:"text-center py-8 space-y-2",children:[e.jsx(Pn,{className:"h-8 w-8 text-slate-300 mx-auto"}),e.jsx("p",{className:"text-sm text-slate-400",children:"No available times on this day"}),e.jsx("p",{className:"text-xs text-slate-400",children:"Try selecting a different date"})]}):e.jsx("div",{className:"grid grid-cols-3 sm:grid-cols-4 gap-2 max-h-52 overflow-y-auto pr-1 custom-scrollbar",children:$.map(K=>{const re=d===K;return e.jsx("button",{onClick:()=>h(K),className:`px-3 py-2.5 rounded-xl text-sm font-medium transition-all duration-150 ${re?"bg-[#406E71] text-white shadow-md shadow-[#406E71]/30 scale-[1.02]":"bg-slate-50 text-slate-700 hover:bg-[#406E71]/10 hover:text-[#406E71] border border-slate-150"}`,children:J(K)},K)})}),d&&e.jsx(H,{className:"w-full h-12 rounded-xl bg-[#406E71] hover:bg-[#365c5e] text-white font-semibold shadow-md shadow-[#406E71]/20 transition-all hover:shadow-lg",onClick:()=>a("form"),children:"Continue to Details"})]})]}),n==="form"&&i&&o&&d&&e.jsxs("div",{className:"space-y-5",children:[e.jsxs("button",{onClick:()=>a("date"),className:"flex items-center gap-1.5 text-xs font-medium text-slate-500 hover:text-slate-800 transition-colors",children:[e.jsx(za,{className:"h-3.5 w-3.5"})," Back"]}),e.jsxs("div",{className:"rounded-xl bg-gradient-to-r from-[#406E71]/5 to-[#2a4c64]/5 border border-[#406E71]/15 p-4 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-lg",children:Pwe[i.icon]||"📅"}),e.jsx("p",{className:"font-semibold text-sm text-slate-800",children:i.name})]}),e.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1 text-xs text-slate-600",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(xu,{className:"h-3.5 w-3.5 text-[#406E71]"}),As(o,"EEE, MMM d, yyyy")]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Pn,{className:"h-3.5 w-3.5 text-[#406E71]"}),J(d)," · ",i.duration_minutes," min"]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{className:"text-xs font-semibold text-slate-700",children:"Full Name *"}),e.jsx(Se,{value:x.name,onChange:K=>y({...x,name:K.target.value}),placeholder:"Jane Smith",className:"h-11 rounded-xl border-slate-200 focus:border-[#406E71] focus:ring-[#406E71]/20"})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{className:"text-xs font-semibold text-slate-700",children:"Email"}),e.jsxs("div",{className:"relative",children:[e.jsx(er,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),e.jsx(Se,{type:"email",value:x.email,onChange:K=>y({...x,email:K.target.value}),placeholder:"jane@email.com",className:"h-11 pl-9 rounded-xl border-slate-200 focus:border-[#406E71] focus:ring-[#406E71]/20"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{className:"text-xs font-semibold text-slate-700",children:"Phone"}),e.jsxs("div",{className:"relative",children:[e.jsx(Yn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),e.jsx(Se,{type:"tel",value:x.phone,onChange:K=>y({...x,phone:K.target.value}),placeholder:"(555) 123-4567",className:"h-11 pl-9 rounded-xl border-slate-200 focus:border-[#406E71] focus:ring-[#406E71]/20"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{className:"text-xs font-semibold text-slate-700",children:"Message (optional)"}),e.jsx(vr,{value:x.message,onChange:K=>y({...x,message:K.target.value}),placeholder:"Anything you'd like the agent to know ahead of time?",rows:3,className:"rounded-xl border-slate-200 focus:border-[#406E71] focus:ring-[#406E71]/20 resize-none"})]})]}),e.jsx(H,{className:"w-full h-12 rounded-xl bg-[#406E71] hover:bg-[#365c5e] text-white font-semibold shadow-md shadow-[#406E71]/20 transition-all hover:shadow-lg disabled:opacity-60",onClick:Z,disabled:!x.name||_,children:_?e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"animate-spin rounded-full h-4 w-4 border-2 border-white border-t-transparent"}),"Booking..."]}):"Confirm Booking"})]}),n==="confirmed"&&e.jsxs("div",{className:"text-center space-y-5 py-6",children:[e.jsxs("div",{className:"relative mx-auto w-20 h-20",children:[e.jsx("div",{className:"absolute inset-0 rounded-full bg-emerald-100 animate-ping opacity-30"}),e.jsx("div",{className:"relative w-20 h-20 rounded-full bg-gradient-to-br from-emerald-400 to-emerald-600 flex items-center justify-center shadow-lg shadow-emerald-200",children:e.jsx(ea,{className:"h-10 w-10 text-white"})})]}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold text-slate-800",children:"You're booked!"}),e.jsxs("p",{className:"text-slate-500 mt-1.5",children:[i==null?void 0:i.name," with ",(T==null?void 0:T.name)||"your agent"]})]}),e.jsx("div",{className:"inline-flex items-center gap-3 px-5 py-3 rounded-xl bg-slate-50 border border-slate-100",children:e.jsxs("div",{className:"text-left text-sm",children:[e.jsx("p",{className:"font-semibold text-slate-800",children:o&&As(o,"EEEE, MMMM d, yyyy")}),e.jsxs("p",{className:"text-slate-500",children:[d&&J(d)," · ",i==null?void 0:i.duration_minutes," min"]})]})}),e.jsx("p",{className:"text-sm text-slate-400 max-w-xs mx-auto",children:"A confirmation with meeting details will be sent to you shortly."}),((T==null?void 0:T.phone)||(T==null?void 0:T.email))&&e.jsxs("div",{className:"flex flex-col items-center gap-2 pt-2",children:[e.jsx("p",{className:"text-xs text-slate-400 uppercase tracking-wider font-semibold",children:"Contact"}),e.jsxs("div",{className:"flex gap-3",children:[(T==null?void 0:T.phone)&&e.jsxs("a",{href:`tel:${T.phone}`,className:"inline-flex items-center gap-1.5 px-4 py-2 rounded-full bg-[#406E71]/10 text-[#406E71] text-xs font-medium hover:bg-[#406E71]/20 transition-colors",children:[e.jsx(Yn,{className:"h-3.5 w-3.5"})," Call"]}),(T==null?void 0:T.email)&&e.jsxs("a",{href:`mailto:${T.email}`,className:"inline-flex items-center gap-1.5 px-4 py-2 rounded-full bg-[#2a4c64]/10 text-[#2a4c64] text-xs font-medium hover:bg-[#2a4c64]/20 transition-colors",children:[e.jsx(er,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})]})}),e.jsx("p",{className:"text-center text-[10px] text-slate-300 mt-6 font-medium tracking-wide uppercase",children:"Powered by LevelUp"})]})]}):e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-[#f0f4f8] via-white to-[#e8f0f8] flex items-center justify-center p-4",children:e.jsxs("div",{className:"max-w-sm w-full text-center space-y-4",children:[e.jsx("div",{className:"mx-auto w-16 h-16 rounded-2xl bg-slate-100 flex items-center justify-center",children:e.jsx(xu,{className:"h-8 w-8 text-slate-400"})}),e.jsx("h2",{className:"text-lg font-semibold text-slate-700",children:"Page Not Available"}),e.jsx("p",{className:"text-sm text-slate-500",children:"This booking page doesn't exist or is currently inactive."})]})})}function vUs(){const t=Vc().pathname.slice(1).split("/")[0];return S.useEffect(()=>{document.body.classList.add("booking-page");const r=()=>{['[id*="lc_text_widget"]','[id*="lc_text-widget"]','[class*="lc-text-widget"]','[class*="lc_text-widget"]','[class*="lc_text_widget"]',".lc_text-widget--bubble",'[id*="chat-widget"]','[class*="chat-widget"]','iframe[src*="widgets.leadconnectorhq"]','iframe[src*="leadconnector"]','iframe[src*="msgsndr"]',"[data-chat-widget]","[data-widget-id]",'div[style*="z-index"][style*="position: fixed"][style*="bottom"]','div[id^="fc_"]','div[id^="hubspot"]',".widget-visible"].forEach(i=>{document.querySelectorAll(i).forEach(l=>{l.style.display="none"})})};r();const n=[setTimeout(r,500),setTimeout(r,1500),setTimeout(r,3e3),setTimeout(r,5e3)];return()=>{document.body.classList.remove("booking-page"),n.forEach(clearTimeout)}},[]),t?e.jsx(Lvt,{slugOverride:t}):e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-50 to-slate-100 dark:from-slate-950 dark:to-slate-900 flex items-center justify-center p-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold mb-2",children:"LevelUp Scheduler"}),e.jsx("p",{className:"text-muted-foreground",children:"Visit a specific agent's booking URL to schedule a meeting."})]})})}function bUs(){const t=Vc().pathname.slice(1);return S.useEffect(()=>{document.body.classList.add("connect-page");const r=()=>{['[id*="lc_text_widget"]','[id*="lc_text-widget"]','[class*="lc-text-widget"]','[class*="lc_text-widget"]','[class*="lc_text_widget"]',".lc_text-widget--bubble",'[id*="chat-widget"]','[class*="chat-widget"]','iframe[src*="widgets.leadconnectorhq"]','iframe[src*="leadconnector"]','iframe[src*="msgsndr"]',"[data-chat-widget]","[data-widget-id]",'div[style*="z-index"][style*="position: fixed"][style*="bottom"]','div[id^="fc_"]','div[id^="hubspot"]',".widget-visible"].forEach(i=>{document.querySelectorAll(i).forEach(l=>{l.style.display="none"})})};r();const n=[setTimeout(r,500),setTimeout(r,1500),setTimeout(r,3e3),setTimeout(r,5e3)];return()=>{document.body.classList.remove("connect-page"),n.forEach(clearTimeout)}},[]),!t||t===""?e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-50 via-white to-slate-100 flex items-center justify-center p-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Connect"}),e.jsx("p",{className:"text-slate-500",children:"Stay connected with your real estate professional."}),e.jsx("p",{className:"text-slate-400 text-sm mt-2",children:"Visit a specific agent link to get started."})]})}):e.jsx(dot,{slugOverride:t})}function _Us(s){try{const t=document.createElement("canvas"),r=t.width=Math.min(s.naturalWidth,64),n=t.height=Math.min(s.naturalHeight,64),a=t.getContext("2d");if(!a)return!0;a.drawImage(s,0,0,r,n);const i=a.getImageData(0,0,r,n).data,l=[[0,0],[r-1,0],[0,n-1],[r-1,n-1],[Math.floor(r/2),0],[Math.floor(r/2),n-1],[0,Math.floor(n/2)],[r-1,Math.floor(n/2)]];for(const[o,c]of l)if(i[(c*r+o)*4+3]<250)return!0;return!1}catch{return!0}}const wUs={playfair:"'Playfair Display', Georgia, serif",baskerville:"'Libre Baskerville', Georgia, serif",instrument:"'Instrument Serif', Georgia, serif",sans:"'Inter', system-ui, sans-serif"};function jUs({page:s,fields:t,answers:r,setAnswers:n,onSubmit:a,isSubmitting:i,renderField:l}){const o=s.accent_color||"#E8B84A",c=s.primary_color||"#0F1B3D",d=wUs[s.heading_font||"playfair"],h=s.eyebrow||null,m=s.headline_accent||null,p=Array.isArray(s.trust_pills)?s.trust_pills:[],x=t.slice(0,5);return e.jsxs("section",{className:"relative w-full min-h-screen md:min-h-[760px] overflow-hidden",style:{backgroundColor:c},children:[s.hero_image_url?e.jsx("img",{src:s.hero_image_url,alt:"",className:"absolute inset-0 w-full h-full object-cover",loading:"eager"}):e.jsx("div",{className:"absolute inset-0",style:{background:`linear-gradient(135deg, ${c}, #000)`}}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-r from-black/85 via-black/55 to-black/25"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-black/70 via-transparent to-black/20"}),e.jsx("div",{className:"relative z-10 mx-auto w-full max-w-7xl px-6 md:px-10 py-16 md:py-24 min-h-screen md:min-h-[760px] flex items-center",children:e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-5 gap-10 lg:gap-12 w-full items-center",children:[e.jsxs("div",{className:"lg:col-span-3 text-white",children:[s.logo_url&&e.jsx(NUs,{src:s.logo_url}),h&&e.jsx("p",{className:"text-xs md:text-sm font-semibold tracking-[0.22em] text-white/80 mb-4 uppercase",children:h}),e.jsxs("h1",{className:"font-bold leading-[1.04] mb-5 text-4xl sm:text-5xl md:text-6xl lg:text-[68px]",style:{fontFamily:d,letterSpacing:"-0.015em"},children:[s.hero_headline,m&&e.jsxs(e.Fragment,{children:[" ",e.jsx("span",{style:{color:o,fontStyle:"italic"},children:m})]})]}),s.hero_subtext&&e.jsx("p",{className:"text-base md:text-lg text-white/85 leading-relaxed max-w-xl",children:s.hero_subtext}),s.agent_name&&e.jsxs("div",{className:"mt-8 flex items-center gap-3",children:[s.agent_photo_url&&e.jsx("img",{src:s.agent_photo_url,alt:s.agent_name,className:"h-12 w-12 rounded-full object-cover ring-2 ring-white/30"}),e.jsxs("div",{className:"text-white/90",children:[e.jsx("p",{className:"font-semibold text-sm",children:s.agent_name}),e.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1 text-xs text-white/70 mt-0.5",children:[s.agent_phone&&e.jsxs("a",{href:`tel:${s.agent_phone}`,className:"flex items-center gap-1 hover:text-white",children:[e.jsx(Yn,{className:"h-3 w-3"})," ",s.agent_phone]}),s.agent_email&&e.jsxs("a",{href:`mailto:${s.agent_email}`,className:"flex items-center gap-1 hover:text-white",children:[e.jsx(er,{className:"h-3 w-3"})," ",s.agent_email]})]})]})]})]}),e.jsx("div",{className:"lg:col-span-2",children:e.jsxs("div",{className:"rounded-2xl border border-white/15 bg-white/10 backdrop-blur-xl shadow-2xl p-5 md:p-6",children:[e.jsxs("form",{className:"space-y-3",onSubmit:a,children:[x.map(y=>e.jsxs("div",{children:[e.jsxs(ue,{className:"block text-[11px] font-semibold tracking-wider uppercase text-white/85 mb-1.5",children:[y.label,y.is_required&&e.jsx("span",{className:"ml-1",style:{color:o},children:"*"})]}),e.jsx("div",{className:"[&_input]:bg-white/95 [&_input]:border-0 [&_input]:text-neutral-900 [&_input]:placeholder:text-neutral-400 [&_textarea]:bg-white/95 [&_textarea]:border-0 [&_textarea]:text-neutral-900 [&_textarea]:placeholder:text-neutral-400 [&_button[role=combobox]]:bg-white/95 [&_button[role=combobox]]:border-0 [&_button[role=combobox]]:text-neutral-900",children:l(y,r,n,c)})]},y.id)),e.jsx("button",{type:"submit",disabled:i,className:"w-full px-6 py-3.5 rounded-lg font-bold text-neutral-900 text-base md:text-lg shadow-lg hover:brightness-110 active:brightness-95 transition-all disabled:opacity-60 mt-2",style:{backgroundColor:o},children:i?"Submitting...":s.cta_text||"Get Started"})]}),p.length>0&&e.jsx("div",{className:"flex flex-wrap gap-x-5 gap-y-2 mt-4",children:p.map((y,_)=>e.jsxs("span",{className:"flex items-center gap-1.5 text-[11px] md:text-xs text-white/80 font-medium",children:[e.jsx("span",{className:"h-1 w-1 rounded-full",style:{backgroundColor:o}}),y]},_))})]})})]})})]})}function NUs({src:s}){const[t,r]=S.useState(null),n=e.jsx("img",{src:s,alt:"Logo",crossOrigin:"anonymous",className:"h-10 md:h-12 w-auto object-contain",onLoad:a=>r(_Us(a.currentTarget)),onError:()=>r(!0)});return t===!1?e.jsx("span",{className:"inline-flex items-center rounded-md bg-white/90 backdrop-blur px-3 py-2 mb-6 shadow-sm",children:n}):e.jsx("div",{className:"mb-6 inline-block drop-shadow-md",children:n})}function Dvt({slugOverride:s}){const{slug:t}=Po(),r=s||t,[n,a]=S.useState(!1),[i,l]=S.useState({}),[o,c]=S.useState(0),[d,h]=S.useState(!1),{data:m,isLoading:p}=yt({queryKey:["public-landing-page",r],queryFn:async()=>{const{data:R,error:z}=await V.from("landing_pages").select("*").eq("slug",r).eq("is_published",!0).single();if(z)throw z;return R},enabled:!!r}),{data:x=[]}=yt({queryKey:["public-landing-page-fields",m==null?void 0:m.id],queryFn:async()=>{const{data:R,error:z}=await V.from("landing_page_fields").select("*").eq("page_id",m.id).order("sort_order");if(z)throw z;return R},enabled:!!(m!=null&&m.id)});S.useEffect(()=>{m!=null&&m.id&&V.from("landing_pages").update({view_count:(m.view_count||0)+1}).eq("id",m.id).then(()=>{})},[m==null?void 0:m.id]);const y=Pt({mutationFn:async()=>{const R=x.find(K=>K.field_type==="text"&&K.label.toLowerCase().includes("name")),z=x.find(K=>K.field_type==="email"),O=x.find(K=>K.field_type==="phone"),$=R?String(i[R.label]||""):null,ee=z?String(i[z.label]||""):null,Z=O?String(i[O.label]||""):null,{error:J}=await V.from("landing_page_submissions").insert([{page_id:m.id,answers:JSON.parse(JSON.stringify(i)),contact_name:$,contact_email:ee,contact_phone:Z,referrer:document.referrer||null,user_agent:navigator.userAgent,utm_source:new URLSearchParams(window.location.search).get("utm_source"),utm_medium:new URLSearchParams(window.location.search).get("utm_medium"),utm_campaign:new URLSearchParams(window.location.search).get("utm_campaign")}]);if(J)throw J;V.functions.invoke("landing-page-lead-notify",{body:{page_id:m.id,contact_name:$,contact_email:ee,contact_phone:Z,answers:i}}).catch(K=>console.error("Landing page lead notification error:",K))},onSuccess:()=>a(!0)}),_=R=>{R.preventDefault(),!(x.filter(O=>O.is_required&&!i[O.label]).length>0)&&y.mutate()};if(p)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gray-50",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-gray-400 border-t-transparent"})});if(!m)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gray-50",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold text-gray-700",children:"Page Not Found"}),e.jsx("p",{className:"text-gray-500 mt-2",children:"This page doesn't exist or is no longer available."})]})});const b=m.primary_color||"#406E71",j=m.accent_color||"#2a4c64",k=m,T=m.page_type==="lead_magnet",E=m.page_type==="just_listed"||m.page_type==="just_sold",A=Array.isArray(k.property_photos)?k.property_photos:[],D=k.lead_magnet_file_url||k.lead_magnet_external_url;if(n)return e.jsx("div",{className:"min-h-screen flex items-center justify-center",style:{background:`linear-gradient(135deg, ${b}, ${j})`},children:e.jsxs("div",{className:"bg-white rounded-2xl shadow-2xl p-8 max-w-md mx-4 text-center",children:[e.jsx(ea,{className:"h-16 w-16 mx-auto mb-4",style:{color:b}}),e.jsx("h2",{className:"text-2xl font-bold mb-2",children:T?"Your download is ready!":"Submitted!"}),e.jsx("p",{className:"text-gray-600",children:m.success_message}),T&&D&&e.jsxs("a",{href:D,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-2 mt-6 px-6 py-3 rounded-lg text-white font-semibold transition-transform hover:scale-105",style:{backgroundColor:b},children:[e.jsx(hi,{className:"h-5 w-5"}),"Download ",k.lead_magnet_file_name||"Your File"]}),m.agent_name&&e.jsxs("div",{className:"mt-6 pt-4 border-t",children:[e.jsx("p",{className:"text-sm text-gray-500",children:"Contact"}),e.jsx("p",{className:"font-semibold",children:m.agent_name}),m.agent_phone&&e.jsxs("a",{href:`tel:${m.agent_phone}`,className:"text-sm flex items-center justify-center gap-1 mt-1",style:{color:b},children:[e.jsx(Yn,{className:"h-3 w-3"})," ",m.agent_phone]}),m.agent_email&&e.jsxs("a",{href:`mailto:${m.agent_email}`,className:"text-sm flex items-center justify-center gap-1 mt-1",style:{color:b},children:[e.jsx(er,{className:"h-3 w-3"})," ",m.agent_email]})]})]})});if(E){const R=z=>{const O=parseFloat(z.replace(/[^0-9.]/g,""));return isNaN(O)?z:new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(O)};return e.jsxs("div",{className:"min-h-screen bg-gray-50",children:[d&&A.length>0&&e.jsxs("div",{className:"fixed inset-0 z-50 bg-black/95 flex items-center justify-center",onClick:()=>h(!1),children:[e.jsx("button",{onClick:()=>h(!1),className:"absolute top-4 right-4 text-white/80 hover:text-white z-10",children:e.jsx(Rr,{className:"h-8 w-8"})}),e.jsx("button",{onClick:z=>{z.stopPropagation(),c(O=>O===0?A.length-1:O-1)},className:"absolute left-4 top-1/2 -translate-y-1/2 bg-white/10 hover:bg-white/20 text-white rounded-full p-3 transition-colors z-10",children:e.jsx(fl,{className:"h-6 w-6"})}),e.jsx("img",{src:A[o],alt:`Property photo ${o+1}`,className:"max-h-[90vh] max-w-[90vw] object-contain rounded-lg",onClick:z=>z.stopPropagation()}),e.jsx("button",{onClick:z=>{z.stopPropagation(),c(O=>O===A.length-1?0:O+1)},className:"absolute right-4 top-1/2 -translate-y-1/2 bg-white/10 hover:bg-white/20 text-white rounded-full p-3 transition-colors z-10",children:e.jsx($a,{className:"h-6 w-6"})}),e.jsxs("div",{className:"absolute bottom-6 left-1/2 -translate-x-1/2 text-white/70 text-sm",children:[o+1," / ",A.length]})]}),A.length>0&&e.jsxs("div",{className:"relative max-w-6xl mx-auto px-4 pt-6",children:[e.jsx("div",{className:"absolute top-10 left-8 z-10 px-4 py-1.5 rounded-full text-white font-bold text-sm uppercase tracking-wider shadow-lg",style:{backgroundColor:k.property_status==="just_sold"?"#e74c3c":b},children:k.property_status==="just_sold"?"🎉 Just Sold":"🏡 Just Listed"}),A.length===1?e.jsxs("div",{className:"rounded-2xl overflow-hidden cursor-pointer group",onClick:()=>{c(0),h(!0)},children:[e.jsx("img",{src:A[0],alt:"Property",className:"w-full h-[50vh] object-cover group-hover:scale-105 transition-transform duration-500"}),e.jsxs("div",{className:"absolute bottom-4 right-4 bg-black/60 text-white px-3 py-1.5 rounded-lg text-sm flex items-center gap-1.5 opacity-0 group-hover:opacity-100 transition-opacity",children:[e.jsx(Qk,{className:"h-4 w-4"})," View"]})]}):A.length===2?e.jsx("div",{className:"grid grid-cols-2 gap-2 rounded-2xl overflow-hidden",children:A.slice(0,2).map((z,O)=>e.jsx("div",{className:"cursor-pointer group relative",onClick:()=>{c(O),h(!0)},children:e.jsx("img",{src:z,alt:`Property ${O+1}`,className:"w-full h-[45vh] object-cover group-hover:scale-105 transition-transform duration-500"})},O))}):e.jsxs("div",{className:"grid grid-cols-4 gap-2 rounded-2xl overflow-hidden",style:{height:"55vh"},children:[e.jsx("div",{className:"col-span-2 row-span-2 cursor-pointer group relative",onClick:()=>{c(0),h(!0)},children:e.jsx("img",{src:A[0],alt:"Property main",className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"})}),A.slice(1,5).map((z,O)=>e.jsxs("div",{className:"cursor-pointer group relative",onClick:()=>{c(O+1),h(!0)},children:[e.jsx("img",{src:z,alt:`Property ${O+2}`,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"}),O===3&&A.length>5&&e.jsxs("div",{className:"absolute inset-0 bg-black/50 flex items-center justify-center text-white font-bold text-lg",children:["+",A.length-5," more"]})]},O))]}),A.length>2&&e.jsxs("button",{onClick:()=>{c(0),h(!0)},className:"absolute bottom-4 right-8 bg-white shadow-lg hover:shadow-xl text-gray-800 px-4 py-2 rounded-lg text-sm font-medium flex items-center gap-2 transition-shadow",children:[e.jsx(Qk,{className:"h-4 w-4"})," View all ",A.length," photos"]})]}),A.length===0&&e.jsx("div",{className:"relative py-16 px-4",style:{background:m.hero_image_url?`linear-gradient(rgba(0,0,0,0.55), rgba(0,0,0,0.55)), url(${m.hero_image_url}) center/cover`:`linear-gradient(135deg, ${b}, ${j})`},children:e.jsxs("div",{className:"max-w-2xl mx-auto text-center text-white",children:[m.logo_url&&e.jsx("img",{src:m.logo_url,alt:"Logo",className:"h-12 w-auto mx-auto mb-6"}),e.jsx("h1",{className:"text-3xl md:text-4xl font-bold",children:m.hero_headline}),m.hero_subtext&&e.jsx("p",{className:"mt-3 text-lg opacity-90",children:m.hero_subtext})]})}),e.jsx("div",{className:"max-w-4xl mx-auto px-4 py-8",children:e.jsxs("div",{className:"grid md:grid-cols-5 gap-6",children:[e.jsx("div",{className:"md:col-span-3 space-y-6",children:e.jsxs("div",{className:"bg-white rounded-2xl shadow-xl p-6 md:p-8",children:[k.property_price&&e.jsx("p",{className:"text-3xl md:text-4xl font-bold mb-2",style:{color:b},children:R(k.property_price)}),k.property_address&&e.jsxs("p",{className:"text-gray-600 flex items-center gap-1.5 mb-5 text-lg",children:[e.jsx(Qa,{className:"h-5 w-5 shrink-0"})," ",k.property_address]}),e.jsxs("div",{className:"flex gap-6 mb-5 py-4 border-y border-gray-100",children:[k.property_beds&&e.jsxs("div",{className:"text-center",children:[e.jsxs("div",{className:"flex items-center justify-center gap-1.5 text-lg font-semibold",children:[e.jsx(x1,{className:"h-5 w-5",style:{color:b}})," ",k.property_beds]}),e.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:"Bedrooms"})]}),k.property_baths&&e.jsxs("div",{className:"text-center",children:[e.jsxs("div",{className:"flex items-center justify-center gap-1.5 text-lg font-semibold",children:[e.jsx(_p,{className:"h-5 w-5",style:{color:b}})," ",k.property_baths]}),e.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:"Bathrooms"})]}),k.property_sqft&&e.jsxs("div",{className:"text-center",children:[e.jsxs("div",{className:"flex items-center justify-center gap-1.5 text-lg font-semibold",children:[e.jsx(LE,{className:"h-5 w-5",style:{color:b}})," ",Number(k.property_sqft).toLocaleString()]}),e.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:"Sq Ft"})]})]}),k.property_description&&e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-gray-800 mb-2",children:"About This Property"}),e.jsx("p",{className:"text-gray-600 leading-relaxed whitespace-pre-line",children:k.property_description})]})]})}),e.jsx("div",{className:"md:col-span-2",children:e.jsxs("div",{className:"bg-white rounded-2xl shadow-xl p-6 sticky top-6",children:[e.jsx("h2",{className:"text-lg font-bold mb-1",style:{color:b},children:k.property_status==="just_sold"?"Want results like this?":"Interested in this property?"}),e.jsx("p",{className:"text-gray-500 text-sm mb-4",children:"Fill out the form and I'll be in touch!"}),m.agent_name&&e.jsxs("div",{className:"flex items-center gap-3 mb-5 pb-4 border-b",children:[m.agent_photo_url&&e.jsx("img",{src:m.agent_photo_url,alt:m.agent_name,className:"h-12 w-12 rounded-full object-cover"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-sm",children:m.agent_name}),e.jsxs("div",{className:"flex flex-col gap-0.5 text-xs text-gray-500",children:[m.agent_phone&&e.jsxs("a",{href:`tel:${m.agent_phone}`,className:"flex items-center gap-1 hover:underline",children:[e.jsx(Yn,{className:"h-3 w-3"})," ",m.agent_phone]}),m.agent_email&&e.jsxs("a",{href:`mailto:${m.agent_email}`,className:"flex items-center gap-1 hover:underline",children:[e.jsx(er,{className:"h-3 w-3"})," ",m.agent_email]})]})]})]}),e.jsxs("form",{onSubmit:_,className:"space-y-3",children:[x.map(z=>e.jsxs("div",{children:[e.jsxs(ue,{className:"text-xs font-medium",children:[z.label,z.is_required&&e.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),Lwe(z,i,l)]},z.id)),e.jsx(H,{type:"submit",className:"w-full text-white",style:{backgroundColor:b},disabled:y.isPending,children:y.isPending?"Submitting...":"Submit"}),y.isError&&e.jsx("p",{className:"text-sm text-red-500 text-center",children:"Something went wrong. Please try again."})]})]})})]})}),e.jsx("div",{className:"text-center py-8 text-xs text-gray-400",children:"Powered by LevelUp"})]})}return m.theme_style!=="classic"&&!T?e.jsxs("div",{className:"min-h-screen bg-neutral-50",children:[e.jsx(jUs,{page:m,fields:x,answers:i,setAnswers:l,onSubmit:_,isSubmitting:y.isPending,renderField:Lwe}),y.isError&&e.jsx("p",{className:"text-sm text-red-500 text-center py-4",children:"Something went wrong. Please try again."}),e.jsx("div",{className:"text-center py-8 text-xs text-gray-400",children:"Powered by LevelUp"})]}):e.jsxs("div",{className:"min-h-screen bg-gray-50",children:[e.jsx("div",{className:"relative py-16 px-4",style:{background:m.hero_image_url?`linear-gradient(rgba(0,0,0,0.55), rgba(0,0,0,0.55)), url(${m.hero_image_url}) center/cover`:`linear-gradient(135deg, ${b}, ${j})`},children:e.jsxs("div",{className:"max-w-2xl mx-auto text-center text-white",children:[m.logo_url&&e.jsx("img",{src:m.logo_url,alt:"Logo",className:"h-12 w-auto mx-auto mb-6"}),e.jsx("h1",{className:"text-3xl md:text-4xl font-bold",children:m.hero_headline}),m.hero_subtext&&e.jsx("p",{className:"mt-3 text-lg opacity-90",children:m.hero_subtext}),T&&k.lead_magnet_file_name&&e.jsxs("div",{className:"mt-6 inline-flex items-center gap-2 bg-white/20 backdrop-blur px-4 py-2 rounded-full text-sm",children:[e.jsx(hi,{className:"h-4 w-4"}),"Free Download: ",k.lead_magnet_file_name]})]})}),e.jsx("div",{className:"max-w-2xl mx-auto px-4 -mt-8",children:e.jsxs("div",{className:"bg-white rounded-2xl shadow-xl p-6 md:p-8",children:[T&&e.jsx("p",{className:"text-sm text-gray-500 mb-4 text-center",children:"Fill out the form below to get your free download!"}),m.agent_name&&e.jsxs("div",{className:"flex items-center gap-3 mb-6 pb-4 border-b",children:[m.agent_photo_url&&e.jsx("img",{src:m.agent_photo_url,alt:m.agent_name,className:"h-12 w-12 rounded-full object-cover"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold",children:m.agent_name}),e.jsxs("div",{className:"flex items-center gap-3 text-sm text-gray-500",children:[m.agent_phone&&e.jsxs("a",{href:`tel:${m.agent_phone}`,className:"flex items-center gap-1 hover:underline",children:[e.jsx(Yn,{className:"h-3 w-3"})," ",m.agent_phone]}),m.agent_email&&e.jsxs("a",{href:`mailto:${m.agent_email}`,className:"flex items-center gap-1 hover:underline",children:[e.jsx(er,{className:"h-3 w-3"})," ",m.agent_email]})]})]})]}),e.jsxs("form",{onSubmit:_,className:"space-y-4",children:[x.map(R=>e.jsxs("div",{children:[e.jsxs(ue,{className:"text-sm font-medium",children:[R.label,R.is_required&&e.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),Lwe(R,i,l)]},R.id)),e.jsx(H,{type:"submit",className:"w-full text-white",style:{backgroundColor:b},disabled:y.isPending,children:y.isPending?"Submitting...":T?"Get My Free Download":"Submit"}),y.isError&&e.jsx("p",{className:"text-sm text-red-500 text-center",children:"Something went wrong. Please try again."})]})]})}),e.jsx("div",{className:"text-center py-8 text-xs text-gray-400",children:"Powered by LevelUp"})]})}function Lwe(s,t,r,n){const a=t[s.label]||"",i=Array.isArray(s.options)?s.options:[];switch(s.field_type){case"text":case"email":case"phone":return e.jsx(Se,{type:s.field_type==="email"?"email":s.field_type==="phone"?"tel":"text",value:String(a),onChange:l=>r(o=>({...o,[s.label]:l.target.value})),placeholder:s.placeholder||"",className:"mt-1"});case"textarea":return e.jsx(vr,{value:String(a),onChange:l=>r(o=>({...o,[s.label]:l.target.value})),placeholder:s.placeholder||"",rows:3,className:"mt-1"});case"select":return e.jsxs(Bs,{value:String(a),onValueChange:l=>r(o=>({...o,[s.label]:l})),children:[e.jsx(Os,{className:"mt-1",children:e.jsx(Us,{placeholder:"Select..."})}),e.jsx(Fs,{children:i.map(l=>e.jsx(pt,{value:l,children:l},l))})]});case"multiselect":return e.jsx("div",{className:"mt-1 space-y-2",children:i.map(l=>{const o=Array.isArray(a)?a:[];return e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx(ao,{checked:o.includes(l),onCheckedChange:c=>{const d=c?[...o,l]:o.filter(h=>h!==l);r(h=>({...h,[s.label]:d}))}}),e.jsx("span",{className:"text-sm",children:l})]},l)})});case"toggle":return e.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[e.jsx(Or,{checked:!!a,onCheckedChange:l=>r(o=>({...o,[s.label]:l?"Yes":"No"}))}),e.jsx("span",{className:"text-sm text-gray-600",children:a?"Yes":"No"})]});default:return e.jsx(Se,{value:String(a),onChange:l=>r(o=>({...o,[s.label]:l.target.value})),className:"mt-1"})}}function kUs(){const t=Vc().pathname.slice(1).split("/")[0];return S.useEffect(()=>{document.body.classList.add("landing-page-public");const r=()=>{['[id*="lc_text_widget"]','[class*="lc-text-widget"]','[class*="lc_text_widget"]',".lc_text-widget--bubble",'[id*="chat-widget"]','[class*="chat-widget"]','iframe[src*="widgets.leadconnectorhq"]','iframe[src*="leadconnector"]','iframe[src*="msgsndr"]',"[data-chat-widget]","[data-widget-id]",'div[style*="z-index"][style*="position: fixed"][style*="bottom"]','div[id^="fc_"]','div[id^="hubspot"]',".widget-visible"].forEach(i=>{document.querySelectorAll(i).forEach(l=>{l.style.display="none"})})};r();const n=[setTimeout(r,500),setTimeout(r,1500),setTimeout(r,3e3),setTimeout(r,5e3)];return()=>{document.body.classList.remove("landing-page-public"),n.forEach(clearTimeout)}},[]),t?e.jsx(Dvt,{slugOverride:t}):e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-50 to-slate-100 flex items-center justify-center p-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold mb-2",children:"LevelUp Pages"}),e.jsx("p",{className:"text-gray-500",children:"Visit a specific page URL to view content."})]})})}const SUs=[{type:"hero",enabled:!0},{type:"featured_listings",enabled:!0},{type:"new_listings",enabled:!1},{type:"open_houses",enabled:!1},{type:"my_listings",enabled:!1},{type:"city_pages",enabled:!1},{type:"featured_areas",enabled:!0},{type:"about",enabled:!0},{type:"testimonials",enabled:!0},{type:"cta_banner",enabled:!0}],fXs={hero:"Hero Section",featured_listings:"Featured Listings",featured_areas:"Featured Areas",about:"About Me",testimonials:"Testimonials",cta_banner:"Call To Action",new_listings:"New Listings Carousel",open_houses:"Open Houses Carousel",my_listings:"My Listings Carousel",city_pages:"City Pages Grid",property_types:"Property Types Gallery",advantages:"Advantages / Why Choose Us",lifestyle_gallery:"Lifestyle Gallery",market_pulse:"Market Pulse",concierge_services:"Concierge Services",land_use_guide:"Land Use Guide",land_valuation_cta:"Land Valuation CTA",acreage_showcase:"Acreage Showcase"},pXs={hero:"Full-screen background image with headline, subtitle, and search bar",featured_listings:"Grid of highlighted properties from the MLS",featured_areas:"Spotlight regions or neighborhoods that link to property search",about:"Agent photo, bio, and credentials section",testimonials:"Client reviews carousel with quotes",cta_banner:"Call-to-action block to drive contact and search engagement",new_listings:"Horizontal carousel of newest listings, filterable by city",open_houses:"Horizontal carousel of open house listings, filterable by city",my_listings:"Showcase the agent's own active listings in a carousel",city_pages:"Grid of your city landing pages with photos and links",property_types:"Visual gallery of property categories (Ranch, Farm, Land, etc.)",advantages:"Feature cards highlighting your expertise and unique value",lifestyle_gallery:"Cinematic photo grid showcasing luxury living — pools, views, interiors",market_pulse:"Sleek market stats dashboard with avg price, days on market, inventory",concierge_services:"White-glove services showcase — staging, design, moving coordination",land_use_guide:"Interactive land use cards — Agriculture, Hunting, Equestrian, Recreational",land_valuation_cta:`"What's Your Land Worth?" — bold call-to-action for landowners`,acreage_showcase:"Large visual cards emphasizing lot size with aerial imagery"},KWe={basic:["hero","featured_listings","new_listings","open_houses","my_listings","city_pages","featured_areas","about","testimonials","cta_banner"],luxury:["hero","featured_listings","new_listings","open_houses","my_listings","city_pages","featured_areas","about","testimonials","cta_banner","lifestyle_gallery","market_pulse","concierge_services"],"land-ranch":["hero","featured_listings","new_listings","open_houses","my_listings","city_pages","featured_areas","about","testimonials","cta_banner","property_types","advantages","land_use_guide","land_valuation_cta","acreage_showcase"]};function gXs(s){return KWe[s]||KWe.basic}function CUs(s){const t=s.theme_config||{};return{themeTier:s.theme_tier||"basic",brandColor:s.brand_color||"#0f172a",accentColor:s.accent_color||"#3b82f6",fontFamily:s.font_family||"Inter",heroImageUrl:s.hero_image_url||null,homepageModules:Array.isArray(s.homepage_modules)&&s.homepage_modules.length?s.homepage_modules:SUs,testimonials:Array.isArray(s.testimonials)?s.testimonials:[],featuredListingIds:s.featured_listing_ids||[],searchCities:Array.isArray(t.searchCities)?t.searchCities:[],searchZipCodes:Array.isArray(t.searchZipCodes)?t.searchZipCodes:[],searchCounties:Array.isArray(t.searchCounties)?t.searchCounties:[],searchSubdivisions:Array.isArray(t.searchSubdivisions)?t.searchSubdivisions:[],referralMode:t.referralMode===!0,referralPrimaryLabel:t.referralPrimaryLabel||void 0,referralPrimaryUrl:t.referralPrimaryUrl||void 0,referralSecondaryLabel:t.referralSecondaryLabel||void 0,referralSecondaryUrl:t.referralSecondaryUrl||void 0}}function TUs(){const t=window.location.hostname.match(/^([^.]+)\.thelocalmove\.com$/i);return t?t[1]:null}function EUs(){const s=TUs(),{data:t,isLoading:r,error:n}=yt({queryKey:["lead-site",s],queryFn:async()=>{var h;if(!s)return null;const{data:a,error:i}=await V.from("lead_sites").select("*").eq("subdomain_slug",s).eq("is_active",!0).maybeSingle();if(i)throw i;if(!a)return null;const{data:l}=await V.from("profiles").select("id, name, avatar_url, email, phone, title, bio, areas_served, years_experience, instagram_url, facebook_url, linkedin_url").eq("id",a.agent_id).single();let o=null;if(a.show_team_logo)if(a.team_logo_url)o=a.team_logo_url;else{const{data:m}=await V.from("team_members").select("team_id, teams(avatar_url, name)").eq("user_id",a.agent_id).limit(1).maybeSingle();m&&((h=m.teams)!=null&&h.avatar_url)&&(o=m.teams.avatar_url)}const c={id:a.id,agentId:a.agent_id,subdomainSlug:a.subdomain_slug,mlsProviderId:a.mls_provider_id,siteTitle:a.site_title,siteTagline:a.site_tagline,leadRegistrationMode:a.lead_registration_mode||"disabled",registrationTriggerCount:a.registration_trigger_count??1,themeConfig:a.theme_config||{},isActive:a.is_active,brokerageLegalName:a.brokerage_legal_name||null,brokerageLicenseNumber:a.brokerage_license_number||null,agentLicenseNumber:a.agent_license_number||null,mlsDisclaimerText:a.mls_disclaimer_text||null,mlsLogoUrl:a.mls_logo_url||null,equalHousingEnabled:a.equal_housing_enabled??!0,faviconUrl:a.favicon_url||null,ogImageUrl:a.og_image_url||null,showTeamLogo:a.show_team_logo??!1,teamLogoUrl:o,agent:l?{id:l.id,full_name:l.name||"",avatar_url:l.avatar_url,email:l.email,phone:l.phone,title:l.title,bio:l.bio,areas_served:l.areas_served||null,years_experience:l.years_experience??null,instagram_url:l.instagram_url||null,facebook_url:l.facebook_url||null,linkedin_url:l.linkedin_url||null}:void 0,testimonials:Array.isArray(a.testimonials)?a.testimonials.filter(m=>m&&typeof m=="object"&&m.text).map(m=>({name:String(m.name||"Client"),text:String(m.text),rating:typeof m.rating=="number"?m.rating:5,location:m.location?String(m.location):void 0})):[],seoMetaTitle:a.seo_meta_title||null,seoMetaDescription:a.seo_meta_description||null},d=CUs(a);return{siteConfig:c,themeConfig:d}},enabled:!!s,staleTime:5*60*1e3,gcTime:30*60*1e3,refetchOnWindowFocus:!1});return{siteConfig:(t==null?void 0:t.siteConfig)??null,themeConfig:(t==null?void 0:t.themeConfig)??null,isLoading:r,error:n,slug:s}}async function AUs(s,t){try{await V.functions.invoke("lead-site-notify",{body:{lead:t,lead_site_id:s}})}catch(r){console.warn("Lead notification failed:",r)}}const Rvt=S.createContext(null);function dye(){const s=S.useContext(Rvt);if(!s)throw new Error("useLeadSiteAuth must be used within LeadSiteAuthProvider");return s}function MUs({siteConfig:s,children:t}){const[r,n]=S.useState(null),[a,i]=S.useState(null),[l,o]=S.useState(!0);S.useEffect(()=>{const{data:{subscription:m}}=V.auth.onAuthStateChange(async(p,x)=>{const y=(x==null?void 0:x.user)??null;if(n(y),y){const{data:_}=await V.from("lead_site_consumer_profiles").select("id, name, phone").eq("user_id",y.id).eq("lead_site_id",s.id).maybeSingle();_&&i({..._,email:y.email||""})}else i(null);o(!1)});return V.auth.getSession().then(({data:{session:p}})=>{n((p==null?void 0:p.user)??null),p!=null&&p.user?V.from("lead_site_consumer_profiles").select("id, name, phone").eq("user_id",p.user.id).eq("lead_site_id",s.id).maybeSingle().then(({data:x})=>{x&&i({...x,email:p.user.email||""}),o(!1)}):o(!1)}),()=>m.unsubscribe()},[s.id]);const c=S.useCallback(async m=>{const p=m.email.toLowerCase().trim(),x=m.phone.replace(/\D/g,""),{data:y,error:_}=await V.auth.signUp({email:p,password:x,options:{data:{full_name:m.name,consumer_site_id:s.id},emailRedirectTo:window.location.origin}});if(_){if(_.message.includes("already registered")){await d(p,x);return}throw _}if(y.user){const{error:b}=await V.from("lead_site_consumer_profiles").insert({user_id:y.user.id,lead_site_id:s.id,name:m.name.trim(),phone:m.phone.trim()});b&&console.warn("Consumer profile insert error:",b);const{error:j}=await V.from("lead_site_leads").insert({lead_site_id:s.id,name:m.name.trim(),email:p,phone:m.phone.trim(),message:"Created account on website",source_page:window.location.pathname,lead_type:"website_registration",metadata:{registered:!0,has_account:!0}});j&&console.error("Lead insert error (CRM sync may not trigger):",j),AUs(s.id,{name:m.name.trim(),email:p,phone:m.phone.trim(),lead_type:"website_registration",message:"Created account on website",source_page:window.location.pathname})}},[s.id]),d=S.useCallback(async(m,p)=>{const x=p.replace(/\D/g,""),{error:y}=await V.auth.signInWithPassword({email:m.toLowerCase().trim(),password:x});if(y)throw y},[]),h=S.useCallback(async()=>{await V.auth.signOut(),n(null),i(null)},[]);return e.jsx(Rvt.Provider,{value:{user:r,profile:a,isLoading:l,signUp:c,signIn:d,signOut:h},children:t})}function v6e({open:s,mode:t,siteConfig:r,onComplete:n,onSkip:a,theme:i="default",accentColor:l}){var J;const{signUp:o,signIn:c}=dye(),[d,h]=S.useState(!1),[m,p]=S.useState(""),[x,y]=S.useState(""),[_,b]=S.useState(""),[j,k]=S.useState(!1),[T,E]=S.useState(""),A=t==="required",D=i==="luxury",R=l||(D?"#c9a96e":"#2563eb"),z=((J=r.agent)==null?void 0:J.full_name)||"the agent",O={borderColor:`${R}66`,"--tw-ring-color":`${R}66`},$=async K=>{var ie;if(K.preventDefault(),E(""),!x.trim()||!_.trim()){E("Email and phone number are required.");return}if(!d&&!m.trim()){E("Name is required.");return}if(_.replace(/\D/g,"").length<7){E("Please enter a valid phone number.");return}k(!0);try{d?await c(x,_):await o({name:m,email:x,phone:_}),n()}catch(ce){(ie=ce==null?void 0:ce.message)!=null&&ie.includes("Invalid login")?E("Invalid email or phone number. Please try again."):E((ce==null?void 0:ce.message)||"Something went wrong. Please try again.")}finally{k(!1)}},ee=D?"w-full px-3 py-2.5 border rounded-lg text-sm focus:outline-none focus:ring-2":"w-full px-3 py-2.5 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-500",Z=D?O:void 0;return e.jsx(bs,{open:s,onOpenChange:A?void 0:K=>{K||a()},children:e.jsxs(vs,{className:`sm:max-w-md ${D?"border-white/10 bg-[#f7f1e7] text-[#201915]":""}`,onPointerDownOutside:A?K=>K.preventDefault():void 0,onEscapeKeyDown:A?K=>K.preventDefault():void 0,children:[e.jsxs(Cs,{children:[e.jsx(Ns,{className:"text-xl",style:D?{fontFamily:"'Playfair Display', Georgia, serif"}:void 0,children:d?"Welcome Back":A?"Create a Free Account to Continue":"Save Your Search & Get Updates"}),e.jsx(nn,{className:D?"text-[#5f5145]":void 0,children:d?"Sign in with your email and phone number.":`Create a free account to save favorites, get alerts, and connect with ${z}.`})]}),e.jsxs("form",{onSubmit:$,className:"space-y-3 mt-2",children:[!d&&e.jsx("input",{type:"text",required:!0,placeholder:"Your name",value:m,onChange:K=>p(K.target.value),className:ee,style:Z}),e.jsx("input",{type:"email",required:!0,placeholder:"Email address",value:x,onChange:K=>y(K.target.value),className:ee,style:Z}),e.jsxs("div",{children:[e.jsx("input",{type:"tel",required:!0,placeholder:"Phone number",value:_,onChange:K=>b(K.target.value),className:ee,style:Z}),e.jsx("p",{className:`text-xs mt-1 ${D?"text-[#8a7869]":"text-gray-400"}`,children:d?"Your phone number is your password":"Your phone number will be used as your password"})]}),T&&e.jsx("p",{className:"text-red-600 text-sm",children:T}),e.jsx("button",{type:"submit",disabled:j,className:`w-full py-2.5 font-medium rounded-lg disabled:opacity-50 transition-colors ${D?"text-black hover:opacity-90 tracking-wider uppercase text-sm":"bg-blue-600 text-white hover:bg-blue-700"}`,style:D?{backgroundColor:R}:void 0,children:j?d?"Signing in...":"Creating account...":d?"Sign In":"Create Account"}),e.jsx("button",{type:"button",onClick:()=>{h(!d),E("")},className:"w-full text-center text-sm hover:opacity-80 transition-opacity",style:{color:R},children:d?"Don't have an account? Sign up":"Already have an account? Sign in"}),!A&&!d&&e.jsx("button",{type:"button",onClick:a,className:`w-full py-2 text-sm transition-colors ${D?"text-[#7a6758] hover:text-[#201915]":"text-gray-500 hover:text-gray-700"}`,children:"Skip for now"})]}),e.jsx("p",{className:`text-xs text-center mt-1 ${D?"text-[#8a7869]":"text-gray-400"}`,children:"By registering you agree to receive property updates. You can unsubscribe anytime."})]})})}function b6e({siteConfig:s,pagePath:t}){const r=s.agent;if(!r)return null;const n=`https://${s.subdomainSlug}.thelocalmove.com`,i=(r.areas_served||"").split(/,|;|\|/).map(T=>T.trim()).filter(Boolean),l=i[0]||"",[o,c]=l.split(/,\s*/),d=(r.bio||"").match(/\b(CRS|GRI|ABR|CNE|SRES|SRS|RENE|MRP|PSA|AHWD|C2EX|CIPS|CRB|e-?PRO)\b/gi)||[],h=[...new Set(d.map(T=>T.toUpperCase()))],m=s.testimonials||[],p=m.length?{"@type":"AggregateRating",ratingValue:(m.reduce((T,E)=>T+(E.rating||5),0)/m.length).toFixed(1),reviewCount:m.length,bestRating:5,worstRating:1}:void 0,x=[r.facebook_url,r.instagram_url,r.linkedin_url].filter(Boolean),y={"@context":"https://schema.org","@type":["RealEstateAgent","LocalBusiness"],"@id":`${n}/#agent`,name:r.full_name,url:n,image:r.avatar_url||s.ogImageUrl||void 0,logo:s.ogImageUrl||r.avatar_url||void 0,email:r.email,telephone:r.phone||void 0,jobTitle:r.title||"Real Estate Agent",description:r.bio||`${r.full_name} is a trusted local real estate professional${l?` serving ${l}`:""}.`,priceRange:"$$",...x.length&&{sameAs:x},...s.brokerageLegalName&&{worksFor:{"@type":"RealEstateAgent",name:s.brokerageLegalName,...s.brokerageLicenseNumber&&{identifier:s.brokerageLicenseNumber}}},...s.agentLicenseNumber&&{identifier:s.agentLicenseNumber},...o&&{address:{"@type":"PostalAddress",addressLocality:o,...c&&{addressRegion:c},addressCountry:"US"}},...i.length&&{areaServed:i.map(T=>{const[E,A]=T.split(/,\s*/);return{"@type":"City",name:E,...A&&{containedInPlace:{"@type":"State",name:A}}}})},...p&&{aggregateRating:p},...m.length&&{review:m.slice(0,10).map(T=>({"@type":"Review",author:{"@type":"Person",name:T.name},reviewBody:T.text,reviewRating:{"@type":"Rating",ratingValue:T.rating||5,bestRating:5,worstRating:1},...T.location&&{locationCreated:{"@type":"Place",name:T.location}}}))}},_={"@context":"https://schema.org","@type":"Person","@id":`${n}/#person`,name:r.full_name,jobTitle:r.title||"Real Estate Agent",description:r.bio||void 0,image:r.avatar_url||void 0,url:n,email:r.email,telephone:r.phone||void 0,...x.length&&{sameAs:x},...r.years_experience&&{knowsAbout:["Residential Real Estate","Home Buying","Home Selling",l?`${l} Real Estate`:"Local Real Estate"].filter(Boolean)},...h.length&&{hasCredential:h.map(T=>({"@type":"EducationalOccupationalCredential",credentialCategory:"designation",name:T}))},...s.brokerageLegalName&&{worksFor:{"@type":"Organization",name:s.brokerageLegalName}}},b={"@context":"https://schema.org","@type":"WebSite","@id":`${n}/#website`,name:s.siteTitle||`${r.full_name} Real Estate`,url:n,publisher:{"@id":`${n}/#agent`},potentialAction:{"@type":"SearchAction",target:{"@type":"EntryPoint",urlTemplate:`${n}/search?q={search_term_string}`},"query-input":"required name=search_term_string"}},j=[{name:"Search Homes",description:`Browse all current MLS listings${l?` in ${l}`:""}.`,path:"/search"},{name:"Featured Areas",description:"Explore featured neighborhoods, cities, and communities.",path:"/areas"},{name:"Sold Properties",description:"See recently sold homes and local market activity.",path:"/sold"},{name:"Home Valuation",description:"Get a free, no-obligation estimate of what your home is worth.",path:"/sell"},{name:"About",description:`Learn more about ${r.full_name}${s.brokerageLegalName?` and ${s.brokerageLegalName}`:""}.`,path:"/about"},{name:"Contact",description:`Get in touch with ${r.full_name} for buying, selling, or relocation help.`,path:"/contact"}],k={"@context":"https://schema.org","@type":"ItemList","@id":`${n}/#nav`,name:"Main Navigation",itemListElement:j.map((T,E)=>({"@type":"SiteNavigationElement",position:E+1,name:T.name,description:T.description,url:`${n}${T.path}`}))};return e.jsxs(el,{children:[e.jsx("script",{type:"application/ld+json",children:JSON.stringify(y)}),e.jsx("script",{type:"application/ld+json",children:JSON.stringify(_)}),e.jsx("script",{type:"application/ld+json",children:JSON.stringify(b)}),e.jsx("script",{type:"application/ld+json",children:JSON.stringify(k)})]})}function xXs({items:s,siteConfig:t}){const r=`https://${t.subdomainSlug}.thelocalmove.com`,n={"@context":"https://schema.org","@type":"BreadcrumbList",itemListElement:s.map((a,i)=>({"@type":"ListItem",position:i+1,name:a.name,item:`${r}${a.path}`}))};return e.jsx(el,{children:e.jsx("script",{type:"application/ld+json",children:JSON.stringify(n)})})}function yXs({listing:s,siteConfig:t}){var a;const r=`https://${t.subdomainSlug}.thelocalmove.com`,n={"@context":"https://schema.org","@type":"SingleFamilyResidence",name:`${s.address}, ${s.city}, ${s.state} ${s.zip}`,url:`${r}/listing/${s.mlsNumber}`,image:((a=s.photos)==null?void 0:a[0])||void 0,numberOfRooms:s.bedrooms,numberOfBathroomsTotal:s.bathrooms,floorSize:s.sqft?{"@type":"QuantitativeValue",value:s.sqft,unitCode:"FTK"}:void 0,address:{"@type":"PostalAddress",streetAddress:s.address,addressLocality:s.city,addressRegion:s.state,postalCode:s.zip},...s.latitude&&s.longitude&&{geo:{"@type":"GeoCoordinates",latitude:s.latitude,longitude:s.longitude}},offers:{"@type":"Offer",price:s.price,priceCurrency:"USD",availability:s.status==="Active"?"https://schema.org/InStock":"https://schema.org/SoldOut"},...s.yearBuilt&&{yearBuilt:s.yearBuilt}};return e.jsx(el,{children:e.jsx("script",{type:"application/ld+json",children:JSON.stringify(n)})})}function IUs({faqs:s}){if(!s.length)return null;const t={"@context":"https://schema.org","@type":"FAQPage",mainEntity:s.map(r=>({"@type":"Question",name:r.question,acceptedAnswer:{"@type":"Answer",text:r.answer}}))};return e.jsx(el,{children:e.jsx("script",{type:"application/ld+json",children:JSON.stringify(t)})})}function vXs({title:s,description:t,publishedAt:r,imageUrl:n,slug:a,siteConfig:i}){const l=`https://${i.subdomainSlug}.thelocalmove.com`,o=i.agent,c={"@context":"https://schema.org","@type":"Article",headline:s,description:t,url:`${l}/blog/${a}`,datePublished:r,...n&&{image:n},author:o?{"@type":"Person",name:o.full_name,url:l}:void 0,publisher:{"@type":"Organization",name:i.siteTitle||(o==null?void 0:o.full_name)||"Agent",url:l}};return e.jsx(el,{children:e.jsx("script",{type:"application/ld+json",children:JSON.stringify(c)})})}function _6e({siteConfig:s}){var x;const t=s.agent;if(!t)return null;const r=t.full_name,n=s.brokerageLegalName||"their brokerage",a=t.areas_served||"the local market",i=((x=a.split(/,|;|\|/)[0])==null?void 0:x.trim())||"the local area",l=t.years_experience,o=t.phone||"",c=t.email,d=s.agentLicenseNumber,h=(t.bio||"").match(/\b(CRS|GRI|ABR|CNE|SRES|SRS|RENE|MRP|PSA|AHWD|C2EX|CIPS|CRB|e-?PRO)\b/gi)||[],m=[...new Set(h.map(y=>y.toUpperCase()))],p=[{question:`Who is ${r}?`,answer:`${r} is a ${t.title||"REALTOR®"} with ${n}${l?`, with ${l}+ years of local real estate experience`:""} serving ${a}. ${t.bio?t.bio.slice(0,280):""}`.trim()},{question:`What areas does ${r} serve?`,answer:`${r} serves ${a} and surrounding communities. Whether you're buying, selling, relocating, or downsizing, ${r.split(" ")[0]} provides expert local guidance.`},{question:`How can I contact ${r}?`,answer:`You can reach ${r} by ${o?`phone at ${o}, `:""}email at ${c}, or by booking a consultation directly through this website.`},...m.length?[{question:`What real estate designations does ${r} hold?`,answer:`${r} holds the following professional designations: ${m.join(", ")}. These designations represent advanced training in specialized areas of real estate.`}]:[],...d?[{question:`Is ${r} a licensed real estate agent?`,answer:`Yes, ${r} is a fully licensed real estate professional (License #${d}) with ${n}.`}]:[],{question:`How do I search for homes for sale in ${i}?`,answer:`Use the property search on this site to view all current MLS listings in ${i}. You can filter by price, bedrooms, neighborhood, school district, and more. Save searches to receive instant email alerts when new homes match your criteria.`},{question:`What is the home buying process like in ${i}?`,answer:`${r} guides buyers through every step: getting pre-approved, searching MLS listings, touring homes, writing competitive offers, navigating inspections and appraisals, and closing on schedule. Contact ${r.split(" ")[0]} for a free buyer consultation.`},{question:`How do I find out what my home is worth in ${i}?`,answer:`Request a free, no-obligation home valuation from ${r}. ${r.split(" ")[0]} provides a comparative market analysis (CMA) using recent sold comps and current market conditions in ${i}.`}];return e.jsx(IUs,{faqs:p})}const YWe="ls_visitor_geo",PUs=1e3*60*60;function LUs(s){return s==="/"?"home":s==="/search"?"search":s==="/sell"?"sell":s==="/blog"?"blog":s.startsWith("/listing/")?"listing":s.startsWith("/homes-for-sale-in-")?"city":s.startsWith("/homes-in-")?"subdivision":s==="/dashboard"?"dashboard":"other"}function DUs(s,t){switch(t){case"home":return"Home";case"search":return"Search";case"sell":return"Sell Your Home";case"blog":return"Blog";case"listing":return`Listing ${s.split("/listing/")[1]||""}`;case"city":return s.replace("/homes-for-sale-in-","").split("-").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ");case"subdivision":return s.replace("/homes-in-","").split("-").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ");case"dashboard":return"My Dashboard";default:return s}}async function RUs(){try{const s=localStorage.getItem(YWe);if(s){const t=JSON.parse(s);if(Date.now()-t.ts{i.current||(i.current=!0,RUs().then(l=>{a.current=l}))},[]),S.useEffect(()=>{if(!(s!=null&&s.id))return;const l=r.pathname;if(l===n.current)return;n.current=l;const o=LUs(l),c=DUs(l,o),d=localStorage.getItem(`ls_visitor_fp_${s.id}`)||null,h=a.current;V.from("lead_site_page_views").insert({lead_site_id:s.id,page_type:o,page_path:l,page_title:c,visitor_fingerprint:d,auth_user_id:t||null,visitor_city:(h==null?void 0:h.city)||null,visitor_region:(h==null?void 0:h.region)||null,visitor_country:(h==null?void 0:h.country)||null,visitor_lat:(h==null?void 0:h.lat)||null,visitor_lng:(h==null?void 0:h.lng)||null}).then(({error:m})=>{m&&console.error("[PageTracking] insert failed:",m.message)})},[r.pathname,s==null?void 0:s.id,t])}const OUs=3e4;function j6e(s,t){const r=Vc(),n=S.useRef(null),a=S.useRef(null),i=S.useRef(0),l=r.pathname,o=FUs(l),c=BUs(l,o),d=o==="listing"&&l.split("/listing/")[1]||null;S.useEffect(()=>{if(!(s!=null&&s.id)||!t)return;o==="listing"&&(i.current+=1);const h=localStorage.getItem(`ls_visitor_fp_${s.id}`)||null,m=async()=>{const{data:p,error:x}=await V.from("lead_site_active_visitors").upsert({lead_site_id:s.id,auth_user_id:t,visitor_fingerprint:h,current_page_path:l,current_page_title:c,current_mls_number:d,last_seen_at:new Date().toISOString(),listing_views_count:i.current},{onConflict:"lead_site_id,coalesce(auth_user_id::text,visitor_fingerprint,'')"}).select("id, notified_agent").single();!x&&p&&(n.current=p.id,i.current>=2&&!p.notified_agent&&V.functions.invoke("lead-site-presence-notify",{body:{visitor_id:p.id,lead_site_id:s.id}}).catch(()=>{}))};return m(),a.current&&clearInterval(a.current),a.current=setInterval(m,OUs),()=>{a.current&&clearInterval(a.current)}},[s==null?void 0:s.id,t,l]),S.useEffect(()=>{if(!(s!=null&&s.id)||!t)return;const h=()=>{n.current&&V.from("lead_site_active_visitors").delete().eq("id",n.current).then(()=>{})};return window.addEventListener("beforeunload",h),()=>window.removeEventListener("beforeunload",h)},[s==null?void 0:s.id,t])}function FUs(s){return s==="/"?"home":s==="/search"?"search":s.startsWith("/listing/")?"listing":s.startsWith("/homes-for-sale-in-")?"city":s.startsWith("/homes-in-")?"subdivision":"other"}function BUs(s,t){switch(t){case"home":return"Home";case"search":return"Search";case"listing":return`Listing ${s.split("/listing/")[1]||""}`;case"city":return s.replace("/homes-for-sale-in-","").split("-").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ");case"subdivision":return s.replace("/homes-in-","").split("-").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ");default:return s}}const ka=Number.isFinite||function(s){return typeof s=="number"&&isFinite(s)},zUs=Number.isSafeInteger||function(s){return typeof s=="number"&&Math.abs(s)<=$Us},$Us=Number.MAX_SAFE_INTEGER||9007199254740991;let ci=function(s){return s.NETWORK_ERROR="networkError",s.MEDIA_ERROR="mediaError",s.KEY_SYSTEM_ERROR="keySystemError",s.MUX_ERROR="muxError",s.OTHER_ERROR="otherError",s}({}),yr=function(s){return s.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",s.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",s.KEY_SYSTEM_NO_SESSION="keySystemNoSession",s.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",s.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",s.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",s.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",s.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",s.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",s.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",s.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",s.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",s.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",s.MANIFEST_LOAD_ERROR="manifestLoadError",s.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",s.MANIFEST_PARSING_ERROR="manifestParsingError",s.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",s.LEVEL_EMPTY_ERROR="levelEmptyError",s.LEVEL_LOAD_ERROR="levelLoadError",s.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",s.LEVEL_PARSING_ERROR="levelParsingError",s.LEVEL_SWITCH_ERROR="levelSwitchError",s.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",s.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",s.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",s.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",s.FRAG_LOAD_ERROR="fragLoadError",s.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",s.FRAG_DECRYPT_ERROR="fragDecryptError",s.FRAG_PARSING_ERROR="fragParsingError",s.FRAG_GAP="fragGap",s.REMUX_ALLOC_ERROR="remuxAllocError",s.KEY_LOAD_ERROR="keyLoadError",s.KEY_LOAD_TIMEOUT="keyLoadTimeOut",s.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",s.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",s.BUFFER_APPEND_ERROR="bufferAppendError",s.BUFFER_APPENDING_ERROR="bufferAppendingError",s.BUFFER_STALLED_ERROR="bufferStalledError",s.BUFFER_FULL_ERROR="bufferFullError",s.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",s.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",s.ASSET_LIST_LOAD_ERROR="assetListLoadError",s.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",s.ASSET_LIST_PARSING_ERROR="assetListParsingError",s.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",s.INTERNAL_EXCEPTION="internalException",s.INTERNAL_ABORTED="aborted",s.ATTACH_MEDIA_ERROR="attachMediaError",s.UNKNOWN="unknown",s}({}),vt=function(s){return s.MEDIA_ATTACHING="hlsMediaAttaching",s.MEDIA_ATTACHED="hlsMediaAttached",s.MEDIA_DETACHING="hlsMediaDetaching",s.MEDIA_DETACHED="hlsMediaDetached",s.MEDIA_ENDED="hlsMediaEnded",s.STALL_RESOLVED="hlsStallResolved",s.BUFFER_RESET="hlsBufferReset",s.BUFFER_CODECS="hlsBufferCodecs",s.BUFFER_CREATED="hlsBufferCreated",s.BUFFER_APPENDING="hlsBufferAppending",s.BUFFER_APPENDED="hlsBufferAppended",s.BUFFER_EOS="hlsBufferEos",s.BUFFERED_TO_END="hlsBufferedToEnd",s.BUFFER_FLUSHING="hlsBufferFlushing",s.BUFFER_FLUSHED="hlsBufferFlushed",s.MANIFEST_LOADING="hlsManifestLoading",s.MANIFEST_LOADED="hlsManifestLoaded",s.MANIFEST_PARSED="hlsManifestParsed",s.LEVEL_SWITCHING="hlsLevelSwitching",s.LEVEL_SWITCHED="hlsLevelSwitched",s.LEVEL_LOADING="hlsLevelLoading",s.LEVEL_LOADED="hlsLevelLoaded",s.LEVEL_UPDATED="hlsLevelUpdated",s.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",s.LEVELS_UPDATED="hlsLevelsUpdated",s.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",s.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",s.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",s.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",s.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",s.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",s.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",s.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",s.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",s.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",s.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",s.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",s.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",s.CUES_PARSED="hlsCuesParsed",s.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",s.INIT_PTS_FOUND="hlsInitPtsFound",s.FRAG_LOADING="hlsFragLoading",s.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",s.FRAG_LOADED="hlsFragLoaded",s.FRAG_DECRYPTED="hlsFragDecrypted",s.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",s.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",s.FRAG_PARSING_METADATA="hlsFragParsingMetadata",s.FRAG_PARSED="hlsFragParsed",s.FRAG_BUFFERED="hlsFragBuffered",s.FRAG_CHANGED="hlsFragChanged",s.FPS_DROP="hlsFpsDrop",s.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",s.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",s.ERROR="hlsError",s.DESTROYING="hlsDestroying",s.KEY_LOADING="hlsKeyLoading",s.KEY_LOADED="hlsKeyLoaded",s.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",s.BACK_BUFFER_REACHED="hlsBackBufferReached",s.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",s.ASSET_LIST_LOADING="hlsAssetListLoading",s.ASSET_LIST_LOADED="hlsAssetListLoaded",s.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",s.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",s.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",s.INTERSTITIAL_STARTED="hlsInterstitialStarted",s.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",s.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",s.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",s.INTERSTITIAL_ENDED="hlsInterstitialEnded",s.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",s.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",s.EVENT_CUE_ENTER="hlsEventCueEnter",s}({});var Vo={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},Ba={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};class I6{constructor(t,r=0,n=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=t,this.alpha_=t?Math.exp(Math.log(.5)/t):0,this.estimate_=r,this.totalWeight_=n}sample(t,r){const n=Math.pow(this.alpha_,t);this.estimate_=r*(1-n)+n*this.estimate_,this.totalWeight_+=t}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const t=1-Math.pow(this.alpha_,this.totalWeight_);if(t)return this.estimate_/t}return this.estimate_}}class UUs{constructor(t,r,n,a=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=n,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new I6(t),this.fast_=new I6(r),this.defaultTTFB_=a,this.ttfb_=new I6(t)}update(t,r){const{slow_:n,fast_:a,ttfb_:i}=this;n.halfLife!==t&&(this.slow_=new I6(t,n.getEstimate(),n.getTotalWeight())),a.halfLife!==r&&(this.fast_=new I6(r,a.getEstimate(),a.getTotalWeight())),i.halfLife!==t&&(this.ttfb_=new I6(t,i.getEstimate(),i.getTotalWeight()))}sample(t,r){t=Math.max(t,this.minDelayMs_);const n=8*r,a=t/1e3,i=n/a;this.fast_.sample(a,i),this.slow_.sample(a,i)}sampleTTFB(t){const r=t/1e3,n=Math.sqrt(2)*Math.exp(-Math.pow(r,2)/2);this.ttfb_.sample(n,Math.max(t,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}}function qUs(s,t,r){return(t=HUs(t))in s?Object.defineProperty(s,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):s[t]=r,s}function Ec(){return Ec=Object.assign?Object.assign.bind():function(s){for(var t=1;t`):ZN}function XWe(s,t,r){return t[s]?t[s].bind(t):WUs(s,r)}const eCe=J4e();function KUs(s,t,r){const n=J4e();if(typeof console=="object"&&s===!0||typeof s=="object"){const a=["debug","log","info","warn","error"];a.forEach(i=>{n[i]=XWe(i,s,r)});try{n.log(`Debug logs enabled for "${t}" in hls.js version 1.6.16`)}catch{return J4e()}a.forEach(i=>{eCe[i]=XWe(i,s)})}else Ec(eCe,n);return n}const gc=eCe;function TS(s=!0){return typeof self>"u"?void 0:(s||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function YUs(s){return typeof self<"u"&&s===self.ManagedMediaSource}function Ovt(s,t){const r=Object.keys(s),n=Object.keys(t),a=r.length,i=n.length;return!a||!i||a===i&&!r.some(l=>n.indexOf(l)===-1)}function w0(s,t=!1){if(typeof TextDecoder<"u"){const d=new TextDecoder("utf-8").decode(s);if(t){const h=d.indexOf("\0");return h!==-1?d.substring(0,h):d}return d.replace(/\0/g,"")}const r=s.length;let n,a,i,l="",o=0;for(;o>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:l+=String.fromCharCode(n);break;case 12:case 13:a=s[o++],l+=String.fromCharCode((n&31)<<6|a&63);break;case 14:a=s[o++],i=s[o++],l+=String.fromCharCode((n&15)<<12|(a&63)<<6|(i&63)<<0);break}}return l}function Pf(s){let t="";for(let r=0;r1||a===1&&(r=this.levelkeys[n[0]])!=null&&r.encrypted)return!0}return!1}get programDateTime(){return this._programDateTime===null&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(t){if(!ka(t)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=t}get ref(){return dh(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(t){this.setStart(this.start+t)}setStart(t){this.start=t,this._ref&&(this._ref.start=t)}setDuration(t){this.duration=t,this._ref&&(this._ref.duration=t)}setKeyFormat(t){const r=this.levelkeys;if(r){var n;const a=r[t];a&&!((n=this._decryptdata)!=null&&n.keyId)&&(this._decryptdata=a.getDecryptData(this.sn,r))}}abortRequests(){var t,r;(t=this.loader)==null||t.abort(),(r=this.keyLoader)==null||r.abort()}setElementaryStreamInfo(t,r,n,a,i,l=!1){const{elementaryStreams:o}=this,c=o[t];if(!c){o[t]={startPTS:r,endPTS:n,startDTS:a,endDTS:i,partial:l};return}c.startPTS=Math.min(c.startPTS,r),c.endPTS=Math.max(c.endPTS,n),c.startDTS=Math.min(c.startDTS,a),c.endDTS=Math.max(c.endDTS,i)}}class QUs extends Bvt{constructor(t,r,n,a,i){super(n),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.duration=t.decimalFloatingPoint("DURATION"),this.gap=t.bool("GAP"),this.independent=t.bool("INDEPENDENT"),this.relurl=t.enumeratedString("URI"),this.fragment=r,this.index=a;const l=t.enumeratedString("BYTERANGE");l&&this.setByteRange(l,i),i&&(this.fragOffset=i.fragOffset+i.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:t}=this;return!!(t.audio||t.video||t.audiovideo)}}function zvt(s,t){const r=Object.getPrototypeOf(s);if(r){const n=Object.getOwnPropertyDescriptor(r,t);return n||zvt(r,t)}}function JUs(s,t){const r=zvt(s,t);r&&(r.enumerable=!0,Object.defineProperty(s,t,r))}const JWe=Math.pow(2,32)-1,eqs=[].push,$vt={video:1,audio:2,id3:3,text:4};function rm(s){return String.fromCharCode.apply(null,s)}function Uvt(s,t){const r=s[t]<<8|s[t+1];return r<0?65536+r:r}function ro(s,t){const r=qvt(s,t);return r<0?4294967296+r:r}function eKe(s,t){let r=ro(s,t);return r*=Math.pow(2,32),r+=ro(s,t+4),r}function qvt(s,t){return s[t]<<24|s[t+1]<<16|s[t+2]<<8|s[t+3]}function tqs(s){const t=s.byteLength;for(let r=0;r8&&s[r+4]===109&&s[r+5]===111&&s[r+6]===111&&s[r+7]===102)return!0;r=n>1?r+n:t}return!1}function zo(s,t){const r=[];if(!t.length)return r;const n=s.byteLength;for(let a=0;a1?a+i:n;if(l===t[0])if(t.length===1)r.push(s.subarray(a+8,o));else{const c=zo(s.subarray(a+8,o),t.slice(1));c.length&&eqs.apply(r,c)}a=o}return r}function sqs(s){const t=[],r=s[0];let n=8;const a=ro(s,n);n+=4;let i=0,l=0;r===0?(i=ro(s,n),l=ro(s,n+4),n+=8):(i=eKe(s,n),l=eKe(s,n+8),n+=16),n+=2;let o=s.length+l;const c=Uvt(s,n);n+=2;for(let d=0;d>>31===1)return gc.warn("SIDX has hierarchical references (not supported)"),null;const y=ro(s,h);h+=4,t.push({referenceSize:p,subsegmentDuration:y,info:{duration:y/a,start:o,end:o+p-1}}),o+=p,h+=4,n=h}return{earliestPresentationTime:i,timescale:a,version:r,referencesCount:c,references:t}}function Vvt(s){const t=[],r=zo(s,["moov","trak"]);for(let a=0;a{const i=ro(a,4),l=t[i];l&&(l.default={duration:ro(a,12),flags:ro(a,20)})}),t}function rqs(s){const t=s.subarray(8),r=t.subarray(86),n=rm(t.subarray(4,8));let a=n,i;const l=n==="enca"||n==="encv";if(l){const d=zo(t,[n])[0].subarray(n==="enca"?28:78);zo(d,["sinf"]).forEach(m=>{const p=zo(m,["schm"])[0];if(p){const x=rm(p.subarray(4,8));if(x==="cbcs"||x==="cenc"){const y=zo(m,["frma"])[0];y&&(a=rm(y))}}})}const o=a;switch(a){case"avc1":case"avc2":case"avc3":case"avc4":{const c=zo(r,["avcC"])[0];c&&c.length>3&&(a+="."+cV(c[1])+cV(c[2])+cV(c[3]),i=lV(o==="avc1"?"dva1":"dvav",r));break}case"mp4a":{const c=zo(t,[n])[0],d=zo(c.subarray(28),["esds"])[0];if(d&&d.length>7){let h=4;if(d[h++]!==3)break;h=Owe(d,h),h+=2;const m=d[h++];if(m&128&&(h+=2),m&64&&(h+=d[h++]),d[h++]!==4)break;h=Owe(d,h);const p=d[h++];if(p===64)a+="."+cV(p);else break;if(h+=12,d[h++]!==5)break;h=Owe(d,h);const x=d[h++];let y=(x&248)>>3;y===31&&(y+=1+((x&7)<<3)+((d[h]&224)>>5)),a+="."+y}break}case"hvc1":case"hev1":{const c=zo(r,["hvcC"])[0];if(c&&c.length>12){const d=c[1],h=["","A","B","C"][d>>6],m=d&31,p=ro(c,2),x=(d&32)>>5?"H":"L",y=c[12],_=c.subarray(6,12);a+="."+h+m,a+="."+nqs(p).toString(16).toUpperCase(),a+="."+x+y;let b="";for(let j=_.length;j--;){const k=_[j];(k||b)&&(b="."+k.toString(16).toUpperCase()+b)}a+=b}i=lV(o=="hev1"?"dvhe":"dvh1",r);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{a=lV(a,r)||a;break}case"vp09":{const c=zo(r,["vpcC"])[0];if(c&&c.length>6){const d=c[4],h=c[5],m=c[6]>>4&15;a+="."+Ub(d)+"."+Ub(h)+"."+Ub(m)}break}case"av01":{const c=zo(r,["av1C"])[0];if(c&&c.length>2){const d=c[1]>>>5,h=c[1]&31,m=c[2]>>>7?"H":"M",p=(c[2]&64)>>6,x=(c[2]&32)>>5,y=d===2&&p?x?12:10:p?10:8,_=(c[2]&16)>>4,b=(c[2]&8)>>3,j=(c[2]&4)>>2,k=c[2]&3;a+="."+d+"."+Ub(h)+m+"."+Ub(y)+"."+_+"."+b+j+k+"."+Ub(1)+"."+Ub(1)+"."+Ub(1)+"."+0,i=lV("dav1",r)}break}}return{codec:a,encrypted:l,supplemental:i}}function lV(s,t){const r=zo(t,["dvvC"]),n=r.length?r[0]:zo(t,["dvcC"])[0];if(n){const a=n[2]>>1&127,i=n[2]<<5&32|n[3]>>3&31;return s+"."+Ub(a)+"."+Ub(i)}}function nqs(s){let t=0;for(let r=0;r<32;r++)t|=(s>>r&1)<<31-r;return t>>>0}function Owe(s,t){const r=t+5;for(;s[t++]&128&&t{const i=n.subarray(8,24);i.some(l=>l!==0)||(gc.log(`[eme] Patching keyId in 'enc${a?"a":"v"}>sinf>>tenc' box: ${Pf(i)} -> ${Pf(r)}`),n.set(r,8))})}function iqs(s){const t=[];return Hvt(s,r=>t.push(r.subarray(8,24))),t}function Hvt(s,t){zo(s,["moov","trak"]).forEach(n=>{const a=zo(n,["mdia","minf","stbl","stsd"])[0];if(!a)return;const i=a.subarray(8);let l=zo(i,["enca"]);const o=l.length>0;o||(l=zo(i,["encv"])),l.forEach(c=>{const d=o?c.subarray(28):c.subarray(78);zo(d,["sinf"]).forEach(m=>{const p=Gvt(m);p&&t(p,o)})})})}function Gvt(s){const t=zo(s,["schm"])[0];if(t){const r=rm(t.subarray(4,8));if(r==="cbcs"||r==="cenc"){const n=zo(s,["schi","tenc"])[0];if(n)return n}}}function oqs(s,t,r){const n={},a=zo(s,["moof","traf"]);for(let i=0;in[i].duration)){let i=1/0,l=0;const o=zo(s,["sidx"]);for(let c=0;cm+p.info.duration||0,0);l=Math.max(l,h+d.earliestPresentationTime/d.timescale)}}l&&ka(l)&&Object.keys(n).forEach(c=>{n[c].duration||(n[c].duration=l*n[c].timescale-n[c].start)})}return n}function lqs(s){const t={valid:null,remainder:null},r=zo(s,["moof"]);if(r.length<2)return t.remainder=s,t;const n=r[r.length-1];return t.valid=s.slice(0,n.byteOffset-8),t.remainder=s.slice(n.byteOffset-8),t}function tv(s,t){const r=new Uint8Array(s.length+t.length);return r.set(s),r.set(t,s.length),r}function tKe(s,t){const r=[],n=t.samples,a=t.timescale,i=t.id;let l=!1;return zo(n,["moof"]).map(c=>{const d=c.byteOffset-8;zo(c,["traf"]).map(m=>{const p=zo(m,["tfdt"]).map(x=>{const y=x[0];let _=ro(x,4);return y===1&&(_*=Math.pow(2,32),_+=ro(x,8)),_/a})[0];return p!==void 0&&(s=p),zo(m,["tfhd"]).map(x=>{const y=ro(x,4),_=ro(x,0)&16777215,b=(_&1)!==0,j=(_&2)!==0,k=(_&8)!==0;let T=0;const E=(_&16)!==0;let A=0;const D=(_&32)!==0;let R=8;y===i&&(b&&(R+=8),j&&(R+=4),k&&(T=ro(x,R),R+=4),E&&(A=ro(x,R),R+=4),D&&(R+=4),t.type==="video"&&(l=uye(t.codec)),zo(m,["trun"]).map(z=>{const O=z[0],$=ro(z,0)&16777215,ee=($&1)!==0;let Z=0;const J=($&4)!==0,K=($&256)!==0;let re=0;const ie=($&512)!==0;let ce=0;const ne=($&1024)!==0,le=($&2048)!==0;let be=0;const fe=ro(z,4);let je=8;ee&&(Z=ro(z,je),je+=4),J&&(je+=4);let ve=Z+d;for(let We=0;We>1&63;return r===39||r===40}else return(t&31)===6}function S6e(s,t,r,n){const a=Wvt(s);let i=0;i+=t;let l=0,o=0,c=0;for(;i=a.length)break;c=a[i++],l+=c}while(c===255);o=0;do{if(i>=a.length)break;c=a[i++],o+=c}while(c===255);const d=a.length-i;let h=i;if(od){gc.error(`Malformed SEI payload. ${o} is too small, only ${d} bytes left to parse.`);break}if(l===4){if(a[h++]===181){const p=Uvt(a,h);if(h+=2,p===49){const x=ro(a,h);if(h+=4,x===1195456820){const y=a[h++];if(y===3){const _=a[h++],b=31&_,j=64&_,k=j?2+b*3:0,T=new Uint8Array(k);if(j){T[0]=_;for(let E=1;E16){const m=[];for(let y=0;y<16;y++){const _=a[h++].toString(16);m.push(_.length==1?"0"+_:_),(y===3||y===5||y===7||y===9)&&m.push("-")}const p=o-16,x=new Uint8Array(p);for(let y=0;y>24&255,i[1]=n>>16&255,i[2]=n>>8&255,i[3]=n&255,i.set(s,4),a=0,n=8;a0?(i=new Uint8Array(4),t.length>0&&new DataView(i.buffer).setUint32(0,t.length,!1)):i=new Uint8Array;const l=new Uint8Array(4);return r.byteLength>0&&new DataView(l.buffer).setUint32(0,r.byteLength,!1),uqs([112,115,115,104],new Uint8Array([n,0,0,0]),s,i,a,l,r)}function mqs(s){const t=[];if(s instanceof ArrayBuffer){const r=s.byteLength;let n=0;for(;n+32>>24;if(i!==0&&i!==1)return{offset:r,size:t};const l=s.buffer,o=Pf(new Uint8Array(l,r+12,16));let c=null,d=null,h=0;if(i===0)h=28;else{const p=s.getUint32(28);if(!p||n<32+p*16)return{offset:r,size:t};c=[];for(let x=0;x/\(Windows.+Firefox\//i.test(navigator.userAgent),XL={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,dav1:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1}};function C6e(s,t){const r=XL[t];return!!r&&!!r[s.slice(0,4)]}function vB(s,t,r=!0){return!s.split(",").some(n=>!T6e(n,t,r))}function T6e(s,t,r=!0){var n;const a=TS(r);return(n=a==null?void 0:a.isTypeSupported(bB(s,t)))!=null?n:!1}function bB(s,t){return`${t}/mp4;codecs=${s}`}function sKe(s){if(s){const t=s.substring(0,4);return XL.video[t]}return 2}function ppe(s){const t=Kvt();return s.split(",").reduce((r,n)=>{const i=t&&uye(n)?9:XL.video[n];return i?(i*2+r)/(r?3:2):(XL.audio[n]+r)/(r?2:1)},0)}const Fwe={};function pqs(s,t=!0){if(Fwe[s])return Fwe[s];const r={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[s];for(let a=0;apqs(r.toLowerCase(),t))}function xqs(s,t){const r=[];if(s){const n=s.split(",");for(let a=0;a4||["ac-3","ec-3","alac","fLaC","Opus"].indexOf(s)!==-1)&&(rKe(s,"audio")||rKe(s,"video")))return s;if(t){const r=t.split(",");if(r.length>1){if(s){for(let n=r.length;n--;)if(r[n].substring(0,4)===s.substring(0,4))return r[n]}return r[0]}}return t||s}function rKe(s,t){return C6e(s,t)&&T6e(s,t)}function yqs(s){const t=s.split(",");for(let r=0;r2&&n[0]==="avc1"&&(t[r]=`avc1.${parseInt(n[1]).toString(16)}${("000"+parseInt(n[2]).toString(16)).slice(-4)}`)}return t.join(",")}function vqs(s){if(s.startsWith("av01.")){const t=s.split("."),r=["0","111","01","01","01","0"];for(let n=t.length;n>4&&n<10;n++)t[n]=r[n-4];return t.join(".")}return s}function nKe(s){const t=TS(s)||{isTypeSupported:()=>!1};return{mpeg:t.isTypeSupported("audio/mpeg"),mp3:t.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:t.isTypeSupported('audio/mp4; codecs="ac-3"')}}function tCe(s){return s.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const bqs={supported:!0,powerEfficient:!0,smooth:!0},_qs={supported:!1,smooth:!1,powerEfficient:!1},Yvt={supported:!0,configurations:[],decodingInfoResults:[bqs]};function Zvt(s,t){return{supported:!1,configurations:t,decodingInfoResults:[_qs],error:s}}function wqs(s,t,r,n,a,i){const l=s.videoCodec,o=s.audioCodec?s.audioGroups:null,c=i==null?void 0:i.audioCodec,d=i==null?void 0:i.channels,h=d?parseInt(d):c?1/0:2;let m=null;if(o!=null&&o.length)try{o.length===1&&o[0]?m=t.groups[o[0]].channels:m=o.reduce((p,x)=>{if(x){const y=t.groups[x];if(!y)throw new Error(`Audio track group ${x} not found`);Object.keys(y.channels).forEach(_=>{p[_]=(p[_]||0)+y.channels[_]})}return p},{2:0})}catch{return!0}return l!==void 0&&(l.split(",").some(p=>uye(p))||s.width>1920&&s.height>1088||s.height>1920&&s.width>1088||s.frameRate>Math.max(n,30)||s.videoRange!=="SDR"&&s.videoRange!==r||s.bitrate>Math.max(a,8e6))||!!m&&ka(h)&&Object.keys(m).some(p=>parseInt(p)>h)}function Xvt(s,t,r,n={}){const a=s.videoCodec;if(!a&&!s.audioCodec||!r)return Promise.resolve(Yvt);const i=[],l=jqs(s),o=l.length,c=Nqs(s,t,o>0),d=c.length;for(let h=o||1*d||1;h--;){const m={type:"media-source"};if(o&&(m.video=l[h%o]),d){m.audio=c[h%d];const p=m.audio.bitrate;m.video&&p&&(m.video.bitrate-=p)}i.push(m)}if(a){const h=navigator.userAgent;if(a.split(",").some(m=>uye(m))&&Kvt())return Promise.resolve(Zvt(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${h})`),i))}return Promise.all(i.map(h=>{const m=Sqs(h);return n[m]||(n[m]=r.decodingInfo(h))})).then(h=>({supported:!h.some(m=>!m.supported),configurations:i,decodingInfoResults:h})).catch(h=>({supported:!1,configurations:i,decodingInfoResults:[],error:h}))}function jqs(s){var t;const r=(t=s.videoCodec)==null?void 0:t.split(","),n=Qvt(s),a=s.width||640,i=s.height||480,l=s.frameRate||30,o=s.videoRange.toLowerCase();return r?r.map(c=>{const d={contentType:bB(vqs(c),"video"),width:a,height:i,bitrate:n,framerate:l};return o!=="sdr"&&(d.transferFunction=o),d}):[]}function Nqs(s,t,r){var n;const a=(n=s.audioCodec)==null?void 0:n.split(","),i=Qvt(s);return a&&s.audioGroups?s.audioGroups.reduce((l,o)=>{var c;const d=o?(c=t.groups[o])==null?void 0:c.tracks:null;return d?d.reduce((h,m)=>{if(m.groupId===o){const p=parseFloat(m.channels||"");a.forEach(x=>{const y={contentType:bB(x,"audio"),bitrate:r?kqs(x,i):i};p&&(y.channels=""+p),h.push(y)})}return h},l):l},[]):[]}function kqs(s,t){if(t<=1)return 1;let r=128e3;return s==="ec-3"?r=768e3:s==="ac-3"&&(r=64e4),Math.min(t/2,r)}function Qvt(s){return Math.ceil(Math.max(s.bitrate*.9,s.averageBitrate)/1e3)*1e3||1}function Sqs(s){let t="";const{audio:r,video:n}=s;if(n){const a=tCe(n.contentType);t+=`${a}_r${n.height}x${n.width}f${Math.ceil(n.framerate)}${n.transferFunction||"sd"}_${Math.ceil(n.bitrate/1e5)}`}if(r){const a=tCe(r.contentType);t+=`${n?"_":""}${a}_c${r.channels}`}return t}const sCe=["NONE","TYPE-0","TYPE-1",null];function Cqs(s){return sCe.indexOf(s)>-1}const xpe=["SDR","PQ","HLG"];function Tqs(s){return!!s&&xpe.indexOf(s)>-1}var zue={No:"",Yes:"YES",v2:"v2"};function aKe(s){const{canSkipUntil:t,canSkipDateRanges:r,age:n}=s,a=n!!n).map(n=>n.substring(0,4)).join(","),"supplemental"in t){var r;this.supplemental=t.supplemental;const n=(r=t.supplemental)==null?void 0:r.videoCodec;n&&n!==t.videoCodec&&(this.codecSet+=`,${n.substring(0,4)}`)}this.addGroupId("audio",t.attrs.AUDIO),this.addGroupId("text",t.attrs.SUBTITLES)}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(t){return oKe(this._audioGroups,t)}hasSubtitleGroup(t){return oKe(this._subtitleGroups,t)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(t,r){if(r){if(t==="audio"){let n=this._audioGroups;n||(n=this._audioGroups=[]),n.indexOf(r)===-1&&n.push(r)}else if(t==="text"){let n=this._subtitleGroups;n||(n=this._subtitleGroups=[]),n.indexOf(r)===-1&&n.push(r)}}}get urlId(){return 0}set urlId(t){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var t;return(t=this.audioGroups)==null?void 0:t[0]}get textGroupId(){var t;return(t=this.subtitleGroups)==null?void 0:t[0]}addFallback(){}}function oKe(s,t){return!t||!s?!1:s.indexOf(t)!==-1}function Eqs(){if(typeof matchMedia=="function"){const s=matchMedia("(dynamic-range: high)"),t=matchMedia("bad query");if(s.media!==t.media)return s.matches===!0}return!1}function Aqs(s,t){let r=!1,n=[];if(s&&(r=s!=="SDR",n=[s]),t){n=t.allowedVideoRanges||xpe.slice(0);const a=n.join("")!=="SDR"&&!t.videoCodec;r=t.preferHDR!==void 0?t.preferHDR:a&&Eqs(),r||(n=["SDR"])}return{preferHDR:r,allowedVideoRanges:n}}const Mqs=s=>{const t=new WeakSet;return(r,n)=>{if(s&&(n=s(r,n)),typeof n=="object"&&n!==null){if(t.has(n))return;t.add(n)}return n}},Uc=(s,t)=>JSON.stringify(s,Mqs(t));function Iqs(s,t,r,n,a){const i=Object.keys(s),l=n==null?void 0:n.channels,o=n==null?void 0:n.audioCodec,c=a==null?void 0:a.videoCodec,d=l&&parseInt(l)===2;let h=!1,m=!1,p=1/0,x=1/0,y=1/0,_=1/0,b=0,j=[];const{preferHDR:k,allowedVideoRanges:T}=Aqs(t,a);for(let z=i.length;z--;){const O=s[i[z]];h||(h=O.channels[2]>0),p=Math.min(p,O.minHeight),x=Math.min(x,O.minFramerate),y=Math.min(y,O.minBitrate),T.filter(ee=>O.videoRanges[ee]>0).length>0&&(m=!0)}p=ka(p)?p:0,x=ka(x)?x:0;const E=Math.max(1080,p),A=Math.max(30,x);y=ka(y)?y:r,r=Math.max(y,r),m||(t=void 0);const D=i.length>1;return{codecSet:i.reduce((z,O)=>{const $=s[O];if(O===z)return z;if(j=m?T.filter(ee=>$.videoRanges[ee]>0):[],D){if($.minBitrate>r)return Ab(O,`min bitrate of ${$.minBitrate} > current estimate of ${r}`),z;if(!$.hasDefaultAudio)return Ab(O,"no renditions with default or auto-select sound found"),z;if(o&&O.indexOf(o.substring(0,4))%5!==0)return Ab(O,`audio codec preference "${o}" not found`),z;if(l&&!d){if(!$.channels[l])return Ab(O,`no renditions with ${l} channel sound found (channels options: ${Object.keys($.channels)})`),z}else if((!o||d)&&h&&$.channels[2]===0)return Ab(O,"no renditions with stereo sound found"),z;if($.minHeight>E)return Ab(O,`min resolution of ${$.minHeight} > maximum of ${E}`),z;if($.minFramerate>A)return Ab(O,`min framerate of ${$.minFramerate} > maximum of ${A}`),z;if(!j.some(ee=>$.videoRanges[ee]>0))return Ab(O,`no variants with VIDEO-RANGE of ${Uc(j)} found`),z;if(c&&O.indexOf(c.substring(0,4))%5!==0)return Ab(O,`video codec preference "${c}" not found`),z;if($.maxScore=ppe(z)||$.fragmentError>s[z].fragmentError)?z:(_=$.minIndex,b=$.maxScore,O)},void 0),videoRanges:j,preferHDR:k,minFramerate:x,minBitrate:y,minIndex:_}}function Ab(s,t){gc.log(`[abr] start candidates with "${s}" ignored because ${t}`)}function Jvt(s){return s.reduce((t,r)=>{let n=t.groups[r.groupId];n||(n=t.groups[r.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),n.tracks.push(r);const a=r.channels||"2";return n.channels[a]=(n.channels[a]||0)+1,n.hasDefault=n.hasDefault||r.default,n.hasAutoSelect=n.hasAutoSelect||r.autoselect,n.hasDefault&&(t.hasDefaultAudio=!0),n.hasAutoSelect&&(t.hasAutoSelectAudio=!0),t},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function Pqs(s,t,r,n){return s.slice(r,n+1).reduce((a,i,l)=>{if(!i.codecSet)return a;const o=i.audioGroups;let c=a[i.codecSet];c||(a[i.codecSet]=c={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:l,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!o,fragmentError:0}),c.minBitrate=Math.min(c.minBitrate,i.bitrate);const d=Math.min(i.height,i.width);return c.minHeight=Math.min(c.minHeight,d),c.minFramerate=Math.min(c.minFramerate,i.frameRate),c.minIndex=Math.min(c.minIndex,l),c.maxScore=Math.max(c.maxScore,i.score),c.fragmentError+=i.fragmentError,c.videoRanges[i.videoRange]=(c.videoRanges[i.videoRange]||0)+1,o&&o.forEach(h=>{if(!h)return;const m=t.groups[h];m&&(c.hasDefaultAudio=c.hasDefaultAudio||t.hasDefaultAudio?m.hasDefault:m.hasAutoSelect||!t.hasDefaultAudio&&!t.hasAutoSelectAudio,Object.keys(m.channels).forEach(p=>{c.channels[p]=(c.channels[p]||0)+m.channels[p]}))}),a},{})}function lKe(s){if(!s)return s;const{lang:t,assocLang:r,characteristics:n,channels:a,audioCodec:i}=s;return{lang:t,assocLang:r,characteristics:n,channels:a,audioCodec:i}}function o_(s,t,r){if("attrs"in s){const n=t.indexOf(s);if(n!==-1)return n}for(let n=0;nn.indexOf(a)===-1)}function CT(s,t){const{audioCodec:r,channels:n}=s;return(r===void 0||(t.audioCodec||"").substring(0,4)===r.substring(0,4))&&(n===void 0||n===(t.channels||"2"))}function Rqs(s,t,r,n,a){const i=t[n],o=t.reduce((p,x,y)=>{const _=x.uri;return(p[_]||(p[_]=[])).push(y),p},{})[i.uri];o.length>1&&(n=Math.max.apply(Math,o));const c=i.videoRange,d=i.frameRate,h=i.codecSet.substring(0,4),m=cKe(t,n,p=>{if(p.videoRange!==c||p.frameRate!==d||p.codecSet.substring(0,4)!==h)return!1;const x=p.audioGroups,y=r.filter(_=>!x||x.indexOf(_.groupId)!==-1);return o_(s,y,a)>-1});return m>-1?m:cKe(t,n,p=>{const x=p.audioGroups,y=r.filter(_=>!x||x.indexOf(_.groupId)!==-1);return o_(s,y,a)>-1})}function cKe(s,t,r){for(let n=t;n>-1;n--)if(r(s[n]))return n;for(let n=t+1;n{var n;const{fragCurrent:a,partCurrent:i,hls:l}=this,{autoLevelEnabled:o,media:c}=l;if(!a||!c)return;const d=performance.now(),h=i?i.stats:a.stats,m=i?i.duration:a.duration,p=d-h.loading.start,x=l.minAutoLevel,y=a.level,_=this._nextAutoLevel;if(h.aborted||h.loaded&&h.loaded===h.total||y<=x){this.clearTimer(),this._nextAutoLevel=-1;return}if(!o)return;const b=_>-1&&_!==y,j=!!r||b;if(!j&&(c.paused||!c.playbackRate||!c.readyState))return;const k=l.mainForwardBufferInfo;if(!j&&k===null)return;const T=this.bwEstimator.getEstimateTTFB(),E=Math.abs(c.playbackRate);if(p<=Math.max(T,1e3*(m/(E*2))))return;const A=k?k.len/E:0,D=h.loading.first?h.loading.first-h.loading.start:-1,R=h.loaded&&D>-1,z=this.getBwEstimate(),O=l.levels,$=O[y],ee=Math.max(h.loaded,Math.round(m*(a.bitrate||$.averageBitrate)/8));let Z=R?p-D:p;Z<1&&R&&(Z=Math.min(p,h.loaded*8/z));const J=R?h.loaded*1e3/Z:0,K=T/1e3,re=J?(ee-h.loaded)/J:ee*8/z+K;if(re<=A)return;const ie=J?J*8:z,ce=((n=(r==null?void 0:r.details)||this.hls.latestLevelDetails)==null?void 0:n.live)===!0,ne=this.hls.config.abrBandWidthUpFactor;let le=Number.POSITIVE_INFINITY,be;for(be=y-1;be>x;be--){const We=O[be].maxBitrate,Ve=!O[be].details||ce;if(le=this.getTimeToLoadFrag(K,ie,m*We,Ve),le=re||le>m*10)return;R?this.bwEstimator.sample(p-Math.min(T,D),h.loaded):this.bwEstimator.sampleTTFB(p);const fe=O[be].maxBitrate;this.getBwEstimate()*ne>fe&&this.resetEstimator(fe);const je=this.findBestLevel(fe,x,be,0,A,1,1);je>-1&&(be=je),this.warn(`Fragment ${a.sn}${i?" part "+i.index:""} of level ${y} is loading too slowly; Fragment duration: ${a.duration.toFixed(3)} Time to underbuffer: ${A.toFixed(3)} s Estimated load time for current fragment: ${re.toFixed(3)} s Estimated load time for down switch fragment: ${le.toFixed(3)} s TTFB estimate: ${D|0} ms Current BW estimate: ${ka(z)?z|0:"Unknown"} bps New BW estimate: ${this.getBwEstimate()|0} bps Switching to level ${be} @ ${fe|0} bps`),l.nextLoadLevel=l.nextAutoLevel=be,this.clearTimer();const ve=()=>{if(this.clearTimer(),this.fragCurrent===a&&this.hls.loadLevel===be&&be>0){const We=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${be>0?"and switching down":""} Fragment duration: ${a.duration.toFixed(3)} s Time to underbuffer: ${We.toFixed(3)} s`),a.abortRequests(),this.fragCurrent=this.partCurrent=null,be>x){let Ve=this.findBestLevel(this.hls.levels[x].bitrate,x,be,0,We,1,1);Ve===-1&&(Ve=x),this.hls.nextLoadLevel=this.hls.nextAutoLevel=Ve,this.resetEstimator(this.hls.levels[Ve].bitrate)}}};b||re>le*2?ve():this.timer=self.setInterval(ve,le*1e3),l.trigger(vt.FRAG_LOAD_EMERGENCY_ABORTED,{frag:a,part:i,stats:h})},this.hls=t,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(t){t&&(this.log(`setting initial bwe to ${t}`),this.hls.config.abrEwmaDefaultEstimate=t),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){const t=this.hls.config;return new UUs(t.abrEwmaSlowVoD,t.abrEwmaFastVoD,t.abrEwmaDefaultEstimate)}registerListeners(){const{hls:t}=this;t.on(vt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(vt.FRAG_LOADING,this.onFragLoading,this),t.on(vt.FRAG_LOADED,this.onFragLoaded,this),t.on(vt.FRAG_BUFFERED,this.onFragBuffered,this),t.on(vt.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(vt.LEVEL_LOADED,this.onLevelLoaded,this),t.on(vt.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(vt.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.on(vt.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t&&(t.off(vt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(vt.FRAG_LOADING,this.onFragLoading,this),t.off(vt.FRAG_LOADED,this.onFragLoaded,this),t.off(vt.FRAG_BUFFERED,this.onFragBuffered,this),t.off(vt.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(vt.LEVEL_LOADED,this.onLevelLoaded,this),t.off(vt.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(vt.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.off(vt.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(t,r){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(t,r){const n=r.frag;if(!this.ignoreFragment(n)){if(!n.bitrateTest){var a;this.fragCurrent=n,this.partCurrent=(a=r.part)!=null?a:null}this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(t,r){this.clearTimer()}onError(t,r){if(!r.fatal)switch(r.details){case yr.BUFFER_ADD_CODEC_ERROR:case yr.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case yr.FRAG_LOAD_TIMEOUT:{const n=r.frag,{fragCurrent:a,partCurrent:i}=this;if(n&&a&&n.sn===a.sn&&n.level===a.level){const l=performance.now(),o=i?i.stats:n.stats,c=l-o.loading.start,d=o.loading.first?o.loading.first-o.loading.start:-1;if(o.loaded&&d>-1){const m=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(c-Math.min(m,d),o.loaded)}else this.bwEstimator.sampleTTFB(c)}break}}}getTimeToLoadFrag(t,r,n,a){const i=t+n/r,l=a?t+this.lastLevelLoadSec:0;return i+l}onLevelLoaded(t,r){const n=this.hls.config,{loading:a}=r.stats,i=a.end-a.first;ka(i)&&(this.lastLevelLoadSec=i/1e3),r.details.live?this.bwEstimator.update(n.abrEwmaSlowLive,n.abrEwmaFastLive):this.bwEstimator.update(n.abrEwmaSlowVoD,n.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(r.levelInfo)}onFragLoaded(t,{frag:r,part:n}){const a=n?n.stats:r.stats;if(r.type===Ba.MAIN&&this.bwEstimator.sampleTTFB(a.loading.first-a.loading.start),!this.ignoreFragment(r)){if(this.clearTimer(),r.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const i=n?n.duration:r.duration,l=this.hls.levels[r.level],o=(l.loaded?l.loaded.bytes:0)+a.loaded,c=(l.loaded?l.loaded.duration:0)+i;l.loaded={bytes:o,duration:c},l.realBitrate=Math.round(8*o/c)}if(r.bitrateTest){const i={stats:a,frag:r,part:n,id:r.type};this.onFragBuffered(vt.FRAG_BUFFERED,i),r.bitrateTest=!1}else this.lastLoadedFragLevel=r.level}}onFragBuffered(t,r){const{frag:n,part:a}=r,i=a!=null&&a.stats.loaded?a.stats:n.stats;if(i.aborted||this.ignoreFragment(n))return;const l=i.parsing.end-i.loading.start-Math.min(i.loading.first-i.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(l,i.loaded),i.bwEstimate=this.getBwEstimate(),n.bitrateTest?this.bitrateTestDelay=l/1e3:this.bitrateTestDelay=0}ignoreFragment(t){return t.type!==Ba.MAIN||t.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:t,minAutoLevel:r}=this.hls,n=this.getBwEstimate(),a=this.hls.config.maxStarvationDelay,i=this.findBestLevel(n,r,t,0,a,1,1);if(i>-1)return i;const l=this.hls.firstLevel,o=Math.min(Math.max(l,r),t);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${l} clamped to ${o}`),o}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const t=this.forcedAutoLevel,n=this.bwEstimator.canEstimate(),a=this.lastLoadedFragLevel>-1;if(t!==-1&&(!n||!a||this.nextAutoLevelKey===this.getAutoLevelKey()))return t;const i=n&&a?this.getNextABRAutoLevel():this.firstAutoLevel;if(t!==-1){const l=this.hls.levels;if(l.length>Math.max(t,i)&&l[t].loadError<=l[i].loadError)return t}return this._nextAutoLevel=i,this.nextAutoLevelKey=this.getAutoLevelKey(),i}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:t,partCurrent:r,hls:n}=this;if(n.levels.length<=1)return n.loadLevel;const{maxAutoLevel:a,config:i,minAutoLevel:l}=n,o=r?r.duration:t?t.duration:0,c=this.getBwEstimate(),d=this.getStarvationDelay();let h=i.abrBandWidthFactor,m=i.abrBandWidthUpFactor;if(d){const b=this.findBestLevel(c,l,a,d,0,h,m);if(b>=0)return this.rebufferNotice=-1,b}let p=o?Math.min(o,i.maxStarvationDelay):i.maxStarvationDelay;if(!d){const b=this.bitrateTestDelay;b&&(p=(o?Math.min(o,i.maxLoadingDelay):i.maxLoadingDelay)-b,this.info(`bitrate test took ${Math.round(1e3*b)}ms, set first fragment max fetchDuration to ${Math.round(1e3*p)} ms`),h=m=1)}const x=this.findBestLevel(c,l,a,d,p,h,m);if(this.rebufferNotice!==x&&(this.rebufferNotice=x,this.info(`${d?"rebuffering expected":"buffer is empty"}, optimal quality level ${x}`)),x>-1)return x;const y=n.levels[l],_=n.loadLevelObj;return _&&(y==null?void 0:y.bitrate)<_.bitrate?l:n.loadLevel}getStarvationDelay(){const t=this.hls,r=t.media;if(!r)return 1/0;const n=r&&r.playbackRate!==0?Math.abs(r.playbackRate):1,a=t.mainForwardBufferInfo;return(a?a.len:0)/n}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(t,r,n,a,i,l,o){var c;const d=a+i,h=this.lastLoadedFragLevel,m=h===-1?this.hls.firstLevel:h,{fragCurrent:p,partCurrent:x}=this,{levels:y,allAudioTracks:_,loadLevel:b,config:j}=this.hls;if(y.length===1)return 0;const k=y[m],T=!!((c=this.hls.latestLevelDetails)!=null&&c.live),E=b===-1||h===-1;let A,D="SDR",R=(k==null?void 0:k.frameRate)||0;const{audioPreference:z,videoPreference:O}=j,$=this.audioTracksByGroup||(this.audioTracksByGroup=Jvt(_));let ee=-1;if(E){if(this.firstSelection!==-1)return this.firstSelection;const ie=this.codecTiers||(this.codecTiers=Pqs(y,$,r,n)),ce=Iqs(ie,D,t,z,O),{codecSet:ne,videoRanges:le,minFramerate:be,minBitrate:fe,minIndex:je,preferHDR:ve}=ce;ee=je,A=ne,D=ve?le[le.length-1]:le[0],R=be,t=Math.max(t,fe),this.log(`picked start tier ${Uc(ce)}`)}else A=k==null?void 0:k.codecSet,D=k==null?void 0:k.videoRange;const Z=x?x.duration:p?p.duration:0,J=this.bwEstimator.getEstimateTTFB()/1e3,K=[];for(let ie=n;ie>=r;ie--){var re;const ce=y[ie],ne=ie>m;if(!ce)continue;if(j.useMediaCapabilities&&!ce.supportedResult&&!ce.supportedPromise){const Ve=navigator.mediaCapabilities;typeof(Ve==null?void 0:Ve.decodingInfo)=="function"&&wqs(ce,$,D,R,t,z)?(ce.supportedPromise=Xvt(ce,$,Ve,this.supportedCache),ce.supportedPromise.then(Le=>{if(!this.hls)return;ce.supportedResult=Le;const Me=this.hls.levels,ze=Me.indexOf(ce);Le.error?this.warn(`MediaCapabilities decodingInfo error: "${Le.error}" for level ${ze} ${Uc(Le)}`):Le.supported?Le.decodingInfoResults.some(Pe=>Pe.smooth===!1||Pe.powerEfficient===!1)&&this.log(`MediaCapabilities decodingInfo for level ${ze} not smooth or powerEfficient: ${Uc(Le)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${ze} ${Uc(Le)}`),ze>-1&&Me.length>1&&(this.log(`Removing unsupported level ${ze}`),this.hls.removeLevel(ze),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))}).catch(Le=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${Le}`)})):ce.supportedResult=Yvt}if((A&&ce.codecSet!==A||D&&ce.videoRange!==D||ne&&R>ce.frameRate||!ne&&R>0&&RVe.smooth===!1))&&(!E||ie!==ee)){K.push(ie);continue}const le=ce.details,be=(x?le==null?void 0:le.partTarget:le==null?void 0:le.averagetargetduration)||Z;let fe;ne?fe=o*t:fe=l*t;const je=Z&&a>=Z*2&&i===0?ce.averageBitrate:ce.maxBitrate,ve=this.getTimeToLoadFrag(J,fe,je*be,le===void 0);if(fe>=je&&(ie===h||ce.loadError===0&&ce.fragmentError===0)&&(ve<=J||!ka(ve)||T&&!this.bitrateTestDelay||ve${ie} adjustedbw(${Math.round(fe)})-bitrate=${Math.round(fe-je)} ttfb:${J.toFixed(1)} avgDuration:${be.toFixed(1)} maxFetchDuration:${d.toFixed(1)} fetchDuration:${ve.toFixed(1)} firstSelection:${E} codecSet:${ce.codecSet} videoRange:${ce.videoRange} hls.loadLevel:${b}`)),E&&(this.firstSelection=ie),ie}}return-1}set nextAutoLevel(t){const r=this.deriveNextAutoLevel(t);this._nextAutoLevel!==r&&(this.nextAutoLevelKey="",this._nextAutoLevel=r)}deriveNextAutoLevel(t){const{maxAutoLevel:r,minAutoLevel:n}=this.hls;return Math.min(Math.max(t,n),r)}}const e1t={search:function(s,t){let r=0,n=s.length-1,a=null,i=null;for(;r<=n;){a=(r+n)/2|0,i=s[a];const l=t(i);if(l>0)r=a+1;else if(l<0)n=a-1;else return i}return null}};function Fqs(s,t,r){if(t===null||!Array.isArray(s)||!s.length||!ka(t))return null;const n=s[0].programDateTime;if(t<(n||0))return null;const a=s[s.length-1].endProgramDateTime;if(t>=(a||0))return null;for(let i=0;i0&&o<15e-7&&(r+=15e-7),i&&s.level!==i.level&&i.end<=s.end&&(i=t[2+s.sn-t[0].sn]||null)}else r===0&&t[0].start===0&&(i=t[0]);if(i&&((!s||s.level===i.level)&&dKe(r,n,i)===0||Bqs(i,s,Math.min(a,n))))return i;const l=e1t.search(t,dKe.bind(null,r,n));return l&&(l!==s||!i)?l:i}function Bqs(s,t,r){if(t&&t.start===0&&t.level0){const n=t.tagList.reduce((a,i)=>(i[0]==="INF"&&(a+=parseFloat(i[1])),a),r);return s.start<=n}return!1}function dKe(s=0,t=0,r){if(r.start<=s&&r.start+r.duration>s)return 0;const n=Math.min(t,r.duration+(r.deltaPTS?r.deltaPTS:0));return r.start+r.duration-n<=s?1:r.start-n>s&&r.start?-1:0}function zqs(s,t,r){const n=Math.min(t,r.duration+(r.deltaPTS?r.deltaPTS:0))*1e3;return(r.endProgramDateTime||0)-n>s}function t1t(s,t,r){if(s&&s.startCC<=t&&s.endCC>=t){let n=s.fragments;const{fragmentHint:a}=s;a&&(n=n.concat(a));let i;return e1t.search(n,l=>l.cct?-1:(i=l,l.end<=r?1:l.start>r?-1:0)),i||null}return null}function vpe(s){switch(s.details){case yr.FRAG_LOAD_TIMEOUT:case yr.KEY_LOAD_TIMEOUT:case yr.LEVEL_LOAD_TIMEOUT:case yr.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function s1t(s){return s.details.startsWith("key")}function r1t(s){return s1t(s)&&!!s.frag&&!s.frag.decryptdata}function uKe(s,t){const r=vpe(t);return s.default[`${r?"timeout":"error"}Retry`]}function E6e(s,t){const r=s.backoff==="linear"?1:Math.pow(2,t);return Math.min(r*s.retryDelayMs,s.maxRetryDelayMs)}function hKe(s){return hc(hc({},s),{errorRetry:null,timeoutRetry:null})}function bpe(s,t,r,n){if(!s)return!1;const a=n==null?void 0:n.code,i=t499)}function rCe(s){return s===0&&navigator.onLine===!1}var If={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},Kx={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4,SwitchToSDR:8};class Uqs extends dv{constructor(t){super("error-controller",t.logger),this.hls=void 0,this.playlistError=0,this.hls=t,this.registerListeners()}registerListeners(){const t=this.hls;t.on(vt.ERROR,this.onError,this),t.on(vt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(vt.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const t=this.hls;t&&(t.off(vt.ERROR,this.onError,this),t.off(vt.ERROR,this.onErrorOut,this),t.off(vt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(vt.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(t){}stopLoad(){this.playlistError=0}getVariantLevelIndex(t){return(t==null?void 0:t.type)===Ba.MAIN?t.level:this.getVariantIndex()}getVariantIndex(){var t;const r=this.hls,n=r.currentLevel;return(t=r.loadLevelObj)!=null&&t.details||n===-1?r.loadLevel:n}variantHasKey(t,r){if(t){var n;if((n=t.details)!=null&&n.hasKey(r))return!0;const a=t.audioGroups;if(a)return this.hls.allAudioTracks.filter(l=>a.indexOf(l.groupId)>=0).some(l=>{var o;return(o=l.details)==null?void 0:o.hasKey(r)})}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(t,r){var n;if(r.fatal)return;const a=this.hls,i=r.context;switch(r.details){case yr.FRAG_LOAD_ERROR:case yr.FRAG_LOAD_TIMEOUT:case yr.KEY_LOAD_ERROR:case yr.KEY_LOAD_TIMEOUT:r.errorAction=this.getFragRetryOrSwitchAction(r);return;case yr.FRAG_PARSING_ERROR:if((n=r.frag)!=null&&n.gap){r.errorAction=wP();return}case yr.FRAG_GAP:case yr.FRAG_DECRYPT_ERROR:{r.errorAction=this.getFragRetryOrSwitchAction(r),r.errorAction.action=If.SendAlternateToPenaltyBox;return}case yr.LEVEL_EMPTY_ERROR:case yr.LEVEL_PARSING_ERROR:{var l;const c=r.parent===Ba.MAIN?r.level:a.loadLevel;r.details===yr.LEVEL_EMPTY_ERROR&&((l=r.context)!=null&&(l=l.levelDetails)!=null&&l.live)?r.errorAction=this.getPlaylistRetryOrSwitchAction(r,c):(r.levelRetry=!1,r.errorAction=this.getLevelSwitchAction(r,c))}return;case yr.LEVEL_LOAD_ERROR:case yr.LEVEL_LOAD_TIMEOUT:typeof(i==null?void 0:i.level)=="number"&&(r.errorAction=this.getPlaylistRetryOrSwitchAction(r,i.level));return;case yr.AUDIO_TRACK_LOAD_ERROR:case yr.AUDIO_TRACK_LOAD_TIMEOUT:case yr.SUBTITLE_LOAD_ERROR:case yr.SUBTITLE_TRACK_LOAD_TIMEOUT:if(i){const c=a.loadLevelObj;if(c&&(i.type===Vo.AUDIO_TRACK&&c.hasAudioGroup(i.groupId)||i.type===Vo.SUBTITLE_TRACK&&c.hasSubtitleGroup(i.groupId))){r.errorAction=this.getPlaylistRetryOrSwitchAction(r,a.loadLevel),r.errorAction.action=If.SendAlternateToPenaltyBox,r.errorAction.flags=Kx.MoveAllAlternatesMatchingHost;return}}return;case yr.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:r.errorAction={action:If.SendAlternateToPenaltyBox,flags:Kx.MoveAllAlternatesMatchingHDCP};return;case yr.KEY_SYSTEM_SESSION_UPDATE_FAILED:case yr.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case yr.KEY_SYSTEM_NO_SESSION:r.errorAction={action:If.SendAlternateToPenaltyBox,flags:Kx.MoveAllAlternatesMatchingKey};return;case yr.BUFFER_ADD_CODEC_ERROR:case yr.REMUX_ALLOC_ERROR:case yr.BUFFER_APPEND_ERROR:if(!r.errorAction){var o;r.errorAction=this.getLevelSwitchAction(r,(o=r.level)!=null?o:a.loadLevel)}return;case yr.INTERNAL_EXCEPTION:case yr.BUFFER_APPENDING_ERROR:case yr.BUFFER_FULL_ERROR:case yr.LEVEL_SWITCH_ERROR:case yr.BUFFER_STALLED_ERROR:case yr.BUFFER_SEEK_OVER_HOLE:case yr.BUFFER_NUDGE_ON_STALL:r.errorAction=wP();return}r.type===ci.KEY_SYSTEM_ERROR&&(r.levelRetry=!1,r.errorAction=wP())}getPlaylistRetryOrSwitchAction(t,r){const n=this.hls,a=uKe(n.config.playlistLoadPolicy,t),i=this.playlistError++;if(bpe(a,i,vpe(t),t.response))return{action:If.RetryRequest,flags:Kx.None,retryConfig:a,retryCount:i};const o=this.getLevelSwitchAction(t,r);return a&&(o.retryConfig=a,o.retryCount=i),o}getFragRetryOrSwitchAction(t){const r=this.hls,n=this.getVariantLevelIndex(t.frag),a=r.levels[n],{fragLoadPolicy:i,keyLoadPolicy:l}=r.config,o=uKe(s1t(t)?l:i,t),c=r.levels.reduce((h,m)=>h+m.fragmentError,0);if(a&&(t.details!==yr.FRAG_GAP&&a.fragmentError++,!r1t(t)&&bpe(o,c,vpe(t),t.response)))return{action:If.RetryRequest,flags:Kx.None,retryConfig:o,retryCount:c};const d=this.getLevelSwitchAction(t,n);return o&&(d.retryConfig=o,d.retryCount=c),d}getLevelSwitchAction(t,r){const n=this.hls;r==null&&(r=n.loadLevel);const a=this.hls.levels[r];if(a){var i,l;const d=t.details;a.loadError++,d===yr.BUFFER_APPEND_ERROR&&a.fragmentError++;let h=-1;const{levels:m,loadLevel:p,minAutoLevel:x,maxAutoLevel:y}=n;!n.autoLevelEnabled&&!n.config.preserveManualLevelOnError&&(n.loadLevel=-1);const _=(i=t.frag)==null?void 0:i.type,j=(_===Ba.AUDIO&&d===yr.FRAG_PARSING_ERROR||t.sourceBufferName==="audio"&&(d===yr.BUFFER_ADD_CODEC_ERROR||d===yr.BUFFER_APPEND_ERROR))&&m.some(({audioCodec:D})=>a.audioCodec!==D),T=t.sourceBufferName==="video"&&(d===yr.BUFFER_ADD_CODEC_ERROR||d===yr.BUFFER_APPEND_ERROR)&&m.some(({codecSet:D,audioCodec:R})=>a.codecSet!==D&&a.audioCodec===R),{type:E,groupId:A}=(l=t.context)!=null?l:{};for(let D=m.length;D--;){const R=(D+p)%m.length;if(R!==p&&R>=x&&R<=y&&m[R].loadError===0){var o,c;const z=m[R];if(d===yr.FRAG_GAP&&_===Ba.MAIN&&t.frag){const O=m[R].details;if(O){const $=OA(t.frag,O.fragments,t.frag.start);if($!=null&&$.gap)continue}}else{if(E===Vo.AUDIO_TRACK&&z.hasAudioGroup(A)||E===Vo.SUBTITLE_TRACK&&z.hasSubtitleGroup(A))continue;if(_===Ba.AUDIO&&(o=a.audioGroups)!=null&&o.some(O=>z.hasAudioGroup(O))||_===Ba.SUBTITLE&&(c=a.subtitleGroups)!=null&&c.some(O=>z.hasSubtitleGroup(O))||j&&a.audioCodec===z.audioCodec||T&&a.codecSet===z.codecSet||!j&&a.codecSet!==z.codecSet)continue}h=R;break}}if(h>-1&&n.loadLevel!==h)return t.levelRetry=!0,this.playlistError=0,{action:If.SendAlternateToPenaltyBox,flags:Kx.None,nextAutoLevel:h}}return{action:If.SendAlternateToPenaltyBox,flags:Kx.MoveAllAlternatesMatchingHost}}onErrorOut(t,r){var n;switch((n=r.errorAction)==null?void 0:n.action){case If.DoNothing:break;case If.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(r),!r.errorAction.resolved&&r.details!==yr.FRAG_GAP?r.fatal=!0:/MediaSource readyState: ended/.test(r.error.message)&&(this.warn(`MediaSource ended after "${r.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError());break}if(r.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(t){const r=this.hls,n=t.errorAction;if(!n)return;const{flags:a}=n,i=n.nextAutoLevel;switch(a){case Kx.None:this.switchLevel(t,i);break;case Kx.MoveAllAlternatesMatchingHDCP:{const c=this.getVariantLevelIndex(t.frag),d=r.levels[c],h=d==null?void 0:d.attrs["HDCP-LEVEL"];if(n.hdcpLevel=h,h==="NONE")this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");else if(h){r.maxHdcpLevel=sCe[sCe.indexOf(h)-1],n.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${r.maxHdcpLevel}" or lower`);break}}case Kx.MoveAllAlternatesMatchingKey:{const c=t.decryptdata;if(c){const d=this.hls.levels,h=d.length;for(let p=h;p--;)if(this.variantHasKey(d[p],c)){var l,o;this.log(`Banned key found in level ${p} (${d[p].bitrate}bps) or audio group "${(l=d[p].audioGroups)==null?void 0:l.join(",")}" (${(o=t.frag)==null?void 0:o.type} fragment) ${Pf(c.keyId||[])}`),d[p].fragmentError++,d[p].loadError++,this.log(`Removing level ${p} with key error (${t.error})`),this.hls.removeLevel(p)}const m=t.frag;if(this.hls.levels.length{const c=this.fragments[o];if(!c||l>=c.body.sn)return;if(!c.buffered&&(!c.loaded||i)){c.body.type===n&&this.removeFragment(c.body);return}const d=c.range[t];if(d){if(d.time.length===0){this.removeFragment(c.body);return}d.time.some(h=>{const m=!this.isTimeBuffered(h.startPTS,h.endPTS,r);return m&&this.removeFragment(c.body),m})}})}detectPartialFragments(t){const r=this.timeRanges;if(!r||t.frag.sn==="initSegment")return;const n=t.frag,a=P6(n),i=this.fragments[a];if(!i||i.buffered&&n.gap)return;const l=!n.relurl;Object.keys(r).forEach(o=>{const c=n.elementaryStreams[o];if(!c)return;const d=r[o],h=l||c.partial===!0;i.range[o]=this.getBufferedTimes(n,t.part,h,d)}),i.loaded=null,Object.keys(i.range).length?(this.bufferedEnd(i,n),dV(i)||this.removeParts(n.sn-1,n.type)):this.removeFragment(i.body)}bufferedEnd(t,r){t.buffered=!0,(t.body.endList=r.endList||t.body.endList)&&(this.endListFragments[t.body.type]=t)}removeParts(t,r){const n=this.activePartLists[r];n&&(this.activePartLists[r]=mKe(n,a=>a.fragment.sn>=t))}fragBuffered(t,r){const n=P6(t);let a=this.fragments[n];!a&&r&&(a=this.fragments[n]={body:t,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},t.gap&&(this.hasGaps=!0)),a&&(a.loaded=null,this.bufferedEnd(a,t))}getBufferedTimes(t,r,n,a){const i={time:[],partial:n},l=t.start,o=t.end,c=t.minEndPTS||o,d=t.maxStartPTS||l;for(let h=0;h=m&&c<=p){i.time.push({startPTS:Math.max(l,a.start(h)),endPTS:Math.min(o,a.end(h))});break}else if(lm){const x=Math.max(l,a.start(h)),y=Math.min(o,a.end(h));y>x&&(i.partial=!0,i.time.push({startPTS:x,endPTS:y}))}else if(o<=m)break}return i}getPartialFragment(t){let r=null,n,a,i,l=0;const{bufferPadding:o,fragments:c}=this;return Object.keys(c).forEach(d=>{const h=c[d];h&&dV(h)&&(a=h.body.start-o,i=h.body.end+o,t>=a&&t<=i&&(n=Math.min(t-a,i-t),l<=n&&(r=h.body,l=n)))}),r}isEndListAppended(t){const r=this.endListFragments[t];return r!==void 0&&(r.buffered||dV(r))}getState(t){const r=P6(t),n=this.fragments[r];return n?n.buffered?dV(n)?im.PARTIAL:im.OK:im.APPENDING:im.NOT_LOADED}isTimeBuffered(t,r,n){let a,i;for(let l=0;l=a&&r<=i)return!0;if(r<=a)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(t,r){if(r.frag.sn==="initSegment"||r.frag.bitrateTest)return;const n=r.frag,a=r.part?null:r,i=P6(n);this.fragments[i]={body:n,appendedPTS:null,loaded:a,buffered:!1,range:Object.create(null)}}onBufferAppended(t,r){const{frag:n,part:a,timeRanges:i,type:l}=r;if(n.sn==="initSegment")return;const o=n.type;if(a){let d=this.activePartLists[o];d||(this.activePartLists[o]=d=[]),d.push(a)}this.timeRanges=i;const c=i[l];this.detectEvictedFragments(l,c,o,a)}onFragBuffered(t,r){this.detectPartialFragments(r)}hasFragment(t){const r=P6(t);return!!this.fragments[r]}hasFragments(t){const{fragments:r}=this,n=Object.keys(r);if(!t)return n.length>0;for(let a=n.length;a--;){const i=r[n[a]];if((i==null?void 0:i.body.type)===t)return!0}return!1}hasParts(t){var r;return!!((r=this.activePartLists[t])!=null&&r.length)}removeFragmentsInRange(t,r,n,a,i){a&&!this.hasGaps||Object.keys(this.fragments).forEach(l=>{const o=this.fragments[l];if(!o)return;const c=o.body;c.type!==n||a&&!c.gap||c.startt&&(o.buffered||i)&&this.removeFragment(c)})}removeFragment(t){const r=P6(t);t.clearElementaryStreamInfo();const n=this.activePartLists[t.type];if(n){const a=t.sn;this.activePartLists[t.type]=mKe(n,i=>i.fragment.sn!==a)}delete this.fragments[r],t.endList&&delete this.endListFragments[t.type]}removeAllFragments(){var t;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;const r=(t=this.hls)==null||(t=t.latestLevelDetails)==null?void 0:t.partList;r&&r.forEach(n=>n.clearElementaryStreamInfo())}}function dV(s){var t,r,n;return s.buffered&&!!(s.body.gap||(t=s.range.video)!=null&&t.partial||(r=s.range.audio)!=null&&r.partial||(n=s.range.audiovideo)!=null&&n.partial)}function P6(s){return`${s.type}_${s.level}_${s.sn}`}function mKe(s,t){return s.filter(r=>{const n=t(r);return n||r.clearElementaryStreamInfo(),n})}var ES={cbc:0,ctr:1};class Vqs{constructor(t,r,n){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=t,this.aesIV=r,this.aesMode=n}decrypt(t,r){switch(this.aesMode){case ES.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},r,t);case ES.ctr:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},r,t);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}}function Hqs(s){const t=s.byteLength,r=t&&new DataView(s.buffer).getUint8(t-1);return r?s.slice(0,t-r):s}class Gqs{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(t){const r=new DataView(t),n=new Uint32Array(4);for(let a=0;a<4;a++)n[a]=r.getUint32(a*4);return n}initTable(){const t=this.sBox,r=this.invSBox,n=this.subMix,a=n[0],i=n[1],l=n[2],o=n[3],c=this.invSubMix,d=c[0],h=c[1],m=c[2],p=c[3],x=new Uint32Array(256);let y=0,_=0,b=0;for(b=0;b<256;b++)b<128?x[b]=b<<1:x[b]=b<<1^283;for(b=0;b<256;b++){let j=_^_<<1^_<<2^_<<3^_<<4;j=j>>>8^j&255^99,t[y]=j,r[j]=y;const k=x[y],T=x[k],E=x[T];let A=x[j]*257^j*16843008;a[y]=A<<24|A>>>8,i[y]=A<<16|A>>>16,l[y]=A<<8|A>>>24,o[y]=A,A=E*16843009^T*65537^k*257^y*16843008,d[j]=A<<24|A>>>8,h[j]=A<<16|A>>>16,m[j]=A<<8|A>>>24,p[j]=A,y?(y=k^x[x[x[E^k]]],_^=x[x[_]]):y=_=1}}expandKey(t){const r=this.uint8ArrayToUint32Array_(t);let n=!0,a=0;for(;a{const o=ArrayBuffer.isView(t)?t:new Uint8Array(t);this.softwareDecrypt(o,r,n,a);const c=this.flush();c?i(c.buffer):l(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(t),r,n,a)}softwareDecrypt(t,r,n,a){const{currentIV:i,currentResult:l,remainderData:o}=this;if(a!==ES.cbc||r.byteLength!==16)return gc.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),o&&(t=tv(o,t),this.remainderData=null);const c=this.getValidChunk(t);if(!c.length)return null;i&&(n=i);let d=this.softwareDecrypter;d||(d=this.softwareDecrypter=new Gqs),d.expandKey(r);const h=l;return this.currentResult=d.decrypt(c.buffer,0,n),this.currentIV=c.slice(-16).buffer,h||null}webCryptoDecrypt(t,r,n,a){if(this.key!==r||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(t,r,n,a));this.key=r,this.fastAesKey=new Wqs(this.subtle,r,a)}return this.fastAesKey.expandKey().then(i=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new Vqs(this.subtle,new Uint8Array(n),a).decrypt(t.buffer,i)):Promise.reject(new Error("web crypto not initialized"))).catch(i=>(gc.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${i.name}: ${i.message}`),this.onWebCryptoError(t,r,n,a)))}onWebCryptoError(t,r,n,a){const i=this.enableSoftwareAES;if(i){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(t,r,n,a);const l=this.flush();if(l)return l.buffer}throw new Error("WebCrypto"+(i?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(t){let r=t;const n=t.length-t.length%Yqs;return n!==t.length&&(r=t.slice(0,n),this.remainderData=t.slice(n)),r}logOnce(t){this.logEnabled&&(gc.log(`[decrypter]: ${t}`),this.logEnabled=!1)}}const fKe=Math.pow(2,17);class Zqs{constructor(t){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=t}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(t,r){const n=t.url;if(!n)return Promise.reject(new g2({type:ci.NETWORK_ERROR,details:yr.FRAG_LOAD_ERROR,fatal:!1,frag:t,error:new Error(`Fragment does not have a ${n?"part list":"url"}`),networkDetails:null}));this.abort();const a=this.config,i=a.fLoader,l=a.loader;return new Promise((o,c)=>{if(this.loader&&this.loader.destroy(),t.gap)if(t.tagList.some(y=>y[0]==="GAP")){c(gKe(t));return}else t.gap=!1;const d=this.loader=i?new i(a):new l(a),h=pKe(t);t.loader=d;const m=hKe(a.fragLoadPolicy.default),p={loadPolicy:m,timeout:m.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:t.sn==="initSegment"?1/0:fKe};t.stats=d.stats;const x={onSuccess:(y,_,b,j)=>{this.resetLoader(t,d);let k=y.data;b.resetIV&&t.decryptdata&&(t.decryptdata.iv=new Uint8Array(k.slice(0,16)),k=k.slice(16)),o({frag:t,part:null,payload:k,networkDetails:j})},onError:(y,_,b,j)=>{this.resetLoader(t,d),c(new g2({type:ci.NETWORK_ERROR,details:yr.FRAG_LOAD_ERROR,fatal:!1,frag:t,response:hc({url:n,data:void 0},y),error:new Error(`HTTP Error ${y.code} ${y.text}`),networkDetails:b,stats:j}))},onAbort:(y,_,b)=>{this.resetLoader(t,d),c(new g2({type:ci.NETWORK_ERROR,details:yr.INTERNAL_ABORTED,fatal:!1,frag:t,error:new Error("Aborted"),networkDetails:b,stats:y}))},onTimeout:(y,_,b)=>{this.resetLoader(t,d),c(new g2({type:ci.NETWORK_ERROR,details:yr.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,error:new Error(`Timeout after ${p.timeout}ms`),networkDetails:b,stats:y}))}};r&&(x.onProgress=(y,_,b,j)=>r({frag:t,part:null,payload:b,networkDetails:j})),d.load(h,p,x)})}loadPart(t,r,n){this.abort();const a=this.config,i=a.fLoader,l=a.loader;return new Promise((o,c)=>{if(this.loader&&this.loader.destroy(),t.gap||r.gap){c(gKe(t,r));return}const d=this.loader=i?new i(a):new l(a),h=pKe(t,r);t.loader=d;const m=hKe(a.fragLoadPolicy.default),p={loadPolicy:m,timeout:m.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:fKe};r.stats=d.stats,d.load(h,p,{onSuccess:(x,y,_,b)=>{this.resetLoader(t,d),this.updateStatsFromPart(t,r);const j={frag:t,part:r,payload:x.data,networkDetails:b};n(j),o(j)},onError:(x,y,_,b)=>{this.resetLoader(t,d),c(new g2({type:ci.NETWORK_ERROR,details:yr.FRAG_LOAD_ERROR,fatal:!1,frag:t,part:r,response:hc({url:h.url,data:void 0},x),error:new Error(`HTTP Error ${x.code} ${x.text}`),networkDetails:_,stats:b}))},onAbort:(x,y,_)=>{t.stats.aborted=r.stats.aborted,this.resetLoader(t,d),c(new g2({type:ci.NETWORK_ERROR,details:yr.INTERNAL_ABORTED,fatal:!1,frag:t,part:r,error:new Error("Aborted"),networkDetails:_,stats:x}))},onTimeout:(x,y,_)=>{this.resetLoader(t,d),c(new g2({type:ci.NETWORK_ERROR,details:yr.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,part:r,error:new Error(`Timeout after ${p.timeout}ms`),networkDetails:_,stats:x}))}})})}updateStatsFromPart(t,r){const n=t.stats,a=r.stats,i=a.total;if(n.loaded+=a.loaded,i){const c=Math.round(t.duration/r.duration),d=Math.min(Math.round(n.loaded/i),c),m=(c-d)*Math.round(n.loaded/d);n.total=n.loaded+m}else n.total=Math.max(n.loaded,n.total);const l=n.loading,o=a.loading;l.start?l.first+=o.first-o.start:(l.start=o.start,l.first=o.first),l.end=o.end}resetLoader(t,r){t.loader=null,this.loader===r&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),r.destroy()}}function pKe(s,t=null){const r=t||s,n={frag:s,part:t,responseType:"arraybuffer",url:r.url,headers:{},rangeStart:0,rangeEnd:0},a=r.byteRangeStartOffset,i=r.byteRangeEndOffset;if(ka(a)&&ka(i)){var l;let o=a,c=i;if(s.sn==="initSegment"&&Xqs((l=s.decryptdata)==null?void 0:l.method)){const d=i-a;d%16&&(c=i+(16-d%16)),a!==0&&(n.resetIV=!0,o=a-16)}n.rangeStart=o,n.rangeEnd=c}return n}function gKe(s,t){const r=new Error(`GAP ${s.gap?"tag":"attribute"} found`),n={type:ci.MEDIA_ERROR,details:yr.FRAG_GAP,fatal:!1,frag:s,error:r,networkDetails:null};return t&&(n.part=t),(t||s).stats.aborted=!0,new g2(n)}function Xqs(s){return s==="AES-128"||s==="AES-256"}class g2 extends Error{constructor(t){super(t.error.message),this.data=void 0,this.data=t}}class n1t extends dv{constructor(t,r){super(t,r),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(t){return this._tickInterval?!1:(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,t),!0)}clearInterval(){return this._tickInterval?(self.clearInterval(this._tickInterval),this._tickInterval=null,!0):!1}clearNextTick(){return this._tickTimer?(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0):!1}tick(){this._tickCallCount++,this._tickCallCount===1&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}class M6e{constructor(t,r,n,a=0,i=-1,l=!1){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing=uV(),this.buffering={audio:uV(),video:uV(),audiovideo:uV()},this.level=t,this.sn=r,this.id=n,this.size=a,this.part=i,this.partial=l}}function uV(){return{start:0,executeStart:0,executeEnd:0,end:0}}const xKe={length:0,start:()=>0,end:()=>0};class mo{static isBuffered(t,r){if(t){const n=mo.getBuffered(t);for(let a=n.length;a--;)if(r>=n.start(a)&&r<=n.end(a))return!0}return!1}static bufferedRanges(t){if(t){const r=mo.getBuffered(t);return mo.timeRangesToArray(r)}return[]}static timeRangesToArray(t){const r=[];for(let n=0;n1&&t.sort((h,m)=>h.start-m.start||m.end-h.end);let a=-1,i=[];if(n)for(let h=0;h=t[h].start&&r<=t[h].end&&(a=h);const m=i.length;if(m){const p=i[m-1].end;t[h].start-pp&&(i[m-1].end=t[h].end):i.push(t[h])}else i.push(t[h])}else i=t;let l=0,o,c=r,d=r;for(let h=0;h=m&&r<=p&&(a=h),r+n>=m&&r{const a=n.substring(2,n.length-1),i=r==null?void 0:r[a];return i===void 0?(s.playlistParsingError||(s.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${a}"`)),n):i})}return t}function vKe(s,t,r){let n=s.variableList;n||(s.variableList=n={});let a,i;if("QUERYPARAM"in t){a=t.QUERYPARAM;try{const l=new self.URL(r).searchParams;if(l.has(a))i=l.get(a);else throw new Error(`"${a}" does not match any query parameter in URI: "${r}"`)}catch(l){s.playlistParsingError||(s.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${l.message}`))}}else a=t.NAME,i=t.VALUE;a in n?s.playlistParsingError||(s.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${a}"`)):n[a]=i||""}function Qqs(s,t,r){const n=t.IMPORT;if(r&&n in r){let a=s.variableList;a||(s.variableList=a={}),a[n]=r[n]}else s.playlistParsingError||(s.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${n}"`))}const Jqs=/^(\d+)x(\d+)$/,bKe=/(.+?)=(".*?"|.*?)(?:,|$)/g;class au{constructor(t,r){typeof t=="string"&&(t=au.parseAttrList(t,r)),Ec(this,t)}get clientAttrs(){return Object.keys(this).filter(t=>t.substring(0,2)==="X-")}decimalInteger(t){const r=parseInt(this[t],10);return r>Number.MAX_SAFE_INTEGER?1/0:r}hexadecimalInteger(t){if(this[t]){let r=(this[t]||"0x").slice(2);r=(r.length&1?"0":"")+r;const n=new Uint8Array(r.length/2);for(let a=0;aNumber.MAX_SAFE_INTEGER?1/0:r}decimalFloatingPoint(t){return parseFloat(this[t])}optionalFloat(t,r){const n=this[t];return n?parseFloat(n):r}enumeratedString(t){return this[t]}enumeratedStringList(t,r){const n=this[t];return(n?n.split(/[ ,]+/):[]).reduce((a,i)=>(a[i.toLowerCase()]=!0,a),r)}bool(t){return this[t]==="YES"}decimalResolution(t){const r=Jqs.exec(this[t]);if(r!==null)return{width:parseInt(r[1],10),height:parseInt(r[2],10)}}static parseAttrList(t,r){let n;const a={},i='"';for(bKe.lastIndex=0;(n=bKe.exec(t))!==null;){const l=n[1].trim();let o=n[2];const c=o.indexOf(i)===0&&o.lastIndexOf(i)===o.length-1;let d=!1;if(c)o=o.slice(1,-1);else switch(l){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":d=!0}if(r&&(c||d))o=nCe(r,o);else if(!d&&!c)switch(l){case"CLOSED-CAPTIONS":if(o==="NONE")break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":gc.warn(`${t}: attribute ${l} is missing quotes`)}a[l]=o}return a}}const eVs="com.apple.hls.interstitial";function tVs(s){return s!=="ID"&&s!=="CLASS"&&s!=="CUE"&&s!=="START-DATE"&&s!=="DURATION"&&s!=="END-DATE"&&s!=="END-ON-NEXT"}function sVs(s){return s==="SCTE35-OUT"||s==="SCTE35-IN"||s==="SCTE35-CMD"}class i1t{constructor(t,r,n=0){var a;if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=(r==null?void 0:r.tagAnchor)||null,this.tagOrder=(a=r==null?void 0:r.tagOrder)!=null?a:n,r){const i=r.attr;for(const l in i)if(Object.prototype.hasOwnProperty.call(t,l)&&t[l]!==i[l]){gc.warn(`DATERANGE tag attribute: "${l}" does not match for tags with ID: "${t.ID}"`),this._badValueForSameId=l;break}t=Ec(new au({}),i,t)}if(this.attr=t,r?(this._startDate=r._startDate,this._cue=r._cue,this._endDate=r._endDate,this._dateAtEnd=r._dateAtEnd):this._startDate=new Date(t["START-DATE"]),"END-DATE"in this.attr){const i=(r==null?void 0:r.endDate)||new Date(this.attr["END-DATE"]);ka(i.getTime())&&(this._endDate=i)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const t=this._cue;return t===void 0?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):t}get startTime(){const{tagAnchor:t}=this;return t===null||t.programDateTime===null?(gc.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${t}`),NaN):t.start+(this.startDate.getTime()-t.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){const t=this._endDate||this._dateAtEnd;if(t)return t;const r=this.duration;return r!==null?this._dateAtEnd=new Date(this._startDate.getTime()+r*1e3):null}get duration(){if("DURATION"in this.attr){const t=this.attr.decimalFloatingPoint("DURATION");if(ka(t))return t}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isInterstitial(){return this.class===eVs}get isValid(){return!!this.id&&!this._badValueForSameId&&ka(this.startDate.getTime())&&(this.duration===null||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}}const rVs=10;class nVs{constructor(t){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=t}reloaded(t){if(!t){this.advanced=!0,this.updated=!0;return}const r=this.lastPartSn-t.lastPartSn,n=this.lastPartIndex-t.lastPartIndex;this.updated=this.endSN!==t.endSN||!!n||!!r||!this.live,this.advanced=this.endSN>t.endSN||r>0||r===0&&n>0,this.updated||this.advanced?this.misses=Math.floor(t.misses*.6):this.misses=t.misses+1}hasKey(t){return this.encryptedFragments.some(r=>{let n=r.decryptdata;return n||(r.setKeyFormat(t.keyFormat),n=r.decryptdata),!!n&&t.matches(n)})}get hasProgramDateTime(){return this.fragments.length?ka(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||rVs}get drift(){const t=this.driftEndTime-this.driftStartTime;return t>0?(this.driftEnd-this.driftStart)*1e3/t:1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var t;return(t=this.partList)!=null&&t.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){return this.fragments.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var t;return(t=this.partList)!=null&&t.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){const t=this.partList;if(t){const r=this.lastPartIndex;if(r!==-1){for(let n=t.length;n--;)if(t[n].index>r)return t[n].index;return r}}return 0}get lastPartSn(){var t;return(t=this.partList)!=null&&t.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){const t=this.partEnd-this.fragmentStart;return this.age>Math.max(t,this.totalduration)+this.levelTargetDuration}return!1}}function _pe(s,t){return s.length===t.length?!s.some((r,n)=>r!==t[n]):!1}function _Ke(s,t){return!s&&!t?!0:!s||!t?!1:_pe(s,t)}function jP(s){return s==="AES-128"||s==="AES-256"||s==="AES-256-CTR"}function I6e(s){switch(s){case"AES-128":case"AES-256":return ES.cbc;case"AES-256-CTR":return ES.ctr;default:throw new Error(`invalid full segment method ${s}`)}}function P6e(s){return Uint8Array.from(atob(s),t=>t.charCodeAt(0))}function aCe(s){return Uint8Array.from(unescape(encodeURIComponent(s)),t=>t.charCodeAt(0))}function aVs(s){const t=aCe(s).subarray(0,16),r=new Uint8Array(16);return r.set(t,16-t.length),r}function o1t(s){const t=function(n,a,i){const l=n[a];n[a]=n[i],n[i]=l};t(s,0,3),t(s,1,2),t(s,4,5),t(s,6,7)}function l1t(s){const t=s.split(":");let r=null;if(t[0]==="data"&&t.length===2){const n=t[1].split(";"),a=n[n.length-1].split(",");if(a.length===2){const i=a[0]==="base64",l=a[1];i?(n.splice(-1,1),r=P6e(l)):r=aVs(l)}}return r}const wpe=typeof self<"u"?self:void 0;var hu={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},Rf={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function $ue(s){switch(s){case Rf.FAIRPLAY:return hu.FAIRPLAY;case Rf.PLAYREADY:return hu.PLAYREADY;case Rf.WIDEVINE:return hu.WIDEVINE;case Rf.CLEARKEY:return hu.CLEARKEY}}function Bwe(s){switch(s){case hu.FAIRPLAY:return Rf.FAIRPLAY;case hu.PLAYREADY:return Rf.PLAYREADY;case hu.WIDEVINE:return Rf.WIDEVINE;case hu.CLEARKEY:return Rf.CLEARKEY}}function LO(s){const{drmSystems:t,widevineLicenseUrl:r}=s,n=t?[hu.FAIRPLAY,hu.WIDEVINE,hu.PLAYREADY,hu.CLEARKEY].filter(a=>!!t[a]):[];return!n[hu.WIDEVINE]&&r&&n.push(hu.WIDEVINE),n}const c1t=function(s){return wpe!=null&&(s=wpe.navigator)!=null&&s.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function iVs(s,t,r,n){let a;switch(s){case hu.FAIRPLAY:a=["cenc","sinf"];break;case hu.WIDEVINE:case hu.PLAYREADY:a=["cenc"];break;case hu.CLEARKEY:a=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${s}`)}return oVs(a,t,r,n)}function oVs(s,t,r,n){return[{initDataTypes:s,persistentState:n.persistentState||"optional",distinctiveIdentifier:n.distinctiveIdentifier||"optional",sessionTypes:n.sessionTypes||[n.sessionType||"temporary"],audioCapabilities:t.map(i=>({contentType:`audio/mp4; codecs=${i}`,robustness:n.audioRobustness||"",encryptionScheme:n.audioEncryptionScheme||null})),videoCapabilities:r.map(i=>({contentType:`video/mp4; codecs=${i}`,robustness:n.videoRobustness||"",encryptionScheme:n.videoEncryptionScheme||null}))}]}function lVs(s){var t;return!!s&&(s.sessionType==="persistent-license"||!!((t=s.sessionTypes)!=null&&t.some(r=>r==="persistent-license")))}function d1t(s){const t=new Uint16Array(s.buffer,s.byteOffset,s.byteLength/2),r=String.fromCharCode.apply(null,Array.from(t)),n=r.substring(r.indexOf("<"),r.length),l=new DOMParser().parseFromString(n,"text/xml").getElementsByTagName("KID")[0];if(l){const o=l.childNodes[0]?l.childNodes[0].nodeValue:l.getAttribute("VALUE");if(o){const c=P6e(o).subarray(0,16);return o1t(c),c}}return null}let L6={};class dS{static clearKeyUriToKeyIdMap(){L6={}}static setKeyIdForUri(t,r){L6[t]=r}static addKeyIdForUri(t){const r=Object.keys(L6).length%Number.MAX_SAFE_INTEGER,n=new Uint8Array(16);return new DataView(n.buffer,12,4).setUint32(0,r),L6[t]=n,n}constructor(t,r,n,a=[1],i=null,l){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=t,this.uri=r,this.keyFormat=n,this.keyFormatVersions=a,this.iv=i,this.encrypted=t?t!=="NONE":!1,this.isCommonEncryption=this.encrypted&&!jP(t),l!=null&&l.startsWith("0x")&&(this.keyId=new Uint8Array(Fvt(l)))}matches(t){return t.uri===this.uri&&t.method===this.method&&t.encrypted===this.encrypted&&t.keyFormat===this.keyFormat&&_pe(t.keyFormatVersions,this.keyFormatVersions)&&_Ke(t.iv,this.iv)&&_Ke(t.keyId,this.keyId)}isSupported(){if(this.method){if(jP(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case Rf.FAIRPLAY:case Rf.WIDEVINE:case Rf.PLAYREADY:case Rf.CLEARKEY:return["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)!==-1}}return!1}getDecryptData(t,r){if(!this.encrypted||!this.uri)return null;if(jP(this.method)){let i=this.iv;return i||(typeof t!="number"&&(gc.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),t=0),i=dVs(t)),new dS(this.method,this.uri,"identity",this.keyFormatVersions,i)}if(this.keyId){const i=L6[this.uri];if(i&&!_pe(this.keyId,i)&&dS.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const n=l1t(this.uri);if(n)switch(this.keyFormat){case Rf.WIDEVINE:if(this.pssh=n,!this.keyId){const i=mqs(n.buffer);if(i.length){var a;const l=i[0];this.keyId=(a=l.kids)!=null&&a.length?l.kids[0]:null}}this.keyId||(this.keyId=wKe(r));break;case Rf.PLAYREADY:{const i=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=hqs(i,null,n),this.keyId=d1t(n);break}default:{let i=n.subarray(0,16);if(i.length!==16){const l=new Uint8Array(16);l.set(i,16-i.length),i=l}this.keyId=i;break}}if(!this.keyId||this.keyId.byteLength!==16){let i;i=cVs(r),i||(i=wKe(r),i||(i=L6[this.uri])),i&&(this.keyId=i,dS.setKeyIdForUri(this.uri,i))}return this}}function cVs(s){const t=s==null?void 0:s[Rf.WIDEVINE];return t?t.keyId:null}function wKe(s){const t=s==null?void 0:s[Rf.PLAYREADY];if(t){const r=l1t(t.uri);if(r)return d1t(r)}return null}function dVs(s){const t=new Uint8Array(16);for(let r=12;r<16;r++)t[r]=s>>8*(15-r)&255;return t}const jKe=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)[\r\n]+/g,NKe=/#EXT-X-MEDIA:(.*)/g,uVs=/^#EXT(?:INF|-X-TARGETDURATION):/m,zwe=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),hVs=new RegExp([/#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|"));class l_{static findGroup(t,r){for(let n=0;n0&&i.length({id:d.attrs.AUDIO,audioCodec:d.audioCodec})),SUBTITLES:l.map(d=>({id:d.attrs.SUBTITLES,textCodec:d.textCodec})),"CLOSED-CAPTIONS":[]};let c=0;for(NKe.lastIndex=0;(a=NKe.exec(t))!==null;){const d=new au(a[1],n),h=d.TYPE;if(h){const m=o[h],p=i[h]||[];i[h]=p;const x=d.LANGUAGE,y=d["ASSOC-LANGUAGE"],_=d.CHANNELS,b=d.CHARACTERISTICS,j=d["INSTREAM-ID"],k={attrs:d,bitrate:0,id:c++,groupId:d["GROUP-ID"]||"",name:d.NAME||x||"",type:h,default:d.bool("DEFAULT"),autoselect:d.bool("AUTOSELECT"),forced:d.bool("FORCED"),lang:x,url:d.URI?l_.resolve(d.URI,r):""};if(y&&(k.assocLang=y),_&&(k.channels=_),b&&(k.characteristics=b),j&&(k.instreamId=j),m!=null&&m.length){const T=l_.findGroup(m,k.groupId)||m[0];TKe(k,T,"audioCodec"),TKe(k,T,"textCodec")}p.push(k)}}return i}static parseLevelPlaylist(t,r,n,a,i,l){var o;const c={url:r},d=new nVs(r),h=d.fragments,m=[];let p=null,x=0,y=0,_=0,b=0,j=0,k=null,T=new Rwe(a,c),E,A,D,R=-1,z=!1,O=null,$;if(zwe.lastIndex=0,d.m3u8=t,d.hasVariableRefs=yKe(t),((o=zwe.exec(t))==null?void 0:o[0])!=="#EXTM3U")return d.playlistParsingError=new Error("Missing format identifier #EXTM3U"),d;for(;(E=zwe.exec(t))!==null;){z&&(z=!1,T=new Rwe(a,c),T.playlistOffset=_,T.setStart(_),T.sn=x,T.cc=b,j&&(T.bitrate=j),T.level=n,p&&(T.initSegment=p,p.rawProgramDateTime&&(T.rawProgramDateTime=p.rawProgramDateTime,p.rawProgramDateTime=null),O&&(T.setByteRange(O),O=null)));const K=E[1];if(K){T.duration=parseFloat(K);const re=(" "+E[2]).slice(1);T.title=re||null,T.tagList.push(re?["INF",K,re]:["INF",K])}else if(E[3]){if(ka(T.duration)){T.playlistOffset=_,T.setStart(_),D&&AKe(T,D,d),T.sn=x,T.level=n,T.cc=b,h.push(T);const re=(" "+E[3]).slice(1);T.relurl=nCe(d,re),iCe(T,k,m),k=T,_+=T.duration,x++,y=0,z=!0}}else{if(E=E[0].match(hVs),!E){gc.warn("No matches on slow regex match for level playlist!");continue}for(A=1;A0&&MKe(d,re,E),x=d.startSN=parseInt(ie);break;case"SKIP":{d.skippedSegments&&i2(d,re,E);const ne=new au(ie,d),le=ne.decimalInteger("SKIPPED-SEGMENTS");if(ka(le)){d.skippedSegments+=le;for(let fe=le;fe--;)h.push(null);x+=le}const be=ne.enumeratedString("RECENTLY-REMOVED-DATERANGES");be&&(d.recentlyRemovedDateranges=(d.recentlyRemovedDateranges||[]).concat(be.split(" ")));break}case"TARGETDURATION":d.targetduration!==0&&i2(d,re,E),d.targetduration=Math.max(parseInt(ie),1);break;case"VERSION":d.version!==null&&i2(d,re,E),d.version=parseInt(ie);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":d.live||i2(d,re,E),d.live=!1;break;case"#":(ie||ce)&&T.tagList.push(ce?[ie,ce]:[ie]);break;case"DISCONTINUITY":b++,T.tagList.push(["DIS"]);break;case"GAP":T.gap=!0,T.tagList.push([re]);break;case"BITRATE":T.tagList.push([re,ie]),j=parseInt(ie)*1e3,ka(j)?T.bitrate=j:j=0;break;case"DATERANGE":{const ne=new au(ie,d),le=new i1t(ne,d.dateRanges[ne.ID],d.dateRangeTagCount);d.dateRangeTagCount++,le.isValid||d.skippedSegments?d.dateRanges[le.id]=le:gc.warn(`Ignoring invalid DATERANGE tag: "${ie}"`),T.tagList.push(["EXT-X-DATERANGE",ie]);break}case"DEFINE":{{const ne=new au(ie,d);"IMPORT"in ne?Qqs(d,ne,l):vKe(d,ne,r)}break}case"DISCONTINUITY-SEQUENCE":d.startCC!==0?i2(d,re,E):h.length>0&&MKe(d,re,E),d.startCC=b=parseInt(ie);break;case"KEY":{const ne=kKe(ie,r,d);if(ne.isSupported()){if(ne.method==="NONE"){D=void 0;break}D||(D={});const le=D[ne.keyFormat];le!=null&&le.matches(ne)||(le&&(D=Ec({},D)),D[ne.keyFormat]=ne)}else gc.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${ie}"`);break}case"START":d.startTimeOffset=SKe(ie);break;case"MAP":{const ne=new au(ie,d);if(T.duration){const le=new Rwe(a,c);EKe(le,ne,n,D),p=le,T.initSegment=p,p.rawProgramDateTime&&!T.rawProgramDateTime&&(T.rawProgramDateTime=p.rawProgramDateTime)}else{const le=T.byteRangeEndOffset;if(le){const be=T.byteRangeStartOffset;O=`${le-be}@${be}`}else O=null;EKe(T,ne,n,D),p=T,z=!0}p.cc=b;break}case"SERVER-CONTROL":{$&&i2(d,re,E),$=new au(ie),d.canBlockReload=$.bool("CAN-BLOCK-RELOAD"),d.canSkipUntil=$.optionalFloat("CAN-SKIP-UNTIL",0),d.canSkipDateRanges=d.canSkipUntil>0&&$.bool("CAN-SKIP-DATERANGES"),d.partHoldBack=$.optionalFloat("PART-HOLD-BACK",0),d.holdBack=$.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{d.partTarget&&i2(d,re,E);const ne=new au(ie);d.partTarget=ne.decimalFloatingPoint("PART-TARGET");break}case"PART":{let ne=d.partList;ne||(ne=d.partList=[]);const le=y>0?ne[ne.length-1]:void 0,be=y++,fe=new au(ie,d),je=new QUs(fe,T,c,be,le);ne.push(je),T.duration+=je.duration;break}case"PRELOAD-HINT":{const ne=new au(ie,d);d.preloadHint=ne;break}case"RENDITION-REPORT":{const ne=new au(ie,d);d.renditionReports=d.renditionReports||[],d.renditionReports.push(ne);break}default:gc.warn(`line parsed but not handled: ${E}`);break}}}k&&!k.relurl?(h.pop(),_-=k.duration,d.partList&&(d.fragmentHint=k)):d.partList&&(iCe(T,k,m),T.cc=b,d.fragmentHint=T,D&&AKe(T,D,d)),d.targetduration||(d.playlistParsingError=new Error("Missing Target Duration"));const ee=h.length,Z=h[0],J=h[ee-1];if(_+=d.skippedSegments*d.targetduration,_>0&&ee&&J){d.averagetargetduration=_/ee;const K=J.sn;d.endSN=K!=="initSegment"?K:0,d.live||(J.endList=!0),R>0&&(fVs(h,R),Z&&m.unshift(Z))}return d.fragmentHint&&(_+=d.fragmentHint.duration),d.totalduration=_,m.length&&d.dateRangeTagCount&&Z&&u1t(m,d),d.endCC=b,d}}function u1t(s,t){let r=s.length;if(!r)if(t.hasProgramDateTime){const o=t.fragments[t.fragments.length-1];s.push(o),r++}else return;const n=s[r-1],a=t.live?1/0:t.totalduration,i=Object.keys(t.dateRanges);for(let o=i.length;o--;){const c=t.dateRanges[i[o]],d=c.startDate.getTime();c.tagAnchor=n.ref;for(let h=r;h--;){var l;if(((l=s[h])==null?void 0:l.sn)=o||n===0){var l;const c=(((l=r[n+1])==null?void 0:l.start)||a)-i.start;if(t<=o+c*1e3){const d=r[n].sn-s.startSN;if(d<0)return-1;const h=s.fragments;if(h.length>r.length){const p=(r[n+1]||h[h.length-1]).sn-s.startSN;for(let x=p;x>d;x--){const y=h[x].programDateTime;if(t>=y&&tn);["video","audio","text"].forEach(n=>{const a=r.filter(i=>C6e(i,n));a.length&&(t[`${n}Codec`]=a.map(i=>i.split("/")[0]).join(","),r=r.filter(i=>a.indexOf(i)===-1))}),t.unknownCodecs=r}function TKe(s,t,r){const n=t[r];n&&(s[r]=n)}function fVs(s,t){let r=s[t];for(let n=t;n--;){const a=s[n];if(!a)return;a.programDateTime=r.programDateTime-a.duration*1e3,r=a}}function iCe(s,t,r){s.rawProgramDateTime?r.push(s):t!=null&&t.programDateTime&&(s.programDateTime=t.endProgramDateTime)}function EKe(s,t,r,n){s.relurl=t.URI,t.BYTERANGE&&s.setByteRange(t.BYTERANGE),s.level=r,s.sn="initSegment",n&&(s.levelkeys=n),s.initSegment=null}function AKe(s,t,r){s.levelkeys=t;const{encryptedFragments:n}=r;(!n.length||n[n.length-1].levelkeys!==t)&&Object.keys(t).some(a=>t[a].isCommonEncryption)&&n.push(s)}function i2(s,t,r){s.playlistParsingError=new Error(`#EXT-X-${t} must not appear more than once (${r[0]})`)}function MKe(s,t,r){s.playlistParsingError=new Error(`#EXT-X-${t} must appear before the first Media Segment (${r[0]})`)}function $we(s,t){const r=t.startPTS;if(ka(r)){let n=0,a;t.sn>s.sn?(n=r-s.start,a=s):(n=s.start-r,a=t),a.duration!==n&&a.setDuration(n)}else t.sn>s.sn?s.cc===t.cc&&s.minEndPTS?t.setStart(s.start+(s.minEndPTS-s.start)):t.setStart(s.start+s.duration):t.setStart(Math.max(s.start-t.duration,0))}function h1t(s,t,r,n,a,i,l){n-r<=0&&(l.warn("Fragment should have a positive duration",t),n=r+t.duration,i=a+t.duration);let c=r,d=n;const h=t.startPTS,m=t.endPTS;if(ka(h)){const j=Math.abs(h-r);s&&j>s.totalduration?l.warn(`media timestamps and playlist times differ by ${j}s for level ${t.level} ${s.url}`):ka(t.deltaPTS)?t.deltaPTS=Math.max(j,t.deltaPTS):t.deltaPTS=j,c=Math.max(r,h),r=Math.min(r,h),a=t.startDTS!==void 0?Math.min(a,t.startDTS):a,d=Math.min(n,m),n=Math.max(n,m),i=t.endDTS!==void 0?Math.max(i,t.endDTS):i}const p=r-t.start;t.start!==0&&t.setStart(r),t.setDuration(n-t.start),t.startPTS=r,t.maxStartPTS=c,t.startDTS=a,t.endPTS=n,t.minEndPTS=d,t.endDTS=i;const x=t.sn;if(!s||xs.endSN)return 0;let y;const _=x-s.startSN,b=s.fragments;for(b[_]=t,y=_;y>0;y--)$we(b[y],b[y-1]);for(y=_;y=0;h--){const m=a[h].initSegment;if(m){n=m;break}}s.fragmentHint&&delete s.fragmentHint.endPTS;let i;yVs(s,t,(h,m,p,x)=>{if((!t.startCC||t.skippedSegments)&&m.cc!==h.cc){const y=h.cc-m.cc;for(let _=p;_{var m;h&&(!h.initSegment||h.initSegment.relurl===((m=n)==null?void 0:m.relurl))&&(h.initSegment=n)}),t.skippedSegments){if(t.deltaUpdateFailed=l.some(h=>!h),t.deltaUpdateFailed){r.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let h=t.skippedSegments;h--;)l.shift();t.startSN=l[0].sn}else{t.canSkipDateRanges&&(t.dateRanges=gVs(s.dateRanges,t,r));const h=s.fragments.filter(m=>m.rawProgramDateTime);if(s.hasProgramDateTime&&!t.hasProgramDateTime)for(let m=1;m{m.elementaryStreams=h.elementaryStreams,m.stats=h.stats}),i?h1t(t,i,i.startPTS,i.endPTS,i.startDTS,i.endDTS,r):m1t(s,t),l.length&&(t.totalduration=t.edge-l[0].start),t.driftStartTime=s.driftStartTime,t.driftStart=s.driftStart;const d=t.advancedDateTime;if(t.advanced&&d){const h=t.edge;t.driftStart||(t.driftStartTime=d,t.driftStart=h),t.driftEndTime=d,t.driftEnd=h}else t.driftEndTime=s.driftEndTime,t.driftEnd=s.driftEnd,t.advancedDateTime=s.advancedDateTime;t.requestScheduled===-1&&(t.requestScheduled=s.requestScheduled)}function gVs(s,t,r){const{dateRanges:n,recentlyRemovedDateranges:a}=t,i=Ec({},s);a&&a.forEach(c=>{delete i[c]});const o=Object.keys(i).length;return o?(Object.keys(n).forEach(c=>{const d=i[c],h=new i1t(n[c].attr,d);h.isValid?(i[c]=h,d||(h.tagOrder+=o)):r.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${Uc(n[c].attr)}"`)}),i):n}function xVs(s,t,r){if(s&&t){let n=0;for(let a=0,i=s.length;a<=i;a++){const l=s[a],o=t[a+n];l&&o&&l.index===o.index&&l.fragment.sn===o.fragment.sn?r(l,o):n--}}}function yVs(s,t,r){const n=t.skippedSegments,a=Math.max(s.startSN,t.startSN)-t.startSN,i=(s.fragmentHint?1:0)+(n?t.endSN:Math.min(s.endSN,t.endSN))-t.startSN,l=t.startSN-s.startSN,o=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,c=s.fragmentHint?s.fragments.concat(s.fragmentHint):s.fragments;for(let d=a;d<=i;d++){const h=c[l+d];let m=o[d];if(n&&!m&&h&&(m=t.fragments[d]=h),h&&m){r(h,m,d,o);const p=h.relurl,x=m.relurl;if(p&&vVs(p,x)){t.playlistParsingError=IKe(`media sequence mismatch ${m.sn}:`,s,t,h,m);return}else if(h.cc!==m.cc){t.playlistParsingError=IKe(`discontinuity sequence mismatch (${h.cc}!=${m.cc})`,s,t,h,m);return}}}}function IKe(s,t,r,n,a){return new Error(`${s} ${a.url} Playlist starting @${t.startSN} ${t.m3u8} Playlist starting @${r.startSN} ${r.m3u8}`)}function m1t(s,t,r=!0){const n=t.startSN+t.skippedSegments-s.startSN,a=s.fragments,i=n>=0;let l=0;if(i&&nt){const i=n[n.length-1].duration*1e3;i{var n;(n=t.details)==null||n.fragments.forEach(a=>{a.level=r,a.initSegment&&(a.initSegment.level=r)})})}function vVs(s,t){return s!==t&&t?LKe(s)!==LKe(t):!1}function LKe(s){return s.replace(/\?[^?]*$/,"")}function I7(s,t){for(let n=0,a=s.length;ns.startCC)}function DKe(s,t){const r=s.start+t;s.startPTS=r,s.setStart(r),s.endPTS=r+s.duration}function y1t(s,t){const r=t.fragments;for(let n=0,a=r.length;n{const{config:l,fragCurrent:o,media:c,mediaBuffer:d,state:h}=this,m=c?c.currentTime:0,p=mo.bufferInfo(d||c,m,l.maxBufferHole),x=!p.len;if(this.log(`Media seeking to ${ka(m)?m.toFixed(3):m}, state: ${h}, ${x?"out of":"in"} buffer`),this.state===Qr.ENDED)this.resetLoadingState();else if(o){const y=l.maxFragLookUpTolerance,_=o.start-y,b=o.start+o.duration+y;if(x||bp.end){const j=m>b;(m<_||j)&&(j&&o.loader&&(this.log(`Cancelling fragment load for seek (sn: ${o.sn})`),o.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(c){this.fragmentTracker.removeFragmentsInRange(m,1/0,this.playlistType,!0);const y=this.lastCurrentTime;if(m>y&&(this.lastCurrentTime=m),!this.loadingParts){const _=Math.max(p.end,m),b=this.shouldLoadParts(this.getLevelDetails(),_);b&&(this.log(`LL-Part loading ON after seeking to ${m.toFixed(2)} with buffer @${_.toFixed(2)}`),this.loadingParts=b)}}this.hls.hasEnoughToStart||(this.log(`Setting ${x?"startPosition":"nextLoadPosition"} to ${m} for seek without enough to start`),this.nextLoadPosition=m,x&&(this.startPosition=m)),x&&this.state===Qr.IDLE&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=i,this.hls=t,this.fragmentLoader=new Zqs(t.config),this.keyLoader=n,this.fragmentTracker=r,this.config=t.config,this.decrypter=new A6e(t.config)}registerListeners(){const{hls:t}=this;t.on(vt.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(vt.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(vt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(vt.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(vt.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(vt.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(vt.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(vt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(vt.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(vt.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(t){}stopLoad(){if(this.state===Qr.STOPPED)return;this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const t=this.fragCurrent;t!=null&&t.loader&&(t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=Qr.STOPPED}get startPositionValue(){const{nextLoadPosition:t,startPosition:r}=this;return r===-1&&t?t:r}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(t,r){if(r.live||!this.media)return!1;const n=t.end||0,a=this.config.timelineOffset||0;if(n<=a)return!1;const i=t.buffered;this.config.maxBufferHole&&i&&i.length>1&&(t=mo.bufferedInfo(i,t.start,0));const l=t.nextStart;if(l&&l>a&&l{const l=i.frag;if(this.fragContextChanged(l)){this.warn(`${l.type} sn: ${l.sn}${i.part?" part: "+i.part.index:""} of ${this.fragInfo(l,!1,i.part)}) was dropped during download.`),this.fragmentTracker.removeFragment(l);return}l.stats.chunkCount++,this._handleFragmentLoadProgress(i)};this._doFragLoad(t,r,n,a).then(i=>{if(!i)return;const l=this.state,o=i.frag;if(this.fragContextChanged(o)){(l===Qr.FRAG_LOADING||!this.fragCurrent&&l===Qr.PARSING)&&(this.fragmentTracker.removeFragment(o),this.state=Qr.IDLE);return}"payload"in i&&(this.log(`Loaded ${o.type} sn: ${o.sn} of ${this.playlistLabel()} ${o.level}`),this.hls.trigger(vt.FRAG_LOADED,i)),this._handleFragmentLoadComplete(i)}).catch(i=>{this.state===Qr.STOPPED||this.state===Qr.ERROR||(this.warn(`Frag error: ${(i==null?void 0:i.message)||i}`),this.resetFragmentLoading(t))})}clearTrackerIfNeeded(t){var r;const{fragmentTracker:n}=this;if(n.getState(t)===im.APPENDING){const i=t.type,l=this.getFwdBufferInfo(this.mediaBuffer,i),o=Math.max(t.duration,l?l.len:this.config.maxBufferLength),c=this.backtrackFragment;((c?t.sn-c.sn:0)===1||this.reduceMaxBufferLength(o,t.duration))&&n.removeFragment(t)}else((r=this.mediaBuffer)==null?void 0:r.buffered.length)===0?n.removeAllFragments():n.hasParts(t.type)&&(n.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type}),n.getState(t)===im.PARTIAL&&n.removeFragment(t))}checkLiveUpdate(t){if(t.updated&&!t.live){const r=t.fragments[t.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:r,part:null,stats:r.stats,id:r.type})}t.fragments[0]||(t.deltaUpdateFailed=!0)}waitForLive(t){const r=t.details;return(r==null?void 0:r.live)&&r.type!=="EVENT"&&(this.levelLastLoaded!==t||r.expired)}flushMainBuffer(t,r,n=null){if(!(t-r))return;const a={startOffset:t,endOffset:r,type:n};this.hls.trigger(vt.BUFFER_FLUSHING,a)}_loadInitSegment(t,r){this._doFragLoad(t,r).then(n=>{const a=n==null?void 0:n.frag;if(!a||this.fragContextChanged(a)||!this.levels)throw new Error("init load aborted");return n}).then(n=>{const{hls:a}=this,{frag:i,payload:l}=n,o=i.decryptdata;if(l&&l.byteLength>0&&o!=null&&o.key&&o.iv&&jP(o.method)){const c=self.performance.now();return this.decrypter.decrypt(new Uint8Array(l),o.key.buffer,o.iv.buffer,I6e(o.method)).catch(d=>{throw a.trigger(vt.ERROR,{type:ci.MEDIA_ERROR,details:yr.FRAG_DECRYPT_ERROR,fatal:!1,error:d,reason:d.message,frag:i}),d}).then(d=>{const h=self.performance.now();return a.trigger(vt.FRAG_DECRYPTED,{frag:i,payload:d,stats:{tstart:c,tdecrypt:h}}),n.payload=d,this.completeInitSegmentLoad(n)})}return this.completeInitSegmentLoad(n)}).catch(n=>{this.state===Qr.STOPPED||this.state===Qr.ERROR||(this.warn(n),this.resetFragmentLoading(t))})}completeInitSegmentLoad(t){const{levels:r}=this;if(!r)throw new Error("init load aborted, missing levels");const n=t.frag.stats;this.state!==Qr.STOPPED&&(this.state=Qr.IDLE),t.frag.data=new Uint8Array(t.payload),n.parsing.start=n.buffering.start=self.performance.now(),n.parsing.end=n.buffering.end=self.performance.now(),this.tick()}unhandledEncryptionError(t,r){var n,a;const i=t.tracks;if(i&&!r.encrypted&&((n=i.audio)!=null&&n.encrypted||(a=i.video)!=null&&a.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){const l=this.media,o=new Error(`Encrypted track with no key in ${this.fragInfo(r)} (media ${l?"attached mediaKeys: "+l.mediaKeys:"detached"})`);return this.warn(o.message),!l||l.mediaKeys?!1:(this.hls.trigger(vt.ERROR,{type:ci.KEY_SYSTEM_ERROR,details:yr.KEY_SYSTEM_NO_KEYS,fatal:!1,error:o,frag:r}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(t){const{fragCurrent:r}=this;return!t||!r||t.sn!==r.sn||t.level!==r.level}fragBufferedComplete(t,r){const n=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${t.type} sn: ${t.sn}${r?" part: "+r.index:""} of ${this.fragInfo(t,!1,r)} > buffer:${n?wVs.toString(mo.getBuffered(n)):"(detached)"})`),dh(t)){var a;if(t.type!==Ba.SUBTITLE){const l=t.elementaryStreams;if(!Object.keys(l).some(o=>!!l[o])){this.state=Qr.IDLE;return}}const i=(a=this.levels)==null?void 0:a[t.level];i!=null&&i.fragmentError&&(this.log(`Resetting level fragment error count of ${i.fragmentError} on frag buffered`),i.fragmentError=0)}this.state=Qr.IDLE}_handleFragmentLoadComplete(t){const{transmuxer:r}=this;if(!r)return;const{frag:n,part:a,partsLoaded:i}=t,l=!i||i.length===0||i.some(c=>!c),o=new M6e(n.level,n.sn,n.stats.chunkCount+1,0,a?a.index:-1,!l);r.flush(o)}_handleFragmentLoadProgress(t){}_doFragLoad(t,r,n=null,a){var i;this.fragCurrent=t;const l=r.details;if(!this.levels||!l)throw new Error(`frag load aborted, missing level${l?"":" detail"}s`);let o=null;if(t.encrypted&&!((i=t.decryptdata)!=null&&i.key)){if(this.log(`Loading key for ${t.sn} of [${l.startSN}-${l.endSN}], ${this.playlistLabel()} ${t.level}`),this.state=Qr.KEY_LOADING,this.fragCurrent=t,o=this.keyLoader.load(t).then(p=>{if(!this.fragContextChanged(p.frag))return this.hls.trigger(vt.KEY_LOADED,p),this.state===Qr.KEY_LOADING&&(this.state=Qr.IDLE),p}),this.hls.trigger(vt.KEY_LOADING,{frag:t}),this.fragCurrent===null)return this.log("context changed in KEY_LOADING"),Promise.resolve(null)}else t.encrypted||(o=this.keyLoader.loadClear(t,l.encryptedFragments,this.startFragRequested),o&&this.log("[eme] blocking frag load until media-keys acquired"));const c=this.fragPrevious;if(dh(t)&&(!c||t.sn!==c.sn)){const p=this.shouldLoadParts(r.details,t.end);p!==this.loadingParts&&(this.log(`LL-Part loading ${p?"ON":"OFF"} loading sn ${c==null?void 0:c.sn}->${t.sn}`),this.loadingParts=p)}if(n=Math.max(t.start,n||0),this.loadingParts&&dh(t)){const p=l.partList;if(p&&a){n>l.fragmentEnd&&l.fragmentHint&&(t=l.fragmentHint);const x=this.getNextPart(p,t,n);if(x>-1){const y=p[x];t=this.fragCurrent=y.fragment,this.log(`Loading ${t.type} sn: ${t.sn} part: ${y.index} (${x}/${p.length-1}) of ${this.fragInfo(t,!1,y)}) cc: ${t.cc} [${l.startSN}-${l.endSN}], target: ${parseFloat(n.toFixed(3))}`),this.nextLoadPosition=y.start+y.duration,this.state=Qr.FRAG_LOADING;let _;return o?_=o.then(b=>!b||this.fragContextChanged(b.frag)?null:this.doFragPartsLoad(t,y,r,a)).catch(b=>this.handleFragLoadError(b)):_=this.doFragPartsLoad(t,y,r,a).catch(b=>this.handleFragLoadError(b)),this.hls.trigger(vt.FRAG_LOADING,{frag:t,part:y,targetBufferTime:n}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):_}else if(!t.url||this.loadedEndOfParts(p,n))return Promise.resolve(null)}}if(dh(t)&&this.loadingParts){var d;this.log(`LL-Part loading OFF after next part miss @${n.toFixed(2)} Check buffer at sn: ${t.sn} loaded parts: ${(d=l.partList)==null?void 0:d.filter(p=>p.loaded).map(p=>`[${p.start}-${p.end}]`)}`),this.loadingParts=!1}else if(!t.url)return Promise.resolve(null);this.log(`Loading ${t.type} sn: ${t.sn} of ${this.fragInfo(t,!1)}) cc: ${t.cc} ${"["+l.startSN+"-"+l.endSN+"]"}, target: ${parseFloat(n.toFixed(3))}`),ka(t.sn)&&!this.bitrateTest&&(this.nextLoadPosition=t.start+t.duration),this.state=Qr.FRAG_LOADING;const h=this.config.progressive&&t.type!==Ba.SUBTITLE;let m;return h&&o?m=o.then(p=>!p||this.fragContextChanged(p.frag)?null:this.fragmentLoader.load(t,a)).catch(p=>this.handleFragLoadError(p)):m=Promise.all([this.fragmentLoader.load(t,h?a:void 0),o]).then(([p])=>(!h&&a&&a(p),p)).catch(p=>this.handleFragLoadError(p)),this.hls.trigger(vt.FRAG_LOADING,{frag:t,targetBufferTime:n}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):m}doFragPartsLoad(t,r,n,a){return new Promise((i,l)=>{var o;const c=[],d=(o=n.details)==null?void 0:o.partList,h=m=>{this.fragmentLoader.loadPart(t,m,a).then(p=>{c[m.index]=p;const x=p.part;this.hls.trigger(vt.FRAG_LOADED,p);const y=PKe(n.details,t.sn,m.index+1)||g1t(d,t.sn,m.index+1);if(y)h(y);else return i({frag:t,part:x,partsLoaded:c})}).catch(l)};h(r)})}handleFragLoadError(t){if("data"in t){const r=t.data;r.frag&&r.details===yr.INTERNAL_ABORTED?this.handleFragLoadAborted(r.frag,r.part):r.frag&&r.type===ci.KEY_SYSTEM_ERROR?(r.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(r.frag)):this.hls.trigger(vt.ERROR,r)}else this.hls.trigger(vt.ERROR,{type:ci.OTHER_ERROR,details:yr.INTERNAL_EXCEPTION,err:t,error:t,fatal:!0});return null}_handleTransmuxerFlush(t){const r=this.getCurrentContext(t);if(!r||this.state!==Qr.PARSING){!this.fragCurrent&&this.state!==Qr.STOPPED&&this.state!==Qr.ERROR&&(this.state=Qr.IDLE);return}const{frag:n,part:a,level:i}=r,l=self.performance.now();n.stats.parsing.end=l,a&&(a.stats.parsing.end=l);const o=this.getLevelDetails(),d=o&&n.sn>o.endSN||this.shouldLoadParts(o,n.end);d!==this.loadingParts&&(this.log(`LL-Part loading ${d?"ON":"OFF"} after parsing segment ending @${n.end.toFixed(2)}`),this.loadingParts=d),this.updateLevelTiming(n,a,i,t.partial)}shouldLoadParts(t,r){if(this.config.lowLatencyMode){if(!t)return this.loadingParts;if(t.partList){var n;const i=t.partList[0];if(i.fragment.type===Ba.SUBTITLE)return!1;const l=i.end+(((n=t.fragmentHint)==null?void 0:n.duration)||0);if(r>=l){var a;if((this.hls.hasEnoughToStart?((a=this.media)==null?void 0:a.currentTime)||this.lastCurrentTime:this.getLoadPosition())>i.start-i.fragment.duration)return!0}}}return!1}getCurrentContext(t){const{levels:r,fragCurrent:n}=this,{level:a,sn:i,part:l}=t;if(!(r!=null&&r[a]))return this.warn(`Levels object was unset while buffering fragment ${i} of ${this.playlistLabel()} ${a}. The current chunk will not be buffered.`),null;const o=r[a],c=o.details,d=l>-1?PKe(c,i,l):null,h=d?d.fragment:p1t(c,i,n);return h?(n&&n!==h&&(h.stats=n.stats),{frag:h,part:d,level:o}):null}bufferFragmentData(t,r,n,a,i){if(this.state!==Qr.PARSING)return;const{data1:l,data2:o}=t;let c=l;if(o&&(c=tv(l,o)),!c.length)return;const d=this.initPTS[r.cc],h=d?-d.baseTime/d.timescale:void 0,m={type:t.type,frag:r,part:n,chunkMeta:a,offset:h,parent:r.type,data:c};if(this.hls.trigger(vt.BUFFER_APPENDING,m),t.dropped&&t.independent&&!n){if(i)return;this.flushBufferGap(r)}}flushBufferGap(t){const r=this.media;if(!r)return;if(!mo.isBuffered(r,r.currentTime)){this.flushMainBuffer(0,t.start);return}const n=r.currentTime,a=mo.bufferInfo(r,n,0),i=t.duration,l=Math.min(this.config.maxFragLookUpTolerance*2,i*.25),o=Math.max(Math.min(t.start-l,a.end-l),n+l);t.start-o>l&&this.flushMainBuffer(o,t.start)}getFwdBufferInfo(t,r){var n;const a=this.getLoadPosition();if(!ka(a))return null;const l=this.lastCurrentTime>a||(n=this.media)!=null&&n.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(t,a,r,l)}getFwdBufferInfoAtPos(t,r,n,a){const i=mo.bufferInfo(t,r,a);if(i.len===0&&i.nextStart!==void 0){const l=this.fragmentTracker.getBufferedFrag(r,n);if(l&&(i.nextStart<=l.end||l.gap)){const o=Math.max(Math.min(i.nextStart,l.end)-r,a);return mo.bufferInfo(t,r,o)}}return i}getMaxBufferLength(t){const{config:r}=this;let n;return t?n=Math.max(8*r.maxBufferSize/t,r.maxBufferLength):n=r.maxBufferLength,Math.min(n,r.maxMaxBufferLength)}exceedsMaxBuffer(t,r,n){const a=t.nextStart;if(a&&n.start>a){const i=t.buffered;if(i){let l=t.len;const o=t.bufferedIndex;for(let c=i.length-1;c>o;c--)i[c].start=r}}return!1}reduceMaxBufferLength(t,r){const n=this.config,a=Math.max(Math.min(t-r,n.maxBufferLength),r),i=Math.max(t-r*3,n.maxMaxBufferLength/2,a);return i>=a?(n.maxMaxBufferLength=i,this.warn(`Reduce max buffer length to ${i}s`),!0):!1}getAppendedFrag(t,r=Ba.MAIN){const n=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(t,r):null;return n&&"fragment"in n?n.fragment:n}getNextFragment(t,r){const n=r.fragments,a=n.length;if(!a)return null;const{config:i}=this,l=r.fragmentStart,o=i.lowLatencyMode&&!!r.partList;let c=null;if(r.live){const m=i.initialLiveManifestSize;if(a=l?(b=x,j=x===p?"config":"next load start"):y!==null?(b=y,j="live edge"):(b=t,j="buffer pos"),b<_&&(b=_,j="live frag start"),b=i){const c=l.sn;return this.loopSn!==c&&(this.log(`buffer full after gaps in "${a}" playlist starting at sn: ${c}`),this.loopSn=c),null}}return this.loopSn=void 0,l}get primaryPrefetch(){if(RKe(this.config)){var t;if((t=this.hls.interstitialsManager)==null||(t=t.playingItem)==null?void 0:t.event)return!0}return!1}filterReplacedPrimary(t,r){if(!t)return t;if(RKe(this.config)&&t.type!==Ba.SUBTITLE){const n=this.hls.interstitialsManager,a=n==null?void 0:n.bufferingItem;if(a){const l=a.event;if(l){if(l.appendInPlace||Math.abs(t.start-a.start)>1||a.start===0)return null}else if(t.end<=a.start&&(r==null?void 0:r.live)===!1||t.start>a.end&&a.nextEvent&&(a.nextEvent.appendInPlace||t.start-a.end>1))return null}const i=n==null?void 0:n.playerQueue;if(i)for(let l=i.length;l--;){const o=i[l].interstitial;if(o.appendInPlace&&t.start>=o.startTime&&t.end<=o.resumeTime)return null}}return t}mapToInitFragWhenRequired(t){return t!=null&&t.initSegment&&!t.initSegment.data&&!this.bitrateTest?t.initSegment:t}getNextPart(t,r,n){let a=-1,i=!1,l=!0;for(let o=0,c=t.length;o-1&&nn.start)return!0}return!1}getInitialLiveFragment(t){const r=t.fragments,n=this.fragPrevious;let a=null;if(n){if(t.hasProgramDateTime&&(a=Fqs(r,n.endProgramDateTime,this.config.maxFragLookUpTolerance),a&&this.log(`Live playlist, switching playlist, load frag with same PDT: ${n.programDateTime}`)),!a){const i=n.sn+1;if(i>=t.startSN&&i<=t.endSN){const l=r[i-t.startSN];n.cc===l.cc&&(a=l,this.log(`Live playlist, switching playlist, load frag with next SN: ${a.sn}`))}a||(a=t1t(t,n.cc,n.end),a&&this.log(`Live playlist, switching playlist, load frag with same CC: ${a.sn}`))}}else{const i=this.hls.liveSyncPosition;i!==null&&(a=this.getFragmentAtPosition(i,this.bitrateTest?t.fragmentEnd:t.edge,t))}return a}getFragmentAtPosition(t,r,n){const{config:a}=this;let{fragPrevious:i}=this,{fragments:l,endSN:o}=n;const{fragmentHint:c}=n,{maxFragLookUpTolerance:d}=a,h=n.partList,m=!!(this.loadingParts&&h!=null&&h.length&&c);m&&!this.bitrateTest&&h[h.length-1].fragment.sn===c.sn&&(l=l.concat(c),o=c.sn);let p;if(tr-d||(x=this.media)!=null&&x.paused||!this.startFragRequested?0:d;p=OA(i,l,t,_)}else p=l[l.length-1];if(p){const y=p.sn-n.startSN,_=this.fragmentTracker.getState(p);if((_===im.OK||_===im.PARTIAL&&p.gap)&&(i=p),i&&p.sn===i.sn&&(!m||h[0].fragment.sn>p.sn||!n.live)&&p.level===i.level){const j=l[y+1];p.sn${t.startSN} fragments: ${a}`),c}return i}waitForCdnTuneIn(t){return t.live&&t.canBlockReload&&t.partTarget&&t.tuneInGoal>Math.max(t.partHoldBack,t.partTarget*3)}setStartPosition(t,r){let n=this.startPosition;n=0&&(n=this.nextLoadPosition),n}handleFragLoadAborted(t,r){this.transmuxer&&t.type===this.playlistType&&dh(t)&&t.stats.aborted&&(this.log(`Fragment ${t.sn}${r?" part "+r.index:""} of ${this.playlistLabel()} ${t.level} was aborted`),this.resetFragmentLoading(t))}resetFragmentLoading(t){(!this.fragCurrent||!this.fragContextChanged(t)&&this.state!==Qr.FRAG_LOADING_WAITING_RETRY)&&(this.state=Qr.IDLE)}onFragmentOrKeyLoadError(t,r){var n;if(r.chunkMeta&&!r.frag){const j=this.getCurrentContext(r.chunkMeta);j&&(r.frag=j.frag)}const a=r.frag;if(!a||a.type!==t||!this.levels)return;if(this.fragContextChanged(a)){var i;this.warn(`Frag load error must match current frag to retry ${a.url} > ${(i=this.fragCurrent)==null?void 0:i.url}`);return}const l=r.details===yr.FRAG_GAP;l&&this.fragmentTracker.fragBuffered(a,!0);const o=r.errorAction;if(!o){this.state=Qr.ERROR;return}const{action:c,flags:d,retryCount:h=0,retryConfig:m}=o,p=!!m,x=p&&c===If.RetryRequest,y=p&&!o.resolved&&d===Kx.MoveAllAlternatesMatchingHost,_=(n=this.hls.latestLevelDetails)==null?void 0:n.live;if(!x&&y&&dh(a)&&!a.endList&&_&&!r1t(r))this.resetFragmentErrors(t),this.treatAsGap(a),o.resolved=!0;else if((x||y)&&h=r||n&&!rCe(0))&&(n&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=Qr.IDLE)}reduceLengthAndFlushBuffer(t){if(this.state===Qr.PARSING||this.state===Qr.PARSED){const r=t.frag,n=t.parent,a=this.getFwdBufferInfo(this.mediaBuffer,n),i=a&&a.len>.5;i&&this.reduceMaxBufferLength(a.len,(r==null?void 0:r.duration)||10);const l=!i;return l&&this.warn(`Buffer full error while media.currentTime (${this.getLoadPosition()}) is not buffered, flush ${n} buffer`),r&&(this.fragmentTracker.removeFragment(r),this.nextLoadPosition=r.start),this.resetLoadingState(),l}return!1}resetFragmentErrors(t){t===Ba.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==Qr.STOPPED&&(this.state=Qr.IDLE)}afterBufferFlushed(t,r,n){if(!t)return;const a=mo.getBuffered(t);this.fragmentTracker.detectEvictedFragments(r,a,n),this.state===Qr.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==Qr.STOPPED&&(this.state=Qr.IDLE)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const t=this.levelLastLoaded,r=t?t.details:null;r!=null&&r.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(r,r.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(t){this.log(`Loading context changed while buffering sn ${t.sn} of ${this.playlistLabel()} ${t.level===-1?"":t.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(t=0){this.fragmentTracker.removeFragmentsInRange(t,1/0,this.playlistType,!1,!0)}updateLevelTiming(t,r,n,a){const i=n.details;if(!i){this.warn("level.details undefined");return}if(!Object.keys(t.elementaryStreams).reduce((c,d)=>{const h=t.elementaryStreams[d];if(h){const m=h.endPTS-h.startPTS;if(m<=0)return this.warn(`Could not parse fragment ${t.sn} ${d} duration reliably (${m})`),c||!1;const p=a?0:h1t(i,t,h.startPTS,h.endPTS,h.startDTS,h.endDTS,this);return this.hls.trigger(vt.LEVEL_PTS_UPDATED,{details:i,level:n,drift:p,type:d,frag:t,start:h.startPTS,end:h.endPTS}),!0}return c},!1)){var o;const c=((o=this.transmuxer)==null?void 0:o.error)===null;if((n.fragmentError===0||c&&(n.fragmentError<2||t.endList))&&this.treatAsGap(t,n),c){const d=new Error(`Found no media in fragment ${t.sn} of ${this.playlistLabel()} ${t.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(d.message),this.hls.trigger(vt.ERROR,{type:ci.MEDIA_ERROR,details:yr.FRAG_PARSING_ERROR,fatal:!1,error:d,frag:t,reason:`Found no media in msn ${t.sn} of ${this.playlistLabel()} "${n.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=Qr.PARSED,this.log(`Parsed ${t.type} sn: ${t.sn}${r?" part: "+r.index:""} of ${this.fragInfo(t,!1,r)})`),this.hls.trigger(vt.FRAG_PARSED,{frag:t,part:r})}playlistLabel(){return this.playlistType===Ba.MAIN?"level":"track"}fragInfo(t,r=!0,n){var a,i;return`${this.playlistLabel()} ${t.level} (${n?"part":"frag"}:[${((a=r&&!n?t.startPTS:(n||t).start)!=null?a:NaN).toFixed(3)}-${((i=r&&!n?t.endPTS:(n||t).end)!=null?i:NaN).toFixed(3)}]${n&&t.type==="main"?"INDEPENDENT="+(n.independent?"YES":"NO"):""}`}treatAsGap(t,r){r&&r.fragmentError++,t.gap=!0,this.fragmentTracker.removeFragment(t),this.fragmentTracker.fragBuffered(t,!0)}resetTransmuxer(){var t;(t=this.transmuxer)==null||t.reset()}recoverWorkerError(t){t.event==="demuxerWorker"&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(t){const r=this._state;r!==t&&(this._state=t,this.log(`${r}->${t}`))}get state(){return this._state}}function RKe(s){return!!s.interstitialsController&&s.enableInterstitialPlayback!==!1}class b1t{constructor(){this.chunks=[],this.dataLength=0}push(t){this.chunks.push(t),this.dataLength+=t.length}flush(){const{chunks:t,dataLength:r}=this;let n;if(t.length)t.length===1?n=t[0]:n=jVs(t,r);else return new Uint8Array(0);return this.reset(),n}reset(){this.chunks.length=0,this.dataLength=0}}function jVs(s,t){const r=new Uint8Array(t);let n=0;for(let a=0;a0)return s.subarray(r,r+n)}function AVs(s,t,r,n){const a=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],i=t[r+2],l=i>>2&15;if(l>12){const x=new Error(`invalid ADTS sampling index:${l}`);s.emit(vt.ERROR,vt.ERROR,{type:ci.MEDIA_ERROR,details:yr.FRAG_PARSING_ERROR,fatal:!0,error:x,reason:x.message});return}const o=(i>>6&3)+1,c=t[r+3]>>6&3|(i&1)<<2,d="mp4a.40."+o,h=a[l];let m=l;(o===5||o===29)&&(m-=3);const p=[o<<3|(m&14)>>1,(m&1)<<7|c<<3];return gc.log(`manifest codec:${n}, parsed codec:${d}, channels:${c}, rate:${h} (ADTS object type:${o} sampling index:${l})`),{config:p,samplerate:h,channelCount:c,codec:d,parsedCodec:d,manifestCodec:n}}function w1t(s,t){return s[t]===255&&(s[t+1]&246)===240}function j1t(s,t){return s[t+1]&1?7:9}function O6e(s,t){return(s[t+3]&3)<<11|s[t+4]<<3|(s[t+5]&224)>>>5}function MVs(s,t){return t+5=s.length)return!1;const n=O6e(s,t);if(n<=r)return!1;const a=t+n;return a===s.length||Npe(s,a)}return!1}function N1t(s,t,r,n,a){if(!s.samplerate){const i=AVs(t,r,n,a);if(!i)return;Ec(s,i)}}function k1t(s){return 1024*9e4/s}function LVs(s,t){const r=j1t(s,t);if(t+r<=s.length){const n=O6e(s,t)-r;if(n>0)return{headerLength:r,frameLength:n}}}function S1t(s,t,r,n,a){const i=k1t(s.samplerate),l=n+a*i,o=LVs(t,r);let c;if(o){const{frameLength:m,headerLength:p}=o,x=p+m,y=Math.max(0,r+x-t.length);y?(c=new Uint8Array(x-p),c.set(t.subarray(r+p,t.length),0)):c=t.subarray(r+p,r+x);const _={unit:c,pts:l};return y||s.samples.push(_),{sample:_,length:x,missing:y}}const d=t.length-r;return c=new Uint8Array(d),c.set(t.subarray(r,t.length),0),{sample:{unit:c,pts:l},length:d,missing:-1}}function DVs(s,t){return R6e(s,t)&&hye(s,t+6)+10<=s.length-t}function RVs(s){return s instanceof ArrayBuffer?s:s.byteOffset==0&&s.byteLength==s.buffer.byteLength?s.buffer:new Uint8Array(s).buffer}function qwe(s,t=0,r=1/0){return OVs(s,t,r,Uint8Array)}function OVs(s,t,r,n){const a=FVs(s);let i=1;"BYTES_PER_ELEMENT"in n&&(i=n.BYTES_PER_ELEMENT);const l=BVs(s)?s.byteOffset:0,o=(l+s.byteLength)/i,c=(l+t)/i,d=Math.floor(Math.max(0,Math.min(c,o))),h=Math.floor(Math.min(d+Math.max(r,0),o));return new n(a,d,h-d)}function FVs(s){return s instanceof ArrayBuffer?s:s.buffer}function BVs(s){return s&&s.buffer instanceof ArrayBuffer&&s.byteLength!==void 0&&s.byteOffset!==void 0}function zVs(s){const t={key:s.type,description:"",data:"",mimeType:null,pictureType:null},r=3;if(s.size<2)return;if(s.data[0]!==r){console.log("Ignore frame with unrecognized character encoding");return}const n=s.data.subarray(1).indexOf(0);if(n===-1)return;const a=w0(qwe(s.data,1,n)),i=s.data[2+n],l=s.data.subarray(3+n).indexOf(0);if(l===-1)return;const o=w0(qwe(s.data,3+n,l));let c;return a==="-->"?c=w0(qwe(s.data,4+n+l)):c=RVs(s.data.subarray(4+n+l)),t.mimeType=a,t.pictureType=i,t.description=o,t.data=c,t}function $Vs(s){if(s.size<2)return;const t=w0(s.data,!0),r=new Uint8Array(s.data.subarray(t.length+1));return{key:s.type,info:t,data:r.buffer}}function UVs(s){if(s.size<2)return;if(s.type==="TXXX"){let r=1;const n=w0(s.data.subarray(r),!0);r+=n.length+1;const a=w0(s.data.subarray(r));return{key:s.type,info:n,data:a}}const t=w0(s.data.subarray(1));return{key:s.type,info:"",data:t}}function qVs(s){if(s.type==="WXXX"){if(s.size<2)return;let r=1;const n=w0(s.data.subarray(r),!0);r+=n.length+1;const a=w0(s.data.subarray(r));return{key:s.type,info:n,data:a}}const t=w0(s.data);return{key:s.type,info:"",data:t}}function VVs(s){return s.type==="PRIV"?$Vs(s):s.type[0]==="W"?qVs(s):s.type==="APIC"?zVs(s):UVs(s)}function HVs(s){const t=String.fromCharCode(s[0],s[1],s[2],s[3]),r=hye(s,4),n=10;return{type:t,size:r,data:s.subarray(n,n+r)}}const hV=10,GVs=10;function C1t(s){let t=0;const r=[];for(;R6e(s,t);){const n=hye(s,t+6);s[t+5]>>6&1&&(t+=hV),t+=hV;const a=t+n;for(;t+GVs0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:n,type:s0.audioId3,duration:Number.POSITIVE_INFINITY});a{if(ka(s))return s*90;const n=r?r.baseTime*9e4/r.timescale:0;return t*9e4+n};let mV=null;const YVs=[32,64,96,128,160,192,224,256,288,320,352,384,416,448,32,48,56,64,80,96,112,128,160,192,224,256,320,384,32,40,48,56,64,80,96,112,128,160,192,224,256,320,32,48,56,64,80,96,112,128,144,160,176,192,224,256,8,16,24,32,40,48,56,64,80,96,112,128,144,160],ZVs=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],XVs=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],QVs=[0,1,1,4];function E1t(s,t,r,n,a){if(r+24>t.length)return;const i=A1t(t,r);if(i&&r+i.frameLength<=t.length){const l=i.samplesPerFrame*9e4/i.sampleRate,o=n+a*l,c={unit:t.subarray(r,r+i.frameLength),pts:o,dts:o};return s.config=[],s.channelCount=i.channelCount,s.samplerate=i.sampleRate,s.samples.push(c),{sample:c,length:i.frameLength,missing:0}}}function A1t(s,t){const r=s[t+1]>>3&3,n=s[t+1]>>1&3,a=s[t+2]>>4&15,i=s[t+2]>>2&3;if(r!==1&&a!==0&&a!==15&&i!==3){const l=s[t+2]>>1&1,o=s[t+3]>>6,c=r===3?3-n:n===3?3:4,d=YVs[c*14+a-1]*1e3,m=ZVs[(r===3?0:r===2?1:2)*3+i],p=o===3?1:2,x=XVs[r][n],y=QVs[n],_=x*8*y,b=Math.floor(x*d/m+l)*y;if(mV===null){const T=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);mV=T?parseInt(T[1]):0}return!!mV&&mV<=87&&n===2&&d>=224e3&&o===0&&(s[t+3]=s[t+3]|128),{sampleRate:m,channelCount:p,frameLength:b,samplesPerFrame:_}}}function z6e(s,t){return s[t]===255&&(s[t+1]&224)===224&&(s[t+1]&6)!==0}function M1t(s,t){return t+1{let r=0,n=5;t+=n;const a=new Uint32Array(1),i=new Uint32Array(1),l=new Uint8Array(1);for(;n>0;){l[0]=s[t];const o=Math.min(n,8),c=8-o;i[0]=4278190080>>>24+c<>c,r=r?r<t.length||t[r]!==11||t[r+1]!==119)return-1;const i=t[r+4]>>6;if(i>=3)return-1;const o=[48e3,44100,32e3][i],c=t[r+4]&63,h=[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][c*3+i]*2;if(r+h>t.length)return-1;const m=t[r+6]>>5;let p=0;m===2?p+=2:(m&1&&m!==1&&(p+=2),m&4&&(p+=2));const x=(t[r+6]<<8|t[r+7])>>12-p&1,_=[2,1,2,3,3,4,4,5][m]+x,b=t[r+5]>>3,j=t[r+5]&7,k=new Uint8Array([i<<6|b<<1|j>>2,(j&3)<<6|m<<3|x<<2|c>>4,c<<4&224]),T=1536/o*9e4,E=n+a*T,A=t.subarray(r,r+h);return s.config=k,s.channelCount=_,s.samplerate=o,s.samples.push({unit:A,pts:E}),h}class sHs extends B6e{resetInitSegment(t,r,n,a){super.resetInitSegment(t,r,n,a),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:r,duration:a,inputTimeScale:9e4,dropped:0}}static probe(t){if(!t)return!1;const r=jB(t,0);let n=(r==null?void 0:r.length)||0;if(r&&t[n]===11&&t[n+1]===119&&F6e(r)!==void 0&&P1t(t,n)<=16)return!1;for(let a=t.length;n{const l=dqs(i);if(rHs.test(l.schemeIdUri)){const o=FKe(l,r);let c=l.eventDuration===4294967295?Number.POSITIVE_INFINITY:l.eventDuration/l.timeScale;c<=.001&&(c=Number.POSITIVE_INFINITY);const d=l.payload;n.samples.push({data:d,len:d.byteLength,dts:o,pts:o,type:s0.emsg,duration:c})}else if(this.config.enableEmsgKLVMetadata&&l.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const o=FKe(l,r);n.samples.push({data:l.payload,len:l.payload.byteLength,dts:o,pts:o,type:s0.misbklv,duration:Number.POSITIVE_INFINITY})}})}return n}demuxSampleAes(t,r,n){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0}}function FKe(s,t){return ka(s.presentationTime)?s.presentationTime/s.timeScale:t+s.presentationTimeDelta/s.timeScale}class aHs{constructor(t,r,n){this.keyData=void 0,this.decrypter=void 0,this.keyData=n,this.decrypter=new A6e(r,{removePKCS7Padding:!1})}decryptBuffer(t){return this.decrypter.decrypt(t,this.keyData.key.buffer,this.keyData.iv.buffer,ES.cbc)}decryptAacSample(t,r,n){const a=t[r].unit;if(a.length<=16)return;const i=a.subarray(16,a.length-a.length%16),l=i.buffer.slice(i.byteOffset,i.byteOffset+i.length);this.decryptBuffer(l).then(o=>{const c=new Uint8Array(o);a.set(c,16),this.decrypter.isSync()||this.decryptAacSamples(t,r+1,n)}).catch(n)}decryptAacSamples(t,r,n){for(;;r++){if(r>=t.length){n();return}if(!(t[r].unit.length<32)&&(this.decryptAacSample(t,r,n),!this.decrypter.isSync()))return}}getAvcEncryptedData(t){const r=Math.floor((t.length-48)/160)*16+16,n=new Int8Array(r);let a=0;for(let i=32;i{i.data=this.getAvcDecryptedUnit(l,c),this.decrypter.isSync()||this.decryptAvcSamples(t,r,n+1,a)}).catch(a)}decryptAvcSamples(t,r,n,a){if(t instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;r++,n=0){if(r>=t.length){a();return}const i=t[r].units;for(;!(n>=i.length);n++){const l=i[n];if(!(l.data.length<=48||l.type!==1&&l.type!==5)&&(this.decryptAvcSample(t,r,n,a,l),!this.decrypter.isSync()))return}}}}class D1t{constructor(){this.VideoSample=null}createVideoSample(t,r,n){return{key:t,frame:!1,pts:r,dts:n,units:[],length:0}}getLastNalUnit(t){var r;let n=this.VideoSample,a;if((!n||n.units.length===0)&&(n=t[t.length-1]),(r=n)!=null&&r.units){const i=n.units;a=i[i.length-1]}return a}pushAccessUnit(t,r){if(t.units.length&&t.frame){if(t.pts===void 0){const n=r.samples,a=n.length;if(a){const i=n[a-1];t.pts=i.pts,t.dts=i.dts}else{r.dropped++;return}}r.samples.push(t)}}parseNALu(t,r,n){const a=r.byteLength;let i=t.naluState||0;const l=i,o=[];let c=0,d,h,m,p=-1,x=0;for(i===-1&&(p=0,x=this.getNALuType(r,0),i=0,c=1);c=0){const y={data:r.subarray(p,h),type:x};o.push(y)}else{const y=this.getLastNalUnit(t.samples);y&&(l&&c<=4-l&&y.state&&(y.data=y.data.subarray(0,y.data.byteLength-l)),h>0&&(y.data=tv(y.data,r.subarray(0,h)),y.state=0))}c=0&&i>=0){const y={data:r.subarray(p,a),type:x,state:i};o.push(y)}if(o.length===0){const y=this.getLastNalUnit(t.samples);y&&(y.data=tv(y.data,r))}return t.naluState=i,o}}class P7{constructor(t){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=t,this.bytesAvailable=t.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const t=this.data,r=this.bytesAvailable,n=t.byteLength-r,a=new Uint8Array(4),i=Math.min(4,r);if(i===0)throw new Error("no bytes available");a.set(t.subarray(n,n+i)),this.word=new DataView(a.buffer).getUint32(0),this.bitsAvailable=i*8,this.bytesAvailable-=i}skipBits(t){let r;t=Math.min(t,this.bytesAvailable*8+this.bitsAvailable),this.bitsAvailable>t?(this.word<<=t,this.bitsAvailable-=t):(t-=this.bitsAvailable,r=t>>3,t-=r<<3,this.bytesAvailable-=r,this.loadWord(),this.word<<=t,this.bitsAvailable-=t)}readBits(t){let r=Math.min(this.bitsAvailable,t);const n=this.word>>>32-r;if(t>32&&gc.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=r,this.bitsAvailable>0)this.word<<=r;else if(this.bytesAvailable>0)this.loadWord();else throw new Error("no bits available");return r=t-r,r>0&&this.bitsAvailable?n<>>t)return this.word<<=t,this.bitsAvailable-=t,t;return this.loadWord(),t+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const t=this.skipLZ();return this.readBits(t+1)-1}readEG(){const t=this.readUEG();return 1&t?1+t>>>1:-1*(t>>>1)}readBoolean(){return this.readBits(1)===1}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}}class iHs extends D1t{parsePES(t,r,n,a){const i=this.parseNALu(t,n.data,a);let l=this.VideoSample,o,c=!1;n.data=null,l&&i.length&&!t.audFound&&(this.pushAccessUnit(l,t),l=this.VideoSample=this.createVideoSample(!1,n.pts,n.dts)),i.forEach(d=>{var h,m;switch(d.type){case 1:{let _=!1;o=!0;const b=d.data;if(c&&b.length>4){const j=this.readSliceType(b);(j===2||j===4||j===7||j===9)&&(_=!0)}if(_){var p;(p=l)!=null&&p.frame&&!l.key&&(this.pushAccessUnit(l,t),l=this.VideoSample=null)}l||(l=this.VideoSample=this.createVideoSample(!0,n.pts,n.dts)),l.frame=!0,l.key=_;break}case 5:o=!0,(h=l)!=null&&h.frame&&!l.key&&(this.pushAccessUnit(l,t),l=this.VideoSample=null),l||(l=this.VideoSample=this.createVideoSample(!0,n.pts,n.dts)),l.key=!0,l.frame=!0;break;case 6:{o=!0,S6e(d.data,1,n.pts,r.samples);break}case 7:{var x,y;o=!0,c=!0;const _=d.data,b=this.readSPS(_);if(!t.sps||t.width!==b.width||t.height!==b.height||((x=t.pixelRatio)==null?void 0:x[0])!==b.pixelRatio[0]||((y=t.pixelRatio)==null?void 0:y[1])!==b.pixelRatio[1]){t.width=b.width,t.height=b.height,t.pixelRatio=b.pixelRatio,t.sps=[_];const j=_.subarray(1,4);let k="avc1.";for(let T=0;T<3;T++){let E=j[T].toString(16);E.length<2&&(E="0"+E),k+=E}t.codec=k}break}case 8:o=!0,t.pps=[d.data];break;case 9:o=!0,t.audFound=!0,(m=l)!=null&&m.frame&&(this.pushAccessUnit(l,t),l=null),l||(l=this.VideoSample=this.createVideoSample(!1,n.pts,n.dts));break;case 12:o=!0;break;default:o=!1;break}l&&o&&l.units.push(d)}),a&&l&&(this.pushAccessUnit(l,t),this.VideoSample=null)}getNALuType(t,r){return t[r]&31}readSliceType(t){const r=new P7(t);return r.readUByte(),r.readUEG(),r.readUEG()}skipScalingList(t,r){let n=8,a=8,i;for(let l=0;l{var h,m;switch(d.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:l||(l=this.VideoSample=this.createVideoSample(!1,n.pts,n.dts)),l.frame=!0,o=!0;break;case 16:case 17:case 18:case 21:if(o=!0,c){var p;(p=l)!=null&&p.frame&&!l.key&&(this.pushAccessUnit(l,t),l=this.VideoSample=null)}l||(l=this.VideoSample=this.createVideoSample(!0,n.pts,n.dts)),l.key=!0,l.frame=!0;break;case 19:case 20:o=!0,(h=l)!=null&&h.frame&&!l.key&&(this.pushAccessUnit(l,t),l=this.VideoSample=null),l||(l=this.VideoSample=this.createVideoSample(!0,n.pts,n.dts)),l.key=!0,l.frame=!0;break;case 39:o=!0,S6e(d.data,2,n.pts,r.samples);break;case 32:o=!0,t.vps||(typeof t.params!="object"&&(t.params={}),t.params=Ec(t.params,this.readVPS(d.data)),this.initVPS=d.data),t.vps=[d.data];break;case 33:if(o=!0,c=!0,t.vps!==void 0&&t.vps[0]!==this.initVPS&&t.sps!==void 0&&!this.matchSPS(t.sps[0],d.data)&&(this.initVPS=t.vps[0],t.sps=t.pps=void 0),!t.sps){const x=this.readSPS(d.data);t.width=x.width,t.height=x.height,t.pixelRatio=x.pixelRatio,t.codec=x.codecString,t.sps=[],typeof t.params!="object"&&(t.params={});for(const y in x.params)t.params[y]=x.params[y]}this.pushParameterSet(t.sps,d.data,t.vps),l||(l=this.VideoSample=this.createVideoSample(!0,n.pts,n.dts)),l.key=!0;break;case 34:if(o=!0,typeof t.params=="object"){if(!t.pps){t.pps=[];const x=this.readPPS(d.data);for(const y in x)t.params[y]=x[y]}this.pushParameterSet(t.pps,d.data,t.vps)}break;case 35:o=!0,t.audFound=!0,(m=l)!=null&&m.frame&&(this.pushAccessUnit(l,t),l=null),l||(l=this.VideoSample=this.createVideoSample(!1,n.pts,n.dts));break;default:o=!1;break}l&&o&&l.units.push(d)}),a&&l&&(this.pushAccessUnit(l,t),this.VideoSample=null)}pushParameterSet(t,r,n){(n&&n[0]===this.initVPS||!n&&!t.length)&&t.push(r)}getNALuType(t,r){return(t[r]&126)>>>1}ebsp2rbsp(t){const r=new Uint8Array(t.byteLength);let n=0;for(let a=0;a=2&&t[a]===3&&t[a-1]===0&&t[a-2]===0||(r[n]=t[a],n++);return new Uint8Array(r.buffer,0,n)}pushAccessUnit(t,r){super.pushAccessUnit(t,r),this.initVPS&&(this.initVPS=null)}readVPS(t){const r=new P7(t);r.readUByte(),r.readUByte(),r.readBits(4),r.skipBits(2),r.readBits(6);const n=r.readBits(3),a=r.readBoolean();return{numTemporalLayers:n+1,temporalIdNested:a}}readSPS(t){const r=new P7(this.ebsp2rbsp(t));r.readUByte(),r.readUByte(),r.readBits(4);const n=r.readBits(3);r.readBoolean();const a=r.readBits(2),i=r.readBoolean(),l=r.readBits(5),o=r.readUByte(),c=r.readUByte(),d=r.readUByte(),h=r.readUByte(),m=r.readUByte(),p=r.readUByte(),x=r.readUByte(),y=r.readUByte(),_=r.readUByte(),b=r.readUByte(),j=r.readUByte(),k=[],T=[];for(let Ue=0;Ue0)for(let Ue=n;Ue<8;Ue++)r.readBits(2);for(let Ue=0;Ue1&&r.readEG();for(let it=0;it<$e;it++)r.readEG()}r.readBoolean(),r.readBoolean(),r.readBoolean()&&(r.readUByte(),r.skipUEG(),r.skipUEG(),r.readBoolean());const ne=r.readUEG();let le=0;for(let Ue=0;Ue0&&Je<16?(je=st[Je-1],ve=mt[Je-1]):Je===255&&(je=r.readBits(16),ve=r.readBits(16))}if(r.readBoolean()&&r.readBoolean(),r.readBoolean()&&(r.readBits(3),r.readBoolean(),r.readBoolean()&&(r.readUByte(),r.readUByte(),r.readUByte())),r.readBoolean()&&(r.readUEG(),r.readUEG()),r.readBoolean(),r.readBoolean(),r.readBoolean(),Me=r.readBoolean(),Me&&(r.skipUEG(),r.skipUEG(),r.skipUEG(),r.skipUEG()),r.readBoolean()&&(Ve=r.readBits(32),Le=r.readBits(32),r.readBoolean()&&r.readUEG(),r.readBoolean())){const mt=r.readBoolean(),wt=r.readBoolean();let at=!1;(mt||wt)&&(at=r.readBoolean(),at&&(r.readUByte(),r.readBits(5),r.readBoolean(),r.readBits(5)),r.readBits(4),r.readBits(4),at&&r.readBits(4),r.readBits(5),r.readBits(5),r.readBits(5));for(let rt=0;rt<=n;rt++){We=r.readBoolean();const Et=We||r.readBoolean();let hs=!1;Et?r.readEG():hs=r.readBoolean();const Is=hs?1:r.readUEG()+1;if(mt)for(let lr=0;lr>Ue&1)<<31-Ue)>>>0;let ge=tt.toString(16);return l===1&&ge==="2"&&(ge="6"),{codecString:`hvc1.${De}${l}.${ge}.${i?"H":"L"}${j}.B0`,params:{general_tier_flag:i,general_profile_idc:l,general_profile_space:a,general_profile_compatibility_flags:[o,c,d,h],general_constraint_indicator_flags:[m,p,x,y,_,b],general_level_idc:j,bit_depth:Z+8,bit_depth_luma_minus8:Z,bit_depth_chroma_minus8:J,min_spatial_segmentation_idc:fe,chroma_format_idc:E,frame_rate:{fixed:We,fps:Le/Ve}},width:Pe,height:Ie,pixelRatio:[je,ve]}}readPPS(t){const r=new P7(this.ebsp2rbsp(t));r.readUByte(),r.readUByte(),r.skipUEG(),r.skipUEG(),r.skipBits(2),r.skipBits(3),r.skipBits(2),r.skipUEG(),r.skipUEG(),r.skipEG(),r.skipBits(2),r.readBoolean()&&r.skipUEG(),r.skipEG(),r.skipEG(),r.skipBits(4);const a=r.readBoolean(),i=r.readBoolean();let l=1;return i&&a?l=0:i?l=3:a&&(l=2),{parallelismType:l}}matchSPS(t,r){return String.fromCharCode.apply(null,t).substr(3)===String.fromCharCode.apply(null,r).substr(3)}}const Vm=188;class XN{constructor(t,r,n,a){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=t,this.config=r,this.typeSupported=n,this.logger=a,this.videoParser=null}static probe(t,r){const n=XN.syncOffset(t);return n>0&&r.warn(`MPEG2-TS detected but first sync word found @ offset ${n}`),n!==-1}static syncOffset(t){const r=t.length;let n=Math.min(Vm*5,r-Vm)+1,a=0;for(;a1&&(l===0&&o>2||c+Vm>n))return l}else{if(o)return-1;break}a++}return-1}static createTrack(t,r){return{container:t==="video"||t==="audio"?"video/mp2t":void 0,type:t,id:$vt[t],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:t==="audio"?r:void 0}}resetInitSegment(t,r,n,a){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=XN.createTrack("video"),this._videoTrack.duration=a,this._audioTrack=XN.createTrack("audio",a),this._id3Track=XN.createTrack("id3"),this._txtTrack=XN.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=r,this.videoCodec=n}resetTimeStamp(){}resetContiguity(){const{_audioTrack:t,_videoTrack:r,_id3Track:n}=this;t&&(t.pesData=null),r&&(r.pesData=null),n&&(n.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(t,r,n=!1,a=!1){n||(this.sampleAes=null);let i;const l=this._videoTrack,o=this._audioTrack,c=this._id3Track,d=this._txtTrack;let h=l.pid,m=l.pesData,p=o.pid,x=c.pid,y=o.pesData,_=c.pesData,b=null,j=this.pmtParsed,k=this._pmtId,T=t.length;if(this.remainderData&&(t=tv(this.remainderData,t),T=t.length,this.remainderData=null),T>4;let ee;if($>1){if(ee=R+5+t[R+4],ee===R+Vm)continue}else ee=R+4;switch(O){case h:z&&(m&&(i=D6(m,this.logger))&&(this.readyVideoParser(l.segmentCodec),this.videoParser!==null&&this.videoParser.parsePES(l,d,i,!1)),m={data:[],size:0}),m&&(m.data.push(t.subarray(ee,R+Vm)),m.size+=R+Vm-ee);break;case p:if(z){if(y&&(i=D6(y,this.logger)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,i);break;case"mp3":this.parseMPEGPES(o,i);break;case"ac3":this.parseAC3PES(o,i);break}y={data:[],size:0}}y&&(y.data.push(t.subarray(ee,R+Vm)),y.size+=R+Vm-ee);break;case x:z&&(_&&(i=D6(_,this.logger))&&this.parseID3PES(c,i),_={data:[],size:0}),_&&(_.data.push(t.subarray(ee,R+Vm)),_.size+=R+Vm-ee);break;case 0:z&&(ee+=t[ee]+1),k=this._pmtId=lHs(t,ee);break;case k:{z&&(ee+=t[ee]+1);const Z=cHs(t,ee,this.typeSupported,n,this.observer,this.logger);h=Z.videoPid,h>0&&(l.pid=h,l.segmentCodec=Z.segmentVideoCodec),p=Z.audioPid,p>0&&(o.pid=p,o.segmentCodec=Z.segmentAudioCodec),x=Z.id3Pid,x>0&&(c.pid=x),b!==null&&!j&&(this.logger.warn(`MPEG-TS PMT found at ${R} after unknown PID '${b}'. Backtracking to sync byte @${E} to parse all TS packets.`),b=null,R=E-188),j=this.pmtParsed=!0;break}case 17:case 8191:break;default:b=O;break}}else A++;A>0&&cCe(this.observer,new Error(`Found ${A} TS packet/s that do not start with 0x47`),void 0,this.logger),l.pesData=m,o.pesData=y,c.pesData=_;const D={audioTrack:o,videoTrack:l,id3Track:c,textTrack:d};return a&&this.extractRemainingSamples(D),D}flush(){const{remainderData:t}=this;this.remainderData=null;let r;return t?r=this.demux(t,-1,!1,!0):r={videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(r),this.sampleAes?this.decrypt(r,this.sampleAes):r}extractRemainingSamples(t){const{audioTrack:r,videoTrack:n,id3Track:a,textTrack:i}=t,l=n.pesData,o=r.pesData,c=a.pesData;let d;if(l&&(d=D6(l,this.logger))?(this.readyVideoParser(n.segmentCodec),this.videoParser!==null&&(this.videoParser.parsePES(n,i,d,!0),n.pesData=null)):n.pesData=l,o&&(d=D6(o,this.logger))){switch(r.segmentCodec){case"aac":this.parseAACPES(r,d);break;case"mp3":this.parseMPEGPES(r,d);break;case"ac3":this.parseAC3PES(r,d);break}r.pesData=null}else o!=null&&o.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),r.pesData=o;c&&(d=D6(c,this.logger))?(this.parseID3PES(a,d),a.pesData=null):a.pesData=c}demuxSampleAes(t,r,n){const a=this.demux(t,n,!0,!this.config.progressive),i=this.sampleAes=new aHs(this.observer,this.config,r);return this.decrypt(a,i)}readyVideoParser(t){this.videoParser===null&&(t==="avc"?this.videoParser=new iHs:t==="hevc"&&(this.videoParser=new oHs))}decrypt(t,r){return new Promise(n=>{const{audioTrack:a,videoTrack:i}=t;a.samples&&a.segmentCodec==="aac"?r.decryptAacSamples(a.samples,0,()=>{i.samples?r.decryptAvcSamples(i.samples,0,0,()=>{n(t)}):n(t)}):i.samples&&r.decryptAvcSamples(i.samples,0,0,()=>{n(t)})})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0}parseAACPES(t,r){let n=0;const a=this.aacOverFlow;let i=r.data;if(a){this.aacOverFlow=null;const m=a.missing,p=a.sample.unit.byteLength;if(m===-1)i=tv(a.sample.unit,i);else{const x=p-m;a.sample.unit.set(i.subarray(0,m),x),t.samples.push(a.sample),n=a.missing}}let l,o;for(l=n,o=i.length;l0;)o+=c}}parseID3PES(t,r){if(r.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const n=Ec({},r,{type:this._videoTrack?s0.emsg:s0.audioId3,duration:Number.POSITIVE_INFINITY});t.samples.push(n)}}function lCe(s,t){return((s[t+1]&31)<<8)+s[t+2]}function lHs(s,t){return(s[t+10]&31)<<8|s[t+11]}function cHs(s,t,r,n,a,i){const l={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},o=(s[t+1]&15)<<8|s[t+2],c=t+3+o-4,d=(s[t+10]&15)<<8|s[t+11];for(t+=12+d;t0){let p=t+5,x=m;for(;x>2;){switch(s[p]){case 106:r.ac3!==!0?i.log("AC-3 audio found, not supported in this browser for now"):(l.audioPid=h,l.segmentAudioCodec="ac3");break}const _=s[p+1]+2;p+=_,x-=_}}break;case 194:case 135:return cCe(a,new Error("Unsupported EC-3 in M2TS found"),void 0,i),l;case 36:l.videoPid===-1&&(l.videoPid=h,l.segmentVideoCodec="hevc",i.log("HEVC in M2TS found"));break}t+=m+5}return l}function cCe(s,t,r,n){n.warn(`parsing error: ${t.message}`),s.emit(vt.ERROR,vt.ERROR,{type:ci.MEDIA_ERROR,details:yr.FRAG_PARSING_ERROR,fatal:!1,levelRetry:r,error:t,reason:t.message})}function Vwe(s,t){t.log(`${s} with AES-128-CBC encryption found in unencrypted stream`)}function D6(s,t){let r=0,n,a,i,l,o;const c=s.data;if(!s||s.size===0)return null;for(;c[0].length<19&&c.length>1;)c[0]=tv(c[0],c[1]),c.splice(1,1);if(n=c[0],(n[0]<<16)+(n[1]<<8)+n[2]===1){if(a=(n[4]<<8)+n[5],a&&a>s.size-6)return null;const h=n[7];h&192&&(l=(n[9]&14)*536870912+(n[10]&255)*4194304+(n[11]&254)*16384+(n[12]&255)*128+(n[13]&254)/2,h&64?(o=(n[14]&14)*536870912+(n[15]&255)*4194304+(n[16]&254)*16384+(n[17]&255)*128+(n[18]&254)/2,l-o>60*9e4&&(t.warn(`${Math.round((l-o)/9e4)}s delta between PTS and DTS, align them`),l=o)):o=l),i=n[8];let m=i+9;if(s.size<=m)return null;s.size-=m;const p=new Uint8Array(s.size);for(let x=0,y=c.length;x_){m-=_;continue}else n=n.subarray(m),_-=m,m=0;p.set(n,r),r+=_}return a&&(a-=i+3),{data:p,pts:l,dts:o,len:a}}return null}class dHs{static getSilentFrame(t,r){switch(t){case"mp4a.40.2":if(r===1)return new Uint8Array([0,200,0,128,35,128]);if(r===2)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(r===3)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(r===4)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(r===5)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(r===6)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224]);break;default:if(r===1)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(r===2)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(r===3)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);break}}}const SN=Math.pow(2,32)-1;class xr{static init(){xr.types={avc1:[],avcC:[],hvc1:[],hvcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]};let t;for(t in xr.types)xr.types.hasOwnProperty(t)&&(xr.types[t]=[t.charCodeAt(0),t.charCodeAt(1),t.charCodeAt(2),t.charCodeAt(3)]);const r=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),n=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);xr.HDLR_TYPES={video:r,audio:n};const a=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),i=new Uint8Array([0,0,0,0,0,0,0,0]);xr.STTS=xr.STSC=xr.STCO=i,xr.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),xr.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),xr.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),xr.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const l=new Uint8Array([105,115,111,109]),o=new Uint8Array([97,118,99,49]),c=new Uint8Array([0,0,0,1]);xr.FTYP=xr.box(xr.types.ftyp,l,c,l,o),xr.DINF=xr.box(xr.types.dinf,xr.box(xr.types.dref,a))}static box(t,...r){let n=8,a=r.length;const i=a;for(;a--;)n+=r[a].byteLength;const l=new Uint8Array(n);for(l[0]=n>>24&255,l[1]=n>>16&255,l[2]=n>>8&255,l[3]=n&255,l.set(t,4),a=0,n=8;a>24&255,t>>16&255,t>>8&255,t&255,n>>24,n>>16&255,n>>8&255,n&255,a>>24,a>>16&255,a>>8&255,a&255,85,196,0,0]))}static mdia(t){return xr.box(xr.types.mdia,xr.mdhd(t.timescale||0,t.duration||0),xr.hdlr(t.type),xr.minf(t))}static mfhd(t){return xr.box(xr.types.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,t&255]))}static minf(t){return t.type==="audio"?xr.box(xr.types.minf,xr.box(xr.types.smhd,xr.SMHD),xr.DINF,xr.stbl(t)):xr.box(xr.types.minf,xr.box(xr.types.vmhd,xr.VMHD),xr.DINF,xr.stbl(t))}static moof(t,r,n){return xr.box(xr.types.moof,xr.mfhd(t),xr.traf(n,r))}static moov(t){let r=t.length;const n=[];for(;r--;)n[r]=xr.trak(t[r]);return xr.box.apply(null,[xr.types.moov,xr.mvhd(t[0].timescale||0,t[0].duration||0)].concat(n).concat(xr.mvex(t)))}static mvex(t){let r=t.length;const n=[];for(;r--;)n[r]=xr.trex(t[r]);return xr.box.apply(null,[xr.types.mvex,...n])}static mvhd(t,r){r*=t;const n=Math.floor(r/(SN+1)),a=Math.floor(r%(SN+1)),i=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,t&255,n>>24,n>>16&255,n>>8&255,n&255,a>>24,a>>16&255,a>>8&255,a&255,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return xr.box(xr.types.mvhd,i)}static sdtp(t){const r=t.samples||[],n=new Uint8Array(4+r.length);let a,i;for(a=0;a>>8&255),r.push(l&255),r=r.concat(Array.prototype.slice.call(i));for(a=0;a>>8&255),n.push(l&255),n=n.concat(Array.prototype.slice.call(i));const o=xr.box(xr.types.avcC,new Uint8Array([1,r[3],r[4],r[5],255,224|t.sps.length].concat(r).concat([t.pps.length]).concat(n))),c=t.width,d=t.height,h=t.pixelRatio[0],m=t.pixelRatio[1];return xr.box(xr.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,c>>8&255,c&255,d>>8&255,d&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),o,xr.box(xr.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),xr.box(xr.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,h&255,m>>24,m>>16&255,m>>8&255,m&255])))}static esds(t){const r=t.config;return new Uint8Array([0,0,0,0,3,25,0,1,0,4,17,64,21,0,0,0,0,0,0,0,0,0,0,0,5,2,...r,6,1,2])}static audioStsd(t){const r=t.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t.channelCount||0,0,16,0,0,0,0,r>>8&255,r&255,0,0])}static mp4a(t){return xr.box(xr.types.mp4a,xr.audioStsd(t),xr.box(xr.types.esds,xr.esds(t)))}static mp3(t){return xr.box(xr.types[".mp3"],xr.audioStsd(t))}static ac3(t){return xr.box(xr.types["ac-3"],xr.audioStsd(t),xr.box(xr.types.dac3,t.config))}static stsd(t){const{segmentCodec:r}=t;if(t.type==="audio"){if(r==="aac")return xr.box(xr.types.stsd,xr.STSD,xr.mp4a(t));if(r==="ac3"&&t.config)return xr.box(xr.types.stsd,xr.STSD,xr.ac3(t));if(r==="mp3"&&t.codec==="mp3")return xr.box(xr.types.stsd,xr.STSD,xr.mp3(t))}else if(t.pps&&t.sps){if(r==="avc")return xr.box(xr.types.stsd,xr.STSD,xr.avc1(t));if(r==="hevc"&&t.vps)return xr.box(xr.types.stsd,xr.STSD,xr.hvc1(t))}else throw new Error("video track missing pps or sps");throw new Error(`unsupported ${t.type} segment codec (${r}/${t.codec})`)}static tkhd(t){const r=t.id,n=(t.duration||0)*(t.timescale||0),a=t.width||0,i=t.height||0,l=Math.floor(n/(SN+1)),o=Math.floor(n%(SN+1));return xr.box(xr.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,r>>24&255,r>>16&255,r>>8&255,r&255,0,0,0,0,l>>24,l>>16&255,l>>8&255,l&255,o>>24,o>>16&255,o>>8&255,o&255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,a>>8&255,a&255,0,0,i>>8&255,i&255,0,0]))}static traf(t,r){const n=xr.sdtp(t),a=t.id,i=Math.floor(r/(SN+1)),l=Math.floor(r%(SN+1));return xr.box(xr.types.traf,xr.box(xr.types.tfhd,new Uint8Array([0,0,0,0,a>>24,a>>16&255,a>>8&255,a&255])),xr.box(xr.types.tfdt,new Uint8Array([1,0,0,0,i>>24,i>>16&255,i>>8&255,i&255,l>>24,l>>16&255,l>>8&255,l&255])),xr.trun(t,n.length+16+20+8+16+8+8),n)}static trak(t){return t.duration=t.duration||4294967295,xr.box(xr.types.trak,xr.tkhd(t),xr.mdia(t))}static trex(t){const r=t.id;return xr.box(xr.types.trex,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,r&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(t,r){const n=t.samples||[],a=n.length,i=12+16*a,l=new Uint8Array(i);let o,c,d,h,m,p;for(r+=8+i,l.set([t.type==="video"?1:0,0,15,1,a>>>24&255,a>>>16&255,a>>>8&255,a&255,r>>>24&255,r>>>16&255,r>>>8&255,r&255],0),o=0;o>>24&255,d>>>16&255,d>>>8&255,d&255,h>>>24&255,h>>>16&255,h>>>8&255,h&255,m.isLeading<<2|m.dependsOn,m.isDependedOn<<6|m.hasRedundancy<<4|m.paddingValue<<1|m.isNonSync,m.degradPrio&61440,m.degradPrio&15,p>>>24&255,p>>>16&255,p>>>8&255,p&255],12+16*o);return xr.box(xr.types.trun,l)}static initSegment(t){xr.types||xr.init();const r=xr.moov(t);return tv(xr.FTYP,r)}static hvc1(t){const r=t.params,n=[t.vps,t.sps,t.pps],a=4,i=new Uint8Array([1,r.general_profile_space<<6|(r.general_tier_flag?32:0)|r.general_profile_idc,r.general_profile_compatibility_flags[0],r.general_profile_compatibility_flags[1],r.general_profile_compatibility_flags[2],r.general_profile_compatibility_flags[3],r.general_constraint_indicator_flags[0],r.general_constraint_indicator_flags[1],r.general_constraint_indicator_flags[2],r.general_constraint_indicator_flags[3],r.general_constraint_indicator_flags[4],r.general_constraint_indicator_flags[5],r.general_level_idc,240|r.min_spatial_segmentation_idc>>8,255&r.min_spatial_segmentation_idc,252|r.parallelismType,252|r.chroma_format_idc,248|r.bit_depth_luma_minus8,248|r.bit_depth_chroma_minus8,0,parseInt(r.frame_rate.fps),a-1|r.temporal_id_nested<<2|r.num_temporal_layers<<3|(r.frame_rate.fixed?64:0),n.length]);let l=i.length;for(let y=0;y>8,n[y][_].length&255]),l),l+=2,o.set(n[y][_],l),l+=n[y][_].length}const d=xr.box(xr.types.hvcC,o),h=t.width,m=t.height,p=t.pixelRatio[0],x=t.pixelRatio[1];return xr.box(xr.types.hvc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,h>>8&255,h&255,m>>8&255,m&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),d,xr.box(xr.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),xr.box(xr.types.pasp,new Uint8Array([p>>24,p>>16&255,p>>8&255,p&255,x>>24,x>>16&255,x>>8&255,x&255])))}}xr.types=void 0;xr.HDLR_TYPES=void 0;xr.STTS=void 0;xr.STSC=void 0;xr.STCO=void 0;xr.STSZ=void 0;xr.VMHD=void 0;xr.SMHD=void 0;xr.STSD=void 0;xr.FTYP=void 0;xr.DINF=void 0;const R1t=9e4;function $6e(s,t,r=1,n=!1){const a=s*t*r;return n?Math.round(a):a}function uHs(s,t,r=1,n=!1){return $6e(s,t,1/r,n)}function aO(s,t=!1){return $6e(s,1e3,1/R1t,t)}function hHs(s,t=1){return $6e(s,R1t,1/t)}function BKe(s){const{baseTime:t,timescale:r,trackId:n}=s;return`${t/r} (${t}/${r}) trackId: ${n}`}const mHs=10*1e3,fHs=1024,pHs=1152,gHs=1536;let R6=null,Hwe=null;function zKe(s,t,r,n){return{duration:t,size:r,cts:n,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:s?2:1,isNonSync:s?0:1}}}class Uue extends dv{constructor(t,r,n,a){if(super("mp4-remuxer",a),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=t,this.config=r,this.typeSupported=n,this.ISGenerated=!1,R6===null){const l=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);R6=l?parseInt(l[1]):0}if(Hwe===null){const i=navigator.userAgent.match(/Safari\/(\d+)/i);Hwe=i?parseInt(i[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(t){const r=this._initPTS;(!r||!t||t.trackId!==r.trackId||t.baseTime!==r.baseTime||t.timescale!==r.timescale)&&this.log(`Reset initPTS: ${r&&BKe(r)} > ${t&&BKe(t)}`),this._initPTS=this._initDTS=t}resetNextTimestamp(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(t){let r=!1;const n=t[0].pts,a=t.reduce((i,l)=>{let o=l.pts,c=o-i;return c<-4294967296&&(r=!0,o=Yx(o,n),c=o-i),c>0?i:o},n);return r&&this.debug("PTS rollover detected"),a}remux(t,r,n,a,i,l,o,c){let d,h,m,p,x,y,_=i,b=i;const j=t.pid>-1,k=r.pid>-1,T=r.samples.length,E=t.samples.length>0,A=o&&T>0||T>1;if((!j||E)&&(!k||A)||this.ISGenerated||o){if(this.ISGenerated){var R,z,O,$;const K=this.videoTrackConfig;(K&&(r.width!==K.width||r.height!==K.height||((R=r.pixelRatio)==null?void 0:R[0])!==((z=K.pixelRatio)==null?void 0:z[0])||((O=r.pixelRatio)==null?void 0:O[1])!==(($=K.pixelRatio)==null?void 0:$[1]))||!K&&A||this.nextAudioTs===null&&E)&&this.resetInitSegment()}this.ISGenerated||(m=this.generateIS(t,r,i,l));const ee=this.isVideoContiguous;let Z=-1,J;if(A&&(Z=xHs(r.samples),!ee&&this.config.forceKeyFrameOnDiscontinuity))if(y=!0,Z>0){this.warn(`Dropped ${Z} out of ${T} video samples due to a missing keyframe`);const K=this.getVideoStartPts(r.samples);r.samples=r.samples.slice(Z),r.dropped+=Z,b+=(r.samples[0].pts-K)/r.inputTimeScale,J=b}else Z===-1&&(this.warn(`No keyframe found out of ${T} video samples`),y=!1);if(this.ISGenerated){if(E&&A){const K=this.getVideoStartPts(r.samples),ie=(Yx(t.samples[0].pts,K)-K)/r.inputTimeScale;_+=Math.max(0,ie),b+=Math.max(0,-ie)}if(E){if(t.samplerate||(this.warn("regenerate InitSegment as audio detected"),m=this.generateIS(t,r,i,l)),h=this.remuxAudio(t,_,this.isAudioContiguous,l,k||A||c===Ba.AUDIO?b:void 0),A){const K=h?h.endPTS-h.startPTS:0;r.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),m=this.generateIS(t,r,i,l)),d=this.remuxVideo(r,b,ee,K)}}else A&&(d=this.remuxVideo(r,b,ee,0));d&&(d.firstKeyFrame=Z,d.independent=Z!==-1,d.firstKeyFramePTS=J)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(n.samples.length&&(x=O1t(n,i,this._initPTS,this._initDTS)),a.samples.length&&(p=F1t(a,i,this._initPTS))),{audio:h,video:d,initSegment:m,independent:y,text:p,id3:x}}computeInitPts(t,r,n,a){const i=Math.round(n*r);let l=Yx(t,i);if(l0?fe-1:fe].dts&&(k=!0)}k&&l.sort(function(fe,je){const ve=fe.dts-je.dts,We=fe.pts-je.pts;return ve||We}),y=l[0].dts,_=l[l.length-1].dts;const E=_-y,A=E?Math.round(E/(c-1)):x||t.inputTimeScale/30;if(n){const fe=y-T,je=fe>A,ve=fe<-1;if((je||ve)&&(je?this.warn(`${(t.segmentCodec||"").toUpperCase()}: ${aO(fe,!0)} ms (${fe}dts) hole between fragments detected at ${r.toFixed(3)}`):this.warn(`${(t.segmentCodec||"").toUpperCase()}: ${aO(-fe,!0)} ms (${fe}dts) overlapping between fragments detected at ${r.toFixed(3)}`),!ve||T>=l[0].pts||R6)){y=T;const We=l[0].pts-fe;if(je)l[0].dts=y,l[0].pts=We;else{let Ve=!0;for(let Le=0;LeWe&&Ve);Le++){const Me=l[Le].pts;if(l[Le].dts-=fe,l[Le].pts-=fe,Le0?je.dts-l[fe-1].dts:A;if(Ve=fe>0?je.pts-l[fe-1].pts:A,Me.stretchShortVideoTrack&&this.nextAudioTs!==null){const Pe=Math.floor(Me.maxBufferHole*i),Ie=(a?b+a*i:this.nextAudioTs+h)-je.pts;Ie>Pe?(x=Ie-ze,x<0?x=ze:Z=!0,this.log(`It is approximately ${Ie/90} ms to the next segment; using duration ${x/90} ms for the last video frame.`)):x=ze}else x=ze}const Le=Math.round(je.pts-je.dts);J=Math.min(J,x),re=Math.max(re,x),K=Math.min(K,Ve),ie=Math.max(ie,Ve),o.push(zKe(je.key,x,We,Le))}if(o.length){if(R6){if(R6<70){const fe=o[0].flags;fe.dependsOn=2,fe.isNonSync=0}}else if(Hwe&&ie-K0&&(a&&Math.abs(T-(j+k))<9e3||Math.abs(Yx(_[0].pts,T)-(j+k))<20*h),_.forEach(function(ie){ie.pts=Yx(ie.pts,T)}),!n||j<0){const ie=_.length;if(_=_.filter(ce=>ce.pts>=0),ie!==_.length&&this.warn(`Removed ${_.length-ie} of ${ie} samples (initPTS ${k} / ${l})`),!_.length)return;i===0?j=0:a&&!y?j=Math.max(0,T-k):j=_[0].pts-k}if(t.segmentCodec==="aac"){const ie=this.config.maxAudioFramesDrift;for(let ce=0,ne=j+k;ce<_.length;ce++){const le=_[ce],be=le.pts,fe=be-ne,je=Math.abs(1e3*fe/l);if(fe<=-ie*h&&y)ce===0&&(this.warn(`Audio frame @ ${(be/l).toFixed(3)}s overlaps marker by ${Math.round(1e3*fe/l)} ms.`),this.nextAudioTs=j=be-k,ne=be);else if(fe>=ie*h&&je0){R+=b;try{D=new Uint8Array(R)}catch(je){this.observer.emit(vt.ERROR,vt.ERROR,{type:ci.MUX_ERROR,details:yr.REMUX_ALLOC_ERROR,fatal:!1,error:je,bytes:R,reason:`fail allocating audio mdat ${R}`});return}p||(new DataView(D.buffer).setUint32(0,R),D.set(xr.types.mdat,4))}else return;D.set(le,b);const fe=le.byteLength;b+=fe,x.push(zKe(!0,d,fe,0)),A=be}const O=x.length;if(!O)return;const $=x[x.length-1];j=A-k,this.nextAudioTs=j+c*$.duration;const ee=p?new Uint8Array(0):xr.moof(t.sequenceNumber++,E/c,Ec({},t,{samples:x}));t.samples=[];const Z=(E-k)/l,J=this.nextAudioTs/l,re={data1:ee,data2:D,startPTS:Z,endPTS:J,startDTS:Z,endDTS:J,type:"audio",hasAudio:!0,hasVideo:!1,nb:O};return this.isAudioContiguous=!0,re}}function Yx(s,t){let r;if(t===null)return s;for(t4294967296;)s+=r;return s}function xHs(s){for(let t=0;tl.pts-o.pts);const i=s.samples;return s.samples=[],{samples:i}}class yHs extends dv{constructor(t,r,n,a){super("passthrough-remuxer",a),this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.isVideoContiguous=!1}destroy(){}resetTimeStamp(t){this.lastEndTime=null;const r=this.initPTS;r&&t&&r.baseTime===t.baseTime&&r.timescale===t.timescale||(this.initPTS=t)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(t,r,n,a){this.audioCodec=r,this.videoCodec=n,this.generateInitSegment(t,a),this.emitInitSegment=!0}generateInitSegment(t,r){let{audioCodec:n,videoCodec:a}=this;if(!(t!=null&&t.byteLength)){this.initTracks=void 0,this.initData=void 0;return}const{audio:i,video:l}=this.initData=Vvt(t);if(r)aqs(t,r);else{const c=i||l;c!=null&&c.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${c.codec}")!`)}i&&(n=$Ke(i,Dc.AUDIO,this)),l&&(a=$Ke(l,Dc.VIDEO,this));const o={};i&&l?o.audiovideo={container:"video/mp4",codec:n+","+a,supplemental:l.supplemental,encrypted:l.encrypted,initSegment:t,id:"main"}:i?o.audio={container:"audio/mp4",codec:n,encrypted:i.encrypted,initSegment:t,id:"audio"}:l?o.video={container:"video/mp4",codec:a,supplemental:l.supplemental,encrypted:l.encrypted,initSegment:t,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=o}remux(t,r,n,a,i,l){var o,c;let{initPTS:d,lastEndTime:h}=this;const m={audio:void 0,video:void 0,text:a,id3:n,initSegment:void 0};ka(h)||(h=this.lastEndTime=i||0);const p=r.samples;if(!p.length)return m;const x={initPTS:void 0,timescale:void 0,trackId:void 0};let y=this.initData;if((o=y)!=null&&o.length||(this.generateInitSegment(p),y=this.initData),!((c=y)!=null&&c.length))return this.warn("Failed to generate initSegment."),m;this.emitInitSegment&&(x.tracks=this.initTracks,this.emitInitSegment=!1);const _=oqs(p,y,this),b=y.audio?_[y.audio.id]:null,j=y.video?_[y.video.id]:null,k=fV(j,1/0),T=fV(b,1/0),E=fV(j,0,!0),A=fV(b,0,!0);let D=i,R=0;const z=b&&(!j||!d&&T0?this.lastEndTime=ee:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const Z=!!y.audio,J=!!y.video;let K="";Z&&(K+="audio"),J&&(K+="video");const re=(y.audio?y.audio.encrypted:!1)||(y.video?y.video.encrypted:!1),ie={data1:p,startPTS:$,startDTS:$,endPTS:ee,endDTS:ee,type:K,hasAudio:Z,hasVideo:J,nb:1,dropped:0,encrypted:re};m.audio=Z&&!J?ie:void 0,m.video=J?ie:void 0;const ce=j==null?void 0:j.sampleCount;if(ce){const ne=j.keyFrameIndex,le=ne!==-1;ie.nb=ce,ie.dropped=ne===0||this.isVideoContiguous?0:le?ne:ce,ie.independent=le,ie.firstKeyFrame=ne,le&&j.keyFrameStart&&(ie.firstKeyFramePTS=(j.keyFrameStart-d.baseTime)/d.timescale),this.isVideoContiguous||(m.independent=le),this.isVideoContiguous||(this.isVideoContiguous=le),ie.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${ne}/${ce} dropped: ${ie.dropped} start: ${ie.firstKeyFramePTS||"NA"}`)}return m.initSegment=x,m.id3=O1t(n,i,d,d),a.samples.length&&(m.text=F1t(a,i,d)),m}}function fV(s,t,r=!1){return(s==null?void 0:s.start)!==void 0?(s.start+(r?s.duration:0))/s.timescale:t}function vHs(s,t,r,n){if(s===null)return!0;const a=Math.max(n,1),i=t-s.baseTime/s.timescale;return Math.abs(i-r)>a}function $Ke(s,t,r){const n=s.codec;return n&&n.length>4?n:t===Dc.AUDIO?n==="ec-3"||n==="ac-3"||n==="alac"?n:n==="fLaC"||n==="Opus"?gpe(n,!1):(r.warn(`Unhandled audio codec "${n}" in mp4 MAP`),n||"mp4a"):(r.warn(`Unhandled video codec "${n}" in mp4 MAP`),n||"avc1")}let x2;try{x2=self.performance.now.bind(self.performance)}catch{x2=Date.now}const que=[{demux:nHs,remux:yHs},{demux:XN,remux:Uue},{demux:eHs,remux:Uue},{demux:sHs,remux:Uue}];que.splice(2,0,{demux:tHs,remux:Uue});class UKe{constructor(t,r,n,a,i,l){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=t,this.typeSupported=r,this.config=n,this.id=i,this.logger=l}configure(t){this.transmuxConfig=t,this.decrypter&&this.decrypter.reset()}push(t,r,n,a){const i=n.transmuxing;i.executeStart=x2();let l=new Uint8Array(t);const{currentTransmuxState:o,transmuxConfig:c}=this;a&&(this.currentTransmuxState=a);const{contiguous:d,discontinuity:h,trackSwitch:m,accurateTimeOffset:p,timeOffset:x,initSegmentChange:y}=a||o,{audioCodec:_,videoCodec:b,defaultInitPts:j,duration:k,initSegmentData:T}=c,E=bHs(l,r);if(E&&jP(E.method)){const z=this.getDecrypter(),O=I6e(E.method);if(z.isSync()){let $=z.softwareDecrypt(l,E.key.buffer,E.iv.buffer,O);if(n.part>-1){const Z=z.flush();$=Z&&Z.buffer}if(!$)return i.executeEnd=x2(),Gwe(n);l=new Uint8Array($)}else return this.asyncResult=!0,this.decryptionPromise=z.webCryptoDecrypt(l,E.key.buffer,E.iv.buffer,O).then($=>{const ee=this.push($,null,n);return this.decryptionPromise=null,ee}),this.decryptionPromise}const A=this.needsProbing(h,m);if(A){const z=this.configureTransmuxer(l);if(z)return this.logger.warn(`[transmuxer] ${z.message}`),this.observer.emit(vt.ERROR,vt.ERROR,{type:ci.MEDIA_ERROR,details:yr.FRAG_PARSING_ERROR,fatal:!1,error:z,reason:z.message}),i.executeEnd=x2(),Gwe(n)}(h||m||y||A)&&this.resetInitSegment(T,_,b,k,r),(h||y||A)&&this.resetInitialTimestamp(j),d||this.resetContiguity();const D=this.transmux(l,E,x,p,n);this.asyncResult=NB(D);const R=this.currentTransmuxState;return R.contiguous=!0,R.discontinuity=!1,R.trackSwitch=!1,i.executeEnd=x2(),D}flush(t){const r=t.transmuxing;r.executeStart=x2();const{decrypter:n,currentTransmuxState:a,decryptionPromise:i}=this;if(i)return this.asyncResult=!0,i.then(()=>this.flush(t));const l=[],{timeOffset:o}=a;if(n){const m=n.flush();m&&l.push(this.push(m.buffer,null,t))}const{demuxer:c,remuxer:d}=this;if(!c||!d){r.executeEnd=x2();const m=[Gwe(t)];return this.asyncResult?Promise.resolve(m):m}const h=c.flush(o);return NB(h)?(this.asyncResult=!0,h.then(m=>(this.flushRemux(l,m,t),l))):(this.flushRemux(l,h,t),this.asyncResult?Promise.resolve(l):l)}flushRemux(t,r,n){const{audioTrack:a,videoTrack:i,id3Track:l,textTrack:o}=r,{accurateTimeOffset:c,timeOffset:d}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${n.sn}${n.part>-1?" part: "+n.part:""} of ${this.id===Ba.MAIN?"level":"track"} ${n.level}`);const h=this.remuxer.remux(a,i,l,o,d,c,!0,this.id);t.push({remuxResult:h,chunkMeta:n}),n.transmuxing.executeEnd=x2()}resetInitialTimestamp(t){const{demuxer:r,remuxer:n}=this;!r||!n||(r.resetTimeStamp(t),n.resetTimeStamp(t))}resetContiguity(){const{demuxer:t,remuxer:r}=this;!t||!r||(t.resetContiguity(),r.resetNextTimestamp())}resetInitSegment(t,r,n,a,i){const{demuxer:l,remuxer:o}=this;!l||!o||(l.resetInitSegment(t,r,n,a),o.resetInitSegment(t,r,n,i))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(t,r,n,a,i){let l;return r&&r.method==="SAMPLE-AES"?l=this.transmuxSampleAes(t,r,n,a,i):l=this.transmuxUnencrypted(t,n,a,i),l}transmuxUnencrypted(t,r,n,a){const{audioTrack:i,videoTrack:l,id3Track:o,textTrack:c}=this.demuxer.demux(t,r,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(i,l,o,c,r,n,!1,this.id),chunkMeta:a}}transmuxSampleAes(t,r,n,a,i){return this.demuxer.demuxSampleAes(t,r,n).then(l=>({remuxResult:this.remuxer.remux(l.audioTrack,l.videoTrack,l.id3Track,l.textTrack,n,a,!1,this.id),chunkMeta:i}))}configureTransmuxer(t){const{config:r,observer:n,typeSupported:a}=this;let i;for(let m=0,p=que.length;m0&&(t==null?void 0:t.key)!=null&&t.iv!==null&&t.method!=null&&(r=t),r}const Gwe=s=>({remuxResult:{},chunkMeta:s});function NB(s){return"then"in s&&s.then instanceof Function}class _Hs{constructor(t,r,n,a,i){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=t,this.videoCodec=r,this.initSegmentData=n,this.duration=a,this.defaultInitPts=i||null}}class wHs{constructor(t,r,n,a,i,l){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=t,this.contiguous=r,this.accurateTimeOffset=n,this.trackSwitch=a,this.timeOffset=i,this.initSegmentChange=l}}let qKe=0;class B1t{constructor(t,r,n,a){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=qKe++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=c=>{const d=c.data,h=this.hls;if(!(!h||!(d!=null&&d.event)||d.instanceNo!==this.instanceNo))switch(d.event){case"init":{var m;const p=(m=this.workerContext)==null?void 0:m.objectURL;p&&self.URL.revokeObjectURL(p);break}case"transmuxComplete":{this.handleTransmuxComplete(d.data);break}case"flush":{this.onFlush(d.data);break}case"workerLog":{h.logger[d.data.logType]&&h.logger[d.data.logType](d.data.message);break}default:{d.data=d.data||{},d.data.frag=this.frag,d.data.part=this.part,d.data.id=this.id,h.trigger(d.event,d.data);break}}},this.onWorkerError=c=>{if(!this.hls)return;const d=new Error(`${c.message} (${c.filename}:${c.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(vt.ERROR,{type:ci.OTHER_ERROR,details:yr.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:d})};const i=t.config;this.hls=t,this.id=r,this.useWorker=!!i.enableWorker,this.onTransmuxComplete=n,this.onFlush=a;const l=(c,d)=>{d=d||{},d.frag=this.frag||void 0,c===vt.ERROR&&(d=d,d.parent=this.id,d.part=this.part,this.error=d.error),this.hls.trigger(c,d)};this.observer=new D6e,this.observer.on(vt.FRAG_DECRYPTED,l),this.observer.on(vt.ERROR,l);const o=nKe(i.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){const c=this.hls.logger;if(i.workerPath||SVs()){try{i.workerPath?(c.log(`loading Web Worker ${i.workerPath} for "${r}"`),this.workerContext=TVs(i.workerPath)):(c.log(`injecting Web Worker for "${r}"`),this.workerContext=CVs());const{worker:h}=this.workerContext;h.addEventListener("message",this.onWorkerMessage),h.addEventListener("error",this.onWorkerError),h.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:o,id:r,config:Uc(i)})}catch(h){c.warn(`Error setting up "${r}" Web Worker, fallback to inline`,h),this.terminateWorker(),this.error=null,this.transmuxer=new UKe(this.observer,o,i,"",r,t.logger)}return}}this.transmuxer=new UKe(this.observer,o,i,"",r,t.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const t=this.instanceNo;this.instanceNo=qKe++;const r=this.hls.config,n=nKe(r.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:t,typeSupported:n,id:this.id,config:Uc(r)})}}terminateWorker(){if(this.workerContext){const{worker:t}=this.workerContext;this.workerContext=null,t.removeEventListener("message",this.onWorkerMessage),t.removeEventListener("error",this.onWorkerError),EVs(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const r=this.transmuxer;r&&(r.destroy(),this.transmuxer=null)}const t=this.observer;t&&t.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(t,r,n,a,i,l,o,c,d,h){var m,p;d.transmuxing.start=self.performance.now();const{instanceNo:x,transmuxer:y}=this,_=l?l.start:i.start,b=i.decryptdata,j=this.frag,k=!(j&&i.cc===j.cc),T=!(j&&d.level===j.level),E=j?d.sn-j.sn:-1,A=this.part?d.part-this.part.index:-1,D=E===0&&d.id>1&&d.id===(j==null?void 0:j.stats.chunkCount),R=!T&&(E===1||E===0&&(A===1||D&&A<=0)),z=self.performance.now();(T||E||i.stats.parsing.start===0)&&(i.stats.parsing.start=z),l&&(A||!R)&&(l.stats.parsing.start=z);const O=!(j&&((m=i.initSegment)==null?void 0:m.url)===((p=j.initSegment)==null?void 0:p.url)),$=new wHs(k,R,c,T,_,O);if(!R||k||O){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${i.type} sn: ${d.sn}${d.part>-1?" part: "+d.part:""} ${this.id===Ba.MAIN?"level":"track"}: ${d.level} id: ${d.id} discontinuity: ${k} trackSwitch: ${T} contiguous: ${R} accurateTimeOffset: ${c} timeOffset: ${_} initSegmentChange: ${O}`);const ee=new _Hs(n,a,r,o,h);this.configureTransmuxer(ee)}if(this.frag=i,this.part=l,this.workerContext)this.workerContext.worker.postMessage({instanceNo:x,cmd:"demux",data:t,decryptdata:b,chunkMeta:d,state:$},t instanceof ArrayBuffer?[t]:[]);else if(y){const ee=y.push(t,b,d,$);NB(ee)?ee.then(Z=>{this.handleTransmuxComplete(Z)}).catch(Z=>{this.transmuxerError(Z,d,"transmuxer-interface push error")}):this.handleTransmuxComplete(ee)}}flush(t){t.transmuxing.start=self.performance.now();const{instanceNo:r,transmuxer:n}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:r,cmd:"flush",chunkMeta:t});else if(n){const a=n.flush(t);NB(a)?a.then(i=>{this.handleFlushResult(i,t)}).catch(i=>{this.transmuxerError(i,t,"transmuxer-interface flush error")}):this.handleFlushResult(a,t)}}transmuxerError(t,r,n){this.hls&&(this.error=t,this.hls.trigger(vt.ERROR,{type:ci.MEDIA_ERROR,details:yr.FRAG_PARSING_ERROR,chunkMeta:r,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:t,err:t,reason:n}))}handleFlushResult(t,r){t.forEach(n=>{this.handleTransmuxComplete(n)}),this.onFlush(r)}configureTransmuxer(t){const{instanceNo:r,transmuxer:n}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:r,cmd:"configure",config:t}):n&&n.configure(t)}handleTransmuxComplete(t){t.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(t)}}const VKe=100;class jHs extends L6e{constructor(t,r,n){super(t,r,n,"audio-stream-controller",Ba.AUDIO),this.mainAnchor=null,this.mainFragLoading=null,this.audioOnly=!1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.resetItem()}resetItem(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null}registerListeners(){super.registerListeners();const{hls:t}=this;t.on(vt.LEVEL_LOADED,this.onLevelLoaded,this),t.on(vt.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.on(vt.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(vt.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(vt.BUFFER_RESET,this.onBufferReset,this),t.on(vt.BUFFER_CREATED,this.onBufferCreated,this),t.on(vt.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(vt.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(vt.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(vt.FRAG_LOADING,this.onFragLoading,this),t.on(vt.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:t}=this;t&&(super.unregisterListeners(),t.off(vt.LEVEL_LOADED,this.onLevelLoaded,this),t.off(vt.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.off(vt.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(vt.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(vt.BUFFER_RESET,this.onBufferReset,this),t.off(vt.BUFFER_CREATED,this.onBufferCreated,this),t.off(vt.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(vt.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(vt.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(vt.FRAG_LOADING,this.onFragLoading,this),t.off(vt.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(t,{frag:r,id:n,initPTS:a,timescale:i,trackId:l}){if(n===Ba.MAIN){const o=r.cc,c=this.fragCurrent;if(this.initPTS[o]={baseTime:a,timescale:i,trackId:l},this.log(`InitPTS for cc: ${o} found from main: ${a/i} (${a}/${i}) trackId: ${l}`),this.mainAnchor=r,this.state===Qr.WAITING_INIT_PTS){const d=this.waitingData;(!d&&!this.loadingParts||d&&d.frag.cc!==o)&&this.syncWithAnchor(r,d==null?void 0:d.frag)}else!this.hls.hasEnoughToStart&&c&&c.cc!==o?(c.abortRequests(),this.syncWithAnchor(r,c)):this.state===Qr.IDLE&&this.tick()}}getLoadPosition(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(t,r){var n;const a=((n=this.mainFragLoading)==null?void 0:n.frag)||null;if(r&&(a==null?void 0:a.cc)===r.cc)return;const i=(a||t).cc,l=this.getLevelDetails(),o=this.getLoadPosition(),c=t1t(l,i,o);c&&(this.log(`Syncing with main frag at ${c.start} cc ${c.cc}`),this.startFragRequested=!1,this.nextLoadPosition=c.start,this.resetLoadingState(),this.state===Qr.IDLE&&this.doTickIdle())}startLoad(t,r){if(!this.levels){this.startPosition=t,this.state=Qr.STOPPED;return}const n=this.lastCurrentTime;this.stopLoad(),this.setInterval(VKe),n>0&&t===-1?(this.log(`Override startPosition with lastCurrentTime @${n.toFixed(3)}`),t=n,this.state=Qr.IDLE):this.state=Qr.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=r?-1:t,this.tick()}doTick(){switch(this.state){case Qr.IDLE:this.doTickIdle();break;case Qr.WAITING_TRACK:{const{levels:t,trackId:r}=this,n=t==null?void 0:t[r],a=n==null?void 0:n.details;if(a&&!this.waitForLive(n)){if(this.waitForCdnTuneIn(a))break;this.state=Qr.WAITING_INIT_PTS}break}case Qr.FRAG_LOADING_WAITING_RETRY:{this.checkRetryDate();break}case Qr.WAITING_INIT_PTS:{const t=this.waitingData;if(t){const{frag:r,part:n,cache:a,complete:i}=t,l=this.mainAnchor;if(this.initPTS[r.cc]!==void 0){this.waitingData=null,this.state=Qr.FRAG_LOADING;const o=a.flush().buffer,c={frag:r,part:n,payload:o,networkDetails:null};this._handleFragmentLoadProgress(c),i&&super._handleFragmentLoadComplete(c)}else l&&l.cc!==t.frag.cc&&this.syncWithAnchor(l,t.frag)}else this.state=Qr.IDLE}}this.onTickEnd()}resetLoadingState(){const t=this.waitingData;t&&(this.fragmentTracker.removeFragment(t.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){const{media:t}=this;t!=null&&t.readyState&&(this.lastCurrentTime=t.currentTime)}doTickIdle(){var t;const{hls:r,levels:n,media:a,trackId:i}=this,l=r.config;if(!this.buffering||!a&&!this.primaryPrefetch&&(this.startFragRequested||!l.startFragPrefetch)||!(n!=null&&n[i]))return;const o=n[i],c=o.details;if(!c||this.waitForLive(o)||this.waitForCdnTuneIn(c)){this.state=Qr.WAITING_TRACK,this.startFragRequested=!1;return}const d=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&d&&(this.bufferFlushed=!1,this.afterBufferFlushed(d,Dc.AUDIO,Ba.AUDIO));const h=this.getFwdBufferInfo(d,Ba.AUDIO);if(h===null)return;if(!this.switchingTrack&&this._streamEnded(h,c)){r.trigger(vt.BUFFER_EOS,{type:"audio"}),this.state=Qr.ENDED;return}const m=h.len,p=r.maxBufferLength,x=c.fragments,y=x[0].start,_=this.getLoadPosition(),b=this.flushing?_:h.end;if(this.switchingTrack&&a){const T=_;c.PTSKnown&&Ty||h.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),a.currentTime=y+.05)}if(m>=p&&!this.switchingTrack&&bk.end){const E=this.fragmentTracker.getFragAtPos(b,Ba.MAIN);E&&E.end>k.end&&(k=E,this.mainFragLoading={frag:E,targetBufferTime:null})}if(j.start>k.end)return}this.loadFragment(j,o,b)}onMediaDetaching(t,r){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(t,r)}onAudioTracksUpdated(t,{audioTracks:r}){this.resetTransmuxer(),this.levels=r.map(n=>new _B(n))}onAudioTrackSwitching(t,r){const n=!!r.url;this.trackId=r.id;const{fragCurrent:a}=this;a&&(a.abortRequests(),this.removeUnbufferedFrags(a.start)),this.resetLoadingState(),n?(this.switchingTrack=r,this.flushAudioIfNeeded(r),this.state!==Qr.STOPPED&&(this.setInterval(VKe),this.state=Qr.IDLE,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=r,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(t,r){this.mainDetails=r.details;const n=this.cachedTrackLoadedData;n&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(vt.AUDIO_TRACK_LOADED,n))}onAudioTrackLoaded(t,r){var n;const{levels:a}=this,{details:i,id:l,groupId:o,track:c}=r;if(!a){this.warn(`Audio tracks reset while loading track ${l} "${c.name}" of "${o}"`);return}const d=this.mainDetails;if(!d||i.endCC>d.endCC||d.expired){this.cachedTrackLoadedData=r,this.state!==Qr.STOPPED&&(this.state=Qr.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${l} "${c.name}" of "${o}" loaded [${i.startSN},${i.endSN}]${i.lastPartSn?`[part-${i.lastPartSn}-${i.lastPartIndex}]`:""},duration:${i.totalduration}`);const h=a[l];let m=0;if(i.live||(n=h.details)!=null&&n.live){if(this.checkLiveUpdate(i),i.deltaUpdateFailed)return;if(h.details){var p;m=this.alignPlaylists(i,h.details,(p=this.levelLastLoaded)==null?void 0:p.details)}i.alignedSliding||(v1t(i,d),i.alignedSliding||jpe(i,d),m=i.fragmentStart)}h.details=i,this.levelLastLoaded=h,this.startFragRequested||this.setStartPosition(d,m),this.hls.trigger(vt.AUDIO_TRACK_UPDATED,{details:i,id:l,groupId:r.groupId}),this.state===Qr.WAITING_TRACK&&!this.waitForCdnTuneIn(i)&&(this.state=Qr.IDLE),this.tick()}_handleFragmentLoadProgress(t){var r;const n=t.frag,{part:a,payload:i}=t,{config:l,trackId:o,levels:c}=this;if(!c){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${n.sn} of level ${n.level} will not be buffered`);return}const d=c[o];if(!d){this.warn("Audio track is undefined on fragment load progress");return}const h=d.details;if(!h){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(n.start);return}const m=l.defaultAudioCodec||d.audioCodec||"mp4a.40.2";let p=this.transmuxer;p||(p=this.transmuxer=new B1t(this.hls,Ba.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const x=this.initPTS[n.cc],y=(r=n.initSegment)==null?void 0:r.data;if(x!==void 0){const b=a?a.index:-1,j=b!==-1,k=new M6e(n.level,n.sn,n.stats.chunkCount,i.byteLength,b,j);p.push(i,y,m,"",n,a,h.totalduration,!1,k,x)}else{this.log(`Unknown video PTS for cc ${n.cc}, waiting for video PTS before demuxing audio frag ${n.sn} of [${h.startSN} ,${h.endSN}],track ${o}`);const{cache:_}=this.waitingData=this.waitingData||{frag:n,part:a,cache:new b1t,complete:!1};_.push(new Uint8Array(i)),this.state!==Qr.STOPPED&&(this.state=Qr.WAITING_INIT_PTS)}}_handleFragmentLoadComplete(t){if(this.waitingData){this.waitingData.complete=!0;return}super._handleFragmentLoadComplete(t)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(t,r){this.bufferFlushed=this.flushing=!1;const n=r.tracks.audio;n&&(this.mediaBuffer=n.buffer||null)}onFragLoading(t,r){!this.audioOnly&&r.frag.type===Ba.MAIN&&dh(r.frag)&&(this.mainFragLoading=r,this.state===Qr.IDLE&&this.tick())}onFragBuffered(t,r){const{frag:n,part:a}=r;if(n.type!==Ba.AUDIO){!this.audioOnly&&n.type===Ba.MAIN&&!n.elementaryStreams.video&&!n.elementaryStreams.audiovideo&&(this.audioOnly=!0,this.mainFragLoading=null);return}if(this.fragContextChanged(n)){this.warn(`Fragment ${n.sn}${a?" p: "+a.index:""} of level ${n.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(dh(n)){this.fragPrevious=n;const i=this.switchingTrack;i&&(this.bufferedTrack=i,this.switchingTrack=null,this.hls.trigger(vt.AUDIO_TRACK_SWITCHED,hc({},i)))}this.fragBufferedComplete(n,a),this.media&&this.tick()}onError(t,r){var n;if(r.fatal){this.state=Qr.ERROR;return}switch(r.details){case yr.FRAG_GAP:case yr.FRAG_PARSING_ERROR:case yr.FRAG_DECRYPT_ERROR:case yr.FRAG_LOAD_ERROR:case yr.FRAG_LOAD_TIMEOUT:case yr.KEY_LOAD_ERROR:case yr.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Ba.AUDIO,r);break;case yr.AUDIO_TRACK_LOAD_ERROR:case yr.AUDIO_TRACK_LOAD_TIMEOUT:case yr.LEVEL_PARSING_ERROR:!r.levelRetry&&this.state===Qr.WAITING_TRACK&&((n=r.context)==null?void 0:n.type)===Vo.AUDIO_TRACK&&(this.state=Qr.IDLE);break;case yr.BUFFER_ADD_CODEC_ERROR:case yr.BUFFER_APPEND_ERROR:if(r.parent!=="audio")return;this.reduceLengthAndFlushBuffer(r)||this.resetLoadingState();break;case yr.BUFFER_FULL_ERROR:if(r.parent!=="audio")return;this.reduceLengthAndFlushBuffer(r)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case yr.INTERNAL_EXCEPTION:this.recoverWorkerError(r);break}}onBufferFlushing(t,{type:r}){r!==Dc.VIDEO&&(this.flushing=!0)}onBufferFlushed(t,{type:r}){if(r!==Dc.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===Qr.ENDED&&(this.state=Qr.IDLE);const n=this.mediaBuffer||this.media;n&&(this.afterBufferFlushed(n,r,Ba.AUDIO),this.tick())}}_handleTransmuxComplete(t){var r;const n="audio",{hls:a}=this,{remuxResult:i,chunkMeta:l}=t,o=this.getCurrentContext(l);if(!o){this.resetWhenMissingContext(l);return}const{frag:c,part:d,level:h}=o,{details:m}=h,{audio:p,text:x,id3:y,initSegment:_}=i;if(this.fragContextChanged(c)||!m){this.fragmentTracker.removeFragment(c);return}if(this.state=Qr.PARSING,this.switchingTrack&&p&&this.completeAudioSwitch(this.switchingTrack),_!=null&&_.tracks){const b=c.initSegment||c;if(this.unhandledEncryptionError(_,c))return;this._bufferInitSegment(h,_.tracks,b,l),a.trigger(vt.FRAG_PARSING_INIT_SEGMENT,{frag:b,id:n,tracks:_.tracks})}if(p){const{startPTS:b,endPTS:j,startDTS:k,endDTS:T}=p;d&&(d.elementaryStreams[Dc.AUDIO]={startPTS:b,endPTS:j,startDTS:k,endDTS:T}),c.setElementaryStreamInfo(Dc.AUDIO,b,j,k,T),this.bufferFragmentData(p,c,d,l)}if(y!=null&&(r=y.samples)!=null&&r.length){const b=Ec({id:n,frag:c,details:m},y);a.trigger(vt.FRAG_PARSING_METADATA,b)}if(x){const b=Ec({id:n,frag:c,details:m},x);a.trigger(vt.FRAG_PARSING_USERDATA,b)}}_bufferInitSegment(t,r,n,a){if(this.state!==Qr.PARSING||(r.video&&delete r.video,r.audiovideo&&delete r.audiovideo,!r.audio))return;const i=r.audio;i.id=Ba.AUDIO;const l=t.audioCodec;this.log(`Init audio buffer, container:${i.container}, codecs[level/parsed]=[${l}/${i.codec}]`),l&&l.split(",").length===1&&(i.levelCodec=l),this.hls.trigger(vt.BUFFER_CODECS,r);const o=i.initSegment;if(o!=null&&o.byteLength){const c={type:"audio",frag:n,part:null,chunkMeta:a,parent:n.type,data:o};this.hls.trigger(vt.BUFFER_APPENDING,c)}this.tickImmediate()}loadFragment(t,r,n){const a=this.fragmentTracker.getState(t);if(this.switchingTrack||a===im.NOT_LOADED||a===im.PARTIAL){var i;if(!dh(t))this._loadInitSegment(t,r);else if((i=r.details)!=null&&i.live&&!this.initPTS[t.cc]){this.log(`Waiting for video PTS in continuity counter ${t.cc} of live stream before loading audio fragment ${t.sn} of level ${this.trackId}`),this.state=Qr.WAITING_INIT_PTS;const l=this.mainDetails;l&&l.fragmentStart!==r.details.fragmentStart&&jpe(r.details,l)}else super.loadFragment(t,r,n)}else this.clearTrackerIfNeeded(t)}flushAudioIfNeeded(t){if(this.media&&this.bufferedTrack){const{name:r,lang:n,assocLang:a,characteristics:i,audioCodec:l,channels:o}=this.bufferedTrack;tA({name:r,lang:n,assocLang:a,characteristics:i,audioCodec:l,channels:o},t,CT)||(ype(t.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=t)}}completeAudioSwitch(t){const{hls:r}=this;this.flushAudioIfNeeded(t),this.bufferedTrack=t,this.switchingTrack=null,r.trigger(vt.AUDIO_TRACK_SWITCHED,hc({},t))}}class U6e extends dv{constructor(t,r){super(r,t.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=t}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){this.timer!==-1&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(t,r,n){const a=r==null?void 0:r.renditionReports;if(a){let i=-1;for(let l=0;l=0&&h>r.partTarget&&(c+=1)}const d=n&&aKe(n);return new iKe(o,c>=0?c:void 0,d)}}}loadPlaylist(t){this.clearTimer()}loadingPlaylist(t,r){this.clearTimer()}shouldLoadPlaylist(t){return this.canLoad&&!!t&&!!t.url&&(!t.details||t.details.live)}getUrlWithDirectives(t,r){if(r)try{return r.addDirectives(t)}catch(n){this.warn(`Could not construct new URL with HLS Delivery Directives: ${n}`)}return t}playlistLoaded(t,r,n){const{details:a,stats:i}=r,l=self.performance.now(),o=i.loading.first?Math.max(0,l-i.loading.first):0;a.advancedDateTime=Date.now()-o;const c=this.hls.config.timelineOffset;if(c!==a.appliedTimelineOffset){const h=Math.max(c||0,0);a.appliedTimelineOffset=h,a.fragments.forEach(m=>{m.setStart(m.playlistOffset+h)})}if(a.live||n!=null&&n.live){const h="levelInfo"in r?r.levelInfo:r.track;if(a.reloaded(n),n&&a.fragments.length>0){pVs(n,a,this);const k=a.playlistParsingError;if(k){this.warn(k);const T=this.hls;if(!T.config.ignorePlaylistParsingErrors){var d;const{networkDetails:E}=r;T.trigger(vt.ERROR,{type:ci.NETWORK_ERROR,details:yr.LEVEL_PARSING_ERROR,fatal:!1,url:a.url,error:k,reason:k.message,level:r.level||void 0,parent:(d=a.fragments[0])==null?void 0:d.type,networkDetails:E,stats:i});return}a.playlistParsingError=null}}a.requestScheduled===-1&&(a.requestScheduled=i.loading.start);const m=this.hls.mainForwardBufferInfo,p=m?m.end-m.len:0,x=(a.edge-p)*1e3,y=f1t(a,x);if(a.requestScheduled+y0){if(O>a.targetduration*3)this.log(`Playlist last advanced ${z.toFixed(2)}s ago. Omitting segment and part directives.`),b=void 0,j=void 0;else if(n!=null&&n.tuneInGoal&&O-a.partTarget>n.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${n.tuneInGoal} to: ${$} with playlist age: ${a.age}`),$=0;else{const ee=Math.floor($/a.targetduration);if(b+=ee,j!==void 0){const Z=Math.round($%a.targetduration/a.partTarget);j+=Z}this.log(`CDN Tune-in age: ${a.ageHeader}s last advanced ${z.toFixed(2)}s goal: ${$} skip sn ${ee} to part ${j}`)}a.tuneInGoal=$}if(_=this.getDeliveryDirectives(a,r.deliveryDirectives,b,j),k||!R){a.requestScheduled=l,this.loadingPlaylist(h,_);return}}else(a.canBlockReload||a.canSkipUntil)&&(_=this.getDeliveryDirectives(a,r.deliveryDirectives,b,j));_&&b!==void 0&&a.canBlockReload&&(a.requestScheduled=i.loading.first+Math.max(y-o*2,y/2)),this.scheduleLoading(h,_,a)}else this.clearTimer()}scheduleLoading(t,r,n){const a=n||t.details;if(!a){this.loadingPlaylist(t,r);return}const i=self.performance.now(),l=a.requestScheduled;if(i>=l){this.loadingPlaylist(t,r);return}const o=l-i;this.log(`reload live playlist ${t.name||t.bitrate+"bps"} in ${Math.round(o)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(t,r),o)}getDeliveryDirectives(t,r,n,a){let i=aKe(t);return r!=null&&r.skip&&t.deltaUpdateFailed&&(n=r.msn,a=r.part,i=zue.No),new iKe(n,a,i)}checkRetry(t){const r=t.details,n=vpe(t),a=t.errorAction,{action:i,retryCount:l=0,retryConfig:o}=a||{},c=!!a&&!!o&&(i===If.RetryRequest||!a.resolved&&i===If.SendAlternateToPenaltyBox);if(c){var d;if(l>=o.maxNumRetry)return!1;if(n&&(d=t.context)!=null&&d.deliveryDirectives)this.warn(`Retrying playlist loading ${l+1}/${o.maxNumRetry} after "${r}" without delivery-directives`),this.loadPlaylist();else{const h=E6e(o,l);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),h),this.warn(`Retrying playlist loading ${l+1}/${o.maxNumRetry} after "${r}" in ${h}ms`)}t.levelRetry=!0,a.resolved=!0}return c}}function z1t(s,t){if(s.length!==t.length)return!1;for(let r=0;rs[a]!==t[a])}function dCe(s,t){return t.label.toLowerCase()===s.name.toLowerCase()&&(!t.language||t.language.toLowerCase()===(s.lang||"").toLowerCase())}class NHs extends U6e{constructor(t){super(t,"audio-track-controller"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:t}=this;t.on(vt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(vt.MANIFEST_PARSED,this.onManifestParsed,this),t.on(vt.LEVEL_LOADING,this.onLevelLoading,this),t.on(vt.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(vt.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(vt.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(vt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(vt.MANIFEST_PARSED,this.onManifestParsed,this),t.off(vt.LEVEL_LOADING,this.onLevelLoading,this),t.off(vt.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(vt.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(vt.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(t,r){this.tracks=r.audioTracks||[]}onAudioTrackLoaded(t,r){const{id:n,groupId:a,details:i}=r,l=this.tracksInGroup[n];if(!l||l.groupId!==a){this.warn(`Audio track with id:${n} and group:${a} not found in active group ${l==null?void 0:l.groupId}`);return}const o=l.details;l.details=r.details,this.log(`Audio track ${n} "${l.name}" lang:${l.lang} group:${a} loaded [${i.startSN}-${i.endSN}]`),n===this.trackId&&this.playlistLoaded(n,r,o)}onLevelLoading(t,r){this.switchLevel(r.level)}onLevelSwitching(t,r){this.switchLevel(r.level)}switchLevel(t){const r=this.hls.levels[t];if(!r)return;const n=r.audioGroups||null,a=this.groupIds;let i=this.currentTrack;if(!n||(a==null?void 0:a.length)!==(n==null?void 0:n.length)||n!=null&&n.some(o=>(a==null?void 0:a.indexOf(o))===-1)){this.groupIds=n,this.trackId=-1,this.currentTrack=null;const o=this.tracks.filter(p=>!n||n.indexOf(p.groupId)!==-1);if(o.length)this.selectDefaultTrack&&!o.some(p=>p.default)&&(this.selectDefaultTrack=!1),o.forEach((p,x)=>{p.id=x});else if(!i&&!this.tracksInGroup.length)return;this.tracksInGroup=o;const c=this.hls.config.audioPreference;if(!i&&c){const p=o_(c,o,CT);if(p>-1)i=o[p];else{const x=o_(c,this.tracks);i=this.tracks[x]}}let d=this.findTrackId(i);d===-1&&i&&(d=this.findTrackId(null));const h={audioTracks:o};this.log(`Updating audio tracks, ${o.length} track(s) found in group(s): ${n==null?void 0:n.join(",")}`),this.hls.trigger(vt.AUDIO_TRACKS_UPDATED,h);const m=this.trackId;if(d!==-1&&m===-1)this.setAudioTrack(d);else if(o.length&&m===-1){var l;const p=new Error(`No audio track selected for current audio group-ID(s): ${(l=this.groupIds)==null?void 0:l.join(",")} track count: ${o.length}`);this.warn(p.message),this.hls.trigger(vt.ERROR,{type:ci.MEDIA_ERROR,details:yr.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:p})}}}onError(t,r){r.fatal||!r.context||r.context.type===Vo.AUDIO_TRACK&&r.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(r.context.groupId)!==-1)&&this.checkRetry(r)}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(t){this.selectDefaultTrack=!1,this.setAudioTrack(t)}setAudioOption(t){const r=this.hls;if(r.config.audioPreference=t,t){const n=this.allAudioTracks;if(this.selectDefaultTrack=!1,n.length){const a=this.currentTrack;if(a&&tA(t,a,CT))return a;const i=o_(t,this.tracksInGroup,CT);if(i>-1){const l=this.tracksInGroup[i];return this.setAudioTrack(i),l}else if(a){let l=r.loadLevel;l===-1&&(l=r.firstAutoLevel);const o=Rqs(t,r.levels,n,l,CT);if(o===-1)return null;r.nextLoadLevel=o}if(t.channels||t.audioCodec){const l=o_(t,n);if(l>-1)return n[l]}}}return null}setAudioTrack(t){const r=this.tracksInGroup;if(t<0||t>=r.length){this.warn(`Invalid audio track id: ${t}`);return}this.selectDefaultTrack=!1;const n=this.currentTrack,a=r[t],i=a.details&&!a.details.live;if(t===this.trackId&&a===n&&i||(this.log(`Switching to audio-track ${t} "${a.name}" lang:${a.lang} group:${a.groupId} channels:${a.channels}`),this.trackId=t,this.currentTrack=a,this.hls.trigger(vt.AUDIO_TRACK_SWITCHING,hc({},a)),i))return;const l=this.switchParams(a.url,n==null?void 0:n.details,a.details);this.loadPlaylist(l)}findTrackId(t){const r=this.tracksInGroup;for(let n=0;n{const n={label:"async-blocker",execute:r,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(n,t)})}prependBlocker(t){return new Promise(r=>{if(this.queues){const n={label:"async-blocker-prepend",execute:r,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[t].unshift(n)}})}removeBlockers(){this.queues!==null&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(t=>{var r;const n=(r=t[0])==null?void 0:r.label;(n==="async-blocker"||n==="async-blocker-prepend")&&(t[0].execute(),t.splice(0,1))})}unblockAudio(t){if(this.queues===null)return;this.queues.audio[0]===t&&this.shiftAndExecuteNext("audio")}executeNext(t){if(this.queues===null||this.tracks===null)return;const r=this.queues[t];if(r.length){const a=r[0];try{a.execute()}catch(i){var n;if(a.onError(i),this.queues===null||this.tracks===null)return;const l=(n=this.tracks[t])==null?void 0:n.buffer;l!=null&&l.updating||this.shiftAndExecuteNext(t)}}}shiftAndExecuteNext(t){this.queues!==null&&(this.queues[t].shift(),this.executeNext(t))}current(t){var r;return((r=this.queues)==null?void 0:r[t][0])||null}toString(){const{queues:t,tracks:r}=this;return t===null||r===null?"":` ${this.list("video")} ${this.list("audio")} ${this.list("audiovideo")}}`}list(t){var r,n;return(r=this.queues)!=null&&r[t]||(n=this.tracks)!=null&&n[t]?`${t}: (${this.listSbInfo(t)}) ${this.listOps(t)}`:""}listSbInfo(t){var r;const n=(r=this.tracks)==null?void 0:r[t],a=n==null?void 0:n.buffer;return a?`SourceBuffer${a.updating?" updating":""}${n.ended?" ended":""}${n.ending?" ending":""}`:"none"}listOps(t){var r;return((r=this.queues)==null?void 0:r[t].map(n=>n.label).join(", "))||""}}const HKe=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,$1t="HlsJsTrackRemovedError";class SHs extends Error{constructor(t){super(t),this.name=$1t}}class CHs extends dv{constructor(t,r){super("buffer-controller",t.logger),this.hls=void 0,this.fragmentTracker=void 0,this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.blockedAudioAppend=null,this.lastVideoAppendEnd=0,this.appendSource=void 0,this.transferData=void 0,this.overrides=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=n=>{var a;this.hls&&((a=this.mediaSource)==null?void 0:a.readyState)==="open"&&this.hls.pauseBuffering()},this._onStartStreaming=n=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=n=>{const{media:a,mediaSource:i}=this;n&&this.log("Media source opened"),!(!a||!i)&&(i.removeEventListener("sourceopen",this._onMediaSourceOpen),a.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(vt.MEDIA_ATTACHED,{media:a,mediaSource:i}),this.mediaSource!==null&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:n,_objectUrl:a}=this;n!==a&&this.error(`Media element src was set while attaching MediaSource (${a} > ${n})`)},this.hls=t,this.fragmentTracker=r,this.appendSource=YUs(TS(t.config.preferManagedMediaSource)),this.initTracks(),this.registerListeners()}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null}registerListeners(){const{hls:t}=this;t.on(vt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(vt.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(vt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(vt.MANIFEST_PARSED,this.onManifestParsed,this),t.on(vt.BUFFER_RESET,this.onBufferReset,this),t.on(vt.BUFFER_APPENDING,this.onBufferAppending,this),t.on(vt.BUFFER_CODECS,this.onBufferCodecs,this),t.on(vt.BUFFER_EOS,this.onBufferEos,this),t.on(vt.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(vt.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(vt.FRAG_PARSED,this.onFragParsed,this),t.on(vt.FRAG_CHANGED,this.onFragChanged,this),t.on(vt.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(vt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(vt.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(vt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(vt.MANIFEST_PARSED,this.onManifestParsed,this),t.off(vt.BUFFER_RESET,this.onBufferReset,this),t.off(vt.BUFFER_APPENDING,this.onBufferAppending,this),t.off(vt.BUFFER_CODECS,this.onBufferCodecs,this),t.off(vt.BUFFER_EOS,this.onBufferEos,this),t.off(vt.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(vt.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(vt.FRAG_PARSED,this.onFragParsed,this),t.off(vt.FRAG_CHANGED,this.onFragChanged,this),t.off(vt.ERROR,this.onError,this)}transferMedia(){const{media:t,mediaSource:r}=this;if(!t)return null;const n={};if(this.operationQueue){const i=this.isUpdating();i||this.operationQueue.removeBlockers();const l=this.isQueued();(i||l)&&this.warn(`Transfering MediaSource with${l?" operations in queue":""}${i?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const a=this.transferData;return!this.sourceBufferCount&&a&&a.mediaSource===r?Ec(n,a.tracks):this.sourceBuffers.forEach(i=>{const[l]=i;l&&(n[l]=Ec({},this.tracks[l]),this.removeBuffer(l)),i[0]=i[1]=null}),{media:t,mediaSource:r,tracks:n}}initTracks(){const t={};this.sourceBuffers=[[null,null],[null,null]],this.tracks=t,this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null}onManifestParsed(t,r){var n;let a=2;(r.audio&&!r.video||!r.altAudio)&&(a=1),this.bufferCodecEventsTotal=a,this.log(`${a} bufferCodec event(s) expected.`),(n=this.transferData)!=null&&n.mediaSource&&this.sourceBufferCount&&a&&this.bufferCreated()}onMediaAttaching(t,r){const n=this.media=r.media;this.transferData=this.overrides=void 0;const a=TS(this.appendSource);if(a){const i=!!r.mediaSource;(i||r.overrides)&&(this.transferData=r,this.overrides=r.overrides);const l=this.mediaSource=r.mediaSource||new a;if(this.assignMediaSource(l),i)this._objectUrl=n.src,this.attachTransferred();else{const o=this._objectUrl=self.URL.createObjectURL(l);if(this.appendSource)try{n.removeAttribute("src");const c=self.ManagedMediaSource;n.disableRemotePlayback=n.disableRemotePlayback||c&&l instanceof c,GKe(n),THs(n,o),n.load()}catch{n.src=o}else n.src=o}n.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(t){var r,n;this.log(`${((r=this.transferData)==null?void 0:r.mediaSource)===t?"transferred":"created"} media source: ${(n=t.constructor)==null?void 0:n.name}`),t.addEventListener("sourceopen",this._onMediaSourceOpen),t.addEventListener("sourceended",this._onMediaSourceEnded),t.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(t.addEventListener("startstreaming",this._onStartStreaming),t.addEventListener("endstreaming",this._onEndStreaming))}attachTransferred(){const t=this.media,r=this.transferData;if(!r||!t)return;const n=this.tracks,a=r.tracks,i=a?Object.keys(a):null,l=i?i.length:0,o=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(a&&i&&l){if(!this.tracksReady){this.hls.config.startFragPrefetch=!0,this.log("attachTransferred: waiting for SourceBuffer track info");return}if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal}) required tracks: ${Uc(n,(c,d)=>c==="initSegment"?void 0:d)}; transfer tracks: ${Uc(a,(c,d)=>c==="initSegment"?void 0:d)}}`),!Ovt(a,n)){r.mediaSource=null,r.tracks=void 0;const c=t.currentTime,d=this.details,h=Math.max(c,(d==null?void 0:d.fragments[0].start)||0);if(h-c>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${c} -> ${h}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(a)}"->"${Object.keys(n)}") start time: ${h} currentTime: ${c}`),this.onMediaDetaching(vt.MEDIA_DETACHING,{}),this.onMediaAttaching(vt.MEDIA_ATTACHING,r),t.currentTime=h;return}this.transferData=void 0,i.forEach(c=>{const d=c,h=a[d];if(h){const m=h.buffer;if(m){const p=this.fragmentTracker,x=h.id;if(p.hasFragments(x)||p.hasParts(x)){const b=mo.getBuffered(m);p.detectEvictedFragments(d,b,x,null,!0)}const y=Wwe(d),_=[d,m];this.sourceBuffers[y]=_,m.updating&&this.operationQueue&&this.operationQueue.prependBlocker(d),this.trackSourceBuffer(d,h)}}}),o(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),o()}get mediaSourceOpenOrEnded(){var t;const r=(t=this.mediaSource)==null?void 0:t.readyState;return r==="open"||r==="ended"}onMediaDetaching(t,r){const n=!!r.transferMedia;this.transferData=this.overrides=void 0;const{media:a,mediaSource:i,_objectUrl:l}=this;if(i){if(this.log(`media source ${n?"transferring":"detaching"}`),n)this.sourceBuffers.forEach(([o])=>{o&&this.removeBuffer(o)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const o=i.readyState==="open";try{const c=i.sourceBuffers;for(let d=c.length;d--;)o&&c[d].abort(),i.removeSourceBuffer(c[d]);o&&i.endOfStream()}catch(c){this.warn(`onMediaDetaching: ${c.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}i.removeEventListener("sourceopen",this._onMediaSourceOpen),i.removeEventListener("sourceended",this._onMediaSourceEnded),i.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(i.removeEventListener("startstreaming",this._onStartStreaming),i.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}a&&(a.removeEventListener("emptied",this._onMediaEmptied),n||(l&&self.URL.revokeObjectURL(l),this.mediaSrc===l?(a.removeAttribute("src"),this.appendSource&&GKe(a),a.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(vt.MEDIA_DETACHED,r)}onBufferReset(){this.sourceBuffers.forEach(([t])=>{t&&this.resetBuffer(t)}),this.initTracks()}resetBuffer(t){var r;const n=(r=this.tracks[t])==null?void 0:r.buffer;if(this.removeBuffer(t),n)try{var a;(a=this.mediaSource)!=null&&a.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(n)}catch(i){this.warn(`onBufferReset ${t}`,i)}delete this.tracks[t]}removeBuffer(t){this.removeBufferListeners(t),this.sourceBuffers[Wwe(t)]=[null,null];const r=this.tracks[t];r&&(r.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new kHs(this.tracks)}onBufferCodecs(t,r){var n;const a=this.tracks,i=Object.keys(r);this.log(`BUFFER_CODECS: "${i}" (current SB count ${this.sourceBufferCount})`);const l="audiovideo"in r&&(a.audio||a.video)||a.audiovideo&&("audio"in r||"video"in r),o=!l&&this.sourceBufferCount&&this.media&&i.some(c=>!a[c]);if(l||o){this.warn(`Unsupported transition between "${Object.keys(a)}" and "${i}" SourceBuffers`);return}i.forEach(c=>{var d,h;const m=r[c],{id:p,codec:x,levelCodec:y,container:_,metadata:b,supplemental:j}=m;let k=a[c];const T=(d=this.transferData)==null||(d=d.tracks)==null?void 0:d[c],E=T!=null&&T.buffer?T:k,A=(E==null?void 0:E.pendingCodec)||(E==null?void 0:E.codec),D=E==null?void 0:E.levelCodec;k||(k=a[c]={buffer:void 0,listeners:[],codec:x,supplemental:j,container:_,levelCodec:y,metadata:b,id:p});const R=Bue(A,D),z=R==null?void 0:R.replace(HKe,"$1");let O=Bue(x,y);const $=(h=O)==null?void 0:h.replace(HKe,"$1");O&&R&&z!==$&&(c.slice(0,5)==="audio"&&(O=gpe(O,this.appendSource)),this.log(`switching codec ${A} to ${O}`),O!==(k.pendingCodec||k.codec)&&(k.pendingCodec=O),k.container=_,this.appendChangeType(c,_,O))}),(this.tracksReady||this.sourceBufferCount)&&(r.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!r.video&&((n=r.audio)==null?void 0:n.id)==="main"&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks())}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((t,r)=>{const n=this.tracks[r];return t[r]={id:n.id,container:n.container,codec:n.codec,levelCodec:n.levelCodec},t},{})}appendChangeType(t,r,n){const a=`${r};codecs=${n}`,i={label:`change-type=${a}`,execute:()=>{const l=this.tracks[t];if(l){const o=l.buffer;o!=null&&o.changeType&&(this.log(`changing ${t} sourceBuffer type to ${a}`),o.changeType(a),l.codec=n,l.container=r)}this.shiftAndExecuteNext(t)},onStart:()=>{},onComplete:()=>{},onError:l=>{this.warn(`Failed to change ${t} SourceBuffer type`,l)}};this.append(i,t,this.isPending(this.tracks[t]))}blockAudio(t){var r;const n=t.start,a=n+t.duration*.05;if(((r=this.fragmentTracker.getAppendedFrag(n,Ba.MAIN))==null?void 0:r.gap)===!0)return;const l={label:"block-audio",execute:()=>{var o;const c=this.tracks.video;(this.lastVideoAppendEnd>a||c!=null&&c.buffer&&mo.isBuffered(c.buffer,a)||((o=this.fragmentTracker.getAppendedFrag(a,Ba.MAIN))==null?void 0:o.gap)===!0)&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:o=>{this.warn("Error executing block-audio operation",o)}};this.blockedAudioAppend={op:l,frag:t},this.append(l,"audio",!0)}unblockAudio(){const{blockedAudioAppend:t,operationQueue:r}=this;t&&r&&(this.blockedAudioAppend=null,r.unblockAudio(t.op))}onBufferAppending(t,r){const{tracks:n}=this,{data:a,type:i,parent:l,frag:o,part:c,chunkMeta:d,offset:h}=r,m=d.buffering[i],{sn:p,cc:x}=o,y=self.performance.now();m.start=y;const _=o.stats.buffering,b=c?c.stats.buffering:null;_.start===0&&(_.start=y),b&&b.start===0&&(b.start=y);const j=n.audio;let k=!1;i==="audio"&&(j==null?void 0:j.container)==="audio/mpeg"&&(k=!this.lastMpegAudioChunk||d.id===1||this.lastMpegAudioChunk.sn!==d.sn,this.lastMpegAudioChunk=d);const T=n.video,E=T==null?void 0:T.buffer;if(E&&p!=="initSegment"){const R=c||o,z=this.blockedAudioAppend;if(i==="audio"&&l!=="main"&&!this.blockedAudioAppend&&!(T.ending||T.ended)){const $=R.start+R.duration*.05,ee=E.buffered,Z=this.currentOp("video");!ee.length&&!Z?this.blockAudio(R):!Z&&!mo.isBuffered(E,$)&&this.lastVideoAppendEnd<$&&this.blockAudio(R)}else if(i==="video"){const O=R.end;if(z){const $=z.frag.start;(O>$||O{var R;m.executeStart=self.performance.now();const z=(R=this.tracks[i])==null?void 0:R.buffer;z&&(k?this.updateTimestampOffset(z,A,.1,i,p,x):h!==void 0&&ka(h)&&this.updateTimestampOffset(z,h,1e-6,i,p,x)),this.appendExecutor(a,i)},onStart:()=>{},onComplete:()=>{const R=self.performance.now();m.executeEnd=m.end=R,_.first===0&&(_.first=R),b&&b.first===0&&(b.first=R);const z={};this.sourceBuffers.forEach(([O,$])=>{O&&(z[O]=mo.getBuffered($))}),this.appendErrors[i]=0,i==="audio"||i==="video"?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(vt.BUFFER_APPENDED,{type:i,frag:o,part:c,chunkMeta:d,parent:o.type,timeRanges:z})},onError:R=>{var z;const O={type:ci.MEDIA_ERROR,parent:o.type,details:yr.BUFFER_APPEND_ERROR,sourceBufferName:i,frag:o,part:c,chunkMeta:d,error:R,err:R,fatal:!1},$=(z=this.media)==null?void 0:z.error;if(R.code===DOMException.QUOTA_EXCEEDED_ERR||R.name=="QuotaExceededError"||"quota"in R)O.details=yr.BUFFER_FULL_ERROR;else if(R.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!$)O.errorAction=wP(!0);else if(R.name===$1t&&this.sourceBufferCount===0)O.errorAction=wP(!0);else{const ee=++this.appendErrors[i];this.warn(`Failed ${ee}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${i}" sourceBuffer (${$||"no media error"})`),(ee>=this.hls.config.appendErrorMaxRetry||$)&&(O.fatal=!0)}this.hls.trigger(vt.ERROR,O)}};this.log(`queuing "${i}" append sn: ${p}${c?" p: "+c.index:""} of ${o.type===Ba.MAIN?"level":"track"} ${o.level} cc: ${x}`),this.append(D,i,this.isPending(this.tracks[i]))}getFlushOp(t,r,n){return this.log(`queuing "${t}" remove ${r}-${n}`),{label:"remove",execute:()=>{this.removeExecutor(t,r,n)},onStart:()=>{},onComplete:()=>{this.hls.trigger(vt.BUFFER_FLUSHED,{type:t})},onError:a=>{this.warn(`Failed to remove ${r}-${n} from "${t}" SourceBuffer`,a)}}}onBufferFlushing(t,r){const{type:n,startOffset:a,endOffset:i}=r;n?this.append(this.getFlushOp(n,a,i),n):this.sourceBuffers.forEach(([l])=>{l&&this.append(this.getFlushOp(l,a,i),l)})}onFragParsed(t,r){const{frag:n,part:a}=r,i=[],l=a?a.elementaryStreams:n.elementaryStreams;l[Dc.AUDIOVIDEO]?i.push("audiovideo"):(l[Dc.AUDIO]&&i.push("audio"),l[Dc.VIDEO]&&i.push("video"));const o=()=>{const c=self.performance.now();n.stats.buffering.end=c,a&&(a.stats.buffering.end=c);const d=a?a.stats:n.stats;this.hls.trigger(vt.FRAG_BUFFERED,{frag:n,part:a,stats:d,id:n.type})};i.length===0&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${n.type} level: ${n.level} sn: ${n.sn}`),this.blockBuffers(o,i).catch(c=>{this.warn(`Fragment buffered callback ${c}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(t,r){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([t])=>{if(t){const r=this.tracks[t];if(r)return!r.ended||r.ending}return!1})}onBufferEos(t,r){var n;this.sourceBuffers.forEach(([l])=>{if(l){const o=this.tracks[l];(!r.type||r.type===l)&&(o.ending=!0,o.ended||(o.ended=!0,this.log(`${l} buffer reached EOS`)))}});const a=((n=this.overrides)==null?void 0:n.endOfStream)!==!1;this.sourceBufferCount>0&&!this.sourceBuffers.some(([l])=>{var o;return l&&!((o=this.tracks[l])!=null&&o.ended)})?a?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();const{mediaSource:l}=this;if(!l||l.readyState!=="open"){l&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${l.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),l.endOfStream(),this.hls.trigger(vt.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(vt.BUFFERED_TO_END,void 0)):r.type==="video"&&this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach(([t])=>{if(t!==null){const r=this.tracks[t];r&&(r.ending=!1)}})}onLevelUpdated(t,{details:r}){r.fragments.length&&(this.details=r,this.updateDuration())}updateDuration(){this.blockUntilOpen(()=>{const t=this.getDurationAndRange();t&&this.updateMediaSource(t)})}onError(t,r){if(r.details===yr.BUFFER_APPEND_ERROR&&r.frag){var n;const a=(n=r.errorAction)==null?void 0:n.nextAutoLevel;ka(a)&&a!==r.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){const{hls:t,details:r,media:n}=this;if(!n||r===null||!this.sourceBufferCount)return;const a=t.config,i=n.currentTime,l=r.levelTargetDuration,o=r.live&&a.liveBackBufferLength!==null?a.liveBackBufferLength:a.backBufferLength;if(ka(o)&&o>=0){const d=Math.max(o,l),h=Math.floor(i/l)*l-d;this.flushBackBuffer(i,l,h)}const c=a.frontBufferFlushThreshold;if(ka(c)&&c>0){const d=Math.max(a.maxBufferLength,c),h=Math.max(d,l),m=Math.floor(i/l)*l+h;this.flushFrontBuffer(i,l,m)}}flushBackBuffer(t,r,n){this.sourceBuffers.forEach(([a,i])=>{if(i){const o=mo.getBuffered(i);if(o.length>0&&n>o.start(0)){var l;this.hls.trigger(vt.BACK_BUFFER_REACHED,{bufferEnd:n});const c=this.tracks[a];if((l=this.details)!=null&&l.live)this.hls.trigger(vt.LIVE_BACK_BUFFER_REACHED,{bufferEnd:n});else if(c!=null&&c.ended){this.log(`Cannot flush ${a} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(vt.BUFFER_FLUSHING,{startOffset:0,endOffset:n,type:a})}}})}flushFrontBuffer(t,r,n){this.sourceBuffers.forEach(([a,i])=>{if(i){const l=mo.getBuffered(i),o=l.length;if(o<2)return;const c=l.start(o-1),d=l.end(o-1);if(n>c||t>=c&&t<=d)return;this.hls.trigger(vt.BUFFER_FLUSHING,{startOffset:c,endOffset:1/0,type:a})}})}getDurationAndRange(){var t;const{details:r,mediaSource:n}=this;if(!r||!this.media||(n==null?void 0:n.readyState)!=="open")return null;const a=r.edge;if(r.live&&this.hls.config.liveDurationInfinity){if(r.fragments.length&&n.setLiveSeekableRange){const d=Math.max(0,r.fragmentStart),h=Math.max(d,a);return{duration:1/0,start:d,end:h}}return{duration:1/0}}const i=(t=this.overrides)==null?void 0:t.duration;if(i)return ka(i)?{duration:i}:null;const l=this.media.duration,o=ka(n.duration)?n.duration:0;return a>o&&a>l||!ka(l)?{duration:a}:null}updateMediaSource({duration:t,start:r,end:n}){const a=this.mediaSource;!this.media||!a||a.readyState!=="open"||(a.duration!==t&&(ka(t)&&this.log(`Updating MediaSource duration to ${t.toFixed(3)}`),a.duration=t),r!==void 0&&n!==void 0&&(this.log(`MediaSource duration is set to ${a.duration}. Setting seekable range to ${r}-${n}.`),a.setLiveSeekableRange(r,n)))}get tracksReady(){const t=this.pendingTrackCount;return t>0&&(t>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:t,pendingTrackCount:r,tracks:n}=this;if(this.log(`checkPendingTracks (pending: ${r} codec events expected: ${t}) ${Uc(n)}`),this.tracksReady){var a;const i=(a=this.transferData)==null?void 0:a.tracks;i&&Object.keys(i).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const t={};this.sourceBuffers.forEach(([r,n])=>{if(r){const a=this.tracks[r];t[r]={buffer:n,container:a.container,codec:a.codec,supplemental:a.supplemental,levelCodec:a.levelCodec,id:a.id,metadata:a.metadata}}}),this.hls.trigger(vt.BUFFER_CREATED,{tracks:t}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([r])=>{this.executeNext(r)})}else{const t=new Error("could not create source buffer for media codec(s)");this.hls.trigger(vt.ERROR,{type:ci.MEDIA_ERROR,details:yr.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:t,reason:t.message})}}createSourceBuffers(){const{tracks:t,sourceBuffers:r,mediaSource:n}=this;if(!n)throw new Error("createSourceBuffers called when mediaSource was null");for(const i in t){const l=i,o=t[l];if(this.isPending(o)){const c=this.getTrackCodec(o,l),d=`${o.container};codecs=${c}`;o.codec=c,this.log(`creating sourceBuffer(${d})${this.currentOp(l)?" Queued":""} ${Uc(o)}`);try{const h=n.addSourceBuffer(d),m=Wwe(l),p=[l,h];r[m]=p,o.buffer=h}catch(h){var a;this.error(`error while trying to add sourceBuffer: ${h.message}`),this.shiftAndExecuteNext(l),(a=this.operationQueue)==null||a.removeBlockers(),delete this.tracks[l],this.hls.trigger(vt.ERROR,{type:ci.MEDIA_ERROR,details:yr.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:h,sourceBufferName:l,mimeType:d,parent:o.id});return}this.trackSourceBuffer(l,o)}}this.bufferCreated()}getTrackCodec(t,r){const n=t.supplemental;let a=t.codec;n&&(r==="video"||r==="audiovideo")&&vB(n,"video")&&(a=xqs(a,n));const i=Bue(a,t.levelCodec);return i?r.slice(0,5)==="audio"?gpe(i,this.appendSource):i:""}trackSourceBuffer(t,r){const n=r.buffer;if(!n)return;const a=this.getTrackCodec(r,t);this.tracks[t]={buffer:n,codec:a,container:r.container,levelCodec:r.levelCodec,supplemental:r.supplemental,metadata:r.metadata,id:r.id,listeners:[]},this.removeBufferListeners(t),this.addBufferListener(t,"updatestart",this.onSBUpdateStart),this.addBufferListener(t,"updateend",this.onSBUpdateEnd),this.addBufferListener(t,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(t,"bufferedchange",(i,l)=>{const o=l.removedRanges;o!=null&&o.length&&this.hls.trigger(vt.BUFFER_FLUSHED,{type:i})})}get mediaSrc(){var t,r;const n=((t=this.media)==null||(r=t.querySelector)==null?void 0:r.call(t,"source"))||this.media;return n==null?void 0:n.src}onSBUpdateStart(t){const r=this.currentOp(t);r&&r.onStart()}onSBUpdateEnd(t){var r;if(((r=this.mediaSource)==null?void 0:r.readyState)==="closed"){this.resetBuffer(t);return}const n=this.currentOp(t);n&&(n.onComplete(),this.shiftAndExecuteNext(t))}onSBUpdateError(t,r){var n;const a=new Error(`${t} SourceBuffer error. MediaSource readyState: ${(n=this.mediaSource)==null?void 0:n.readyState}`);this.error(`${a}`,r),this.hls.trigger(vt.ERROR,{type:ci.MEDIA_ERROR,details:yr.BUFFER_APPENDING_ERROR,sourceBufferName:t,error:a,fatal:!1});const i=this.currentOp(t);i&&i.onError(a)}updateTimestampOffset(t,r,n,a,i,l){const o=r-t.timestampOffset;Math.abs(o)>=n&&(this.log(`Updating ${a} SourceBuffer timestampOffset to ${r} (sn: ${i} cc: ${l})`),t.timestampOffset=r)}removeExecutor(t,r,n){const{media:a,mediaSource:i}=this,l=this.tracks[t],o=l==null?void 0:l.buffer;if(!a||!i||!o){this.warn(`Attempting to remove from the ${t} SourceBuffer, but it does not exist`),this.shiftAndExecuteNext(t);return}const c=ka(a.duration)?a.duration:1/0,d=ka(i.duration)?i.duration:1/0,h=Math.max(0,r),m=Math.min(n,c,d);m>h&&(!l.ending||l.ended)?(l.ended=!1,this.log(`Removing [${h},${m}] from the ${t} SourceBuffer`),o.remove(h,m)):this.shiftAndExecuteNext(t)}appendExecutor(t,r){const n=this.tracks[r],a=n==null?void 0:n.buffer;if(!a)throw new SHs(`Attempting to append to the ${r} SourceBuffer, but it does not exist`);n.ending=!1,n.ended=!1,a.appendBuffer(t)}blockUntilOpen(t){if(this.isUpdating()||this.isQueued())this.blockBuffers(t).catch(r=>{this.warn(`SourceBuffer blocked callback ${r}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{t()}catch(r){this.warn(`Callback run without blocking ${this.operationQueue} ${r}`)}}isUpdating(){return this.sourceBuffers.some(([t,r])=>t&&r.updating)}isQueued(){return this.sourceBuffers.some(([t])=>t&&!!this.currentOp(t))}isPending(t){return!!t&&!t.buffer}blockBuffers(t,r=this.sourceBufferTypes){if(!r.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(t);const{operationQueue:n}=this,a=r.map(l=>this.appendBlocker(l));return r.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(a).then(l=>{n===this.operationQueue&&(t(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(t){t.forEach(r=>{var n;const a=(n=this.tracks[r])==null?void 0:n.buffer;!a||a.updating||this.shiftAndExecuteNext(r)})}append(t,r,n){this.operationQueue&&this.operationQueue.append(t,r,n)}appendBlocker(t){if(this.operationQueue)return this.operationQueue.appendBlocker(t)}currentOp(t){return this.operationQueue?this.operationQueue.current(t):null}executeNext(t){t&&this.operationQueue&&this.operationQueue.executeNext(t)}shiftAndExecuteNext(t){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(t)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((t,r)=>t+(this.isPending(this.tracks[r])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((t,[r])=>t+(r?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([t])=>t).filter(t=>!!t)}addBufferListener(t,r,n){const a=this.tracks[t];if(!a)return;const i=a.buffer;if(!i)return;const l=n.bind(this,t);a.listeners.push({event:r,listener:l}),i.addEventListener(r,l)}removeBufferListeners(t){const r=this.tracks[t];if(!r)return;const n=r.buffer;n&&(r.listeners.forEach(a=>{n.removeEventListener(a.event,a.listener)}),r.listeners.length=0)}}function GKe(s){const t=s.querySelectorAll("source");[].slice.call(t).forEach(r=>{s.removeChild(r)})}function THs(s,t){const r=self.document.createElement("source");r.type="video/mp4",r.src=t,s.appendChild(r)}function Wwe(s){return s==="audio"?1:0}class q6e{constructor(t){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=t,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(t){this.streamController=t}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:t}=this;t.on(vt.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.on(vt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(vt.MANIFEST_PARSED,this.onManifestParsed,this),t.on(vt.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(vt.BUFFER_CODECS,this.onBufferCodecs,this),t.on(vt.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:t}=this;t.off(vt.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.off(vt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(vt.MANIFEST_PARSED,this.onManifestParsed,this),t.off(vt.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(vt.BUFFER_CODECS,this.onBufferCodecs,this),t.off(vt.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(t,r){const n=this.hls.levels[r.droppedLevel];this.isLevelAllowed(n)&&this.restrictedLevels.push({bitrate:n.bitrate,height:n.height,width:n.width})}onMediaAttaching(t,r){this.media=r.media instanceof HTMLVideoElement?r.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(t,r){const n=this.hls;this.restrictedLevels=[],this.firstLevel=r.firstLevel,n.config.capLevelToPlayerSize&&r.video&&this.startCapping()}onLevelsUpdated(t,r){this.timer&&ka(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(t,r){this.hls.config.capLevelToPlayerSize&&r.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0){this.clientRect=null;return}const t=this.hls.levels;if(t.length){const r=this.hls,n=this.getMaxLevel(t.length-1);n!==this.autoLevelCapping&&r.logger.log(`Setting autoLevelCapping to ${n}: ${t[n].height}p@${t[n].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),r.autoLevelCapping=n,r.autoLevelEnabled&&r.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=r.autoLevelCapping}}}getMaxLevel(t){const r=this.hls.levels;if(!r.length)return-1;const n=r.filter((a,i)=>this.isLevelAllowed(a)&&i<=t);return this.clientRect=null,q6e.getMaxLevelByMediaSize(n,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const t=this.media,r={width:0,height:0};if(t){const n=t.getBoundingClientRect();r.width=n.width,r.height=n.height,!r.width&&!r.height&&(r.width=n.right-n.left||t.width||0,r.height=n.bottom-n.top||t.height||0)}return this.clientRect=r,r}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let t=1;if(!this.hls.config.ignoreDevicePixelRatio)try{t=self.devicePixelRatio}catch{}return Math.min(t,this.hls.config.maxDevicePixelRatio)}isLevelAllowed(t){return!this.restrictedLevels.some(n=>t.bitrate===n.bitrate&&t.width===n.width&&t.height===n.height)}static getMaxLevelByMediaSize(t,r,n){if(!(t!=null&&t.length))return-1;const a=(o,c)=>c?o.width!==c.width||o.height!==c.height:!0;let i=t.length-1;const l=Math.max(r,n);for(let o=0;o=l||c.height>=l)&&a(c,t[o+1])){i=o;break}}return i}}const EHs={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},Vg=EHs,AHs={HLS:"h"},MHs=AHs;class z_{constructor(t,r){Array.isArray(t)&&(t=t.map(n=>n instanceof z_?n:new z_(n))),this.value=t,this.params=r}}const IHs="Dict";function PHs(s){return Array.isArray(s)?JSON.stringify(s):s instanceof Map?"Map{}":s instanceof Set?"Set{}":typeof s=="object"?JSON.stringify(s):String(s)}function LHs(s,t,r,n){return new Error(`failed to ${s} "${PHs(t)}" as ${r}`,{cause:n})}function $_(s,t,r){return LHs("serialize",s,t,r)}class U1t{constructor(t){this.description=t}}const WKe="Bare Item",DHs="Boolean";function RHs(s){if(typeof s!="boolean")throw $_(s,DHs);return s?"?1":"?0"}function OHs(s){return btoa(String.fromCharCode(...s))}const FHs="Byte Sequence";function BHs(s){if(ArrayBuffer.isView(s)===!1)throw $_(s,FHs);return`:${OHs(s)}:`}const zHs="Integer";function $Hs(s){return s<-999999999999999||99999999999999912)throw $_(s,qHs);const r=t.toString();return r.includes(".")?r:`${r}.0`}const HHs="String",GHs=/[\x00-\x1f\x7f]+/;function WHs(s){if(GHs.test(s))throw $_(s,HHs);return`"${s.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function KHs(s){return s.description||s.toString().slice(7,-1)}const YHs="Token";function KKe(s){const t=KHs(s);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(t)===!1)throw $_(t,YHs);return t}function uCe(s){switch(typeof s){case"number":if(!ka(s))throw $_(s,WKe);return Number.isInteger(s)?q1t(s):VHs(s);case"string":return WHs(s);case"symbol":return KKe(s);case"boolean":return RHs(s);case"object":if(s instanceof Date)return UHs(s);if(s instanceof Uint8Array)return BHs(s);if(s instanceof U1t)return KKe(s);default:throw $_(s,WKe)}}const ZHs="Key";function hCe(s){if(/^[a-z*][a-z0-9\-_.*]*$/.test(s)===!1)throw $_(s,ZHs);return s}function V6e(s){return s==null?"":Object.entries(s).map(([t,r])=>r===!0?`;${hCe(t)}`:`;${hCe(t)}=${uCe(r)}`).join("")}function H1t(s){return s instanceof z_?`${uCe(s.value)}${V6e(s.params)}`:uCe(s)}function XHs(s){return`(${s.value.map(H1t).join(" ")})${V6e(s.params)}`}function QHs(s,t={whitespace:!0}){if(typeof s!="object"||s==null)throw $_(s,IHs);const r=s instanceof Map?s.entries():Object.entries(s),n=t!=null&&t.whitespace?" ":"";return Array.from(r).map(([a,i])=>{i instanceof z_||(i=new z_(i));let l=hCe(a);return i.value===!0?l+=V6e(i.params):(l+="=",Array.isArray(i.value)?l+=XHs(i):l+=H1t(i)),l}).join(`,${n}`)}function G1t(s,t){return QHs(s,t)}const Mb="CMCD-Object",Lu="CMCD-Request",lC="CMCD-Session",CN="CMCD-Status",JHs={br:Mb,ab:Mb,d:Mb,ot:Mb,tb:Mb,tpb:Mb,lb:Mb,tab:Mb,lab:Mb,url:Mb,pb:Lu,bl:Lu,tbl:Lu,dl:Lu,ltc:Lu,mtp:Lu,nor:Lu,nrr:Lu,rc:Lu,sn:Lu,sta:Lu,su:Lu,ttfb:Lu,ttfbb:Lu,ttlb:Lu,cmsdd:Lu,cmsds:Lu,smrt:Lu,df:Lu,cs:Lu,ts:Lu,cid:lC,pr:lC,sf:lC,sid:lC,st:lC,v:lC,msd:lC,bs:CN,bsd:CN,cdn:CN,rtp:CN,bg:CN,pt:CN,ec:CN,e:CN},eGs={REQUEST:Lu};function tGs(s){return Object.keys(s).reduce((t,r)=>{var n;return(n=s[r])===null||n===void 0||n.forEach(a=>t[a]=r),t},{})}function sGs(s,t){const r={};if(!s)return r;const n=Object.keys(s),a=t?tGs(t):{};return n.reduce((i,l)=>{var o;const c=JHs[l]||a[l]||eGs.REQUEST,d=(o=i[c])!==null&&o!==void 0?o:i[c]={};return d[l]=s[l],i},r)}function rGs(s){return["ot","sf","st","e","sta"].includes(s)}function nGs(s){return typeof s=="number"?ka(s):s!=null&&s!==""&&s!==!1}const W1t="event";function aGs(s,t){const r=new URL(s),n=new URL(t);if(r.origin!==n.origin)return s;const a=r.pathname.split("/").slice(1),i=n.pathname.split("/").slice(1,-1);for(;a[0]===i[0];)a.shift(),i.shift();for(;i.length;)i.shift(),a.unshift("..");return a.join("/")+r.search+r.hash}const Vue=s=>Math.round(s),mCe=(s,t)=>Array.isArray(s)?s.map(r=>mCe(r,t)):s instanceof z_&&typeof s.value=="string"?new z_(mCe(s.value,t),s.params):(t.baseUrl&&(s=aGs(s,t.baseUrl)),t.version===1?encodeURIComponent(s):s),pV=s=>Vue(s/100)*100,iGs=(s,t)=>{let r=s;return t.version>=2&&(s instanceof z_&&typeof s.value=="string"?r=new z_([s]):typeof s=="string"&&(r=[s])),mCe(r,t)},oGs={br:Vue,d:Vue,bl:pV,dl:pV,mtp:pV,nor:iGs,rtp:pV,tb:Vue},K1t="request",Y1t="response",H6e=["ab","bg","bl","br","bs","bsd","cdn","cid","cs","df","ec","lab","lb","ltc","msd","mtp","pb","pr","pt","sf","sid","sn","st","sta","tab","tb","tbl","tpb","ts","v"],lGs=["e"],cGs=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function mye(s){return cGs.test(s)}function dGs(s){return H6e.includes(s)||lGs.includes(s)||mye(s)}const Z1t=["d","dl","nor","ot","rtp","su"];function uGs(s){return H6e.includes(s)||Z1t.includes(s)||mye(s)}const hGs=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];function mGs(s){return H6e.includes(s)||Z1t.includes(s)||hGs.includes(s)||mye(s)}const fGs=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function pGs(s){return fGs.includes(s)||mye(s)}const gGs={[Y1t]:mGs,[W1t]:dGs,[K1t]:uGs};function X1t(s,t={}){const r={};if(s==null||typeof s!="object")return r;const n=t.version||s.v||1,a=t.reportingMode||K1t,i=n===1?pGs:gGs[a];let l=Object.keys(s).filter(i);const o=t.filter;typeof o=="function"&&(l=l.filter(o));const c=a===Y1t||a===W1t;c&&!l.includes("ts")&&l.push("ts"),n>1&&!l.includes("v")&&l.push("v");const d=Ec({},oGs,t.formatters),h={version:n,reportingMode:a,baseUrl:t.baseUrl};return l.sort().forEach(m=>{let p=s[m];const x=d[m];if(typeof x=="function"&&(p=x(p,h)),m==="v"){if(n===1)return;p=n}m=="pr"&&p===1||(c&&m==="ts"&&!ka(p)&&(p=Date.now()),nGs(p)&&(rGs(m)&&typeof p=="string"&&(p=new U1t(p)),r[m]=p))}),r}function xGs(s,t={}){const r={};if(!s)return r;const n=X1t(s,t),a=sGs(n,t==null?void 0:t.customHeaderMap);return Object.entries(a).reduce((i,[l,o])=>{const c=G1t(o,{whitespace:!1});return c&&(i[l]=c),i},r)}function yGs(s,t,r){return Ec(s,xGs(t,r))}const vGs="CMCD";function bGs(s,t={}){return s?G1t(X1t(s,t),{whitespace:!1}):""}function _Gs(s,t={}){if(!s)return"";const r=bGs(s,t);return encodeURIComponent(r)}function wGs(s,t={}){if(!s)return"";const r=_Gs(s,t);return`${vGs}=${r}`}const YKe=/CMCD=[^&#]+/;function jGs(s,t,r){const n=wGs(t,r);if(!n)return s;if(YKe.test(s))return s.replace(YKe,n);const a=s.includes("?")?"&":"?";return`${s}${a}${n}`}class NGs{constructor(t){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.includeKeys=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=a=>{try{this.apply(a,{ot:Vg.MANIFEST,su:!this.initialized})}catch(i){this.hls.logger.warn("Could not generate manifest CMCD data.",i)}},this.applyFragmentData=a=>{try{const{frag:i,part:l}=a,o=this.hls.levels[i.level],c=this.getObjectType(i),d={d:(l||i).duration*1e3,ot:c};(c===Vg.VIDEO||c===Vg.AUDIO||c==Vg.MUXED)&&(d.br=o.bitrate/1e3,d.tb=this.getTopBandwidth(c)/1e3,d.bl=this.getBufferLength(c));const h=l?this.getNextPart(l):this.getNextFrag(i);h!=null&&h.url&&h.url!==i.url&&(d.nor=h.url),this.apply(a,d)}catch(i){this.hls.logger.warn("Could not generate segment CMCD data.",i)}},this.hls=t;const r=this.config=t.config,{cmcd:n}=r;n!=null&&(r.pLoader=this.createPlaylistLoader(),r.fLoader=this.createFragmentLoader(),this.sid=n.sessionId||t.sessionId,this.cid=n.contentId,this.useHeaders=n.useHeaders===!0,this.includeKeys=n.includeKeys,this.registerListeners())}registerListeners(){const t=this.hls;t.on(vt.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(vt.MEDIA_DETACHED,this.onMediaDetached,this),t.on(vt.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const t=this.hls;t.off(vt.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(vt.MEDIA_DETACHED,this.onMediaDetached,this),t.off(vt.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=this.media=null}onMediaAttached(t,r){this.media=r.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(t,r){var n,a;this.audioBuffer=(n=r.tracks.audio)==null?void 0:n.buffer,this.videoBuffer=(a=r.tracks.video)==null?void 0:a.buffer}createData(){var t;return{v:1,sf:MHs.HLS,sid:this.sid,cid:this.cid,pr:(t=this.media)==null?void 0:t.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(t,r={}){Ec(r,this.createData());const n=r.ot===Vg.INIT||r.ot===Vg.VIDEO||r.ot===Vg.MUXED;this.starved&&n&&(r.bs=!0,r.su=!0,this.starved=!1),r.su==null&&(r.su=this.buffering);const{includeKeys:a}=this;a&&(r=Object.keys(r).reduce((l,o)=>(a.includes(o)&&(l[o]=r[o]),l),{}));const i={baseUrl:t.url};this.useHeaders?(t.headers||(t.headers={}),yGs(t.headers,r,i)):t.url=jGs(t.url,r,i)}getNextFrag(t){var r;const n=(r=this.hls.levels[t.level])==null?void 0:r.details;if(n){const a=t.sn-n.startSN;return n.fragments[a+1]}}getNextPart(t){var r;const{index:n,fragment:a}=t,i=(r=this.hls.levels[a.level])==null||(r=r.details)==null?void 0:r.partList;if(i){const{sn:l}=a;for(let o=i.length-1;o>=0;o--){const c=i[o];if(c.index===n&&c.fragment.sn===l)return i[o+1]}}}getObjectType(t){const{type:r}=t;if(r==="subtitle")return Vg.TIMED_TEXT;if(t.sn==="initSegment")return Vg.INIT;if(r==="audio")return Vg.AUDIO;if(r==="main")return this.hls.audioTracks.length?Vg.VIDEO:Vg.MUXED}getTopBandwidth(t){let r=0,n;const a=this.hls;if(t===Vg.AUDIO)n=a.audioTracks;else{const i=a.maxAutoLevel,l=i>-1?i+1:a.levels.length;n=a.levels.slice(0,l)}return n.forEach(i=>{i.bitrate>r&&(r=i.bitrate)}),r>0?r:NaN}getBufferLength(t){const r=this.media,n=t===Vg.AUDIO?this.audioBuffer:this.videoBuffer;return!n||!r?NaN:mo.bufferInfo(n,r.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){const{pLoader:t}=this.config,r=this.applyPlaylistData,n=t||this.config.loader;return class{constructor(i){this.loader=void 0,this.loader=new n(i)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(i,l,o){r(i),this.loader.load(i,l,o)}}}createFragmentLoader(){const{fLoader:t}=this.config,r=this.applyFragmentData,n=t||this.config.loader;return class{constructor(i){this.loader=void 0,this.loader=new n(i)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(i,l,o){r(i),this.loader.load(i,l,o)}}}}const kGs=3e5;class SGs extends dv{constructor(t){super("content-steering",t.logger),this.hls=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this._pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=t,this.registerListeners()}registerListeners(){const t=this.hls;t.on(vt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(vt.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(vt.MANIFEST_PARSED,this.onManifestParsed,this),t.on(vt.ERROR,this.onError,this)}unregisterListeners(){const t=this.hls;t&&(t.off(vt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(vt.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(vt.MANIFEST_PARSED,this.onManifestParsed,this),t.off(vt.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((t,r)=>(t.indexOf(r.pathwayId)===-1&&t.push(r.pathwayId),t),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(t){this.updatePathwayPriority(t)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const t=this.timeToLoad*1e3-(performance.now()-this.updated);if(t>0){this.scheduleRefresh(this.uri,t);return}}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){this.reloadTimer!==-1&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(t){const r=this.levels;r&&(this.levels=r.filter(n=>n!==t))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(t,r){const{contentSteering:n}=r;n!==null&&(this.pathwayId=n.pathwayId,this.uri=n.uri,this.started&&this.startLoad())}onManifestParsed(t,r){this.audioTracks=r.audioTracks,this.subtitleTracks=r.subtitleTracks}onError(t,r){const{errorAction:n}=r;if((n==null?void 0:n.action)===If.SendAlternateToPenaltyBox&&n.flags===Kx.MoveAllAlternatesMatchingHost){const a=this.levels;let i=this._pathwayPriority,l=this.pathwayId;if(r.context){const{groupId:o,pathwayId:c,type:d}=r.context;o&&a?l=this.getPathwayForGroupId(o,d,l):c&&(l=c)}l in this.penalizedPathways||(this.penalizedPathways[l]=performance.now()),!i&&a&&(i=this.pathways()),i&&i.length>1&&(this.updatePathwayPriority(i),n.resolved=this.pathwayId!==l),r.details===yr.BUFFER_APPEND_ERROR&&!r.fatal?n.resolved=!0:n.resolved||this.warn(`Could not resolve ${r.details} ("${r.error.message}") with content-steering for Pathway: ${l} levels: ${a&&a.length} priorities: ${Uc(i)} penalized: ${Uc(this.penalizedPathways)}`)}}filterParsedLevels(t){this.levels=t;let r=this.getLevelsForPathway(this.pathwayId);if(r.length===0){const n=t[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${n}"`),r=this.getLevelsForPathway(n),this.pathwayId=n}return r.length!==t.length&&this.log(`Found ${r.length}/${t.length} levels in Pathway "${this.pathwayId}"`),r}getLevelsForPathway(t){return this.levels===null?[]:this.levels.filter(r=>t===r.pathwayId)}updatePathwayPriority(t){this._pathwayPriority=t;let r;const n=this.penalizedPathways,a=performance.now();Object.keys(n).forEach(i=>{a-n[i]>kGs&&delete n[i]});for(let i=0;i0){this.log(`Setting Pathway to "${l}"`),this.pathwayId=l,x1t(r),this.hls.trigger(vt.LEVELS_UPDATED,{levels:r});const d=this.hls.levels[o];c&&d&&this.levels&&(d.attrs["STABLE-VARIANT-ID"]!==c.attrs["STABLE-VARIANT-ID"]&&d.bitrate!==c.bitrate&&this.log(`Unstable Pathways change from bitrate ${c.bitrate} to ${d.bitrate}`),this.hls.nextLoadLevel=o);break}}}getPathwayForGroupId(t,r,n){const a=this.getLevelsForPathway(n).concat(this.levels||[]);for(let i=0;i{const{ID:l,"BASE-ID":o,"URI-REPLACEMENT":c}=i;if(r.some(h=>h.pathwayId===l))return;const d=this.getLevelsForPathway(o).map(h=>{const m=new au(h.attrs);m["PATHWAY-ID"]=l;const p=m.AUDIO&&`${m.AUDIO}_clone_${l}`,x=m.SUBTITLES&&`${m.SUBTITLES}_clone_${l}`;p&&(n[m.AUDIO]=p,m.AUDIO=p),x&&(a[m.SUBTITLES]=x,m.SUBTITLES=x);const y=Q1t(h.uri,m["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",c),_=new _B({attrs:m,audioCodec:h.audioCodec,bitrate:h.bitrate,height:h.height,name:h.name,url:y,videoCodec:h.videoCodec,width:h.width});if(h.audioGroups)for(let b=1;b{this.log(`Loaded steering manifest: "${a}"`);const y=h.data;if((y==null?void 0:y.VERSION)!==1){this.log(`Steering VERSION ${y.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=y.TTL;const{"RELOAD-URI":_,"PATHWAY-CLONES":b,"PATHWAY-PRIORITY":j}=y;if(_)try{this.uri=new self.URL(_,a).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${_}`);return}this.scheduleRefresh(this.uri||p.url),b&&this.clonePathways(b);const k={steeringManifest:y,url:a.toString()};this.hls.trigger(vt.STEERING_MANIFEST_LOADED,k),j&&this.updatePathwayPriority(j)},onError:(h,m,p,x)=>{if(this.log(`Error loading steering manifest: ${h.code} ${h.text} (${m.url})`),this.stopLoad(),h.code===410){this.enabled=!1,this.log(`Steering manifest ${m.url} no longer available`);return}let y=this.timeToLoad*1e3;if(h.code===429){const _=this.loader;if(typeof(_==null?void 0:_.getResponseHeader)=="function"){const b=_.getResponseHeader("Retry-After");b&&(y=parseFloat(b)*1e3)}this.log(`Steering manifest ${m.url} rate limited`);return}this.scheduleRefresh(this.uri||m.url,y)},onTimeout:(h,m,p)=>{this.log(`Timeout loading steering manifest (${m.url})`),this.scheduleRefresh(this.uri||m.url)}};this.log(`Requesting steering manifest: ${a}`),this.loader.load(i,c,d)}scheduleRefresh(t,r=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var n;const a=(n=this.hls)==null?void 0:n.media;if(a&&!a.ended){this.loadSteeringManifest(t);return}this.scheduleRefresh(t,this.timeToLoad*1e3)},r)}}function ZKe(s,t,r,n){s&&Object.keys(t).forEach(a=>{const i=s.filter(l=>l.groupId===a).map(l=>{const o=Ec({},l);return o.details=void 0,o.attrs=new au(o.attrs),o.url=o.attrs.URI=Q1t(l.url,l.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",r),o.groupId=o.attrs["GROUP-ID"]=t[a],o.attrs["PATHWAY-ID"]=n,o});s.push(...i)})}function Q1t(s,t,r,n){const{HOST:a,PARAMS:i,[r]:l}=n;let o;t&&(o=l==null?void 0:l[t],o&&(s=o));const c=new self.URL(s);return a&&!o&&(c.host=a),i&&Object.keys(i).sort().forEach(d=>{d&&c.searchParams.set(d,i[d])}),c.href}class NP extends dv{constructor(t){super("eme",t.logger),this.hls=void 0,this.config=void 0,this.media=null,this.mediaResolved=void 0,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.mediaKeys=null,this.setMediaKeysQueue=NP.CDMCleanupPromise?[NP.CDMCleanupPromise]:[],this.bannedKeyIds={},this.onMediaEncrypted=r=>{const{initDataType:n,initData:a}=r,i=`"${r.type}" event: init data type: "${n}"`;if(this.debug(i),a!==null){if(!this.keyFormatPromise){let l=Object.keys(this.keySystemAccessPromises);l.length||(l=LO(this.config));const o=l.map(Bwe).filter(c=>!!c);this.keyFormatPromise=this.getKeyFormatPromise(o)}this.keyFormatPromise.then(l=>{const o=$ue(l);if(n!=="sinf"||o!==hu.FAIRPLAY){this.log(`Ignoring "${r.type}" event with init data type: "${n}" for selected key-system ${o}`);return}let c;try{const x=rm(new Uint8Array(a)),y=P6e(JSON.parse(x).sinf),_=Gvt(y);if(!_)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");c=new Uint8Array(_.subarray(8,24))}catch(x){this.warn(`${i} Failed to parse sinf: ${x}`);return}const d=Pf(c),{keyIdToKeySessionPromise:h,mediaKeySessions:m}=this;let p=h[d];for(let x=0;xthis.generateRequestWithPreferredKeySession(y,n,a,"encrypted-event-key-match")),p.catch(j=>this.handleError(j));break}}p||this.handleError(new Error(`Key ID ${d} not encountered in playlist. Key-system sessions ${m.length}.`))}).catch(l=>this.handleError(l))}},this.onWaitingForKey=r=>{this.log(`"${r.type}" event`)},this.hls=t,this.config=t.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();const t=this.config;t.requestMediaKeySystemAccessFunc=null,t.licenseXhrSetup=t.licenseResponseCallback=void 0,t.drmSystems=t.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){this.hls.on(vt.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(vt.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(vt.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(vt.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(vt.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off(vt.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(vt.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(vt.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(vt.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(vt.DESTROYING,this.onDestroying,this)}getLicenseServerUrl(t){const{drmSystems:r,widevineLicenseUrl:n}=this.config,a=r==null?void 0:r[t];if(a)return a.licenseUrl;if(t===hu.WIDEVINE&&n)return n}getLicenseServerUrlOrThrow(t){const r=this.getLicenseServerUrl(t);if(r===void 0)throw new Error(`no license server URL configured for key-system "${t}"`);return r}getServerCertificateUrl(t){const{drmSystems:r}=this.config,n=r==null?void 0:r[t];if(n)return n.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${t}"]`)}attemptKeySystemAccess(t){const r=this.hls.levels,n=(l,o,c)=>!!l&&c.indexOf(l)===o,a=r.map(l=>l.audioCodec).filter(n),i=r.map(l=>l.videoCodec).filter(n);return a.length+i.length===0&&i.push("avc1.42e01e"),new Promise((l,o)=>{const c=d=>{const h=d.shift();this.getMediaKeysPromise(h,a,i).then(m=>l({keySystem:h,mediaKeys:m})).catch(m=>{d.length?c(d):m instanceof Hx?o(m):o(new Hx({type:ci.KEY_SYSTEM_ERROR,details:yr.KEY_SYSTEM_NO_ACCESS,error:m,fatal:!0},m.message))})};c(t)})}requestMediaKeySystemAccess(t,r){const{requestMediaKeySystemAccessFunc:n}=this.config;if(typeof n!="function"){let a=`Configured requestMediaKeySystemAccess is not a function ${n}`;return c1t===null&&self.location.protocol==="http:"&&(a=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(a))}return n(t,r)}getMediaKeysPromise(t,r,n){var a;const i=iVs(t,r,n,this.config.drmSystemOptions||{});let l=this.keySystemAccessPromises[t],o=(a=l)==null?void 0:a.keySystemAccess;if(!o){this.log(`Requesting encrypted media "${t}" key-system access with config: ${Uc(i)}`),o=this.requestMediaKeySystemAccess(t,i);const c=l=this.keySystemAccessPromises[t]={keySystemAccess:o};return o.catch(d=>{this.log(`Failed to obtain access to key-system "${t}": ${d}`)}),o.then(d=>{this.log(`Access for key-system "${d.keySystem}" obtained`);const h=this.fetchServerCertificate(t);this.log(`Create media-keys for "${t}"`);const m=c.mediaKeys=d.createMediaKeys().then(p=>(this.log(`Media-keys created for "${t}"`),c.hasMediaKeys=!0,h.then(x=>x?this.setMediaKeysServerCertificate(p,t,x):p)));return m.catch(p=>{this.error(`Failed to create media-keys for "${t}"}: ${p}`)}),m})}return o.then(()=>l.mediaKeys)}createMediaKeySessionContext({decryptdata:t,keySystem:r,mediaKeys:n}){this.log(`Creating key-system session "${r}" keyId: ${Pf(t.keyId||[])} keyUri: ${t.uri}`);const a=n.createSession(),i={decryptdata:t,keySystem:r,mediaKeys:n,mediaKeysSession:a,keyStatus:"status-pending"};return this.mediaKeySessions.push(i),i}renewKeySession(t){const r=t.decryptdata;if(r.pssh){const n=this.createMediaKeySessionContext(t),a=gV(r),i="cenc";this.keyIdToKeySessionPromise[a]=this.generateRequestWithPreferredKeySession(n,i,r.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(t)}updateKeySession(t,r){const n=t.mediaKeysSession;return this.log(`Updating key-session "${n.sessionId}" for keyId ${Pf(t.decryptdata.keyId||[])} } (data length: ${r.byteLength})`),n.update(r)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(t=>({keySystem:t,hasMediaKeys:this.keySystemAccessPromises[t].hasMediaKeys})).filter(({hasMediaKeys:t})=>!!t).map(({keySystem:t})=>Bwe(t)).filter(t=>!!t)}getKeySystemAccess(t){return this.getKeySystemSelectionPromise(t).then(({keySystem:r,mediaKeys:n})=>this.attemptSetMediaKeys(r,n))}selectKeySystem(t){return new Promise((r,n)=>{this.getKeySystemSelectionPromise(t).then(({keySystem:a})=>{const i=Bwe(a);i?r(i):n(new Error(`Unable to find format for key-system "${a}"`))}).catch(n)})}selectKeySystemFormat(t){const r=Object.keys(t.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${t.sn} ${t.type}: ${t.level}) key formats ${r.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(r)),this.keyFormatPromise}getKeyFormatPromise(t){const r=LO(this.config),n=t.map($ue).filter(a=>!!a&&r.indexOf(a)!==-1);return this.selectKeySystem(n)}getKeyStatus(t){const{mediaKeySessions:r}=this;for(let n=0;n(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${t.frag.sn} ${t.frag.type}: ${t.frag.level} using key ${i}`),this.attemptSetMediaKeys(c,d).then(()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:c,mediaKeys:d,decryptdata:r}))))).then(c=>{const d="cenc",h=r.pssh?r.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(c,d,h,"playlist-key")});return o.catch(c=>this.handleError(c,t.frag)),this.keyIdToKeySessionPromise[n]=o,o}return l.catch(o=>{if(o instanceof Hx){const c=hc({},o.data);this.getKeyStatus(r)==="internal-error"&&(c.decryptdata=r);const d=new Hx(c,o.message);this.handleError(d,t.frag)}}),l}throwIfDestroyed(t="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(t,r){if(this.hls)if(t instanceof Hx){r&&(t.data.frag=r);const n=t.data.decryptdata;this.error(`${t.message}${n?` (${Pf(n.keyId||[])})`:""}`),this.hls.trigger(vt.ERROR,t.data)}else this.error(t.message),this.hls.trigger(vt.ERROR,{type:ci.KEY_SYSTEM_ERROR,details:yr.KEY_SYSTEM_NO_KEYS,error:t,fatal:!0})}getKeySystemForKeyPromise(t){const r=gV(t),n=this.keyIdToKeySessionPromise[r];if(!n){const a=$ue(t.keyFormat),i=a?[a]:LO(this.config);return this.attemptKeySystemAccess(i)}return n}getKeySystemSelectionPromise(t){if(t.length||(t=LO(this.config)),t.length===0)throw new Hx({type:ci.KEY_SYSTEM_ERROR,details:yr.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${Uc({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(t)}attemptSetMediaKeys(t,r){if(this.mediaResolved=void 0,this.mediaKeys===r)return Promise.resolve();const n=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${t}"`);const a=Promise.all(n).then(()=>this.media?this.media.setMediaKeys(r):new Promise((i,l)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return l(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=r,this.media.setMediaKeys(r).then(i).catch(l)}}));return this.mediaKeys=r,this.setMediaKeysQueue.push(a),a.then(()=>{this.log(`Media-keys set for "${t}"`),n.push(a),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(i=>n.indexOf(i)===-1)})}generateRequestWithPreferredKeySession(t,r,n,a){var i;const l=(i=this.config.drmSystems)==null||(i=i[t.keySystem])==null?void 0:i.generateRequest;if(l)try{const y=l.call(this.hls,r,n,t);if(!y)throw new Error("Invalid response from configured generateRequest filter");r=y.initDataType,n=y.initData?y.initData:null,t.decryptdata.pssh=n?new Uint8Array(n):null}catch(y){if(this.warn(y.message),this.hls&&this.hls.config.debug)throw y}if(n===null)return this.log(`Skipping key-session request for "${a}" (no initData)`),Promise.resolve(t);const o=gV(t.decryptdata),c=t.decryptdata.uri;this.log(`Generating key-session request for "${a}" keyId: ${o} URI: ${c} (init data type: ${r} length: ${n.byteLength})`);const d=new D6e,h=t._onmessage=y=>{const _=t.mediaKeysSession;if(!_){d.emit("error",new Error("invalid state"));return}const{messageType:b,message:j}=y;this.log(`"${b}" message event for session "${_.sessionId}" message size: ${j.byteLength}`),b==="license-request"||b==="license-renewal"?this.renewLicense(t,j).catch(k=>{d.eventNames().length?d.emit("error",k):this.handleError(k)}):b==="license-release"?t.keySystem===hu.FAIRPLAY&&this.updateKeySession(t,aCe("acknowledged")).then(()=>this.removeSession(t)).catch(k=>this.handleError(k)):this.warn(`unhandled media key message type "${b}"`)},m=(y,_)=>{_.keyStatus=y;let b;y.startsWith("usable")?d.emit("resolved"):y==="internal-error"||y==="output-restricted"||y==="output-downscaled"?b=XKe(y,_.decryptdata):y==="expired"?b=new Error(`key expired (keyId: ${o})`):y==="released"?b=new Error("key released"):y==="status-pending"||this.warn(`unhandled key status change "${y}" (keyId: ${o})`),b&&(d.eventNames().length?d.emit("error",b):this.handleError(b))},p=t._onkeystatuseschange=y=>{if(!t.mediaKeysSession){d.emit("error",new Error("invalid state"));return}const b=this.getKeyStatuses(t);if(!Object.keys(b).some(E=>b[E]!=="status-pending"))return;if(b[o]==="expired"){this.log(`Expired key ${Uc(b)} in key-session "${t.mediaKeysSession.sessionId}"`),this.renewKeySession(t);return}let k=b[o];if(k)m(k,t);else{var T;t.keyStatusTimeouts||(t.keyStatusTimeouts={}),(T=t.keyStatusTimeouts)[o]||(T[o]=self.setTimeout(()=>{if(!t.mediaKeysSession||!this.mediaKeys)return;const A=this.getKeyStatus(t.decryptdata);if(A&&A!=="status-pending")return this.log(`No status for keyId ${o} in key-session "${t.mediaKeysSession.sessionId}". Using session key-status ${A} from other session.`),m(A,t);this.log(`key status for ${o} in key-session "${t.mediaKeysSession.sessionId}" timed out after 1000ms`),k="internal-error",m(k,t)},1e3)),this.log(`No status for keyId ${o} (${Uc(b)}).`)}};vg(t.mediaKeysSession,"message",h),vg(t.mediaKeysSession,"keystatuseschange",p);const x=new Promise((y,_)=>{d.on("error",_),d.on("resolved",y)});return t.mediaKeysSession.generateRequest(r,n).then(()=>{this.log(`Request generated for key-session "${t.mediaKeysSession.sessionId}" keyId: ${o} URI: ${c}`)}).catch(y=>{throw new Hx({type:ci.KEY_SYSTEM_ERROR,details:yr.KEY_SYSTEM_NO_SESSION,error:y,decryptdata:t.decryptdata,fatal:!1},`Error generating key-session request: ${y}`)}).then(()=>x).catch(y=>(d.removeAllListeners(),this.removeSession(t).then(()=>{throw y}))).then(()=>(d.removeAllListeners(),t))}getKeyStatuses(t){const r={};return t.mediaKeysSession.keyStatuses.forEach((n,a)=>{if(typeof a=="string"&&typeof n=="object"){const o=a;a=n,n=o}const i="buffer"in a?new Uint8Array(a.buffer,a.byteOffset,a.byteLength):new Uint8Array(a);if(t.keySystem===hu.PLAYREADY&&i.length===16){const o=Pf(i);r[o]=n,o1t(i)}const l=Pf(i);n==="internal-error"&&(this.bannedKeyIds[l]=n),this.log(`key status change "${n}" for keyStatuses keyId: ${l} key-session "${t.mediaKeysSession.sessionId}"`),r[l]=n}),r}fetchServerCertificate(t){const r=this.config,n=r.loader,a=new n(r),i=this.getServerCertificateUrl(t);return i?(this.log(`Fetching server certificate for "${t}"`),new Promise((l,o)=>{const c={responseType:"arraybuffer",url:i},d=r.certLoadPolicy.default,h={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},m={onSuccess:(p,x,y,_)=>{l(p.data)},onError:(p,x,y,_)=>{o(new Hx({type:ci.KEY_SYSTEM_ERROR,details:yr.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:y,response:hc({url:c.url,data:void 0},p)},`"${t}" certificate request failed (${i}). Status: ${p.code} (${p.text})`))},onTimeout:(p,x,y)=>{o(new Hx({type:ci.KEY_SYSTEM_ERROR,details:yr.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:y,response:{url:c.url,data:void 0}},`"${t}" certificate request timed out (${i})`))},onAbort:(p,x,y)=>{o(new Error("aborted"))}};a.load(c,h,m)})):Promise.resolve()}setMediaKeysServerCertificate(t,r,n){return new Promise((a,i)=>{t.setServerCertificate(n).then(l=>{this.log(`setServerCertificate ${l?"success":"not supported by CDM"} (${n.byteLength}) on "${r}"`),a(t)}).catch(l=>{i(new Hx({type:ci.KEY_SYSTEM_ERROR,details:yr.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:l,fatal:!0},l.message))})})}renewLicense(t,r){return this.requestLicense(t,new Uint8Array(r)).then(n=>this.updateKeySession(t,new Uint8Array(n)).catch(a=>{throw new Hx({type:ci.KEY_SYSTEM_ERROR,details:yr.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:t.decryptdata,error:a,fatal:!1},a.message)}))}unpackPlayReadyKeyMessage(t,r){const n=String.fromCharCode.apply(null,new Uint16Array(r.buffer));if(!n.includes("PlayReadyKeyMessage"))return t.setRequestHeader("Content-Type","text/xml; charset=utf-8"),r;const a=new DOMParser().parseFromString(n,"application/xml"),i=a.querySelectorAll("HttpHeader");if(i.length>0){let h;for(let m=0,p=i.length;m in key message");return aCe(atob(d))}setupLicenseXHR(t,r,n,a){const i=this.config.licenseXhrSetup;return i?Promise.resolve().then(()=>{if(!n.decryptdata)throw new Error("Key removed");return i.call(this.hls,t,r,n,a)}).catch(l=>{if(!n.decryptdata)throw l;return t.open("POST",r,!0),i.call(this.hls,t,r,n,a)}).then(l=>(t.readyState||t.open("POST",r,!0),{xhr:t,licenseChallenge:l||a})):(t.open("POST",r,!0),Promise.resolve({xhr:t,licenseChallenge:a}))}requestLicense(t,r){const n=this.config.keyLoadPolicy.default;return new Promise((a,i)=>{const l=this.getLicenseServerUrlOrThrow(t.keySystem);this.log(`Sending license request to URL: ${l}`);const o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=()=>{if(!this.hls||!t.mediaKeysSession)return i(new Error("invalid state"));if(o.readyState===4)if(o.status===200){this._requestLicenseFailureCount=0;let c=o.response;this.log(`License received ${c instanceof ArrayBuffer?c.byteLength:c}`);const d=this.config.licenseResponseCallback;if(d)try{c=d.call(this.hls,o,l,t)}catch(h){this.error(h)}a(c)}else{const c=n.errorRetry,d=c?c.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>d||o.status>=400&&o.status<500)i(new Hx({type:ci.KEY_SYSTEM_ERROR,details:yr.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:t.decryptdata,fatal:!0,networkDetails:o,response:{url:l,data:void 0,code:o.status,text:o.statusText}},`License Request XHR failed (${l}). Status: ${o.status} (${o.statusText})`));else{const h=d-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${h} attempts left`),this.requestLicense(t,r).then(a,i)}}},t.licenseXhr&&t.licenseXhr.readyState!==XMLHttpRequest.DONE&&t.licenseXhr.abort(),t.licenseXhr=o,this.setupLicenseXHR(o,l,t,r).then(({xhr:c,licenseChallenge:d})=>{t.keySystem==hu.PLAYREADY&&(d=this.unpackPlayReadyKeyMessage(c,d)),c.send(d)}).catch(i)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(t,r){if(!this.config.emeEnabled)return;const n=r.media;this.media=n,vg(n,"encrypted",this.onMediaEncrypted),vg(n,"waitingforkey",this.onWaitingForKey);const a=this.mediaResolved;a?a():this.mediaKeys=n.mediaKeys}onMediaDetached(){const t=this.media;t&&(nx(t,"encrypted",this.onMediaEncrypted),nx(t,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var t;this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},this.bannedKeyIds={};const r=this.mediaResolved;if(r&&r(),!this.mediaKeys&&!this.mediaKeySessions.length)return;const n=this.media,a=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,dS.clearKeyUriToKeyIdMap();const i=a.length;NP.CDMCleanupPromise=Promise.all(a.map(l=>this.removeSession(l)).concat((n==null||(t=n.setMediaKeys(null))==null?void 0:t.catch(l=>{this.log(`Could not clear media keys: ${l}`),this.hls&&this.hls.trigger(vt.ERROR,{type:ci.OTHER_ERROR,details:yr.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${l}`)})}))||Promise.resolve())).catch(l=>{this.log(`Could not close sessions and clear media keys: ${l}`),this.hls&&this.hls.trigger(vt.ERROR,{type:ci.OTHER_ERROR,details:yr.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${l}`)})}).then(()=>{i&&this.log("finished closing key sessions and clearing media keys")})}onManifestLoading(){this._clear()}onManifestLoaded(t,{sessionKeys:r}){if(!(!r||!this.config.emeEnabled)&&!this.keyFormatPromise){const n=r.reduce((a,i)=>(a.indexOf(i.keyFormat)===-1&&a.push(i.keyFormat),a),[]);this.log(`Selecting key-system from session-keys ${n.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(n)}}removeSession(t){const{mediaKeysSession:r,licenseXhr:n,decryptdata:a}=t;if(r){this.log(`Remove licenses and keys and close session "${r.sessionId}" keyId: ${Pf((a==null?void 0:a.keyId)||[])}`),t._onmessage&&(r.removeEventListener("message",t._onmessage),t._onmessage=void 0),t._onkeystatuseschange&&(r.removeEventListener("keystatuseschange",t._onkeystatuseschange),t._onkeystatuseschange=void 0),n&&n.readyState!==XMLHttpRequest.DONE&&n.abort(),t.mediaKeysSession=t.decryptdata=t.licenseXhr=void 0;const i=this.mediaKeySessions.indexOf(t);i>-1&&this.mediaKeySessions.splice(i,1);const{keyStatusTimeouts:l}=t;l&&Object.keys(l).forEach(d=>self.clearTimeout(l[d]));const{drmSystemOptions:o}=this.config;return(lVs(o)?new Promise((d,h)=>{self.setTimeout(()=>h(new Error("MediaKeySession.remove() timeout")),8e3),r.remove().then(d).catch(h)}):Promise.resolve()).catch(d=>{this.log(`Could not remove session: ${d}`),this.hls&&this.hls.trigger(vt.ERROR,{type:ci.OTHER_ERROR,details:yr.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${d}`)})}).then(()=>r.close()).catch(d=>{this.log(`Could not close session: ${d}`),this.hls&&this.hls.trigger(vt.ERROR,{type:ci.OTHER_ERROR,details:yr.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${d}`)})})}return Promise.resolve()}}NP.CDMCleanupPromise=void 0;function gV(s){if(!s)throw new Error("Could not read keyId of undefined decryptdata");if(s.keyId===null)throw new Error("keyId is null");return Pf(s.keyId)}function CGs(s,t){if(s.keyId&&t.mediaKeysSession.keyStatuses.has(s.keyId))return t.mediaKeysSession.keyStatuses.get(s.keyId);if(s.matches(t.decryptdata))return t.keyStatus}class Hx extends Error{constructor(t,r){super(r),this.data=void 0,t.error||(t.error=new Error(r)),this.data=t,t.err=t.error}}function XKe(s,t){const r=s==="output-restricted",n=r?yr.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:yr.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new Hx({type:ci.KEY_SYSTEM_ERROR,details:n,fatal:!1,decryptdata:t},r?"HDCP level output restricted":`key status changed to "${s}"`)}class TGs{constructor(t){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=t,this.registerListeners()}setStreamController(t){this.streamController=t}registerListeners(){this.hls.on(vt.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(vt.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(vt.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(vt.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(t,r){const n=this.hls.config;if(n.capLevelOnFPSDrop){const a=r.media instanceof self.HTMLVideoElement?r.media:null;this.media=a,a&&typeof a.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),n.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(t,r,n){const a=performance.now();if(r){if(this.lastTime){const i=a-this.lastTime,l=n-this.lastDroppedFrames,o=r-this.lastDecodedFrames,c=1e3*l/i,d=this.hls;if(d.trigger(vt.FPS_DROP,{currentDropped:l,currentDecoded:o,totalDroppedFrames:n}),c>0&&l>d.config.fpsDroppedMonitoringThreshold*o){let h=d.currentLevel;d.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+h),h>0&&(d.autoLevelCapping===-1||d.autoLevelCapping>=h)&&(h=h-1,d.trigger(vt.FPS_DROP_LEVEL_CAPPING,{level:h,droppedLevel:d.currentLevel}),d.autoLevelCapping=h,this.streamController.nextLevelSwitch())}}this.lastTime=a,this.lastDroppedFrames=n,this.lastDecodedFrames=r}}checkFPSInterval(){const t=this.media;if(t)if(this.isVideoPlaybackQualityAvailable){const r=t.getVideoPlaybackQuality();this.checkFPS(t,r.totalVideoFrames,r.droppedVideoFrames)}else this.checkFPS(t,t.webkitDecodedFrameCount,t.webkitDroppedFrameCount)}}function J1t(s,t){let r;try{r=new Event("addtrack")}catch{r=document.createEvent("Event"),r.initEvent("addtrack",!1,!1)}r.track=s,t.dispatchEvent(r)}function ebt(s,t){const r=s.mode;if(r==="disabled"&&(s.mode="hidden"),s.cues&&!s.cues.getCueById(t.id))try{if(s.addCue(t),!s.cues.getCueById(t.id))throw new Error(`addCue is failed for: ${t}`)}catch(n){gc.debug(`[texttrack-utils]: ${n}`);try{const a=new self.TextTrackCue(t.startTime,t.endTime,t.text);a.id=t.id,s.addCue(a)}catch(a){gc.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${a}`)}}r==="disabled"&&(s.mode=r)}function wI(s,t){const r=s.mode;if(r==="disabled"&&(s.mode="hidden"),s.cues)for(let n=s.cues.length;n--;)t&&s.cues[n].removeEventListener("enter",t),s.removeCue(s.cues[n]);r==="disabled"&&(s.mode=r)}function fCe(s,t,r,n){const a=s.mode;if(a==="disabled"&&(s.mode="hidden"),s.cues&&s.cues.length>0){const i=AGs(s.cues,t,r);for(let l=0;ls[r].endTime)return-1;let n=0,a=r,i;for(;n<=a;)if(i=Math.floor((a+n)/2),ts[i].startTime&&n-1)for(let i=a,l=s.length;i=t&&o.endTime<=r)n.push(o);else if(o.startTime>r)return n}return n}function Hue(s){const t=[];for(let r=0;rthis.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let r=null;const n=Hue(this.media.textTracks);for(let i=0;i-1&&this.toggleTrackModes()}registerListeners(){const{hls:t}=this;t.on(vt.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(vt.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(vt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(vt.MANIFEST_PARSED,this.onManifestParsed,this),t.on(vt.LEVEL_LOADING,this.onLevelLoading,this),t.on(vt.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(vt.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(vt.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(vt.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(vt.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(vt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(vt.MANIFEST_PARSED,this.onManifestParsed,this),t.off(vt.LEVEL_LOADING,this.onLevelLoading,this),t.off(vt.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(vt.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(vt.ERROR,this.onError,this)}onMediaAttached(t,r){this.media=r.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}pollTrackChange(t){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,t)}onMediaDetaching(t,r){const n=this.media;if(!n)return;const a=!!r.transferMedia;if(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||n.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,a)return;Hue(n.textTracks).forEach(l=>{wI(l)})}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(t,r){this.tracks=r.subtitleTracks}onSubtitleTrackLoaded(t,r){const{id:n,groupId:a,details:i}=r,l=this.tracksInGroup[n];if(!l||l.groupId!==a){this.warn(`Subtitle track with id:${n} and group:${a} not found in active group ${l==null?void 0:l.groupId}`);return}const o=l.details;l.details=r.details,this.log(`Subtitle track ${n} "${l.name}" lang:${l.lang} group:${a} loaded [${i.startSN}-${i.endSN}]`),n===this.trackId&&this.playlistLoaded(n,r,o)}onLevelLoading(t,r){this.switchLevel(r.level)}onLevelSwitching(t,r){this.switchLevel(r.level)}switchLevel(t){const r=this.hls.levels[t];if(!r)return;const n=r.subtitleGroups||null,a=this.groupIds;let i=this.currentTrack;if(!n||(a==null?void 0:a.length)!==(n==null?void 0:n.length)||n!=null&&n.some(l=>(a==null?void 0:a.indexOf(l))===-1)){this.groupIds=n,this.trackId=-1,this.currentTrack=null;const l=this.tracks.filter(h=>!n||n.indexOf(h.groupId)!==-1);if(l.length)this.selectDefaultTrack&&!l.some(h=>h.default)&&(this.selectDefaultTrack=!1),l.forEach((h,m)=>{h.id=m});else if(!i&&!this.tracksInGroup.length)return;this.tracksInGroup=l;const o=this.hls.config.subtitlePreference;if(!i&&o){this.selectDefaultTrack=!1;const h=o_(o,l);if(h>-1)i=l[h];else{const m=o_(o,this.tracks);i=this.tracks[m]}}let c=this.findTrackId(i);c===-1&&i&&(c=this.findTrackId(null));const d={subtitleTracks:l};this.log(`Updating subtitle tracks, ${l.length} track(s) found in "${n==null?void 0:n.join(",")}" group-id`),this.hls.trigger(vt.SUBTITLE_TRACKS_UPDATED,d),c!==-1&&this.trackId===-1&&this.setSubtitleTrack(c)}}findTrackId(t){const r=this.tracksInGroup,n=this.selectDefaultTrack;for(let a=0;a-1){const i=this.tracksInGroup[a];return this.setSubtitleTrack(a),i}else{if(n)return null;{const i=o_(t,r);if(i>-1)return r[i]}}}}return null}loadPlaylist(t){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,t)}loadingPlaylist(t,r){super.loadingPlaylist(t,r);const n=t.id,a=t.groupId,i=this.getUrlWithDirectives(t.url,r),l=t.details,o=l==null?void 0:l.age;this.log(`Loading subtitle ${n} "${t.name}" lang:${t.lang} group:${a}${(r==null?void 0:r.msn)!==void 0?" at sn "+r.msn+" part "+r.part:""}${o&&l.live?" age "+o.toFixed(1)+(l.type&&" "+l.type||""):""} ${i}`),this.hls.trigger(vt.SUBTITLE_TRACK_LOADING,{url:i,id:n,groupId:a,deliveryDirectives:r||null,track:t})}toggleTrackModes(){const{media:t}=this;if(!t)return;const r=Hue(t.textTracks),n=this.currentTrack;let a;if(n&&(a=r.filter(i=>dCe(n,i))[0],a||this.warn(`Unable to find subtitle TextTrack with name "${n.name}" and language "${n.lang}"`)),[].slice.call(r).forEach(i=>{i.mode!=="disabled"&&i!==a&&(i.mode="disabled")}),a){const i=this.subtitleDisplay?"showing":"hidden";a.mode!==i&&(a.mode=i)}}setSubtitleTrack(t){const r=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=t;return}if(t<-1||t>=r.length||!ka(t)){this.warn(`Invalid subtitle track id: ${t}`);return}this.selectDefaultTrack=!1;const n=this.currentTrack,a=r[t]||null;if(this.trackId=t,this.currentTrack=a,this.toggleTrackModes(),!a){this.hls.trigger(vt.SUBTITLE_TRACK_SWITCH,{id:t});return}const i=!!a.details&&!a.details.live;if(t===this.trackId&&a===n&&i)return;this.log(`Switching to subtitle-track ${t}`+(a?` "${a.name}" lang:${a.lang} group:${a.groupId}`:""));const{id:l,groupId:o="",name:c,type:d,url:h}=a;this.hls.trigger(vt.SUBTITLE_TRACK_SWITCH,{id:l,groupId:o,name:c,type:d,url:h});const m=this.switchParams(a.url,n==null?void 0:n.details,a.details);this.loadPlaylist(m)}}function IGs(){try{return crypto.randomUUID()}catch{try{const t=URL.createObjectURL(new Blob),r=t.toString();return URL.revokeObjectURL(t),r.slice(r.lastIndexOf("/")+1)}catch{let r=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,a=>{const i=(r+Math.random()*16)%16|0;return r=Math.floor(r/16),(a=="x"?i:i&3|8).toString(16)})}}}function L7(s){let t=5381,r=s.length;for(;r;)t=t*33^s.charCodeAt(--r);return(t>>>0).toString()}const kP=.025;let kpe=function(s){return s[s.Point=0]="Point",s[s.Range=1]="Range",s}({});function PGs(s,t,r){return`${s.identifier}-${r+1}-${L7(t)}`}class LGs{constructor(t,r){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=r,this.dateRange=t,this.setDateRange(t)}setDateRange(t){this.dateRange=t,this.resumeOffset=t.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=t.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=t.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=t.attr.enumeratedStringList("X-SNAP",this.snapOptions)}reset(){var t;this.appendInPlaceStarted=!1,(t=this.assetListLoader)==null||t.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(t){var r;if(t>0&&t>=this.assetList.length)return!0;const n=this.playoutLimit;return t<=0||isNaN(n)?!1:n===0?!0:(((r=this.assetList[t])==null?void 0:r.startOffset)||0)>n}findAssetIndex(t){return this.assetList.indexOf(t)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){const t=this.dateRange.startTime;if(this.snapOptions.out){const r=this.dateRange.tagAnchor;if(r)return Kwe(t,r)}return t}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(this.startTime===0||this.snapOptions.out)return!0;const t=this.dateRange.tagAnchor;if(t){const r=this.dateRange.startTime,n=Kwe(r,t);return r-n<.1}return!1}get resumptionOffset(){const t=this.resumeOffset,r=ka(t)?t:this.duration;return this.cumulativeDuration+r}get resumeTime(){const t=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){const r=this.resumeAnchor;if(r)return Kwe(t,r)}return t}get appendInPlace(){return this.appendInPlaceStarted?!0:this.appendInPlaceDisabled?!1:!!(!this.cue.once&&!this.cue.pre&&this.startIsAligned&&(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)0||this.assetListResponse!==null}toString(){return DGs(this)}}function Kwe(s,t){return s-t.start":s.cue.post?"":""}${s.timelineStart.toFixed(2)}-${s.resumeTime.toFixed(2)}]`}function W6(s){const t=s.timelineStart,r=s.duration||0;return`["${s.identifier}" ${t.toFixed(2)}-${(t+r).toFixed(2)}]`}class RGs{constructor(t,r,n,a){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=()=>{this.reachedPlayout(this.currentTime)&&this.hls&&this.hls.trigger(vt.PLAYOUT_LIMIT_REACHED,{})};const i=this.hls=new t(r);this.interstitial=n,this.assetItem=a;const l=()=>{this.hasDetails=!0};i.once(vt.LEVEL_LOADED,l),i.once(vt.AUDIO_TRACK_LOADED,l),i.once(vt.SUBTITLE_TRACK_LOADED,l),i.on(vt.MEDIA_ATTACHING,(o,{media:c})=>{this.removeMediaListeners(),this.mediaAttached=c,this.interstitial.playoutLimit&&(c.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&i.on(vt.BUFFER_APPENDED,()=>{const h=this.bufferedEnd;this.reachedPlayout(h)&&(this._bufferedEosTime=h,i.trigger(vt.BUFFERED_TO_END,void 0))}))})}get appendInPlace(){return this.interstitial.appendInPlace}loadSource(){const t=this.hls;if(t)if(t.url)t.levels.length&&!t.started&&t.startLoad(-1,!0);else{let r=this.assetItem.uri;try{r=tbt(r,t.config.primarySessionId||"").href}catch{}t.loadSource(r)}}bufferedInPlaceToEnd(t){var r;if(!this.appendInPlace)return!1;if((r=this.hls)!=null&&r.bufferedToEnd)return!0;if(!t)return!1;const n=Math.min(this._bufferedEosTime||1/0,this.duration),a=this.timelineOffset,i=mo.bufferInfo(t,a,0);return this.getAssetTime(i.end)>=n-.02}reachedPlayout(t){const n=this.interstitial.playoutLimit;return this.startOffset+t>=n}get destroyed(){var t;return!((t=this.hls)!=null&&t.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var t;return((t=this.hls)==null?void 0:t.media)||null}get bufferedEnd(){const t=this.media||this.mediaAttached;if(!t)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;const r=mo.bufferInfo(t,t.currentTime,.001);return this.getAssetTime(r.end)}get currentTime(){const t=this.media||this.mediaAttached;return t?this.getAssetTime(t.currentTime):this._currentTime||0}get duration(){const t=this.assetItem.duration;if(!t)return 0;const r=this.interstitial.playoutLimit;if(r){const n=r-this.startOffset;if(n>0&&n1/9e4&&this.hls){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=t}}}getAssetTime(t){const r=this.timelineOffset,n=this.duration;return Math.min(Math.max(0,t-r),n)}removeMediaListeners(){const t=this.mediaAttached;t&&(this._currentTime=t.currentTime,this.bufferSnapShot(),t.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){if(this.mediaAttached){var t;(t=this.hls)!=null&&t.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd)}}destroy(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(t){var r;this.loadSource(),(r=this.hls)==null||r.attachMedia(t)}detachMedia(){var t;this.removeMediaListeners(),this.mediaAttached=null,(t=this.hls)==null||t.detachMedia()}resumeBuffering(){var t;(t=this.hls)==null||t.resumeBuffering()}pauseBuffering(){var t;(t=this.hls)==null||t.pauseBuffering()}transferMedia(){var t;return this.bufferSnapShot(),((t=this.hls)==null?void 0:t.transferMedia())||null}resetDetails(){const t=this.hls;if(t&&this.hasDetails){t.stopLoad();const r=n=>delete n.details;t.levels.forEach(r),t.allAudioTracks.forEach(r),t.allSubtitleTracks.forEach(r),this.hasDetails=!1}}on(t,r,n){var a;(a=this.hls)==null||a.on(t,r)}once(t,r,n){var a;(a=this.hls)==null||a.once(t,r)}off(t,r,n){var a;(a=this.hls)==null||a.off(t,r)}toString(){var t;return`HlsAssetPlayer: ${W6(this.assetItem)} ${(t=this.hls)==null?void 0:t.sessionId} ${this.appendInPlace?"append-in-place":""}`}}const QKe=.033;class OGs extends dv{constructor(t,r){super("interstitials-sched",r),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=t}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(t=>t.reset()),this.events=this.items=null}resetErrorsInRange(t,r){return this.events?this.events.reduce((n,a)=>t<=a.startOffset&&r>a.startOffset?(delete a.error,n+1):n,0):0}get duration(){const t=this.items;return t?t[t.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(t){return t&&this.eventMap[t]||null}hasEvent(t){return t in this.eventMap}findItemIndex(t,r){if(t.event)return this.findEventIndex(t.event.identifier);let n=-1;t.nextEvent?n=this.findEventIndex(t.nextEvent.identifier)-1:t.previousEvent&&(n=this.findEventIndex(t.previousEvent.identifier)+1);const a=this.items;if(a)for(a[n]||(r===void 0&&(r=t.start),n=this.findItemIndexAtTime(r));n>=0&&(i=a[n])!=null&&i.event;){var i;n--}return n}findItemIndexAtTime(t,r){const n=this.items;if(n)for(let a=0;ai.start&&t1)for(let i=0;io&&(r!o.includes(d.identifier)):[];l.length&&l.sort((d,h)=>{const m=d.cue.pre,p=d.cue.post,x=h.cue.pre,y=h.cue.post;if(m&&!x)return-1;if(x&&!m||p&&!y)return 1;if(y&&!p)return-1;if(!m&&!x&&!p&&!y){const _=d.startTime,b=h.startTime;if(_!==b)return _-b}return d.dateRange.tagOrder-h.dateRange.tagOrder}),this.events=l,c.forEach(d=>{this.removeEvent(d)}),this.updateSchedule(t,c)}updateSchedule(t,r=[],n=!1){const a=this.events||[];if(a.length||r.length||this.length<2){const i=this.items,l=this.parseSchedule(a,t);(n||r.length||(i==null?void 0:i.length)!==l.length||l.some((c,d)=>Math.abs(c.playout.start-i[d].playout.start)>.005||Math.abs(c.playout.end-i[d].playout.end)>.005))&&(this.items=l,this.onScheduleUpdate(r,i))}}parseDateRanges(t,r,n){const a=[],i=Object.keys(t);for(let l=0;l!c.error&&!(c.cue.once&&c.hasPlayed)),t.length){this.resolveOffsets(t,r);let c=0,d=0;if(t.forEach((h,m)=>{const p=h.cue.pre,x=h.cue.post,y=t[m-1]||null,_=h.appendInPlace,b=x?i:h.startOffset,j=h.duration,k=h.timelineOccupancy===kpe.Range?j:0,T=h.resumptionOffset,E=(y==null?void 0:y.startTime)===b,A=b+h.cumulativeDuration;let D=_?A+j:b+T;if(p||!x&&b<=0){const z=d;d+=k,h.timelineStart=A;const O=l;l+=j,n.push({event:h,start:A,end:D,playout:{start:O,end:l},integrated:{start:z,end:d}})}else if(b<=i){if(!E){const $=b-c;if($>QKe){const ee=c,Z=d;d+=$;const J=l;l+=$;const K={previousEvent:t[m-1]||null,nextEvent:h,start:ee,end:ee+$,playout:{start:J,end:l},integrated:{start:Z,end:d}};n.push(K)}else $>0&&y&&(y.cumulativeDuration+=$,n[n.length-1].end=b)}x&&(D=A),h.timelineStart=A;const z=d;d+=k;const O=l;l+=j,n.push({event:h,start:A,end:D,playout:{start:O,end:l},integrated:{start:z,end:d}})}else return;const R=h.resumeTime;x||R>i?c=i:c=R}),c{const d=o.cue.pre,h=o.cue.post,m=d?0:h?a:o.startTime;this.updateAssetDurations(o),l===m?o.cumulativeDuration=i:(i=0,l=m),!h&&o.snapOptions.in&&(o.resumeAnchor=OA(null,n.fragments,o.startOffset+o.resumptionOffset,0,0)||void 0),o.appendInPlace&&!o.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(o,r)||(o.appendInPlace=!1)),!o.appendInPlace&&c+1kP?(this.log(`"${t.identifier}" resumption ${n} not aligned with estimated timeline end ${a}`),!1):!Object.keys(r).some(l=>{const o=r[l].details,c=o.edge;if(n>=c)return this.log(`"${t.identifier}" resumption ${n} past ${l} playlist end ${c}`),!1;const d=OA(null,o.fragments,n);if(!d)return this.log(`"${t.identifier}" resumption ${n} does not align with any fragments in ${l} playlist (${o.fragStart}-${o.fragmentEnd})`),!0;const h=l==="audio"?.175:0;return Math.abs(d.start-n){const b=p.data,j=b==null?void 0:b.ASSETS;if(!Array.isArray(j)){const k=this.assignAssetListError(t,yr.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),y.url,x,_);this.hls.trigger(vt.ERROR,k);return}t.assetListResponse=b,this.hls.trigger(vt.ASSET_LIST_LOADED,{event:t,assetListResponse:b,networkDetails:_})},onError:(p,x,y,_)=>{const b=this.assignAssetListError(t,yr.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${p.code} ${p.text} (${x.url})`),x.url,_,y);this.hls.trigger(vt.ERROR,b)},onTimeout:(p,x,y)=>{const _=this.assignAssetListError(t,yr.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${x.url})`),x.url,p,y);this.hls.trigger(vt.ERROR,_)}};return o.load(c,h,m),this.hls.trigger(vt.ASSET_LIST_LOADING,{event:t}),o}assignAssetListError(t,r,n,a,i,l){return t.error=n,{type:ci.NETWORK_ERROR,details:r,fatal:!1,interstitial:t,url:a,error:n,networkDetails:l,stats:i}}}function JKe(s){var t;s==null||(t=s.play())==null||t.catch(()=>{})}function O6(s,t){return`[${s}] Advancing timeline position to ${t}`}class BGs extends dv{constructor(t,r){super("interstitials",t.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{const n=this.currentTime;if(n===void 0||this.playbackDisabled||!this.schedule)return;const a=n-this.timelinePos;if(Math.abs(a)<1/7056e5)return;const l=a<=-.01;this.timelinePos===-1&&!this.effectivePlayingItem&&this.checkStart(),this.timelinePos=n,this.bufferedPos=n;const o=this.playingItem;if(!o){this.checkBuffer();return}if(l&&this.schedule.resetErrorsInRange(n,n-a)&&this.updateSchedule(!0),this.checkBuffer(),l&&n=o.end){var c;const x=this.findItemIndex(o);let y=this.schedule.findItemIndexAtTime(n);if(y===-1&&(y=x+(l?-1:1),this.log(`seeked ${l?"back ":""}to position not covered by schedule ${n} (resolving from ${x} to ${y})`)),!this.isInterstitial(o)&&(c=this.media)!=null&&c.paused&&(this.shouldPlay=!1),!l&&y>x){const _=this.schedule.findJumpRestrictedIndex(x+1,y);if(_>x){this.setSchedulePosition(_);return}}this.setSchedulePosition(y);return}const d=this.playingAsset;if(!d){if(this.playingLastItem&&this.isInterstitial(o)){const x=o.event.assetList[0];x&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(n,x))}return}const h=d.timelineStart,m=d.duration||0;if(l&&n=h+m){var p;(p=o.event)!=null&&p.appendInPlace&&(this.clearAssetPlayers(o.event,o),this.flushFrontBuffer(n)),this.setScheduleToAssetAtTime(n,d)}},this.onTimeupdate=()=>{const n=this.currentTime;if(n===void 0||this.playbackDisabled)return;if(this.timelinePos===-1&&!this.effectivePlayingItem&&this.checkStart(),n>this.timelinePos)this.timelinePos=n,n>this.bufferedPos&&this.checkBuffer();else return;const a=this.playingItem;if(!a||this.playingLastItem)return;if(n>=a.end){this.timelinePos=a.end;const o=this.findItemIndex(a);this.setSchedulePosition(o+1)}const i=this.playingAsset;if(!i)return;const l=i.timelineStart+(i.duration||0);n>=l&&this.setScheduleToAssetAtTime(n,i)},this.onScheduleUpdate=(n,a)=>{const i=this.schedule;if(!i)return;const l=this.playingItem,o=i.events||[],c=i.items||[],d=i.durations,h=n.map(_=>_.identifier),m=!!(o.length||h.length);(m||a)&&this.log(`INTERSTITIALS_UPDATED (${o.length}): ${o} Schedule: ${c.map(_=>Gv(_))} pos: ${this.timelinePos}`),h.length&&this.log(`Removed events ${h}`);let p=null,x=null;l&&(p=this.updateItem(l,this.timelinePos),this.itemsMatch(l,p)?this.playingItem=p:this.waitingItem=this.endedItem=null),this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);const y=this.bufferingItem;if(y&&(x=this.updateItem(y,this.bufferedPos),this.itemsMatch(y,x)?this.bufferingItem=x:y.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(y.event,null))),n.forEach(_=>{_.assetList.forEach(b=>{this.clearAssetPlayer(b.identifier,null)})}),this.playerQueue.forEach(_=>{if(_.interstitial.appendInPlace){const b=_.assetItem.timelineStart,j=_.timelineOffset-b;if(j)try{_.timelineOffset=b}catch(k){Math.abs(j)>kP&&this.warn(`${k} ("${_.assetId}" ${_.timelineOffset}->${b})`)}}}),m||a){if(this.hls.trigger(vt.INTERSTITIALS_UPDATED,{events:o.slice(0),schedule:c.slice(0),durations:d,removedIds:h}),this.isInterstitial(l)&&h.includes(l.event.identifier)){this.warn(`Interstitial "${l.event.identifier}" removed while playing`),this.primaryFallback(l.event);return}l&&this.trimInPlace(p,l),y&&x!==p&&this.trimInPlace(x,y),this.checkBuffer()}},this.hls=t,this.HlsPlayerClass=r,this.assetListLoader=new FGs(t),this.schedule=new OGs(this.onScheduleUpdate,t.logger),this.registerListeners()}registerListeners(){const t=this.hls;t&&(t.on(vt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(vt.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(vt.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(vt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(vt.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(vt.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(vt.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),t.on(vt.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(vt.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),t.on(vt.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),t.on(vt.ASSET_LIST_LOADED,this.onAssetListLoaded,this),t.on(vt.BUFFER_APPENDED,this.onBufferAppended,this),t.on(vt.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(vt.BUFFERED_TO_END,this.onBufferedToEnd,this),t.on(vt.MEDIA_ENDED,this.onMediaEnded,this),t.on(vt.ERROR,this.onError,this),t.on(vt.DESTROYING,this.onDestroying,this))}unregisterListeners(){const t=this.hls;t&&(t.off(vt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(vt.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(vt.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(vt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(vt.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(vt.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(vt.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),t.off(vt.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(vt.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),t.off(vt.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),t.off(vt.ASSET_LIST_LOADED,this.onAssetListLoaded,this),t.off(vt.BUFFER_CODECS,this.onBufferCodecs,this),t.off(vt.BUFFER_APPENDED,this.onBufferAppended,this),t.off(vt.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(vt.BUFFERED_TO_END,this.onBufferedToEnd,this),t.off(vt.MEDIA_ENDED,this.onMediaEnded,this),t.off(vt.ERROR,this.onError,this),t.off(vt.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var t;(t=this.getBufferingPlayer())==null||t.resumeBuffering()}pauseBuffering(){var t;(t=this.getBufferingPlayer())==null||t.pauseBuffering()}destroy(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.schedule=this.manager=null,this.hls=this.HlsPlayerClass=this.log=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){const t=this.primaryMedia||this.media;t&&this.removeMediaListeners(t)}removeMediaListeners(t){nx(t,"play",this.onPlay),nx(t,"pause",this.onPause),nx(t,"seeking",this.onSeeking),nx(t,"timeupdate",this.onTimeupdate)}onMediaAttaching(t,r){const n=this.media=r.media;vg(n,"seeking",this.onSeeking),vg(n,"timeupdate",this.onTimeupdate),vg(n,"play",this.onPlay),vg(n,"pause",this.onPause)}onMediaAttached(t,r){const n=this.effectivePlayingItem,a=this.detachedData;if(this.detachedData=null,n===null)this.checkStart();else if(!a){this.clearScheduleState();const i=this.findItemIndex(n);this.setSchedulePosition(i)}}clearScheduleState(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(t,r){const n=!!r.transferMedia,a=this.media;if(this.media=null,!n&&(a&&this.removeMediaListeners(a),this.detachedData)){const i=this.getBufferingPlayer();i&&(this.log(`Removing schedule state for detachedData and ${i}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,i.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;const t=this,r=()=>t.bufferingItem||t.waitingItem,n=m=>m&&t.getAssetPlayer(m.identifier),a=(m,p,x,y,_)=>{if(m){let b=m[p].start;const j=m.event;if(j){if(p==="playout"||j.timelineOccupancy!==kpe.Point){const k=n(x);(k==null?void 0:k.interstitial)===j&&(b+=k.assetItem.startOffset+k[_])}}else{const k=y==="bufferedPos"?l():t[y];b+=k-m.start}return b}return 0},i=(m,p)=>{var x;if(m!==0&&p!=="primary"&&(x=t.schedule)!=null&&x.length){var y;const _=t.schedule.findItemIndexAtTime(m),b=(y=t.schedule.items)==null?void 0:y[_];if(b){const j=b[p].start-b.start;return m+j}}return m},l=()=>{const m=t.bufferedPos;return m===Number.MAX_VALUE?o("primary"):Math.max(m,0)},o=m=>{var p,x;return(p=t.primaryDetails)!=null&&p.live?t.primaryDetails.edge:((x=t.schedule)==null?void 0:x.durations[m])||0},c=(m,p)=>{var x,y;const _=t.effectivePlayingItem;if(_!=null&&(x=_.event)!=null&&x.restrictions.skip||!t.schedule)return;t.log(`seek to ${m} "${p}"`);const b=t.effectivePlayingItem,j=t.schedule.findItemIndexAtTime(m,p),k=(y=t.schedule.items)==null?void 0:y[j],T=t.getBufferingPlayer(),E=T==null?void 0:T.interstitial,A=E==null?void 0:E.appendInPlace,D=b&&t.itemsMatch(b,k);if(b&&(A||D)){const R=n(t.playingAsset),z=(R==null?void 0:R.media)||t.primaryMedia;if(z){const O=p==="primary"?z.currentTime:a(b,p,t.playingAsset,"timelinePos","currentTime"),$=m-O,ee=(A?O:z.currentTime)+$;if(ee>=0&&(!R||A||ee<=R.duration)){z.currentTime=ee;return}}}if(k){let R=m;if(p!=="primary"){const O=k[p].start,$=m-O;R=k.start+$}const z=!t.isInterstitial(k);if((!t.isInterstitial(b)||b.event.appendInPlace)&&(z||k.event.appendInPlace)){const O=t.media||(A?T==null?void 0:T.media:null);O&&(O.currentTime=R)}else if(b){const O=t.findItemIndex(b);if(j>O){const ee=t.schedule.findJumpRestrictedIndex(O+1,j);if(ee>O){t.setSchedulePosition(ee);return}}let $=0;if(z)t.timelinePos=R,t.checkBuffer();else{const ee=k.event.assetList,Z=m-(k[p]||k).start;for(let J=ee.length;J--;){const K=ee[J];if(K.duration&&Z>=K.startOffset&&Z{const m=t.effectivePlayingItem;if(t.isInterstitial(m))return m;const p=r();return t.isInterstitial(p)?p:null},h={get bufferedEnd(){const m=r(),p=t.bufferingItem;if(p&&p===m){var x;return a(p,"playout",t.bufferingAsset,"bufferedPos","bufferedEnd")-p.playout.start||((x=t.bufferingAsset)==null?void 0:x.startOffset)||0}return 0},get currentTime(){const m=d(),p=t.effectivePlayingItem;return p&&p===m?a(p,"playout",t.effectivePlayingAsset,"timelinePos","currentTime")-p.playout.start:0},set currentTime(m){const p=d(),x=t.effectivePlayingItem;x&&x===p&&c(m+x.playout.start,"playout")},get duration(){const m=d();return m?m.playout.end-m.playout.start:0},get assetPlayers(){var m;const p=(m=d())==null?void 0:m.event.assetList;return p?p.map(x=>t.getAssetPlayer(x.identifier)):[]},get playingIndex(){var m;const p=(m=d())==null?void 0:m.event;return p&&t.effectivePlayingAsset?p.findAssetIndex(t.effectivePlayingAsset):-1},get scheduleItem(){return d()}};return this.manager={get events(){var m;return((m=t.schedule)==null||(m=m.events)==null?void 0:m.slice(0))||[]},get schedule(){var m;return((m=t.schedule)==null||(m=m.items)==null?void 0:m.slice(0))||[]},get interstitialPlayer(){return d()?h:null},get playerQueue(){return t.playerQueue.slice(0)},get bufferingAsset(){return t.bufferingAsset},get bufferingItem(){return r()},get bufferingIndex(){const m=r();return t.findItemIndex(m)},get playingAsset(){return t.effectivePlayingAsset},get playingItem(){return t.effectivePlayingItem},get playingIndex(){const m=t.effectivePlayingItem;return t.findItemIndex(m)},primary:{get bufferedEnd(){return l()},get currentTime(){const m=t.timelinePos;return m>0?m:0},set currentTime(m){c(m,"primary")},get duration(){return o("primary")},get seekableStart(){var m;return((m=t.primaryDetails)==null?void 0:m.fragmentStart)||0}},integrated:{get bufferedEnd(){return a(r(),"integrated",t.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return a(t.effectivePlayingItem,"integrated",t.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(m){c(m,"integrated")},get duration(){return o("integrated")},get seekableStart(){var m;return i(((m=t.primaryDetails)==null?void 0:m.fragmentStart)||0,"integrated")}},skip:()=>{const m=t.effectivePlayingItem,p=m==null?void 0:m.event;if(p&&!p.restrictions.skip){const x=t.findItemIndex(m);if(p.appendInPlace){const y=m.playout.start+m.event.duration;c(y+.001,"playout")}else t.advanceAfterAssetEnded(p,x,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var t;const r=this.playingItem,n=(t=this.schedule)==null?void 0:t.items;return!this.playbackStarted||!r||!n?!1:this.findItemIndex(r)===n.length-1}get playbackStarted(){return this.effectivePlayingItem!==null}get currentTime(){var t,r;if(this.mediaSelection===null)return;const n=this.waitingItem||this.playingItem;if(this.isInterstitial(n)&&!n.event.appendInPlace)return;let a=this.media;!a&&(t=this.bufferingItem)!=null&&(t=t.event)!=null&&t.appendInPlace&&(a=this.primaryMedia);const i=(r=a)==null?void 0:r.currentTime;if(!(i===void 0||!ka(i)))return i}get primaryMedia(){var t;return this.media||((t=this.detachedData)==null?void 0:t.media)||null}isInterstitial(t){return!!(t!=null&&t.event)}retreiveMediaSource(t,r){const n=this.getAssetPlayer(t);n&&this.transferMediaFromPlayer(n,r)}transferMediaFromPlayer(t,r){const n=t.interstitial.appendInPlace,a=t.media;if(n&&a===this.primaryMedia){if(this.bufferingAsset=null,(!r||this.isInterstitial(r)&&!r.event.appendInPlace)&&r&&a){this.detachedData={media:a};return}const i=t.transferMedia();this.log(`transfer MediaSource from ${t} ${Uc(i)}`),this.detachedData=i}else r&&a&&(this.shouldPlay||(this.shouldPlay=!a.paused))}transferMediaTo(t,r){var n,a;if(t.media===r)return;let i=null;const l=this.hls,o=t!==l,c=o&&t.interstitial.appendInPlace,d=(n=this.detachedData)==null?void 0:n.mediaSource;let h;if(l.media)c&&(i=l.transferMedia(),this.detachedData=i),h="Primary";else if(d){const y=this.getBufferingPlayer();y?(i=y.transferMedia(),h=`${y}`):h="detached MediaSource"}else h="detached media";if(!i){if(d)i=this.detachedData,this.log(`using detachedData: MediaSource ${Uc(i)}`);else if(!this.detachedData||l.media===r){const y=this.playerQueue;y.length>1&&y.forEach(_=>{if(o&&_.interstitial.appendInPlace!==c){const b=_.interstitial;this.clearInterstitial(_.interstitial,null),b.appendInPlace=!1,b.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${b}`)}}),this.hls.detachMedia(),this.detachedData={media:r}}}const m=i&&"mediaSource"in i&&((a=i.mediaSource)==null?void 0:a.readyState)!=="closed",p=m&&i?i:r;this.log(`${m?"transfering MediaSource":"attaching media"} to ${o?t:"Primary"} from ${h} (media.currentTime: ${r.currentTime})`);const x=this.schedule;if(p===i&&x){const y=o&&t.assetId===x.assetIdAtEnd;p.overrides={duration:x.duration,endOfStream:!o||y,cueRemoval:!o}}t.attachMedia(p)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const t=this.schedule,r=t==null?void 0:t.events;if(!r||this.playbackDisabled||!this.media)return;this.bufferedPos===-1&&(this.bufferedPos=0);const n=this.timelinePos,a=this.effectivePlayingItem;if(n===-1){const i=this.hls.startPosition;if(this.timelinePos=i,r.length===0)this.setSchedulePosition(0);else if(r[0].cue.pre){this.log(O6("checkStart (preroll)",i));const l=t.findEventIndex(r[0].identifier);this.setSchedulePosition(l)}else if(i>=0||!this.primaryLive){this.log(O6("checkStart",i));const l=this.timelinePos=i>0?i:0,o=t.findItemIndexAtTime(l);this.setSchedulePosition(o)}else this.hls.liveSyncPosition===0?this.setSchedulePosition(0):this.log("[checkStart] waiting for live start")}else if(a&&!this.playingItem){this.log(O6("checkStart (playing item)",a.start));const i=t.findItemIndex(a);this.setSchedulePosition(i)}}advanceAssetBuffering(t,r){const n=t.event,a=n.findAssetIndex(r),i=Ywe(n,a);if(!n.isAssetPastPlayoutLimit(i))this.bufferedToEvent(t,i);else if(this.schedule){var l;const o=(l=this.schedule.items)==null?void 0:l[this.findItemIndex(t)+1];o&&this.bufferedToItem(o)}}advanceAfterAssetEnded(t,r,n){const a=Ywe(t,n);if(t.isAssetPastPlayoutLimit(a)){if(this.schedule){const i=this.schedule.items;if(i){const l=r+1,o=i.length;if(l>=o){this.setSchedulePosition(-1);return}const c=t.resumeTime;this.timelinePos=0?a[t]:null;this.log(`setSchedulePosition ${t}, ${r} (${i&&Gv(i)}) pos: ${this.timelinePos}`);const l=this.waitingItem||this.playingItem,o=this.playingLastItem;if(this.isInterstitial(l)){const h=l.event,m=this.playingAsset,p=m==null?void 0:m.identifier,x=p?this.getAssetPlayer(p):null;if(x&&p&&(!this.eventItemsMatch(l,i)||r!==void 0&&p!==h.assetList[r].identifier)){var c;const y=h.findAssetIndex(m);if(this.log(`INTERSTITIAL_ASSET_ENDED ${y+1}/${h.assetList.length} ${W6(m)}`),this.endedAsset=m,this.playingAsset=null,this.hls.trigger(vt.INTERSTITIAL_ASSET_ENDED,{asset:m,assetListIndex:y,event:h,schedule:a.slice(0),scheduleIndex:t,player:x}),l!==this.playingItem){this.itemsMatch(l,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(h,this.findItemIndex(this.playingItem),y);return}this.retreiveMediaSource(p,i),x.media&&!((c=this.detachedData)!=null&&c.mediaSource)&&x.detachMedia()}if(!this.eventItemsMatch(l,i)&&(this.endedItem=l,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${h} ${Gv(l)}`),h.hasPlayed=!0,this.hls.trigger(vt.INTERSTITIAL_ENDED,{event:h,schedule:a.slice(0),scheduleIndex:t}),h.cue.once)){var d;this.updateSchedule();const y=(d=this.schedule)==null?void 0:d.items;if(i&&y){const _=this.findItemIndex(i);this.advanceSchedule(_,y,r,l,o)}return}}this.advanceSchedule(t,a,r,l,o)}advanceSchedule(t,r,n,a,i){const l=this.schedule;if(!l)return;const o=r[t]||null,c=this.primaryMedia,d=this.playerQueue;if(d.length&&d.forEach(h=>{const m=h.interstitial,p=l.findEventIndex(m.identifier);(pt+1)&&this.clearInterstitial(m,o)}),this.isInterstitial(o)){this.timelinePos=Math.min(Math.max(this.timelinePos,o.start),o.end);const h=o.event;if(n===void 0){n=l.findAssetIndex(h,this.timelinePos);const y=Ywe(h,n-1);if(h.isAssetPastPlayoutLimit(y)||h.appendInPlace&&this.timelinePos===o.end){this.advanceAfterAssetEnded(h,t,n);return}n=y}const m=this.waitingItem;this.assetsBuffered(o,c)||this.setBufferingItem(o);let p=this.preloadAssets(h,n);if(this.eventItemsMatch(o,m||a)||(this.waitingItem=o,this.log(`INTERSTITIAL_STARTED ${Gv(o)} ${h.appendInPlace?"append in place":""}`),this.hls.trigger(vt.INTERSTITIAL_STARTED,{event:h,schedule:r.slice(0),scheduleIndex:t})),!h.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${h}`);return}if(h.assetListLoader&&(h.assetListLoader.destroy(),h.assetListLoader=void 0),!c){this.log(`Waiting for attachMedia to start Interstitial ${h}`);return}this.waitingItem=this.endedItem=null,this.playingItem=o;const x=h.assetList[n];if(!x){this.advanceAfterAssetEnded(h,t,n||0);return}if(p||(p=this.getAssetPlayer(x.identifier)),p===null||p.destroyed){const y=h.assetList.length;this.warn(`asset ${n+1}/${y} player destroyed ${h}`),p=this.createAssetPlayer(h,x,n),p.loadSource()}if(!this.eventItemsMatch(o,this.bufferingItem)&&h.appendInPlace&&this.isAssetBuffered(x))return;this.startAssetPlayer(p,n,r,t,c),this.shouldPlay&&JKe(p.media)}else o?(this.resumePrimary(o,t,a),this.shouldPlay&&JKe(this.hls.media)):i&&this.isInterstitial(a)&&(this.endedItem=null,this.playingItem=a,a.event.appendInPlace||this.attachPrimary(l.durations.primary,null))}get playbackDisabled(){return this.hls.config.enableInterstitialPlayback===!1}get primaryDetails(){var t;return(t=this.mediaSelection)==null?void 0:t.main.details}get primaryLive(){var t;return!!((t=this.primaryDetails)!=null&&t.live)}resumePrimary(t,r,n){var a,i;if(this.playingItem=t,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(t),this.log(`resuming ${Gv(t)}`),!((a=this.detachedData)!=null&&a.mediaSource)){let o=this.timelinePos;(o=t.end)&&(o=this.getPrimaryResumption(t,r),this.log(O6("resumePrimary",o)),this.timelinePos=o),this.attachPrimary(o,t)}if(!n)return;const l=(i=this.schedule)==null?void 0:i.items;l&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${Gv(t)}`),this.hls.trigger(vt.INTERSTITIALS_PRIMARY_RESUMED,{schedule:l.slice(0),scheduleIndex:r}),this.checkBuffer())}getPrimaryResumption(t,r){const n=t.start;if(this.primaryLive){const a=this.primaryDetails;if(r===0)return this.hls.startPosition;if(a&&(na.edge))return this.hls.liveSyncPosition||-1}return n}isAssetBuffered(t){const r=this.getAssetPlayer(t.identifier);return r!=null&&r.hls?r.hls.bufferedToEnd:mo.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=t.timelineStart+(t.duration||0)}attachPrimary(t,r,n){r?this.setBufferingItem(r):this.bufferingItem=this.playingItem,this.bufferingAsset=null;const a=this.primaryMedia;if(!a)return;const i=this.hls;i.media?this.checkBuffer():(this.transferMediaTo(i,a),n&&this.startLoadingPrimaryAt(t,n)),n||(this.log(O6("attachPrimary",t)),this.timelinePos=t,this.startLoadingPrimaryAt(t,n))}startLoadingPrimaryAt(t,r){var n;const a=this.hls;!a.loadingEnabled||!a.media||Math.abs((((n=a.mainForwardBufferInfo)==null?void 0:n.start)||a.media.currentTime)-t)>.5?a.startLoad(t,r):a.bufferingEnabled||a.resumeBuffering()}onManifestLoading(){var t;this.stopLoad(),(t=this.schedule)==null||t.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(vt.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(vt.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(t,r){if(r.level===-1||!this.schedule)return;const n=this.hls.levels[r.level];if(!n.details)return;const a=hc(hc({},this.mediaSelection||this.altSelection),{},{main:n});this.mediaSelection=a,this.schedule.parseInterstitialDateRanges(a,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}onAudioTrackUpdated(t,r){const n=this.hls.audioTracks[r.id],a=this.mediaSelection;if(!a){this.altSelection=hc(hc({},this.altSelection),{},{audio:n});return}const i=hc(hc({},a),{},{audio:n});this.mediaSelection=i}onSubtitleTrackUpdated(t,r){const n=this.hls.subtitleTracks[r.id],a=this.mediaSelection;if(!a){this.altSelection=hc(hc({},this.altSelection),{},{subtitles:n});return}const i=hc(hc({},a),{},{subtitles:n});this.mediaSelection=i}onAudioTrackSwitching(t,r){const n=lKe(r);this.playerQueue.forEach(({hls:a})=>a&&(a.setAudioOption(r)||a.setAudioOption(n)))}onSubtitleTrackSwitch(t,r){const n=lKe(r);this.playerQueue.forEach(({hls:a})=>a&&(a.setSubtitleOption(r)||r.id!==-1&&a.setSubtitleOption(n)))}onBufferCodecs(t,r){const n=r.tracks;n&&(this.requiredTracks=n)}onBufferAppended(t,r){this.checkBuffer()}onBufferFlushed(t,r){const n=this.playingItem;if(n&&!this.itemsMatch(n,this.bufferingItem)&&!this.isInterstitial(n)){const a=this.timelinePos;this.bufferedPos=a,this.checkBuffer()}}onBufferedToEnd(t){if(!this.schedule)return;const r=this.schedule.events;if(this.bufferedPos.25){t.event.assetList.forEach((i,l)=>{t.event.isAssetPastPlayoutLimit(l)&&this.clearAssetPlayer(i.identifier,null)});const n=t.end+.25,a=mo.bufferInfo(this.primaryMedia,n,0);(a.end>n||(a.nextStart||0)>n)&&(this.log(`trim buffered interstitial ${Gv(t)} (was ${Gv(r)})`),this.attachPrimary(n,null,!0),this.flushFrontBuffer(n))}}itemsMatch(t,r){return!!r&&(t===r||t.event&&r.event&&this.eventItemsMatch(t,r)||!t.event&&!r.event&&this.findItemIndex(t)===this.findItemIndex(r))}eventItemsMatch(t,r){var n;return!!r&&(t===r||t.event.identifier===((n=r.event)==null?void 0:n.identifier))}findItemIndex(t,r){return t&&this.schedule?this.schedule.findItemIndex(t,r):-1}updateSchedule(t=!1){var r;const n=this.mediaSelection;n&&((r=this.schedule)==null||r.updateSchedule(n,[],t))}checkBuffer(t){var r;const n=(r=this.schedule)==null?void 0:r.items;if(!n)return;const a=mo.bufferInfo(this.primaryMedia,this.timelinePos,0);t&&(this.bufferedPos=this.timelinePos),t||(t=a.len<1),this.updateBufferedPos(a.end,n,t)}updateBufferedPos(t,r,n){const a=this.schedule,i=this.bufferingItem;if(this.bufferedPos>t||!a)return;if(r.length===1&&this.itemsMatch(r[0],i)){this.bufferedPos=t;return}const l=this.playingItem,o=this.findItemIndex(l);let c=a.findItemIndexAtTime(t);if(this.bufferedPos=i.end||(d=p.event)!=null&&d.appendInPlace&&t+.01>=p.start)&&(c=m),this.isInterstitial(i)){const x=i.event;if(m-o>1&&x.appendInPlace===!1||x.assetList.length===0&&x.assetListLoader)return}if(this.bufferedPos=t,c>h&&c>o)this.bufferedToItem(p);else{const x=this.primaryDetails;this.primaryLive&&x&&t>x.edge-x.targetduration&&p.start{const i=this.getAssetPlayer(a.identifier);return!(i!=null&&i.bufferedInPlaceToEnd(r))})}setBufferingItem(t){const r=this.bufferingItem,n=this.schedule;if(!this.itemsMatch(t,r)&&n){const{items:a,events:i}=n;if(!a||!i)return r;const l=this.isInterstitial(t),o=this.getBufferingPlayer();this.bufferingItem=t,this.bufferedPos=Math.max(t.start,Math.min(t.end,this.timelinePos));const c=o?o.remaining:r?r.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${Gv(t)}`+(r?` (${c.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(l){const d=n.findAssetIndex(t.event,this.bufferedPos);t.event.assetList.forEach((h,m)=>{const p=this.getAssetPlayer(h.identifier);p&&(m===d&&p.loadSource(),p.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(d=>d.pauseBuffering());this.hls.trigger(vt.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:i.slice(0),schedule:a.slice(0),bufferingIndex:this.findItemIndex(t),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==t&&(this.bufferingItem=t);return r}bufferedToItem(t,r=0){const n=this.setBufferingItem(t);if(!this.playbackDisabled){if(this.isInterstitial(t))this.bufferedToEvent(t,r);else if(n!==null){this.bufferingAsset=null;const a=this.detachedData;a?a.mediaSource?this.attachPrimary(t.start,t,!0):this.preloadPrimary(t):this.preloadPrimary(t)}}}preloadPrimary(t){const r=this.findItemIndex(t),n=this.getPrimaryResumption(t,r);this.startLoadingPrimaryAt(n)}bufferedToEvent(t,r){const n=t.event,a=n.assetList.length===0&&!n.assetListLoader,i=n.cue.once;if(a||!i){const l=this.preloadAssets(n,r);if(l!=null&&l.interstitial.appendInPlace){const o=this.primaryMedia;o&&this.bufferAssetPlayer(l,o)}}}preloadAssets(t,r){const n=t.assetUrl,a=t.assetList.length,i=a===0&&!t.assetListLoader,l=t.cue.once;if(i){const c=t.timelineStart;if(t.appendInPlace){var o;const p=this.playingItem;!this.isInterstitial(p)&&(p==null||(o=p.nextEvent)==null?void 0:o.identifier)===t.identifier&&this.flushFrontBuffer(c+.25)}let d,h=0;if(!this.playingItem&&this.primaryLive&&(h=this.hls.startPosition,h===-1&&(h=this.hls.liveSyncPosition||0)),h&&!(t.cue.pre||t.cue.post)){const p=h-c;p>0&&(d=Math.round(p*1e3)/1e3)}if(this.log(`Load interstitial asset ${r+1}/${n?1:a} ${t}${d?` live-start: ${h} start-offset: ${d}`:""}`),n)return this.createAsset(t,0,0,c,t.duration,n);const m=this.assetListLoader.loadAssetList(t,d);m&&(t.assetListLoader=m)}else if(!l&&a){for(let d=r;d{this.hls.trigger(vt.BUFFER_FLUSHING,{startOffset:t,endOffset:1/0,type:a})})}getAssetPlayerQueueIndex(t){const r=this.playerQueue;for(let n=0;n1){const A=r.duration;A&&E{if(E.live){var A;const z=new Error(`Interstitials MUST be VOD assets ${t}`),O={fatal:!0,type:ci.OTHER_ERROR,details:yr.INTERSTITIAL_ASSET_ITEM_ERROR,error:z},$=((A=this.schedule)==null?void 0:A.findEventIndex(t.identifier))||-1;this.handleAssetItemError(O,t,$,n,z.message);return}const D=E.edge-E.fragmentStart,R=r.duration;(_||R===null||D>R)&&(_=!1,this.log(`Interstitial asset "${m}" duration change ${R} > ${D}`),r.duration=D,this.updateSchedule())};y.on(vt.LEVEL_UPDATED,(E,{details:A})=>b(A)),y.on(vt.LEVEL_PTS_UPDATED,(E,{details:A})=>b(A)),y.on(vt.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const j=(E,A)=>{const D=this.getAssetPlayer(m);if(D&&A.tracks){D.off(vt.BUFFER_CODECS,j),D.tracks=A.tracks;const R=this.primaryMedia;this.bufferingAsset===D.assetItem&&R&&!D.media&&this.bufferAssetPlayer(D,R)}};y.on(vt.BUFFER_CODECS,j);const k=()=>{var E;const A=this.getAssetPlayer(m);if(this.log(`buffered to end of asset ${A}`),!A||!this.schedule)return;const D=this.schedule.findEventIndex(t.identifier),R=(E=this.schedule.items)==null?void 0:E[D];this.isInterstitial(R)&&this.advanceAssetBuffering(R,r)};y.on(vt.BUFFERED_TO_END,k);const T=E=>()=>{if(!this.getAssetPlayer(m)||!this.schedule)return;this.shouldPlay=!0;const D=this.schedule.findEventIndex(t.identifier);this.advanceAfterAssetEnded(t,D,E)};return y.once(vt.MEDIA_ENDED,T(n)),y.once(vt.PLAYOUT_LIMIT_REACHED,T(1/0)),y.on(vt.ERROR,(E,A)=>{if(!this.schedule)return;const D=this.getAssetPlayer(m);if(A.details===yr.BUFFER_STALLED_ERROR){if(D!=null&&D.appendInPlace){this.handleInPlaceStall(t);return}this.onTimeupdate(),this.checkBuffer(!0);return}this.handleAssetItemError(A,t,this.schedule.findEventIndex(t.identifier),n,`Asset player error ${A.error} ${t}`)}),y.on(vt.DESTROYING,()=>{if(!this.getAssetPlayer(m)||!this.schedule)return;const A=new Error(`Asset player destroyed unexpectedly ${m}`),D={fatal:!0,type:ci.OTHER_ERROR,details:yr.INTERSTITIAL_ASSET_ITEM_ERROR,error:A};this.handleAssetItemError(D,t,this.schedule.findEventIndex(t.identifier),n,A.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${W6(r)}`),this.hls.trigger(vt.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:r,assetListIndex:n,event:t,player:y}),y}clearInterstitial(t,r){this.clearAssetPlayers(t,r),t.reset()}clearAssetPlayers(t,r){t.assetList.forEach(n=>{this.clearAssetPlayer(n.identifier,r)})}resetAssetPlayer(t){const r=this.getAssetPlayerQueueIndex(t);if(r!==-1){this.log(`reset asset player "${t}" after error`);const n=this.playerQueue[r];this.transferMediaFromPlayer(n,null),n.resetDetails()}}clearAssetPlayer(t,r){const n=this.getAssetPlayerQueueIndex(t);if(n!==-1){const a=this.playerQueue[n];this.log(`clear ${a} toSegment: ${r&&Gv(r)}`),this.transferMediaFromPlayer(a,r),this.playerQueue.splice(n,1),a.destroy()}}emptyPlayerQueue(){let t;for(;t=this.playerQueue.pop();)t.destroy();this.playerQueue=[]}startAssetPlayer(t,r,n,a,i){const{interstitial:l,assetItem:o,assetId:c}=t,d=l.assetList.length,h=this.playingAsset;this.endedAsset=null,this.playingAsset=o,(!h||h.identifier!==c)&&(h&&(this.clearAssetPlayer(h.identifier,n[a]),delete h.error),this.log(`INTERSTITIAL_ASSET_STARTED ${r+1}/${d} ${W6(o)}`),this.hls.trigger(vt.INTERSTITIAL_ASSET_STARTED,{asset:o,assetListIndex:r,event:l,schedule:n.slice(0),scheduleIndex:a,player:t})),this.bufferAssetPlayer(t,i)}bufferAssetPlayer(t,r){var n,a;if(!this.schedule)return;const{interstitial:i,assetItem:l}=t,o=this.schedule.findEventIndex(i.identifier),c=(n=this.schedule.items)==null?void 0:n[o];if(!c)return;t.loadSource(),this.setBufferingItem(c),this.bufferingAsset=l;const d=this.getBufferingPlayer();if(d===t)return;const h=i.appendInPlace;if(h&&(d==null?void 0:d.interstitial.appendInPlace)===!1)return;const m=(d==null?void 0:d.tracks)||((a=this.detachedData)==null?void 0:a.tracks)||this.requiredTracks;if(h&&l!==this.playingAsset){if(!t.tracks){this.log(`Waiting for track info before buffering ${t}`);return}if(m&&!Ovt(m,t.tracks)){const p=new Error(`Asset ${W6(l)} SourceBuffer tracks ('${Object.keys(t.tracks)}') are not compatible with primary content tracks ('${Object.keys(m)}')`),x={fatal:!0,type:ci.OTHER_ERROR,details:yr.INTERSTITIAL_ASSET_ITEM_ERROR,error:p},y=i.findAssetIndex(l);this.handleAssetItemError(x,i,o,y,p.message);return}}this.transferMediaTo(t,r)}handleInPlaceStall(t){const r=this.schedule,n=this.primaryMedia;if(!r||!n)return;const a=n.currentTime,i=r.findAssetIndex(t,a),l=t.assetList[i];if(l){const o=this.getAssetPlayer(l.identifier);if(o){const c=o.currentTime||a-l.timelineStart,d=o.duration-c;if(this.warn(`Stalled at ${c} of ${c+d} in ${o} ${t} (media.currentTime: ${a})`),c&&(d/n.playbackRate<.5||o.bufferedInPlaceToEnd(n))&&o.hls){const h=r.findEventIndex(t.identifier);this.advanceAfterAssetEnded(t,h,i)}}}}advanceInPlace(t){const r=this.primaryMedia;r&&r.currentTime!_.error))r.error=y;else for(let _=a;_{const j=parseFloat(_.DURATION);this.createAsset(i,b,h,c+h,j,_.URI),h+=j}),i.duration=h,this.log(`Loaded asset-list with duration: ${h} (was: ${d}) ${i}`);const m=this.waitingItem,p=(m==null?void 0:m.event.identifier)===l;this.updateSchedule();const x=(a=this.bufferingItem)==null?void 0:a.event;if(p){var y;const _=this.schedule.findEventIndex(l),b=(y=this.schedule.items)==null?void 0:y[_];if(b){if(!this.playingItem&&this.timelinePos>b.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==_){i.error=new Error(`Interstitial ${o.length?"no longer within playback range":"asset-list is empty"} ${this.timelinePos} ${i}`),this.log(i.error.message),this.updateSchedule(!0),this.primaryFallback(i);return}this.setBufferingItem(b)}this.setSchedulePosition(_)}else if((x==null?void 0:x.identifier)===l){const _=i.assetList[0];if(_){const b=this.getAssetPlayer(_.identifier);if(x.appendInPlace){const j=this.primaryMedia;b&&j&&this.bufferAssetPlayer(b,j)}else b&&b.loadSource()}}}onError(t,r){if(this.schedule)switch(r.details){case yr.ASSET_LIST_PARSING_ERROR:case yr.ASSET_LIST_LOAD_ERROR:case yr.ASSET_LIST_LOAD_TIMEOUT:{const n=r.interstitial;n&&(this.updateSchedule(!0),this.primaryFallback(n));break}case yr.BUFFER_STALLED_ERROR:{const n=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(n)&&n.event.appendInPlace){this.handleInPlaceStall(n.event);return}this.log(`Primary player stall @${this.timelinePos} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}}const eYe=500;class zGs extends L6e{constructor(t,r,n){super(t,r,n,"subtitle-stream-controller",Ba.SUBTITLE),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}registerListeners(){super.registerListeners();const{hls:t}=this;t.on(vt.LEVEL_LOADED,this.onLevelLoaded,this),t.on(vt.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(vt.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(vt.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(vt.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.on(vt.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:t}=this;t.off(vt.LEVEL_LOADED,this.onLevelLoaded,this),t.off(vt.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(vt.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(vt.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(vt.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.off(vt.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(t,r){this.stopLoad(),this.state=Qr.IDLE,this.setInterval(eYe),this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=r?-1:t,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(t,r){this.tracksBuffered=[],super.onMediaDetaching(t,r)}onLevelLoaded(t,r){this.mainDetails=r.details}onSubtitleFragProcessed(t,r){const{frag:n,success:a}=r;if(this.fragContextChanged(n)||(dh(n)&&(this.fragPrevious=n),this.state=Qr.IDLE),!a)return;const i=this.tracksBuffered[this.currentTrackId];if(!i)return;let l;const o=n.start;for(let d=0;d=i[d].start&&o<=i[d].end){l=i[d];break}const c=n.start+n.duration;l?l.end=c:(l={start:o,end:c},i.push(l)),this.fragmentTracker.fragBuffered(n),this.fragBufferedComplete(n,null),this.media&&this.tick()}onBufferFlushing(t,r){const{startOffset:n,endOffset:a}=r;if(n===0&&a!==Number.POSITIVE_INFINITY){const i=a-1;if(i<=0)return;r.endOffsetSubtitles=Math.max(0,i),this.tracksBuffered.forEach(l=>{for(let o=0;onew _B(n));return}this.tracksBuffered=[],this.levels=r.map(n=>{const a=new _B(n);return this.tracksBuffered[a.id]=[],a}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,Ba.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(t,r){var n;if(this.currentTrackId=r.id,!((n=this.levels)!=null&&n.length)||this.currentTrackId===-1){this.clearInterval();return}const a=this.levels[this.currentTrackId];a!=null&&a.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,a&&this.state!==Qr.STOPPED&&this.setInterval(eYe)}onSubtitleTrackLoaded(t,r){var n;const{currentTrackId:a,levels:i}=this,{details:l,id:o}=r;if(!i){this.warn(`Subtitle tracks were reset while loading level ${o}`);return}const c=i[o];if(o>=i.length||!c)return;this.log(`Subtitle track ${o} loaded [${l.startSN},${l.endSN}]${l.lastPartSn?`[part-${l.lastPartSn}-${l.lastPartIndex}]`:""},duration:${l.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let d=0;if(l.live||(n=c.details)!=null&&n.live){if(l.deltaUpdateFailed)return;const m=this.mainDetails;if(!m){this.startFragRequested=!1;return}const p=m.fragments[0];if(!c.details)l.hasProgramDateTime&&m.hasProgramDateTime?(jpe(l,m),d=l.fragmentStart):p&&(d=p.start,oCe(l,d));else{var h;d=this.alignPlaylists(l,c.details,(h=this.levelLastLoaded)==null?void 0:h.details),d===0&&p&&(d=p.start,oCe(l,d))}m&&!this.startFragRequested&&this.setStartPosition(m,d)}c.details=l,this.levelLastLoaded=c,o===a&&(this.hls.trigger(vt.SUBTITLE_TRACK_UPDATED,{details:l,id:o,groupId:r.groupId}),this.tick(),l.live&&!this.fragCurrent&&this.media&&this.state===Qr.IDLE&&(OA(null,l.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),c.details=void 0)))}_handleFragmentLoadComplete(t){const{frag:r,payload:n}=t,a=r.decryptdata,i=this.hls;if(!this.fragContextChanged(r)&&n&&n.byteLength>0&&a!=null&&a.key&&a.iv&&jP(a.method)){const l=performance.now();this.decrypter.decrypt(new Uint8Array(n),a.key.buffer,a.iv.buffer,I6e(a.method)).catch(o=>{throw i.trigger(vt.ERROR,{type:ci.MEDIA_ERROR,details:yr.FRAG_DECRYPT_ERROR,fatal:!1,error:o,reason:o.message,frag:r}),o}).then(o=>{const c=performance.now();i.trigger(vt.FRAG_DECRYPTED,{frag:r,payload:o,stats:{tstart:l,tdecrypt:c}})}).catch(o=>{this.warn(`${o.name}: ${o.message}`),this.state=Qr.IDLE})}}doTick(){if(!this.media){this.state=Qr.IDLE;return}if(this.state===Qr.IDLE){const{currentTrackId:t,levels:r}=this,n=r==null?void 0:r[t];if(!n||!r.length||!n.details||this.waitForLive(n))return;const{config:a}=this,i=this.getLoadPosition(),l=mo.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],i,a.maxBufferHole),{end:o,len:c}=l,d=n.details,h=this.hls.maxBufferLength+d.levelTargetDuration;if(c>h)return;const m=d.fragments,p=m.length,x=d.edge;let y=null;const _=this.fragPrevious;if(ox-k?0:k;y=OA(_,m,Math.max(m[0].start,o),T),!y&&_&&_.start{if(a=a>>>0,a>i-1)throw new DOMException(`Failed to execute '${n}' on 'TimeRanges': The index provided (${a}) is greater than the maximum bound (${i})`);return t[a][n]};this.buffered={get length(){return t.length},end(n){return r("end",n,t.length)},start(n){return r("start",n,t.length)}}}}const UGs={42:225,92:233,94:237,95:243,96:250,123:231,124:247,125:209,126:241,127:9608,128:174,129:176,130:189,131:191,132:8482,133:162,134:163,135:9834,136:224,137:32,138:232,139:226,140:234,141:238,142:244,143:251,144:193,145:201,146:211,147:218,148:220,149:252,150:8216,151:161,152:42,153:8217,154:9473,155:169,156:8480,157:8226,158:8220,159:8221,160:192,161:194,162:199,163:200,164:202,165:203,166:235,167:206,168:207,169:239,170:212,171:217,172:249,173:219,174:171,175:187,176:195,177:227,178:205,179:204,180:236,181:210,182:242,183:213,184:245,185:123,186:125,187:92,188:94,189:95,190:124,191:8764,192:196,193:228,194:214,195:246,196:223,197:165,198:164,199:9475,200:197,201:229,202:216,203:248,204:9487,205:9491,206:9495,207:9499},sbt=s=>String.fromCharCode(UGs[s]||s),Zv=15,o2=100,qGs={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},VGs={17:2,18:4,21:6,22:8,23:10,19:13,20:15},HGs={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},GGs={25:2,26:4,29:6,30:8,31:10,27:13,28:15},WGs=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class KGs{constructor(){this.time=null,this.verboseLevel=0}log(t,r){if(this.verboseLevel>=t){const n=typeof r=="function"?r():r;gc.log(`${this.time} [${t}] ${n}`)}}}const cC=function(t){const r=[];for(let n=0;no2&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=o2)}moveCursor(t){const r=this.pos+t;if(t>1)for(let n=this.pos+1;n=144&&this.backSpace();const r=sbt(t);if(this.pos>=o2){this.logger.log(0,()=>"Cannot insert "+t.toString(16)+" ("+r+") at position "+this.pos+". Skipping it!");return}this.chars[this.pos].setChar(r,this.currPenState),this.moveCursor(1)}clearFromPos(t){let r;for(r=t;r"pacData = "+Uc(t));let r=t.row-1;if(this.nrRollUpRows&&r"bkgData = "+Uc(t)),this.backSpace(),this.setPen(t),this.insertChar(32)}setRollUpRows(t){this.nrRollUpRows=t}rollUp(){if(this.nrRollUpRows===null){this.logger.log(3,"roll_up but nrRollUpRows not set yet");return}this.logger.log(1,()=>this.getDisplayText());const t=this.currRow+1-this.nrRollUpRows,r=this.rows.splice(t,1)[0];r.clear(),this.rows.splice(this.currRow,0,r),this.logger.log(2,"Rolling up")}getDisplayText(t){t=t||!1;const r=[];let n="",a=-1;for(let i=0;i0&&(t?n="["+r.join(" | ")+"]":n=r.join(` `)),n}getTextAndFormat(){return this.rows}}class tYe{constructor(t,r,n){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=t,this.outputFilter=r,this.mode=null,this.verbose=0,this.displayedMemory=new Zwe(n),this.nonDisplayedMemory=new Zwe(n),this.lastOutputScreen=new Zwe(n),this.currRollUpRow=this.displayedMemory.rows[Zv-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=n}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[Zv-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(t){this.outputFilter=t}setPAC(t){this.writeScreen.setPAC(t)}setBkgData(t){this.writeScreen.setBkgData(t)}setMode(t){t!==this.mode&&(this.mode=t,this.logger.log(2,()=>"MODE="+t),this.mode==="MODE_POP-ON"?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),this.mode!=="MODE_ROLL-UP"&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=t)}insertChars(t){for(let n=0;nr+": "+this.writeScreen.getDisplayText(!0)),(this.mode==="MODE_PAINT-ON"||this.mode==="MODE_ROLL-UP")&&(this.logger.log(1,()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0)),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),this.mode!=="MODE_TEXT"&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(t){this.logger.log(2,"RU("+t+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(t)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),this.mode==="MODE_POP-ON"){const t=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=t,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>"DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)}ccTO(t){this.logger.log(2,"TO("+t+") - Tab Offset"),this.writeScreen.moveCursor(t)}ccMIDROW(t){const r={flash:!1};if(r.underline=t%2===1,r.italics=t>=46,r.italics)r.foreground="white";else{const n=Math.floor(t/2)-16,a=["white","green","blue","cyan","red","yellow","magenta"];r.foreground=a[n]}this.logger.log(2,"MIDROW: "+Uc(r)),this.writeScreen.setPen(r)}outputDataUpdate(t=!1){const r=this.logger.time;r!==null&&this.outputFilter&&(this.cueStartTime===null&&!this.displayedMemory.isEmpty()?this.cueStartTime=r:this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,r,this.lastOutputScreen),t&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:r),this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(t){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,t,this.displayedMemory),this.cueStartTime=t))}}class sYe{constructor(t,r,n){this.channels=void 0,this.currentChannel=0,this.cmdHistory=QGs(),this.logger=void 0;const a=this.logger=new KGs;this.channels=[null,new tYe(t,r,a),new tYe(t+1,n,a)]}getHandler(t){return this.channels[t].getHandler()}setHandler(t,r){this.channels[t].setHandler(r)}addData(t,r){this.logger.time=t;for(let n=0;n"["+cC([r[n],r[n+1]])+"] -> ("+cC([a,i])+")");const c=this.cmdHistory;if(a>=16&&a<=31){if(XGs(a,i,c)){xV(null,null,c),this.logger.log(3,()=>"Repeated command ("+cC([a,i])+") is dropped");continue}xV(a,i,this.cmdHistory),l=this.parseCmd(a,i),l||(l=this.parseMidrow(a,i)),l||(l=this.parsePAC(a,i)),l||(l=this.parseBackgroundAttributes(a,i))}else xV(null,null,c);if(!l&&(o=this.parseChars(a,i),o)){const h=this.currentChannel;h&&h>0?this.channels[h].insertChars(o):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!l&&!o&&this.logger.log(2,()=>"Couldn't parse cleaned data "+cC([a,i])+" orig: "+cC([r[n],r[n+1]]))}}parseCmd(t,r){const n=(t===20||t===28||t===21||t===29)&&r>=32&&r<=47,a=(t===23||t===31)&&r>=33&&r<=35;if(!(n||a))return!1;const i=t===20||t===21||t===23?1:2,l=this.channels[i];return t===20||t===21||t===28||t===29?r===32?l.ccRCL():r===33?l.ccBS():r===34?l.ccAOF():r===35?l.ccAON():r===36?l.ccDER():r===37?l.ccRU(2):r===38?l.ccRU(3):r===39?l.ccRU(4):r===40?l.ccFON():r===41?l.ccRDC():r===42?l.ccTR():r===43?l.ccRTD():r===44?l.ccEDM():r===45?l.ccCR():r===46?l.ccENM():r===47&&l.ccEOC():l.ccTO(r-32),this.currentChannel=i,!0}parseMidrow(t,r){let n=0;if((t===17||t===25)&&r>=32&&r<=47){if(t===17?n=1:n=2,n!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const a=this.channels[n];return a?(a.ccMIDROW(r),this.logger.log(3,()=>"MIDROW ("+cC([t,r])+")"),!0):!1}return!1}parsePAC(t,r){let n;const a=(t>=17&&t<=23||t>=25&&t<=31)&&r>=64&&r<=127,i=(t===16||t===24)&&r>=64&&r<=95;if(!(a||i))return!1;const l=t<=23?1:2;r>=64&&r<=95?n=l===1?qGs[t]:HGs[t]:n=l===1?VGs[t]:GGs[t];const o=this.channels[l];return o?(o.setPAC(this.interpretPAC(n,r)),this.currentChannel=l,!0):!1}interpretPAC(t,r){let n;const a={color:null,italics:!1,indent:null,underline:!1,row:t};return r>95?n=r-96:n=r-64,a.underline=(n&1)===1,n<=13?a.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(n/2)]:n<=15?(a.italics=!0,a.color="white"):a.indent=Math.floor((n-16)/2)*4,a}parseChars(t,r){let n,a=null,i=null;if(t>=25?(n=2,i=t-8):(n=1,i=t),i>=17&&i<=19){let l;i===17?l=r+80:i===18?l=r+112:l=r+144,this.logger.log(2,()=>"Special char '"+sbt(l)+"' in channel "+n),a=[l]}else t>=32&&t<=127&&(a=r===0?[t]:[t,r]);return a&&this.logger.log(3,()=>"Char codes = "+cC(a).join(",")),a}parseBackgroundAttributes(t,r){const n=(t===16||t===24)&&r>=32&&r<=47,a=(t===23||t===31)&&r>=45&&r<=47;if(!(n||a))return!1;let i;const l={};t===16||t===24?(i=Math.floor((r-32)/2),l.background=WGs[i],r%2===1&&(l.background=l.background+"_semi")):r===45?l.background="transparent":(l.foreground="black",r===47&&(l.underline=!0));const o=t<=23?1:2;return this.channels[o].setBkgData(l),!0}reset(){for(let t=0;t100)throw new Error("Position must be between 0 and 100.");D=$,this.hasBeenReset=!0}})),Object.defineProperty(h,"positionAlign",i({},m,{get:function(){return R},set:function($){const ee=a($);if(!ee)throw new SyntaxError("An invalid or illegal string was specified.");R=ee,this.hasBeenReset=!0}})),Object.defineProperty(h,"size",i({},m,{get:function(){return z},set:function($){if($<0||$>100)throw new Error("Size must be between 0 and 100.");z=$,this.hasBeenReset=!0}})),Object.defineProperty(h,"align",i({},m,{get:function(){return O},set:function($){const ee=a($);if(!ee)throw new SyntaxError("An invalid or illegal string was specified.");O=ee,this.hasBeenReset=!0}})),h.displayState=void 0}return l.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},l}();class JGs{decode(t,r){if(!t)return"";if(typeof t!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(t))}}function nbt(s){function t(n,a,i,l){return(n|0)*3600+(a|0)*60+(i|0)+parseFloat(l||0)}const r=s.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return r?parseFloat(r[2])>59?t(r[2],r[3],0,r[4]):t(r[1],r[2],r[3],r[4]):null}class eWs{constructor(){this.values=Object.create(null)}set(t,r){!this.get(t)&&r!==""&&(this.values[t]=r)}get(t,r,n){return n?this.has(t)?this.values[t]:r[n]:this.has(t)?this.values[t]:r}has(t){return t in this.values}alt(t,r,n){for(let a=0;a=0&&n<=100)return this.set(t,n),!0}return!1}}function abt(s,t,r,n){const a=n?s.split(n):[s];for(const i in a){if(typeof a[i]!="string")continue;const l=a[i].split(r);if(l.length!==2)continue;const o=l[0],c=l[1];t(o,c)}}const pCe=new G6e(0,0,""),yV=pCe.align==="middle"?"middle":"center";function tWs(s,t,r){const n=s;function a(){const o=nbt(s);if(o===null)throw new Error("Malformed timestamp: "+n);return s=s.replace(/^[^\sa-zA-Z-]+/,""),o}function i(o,c){const d=new eWs;abt(o,function(p,x){let y;switch(p){case"region":for(let _=r.length-1;_>=0;_--)if(r[_].id===x){d.set(p,r[_].region);break}break;case"vertical":d.alt(p,x,["rl","lr"]);break;case"line":y=x.split(","),d.integer(p,y[0]),d.percent(p,y[0])&&d.set("snapToLines",!1),d.alt(p,y[0],["auto"]),y.length===2&&d.alt("lineAlign",y[1],["start",yV,"end"]);break;case"position":y=x.split(","),d.percent(p,y[0]),y.length===2&&d.alt("positionAlign",y[1],["start",yV,"end","line-left","line-right","auto"]);break;case"size":d.percent(p,x);break;case"align":d.alt(p,x,["start",yV,"end","left","right"]);break}},/:/,/\s/),c.region=d.get("region",null),c.vertical=d.get("vertical","");let h=d.get("line","auto");h==="auto"&&pCe.line===-1&&(h=-1),c.line=h,c.lineAlign=d.get("lineAlign","start"),c.snapToLines=d.get("snapToLines",!0),c.size=d.get("size",100),c.align=d.get("align",yV);let m=d.get("position","auto");m==="auto"&&pCe.position===50&&(m=c.align==="start"||c.align==="left"?0:c.align==="end"||c.align==="right"?100:50),c.position=m}function l(){s=s.replace(/^\s+/,"")}if(l(),t.startTime=a(),l(),s.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+n);s=s.slice(3),l(),t.endTime=a(),l(),i(s,t)}function ibt(s){return s.replace(//gi,` `)}class sWs{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new JGs,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(t){const r=this;t&&(r.buffer+=r.decoder.decode(t,{stream:!0}));function n(){let i=r.buffer,l=0;for(i=ibt(i);l")===-1){r.cue.id=i;continue}case"CUE":if(!r.cue){r.state="BADCUE";continue}try{tWs(i,r.cue,r.regionList)}catch{r.cue=null,r.state="BADCUE";continue}r.state="CUETEXT";continue;case"CUETEXT":{const o=i.indexOf("-->")!==-1;if(!i||o&&(l=!0)){r.oncue&&r.cue&&r.oncue(r.cue),r.cue=null,r.state="ID";continue}if(r.cue===null)continue;r.cue.text&&(r.cue.text+=` `),r.cue.text+=i}continue;case"BADCUE":i||(r.state="ID")}}}catch{r.state==="CUETEXT"&&r.cue&&r.oncue&&r.oncue(r.cue),r.cue=null,r.state=r.state==="INITIAL"?"BADWEBVTT":"BADCUE"}return this}flush(){const t=this;try{if((t.cue||t.state==="HEADER")&&(t.buffer+=` `,t.parse()),t.state==="INITIAL"||t.state==="BADWEBVTT")throw new Error("Malformed WebVTT signature.")}catch(r){t.onparsingerror&&t.onparsingerror(r)}return t.onflush&&t.onflush(),this}}const rWs=/\r\n|\n\r|\n|\r/g,Xwe=function(t,r,n=0){return t.slice(n,n+r.length)===r},nWs=function(t){let r=parseInt(t.slice(-3));const n=parseInt(t.slice(-6,-4)),a=parseInt(t.slice(-9,-7)),i=t.length>9?parseInt(t.substring(0,t.indexOf(":"))):0;if(!ka(r)||!ka(n)||!ka(a)||!ka(i))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${t}`);return r+=1e3*n,r+=60*1e3*a,r+=60*60*1e3*i,r};function W6e(s,t,r){return L7(s.toString())+L7(t.toString())+L7(r)}const aWs=function(t,r,n){let a=t[r],i=t[a.prevCC];if(!i||!i.new&&a.new){t.ccOffset=t.presentationOffset=a.start,a.new=!1;return}for(;(l=i)!=null&&l.new;){var l;t.ccOffset+=a.start-i.start,a.new=!1,a=i,i=t[a.prevCC]}t.presentationOffset=n};function iWs(s,t,r,n,a,i,l){const o=new sWs,c=w0(new Uint8Array(s)).trim().replace(rWs,` `).split(` `),d=[],h=t?hHs(t.baseTime,t.timescale):0;let m="00:00.000",p=0,x=0,y,_=!0;o.oncue=function(b){const j=r[n];let k=r.ccOffset;const T=(p-h)/9e4;if(j!=null&&j.new&&(x!==void 0?k=r.ccOffset=j.start:aWs(r,n,T)),T){if(!t){y=new Error("Missing initPTS for VTT MPEGTS");return}k=T-r.presentationOffset}const E=b.endTime-b.startTime,A=Yx((b.startTime+k-x)*9e4,a*9e4)/9e4;b.startTime=Math.max(A,0),b.endTime=Math.max(A+E,0);const D=b.text.trim();b.text=decodeURIComponent(encodeURIComponent(D)),b.id||(b.id=W6e(b.startTime,b.endTime,D)),b.endTime>0&&d.push(b)},o.onparsingerror=function(b){y=b},o.onflush=function(){if(y){l(y);return}i(d)},c.forEach(b=>{if(_)if(Xwe(b,"X-TIMESTAMP-MAP=")){_=!1,b.slice(16).split(",").forEach(j=>{Xwe(j,"LOCAL:")?m=j.slice(6):Xwe(j,"MPEGTS:")&&(p=parseInt(j.slice(7)))});try{x=nWs(m)/1e3}catch(j){y=j}return}else b===""&&(_=!1);o.parse(b+` `)}),o.flush()}const Qwe="stpp.ttml.im1t",obt=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,lbt=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,oWs={left:"start",center:"center",right:"end",start:"start",end:"end"};function rYe(s,t,r,n){const a=zo(new Uint8Array(s),["mdat"]);if(a.length===0){n(new Error("Could not parse IMSC1 mdat"));return}const i=a.map(o=>w0(o)),l=uHs(t.baseTime,1,t.timescale);try{i.forEach(o=>r(lWs(o,l)))}catch(o){n(o)}}function lWs(s,t){const a=new DOMParser().parseFromString(s,"text/xml").getElementsByTagName("tt")[0];if(!a)throw new Error("Invalid ttml");const i={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},l=Object.keys(i).reduce((m,p)=>(m[p]=a.getAttribute(`ttp:${p}`)||i[p],m),{}),o=a.getAttribute("xml:space")!=="preserve",c=nYe(Jwe(a,"styling","style")),d=nYe(Jwe(a,"layout","region")),h=Jwe(a,"body","[begin]");return[].map.call(h,m=>{const p=cbt(m,o);if(!p||!m.hasAttribute("begin"))return null;const x=t2e(m.getAttribute("begin"),l),y=t2e(m.getAttribute("dur"),l);let _=t2e(m.getAttribute("end"),l);if(x===null)throw aYe(m);if(_===null){if(y===null)throw aYe(m);_=x+y}const b=new G6e(x-t,_-t,p);b.id=W6e(b.startTime,b.endTime,b.text);const j=d[m.getAttribute("region")],k=c[m.getAttribute("style")],T=cWs(j,k,c),{textAlign:E}=T;if(E){const A=oWs[E];A&&(b.lineAlign=A),b.align=E}return Ec(b,T),b}).filter(m=>m!==null)}function Jwe(s,t,r){const n=s.getElementsByTagName(t)[0];return n?[].slice.call(n.querySelectorAll(r)):[]}function nYe(s){return s.reduce((t,r)=>{const n=r.getAttribute("xml:id");return n&&(t[n]=r),t},{})}function cbt(s,t){return[].slice.call(s.childNodes).reduce((r,n,a)=>{var i;return n.nodeName==="br"&&a?r+` `:(i=n.childNodes)!=null&&i.length?cbt(n,t):t?r+n.textContent.trim().replace(/\s+/g," "):r+n.textContent},"")}function cWs(s,t,r){const n="http://www.w3.org/ns/ttml#styling";let a=null;const i=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],l=s!=null&&s.hasAttribute("style")?s.getAttribute("style"):null;return l&&r.hasOwnProperty(l)&&(a=r[l]),i.reduce((o,c)=>{const d=e2e(t,n,c)||e2e(s,n,c)||e2e(a,n,c);return d&&(o[c]=d),o},{})}function e2e(s,t,r){return s&&s.hasAttributeNS(t,r)?s.getAttributeNS(t,r):null}function aYe(s){return new Error(`Could not parse ttml timestamp ${s}`)}function t2e(s,t){if(!s)return null;let r=nbt(s);return r===null&&(obt.test(s)?r=dWs(s,t):lbt.test(s)&&(r=uWs(s,t))),r}function dWs(s,t){const r=obt.exec(s),n=(r[4]|0)+(r[5]|0)/t.subFrameRate;return(r[1]|0)*3600+(r[2]|0)*60+(r[3]|0)+n/t.frameRate}function uWs(s,t){const r=lbt.exec(s),n=Number(r[1]);switch(r[2]){case"h":return n*3600;case"m":return n*60;case"ms":return n*1e3;case"f":return n/t.frameRate;case"t":return n/t.tickRate}return n}class vV{constructor(t,r){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=t,this.trackName=r}dispatchCue(){this.startTime!==null&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(t,r,n){(this.startTime===null||this.startTime>t)&&(this.startTime=t),this.endTime=r,this.screen=n,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}class hWs{constructor(t){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=oYe(),this.captionsProperties=void 0,this.hls=t,this.config=t.config,this.Cues=t.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},t.on(vt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(vt.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(vt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(vt.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(vt.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(vt.FRAG_LOADING,this.onFragLoading,this),t.on(vt.FRAG_LOADED,this.onFragLoaded,this),t.on(vt.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.on(vt.FRAG_DECRYPTED,this.onFragDecrypted,this),t.on(vt.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(vt.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.on(vt.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:t}=this;t.off(vt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(vt.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(vt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(vt.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(vt.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(vt.FRAG_LOADING,this.onFragLoading,this),t.off(vt.FRAG_LOADED,this.onFragLoaded,this),t.off(vt.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.off(vt.FRAG_DECRYPTED,this.onFragDecrypted,this),t.off(vt.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(vt.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.off(vt.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const t=new vV(this,"textTrack1"),r=new vV(this,"textTrack2"),n=new vV(this,"textTrack3"),a=new vV(this,"textTrack4");this.cea608Parser1=new sYe(1,t,r),this.cea608Parser2=new sYe(3,n,a)}addCues(t,r,n,a,i){let l=!1;for(let o=i.length;o--;){const c=i[o],d=mWs(c[0],c[1],r,n);if(d>=0&&(c[0]=Math.min(c[0],r),c[1]=Math.max(c[1],n),l=!0,d/(n-r)>.5))return}if(l||i.push([r,n]),this.config.renderTextTracksNatively){const o=this.captionsTracks[t];this.Cues.newCue(o,r,n,a)}else{const o=this.Cues.newCue(null,r,n,a);this.hls.trigger(vt.CUES_PARSED,{type:"captions",cues:o,track:t})}}onInitPtsFound(t,{frag:r,id:n,initPTS:a,timescale:i,trackId:l}){const{unparsedVttFrags:o}=this;n===Ba.MAIN&&(this.initPTS[r.cc]={baseTime:a,timescale:i,trackId:l}),o.length&&(this.unparsedVttFrags=[],o.forEach(c=>{this.initPTS[c.frag.cc]?this.onFragLoaded(vt.FRAG_LOADED,c):this.hls.trigger(vt.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:c.frag,error:new Error("Subtitle discontinuity domain does not match main")})}))}getExistingTrack(t,r){const{media:n}=this;if(n)for(let a=0;a{wI(a[i]),delete a[i]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=oYe(),this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){const{media:t}=this;if(!t)return;const r=t.textTracks;if(r)for(let n=0;ni.textCodec===Qwe);if(this.config.enableWebVTT||a&&this.config.enableIMSC1){if(z1t(this.tracks,n)){this.tracks=n;return}if(this.textTracks=[],this.tracks=n,this.config.renderTextTracksNatively){const l=this.media,o=l?Hue(l.textTracks):null;if(this.tracks.forEach((c,d)=>{let h;if(o){let m=null;for(let p=0;pd!==null).map(d=>d.label);c.length&&this.hls.logger.warn(`Media element contains unused subtitle tracks: ${c.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const l=this.tracks.map(o=>({label:o.name,kind:o.type.toLowerCase(),default:o.default,subtitleTrack:o}));this.hls.trigger(vt.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:l})}}}onManifestLoaded(t,r){this.config.enableCEA708Captions&&r.captions&&r.captions.forEach(n=>{const a=/(?:CC|SERVICE)([1-4])/.exec(n.instreamId);if(!a)return;const i=`textTrack${a[1]}`,l=this.captionsProperties[i];l&&(l.label=n.name,n.lang&&(l.languageCode=n.lang),l.media=n)})}closedCaptionsForLevel(t){const r=this.hls.levels[t.level];return r==null?void 0:r.attrs["CLOSED-CAPTIONS"]}onFragLoading(t,r){if(this.enabled&&r.frag.type===Ba.MAIN){var n,a;const{cea608Parser1:i,cea608Parser2:l,lastSn:o}=this,{cc:c,sn:d}=r.frag,h=(n=(a=r.part)==null?void 0:a.index)!=null?n:-1;i&&l&&(d!==o+1||d===o&&h!==this.lastPartIndex+1||c!==this.lastCc)&&(i.reset(),l.reset()),this.lastCc=c,this.lastSn=d,this.lastPartIndex=h}}onFragLoaded(t,r){const{frag:n,payload:a}=r;if(n.type===Ba.SUBTITLE)if(a.byteLength){const i=n.decryptdata,l="stats"in r;if(i==null||!i.encrypted||l){const o=this.tracks[n.level],c=this.vttCCs;c[n.cc]||(c[n.cc]={start:n.start,prevCC:this.prevCC,new:!0},this.prevCC=n.cc),o&&o.textCodec===Qwe?this._parseIMSC1(n,a):this._parseVTTs(r)}}else this.hls.trigger(vt.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:n,error:new Error("Empty subtitle payload")})}_parseIMSC1(t,r){const n=this.hls;rYe(r,this.initPTS[t.cc],a=>{this._appendCues(a,t.level),n.trigger(vt.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:t})},a=>{n.logger.log(`Failed to parse IMSC1: ${a}`),n.trigger(vt.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t,error:a})})}_parseVTTs(t){var r;const{frag:n,payload:a}=t,{initPTS:i,unparsedVttFrags:l}=this,o=i.length-1;if(!i[n.cc]&&o===-1){l.push(t);return}const c=this.hls,d=(r=n.initSegment)!=null&&r.data?tv(n.initSegment.data,new Uint8Array(a)).buffer:a;iWs(d,this.initPTS[n.cc],this.vttCCs,n.cc,n.start,h=>{this._appendCues(h,n.level),c.trigger(vt.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:n})},h=>{const m=h.message==="Missing initPTS for VTT MPEGTS";m?l.push(t):this._fallbackToIMSC1(n,a),c.logger.log(`Failed to parse VTT cue: ${h}`),!(m&&o>n.cc)&&c.trigger(vt.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:n,error:h})})}_fallbackToIMSC1(t,r){const n=this.tracks[t.level];n.textCodec||rYe(r,this.initPTS[t.cc],()=>{n.textCodec=Qwe,this._parseIMSC1(t,r)},()=>{n.textCodec="wvtt"})}_appendCues(t,r){const n=this.hls;if(this.config.renderTextTracksNatively){const a=this.textTracks[r];if(!a||a.mode==="disabled")return;t.forEach(i=>ebt(a,i))}else{const a=this.tracks[r];if(!a)return;const i=a.default?"default":"subtitles"+r;n.trigger(vt.CUES_PARSED,{type:"subtitles",cues:t,track:i})}}onFragDecrypted(t,r){const{frag:n}=r;n.type===Ba.SUBTITLE&&this.onFragLoaded(vt.FRAG_LOADED,r)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(t,r){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:n,samples:a}=r;if(!(n.type===Ba.MAIN&&this.closedCaptionsForLevel(n)==="NONE"))for(let i=0;ifCe(o[c],r,n))}if(this.config.renderTextTracksNatively&&r===0&&a!==void 0){const{textTracks:o}=this;Object.keys(o).forEach(c=>fCe(o[c],r,a))}}}extractCea608Data(t){const r=[[],[]],n=t[0]&31;let a=2;for(let i=0;i=16?c--:c++;const x=ibt(d.trim()),y=W6e(t,r,x);s!=null&&(m=s.cues)!=null&&m.getCueById(y)||(l=new h(t,r,x),l.id=y,l.line=p+1,l.align="left",l.position=10+Math.min(80,Math.floor(c*8/32)*10),a.push(l))}return s&&a.length&&(a.sort((p,x)=>p.line==="auto"||x.line==="auto"?0:p.line>8&&x.line>8?x.line-p.line:p.line-x.line),a.forEach(p=>ebt(s,p))),a}};function gWs(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const xWs=/(\d+)-(\d+)\/(\d+)/;class lYe{constructor(t){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=t.fetchSetup||_Ws,this.controller=new self.AbortController,this.stats=new k6e}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}abort(){var t;this.abortInternal(),(t=this.callbacks)!=null&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(t,r,n){const a=this.stats;if(a.loading.start)throw new Error("Loader can only be used once.");a.loading.start=self.performance.now();const i=yWs(t,this.controller.signal),l=t.responseType==="arraybuffer",o=l?"byteLength":"length",{maxTimeToFirstByteMs:c,maxLoadTimeMs:d}=r.loadPolicy;this.context=t,this.config=r,this.callbacks=n,this.request=this.fetchSetup(t,i),self.clearTimeout(this.requestTimeout),r.timeout=c&&ka(c)?c:d,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(a,t,this.response))},r.timeout),(NB(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(m=>{var p;this.response=this.loader=m;const x=Math.max(self.performance.now(),a.loading.start);if(self.clearTimeout(this.requestTimeout),r.timeout=d,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(a,t,this.response))},d-(x-a.loading.start)),!m.ok){const{status:_,statusText:b}=m;throw new wWs(b||"fetch, bad network response",_,m)}a.loading.first=x,a.total=bWs(m.headers)||a.total;const y=(p=this.callbacks)==null?void 0:p.onProgress;return y&&ka(r.highWaterMark)?this.loadProgressively(m,a,t,r.highWaterMark,y):l?m.arrayBuffer():t.responseType==="json"?m.json():m.text()}).then(m=>{var p,x;const y=this.response;if(!y)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),a.loading.end=Math.max(self.performance.now(),a.loading.first);const _=m[o];_&&(a.loaded=a.total=_);const b={url:y.url,data:m,code:y.status},j=(p=this.callbacks)==null?void 0:p.onProgress;j&&!ka(r.highWaterMark)&&j(a,t,m,y),(x=this.callbacks)==null||x.onSuccess(b,a,t,y)}).catch(m=>{var p;if(self.clearTimeout(this.requestTimeout),a.aborted)return;const x=m&&m.code||0,y=m?m.message:null;(p=this.callbacks)==null||p.onError({code:x,text:y},t,m?m.details:null,a)})}getCacheAge(){let t=null;if(this.response){const r=this.response.headers.get("age");t=r?parseFloat(r):null}return t}getResponseHeader(t){return this.response?this.response.headers.get(t):null}loadProgressively(t,r,n,a=0,i){const l=new b1t,o=t.body.getReader(),c=()=>o.read().then(d=>{if(d.done)return l.dataLength&&i(r,n,l.flush().buffer,t),Promise.resolve(new ArrayBuffer(0));const h=d.value,m=h.length;return r.loaded+=m,m=a&&i(r,n,l.flush().buffer,t)):i(r,n,h.buffer,t),c()}).catch(()=>Promise.reject());return c()}}function yWs(s,t){const r={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(Ec({},s.headers))};return s.rangeEnd&&r.headers.set("Range","bytes="+s.rangeStart+"-"+String(s.rangeEnd-1)),r}function vWs(s){const t=xWs.exec(s);if(t)return parseInt(t[2])-parseInt(t[1])+1}function bWs(s){const t=s.get("Content-Range");if(t){const n=vWs(t);if(ka(n))return n}const r=s.get("Content-Length");if(r)return parseInt(r)}function _Ws(s,t){return new self.Request(s.url,t)}class wWs extends Error{constructor(t,r,n){super(t),this.code=void 0,this.details=void 0,this.code=r,this.details=n}}const jWs=/^age:\s*[\d.]+\s*$/im;class ubt{constructor(t){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=null,this.loader=null,this.stats=void 0,this.xhrSetup=t&&t.xhrSetup||null,this.stats=new k6e,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){const t=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),t&&(t.onreadystatechange=null,t.onprogress=null,t.readyState!==4&&(this.stats.aborted=!0,t.abort()))}abort(){var t;this.abortInternal(),(t=this.callbacks)!=null&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(t,r,n){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=t,this.config=r,this.callbacks=n,this.loadInternal()}loadInternal(){const{config:t,context:r}=this;if(!t||!r)return;const n=this.loader=new self.XMLHttpRequest,a=this.stats;a.loading.first=0,a.loaded=0,a.aborted=!1;const i=this.xhrSetup;i?Promise.resolve().then(()=>{if(!(this.loader!==n||this.stats.aborted))return i(n,r.url)}).catch(l=>{if(!(this.loader!==n||this.stats.aborted))return n.open("GET",r.url,!0),i(n,r.url)}).then(()=>{this.loader!==n||this.stats.aborted||this.openAndSendXhr(n,r,t)}).catch(l=>{var o;(o=this.callbacks)==null||o.onError({code:n.status,text:l.message},r,n,a)}):this.openAndSendXhr(n,r,t)}openAndSendXhr(t,r,n){t.readyState||t.open("GET",r.url,!0);const a=r.headers,{maxTimeToFirstByteMs:i,maxLoadTimeMs:l}=n.loadPolicy;if(a)for(const o in a)t.setRequestHeader(o,a[o]);r.rangeEnd&&t.setRequestHeader("Range","bytes="+r.rangeStart+"-"+(r.rangeEnd-1)),t.onreadystatechange=this.readystatechange.bind(this),t.onprogress=this.loadprogress.bind(this),t.responseType=r.responseType,self.clearTimeout(this.requestTimeout),n.timeout=i&&ka(i)?i:l,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),n.timeout),t.send()}readystatechange(){const{context:t,loader:r,stats:n}=this;if(!t||!r)return;const a=r.readyState,i=this.config;if(!n.aborted&&a>=2&&(n.loading.first===0&&(n.loading.first=Math.max(self.performance.now(),n.loading.start),i.timeout!==i.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),i.timeout=i.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.loadPolicy.maxLoadTimeMs-(n.loading.first-n.loading.start)))),a===4)){self.clearTimeout(this.requestTimeout),r.onreadystatechange=null,r.onprogress=null;const d=r.status,h=r.responseType==="text"?r.responseText:null;if(d>=200&&d<300){const y=h??r.response;if(y!=null){var l,o;n.loading.end=Math.max(self.performance.now(),n.loading.first);const _=r.responseType==="arraybuffer"?y.byteLength:y.length;n.loaded=n.total=_,n.bwEstimate=n.total*8e3/(n.loading.end-n.loading.first);const b=(l=this.callbacks)==null?void 0:l.onProgress;b&&b(n,t,y,r);const j={url:r.responseURL,data:y,code:d};(o=this.callbacks)==null||o.onSuccess(j,n,t,r);return}}const m=i.loadPolicy.errorRetry,p=n.retry,x={url:t.url,data:void 0,code:d};if(bpe(m,p,!1,x))this.retry(m);else{var c;gc.error(`${d} while loading ${t.url}`),(c=this.callbacks)==null||c.onError({code:d,text:r.statusText},t,r,n)}}}loadtimeout(){if(!this.config)return;const t=this.config.loadPolicy.timeoutRetry,r=this.stats.retry;if(bpe(t,r,!0))this.retry(t);else{var n;gc.warn(`timeout while loading ${(n=this.context)==null?void 0:n.url}`);const a=this.callbacks;a&&(this.abortInternal(),a.onTimeout(this.stats,this.context,this.loader))}}retry(t){const{context:r,stats:n}=this;this.retryDelay=E6e(t,n.retry),n.retry++,gc.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${r==null?void 0:r.url}, retrying ${n.retry}/${t.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(t){const r=this.stats;r.loaded=t.loaded,t.lengthComputable&&(r.total=t.total)}getCacheAge(){let t=null;if(this.loader&&jWs.test(this.loader.getAllResponseHeaders())){const r=this.loader.getResponseHeader("age");t=r?parseFloat(r):null}return t}getResponseHeader(t){return this.loader&&new RegExp(`^${t}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(t):null}}const NWs={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},kWs=hc(hc({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,startOnSegmentBoundary:!1,maxBufferSize:60*1e3*1e3,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,ignorePlaylistParsingErrors:!1,loader:ubt,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:Oqs,bufferController:CHs,capLevelController:q6e,errorController:Uqs,fpsController:TGs,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:c1t,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!0,preserveManualLevelOnError:!1,certLoadPolicy:{default:NWs},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},SWs()),{},{subtitleStreamController:zGs,subtitleTrackController:MGs,timelineController:hWs,audioStreamController:jHs,audioTrackController:NHs,emeController:NP,cmcdController:NGs,contentSteeringController:SGs,interstitialsController:BGs});function SWs(){return{cueHandler:pWs,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}}function CWs(s,t,r){if((t.liveSyncDurationCount||t.liveMaxLatencyDurationCount)&&(t.liveSyncDuration||t.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(t.liveMaxLatencyDurationCount!==void 0&&(t.liveSyncDurationCount===void 0||t.liveMaxLatencyDurationCount<=t.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(t.liveMaxLatencyDuration!==void 0&&(t.liveSyncDuration===void 0||t.liveMaxLatencyDuration<=t.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const n=gCe(s),a=["manifest","level","frag"],i=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return a.forEach(l=>{const o=`${l==="level"?"playlist":l}LoadPolicy`,c=t[o]===void 0,d=[];i.forEach(h=>{const m=`${l}Loading${h}`,p=t[m];if(p!==void 0&&c){d.push(m);const x=n[o].default;switch(t[o]={default:x},h){case"TimeOut":x.maxLoadTimeMs=p,x.maxTimeToFirstByteMs=p;break;case"MaxRetry":x.errorRetry.maxNumRetry=p,x.timeoutRetry.maxNumRetry=p;break;case"RetryDelay":x.errorRetry.retryDelayMs=p,x.timeoutRetry.retryDelayMs=p;break;case"MaxRetryTimeout":x.errorRetry.maxRetryDelayMs=p,x.timeoutRetry.maxRetryDelayMs=p;break}}}),d.length&&r.warn(`hls.js config: "${d.join('", "')}" setting(s) are deprecated, use "${o}": ${Uc(t[o])}`)}),hc(hc({},n),t)}function gCe(s){return s&&typeof s=="object"?Array.isArray(s)?s.map(gCe):Object.keys(s).reduce((t,r)=>(t[r]=gCe(s[r]),t),{}):s}function TWs(s,t){const r=s.loader;r!==lYe&&r!==ubt?(t.log("[config]: Custom loader detected, cannot enable progressive streaming"),s.progressive=!1):gWs()&&(s.loader=lYe,s.progressive=!0,s.enableSoftwareAES=!0,t.log("[config]: Progressive streaming enabled, using FetchLoader"))}const Gue=2,EWs=.1,AWs=.05,MWs=100;class IWs extends n1t{constructor(t,r){super("gap-controller",t.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var n;(n=this.media)!=null&&n.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{if(this.hls){var n;this.ended=((n=this.media)==null?void 0:n.currentTime)||1,this.hls.trigger(vt.MEDIA_ENDED,{stalled:!1})}},this.hls=t,this.fragmentTracker=r,this.registerListeners()}registerListeners(){const{hls:t}=this;t&&(t.on(vt.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(vt.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(vt.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(vt.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(vt.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(vt.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(t,r){this.setInterval(MWs),this.mediaSource=r.mediaSource;const n=this.media=r.media;vg(n,"playing",this.onMediaPlaying),vg(n,"waiting",this.onMediaWaiting),vg(n,"ended",this.onMediaEnded)}onMediaDetaching(t,r){this.clearInterval();const{media:n}=this;n&&(nx(n,"playing",this.onMediaPlaying),nx(n,"waiting",this.onMediaWaiting),nx(n,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(t,r){this.buffered=r.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var t;if(!((t=this.media)!=null&&t.readyState)||!this.hasBuffered)return;const r=this.media.currentTime;this.poll(r,this.lastCurrentTime),this.lastCurrentTime=r}poll(t,r){var n,a;const i=(n=this.hls)==null?void 0:n.config;if(!i)return;const l=this.media;if(!l)return;const{seeking:o}=l,c=this.seeking&&!o,d=!this.seeking&&o,h=l.paused&&!o||l.ended||l.playbackRate===0;if(this.seeking=o,t!==r){r&&(this.ended=0),this.moved=!0,o||(this.nudgeRetry=0,i.nudgeOnVideoHole&&!h&&t>r&&this.nudgeOnVideoHole(t,r)),this.waiting===0&&this.stallResolved(t);return}if(d||c){c&&this.stallResolved(t);return}if(h){this.nudgeRetry=0,this.stallResolved(t),!this.ended&&l.ended&&this.hls&&(this.ended=t||1,this.hls.trigger(vt.MEDIA_ENDED,{stalled:!1}));return}if(!mo.getBuffered(l).length){this.nudgeRetry=0;return}const m=mo.bufferInfo(l,t,0),p=m.nextStart||0,x=this.fragmentTracker;if(o&&x&&this.hls){const D=cYe(this.hls.inFlightFragments,t),R=m.len>Gue,z=!p||D||p-t>Gue&&!x.getPartialFragment(t);if(R||z)return;this.moved=!1}const y=(a=this.hls)==null?void 0:a.latestLevelDetails;if(!this.moved&&this.stalled!==null&&x){if(!(m.len>0)&&!p)return;const R=Math.max(p,m.start||0)-t,O=!!(y!=null&&y.live)?y.targetduration*2:Gue,$=bV(t,x);if(R>0&&(R<=O||$)){l.paused||this._trySkipBufferHole($);return}}const _=i.detectStallWithCurrentTimeMs,b=self.performance.now(),j=this.waiting;let k=this.stalled;if(k===null)if(j>0&&b-j<_)k=this.stalled=j;else{this.stalled=b;return}const T=b-k;if(!o&&(T>=_||j)&&this.hls){var E;if(((E=this.mediaSource)==null?void 0:E.readyState)==="ended"&&!(y!=null&&y.live)&&Math.abs(t-((y==null?void 0:y.edge)||0))<1){if(this.ended)return;this.ended=t||1,this.hls.trigger(vt.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(m),!this.media||!this.hls)return}const A=mo.bufferInfo(l,t,i.maxBufferHole);this._tryFixBufferStall(A,T,t)}stallResolved(t){const r=this.stalled;if(r&&this.hls&&(this.stalled=null,this.stallReported)){const n=self.performance.now()-r;this.log(`playback not stuck anymore @${t}, after ${Math.round(n)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(vt.STALL_RESOLVED,{})}}nudgeOnVideoHole(t,r){var n;const a=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(n=this.buffered.audio)!=null&&n.length&&a&&a.length>1&&t>a.end(0)){const i=mo.bufferedInfo(mo.timeRangesToArray(this.buffered.audio),t,0);if(i.len>1&&r>=i.start){const l=mo.timeRangesToArray(a),o=mo.bufferedInfo(l,r,0).bufferedIndex;if(o>-1&&oo)&&h-d<1&&t-d<2){const m=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${t} hole: ${d} -> ${h} buffered index: ${c}`);this.warn(m.message),this.media.currentTime+=1e-6;let p=bV(t,this.fragmentTracker);p&&"fragment"in p?p=p.fragment:p||(p=void 0);const x=mo.bufferInfo(this.media,t,0);this.hls.trigger(vt.ERROR,{type:ci.MEDIA_ERROR,details:yr.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:m,reason:m.message,frag:p,buffer:x.len,bufferInfo:x})}}}}}_tryFixBufferStall(t,r,n){var a,i;const{fragmentTracker:l,media:o}=this,c=(a=this.hls)==null?void 0:a.config;if(!o||!l||!c)return;const d=(i=this.hls)==null?void 0:i.latestLevelDetails,h=bV(n,l);if((h||d!=null&&d.live&&n1&&t.len>c.maxBufferHole||t.nextStart&&(t.nextStart-nc.highBufferWatchdogPeriod*1e3||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(t))}adjacentTraversal(t,r){const n=this.fragmentTracker,a=t.nextStart;if(n&&a){const i=n.getFragAtPos(r,Ba.MAIN),l=n.getFragAtPos(a,Ba.MAIN);if(i&&l)return l.sn-i.sn<2}return!1}_reportStall(t){const{hls:r,media:n,stallReported:a,stalled:i}=this;if(!a&&i!==null&&n&&r){this.stallReported=!0;const l=new Error(`Playback stalling at @${n.currentTime} due to low buffer (${Uc(t)})`);this.warn(l.message),r.trigger(vt.ERROR,{type:ci.MEDIA_ERROR,details:yr.BUFFER_STALLED_ERROR,fatal:!1,error:l,buffer:t.len,bufferInfo:t,stalled:{start:i}})}}_trySkipBufferHole(t){var r;const{fragmentTracker:n,media:a}=this,i=(r=this.hls)==null?void 0:r.config;if(!a||!n||!i)return 0;const l=a.currentTime,o=mo.bufferInfo(a,l,0),c=l0&&o.len<1&&a.readyState<3,p=c-l;if(p>0&&(h||m)){if(p>i.maxBufferHole){let y=!1;if(l===0){const _=n.getAppendedFrag(0,Ba.MAIN);_&&c<_.end&&(y=!0)}if(!y&&t){var d;if(!((d=this.hls.loadLevelObj)!=null&&d.details)||cYe(this.hls.inFlightFragments,c))return 0;let b=!1,j=t.end;for(;j"u"))return self.VTTCue||self.TextTrackCue}function s2e(s,t,r,n,a){let i=new s(t,r,"");try{i.value=n,a&&(i.type=a)}catch{i=new s(t,r,Uc(a?hc({type:a},n):n))}return i}const _V=(()=>{const s=xCe();try{s&&new s(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class LWs{constructor(t){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(vt.EVENT_CUE_ENTER,{})},this.hls=t,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){const{hls:t}=this;t&&(t.on(vt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(vt.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(vt.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(vt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(vt.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.on(vt.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(vt.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(vt.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:t}=this;t&&(t.off(vt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(vt.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(vt.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(vt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(vt.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.off(vt.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(vt.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(vt.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(t,r){var n;this.media=r.media,((n=r.overrides)==null?void 0:n.cueRemoval)===!1&&(this.removeCues=!1)}onMediaAttached(){var t;const r=(t=this.hls)==null?void 0:t.latestLevelDetails;r&&this.updateDateRangeCues(r)}onMediaDetaching(t,r){this.media=null,!r.transferMedia&&(this.id3Track&&(this.removeCues&&wI(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(t){const r=this.getID3Track(t.textTracks);return r.mode="hidden",r}getID3Track(t){if(this.media){for(let r=0;r_V&&(m=_V),m-h<=0&&(m=h+PWs);for(let x=0;xh.type===s0.audioId3&&c:a==="video"?d=h=>h.type===s0.emsg&&o:d=h=>h.type===s0.audioId3&&c||h.type===s0.emsg&&o,fCe(i,r,n,d)}}onLevelUpdated(t,{details:r}){this.updateDateRangeCues(r,!0)}onLevelPtsUpdated(t,r){Math.abs(r.drift)>.01&&this.updateDateRangeCues(r.details)}updateDateRangeCues(t,r){if(!this.hls||!this.media)return;const{assetPlayerId:n,timelineOffset:a,enableDateRangeMetadataCues:i,interstitialsController:l}=this.hls.config;if(!i)return;const o=xCe();if(n&&a&&!l){const{fragmentStart:_,fragmentEnd:b}=t;let j=this.assetCue;j?(j.startTime=_,j.endTime=b):o&&(j=this.assetCue=s2e(o,_,b,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),j&&(j.id=n,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(j),j.addEventListener("enter",this.onEventCueEnter)))}if(!t.hasProgramDateTime)return;const{id3Track:c}=this,{dateRanges:d}=t,h=Object.keys(d);let m=this.dateRangeCuesAppended;if(c&&r){var p;if((p=c.cues)!=null&&p.length){const _=Object.keys(m).filter(b=>!h.includes(b));for(let b=_.length;b--;){var x;const j=_[b],k=(x=m[j])==null?void 0:x.cues;delete m[j],k&&Object.keys(k).forEach(T=>{const E=k[T];if(E){E.removeEventListener("enter",this.onEventCueEnter);try{c.removeCue(E)}catch{}}})}}else m=this.dateRangeCuesAppended={}}const y=t.fragments[t.fragments.length-1];if(!(h.length===0||!ka(y==null?void 0:y.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let _=0;_{if(Z!==j.id){const J=d[Z];if(J.class===j.class&&J.startDate>j.startDate&&(!ee||j.startDate.01&&(Z.startTime=k,Z.endTime=D);else if(o){let J=j.attr[ee];sVs(ee)&&(J=Fvt(J));const re=s2e(o,k,D,{key:ee,data:J},s0.dateRange);re&&(re.id=b,this.id3Track.addCue(re),E[ee]=re,l&&(ee==="X-ASSET-LIST"||ee==="X-ASSET-URL")&&re.addEventListener("enter",this.onEventCueEnter))}}m[b]={cues:E,dateRange:j,durationKnown:A}}}}}class DWs{constructor(t){this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{const{media:r}=this,n=this.levelDetails;if(!r||!n)return;this.currentTime=r.currentTime;const a=this.computeLatency();if(a===null)return;this._latency=a;const{lowLatencyMode:i,maxLiveSyncPlaybackRate:l}=this.config;if(!i||l===1||!n.live)return;const o=this.targetLatency;if(o===null)return;const c=a-o,d=Math.min(this.maxLatency,o+n.targetduration);if(c.05&&this.forwardBufferLength>1){const m=Math.min(2,Math.max(1,l)),p=Math.round(2/(1+Math.exp(-.75*c-this.edgeStalled))*20)/20,x=Math.min(m,Math.max(1,p));this.changeMediaPlaybackRate(r,x)}else r.playbackRate!==1&&r.playbackRate!==0&&this.changeMediaPlaybackRate(r,1)},this.hls=t,this.config=t.config,this.registerListeners()}get levelDetails(){var t;return((t=this.hls)==null?void 0:t.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){const{config:t}=this;if(t.liveMaxLatencyDuration!==void 0)return t.liveMaxLatencyDuration;const r=this.levelDetails;return r?t.liveMaxLatencyDurationCount*r.targetduration:0}get targetLatency(){const t=this.levelDetails;if(t===null||this.hls===null)return null;const{holdBack:r,partHoldBack:n,targetduration:a}=t,{liveSyncDuration:i,liveSyncDurationCount:l,lowLatencyMode:o}=this.config,c=this.hls.userConfig;let d=o&&n||r;(this._targetLatencyUpdated||c.liveSyncDuration||c.liveSyncDurationCount||d===0)&&(d=i!==void 0?i:l*a);const h=a;return d+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,h)}set targetLatency(t){this.stallCount=0,this.config.liveSyncDuration=t,this._targetLatencyUpdated=!0}get liveSyncPosition(){const t=this.estimateLiveEdge(),r=this.targetLatency;if(t===null||r===null)return null;const n=this.levelDetails;if(n===null)return null;const a=n.edge,i=t-r-this.edgeStalled,l=a-n.totalduration,o=a-(this.config.lowLatencyMode&&n.partTarget||n.targetduration);return Math.min(Math.max(l,i),o)}get drift(){const t=this.levelDetails;return t===null?1:t.drift}get edgeStalled(){const t=this.levelDetails;if(t===null)return 0;const r=(this.config.lowLatencyMode&&t.partTarget||t.targetduration)*3;return Math.max(t.age-r,0)}get forwardBufferLength(){const{media:t}=this,r=this.levelDetails;if(!t||!r)return 0;const n=t.buffered.length;return(n?t.buffered.end(n-1):r.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){const{hls:t}=this;t&&(t.on(vt.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(vt.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(vt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(vt.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(vt.ERROR,this.onError,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(vt.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(vt.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(vt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(vt.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(vt.ERROR,this.onError,this))}onMediaAttached(t,r){this.media=r.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(t,{details:r}){r.advanced&&this.onTimeupdate(),!r.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(t,r){var n;r.details===yr.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&(n=this.levelDetails)!=null&&n.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(t,r){var n,a;t.playbackRate!==r&&((n=this.hls)==null||n.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${(a=this.targetLatency)==null?void 0:a.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${t.playbackRate} to ${r}`),t.playbackRate=r)}estimateLiveEdge(){const t=this.levelDetails;return t===null?null:t.edge+t.age}computeLatency(){const t=this.estimateLiveEdge();return t===null?null:t-this.currentTime}}class RWs extends U6e{constructor(t,r){super(t,"level-controller"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=r,this._registerListeners()}_registerListeners(){const{hls:t}=this;t.on(vt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(vt.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(vt.LEVEL_LOADED,this.onLevelLoaded,this),t.on(vt.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(vt.FRAG_BUFFERED,this.onFragBuffered,this),t.on(vt.ERROR,this.onError,this)}_unregisterListeners(){const{hls:t}=this;t.off(vt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(vt.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(vt.LEVEL_LOADED,this.onLevelLoaded,this),t.off(vt.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(vt.FRAG_BUFFERED,this.onFragBuffered,this),t.off(vt.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(r=>{r.loadError=0,r.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(t,r){this.resetLevels()}onManifestLoaded(t,r){const n=this.hls.config.preferManagedMediaSource,a=[],i={},l={};let o=!1,c=!1,d=!1;r.levels.forEach(h=>{const m=h.attrs;let{audioCodec:p,videoCodec:x}=h;p&&(h.audioCodec=p=gpe(p,n)||void 0),x&&(x=h.videoCodec=yqs(x));const{width:y,height:_,unknownCodecs:b}=h,j=(b==null?void 0:b.length)||0;if(o||(o=!!(y&&_)),c||(c=!!x),d||(d=!!p),j||p&&!this.isAudioSupported(p)||x&&!this.isVideoSupported(x)){this.log(`Some or all CODECS not supported "${m.CODECS}"`);return}const{CODECS:k,"FRAME-RATE":T,"HDCP-LEVEL":E,"PATHWAY-ID":A,RESOLUTION:D,"VIDEO-RANGE":R}=m,O=`${`${A||"."}-`}${h.bitrate}-${D}-${T}-${k}-${R}-${E}`;if(i[O])if(i[O].uri!==h.url&&!h.attrs["PATHWAY-ID"]){const $=l[O]+=1;h.attrs["PATHWAY-ID"]=new Array($+1).join(".");const ee=this.createLevel(h);i[O]=ee,a.push(ee)}else i[O].addGroupId("audio",m.AUDIO),i[O].addGroupId("text",m.SUBTITLES);else{const $=this.createLevel(h);i[O]=$,l[O]=1,a.push($)}}),this.filterAndSortMediaOptions(a,r,o,c,d)}createLevel(t){const r=new _B(t),n=t.supplemental;if(n!=null&&n.videoCodec&&!this.isVideoSupported(n.videoCodec)){const a=new Error(`SUPPLEMENTAL-CODECS not supported "${n.videoCodec}"`);this.log(a.message),r.supportedResult=Zvt(a,[])}return r}isAudioSupported(t){return vB(t,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(t){return vB(t,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(t,r,n,a,i){var l;let o=[],c=[],d=t;const h=((l=r.stats)==null?void 0:l.parsing)||{};if((n||a)&&i&&(d=d.filter(({videoCodec:k,videoRange:T,width:E,height:A})=>(!!k||!!(E&&A))&&Tqs(T))),d.length===0){Promise.resolve().then(()=>{if(this.hls){let k="no level with compatible codecs found in manifest",T=k;r.levels.length&&(T=`one or more CODECS in variant not supported: ${Uc(r.levels.map(A=>A.attrs.CODECS).filter((A,D,R)=>R.indexOf(A)===D))}`,this.warn(T),k+=` (${T})`);const E=new Error(k);this.hls.trigger(vt.ERROR,{type:ci.MEDIA_ERROR,details:yr.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:r.url,error:E,reason:T})}}),h.end=performance.now();return}r.audioTracks&&(o=r.audioTracks.filter(k=>!k.audioCodec||this.isAudioSupported(k.audioCodec)),uYe(o)),r.subtitles&&(c=r.subtitles,uYe(c));const m=d.slice(0);d.sort((k,T)=>{if(k.attrs["HDCP-LEVEL"]!==T.attrs["HDCP-LEVEL"])return(k.attrs["HDCP-LEVEL"]||"")>(T.attrs["HDCP-LEVEL"]||"")?1:-1;if(n&&k.height!==T.height)return k.height-T.height;if(k.frameRate!==T.frameRate)return k.frameRate-T.frameRate;if(k.videoRange!==T.videoRange)return xpe.indexOf(k.videoRange)-xpe.indexOf(T.videoRange);if(k.videoCodec!==T.videoCodec){const E=sKe(k.videoCodec),A=sKe(T.videoCodec);if(E!==A)return A-E}if(k.uri===T.uri&&k.codecSet!==T.codecSet){const E=ppe(k.codecSet),A=ppe(T.codecSet);if(E!==A)return A-E}return k.averageBitrate!==T.averageBitrate?k.averageBitrate-T.averageBitrate:0});let p=m[0];if(this.steering&&(d=this.steering.filterParsedLevels(d),d.length!==m.length)){for(let k=0;kE&&E===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=A)}break}const y=i&&!a,_=this.hls.config,b=!!(_.audioStreamController&&_.audioTrackController),j={levels:d,audioTracks:o,subtitleTracks:c,sessionData:r.sessionData,sessionKeys:r.sessionKeys,firstLevel:this._firstLevel,stats:r.stats,audio:i,video:a,altAudio:b&&!y&&o.some(k=>!!k.url)};h.end=performance.now(),this.hls.trigger(vt.MANIFEST_PARSED,j)}get levels(){return this._levels.length===0?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(t){const r=this._levels;if(r.length===0)return;if(t<0||t>=r.length){const h=new Error("invalid level idx"),m=t<0;if(this.hls.trigger(vt.ERROR,{type:ci.OTHER_ERROR,details:yr.LEVEL_SWITCH_ERROR,level:t,fatal:m,error:h,reason:h.message}),m)return;t=Math.min(t,r.length-1)}const n=this.currentLevelIndex,a=this.currentLevel,i=a?a.attrs["PATHWAY-ID"]:void 0,l=r[t],o=l.attrs["PATHWAY-ID"];if(this.currentLevelIndex=t,this.currentLevel=l,n===t&&a&&i===o)return;this.log(`Switching to level ${t} (${l.height?l.height+"p ":""}${l.videoRange?l.videoRange+" ":""}${l.codecSet?l.codecSet+" ":""}@${l.bitrate})${o?" with Pathway "+o:""} from level ${n}${i?" with Pathway "+i:""}`);const c={level:t,attrs:l.attrs,details:l.details,bitrate:l.bitrate,averageBitrate:l.averageBitrate,maxBitrate:l.maxBitrate,realBitrate:l.realBitrate,width:l.width,height:l.height,codecSet:l.codecSet,audioCodec:l.audioCodec,videoCodec:l.videoCodec,audioGroups:l.audioGroups,subtitleGroups:l.subtitleGroups,loaded:l.loaded,loadError:l.loadError,fragmentError:l.fragmentError,name:l.name,id:l.id,uri:l.uri,url:l.url,urlId:0,audioGroupIds:l.audioGroupIds,textGroupIds:l.textGroupIds};this.hls.trigger(vt.LEVEL_SWITCHING,c);const d=l.details;if(!d||d.live){const h=this.switchParams(l.uri,a==null?void 0:a.details,d);this.loadPlaylist(h)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(t){this.manualLevelIndex=t,this._startLevel===void 0&&(this._startLevel=t),t!==-1&&(this.level=t)}get firstLevel(){return this._firstLevel}set firstLevel(t){this._firstLevel=t}get startLevel(){if(this._startLevel===void 0){const t=this.hls.config.startLevel;return t!==void 0?t:this.hls.firstAutoLevel}return this._startLevel}set startLevel(t){this._startLevel=t}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(t){if(this.steering){const r=this.steering.pathways(),n=t.filter(a=>r.indexOf(a)!==-1);if(t.length<1){this.warn(`pathwayPriority ${t} should contain at least one pathway from list: ${r}`);return}this.steering.pathwayPriority=n}}onError(t,r){r.fatal||!r.context||r.context.type===Vo.LEVEL&&r.context.level===this.level&&this.checkRetry(r)}onFragBuffered(t,{frag:r}){if(r!==void 0&&r.type===Ba.MAIN){const n=r.elementaryStreams;if(!Object.keys(n).some(i=>!!n[i]))return;const a=this._levels[r.level];a!=null&&a.loadError&&(this.log(`Resetting level error count of ${a.loadError} on frag buffered`),a.loadError=0)}}onLevelLoaded(t,r){var n;const{level:a,details:i}=r,l=r.levelInfo;if(!l){var o;this.warn(`Invalid level index ${a}`),(o=r.deliveryDirectives)!=null&&o.skip&&(i.deltaUpdateFailed=!0);return}if(l===this.currentLevel||r.withoutMultiVariant){l.fragmentError===0&&(l.loadError=0);let c=l.details;c===r.details&&c.advanced&&(c=void 0),this.playlistLoaded(a,r,c)}else(n=r.deliveryDirectives)!=null&&n.skip&&(i.deltaUpdateFailed=!0)}loadPlaylist(t){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,t)}loadingPlaylist(t,r){super.loadingPlaylist(t,r);const n=this.getUrlWithDirectives(t.uri,r),a=this.currentLevelIndex,i=t.attrs["PATHWAY-ID"],l=t.details,o=l==null?void 0:l.age;this.log(`Loading level index ${a}${(r==null?void 0:r.msn)!==void 0?" at sn "+r.msn+" part "+r.part:""}${i?" Pathway "+i:""}${o&&l.live?" age "+o.toFixed(1)+(l.type&&" "+l.type||""):""} ${n}`),this.hls.trigger(vt.LEVEL_LOADING,{url:n,level:a,levelInfo:t,pathwayId:t.attrs["PATHWAY-ID"],id:0,deliveryDirectives:r||null})}get nextLoadLevel(){return this.manualLevelIndex!==-1?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(t){this.level=t,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=t)}removeLevel(t){var r;if(this._levels.length===1)return;const n=this._levels.filter((i,l)=>l!==t?!0:(this.steering&&this.steering.removeLevel(i),i===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,i.details&&i.details.fragments.forEach(o=>o.level=-1)),!1));x1t(n),this._levels=n,this.currentLevelIndex>-1&&(r=this.currentLevel)!=null&&r.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);const a=n.length-1;this._firstLevel=Math.min(this._firstLevel,a),this._startLevel&&(this._startLevel=Math.min(this._startLevel,a)),this.hls.trigger(vt.LEVELS_UPDATED,{levels:n})}onLevelsUpdated(t,{levels:r}){this._levels=r}checkMaxAutoUpdated(){const{autoLevelCapping:t,maxAutoLevel:r,maxHdcpLevel:n}=this.hls;this._maxAutoLevel!==r&&(this._maxAutoLevel=r,this.hls.trigger(vt.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:t,levels:this.levels,maxAutoLevel:r,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:n}))}}function uYe(s){const t={};s.forEach(r=>{const n=r.groupId||"";r.id=t[n]=t[n]||0,t[n]++})}function hbt(){return self.SourceBuffer||self.WebKitSourceBuffer}function mbt(){if(!TS())return!1;const t=hbt();return!t||t.prototype&&typeof t.prototype.appendBuffer=="function"&&typeof t.prototype.remove=="function"}function OWs(){if(!mbt())return!1;const s=TS();return typeof(s==null?void 0:s.isTypeSupported)=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(t=>s.isTypeSupported(bB(t,"video")))||["mp4a.40.2","fLaC"].some(t=>s.isTypeSupported(bB(t,"audio"))))}function FWs(){var s;const t=hbt();return typeof(t==null||(s=t.prototype)==null?void 0:s.changeType)=="function"}const BWs=100;class zWs extends L6e{constructor(t,r,n){super(t,r,n,"stream-controller",Ba.MAIN),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=0,this.audioOnly=!1,this.fragPlaying=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{const a=this.media,i=a?a.currentTime:null;if(i===null||!ka(i)||(this.log(`Media seeked to ${i.toFixed(3)}`),!this.getBufferedFrag(i)))return;const l=this.getFwdBufferInfoAtPos(a,i,Ba.MAIN,0);if(l===null||l.len===0){this.warn(`Main forward buffer length at ${i} on "seeked" event ${l?l.len:"empty"})`);return}this.tick()},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:t}=this;t.on(vt.MANIFEST_PARSED,this.onManifestParsed,this),t.on(vt.LEVEL_LOADING,this.onLevelLoading,this),t.on(vt.LEVEL_LOADED,this.onLevelLoaded,this),t.on(vt.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.on(vt.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(vt.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.on(vt.BUFFER_CREATED,this.onBufferCreated,this),t.on(vt.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(vt.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(vt.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:t}=this;t.off(vt.MANIFEST_PARSED,this.onManifestParsed,this),t.off(vt.LEVEL_LOADED,this.onLevelLoaded,this),t.off(vt.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.off(vt.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(vt.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.off(vt.BUFFER_CREATED,this.onBufferCreated,this),t.off(vt.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(vt.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(vt.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(t,r){if(this.levels){const{lastCurrentTime:n,hls:a}=this;if(this.stopLoad(),this.setInterval(BWs),this.level=-1,!this.startFragRequested){let i=a.startLevel;i===-1&&(a.config.testBandwidth&&this.levels.length>1?(i=0,this.bitrateTest=!0):i=a.firstAutoLevel),a.nextLoadLevel=i,this.level=a.loadLevel,this._hasEnoughToStart=!!r}n>0&&t===-1&&!r&&(this.log(`Override startPosition with lastCurrentTime @${n.toFixed(3)}`),t=n),this.state=Qr.IDLE,this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=r?-1:t,this.tick()}else this._forceStartLoad=!0,this.state=Qr.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case Qr.WAITING_LEVEL:{const{levels:t,level:r}=this,n=t==null?void 0:t[r],a=n==null?void 0:n.details;if(a&&(!a.live||this.levelLastLoaded===n&&!this.waitForLive(n))){if(this.waitForCdnTuneIn(a))break;this.state=Qr.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=Qr.IDLE;break}break}case Qr.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}this.state===Qr.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var t;super.onTickEnd(),(t=this.media)!=null&&t.readyState&&this.media.seeking===!1&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){const{hls:t,levelLastLoaded:r,levels:n,media:a}=this;if(r===null||!a&&!this.primaryPrefetch&&(this.startFragRequested||!t.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;const i=this.buffering?t.nextLoadLevel:t.loadLevel;if(!(n!=null&&n[i]))return;const l=n[i],o=this.getMainFwdBufferInfo();if(o===null)return;const c=this.getLevelDetails();if(c&&this._streamEnded(o,c)){const _={};this.altAudio===2&&(_.type="video"),this.hls.trigger(vt.BUFFER_EOS,_),this.state=Qr.ENDED;return}if(!this.buffering)return;t.loadLevel!==i&&t.manualLevel===-1&&this.log(`Adapting to level ${i} from level ${this.level}`),this.level=t.nextLoadLevel=i;const d=l.details;if(!d||this.state===Qr.WAITING_LEVEL||this.waitForLive(l)){this.level=i,this.state=Qr.WAITING_LEVEL,this.startFragRequested=!1;return}const h=o.len,m=this.getMaxBufferLength(l.maxBitrate);if(h>=m)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=null);const p=this.backtrackFragment?this.backtrackFragment.start:o.end;let x=this.getNextFragment(p,d);if(this.couldBacktrack&&!this.fragPrevious&&x&&dh(x)&&this.fragmentTracker.getState(x)!==im.OK){var y;const b=((y=this.backtrackFragment)!=null?y:x).sn-d.startSN,j=d.fragments[b-1];j&&x.cc===j.cc&&(x=j,this.fragmentTracker.removeFragment(j))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=null);if(x&&this.isLoopLoading(x,p)){if(!x.gap){const b=this.audioOnly&&!this.altAudio?Dc.AUDIO:Dc.VIDEO,j=(b===Dc.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;j&&this.afterBufferFlushed(j,b,Ba.MAIN)}x=this.getNextFragmentLoopLoading(x,d,o,Ba.MAIN,m)}x&&(this.exceedsMaxBuffer(o,m,x)||(x.initSegment&&!x.initSegment.data&&!this.bitrateTest&&(x=x.initSegment),this.loadFragment(x,l,p)))}loadFragment(t,r,n){const a=this.fragmentTracker.getState(t);a===im.NOT_LOADED||a===im.PARTIAL?dh(t)?this.bitrateTest?(this.log(`Fragment ${t.sn} of level ${t.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(t,r)):super.loadFragment(t,r,n):this._loadInitSegment(t,r):this.clearTrackerIfNeeded(t)}getBufferedFrag(t){return this.fragmentTracker.getBufferedFrag(t,Ba.MAIN)}followingBufferedFrag(t){return t?this.getBufferedFrag(t.end+.5):null}immediateLevelSwitch(){if(this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY),this.altAudio!==0){var t;(((t=this.getLevelDetails())==null?void 0:t.fragmentStart)||0)>this.lastCurrentTime&&super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio")}}nextLevelSwitch(){const{levels:t,media:r}=this;if(r!=null&&r.readyState){let n;const a=this.getAppendedFrag(r.currentTime);a&&a.start>1&&this.flushMainBuffer(0,a.start-1);const i=this.getLevelDetails();if(i!=null&&i.live){const o=this.getMainFwdBufferInfo();if(!o||o.len=l-r.maxFragLookUpTolerance&&i<=o;if(a!==null&&n.duration>a&&(i{this.hls&&this.hls.trigger(vt.AUDIO_TRACK_SWITCHED,r)}),n.trigger(vt.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}n.trigger(vt.AUDIO_TRACK_SWITCHED,r)}}onAudioTrackSwitched(t,r){const n=ype(r.url,this.hls);if(n){const a=this.videoBuffer;a&&this.mediaBuffer!==a&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=a)}this.altAudio=n?2:0,this.tick()}onBufferCreated(t,r){const n=r.tracks;let a,i,l=!1;for(const o in n){const c=n[o];if(c.id==="main"){if(i=o,a=c,o==="video"){const d=n[o];d&&(this.videoBuffer=d.buffer)}}else l=!0}l&&a?(this.log(`Alternate track found, use ${i}.buffered to schedule main fragment loading`),this.mediaBuffer=a.buffer):this.mediaBuffer=this.media}onFragBuffered(t,r){const{frag:n,part:a}=r,i=n.type===Ba.MAIN;if(i){if(this.fragContextChanged(n)){this.warn(`Fragment ${n.sn}${a?" p: "+a.index:""} of level ${n.level} finished buffering, but was aborted. state: ${this.state}`),this.state===Qr.PARSED&&(this.state=Qr.IDLE);return}const o=a?a.stats:n.stats;this.fragLastKbps=Math.round(8*o.total/(o.buffering.end-o.loading.first)),dh(n)&&(this.fragPrevious=n),this.fragBufferedComplete(n,a)}const l=this.media;l&&(!this._hasEnoughToStart&&mo.getBuffered(l).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),i&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(t,r){var n;if(r.fatal){this.state=Qr.ERROR;return}switch(r.details){case yr.FRAG_GAP:case yr.FRAG_PARSING_ERROR:case yr.FRAG_DECRYPT_ERROR:case yr.FRAG_LOAD_ERROR:case yr.FRAG_LOAD_TIMEOUT:case yr.KEY_LOAD_ERROR:case yr.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Ba.MAIN,r);break;case yr.LEVEL_LOAD_ERROR:case yr.LEVEL_LOAD_TIMEOUT:case yr.LEVEL_PARSING_ERROR:!r.levelRetry&&this.state===Qr.WAITING_LEVEL&&((n=r.context)==null?void 0:n.type)===Vo.LEVEL&&(this.state=Qr.IDLE);break;case yr.BUFFER_ADD_CODEC_ERROR:case yr.BUFFER_APPEND_ERROR:if(r.parent!=="main")return;this.reduceLengthAndFlushBuffer(r)&&this.resetLoadingState();break;case yr.BUFFER_FULL_ERROR:if(r.parent!=="main")return;this.reduceLengthAndFlushBuffer(r)&&(!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY));break;case yr.INTERNAL_EXCEPTION:this.recoverWorkerError(r);break}}onFragLoadEmergencyAborted(){this.state=Qr.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(t,{type:r}){if(r!==Dc.AUDIO||!this.altAudio){const n=(r===Dc.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;n&&(this.afterBufferFlushed(n,r,Ba.MAIN),this.tick())}}onLevelsUpdated(t,r){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,this.level===-1&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=r.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:t}=this;if(!t)return;const r=t.currentTime;let n=this.startPosition;if(n>=0&&r0&&(c{const{hls:a}=this,i=n==null?void 0:n.frag;if(!i||this.fragContextChanged(i))return;r.fragmentError=0,this.state=Qr.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const l=i.stats;l.parsing.start=l.parsing.end=l.buffering.start=l.buffering.end=self.performance.now(),a.trigger(vt.FRAG_LOADED,n),i.bitrateTest=!1}).catch(n=>{this.state===Qr.STOPPED||this.state===Qr.ERROR||(this.warn(n),this.resetFragmentLoading(t))})}_handleTransmuxComplete(t){const r=this.playlistType,{hls:n}=this,{remuxResult:a,chunkMeta:i}=t,l=this.getCurrentContext(i);if(!l){this.resetWhenMissingContext(i);return}const{frag:o,part:c,level:d}=l,{video:h,text:m,id3:p,initSegment:x}=a,{details:y}=d,_=this.altAudio?void 0:a.audio;if(this.fragContextChanged(o)){this.fragmentTracker.removeFragment(o);return}if(this.state=Qr.PARSING,x){const b=x.tracks;if(b){const E=o.initSegment||o;if(this.unhandledEncryptionError(x,o))return;this._bufferInitSegment(d,b,E,i),n.trigger(vt.FRAG_PARSING_INIT_SEGMENT,{frag:E,id:r,tracks:b})}const j=x.initPTS,k=x.timescale,T=this.initPTS[o.cc];if(ka(j)&&(!T||T.baseTime!==j||T.timescale!==k)){const E=x.trackId;this.initPTS[o.cc]={baseTime:j,timescale:k,trackId:E},n.trigger(vt.INIT_PTS_FOUND,{frag:o,id:r,initPTS:j,timescale:k,trackId:E})}}if(h&&y){_&&h.type==="audiovideo"&&this.logMuxedErr(o);const b=y.fragments[o.sn-1-y.startSN],j=o.sn===y.startSN,k=!b||o.cc>b.cc;if(a.independent!==!1){const{startPTS:T,endPTS:E,startDTS:A,endDTS:D}=h;if(c)c.elementaryStreams[h.type]={startPTS:T,endPTS:E,startDTS:A,endDTS:D};else if(h.firstKeyFrame&&h.independent&&i.id===1&&!k&&(this.couldBacktrack=!0),h.dropped&&h.independent){const R=this.getMainFwdBufferInfo(),z=(R?R.end:this.getLoadPosition())+this.config.maxBufferHole,O=h.firstKeyFramePTS?h.firstKeyFramePTS:T;if(!j&&zGue&&(o.gap=!0);o.setElementaryStreamInfo(h.type,T,E,A,D),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(h,o,c,i,j||k)}else if(j||k)o.gap=!0;else{this.backtrack(o);return}}if(_){const{startPTS:b,endPTS:j,startDTS:k,endDTS:T}=_;c&&(c.elementaryStreams[Dc.AUDIO]={startPTS:b,endPTS:j,startDTS:k,endDTS:T}),o.setElementaryStreamInfo(Dc.AUDIO,b,j,k,T),this.bufferFragmentData(_,o,c,i)}if(y&&p!=null&&p.samples.length){const b={id:r,frag:o,details:y,samples:p.samples};n.trigger(vt.FRAG_PARSING_METADATA,b)}if(y&&m){const b={id:r,frag:o,details:y,samples:m.samples};n.trigger(vt.FRAG_PARSING_USERDATA,b)}}logMuxedErr(t){this.warn(`${dh(t)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${t.url}`)}_bufferInitSegment(t,r,n,a){if(this.state!==Qr.PARSING)return;this.audioOnly=!!r.audio&&!r.video,this.altAudio&&!this.audioOnly&&(delete r.audio,r.audiovideo&&this.logMuxedErr(n));const{audio:i,video:l,audiovideo:o}=r;if(i){const d=t.audioCodec;let h=Bue(i.codec,d);h==="mp4a"&&(h="mp4a.40.5");const m=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){h&&(h.indexOf("mp4a.40.5")!==-1?h="mp4a.40.2":h="mp4a.40.5");const p=i.metadata;p&&"channelCount"in p&&(p.channelCount||1)!==1&&m.indexOf("firefox")===-1&&(h="mp4a.40.5")}h&&h.indexOf("mp4a.40.5")!==-1&&m.indexOf("android")!==-1&&i.container!=="audio/mpeg"&&(h="mp4a.40.2",this.log(`Android: force audio codec to ${h}`)),d&&d!==h&&this.log(`Swapping manifest audio codec "${d}" for "${h}"`),i.levelCodec=h,i.id=Ba.MAIN,this.log(`Init audio buffer, container:${i.container}, codecs[selected/level/parsed]=[${h||""}/${d||""}/${i.codec}]`),delete r.audiovideo}if(l){l.levelCodec=t.videoCodec,l.id=Ba.MAIN;const d=l.codec;if((d==null?void 0:d.length)===4)switch(d){case"hvc1":case"hev1":l.codec="hvc1.1.6.L120.90";break;case"av01":l.codec="av01.0.04M.08";break;case"avc1":l.codec="avc1.42e01e";break}this.log(`Init video buffer, container:${l.container}, codecs[level/parsed]=[${t.videoCodec||""}/${d}]${l.codec!==d?" parsed-corrected="+l.codec:""}${l.supplemental?" supplemental="+l.supplemental:""}`),delete r.audiovideo}o&&(this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${t.codecs}/${o.codec}]`),delete r.video,delete r.audio);const c=Object.keys(r);if(c.length){if(this.hls.trigger(vt.BUFFER_CODECS,r),!this.hls)return;c.forEach(d=>{const m=r[d].initSegment;m!=null&&m.byteLength&&this.hls.trigger(vt.BUFFER_APPENDING,{type:d,data:m,frag:n,part:null,chunkMeta:a,parent:n.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const t=this.mediaBuffer&&this.altAudio===2?this.mediaBuffer:this.media;return this.getFwdBufferInfo(t,Ba.MAIN)}get maxBufferLength(){const{levels:t,level:r}=this,n=t==null?void 0:t[r];return n?this.getMaxBufferLength(n.maxBitrate):this.config.maxBufferLength}backtrack(t){this.couldBacktrack=!0,this.backtrackFragment=t,this.resetTransmuxer(),this.flushBufferGap(t),this.fragmentTracker.removeFragment(t),this.fragPrevious=null,this.nextLoadPosition=t.start,this.state=Qr.IDLE}checkFragmentChanged(){const t=this.media;let r=null;if(t&&t.readyState>1&&t.seeking===!1){const n=t.currentTime;if(mo.isBuffered(t,n)?r=this.getAppendedFrag(n):mo.isBuffered(t,n+.1)&&(r=this.getAppendedFrag(n+.1)),r){this.backtrackFragment=null;const a=this.fragPlaying,i=r.level;(!a||r.sn!==a.sn||a.level!==i)&&(this.fragPlaying=r,this.hls.trigger(vt.FRAG_CHANGED,{frag:r}),(!a||a.level!==i)&&this.hls.trigger(vt.LEVEL_SWITCHED,{level:i}))}}}get nextLevel(){const t=this.nextBufferedFrag;return t?t.level:-1}get currentFrag(){var t;if(this.fragPlaying)return this.fragPlaying;const r=((t=this.media)==null?void 0:t.currentTime)||this.lastCurrentTime;return ka(r)?this.getAppendedFrag(r):null}get currentProgramDateTime(){var t;const r=((t=this.media)==null?void 0:t.currentTime)||this.lastCurrentTime;if(ka(r)){const n=this.getLevelDetails(),a=this.currentFrag||(n?OA(null,n.fragments,r):null);if(a){const i=a.programDateTime;if(i!==null){const l=i+(r-a.start)*1e3;return new Date(l)}}}return null}get currentLevel(){const t=this.currentFrag;return t?t.level:-1}get nextBufferedFrag(){const t=this.currentFrag;return t?this.followingBufferedFrag(t):null}get forceStartLoad(){return this._forceStartLoad}}class $Ws extends dv{constructor(t,r){super("key-loader",r),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=t}abort(t){for(const n in this.keyIdToKeyInfo){const a=this.keyIdToKeyInfo[n].loader;if(a){var r;if(t&&t!==((r=a.context)==null?void 0:r.frag.type))return;a.abort()}}}detach(){for(const t in this.keyIdToKeyInfo){const r=this.keyIdToKeyInfo[t];(r.mediaKeySessionContext||r.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[t]}}destroy(){this.detach();for(const t in this.keyIdToKeyInfo){const r=this.keyIdToKeyInfo[t].loader;r&&r.destroy()}this.keyIdToKeyInfo={}}createKeyLoadError(t,r=yr.KEY_LOAD_ERROR,n,a,i){return new g2({type:ci.NETWORK_ERROR,details:r,fatal:!1,frag:t,response:i,error:n,networkDetails:a})}loadClear(t,r,n){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(r.length)for(let a=0,i=r.length;a{if(!this.emeController)return;l.setKeyFormat(o);const c=$ue(o);if(c)return this.emeController.getKeySystemAccess([c])})}if(this.config.requireKeySystemAccessOnStart){const a=LO(this.config);if(a.length)return this.emeController.getKeySystemAccess(a)}}return null}load(t){return!t.decryptdata&&t.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(t).then(r=>this.loadInternal(t,r)):this.loadInternal(t)}loadInternal(t,r){var n,a;r&&t.setKeyFormat(r);const i=t.decryptdata;if(!i){const d=new Error(r?`Expected frag.decryptdata to be defined after setting format ${r}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(this.createKeyLoadError(t,yr.KEY_LOAD_ERROR,d))}const l=i.uri;if(!l)return Promise.reject(this.createKeyLoadError(t,yr.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${l}"`)));const o=r2e(i);let c=this.keyIdToKeyInfo[o];if((n=c)!=null&&n.decryptdata.key)return i.key=c.decryptdata.key,Promise.resolve({frag:t,keyInfo:c});if(this.emeController&&(a=c)!=null&&a.keyLoadPromise)switch(this.emeController.getKeyStatus(c.decryptdata)){case"usable":case"usable-in-future":return c.keyLoadPromise.then(h=>{const{keyInfo:m}=h;return i.key=m.decryptdata.key,{frag:t,keyInfo:m}})}switch(this.log(`${this.keyIdToKeyInfo[o]?"Rel":"L"}oading${i.keyId?" keyId: "+Pf(i.keyId):""} URI: ${i.uri} from ${t.type} ${t.level}`),c=this.keyIdToKeyInfo[o]={decryptdata:i,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},i.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return i.keyFormat==="identity"?this.loadKeyHTTP(c,t):this.loadKeyEME(c,t);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(c,t);default:return Promise.reject(this.createKeyLoadError(t,yr.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${i.method}"`)))}}loadKeyEME(t,r){const n={frag:r,keyInfo:t};if(this.emeController&&this.config.emeEnabled){var a;if(!t.decryptdata.keyId&&(a=r.initSegment)!=null&&a.data){const l=iqs(r.initSegment.data);if(l.length){let o=l[0];o.some(c=>c!==0)?(this.log(`Using keyId found in init segment ${Pf(o)}`),dS.setKeyIdForUri(t.decryptdata.uri,o)):(o=dS.addKeyIdForUri(t.decryptdata.uri),this.log(`Generating keyId to patch media ${Pf(o)}`)),t.decryptdata.keyId=o}}if(!t.decryptdata.keyId&&!dh(r))return Promise.resolve(n);const i=this.emeController.loadKey(n);return(t.keyLoadPromise=i.then(l=>(t.mediaKeySessionContext=l,n))).catch(l=>{throw t.keyLoadPromise=null,"data"in l&&(l.data.frag=r),l})}return Promise.resolve(n)}loadKeyHTTP(t,r){const n=this.config,a=n.loader,i=new a(n);return r.keyLoader=t.loader=i,t.keyLoadPromise=new Promise((l,o)=>{const c={keyInfo:t,frag:r,responseType:"arraybuffer",url:t.decryptdata.uri},d=n.keyLoadPolicy.default,h={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},m={onSuccess:(p,x,y,_)=>{const{frag:b,keyInfo:j}=y,k=r2e(j.decryptdata);if(!b.decryptdata||j!==this.keyIdToKeyInfo[k])return o(this.createKeyLoadError(b,yr.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),_));j.decryptdata.key=b.decryptdata.key=new Uint8Array(p.data),b.keyLoader=null,j.loader=null,l({frag:b,keyInfo:j})},onError:(p,x,y,_)=>{this.resetLoader(x),o(this.createKeyLoadError(r,yr.KEY_LOAD_ERROR,new Error(`HTTP Error ${p.code} loading key ${p.text}`),y,hc({url:c.url,data:void 0},p)))},onTimeout:(p,x,y)=>{this.resetLoader(x),o(this.createKeyLoadError(r,yr.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),y))},onAbort:(p,x,y)=>{this.resetLoader(x),o(this.createKeyLoadError(r,yr.INTERNAL_ABORTED,new Error("key loading aborted"),y))}};i.load(c,h,m)})}resetLoader(t){const{frag:r,keyInfo:n,url:a}=t,i=n.loader;r.keyLoader===i&&(r.keyLoader=null,n.loader=null);const l=r2e(n.decryptdata)||a;delete this.keyIdToKeyInfo[l],i&&i.destroy()}}function r2e(s){if(s.keyFormat!==Rf.FAIRPLAY){const t=s.keyId;if(t)return Pf(t)}return s.uri}function hYe(s){const{type:t}=s;switch(t){case Vo.AUDIO_TRACK:return Ba.AUDIO;case Vo.SUBTITLE_TRACK:return Ba.SUBTITLE;default:return Ba.MAIN}}function n2e(s,t){let r=s.url;return(r===void 0||r.indexOf("data:")===0)&&(r=t.url),r}class UWs{constructor(t){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=t,this.registerListeners()}startLoad(t){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:t}=this;t.on(vt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(vt.LEVEL_LOADING,this.onLevelLoading,this),t.on(vt.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.on(vt.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.on(vt.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:t}=this;t.off(vt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(vt.LEVEL_LOADING,this.onLevelLoading,this),t.off(vt.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.off(vt.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.off(vt.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(t){const r=this.hls.config,n=r.pLoader,a=r.loader,i=n||a,l=new i(r);return this.loaders[t.type]=l,l}getInternalLoader(t){return this.loaders[t.type]}resetInternalLoader(t){this.loaders[t]&&delete this.loaders[t]}destroyInternalLoaders(){for(const t in this.loaders){const r=this.loaders[t];r&&r.destroy(),this.resetInternalLoader(t)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(t,r){const{url:n}=r;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:Vo.MANIFEST,url:n,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(t,r){const{id:n,level:a,pathwayId:i,url:l,deliveryDirectives:o,levelInfo:c}=r;this.load({id:n,level:a,pathwayId:i,responseType:"text",type:Vo.LEVEL,url:l,deliveryDirectives:o,levelOrTrack:c})}onAudioTrackLoading(t,r){const{id:n,groupId:a,url:i,deliveryDirectives:l,track:o}=r;this.load({id:n,groupId:a,level:null,responseType:"text",type:Vo.AUDIO_TRACK,url:i,deliveryDirectives:l,levelOrTrack:o})}onSubtitleTrackLoading(t,r){const{id:n,groupId:a,url:i,deliveryDirectives:l,track:o}=r;this.load({id:n,groupId:a,level:null,responseType:"text",type:Vo.SUBTITLE_TRACK,url:i,deliveryDirectives:l,levelOrTrack:o})}onLevelsUpdated(t,r){const n=this.loaders[Vo.LEVEL];if(n){const a=n.context;a&&!r.levels.some(i=>i===a.levelOrTrack)&&(n.abort(),delete this.loaders[Vo.LEVEL])}}load(t){var r;const n=this.hls.config;let a=this.getInternalLoader(t);if(a){const d=this.hls.logger,h=a.context;if(h&&h.levelOrTrack===t.levelOrTrack&&(h.url===t.url||h.deliveryDirectives&&!t.deliveryDirectives)){h.url===t.url?d.log(`[playlist-loader]: ignore ${t.url} ongoing request`):d.log(`[playlist-loader]: ignore ${t.url} in favor of ${h.url}`);return}d.log(`[playlist-loader]: aborting previous loader for type: ${t.type}`),a.abort()}let i;if(t.type===Vo.MANIFEST?i=n.manifestLoadPolicy.default:i=Ec({},n.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),a=this.createInternalLoader(t),ka((r=t.deliveryDirectives)==null?void 0:r.part)){let d;if(t.type===Vo.LEVEL&&t.level!==null?d=this.hls.levels[t.level].details:t.type===Vo.AUDIO_TRACK&&t.id!==null?d=this.hls.audioTracks[t.id].details:t.type===Vo.SUBTITLE_TRACK&&t.id!==null&&(d=this.hls.subtitleTracks[t.id].details),d){const h=d.partTarget,m=d.targetduration;if(h&&m){const p=Math.max(h*3,m*.8)*1e3;i=Ec({},i,{maxTimeToFirstByteMs:Math.min(p,i.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(p,i.maxTimeToFirstByteMs)})}}}const l=i.errorRetry||i.timeoutRetry||{},o={loadPolicy:i,timeout:i.maxLoadTimeMs,maxRetry:l.maxNumRetry||0,retryDelay:l.retryDelayMs||0,maxRetryDelay:l.maxRetryDelayMs||0},c={onSuccess:(d,h,m,p)=>{const x=this.getInternalLoader(m);this.resetInternalLoader(m.type);const y=d.data;h.parsing.start=performance.now(),l_.isMediaPlaylist(y)||m.type!==Vo.MANIFEST?this.handleTrackOrLevelPlaylist(d,h,m,p||null,x):this.handleMasterPlaylist(d,h,m,p)},onError:(d,h,m,p)=>{this.handleNetworkError(h,m,!1,d,p)},onTimeout:(d,h,m)=>{this.handleNetworkError(h,m,!0,void 0,d)}};a.load(t,o,c)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:t,startPosition:r},forceStartLoad:n}=this.hls;(t||n)&&(this.hls.logger.log(`${t?"auto":"force"} startLoad with configured startPosition ${r}`),this.hls.startLoad(r))}handleMasterPlaylist(t,r,n,a){const i=this.hls,l=t.data,o=n2e(t,n),c=l_.parseMasterPlaylist(l,o);if(c.playlistParsingError){r.parsing.end=performance.now(),this.handleManifestParsingError(t,n,c.playlistParsingError,a,r);return}const{contentSteering:d,levels:h,sessionData:m,sessionKeys:p,startTimeOffset:x,variableList:y}=c;this.variableList=y,h.forEach(k=>{const{unknownCodecs:T}=k;if(T){const{preferManagedMediaSource:E}=this.hls.config;let{audioCodec:A,videoCodec:D}=k;for(let R=T.length;R--;){const z=T[R];vB(z,"audio",E)?(k.audioCodec=A=A?`${A},${z}`:z,XL.audio[A.substring(0,4)]=2,T.splice(R,1)):vB(z,"video",E)&&(k.videoCodec=D=D?`${D},${z}`:z,XL.video[D.substring(0,4)]=2,T.splice(R,1))}}});const{AUDIO:_=[],SUBTITLES:b,"CLOSED-CAPTIONS":j}=l_.parseMasterPlaylistMedia(l,o,c);_.length&&!_.some(T=>!T.url)&&h[0].audioCodec&&!h[0].attrs.AUDIO&&(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),_.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new au({}),bitrate:0,url:""})),i.trigger(vt.MANIFEST_LOADED,{levels:h,audioTracks:_,subtitles:b,captions:j,contentSteering:d,url:o,stats:r,networkDetails:a,sessionData:m,sessionKeys:p,startTimeOffset:x,variableList:y})}handleTrackOrLevelPlaylist(t,r,n,a,i){const l=this.hls,{id:o,level:c,type:d}=n,h=n2e(t,n),m=ka(c)?c:ka(o)?o:0,p=hYe(n),x=l_.parseLevelPlaylist(t.data,h,m,p,0,this.variableList);if(d===Vo.MANIFEST){const y={attrs:new au({}),bitrate:0,details:x,name:"",url:h};x.requestScheduled=r.loading.start+f1t(x,0),l.trigger(vt.MANIFEST_LOADED,{levels:[y],audioTracks:[],url:h,stats:r,networkDetails:a,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}r.parsing.end=performance.now(),n.levelDetails=x,this.handlePlaylistLoaded(x,t,r,n,a,i)}handleManifestParsingError(t,r,n,a,i){this.hls.trigger(vt.ERROR,{type:ci.NETWORK_ERROR,details:yr.MANIFEST_PARSING_ERROR,fatal:r.type===Vo.MANIFEST,url:t.url,err:n,error:n,reason:n.message,response:t,context:r,networkDetails:a,stats:i})}handleNetworkError(t,r,n=!1,a,i){let l=`A network ${n?"timeout":"error"+(a?" (status "+a.code+")":"")} occurred while loading ${t.type}`;t.type===Vo.LEVEL?l+=`: ${t.level} id: ${t.id}`:(t.type===Vo.AUDIO_TRACK||t.type===Vo.SUBTITLE_TRACK)&&(l+=` id: ${t.id} group-id: "${t.groupId}"`);const o=new Error(l);this.hls.logger.warn(`[playlist-loader]: ${l}`);let c=yr.UNKNOWN,d=!1;const h=this.getInternalLoader(t);switch(t.type){case Vo.MANIFEST:c=n?yr.MANIFEST_LOAD_TIMEOUT:yr.MANIFEST_LOAD_ERROR,d=!0;break;case Vo.LEVEL:c=n?yr.LEVEL_LOAD_TIMEOUT:yr.LEVEL_LOAD_ERROR,d=!1;break;case Vo.AUDIO_TRACK:c=n?yr.AUDIO_TRACK_LOAD_TIMEOUT:yr.AUDIO_TRACK_LOAD_ERROR,d=!1;break;case Vo.SUBTITLE_TRACK:c=n?yr.SUBTITLE_TRACK_LOAD_TIMEOUT:yr.SUBTITLE_LOAD_ERROR,d=!1;break}h&&this.resetInternalLoader(t.type);const m={type:ci.NETWORK_ERROR,details:c,fatal:d,url:t.url,loader:h,context:t,error:o,networkDetails:r,stats:i};if(a){const p=(r==null?void 0:r.url)||t.url;m.response=hc({url:p,data:void 0},a)}this.hls.trigger(vt.ERROR,m)}handlePlaylistLoaded(t,r,n,a,i,l){const o=this.hls,{type:c,level:d,levelOrTrack:h,id:m,groupId:p,deliveryDirectives:x}=a,y=n2e(r,a),_=hYe(a);let b=typeof a.level=="number"&&_===Ba.MAIN?d:void 0;const j=t.playlistParsingError;if(j){if(this.hls.logger.warn(`${j} ${t.url}`),!o.config.ignorePlaylistParsingErrors){o.trigger(vt.ERROR,{type:ci.NETWORK_ERROR,details:yr.LEVEL_PARSING_ERROR,fatal:!1,url:y,error:j,reason:j.message,response:r,context:a,level:b,parent:_,networkDetails:i,stats:n});return}t.playlistParsingError=null}if(!t.fragments.length){const k=t.playlistParsingError=new Error("No Segments found in Playlist");o.trigger(vt.ERROR,{type:ci.NETWORK_ERROR,details:yr.LEVEL_EMPTY_ERROR,fatal:!1,url:y,error:k,reason:k.message,response:r,context:a,level:b,parent:_,networkDetails:i,stats:n});return}switch(t.live&&l&&(l.getCacheAge&&(t.ageHeader=l.getCacheAge()||0),(!l.getCacheAge||isNaN(t.ageHeader))&&(t.ageHeader=0)),c){case Vo.MANIFEST:case Vo.LEVEL:if(b){if(!h)b=0;else if(h!==o.levels[b]){const k=o.levels.indexOf(h);k>-1&&(b=k)}}o.trigger(vt.LEVEL_LOADED,{details:t,levelInfo:h||o.levels[0],level:b||0,id:m||0,stats:n,networkDetails:i,deliveryDirectives:x,withoutMultiVariant:c===Vo.MANIFEST});break;case Vo.AUDIO_TRACK:o.trigger(vt.AUDIO_TRACK_LOADED,{details:t,track:h,id:m||0,groupId:p||"",stats:n,networkDetails:i,deliveryDirectives:x});break;case Vo.SUBTITLE_TRACK:o.trigger(vt.SUBTITLE_TRACK_LOADED,{details:t,track:h,id:m||0,groupId:p||"",stats:n,networkDetails:i,deliveryDirectives:x});break}}}class e_{static get version(){return wB}static isMSESupported(){return mbt()}static isSupported(){return OWs()}static getMediaSource(){return TS()}static get Events(){return vt}static get MetadataSchema(){return s0}static get ErrorTypes(){return ci}static get ErrorDetails(){return yr}static get DefaultConfig(){return e_.defaultConfig?e_.defaultConfig:kWs}static set DefaultConfig(t){e_.defaultConfig=t}constructor(t={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new D6e,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._url=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;const r=this.logger=KUs(t.debug||!1,"Hls instance",t.assetPlayerId),n=this.config=CWs(e_.DefaultConfig,t,r);this.userConfig=t,n.progressive&&TWs(n,r);const{abrController:a,bufferController:i,capLevelController:l,errorController:o,fpsController:c}=n,d=new o(this),h=this.abrController=new a(this),m=new qqs(this),p=n.interstitialsController,x=p?this.interstitialsController=new p(this,e_):null,y=this.bufferController=new i(this,m),_=this.capLevelController=new l(this),b=new c(this),j=new UWs(this),k=n.contentSteeringController,T=k?new k(this):null,E=this.levelController=new RWs(this,T),A=new LWs(this),D=new $Ws(this.config,this.logger),R=this.streamController=new zWs(this,m,D),z=this.gapController=new IWs(this,m);_.setStreamController(R),b.setStreamController(R);const O=[j,E,R];x&&O.splice(1,0,x),T&&O.splice(1,0,T),this.networkControllers=O;const $=[h,y,z,_,b,A,m];this.audioTrackController=this.createController(n.audioTrackController,O);const ee=n.audioStreamController;ee&&O.push(this.audioStreamController=new ee(this,m,D)),this.subtitleTrackController=this.createController(n.subtitleTrackController,O);const Z=n.subtitleStreamController;Z&&O.push(this.subtititleStreamController=new Z(this,m,D)),this.createController(n.timelineController,$),D.emeController=this.emeController=this.createController(n.emeController,$),this.cmcdController=this.createController(n.cmcdController,$),this.latencyController=this.createController(DWs,$),this.coreComponents=$,O.push(d);const J=d.onErrorOut;typeof J=="function"&&this.on(vt.ERROR,J,d),this.on(vt.MANIFEST_LOADED,j.onManifestLoaded,j)}createController(t,r){if(t){const n=new t(this);return r&&r.push(n),n}return null}on(t,r,n=this){this._emitter.on(t,r,n)}once(t,r,n=this){this._emitter.once(t,r,n)}removeAllListeners(t){this._emitter.removeAllListeners(t)}off(t,r,n=this,a){this._emitter.off(t,r,n,a)}listeners(t){return this._emitter.listeners(t)}emit(t,r,n){return this._emitter.emit(t,r,n)}trigger(t,r){if(this.config.debug)return this.emit(t,t,r);try{return this.emit(t,t,r)}catch(n){if(this.logger.error("An internal error happened while handling event "+t+'. Error message: "'+n.message+'". Here is a stacktrace:',n),!this.triggeringException){this.triggeringException=!0;const a=t===vt.ERROR;this.trigger(vt.ERROR,{type:ci.OTHER_ERROR,details:yr.INTERNAL_EXCEPTION,fatal:a,event:t,error:n}),this.triggeringException=!1}}return!1}listenerCount(t){return this._emitter.listenerCount(t)}destroy(){this.logger.log("destroy"),this.trigger(vt.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(r=>r.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(r=>r.destroy()),this.coreComponents.length=0;const t=this.config;t.xhrSetup=t.fetchSetup=void 0,this.userConfig=null}attachMedia(t){if(!t||"media"in t&&!t.media){const i=new Error(`attachMedia failed: invalid argument (${t})`);this.trigger(vt.ERROR,{type:ci.OTHER_ERROR,details:yr.ATTACH_MEDIA_ERROR,fatal:!0,error:i});return}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());const r="media"in t,n=r?t.media:t,a=r?t:{media:n};this._media=n,this.trigger(vt.MEDIA_ATTACHING,a)}detachMedia(){this.logger.log("detachMedia"),this.trigger(vt.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const t=this.bufferController.transferMedia();return this.trigger(vt.MEDIA_DETACHING,{transferMedia:t}),t}loadSource(t){this.stopLoad();const r=this.media,n=this._url,a=this._url=N6e.buildAbsoluteURL(self.location.href,t,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${a}`),r&&n&&(n!==a||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(r)),this.trigger(vt.MANIFEST_LOADING,{url:t})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(t=-1,r){this.logger.log(`startLoad(${t+(r?", ":"")})`),this.started=!0,this.resumeBuffering();for(let n=0;n{t.resumeBuffering&&t.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(t=>{t.pauseBuffering&&t.pauseBuffering()}))}get inFlightFragments(){const t={[Ba.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(t[Ba.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(t[Ba.SUBTITLE]=this.subtititleStreamController.inFlightFrag),t}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const t=this._media,r=t==null?void 0:t.currentTime;this.detachMedia(),t&&(this.attachMedia(t),r&&this.startLoad(r))}removeLevel(t){this.levelController.removeLevel(t)}get sessionId(){let t=this._sessionId;return t||(t=this._sessionId=IGs()),t}get levels(){const t=this.levelController.levels;return t||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(t){this.logger.log(`set currentLevel:${t}`),this.levelController.manualLevel=t,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(t){this.logger.log(`set nextLevel:${t}`),this.levelController.manualLevel=t,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(t){this.logger.log(`set loadLevel:${t}`),this.levelController.manualLevel=t}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(t){this.levelController.nextLoadLevel=t}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(t){this.logger.log(`set firstLevel:${t}`),this.levelController.firstLevel=t}get startLevel(){const t=this.levelController.startLevel;return t===-1&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:t}set startLevel(t){this.logger.log(`set startLevel:${t}`),t!==-1&&(t=Math.max(t,this.minAutoLevel)),this.levelController.startLevel=t}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(t){const r=!!t;r!==this.config.capLevelToPlayerSize&&(r?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=r)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimate():NaN}set bandwidthEstimate(t){this.abrController.resetEstimator(t)}get abrEwmaDefaultEstimate(){const{bwEstimator:t}=this.abrController;return t?t.defaultEstimate:NaN}get ttfbEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimateTTFB():NaN}set autoLevelCapping(t){this._autoLevelCapping!==t&&(this.logger.log(`set autoLevelCapping:${t}`),this._autoLevelCapping=t,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(t){Cqs(t)&&this._maxHdcpLevel!==t&&(this._maxHdcpLevel=t,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return this.levelController.manualLevel===-1}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:t,config:{minAutoBitrate:r}}=this;if(!t)return 0;const n=t.length;for(let a=0;a=r)return a;return 0}get maxAutoLevel(){const{levels:t,autoLevelCapping:r,maxHdcpLevel:n}=this;let a;if(r===-1&&t!=null&&t.length?a=t.length-1:a=r,n)for(let i=a;i--;){const l=t[i].attrs["HDCP-LEVEL"];if(l&&l<=n)return i}return a}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(t){this.abrController.nextAutoLevel=t}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(t){var r;return((r=this.audioTrackController)==null?void 0:r.setAudioOption(t))||null}setSubtitleOption(t){var r;return((r=this.subtitleTrackController)==null?void 0:r.setSubtitleOption(t))||null}get allAudioTracks(){const t=this.audioTrackController;return t?t.allAudioTracks:[]}get audioTracks(){const t=this.audioTrackController;return t?t.audioTracks:[]}get audioTrack(){const t=this.audioTrackController;return t?t.audioTrack:-1}set audioTrack(t){const r=this.audioTrackController;r&&(r.audioTrack=t)}get allSubtitleTracks(){const t=this.subtitleTrackController;return t?t.allSubtitleTracks:[]}get subtitleTracks(){const t=this.subtitleTrackController;return t?t.subtitleTracks:[]}get subtitleTrack(){const t=this.subtitleTrackController;return t?t.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(t){const r=this.subtitleTrackController;r&&(r.subtitleTrack=t)}get subtitleDisplay(){const t=this.subtitleTrackController;return t?t.subtitleDisplay:!1}set subtitleDisplay(t){const r=this.subtitleTrackController;r&&(r.subtitleDisplay=t)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(t){this.config.lowLatencyMode=t}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}set targetLatency(t){this.latencyController.targetLatency=t}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(t){this.levelController.pathwayPriority=t}get bufferedToEnd(){var t;return!!((t=this.bufferController)!=null&&t.bufferedToEnd)}get interstitialsManager(){var t;return((t=this.interstitialsController)==null?void 0:t.interstitialsManager)||null}getMediaDecodingInfo(t,r=this.allAudioTracks){const n=Jvt(r);return Xvt(t,n,navigator.mediaCapabilities)}}e_.defaultConfig=void 0;const qWs=/(?:player\.mediadelivery\.net|iframe\.mediadelivery\.net|iframe\.n\.net|video\.bunnycdn\.com|[a-z0-9-]+\.b-cdn\.net)/i;function jI(s){return!!s&&qWs.test(s)&&!/\.mp4($|\?)/i.test(s)}function VWs(s){const t=s.match(/\/(?:play|embed)\/(\d+)\/([a-z0-9-]+)/i);return t?{libraryId:t[1],videoId:t[2]}:null}function HWs(s,t){if(!s)return null;const r=VWs(s);if(r){const n=new URLSearchParams({autoplay:t!=null&&t.autoplay?"true":"false",muted:t!=null&&t.muted?"true":"false",loop:t!=null&&t.loop?"true":"false",preload:"true",responsive:"true",playsinline:"true"});return`https://player.mediadelivery.net/embed/${r.libraryId}/${r.videoId}?${n.toString()}`}return/player\.mediadelivery\.net\/embed\//i.test(s)?s:/iframe\.mediadelivery\.net\/(?:play|embed)\//i.test(s)?s.replace("iframe.mediadelivery.net/play/","player.mediadelivery.net/embed/").replace("iframe.mediadelivery.net/embed/","player.mediadelivery.net/embed/"):s}function GWs(s){const t=s.match(/https:\/\/[^"']+playlist\.m3u8[^"']*/i);return t?t[0].replace(/&/g,"&").replace(/\u0026/g,"&"):null}const yCe=S.forwardRef(function({sourceUrl:t,thumbnailUrl:r,autoPlay:n,muted:a,loop:i,playsInline:l=!0,...o},c){const d=S.useRef(null),[h,m]=S.useState(null),p=S.useMemo(()=>HWs(t,{autoplay:!!n,muted:!!a,loop:!!i}),[t,n,a,i]);S.useEffect(()=>{let y=!1;if(!t){m(null);return}if(!jI(t)){m(t);return}if(!p){m(null);return}return m(null),fetch(p).then(async _=>{if(!_.ok)throw new Error(`Failed to load Bunny embed (${_.status})`);const b=await _.text();return GWs(b)}).then(_=>{y||m(_)}).catch(()=>{y||m(null)}),()=>{y=!0}},[p,t]),S.useEffect(()=>{const y=d.current;if(!y||!h)return;let _=null;const b=()=>{if(!n)return;const k=y.play();k&&k.catch(()=>{})};if(y.muted=!!a,y.loop=!!i,h.endsWith(".m3u8")){if(y.canPlayType("application/vnd.apple.mpegurl")){y.src=h;const k=()=>b();return y.addEventListener("loadedmetadata",k),()=>{y.removeEventListener("loadedmetadata",k),y.removeAttribute("src"),y.load()}}return e_.isSupported()?(_=new e_({enableWorker:!0,lowLatencyMode:!0}),_.loadSource(h),_.attachMedia(y),_.on(e_.Events.MANIFEST_PARSED,b),()=>{_==null||_.destroy(),y.removeAttribute("src"),y.load()}):void 0}y.src=h;const j=()=>b();return y.addEventListener("loadedmetadata",j),()=>{y.removeEventListener("loadedmetadata",j),y.removeAttribute("src"),y.load()}},[n,i,a,h]),S.useEffect(()=>{const y=d.current;if(y){if(y.muted=!!a,y.loop=!!i,n&&h){const _=y.play();_&&_.catch(()=>{});return}y.pause()}},[n,i,a,h]);const x=y=>{if(d.current=y,typeof c=="function"){c(y);return}c&&(c.current=y)};return e.jsx("video",{ref:x,poster:r||void 0,autoPlay:n,muted:a,loop:i,playsInline:l,preload:"metadata",...o})}),WWs={portrait:{sm:{w:130,h:231},md:{w:170,h:302},lg:{w:210,h:373}},landscape:{sm:{w:178,h:100},md:{w:220,h:124},lg:{w:270,h:152}}};function KWs(){try{let s=localStorage.getItem("vg_visitor_token");return s||(s=crypto.randomUUID(),localStorage.setItem("vg_visitor_token",s)),s}catch{return null}}function mYe(s,t){return!s||s.length===0?!1:s.some(r=>r?r===t?!0:r.endsWith("*")?t.startsWith(r.slice(0,-1)):t.startsWith(r):!1)}function K6e({config:s,appSlug:t="video_greeter",preview:r=!1,embedded:n=!1}){const[a,i]=S.useState(!1),[l,o]=S.useState(!1),[c,d]=S.useState(!0),[h,m]=S.useState(!1),[p,x]=S.useState("portrait"),[y,_]=S.useState(!1),[b,j]=S.useState(!1),[k,T]=S.useState({name:"",email:"",phone:""}),[E,A]=S.useState(()=>({width:typeof window<"u"?window.innerWidth:1280,height:typeof window<"u"?window.innerHeight:720})),D=S.useRef(null),R=S.useRef(null),z=S.useRef(!1),O=async(Ue,et)=>{if(!r)try{await V.from("widget_events").insert({user_id:s.user_id,app_slug:t,event_type:Ue,visitor_token:KWs(),page_url:typeof window<"u"?window.location.href:null,metadata:et||{}})}catch{}};S.useEffect(()=>{if(h)return;const Ue=typeof window<"u"?window.location.pathname:"/",et=s.targeting||{mode:"all"};if(et.mode==="include"&&!mYe(et.include,Ue)||et.mode==="exclude"&&mYe(et.exclude,Ue))return;const Qe=s.trigger||{type:"immediate"};if(Qe.type==="immediate"||r){i(!0);return}if(Qe.type==="delay"){const Ne=(Qe.value||3)*1e3,$e=setTimeout(()=>i(!0),Ne);return()=>clearTimeout($e)}if(Qe.type==="scroll"){const Ne=(Qe.value||25)/100,$e=()=>{(window.scrollY+window.innerHeight)/document.documentElement.scrollHeight>=Ne&&(i(!0),window.removeEventListener("scroll",$e))};return window.addEventListener("scroll",$e,{passive:!0}),()=>window.removeEventListener("scroll",$e)}if(Qe.type==="exit_intent"){const Ne=$e=>{$e.clientY<=0&&i(!0)};return document.addEventListener("mouseleave",Ne),()=>document.removeEventListener("mouseleave",Ne)}},[h,s.targeting,s.trigger,r]),S.useEffect(()=>{a&&!z.current&&(z.current=!0,O("impression"))},[a]),S.useEffect(()=>{if(l&&R.current&&!jI(s.video_url)){R.current.currentTime=0,R.current.muted=!1,d(!1);const Ue=R.current.play();Ue&&Ue.catch(()=>{})}else l&&jI(s.video_url)&&d(!1)},[l,s.video_url]),S.useEffect(()=>{if(!s.thumbnail_url)return;let Ue=!1;const et=new Image;return et.onload=()=>{Ue||x(et.naturalWidth>et.naturalHeight?"landscape":"portrait")},et.src=s.thumbnail_url,()=>{Ue=!0}},[s.thumbnail_url]),S.useEffect(()=>{const Ue=()=>{A({width:window.innerWidth,height:window.innerHeight})};return Ue(),window.addEventListener("resize",Ue),()=>window.removeEventListener("resize",Ue)},[]);const $=()=>{o(!0),O("expand")},ee=Ue=>{Ue.stopPropagation(),m(!0),o(!1)},Z=Ue=>{O("cta_click",{cta_id:Ue.id,label:Ue.label,url:Ue.url})},J=async Ue=>{if(Ue.preventDefault(),r){_(!0);return}if(!(!k.email||!k.name)){j(!0);try{const{error:et}=await V.functions.invoke("submit-widget-lead",{body:{user_id:s.user_id,app_slug:t,name:k.name,email:k.email,phone:k.phone||void 0,page_url:window.location.href}});if(et)throw et;O("lead_capture",{email:k.email}),_(!0)}catch(et){console.error("lead submit failed",et)}finally{j(!1)}}};if(!a||h||!s.video_url&&!s.video_embed_url)return null;const K=WWs[p][s.size||"md"],re=n?"absolute left-2 bottom-2":r?s.position==="bottom-right"?"absolute right-4 bottom-4":"absolute left-4 bottom-4":s.position==="bottom-right"?"fixed right-4 bottom-4 md:right-6 md:bottom-6":"fixed left-4 bottom-4 md:left-6 md:bottom-6",ie=s.shape==="circle"?"rounded-full":"rounded-2xl",ce=r?p==="landscape"?"w-[280px]":"w-[220px]":p==="landscape"?"w-[360px] sm:w-[420px]":"w-[300px] sm:w-[340px]",ne=p==="landscape"?"aspect-video":"aspect-[9/16]",le=s.agent||{},be=s.lead_form_fields||["name","email","phone"],fe=!!(s.show_socials&&(le.instagram_url||le.facebook_url||le.linkedin_url)),je=108+(s.ctas||[]).length*48+(s.lead_form_enabled&&!y?72+be.length*42:0)+(y?40:0)+(fe?34:0),ve=Math.max(300,E.height-32),We=Math.max(220,E.width-32),Ve=Math.max(150,ve-je),Le=Math.floor(p==="landscape"?Ve*(16/9):Ve*(9/16)),Me=p==="landscape"?Math.max(220,Math.min(420,We,Le)):Math.max(180,Math.min(340,We,Le)),ze=n?"bg-white rounded-2xl shadow-2xl overflow-hidden border border-black/10 animate-in fade-in zoom-in-95 duration-300 flex flex-col":`${ce} max-h-[calc(100dvh-2rem)] bg-white rounded-2xl shadow-2xl overflow-hidden border border-black/10 animate-in fade-in zoom-in-95 duration-300 flex flex-col`,Pe=n?{width:`${Me}px`,maxHeight:"calc(100dvh - 2rem)"}:void 0,Ie=n?"p-3 space-y-2.5":"p-4 space-y-3",De=n?"w-9 h-9 rounded-full object-cover":"w-10 h-10 rounded-full object-cover",pe=n?"font-bold text-[15px] text-gray-900 leading-tight":"font-bold text-gray-900 leading-tight",tt=n?"text-[11px] text-gray-500 mt-0.5":"text-xs text-gray-500 mt-0.5",ge=n?"w-full px-3 py-1.5 text-sm rounded-lg border border-gray-200 focus:border-gray-900 focus:outline-none bg-white text-gray-900 placeholder:text-gray-400":"w-full px-3 py-2 text-sm rounded-lg border border-gray-200 focus:border-gray-900 focus:outline-none bg-white text-gray-900 placeholder:text-gray-400",ct=n?"w-full flex items-center justify-center gap-2 px-3 py-2 bg-gray-900 text-white rounded-xl text-sm font-semibold hover:bg-black transition-colors disabled:opacity-60":"w-full flex items-center justify-center gap-2 px-3 py-2.5 bg-gray-900 text-white rounded-xl text-sm font-semibold hover:bg-black transition-colors disabled:opacity-60";return e.jsx("div",{"data-vg-widget":!0,"data-expanded":l?"true":"false",className:`${re} z-[70]`,style:{paddingBottom:"env(safe-area-inset-bottom)"},children:l?e.jsxs("div",{className:ze,style:Pe,children:[e.jsxs("div",{className:`relative bg-black ${ne}`,children:[jI(s.video_url)?e.jsx(yCe,{ref:R,sourceUrl:s.video_url,thumbnailUrl:s.thumbnail_url,autoPlay:!0,muted:c,loop:!1,className:"w-full h-full object-cover",onLoadedMetadata:Ue=>{const{videoWidth:et,videoHeight:Qe}=Ue.currentTarget;et&&Qe&&x(et>Qe?"landscape":"portrait")},onEnded:()=>O("watch_complete")},`expanded-${s.video_url}-${s.thumbnail_url||"no-thumb"}-${l?"on":"off"}`):e.jsx("video",{ref:R,src:s.video_url||void 0,poster:s.thumbnail_url||void 0,autoPlay:!0,playsInline:!0,controls:!1,className:"w-full h-full object-cover",onEnded:()=>O("watch_complete"),onLoadedMetadata:Ue=>{const{videoWidth:et,videoHeight:Qe}=Ue.currentTarget;et&&Qe&&x(et>Qe?"landscape":"portrait")}}),e.jsx("button",{onClick:()=>{R.current&&(R.current.muted=!R.current.muted,d(R.current.muted))},className:"absolute bottom-3 right-3 w-9 h-9 rounded-full bg-black/60 hover:bg-black text-white flex items-center justify-center backdrop-blur",children:c?e.jsx($F,{className:"w-4 h-4"}):e.jsx(zF,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>o(!1),className:"absolute top-3 right-3 w-8 h-8 rounded-full bg-black/60 hover:bg-black text-white flex items-center justify-center backdrop-blur","aria-label":"Minimize",children:e.jsx(Rr,{className:"w-4 h-4"})})]}),e.jsxs("div",{className:Ie,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[le.avatar_url&&e.jsx("img",{src:le.avatar_url,alt:le.name||"",className:De}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:pe,children:s.greeting_title||"Glad you're here!"}),s.greeting_subtitle&&e.jsx("p",{className:tt,children:s.greeting_subtitle})]})]}),(s.ctas||[]).length>0&&e.jsx("div",{className:"space-y-2",children:(s.ctas||[]).map(Ue=>{var et;return e.jsxs("a",{href:Ue.url,target:(et=Ue.url)!=null&&et.startsWith("http")?"_blank":void 0,rel:"noopener noreferrer",onClick:()=>Z(Ue),className:`flex items-center justify-between gap-2 ${n?"px-3 py-2":"px-3.5 py-2.5"} rounded-xl text-sm font-semibold transition-colors ${Ue.style==="secondary"?"bg-gray-100 text-gray-900 hover:bg-gray-200":"bg-gray-900 text-white hover:bg-gray-800"}`,children:[e.jsx("span",{children:Ue.label}),e.jsx(gn,{className:"w-3.5 h-3.5 opacity-60"})]},Ue.id)})}),s.lead_form_enabled&&!y&&e.jsxs("form",{onSubmit:J,className:"space-y-2 pt-1",children:[be.includes("name")&&e.jsx("input",{type:"text",placeholder:"Name",required:!0,value:k.name,onChange:Ue=>T({...k,name:Ue.target.value}),className:ge}),be.includes("email")&&e.jsx("input",{type:"email",placeholder:"Email",required:!0,value:k.email,onChange:Ue=>T({...k,email:Ue.target.value}),className:ge}),be.includes("phone")&&e.jsx("input",{type:"tel",placeholder:"Phone (optional)",value:k.phone,onChange:Ue=>T({...k,phone:Ue.target.value}),className:ge}),e.jsxs("button",{type:"submit",disabled:b,className:ct,children:[e.jsx(yn,{className:"w-3.5 h-3.5"}),b?"Sending...":"Send"]})]}),y&&e.jsx("p",{className:"text-sm text-emerald-600 font-medium text-center py-2",children:"Thanks! I'll be in touch shortly."}),s.show_socials&&(le.instagram_url||le.facebook_url||le.linkedin_url)&&e.jsxs("div",{className:"flex items-center justify-center gap-3 pt-2 border-t border-gray-100",children:[le.instagram_url&&e.jsx("a",{href:le.instagram_url,target:"_blank",rel:"noopener noreferrer",className:"text-gray-400 hover:text-gray-900",onClick:()=>O("cta_click",{social:"instagram"}),children:e.jsx(yu,{className:"w-4 h-4"})}),le.facebook_url&&e.jsx("a",{href:le.facebook_url,target:"_blank",rel:"noopener noreferrer",className:"text-gray-400 hover:text-gray-900",onClick:()=>O("cta_click",{social:"facebook"}),children:e.jsx(fh,{className:"w-4 h-4"})}),le.linkedin_url&&e.jsx("a",{href:le.linkedin_url,target:"_blank",rel:"noopener noreferrer",className:"text-gray-400 hover:text-gray-900",onClick:()=>O("cta_click",{social:"linkedin"}),children:e.jsx(qf,{className:"w-4 h-4"})})]})]})]}):e.jsxs("div",{className:"relative animate-in fade-in slide-in-from-bottom-4 duration-500",children:[e.jsxs("button",{onClick:$,className:`relative ${ie} overflow-hidden shadow-2xl ring-2 ring-white/40 hover:ring-white/80 hover:scale-105 transition-all bg-black`,style:{width:K.w,height:K.h},"aria-label":"Play video greeting",children:[jI(s.video_url)?e.jsx(yCe,{ref:D,sourceUrl:s.video_url,thumbnailUrl:s.thumbnail_url,autoPlay:!0,muted:!0,loop:!0,className:"w-full h-full object-cover pointer-events-none",onLoadedMetadata:Ue=>{const{videoWidth:et,videoHeight:Qe}=Ue.currentTarget;et&&Qe&&x(et>Qe?"landscape":"portrait")}},`collapsed-${s.video_url}-${s.thumbnail_url||"no-thumb"}`):e.jsx("video",{ref:D,src:s.video_url||void 0,poster:s.thumbnail_url||void 0,autoPlay:!0,muted:!0,loop:!0,playsInline:!0,preload:"metadata",className:"w-full h-full object-cover",onLoadedMetadata:Ue=>{const{videoWidth:et,videoHeight:Qe}=Ue.currentTarget;et&&Qe&&x(et>Qe?"landscape":"portrait")}}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-black/40 via-transparent to-transparent pointer-events-none"}),e.jsx("div",{className:"absolute bottom-2 left-1/2 -translate-x-1/2 w-12 h-12 rounded-full bg-white/95 flex items-center justify-center shadow-lg pointer-events-none",children:e.jsx("svg",{viewBox:"0 0 24 24",className:"w-6 h-6 text-black ml-0.5",fill:"currentColor",children:e.jsx("path",{d:"M8 5v14l11-7z"})})}),e.jsx("span",{className:"absolute top-2 right-2 px-2 py-0.5 text-[10px] font-bold uppercase tracking-wider bg-red-500 text-white rounded-full animate-pulse",children:"Live"})]}),e.jsx("button",{onClick:ee,className:"absolute -top-2 -right-2 w-7 h-7 rounded-full bg-black/80 text-white shadow-lg hover:bg-black flex items-center justify-center","aria-label":"Close",children:e.jsx(Rr,{className:"w-3.5 h-3.5"})})]})})}function Y6e({slug:s}){const[t,r]=S.useState(null);return S.useEffect(()=>{if(!s)return;let n=!1;return(async()=>{const{data:a,error:i}=await V.rpc("get_public_video_greeter_config",{_slug:s});!n&&!i&&a&&r(a)})(),()=>{n=!0}},[s]),t?e.jsx(K6e,{config:t}):null}const fbt="eip_last_shown",fYe="eip_visitor_token";function YWs(){try{let s=localStorage.getItem(fYe);return s||(s=crypto.randomUUID(),localStorage.setItem(fYe,s)),s}catch{return}}function ZWs(s){try{const t=Number(localStorage.getItem(fbt)||0);return t?Date.now()-t>s*24*60*60*1e3:!0}catch{return!0}}function XWs(s){if(!s||s.mode==="all")return!0;const t=window.location.pathname,n=(s.mode==="include"?s.include||[]:s.exclude||[]).some(a=>t.startsWith(a));return s.mode==="include"?n:!n}function pbt({config:s,preview:t=!1,forceOpen:r=!1}){const[n,a]=S.useState(r),[i,l]=S.useState(!1),[o,c]=S.useState(!1),[d,h]=S.useState({name:"",email:"",phone:""}),m=S.useRef(!1),p=S.useRef(!1),x=async(D,R={})=>{if(!t)try{await V.from("widget_events").insert({user_id:s.user_id,app_slug:"exit_intent",event_type:D,visitor_token:YWs(),page_url:window.location.href,metadata:R})}catch{}};S.useEffect(()=>{if(t||!XWs(s.targeting)||!ZWs(s.frequency_days))return;const D=/Mobi|Android/i.test(navigator.userAgent),R={low:5,medium:15,high:30}[s.trigger_sensitivity]||15,z=Z=>{if(!m.current){m.current=!0,a(!0);try{localStorage.setItem(fbt,String(Date.now()))}catch{}x("impression",{reason:Z})}},O=Z=>{Z.clientY<=R&&z("mouse_leave")},$=()=>{s.enable_mobile_back&&D&&z("back_button")};if(s.enable_mobile_back&&D){try{window.history.pushState({eip:!0},"")}catch{}window.addEventListener("popstate",$)}else document.addEventListener("mouseleave",O);let ee;return s.enable_time_fallback&&(ee=window.setTimeout(()=>z("time_fallback"),Math.max(5,s.time_fallback_seconds)*1e3)),()=>{document.removeEventListener("mouseleave",O),window.removeEventListener("popstate",$),ee&&window.clearTimeout(ee)}},[s,t]),S.useEffect(()=>{n&&!p.current&&!t&&!m.current&&(p.current=!0)},[n,t]);const y=()=>{a(!1),t||x("close")},_=async D=>{if(D.preventDefault(),t){l(!0);return}if(!(!d.email||!d.name)){c(!0);try{const{error:R}=await V.functions.invoke("submit-widget-lead",{body:{user_id:s.user_id,app_slug:"exit_intent",name:d.name,email:d.email,phone:d.phone||void 0,page_url:window.location.href}});if(R)throw R;x("lead_capture",{email:d.email}),l(!0),s.cta_url&&setTimeout(()=>{window.location.href=s.cta_url},1200)}catch(R){console.error("exit intent submit failed",R)}finally{c(!1)}}};if(!n)return null;const b=s.form_fields||["name","email"],j=s.agent||{},k=[j.first_name,j.last_name].filter(Boolean).join(" "),T=s.use_agent_photo&&j.avatar_url||s.image_url,E=s.theme_color||"#f97316",A=t?"absolute inset-0 flex items-center justify-center p-4 z-10":"fixed inset-0 z-[80] flex items-center justify-center p-4";return e.jsx("div",{className:A,style:{background:t?"transparent":"rgba(0,0,0,0.6)"},children:e.jsxs("div",{className:"relative w-full max-w-md bg-background rounded-2xl shadow-2xl overflow-hidden animate-in fade-in zoom-in-95 duration-300",onClick:D=>D.stopPropagation(),children:[e.jsx("div",{className:"h-2 w-full",style:{background:`linear-gradient(90deg, ${E}, ${a2e(E,-25)})`}}),e.jsx("button",{onClick:y,className:"absolute top-3 right-3 z-10 w-8 h-8 rounded-full bg-background/80 backdrop-blur hover:bg-background flex items-center justify-center text-muted-foreground hover:text-foreground transition","aria-label":"Close",children:e.jsx(Rr,{className:"w-4 h-4"})}),e.jsxs("div",{className:"p-6 sm:p-7 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[T&&e.jsx("img",{src:T,alt:k||"Agent",className:"w-14 h-14 rounded-full object-cover ring-2 shadow-md",style:{boxShadow:`0 0 0 2px ${E}33`,"--tw-ring-color":E}}),e.jsxs("div",{className:"inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-semibold",style:{background:`${E}1A`,color:E},children:[e.jsx(Lr,{className:"w-3 h-3"}),s.offer_label]})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-extrabold tracking-tight leading-tight",children:s.headline}),e.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:s.subheadline})]}),i?e.jsxs("div",{className:"rounded-xl p-5 text-center space-y-2",style:{background:`${E}10`,color:E},children:[e.jsx("div",{className:"text-3xl",children:"🎉"}),e.jsx("p",{className:"text-sm font-medium",style:{color:E},children:s.success_message})]}):s.form_enabled?e.jsxs("form",{onSubmit:_,className:"space-y-2.5",children:[b.includes("name")&&e.jsx("input",{type:"text",placeholder:"Your name",value:d.name,onChange:D=>h({...d,name:D.target.value}),className:"w-full px-4 py-3 text-sm rounded-lg border border-input bg-background focus:outline-none focus:ring-2 transition",style:{"--tw-ring-color":E},required:!0}),b.includes("email")&&e.jsx("input",{type:"email",placeholder:"you@email.com",value:d.email,onChange:D=>h({...d,email:D.target.value}),className:"w-full px-4 py-3 text-sm rounded-lg border border-input bg-background focus:outline-none focus:ring-2 transition",style:{"--tw-ring-color":E},required:!0}),b.includes("phone")&&e.jsx("input",{type:"tel",placeholder:"Phone (optional)",value:d.phone,onChange:D=>h({...d,phone:D.target.value}),className:"w-full px-4 py-3 text-sm rounded-lg border border-input bg-background focus:outline-none focus:ring-2 transition",style:{"--tw-ring-color":E}}),e.jsx("button",{type:"submit",disabled:o,className:"w-full py-3 rounded-lg font-semibold text-white shadow-lg hover:opacity-95 active:scale-[0.99] transition disabled:opacity-60",style:{background:`linear-gradient(135deg, ${E}, ${a2e(E,-20)})`},children:o?"Sending...":s.cta_label}),e.jsx("p",{className:"text-[10px] text-center text-muted-foreground pt-1",children:"We respect your inbox. Unsubscribe anytime."})]}):e.jsx("a",{href:s.cta_url||"#",onClick:()=>x("cta_click",{url:s.cta_url}),className:"block w-full text-center py-3 rounded-lg font-semibold text-white shadow-lg hover:opacity-95 transition",style:{background:`linear-gradient(135deg, ${E}, ${a2e(E,-20)})`},children:s.cta_label}),k&&e.jsxs("p",{className:"text-[11px] text-center text-muted-foreground pt-1",children:["Sent personally by ",k]})]})]})})}function a2e(s,t){try{const r=parseInt(s.slice(1),16),n=t<0?0:255,a=Math.abs(t)/100,i=r>>16,l=r>>8&255,o=r&255,c=Math.round((n-i)*a)+i,d=Math.round((n-l)*a)+l,h=Math.round((n-o)*a)+o;return"#"+(16777216+(c<<16)+(d<<8)+h).toString(16).slice(1)}catch{return s}}function Z6e({slug:s}){const[t,r]=S.useState(null);return S.useEffect(()=>{if(!s)return;let n=!1;return(async()=>{const{data:a,error:i}=await V.rpc("get_public_exit_intent_config",{_slug:s});!n&&!i&&a&&r(a)})(),()=>{n=!0}},[s]),t?e.jsx(pbt,{config:t}):null}const pYe="lm_dismissed",gYe="lm_visitor_token";function QWs(){try{let s=localStorage.getItem(gYe);return s||(s=crypto.randomUUID(),localStorage.setItem(gYe,s)),s}catch{return}}function JWs(s){if(!s||s.mode==="all")return!0;const t=window.location.pathname,n=(s.mode==="include"?s.include||[]:s.exclude||[]).some(a=>t.startsWith(a));return s.mode==="include"?n:!n}function X6e({config:s,preview:t=!1}){const[r,n]=S.useState(!1),[a,i]=S.useState(!1),[l,o]=S.useState(!1),[c,d]=S.useState(!1),[h,m]=S.useState({name:"",email:"",phone:""}),p=S.useRef(!1),x=async(T,E={})=>{if(!t)try{await V.from("widget_events").insert({user_id:s.user_id,app_slug:"lead_magnet",event_type:T,visitor_token:QWs(),page_url:window.location.href,metadata:E})}catch{}};S.useEffect(()=>{if(t){n(!0);return}if(!JWs(s.targeting))return;try{if(sessionStorage.getItem(pYe))return}catch{}const T=()=>{p.current||(p.current=!0,n(!0),x("impression"))};if(s.trigger_type==="immediate")T();else if(s.trigger_type==="delay"){const E=window.setTimeout(T,Math.max(0,s.trigger_value)*1e3);return()=>window.clearTimeout(E)}else if(s.trigger_type==="scroll"){const E=()=>{(window.scrollY+window.innerHeight)/document.documentElement.scrollHeight*100>=(s.trigger_value||30)&&T()};return window.addEventListener("scroll",E,{passive:!0}),()=>window.removeEventListener("scroll",E)}},[s,t]);const y=()=>{n(!1);try{sessionStorage.setItem(pYe,"1")}catch{}t||x("close")},_=async T=>{if(T.preventDefault(),t){o(!0);return}if(!(!h.email||!h.name)){d(!0);try{const{error:E}=await V.functions.invoke("submit-widget-lead",{body:{user_id:s.user_id,app_slug:"lead_magnet",name:h.name,email:h.email,phone:h.phone||void 0,page_url:window.location.href}});if(E)throw E;x("lead_capture",{email:h.email}),o(!0),(s.delivery_method==="instant"||s.delivery_method==="both")&&s.download_url&&setTimeout(()=>{const A=document.createElement("a");A.href=s.download_url,A.target="_blank",A.rel="noopener",A.download="",document.body.appendChild(A),A.click(),A.remove()},600)}catch(E){console.error("lead magnet submit failed",E)}finally{d(!1)}}};if(!r)return null;const b=s.theme_color||"#2563eb",j=t?s.position==="bottom-left"?"absolute left-4 bottom-4":"absolute right-4 bottom-4":s.position==="bottom-left"?"fixed left-4 bottom-4 md:left-6 md:bottom-6":"fixed right-4 bottom-4 md:right-6 md:bottom-6";if(s.display_style==="bar")return e.jsxs("div",{className:t?"absolute left-0 right-0 bottom-0 z-10":"fixed left-0 right-0 bottom-0 z-[75]",style:{paddingBottom:"env(safe-area-inset-bottom)"},children:[e.jsx("div",{className:"text-white shadow-2xl",style:{background:`linear-gradient(90deg, ${b}, ${iO(b,-20)})`},children:e.jsxs("div",{className:"max-w-6xl mx-auto px-4 py-3 flex items-center gap-3 flex-wrap",children:[e.jsx(Di,{className:"w-5 h-5 shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-semibold truncate",children:s.title}),e.jsx("p",{className:"text-xs text-white/80 truncate",children:s.description})]}),e.jsx("button",{onClick:()=>{i(!0),x("expand")},className:"px-4 py-2 rounded-lg text-sm font-semibold bg-white shrink-0 hover:bg-white/95 transition",style:{color:b},children:s.download_label}),e.jsx("button",{onClick:y,className:"text-white/80 hover:text-white","aria-label":"Close",children:e.jsx(Rr,{className:"w-4 h-4"})})]})}),a&&k()]});if(!a)return e.jsxs(e.Fragment,{children:[e.jsxs("button",{onClick:()=>{i(!0),x("expand")},className:`${j} z-[75] group flex items-center gap-3 pl-3 pr-4 py-3 rounded-2xl shadow-2xl hover:shadow-3xl transition-all hover:scale-[1.03] animate-in fade-in slide-in-from-bottom-4 duration-500`,style:{background:`linear-gradient(135deg, ${b}, ${iO(b,-20)})`,paddingBottom:"env(safe-area-inset-bottom)"},children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-white/20 backdrop-blur flex items-center justify-center text-white",children:e.jsx(tf,{className:"w-5 h-5"})}),e.jsxs("div",{className:"text-left text-white",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wider opacity-90 font-semibold",children:s.badge_label}),e.jsx("div",{className:"text-sm font-bold leading-tight max-w-[180px] truncate",children:s.title})]}),e.jsx("button",{onClick:T=>{T.stopPropagation(),y()},className:"ml-1 w-6 h-6 rounded-full bg-white/20 hover:bg-white/30 flex items-center justify-center text-white","aria-label":"Close",children:e.jsx(Rr,{className:"w-3 h-3"})})]}),a&&k()]});return k();function k(){const T=s.form_fields||["name","email"],E=s.agent||{},A=[E.first_name,E.last_name].filter(Boolean).join(" ");return e.jsx("div",{className:t?"absolute inset-0 flex items-center justify-center p-4 z-20":"fixed inset-0 z-[85] flex items-center justify-center p-4",style:{background:t?"transparent":"rgba(0,0,0,0.6)"},onClick:()=>i(!1),children:e.jsxs("div",{className:"relative w-full max-w-lg bg-background rounded-2xl shadow-2xl overflow-hidden animate-in fade-in zoom-in-95 duration-300",onClick:D=>D.stopPropagation(),children:[e.jsxs("div",{className:"relative h-44 sm:h-52 overflow-hidden",style:{background:`linear-gradient(135deg, ${b}, ${iO(b,-25)})`},children:[s.cover_image_url?e.jsx("img",{src:s.cover_image_url,alt:s.title,className:"w-full h-full object-cover opacity-90"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(kn,{className:"w-20 h-20 text-white/40"})}),e.jsxs("div",{className:"absolute top-3 left-3 inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-[11px] font-semibold bg-white shadow",style:{color:b},children:[e.jsx(Di,{className:"w-3 h-3"}),s.badge_label]}),e.jsx("button",{onClick:()=>i(!1),className:"absolute top-3 right-3 w-8 h-8 rounded-full bg-white/95 hover:bg-white flex items-center justify-center text-foreground/70 hover:text-foreground transition","aria-label":"Close",children:e.jsx(Rr,{className:"w-4 h-4"})})]}),e.jsxs("div",{className:"p-6 sm:p-7 space-y-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-extrabold tracking-tight leading-tight",children:s.title}),e.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:s.description})]}),l?e.jsxs("div",{className:"rounded-xl p-5 text-center space-y-2",style:{background:`${b}10`},children:[e.jsx(hi,{className:"w-8 h-8 mx-auto",style:{color:b}}),e.jsx("p",{className:"text-sm font-medium",style:{color:b},children:s.success_message}),s.download_url&&e.jsx("a",{href:s.download_url,target:"_blank",rel:"noopener",className:"inline-block mt-2 text-xs underline",style:{color:b},children:"Click here if download didn't start"})]}):s.form_enabled?e.jsxs("form",{onSubmit:_,className:"space-y-2.5",children:[T.includes("name")&&e.jsx("input",{type:"text",placeholder:"Your name",value:h.name,onChange:D=>m({...h,name:D.target.value}),className:"w-full px-4 py-3 text-sm rounded-lg border border-input bg-background focus:outline-none focus:ring-2 transition",style:{"--tw-ring-color":b},required:!0}),T.includes("email")&&e.jsx("input",{type:"email",placeholder:"you@email.com",value:h.email,onChange:D=>m({...h,email:D.target.value}),className:"w-full px-4 py-3 text-sm rounded-lg border border-input bg-background focus:outline-none focus:ring-2 transition",style:{"--tw-ring-color":b},required:!0}),T.includes("phone")&&e.jsx("input",{type:"tel",placeholder:"Phone (optional)",value:h.phone,onChange:D=>m({...h,phone:D.target.value}),className:"w-full px-4 py-3 text-sm rounded-lg border border-input bg-background focus:outline-none focus:ring-2 transition",style:{"--tw-ring-color":b}}),e.jsxs("button",{type:"submit",disabled:c,className:"w-full py-3 rounded-lg font-semibold text-white shadow-lg hover:opacity-95 active:scale-[0.99] transition disabled:opacity-60 inline-flex items-center justify-center gap-2",style:{background:`linear-gradient(135deg, ${b}, ${iO(b,-20)})`},children:[e.jsx(hi,{className:"w-4 h-4"}),c?"Sending...":s.download_label]}),e.jsx("p",{className:"text-[10px] text-center text-muted-foreground pt-1",children:"We'll email you a copy too. No spam — promise."})]}):e.jsx("a",{href:s.download_url||"#",target:"_blank",rel:"noopener",onClick:()=>x("cta_click",{url:s.download_url}),className:"block w-full text-center py-3 rounded-lg font-semibold text-white shadow-lg",style:{background:`linear-gradient(135deg, ${b}, ${iO(b,-20)})`},children:s.download_label}),A&&e.jsxs("p",{className:"text-[11px] text-center text-muted-foreground",children:["Curated by ",A]})]})]})})}}function iO(s,t){try{const r=parseInt(s.slice(1),16),n=t<0?0:255,a=Math.abs(t)/100,i=r>>16,l=r>>8&255,o=r&255,c=Math.round((n-i)*a)+i,d=Math.round((n-l)*a)+l,h=Math.round((n-o)*a)+o;return"#"+(16777216+(c<<16)+(d<<8)+h).toString(16).slice(1)}catch{return s}}function Q6e({slug:s}){const[t,r]=S.useState(null);return S.useEffect(()=>{if(!s)return;let n=!1;return(async()=>{const{data:a,error:i}=await V.rpc("get_public_lead_magnet_config",{_slug:s});!n&&!i&&a&&r(a)})(),()=>{n=!0}},[s]),t?e.jsx(X6e,{config:t}):null}function eKs({children:s,siteConfig:t}){var fe,je,ve,We,Ve,Le,Me,ze,Pe,Ie;const r=Vc(),n=Fr(),[a,i]=S.useState(!1),[l,o]=S.useState(!1),[c,d]=S.useState(!1),[h,m]=S.useState([]),[p,x]=S.useState([]),[y,_]=S.useState(null),b=S.useRef(null),j=S.useRef(null),{user:k,profile:T,signOut:E}=dye();w6e(t,k==null?void 0:k.id),j6e(t,k==null?void 0:k.id);const A=((fe=t.agent)==null?void 0:fe.full_name)||"Agent",D=t.siteTitle||`${A} Real Estate`,R=r.pathname==="/search",z=r.pathname==="/",O=t.leadRegistrationMode!=="disabled";S.useEffect(()=>{(async()=>{const{data:pe}=await V.from("lead_site_city_pages").select("city_name, city_slug").eq("site_id",t.id).eq("is_published",!0).order("sort_order",{ascending:!0});m(pe||[])})()},[t.id]),S.useEffect(()=>{(async()=>{const{data:pe}=await V.from("lead_site_menu_items").select("*").eq("site_id",t.id).eq("is_visible",!0).order("sort_order",{ascending:!0});x(pe||[])})()},[t.id]),S.useEffect(()=>{const De=pe=>{b.current&&!b.current.contains(pe.target)&&d(!1),j.current&&!j.current.contains(pe.target)&&_(null)};return document.addEventListener("mousedown",De),()=>document.removeEventListener("mousedown",De)},[]);const $=((je=t==null?void 0:t.themeConfig)==null?void 0:je.referralMode)===!0||!t.mlsProviderId,ee=p.length>0,Z=[{to:"/",label:"Home"},...$?[]:[{to:"/search",label:"Search"}],{to:"/sell",label:"Sell"},{to:"/blog",label:"Blog"},{to:"/community",label:"Community"},{to:"/about",label:"About"},{to:"/contact",label:"Contact"}],J=ee?[]:Z,K=p.filter(De=>!De.parent_id),re=De=>p.filter(pe=>pe.parent_id===De),ie=z?"bg-transparent text-white":"bg-white/95 backdrop-blur text-gray-900 border-b border-gray-100 shadow-sm",ce=t.siteTitle||`${A} - Real Estate`,ne=t.siteTagline||`Browse homes and listings with ${A}`,le=t.ogImageUrl||((ve=t.agent)==null?void 0:ve.avatar_url)||"",be=`https://${t.subdomainSlug||""}.thelocalmove.com`;return e.jsxs("div",{className:`flex flex-col ${R?"h-screen overflow-hidden":"min-h-screen"} bg-white`,children:[e.jsx(b6e,{siteConfig:t,pagePath:r.pathname}),e.jsx(_6e,{siteConfig:t}),e.jsxs(el,{children:[e.jsx("title",{children:ce}),e.jsx("meta",{name:"description",content:ne}),e.jsx("meta",{property:"og:title",content:ce}),e.jsx("meta",{property:"og:description",content:ne}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("meta",{property:"og:url",content:be+r.pathname}),le&&e.jsx("meta",{property:"og:image",content:le}),e.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),e.jsx("meta",{name:"twitter:title",content:ce}),e.jsx("meta",{name:"twitter:description",content:ne}),le&&e.jsx("meta",{name:"twitter:image",content:le}),t.faviconUrl&&e.jsx("link",{rel:"icon",href:t.faviconUrl,type:"image/png"}),e.jsx("link",{rel:"canonical",href:`${be}${r.pathname}`}),t.subdomainSlug==="matthogg"&&e.jsx("script",{src:"https://analytics.ahrefs.com/analytics.js","data-key":"kyFjzruyvE0yTdMokzgCBw",async:!0})]}),e.jsxs("header",{className:`${z?"absolute":"sticky"} top-0 left-0 right-0 z-50 transition-all ${ie}`,children:[e.jsx("div",{className:"max-w-7xl mx-auto px-6 lg:px-8",children:e.jsxs("div",{className:"flex items-center justify-between h-20",children:[e.jsxs(Xn,{to:"/",className:"flex items-center gap-3",children:[((We=t.agent)==null?void 0:We.avatar_url)&&e.jsx("img",{src:t.agent.avatar_url,alt:A,className:"h-10 w-10 rounded-full object-cover ring-2 ring-white/20"}),e.jsx("div",{children:e.jsx("span",{className:"font-bold text-lg leading-none tracking-tight",children:D})})]}),e.jsxs("nav",{className:"hidden md:flex items-center gap-1",children:[J.map(De=>e.jsx(Xn,{to:De.to,className:`px-4 py-2 rounded-lg text-sm font-medium tracking-wide transition-colors ${r.pathname===De.to?z?"bg-white/15 text-white":"bg-gray-100 text-gray-900":z?"text-white/70 hover:text-white hover:bg-white/10":"text-gray-500 hover:text-gray-900 hover:bg-gray-50"}`,children:De.label},De.to)),ee&&K.map(De=>{if(De.item_type==="dropdown"){const pe=re(De.id);return e.jsxs("div",{ref:j,className:"relative",children:[e.jsxs("button",{onClick:()=>_(y===De.id?null:De.id),className:`flex items-center gap-1 px-4 py-2 rounded-lg text-sm font-medium tracking-wide transition-colors ${z?"text-white/70 hover:text-white hover:bg-white/10":"text-gray-500 hover:text-gray-900 hover:bg-gray-50"}`,children:[De.label," ",e.jsx(Io,{className:`h-3.5 w-3.5 transition-transform ${y===De.id?"rotate-180":""}`})]}),y===De.id&&pe.length>0&&e.jsx("div",{className:"absolute top-full right-0 mt-2 w-52 bg-white rounded-xl shadow-xl border border-gray-100 py-2 z-50 animate-in fade-in slide-in-from-top-2 duration-150",children:pe.map(tt=>e.jsx(wV,{item:tt,onClick:()=>_(null),className:"w-full text-left px-4 py-2.5 text-sm text-gray-700 hover:bg-gray-50 hover:text-gray-900 transition-colors block"},tt.id))})]},De.id)}return e.jsx(wV,{item:De,className:`px-4 py-2 rounded-lg text-sm font-medium tracking-wide transition-colors ${z?"text-white/70 hover:text-white hover:bg-white/10":"text-gray-500 hover:text-gray-900 hover:bg-gray-50"}`},De.id)}),h.length>0&&e.jsxs("div",{ref:b,className:"relative",children:[e.jsxs("button",{onClick:()=>d(!c),className:`flex items-center gap-1 px-4 py-2 rounded-lg text-sm font-medium tracking-wide transition-colors ${r.pathname.startsWith("/homes-for-sale-in-")?z?"bg-white/15 text-white":"bg-gray-100 text-gray-900":z?"text-white/70 hover:text-white hover:bg-white/10":"text-gray-500 hover:text-gray-900 hover:bg-gray-50"}`,children:["Cities ",e.jsx(Io,{className:`h-3.5 w-3.5 transition-transform ${c?"rotate-180":""}`})]}),c&&e.jsx("div",{className:"absolute top-full right-0 mt-2 w-52 bg-white rounded-xl shadow-xl border border-gray-100 py-2 z-50 animate-in fade-in slide-in-from-top-2 duration-150",children:h.map(De=>e.jsx("button",{onClick:()=>{n(`/homes-for-sale-in-${De.city_slug}`),d(!1)},className:"w-full text-left px-4 py-2.5 text-sm text-gray-700 hover:bg-gray-50 hover:text-gray-900 transition-colors",children:De.city_name},De.city_slug))})]}),k?e.jsxs("div",{className:"flex items-center gap-1 ml-2",children:[e.jsxs(Xn,{to:"/account",className:`flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm font-medium transition-colors ${z?"text-white/70 hover:text-white hover:bg-white/10":"text-gray-500 hover:text-gray-900 hover:bg-gray-50"}`,children:[e.jsx(Bi,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden lg:inline",children:"Saved"})]}),e.jsxs(Xn,{to:"/account",className:`flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm font-medium transition-colors ${z?"text-white/70 hover:text-white hover:bg-white/10":"text-gray-500 hover:text-gray-900 hover:bg-gray-50"}`,children:[e.jsx(io,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden lg:inline",children:((Ve=T==null?void 0:T.name)==null?void 0:Ve.split(" ")[0])||"Account"})]})]}):O?e.jsx("button",{onClick:()=>o(!0),className:`ml-2 px-4 py-2 rounded-lg text-sm font-medium transition-colors ${z?"bg-white/15 text-white hover:bg-white/25":"bg-blue-600 text-white hover:bg-blue-700"}`,children:"Sign In"}):null]}),e.jsx("button",{onClick:()=>i(!a),className:`md:hidden p-2 rounded-lg ${z?"text-white hover:bg-white/10":"text-gray-600 hover:bg-gray-100"}`,children:a?e.jsx(Rr,{className:"h-5 w-5"}):e.jsx(TE,{className:"h-5 w-5"})})]})}),a&&e.jsx("div",{className:`md:hidden border-t ${z?"border-white/10 bg-black/95 backdrop-blur":"border-gray-100 bg-white"} max-h-[calc(100vh-5rem)] overflow-y-auto overscroll-contain`,children:e.jsxs("div",{className:"px-4 py-3 space-y-1 pb-8",children:[J.map(De=>e.jsx(Xn,{to:De.to,onClick:()=>i(!1),className:`block px-3 py-2.5 rounded-lg text-sm font-medium ${r.pathname===De.to?z?"bg-white/15 text-white":"bg-gray-100 text-gray-900":z?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`,children:De.label},De.to)),ee&&K.map(De=>{if(De.item_type==="dropdown"){const pe=re(De.id);return e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:`px-3 pt-3 pb-1 text-xs font-semibold uppercase tracking-wider ${z?"text-white/40":"text-gray-400"}`,children:De.label}),pe.map(tt=>e.jsx(wV,{item:tt,onClick:()=>i(!1),className:`block px-3 py-2.5 rounded-lg text-sm font-medium ${z?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`},tt.id))]},De.id)}return e.jsx(wV,{item:De,onClick:()=>i(!1),className:`block px-3 py-2.5 rounded-lg text-sm font-medium ${z?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`},De.id)}),h.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:`px-3 pt-3 pb-1 text-xs font-semibold uppercase tracking-wider ${z?"text-white/40":"text-gray-400"}`,children:"Cities"}),h.map(De=>e.jsx(Xn,{to:`/homes-for-sale-in-${De.city_slug}`,onClick:()=>i(!1),className:`block px-3 py-2.5 rounded-lg text-sm font-medium ${r.pathname===`/homes-for-sale-in-${De.city_slug}`?z?"bg-white/15 text-white":"bg-gray-100 text-gray-900":z?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`,children:De.city_name},De.city_slug))]}),k?e.jsxs(e.Fragment,{children:[e.jsx(Xn,{to:"/account",onClick:()=>i(!1),className:`block px-3 py-2.5 rounded-lg text-sm font-medium ${z?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`,children:"My Account"}),e.jsx("button",{onClick:async()=>{await E(),i(!1)},className:`block w-full text-left px-3 py-2.5 rounded-lg text-sm font-medium ${z?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`,children:"Sign Out"})]}):O?e.jsx("button",{onClick:()=>{o(!0),i(!1)},className:`block w-full text-left px-3 py-2.5 rounded-lg text-sm font-medium ${z?"text-white/70 hover:bg-white/10":"text-blue-600 hover:bg-blue-50"}`,children:"Sign In / Register"}):null]})})]}),e.jsx("main",{className:"flex-1 min-h-0 flex flex-col",children:s}),!R&&e.jsx("footer",{className:"bg-gray-950 text-gray-400",children:e.jsxs("div",{className:"max-w-7xl mx-auto px-6 lg:px-8 py-16",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-12",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-4 mb-4",children:[((Le=t.agent)==null?void 0:Le.avatar_url)&&e.jsx("img",{src:t.agent.avatar_url,alt:A,className:"h-16 w-16 rounded-2xl object-cover ring-2 ring-white/10"}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-bold text-white text-lg tracking-tight",children:A}),e.jsx("p",{className:"text-sm text-gray-500",children:((Me=t.agent)==null?void 0:Me.title)||"Real Estate Professional"})]})]}),((ze=t.agent)==null?void 0:ze.phone)&&e.jsx("p",{className:"text-sm mt-3",children:e.jsxs("a",{href:`tel:${t.agent.phone}`,className:"hover:text-white transition-colors flex items-center gap-2",children:[e.jsx(Yn,{className:"h-3.5 w-3.5"})," ",t.agent.phone]})}),((Pe=t.agent)==null?void 0:Pe.email)&&e.jsx("p",{className:"text-sm mt-1",children:e.jsxs("a",{href:`mailto:${t.agent.email}`,className:"hover:text-white transition-colors flex items-center gap-2",children:[e.jsx(er,{className:"h-3.5 w-3.5"})," ",t.agent.email]})})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-semibold text-white mb-4 text-sm tracking-wider uppercase",children:"Quick Links"}),e.jsx("ul",{className:"space-y-3 text-sm",children:J.map(De=>e.jsx("li",{children:e.jsx(Xn,{to:De.to,className:"hover:text-white transition-colors",children:De.label})},De.to))})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-semibold text-white mb-4 text-sm tracking-wider uppercase",children:"Get In Touch"}),e.jsx("p",{className:"text-sm text-gray-500 leading-relaxed mb-4",children:"Ready to find your dream home? Get in touch today for a personalized consultation."}),e.jsx(Xn,{to:"/contact",className:"inline-block px-5 py-2.5 bg-white text-gray-900 text-sm font-semibold rounded-lg hover:bg-gray-100 transition-colors",children:"Contact Me"})]})]}),e.jsxs("div",{className:"mt-14 pt-6 border-t border-gray-800/50",children:[t.showTeamLogo&&t.teamLogoUrl&&e.jsx("div",{className:"flex items-center justify-center mb-6",children:e.jsx("img",{src:t.teamLogoUrl,alt:"Team",className:"h-12 w-auto object-contain"})}),t.brokerageLegalName&&e.jsxs("div",{className:"flex flex-wrap items-center justify-center gap-x-4 gap-y-1 text-xs text-gray-500 mb-3",children:[e.jsxs("span",{children:[A," · ",t.brokerageLegalName]}),t.agentLicenseNumber&&e.jsx("span",{children:t.agentLicenseNumber}),t.brokerageLicenseNumber&&e.jsxs("span",{children:["Brokerage #",t.brokerageLicenseNumber]})]}),t.mlsDisclaimerText&&e.jsxs("div",{className:"flex items-start justify-center gap-3 mb-4",children:[t.mlsLogoUrl&&e.jsx("img",{src:t.mlsLogoUrl,alt:"MLS",className:"h-8 w-auto flex-shrink-0 mt-0.5"}),e.jsx("p",{className:"text-[11px] text-gray-600 leading-relaxed max-w-3xl text-center",children:t.mlsDisclaimerText})]}),e.jsxs("div",{className:"flex items-center justify-center gap-4 text-xs text-gray-600",children:[t.equalHousingEnabled&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor",className:"h-5 w-5 text-gray-500",children:e.jsx("path",{d:"M12 2L2 8v2h20V8L12 2zm0 2.5L18.5 8h-13L12 4.5zM4 12v8h4v-6h8v6h4v-8H4zm6 8v-4h4v4h-4z"})}),e.jsx("span",{children:"Equal Housing Opportunity"})]}),e.jsxs("span",{children:["© ",new Date().getFullYear()," ",A,". Powered by LevelUp."]})]})]})]})}),!R&&((Ie=t.agent)==null?void 0:Ie.avatar_url)&&e.jsx(tKs,{agent:t.agent}),l&&e.jsx(v6e,{open:l,mode:"optional",siteConfig:t,onComplete:()=>o(!1),onSkip:()=>o(!1)}),e.jsx(Y6e,{slug:t.subdomainSlug}),e.jsx(Z6e,{slug:t.subdomainSlug}),e.jsx(Q6e,{slug:t.subdomainSlug})]})}function tKs({agent:s}){var a;const[t,r]=S.useState(!1),n=Fr();return s?e.jsx("div",{className:"fixed bottom-6 right-6 z-40",children:t?e.jsxs("div",{className:"bg-white rounded-2xl shadow-2xl border border-gray-200 w-72 overflow-hidden animate-in slide-in-from-bottom-4 fade-in duration-200",children:[e.jsxs("div",{className:"p-5",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[e.jsx("img",{src:s.avatar_url,alt:s.full_name,className:"h-12 w-12 rounded-full object-cover ring-2 ring-gray-100"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-bold text-gray-900 text-sm",children:s.full_name}),e.jsx("p",{className:"text-xs text-gray-500",children:s.title||"Real Estate Professional"})]})]}),e.jsx("p",{className:"text-xs text-gray-500 mb-4",children:"Have questions about a property or the area? I'm here to help!"}),e.jsxs("div",{className:"space-y-2",children:[s.phone&&e.jsxs("a",{href:`tel:${s.phone}`,className:"flex items-center gap-2 w-full px-3 py-2 bg-gray-50 hover:bg-gray-100 rounded-xl text-sm text-gray-700 transition-colors",children:[e.jsx(Yn,{className:"h-4 w-4 text-gray-400"}),s.phone]}),s.email&&e.jsxs("a",{href:`mailto:${s.email}`,className:"flex items-center gap-2 w-full px-3 py-2 bg-gray-50 hover:bg-gray-100 rounded-xl text-sm text-gray-700 transition-colors",children:[e.jsx(er,{className:"h-4 w-4 text-gray-400"}),"Email Me"]}),e.jsx("button",{onClick:()=>{r(!1),n("/contact")},className:"w-full px-3 py-2.5 bg-blue-600 hover:bg-blue-700 text-white text-sm font-semibold rounded-xl transition-colors",children:"Send a Message"})]})]}),e.jsx("button",{onClick:()=>r(!1),className:"absolute top-3 right-3 p-1 text-gray-400 hover:text-gray-600 rounded-full hover:bg-gray-100",children:e.jsx(Rr,{className:"h-4 w-4"})})]}):e.jsxs("button",{onClick:()=>r(!0),className:"group flex items-center gap-3 bg-white pl-1.5 pr-5 py-1.5 rounded-full shadow-xl border border-gray-200 hover:shadow-2xl transition-all hover:scale-105",children:[e.jsx("img",{src:s.avatar_url,alt:s.full_name,className:"h-10 w-10 rounded-full object-cover ring-2 ring-blue-100"}),e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"text-xs font-bold text-gray-900 leading-none",children:(a=s.full_name)==null?void 0:a.split(" ")[0]}),e.jsx("p",{className:"text-[10px] text-blue-600 font-medium mt-0.5",children:"Chat with me →"})]})]})}):null}function wV({item:s,className:t,onClick:r}){const n=s.target_url||"#";return s.item_type==="external"||s.open_in_new_tab?e.jsx("a",{href:n,target:"_blank",rel:"noopener noreferrer",className:t,onClick:r,children:s.label}):e.jsx(Xn,{to:n,className:t,onClick:r,children:s.label})}function sKs({children:s,siteConfig:t}){var le,be,fe,je,ve,We,Ve;const r=Vc(),n=Fr(),[a,i]=S.useState(!1),[l,o]=S.useState(!1),[c,d]=S.useState(!1),[h,m]=S.useState([]),[p,x]=S.useState(!1),y=S.useRef(null),{user:_,profile:b,signOut:j}=dye();w6e(t,_==null?void 0:_.id),j6e(t,_==null?void 0:_.id);const k=((le=t.agent)==null?void 0:le.full_name)||"Agent",T=t.siteTitle||`${k} Real Estate`,E=t.brokerageLegalName?`${k} | ${t.brokerageLegalName}`:k,A=Le=>{if(!Le)return Le;const Me=k.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),ze=new RegExp(`^\\s*${Me}\\s*[|\\-–—:]\\s*`,"i");return Le.replace(ze,"").trim()},D=T&&T!==`${k} Real Estate`?T:null,R=D?A(D):null,z=R&&R.toLowerCase()!==k.toLowerCase()?R:null,O=r.pathname==="/search",$=r.pathname==="/",ee=t.leadRegistrationMode!=="disabled",Z="#c9a96e";S.useEffect(()=>{const Le=()=>x(window.scrollY>80);return window.addEventListener("scroll",Le,{passive:!0}),()=>window.removeEventListener("scroll",Le)},[]),S.useEffect(()=>{(async()=>{const{data:Me}=await V.from("lead_site_city_pages").select("city_name, city_slug").eq("site_id",t.id).eq("is_published",!0).order("sort_order",{ascending:!0});m(Me||[])})()},[t.id]),S.useEffect(()=>{const Le=Me=>{y.current&&!y.current.contains(Me.target)&&d(!1)};return document.addEventListener("mousedown",Le),()=>document.removeEventListener("mousedown",Le)},[]);const J=[{to:"/",label:"Home"},{to:"/search",label:"Search"},{to:"/sell",label:"Sell"},{to:"/blog",label:"Blog"},{to:"/community",label:"Community"},{to:"/about",label:"About"},{to:"/contact",label:"Contact"}],K=t.siteTitle||`${k} - Real Estate`,re=t.siteTagline||`Browse homes and listings with ${k}`,ie=t.ogImageUrl||((be=t.agent)==null?void 0:be.avatar_url)||"",ce=`https://${t.subdomainSlug||""}.thelocalmove.com`,ne=$?p?"bg-[#0d0b0a]/95 backdrop-blur-lg border-b border-white/5":"bg-transparent":"bg-[#0d0b0a] border-b border-white/5";return e.jsxs("div",{className:`flex flex-col ${O?"h-screen overflow-hidden":"min-h-screen"} bg-[#0d0b0a]`,children:[e.jsx(b6e,{siteConfig:t,pagePath:r.pathname}),e.jsx(_6e,{siteConfig:t}),e.jsxs(el,{children:[e.jsx("title",{children:K}),e.jsx("meta",{name:"description",content:re}),e.jsx("meta",{property:"og:title",content:K}),e.jsx("meta",{property:"og:description",content:re}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("meta",{property:"og:url",content:ce+r.pathname}),ie&&e.jsx("meta",{property:"og:image",content:ie}),e.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),e.jsx("meta",{name:"twitter:title",content:K}),e.jsx("meta",{name:"twitter:description",content:re}),ie&&e.jsx("meta",{name:"twitter:image",content:ie}),t.faviconUrl&&e.jsx("link",{rel:"icon",href:t.faviconUrl,type:"image/png"}),e.jsx("link",{rel:"canonical",href:`${ce}${r.pathname}`}),e.jsx("link",{href:"https://fonts.googleapis.com/css2?family=Playfair+Display:ital,wght@0,400;0,500;0,600;0,700;1,400;1,500&display=swap",rel:"stylesheet"})]}),e.jsxs("header",{className:`${$?"fixed":"sticky"} top-0 left-0 right-0 z-50 transition-all duration-500 ${ne}`,children:[e.jsx("div",{className:"max-w-7xl mx-auto px-6 lg:px-8",children:e.jsxs("div",{className:"flex items-center justify-between h-20",children:[e.jsx(Xn,{to:"/",className:"flex items-center gap-3 min-w-0",children:e.jsxs("span",{className:"flex flex-col leading-none max-w-[320px] xl:max-w-[420px]",children:[e.jsx("span",{className:"block whitespace-normal text-white text-xl tracking-tight",style:{fontFamily:"'Playfair Display', Georgia, serif"},children:E}),z&&e.jsx("span",{className:"mt-1 text-[11px] tracking-[0.18em] uppercase text-white/70",children:z})]})}),e.jsxs("nav",{className:"hidden lg:flex items-center gap-1",children:[J.map(Le=>e.jsx(Xn,{to:Le.to,className:`px-4 py-2 text-xs tracking-[0.15em] uppercase transition-colors duration-300 ${r.pathname===Le.to?"text-white":"text-white/40 hover:text-white"}`,children:Le.label},Le.to)),h.length>0&&e.jsxs("div",{ref:y,className:"relative",children:[e.jsxs("button",{onClick:()=>d(!c),className:`flex items-center gap-1 px-4 py-2 text-xs tracking-[0.15em] uppercase transition-colors duration-300 ${r.pathname.startsWith("/homes-for-sale-in-")?"text-white":"text-white/40 hover:text-white"}`,children:["Cities ",e.jsx(Io,{className:`h-3 w-3 transition-transform ${c?"rotate-180":""}`})]}),c&&e.jsx("div",{className:"absolute top-full right-0 mt-2 w-56 bg-[#1a1715] border border-white/10 py-2 z-50 animate-in fade-in slide-in-from-top-2 duration-150",children:h.map(Le=>e.jsx("button",{onClick:()=>{n(`/homes-for-sale-in-${Le.city_slug}`),d(!1)},className:"w-full text-left px-5 py-2.5 text-xs tracking-wider text-white/50 hover:text-white hover:bg-white/5 uppercase transition-colors",children:Le.city_name},Le.city_slug))})]}),_?e.jsxs("div",{className:"flex items-center gap-1 ml-3",children:[e.jsxs(Xn,{to:"/account",className:"flex items-center gap-1.5 px-3 py-2 text-xs tracking-wider text-white/40 hover:text-white uppercase transition-colors",children:[e.jsx(Bi,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden xl:inline",children:"Saved"})]}),e.jsxs(Xn,{to:"/account",className:"flex items-center gap-1.5 px-3 py-2 text-xs tracking-wider text-white/40 hover:text-white uppercase transition-colors",children:[e.jsx(io,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden xl:inline",children:((fe=b==null?void 0:b.name)==null?void 0:fe.split(" ")[0])||"Account"})]})]}):ee?e.jsx("button",{onClick:()=>o(!0),className:"ml-3 px-5 py-2 text-xs tracking-[0.2em] uppercase border border-white/20 text-white/60 hover:bg-white hover:text-black transition-all duration-500",children:"Sign In"}):null]}),e.jsxs("button",{onClick:()=>i(!a),className:"lg:hidden p-2 text-white/60 hover:text-white",children:[e.jsx("div",{className:"flex flex-col items-center gap-0.5",children:a?e.jsx(Rr,{className:"h-5 w-5"}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-6 h-px bg-current"}),e.jsx("div",{className:"w-4 h-px bg-current mt-1.5"}),e.jsx("div",{className:"w-6 h-px bg-current mt-1.5"})]})}),e.jsx("span",{className:"text-[8px] tracking-[0.3em] uppercase mt-1 block",children:"MENU"})]})]})}),a&&e.jsx("div",{className:"lg:hidden border-t border-white/5 bg-[#0d0b0a]/98 backdrop-blur-lg",children:e.jsxs("div",{className:"px-6 py-4 space-y-1",children:[J.map(Le=>e.jsx(Xn,{to:Le.to,onClick:()=>i(!1),className:`block px-3 py-3 text-xs tracking-[0.2em] uppercase transition-colors ${r.pathname===Le.to?"text-white":"text-white/40 hover:text-white"}`,children:Le.label},Le.to)),h.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-3 pt-4 pb-2 text-[10px] tracking-[0.3em] uppercase",style:{color:Z},children:"Cities"}),h.map(Le=>e.jsx(Xn,{to:`/homes-for-sale-in-${Le.city_slug}`,onClick:()=>i(!1),className:"block px-3 py-2.5 text-xs tracking-wider text-white/40 hover:text-white uppercase transition-colors",children:Le.city_name},Le.city_slug))]}),_?e.jsxs(e.Fragment,{children:[e.jsx(Xn,{to:"/account",onClick:()=>i(!1),className:"block px-3 py-3 text-xs tracking-[0.2em] uppercase text-white/40 hover:text-white",children:"My Account"}),e.jsx("button",{onClick:async()=>{await j(),i(!1)},className:"block w-full text-left px-3 py-3 text-xs tracking-[0.2em] uppercase text-white/40 hover:text-white",children:"Sign Out"})]}):ee?e.jsx("button",{onClick:()=>{o(!0),i(!1)},className:"block w-full text-left px-3 py-3 text-xs tracking-[0.2em] uppercase text-white/40 hover:text-white",children:"Sign In / Register"}):null]})})]}),e.jsx("main",{className:"flex-1 min-h-0 flex flex-col",children:s}),!O&&e.jsx("footer",{className:"bg-[#0a0908] text-white/30 border-t border-white/5",children:e.jsxs("div",{className:"max-w-7xl mx-auto px-6 lg:px-8 py-20",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-16",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-white text-xl tracking-tight mb-6",style:{fontFamily:"'Playfair Display', Georgia, serif"},children:k}),e.jsx("p",{className:"text-white/20 text-xs tracking-[0.15em] uppercase mb-6",children:((je=t.agent)==null?void 0:je.title)||"Real Estate Professional"}),((ve=t.agent)==null?void 0:ve.phone)&&e.jsxs("a",{href:`tel:${t.agent.phone}`,className:"flex items-center gap-3 text-sm text-white/30 hover:text-white transition-colors mb-3",children:[e.jsx(Yn,{className:"h-3.5 w-3.5"})," ",t.agent.phone]}),((We=t.agent)==null?void 0:We.email)&&e.jsxs("a",{href:`mailto:${t.agent.email}`,className:"flex items-center gap-3 text-sm text-white/30 hover:text-white transition-colors",children:[e.jsx(er,{className:"h-3.5 w-3.5"})," ",t.agent.email]})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-xs tracking-[0.3em] uppercase mb-6",style:{color:Z},children:"Quick Links"}),e.jsx("ul",{className:"space-y-3",children:J.map(Le=>e.jsx("li",{children:e.jsx(Xn,{to:Le.to,className:"text-xs tracking-wider uppercase text-white/30 hover:text-white transition-colors",children:Le.label})},Le.to))})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-xs tracking-[0.3em] uppercase mb-6",style:{color:Z},children:"Get In Touch"}),e.jsx("p",{className:"text-sm text-white/20 leading-relaxed mb-6",style:{fontFamily:"'Playfair Display', Georgia, serif",fontStyle:"italic"},children:"Ready to experience luxury real estate? Let's connect."}),e.jsx(Xn,{to:"/contact",className:"inline-block px-8 py-3 text-xs tracking-[0.3em] uppercase border border-white/15 text-white/50 hover:bg-white hover:text-black transition-all duration-500",children:"Contact Me"})]})]}),e.jsxs("div",{className:"mt-16 pt-8 border-t border-white/5",children:[t.showTeamLogo&&t.teamLogoUrl&&e.jsx("div",{className:"flex items-center justify-center mb-6",children:e.jsx("img",{src:t.teamLogoUrl,alt:"Team",className:"h-10 w-auto object-contain opacity-40"})}),t.brokerageLegalName&&e.jsxs("div",{className:"flex flex-wrap items-center justify-center gap-x-4 gap-y-1 text-[10px] text-white/15 tracking-wider uppercase mb-3",children:[e.jsxs("span",{children:[k," · ",t.brokerageLegalName]}),t.agentLicenseNumber&&e.jsx("span",{children:t.agentLicenseNumber}),t.brokerageLicenseNumber&&e.jsxs("span",{children:["Brokerage #",t.brokerageLicenseNumber]})]}),t.mlsDisclaimerText&&e.jsxs("div",{className:"flex items-start justify-center gap-3 mb-4",children:[t.mlsLogoUrl&&e.jsx("img",{src:t.mlsLogoUrl,alt:"MLS",className:"h-6 w-auto flex-shrink-0 mt-0.5 opacity-30"}),e.jsx("p",{className:"text-[10px] text-white/15 leading-relaxed max-w-3xl text-center",children:t.mlsDisclaimerText})]}),e.jsxs("div",{className:"flex items-center justify-center gap-4 text-[10px] text-white/15 tracking-wider uppercase",children:[t.equalHousingEnabled&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor",className:"h-4 w-4",children:e.jsx("path",{d:"M12 2L2 8v2h20V8L12 2zm0 2.5L18.5 8h-13L12 4.5zM4 12v8h4v-6h8v6h4v-8H4zm6 8v-4h4v4h-4z"})}),e.jsx("span",{children:"Equal Housing Opportunity"})]}),e.jsxs("span",{children:["© ",new Date().getFullYear()," ",k,". Powered by LevelUp."]})]})]})]})}),!O&&((Ve=t.agent)==null?void 0:Ve.avatar_url)&&e.jsx(rKs,{agent:t.agent,accentColor:Z}),l&&e.jsx(v6e,{open:l,mode:"optional",siteConfig:t,onComplete:()=>o(!1),onSkip:()=>o(!1),theme:"luxury",accentColor:Z}),e.jsx(Y6e,{slug:t.subdomainSlug}),e.jsx(Z6e,{slug:t.subdomainSlug}),e.jsx(Q6e,{slug:t.subdomainSlug})]})}function rKs({agent:s,accentColor:t}){var i;const[r,n]=S.useState(!1),a=Fr();return s?e.jsx("div",{className:"fixed bottom-6 right-6 z-40",children:r?e.jsxs("div",{className:"bg-[#1a1715] border border-white/10 w-72 overflow-hidden animate-in slide-in-from-bottom-4 fade-in duration-200",children:[e.jsxs("div",{className:"p-5",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[e.jsx("img",{src:s.avatar_url,alt:s.full_name,className:"h-12 w-12 rounded-full object-cover ring-1 ring-white/10"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-white text-sm font-medium",style:{fontFamily:"'Playfair Display', Georgia, serif"},children:s.full_name}),e.jsx("p",{className:"text-white/30 text-[10px] tracking-[0.1em] uppercase",children:s.title||"Real Estate Professional"})]})]}),e.jsxs("div",{className:"space-y-2",children:[s.phone&&e.jsxs("a",{href:`tel:${s.phone}`,className:"flex items-center gap-2 w-full px-3 py-2.5 bg-white/5 hover:bg-white/10 text-xs text-white/50 hover:text-white transition-colors tracking-wider",children:[e.jsx(Yn,{className:"h-3.5 w-3.5"})," ",s.phone]}),s.email&&e.jsxs("a",{href:`mailto:${s.email}`,className:"flex items-center gap-2 w-full px-3 py-2.5 bg-white/5 hover:bg-white/10 text-xs text-white/50 hover:text-white transition-colors tracking-wider",children:[e.jsx(er,{className:"h-3.5 w-3.5"})," Email Me"]}),e.jsx("button",{onClick:()=>{n(!1),a("/contact")},className:"w-full px-3 py-2.5 text-xs tracking-[0.2em] uppercase text-black hover:opacity-90 transition-colors",style:{backgroundColor:t},children:"Send a Message"})]})]}),e.jsx("button",{onClick:()=>n(!1),className:"absolute top-3 right-3 p-1 text-white/20 hover:text-white/50",children:e.jsx(Rr,{className:"h-4 w-4"})})]}):e.jsxs("button",{onClick:()=>n(!0),className:"group flex items-center gap-3 bg-[#1a1715] border border-white/10 pl-1.5 pr-5 py-1.5 hover:border-white/20 transition-all",children:[e.jsx("img",{src:s.avatar_url,alt:s.full_name,className:"h-10 w-10 rounded-full object-cover ring-1 ring-white/10"}),e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"text-[11px] text-white leading-none",style:{fontFamily:"'Playfair Display', Georgia, serif"},children:(i=s.full_name)==null?void 0:i.split(" ")[0]}),e.jsx("p",{className:"text-[9px] tracking-[0.15em] uppercase mt-1",style:{color:t},children:"Let's connect →"})]})]})}):null}const oO="#2c1810",Ib="#b8860b";function nKs({children:s,siteConfig:t}){var z,O,$;const r=Vc();Fr();const[n,a]=S.useState(!1),[i,l]=S.useState(!1),[o,c]=S.useState(!1),[d,h]=S.useState([]),[m,p]=S.useState(!1),x=S.useRef(null),{user:y,profile:_,signOut:b}=dye();w6e(t,y==null?void 0:y.id),j6e(t,y==null?void 0:y.id);const j=((z=t.agent)==null?void 0:z.full_name)||"Agent",k=t.siteTitle||`${j} Land & Ranch`,T=r.pathname==="/",E=t.leadRegistrationMode!=="disabled";S.useEffect(()=>{const ee=()=>p(window.scrollY>80);return window.addEventListener("scroll",ee,{passive:!0}),()=>window.removeEventListener("scroll",ee)},[]),S.useEffect(()=>{(async()=>{const{data:Z}=await V.from("lead_site_city_pages").select("city_name, city_slug").eq("site_id",t.id).eq("is_published",!0).order("sort_order");Z&&h(Z)})()},[t.id]),S.useEffect(()=>{const ee=Z=>{x.current&&!x.current.contains(Z.target)&&c(!1)};return document.addEventListener("mousedown",ee),()=>document.removeEventListener("mousedown",ee)},[]);const A=[{label:"Home",path:"/"},{label:"Search Properties",path:"/search"},{label:"About",path:"/about"},{label:"Blog",path:"/blog"},{label:"Contact",path:"/contact"}],D=m||!T?"bg-white/95 backdrop-blur-md shadow-sm":"bg-transparent",R=m||!T?oO:"#ffffff";return e.jsxs("div",{className:"min-h-screen",style:{fontFamily:"'Lora', Georgia, serif"},children:[e.jsxs(el,{children:[e.jsx("title",{children:k}),e.jsx("link",{href:"https://fonts.googleapis.com/css2?family=Playfair+Display:wght@400;600;700;800&family=Lora:wght@400;500;600&display=swap",rel:"stylesheet"})]}),e.jsx(b6e,{siteConfig:t}),e.jsx(_6e,{siteConfig:t}),e.jsxs("header",{className:`fixed top-0 left-0 right-0 z-50 transition-all duration-300 ${D}`,children:[e.jsx("div",{className:"max-w-7xl mx-auto px-4 sm:px-6",children:e.jsxs("div",{className:"flex items-center justify-between h-16 md:h-20",children:[e.jsxs(Xn,{to:"/",className:"flex items-center gap-2.5",children:[e.jsx(LI,{className:"w-7 h-7",style:{color:Ib}}),e.jsx("span",{className:"text-lg font-bold tracking-wide",style:{color:R,fontFamily:"'Playfair Display', Georgia, serif"},children:k})]}),e.jsxs("nav",{className:"hidden md:flex items-center gap-1",children:[A.map(ee=>e.jsx(Xn,{to:ee.path,className:"px-4 py-2 text-sm font-medium tracking-wide uppercase transition-colors hover:opacity-80",style:{color:r.pathname===ee.path?Ib:R},children:ee.label},ee.path)),d.length>0&&e.jsxs("div",{ref:x,className:"relative",children:[e.jsxs("button",{onClick:()=>c(!o),className:"px-4 py-2 text-sm font-medium tracking-wide uppercase flex items-center gap-1 transition-colors hover:opacity-80",style:{color:R},children:["Areas ",e.jsx(Io,{className:`w-3.5 h-3.5 transition-transform ${o?"rotate-180":""}`})]}),o&&e.jsx("div",{className:"absolute top-full right-0 mt-2 w-56 bg-white rounded-xl shadow-xl border border-gray-100 py-2 animate-in fade-in-0 slide-in-from-top-2",children:d.map(ee=>e.jsx(Xn,{to:`/homes-for-sale-in-${ee.city_slug}`,className:"block px-4 py-2.5 text-sm hover:bg-gray-50 transition-colors",style:{color:oO},onClick:()=>c(!1),children:ee.city_name},ee.city_slug))})]}),y?e.jsx("div",{className:"flex items-center gap-2 ml-3",children:e.jsxs(Xn,{to:"/account",className:"px-4 py-2 text-sm font-medium rounded-full border-2 transition-all hover:scale-105",style:{borderColor:Ib,color:R},children:[e.jsx(io,{className:"w-4 h-4 inline mr-1.5"}),(_==null?void 0:_.name)||"Account"]})}):E?e.jsx("button",{onClick:()=>l(!0),className:"ml-3 px-5 py-2.5 text-sm font-semibold text-white rounded-full hover:shadow-lg transition-all hover:scale-105",style:{backgroundColor:Ib},children:"Sign In"}):null]}),e.jsx("button",{onClick:()=>a(!n),className:"md:hidden p-2",style:{color:R},children:n?e.jsx(Rr,{className:"w-6 h-6"}):e.jsx(TE,{className:"w-6 h-6"})})]})}),n&&e.jsx("div",{className:"md:hidden bg-white border-t border-gray-100 shadow-xl animate-in slide-in-from-top-2",children:e.jsxs("div",{className:"px-4 py-4 space-y-1",children:[A.map(ee=>e.jsx(Xn,{to:ee.path,className:"block px-4 py-3 text-base font-medium rounded-lg hover:bg-gray-50 transition-colors",style:{color:r.pathname===ee.path?Ib:oO},onClick:()=>a(!1),children:ee.label},ee.path)),d.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-4 py-2 text-xs font-semibold tracking-wider uppercase text-gray-400",children:"Areas"}),d.map(ee=>e.jsx(Xn,{to:`/homes-for-sale-in-${ee.city_slug}`,className:"block px-4 py-2.5 text-sm rounded-lg hover:bg-gray-50",style:{color:oO},onClick:()=>a(!1),children:ee.city_name},ee.city_slug))]}),!y&&E&&e.jsx("button",{onClick:()=>{l(!0),a(!1)},className:"w-full mt-3 px-5 py-3 text-white font-semibold rounded-full",style:{backgroundColor:Ib},children:"Sign In"})]})})]}),e.jsx("main",{children:s}),e.jsx("footer",{className:"py-16 px-4",style:{backgroundColor:oO},children:e.jsxs("div",{className:"max-w-6xl mx-auto",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-10",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx(LI,{className:"w-6 h-6",style:{color:Ib}}),e.jsx("span",{className:"text-lg font-bold text-white",style:{fontFamily:"'Playfair Display', Georgia, serif"},children:k})]}),e.jsx("p",{className:"text-white/60 text-sm leading-relaxed",children:"Your trusted specialist in land, ranch, and rural properties. Expert guidance for every acre."})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-white font-semibold mb-4 text-sm tracking-wider uppercase",children:"Quick Links"}),e.jsx("div",{className:"space-y-2",children:A.map(ee=>e.jsx(Xn,{to:ee.path,className:"block text-white/60 hover:text-white text-sm transition-colors",children:ee.label},ee.path))})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-white font-semibold mb-4 text-sm tracking-wider uppercase",children:"Contact"}),e.jsxs("div",{className:"space-y-3",children:[((O=t.agent)==null?void 0:O.phone)&&e.jsxs("a",{href:`tel:${t.agent.phone}`,className:"flex items-center gap-2 text-white/60 hover:text-white text-sm transition-colors",children:[e.jsx(Yn,{className:"w-4 h-4",style:{color:Ib}}),t.agent.phone]}),(($=t.agent)==null?void 0:$.email)&&e.jsxs("a",{href:`mailto:${t.agent.email}`,className:"flex items-center gap-2 text-white/60 hover:text-white text-sm transition-colors",children:[e.jsx(er,{className:"w-4 h-4",style:{color:Ib}}),t.agent.email]})]})]})]}),e.jsxs("div",{className:"mt-12 pt-8 border-t border-white/10 flex items-center justify-between",children:[e.jsxs("p",{className:"text-white/40 text-xs",children:["© ",new Date().getFullYear()," ",k,". All rights reserved."]}),e.jsx("div",{className:"h-px w-16",style:{backgroundColor:Ib}})]})]})}),i&&e.jsx(v6e,{open:i,mode:t.leadRegistrationMode==="required"?"required":"optional",siteConfig:t,onSkip:()=>l(!1),onComplete:()=>l(!1)}),e.jsx(Y6e,{slug:t.subdomainSlug}),e.jsx(Z6e,{slug:t.subdomainSlug}),e.jsx(Q6e,{slug:t.subdomainSlug})]})}const aKs=S.lazy(()=>Ti(()=>import("./LeadSiteHome-760wC_Hs.js"),__vite__mapDeps([0,1,2,3]))),iKs=S.lazy(()=>Ti(()=>import("./LeadSiteLuxuryHome-cDAp7Hfb.js"),__vite__mapDeps([4,2,3]))),oKs=S.lazy(()=>Ti(()=>import("./LeadSiteLandRanchHome-B9Gs3Yiq.js"),__vite__mapDeps([5,1,2,3]))),lKs=S.lazy(()=>Ti(()=>import("./LeadSiteSearch-Bq-aIH-g.js"),__vite__mapDeps([6,1,7,3,8]))),cKs=S.lazy(()=>Ti(()=>import("./LeadSiteLuxurySearch-Ber2cw73.js"),__vite__mapDeps([9,1,7,3,8]))),dKs=S.lazy(()=>Ti(()=>import("./LeadSiteListingDetail-Cstv6WyB.js"),__vite__mapDeps([10,11,3,12]))),uKs=S.lazy(()=>Ti(()=>import("./LeadSiteLuxuryListingDetail-mjTwomMD.js"),__vite__mapDeps([13,11,3,12]))),hKs=S.lazy(()=>Ti(()=>import("./LeadSiteAbout-Bc2ZmgUb.js"),[])),mKs=S.lazy(()=>Ti(()=>import("./LeadSiteLuxuryAbout-D4VDP1en.js"),[])),fKs=S.lazy(()=>Ti(()=>import("./LeadSiteContact-BIBMoBEw.js"),[])),pKs=S.lazy(()=>Ti(()=>import("./LeadSiteLuxuryContact-CaGCGxbX.js"),[])),gKs=S.lazy(()=>Ti(()=>import("./LeadSiteConsumerDashboard-DBaIR-HP.js"),[])),xYe=S.lazy(()=>Ti(()=>import("./LeadSiteBlog-xXqws6tM.js"),[])),xKs=S.lazy(()=>Ti(()=>import("./LeadSiteCommunity-CEBe8u_z.js"),[])),yKs=S.lazy(()=>Ti(()=>import("./LeadSiteSellers-BZLzh8Tr.js"),[])),vKs=S.lazy(()=>Ti(()=>import("./LeadSiteCityPage-siD5Qjgy.js"),__vite__mapDeps([14,3,8]))),bKs=S.lazy(()=>Ti(()=>import("./LeadSiteSubdivisionPage-rEaCgKKL.js"),__vite__mapDeps([15,3]))),_Ks=S.lazy(()=>Ti(()=>import("./LeadSiteCustomPage-BLAXsRsl.js"),[]));function wKs(){return e.jsx("div",{className:"min-h-[60vh] flex items-center justify-center",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-blue-600 border-t-transparent"})})}function jKs(){const{siteConfig:s,themeConfig:t,isLoading:r,error:n}=EUs();if(r)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-white",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-blue-600 border-t-transparent mx-auto mb-4"}),e.jsx("p",{className:"text-gray-500",children:"Loading..."})]})});if(n||!s)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gray-50 p-6",children:e.jsxs("div",{className:"text-center max-w-md",children:[e.jsx("h1",{className:"text-2xl font-bold text-gray-900 mb-2",children:"Site Not Found"}),e.jsx("p",{className:"text-gray-500",children:"This lead site is not available or has not been set up yet."})]})});const a=(t==null?void 0:t.themeTier)==="luxury",i=(t==null?void 0:t.themeTier)==="land-ranch",l=i?nKs:a?sKs:eKs,o=i?e.jsx(oKs,{siteConfig:s,themeConfig:t??void 0}):a?e.jsx(iKs,{siteConfig:s,themeConfig:t??void 0}):e.jsx(aKs,{siteConfig:s,themeConfig:t??void 0});return e.jsx(MUs,{siteConfig:s,children:e.jsx(l,{siteConfig:s,children:e.jsx(S.Suspense,{fallback:e.jsx(wKs,{}),children:e.jsxs(She,{children:[e.jsx(gs,{path:"/",element:o}),e.jsx(gs,{path:"/search",element:a?e.jsx(cKs,{siteConfig:s}):e.jsx(lKs,{siteConfig:s})}),e.jsx(gs,{path:"/listing/:mlsNumber",element:a?e.jsx(uKs,{siteConfig:s}):e.jsx(dKs,{siteConfig:s})}),e.jsx(gs,{path:"/about",element:a?e.jsx(mKs,{siteConfig:s}):e.jsx(hKs,{siteConfig:s})}),e.jsx(gs,{path:"/contact",element:a?e.jsx(pKs,{siteConfig:s}):e.jsx(fKs,{siteConfig:s})}),e.jsx(gs,{path:"/account",element:e.jsx(gKs,{siteConfig:s})}),e.jsx(gs,{path:"/blog",element:e.jsx(xYe,{siteConfig:s,isLuxury:a})}),e.jsx(gs,{path:"/blog/:slug",element:e.jsx(xYe,{siteConfig:s,isLuxury:a})}),e.jsx(gs,{path:"/sell",element:e.jsx(yKs,{siteConfig:s,themeConfig:t??void 0,isLuxury:a})}),e.jsx(gs,{path:"/community",element:e.jsx(xKs,{siteConfig:s,isLuxury:a})}),e.jsx(gs,{path:"/p/:pageSlug",element:e.jsx(_Ks,{siteConfig:s})}),e.jsx(gs,{path:"/*",element:e.jsx(NKs,{siteConfig:s,referralMode:(t==null?void 0:t.referralMode)===!0||!s.mlsProviderId})})]})})})})}function NKs({siteConfig:s,referralMode:t}){const r=Vc(),n=r.pathname.match(/^\/homes-in-(.+)$/);if(n)return e.jsx(bKs,{siteConfig:s,subdivisionSlug:n[1]});const a=r.pathname.match(/^\/homes-for-sale-in-(.+)$/);return a?e.jsx(vKs,{siteConfig:s,citySlugOverride:a[1],referralMode:t}):null}const kKs=({team:s,onSelect:t})=>{const{data:r}=yt({queryKey:["team-card-info",s.id],queryFn:async()=>{const{data:n}=await V.from("team_members").select("user_id, role").eq("team_id",s.id),a=(n==null?void 0:n.length)||0,i=n==null?void 0:n.find(o=>o.role==="team_leader");let l=null;if(i){const{data:o}=await V.from("profiles").select("name, avatar_url").eq("id",i.user_id).single();l=o}return{count:a,leaderProfile:l}}});return e.jsxs(ke,{className:"cursor-pointer hover:shadow-md transition-shadow group",onClick:t,children:[e.jsx(Ot,{className:"pb-3",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(zt,{className:"text-lg truncate",children:s.name}),s.description&&e.jsx(Br,{className:"mt-1 line-clamp-2",children:s.description})]}),e.jsxs(Xe,{variant:"secondary",className:"ml-2 shrink-0",children:[e.jsx(Ar,{className:"h-3 w-3 mr-1"}),(r==null?void 0:r.count)??"…"]})]})}),e.jsxs(Oe,{className:"space-y-3",children:[(r==null?void 0:r.leaderProfile)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Un,{className:"h-6 w-6",children:[e.jsx(Ka,{src:r.leaderProfile.avatar_url||""}),e.jsx(qn,{className:"text-xs",children:(r.leaderProfile.name||"?").charAt(0).toUpperCase()})]}),e.jsxs("span",{className:"text-sm text-muted-foreground flex items-center gap-1",children:[e.jsx(zf,{className:"h-3 w-3 text-[hsl(var(--chart-4))]"}),r.leaderProfile.name||"Team Leader"]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap text-sm text-muted-foreground",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Fh,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"capitalize text-xs",children:s.contact_visibility.replace("_"," ")})]}),s.lead_pond_enabled&&e.jsx(Xe,{variant:"outline",className:"text-xs py-0",children:"Lead Pond"}),s.shared_assets_enabled&&e.jsx(Xe,{variant:"outline",className:"text-xs py-0",children:"Shared Assets"}),s.shared_videos_enabled&&e.jsx(Xe,{variant:"outline",className:"text-xs py-0",children:"Shared Videos"})]})]})]})},SKs=()=>{const{user:s,isAdmin:t,isBrokerageManager:r,brokerageId:n,managedBrokerages:a,selectedBrokerageId:i}=Ms(),l=i||(a.length>0?a[0].id:n),o=t?void 0:l||void 0,{teams:c,isLoading:d,createTeam:h,updateTeam:m,deleteTeam:p,addMember:x,removeMember:y,updateMemberRole:_}=XA(o),[b,j]=S.useState(!1),[k,T]=S.useState(null),{data:E}=yt({queryKey:["all-brokerages-for-teams"],queryFn:async()=>{const{data:R,error:z}=await V.from("brokerages").select("id, name").order("name");if(z)throw z;return R||[]},enabled:t}),{data:A}=yt({queryKey:["brokerage-agents-for-teams",l],queryFn:async()=>{const{data:R,error:z}=await V.from("profiles").select("id, name, email, avatar_url").eq("brokerage_id",l).order("name");if(z)throw z;return R||[]},enabled:!!l}),D=async R=>{const z=R.brokerage_id||l||null,O=await h.mutateAsync({name:R.name,brokerage_id:z,description:R.description});if(R.leaderId&&R.leaderId!=="none"&&await x.mutateAsync({team_id:O.id,user_id:R.leaderId,role:"team_leader"}),R.memberIds)for(const $ of R.memberIds)await x.mutateAsync({team_id:O.id,user_id:$,role:"team_member"});j(!1)};return!r&&!t?e.jsx(Ss,{title:"Teams",description:"Team Management",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Ar,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h2",{className:"text-xl font-semibold mb-2",children:"Access Denied"}),e.jsx("p",{className:"text-muted-foreground",children:"You need brokerage manager access to manage teams."})]})}):e.jsx(Ss,{title:"Teams",description:"Create and manage teams within your brokerage",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold tracking-tight",children:"Teams"}),e.jsx("p",{className:"text-muted-foreground",children:"Organize your agents into teams with leaders and shared resources."})]}),e.jsxs(H,{onClick:()=>j(!0),children:[e.jsx(Ys,{className:"mr-2 h-4 w-4"}),"Create Team"]})]}),e.jsx(xht,{open:b,onOpenChange:j,onCreateTeam:D,isCreating:h.isPending,brokerageAgents:A||[],isAdmin:t,allBrokerages:E,activeBrokerageId:l}),d&&e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:[1,2,3].map(R=>e.jsx(ke,{children:e.jsxs(Oe,{className:"p-6",children:[e.jsx(Ks,{className:"h-5 w-32 mb-3"}),e.jsx(Ks,{className:"h-4 w-48 mb-4"}),e.jsx(Ks,{className:"h-8 w-full"})]})},R))}),!d&&c.length===0&&!k&&e.jsx(ke,{children:e.jsxs(Oe,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Ar,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold mb-2",children:"No Teams Yet"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"Create your first team to organize agents and share resources."}),e.jsxs(H,{onClick:()=>j(!0),children:[e.jsx(Ys,{className:"mr-2 h-4 w-4"}),"Create Your First Team"]})]})}),!d&&c.length>0&&!k&&e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:c.map(R=>e.jsx(kKs,{team:R,onSelect:()=>T(R)},R.id))}),k&&e.jsx(ght,{team:k,brokerageAgents:A||[],onBack:()=>T(null),onUpdate:R=>m.mutateAsync({id:k.id,...R}).then(z=>T(z)),onAddMember:(R,z)=>x.mutateAsync({team_id:k.id,user_id:R,role:z}),onRemoveMember:R=>y.mutateAsync({team_id:k.id,member_id:R}),onUpdateRole:(R,z)=>_.mutateAsync({team_id:k.id,member_id:R,role:z}),onDeleteTeam:()=>p.mutate(k.id),isUpdating:m.isPending,isAddingMember:x.isPending})]})})},CKs=()=>{const{data:s,isLoading:t}=sv(),{useTeamMembers:r}=XA(),{data:n=[],isLoading:a}=r((s==null?void 0:s.teamId)||"");if(t)return e.jsx(Ss,{title:"My Team",description:"Your team",children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ks,{className:"h-8 w-48"}),e.jsx(Ks,{className:"h-40 w-full"})]})});if(!s)return e.jsx(Ss,{title:"My Team",description:"Your team",children:e.jsx(ke,{children:e.jsxs(Oe,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Ar,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h2",{className:"text-xl font-semibold mb-2",children:"No Team Yet"}),e.jsx("p",{className:"text-muted-foreground",children:"You haven't been assigned to a team. Ask your brokerage manager to add you."})]})})});const i=s.team;return e.jsx(Ss,{title:"My Team",description:i.name,children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h2",{className:"text-2xl font-bold tracking-tight",children:i.name}),e.jsx(Xe,{variant:s.role==="team_leader"?"default":"secondary",className:"capitalize",children:s.role==="team_leader"?e.jsxs(e.Fragment,{children:[e.jsx(zf,{className:"mr-1 h-3 w-3"})," Leader"]}):"Member"})]}),i.description&&e.jsx("p",{className:"text-muted-foreground mt-1",children:i.description})]}),e.jsxs(ta,{defaultValue:"members",className:"space-y-4",children:[e.jsxs(Qn,{className:"flex-wrap",children:[e.jsx(ts,{value:"members",children:"Members"}),i.contact_visibility!=="private"&&e.jsxs(ts,{value:"contacts",children:[e.jsx(xE,{className:"mr-1 h-3.5 w-3.5"}),"Team Contacts"]}),i.lead_pond_enabled&&e.jsxs(ts,{value:"lead-pond",children:[e.jsx(y1,{className:"mr-1 h-3.5 w-3.5"}),"Lead Pond"]}),i.shared_assets_enabled&&e.jsxs(ts,{value:"shared-assets",children:[e.jsx(Uf,{className:"mr-1 h-3.5 w-3.5"}),"Shared Assets"]})]}),e.jsx(cs,{value:"members",className:"space-y-2",children:a?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(l=>e.jsx(Ks,{className:"h-16 w-full"},l))}):n.map(l=>{var o,c,d,h;return e.jsx(ke,{children:e.jsxs(Oe,{className:"flex items-center gap-3 p-4",children:[e.jsxs(Un,{className:"h-10 w-10",children:[e.jsx(Ka,{src:((o=l.profile)==null?void 0:o.avatar_url)||""}),e.jsx(qn,{children:(((c=l.profile)==null?void 0:c.name)||"?").charAt(0).toUpperCase()})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium",children:((d=l.profile)==null?void 0:d.name)||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(h=l.profile)==null?void 0:h.email})]}),l.role==="team_leader"?e.jsxs(Xe,{className:"ml-auto bg-amber-500/10 text-amber-600 border-amber-500",children:[e.jsx(zf,{className:"mr-1 h-3 w-3"})," Leader"]}):e.jsx(Xe,{variant:"secondary",className:"ml-auto",children:"Member"})]})},l.id)})}),i.contact_visibility!=="private"&&e.jsx(cs,{value:"contacts",className:"space-y-4",children:e.jsx(VEe,{})}),i.lead_pond_enabled&&e.jsx(cs,{value:"lead-pond",className:"space-y-4",children:e.jsx(HEe,{teamId:s.teamId})}),i.shared_assets_enabled&&e.jsx(cs,{value:"shared-assets",className:"space-y-4",children:e.jsx(pht,{teamId:s.teamId})})]})]})})};function TKs(){const{user:s}=Ms(),t=ns(),r=yt({queryKey:["booking-settings",s==null?void 0:s.id],queryFn:async()=>{const{data:b,error:j}=await V.from("agent_booking_settings").select("*").eq("user_id",s.id).maybeSingle();if(j)throw j;return b},enabled:!!s}),n=yt({queryKey:["booking-types",s==null?void 0:s.id],queryFn:async()=>{const{data:b,error:j}=await V.from("agent_booking_types").select("*").eq("user_id",s.id).order("sort_order");if(j)throw j;return b},enabled:!!s}),a=yt({queryKey:["availability-slots",s==null?void 0:s.id],queryFn:async()=>{const{data:b,error:j}=await V.from("agent_availability_slots").select("*").eq("user_id",s.id).order("day_of_week").order("start_time");if(j)throw j;return b},enabled:!!s}),i=yt({queryKey:["blocked-dates",s==null?void 0:s.id],queryFn:async()=>{const{data:b,error:j}=await V.from("agent_blocked_dates").select("*").eq("user_id",s.id).order("blocked_date");if(j)throw j;return b},enabled:!!s}),l=yt({queryKey:["bookings",s==null?void 0:s.id],queryFn:async()=>{const{data:b,error:j}=await V.from("bookings").select("*, booking_type:agent_booking_types(*)").eq("agent_user_id",s.id).order("booking_date",{ascending:!1});if(j)throw j;return b},enabled:!!s}),o=Pt({mutationFn:async()=>{const{data:b,error:j}=await V.from("agent_booking_settings").insert({user_id:s.id,slug:""}).select().single();if(j)throw j;const k=[{name:"Listing Consultation",description:"Get a comprehensive market analysis and listing strategy for your home",duration_minutes:60,color:"#10B981",icon:"Home",sort_order:0},{name:"Buyer Consultation",description:"Discuss your home search criteria, budget, and buying process",duration_minutes:45,color:"#3B82F6",icon:"Search",sort_order:1},{name:"Home Valuation",description:"Find out what your home is worth in today's market",duration_minutes:30,color:"#F59E0B",icon:"DollarSign",sort_order:2},{name:"General Meeting",description:"Coffee chat, check-in, or quick real estate question",duration_minutes:30,color:"#8B5CF6",icon:"Coffee",sort_order:3}],{error:T}=await V.from("agent_booking_types").insert(k.map(D=>({...D,user_id:s.id})));if(T)throw T;const E=[1,2,3,4,5].map(D=>({user_id:s.id,day_of_week:D,start_time:"09:00",end_time:"17:00"})),{error:A}=await V.from("agent_availability_slots").insert(E);if(A)throw A;return b},onSuccess:()=>{t.invalidateQueries({queryKey:["booking-settings"]}),t.invalidateQueries({queryKey:["booking-types"]}),t.invalidateQueries({queryKey:["availability-slots"]}),he.success("Scheduler set up successfully!")},onError:b=>he.error(b.message)}),c=Pt({mutationFn:async b=>{const{error:j}=await V.from("agent_booking_settings").update(b).eq("user_id",s.id);if(j)throw j},onSuccess:()=>{t.invalidateQueries({queryKey:["booking-settings"]}),he.success("Settings updated")},onError:b=>he.error(b.message)}),d=Pt({mutationFn:async b=>{const j={...b,user_id:s.id};if(b.id){const{error:k}=await V.from("agent_booking_types").update(j).eq("id",b.id);if(k)throw k}else{const{error:k}=await V.from("agent_booking_types").insert(j);if(k)throw k}},onSuccess:()=>{t.invalidateQueries({queryKey:["booking-types"]}),he.success("Booking type saved")},onError:b=>he.error(b.message)}),h=Pt({mutationFn:async b=>{const{error:j}=await V.from("agent_booking_types").delete().eq("id",b);if(j)throw j},onSuccess:()=>{t.invalidateQueries({queryKey:["booking-types"]}),he.success("Booking type deleted")},onError:b=>he.error(b.message)}),m=Pt({mutationFn:async b=>{const j={...b,user_id:s.id};if(b.id){const{error:k}=await V.from("agent_availability_slots").update(j).eq("id",b.id);if(k)throw k}else{const{error:k}=await V.from("agent_availability_slots").insert(j);if(k)throw k}},onSuccess:()=>{t.invalidateQueries({queryKey:["availability-slots"]})},onError:b=>he.error(b.message)}),p=Pt({mutationFn:async b=>{const{error:j}=await V.from("agent_availability_slots").delete().eq("id",b);if(j)throw j},onSuccess:()=>{t.invalidateQueries({queryKey:["availability-slots"]})},onError:b=>he.error(b.message)}),x=Pt({mutationFn:async b=>{const{error:j}=await V.from("agent_blocked_dates").insert({...b,user_id:s.id});if(j)throw j},onSuccess:()=>{t.invalidateQueries({queryKey:["blocked-dates"]}),he.success("Date blocked")},onError:b=>he.error(b.message)}),y=Pt({mutationFn:async b=>{const{error:j}=await V.from("agent_blocked_dates").delete().eq("id",b);if(j)throw j},onSuccess:()=>{t.invalidateQueries({queryKey:["blocked-dates"]})},onError:b=>he.error(b.message)}),_=Pt({mutationFn:async({id:b,reason:j})=>{const{error:k}=await V.from("bookings").update({status:"cancelled",cancelled_at:new Date().toISOString(),cancel_reason:j}).eq("id",b);if(k)throw k},onSuccess:()=>{t.invalidateQueries({queryKey:["bookings"]}),he.success("Booking cancelled")},onError:b=>he.error(b.message)});return{settings:r.data,bookingTypes:n.data??[],availability:a.data??[],blockedDates:i.data??[],bookings:l.data??[],isLoading:r.isLoading,initializeSettings:o,updateSettings:c,upsertBookingType:d,deleteBookingType:h,upsertAvailability:m,deleteAvailability:p,addBlockedDate:x,removeBlockedDate:y,cancelBooking:_}}const yYe={Home:"🏠",Search:"🔍",DollarSign:"💰",Coffee:"☕",Calendar:"📅",Users:"👥",Phone:"📞",Video:"🎥"};function EKs({types:s,onSave:t,onDelete:r}){const[n,a]=S.useState(null),[i,l]=S.useState(!1),o=()=>{a({name:"",description:"",duration_minutes:30,color:"#3B82F6",icon:"Calendar",is_active:!0,qualification_enabled:!1}),l(!0)},c=h=>{a({...h}),l(!0)},d=()=>{n!=null&&n.name&&(t(n),l(!1),a(null))};return e.jsxs(e.Fragment,{children:[e.jsxs(ke,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(zt,{children:"Booking Types"}),e.jsx(Br,{children:"The meeting types prospects can book with you"})]}),e.jsxs(H,{onClick:o,size:"sm",children:[e.jsx(Ys,{className:"h-4 w-4 mr-1"})," Add Type"]})]}),e.jsx(Oe,{children:s.length===0?e.jsx("p",{className:"text-center text-muted-foreground py-8",children:"No booking types yet. Add one to get started."}):e.jsx("div",{className:"grid gap-3",children:s.map(h=>e.jsxs("div",{className:"flex items-center justify-between p-4 rounded-lg border hover:bg-muted/50 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg flex items-center justify-center text-lg",style:{backgroundColor:h.color+"20"},children:yYe[h.icon]||"📅"}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"font-medium",children:h.name}),!h.is_active&&e.jsx(Xe,{variant:"secondary",className:"text-xs",children:"Inactive"}),h.qualification_enabled&&e.jsxs(Xe,{variant:"outline",className:"text-xs gap-1",children:[e.jsx(bF,{className:"h-3 w-3"})," Qualifying"]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Pn,{className:"h-3 w-3"}),h.duration_minutes," min",h.description&&e.jsxs("span",{children:["· ",h.description.slice(0,60),h.description.length>60?"...":""]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(H,{variant:"ghost",size:"sm",onClick:()=>c(h),children:e.jsx(ni,{className:"h-4 w-4"})}),e.jsx(H,{variant:"ghost",size:"sm",onClick:()=>r(h.id),className:"text-destructive hover:text-destructive",children:e.jsx(Dr,{className:"h-4 w-4"})})]})]},h.id))})})]}),e.jsx(bs,{open:i,onOpenChange:l,children:e.jsxs(vs,{children:[e.jsx(Cs,{children:e.jsxs(Ns,{children:[n!=null&&n.id?"Edit":"New"," Booking Type"]})}),n&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Name"}),e.jsx(Se,{value:n.name||"",onChange:h=>a({...n,name:h.target.value}),placeholder:"e.g. Listing Consultation"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Description"}),e.jsx(vr,{value:n.description||"",onChange:h=>a({...n,description:h.target.value}),placeholder:"Brief description for prospects",rows:2})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Duration (minutes)"}),e.jsx(Se,{type:"number",min:15,max:180,step:15,value:n.duration_minutes||30,onChange:h=>a({...n,duration_minutes:parseInt(h.target.value)||30})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:n.color||"#3B82F6",onChange:h=>a({...n,color:h.target.value}),className:"h-10 w-10 rounded border cursor-pointer"}),e.jsx(Se,{value:n.color||"#3B82F6",onChange:h=>a({...n,color:h.target.value}),className:"flex-1"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Icon"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:Object.entries(yYe).map(([h,m])=>e.jsx("button",{onClick:()=>a({...n,icon:h}),className:`w-10 h-10 rounded-lg text-lg flex items-center justify-center border transition-colors ${n.icon===h?"border-primary bg-primary/10":"hover:bg-muted"}`,children:m},h))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Meeting Link Override (optional)"}),e.jsx(Se,{value:n.meeting_link_override||"",onChange:h=>a({...n,meeting_link_override:h.target.value||null}),placeholder:"Use a different link for this type"})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ue,{children:"Pre-Qualification Questions"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Ask qualifying questions before booking"})]}),e.jsx(Or,{checked:n.qualification_enabled||!1,onCheckedChange:h=>a({...n,qualification_enabled:h})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ue,{children:"Active"}),e.jsx(Or,{checked:n.is_active??!0,onCheckedChange:h=>a({...n,is_active:h})})]})]}),e.jsxs(wn,{children:[e.jsx(H,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx(H,{onClick:d,children:"Save"})]})]})})]})}const vYe=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];function AKs({slots:s,onSave:t,onDelete:r}){const[n,a]=S.useState(null),[i,l]=S.useState("09:00"),[o,c]=S.useState("17:00"),d=vYe.map((m,p)=>s.filter(x=>x.day_of_week===p)),h=()=>{n!==null&&(t({day_of_week:n,start_time:i,end_time:o,is_active:!0}),a(null),l("09:00"),c("17:00"))};return e.jsxs(ke,{children:[e.jsxs(Ot,{children:[e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(Pn,{className:"h-5 w-5"}),"Weekly Availability"]}),e.jsx(Br,{children:"Set your available hours for each day"})]}),e.jsx(Oe,{className:"space-y-2",children:vYe.map((m,p)=>{const x=d[p];return e.jsxs("div",{className:"flex items-start gap-3 py-2 border-b last:border-0",children:[e.jsx("div",{className:"w-24 pt-1",children:e.jsx("p",{className:"text-sm font-medium",children:m})}),e.jsxs("div",{className:"flex-1 space-y-1",children:[x.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-1",children:"Unavailable"}):x.map(y=>{var _,b;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Se,{type:"time",className:"w-28 h-8 text-sm",defaultValue:(_=y.start_time)==null?void 0:_.slice(0,5),onBlur:j=>t({id:y.id,start_time:j.target.value})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"to"}),e.jsx(Se,{type:"time",className:"w-28 h-8 text-sm",defaultValue:(b=y.end_time)==null?void 0:b.slice(0,5),onBlur:j=>t({id:y.id,end_time:j.target.value})}),e.jsx(Or,{checked:y.is_active,onCheckedChange:j=>t({id:y.id,is_active:j})}),e.jsx(H,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>r(y.id),children:e.jsx(Dr,{className:"h-3.5 w-3.5 text-muted-foreground"})})]},y.id)}),n===p?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Se,{type:"time",className:"w-28 h-8 text-sm",value:i,onChange:y=>l(y.target.value)}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"to"}),e.jsx(Se,{type:"time",className:"w-28 h-8 text-sm",value:o,onChange:y=>c(y.target.value)}),e.jsx(H,{size:"sm",className:"h-8",onClick:h,children:"Add"}),e.jsx(H,{variant:"ghost",size:"sm",className:"h-8",onClick:()=>a(null),children:"Cancel"})]}):e.jsxs(H,{variant:"ghost",size:"sm",className:"h-7 text-xs text-muted-foreground",onClick:()=>a(p),children:[e.jsx(Ys,{className:"h-3 w-3 mr-1"})," Add hours"]})]})]},m)})})]})}const MKs={confirmed:"bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400",cancelled:"bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400",completed:"bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-400",no_show:"bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-400"};function IKs({bookings:s,onCancel:t}){const r=s.filter(i=>i.status==="confirmed"&&new Date(i.booking_date)>=new Date(new Date().toDateString())),n=s.filter(i=>i.status!=="confirmed"||new Date(i.booking_date){var o,c;return e.jsxs("div",{className:"flex items-start justify-between p-4 rounded-lg border hover:bg-muted/30 transition-colors",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(io,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"font-medium",children:i.guest_name}),e.jsx(Xe,{className:`text-xs ${MKs[i.status]||""}`,children:i.status})]}),e.jsxs("div",{className:"flex items-center gap-4 text-sm text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(xu,{className:"h-3.5 w-3.5"}),As(new Date(i.booking_date+"T00:00:00"),"MMM d, yyyy")]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Pn,{className:"h-3.5 w-3.5"}),(o=i.start_time)==null?void 0:o.slice(0,5)," - ",(c=i.end_time)==null?void 0:c.slice(0,5)]})]}),e.jsxs("div",{className:"flex items-center gap-3 text-sm text-muted-foreground",children:[i.guest_email&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(er,{className:"h-3 w-3"}),i.guest_email]}),i.guest_phone&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Yn,{className:"h-3 w-3"}),i.guest_phone]})]}),i.booking_type&&e.jsx(Xe,{variant:"outline",className:"text-xs mt-1",children:i.booking_type.name}),i.guest_message&&e.jsxs("p",{className:"text-sm text-muted-foreground mt-1 italic",children:['"',i.guest_message,'"']})]}),l&&i.status==="confirmed"&&e.jsxs(H,{variant:"ghost",size:"sm",onClick:()=>t(i.id),className:"text-destructive hover:text-destructive",children:[e.jsx(kd,{className:"h-4 w-4 mr-1"})," Cancel"]})]},i.id)};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(ke,{children:[e.jsxs(Ot,{children:[e.jsx(zt,{children:"Upcoming Bookings"}),e.jsxs(Br,{children:[r.length," upcoming appointment",r.length!==1?"s":""]})]}),e.jsx(Oe,{children:r.length===0?e.jsx("p",{className:"text-center text-muted-foreground py-8",children:"No upcoming bookings"}):e.jsx("div",{className:"space-y-3",children:r.map(i=>a(i,!0))})})]}),n.length>0&&e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsx(zt,{children:"Past & Cancelled"})}),e.jsx(Oe,{children:e.jsx("div",{className:"space-y-3",children:n.slice(0,20).map(i=>a(i))})})]})]})}function PKs({blockedDates:s,onAdd:t,onRemove:r}){const[n,a]=S.useState(!1),[i,l]=S.useState(""),[o,c]=S.useState(""),d=()=>{i&&(t({blocked_date:i,reason:o||void 0}),a(!1),l(""),c(""))};return e.jsxs(ke,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(rF,{className:"h-5 w-5"}),"Blocked Dates"]}),e.jsx(Br,{children:"Block specific dates (vacations, holidays, etc.)"})]}),e.jsxs(H,{size:"sm",variant:"outline",onClick:()=>a(!0),children:[e.jsx(Ys,{className:"h-4 w-4 mr-1"})," Block Date"]})]}),e.jsxs(Oe,{children:[n&&e.jsxs("div",{className:"flex items-center gap-2 mb-3 p-3 rounded-lg border bg-muted/30",children:[e.jsx(Se,{type:"date",value:i,onChange:h=>l(h.target.value),className:"w-40"}),e.jsx(Se,{placeholder:"Reason (optional)",value:o,onChange:h=>c(h.target.value),className:"flex-1"}),e.jsx(H,{size:"sm",onClick:d,children:"Add"}),e.jsx(H,{size:"sm",variant:"ghost",onClick:()=>a(!1),children:"Cancel"})]}),s.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No blocked dates"}):e.jsx("div",{className:"flex flex-wrap gap-2",children:s.map(h=>e.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-1.5 rounded-full border bg-muted/50 text-sm",children:[e.jsx("span",{children:As(new Date(h.blocked_date+"T00:00:00"),"MMM d, yyyy")}),h.reason&&e.jsxs("span",{className:"text-muted-foreground",children:["(",h.reason,")"]}),e.jsx("button",{onClick:()=>r(h.id),className:"ml-1 text-muted-foreground hover:text-destructive",children:e.jsx(Rr,{className:"h-3.5 w-3.5"})})]},h.id))})]})]})}function LKs(){const{settings:s,bookingTypes:t,availability:r,blockedDates:n,bookings:a,isLoading:i,initializeSettings:l,updateSettings:o,upsertBookingType:c,deleteBookingType:d,upsertAvailability:h,deleteAvailability:m,addBlockedDate:p,removeBlockedDate:x,cancelBooking:y}=TKs(),[_,b]=S.useState("");S.useState(15),_||s!=null&&s.meeting_link;const j=s!=null&&s.slug?`https://booking.relevelup.com/${s.slug}`:null;return i?e.jsx(Ss,{children:e.jsx("div",{className:"flex items-center justify-center h-64",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary"})})}):s?e.jsx(Ss,{children:e.jsxs("div",{className:"space-y-6 p-4 md:p-8",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-2xl font-bold flex items-center gap-2",children:[e.jsx(xu,{className:"h-6 w-6 text-primary"}),"LevelUp Scheduler"]}),e.jsx("p",{className:"text-muted-foreground",children:"Manage your booking types, availability, and appointments"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[j&&e.jsxs(e.Fragment,{children:[e.jsxs(H,{variant:"outline",size:"sm",onClick:()=>{navigator.clipboard.writeText(j),he.success("Booking link copied!")},children:[e.jsx(ui,{className:"h-4 w-4 mr-1"})," Copy Link"]}),e.jsx(H,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:j,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(gn,{className:"h-4 w-4 mr-1"})," Preview"]})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ue,{htmlFor:"scheduler-active",className:"text-sm",children:"Active"}),e.jsx(Or,{id:"scheduler-active",checked:s.is_active,onCheckedChange:k=>o.mutate({is_active:k})})]})]})]}),e.jsxs(ta,{defaultValue:"types",className:"space-y-4",children:[e.jsxs(Qn,{children:[e.jsx(ts,{value:"types",children:"Booking Types"}),e.jsx(ts,{value:"availability",children:"Availability"}),e.jsx(ts,{value:"settings",children:"Settings"}),e.jsxs(ts,{value:"bookings",children:["Bookings",a.filter(k=>k.status==="confirmed").length>0&&e.jsx(Xe,{variant:"secondary",className:"ml-1.5 text-xs",children:a.filter(k=>k.status==="confirmed").length})]})]}),e.jsx(cs,{value:"types",children:e.jsx(EKs,{types:t,onSave:k=>c.mutate(k),onDelete:k=>d.mutate(k)})}),e.jsx(cs,{value:"availability",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(AKs,{slots:r,onSave:k=>h.mutate(k),onDelete:k=>m.mutate(k)}),e.jsx(PKs,{blockedDates:n,onAdd:k=>p.mutate(k),onRemove:k=>x.mutate(k)})]})}),e.jsx(cs,{value:"settings",children:e.jsxs(ke,{children:[e.jsxs(Ot,{children:[e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(MF,{className:"h-5 w-5"}),"General Settings"]}),e.jsx(Br,{children:"Configure your booking page defaults"})]}),e.jsxs(Oe,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Booking Page URL"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Se,{value:s.slug,readOnly:!0,className:"bg-muted"}),e.jsx(H,{variant:"outline",size:"sm",onClick:()=>{j&&(navigator.clipboard.writeText(j),he.success("Copied!"))},children:e.jsx(ui,{className:"h-4 w-4"})})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:j})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ue,{htmlFor:"meeting-link",children:[e.jsx(ql,{className:"h-4 w-4 inline mr-1"}),"Default Meeting Link"]}),e.jsx(Se,{id:"meeting-link",placeholder:"https://zoom.us/j/your-personal-link",defaultValue:s.meeting_link||"",onBlur:k=>o.mutate({meeting_link:k.target.value||null})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Your Zoom personal link, Google Meet, or phone number"})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Buffer Between Meetings"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Se,{type:"number",min:0,max:60,defaultValue:s.buffer_minutes,onBlur:k=>o.mutate({buffer_minutes:parseInt(k.target.value)||15})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"min"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Minimum Notice"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Se,{type:"number",min:0,max:72,defaultValue:s.min_notice_hours,onBlur:k=>o.mutate({min_notice_hours:parseInt(k.target.value)||2})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"hours"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{children:"Max Advance Booking"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Se,{type:"number",min:1,max:90,defaultValue:s.max_advance_days,onBlur:k=>o.mutate({max_advance_days:parseInt(k.target.value)||30})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"days"})]})]})]})]})]})}),e.jsx(cs,{value:"bookings",children:e.jsx(IKs,{bookings:a,onCancel:k=>y.mutate({id:k})})})]})]})}):e.jsx(Ss,{children:e.jsxs("div",{className:"max-w-2xl mx-auto p-4 md:p-8 space-y-8",children:[e.jsxs("div",{className:"text-center space-y-4",children:[e.jsx("div",{className:"mx-auto w-16 h-16 bg-primary/10 rounded-2xl flex items-center justify-center",children:e.jsx(xu,{className:"h-8 w-8 text-primary"})}),e.jsx("h1",{className:"text-3xl font-bold",children:"LevelUp Scheduler"}),e.jsx("p",{className:"text-muted-foreground text-lg max-w-md mx-auto",children:"Your own booking page — built for real estate. Prospects book with you, get auto-added to your CRM, and you never miss a lead."})]}),e.jsx(ke,{children:e.jsxs(Oe,{className:"pt-6 space-y-4",children:[e.jsx("div",{className:"grid grid-cols-2 gap-4",children:[{icon:"🏠",title:"Listing Consultation",desc:"60 min"},{icon:"🔍",title:"Buyer Consultation",desc:"45 min"},{icon:"💰",title:"Home Valuation",desc:"30 min"},{icon:"☕",title:"General Meeting",desc:"30 min"}].map(k=>e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg border bg-muted/30",children:[e.jsx("span",{className:"text-2xl",children:k.icon}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:k.title}),e.jsx("p",{className:"text-xs text-muted-foreground",children:k.desc})]})]},k.title))}),e.jsx(Qo,{}),e.jsxs("div",{className:"space-y-2 text-sm text-muted-foreground",children:[e.jsx("p",{children:"✅ Auto-creates CRM contacts from every booking"}),e.jsx("p",{children:"✅ Optional pre-qualification questions per booking type"}),e.jsx("p",{children:"✅ Embeds on your Smart Card — replaces TidyCal"}),e.jsx("p",{children:"✅ Standalone shareable booking page"})]}),e.jsxs(H,{onClick:()=>l.mutate(),disabled:l.isPending,className:"w-full",size:"lg",children:[e.jsx(Lr,{className:"h-4 w-4 mr-2"}),l.isPending?"Setting up...":"Activate Scheduler"]})]})})]})})}const bYe=[{id:"event_registration",label:"Event Registration",description:"Capture RSVPs for open houses, expos, seminars"},{id:"buyer_consultation",label:"Buyer Consultation",description:"Pre-qualify buyers with targeted questions"},{id:"home_valuation",label:"Home Valuation Request",description:`"What's your home worth?" lead capture`},{id:"lead_capture",label:"General Lead Capture",description:"Flexible form for any lead gen purpose"},{id:"lead_magnet",label:"Lead Magnet / Giveaway",description:"Offer a free download (PDF, guide, checklist) in exchange for contact info"},{id:"just_listed",label:"Just Listed",description:"Showcase a new listing with photos & details + contact CTA"},{id:"just_sold",label:"Just Sold",description:'Celebrate a sale & capture "Want results like this?" leads'}];function DKs(){const{user:s}=Ms(),t=ba(),{toast:r}=li(),n=Fr(),a=ns(),[i,l]=S.useState(!1),[o,c]=S.useState(null),[d,h]=S.useState(null),[m,p]=S.useState({title:"",description:"",page_type:"lead_capture"}),{data:x=[],isLoading:y}=yt({queryKey:["landing-pages",t],queryFn:async()=>{const{data:k,error:T}=await V.from("landing_pages").select("*").eq("user_id",t).order("created_at",{ascending:!1});if(T)throw T;return k},enabled:!!t}),_=Pt({mutationFn:async()=>{const k=m.title.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,"")+"-"+Date.now().toString(36),{data:T}=await V.from("profiles").select("name, phone, avatar_url, email").eq("id",t).single(),E=m.page_type==="just_listed"||m.page_type==="just_sold",{data:A,error:D}=await V.from("landing_pages").insert({user_id:t,title:m.title,description:m.description||null,page_type:m.page_type,slug:k,hero_headline:E?m.page_type==="just_listed"?"🏡 Just Listed":"🎉 Just Sold":m.page_type==="lead_magnet"?"📥 Free Download":m.title,agent_name:(T==null?void 0:T.name)||null,agent_phone:(T==null?void 0:T.phone)||null,agent_email:(T==null?void 0:T.email)||s.email||null,agent_photo_url:(T==null?void 0:T.avatar_url)||null,property_status:E?m.page_type.replace("just_",""):null}).select().single();if(D)throw D;const R=RKs(m.page_type);if(R.length>0){const{error:z}=await V.from("landing_page_fields").insert(R.map((O,$)=>({...O,page_id:A.id,sort_order:$})));if(z)throw z}return A},onSuccess:k=>{a.invalidateQueries({queryKey:["landing-pages"]}),l(!1),p({title:"",description:"",page_type:"lead_capture"}),r({title:"Landing page created!"}),n(`/mission-control/landing-pages/${k.id}`)},onError:k=>r({title:"Error",description:k.message,variant:"destructive"})}),b=Pt({mutationFn:async k=>{const{error:T}=await V.from("landing_pages").delete().eq("id",k);if(T)throw T},onSuccess:()=>{a.invalidateQueries({queryKey:["landing-pages"]}),c(null),r({title:"Landing page deleted"})}}),j=k=>`https://pages.relevelup.com/${k}`;return e.jsxs(Ss,{title:"Landing Pages",children:[e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Landing Pages"}),e.jsx("p",{className:"text-muted-foreground text-sm mt-1",children:"Create branded lead capture pages for events, consultations, and more"})]}),e.jsxs(H,{onClick:()=>l(!0),children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"})," New Page"]})]}),y?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):x.length===0?e.jsx(ke,{children:e.jsxs(Oe,{className:"flex flex-col items-center justify-center py-16",children:[e.jsx(kn,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold",children:"No landing pages yet"}),e.jsx("p",{className:"text-muted-foreground text-sm mt-1 mb-4",children:"Create your first page to start capturing leads"}),e.jsxs(H,{onClick:()=>l(!0),children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"})," Create Landing Page"]})]})}):e.jsx("div",{className:"grid gap-4",children:x.map(k=>{var T;return e.jsx(ke,{className:"hover:shadow-md transition-shadow",children:e.jsx(Oe,{className:"p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex-1 min-w-0 cursor-pointer",onClick:()=>n(`/mission-control/landing-pages/${k.id}`),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"font-semibold truncate",children:k.title}),e.jsx(Xe,{variant:k.is_published?"default":"secondary",className:"text-[10px]",children:k.is_published?"Published":"Draft"}),e.jsx(Xe,{variant:"outline",className:"text-[10px]",children:((T=bYe.find(E=>E.id===k.page_type))==null?void 0:T.label)||k.page_type})]}),k.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1 truncate",children:k.description}),e.jsxs("div",{className:"flex items-center gap-4 mt-2 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Bn,{className:"h-3 w-3"})," ",k.view_count," views"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(kn,{className:"h-3 w-3"})," ",k.submission_count," submissions"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 ml-4",children:[k.is_published&&e.jsxs(e.Fragment,{children:[e.jsx(H,{size:"sm",variant:"outline",onClick:()=>h(j(k.slug)),children:e.jsx(y_,{className:"h-3.5 w-3.5"})}),e.jsx(H,{size:"sm",variant:"outline",onClick:()=>{navigator.clipboard.writeText(j(k.slug)),r({title:"Link copied!"})},children:e.jsx(ui,{className:"h-3.5 w-3.5"})}),e.jsx(H,{size:"sm",variant:"outline",asChild:!0,children:e.jsx("a",{href:j(k.slug),target:"_blank",rel:"noopener noreferrer",children:e.jsx(gn,{className:"h-3.5 w-3.5"})})})]}),e.jsxs(Xu,{children:[e.jsx(Qu,{asChild:!0,children:e.jsx(H,{size:"sm",variant:"ghost",children:e.jsx(Ay,{className:"h-4 w-4"})})}),e.jsxs(wu,{align:"end",children:[e.jsxs(di,{onClick:()=>n(`/mission-control/landing-pages/${k.id}`),children:[e.jsx(ni,{className:"h-3.5 w-3.5 mr-2"})," Edit"]}),e.jsxs(di,{onClick:()=>c(k.id),className:"text-destructive",children:[e.jsx(Dr,{className:"h-3.5 w-3.5 mr-2"})," Delete"]})]})]})]})]})})},k.id)})})]}),e.jsx(bs,{open:i,onOpenChange:l,children:e.jsxs(vs,{children:[e.jsx(Cs,{children:e.jsx(Ns,{children:"Create Landing Page"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ue,{children:"Page Title"}),e.jsx(Se,{value:m.title,onChange:k=>p(T=>({...T,title:k.target.value})),placeholder:"e.g. Veterans Home & Land Expo"})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Description (optional)"}),e.jsx(vr,{value:m.description,onChange:k=>p(T=>({...T,description:k.target.value})),placeholder:"Brief internal description...",rows:2})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Page Template"}),e.jsxs(Bs,{value:m.page_type,onValueChange:k=>p(T=>({...T,page_type:k})),children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsx(Fs,{children:bYe.map(k=>e.jsx(pt,{value:k.id,children:e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:k.label}),e.jsx("div",{className:"text-xs text-muted-foreground",children:k.description})]})},k.id))})]})]})]}),e.jsxs(wn,{children:[e.jsx(H,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx(H,{onClick:()=>_.mutate(),disabled:!m.title.trim()||_.isPending,children:_.isPending?"Creating...":"Create Page"})]})]})}),e.jsx(Rl,{open:!!o,onOpenChange:()=>c(null),children:e.jsxs(jl,{children:[e.jsxs(Nl,{children:[e.jsx(Sl,{children:"Delete Landing Page?"}),e.jsx(Cl,{children:"This will permanently delete this page and all its submissions."})]}),e.jsxs(kl,{children:[e.jsx(Tl,{children:"Cancel"}),e.jsx(ml,{onClick:()=>o&&b.mutate(o),children:"Delete"})]})]})}),e.jsx(bs,{open:!!d,onOpenChange:()=>h(null),children:e.jsxs(vs,{className:"max-w-sm",children:[e.jsx(Cs,{children:e.jsx(Ns,{children:"QR Code"})}),e.jsxs("div",{className:"flex flex-col items-center gap-4 py-4",children:[d&&e.jsx(Vz,{value:d,size:240}),e.jsx("p",{className:"text-xs text-muted-foreground text-center break-all",children:d}),e.jsxs(H,{variant:"outline",size:"sm",onClick:()=>{d&&(navigator.clipboard.writeText(d),r({title:"URL copied!"}))},children:[e.jsx(ui,{className:"h-3.5 w-3.5 mr-1"})," Copy URL"]})]})]})})]})}function RKs(s){const t=[{field_type:"text",label:"Full Name",placeholder:"Your name",is_required:!0},{field_type:"email",label:"Email",placeholder:"your@email.com",is_required:!0},{field_type:"phone",label:"Phone",placeholder:"(555) 123-4567",is_required:!1}];switch(s){case"event_registration":return[...t,{field_type:"select",label:"How did you hear about this event?",options:JSON.stringify(["Social Media","Friend/Referral","Email","Flyer/Sign","Other"]),is_required:!1},{field_type:"textarea",label:"Any questions or special needs?",placeholder:"Let us know...",is_required:!1}];case"buyer_consultation":return[...t,{field_type:"select",label:"Interested in",options:JSON.stringify(["Buying","Selling","Both"]),is_required:!0},{field_type:"select",label:"Timeline",options:JSON.stringify(["0-3 months","3-6 months","6-12 months","Just exploring"]),is_required:!1},{field_type:"toggle",label:"Already working with a Realtor?",is_required:!1},{field_type:"toggle",label:"Do you have property to sell?",is_required:!1},{field_type:"textarea",label:"Anything else we should know?",placeholder:"Tell us about your situation...",is_required:!1}];case"home_valuation":return[...t,{field_type:"text",label:"Property Address",placeholder:"123 Main St, City, State",is_required:!0},{field_type:"select",label:"Reason for Valuation",options:JSON.stringify(["Thinking of selling","Refinancing","Curiosity","Estate planning","Other"]),is_required:!1},{field_type:"select",label:"Timeline to Sell",options:JSON.stringify(["ASAP","1-3 months","3-6 months","6+ months","Not sure"]),is_required:!1}];case"lead_magnet":return[...t,{field_type:"select",label:"Are you currently working with a Realtor?",options:JSON.stringify(["Yes","No","Not yet"]),is_required:!1}];case"just_listed":return[...t,{field_type:"select",label:"I am interested in",options:JSON.stringify(["Scheduling a showing","Getting more details","Similar properties","Selling my home"]),is_required:!0},{field_type:"textarea",label:"Message",placeholder:"Tell me more about this property...",is_required:!1}];case"just_sold":return[...t,{field_type:"select",label:"I am looking to",options:JSON.stringify(["Sell my home","Buy a home","Both","Just curious"]),is_required:!0},{field_type:"text",label:"My Property Address",placeholder:"123 Main St, City, State",is_required:!1}];default:return[...t,{field_type:"textarea",label:"Message",placeholder:"How can we help you?",is_required:!1}]}}const OKs=[{value:"text",label:"Short Text"},{value:"email",label:"Email"},{value:"phone",label:"Phone"},{value:"textarea",label:"Long Text"},{value:"select",label:"Dropdown"},{value:"multiselect",label:"Multi-Select"},{value:"toggle",label:"Yes / No Toggle"}];let FKs=0;const _Ye=()=>`f_${Date.now()}_${++FKs}`;function BKs({field:s,index:t,updateField:r,removeField:n}){const{attributes:a,listeners:i,setNodeRef:l,transform:o,transition:c,isDragging:d}=zxe({id:s.clientId}),h={transform:kS.Transform.toString(o),transition:c,zIndex:d?50:void 0,opacity:d?.85:1};return e.jsx(ke,{ref:l,style:h,children:e.jsx(Oe,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("button",{type:"button",...a,...i,className:"mt-1 p-1 rounded text-muted-foreground hover:text-foreground hover:bg-muted cursor-grab active:cursor-grabbing touch-none","aria-label":"Drag to reorder",children:e.jsx(Oh,{className:"h-4 w-4"})}),e.jsxs("div",{className:"flex-1 space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs",children:"Field Type"}),e.jsxs(Bs,{value:s.field_type,onValueChange:m=>r(t,{field_type:m}),children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsx(Fs,{children:OKs.map(m=>e.jsx(pt,{value:m.value,children:m.label},m.value))})]})]}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs",children:"Label"}),e.jsx(Se,{value:s.label,onChange:m=>r(t,{label:m.target.value}),placeholder:"e.g. Full Name"})]}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs",children:"Placeholder"}),e.jsx(Se,{value:s.placeholder||"",onChange:m=>r(t,{placeholder:m.target.value}),placeholder:"Optional hint text"})]})]}),(s.field_type==="select"||s.field_type==="multiselect")&&e.jsxs("div",{children:[e.jsx(ue,{className:"text-xs",children:"Options (comma-separated)"}),e.jsx(Se,{value:s.options?(typeof s.options=="string"?JSON.parse(s.options):s.options).join(", "):"",onChange:m=>r(t,{options:JSON.stringify(m.target.value.split(",").map(p=>p.trim()).filter(Boolean))}),placeholder:"Option 1, Option 2, Option 3"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Or,{checked:s.is_required,onCheckedChange:m=>r(t,{is_required:m})}),e.jsx(ue,{className:"text-xs",children:"Required"})]})]}),e.jsx(H,{variant:"ghost",size:"sm",onClick:()=>n(t),children:e.jsx(Dr,{className:"h-3.5 w-3.5 text-destructive"})})]})})})}function zKs(){const{pageId:s}=Po(),t=Fr(),{user:r}=Ms(),n=ba(),{toast:a}=li(),i=ns(),[l,o]=S.useState(null),[c,d]=S.useState(!1),{data:h,isLoading:m}=yt({queryKey:["landing-page",s],queryFn:async()=>{const{data:ne,error:le}=await V.from("landing_pages").select("*").eq("id",s).single();if(le)throw le;return ne},enabled:!!s}),{data:p=[],isLoading:x}=yt({queryKey:["landing-page-fields",s],queryFn:async()=>{const{data:ne,error:le}=await V.from("landing_page_fields").select("*").eq("page_id",s).order("sort_order");if(le)throw le;return ne},enabled:!!s}),{data:y=[]}=yt({queryKey:["landing-page-submissions",s],queryFn:async()=>{const{data:ne,error:le}=await V.from("landing_page_submissions").select("*").eq("page_id",s).order("created_at",{ascending:!1});if(le)throw le;return ne},enabled:!!s}),{data:_=[]}=yt({queryKey:["my-listings-for-pages",n],queryFn:async()=>{const{data:ne,error:le}=await V.from("listings").select("id, property_address, city, state, price, bedrooms, bathrooms, square_footage, description, status").eq("agent_id",n).order("created_at",{ascending:!1});if(le)throw le;return ne},enabled:!!r&&((h==null?void 0:h.page_type)==="just_listed"||(h==null?void 0:h.page_type)==="just_sold")}),[b,j]=S.useState({title:"",hero_headline:"",hero_subtext:"",hero_image_url:null,logo_url:null,primary_color:"#406E71",accent_color:"#2a4c64",agent_name:"",agent_phone:"",agent_email:"",agent_photo_url:null,success_message:"Thank you! We'll be in touch soon.",is_published:!1,description:"",lead_magnet_file_url:null,lead_magnet_file_name:null,lead_magnet_external_url:null,listing_id:null,property_address:"",property_price:"",property_beds:"",property_baths:"",property_sqft:"",property_description:"",property_photos:[],property_status:"just_listed",theme_style:"premium",eyebrow:"",headline_accent:"",heading_font:"playfair",trust_pills:["No obligation","100% free","60 seconds or less"]}),[k,T]=S.useState([]);S.useEffect(()=>{h&&j({title:h.title,hero_headline:h.hero_headline,hero_subtext:h.hero_subtext||"",hero_image_url:h.hero_image_url,logo_url:h.logo_url,primary_color:h.primary_color,accent_color:h.accent_color,agent_name:h.agent_name||"",agent_phone:h.agent_phone||"",agent_email:h.agent_email||"",agent_photo_url:h.agent_photo_url,success_message:h.success_message||"Thank you! We'll be in touch soon.",is_published:h.is_published,description:h.description||"",lead_magnet_file_url:h.lead_magnet_file_url||null,lead_magnet_file_name:h.lead_magnet_file_name||null,lead_magnet_external_url:h.lead_magnet_external_url||null,listing_id:h.listing_id||null,property_address:h.property_address||"",property_price:h.property_price||"",property_beds:h.property_beds||"",property_baths:h.property_baths||"",property_sqft:h.property_sqft||"",property_description:h.property_description||"",property_photos:Array.isArray(h.property_photos)?h.property_photos:[],property_status:h.property_status||"just_listed",theme_style:h.theme_style||"premium",eyebrow:h.eyebrow||"",headline_accent:h.headline_accent||"",heading_font:h.heading_font||"playfair",trust_pills:Array.isArray(h.trust_pills)?h.trust_pills:["No obligation","100% free","60 seconds or less"]})},[h]),S.useEffect(()=>{p.length>0&&T(p.map(ne=>({id:ne.id,clientId:ne.id||_Ye(),field_type:ne.field_type,label:ne.label,placeholder:ne.placeholder,is_required:ne.is_required,options:typeof ne.options=="string"?ne.options:ne.options?JSON.stringify(ne.options):null,sort_order:ne.sort_order})))},[p]);const E=Pt({mutationFn:async()=>{const{error:ne}=await V.from("landing_pages").update({title:b.title,hero_headline:b.hero_headline,hero_subtext:b.hero_subtext||null,hero_image_url:b.hero_image_url,logo_url:b.logo_url,primary_color:b.primary_color,accent_color:b.accent_color,agent_name:b.agent_name||null,agent_phone:b.agent_phone||null,agent_email:b.agent_email||null,agent_photo_url:b.agent_photo_url,success_message:b.success_message,is_published:b.is_published,description:b.description||null,lead_magnet_file_url:b.lead_magnet_file_url,lead_magnet_file_name:b.lead_magnet_file_name,lead_magnet_external_url:b.lead_magnet_external_url,listing_id:b.listing_id,property_address:b.property_address||null,property_price:b.property_price||null,property_beds:b.property_beds||null,property_baths:b.property_baths||null,property_sqft:b.property_sqft||null,property_description:b.property_description||null,property_photos:b.property_photos,property_status:b.property_status,theme_style:b.theme_style,eyebrow:b.eyebrow||null,headline_accent:b.headline_accent||null,heading_font:b.heading_font,trust_pills:b.trust_pills,updated_at:new Date().toISOString()}).eq("id",s);if(ne)throw ne;if(await V.from("landing_page_fields").delete().eq("page_id",s),k.length>0){const{error:le}=await V.from("landing_page_fields").insert(k.map((be,fe)=>({page_id:s,field_type:be.field_type,label:be.label,placeholder:be.placeholder||null,is_required:be.is_required,options:be.options?JSON.parse(be.options):null,sort_order:fe})));if(le)throw le}},onSuccess:()=>{i.invalidateQueries({queryKey:["landing-page",s]}),i.invalidateQueries({queryKey:["landing-page-fields",s]}),a({title:"Page saved!"})},onError:ne=>a({title:"Error",description:ne.message,variant:"destructive"})}),A=async(ne,le)=>{const be=ne.name.split(".").pop(),fe=`landing-pages/${r.id}/${le}-${Date.now()}.${be}`,{error:je}=await V.storage.from("recruit-landing").upload(fe,ne);if(je)throw je;const{data:{publicUrl:ve}}=V.storage.from("recruit-landing").getPublicUrl(fe);return ve},D=async(ne,le)=>{var fe;const be=(fe=ne.target.files)==null?void 0:fe[0];if(be){o(le);try{const je=await A(be,le);j(ve=>({...ve,[le]:je})),a({title:"Image uploaded!"})}catch(je){a({title:"Upload failed",description:je.message,variant:"destructive"})}finally{o(null)}}},R=async ne=>{var be;const le=(be=ne.target.files)==null?void 0:be[0];if(le){o("lead_magnet");try{const fe=await A(le,"lead-magnet");j(je=>({...je,lead_magnet_file_url:fe,lead_magnet_file_name:le.name})),a({title:"File uploaded!"})}catch(fe){a({title:"Upload failed",description:fe.message,variant:"destructive"})}finally{o(null)}}},z=async ne=>{const le=ne.target.files;if(!(!le||le.length===0)){o("property_photos");try{const be=[];for(const fe of Array.from(le)){const je=await A(fe,"property-photo");be.push(je)}j(fe=>({...fe,property_photos:[...fe.property_photos,...be]})),a({title:`${be.length} photo(s) uploaded!`})}catch(be){a({title:"Upload failed",description:be.message,variant:"destructive"})}finally{o(null)}}},O=async ne=>{const le=_.find(fe=>fe.id===ne);if(!le)return;const{data:be}=await V.from("listing_photos").select("photo_url").eq("listing_id",ne).order("sort_order");j(fe=>({...fe,listing_id:ne,property_address:le.property_address||`${le.city}, ${le.state}`,property_price:le.price?`$${le.price.toLocaleString()}`:"",property_beds:le.bedrooms?String(le.bedrooms):"",property_baths:le.bathrooms?String(le.bathrooms):"",property_sqft:le.square_footage?le.square_footage.toLocaleString():"",property_description:le.description||"",property_photos:(be==null?void 0:be.map(je=>je.photo_url))||fe.property_photos})),a({title:"Listing data imported!"})},$=()=>{T(ne=>[...ne,{clientId:_Ye(),field_type:"text",label:"",placeholder:"",is_required:!1,options:null,sort_order:ne.length}])},ee=(ne,le)=>{T(be=>be.map((fe,je)=>je===ne?{...fe,...le}:fe))},Z=ne=>{T(le=>le.filter((be,fe)=>fe!==ne))},J=Mxe(fL(T8,{activationConstraint:{distance:6}}),fL(Lxe,{coordinateGetter:zht})),K=ne=>{const{active:le,over:be}=ne;!be||le.id===be.id||T(fe=>{const je=fe.findIndex(We=>We.clientId===le.id),ve=fe.findIndex(We=>We.clientId===be.id);return je<0||ve<0?fe:Fxe(fe,je,ve).map((We,Ve)=>({...We,sort_order:Ve}))})},re=h?`https://pages.relevelup.com/${h.slug}`:"",ie=(h==null?void 0:h.page_type)==="lead_magnet",ce=(h==null?void 0:h.page_type)==="just_listed"||(h==null?void 0:h.page_type)==="just_sold";return m||x?e.jsx(Ss,{title:"Loading...",children:e.jsx("div",{className:"flex justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):h?e.jsxs(Ss,{title:b.title||"Edit Page",children:[e.jsxs("div",{className:"space-y-6 max-w-4xl mx-auto",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(H,{variant:"ghost",size:"sm",onClick:()=>t("/mission-control/landing-pages"),children:e.jsx(za,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-xl font-bold",children:b.title||"Untitled Page"}),e.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[e.jsx(Xe,{variant:b.is_published?"default":"secondary",className:"text-[10px]",children:b.is_published?"Published":"Draft"}),e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Bn,{className:"h-3 w-3"})," ",h.view_count," views"]}),e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Ar,{className:"h-3 w-3"})," ",y.length," submissions"]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[b.is_published&&e.jsxs(e.Fragment,{children:[e.jsx(H,{size:"sm",variant:"outline",onClick:()=>d(!0),children:e.jsx(y_,{className:"h-3.5 w-3.5"})}),e.jsxs(H,{size:"sm",variant:"outline",onClick:()=>{navigator.clipboard.writeText(re),a({title:"Link copied!"})},children:[e.jsx(ui,{className:"h-3.5 w-3.5 mr-1"})," Copy Link"]}),e.jsx(H,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:re,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(gn,{className:"h-3.5 w-3.5 mr-1"})," Preview"]})})]}),e.jsxs(H,{onClick:()=>E.mutate(),disabled:E.isPending,children:[e.jsx(vc,{className:"h-4 w-4 mr-2"}),E.isPending?"Saving...":"Save"]})]})]}),e.jsxs(ta,{defaultValue:"design",children:[e.jsxs(Qn,{children:[e.jsx(ts,{value:"design",children:"Design"}),ie&&e.jsx(ts,{value:"lead_magnet",children:"Lead Magnet"}),ce&&e.jsx(ts,{value:"property",children:"Property Details"}),e.jsxs(ts,{value:"fields",children:["Form Fields (",k.length,")"]}),e.jsxs(ts,{value:"submissions",children:["Submissions (",y.length,")"]}),e.jsx(ts,{value:"settings",children:"Settings"})]}),e.jsxs(cs,{value:"design",className:"space-y-4 mt-4",children:[e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-base",children:"Page Details"})}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ue,{children:"Page Title (internal)"}),e.jsx(Se,{value:b.title,onChange:ne=>j(le=>({...le,title:ne.target.value}))})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Description (internal)"}),e.jsx(Se,{value:b.description,onChange:ne=>j(le=>({...le,description:ne.target.value}))})]})]})]}),e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsxs(zt,{className:"text-base flex items-center gap-2",children:["Theme & Style",e.jsx(Xe,{variant:"secondary",className:"text-[10px]",children:"New"})]})}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(ue,{children:"Theme Style"}),e.jsxs(Bs,{value:b.theme_style,onValueChange:ne=>j(le=>({...le,theme_style:ne})),children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"premium",children:"Premium — cinematic + glass form"}),e.jsx(pt,{value:"classic",children:"Classic — centered card"})]})]})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Headline Font"}),e.jsxs(Bs,{value:b.heading_font,onValueChange:ne=>j(le=>({...le,heading_font:ne})),children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(pt,{value:"playfair",children:"Playfair Display (editorial serif)"}),e.jsx(pt,{value:"baskerville",children:"Libre Baskerville (classic serif)"}),e.jsx(pt,{value:"instrument",children:"Instrument Serif (modern serif)"}),e.jsx(pt,{value:"sans",children:"Inter (clean sans-serif)"})]})]})]})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Trust Pills (comma separated, shown under CTA)"}),e.jsx(Se,{value:b.trust_pills.join(", "),onChange:ne=>j(le=>({...le,trust_pills:ne.target.value.split(",").map(be=>be.trim()).filter(Boolean)})),placeholder:"No obligation, 100% free, 60 seconds or less"})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Premium theme uses a cinematic full-screen hero, italic accent word, glass-effect form, and trust pills — magazine-style."})]})]}),e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-base",children:"Hero Section"})}),e.jsxs(Oe,{className:"space-y-4",children:[b.theme_style==="premium"&&e.jsxs("div",{children:[e.jsx(ue,{children:"Eyebrow (small label above headline)"}),e.jsx(Se,{value:b.eyebrow,onChange:ne=>j(le=>({...le,eyebrow:ne.target.value})),placeholder:"HOME VALUE"})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Headline"}),e.jsx(Se,{value:b.hero_headline,onChange:ne=>j(le=>({...le,hero_headline:ne.target.value})),placeholder:"What Is Your Home"})]}),b.theme_style==="premium"&&e.jsxs("div",{children:[e.jsx(ue,{children:"Accent Word(s) — italic & colored (optional)"}),e.jsx(Se,{value:b.headline_accent,onChange:ne=>j(le=>({...le,headline_accent:ne.target.value})),placeholder:"Actually Worth?"})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Subtext"}),e.jsx(vr,{value:b.hero_subtext,onChange:ne=>j(le=>({...le,hero_subtext:ne.target.value})),rows:3,placeholder:"A brief description..."})]}),e.jsxs("div",{children:[e.jsxs(ue,{children:["Background Image ",b.theme_style==="premium"&&e.jsx("span",{className:"text-[11px] text-muted-foreground",children:"(dusk/cinematic recommended)"})]}),e.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[b.hero_image_url&&e.jsx("img",{src:b.hero_image_url,alt:"Hero",className:"h-16 w-28 object-cover rounded"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(H,{variant:"outline",size:"sm",asChild:!0,disabled:l==="hero_image_url",children:e.jsxs("span",{children:[e.jsx(Ea,{className:"h-3.5 w-3.5 mr-1"}),l==="hero_image_url"?"Uploading...":"Upload"]})}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:ne=>D(ne,"hero_image_url")})]}),b.hero_image_url&&e.jsx(H,{variant:"ghost",size:"sm",onClick:()=>j(ne=>({...ne,hero_image_url:null})),children:e.jsx(Dr,{className:"h-3.5 w-3.5"})})]})]})]})]}),e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-base",children:"Branding"})}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(ue,{children:"Logo"}),e.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[b.logo_url&&e.jsx("img",{src:b.logo_url,alt:"Logo",className:"h-10 w-auto rounded"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(H,{variant:"outline",size:"sm",asChild:!0,disabled:l==="logo_url",children:e.jsxs("span",{children:[e.jsx(Ea,{className:"h-3.5 w-3.5 mr-1"}),l==="logo_url"?"...":"Upload"]})}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:ne=>D(ne,"logo_url")})]})]})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Agent Photo"}),e.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[b.agent_photo_url&&e.jsx("img",{src:b.agent_photo_url,alt:"Agent",className:"h-10 w-10 rounded-full object-cover"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(H,{variant:"outline",size:"sm",asChild:!0,disabled:l==="agent_photo_url",children:e.jsxs("span",{children:[e.jsx(Ea,{className:"h-3.5 w-3.5 mr-1"}),l==="agent_photo_url"?"...":"Upload"]})}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:ne=>D(ne,"agent_photo_url")})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(ue,{children:"Primary Color"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("input",{type:"color",value:b.primary_color,onChange:ne=>j(le=>({...le,primary_color:ne.target.value})),className:"h-9 w-12 rounded border cursor-pointer"}),e.jsx(Se,{value:b.primary_color,onChange:ne=>j(le=>({...le,primary_color:ne.target.value})),className:"font-mono text-xs"})]})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Accent Color"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("input",{type:"color",value:b.accent_color,onChange:ne=>j(le=>({...le,accent_color:ne.target.value})),className:"h-9 w-12 rounded border cursor-pointer"}),e.jsx(Se,{value:b.accent_color,onChange:ne=>j(le=>({...le,accent_color:ne.target.value})),className:"font-mono text-xs"})]})]})]})]})]}),e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-base",children:"Agent Info (shown on page)"})}),e.jsx(Oe,{className:"space-y-4",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx(ue,{children:"Name"}),e.jsx(Se,{value:b.agent_name,onChange:ne=>j(le=>({...le,agent_name:ne.target.value}))})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Phone"}),e.jsx(Se,{value:b.agent_phone,onChange:ne=>j(le=>({...le,agent_phone:ne.target.value}))})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Email"}),e.jsx(Se,{value:b.agent_email,onChange:ne=>j(le=>({...le,agent_email:ne.target.value}))})]})]})})]})]}),ie&&e.jsx(cs,{value:"lead_magnet",className:"space-y-4 mt-4",children:e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsxs(zt,{className:"text-base flex items-center gap-2",children:[e.jsx(hi,{className:"h-4 w-4"})," Giveaway File"]})}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Upload a file or provide an external URL. Visitors will receive the download link after submitting the form."}),e.jsxs("div",{children:[e.jsx(ue,{children:"Upload File (PDF, guide, checklist, etc.)"}),e.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[b.lead_magnet_file_name&&e.jsxs(Xe,{variant:"outline",className:"gap-1",children:[e.jsx(hi,{className:"h-3 w-3"})," ",b.lead_magnet_file_name]}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(H,{variant:"outline",size:"sm",asChild:!0,disabled:l==="lead_magnet",children:e.jsxs("span",{children:[e.jsx(Ea,{className:"h-3.5 w-3.5 mr-1"}),l==="lead_magnet"?"Uploading...":"Upload File"]})}),e.jsx("input",{type:"file",className:"hidden",onChange:R})]}),b.lead_magnet_file_url&&e.jsx(H,{variant:"ghost",size:"sm",onClick:()=>j(ne=>({...ne,lead_magnet_file_url:null,lead_magnet_file_name:null})),children:e.jsx(Dr,{className:"h-3.5 w-3.5"})})]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx("div",{className:"flex-1 border-t"}),e.jsx("span",{children:"OR"}),e.jsx("div",{className:"flex-1 border-t"})]}),e.jsxs("div",{children:[e.jsxs(ue,{className:"flex items-center gap-1",children:[e.jsx(ql,{className:"h-3.5 w-3.5"})," External URL"]}),e.jsx(Se,{value:b.lead_magnet_external_url||"",onChange:ne=>j(le=>({...le,lead_magnet_external_url:ne.target.value||null})),placeholder:"https://drive.google.com/... or https://dropbox.com/...",className:"mt-1"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Link to a file on Google Drive, Dropbox, or any URL"})]})]})]})}),ce&&e.jsxs(cs,{value:"property",className:"space-y-4 mt-4",children:[e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsxs(zt,{className:"text-base flex items-center gap-2",children:[e.jsx(Fn,{className:"h-4 w-4"})," Import from Listing Exchange"]})}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Pull property details and photos directly from one of your listings, or enter them manually below."}),e.jsxs(Bs,{value:b.listing_id||"",onValueChange:ne=>O(ne),children:[e.jsx(Os,{children:e.jsx(Us,{placeholder:"Select a listing to import..."})}),e.jsx(Fs,{children:_.map(ne=>{var le;return e.jsxs(pt,{value:ne.id,children:[ne.property_address||`${ne.city}, ${ne.state}`," — $",(le=ne.price)==null?void 0:le.toLocaleString()]},ne.id)})})]})]})]}),e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-base",children:"Property Information"})}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ue,{children:"Property Address"}),e.jsx(Se,{value:b.property_address,onChange:ne=>j(le=>({...le,property_address:ne.target.value})),placeholder:"123 Main St, City, State"})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsxs("div",{children:[e.jsx(ue,{children:"Price"}),e.jsx(Se,{value:b.property_price,onChange:ne=>j(le=>({...le,property_price:ne.target.value})),placeholder:"$450,000"})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Beds"}),e.jsx(Se,{value:b.property_beds,onChange:ne=>j(le=>({...le,property_beds:ne.target.value})),placeholder:"4"})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Baths"}),e.jsx(Se,{value:b.property_baths,onChange:ne=>j(le=>({...le,property_baths:ne.target.value})),placeholder:"3"})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Sq Ft"}),e.jsx(Se,{value:b.property_sqft,onChange:ne=>j(le=>({...le,property_sqft:ne.target.value})),placeholder:"2,400"})]})]}),e.jsxs("div",{children:[e.jsx(ue,{children:"Description"}),e.jsx(vr,{value:b.property_description,onChange:ne=>j(le=>({...le,property_description:ne.target.value})),rows:3,placeholder:"Beautiful home in a great neighborhood..."})]})]})]}),e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-base",children:"Property Photos"})}),e.jsxs(Oe,{className:"space-y-4",children:[b.property_photos.length>0&&e.jsx("div",{className:"grid grid-cols-3 md:grid-cols-4 gap-2",children:b.property_photos.map((ne,le)=>e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:ne,alt:`Property ${le+1}`,className:"h-24 w-full object-cover rounded"}),e.jsx(H,{variant:"destructive",size:"sm",className:"absolute top-1 right-1 h-6 w-6 p-0 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>j(be=>({...be,property_photos:be.property_photos.filter((fe,je)=>je!==le)})),children:e.jsx(Dr,{className:"h-3 w-3"})})]},le))}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(H,{variant:"outline",size:"sm",asChild:!0,disabled:l==="property_photos",children:e.jsxs("span",{children:[e.jsx(Ea,{className:"h-3.5 w-3.5 mr-1"}),l==="property_photos"?"Uploading...":"Add Photos"]})}),e.jsx("input",{type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:z})]})]})]})]}),e.jsxs(cs,{value:"fields",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Configure the form fields visitors will fill out"}),e.jsxs(H,{size:"sm",onClick:$,children:[e.jsx(Ys,{className:"h-3.5 w-3.5 mr-1"})," Add Field"]})]}),k.length===0?e.jsx(ke,{children:e.jsx(Oe,{className:"py-8 text-center text-muted-foreground",children:"No fields yet. Add fields to build your form."})}):e.jsx(Oxe,{sensors:J,collisionDetection:Ixe,onDragEnd:K,children:e.jsx(Bxe,{items:k.map(ne=>ne.clientId),strategy:zds,children:e.jsx("div",{className:"space-y-3",children:k.map((ne,le)=>e.jsx(BKs,{field:ne,index:le,updateField:ee,removeField:Z},ne.clientId))})})})]}),e.jsx(cs,{value:"submissions",className:"mt-4",children:y.length===0?e.jsx(ke,{children:e.jsx(Oe,{className:"py-12 text-center text-muted-foreground",children:"No submissions yet. Share your page to start collecting leads!"})}):e.jsx("div",{className:"space-y-3",children:y.map(ne=>e.jsx(ke,{children:e.jsx(Oe,{className:"p-4",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium",children:ne.contact_name||"Anonymous"}),ne.synced_to_crm&&e.jsx(Xe,{variant:"outline",className:"text-[10px]",children:"Synced"})]}),e.jsxs("div",{className:"text-sm text-muted-foreground mt-0.5",children:[ne.contact_email&&e.jsx("span",{className:"mr-3",children:ne.contact_email}),ne.contact_phone&&e.jsx("span",{children:ne.contact_phone})]}),ne.answers&&typeof ne.answers=="object"&&e.jsx("div",{className:"mt-2 text-sm space-y-1",children:Object.entries(ne.answers).map(([le,be])=>e.jsxs("div",{children:[e.jsxs("span",{className:"font-medium text-muted-foreground",children:[le,":"]})," ",e.jsx("span",{children:String(be)})]},le))})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:new Date(ne.created_at).toLocaleDateString()})]})})},ne.id))})}),e.jsxs(cs,{value:"settings",className:"space-y-4 mt-4",children:[e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-base",children:"Publishing"})}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ue,{children:"Published"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Make this page publicly accessible"})]}),e.jsx(Or,{checked:b.is_published,onCheckedChange:ne=>j(le=>({...le,is_published:ne}))})]}),b.is_published&&e.jsxs("div",{className:"p-3 bg-muted/50 rounded-lg border",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Public URL:"}),e.jsx("code",{className:"text-xs ml-2 break-all",children:re})]})]})]}),e.jsxs(ke,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-base",children:"Thank You Message"})}),e.jsx(Oe,{children:e.jsx(vr,{value:b.success_message,onChange:ne=>j(le=>({...le,success_message:ne.target.value})),rows:2,placeholder:"Message shown after form submission"})})]})]})]})]}),e.jsx(bs,{open:c,onOpenChange:d,children:e.jsxs(vs,{className:"max-w-sm",children:[e.jsx(Cs,{children:e.jsx(Ns,{children:"QR Code"})}),e.jsxs("div",{className:"flex flex-col items-center gap-4 py-4",children:[e.jsx(Vz,{value:re,size:240}),e.jsx("p",{className:"text-xs text-muted-foreground text-center break-all",children:re})]})]})})]}):e.jsx(Ss,{title:"Not Found",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx("p",{className:"text-muted-foreground",children:"Page not found"}),e.jsx(H,{variant:"link",onClick:()=>t("/mission-control/landing-pages"),children:"Go back"})]})})}function $Ks(){return yt({queryKey:["website-apps"],queryFn:async()=>{const{data:s,error:t}=await V.from("website_apps").select("*").order("sort_order",{ascending:!0});if(t)throw t;return s||[]}})}function fye(){const{user:s}=Ms();return yt({queryKey:["agent-website-app-installs",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return[];const{data:t,error:r}=await V.from("agent_website_app_installs").select("*").eq("user_id",s.id);if(r)throw r;return t||[]},enabled:!!(s!=null&&s.id)})}function pye(){const{user:s}=Ms(),t=ns();return Pt({mutationFn:async({app_slug:r,enabled:n})=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{error:a}=await V.from("agent_website_app_installs").upsert({user_id:s.id,app_slug:r,enabled:n},{onConflict:"user_id,app_slug"});if(a)throw a},onSuccess:(r,n)=>{t.invalidateQueries({queryKey:["agent-website-app-installs"]}),he.success(n.enabled?"App installed":"App turned off")},onError:r=>he.error(r.message||"Failed to update app")})}const UKs={video_greeter:{gradient:"from-rose-500 via-fuchsia-500 to-indigo-500",iconBg:"bg-gradient-to-br from-rose-500 to-fuchsia-600",iconText:"text-white",ring:"hover:ring-fuchsia-400/50",chip:"bg-fuchsia-100 text-fuchsia-700"},exit_popup:{gradient:"from-amber-400 via-orange-500 to-red-500",iconBg:"bg-gradient-to-br from-amber-400 to-orange-600",iconText:"text-white",ring:"hover:ring-orange-400/50",chip:"bg-orange-100 text-orange-700"},chatbot:{gradient:"from-emerald-400 via-teal-500 to-cyan-600",iconBg:"bg-gradient-to-br from-emerald-500 to-teal-600",iconText:"text-white",ring:"hover:ring-teal-400/50",chip:"bg-teal-100 text-teal-700"},lead_magnet:{gradient:"from-sky-400 via-blue-500 to-indigo-600",iconBg:"bg-gradient-to-br from-sky-500 to-indigo-600",iconText:"text-white",ring:"hover:ring-blue-400/50",chip:"bg-blue-100 text-blue-700"}},qKs={gradient:"from-violet-500 via-purple-500 to-pink-500",iconBg:"bg-gradient-to-br from-violet-500 to-purple-600",iconText:"text-white",ring:"hover:ring-violet-400/50",chip:"bg-violet-100 text-violet-700"};function VKs(){const s=Fr(),{data:t=[],isLoading:r}=$Ks(),{data:n=[]}=fye(),{hasLeadSite:a,siteUrl:i,isLoading:l}=av(),o=pye(),[c,d]=S.useState(!1),h=p=>{var x;return((x=n.find(y=>y.app_slug===p))==null?void 0:x.enabled)??!1},m=p=>n.some(x=>x.app_slug===p);return e.jsxs(Ss,{title:"Website Apps",description:"Conversion-boosting widgets for your website",children:[e.jsxs("div",{className:"max-w-6xl mx-auto p-6 lg:p-8 space-y-8",children:[e.jsxs("div",{className:"relative overflow-hidden rounded-3xl bg-gradient-to-br from-indigo-600 via-fuchsia-600 to-rose-500 p-8 lg:p-10 shadow-xl",children:[e.jsx("div",{className:"absolute -top-20 -right-20 w-72 h-72 rounded-full bg-white/10 blur-3xl"}),e.jsx("div",{className:"absolute -bottom-24 -left-16 w-80 h-80 rounded-full bg-fuchsia-300/20 blur-3xl"}),e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 px-3 py-1 rounded-full bg-white/15 backdrop-blur-sm text-white text-xs font-semibold uppercase tracking-wider mb-4",children:[e.jsx(ym,{className:"w-3.5 h-3.5"})," Boost conversions on autopilot"]}),e.jsxs("h1",{className:"text-3xl lg:text-4xl font-extrabold tracking-tight text-white flex items-center gap-3",children:[e.jsx(Lr,{className:"w-8 h-8 text-yellow-300 drop-shadow"}),"Website Apps"]}),e.jsx("p",{className:"text-white/90 mt-2 max-w-2xl text-base lg:text-lg",children:"Drop-in widgets that turn website visitors into leads. Add them to your Lead Site or embed on your own website with one line of code."}),e.jsxs(H,{onClick:()=>d(!0),className:"mt-5 bg-white text-indigo-700 hover:bg-white/90 shadow-lg font-semibold gap-2",children:[e.jsx(cg,{className:"w-5 h-5"}),"Watch: How to use Website Apps"]})]})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(ke,{className:`p-5 border-2 ${a?"border-emerald-200 bg-emerald-50/50":"border-dashed border-muted"}`,children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:`w-11 h-11 rounded-xl flex items-center justify-center flex-shrink-0 ${a?"bg-emerald-500 text-white":"bg-muted text-muted-foreground"}`,children:e.jsx(ld,{className:"w-5 h-5"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("h3",{className:"font-semibold text-sm",children:"Option 1 — The Local Move Websites"}),a&&e.jsxs(Xe,{className:"bg-emerald-100 text-emerald-700 hover:bg-emerald-100 text-[10px] gap-1",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-emerald-500 animate-pulse"})," Auto-installed"]})]}),a&&i?e.jsxs("a",{href:i,target:"_blank",rel:"noreferrer",className:"text-xs text-emerald-700 hover:underline inline-flex items-center gap-1 mt-1",children:[i.replace(/^https?:\/\//,"")," ",e.jsx(gn,{className:"w-3 h-3"})]}):e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Don't have a Local Move website yet? Visit"," ",e.jsxs("a",{href:"https://www.thelocalmove.com",target:"_blank",rel:"noreferrer",className:"text-primary font-medium hover:underline inline-flex items-center gap-0.5",children:["www.thelocalmove.com ",e.jsx(gn,{className:"w-3 h-3"})]})," ","to learn more — apps install automatically once you have one."]})]})]})}),e.jsx(ke,{className:"p-5 border-2 border-indigo-200 bg-indigo-50/40",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"w-11 h-11 rounded-xl bg-gradient-to-br from-indigo-500 to-fuchsia-600 text-white flex items-center justify-center flex-shrink-0",children:e.jsx(b2,{className:"w-5 h-5"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-semibold text-sm",children:"Option 2 — Your existing website"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Already have a site (Wix, Squarespace, WordPress, custom)? Paste a one-line snippet and the widget appears anywhere."}),e.jsx("p",{className:"text-[11px] text-indigo-700 mt-2 font-medium",children:'Open any app below → "Install on my website" tab to copy your code.'})]})]})})]}),r?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading apps..."}):e.jsx("div",{className:"grid gap-5 sm:grid-cols-2 lg:grid-cols-3",children:t.map(p=>{const x=Vpe[p.icon||"Sparkles"]||Lr,y=h(p.slug),_=m(p.slug),b=p.status==="coming_soon",j=UKs[p.slug]||qKs;return e.jsxs(ke,{className:`group relative overflow-hidden border-0 ring-1 ring-border ${j.ring} hover:ring-2 transition-all hover:shadow-xl ${b?"opacity-70":""}`,children:[e.jsx("div",{className:`h-1.5 w-full bg-gradient-to-r ${j.gradient}`}),e.jsxs("div",{className:"p-5 flex flex-col gap-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsx("div",{className:`w-14 h-14 rounded-2xl ${j.iconBg} ${j.iconText} flex items-center justify-center shadow-md group-hover:scale-105 transition-transform`,children:e.jsx(x,{className:"w-7 h-7"})}),b?e.jsx(Xe,{variant:"secondary",children:"Coming soon"}):y?e.jsxs(Xe,{className:"bg-emerald-100 text-emerald-700 hover:bg-emerald-100 gap-1",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-emerald-500 animate-pulse"}),"Live"]}):_?e.jsx(Xe,{variant:"outline",children:"Paused"}):e.jsx(Xe,{className:j.chip+" hover:"+j.chip,children:"New"})]}),e.jsxs("div",{className:"space-y-1 flex-1",children:[e.jsx("h3",{className:"font-bold text-lg",children:p.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:p.description})]}),!b&&e.jsxs("div",{className:"flex items-center justify-between gap-3 pt-3 border-t",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Or,{checked:y,onCheckedChange:k=>o.mutate({app_slug:p.slug,enabled:k})}),e.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:y?"On":"Off"})]}),e.jsxs(H,{size:"sm",className:`bg-gradient-to-r ${j.gradient} text-white hover:opacity-90 shadow-md border-0`,onClick:()=>s(`/website-apps/${p.slug}`),children:[e.jsx(Go,{className:"w-3.5 h-3.5 mr-1.5"}),"Configure",e.jsx(bi,{className:"w-3.5 h-3.5 ml-1"})]})]})]})]},p.id)})})]}),e.jsx(bs,{open:c,onOpenChange:d,children:e.jsxs(vs,{className:"max-w-4xl p-0 overflow-hidden bg-black border-0",children:[e.jsx(Cs,{className:"px-5 pt-4 pb-2 bg-background",children:e.jsx(Ns,{children:"How to use Website Apps"})}),c&&e.jsx("video",{src:"/website-apps-tutorial.mp4",controls:!0,autoPlay:!0,playsInline:!0,className:"w-full h-auto bg-black"})]})})]})}const i2e={video_id:null,video_url:null,video_embed_url:null,thumbnail_url:null,greeting_title:"Glad you're here!",greeting_subtitle:"",position:"bottom-left",size:"md",shape:"rounded",ctas:[],show_socials:!0,lead_form_enabled:!0,lead_form_fields:["name","email","phone"],targeting:{mode:"all",include:[],exclude:[]},trigger:{type:"immediate",value:0},schedule:{mode:"always"}};function HKs(){const{user:s}=Ms();return yt({queryKey:["video-greeter-config",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return i2e;const{data:t,error:r}=await V.from("video_greeter_configs").select("*").eq("user_id",s.id).maybeSingle();if(r)throw r;return t?{...i2e,...t}:i2e},enabled:!!(s!=null&&s.id)})}function GKs(){const{user:s}=Ms(),t=ns();return Pt({mutationFn:async r=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{error:n}=await V.from("video_greeter_configs").upsert({user_id:s.id,...r},{onConflict:"user_id"});if(n)throw n},onSuccess:()=>{t.invalidateQueries({queryKey:["video-greeter-config"]}),he.success("Saved")},onError:r=>he.error(r.message||"Failed to save")})}function WKs({label:s,value:t,onChange:r,thumbnailUrl:n,placeholder:a="https://...",hint:i}){const l=S.useRef(null),[o,c]=S.useState(!1),d=async h=>{var p;const m=(p=h.target.files)==null?void 0:p[0];if(m){if(!m.type.startsWith("video/")){he.error("Please select a video file");return}if(m.size>50*1024*1024){he.error("Video must be under 50MB");return}c(!0);try{const x=m.name.split(".").pop()||"mp4",y=`lead-site/videos/${Date.now()}-${Math.random().toString(36).slice(2,6)}.${x}`,{error:_}=await V.storage.from("agent-uploads").upload(y,m,{upsert:!0});if(_)throw _;const{data:{publicUrl:b}}=V.storage.from("agent-uploads").getPublicUrl(y);r(b),he.success("Video uploaded!")}catch(x){he.error(x.message||"Upload failed")}finally{c(!1),l.current&&(l.current.value="")}}};return e.jsxs("div",{children:[e.jsx(ue,{children:s}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Se,{value:t,onChange:h=>r(h.target.value),placeholder:a,className:"flex-1"}),e.jsxs(H,{type:"button",variant:"outline",size:"sm",className:"shrink-0 gap-1.5 h-9",onClick:()=>{var h;return(h=l.current)==null?void 0:h.click()},disabled:o,children:[o?e.jsx(is,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Ea,{className:"h-3.5 w-3.5"}),o?"Uploading...":"Upload"]}),e.jsx("input",{ref:l,type:"file",accept:"video/*",className:"hidden",onChange:d})]}),i&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:i}),t&&e.jsxs("div",{className:"relative group mt-2",children:[e.jsx("div",{className:"rounded-lg border border-border overflow-hidden bg-black w-full max-w-sm aspect-[9/16] mx-auto",children:jI(t)?e.jsx(yCe,{sourceUrl:t,thumbnailUrl:n,autoPlay:!0,muted:!0,loop:!0,className:"w-full h-full object-contain"}):e.jsx("video",{src:t,className:"w-full h-full object-contain",muted:!0,preload:"metadata"})}),e.jsx(H,{type:"button",variant:"destructive",size:"icon",className:"absolute top-1 right-1 h-6 w-6 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>r(""),children:e.jsx(Rr,{className:"h-3 w-3"})})]})]})}const KKs=[{id:"warm-welcome",title:"Warm Welcome",duration:"15-20 sec",description:"Friendly intro that invites visitors to click for more.",text:"Hey there — welcome! I'm so glad you stopped by. I'm here to help you make smart, confident moves in this market — whether you're buying, selling, or just exploring. Click play and let me share a quick something that might help you today."},{id:"just-listed",title:"Just Listed Highlight",duration:"20-25 sec",description:"Drive attention to a new listing on your site.",text:"Hi! Quick heads up — I just listed a beautiful new home you'll want to see before anyone else. Click the video and I'll walk you through what makes it special and how to get a private showing this week."},{id:"home-value",title:"Free Home Value",duration:"15-20 sec",description:"Encourage seller leads to request an evaluation.",text:"Curious what your home is actually worth in today's market? It's probably more — or less — than you think. Click play and I'll show you exactly how to get a real, no-pressure home value report in under a minute."},{id:"buyer-tips",title:"Buyer Quick Tips",duration:"25-30 sec",description:"Position yourself as the trusted local expert for buyers.",text:"Thinking about buying? Before you do anything else, there are three things every smart buyer should know about our market right now. Click the video — I'll break them down in plain English so you can move forward with total confidence."},{id:"market-update",title:"Monthly Market Update",duration:"30 sec",description:"Quick authority builder — refresh monthly.",text:"Hey — quick market update. The numbers just dropped and there's something really interesting happening in our area that affects buyers AND sellers. Click play and I'll give you the 30-second breakdown so you know exactly where things stand."},{id:"book-call",title:"Book a Call",duration:"15 sec",description:"Direct invitation to schedule a chat.",text:"Hi! If you'd rather just talk it through with a real person — that's what I do best. Click play, then grab a 15-minute call with me. No pressure, no pitch — just answers to your questions."}];function YKs({onVideoReady:s}){const[t,r]=S.useState(!1),[n,a]=S.useState("script"),[i,l]=S.useState(""),[o,c]=S.useState(!0),[d,h]=S.useState(!1),[m,p]=S.useState(0),[x,y]=S.useState(0),_=Cj(),b=()=>{a("script"),l(""),p(0),y(0),c(!0)},j=T=>{!T&&(n==="uploading"||n==="processing")||(r(T),T||b())},k=S.useCallback(async(T,E)=>{a("uploading");try{const A="Video Greeter",{videoId:D,libraryId:R}=await tM(A),{uploadUrl:z,apiKey:O}=await sM(D),$=new XMLHttpRequest;$.upload.onprogress=le=>{le.lengthComputable&&p(le.loaded/le.total*100)},await new Promise((le,be)=>{$.onload=()=>$.status>=200&&$.status<300?le():be(new Error("Upload failed")),$.onerror=()=>be(new Error("Upload failed")),$.open("PUT",z),$.setRequestHeader("AccessKey",O),$.send(T)}),a("processing");let ee=0;const Z=Date.now(),J=9e4,K=`https://iframe.mediadelivery.net/embed/${R}/${D}`,re=`https://iframe.mediadelivery.net/play/${R}/${D}`;for(;ee<4;){if(await new Promise(be=>setTimeout(be,3e3)),Date.now()-Z>J){const be=T.size/1048576,fe=await _.mutateAsync({bunny_video_id:D,playback_url:re,file_size_mb:be,title:A,status:"processing",touch_type:"video"});s({videoId:(fe==null?void 0:fe.id)||D,playbackUrl:K,thumbnailUrl:null}),he.success("Video saved — still encoding. Will be ready shortly."),a("done"),setTimeout(()=>{r(!1),b()},1500);return}const le=await F_(D);if(ee=le.status,y(le.encodeProgress||0),ee===5||ee===6)throw new Error("Video processing failed")}const ie=await F_(D),ce=(ie.storageSize||T.size)/(1024*1024),ne=await _.mutateAsync({bunny_video_id:D,playback_url:ie.directPlayUrl||K,thumbnail_url:ie.thumbnailUrl,preview_url:ie.previewUrl||null,duration_seconds:ie.length||E,file_size_mb:ce,title:A,status:"ready",touch_type:"video"});s({videoId:(ne==null?void 0:ne.id)||D,playbackUrl:ie.directPlayUrl||K,thumbnailUrl:ie.thumbnailUrl||null}),he.success("Video recorded & added to your library!"),a("done"),setTimeout(()=>{r(!1),b()},1500)}catch(A){console.error(A),he.error("Failed to process video. Please try again."),a("record")}},[_,s]);return e.jsxs(bs,{open:t,onOpenChange:j,children:[e.jsx(Qi,{asChild:!0,children:e.jsxs(H,{variant:"default",size:"sm",className:"gap-1.5",children:[e.jsx(xn,{className:"h-4 w-4"}),"Record now"]})}),e.jsxs(vs,{className:"sm:max-w-3xl max-h-[92vh] overflow-y-auto",children:[e.jsx(Cs,{children:e.jsxs(Ns,{className:"flex items-center gap-2",children:[e.jsx(Lr,{className:"h-5 w-5 text-primary"}),"Record your Video Greeter"]})}),n==="script"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-sm mb-1",children:"1. Pick a script (optional)"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-3",children:"Edit it to sound like you, or skip and freestyle."}),e.jsx(Ci,{className:"h-[280px] pr-3",children:e.jsx("div",{className:"grid sm:grid-cols-2 gap-3",children:KKs.map(T=>e.jsxs(ke,{className:"p-3 cursor-pointer hover:border-primary transition-colors",onClick:()=>l(T.text),children:[e.jsxs("div",{className:"flex items-start justify-between gap-2 mb-1",children:[e.jsx("h4",{className:"font-medium text-sm",children:T.title}),e.jsx(Xe,{variant:"outline",className:"text-[10px] shrink-0",children:T.duration})]}),e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2",children:T.description})]},T.id))})})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-sm mb-1",children:"2. Edit your script"}),e.jsx(vr,{rows:5,value:i,onChange:T=>l(T.target.value),placeholder:"Pick a script above or type your own. Leave blank to freestyle."})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2 border-t",children:[e.jsx(H,{variant:"ghost",onClick:()=>{l(""),a("record")},children:"Skip — freestyle"}),e.jsxs(H,{onClick:()=>a("record"),children:[e.jsx(kn,{className:"h-4 w-4 mr-1.5"})," Continue to recorder"]})]})]}),n==="record"&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(aD,{maxDurationSeconds:60,onRecordingComplete:k,onRecordingStateChange:h,onError:T=>he.error(T),teleprompterContent:o&&i?e.jsx(c6e,{text:i,isVisible:o,onToggleVisibility:()=>c(!1),isRecording:d,startCountdown:!1}):void 0}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(H,{variant:"ghost",size:"sm",onClick:()=>a("script"),children:"← Back to script"}),i&&!o&&e.jsxs(H,{variant:"outline",size:"sm",onClick:()=>c(!0),children:[e.jsx(kn,{className:"h-4 w-4 mr-1.5"})," Show teleprompter"]})]})]}),n==="uploading"&&e.jsxs("div",{className:"flex flex-col items-center gap-4 py-12",children:[e.jsx(is,{className:"h-10 w-10 animate-spin text-primary"}),e.jsx("p",{className:"text-sm font-medium",children:"Uploading video..."}),e.jsx(Mi,{value:m,className:"w-64"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Math.round(m),"%"]})]}),n==="processing"&&e.jsxs("div",{className:"flex flex-col items-center gap-4 py-12",children:[e.jsx(is,{className:"h-10 w-10 animate-spin text-primary"}),e.jsx("p",{className:"text-sm font-medium",children:"Processing video..."}),e.jsx(Mi,{value:x,className:"w-64"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Math.round(x),"%"]})]}),n==="done"&&e.jsxs("div",{className:"flex flex-col items-center gap-3 py-12",children:[e.jsx(zi,{className:"h-12 w-12 text-emerald-500"}),e.jsx("p",{className:"text-sm font-medium",children:"Video attached to your greeter!"})]})]})]})}function ZKs(){var E;const s=Fr(),{user:t}=Ms(),{leadSite:r}=av(),{data:n}=HKs(),a=GKs(),{data:i=[]}=fye(),l=pye(),[o,c]=S.useState(null),[d,h]=S.useState({impressions:0,expands:0,ctaClicks:0,leads:0});if(S.useEffect(()=>{n&&!o&&c(n)},[n,o]),S.useEffect(()=>{t!=null&&t.id&&V.from("widget_events").select("event_type",{count:"exact"}).eq("user_id",t.id).eq("app_slug","video_greeter").then(({data:A})=>{const D=A||[];h({impressions:D.filter(R=>R.event_type==="impression").length,expands:D.filter(R=>R.event_type==="expand").length,ctaClicks:D.filter(R=>R.event_type==="cta_click").length,leads:D.filter(R=>R.event_type==="lead_capture").length})})},[t==null?void 0:t.id]),!o)return e.jsx(Ss,{title:"Video Greeter",children:e.jsx("div",{className:"p-8 text-sm text-muted-foreground",children:"Loading..."})});const m=((E=i.find(A=>A.app_slug==="video_greeter"))==null?void 0:E.enabled)??!1,p=A=>c({...o,...A}),x=A=>p({ctas:A}),y=()=>x([...o.ctas||[],{id:crypto.randomUUID(),label:"New Button",url:"https://",style:"primary"}]),_=A=>x((o.ctas||[]).filter(D=>D.id!==A)),b=(A,D)=>x((o.ctas||[]).map(R=>R.id===A?{...R,...D}:R)),j=()=>a.mutate(o),k=(r==null?void 0:r.subdomain_slug)||(t==null?void 0:t.id)||"",T=`